icoa-cli 2.19.446 → 2.19.448

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.
@@ -17,3 +17,4 @@
17
17
  */
18
18
  import type { Command } from 'commander';
19
19
  export declare function registerIpynbCommand(program: Command): void;
20
+ export declare function runIpynb(file?: string): Promise<void>;
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as g,resolve as y}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as u,askIoaiOneShot as h}from"./ai4ioai.js";import{getConfig as p}from"../lib/config.js";import{editTextInEditor as m}from"../lib/editor-spawn.js";import{buildSshArgs as f,leaseConnectProblems as w,parseLeaseResponse as b,queueLine as k}from"../lib/gpu.js";import{shouldExecuteCell as v}from"../lib/ipynb-input.js";import{looksLikeMarkdown as $,renderMarkdown as x}from"../lib/md-term.js";import{NotebookKernel as P,buildRemoteBridgeCommand as E}from"../lib/kernel.js";import{getMainRl as G}from"../lib/main-rl.js";import{logCommand as S}from"../lib/logger.js";import{startLogSync as A,stopLogSync as N}from"../lib/log-sync.js";import{cellPreview as j,parseIpynb as q,parsePercentPy as U,parseRunRange as I,serializeIpynb as O,statusChar as C}from"../lib/notebook-doc.js";import{openFile as _}from"../lib/open-file.js";const L=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function T(){return(p().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(p){p.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async p=>{await async function(p){const b=d(t()),K=g(t(),".icoa","ipynb-out");if(R(),!e(b.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const V=p?function(o){const l=i(o)?o:y(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?q(e):U(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(p):null,Q=V?V.doc:{cells:[],path:null,dirty:!1};let X=new P({venvPython:b.python,venvRoot:b.root}),Z=null,ee=z(Q.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await X.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),V&&console.log(V.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const oe=G(),ne=null!==oe,le=ne?oe.listeners("line").slice():[];ne&&oe.removeAllListeners("line");const te=ne?oe:a({input:process.stdin,output:process.stdout,terminal:!0}),re=ne?te.prompt:null;ne&&(te.prompt=r.prototype.prompt),ne||A();const ae=[];let se=!1,ce=!1,ie=!1;const ge=()=>{const e=Z?"icoa ipynb ⚡gpu":"icoa ipynb";te.setPrompt(chalk.bold.cyan(ae.length?`${e} ...> `:`${e}> `)),te.prompt()};let ye=()=>{};const de=new Promise(e=>{ye=e}),ue=async()=>{if(!Z)return void console.log(chalk.gray(" not on a GPU kernel."));const e=J();await X.shutdown().catch(()=>{}),e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{X=new P({venvPython:b.python,venvRoot:b.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await X.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},he=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(Z)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=J();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));ee||(ee=z(Q.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await Y("lease",e,ee??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(k(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await Y("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=w(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await Y("release",e);const s=ee?`${n.dataRoot}/${ee}`:n.dataRoot,c=E(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=g(t(),".icoa","gpu","lease-key");try{o(g(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await Y("release",e)}i={command:"ssh",args:f(n,r,c)}}const y=new P({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await y.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await Y("release",e)}await X.shutdown().catch(()=>{}),X=y,Z=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),ee&&console.log(chalk.gray(` Dataset is already on the box (${ee}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await ue():"status"===a||""===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await Y("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Z?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${k(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${B()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(g(t(),".icoa"),{recursive:!0}),l(W(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${W()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},pe=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Q.cells.length?(console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Q.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Q.cells[o-1],idx:o}},me=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let fe=!1;const we=async e=>{const o=e.trim().split(/\s+/).filter(Boolean),l=o.length>0&&/^\d+$/.test(o[0]),t=(l?o.slice(1):o).join(" ").trim(),r=l?Number(o[0]):(()=>{for(let e=Q.cells.length-1;e>=0;e--)if((Q.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Q.cells.length;if(0===Q.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=pe(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(L,"")).join("\n")));return o.join("\n").replace(L,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Q.path||!z(Q.path))return"";try{const e=JSON.parse(n(g(c(Q.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return me(o,350)}catch{return""}})(),y=T(),d=y?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",p=d.length+t.length+120,m=Math.max(400,u-p-i.length),f=me(a.cell.source,Math.floor(.6*m)),w=s?($=s,P=m-f.length,$.length<=P?$:`…(${$.length-P} chars elided)…\n${$.slice(-P)}`):"",b=[d,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${f}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",t?`\n[question]\n${t}`:""].filter(Boolean).join("\n"),k=b.includes("chars elided"),v=y;var $,P;console.log(),fe||(fe=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(T()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${u} ${T()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(T()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(T()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${b.length}/${u} chars`)+chalk.gray(v?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(v?" · 含输出":" · output included"):"")+(k?chalk.yellow(v?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),S(`ipynb: ai ${a.idx}${t?` — ${t}`:""}`);const E=await h(b);if(console.log(),!E.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(E.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of x(E.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${v?"<你的问题>":"<your question>"}`)+chalk.gray(v?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(v?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(v?" 再跑一次":" run it again")),console.log(chalk.gray(v?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()},be=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!$(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),ke=async t=>{if(t.trim()&&S(`ipynb: ${t.trim()}`),ce)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ae.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ae.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(ie=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return Q.dirty&&!ie?(ie=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ge()):void await(async()=>{if(te.removeAllListeners("line"),ne||N(),console.log(),Z){const e=J();e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await X.shutdown().catch(()=>{}),ne){re&&(te.prompt=re);for(const e of le)te.on("line",e);te.prompt(),ye()}else ye(),te.close()})();if("clear"===a||"cls"===a)return console.clear(),R(),void ge();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await X.shutdown().catch(()=>{});try{await X.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void ge();if("help"===a||"?"===a)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(T()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ge();if("guide"===a||"/guide"===a)return(()=>{const o=Q.path?c(Q.path):process.cwd(),l=z(Q.path);let t="",r=!1;try{const e=JSON.parse(n(g(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Q.cells.filter(e=>null!==e.result).length,i=e(g(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Q.path?s(Q.path):"new empty notebook")+chalk.gray(` · ${Q.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Z?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ge();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ge();if("open"===a)return F&&_(F)?console.log(chalk.gray(" reopening ")+chalk.cyan(F)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ge();if("cells"===a||"ls"===a)return(()=>{if(0===Q.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);Q.cells.forEach((o,n)=>{const l=C(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(j(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void ge();if("show"===a)return(e=>{const o=pe(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of x(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),H(o.cell.result,K)),console.log()}})(d),void ge();if("edit"===a)return(e=>{const o=pe(e);if(!o)return;te.pause();const n=m(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(te.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(d),void ge();if("add"===a)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));te.pause();const l=m(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");te.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(Q.cells.push({kind:n?"markdown":"code",source:t,result:null}),Q.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Q.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Q.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ge();if("del"===a||"delete"===a)return(e=>{const o=pe(e);o&&(Q.cells.splice(o.idx-1,1),Q.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Q.cells.length} left.`)+(o.idx<=Q.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(d),void ge();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=pe(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(d,"md"===a?"markdown":"code"),void ge();if("gpu"===a)return ce=!0,await he(d),ce=!1,void ge();if("download"===a||"dl"===a)return ce=!0,await(async e=>{if(!Z)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${Z.outDir}/${n}`;let r;try{r=await X.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=ee?g(process.cwd(),"icoa-kaggle",ee):process.cwd(),c=g(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),ee&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${ee}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),ce=!1,void ge();if("ai"===a||"/ai"===a)return ce=!0,await we(d),ce=!1,void ge();if("run"===a)return ce=!0,await(async e=>{const o=I(e,Q.cells.length);if(o)for(const e of o){const n=Q.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(j(n,50))+chalk.gray(" ──"));try{n.result=await X.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void D()}if(Q.dirty=!0,H(n.result,K),be(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(T()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(T()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void D()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of x(n.source))console.log(e);console.log()}}else console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(d),ce=!1,void ge();if("save"===a)return(e=>{if(0===Q.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():y(process.cwd(),e.trim()):Q.path?Q.path.endsWith(".ipynb")?Q.path:`${Q.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,O(Q.cells)),Q.path=o,Q.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Q.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ge();if(""===r)return void ge()}if(ae.length>0&&M.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ge();if(ae.push(t),!v(ae))return 1!==ae.length||se||(se=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ge();const a=ae.join("\n").replace(/\s+$/,"");if(ae.length=0,""!==a.trim()){ce=!0;try{const e=await X.execute(a);Q.cells.push({kind:"code",source:a,result:e}),Q.dirty=!0,H(e,K);const o=be(Q.cells[Q.cells.length-1],Q.cells.length);e.ok||o||D()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),D()}ce=!1,ge()}else ge()};te.on("line",e=>{ke(e)}),ne||te.on("close",async()=>{await X.shutdown().catch(()=>{}),process.exit(0)}),ge(),await de}(p)})}function R(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const M=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function D(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const K="https://practice.icoa2026.au";function B(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):K}function W(){return g(t(),".icoa","gpu-key")}function J(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(W(),"utf-8").trim()||null}catch{return null}}async function Y(e,o,n){try{const l=await fetch(`${B()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return b(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function z(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let V=0,F=null;function H(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(L,"")}`))}else"display"===n.kind&&Q(n.data,o)}function Q(e,n){if(e["image/png"])try{o(n,{recursive:!0}),V+=1;const t=g(n,`figure-${V}.png`);return l(t,Buffer.from(e["image/png"],"base64")),F=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(_(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
1
+ import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as g,resolve as y}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as u,askIoaiOneShot as h}from"./ai4ioai.js";import{getConfig as p}from"../lib/config.js";import{editTextInEditor as m}from"../lib/editor-spawn.js";import{buildSshArgs as f,leaseConnectProblems as w,parseLeaseResponse as b,queueLine as k}from"../lib/gpu.js";import{shouldExecuteCell as v}from"../lib/ipynb-input.js";import{looksLikeMarkdown as $,renderMarkdown as x}from"../lib/md-term.js";import{NotebookKernel as P,buildRemoteBridgeCommand as E}from"../lib/kernel.js";import{getMainRl as G}from"../lib/main-rl.js";import{logCommand as S}from"../lib/logger.js";import{startLogSync as A,stopLogSync as I}from"../lib/log-sync.js";import{cellPreview as N,parseIpynb as j,parsePercentPy as q,parseRunRange as U,serializeIpynb as O,statusChar as C}from"../lib/notebook-doc.js";import{openFile as _}from"../lib/open-file.js";const L=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function T(){return(p().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(e){e.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async e=>{await runIpynb(e)})}function R(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const M=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function D(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const K="https://practice.icoa2026.au";function B(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):K}function W(){return g(t(),".icoa","gpu-key")}function J(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(W(),"utf-8").trim()||null}catch{return null}}async function Y(e,o,n){try{const l=await fetch(`${B()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return b(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function z(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let V=0,F=null;function H(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(L,"")}`))}else"display"===n.kind&&Q(n.data,o)}function Q(e,n){if(e["image/png"])try{o(n,{recursive:!0}),V+=1;const t=g(n,`figure-${V}.png`);return l(t,Buffer.from(e["image/png"],"base64")),F=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(_(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}export async function runIpynb(p){const b=d(t()),K=g(t(),".icoa","ipynb-out");if(R(),!e(b.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const V=p?function(o){const l=i(o)?o:y(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?j(e):q(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(p):null,Q=V?V.doc:{cells:[],path:null,dirty:!1};let X=new P({venvPython:b.python,venvRoot:b.root}),Z=null,ee=z(Q.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await X.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),V&&console.log(V.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const oe=G(),ne=null!==oe,le=ne?oe.listeners("line").slice():[];ne&&oe.removeAllListeners("line");const te=ne?oe:a({input:process.stdin,output:process.stdout,terminal:!0}),re=ne?te.prompt:null;ne&&(te.prompt=r.prototype.prompt),ne||A();const ae=[];let se=!1,ce=!1,ie=!1;const ge=()=>{const e=Z?"icoa ipynb ⚡gpu":"icoa ipynb";te.setPrompt(chalk.bold.cyan(ae.length?`${e} ...> `:`${e}> `)),te.prompt()};let ye=()=>{};const de=new Promise(e=>{ye=e}),ue=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(Z)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=J();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));ee||(ee=z(Q.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await Y("lease",e,ee??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(k(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await Y("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=w(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await Y("release",e);const s=ee?`${n.dataRoot}/${ee}`:n.dataRoot,c=E(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=g(t(),".icoa","gpu","lease-key");try{o(g(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await Y("release",e)}i={command:"ssh",args:f(n,r,c)}}const y=new P({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await y.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await Y("release",e)}await X.shutdown().catch(()=>{}),X=y,Z=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),ee&&console.log(chalk.gray(` Dataset is already on the box (${ee}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await(async()=>{if(!Z)return void console.log(chalk.gray(" not on a GPU kernel."));const e=J();await X.shutdown().catch(()=>{}),e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{X=new P({venvPython:b.python,venvRoot:b.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await X.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()})():"status"===a||""===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await Y("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Z?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${k(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=J();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${B()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(g(t(),".icoa"),{recursive:!0}),l(W(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${W()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},he=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Q.cells.length?(console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Q.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Q.cells[o-1],idx:o}},pe=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let me=!1;const fe=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!$(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),we=async t=>{if(t.trim()&&S(`ipynb: ${t.trim()}`),ce)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ae.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ae.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(ie=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return Q.dirty&&!ie?(ie=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ge()):void await(async()=>{if(te.removeAllListeners("line"),ne||I(),console.log(),Z){const e=J();e&&await Y("release",e),Z=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await X.shutdown().catch(()=>{}),ne){re&&(te.prompt=re);for(const e of le)te.on("line",e);te.prompt(),ye()}else ye(),te.close()})();if("clear"===a||"cls"===a)return console.clear(),R(),void ge();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await X.shutdown().catch(()=>{});try{await X.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void ge();if("help"===a||"?"===a)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(T()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ge();if("guide"===a||"/guide"===a)return(()=>{const o=Q.path?c(Q.path):process.cwd(),l=z(Q.path);let t="",r=!1;try{const e=JSON.parse(n(g(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Q.cells.filter(e=>null!==e.result).length,i=e(g(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Q.path?s(Q.path):"new empty notebook")+chalk.gray(` · ${Q.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Z?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ge();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ge();if("open"===a)return F&&_(F)?console.log(chalk.gray(" reopening ")+chalk.cyan(F)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ge();if("cells"===a||"ls"===a)return(()=>{if(0===Q.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);Q.cells.forEach((o,n)=>{const l=C(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(N(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void ge();if("show"===a)return(e=>{const o=he(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of x(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),H(o.cell.result,K)),console.log()}})(d),void ge();if("edit"===a)return(e=>{const o=he(e);if(!o)return;te.pause();const n=m(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(te.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(d),void ge();if("add"===a)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));te.pause();const l=m(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");te.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(Q.cells.push({kind:n?"markdown":"code",source:t,result:null}),Q.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Q.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Q.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ge();if("del"===a||"delete"===a)return(e=>{const o=he(e);o&&(Q.cells.splice(o.idx-1,1),Q.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Q.cells.length} left.`)+(o.idx<=Q.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(d),void ge();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=he(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Q.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(d,"md"===a?"markdown":"code"),void ge();if("gpu"===a)return ce=!0,await ue(d),ce=!1,void ge();if("download"===a||"dl"===a)return ce=!0,await(async e=>{if(!Z)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${Z.outDir}/${n}`;let r;try{r=await X.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=ee?g(process.cwd(),"icoa-kaggle",ee):process.cwd(),c=g(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),ee&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${ee}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),ce=!1,void ge();if("ai"===a||"/ai"===a)return ce=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),l=o.length>0&&/^\d+$/.test(o[0]),t=(l?o.slice(1):o).join(" ").trim(),r=l?Number(o[0]):(()=>{for(let e=Q.cells.length-1;e>=0;e--)if((Q.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Q.cells.length;if(0===Q.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=he(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(L,"")).join("\n")));return o.join("\n").replace(L,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Q.path||!z(Q.path))return"";try{const e=JSON.parse(n(g(c(Q.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return pe(o,350)}catch{return""}})(),y=T(),d=y?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",p=d.length+t.length+120,m=Math.max(400,u-p-i.length),f=pe(a.cell.source,Math.floor(.6*m)),w=s?(b=s,k=m-f.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[d,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${f}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",t?`\n[question]\n${t}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),P=y;console.log(),me||(me=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(T()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${u} ${T()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(T()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(T()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${u} chars`)+chalk.gray(P?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(P?" · 含输出":" · output included"):"")+($?chalk.yellow(P?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),S(`ipynb: ai ${a.idx}${t?` — ${t}`:""}`);const E=await h(v);if(console.log(),!E.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(E.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of x(E.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${P?"<你的问题>":"<your question>"}`)+chalk.gray(P?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(P?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(P?" 再跑一次":" run it again")),console.log(chalk.gray(P?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(d),ce=!1,void ge();if("run"===a)return ce=!0,await(async e=>{const o=U(e,Q.cells.length);if(o)for(const e of o){const n=Q.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(N(n,50))+chalk.gray(" ──"));try{n.result=await X.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void D()}if(Q.dirty=!0,H(n.result,K),fe(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(T()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(T()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void D()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of x(n.source))console.log(e);console.log()}}else console.log(0===Q.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(d),ce=!1,void ge();if("save"===a)return(e=>{if(0===Q.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():y(process.cwd(),e.trim()):Q.path?Q.path.endsWith(".ipynb")?Q.path:`${Q.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,O(Q.cells)),Q.path=o,Q.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Q.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ge();if(""===r)return void ge()}if(ae.length>0&&M.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ge();if(ae.push(t),!v(ae))return 1!==ae.length||se||(se=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ge();const a=ae.join("\n").replace(/\s+$/,"");if(ae.length=0,""!==a.trim()){ce=!0;try{const e=await X.execute(a);Q.cells.push({kind:"code",source:a,result:e}),Q.dirty=!0,H(e,K);const o=fe(Q.cells[Q.cells.length-1],Q.cells.length);e.ok||o||D()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),D()}ce=!1,ge()}else ge()};te.on("line",e=>{we(e)}),ne||te.on("close",async()=>{await X.shutdown().catch(()=>{}),process.exit(0)}),ge(),await de}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as t}from"node:fs";import{createInterface as l}from"node:readline";import{dirname as s,join as a}from"node:path";import{fileURLToPath as r}from"node:url";import chalk from"chalk";import{getConfig as c}from"../lib/config.js";import{getMainRl as i}from"../lib/main-rl.js";import{logCommand as g}from"../lib/logger.js";let y=!1;export function isSprintActive(){return y}const d=s(r(import.meta.url)),p=a(process.env.HOME||".",".icoa"),m=a(p,"sprint-state.json"),u={"T-torch":"裸 torch:手写 attention / causal mask / perplexity","T-umap":"降维当特征提取器,不是画图工具","T-lora":"peft LoRA 参数高效微调","T-librosa":"音频特征流水线:mel / MFCC → 定长向量"},h=["",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 f(o){const n=[a(d,"..","data",o),a(d,"..","..","src","data",o)];for(const o of n)if(e(o))return o;return n[0]}function w(e){try{o(p,{recursive:!0}),t(m,`${JSON.stringify(e,null,1)}\n`)}catch{}}function b(e,o){return(c().language||"en").toLowerCase().startsWith("zh")?e:o}function $(e){return"★".repeat(Math.max(1,Math.min(5,e||3)))}const k=a(p,"sprint-memos.json");function S(e){try{o(p,{recursive:!0}),t(k,`${JSON.stringify(e,null,1)}\n`)}catch{}}function q(e,o){const n=new Set(o.done),t=new Set(o.opened);console.log(),console.log(chalk.bold.cyan(b(" ⚔ IOAI 2026 · 四工具冲刺"," ⚔ IOAI 2026 · four-tool sprint"))+chalk.gray(` ${b("已攻克","cleared")} ${n.size} / ${e.length}`));const l=new Map;for(const o of e)l.has(o.bullseye)||l.set(o.bullseye,[]),l.get(o.bullseye)?.push(o);for(const[e,o]of l){console.log(),console.log(chalk.bold.white(` ${e}`)+chalk.gray(` — ${u[e]||""}`));for(const e of o){const o=n.has(e.seq)?chalk.green("✓"):t.has(e.seq)?chalk.yellow("◐"):chalk.gray("⬜");console.log(` ${o} ${chalk.bold.white(String(e.seq).padStart(2))} `+chalk.white(e.title.slice(0,34).padEnd(34))+chalk.gray($(e.difficulty).padEnd(5))+chalk.gray(e.needs_gpu?" ⚡":" ")+chalk.gray(` ${e.data_mb}M`)+("teleload"===e.status?chalk.gray(b(" · teleload"," · teleload")):"")+(e.judged?chalk.green(b(" · 可出分"," · scored")):""))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(b(" 看题 · "," view · "))+chalk.cyan("done <n>")+chalk.gray(b(" 标记攻克 · "," mark cleared · "))+chalk.cyan("ai")+chalk.gray(b(" 问 Gemma · "," ask Gemma · "))+chalk.cyan("memo")+chalk.gray(b(" 记问题 · "," report a problem · "))+chalk.cyan("back")+chalk.gray(b(" 退出"," leave"))),console.log(chalk.gray(b(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克"," ⬜ unseen ◐ opened ✓ cleared"))),console.log(chalk.gray(b(" ⚡ 要 GPU(notebook 里 gpu key → gpu on) · teleload 数据是大包,用 teleload 拉 · 可出分 交上去有真分数"," ⚡ needs GPU (inside the notebook: gpu key → gpu on) · teleload big pack, pull with teleload · scored real score on submit"))),console.log()}function A(e,o){const n=[];let t="",l=0;for(const s of e){const e=/[ -鿿＀-￯]/.test(s)?2:1;l+e>o&&(n.push(t),t="",l=0),t+=s,l+=e}return t&&n.push(t),n}export async function runSprint(){g("sprint");const e=function(){try{const e=JSON.parse(n(f("sprint-tasks.json"),"utf8")),o=Array.isArray(e?.tasks)?e.tasks:[];try{const e=JSON.parse(n(f("sprint-cards.json"),"utf8")),t=new Map((e.cards||[]).map(e=>[e.seq,e]));for(const e of o){const o=t.get(e.seq);o&&Object.assign(e,{star:o.star,trap:o.trap,action:o.action,hint:o.hint,meta:o.meta})}}catch{}return o.sort((e,o)=>e.seq-o.seq)}catch{return[]}}();if(0===e.length)return console.log(),console.log(chalk.yellow(" 冲刺题单还没装进这个版本。")),console.log(chalk.gray(" 升级后再试:")+chalk.cyan("npm install -g icoa-cli@latest")),void console.log();const o=function(){try{const e=JSON.parse(n(m,"utf8"));return{who:e.who||"",opened:e.opened||[],done:e.done||[]}}catch{return{who:"",opened:[],done:[]}}}();if(0===o.opened.length&&0===o.done.length)for(const e of h)console.log(e);o.who||(o.who=""),q(e,o);const t=i(),s=null!==t,a=s?t:l({input:process.stdin,output:process.stdout,terminal:!0}),r=s?a.listeners("line").slice():[];a.removeAllListeners("line");const c=a.prompt.bind(a);y=!0,a.setPrompt(chalk.bold.cyan("icoa ioai2026> ")),await new Promise(t=>{a.on("line",async l=>{const i=l.trim(),[d,p]=[i.split(/\s+/)[0]?.toLowerCase()||"",i.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(d))return w(o),console.log(chalk.gray(" 进度已保存。")),(()=>{if(y=!1,a.removeAllListeners("line"),s){for(const e of r)a.on("line",e);a.setPrompt(chalk.green("icoa> ")),a.prompt()}else a.close()})(),void t();if(""===d||["challenges","list","ls"].includes(d))q(e,o);else if(["open","o"].includes(d)||/^\d+$/.test(d)){const n=Number.parseInt(/^\d+$/.test(d)?d:p,10),t=e.find(e=>e.seq===n);t?(o.opened.includes(n)||o.opened.push(n),w(o),function(e){console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(`${e.seq} · ${e.title}`)+chalk.gray(` · ${e.bullseye}`)+chalk.cyan(" ─────")),console.log(chalk.cyan(" │"));const o=[e.star,e.trap,e.action,e.hint?` ${e.hint}`:""].filter(Boolean);0===o.length&&e.topic_cn&&o.push(`▸ ${e.topic_cn}`);for(const e of o){for(const o of A(e,58))console.log(chalk.cyan(" │ ")+chalk.white(o));console.log(chalk.cyan(" │"))}console.log(chalk.cyan(" │ ")+chalk.gray(e.meta||`⏱ 难度 ${$(e.difficulty)}`)+chalk.gray(e.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────")),console.log(chalk.gray(" ")+chalk.cyan("ai")+chalk.gray(b(" 问 Gemma · "," ask Gemma · "))+chalk.cyan(`done ${e.seq}`)+chalk.gray(b(" 标记攻克 · "," mark cleared · "))+chalk.cyan(`memo ${e.seq}`)+chalk.gray(b(" 记问题 · "," report · "))+chalk.cyan("back")+chalk.gray(b(" 回列表"," back to list"))),console.log()}(t)):console.log(chalk.yellow(` 没有第 ${p||d} 题。`)+chalk.gray(` 题号 1-${e.length}。`))}else if("done"===d){const n=Number.parseInt(p,10);e.some(e=>e.seq===n)?(o.done.includes(n)||o.done.push(n),w(o),console.log(chalk.green(` ✓ 第 ${n} 题标记为攻克`)+chalk.gray(` (${o.done.length}/${e.length})`))):console.log(chalk.yellow(` 题号 1-${e.length}。`))}else"memo"===d||"note"===d?await async function(e,o){const t=function(){try{const e=JSON.parse(n(k,"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}(),l=e.trim();if(""===l||"list"===l||"ls"===l){if(console.log(),0===t.length)console.log(chalk.gray(b(" 还没有记录。"," Nothing noted yet."))),console.log(chalk.gray(b(" 用法:"," Usage: "))+chalk.cyan(b("memo 17 卡片说的命令在这里敲不了","memo 17 the command on the card does not work here"))),console.log(chalk.gray(b(" "," "))+chalk.cyan(b("memo teleload 是什么意思","memo what does teleload mean"))+chalk.gray(b(" (不带题号 = 通用反馈)"," (no number = general feedback)")));else{console.log(chalk.bold.white(b(` 📝 已记 ${t.length} 条`,` 📝 ${t.length} noted`)));for(const e of t.slice(-12)){const o=e.seq?chalk.cyan(`#${e.seq}`):chalk.gray("—");console.log(` ${o} ${chalk.white(e.text.slice(0,60))}`+chalk.gray(e.synced?b(" ·已上报"," ·sent"):b(" ·仅本地"," ·local only")))}console.log(chalk.gray(` ${k}`))}return void console.log()}const s=l.split(/\s+/),a=/^\d+$/.test(s[0])&&o.some(e=>e.seq===Number(s[0])),r=a?Number(s[0]):null,c=(a?s.slice(1):s).join(" ").trim();if(""===c)return void console.log(chalk.yellow(b(" 写点什么吧:"," Say what happened: "))+chalk.cyan(`memo ${s[0]} …`));const i={ts:(new Date).toISOString(),seq:r,text:c,synced:!1};t.push(i),S(t),g(`sprint: memo${r?` ${r}`:""} — ${c}`);let y=!1;try{const{loadLearnState:e}=await import("../lib/learn-state.js"),o=e()?.token??"";if(o){const{syncCardFeedback:e}=await import("../lib/learn-curricula.js");y=await e(o,{curriculum_id:"pandahelpme31",card_number:r??0,feedback_text:c})}}catch{}y&&(i.synced=!0,S(t)),console.log(),console.log(chalk.green(b(" ✓ 记下了"," ✓ noted"))+(r?chalk.gray(b(` (第 ${r} 题)`,` (task ${r})`)):"")+chalk.gray(y?b(" ·已上报"," ·sent"):b(" ·存在本机,教练可以来取"," ·saved on this machine"))),console.log(chalk.gray(b(" 继续做题就好。"," Carry on."))),console.log()}(i.split(/\s+/).slice(1).join(" "),e):"ai"===d?(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(d)?q(e,o):console.log(chalk.gray(" ")+chalk.cyan("challenges")+chalk.gray(" 列表 · ")+chalk.cyan("open <n>")+chalk.gray(" 看题 · ")+chalk.cyan("done <n>")+chalk.gray(" 标记 · ")+chalk.cyan("memo")+chalk.gray(" 记问题 · ")+chalk.cyan("back")+chalk.gray(b(" 退出"," leave")));a.prompt=c,a.prompt()}),s||a.once("close",()=>t()),a.prompt=c,a.prompt()})}export function registerSprintCommand(e){e.command("pandahelpme31",{hidden:!0}).action(async()=>{await runSprint()})}
1
+ import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as t}from"node:fs";import{createInterface as l}from"node:readline";import{dirname as a,join as s}from"node:path";import{fileURLToPath as r}from"node:url";import chalk from"chalk";import{getConfig as i}from"../lib/config.js";import{getMainRl as c,setMainRl as g}from"../lib/main-rl.js";import{logCommand as y}from"../lib/logger.js";let d=!1;export function isSprintActive(){return d}const p=a(r(import.meta.url)),u=s(process.env.HOME||".",".icoa"),h=s(u,"sprint-state.json"),m={"T-torch":"裸 torch:手写 attention / causal mask / perplexity","T-umap":"降维当特征提取器,不是画图工具","T-lora":"peft LoRA 参数高效微调","T-librosa":"音频特征流水线:mel / MFCC → 定长向量"},f=["",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 w(o){const n=[s(p,"..","data",o),s(p,"..","..","src","data",o)];for(const o of n)if(e(o))return o;return n[0]}function b(e){try{o(u,{recursive:!0}),t(h,`${JSON.stringify(e,null,1)}\n`)}catch{}}function k(e,o){return(i().language||"en").toLowerCase().startsWith("zh")?e:o}function $(e){return"★".repeat(Math.max(1,Math.min(5,e||3)))}const S=s(u,"sprint-memos.json");function A(e){try{o(u,{recursive:!0}),t(S,`${JSON.stringify(e,null,1)}\n`)}catch{}}function q(e,o){const n=new Set(o.done),t=new Set(o.opened);console.log(),console.log(chalk.bold.cyan(k(" ⚔ IOAI 2026 · 四工具冲刺"," ⚔ IOAI 2026 · four-tool sprint"))+chalk.gray(` ${k("已攻克","cleared")} ${n.size} / ${e.length}`));const l=new Map;for(const o of e)l.has(o.bullseye)||l.set(o.bullseye,[]),l.get(o.bullseye)?.push(o);for(const[e,o]of l){console.log(),console.log(chalk.bold.white(` ${e}`)+chalk.gray(` — ${m[e]||""}`));for(const e of o){const o=n.has(e.seq)?chalk.green("✓"):t.has(e.seq)?chalk.yellow("◐"):chalk.gray("⬜");console.log(` ${o} ${chalk.bold.white(String(e.seq).padStart(2))} `+chalk.white(e.title.slice(0,34).padEnd(34))+chalk.gray($(e.difficulty).padEnd(5))+chalk.gray(e.needs_gpu?" ⚡":" ")+chalk.gray(` ${e.data_mb}M`)+("teleload"===e.status?chalk.gray(k(" · teleload"," · teleload")):"")+(e.judged?chalk.green(k(" · 可出分"," · scored")):""))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(k(" 看题 · "," view · "))+chalk.cyan("done <n>")+chalk.gray(k(" 标记攻克 · "," mark cleared · "))+chalk.cyan("ai4ioai")+chalk.gray(k(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan("memo")+chalk.gray(k(" 记问题 · "," report a problem · "))+chalk.cyan("back")+chalk.gray(k(" 退出"," leave"))),console.log(chalk.gray(k(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克"," ⬜ unseen ◐ opened ✓ cleared"))),console.log(chalk.gray(k(" ⚡ 要 GPU(notebook 里 gpu key → gpu on) · teleload 数据是大包,用 teleload 拉 · 可出分 交上去有真分数"," ⚡ needs GPU (inside the notebook: gpu key → gpu on) · teleload big pack, pull with teleload · scored real score on submit"))),console.log()}function v(e,o){const n=[];let t="",l=0;for(const a of e){const e=/[ -鿿＀-￯]/.test(a)?2:1;l+e>o&&(n.push(t),t="",l=0),t+=a,l+=e}return t&&n.push(t),n}export async function runSprint(){y("sprint");const e=function(){try{const e=JSON.parse(n(w("sprint-tasks.json"),"utf8")),o=Array.isArray(e?.tasks)?e.tasks:[];try{const e=JSON.parse(n(w("sprint-cards.json"),"utf8")),t=new Map((e.cards||[]).map(e=>[e.seq,e]));for(const e of o){const o=t.get(e.seq);o&&Object.assign(e,{star:o.star,trap:o.trap,action:o.action,hint:o.hint,meta:o.meta})}}catch{}return o.sort((e,o)=>e.seq-o.seq)}catch{return[]}}();if(0===e.length)return console.log(),console.log(chalk.yellow(" 冲刺题单还没装进这个版本。")),console.log(chalk.gray(" 升级后再试:")+chalk.cyan("npm install -g icoa-cli@latest")),void console.log();const o=function(){try{const e=JSON.parse(n(h,"utf8"));return{who:e.who||"",opened:e.opened||[],done:e.done||[]}}catch{return{who:"",opened:[],done:[]}}}();if(0===o.opened.length&&0===o.done.length)for(const e of f)console.log(e);o.who||(o.who=""),q(e,o);const t=c(),a=null!==t,s=a?t:l({input:process.stdin,output:process.stdout,terminal:!0});a||g(s);const r=a?s.listeners("line").slice():[];s.removeAllListeners("line");const i=s.prompt.bind(s);d=!0;const p=chalk.bold.cyan("icoa ioai2026> ");s.setPrompt(p);let u=null;await new Promise(t=>{s.on("line",async l=>{const c=l.trim().replace(/^icoa\s+/i,""),[h,m]=[c.split(/\s+/)[0]?.toLowerCase()||"",c.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(h))return b(o),console.log(chalk.gray(" 进度已保存。")),(()=>{if(d=!1,s.removeAllListeners("line"),a){for(const e of r)s.on("line",e);s.setPrompt(chalk.green("icoa> ")),s.prompt()}else g(null),s.close()})(),void t();if(""===h||["challenges","list","ls"].includes(h))q(e,o);else if(["open","o"].includes(h)||/^\d+$/.test(h)){const n=Number.parseInt(/^\d+$/.test(h)?h:m,10),t=e.find(e=>e.seq===n);t?(o.opened.includes(n)||o.opened.push(n),b(o),u=n,function(e){console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(`${e.seq} · ${e.title}`)+chalk.gray(` · ${e.bullseye}`)+chalk.cyan(" ─────")),console.log(chalk.cyan(" │"));const o=[e.star,e.trap,e.action,e.hint?` ${e.hint}`:""].filter(Boolean);0===o.length&&e.topic_cn&&o.push(`▸ ${e.topic_cn}`);for(const e of o){for(const o of v(e,58))console.log(chalk.cyan(" │ ")+chalk.white(o));console.log(chalk.cyan(" │"))}console.log(chalk.cyan(" │ ")+chalk.gray(e.meta||`⏱ 难度 ${$(e.difficulty)}`)+chalk.gray(e.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────"));const n=function(e){const o=/(?:kaggle|teleload)\s+[a-z0-9][a-z0-9-]*/i.exec(e.action||"");return o?o[0]:null}(e);n&&console.log(chalk.bold.white(k(" ▸ 就在这里敲: "," ▸ Type it right here: "))+chalk.bold.cyan(n)+chalk.gray(k(" ← 数据 + notebook 落到本机"," ← pulls the data + notebook"))),console.log(chalk.gray(" ")+chalk.cyan("ai4ioai")+chalk.gray(k(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan(`done ${e.seq}`)+chalk.gray(k(" 标记攻克 · "," mark cleared · "))+chalk.cyan("memo")+chalk.gray(k(` 记问题(自动记在第 ${e.seq} 题) · `,` report (auto-filed under ${e.seq}) · `))+chalk.cyan("back")+chalk.gray(k(" 回列表"," back to list"))),console.log()}(t)):console.log(chalk.yellow(` 没有第 ${m||h} 题。`)+chalk.gray(` 题号 1-${e.length}。`))}else if("done"===h){const n=Number.parseInt(m,10);e.some(e=>e.seq===n)?(o.done.includes(n)||o.done.push(n),b(o),console.log(chalk.green(` ✓ 第 ${n} 题标记为攻克`)+chalk.gray(` (${o.done.length}/${e.length})`))):console.log(chalk.yellow(` 题号 1-${e.length}。`))}else["kaggle","teleload","ipynb"].includes(h)?await async function(e,o){const n=o.split(/\s+/).filter(Boolean);try{if("teleload"===e){const{runTeleload:e}=await import("./teleload.js");return void await e(n[0])}if("ipynb"===e){const{runIpynb:e}=await import("./ipynb.js");return void await e(n[0])}const o=await import("./kaggle.js"),t=(n[0]||"").toLowerCase();"submit"===t?await o.runKaggleSubmit(n[1]):"check"===t?await o.runKaggleCheck(n[1]):"guide"===t?await o.runKaggleGuide(n[1]):await o.runKaggle(n[0])}catch(e){console.log(),console.log(chalk.yellow(k(" 这条命令没跑成:"," That command failed: "))+chalk.gray(String(e))),console.log(chalk.gray(k(" 记一条给教练:"," Tell the coach: "))+chalk.cyan(k("memo …","memo …"))),console.log()}}(h,c.split(/\s+/).slice(1).join(" ")):"memo"===h||"note"===h?await async function(e,o,t,l){const a=function(){try{const e=JSON.parse(n(S,"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}(),s=e.trim();if(["list","ls","all"].includes(s.toLowerCase())){if(console.log(),0===a.length)console.log(chalk.gray(k(" 还没有记录。"," Nothing noted yet.")));else{console.log(chalk.bold.white(k(` 📝 已记 ${a.length} 条`,` 📝 ${a.length} noted`)));for(const e of a.slice(-12)){const o=e.seq?chalk.cyan(`#${e.seq}`):chalk.gray("—");console.log(` ${o} ${chalk.white(e.text.slice(0,60))}`+chalk.gray(e.synced?k(" ·已上报"," ·sent"):k(" ·仅本地"," ·local only")))}console.log(chalk.gray(` ${S}`))}return console.log(chalk.gray(k(" 再记一条:"," Note another: "))+chalk.cyan("memo")+chalk.gray(k(" (光敲这一个词就给你写字的地方)"," (just the word — it gives you a place to type)"))),void console.log()}const r=s?s.split(/\s+/):[],i=r.length>0&&/^\d+$/.test(r[0])&&o.some(e=>e.seq===Number(r[0])),c=i?Number(r[0]):t;let g=(i?r.slice(1):r).join(" ").trim();if(""===g){const e=c?chalk.gray(k(` —— 记在第 ${c} 题下`,` — filed under task ${c}`)):chalk.gray(k(" —— 通用反馈"," — general feedback"));if(console.log(),console.log(chalk.bold.white(k(" 📝 撞到什么就写什么"," 📝 Say what you hit"))+e),console.log(chalk.gray(k(" 一行写完,回车就存下(不用等回复);直接回车 = 不记。"," One line, Enter files it (no reply comes back). Empty Enter cancels."))),g=await function(e,o){return new Promise(n=>{e.question(o,e=>n(e.trim()))})}(l,chalk.cyan(" memo > ")),""===g)return console.log(chalk.gray(k(" 没记。"," Nothing noted."))),void console.log()}const d={ts:(new Date).toISOString(),seq:c,text:g,synced:!1};a.push(d),A(a),y(`sprint: memo${c?` ${c}`:""} — ${g}`);let p=!1;try{const{loadLearnState:e}=await import("../lib/learn-state.js"),o=e()?.token??"";if(o){const{syncCardFeedback:e}=await import("../lib/learn-curricula.js");p=await e(o,{curriculum_id:"pandahelpme31",card_number:c??0,feedback_text:g})}}catch{}p&&(d.synced=!0,A(a)),console.log(),console.log(chalk.green(k(" ✓ 记下了"," ✓ noted"))+(c?chalk.gray(k(` (第 ${c} 题)`,` (task ${c})`)):"")+chalk.gray(p?k(" ·已上报"," ·sent"):k(" ·存在本机,教练可以来取"," ·saved on this machine"))),console.log(chalk.gray(k(" 继续做题就好。看全部:"," Carry on. See them all: "))+chalk.cyan("memo list")),console.log()}(c.split(/\s+/).slice(1).join(" "),e,u,s):["ai4ioai","/ai4ioai","ai"].includes(h)?(console.log(),console.log(chalk.bold.white(k(" 左右分屏,左边看题右边问 AI:"," Split the screen — tasks left, AI right:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(k(" 左右分屏(上下分屏是 "," split left/right (up/down is "))+chalk.cyan('Ctrl-b "')+chalk.gray(k(")",")"))),console.log(chalk.gray(" 2. ")+chalk.gray(k("右边那格输 ","in the right pane type "))+chalk.bold.cyan("icoa")+chalk.gray(k(" ,再输 "," , then "))+chalk.bold.cyan("ai4ioai")),console.log(chalk.gray(k(" 3. 两格之间切换:"," 3. move between panes: "))+chalk.cyan("Ctrl-b ←")+chalk.gray(" / ")+chalk.cyan("Ctrl-b →")),console.log(),console.log(chalk.gray(k(" 它是弱模型 —— 单轮、2000 字符以内。把问题问准,就是这次要练的本事。"," A deliberately weak model — single-turn, 2000 chars. Asking precisely is the skill."))),console.log(chalk.gray(k(" 在 notebook 里卡住时,那边可以直接敲 "," Stuck inside a notebook? there you can type "))+chalk.cyan("ai")+chalk.gray(k(" —— 它会把那一格的代码和报错一起带上。"," — it carries that cell and its traceback."))),console.log()):["help","?","guide"].includes(h)?q(e,o):(console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(k(" 看题 · "," view · "))+chalk.cyan("kaggle <题目id>")+chalk.gray(k(" 领数据 · "," get the data · "))+chalk.cyan("ipynb <路径>")+chalk.gray(k(" 开 notebook · "," open the notebook · "))+chalk.cyan("done <n>")+chalk.gray(k(" 标记 · "," mark · "))+chalk.cyan("memo")+chalk.gray(k(" 记问题 · "," report · "))+chalk.cyan("back")+chalk.gray(k(" 退出"," leave"))),console.log(chalk.gray(k(" 题目 id 在卡片的 ▸ 那一行,例如 "," The task id is on the card’s ▸ line, e.g. "))+chalk.cyan("open 17")+chalk.gray(" → ")+chalk.cyan("kaggle s17-bazarul-lui-riki")));s.prompt=i,s.setPrompt(p),s.prompt()}),a||s.once("close",()=>t()),s.prompt=i,s.prompt()})}export function registerSprintCommand(e){e.command("pandahelpme31",{hidden:!0}).action(async()=>{await runSprint()})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.446",
3
+ "version": "2.19.448",
4
4
  "description": "ICOA CLI — The world's first CLI-native cyber & AI security olympiad terminal: AI4CTF (Day 1), CTF4AI (Day 2), VLA4CTF (Pioneer Round — embodied AI)",
5
5
  "type": "module",
6
6
  "bin": {