icoa-cli 2.19.419 → 2.19.421

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as y,resolve as g}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{editTextInEditor as u}from"../lib/editor-spawn.js";import{buildSshArgs as p,leaseConnectProblems as h,parseLeaseResponse as m,queueLine as w}from"../lib/gpu.js";import{shouldExecuteCell as f}from"../lib/ipynb-input.js";import{looksLikeMarkdown as b,renderMarkdown as k}from"../lib/md-term.js";import{NotebookKernel as v,buildRemoteBridgeCommand as $}from"../lib/kernel.js";import{getMainRl as P}from"../lib/main-rl.js";import{logCommand as x}from"../lib/logger.js";import{startLogSync as E,stopLogSync as G}from"../lib/log-sync.js";import{cellPreview as S,parseIpynb as U,parsePercentPy as N,parseRunRange as q,serializeIpynb as C,statusChar as A}from"../lib/notebook-doc.js";import{openFile as O}from"../lib/open-file.js";const j=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(m){m.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async m=>{await async function(m){const j=d(t()),T=y(t(),".icoa","ipynb-out");if(_(),!e(j.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const J=m?function(o){const l=i(o)?o:g(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?U(e):N(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(m):null,z=J?J.doc:{cells:[],path:null,dirty:!1};let B=new v({venvPython:j.python,venvRoot:j.root}),F=null,H=W(z.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await B.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),J&&console.log(J.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const Q=P(),X=null!==Q,Z=X?Q.listeners("line").slice():[];X&&Q.removeAllListeners("line");const ee=X?Q:a({input:process.stdin,output:process.stdout,terminal:!0}),oe=X?ee.prompt:null;X&&(ee.prompt=r.prototype.prompt),X||E();const ne=[];let le=!1,te=!1,re=!1;const ae=()=>{const e=F?"icoa ipynb ⚡gpu":"icoa ipynb";ee.setPrompt(chalk.bold.cyan(ne.length?`${e} ...> `:`${e}> `)),ee.prompt()};let se=()=>{};const ce=new Promise(e=>{se=e}),ie=async()=>{if(!F)return void console.log(chalk.gray(" not on a GPU kernel."));const e=D();await B.shutdown().catch(()=>{}),e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{B=new v({venvPython:j.python,venvRoot:j.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await B.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},ye=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(F)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=D();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));H||(H=W(z.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await K("lease",e,H??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(w(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await K("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=h(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await K("release",e);const s=H?`${n.dataRoot}/${H}`:n.dataRoot,c=$(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=y(t(),".icoa","gpu","lease-key");try{o(y(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await K("release",e)}i={command:"ssh",args:p(n,r,c)}}const g=new v({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await K("release",e)}await B.shutdown().catch(()=>{}),B=g,F=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),H&&console.log(chalk.gray(` Dataset is already on the box (${H}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await ie():"status"===a||""===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await K("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(F?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${w(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${R()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(t(),".icoa"),{recursive:!0}),l(M(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${M()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},ge=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>z.cells.length?(console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${z.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:z.cells[o-1],idx:o}},de=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!b(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),ue=async t=>{if(t.trim()&&x(`ipynb: ${t.trim()}`),te)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ne.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ne.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(re=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return z.dirty&&!re?(re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ae()):void await(async()=>{if(ee.removeAllListeners("line"),X||G(),console.log(),F){const e=D();e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await B.shutdown().catch(()=>{}),X){oe&&(ee.prompt=oe);for(const e of Z)ee.on("line",e);ee.prompt(),se()}else se(),ee.close()})();if("clear"===a||"cls"===a)return console.clear(),_(),void ae();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await B.shutdown().catch(()=>{});try{await B.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void ae();if("help"===a||"?"===a)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ae();if("guide"===a||"/guide"===a)return(()=>{const o=z.path?c(z.path):process.cwd(),l=W(z.path);let t="",r=!1;try{const e=JSON.parse(n(y(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=z.cells.filter(e=>null!==e.result).length,i=e(y(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(z.path?s(z.path):"new empty notebook")+chalk.gray(` · ${z.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),F?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ae();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ae();if("open"===a)return V&&O(V)?console.log(chalk.gray(" reopening ")+chalk.cyan(V)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ae();if("cells"===a||"ls"===a)return(()=>{if(0===z.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);z.cells.forEach((o,n)=>{const l=A(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(S(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void ae();if("show"===a)return(e=>{const o=ge(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of k(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),Y(o.cell.result,T)),console.log()}})(d),void ae();if("edit"===a)return(e=>{const o=ge(e);if(!o)return;ee.pause();const n=u(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(ee.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,z.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(d),void ae();if("add"===a)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));ee.pause();const l=u(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");ee.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(z.cells.push({kind:n?"markdown":"code",source:t,result:null}),z.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${z.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${z.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ae();if("del"===a||"delete"===a)return(e=>{const o=ge(e);o&&(z.cells.splice(o.idx-1,1),z.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${z.cells.length} left.`)))})(d),void ae();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=ge(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,z.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(d,"md"===a?"markdown":"code"),void ae();if("gpu"===a)return te=!0,await ye(d),te=!1,void ae();if("download"===a||"dl"===a)return te=!0,await(async e=>{if(!F)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${F.outDir}/${n}`;let r;try{r=await B.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=H?y(process.cwd(),"icoa-kaggle",H):process.cwd(),c=y(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),H&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${H}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),te=!1,void ae();if("run"===a)return te=!0,await(async e=>{const o=q(e,z.cells.length);if(o)for(const e of o){const n=z.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(S(n,50))+chalk.gray(" ──"));try{n.result=await B.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void L()}if(z.dirty=!0,Y(n.result,T),de(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),void L()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of k(n.source))console.log(e);console.log()}}else console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(d),te=!1,void ae();if("save"===a)return(e=>{if(0===z.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():g(process.cwd(),e.trim()):z.path?z.path.endsWith(".ipynb")?z.path:`${z.path.replace(/\.[^./]+$/,"")}.ipynb`:g(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(z.cells)),z.path=o,z.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${z.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ae();if(""===r)return void ae()}if(ne.length>0&&I.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ae();if(ne.push(t),!f(ne))return 1!==ne.length||le||(le=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ae();const a=ne.join("\n").replace(/\s+$/,"");if(ne.length=0,""!==a.trim()){te=!0;try{const e=await B.execute(a);z.cells.push({kind:"code",source:a,result:e}),z.dirty=!0,Y(e,T);const o=de(z.cells[z.cells.length-1],z.cells.length);e.ok||o||L()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),L()}te=!1,ae()}else ae()};ee.on("line",e=>{ue(e)}),X||ee.on("close",async()=>{await B.shutdown().catch(()=>{}),process.exit(0)}),ae(),await ce}(m)})}function _(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const I=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function L(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const T="https://practice.icoa2026.au";function R(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):T}function M(){return y(t(),".icoa","gpu-key")}function D(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(M(),"utf-8").trim()||null}catch{return null}}async function K(e,o,n){try{const l=await fetch(`${R()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return m(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function W(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let J=0,V=null;function Y(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(j,"")}`))}else"display"===n.kind&&z(n.data,o)}function z(e,n){if(e["image/png"])try{o(n,{recursive:!0}),J+=1;const t=y(n,`figure-${J}.png`);return l(t,Buffer.from(e["image/png"],"base64")),V=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(O(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
1
+ import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as y,resolve as g}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{editTextInEditor as u}from"../lib/editor-spawn.js";import{buildSshArgs as p,leaseConnectProblems as h,parseLeaseResponse as m,queueLine as w}from"../lib/gpu.js";import{shouldExecuteCell as f}from"../lib/ipynb-input.js";import{looksLikeMarkdown as b,renderMarkdown as k}from"../lib/md-term.js";import{NotebookKernel as v,buildRemoteBridgeCommand as $}from"../lib/kernel.js";import{getMainRl as x}from"../lib/main-rl.js";import{logCommand as P}from"../lib/logger.js";import{startLogSync as E,stopLogSync as G}from"../lib/log-sync.js";import{cellPreview as S,parseIpynb as U,parsePercentPy as N,parseRunRange as q,serializeIpynb as C,statusChar as A}from"../lib/notebook-doc.js";import{openFile as O}from"../lib/open-file.js";const j=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(m){m.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async m=>{await async function(m){const j=d(t()),T=y(t(),".icoa","ipynb-out");if(_(),!e(j.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const J=m?function(o){const l=i(o)?o:g(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?U(e):N(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(m):null,z=J?J.doc:{cells:[],path:null,dirty:!1};let B=new v({venvPython:j.python,venvRoot:j.root}),F=null,H=W(z.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await B.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),J&&console.log(J.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const Q=x(),X=null!==Q,Z=X?Q.listeners("line").slice():[];X&&Q.removeAllListeners("line");const ee=X?Q:a({input:process.stdin,output:process.stdout,terminal:!0}),oe=X?ee.prompt:null;X&&(ee.prompt=r.prototype.prompt),X||E();const ne=[];let le=!1,te=!1,re=!1;const ae=()=>{const e=F?"icoa ipynb ⚡gpu":"icoa ipynb";ee.setPrompt(chalk.bold.cyan(ne.length?`${e} ...> `:`${e}> `)),ee.prompt()};let se=()=>{};const ce=new Promise(e=>{se=e}),ie=async()=>{if(!F)return void console.log(chalk.gray(" not on a GPU kernel."));const e=D();await B.shutdown().catch(()=>{}),e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{B=new v({venvPython:j.python,venvRoot:j.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await B.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},ye=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(F)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=D();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));H||(H=W(z.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await K("lease",e,H??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(w(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await K("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=h(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await K("release",e);const s=H?`${n.dataRoot}/${H}`:n.dataRoot,c=$(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=y(t(),".icoa","gpu","lease-key");try{o(y(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await K("release",e)}i={command:"ssh",args:p(n,r,c)}}const g=new v({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await K("release",e)}await B.shutdown().catch(()=>{}),B=g,F=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),H&&console.log(chalk.gray(` Dataset is already on the box (${H}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await ie():"status"===a||""===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await K("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(F?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${w(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${R()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(t(),".icoa"),{recursive:!0}),l(M(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${M()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},ge=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>z.cells.length?(console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${z.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:z.cells[o-1],idx:o}},de=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!b(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),ue=async t=>{if(t.trim()&&P(`ipynb: ${t.trim()}`),te)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ne.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ne.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(re=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return z.dirty&&!re?(re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ae()):void await(async()=>{if(ee.removeAllListeners("line"),X||G(),console.log(),F){const e=D();e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await B.shutdown().catch(()=>{}),X){oe&&(ee.prompt=oe);for(const e of Z)ee.on("line",e);ee.prompt(),se()}else se(),ee.close()})();if("clear"===a||"cls"===a)return console.clear(),_(),void ae();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await B.shutdown().catch(()=>{});try{await B.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void ae();if("help"===a||"?"===a)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ae();if("guide"===a||"/guide"===a)return(()=>{const o=z.path?c(z.path):process.cwd(),l=W(z.path);let t="",r=!1;try{const e=JSON.parse(n(y(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=z.cells.filter(e=>null!==e.result).length,i=e(y(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(z.path?s(z.path):"new empty notebook")+chalk.gray(` · ${z.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),F?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ae();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ae();if("open"===a)return V&&O(V)?console.log(chalk.gray(" reopening ")+chalk.cyan(V)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ae();if("cells"===a||"ls"===a)return(()=>{if(0===z.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);z.cells.forEach((o,n)=>{const l=A(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(S(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void ae();if("show"===a)return(e=>{const o=ge(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of k(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),Y(o.cell.result,T)),console.log()}})(d),void ae();if("edit"===a)return(e=>{const o=ge(e);if(!o)return;ee.pause();const n=u(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(ee.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,z.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(d),void ae();if("add"===a)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));ee.pause();const l=u(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");ee.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(z.cells.push({kind:n?"markdown":"code",source:t,result:null}),z.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${z.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${z.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ae();if("del"===a||"delete"===a)return(e=>{const o=ge(e);o&&(z.cells.splice(o.idx-1,1),z.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${z.cells.length} left.`)+(o.idx<=z.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(d),void ae();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=ge(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,z.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(d,"md"===a?"markdown":"code"),void ae();if("gpu"===a)return te=!0,await ye(d),te=!1,void ae();if("download"===a||"dl"===a)return te=!0,await(async e=>{if(!F)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${F.outDir}/${n}`;let r;try{r=await B.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=H?y(process.cwd(),"icoa-kaggle",H):process.cwd(),c=y(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),H&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${H}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),te=!1,void ae();if("run"===a)return te=!0,await(async e=>{const o=q(e,z.cells.length);if(o)for(const e of o){const n=z.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(S(n,50))+chalk.gray(" ──"));try{n.result=await B.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void L()}if(z.dirty=!0,Y(n.result,T),de(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),void L()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of k(n.source))console.log(e);console.log()}}else console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(d),te=!1,void ae();if("save"===a)return(e=>{if(0===z.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():g(process.cwd(),e.trim()):z.path?z.path.endsWith(".ipynb")?z.path:`${z.path.replace(/\.[^./]+$/,"")}.ipynb`:g(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(z.cells)),z.path=o,z.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${z.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ae();if(""===r)return void ae()}if(ne.length>0&&I.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ae();if(ne.push(t),!f(ne))return 1!==ne.length||le||(le=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ae();const a=ne.join("\n").replace(/\s+$/,"");if(ne.length=0,""!==a.trim()){te=!0;try{const e=await B.execute(a);z.cells.push({kind:"code",source:a,result:e}),z.dirty=!0,Y(e,T);const o=de(z.cells[z.cells.length-1],z.cells.length);e.ok||o||L()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),L()}te=!1,ae()}else ae()};ee.on("line",e=>{ue(e)}),X||ee.on("close",async()=>{await B.shutdown().catch(()=>{}),process.exit(0)}),ae(),await ce}(m)})}function _(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const I=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function L(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const T="https://practice.icoa2026.au";function R(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):T}function M(){return y(t(),".icoa","gpu-key")}function D(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(M(),"utf-8").trim()||null}catch{return null}}async function K(e,o,n){try{const l=await fetch(`${R()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return m(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function W(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let J=0,V=null;function Y(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(j,"")}`))}else"display"===n.kind&&z(n.data,o)}function z(e,n){if(e["image/png"])try{o(n,{recursive:!0}),J+=1;const t=y(n,`figure-${J}.png`);return l(t,Buffer.from(e["image/png"],"base64")),V=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(O(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
@@ -1 +1 @@
1
- import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as l,writeFileSync as t}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{logCommand as i}from"../lib/logger.js";import{openFile as r}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{loadLearnState as g}from"../lib/learn-state.js";import{buildStarterCells as u,dataFileUrls as y,parseKaggleTaskList as d,parseSubmitResponse as h,validateSubmissionText as b}from"../lib/kaggle.js";function m(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function p(o){try{const e=await fetch(m()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function f(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function w(){console.log(),console.log(chalk.yellow(" The practice server is not reachable right now.")),console.log(chalk.gray(" Check your connection, or try again later.")),console.log()}function k(o){return s(process.cwd(),"icoa-kaggle",o)}function v(o,e){const n=[];let l="";for(const t of o.split(/\s+/))""!==l&&l.length+1+t.length>e?(n.push(l),l=t):l=""===l?t:`${l} ${t}`;return""!==l&&n.push(l),n}function $(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(" Scoring (inside the notebook):")),void console.log(chalk.gray(" run the final cell — the ")+chalk.white("FINAL")+chalk.gray(" line is your score. Nothing to upload."))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(" Submit to ICOA (scored on the server):")),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(" scores vs the secret test labels → live rank on ")+chalk.cyan("board"))):(console.log(chalk.bold.white(" Submit on Kaggle (manual, your own account):")),void(o?.kaggle_url?(console.log(chalk.gray(" 1. open ")+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(" 2. submit the file your notebook produced")+chalk.gray(" — its final cell has the exact steps")):console.log(chalk.gray(" 2. Submit Predictions → upload ")+chalk.white("submission.csv")),console.log(chalk.gray(" 3. read your score, improve the MODEL cell, re-run, repeat."))):(console.log(chalk.gray(" (placeholder dataset — no live Kaggle page yet; when the real")),console.log(chalk.gray(" competition dataset lands, its submission link will appear here.)")))))}export async function runKaggle(n){const l=a(),r=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · real ML competitions, a runnable starter notebook")),console.log(chalk.gray(" Small tasks run on your CPU; ")+chalk.magenta("⚡ GPU tasks")+chalk.gray(" run on the ICOA GPU box.")),console.log();const l=await p("/api/icoa/kaggle/tasks");if(!l)return w();const a=d(l);if(0===a.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let g=n?a.find(o=>o.comp_id===n):void 0;if(n&&!g&&console.log(chalk.yellow(` No competition called "${n}".`)),!g){console.log(chalk.white(" Live practice competitions:")),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!g;o++){const o=(await r(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);g=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,g||console.log(chalk.gray(` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`))}if(!g)return}const h=g.comp_id;if(i(`kaggle: download ${h}`),g.needs_gpu)return void await async function(n,l){const a=k(n);if(console.log(),console.log(chalk.white(` ${l.title}`)+chalk.gray(` · ${l.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),l.description){console.log();for(const o of v(l.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Fetching the notebook…")+chalk.gray(" (the dataset stays on the GPU box — no download)"));const i=await p(`/api/icoa/kaggle/${n}/starter`),r=i?.data?.starter??i?.starter;if("string"!=typeof r||0===r.length)return w();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:t(c,r),t(s(a,"meta.json"),`${JSON.stringify(l,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the notebook here — check directory permissions."))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?" (kept your existing one)":" (the real IOAI task inside)")),console.log(chalk.green(" ✓ dataset: ")+chalk.white("already on the GPU box")+chalk.gray(" — no download needed")),console.log(),console.log(chalk.bold.white(" This is a GPU task — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" (connects you to the box where the data lives)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(" → the notebook trains on the GPU.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting")),console.log(),l.kaggle_url&&(console.log(chalk.gray(" Submit on Kaggle: ")+chalk.cyan(l.kaggle_url)),console.log())}(h,g);if(console.log(),console.log(chalk.white(` ${g.title}`)+chalk.gray(` · ${g.metric}`)),g.description){console.log();for(const o of v(g.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Downloading data…"));let b=null;const m=y(g);if(m){const[o,e,n]=await Promise.all([f(m.train),f(m.test),f(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await p(`/api/icoa/kaggle/${h}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return w();const $=k(h),j={...g,...b.meta??{}};try{e($,{recursive:!0}),t(s($,"train.csv"),b.train),t(s($,"test.csv"),b.test),t(s($,"sample_submission.csv"),b.sample_submission),t(s($,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const S=s($,"starter.ipynb");let x=!1;if(o(S))x=!0;else{const o=await p(`/api/icoa/kaggle/${h}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?t(S,e):t(S,c(u($,j)))}const G="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",N="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s($,"train.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s($,"test.csv"))+chalk.gray(` (${N})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s($,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(S)+chalk.gray(x?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),_(h,j,S),console.log()}finally{l.close()}}function _(o,e,n){e?.needs_gpu?(console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"))):(console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline."))),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),$(e)}export async function runKaggleGuide(e){console.log();const l=j(e,"guide");if(!l)return;const t=k(l);let a=null;try{a=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{a=null}i(`kaggle: guide ${l}`);const r=s(t,"starter.ipynb"),c=o(s(t,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??l} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),_(l,a,r),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function j(e,n){if(e)return e;const t=s(process.cwd(),"icoa-kaggle"),a=o(t)?l(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(t,e.name,"sample_submission.csv"))||o(s(t,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const l=j(e,"check");if(!l)return;const t=k(l),a=s(t,"submission.csv"),c=s(t,"sample_submission.csv");try{if(JSON.parse(n(s(t,"meta.json"),"utf-8")).needs_gpu&&!o(c))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const g=b(n(a,"utf-8"),n(c,"utf-8"));i(`kaggle: check ${l} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv is Kaggle-ready")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),$(u),r(t);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const l=j(e,"submit");if(!l)return;const t=k(l),r=s(t,"submission.csv"),c=s(t,"sample_submission.csv");let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if("local-eval"===u?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),$(u),void console.log();if(!u||!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==u.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),$(u),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const y=n(r,"utf-8"),d=b(y,n(c,"utf-8"));if(!d.ok){i(`kaggle: submit ${l} → local-reject: ${d.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of d.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let p=g()?.token??"";if(!p){const o=a();try{p=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!p)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const f=await async function(o,e){try{const n=await fetch(m()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${l}/submit`,{token:p,submission_csv:y}),w=h(f);if(i(`kaggle: submit ${l} → ${w.ok?`${w.metric}=${w.score}${w.deduped?" (deduped)":""} rank=${w.rank??"-"}`:w.reason??"error"}`),console.log(),w.ok){const o=`${w.metric}: ${Number(w.score).toFixed(4).replace(/\.?0+$/,"")}`;w.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof w.rank&&"number"==typeof w.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${w.rank}`)+chalk.gray(` of ${w.fieldSize}`))),w.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${w.boardEvent} ${l}`))}else switch(w.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of w.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as l,writeFileSync as t}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{logCommand as i}from"../lib/logger.js";import{openFile as r}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{loadLearnState as g}from"../lib/learn-state.js";import{buildStarterCells as u,dataFileUrls as y,parseKaggleTaskList as d,parseSubmitResponse as h,validateSubmissionText as b}from"../lib/kaggle.js";function m(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function p(o){try{const e=await fetch(m()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function f(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function k(){console.log(),console.log(chalk.yellow(" The practice server is not reachable right now.")),console.log(chalk.gray(" Check your connection, or try again later.")),console.log()}function w(o){return s(process.cwd(),"icoa-kaggle",o)}function v(o,e){const n=[];let l="";for(const t of o.split(/\s+/))""!==l&&l.length+1+t.length>e?(n.push(l),l=t):l=""===l?t:`${l} ${t}`;return""!==l&&n.push(l),n}function $(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(" Scoring (inside the notebook):")),void console.log(chalk.gray(" run the final cell — the ")+chalk.white("FINAL")+chalk.gray(" line is your score. Nothing to upload."))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(" Submit to ICOA (scored on the server):")),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(" scores vs the secret test labels → live rank on ")+chalk.cyan("board"))):"nitro"===o?.judge?(console.log(chalk.bold.white(" 怎么知道做得对不对:")),console.log(chalk.gray(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上")),console.log(chalk.gray(" · 想要真分数:去 ")+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" 注册后提交")),void console.log(chalk.gray(" · 冲刺期更快的办法:做完对照官方解答,或问 ")+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(" Submit on Kaggle (manual, your own account):")),void(o?.kaggle_url?(console.log(chalk.gray(" 1. open ")+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(" 2. submit the file your notebook produced")+chalk.gray(" — its final cell has the exact steps")):console.log(chalk.gray(" 2. Submit Predictions → upload ")+chalk.white("submission.csv")),console.log(chalk.gray(" 3. read your score, improve the MODEL cell, re-run, repeat."))):(console.log(chalk.gray(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。")),console.log(chalk.gray(" 卡住了问 ")+chalk.cyan("ai4ioai")+chalk.gray(" —— 它是弱模型,把问题问准是这次要练的本事。")))))}export async function runKaggle(n){const l=a(),r=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · real ML competitions, a runnable starter notebook")),console.log(chalk.gray(" Small tasks run on your CPU; ")+chalk.magenta("⚡ GPU tasks")+chalk.gray(" run on the ICOA GPU box.")),console.log();const l=await p("/api/icoa/kaggle/tasks");if(!l)return k();const a=d(l);if(0===a.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let g=n?a.find(o=>o.comp_id===n):void 0;if(n&&!g&&console.log(chalk.yellow(` No competition called "${n}".`)),!g){console.log(chalk.white(" Live practice competitions:")),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!g;o++){const o=(await r(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);g=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,g||console.log(chalk.gray(` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`))}if(!g)return}const h=g.comp_id;if(i(`kaggle: download ${h}`),g.needs_gpu)return void await async function(n,l){const a=w(n);if(console.log(),console.log(chalk.white(` ${l.title}`)+chalk.gray(` · ${l.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),l.description){console.log();for(const o of v(l.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Fetching the notebook…")+chalk.gray(" (the dataset stays on the GPU box — no download)"));const i=await p(`/api/icoa/kaggle/${n}/starter`),r=i?.data?.starter??i?.starter;if("string"!=typeof r||0===r.length)return k();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:t(c,r),t(s(a,"meta.json"),`${JSON.stringify(l,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the notebook here — check directory permissions."))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?" (kept your existing one)":" (the real IOAI task inside)")),console.log(chalk.green(" ✓ dataset: ")+chalk.white("already on the GPU box")+chalk.gray(" — no download needed")),console.log(),console.log(chalk.bold.white(" This is a GPU task — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" (connects you to the box where the data lives)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(" → the notebook trains on the GPU.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting")),console.log(),l.kaggle_url&&(console.log(chalk.gray(" Submit on Kaggle: ")+chalk.cyan(l.kaggle_url)),console.log())}(h,g);if(console.log(),console.log(chalk.white(` ${g.title}`)+chalk.gray(` · ${g.metric}`)),g.description){console.log();for(const o of v(g.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Downloading data…"));let b=null;const m=y(g);if(m){const[o,e,n]=await Promise.all([f(m.train),f(m.test),f(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await p(`/api/icoa/kaggle/${h}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return k();const $=w(h),j={...g,...b.meta??{}};try{e($,{recursive:!0}),t(s($,"train.csv"),b.train),t(s($,"test.csv"),b.test),t(s($,"sample_submission.csv"),b.sample_submission),t(s($,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const S=s($,"starter.ipynb");let x=!1;if(o(S))x=!0;else{const o=await p(`/api/icoa/kaggle/${h}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?t(S,e):t(S,c(u($,j)))}const G="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",N="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s($,"train.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s($,"test.csv"))+chalk.gray(` (${N})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s($,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(S)+chalk.gray(x?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),_(h,j,S),console.log()}finally{l.close()}}function _(o,e,n){e?.needs_gpu?(console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"))):(console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline."))),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),$(e)}export async function runKaggleGuide(e){console.log();const l=j(e,"guide");if(!l)return;const t=w(l);let a=null;try{a=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{a=null}i(`kaggle: guide ${l}`);const r=s(t,"starter.ipynb"),c=o(s(t,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??l} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),_(l,a,r),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function j(e,n){if(e)return e;const t=s(process.cwd(),"icoa-kaggle"),a=o(t)?l(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(t,e.name,"sample_submission.csv"))||o(s(t,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const l=j(e,"check");if(!l)return;const t=w(l),a=s(t,"submission.csv"),c=s(t,"sample_submission.csv");try{if(JSON.parse(n(s(t,"meta.json"),"utf-8")).needs_gpu&&!o(c))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const g=b(n(a,"utf-8"),n(c,"utf-8"));i(`kaggle: check ${l} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv is Kaggle-ready")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),$(u),r(t);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const l=j(e,"submit");if(!l)return;const t=w(l),r=s(t,"submission.csv"),c=s(t,"sample_submission.csv");let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if("local-eval"===u?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),$(u),void console.log();if(!u||!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==u.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),$(u),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const y=n(r,"utf-8"),d=b(y,n(c,"utf-8"));if(!d.ok){i(`kaggle: submit ${l} → local-reject: ${d.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of d.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let p=g()?.token??"";if(!p){const o=a();try{p=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!p)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const f=await async function(o,e){try{const n=await fetch(m()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${l}/submit`,{token:p,submission_csv:y}),k=h(f);if(i(`kaggle: submit ${l} → ${k.ok?`${k.metric}=${k.score}${k.deduped?" (deduped)":""} rank=${k.rank??"-"}`:k.reason??"error"}`),console.log(),k.ok){const o=`${k.metric}: ${Number(k.score).toFixed(4).replace(/\.?0+$/,"")}`;k.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof k.rank&&"number"==typeof k.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${k.rank}`)+chalk.gray(` of ${k.fieldSize}`))),k.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${k.boardEvent} ${l}`))}else switch(k.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of k.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{logCommand as s}from"../lib/logger.js";import{getMainRl as l}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as a,handleAi4ioaiMessage as i,startAi4ioaiChat as c}from"./ai4ioai.js";import{existsSync as d,mkdirSync as g,readdirSync as u,readFileSync as m,renameSync as y,writeFileSync as h}from"node:fs";import{dirname as p,join as f}from"node:path";import{fileURLToPath as b}from"node:url";import{loadCurriculumById as w,validateEAToken as $,syncProgress as k,syncCardFeedback as v}from"../lib/learn-curricula.js";import{normalizeTokenBody as C}from"../lib/token-format.js";import{fetchMyScores as A,recallCoach as _,setNickname as I,streamLearnTutor as T,submitPqs as x,viewPqsTop as E,viewHonors as q}from"../lib/learn-ai.js";import{contestReset as M,contestStart as S,contestSubmit as R,fetchGate as P,timeLeft as O}from"../lib/learn-contest.js";import{getConfig as W,saveConfig as D}from"../lib/config.js";import{loadLearnState as L,saveLearnState as N,newLearnState as j,updateStreak as Y,markCardComplete as z,recordMCQ as B,recordCheck as U,markPracticalComplete as F,addAchievement as Z}from"../lib/learn-state.js";import{renderWelcome as H,renderKnowledgeCard as J,renderMCQCard as K,renderMCQFeedback as Q,renderPracticalCard as V,renderPracticalSuccess as G,renderSimDemoCard as X,renderMilestone as ee,renderArenaTaskCard as oe,renderComingSoonCard as te,renderStatus as ne,renderPhaseComplete as re,renderCurriculumComplete as se,setLearnAiEnabled as le,setLearnHonorRanks as ae,setLearnPqsViewCards as ie,setLearnWide as ce,learnW as de,renderHonorWall as ge,wrapMixed as ue}from"../lib/learn-render.js";import{printError as me}from"../lib/ui.js";export function registerLearnCommand(ye){ye.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ye=>{ye?.trim()||(console.log(),console.log(chalk.gray(" No token given — starting free 11-card demo (")+chalk.bold.green("LEARNDEMO01")+chalk.gray(").")),console.log(chalk.gray(" Full curriculum: ")+chalk.bold.yellow("learn <your token>")+chalk.gray(" (2 letters + 8 chars) — from your country team leader.")),console.log(),ye="LEARNDEMO01");let he=ye.trim().toUpperCase(),pe=null;const fe=/^[A-Z0-9]+DEMO01$/i.test(he),be=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(he);let we=!1,$e=!1;if(fe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),pe=await w(he,he);else if(be){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(he);if(!e.ok){const o=C(he);if(o!==he){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${he} → ${o}`)),e=t,he=o)}}if(!e.ok)return me(`Token validation failed: ${e.message}`),console.log(),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${e.curriculumId} · status: ${e.status}`)+(!0===e.aiEnabled?chalk.bold.magenta(" · ⭐ AI tutor"):"")),we=!0===e.aiEnabled,$e=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),pe=await w(e.curriculumId||"LEARNDEMO01",he),!pe)return me(`Could not open a learn curriculum for token '${he}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${he}`)+chalk.gray(" instead.")),console.log(chalk.gray(" Otherwise: the full curriculum is ~3 MB; on a slow link the download")),console.log(chalk.gray(" can take a while — stay on a stable connection and run ")+chalk.bold.yellow(`learn ${he}`)+chalk.gray(" again")),console.log(chalk.gray(" (it caches after the first load). If it keeps failing, check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()}if(!pe)return me(`Unknown learn token: ${he}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Every track has a free demo — ask for its name if you were not given one.")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log();let ke=L(),ve=!1;try{ke&&ke.token===he?Y(ke):(ke=j(he,pe.id,pe.totalCards),ve=!0),N(ke),H(pe,ke,ve)}catch{return me("Could not open this curriculum — it may be malformed or not a learn curriculum."),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${he}`)+chalk.gray(".")),void console.log()}const Ce=l(),Ae=null!==Ce,_e=Ae?Ce.listeners("line").slice():[];Ae&&Ce.removeAllListeners("line");const Ie=Ae?Ce:o({input:process.stdin,output:process.stdout,terminal:!0}),Te=Ae?Ie.prompt:null;Ae&&(Ie.prompt=e.prototype.prompt);const xe=()=>{Ae&&Te&&(Ie.prompt=Te)},Ee=()=>{Ie.setPrompt(Ye?chalk.bold.green(`icoa ${a()}> `):We?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Pe?"icoa learn ai> ":"icoa learn> ")),Ie.prompt()};let qe=null,Me=null,Se=null,Re=null,Pe=!1,Oe=!1,We=!1,De=null,Le=!1,Ne=0,je=!1,Ye=!1;const ze=new Map,Be=()=>{let e=ze.get(ke.currentCard);return e||(e=[],ze.set(ke.currentCard,e)),e};let Ue=!1;const Fe=new Set;let Ze=!1,He=0;const Je=()=>(W().language||"en").toLowerCase().startsWith("zh");le(we),ce(!!W().learnWide),ie(Fe);const Ke=new Map;ae(Ke);const Qe=[];let Ve=null;const Ge=new Promise(e=>{Ve=e}),Xe=()=>{const e=Ve;Ve=null,e?.()},eo="1"===process.env.ICOA_LEARN_EMBEDDED,oo=e=>pe.cards.find(o=>o.number===e);let to=null,no=null;const ro=!he.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(he),so=async()=>{if(!ro)return;const e=await P(he);e.ok&&e.data&&(to=e.data)},lo=e=>{const o=pe.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},ao=e=>{if(!$e||!to)return null;const o=lo(e);if(o<=to.unlocked_through_phase)return null;const t=to.phases.find(e=>e.phase===to.unlocked_through_phase),n=[chalk.yellow(Je()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${to.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${to.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(Je()?` ⚔ 练习赛 ${to.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${to.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(Je()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(Je()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},io=async e=>$e?null===ao(e)?null:(await so(),ao(e)):null;$e&&await so();const co=async e=>{const o=pe.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=pe.modules.find(e=>e.number===o.number+1);let n;if(we){const e=await A({token:he,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}ro&&await so();const r=to?.phases.find(e=>e.phase===o.number);return re(pe,ke,o,t,n,r),!0},go=()=>{Ze=!0,console.log(chalk.gray(Je()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},uo=()=>{De=null;const e=oo(ke.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":J(e,pe),e.check?(Se=e.number,He=Date.now()):(z(ke,e.number),N(ke));break;case"mcq":K(e,pe),qe=e.number;break;case"practical":V(e,pe),Me=e.number;break;case"sim_demo":X(e,pe),z(ke,e.number),N(ke);break;case"milestone":ee(e,pe),Z(ke,e.badge),z(ke,e.number),N(ke);break;case"arena_task":oe(e,pe),z(ke,e.number),N(ke);break;case"coming_soon":te(e,pe),z(ke,e.number),N(ke)}mo(e.number)},mo=e=>{if(!$e||!ro||!to)return;const o=pe.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1;if(t%4!=0)return;const n=t/4,r=to.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n);if(!s)return;const l=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),l=(n||"").slice(0,10);return`🏆 ${e} ${o}/${s.n}`+(r?Je()?` · 用时 ${r}`:` · ${r}`:"")+(l?` · ${l}`:"")},a=s.perfect_runs??[],i=!!s.best&&(s.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(de());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${Je()?"练习赛":"PY Arena"} ${o.number}-${n}`)+(s.passed?chalk.bold.green(Je()?" ✅ 已通过":" ✅ passed"):"")),s.passed||(Je()?console.log(c+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(c+chalk.white("You learned the cards — now prove it.")),console.log(c+chalk.white("The clock starts the moment you type the command."))),console.log(c+chalk.gray(Je()?`${s.n} 题 · AC ${s.need} 过关 · 限时 ${s.duration_minutes} 分钟 · 无限重开`:`${s.n} problems · AC ${s.need} to pass · ${s.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(Je()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))),a.length>0)for(const e of a)console.log(c+chalk.bold.yellow(l(Je()?"满分":"Perfect",s.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(l(Je()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(s.passed?chalk.gray(Je()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Je()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(Je()?" 继续学习":" keep going"):chalk.gray(Je()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(Je()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},yo=()=>{he.endsWith("DEMO01")?console.log(chalk.yellow(Je()?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Je()?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Je()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},ho=async(e,o)=>{if(we){Oe=!0;try{console.log(),console.log(chalk.gray("deep"===o?Je()?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Je()?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await T({token:he,cardNumber:ke.currentCard,question:e,mode:o,history:Be().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(Je()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Be().push({role:"user",content:e},{role:"assistant",content:r.answer}),null!=r.spent&&null!=r.cap&&r.spent/r.cap>.8&&console.log(chalk.gray(` (${Je()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Je()?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==Se&&console.log(chalk.gray(Je()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Oe=!1}}else yo()},po=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],fo=async()=>{Oe=!0;try{console.log();const e=await q({token:he,curriculumId:pe.id,cardNumber:ke.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Je()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Je()?` 🏆 本卡实时 Top-3 — 第 ${ke.currentCard} 张`:` 🏆 Live top-3 — card ${ke.currentCard}`)),e.board&&0!==e.board.length)for(const o of e.board){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(chalk.white(` ${o.icon} `)+chalk.bold.cyan(o.name||`Rank ${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(Je()?" (你)":" (you)"):""))}else console.log(chalk.gray(Je()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Ke.set(ke.currentCard,e.mine.rank),console.log(chalk.white(Je()?" 你: ":" You: ")+chalk.bold.yellow(Je()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Je()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):we&&console.log(chalk.gray(Je()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),ge({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Je()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Je()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Je()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),De="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Je()?" 返回卡片":" returns to the card")),console.log()}finally{Oe=!1}},bo=e=>Je()&&e.title_zh||e.title,wo=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of ue(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},$o=e=>no.data.solved.includes(e.id)?"✅":no.tried.has(e.id)?"❌":"⬜",ko=()=>{const e=no.data,o=O(e.deadline),t=e.solved.length,n=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(Je()?` · 第 ${e.slot}/${e.group_count} 组 · 第 ${e.attempt} 次尝试${e.resumed?"(续)":""}`:` · group ${e.slot}/${e.group_count} · attempt ${e.attempt}${e.resumed?" (resumed)":""}`)),console.log((o?chalk.bold.yellow(` ⏱ ${o}`):chalk.red(Je()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(Je()?`(共 ${e.n} 题)`:` (of ${e.n})`));const r=Date.parse(e.deadline)-Date.now();o?e.resumed&&r<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(Je()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Je()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(Je()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(Je()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+$o(e)+chalk.white(` ${bo(e)}`))}),console.log(),vo()},vo=()=>{console.log(chalk.gray(Je()?" /read <n> 读题 · /edit <n> 写码(vi) · /run <n> 样例自测 · /debug <n> 自由调试 · /submit <n> 判分":" /read <n> statement · /edit <n> code (vi) · /run <n> sample check · /debug <n> free run · /submit <n> judge")),console.log(chalk.gray(Je()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Je()?" 返回课程":" returns to the lesson")),console.log()},Co=e=>{const o=parseInt(e,10),t=no.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(Je()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}},Ao=e=>{const o=Co(e);if(!o)return;const{p:t,n:n}=o;console.log(),console.log(chalk.bold.white(` ${$o(t)} ${bo(t)}`)),console.log();for(const e of(e=>Je()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of ue(e,de()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(Je()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Je()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(Je()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(Je()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Je()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(Je()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(Je()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Je()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log()},_o=async(e,o)=>{await new Promise(t=>{const n=process.stdin,s=!!n.isTTY&&!!n.isRaw;if(Ie.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e,o,{stdio:"inherit",cwd:no.dir}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&s)try{n.setRawMode(!0)}catch{}Ie.resume(),t()};l.on("close",a),l.on("error",a)})},Io=new Map,To=async e=>{const o=e.trim().toLowerCase(),l=We&&o.startsWith("/")?o.slice(1):o;if(!Oe){if(null!==Re){const o=e.trim(),t=Re;if(Re=null,""===o)console.log(chalk.gray(Je()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=He>0?Date.now()-He:void 0;await v(he,{curriculum_id:pe.id,card_number:t,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(Je()?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Je()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void Ee()}if(Le){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Le=!1,console.log(),console.log(chalk.yellow(Je()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(Je()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(Je()?" 即可执行该命令。":" again to run it.")),console.log(),void Ee();if(!o)return Le=!1,console.log(chalk.gray(Je()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Ee();const t=await I({token:he,nickname:o});if(t.ok)Le=!1,console.log(chalk.bold.green(Je()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Je()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Ne+=1;const e="taken"===t.code?Je()?"已被占用":"already taken":"bad_charset"===t.code?Je()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?Je()?"未通过审核":"did not pass review":t.message||"error";if(!(Ne>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Je()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Ee();Le=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Je()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Ee()}if(Ue){Ue=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Oe=!0;try{console.log(),console.log(chalk.gray(Je()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await x({token:he,cardNumber:ke.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Je()?"评审暂不可用。":"Review unavailable.")}`)),void console.log();(e=>{const o="green"===e.tier?chalk.bold.green:"blue"===e.tier?chalk.bold.cyan:"yellow"===e.tier?chalk.bold.yellow:chalk.bold.red;if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.white(Je()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Je()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Je()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Je()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Je()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Je()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=Je()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(Je()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Je()?` 第 ${e.submissionIndex??"?"} / 2 次提交 · 剩余 ${e.submissionsLeft??0} 次(可先追加 /ai 对话再交)`:` Attempt ${e.submissionIndex??"?"} of 2 · ${e.submissionsLeft??0} left (extend the /ai conversation before your next one)`)),e.feedback){console.log();for(const o of po(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Je()?" 改进提问: ":" Ask better: ")+chalk.gray(e.improve))),console.log(chalk.gray(" ─────────────────────────────────────────")),null!=e.spent&&null!=e.cap&&e.spent/e.cap>.8&&console.log(chalk.gray(` (${Je()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Fe.add(ke.currentCard):Fe.delete(ke.currentCard),"number"==typeof e.rank&&Ke.set(ke.currentCard,e.rank);const o=await q({token:he,curriculumId:pe.id,cardNumber:ke.currentCard});o.ok&&o.totals&&o.chapters&&(ge({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!fe&&(Le=!0,Ne=0,console.log(chalk.bold.yellow(Je()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Je()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Je()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Oe=!1}})():(console.log(chalk.gray(Je()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Se&&(console.log(chalk.gray(Je()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Ee()}if(Ze)return Ze=!1,uo(),void Ee();if(o){if(Ye)return"exit"===await i(e.trim())&&(Ye=!1),void Ee();if(Pe){if(["q","quit","exit","back","b","menu"].includes(o))return Pe=!1,console.log(chalk.gray(Je()?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void Ee();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await ho(n,t?"fast":"deep"),console.log(chalk.gray(Je()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Ee()}if(We&&no){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${no.phase}s${no.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return We=!1,console.log(chalk.gray(Je()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),uo(),void Ee();if(/^\d+$/.test(o))return Ao(o),void Ee();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,r]=e;return"list"===o?ko():r?"read"===o||"open"===o?Ao(r):"edit"===o?await(async e=>{const o=Co(e);if(o){try{n("command -v vi",{stdio:"ignore"})}catch{return console.log(chalk.yellow(Je()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),void console.log(chalk.bold.white(` ${f(no.dir,`sol-${o.n}.py`)}`))}console.log(chalk.gray(Je()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await _o("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(Je()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Je()?" 自测样例。":" to self-check the sample.")),console.log()}})(r):"run"===o?(e=>{const o=Co(e);if(!o)return;const{p:n,n:r}=o,s=f(no.dir,`sol-${r}.py`);if(!d(s))return void console.log(chalk.yellow(Je()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const l=(n.samples??[])[0];if(!l)return void console.log(chalk.gray(Je()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=t("python3",[s],{input:l.in.endsWith("\n")?l.in:`${l.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if(o.killed)console.log(chalk.yellow(Je()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Je()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const i=a.replace(/\r\n/g,"\n").trimEnd(),c=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(Je()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Je()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(Je()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Je()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Je()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Je()?" 改完再 /run。":" then /run again.")),console.log()})(r):"debug"===o?await(async e=>{const o=Co(e);if(!o)return;const t=f(no.dir,`sol-${o.n}.py`);d(t)?(console.log(chalk.gray(Je()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log(),await _o("python3",[`sol-${o.n}.py`]),console.log(),console.log(chalk.gray(Je()?" 回到竞技场。":" Back in the arena.")),console.log()):console.log(chalk.yellow(Je()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`))})(r):"recall"===o&&await(async e=>{const o=Co(e);if(!o)return;if(!we)return void yo();const{p:t,n:n}=o,r=f(process.cwd(),"icoa-contest"),s=`${pe.id}-phase${no.phase}-g${no.data.slot}-archived-`;let l=null;try{for(const e of u(r))e.startsWith(s)&&(!l||e>l)&&(l=e)}catch{}const a=l?f(r,l,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(Je()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${no.phase}-${no.data.slot}-${n}`,g=Math.min(3,(Io.get(c)??0)+1);console.log(chalk.gray(Je()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const y=await _({token:he,phase:no.phase,slot:no.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:Je()?"zh":"en"});if(y.ok){Io.set(c,g),console.log();for(const e of ue(y.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(Je()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(Je()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===y.code?console.log(chalk.yellow(Je()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${y.message}`)):console.log(chalk.yellow(` ${y.message||"Coach unavailable."}`))})(r):console.log(chalk.yellow(Je()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(Je()?" (花名册: /list)":" (roster: /list)")),void Ee()}if("contest"===o||"/contest"===o)return ko(),void Ee();if("submit"!==l&&!l.startsWith("submit ")&&!o.startsWith("contest ")&&"contest reset"!==o&&"menu"!==o&&"menu confirm"!==o)return console.log(chalk.gray(Je()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Ee()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(Je()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Ee()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(Ie.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Ie.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void Ee()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Ye=!0),void Ee();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!we)return yo(),void Ee();je||(je=!0,console.log(),console.log(chalk.bold.cyan(Je()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Je()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Je()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Je()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Pe=!0;const e=oo(ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Je()?"AI 导师":"AI tutor")+(o?chalk.gray(Je()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Je()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Ee()}return await ho(n,t?"fast":"deep"),void Ee()}if(!We&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!we)return yo(),void Ee();const e=oo(ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Je()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Je()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Je()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Je()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Je()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Je()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Je()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Ue=!0,void Ee()}if(!We&&("/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!we)return yo(),void Ee();const e=/^\/?view ([1-3])$/.exec(o);return await(async e=>{Oe=!0;try{console.log();const o=await E({token:he,cardNumber:ke.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Je()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Fe.delete(ke.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Fe.add(ke.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Je()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${ke.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${ke.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Je()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(Je()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=po(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(Je()?" (无可显示的提问)":" (no questions to show)"))}console.log(),De="view",console.log(chalk.gray((Je()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Je()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Oe=!1}})(e?parseInt(e[1],10):void 0),void Ee()}if("/honors"===o||"honors"===o)return fe?(console.log(),console.log(chalk.gray(Je()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Ee()):(await fo(),void Ee());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return ne(pe,ke),void Ee();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(W().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Ee();const t=pe.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,s=r?n:"en";return D({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Se=null,qe=null,Me=null,Re=null,Ze=!1,Ue=!1,uo(),void Ee()}if(["wide","wide on","normal","narrow","wide off"].includes(o)){const e="wide"===o||"wide on"===o;return e===!!W().learnWide?(console.log(chalk.gray(e?Je()?` 已是宽屏(${de()} 列)。输 normal 恢复 64 列。`:` Already wide (${de()} cols). Type normal to restore 64.`:Je()?" 已是标准 64 列。输 wide 拉伸到终端宽度。":" Already at the standard 64 cols. Type wide to stretch.")),void Ee()):(D({learnWide:e}),ce(e),console.log(chalk.green(" ✓ ")+chalk.gray(e?Je()?`宽屏开 — 卡片拉伸到终端宽度(现在 ${de()} 列,上限 96)。输 normal 恢复。`:`Wide mode ON — cards stretch to your terminal (now ${de()} cols, max 96). Type normal to restore.`:Je()?"已恢复 64 列标准宽。输 wide 再拉伸。":"Back to the 64-col standard width. Type wide to stretch again.")),Se=null,qe=null,Me=null,Re=null,Ze=!1,Ue=!1,uo(),void Ee())}if("sim"===o){const e=oo(ke.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=p(b(import.meta.url)),o=[f(e,"..","..","panda","mujoco-launcher.py"),f(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void Ee()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Ee())}if("bookmark"===o){const e=ke.currentCard;return ke.bookmarks.includes(e)||ke.bookmarks.push(e),N(ke),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void Ee()}if("e"===o)return Re=ke.currentCard,console.log(chalk.gray(Je()?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void Ee();if("back"===o||"b"===o)return"view"===De?(await fo(),void Ee()):"honors"===De?(De=null,uo(),void Ee()):(ke.currentCard>1&&(ke.currentCard-=1),qe=null,Me=null,Se=null,N(ke),uo(),void Ee());if("contest"===o||"contest start"===o||"contest status"===o||"contest reset"===o||/^contest [1-9]$/.test(o)){if(!ro)return console.log(chalk.yellow(Je()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Ee();const e=lo(ke.currentCard);if("contest reset"===o){const o=await M(he,e);if(o.ok){console.log(chalk.yellow(Je()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let t=1;t<=3;t++){const n=f(process.cwd(),"icoa-contest",`${pe.id}-phase${e}-g${t}`);if(d(n))try{y(n,`${n}-archived-${o}`),console.log(chalk.gray(Je()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(Je()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(Je()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),no=null,We=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Ee()}const t=/^contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Je()?" 连接判分赛…":" Contacting contest server…"));const n=await S(he,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(Je()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void Ee();const r=n.data,s=f(process.cwd(),"icoa-contest",`${pe.id}-phase${e}-g${r.slot}`);g(s,{recursive:!0});const l=no&&no.phase===e&&no.data.slot===r.slot?no.tried:new Set;no={phase:e,dir:s,data:r,tried:l},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,s=(t.samples??[])[0];s&&h(f(o,`sample-${r}.txt`),s.in.endsWith("\n")?s.in:`${s.in}\n`);const l=f(o,`sol-${r}.py`);if(d(l))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...wo(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),s){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of s.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of s.out.split("\n"))a.push(`# ${e}`)}a.push("#","# ── vi quick guide ── (/edit opens this file in vi)","# i = insert mode — start typing","# Esc = back to command mode","# :wq or ZZ = save & quit · :q! = quit WITHOUT saving","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),h(l,a.join("\n"))})})(r,s),We=!0,ko(),console.log(chalk.gray(Je()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(s));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(Je()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(Je()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Ee()}if("submit"===l)return console.log(chalk.yellow(Je()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(Je()?" 例如 submit 1 判第 1 题(默认判 sol-…q1.py;submit 1 <路径> 判指定文件)":" e.g. submit 1 grades problem 1 (defaults to sol-…q1.py; submit 1 <path> for a custom file)")),no||console.log(chalk.gray(Je()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Ee();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const t=e[2];if(!no)return console.log(chalk.yellow(Je()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Ee();const n=no.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=n.length&&!n.some(e=>e.id===o)&&(o=n[r-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(Je()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Ee();const s=n.findIndex(e=>e.id===o)+1,a=t||f(no.dir,`sol-${s}.py`);let i;try{i=m(a,"utf-8")}catch{return console.log(chalk.red(Je()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Ee()}console.log(chalk.gray(Je()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await R(he,no.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(Je()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((Je()," "))+chalk.bold.green("contest")+chalk.gray(Je()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(Je()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void Ee();const d=c.data;if(d.already_ac)console.log(chalk.green(Je()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(Je()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(Je()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),no.data.solved.includes(o)||no.data.solved.push(o),no.tried.delete(o);else{no.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?Je()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(Je()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=O(d.deadline||"");if(console.log(chalk.white(Je()?` 本组进度: 已过 ${d.ac_count} 题 · 过 ${d.need} 题过关(共 ${d.n} 题)`:` Group progress: ${d.ac_count} solved · ${d.need} needed to pass (${d.n} problems)`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(Je()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await so();else if(!d.late){const e=n.findIndex(e=>!no.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Je()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${bo(n[e])}`))}return void Ee()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>pe.totalCards)return console.log(chalk.yellow(` Card number must be 1..${pe.totalCards}. Try: `)+chalk.bold.green("card 1")),void Ee();const n=await io(t);return n?(console.log(n),void Ee()):(ke.currentCard=t,qe=null,Me=null,Se=null,N(ke),uo(),void Ee())}if(null!==Se&&["y","yes","n","no"].includes(o)){const e=oo(Se);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-He;z(ke,e.number),U(ke,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),N(ke);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),Qe.push(k(he,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Se=null,e.solution&&e.solution.length>0)return void Ee();if(ke.currentCard<pe.totalCards){const e=ke.currentCard,o=await io(e+1);if(o)return await co(e),console.log(o),void Ee();ke.currentCard+=1,N(ke),await co(e)?go():uo(),Ee()}else se(pe,ke),Ee();return}}if(null!==qe&&["a","b","c","d"].includes(o)){const e=oo(qe);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(B(ke,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),z(ke,e.number),N(ke),Q(e,t,n,ke),Qe.push(k(he,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),qe=null,n)if(ke.currentCard<pe.totalCards){const e=await io(ke.currentCard+1);if(e)return console.log(e),void Ee();ke.currentCard+=1,N(ke),uo()}else se(pe,ke),Ee();else Ee();return}}if(null!==Me){if("done"===o){const e=oo(Me);if(e&&"practical"===e.type)return F(ke,e.number),z(ke,e.number),N(ke),G(e),Me=null,void Ee()}if("skip"===o)return z(ke,Me),N(ke),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Me=null,void Ee()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==qe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Ee();if(null!==Me)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Ee();if(null!==Se)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Ee();const e=ke.currentCard,o=e<pe.totalCards?await io(e+1):null;return o?(await co(e),console.log(o),void Ee()):(ke.currentCard+=1,N(ke),ke.currentCard>pe.totalCards?se(pe,ke):await co(e)?go():uo(),void Ee())}if(null!==Se)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Ee();if(null!==qe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Ee();if(null!==Me)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Ee();console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("/ai")+chalk.gray(" / ")+chalk.white("quit")),Ee()}else{if("view"===De)return await fo(),void Ee();if("honors"===De)return De=null,uo(),void Ee();if(Qe.length>0&&await Promise.race([Promise.allSettled(Qe),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ke.streakDays} day(s)`)),console.log(),Ae){Ie.removeAllListeners("line"),xe();for(const e of _e)Ie.on("line",e);Ie.prompt(),Xe()}else Ie.removeAllListeners("line"),Ie.close()}else if(Qe.length>0&&await Promise.race([Promise.allSettled(Qe),new Promise(e=>setTimeout(e,3e3))]),Ie.removeAllListeners("line"),xe(),Ae||!eo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Ae?Ie:void 0),Xe()}else Ie.close()}else Ee()}};Ie.on("line",e=>{To(e).catch(e=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),Ee()})}),Ae||Ie.on("close",async()=>{Qe.length>0&&await Promise.race([Promise.allSettled(Qe),new Promise(e=>setTimeout(e,5e3))]),eo?Xe():process.exit(0)});try{uo(),Ee();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(me("Could not render this card — the curriculum may be malformed."),Ae){Ie.removeAllListeners("line"),xe();for(const e of _e)Ie.on("line",e);Ie.prompt()}else Ie.close();Xe()}await Ge}),ye.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),s=await w(e),l=Date.now()-o;if(s){const e=s.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(s).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${l.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{logCommand as l}from"../lib/logger.js";import{getMainRl as s}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as a,handleAi4ioaiMessage as i,startAi4ioaiChat as c}from"./ai4ioai.js";import{existsSync as d,mkdirSync as g,readdirSync as u,readFileSync as y,renameSync as m,writeFileSync as h}from"node:fs";import{dirname as p,join as f}from"node:path";import{fileURLToPath as w}from"node:url";import{loadCurriculumById as b,validateEAToken as $,syncProgress as k,syncCardFeedback as v}from"../lib/learn-curricula.js";import{normalizeTokenBody as C}from"../lib/token-format.js";import{fetchMyScores as A,recallCoach as _,setNickname as I,streamLearnTutor as T,submitPqs as x,viewPqsTop as E,viewHonors as q}from"../lib/learn-ai.js";import{contestReset as S,contestStart as M,contestSubmit as R,fetchGate as P,timeLeft as O}from"../lib/learn-contest.js";import{getConfig as L,saveConfig as W}from"../lib/config.js";import{loadLearnState as j,saveLearnState as D,newLearnState as N,updateStreak as Y,markCardComplete as z,recordMCQ as B,recordCheck as F,markPracticalComplete as U,addAchievement as Z}from"../lib/learn-state.js";import{renderWelcome as H,renderKnowledgeCard as J,renderMCQCard as K,renderMCQFeedback as Q,renderPracticalCard as V,renderPracticalSuccess as G,renderSimDemoCard as X,renderMilestone as ee,renderArenaTaskCard as oe,renderComingSoonCard as te,renderStatus as ne,renderPhaseComplete as re,renderCurriculumComplete as le,setLearnAiEnabled as se,setLearnHonorRanks as ae,setLearnPqsViewCards as ie,setLearnWide as ce,learnW as de,renderHonorWall as ge,wrapMixed as ue}from"../lib/learn-render.js";import{printError as ye}from"../lib/ui.js";export function registerLearnCommand(me){me.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async me=>{me?.trim()||(console.log(),console.log(chalk.gray(" No token given — starting free 11-card demo (")+chalk.bold.green("LEARNDEMO01")+chalk.gray(").")),console.log(chalk.gray(" Full curriculum: ")+chalk.bold.yellow("learn <your token>")+chalk.gray(" (2 letters + 8 chars) — from your country team leader.")),console.log(),me="LEARNDEMO01");let he=me.trim().toUpperCase(),pe=null;const fe=/^[A-Z0-9]+DEMO01$/i.test(he),we=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(he);let be=!1,$e=!1;if(fe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),pe=await b(he,he);else if(we){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(he);if(!e.ok){const o=C(he);if(o!==he){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${he} → ${o}`)),e=t,he=o)}}if(!e.ok)return ye(`Token validation failed: ${e.message}`),console.log(),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${e.curriculumId} · status: ${e.status}`)+(!0===e.aiEnabled?chalk.bold.magenta(" · ⭐ AI tutor"):"")),be=!0===e.aiEnabled,$e=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),pe=await b(e.curriculumId||"LEARNDEMO01",he),!pe)return ye(`Could not open a learn curriculum for token '${he}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${he}`)+chalk.gray(" instead.")),console.log(chalk.gray(" Otherwise: the full curriculum is ~3 MB; on a slow link the download")),console.log(chalk.gray(" can take a while — stay on a stable connection and run ")+chalk.bold.yellow(`learn ${he}`)+chalk.gray(" again")),console.log(chalk.gray(" (it caches after the first load). If it keeps failing, check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()}if(!pe){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(ye(`Could not reach the learn server to open ${he}.`),console.log(),console.log(chalk.gray(" Your token may be perfectly fine — we could not ask.")),console.log(chalk.gray(" Check your connection, then run ")+chalk.bold.yellow(`learn ${he}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(ye(`Unknown learn token: ${he}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Most tracks have a free demo. From the ")+chalk.bold.green("learn")+chalk.gray(" menu you can type the track name itself")),console.log(chalk.gray(" (e.g. ")+chalk.bold.green("biology")+chalk.gray(", ")+chalk.bold.green("ioipy")+chalk.gray(") and it opens that track's demo if one is published.")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log())}let ke=j(),ve=!1;try{ke&&ke.token===he?Y(ke):(ke=N(he,pe.id,pe.totalCards),ve=!0),D(ke),H(pe,ke,ve)}catch{return ye("Could not open this curriculum — it may be malformed or not a learn curriculum."),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${he}`)+chalk.gray(".")),void console.log()}const Ce=s(),Ae=null!==Ce,_e=Ae?Ce.listeners("line").slice():[];Ae&&Ce.removeAllListeners("line");const Ie=Ae?Ce:o({input:process.stdin,output:process.stdout,terminal:!0}),Te=Ae?Ie.prompt:null;Ae&&(Ie.prompt=e.prototype.prompt);const xe=()=>{Ae&&Te&&(Ie.prompt=Te)},Ee=()=>{Ie.setPrompt(Ye?chalk.bold.green(`icoa ${a()}> `):Le?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Pe?"icoa learn ai> ":"icoa learn> ")),Ie.prompt()};let qe=null,Se=null,Me=null,Re=null,Pe=!1,Oe=!1,Le=!1,We=null,je=!1,De=0,Ne=!1,Ye=!1;const ze=new Map,Be=()=>{let e=ze.get(ke.currentCard);return e||(e=[],ze.set(ke.currentCard,e)),e};let Fe=!1;const Ue=new Set;let Ze=!1,He=0;const Je=()=>(L().language||"en").toLowerCase().startsWith("zh");se(be),ce(!!L().learnWide),ie(Ue);const Ke=new Map;ae(Ke);const Qe=[];let Ve=null;const Ge=new Promise(e=>{Ve=e}),Xe=()=>{const e=Ve;Ve=null,e?.()},eo="1"===process.env.ICOA_LEARN_EMBEDDED,oo=e=>pe.cards.find(o=>o.number===e);let to=null,no=null;const ro=!he.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(he),lo=async()=>{if(!ro)return;const e=await P(he);e.ok&&e.data&&(to=e.data)},so=e=>{const o=pe.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},ao=e=>{if(!$e||!to)return null;const o=so(e);if(o<=to.unlocked_through_phase)return null;const t=to.phases.find(e=>e.phase===to.unlocked_through_phase),n=[chalk.yellow(Je()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${to.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${to.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(Je()?` ⚔ 练习赛 ${to.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${to.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(Je()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(Je()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},io=async e=>$e?null===ao(e)?null:(await lo(),ao(e)):null;$e&&await lo();const co=async e=>{const o=pe.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=pe.modules.find(e=>e.number===o.number+1);let n;if(be){const e=await A({token:he,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}ro&&await lo();const r=to?.phases.find(e=>e.phase===o.number);return re(pe,ke,o,t,n,r),!0},go=()=>{Ze=!0,console.log(chalk.gray(Je()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},uo=()=>{We=null;const e=oo(ke.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":J(e,pe),e.check?(Me=e.number,He=Date.now()):(z(ke,e.number),D(ke));break;case"mcq":K(e,pe),qe=e.number;break;case"practical":V(e,pe),Se=e.number;break;case"sim_demo":X(e,pe),z(ke,e.number),D(ke);break;case"milestone":ee(e,pe),Z(ke,e.badge),z(ke,e.number),D(ke);break;case"arena_task":oe(e,pe),z(ke,e.number),D(ke);break;case"coming_soon":te(e,pe),z(ke,e.number),D(ke)}yo(e.number)},yo=e=>{if(!$e||!ro||!to)return;const o=pe.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1;if(t%4!=0)return;const n=t/4,r=to.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===n);if(!l)return;const s=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),s=(n||"").slice(0,10);return`🏆 ${e} ${o}/${l.n}`+(r?Je()?` · 用时 ${r}`:` · ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(de());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${Je()?"练习赛":"PY Arena"} ${o.number}-${n}`)+(l.passed?chalk.bold.green(Je()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(Je()?console.log(c+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(c+chalk.white("You learned the cards — now prove it.")),console.log(c+chalk.white("The clock starts the moment you type the command."))),console.log(c+chalk.gray(Je()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(Je()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))),a.length>0)for(const e of a)console.log(c+chalk.bold.yellow(s(Je()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(Je()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(l.passed?chalk.gray(Je()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Je()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(Je()?" 继续学习":" keep going"):chalk.gray(Je()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(Je()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},mo=()=>{he.endsWith("DEMO01")?console.log(chalk.yellow(Je()?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Je()?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Je()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},ho=async(e,o)=>{if(be){Oe=!0;try{console.log(),console.log(chalk.gray("deep"===o?Je()?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Je()?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await T({token:he,cardNumber:ke.currentCard,question:e,mode:o,history:Be().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(Je()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Be().push({role:"user",content:e},{role:"assistant",content:r.answer}),null!=r.spent&&null!=r.cap&&r.spent/r.cap>.8&&console.log(chalk.gray(` (${Je()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Je()?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==Me&&console.log(chalk.gray(Je()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Oe=!1}}else mo()},po=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],fo=async()=>{Le&&no?_o?Io(_o):vo():We?await wo():uo()},wo=async()=>{Oe=!0;try{console.log();const e=await q({token:he,curriculumId:pe.id,cardNumber:ke.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Je()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Je()?` 🏆 本卡实时 Top-3 — 第 ${ke.currentCard} 张`:` 🏆 Live top-3 — card ${ke.currentCard}`)),e.board&&0!==e.board.length)for(const o of e.board){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(chalk.white(` ${o.icon} `)+chalk.bold.cyan(o.name||`Rank ${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(Je()?" (你)":" (you)"):""))}else console.log(chalk.gray(Je()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Ke.set(ke.currentCard,e.mine.rank),console.log(chalk.white(Je()?" 你: ":" You: ")+chalk.bold.yellow(Je()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Je()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):be&&console.log(chalk.gray(Je()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),ge({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Je()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Je()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Je()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),We="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Je()?" 返回卡片":" returns to the card")),console.log()}finally{Oe=!1}},bo=e=>Je()&&e.title_zh||e.title,$o=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of ue(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},ko=e=>no.data.solved.includes(e.id)?"✅":no.tried.has(e.id)?"❌":"⬜",vo=()=>{const e=no.data,o=O(e.deadline),t=e.solved.length,n=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(Je()?` · 第 ${e.slot}/${e.group_count} 组 · 第 ${e.attempt} 次尝试${e.resumed?"(续)":""}`:` · group ${e.slot}/${e.group_count} · attempt ${e.attempt}${e.resumed?" (resumed)":""}`)),console.log((o?chalk.bold.yellow(` ⏱ ${o}`):chalk.red(Je()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(Je()?`(共 ${e.n} 题)`:` (of ${e.n})`));const r=Date.parse(e.deadline)-Date.now();o?e.resumed&&r<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(Je()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Je()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(Je()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(Je()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+ko(e)+chalk.white(` ${bo(e)}`))}),console.log(),Co()},Co=()=>{console.log(chalk.gray(Je()?" /read <n> 读题 · /edit <n> 写码(vi) · /run <n> 样例自测 · /debug <n> 自由调试 · /submit <n> 判分":" /read <n> statement · /edit <n> code (vi) · /run <n> sample check · /debug <n> free run · /submit <n> judge")),console.log(chalk.gray(Je()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Je()?" 返回课程":" returns to the lesson")),console.log()},Ao=e=>{const o=parseInt(e,10),t=no.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(Je()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}};let _o=null;const Io=e=>{const o=Ao(e);if(!o)return;const{p:t,n:n}=o;_o=String(n),console.log(),console.log(chalk.bold.white(` ${ko(t)} ${bo(t)}`)),console.log();for(const e of(e=>Je()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of ue(e,de()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(Je()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Je()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(Je()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(Je()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Je()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(Je()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(Je()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Je()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((Je()," ↩ "))+chalk.bold.green("back")+chalk.gray(Je()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(Je()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((Je()," / "))+chalk.bold.green("wide")+chalk.gray(Je()?" 换语言/宽度":" language / width")),console.log()},To=async(e,o)=>{await new Promise(t=>{const n=process.stdin,l=!!n.isTTY&&!!n.isRaw;if(Ie.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:no.dir}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&l)try{n.setRawMode(!0)}catch{}Ie.resume(),t()};s.on("close",a),s.on("error",a)})},xo=new Map,Eo=async e=>{const o=e.trim().toLowerCase(),s=Le&&o.startsWith("/")?o.slice(1):o;if(Oe)return;if(null!==Re){const o=e.trim(),t=Re;if(Re=null,""===o)console.log(chalk.gray(Je()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=He>0?Date.now()-He:void 0;await v(he,{curriculum_id:pe.id,card_number:t,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(Je()?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Je()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void Ee()}if(je){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return je=!1,console.log(),console.log(chalk.yellow(Je()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(Je()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(Je()?" 即可执行该命令。":" again to run it.")),console.log(),void Ee();if(!o)return je=!1,console.log(chalk.gray(Je()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Ee();const t=await I({token:he,nickname:o});if(t.ok)je=!1,console.log(chalk.bold.green(Je()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Je()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{De+=1;const e="taken"===t.code?Je()?"已被占用":"already taken":"bad_charset"===t.code?Je()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?Je()?"未通过审核":"did not pass review":t.message||"error";if(!(De>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Je()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Ee();je=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Je()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Ee()}if(Fe){Fe=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Oe=!0;try{console.log(),console.log(chalk.gray(Je()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await x({token:he,cardNumber:ke.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Je()?"评审暂不可用。":"Review unavailable.")}`)),void console.log();(e=>{const o="green"===e.tier?chalk.bold.green:"blue"===e.tier?chalk.bold.cyan:"yellow"===e.tier?chalk.bold.yellow:chalk.bold.red;if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.white(Je()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Je()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Je()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Je()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Je()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Je()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=Je()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(Je()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Je()?` 第 ${e.submissionIndex??"?"} / 2 次提交 · 剩余 ${e.submissionsLeft??0} 次(可先追加 /ai 对话再交)`:` Attempt ${e.submissionIndex??"?"} of 2 · ${e.submissionsLeft??0} left (extend the /ai conversation before your next one)`)),e.feedback){console.log();for(const o of po(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Je()?" 改进提问: ":" Ask better: ")+chalk.gray(e.improve))),console.log(chalk.gray(" ─────────────────────────────────────────")),null!=e.spent&&null!=e.cap&&e.spent/e.cap>.8&&console.log(chalk.gray(` (${Je()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Ue.add(ke.currentCard):Ue.delete(ke.currentCard),"number"==typeof e.rank&&Ke.set(ke.currentCard,e.rank);const o=await q({token:he,curriculumId:pe.id,cardNumber:ke.currentCard});o.ok&&o.totals&&o.chapters&&(ge({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!fe&&(je=!0,De=0,console.log(chalk.bold.yellow(Je()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Je()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Je()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Oe=!1}})():(console.log(chalk.gray(Je()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Me&&(console.log(chalk.gray(Je()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Ee()}if(Ze)return Ze=!1,uo(),void Ee();if(!o)return void Ee();if(Ye)return"exit"===await i(e.trim())&&(Ye=!1),void Ee();if(Pe){if(["q","quit","exit","back","b","menu"].includes(o))return Pe=!1,console.log(chalk.gray(Je()?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void Ee();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await ho(n,t?"fast":"deep"),console.log(chalk.gray(Je()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Ee()}if(Le&&no){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${no.phase}s${no.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Le=!1,console.log(chalk.gray(Je()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),uo(),void Ee();if(/^\d+$/.test(o))return Io(o),void Ee();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,r]=e;return"list"===o?vo():r?"read"===o||"open"===o?Io(r):"edit"===o?await(async e=>{const o=Ao(e);if(o){try{n("command -v vi",{stdio:"ignore"})}catch{return console.log(chalk.yellow(Je()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),void console.log(chalk.bold.white(` ${f(no.dir,`sol-${o.n}.py`)}`))}console.log(chalk.gray(Je()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await To("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(Je()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Je()?" 自测样例。":" to self-check the sample.")),console.log()}})(r):"run"===o?(e=>{const o=Ao(e);if(!o)return;const{p:n,n:r}=o,l=f(no.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(Je()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const s=(n.samples??[])[0];if(!s)return void console.log(chalk.gray(Je()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=t("python3",[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if(o.killed)console.log(chalk.yellow(Je()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Je()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const i=a.replace(/\r\n/g,"\n").trimEnd(),c=s.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(Je()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Je()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(Je()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Je()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Je()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Je()?" 改完再 /run。":" then /run again.")),console.log()})(r):"debug"===o?await(async e=>{const o=Ao(e);if(!o)return;const t=f(no.dir,`sol-${o.n}.py`);d(t)?(console.log(chalk.gray(Je()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log(),await To("python3",[`sol-${o.n}.py`]),console.log(),console.log(chalk.gray(Je()?" 回到竞技场。":" Back in the arena.")),console.log()):console.log(chalk.yellow(Je()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`))})(r):"recall"===o&&await(async e=>{const o=Ao(e);if(!o)return;if(!be)return void mo();const{p:t,n:n}=o,r=f(process.cwd(),"icoa-contest"),l=`${pe.id}-phase${no.phase}-g${no.data.slot}-archived-`;let s=null;try{for(const e of u(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?f(r,s,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(Je()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${no.phase}-${no.data.slot}-${n}`,g=Math.min(3,(xo.get(c)??0)+1);console.log(chalk.gray(Je()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await _({token:he,phase:no.phase,slot:no.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:Je()?"zh":"en"});if(m.ok){xo.set(c,g),console.log();for(const e of ue(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(Je()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(Je()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(Je()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(r):console.log(chalk.yellow(Je()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(Je()?" (花名册: /list)":" (roster: /list)")),void Ee()}if("contest"===o||"/contest"===o)return vo(),void Ee();const r="lang"===o||/^lang\s+\S+$/.test(o),a=/^(wide|wide on|wide off|normal|narrow)$/.test(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||r||a||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(Je()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Ee()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(Je()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Ee()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(Ie.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Ie.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Ee()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Ye=!0),void Ee();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!be)return mo(),void Ee();Ne||(Ne=!0,console.log(),console.log(chalk.bold.cyan(Je()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Je()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Je()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Je()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Pe=!0;const e=oo(ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Je()?"AI 导师":"AI tutor")+(o?chalk.gray(Je()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Je()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Ee()}return await ho(n,t?"fast":"deep"),void Ee()}if(!Le&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!be)return mo(),void Ee();const e=oo(ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Je()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Je()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Je()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Je()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Je()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Je()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Je()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Fe=!0,void Ee()}const a=!Le&&"honors"===We&&/^[1-3]$/.test(o);if(!Le&&We&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(Je()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(Je()?" ↩ back 回上一层":" ↩ back goes up one level")),void Ee();if(!Le&&(a||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!be)return mo(),void Ee();const e=/^\/?view ([1-3])$/.exec(o),t=a?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Oe=!0;try{console.log();const o=await E({token:he,cardNumber:ke.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Je()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Ue.delete(ke.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Ue.add(ke.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Je()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${ke.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${ke.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Je()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(Je()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=po(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(Je()?" (无可显示的提问)":" (no questions to show)"))}console.log(),We="view",console.log(chalk.gray((Je()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Je()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Oe=!1}})(t),void Ee()}if("/honors"===o||"honors"===o)return fe?(console.log(),console.log(chalk.gray(Je()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Ee()):(await wo(),void Ee());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return ne(pe,ke),void Ee();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(L().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Ee();const t=pe.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,l=r?n:"en";return W({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Me=null,qe=null,Se=null,Re=null,Ze=!1,Fe=!1,await fo(),void Ee()}if(["wide","wide on","normal","narrow","wide off"].includes(o)){const e="wide"===o||"wide on"===o;return e===!!L().learnWide?(console.log(chalk.gray(e?Je()?` 已是宽屏(${de()} 列)。输 normal 恢复 64 列。`:` Already wide (${de()} cols). Type normal to restore 64.`:Je()?" 已是标准 64 列。输 wide 拉伸到终端宽度。":" Already at the standard 64 cols. Type wide to stretch.")),void Ee()):(W({learnWide:e}),ce(e),console.log(chalk.green(" ✓ ")+chalk.gray(e?Je()?`宽屏开 — 卡片拉伸到终端宽度(现在 ${de()} 列,上限 96)。输 normal 恢复。`:`Wide mode ON — cards stretch to your terminal (now ${de()} cols, max 96). Type normal to restore.`:Je()?"已恢复 64 列标准宽。输 wide 再拉伸。":"Back to the 64-col standard width. Type wide to stretch again.")),Me=null,qe=null,Se=null,Re=null,Ze=!1,Fe=!1,await fo(),void Ee())}if("sim"===o){const e=oo(ke.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=p(w(import.meta.url)),o=[f(e,"..","..","panda","mujoco-launcher.py"),f(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void Ee()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Ee())}if("bookmark"===o){const e=ke.currentCard;return ke.bookmarks.includes(e)||ke.bookmarks.push(e),D(ke),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void Ee()}if("e"===o)return Re=ke.currentCard,console.log(chalk.gray(Je()?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void Ee();if("back"===o||"b"===o)return"view"===We?(await wo(),void Ee()):"honors"===We?(We=null,uo(),void Ee()):(ke.currentCard>1&&(ke.currentCard-=1),qe=null,Se=null,Me=null,D(ke),uo(),void Ee());if("contest"===o||"/contest"===o||"arena"===o||"contest start"===o||"/contest start"===o||"contest status"===o||"contest reset"===o||/^\/?contest [1-9]$/.test(o)){if(!ro)return console.log(chalk.yellow(Je()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Ee();const e=so(ke.currentCard);if("contest reset"===o){const o=await S(he,e);if(o.ok){console.log(chalk.yellow(Je()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let t=1;t<=3;t++){const n=f(process.cwd(),"icoa-contest",`${pe.id}-phase${e}-g${t}`);if(d(n))try{m(n,`${n}-archived-${o}`),console.log(chalk.gray(Je()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(Je()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(Je()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),no=null,Le=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Ee()}const t=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Je()?" 连接判分赛…":" Contacting contest server…"));const n=await M(he,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(Je()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void Ee();const r=n.data,l=f(process.cwd(),"icoa-contest",`${pe.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=no&&no.phase===e&&no.data.slot===r.slot?no.tried:new Set;no={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,l=(t.samples??[])[0];l&&h(f(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=f(o,`sol-${r}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...$o(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.out.split("\n"))a.push(`# ${e}`)}a.push("#","# ── vi quick guide ── (/edit opens this file in vi)","# i = insert mode — start typing","# Esc = back to command mode","# :wq or ZZ = save & quit · :q! = quit WITHOUT saving","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),h(s,a.join("\n"))})})(r,l),Le=!0,vo(),console.log(chalk.gray(Je()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(Je()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(Je()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Ee()}if("submit"===s)return console.log(chalk.yellow(Je()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(Je()?" 例如 submit 1 判第 1 题(默认判 sol-…q1.py;submit 1 <路径> 判指定文件)":" e.g. submit 1 grades problem 1 (defaults to sol-…q1.py; submit 1 <path> for a custom file)")),no||console.log(chalk.gray(Je()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Ee();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!no)return console.log(chalk.yellow(Je()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Ee();const n=no.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=n.length&&!n.some(e=>e.id===o)&&(o=n[r-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(Je()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Ee();const l=n.findIndex(e=>e.id===o)+1,a=t||f(no.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(Je()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Ee()}console.log(chalk.gray(Je()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await R(he,no.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(Je()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((Je()," "))+chalk.bold.green("contest")+chalk.gray(Je()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(Je()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void Ee();const d=c.data;if(d.already_ac)console.log(chalk.green(Je()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(Je()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(Je()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),no.data.solved.includes(o)||no.data.solved.push(o),no.tried.delete(o);else{no.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?Je()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(Je()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=O(d.deadline||"");if(console.log(chalk.white(Je()?` 本组进度: 已过 ${d.ac_count} 题 · 过 ${d.need} 题过关(共 ${d.n} 题)`:` Group progress: ${d.ac_count} solved · ${d.need} needed to pass (${d.n} problems)`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(Je()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await lo();else if(!d.late){const e=n.findIndex(e=>!no.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Je()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${bo(n[e])}`))}return void Ee()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>pe.totalCards)return console.log(chalk.yellow(` Card number must be 1..${pe.totalCards}. Try: `)+chalk.bold.green("card 1")),void Ee();const n=await io(t);return n?(console.log(n),void Ee()):(ke.currentCard=t,qe=null,Se=null,Me=null,D(ke),uo(),void Ee())}if(null!==Me&&["y","yes","n","no"].includes(o)){const e=oo(Me);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-He;z(ke,e.number),F(ke,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),D(ke);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),Qe.push(k(he,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Me=null,e.solution&&e.solution.length>0)return void Ee();if(ke.currentCard<pe.totalCards){const e=ke.currentCard,o=await io(e+1);if(o)return await co(e),console.log(o),void Ee();ke.currentCard+=1,D(ke),await co(e)?go():uo(),Ee()}else le(pe,ke),Ee();return}}if(null!==qe&&["a","b","c","d"].includes(o)){const e=oo(qe);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(B(ke,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),z(ke,e.number),D(ke),Q(e,t,n,ke),Qe.push(k(he,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),qe=null,n)if(ke.currentCard<pe.totalCards){const e=await io(ke.currentCard+1);if(e)return console.log(e),void Ee();ke.currentCard+=1,D(ke),uo()}else le(pe,ke),Ee();else Ee();return}}if(null!==Se){if("done"===o){const e=oo(Se);if(e&&"practical"===e.type)return U(ke,e.number),z(ke,e.number),D(ke),G(e),Se=null,void Ee()}if("skip"===o)return z(ke,Se),D(ke),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Se=null,void Ee()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==qe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Ee();if(null!==Se)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Ee();if(null!==Me)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Ee();const e=ke.currentCard,o=e<pe.totalCards?await io(e+1):null;return o?(await co(e),console.log(o),void Ee()):(ke.currentCard+=1,D(ke),ke.currentCard>pe.totalCards?le(pe,ke):await co(e)?go():uo(),void Ee())}if(null!==Me)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Ee();if(null!==qe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Ee();if(null!==Se)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Ee();"view"===We?console.log(chalk.gray(Je()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(Je()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(Je()?" 回卡片":" to the card")):"honors"===We?console.log(chalk.gray(Je()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(Je()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(Je()?" 回卡片":" to the card")):console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("/ai")+chalk.gray(" / ")+chalk.white("quit")),Ee()}else{if("view"===We)return await wo(),void Ee();if("honors"===We)return We=null,uo(),void Ee();if(Qe.length>0&&await Promise.race([Promise.allSettled(Qe),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ke.streakDays} day(s)`)),console.log(),Ae){Ie.removeAllListeners("line"),xe();for(const e of _e)Ie.on("line",e);Ie.prompt(),Xe()}else Ie.removeAllListeners("line"),Ie.close()}else if(Qe.length>0&&await Promise.race([Promise.allSettled(Qe),new Promise(e=>setTimeout(e,3e3))]),Ie.removeAllListeners("line"),xe(),Ae||!eo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Ae?Ie:void 0),Xe()}else Ie.close()};Ie.on("line",e=>{Eo(e).catch(e=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),Ee()})}),Ae||Ie.on("close",async()=>{Qe.length>0&&await Promise.race([Promise.allSettled(Qe),new Promise(e=>setTimeout(e,5e3))]),eo?Xe():process.exit(0)});try{uo(),Ee();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(ye("Could not render this card — the curriculum may be malformed."),Ae){Ie.removeAllListeners("line"),xe();for(const e of _e)Ie.on("line",e);Ie.prompt()}else Ie.close();Xe()}await Ge}),me.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await b(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
@@ -0,0 +1,7 @@
1
+ import type { Command } from 'commander';
2
+ export declare function isSprintActive(): boolean;
3
+ /**
4
+ * Entry point. Hidden keyword → manifesto (first time) → CTF-style list loop.
5
+ */
6
+ export declare function runSprint(): Promise<void>;
7
+ export declare function registerSprintCommand(program: Command): void;
@@ -0,0 +1 @@
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,writeFileSync as t}from"node:fs";import{dirname as s,join as l}from"node:path";import{fileURLToPath as r}from"node:url";import chalk from"chalk";import{getMainRl as a}from"../lib/main-rl.js";import{logCommand as c}from"../lib/logger.js";let i=!1;export function isSprintActive(){return i}const g=s(r(import.meta.url)),y=l(process.env.HOME||".",".icoa"),p=l(y,"sprint-state.json"),d={"T-torch":"裸 torch:手写 attention / causal mask / perplexity","T-umap":"降维当特征提取器,不是画图工具","T-lora":"peft LoRA 参数高效微调","T-librosa":"音频特征流水线:mel / MFCC → 定长向量"},u=["",chalk.bold.cyan(" ASTANA 2027"),chalk.gray(" — 给还没出发的你"),"",chalk.white(" 草原的风从额尔齐斯河吹到阿斯塔纳的时候,会带着一点雪的味道。"),chalk.white(" 你还没去过那里。但那里已经有一个座位,写着你的名字。"),"",chalk.white(" 你现在坐在屏幕前,离比赛还有几天。"),chalk.white(" 你可能会想:几天能改变什么?"),"",chalk.white(" 足够让一个人从「看着题发呆」变成「看到题就知道该拆哪一层」。"),chalk.white(" 足够让手指记住 import torch 之后该敲什么。"),chalk.white(" 足够让你在比赛那天早上醒来时,不再害怕。"),"",chalk.bold.yellow(" M")+chalk.white(" —— 你总是第一个说「我先试试」的那个。别停。"),chalk.bold.yellow(" V")+chalk.white(" —— 你总是问「为什么是这样」的那个。继续问。"),chalk.bold.yellow(" A")+chalk.white(" —— 你总是在别人放弃时还在改最后一版的那个。改下去。"),"",chalk.white(" 你们三个人,一个人是一条腿走路,三个人是奔跑。"),"",chalk.white(" 你们要面对的不是一场考试,是一次证明:"),chalk.bold.white(" 中国的高中生,可以在 AI 的赛场上,和世界站在同一排。"),"",chalk.white(" 而 2027 年的阿斯塔纳,是我们下一个约定。"),"",chalk.gray(" 现在,把这行字关掉,去做第 1 题。"),chalk.gray(" — 熊猫教练"),""];function h(e){const n=[l(g,"..","data",e),l(g,"..","..","src","data",e)];for(const e of n)if(o(e))return e;return n[0]}function f(o){try{e(y,{recursive:!0}),t(p,`${JSON.stringify(o,null,1)}\n`)}catch{}}function m(o){return"★".repeat(Math.max(1,Math.min(5,o||3)))}function w(o,e){const n=new Set(e.done),t=new Set(e.opened);console.log(),console.log(chalk.bold.cyan(" ⚔ IOAI 2026 · 四工具冲刺")+chalk.gray(` 已攻克 ${n.size} / ${o.length}`));const s=new Map;for(const e of o)s.has(e.bullseye)||s.set(e.bullseye,[]),s.get(e.bullseye)?.push(e);for(const[o,e]of s){console.log(),console.log(chalk.bold.white(` ${o}`)+chalk.gray(` — ${d[o]||""}`));for(const o of e){const e=n.has(o.seq)?chalk.green("✓"):t.has(o.seq)?chalk.yellow("◐"):chalk.gray("⬜");console.log(` ${e} ${chalk.bold.white(String(o.seq).padStart(2))} `+chalk.white(o.title.slice(0,34).padEnd(34))+chalk.gray(m(o.difficulty).padEnd(5))+chalk.gray(o.needs_gpu?" ⚡":" ")+chalk.gray(` ${o.data_mb}M`))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(" 看题 · ")+chalk.cyan("done <n>")+chalk.gray(" 标记攻克 · ")+chalk.cyan("ai")+chalk.gray(" 问 Gemma · ")+chalk.cyan("back")+chalk.gray(" 退出")),console.log(chalk.gray(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克")),console.log()}function b(o,e){const n=[];let t="",s=0;for(const l of o){const o=/[ -鿿＀-￯]/.test(l)?2:1;s+o>e&&(n.push(t),t="",s=0),t+=l,s+=o}return t&&n.push(t),n}export async function runSprint(){c("sprint");const o=function(){try{const o=JSON.parse(n(h("sprint-tasks.json"),"utf8")),e=Array.isArray(o?.tasks)?o.tasks:[];try{const o=JSON.parse(n(h("sprint-cards.json"),"utf8")),t=new Map((o.cards||[]).map(o=>[o.seq,o]));for(const o of e){const e=t.get(o.seq);e&&Object.assign(o,{star:e.star,trap:e.trap,action:e.action,meta:e.meta})}}catch{}return e.sort((o,e)=>o.seq-e.seq)}catch{return[]}}();if(0===o.length)return console.log(),console.log(chalk.yellow(" 冲刺题单还没装进这个版本。")),console.log(chalk.gray(" 升级后再试:")+chalk.cyan("npm install -g icoa-cli@latest")),void console.log();const e=function(){try{const o=JSON.parse(n(p,"utf8"));return{who:o.who||"",opened:o.opened||[],done:o.done||[]}}catch{return{who:"",opened:[],done:[]}}}();if(0===e.opened.length&&0===e.done.length)for(const o of u)console.log(o);e.who||(e.who=""),w(o,e);const t=a();if(null===t)return;const s=t.listeners("line").slice();t.removeAllListeners("line");const l=t.prompt.bind(t);i=!0,t.setPrompt(chalk.bold.cyan("icoa ioai2026> ")),await new Promise(n=>{t.on("line",async r=>{const a=r.trim(),[c,g]=[a.split(/\s+/)[0]?.toLowerCase()||"",a.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(c))return f(e),console.log(chalk.gray(" 进度已保存。")),(()=>{i=!1,t.removeAllListeners("line");for(const o of s)t.on("line",o);t.setPrompt(chalk.green("icoa> ")),t.prompt()})(),void n();if(""===c||["challenges","list","ls"].includes(c))w(o,e);else if(["open","o"].includes(c)||/^\d+$/.test(c)){const n=Number.parseInt(/^\d+$/.test(c)?c:g,10),t=o.find(o=>o.seq===n);t?(e.opened.includes(n)||e.opened.push(n),f(e),function(o){console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(`${o.seq} · ${o.title}`)+chalk.gray(` · ${o.bullseye}`)+chalk.cyan(" ─────")),console.log(chalk.cyan(" │"));const e=[o.star,o.trap,o.action].filter(Boolean);0===e.length&&o.topic_cn&&e.push(`▸ ${o.topic_cn}`);for(const o of e){for(const e of b(o,58))console.log(chalk.cyan(" │ ")+chalk.white(e));console.log(chalk.cyan(" │"))}console.log(chalk.cyan(" │ ")+chalk.gray(o.meta||`⏱ 难度 ${m(o.difficulty)}`)+chalk.gray(o.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────")),console.log(chalk.gray(" ")+chalk.cyan("ai")+chalk.gray(" 问 Gemma · ")+chalk.cyan(`done ${o.seq}`)+chalk.gray(" 标记攻克 · ")+chalk.cyan("back")+chalk.gray(" 回列表")),console.log()}(t)):console.log(chalk.yellow(` 没有第 ${g||c} 题。`)+chalk.gray(` 题号 1-${o.length}。`))}else if("done"===c){const n=Number.parseInt(g,10);o.some(o=>o.seq===n)?(e.done.includes(n)||e.done.push(n),f(e),console.log(chalk.green(` ✓ 第 ${n} 题标记为攻克`)+chalk.gray(` (${e.done.length}/${o.length})`))):console.log(chalk.yellow(` 题号 1-${o.length}。`))}else"ai"===c?(console.log(),console.log(chalk.gray(" 开另一个窗口问 Gemma:")+chalk.cyan(" Ctrl-b %")+chalk.gray(" 分屏,右边输 ")+chalk.cyan("icoa")+chalk.gray(" 再输 ")+chalk.cyan("ai4ioai")),console.log(chalk.gray(" 它是弱模型,单轮、2000 字符以内 —— 把问题问准是这次要练的本事。")),console.log()):["help","?","guide"].includes(c)?w(o,e):console.log(chalk.gray(" ")+chalk.cyan("challenges")+chalk.gray(" 列表 · ")+chalk.cyan("open <n>")+chalk.gray(" 看题 · ")+chalk.cyan("done <n>")+chalk.gray(" 标记 · ")+chalk.cyan("back")+chalk.gray(" 退出"));t.prompt=l,t.prompt()}),t.prompt=l,t.prompt()})}export function registerSprintCommand(o){o.command("pandahelpme31",{hidden:!0}).action(async()=>{await runSprint()})}