icoa-cli 2.19.679 → 2.19.681
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.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/aienv.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/ipynb.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/lib/arena-edit-dynamics.js +1 -1
- package/dist/lib/editor-spawn.js +1 -1
- package/dist/lib/notebook-doc.js +1 -1
- package/dist/lib/paste-probe.js +1 -0
- package/dist/repl.js +1 -1
- package/package.json +1 -1
package/dist/commands/ipynb.js
CHANGED
|
@@ -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 w,leaseConnectProblems as f,parseLeaseResponse as b,queueLine as k,windowLine as v}from"../lib/gpu.js";import{shouldExecuteCell as $}from"../lib/ipynb-input.js";import{looksLikeMarkdown as x,renderMarkdown as P}from"../lib/md-term.js";import{NotebookKernel as E,buildRemoteBridgeCommand as G}from"../lib/kernel.js";import{getMainRl as S,setMainRl as A}from"../lib/main-rl.js";import{logCommand as U}from"../lib/logger.js";import{startLogSync as j,stopLogSync as C}from"../lib/log-sync.js";import{cellPreview as I,parseIpynb as N,parsePercentPy as q,parseRunRange as O,serializeIpynb as _,statusChar as T}from"../lib/notebook-doc.js";import{openFile as L}from"../lib/open-file.js";const R=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function M(){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 K(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const B=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 W="https://practice.icoa2026.au";function J(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):W}function Y(){return g(t(),".icoa","gpu-key")}function z(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(Y(),"utf-8").trim()||null}catch{return null}}async function V(e,o,n){try{const l=await fetch(`${J()}/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 F(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let H=0,Q=null;function X(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(R,"")}`))}else"display"===n.kind&&Z(n.data,o)}function Z(e,n){if(e["image/png"])try{o(n,{recursive:!0}),H+=1;const t=g(n,`figure-${H}.png`);return l(t,Buffer.from(e["image/png"],"base64")),Q=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(L(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()),W=g(t(),".icoa","ipynb-out");if(K(),!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 H=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")?N(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,Z=H?H.doc:{cells:[],path:null,dirty:!1};let ee=new E({venvPython:b.python,venvRoot:b.root}),oe=null,ne=F(Z.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await ee.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.")),H&&console.log(H.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 le=S(),te=null!==le,re=te?le.listeners("line").slice():[];te&&le.removeAllListeners("line");const ae=te?le:a({input:process.stdin,output:process.stdout,terminal:!0});te||A(ae);const se=te?ae.prompt:null,ce=te?ae.getPrompt():"";te&&(ae.prompt=r.prototype.prompt),te||j();const ie=[];let ge=!1,ye=!1,de=!1;const ue=()=>{const e=oe?"icoa ipynb ⚡gpu":"icoa ipynb";ae.setPrompt(chalk.bold.cyan(ie.length?`${e} ...> `:`${e}> `)),ae.prompt()};let he=()=>{};const pe=new Promise(e=>{he=e}),me=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(oe)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=z();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)."));ne||(ne=F(Z.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await V("lease",e,ne??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 V("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=f(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 V("release",e);const s=ne?`${n.dataRoot}/${ne}`:n.dataRoot,c=G(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 V("release",e)}i={command:"ssh",args:w(n,r,c)}}const y=new E({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 V("release",e)}await ee.shutdown().catch(()=>{}),ee=y,oe=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.`));const u=v(n.windowCloseEpoch);u&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${u}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),ne&&console.log(chalk.gray(` Dataset is already on the box (${ne}) — 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(!oe)return void console.log(chalk.gray(" not on a GPU kernel."));const e=z();await ee.shutdown().catch(()=>{}),e&&await V("release",e),oe=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{ee=new E({venvPython:b.python,venvRoot:b.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await ee.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=z();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await V("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(oe?" (this notebook is connected)":" (not connected here — gpu on)"));const n=v(o.windowCloseEpoch);n&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${n}.`))}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=z();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(`${J()}/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`));const a=v("number"==typeof o.window_close_epoch?o.window_close_epoch:void 0);a&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${a}.`)),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(Y(),`${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(` (${Y()})`))}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>"))},we=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}},fe=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let be=!1;const ke=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!x(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)),ve=async t=>{if(t.trim()&&U(`ipynb: ${t.trim()}`),ye)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ie.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ie.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&&(de=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return Z.dirty&&!de?(de=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ue()):void await(async()=>{if(ae.removeAllListeners("line"),te||C(),console.log(),oe){const e=z();e&&await V("release",e),oe=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await ee.shutdown().catch(()=>{}),te){se&&(ae.prompt=se),ae.setPrompt(ce);for(const e of re)ae.on("line",e);ae.prompt(),he()}else A(null),he(),ae.close()})();if("clear"===a||"cls"===a)return console.clear(),K(),void ue();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await ee.shutdown().catch(()=>{});try{await ee.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 ue();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(M()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" check / submit")+chalk.gray(" verify / score your submission.csv — right here, no quit needed")),console.log(chalk.cyan(" board")+chalk.gray(" live standings for this competition")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void ue();if("guide"===a||"/guide"===a)return(()=>{const o=Z.path?c(Z.path):process.cwd(),l=F(Z.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=Z.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(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"))),oe?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("submit")+chalk.gray(" — scored + ranked right here, no need to leave (")+chalk.cyan("board")+chalk.gray(" shows standings)")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ue();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 ue();if("open"===a)return Q&&L(Q)?console.log(chalk.gray(" reopening ")+chalk.cyan(Q)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ue();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=T(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(I(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 ue();if("show"===a)return(e=>{const o=we(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of P(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),X(o.cell.result,W)),console.log()}})(d),void ue();if("edit"===a)return(e=>{const o=we(e);if(!o)return;ae.pause();const n=m(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(ae.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 ue();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)"));ae.pause();const l=m(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");ae.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 ue();if("del"===a||"delete"===a)return(e=>{const o=we(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 ue();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=we(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 ue();if("gpu"===a)return ye=!0,await me(d),ye=!1,void ue();if("download"===a||"dl"===a)return ye=!0,await(async e=>{if(!oe)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:`${oe.outDir}/${n}`;let r;try{r=await ee.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=ne?g(process.cwd(),"icoa-kaggle",ne):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)`)),ne&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${ne}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),ye=!1,void ue();if("check"===a||"submit"===a||"kaggle"===a){const e=await import("./kaggle.js"),o=d.split(/\s+/).filter(Boolean),n="kaggle"===a?(o[0]||"").toLowerCase():a,l=("kaggle"===a?o[1]:o[0])||F(Z.path)||void 0;ye=!0;try{"submit"===n?await e.runKaggleSubmit(l):"check"===n?await e.runKaggleCheck(l):"guide"===n?await e.runKaggleGuide(l):await e.runKaggle("kaggle"===a?o[0]:l)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return ye=!1,void ue()}if("board"===a){const{runBoard:e}=await import("./board.js"),o=d.split(/\s+/).filter(Boolean);ye=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return ye=!1,void ue()}if("ai"===a||"/ai"===a)return ye=!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=Z.cells.length-1;e>=0;e--)if((Z.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Z.cells.length;if(0===Z.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=we(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(R,"")).join("\n")));return o.join("\n").replace(R,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Z.path||!F(Z.path))return"";try{const e=JSON.parse(n(g(c(Z.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return fe(o,350)}catch{return""}})(),y=M(),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),w=fe(a.cell.source,Math.floor(.6*m)),f=s?(b=s,k=m-w.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${w}`,f?`\n[cell ${a.idx} output]\n${f}`:"\n(this cell has not been run yet)",t?`\n[question]\n${t}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),x=y;console.log(),be||(be=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(M()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${u} ${M()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(M()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(M()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — 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(x?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(x?" · 含输出":" · output included"):"")+($?chalk.yellow(x?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),U(`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 P(E.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${x?"<你的问题>":"<your question>"}`)+chalk.gray(x?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(x?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(x?" 再跑一次":" run it again")),console.log(chalk.gray(x?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(d),ye=!1,void ue();if("run"===a)return ye=!0,await(async e=>{const o=O(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(I(n,50))+chalk.gray(" ──"));try{n.result=await ee.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void D()}if(Z.dirty=!0,X(n.result,W),ke(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(M()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(M()?" 把这一格的代码和报错一起问 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 P(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),ye=!1,void ue();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():y(process.cwd(),e.trim()):Z.path?Z.path.endsWith(".ipynb")?Z.path:`${Z.path.replace(/\.[^./]+$/,"")}.ipynb`:y(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,_(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 ue();if(""===r)return void ue()}if(ie.length>0&&B.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 ue();if(ie.push(t),!$(ie))return 1!==ie.length||ge||(ge=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ue();const a=ie.join("\n").replace(/\s+$/,"");if(ie.length=0,""!==a.trim()){ye=!0;try{const e=await ee.execute(a);Z.cells.push({kind:"code",source:a,result:e}),Z.dirty=!0,X(e,W);const o=ke(Z.cells[Z.cells.length-1],Z.cells.length);e.ok||o||D()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),D()}ye=!1,ue()}else ue()};ae.on("line",e=>{ve(e)}),te||ae.on("close",async()=>{await ee.shutdown().catch(()=>{}),process.exit(0)}),ue(),await pe}
|
|
1
|
+
import{existsSync as e,mkdirSync as o,readFileSync as n,statSync as t,writeFileSync as l}from"node:fs";import{homedir as r}from"node:os";import{Interface as a,createInterface as s}from"node:readline";import{basename as i,dirname as c,isAbsolute as g,join as y,resolve as d}from"node:path";import chalk from"chalk";import{aienvPaths as u}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as h,askIoaiOneShot as p}from"./ai4ioai.js";import{getConfig as m,saveConfig as f}from"../lib/config.js";import{editTextInEditor as w,editorInstalled as b,editorLabel as k,namedEditor as v,resolveEditor as $}from"../lib/editor-spawn.js";import{buildSshArgs as x,leaseConnectProblems as P,parseLeaseResponse as E,queueLine as S,windowLine as C}from"../lib/gpu.js";import{shouldExecuteCell as G}from"../lib/ipynb-input.js";import{looksLikeMarkdown as j,renderMarkdown as I}from"../lib/md-term.js";import{NotebookKernel as A,buildRemoteBridgeCommand as N}from"../lib/kernel.js";import{getMainRl as U,setMainRl as O}from"../lib/main-rl.js";import{logCommand as q}from"../lib/logger.js";import{startLogSync as T,stopLogSync as L}from"../lib/log-sync.js";import{cellPreview as M,mergeReloadedCells as _,normalizePathArg as R,parseIpynb as D,parsePercentPy as K,parseRunRange as B,serializeIpynb as W,statusChar as J}from"../lib/notebook-doc.js";import{openFile as V}from"../lib/open-file.js";const Y=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function z(){return(m().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 F(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const X=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),H=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function Q(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const Z="https://practice.icoa2026.au";function ee(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):Z}function oe(){return y(r(),".icoa","gpu-key")}function ne(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(oe(),"utf-8").trim()||null}catch{return null}}async function te(e,o,n){try{const t=await fetch(`${ee()}/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 E(await t.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function le(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let re=0,ae=null;function se(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(Y,"")}`))}else"display"===n.kind&&ie(n.data,o)}function ie(e,n){if(e["image/png"])try{o(n,{recursive:!0}),re+=1;const t=y(n,`figure-${re}.png`);return l(t,Buffer.from(e["image/png"],"base64")),ae=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(V(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"]}`))}function ce(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function ge(e){if(e)try{return t(e).mtimeMs}catch{return}}function ye(o){const t=R(o,r()),l=g(t)?t:d(process.cwd(),t);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")?D(e):K(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:ge(l),diskSig:ce(o)},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.")}}}export async function runIpynb(t){const E=u(r()),Z=y(r(),".icoa","ipynb-out");if(F(),!e(E.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 re=t?ye(t):null,ie=re?re.doc:{cells:[],path:null,dirty:!1};let de=new A({venvPython:E.python,venvRoot:E.root}),ue=null,he=le(ie.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await de.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.")),re&&console.log(re.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 pe=U(),me=null!==pe,fe=me?pe.listeners("line").slice():[];me&&pe.removeAllListeners("line");const we=me?pe:s({input:process.stdin,output:process.stdout,terminal:!0});me||O(we);const be=me?we.prompt:null,ke=me?we.getPrompt():"";me&&(we.prompt=a.prototype.prompt),me||T();const ve=[];let $e,xe=!1,Pe=!1,Ee=!1,Se=null,Ce=null;const Ge=()=>{if(Ce)return we.setPrompt(chalk.bold.cyan(` editor 1-${Ce.options.length} > `)),void we.prompt();const e=ue?"icoa ipynb ⚡gpu":"icoa ipynb";we.setPrompt(chalk.bold.cyan(ve.length?`${e} ...> `:`${e}> `)),we.prompt()};let je=()=>{};const Ie=new Promise(e=>{je=e}),Ae=async e=>{const[n,...t]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(ue)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=ne();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)."));he||(he=le(ie.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await te("lease",e,he??void 0),t=0;for(;"queued"===n.state&&t<24;)0===t&&console.log(),process.stdout.write(`\r ${chalk.yellow(S(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await te("status",e),t++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=P(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await te("release",e);const s=he?`${n.dataRoot}/${he}`:n.dataRoot,i=N(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let c;if("local"===n.transport)c={command:"/bin/sh",args:["-c",i]};else{const t=y(r(),".icoa","gpu","lease-key");try{o(y(r(),".icoa","gpu"),{recursive:!0}),l(t,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await te("release",e)}c={command:"ssh",args:x(n,t,i)}}const g=new A({spawnSpec:c,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 te("release",e)}await de.shutdown().catch(()=>{}),de=g,ue=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.`));const u=C(n.windowCloseEpoch);u&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${u}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),he&&console.log(chalk.gray(` Dataset is already on the box (${he}) — 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(!ue)return void console.log(chalk.gray(" not on a GPU kernel."));const e=ne();await de.shutdown().catch(()=>{}),e&&await te("release",e),ue=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{de=new A({venvPython:E.python,venvRoot:E.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await de.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=ne();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await te("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(ue?" (this notebook is connected)":" (not connected here — gpu on)"));const n=C(o.windowCloseEpoch);n&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${n}.`))}else"queued"===o.state?console.log(chalk.yellow(` ${S(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=ne();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(`${ee()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await n.json();o=t.data??t}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,t="number"==typeof o.free?o.free:0,l=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"} · ${t} free`));const a=C("number"==typeof o.window_close_epoch?o.window_close_epoch:void 0);a&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${a}.`)),console.log(chalk.bold.white(" ▶ running now:")),0===l.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,t=Math.floor(n/60),l=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${t}:${l} 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:"?",t=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+t)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(r(),".icoa"),{recursive:!0}),l(oe(),`${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(` (${oe()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(t.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>"))},Ne=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>ie.cells.length?(console.log(0===ie.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${ie.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:ie.cells[o-1],idx:o}},Ue=(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 Oe=!1;const qe=()=>{const e=m().notebookEditor;return e?v(e):null},Te=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),Le=()=>qe()??$(),Me={nano:"easiest — Ctrl+O save, Ctrl+X exit",code:"VS Code window — save, close the tab to come back",vi:"i to type, Esc then :wq to save and exit"},_e=(e,o)=>{if(e){const n=v(e);return n?b(n.cmd)?(o(n),!0):(console.log(chalk.yellow(` ${k(n)} is not installed on this computer.`)+chalk.gray(" See the choices: ")+chalk.cyan("editor")),!0):(console.log(chalk.yellow(` unknown editor "${e}" — use `)+chalk.cyan("nano")+chalk.yellow(", ")+chalk.cyan("code")+chalk.yellow(" or ")+chalk.cyan("vi")),!0)}if(qe()||Te())return o(Le()),!0;const n=["nano","code","vi"].map(e=>v(e)).filter(e=>null!==e&&b(e.cmd));return n.length<2||!process.stdin.isTTY?(o($()),!0):((e=>{console.log(),console.log(chalk.bold.white(" Which editor should edit / add open?")+chalk.gray(" (asked once)")),e.forEach((e,o)=>{const n=k(e);console.log(chalk.cyan(` ${o+1} ${n.padEnd(5)}`)+chalk.gray(` ${Me[n]??""}`)+("nano"===n?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(n),Ce={resume:o,tries:0,options:n},!1)},Re=e=>{if(!ie.path)return!1;let o;try{const e=n(ie.path,"utf8");o=ie.path.endsWith(".ipynb")?D(e):K(e)}catch(e){return console.log(chalk.yellow(" could not re-read the file: ")+chalk.gray(e instanceof Error?e.message:String(e))),!1}const t=_(ie.cells,o);return ie.cells=t.cells,ie.dirty=!1,ie.mtimeMs=ge(ie.path),ie.diskSig=ce(o),$e=void 0,console.log(chalk.gray(` ↻ reloaded ${i(ie.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${t.cells.length} cells, ${t.changed} changed`)+chalk.gray(t.kept?`, ${t.kept} kept their output.`:".")),console.log(chalk.gray(" variables stay in the kernel — run just the cells you changed, or ")+chalk.cyan("run all")),!0},De=()=>void 0!==ie.diskSig?ce(ie.cells)!==ie.diskSig:ie.dirty,Ke=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!j(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)),Be=async t=>{if(t.trim()&&q(`ipynb: ${t.trim()}`),Pe)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Ce){const e=Ce,o=t.trim().toLowerCase(),n=v(o),l=/^\d+$/.test(o)?e.options[Number(o)-1]:n?e.options.find(e=>k(e)===k(n)):void 0;return l?(Ce=null,f({notebookEditor:k(l)}),console.log(chalk.green(` ✓ edit / add will open ${k(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===o||["q","quit","back","cancel","exit"].includes(o)?(Ce=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Ce=null,console.log(chalk.gray(" no editor chosen — nothing changed. Choose later with ")+chalk.cyan("editor nano"))):console.log(chalk.yellow(` type a number 1-${e.options.length}, or a name: `)+chalk.cyan(e.options.map(e=>k(e)).join(" / "))),void Ge()}let a=t.trim();if(0===ve.length&&/^icoa\s+[a-z/]/i.test(a)&&(a=a.replace(/^icoa\s+/i,"")),0===ve.length){const t=a.split(/\s+/),s=(t[0]??"").toLowerCase(),u=a.slice(t[0]?.length??0).trim();if("quit"!==s&&"exit"!==s&&"q"!==s&&(Ee=!1),Se&&s!==Se&&(Se=null),H.has(s)&&(()=>{if(!ie.path||void 0===ie.mtimeMs)return;const e=ge(ie.path);if(void 0!==e&&e!==ie.mtimeMs){if(De()){if($e===e)return;return $e=e,console.log(chalk.yellow(` ⚠ ${i(ie.path)} changed in your editor, and this notebook has unsaved changes too.`)),void console.log(chalk.gray(" take the file: ")+chalk.cyan("reload")+chalk.gray(" · keep these and overwrite the file: ")+chalk.cyan("save"))}Re(!0)}})(),"quit"===s||"exit"===s||"back"===s||"q"===s||"menu"===s)return ie.dirty&&!Ee?(Ee=!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(we.removeAllListeners("line"),me||L(),console.log(),ue){const e=ne();e&&await te("release",e),ue=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await de.shutdown().catch(()=>{}),me){be&&(we.prompt=be),we.setPrompt(ke);for(const e of fe)we.on("line",e);we.prompt(),je()}else O(null),je(),we.close()})();if("clear"===s||"cls"===s)return console.clear(),F(),void Ge();if("restart"===s)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await de.shutdown().catch(()=>{});try{await de.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"===s||"?"===s)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 · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor 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(z()?" 问 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(" load <file>")+chalk.gray(" open another .ipynb / .py (drag the file into this window)")),console.log(chalk.cyan(" reload")+chalk.gray(" re-read the file — or just save in Jupyter / VS Code: the next run picks it up")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" check / submit")+chalk.gray(" verify / score your submission.csv — right here, no quit needed")),console.log(chalk.cyan(" board")+chalk.gray(" live standings for this competition")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void Ge();if("guide"===s||"/guide"===s)return(()=>{const o=ie.path?c(ie.path):process.cwd(),t=le(ie.path);let l="",r=!1;try{const e=JSON.parse(n(y(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=ie.cells.filter(e=>null!==e.result).length,s=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(ie.path?i(ie.path):"new empty notebook")+chalk.gray(` · ${ie.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),ue?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")),t&&"icoa-holdout"===l?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("submit")+chalk.gray(" — scored + ranked right here, no need to leave (")+chalk.cyan("board")+chalk.gray(" shows standings)")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):t&&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."))):t?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void Ge();if("python"===s||"python3"===s)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"===s&&""===u)return ae&&V(ae)?console.log(chalk.gray(" reopening ")+chalk.cyan(ae)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ge();if("cells"===s||"ls"===s)return(()=>{if(0===ie.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);ie.cells.forEach((o,n)=>{const t=J(o),l="✓"===t?chalk.green(t.padEnd(2)):"✗"===t?chalk.red(t.padEnd(2)):"md"===t?chalk.magenta(t.padEnd(2)):chalk.gray(t.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${l} ${chalk.white(M(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"===s)return(e=>{const o=Ne(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 I(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 ──")),se(o.cell.result,Z)),console.log()}})(u),void Ge();if("edit"===s){const[e,o]=u.split(/\s+/);return Ne(e??"")&&_e(o,o=>((e,o)=>{const n=Ne(e);if(!n)return;we.pause();const t=w(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(we.resume(),null===t)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=t.replace(/\s+$/,"");l!==n.cell.source?(n.cell.source=l,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,ie.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(e,o)),void Ge()}if("add"===s){const e=u.split(/\s+/).filter(Boolean),o=e.find(e=>null!==v(e)),n=e.filter(e=>e!==o).join(" ");return _e(o,e=>((e,o)=>{const n=e.trim().toLowerCase(),t="md"===n||"markdown"===n||"text"===n||"txt"===n;if(n&&!t&&"py"!==n&&"code"!==n&&"python"!==n)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));we.pause();const l=w(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);we.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(ie.cells.push({kind:t?"markdown":"code",source:r,result:null}),ie.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${ie.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${ie.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void Ge()}if("editor"===s&&/^[\w-]*$/.test(u))return(e=>{const o=e.trim().toLowerCase(),n=k(Le());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${qe()?"saved":Te()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=v(e),t=b(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(t?` ${Me[e]}`:" not installed here")+(e===n?chalk.green(" ← now"):""))}return console.log(chalk.gray(" one edit only: ")+chalk.cyan("edit 3 nano")+chalk.gray(" · back to $EDITOR / vi: ")+chalk.cyan("editor default")),void console.log()}if("default"===o||"reset"===o||"off"===o)return f({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${k($())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const t=v(o);if(!t)return void console.log(chalk.yellow(` unknown editor "${o}" — `)+chalk.cyan("editor nano")+chalk.yellow(" · ")+chalk.cyan("editor code")+chalk.yellow(" · ")+chalk.cyan("editor vi"));const l=k(t);qe()&&k(qe())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):b(t.cmd)?(f({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${n===l?"default":n}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(u),void Ge();if("reload"===s&&""===u)return ie.path&&e(ie.path)?De()&&"reload"!==Se?(Se="reload",console.log(chalk.yellow(" unsaved changes here will be replaced by the file — ")+chalk.cyan("reload")+chalk.yellow(" again to go ahead, or ")+chalk.cyan("save")+chalk.yellow(" first."))):(Se=null,Re(!1)):console.log(chalk.gray(" nothing to reload — this notebook has no file yet (")+chalk.cyan("save")+chalk.gray(" first, or ")+chalk.cyan("load <file>")+chalk.gray(").")),void Ge();if("load"===s&&!/^[=(.[]/.test(u)||"open"===s&&""!==u){if(!u)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ge();const o=R(u,r()),n=g(o)?o:d(process.cwd(),o);if(e(n))if(ie.dirty&&"load"!==Se)Se="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(s)+chalk.yellow(" again to discard them."));else{Se=null;const e=ye(n);ie.cells=e.doc.cells,ie.path=e.doc.path,ie.dirty=!1,ie.mtimeMs=e.doc.mtimeMs,ie.diskSig=e.doc.diskSig,$e=void 0,he=le(ie.path),console.log(e.note),console.log(chalk.gray(" the kernel keeps its variables — ")+chalk.cyan("restart")+chalk.gray(" for a clean start."))}else console.log(chalk.yellow(" no such file: ")+chalk.white(n)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ge()}if("del"===s||"delete"===s)return(e=>{const o=Ne(e);o&&(ie.cells.splice(o.idx-1,1),ie.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${ie.cells.length} left.`)+(o.idx<=ie.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(u),void Ge();if(("md"===s||"py"===s)&&/^\d+$/.test(u))return((e,o)=>{const n=Ne(e);if(!n)return;const t="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,ie.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${t}`)+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 ${t}.`))})(u,"md"===s?"markdown":"code"),void Ge();if("gpu"===s)return Pe=!0,await Ae(u),Pe=!1,void Ge();if("download"===s||"dl"===s)return Pe=!0,await(async e=>{if(!ue)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:`${ue.outDir}/${n}`;let r;try{r=await de.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=he?y(process.cwd(),"icoa-kaggle",he):process.cwd(),s=y(a,i(n));try{o(a,{recursive:!0}),l(s,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(s)+chalk.gray(` (${r.length} bytes)`)),he&&"submission.csv"===i(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${he}`)+chalk.gray(" — then upload on Kaggle yourself."))})(u),Pe=!1,void Ge();if("check"===s||"submit"===s||"kaggle"===s){const e=await import("./kaggle.js"),o=u.split(/\s+/).filter(Boolean),n="kaggle"===s?(o[0]||"").toLowerCase():s,t=("kaggle"===s?o[1]:o[0])||le(ie.path)||void 0;Pe=!0;try{"submit"===n?await e.runKaggleSubmit(t):"check"===n?await e.runKaggleCheck(t):"guide"===n?await e.runKaggleGuide(t):await e.runKaggle("kaggle"===s?o[0]:t)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Pe=!1,void Ge()}if("board"===s){const{runBoard:e}=await import("./board.js"),o=u.split(/\s+/).filter(Boolean);Pe=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Pe=!1,void Ge()}if("ai"===s||"/ai"===s)return Pe=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),t=o.length>0&&/^\d+$/.test(o[0]),l=(t?o.slice(1):o).join(" ").trim(),r=t?Number(o[0]):(()=>{for(let e=ie.cells.length-1;e>=0;e--)if((ie.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??ie.cells.length;if(0===ie.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=Ne(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(Y,"")).join("\n")));return o.join("\n").replace(Y,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!ie.path||!le(ie.path))return"";try{const e=JSON.parse(n(y(c(ie.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return Ue(o,350)}catch{return""}})(),g=z(),d=g?"你在帮一个 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.",u=d.length+l.length+120,m=Math.max(400,h-u-i.length),f=Ue(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)",l?`\n[question]\n${l}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),x=g;console.log(),Oe||(Oe=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(z()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${h} ${z()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(z()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(z()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${h} chars`)+chalk.gray(x?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(x?" · 含输出":" · output included"):"")+($?chalk.yellow(x?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),q(`ipynb: ai ${a.idx}${l?` — ${l}`:""}`);const P=await p(v);if(console.log(),!P.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(P.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of I(P.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${x?"<你的问题>":"<your question>"}`)+chalk.gray(x?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(x?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(x?" 再跑一次":" run it again")),console.log(chalk.gray(x?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(u),Pe=!1,void Ge();if("run"===s)return Pe=!0,await(async e=>{const o=B(e,ie.cells.length);if(o)for(const e of o){const n=ie.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(M(n,50))+chalk.gray(" ──"));try{n.result=await de.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void Q()}if(ie.dirty=!0,se(n.result,Z),Ke(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(z()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(z()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void Q()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of I(n.source))console.log(e);console.log()}}else console.log(0===ie.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"))})(u),Pe=!1,void Ge();if("save"===s)return(e=>{if(0===ie.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?g(e.trim())?e.trim():d(process.cwd(),e.trim()):ie.path?ie.path.endsWith(".ipynb")?ie.path:`${ie.path.replace(/\.[^./]+$/,"")}.ipynb`:d(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===ie.path?ge(o):void 0;if(void 0!==n&&void 0!==ie.mtimeMs&&n!==ie.mtimeMs&&"save"!==Se)return Se="save",console.log(chalk.yellow(` ${i(o)} was changed in your editor after this notebook read it.`)),void console.log(chalk.gray(" ")+chalk.cyan("save")+chalk.gray(" again to overwrite those changes · ")+chalk.cyan("reload")+chalk.gray(" to take the file instead"));Se=null;try{l(o,W(ie.cells)),ie.path=o,ie.dirty=!1,ie.mtimeMs=ge(o),ie.diskSig=ce(ie.cells),$e=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${ie.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(u),void Ge();if(""===a)return void Ge()}if(ve.length>0&&X.has(a.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(a.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ge();if(ve.push(t),!G(ve))return 1!==ve.length||xe||(xe=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ge();const s=ve.join("\n").replace(/\s+$/,"");if(ve.length=0,""!==s.trim()){Pe=!0;try{const e=await de.execute(s);ie.cells.push({kind:"code",source:s,result:e}),ie.dirty=!0,se(e,Z);const o=Ke(ie.cells[ie.cells.length-1],ie.cells.length);e.ok||o||Q()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),Q()}Pe=!1,Ge()}else Ge()};we.on("line",e=>{Be(e)}),me||we.on("close",async()=>{await de.shutdown().catch(()=>{}),process.exit(0)}),Ge(),await Ie}
|