icoa-cli 2.19.713 → 2.19.715

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readdirSync as t,readFileSync as n,statSync as l,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{createHash as s}from"node:crypto";import{Interface as i,createInterface as c}from"node:readline";import{basename as g,dirname as y,isAbsolute as d,join as u,resolve as h}from"node:path";import chalk from"chalk";import{aienvPaths as p}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as f,askIoaiOneShot as m}from"./ai4ioai.js";import{getConfig as w,saveConfig as b}from"../lib/config.js";import{editTextInEditor as k,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as S,parseLeaseResponse as E,queueLine as C,windowLine as j}from"../lib/gpu.js";import{shouldExecuteCell as G}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{isPng as I,mdImages as N,mdWithoutImages as O,thumbForTerminal as T}from"../lib/term-image.js";import{NotebookKernel as M,buildRemoteBridgeCommand as D}from"../lib/kernel.js";import{getMainRl as q,setMainRl as L}from"../lib/main-rl.js";import{logCommand as z}from"../lib/logger.js";import{startLogSync as R,stopLogSync as K}from"../lib/log-sync.js";import{cellPreview as B,fromWholeEditText as F,mergeReloadedCells as W,normalizePathArg as J,parseIpynb as V,parsePercentPy as Y,parseRunRange as H,serializeIpynb as X,statusChar as Z,toWholeEditText as Q}from"../lib/notebook-doc.js";import{committeeLease as ee,readCommitteeSession as oe,TIER_LABEL as te}from"../lib/gputask-session.js";import{enterPanel as ne,leavePanel as le,printHelp as re}from"../lib/guide-panel.js";import{lazyFile as ae}from"../lib/lazy-assets.js";import{openFile as se}from"../lib/open-file.js";import{serviceBase as ie,siteBase as ce}from"../lib/site.js";const ge=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function ye(){return(w().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 de(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const ue=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),he=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function pe(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const fe=ce();function me(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):fe}function we(){return u(a(),".icoa","gpu-key")}function be(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(we(),"utf-8").trim()||null}catch{return null}}async function ke(e,o,t){try{const n=await fetch(`${me()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{key:o,task:t}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await n.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function ve(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let $e=0,_e=null;function xe(e,o){for(const t of e.outputs)if("stream"===t.kind){const e=t.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===t.name?chalk.yellow(e):chalk.white(e))}else if("result"===t.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(t.text));else if("error"===t.kind){console.log(chalk.bold.red(` ${t.ename}: ${t.evalue}`));for(const e of t.traceback)console.log(chalk.gray(` ${e.replace(ge,"")}`))}else"display"===t.kind&&Pe(t.data,o)}function Pe(e,t){if(e["image/png"])try{o(t,{recursive:!0}),$e+=1;const n=u(t,`figure-${$e}.png`),l=Buffer.from(e["image/png"],"base64");r(n,l),_e=n;for(const e of T(l))console.log(e);return console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(n)),void(se(n)?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 Se(t,a,s){for(const i of N(t.source)){const c=i.alt||g(i.target.split("?")[0])||"image";let y=null,p="png";try{if(i.target.startsWith("attachment:")){const e=t.attachments?.[decodeURIComponent(i.target.slice(11))],o=e?Object.keys(e).find(e=>e.startsWith("image/")):void 0;e&&o&&(y=Buffer.from(e[o],"base64"),p="image/jpeg"===o?"jpg":o.slice(6).replace("svg+xml","svg"))}else if(i.target.startsWith("data:image/")){const e=/^data:image\/([a-z0-9+.-]+);base64,(.+)$/i.exec(i.target);e&&(y=Buffer.from(e[2],"base64"),p="jpeg"===e[1]?"jpg":e[1].replace("svg+xml","svg"))}else{if(/^https?:/i.test(i.target)){console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+chalk.gray(` — web image, not fetched: ${i.target}`));continue}{const o=d(i.target)?i.target:h(a,decodeURIComponent(i.target));e(o)&&l(o).size<=31457280&&(y=n(o),p=(o.split(".").pop()||"png").toLowerCase())}}}catch{y=null}if(!y){console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+chalk.gray(` — image not found: ${i.target.slice(0,60)}`));continue}let f="";try{o(s,{recursive:!0}),$e+=1,f=u(s,`figure-${$e}.${p.replace(/[^a-z0-9]/g,"")||"png"}`),r(f,y),_e=f}catch{f=""}const m=I(y)?T(y):[];for(const e of m)console.log(e);console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+(f?chalk.gray(" → ")+chalk.cyan(f):"")+chalk.gray(m.length?" (type ":" (no in-terminal preview for this format — type ")+chalk.cyan("open")+chalk.gray(" for full size)"))}}function Ee(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function Ce(e){if(e)try{return l(e).mtimeMs}catch{return}}function je(o){const t=J(o,a()),l=d(t)?t:h(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")?V(e):Y(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:Ce(l),diskSig:Ee(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.")}}}const Ge={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const I=E?.trim().toLowerCase().replace(/-demo$/,"");if(I&&Ge[I]){const t=await async function(t){const l=Ge[t],a=u(process.cwd(),"icoa-lab"),s=u(a,g(l));if(e(s))return console.log(chalk.gray(" Using your copy ")+chalk.cyan(s)+chalk.gray(" (edits kept — delete the file to start from the original).")),s;process.stdout.write(chalk.gray(" Fetching the demo notebook…"));const i=await ae(l);if(!i)return console.log(chalk.yellow(" not available right now.")),console.log(chalk.gray(" It needs one online moment — try ")+chalk.cyan(`ipynb ${t}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,n(i))}catch(e){return console.log(chalk.yellow(` could not write ${s}: ${e instanceof Error?e.message:String(e)}`)),null}return console.log(chalk.green(" saved ")+chalk.cyan(s)),s}(I);if(!t)return;E=t}const N=p(a()),T=u(a(),".icoa","ipynb-out");de();const ce=e(N.python),fe=oe();if(!ce&&!fe)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).")),console.log(chalk.gray(" (Committee seat holders: open the seat with ")+chalk.cyan("gpufortask")+chalk.gray(" and the notebook runs there instead.)")),void console.log();const $e=E?je(E):null,Pe=$e?$e.doc:{cells:[],path:null,dirty:!1},Ue=()=>Pe.path?y(Pe.path):void 0;let Ae=new M({venvPython:N.python,venvRoot:N.root,cwd:Ue()}),Ie=null,Ne=null,Oe=null,Te=ve(Pe.path);if(ce){process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Ae.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."))}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — cells run on your committee seat: type ")+chalk.bold.green("gpu on")+chalk.gray("."));$e&&console.log($e.note);let Me=!1,De=!1;ne({id:"ipynb",title:{en:"Notebook",zh:"Notebook 笔记本"},what:{en:"A Jupyter notebook inside the terminal: cells run one by one in a live Python kernel. You are already inside it — never type python file.ipynb here.",zh:"终端里的 Jupyter notebook:cell 在常驻 Python 内核里逐格运行。你已经在 notebook 里面了 —— 不要再敲 python file.ipynb。"},steps:[{verb:"cells",what:{en:"list the cells (md = explanation, ○ = not run yet)",zh:"列出所有 cell(md = 讲解,○ = 还没跑)"},done:()=>Me},{verb:"run all",what:{en:"run every cell top to bottom; stops at the first error",zh:"从头到尾跑每一格;遇到第一个报错就停"},done:()=>Pe.cells.some(e=>null!==e.result)},{verb:"edit",what:{en:"open the WHOLE notebook in your editor (edit 3 = one cell)",zh:"整本在编辑器里打开(edit 3 = 只开第 3 格)"},done:()=>Pe.dirty},{verb:"save",what:{en:"write it back to disk as a real .ipynb",zh:"存回磁盘,标准 .ipynb"},done:()=>De},{verb:"gpu on",what:{en:"run the cells on a GPU box (a T4 starts for you, ~1–2 min); gpu off hands it back",zh:"把 cell 搬到 GPU 上跑(T4 按需开机约 1–2 分钟);gpu off 归还"},done:()=>null!==Ie,optional:!0},{verb:"ai 4",what:{en:"ask the tutor why cell 4 did that (ai = the last error)",zh:"问导师第 4 格为什么这样(裸 ai = 最后一个报错)"},optional:!0}],notes:[{en:"Plain Python typed at the prompt runs as a new cell (a blank line ends a block). help all = every command.",zh:"直接敲 Python 就是新的一格(空行结束多行块)。help all = 全部命令。"}],leave:{verb:"quit",what:{en:"leave the notebook",zh:"离开 notebook"}},guide:()=>Qe()});const qe=q(),Le=null!==qe,ze=Le?qe.listeners("line").slice():[];Le&&qe.removeAllListeners("line");const Re=Le?qe:c({input:process.stdin,output:process.stdout,terminal:!0});Le||L(Re);const Ke=Le?Re.prompt:null,Be=Le?Re.getPrompt():"";Le&&(Re.prompt=i.prototype.prompt),Le||R();const Fe=[];let We,Je=!1,Ve=!1,Ye=!1,He=null,Xe=null;const Ze=()=>{if(Xe)return Re.setPrompt(chalk.bold.cyan(` editor 1-${Xe.options.length} > `)),void Re.prompt();const e=Ie?"icoa ipynb ⚡gpu":"icoa ipynb";Re.setPrompt(chalk.bold.cyan(Fe.length?`${e} ...> `:`${e}> `)),Re.prompt()},Qe=()=>{const o=Pe.path?y(Pe.path):process.cwd(),t=ve(Pe.path);let l="",r=!1;try{const e=JSON.parse(n(u(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Pe.cells.filter(e=>null!==e.result).length,s=e(u(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Pe.path?g(Pe.path):"new empty notebook")+chalk.gray(` · ${Pe.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Ie?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(t?" — trains the baseline, writes submission.csv":" — runs every cell top to bottom")),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()};let eo=()=>{};const oo=new Promise(e=>{eo=e}),to=async()=>{if(Ae=new M({venvPython:N.python,venvRoot:N.root,cwd:Ue()}),e(N.python)){process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Ae.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"))}}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — ")+chalk.cyan("gpu on")+chalk.gray(" reconnects to your seat."))},no=async(e,t=!1)=>{const n=ee(e),l=S(n);if(l.length>0)return console.log(chalk.red(" committee seat file rejected: ")+chalk.gray(l.join(", "))),!1;const s=u(a(),".icoa","gputask","key");try{o(u(a(),".icoa","gputask"),{recursive:!0}),r(s,e.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),!1}const i=Pe.path?g(y(Pe.path)):"work",c=`${n.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=D(n.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new M({spawnSpec:{command:"ssh",args:P(n,s,d)},readyTimeoutMs:9e4});t||process.stdout.write(chalk.gray(` Connecting to your seat (${e.host})…`));try{await h.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" The box may be rebuilding (Spot reclaim) — ")+chalk.cyan("gpufortask")+chalk.gray(" shows the seat state; ")+chalk.cyan("gpu on")+chalk.gray(" again once it is ready.")),!1}await Ae.shutdown().catch(()=>{}),Ae=h,Ie={...n,outDir:c},Oe=e,Ne=Date.now(),h.onUnexpectedExit=()=>{Ae===h&&(console.log(),console.log(chalk.bold.yellow(" ⚠ The GPU box went away (Spot reclaim or seat ended).")),console.log(chalk.gray(" Files are kept on the seat; variables are gone. ")+chalk.cyan("gpu on")+chalk.gray(" in 1–2 min reconnects (the seat is rebuilt automatically).")),Ie=null,Oe=null,Ne=null,to().then(()=>Ze()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${te[e.tier]} · cells run in ${c}`));const p=await lo();return p>0&&console.log(chalk.gray(` ${p} small file${1===p?"":"s"} from this notebook's folder sent to the box.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to rerun there · ")+chalk.cyan("upload <file>")+chalk.gray(" sends more · ")+chalk.cyan("download <file>")+chalk.gray(" brings results back · ")+chalk.cyan("gpu off")+chalk.gray(" returns to the local kernel (seat stays).")),!0},lo=async()=>{if(!Pe.path||!Ie?.outDir)return 0;const e=y(Pe.path);let o=[];try{o=t(e)}catch{return 0}let r=0;for(const t of o){if(t.startsWith("."))continue;const o=u(e,t);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await Ae.putFile(`${Ie.outDir}/${t}`,n(o)),r++}catch{}}return r},ro=async(e,t=!1)=>{if(!Ie)return t||console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed).")),!1;const n=e.trim()||"submission.csv",l=n.startsWith("/")?n:`${Ie.outDir}/${n}`;let a;try{a=await Ae.fetchFile(l)}catch(e){return console.log(chalk.yellow(` could not fetch ${l}: `)+chalk.gray(e instanceof Error?e.message:String(e))),console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)")),!1}const s=Te?u(process.cwd(),"icoa-kaggle",Te):process.cwd(),i=u(s,g(n));try{o(s,{recursive:!0}),r(i,a)}catch{return console.log(chalk.yellow(" could not write the file here — check directory permissions.")),!1}return console.log(chalk.green(" ✓ downloaded ")+chalk.white(i)+chalk.gray(` (${a.length} bytes)`)),!t&&Te&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Te}`)+chalk.gray(" · score it: ")+chalk.cyan("submit")),!0},ao=async e=>{const[t,...n]=e.trim().split(/\s+/),l=(t??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ie)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=oe();if(e)return void await(async e=>{await no(e)})(e);const t=be();if(!t)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)."));Te||(Te=ve(Pe.path));const n=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await ke("lease",t,Te??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-n)/1e3)} s`;for(;"queued"===l.state&&s<(l.bootStage||i?60:24);)l.bootStage&&(i=!0),0===s&&console.log(),process.stdout.write(`\r ${chalk.yellow(C(l))} `),await new Promise(e=>setTimeout(e,5e3)),l=await ke("status",t),s++;if("queued"===l.state)return console.log(),void(i?(console.log(chalk.yellow(` The GPU box is still starting (${c()} so far) — your place is held.`)),console.log(chalk.gray(" Keep editing; ")+chalk.cyan("gpu on")+chalk.gray(" again in a minute picks it up."))):(console.log(chalk.yellow(" Still queued — your place is held server-side.")),console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."))));if(i&&"ready"===l.state&&(console.log(),console.log(chalk.green(` ✓ GPU box ready in ${c()}`)+chalk.gray(` · ${l.gpuName??"GPU"}${l.zone?` · ${l.zone}`:""} · built just for this session`))),"ready"!==l.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${l.message??"no lease granted"}`));const g=S(l);if("local"!==l.transport||process.env.ICOA_GPU_SERVER||g.push("local transport from a non-dev broker"),g.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(g.join(", "))),void await ke("release",t);const y=Te?`${l.dataRoot}/${Te}`:l.dataRoot,d=D(l.python,{ICOA_KAGGLE_DATA:y,ICOA_KAGGLE_OUT:l.outDir},l.outDir);let h;if("local"===l.transport)h={command:"/bin/sh",args:["-c",d]};else{const e=u(a(),".icoa","gpu","lease-key");try{o(u(a(),".icoa","gpu"),{recursive:!0}),r(e,l.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await ke("release",t)}h={command:"ssh",args:P(l,e,d)}}const p=new M({spawnSpec:h,readyTimeoutMs:9e4}),f=Date.now();process.stdout.write(chalk.gray(" connecting…"));try{await p.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),void await ke("release",t)}await Ae.shutdown().catch(()=>{}),Ae=p,Ie=l,Ne=Date.now();const m=Math.round((l.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected")+chalk.gray(` (${Math.round((Date.now()-f)/1e3)} s).`)),console.log(chalk.gray(` Cells now run on the ${l.gpuName?`${l.gpuName} `:""}GPU box · ${m}m left on this lease.`));const w=j(l.windowCloseEpoch);w&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${w}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),Te&&console.log(chalk.gray(` Dataset is already on the box (${Te}) — 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"===l||"disconnect"===l?await(async()=>{if(Ie&&Oe){const e=Ne?Math.round((Date.now()-Ne)/1e3):0;return await Ae.shutdown().catch(()=>{}),Ie=null,Oe=null,Ne=null,console.log(chalk.green(` ⚡ Back to the local kernel after ${Math.floor(e/60)} m ${e%60} s`)+chalk.gray(" — the seat stays open (files kept); ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now.")),void await to()}if(!Ie)return void console.log(chalk.gray(" not on a GPU kernel."));const e=be(),o=void 0!==Ie.gpuName,t=Ne?Math.round((Date.now()-Ne)/1e3):0;await Ae.shutdown().catch(()=>{}),e&&await ke("release",e),Ie=null,Ne=null;const n=Math.floor(t/60),l=n>0?`${n} m ${t%60} s`:`${t} s`;console.log(chalk.green(` ⚡ GPU lease released after ${l}`)+chalk.gray(" — billing for you stopped.")),o&&console.log(chalk.gray(" The box recycles itself now that nobody holds it (")+chalk.cyan("gpu queue")+chalk.gray(" shows 0 boxes once it is gone); the next ")+chalk.cyan("gpu on")+chalk.gray(" builds a fresh one.")),await to()})():"status"===l||""===l?await(async()=>{const e=oe();if(e)return console.log(chalk.green(` ⚡ committee seat · ${te[e.tier]} · ${e.host}`)+chalk.gray(Oe?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=be();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const t=await ke("status",o);if("ready"===t.state){const e=Math.round((t.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Ie?" (this notebook is connected)":" (not connected here — gpu on)"));const o=j(t.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===t.state?console.log(chalk.yellow(` ${C(t)}`)):"none"===t.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${t.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=be();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const t=await fetch(`${me()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),n=await t.json();o=n.data??n}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 t="number"==typeof o.boxes?o.boxes:0,n="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(` · ${t} box${1===t?"":"es"} · ${n} free`));const a=j("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(0===t?" (no box up — gpu on starts a T4 for you, ~1–2 min)":" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",t="number"==typeof e.time_left_sec?e.time_left_sec:0,n=Math.floor(t/60),l=String(t%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${n}:${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:"?",t="number"==typeof e.position?e.position:"?",n=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${t} `)+chalk.white(o.padEnd(8))+n)}console.log()})():"key"===l?(e=>{const t=e.trim();if(t)try{o(u(a(),".icoa"),{recursive:!0}),r(we(),`${t}\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(` (${we()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(n.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>"))},so=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Pe.cells.length?(console.log(0===Pe.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Pe.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Pe.cells[o-1],idx:o}},io=(e,o)=>{if(e.length<=o)return e;const t=Math.floor(.6*o);return`${e.slice(0,t)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-t))}`};let co=!1;const go=()=>{const e=w().notebookEditor;return e?_(e):null},yo=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),uo=()=>go()??x(),ho={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"},po=(e,o)=>{if(e){const t=_(e);return t?v(t.cmd)?(o(t),!0):(console.log(chalk.yellow(` ${$(t)} 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(go()||yo())return o(uo()),!0;const t=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return t.length<2||!process.stdin.isTTY?(o(x()),!0):((e=>{console.log(),console.log(chalk.bold.white(" Which editor should edit / add open?")+chalk.gray(" (asked once)")),e.forEach((e,o)=>{const t=$(e);console.log(chalk.cyan(` ${o+1} ${t.padEnd(5)}`)+chalk.gray(` ${ho[t]??""}`)+("nano"===t?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(t),Xe={resume:o,tries:0,options:t},!1)},fo=e=>{if(!Pe.path)return!1;let o;try{const e=n(Pe.path,"utf8");o=Pe.path.endsWith(".ipynb")?V(e):Y(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=W(Pe.cells,o);return Pe.cells=t.cells,Pe.dirty=!1,Pe.mtimeMs=Ce(Pe.path),Pe.diskSig=Ee(o),We=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Pe.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},mo=()=>void 0!==Pe.diskSig?Ee(Pe.cells)!==Pe.diskSig:Pe.dirty,wo=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!U(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)),bo=async o=>{if(o.trim()&&z(`ipynb: ${o.trim()}`),Ve)return void(o.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Xe){const e=Xe,t=o.trim().toLowerCase(),n=_(t),l=/^\d+$/.test(t)?e.options[Number(t)-1]:n?e.options.find(e=>$(e)===$(n)):void 0;return l?(Xe=null,b({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===t||["q","quit","back","cancel","exit"].includes(t)?(Xe=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Xe=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=>$(e)).join(" / "))),void Ze()}let t=o.trim();if(0===Fe.length&&/^icoa\s+[a-z/]/i.test(t)&&(t=t.replace(/^icoa\s+/i,"")),0===Fe.length){const o=t.split(/\s+/),l=(o[0]??"").toLowerCase(),i=t.slice(o[0]?.length??0).trim();if("quit"!==l&&"exit"!==l&&"q"!==l&&(Ye=!1),He&&l!==He&&(He=null),he.has(l)&&(()=>{if(!Pe.path||void 0===Pe.mtimeMs)return;const e=Ce(Pe.path);if(void 0!==e&&e!==Pe.mtimeMs){if(mo()){if(We===e)return;return We=e,console.log(chalk.yellow(` ⚠ ${g(Pe.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"))}fo(!0)}})(),"quit"===l||"exit"===l||"back"===l||"q"===l||"menu"===l)return Pe.dirty&&!Ye?(Ye=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ze()):void await(async()=>{if(le("ipynb"),Re.removeAllListeners("line"),Le||K(),console.log(),Ie&&Oe)Ie=null,console.log(chalk.gray(" ⚡ Committee seat stays open (files kept) — ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now, or it closes after 40 min idle."));else if(Ie){const e=be();e&&await ke("release",e),Ie=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Ae.shutdown().catch(()=>{}),Le){Ke&&(Re.prompt=Ke),Re.setPrompt(Be);for(const e of ze)Re.on("line",e);Re.prompt(),eo()}else L(null),eo(),Re.close()})();if("clear"===l||"cls"===l)return console.clear(),de(),void Ze();if("restart"===l)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Ae.shutdown().catch(()=>{});try{await Ae.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 Ze();if("help"===l||"?"===l)return/^(all|commands|full)$/i.test(i.trim())?(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(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),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(ye()?" 问 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 GPU box — a GCP T4 starts for you on demand (~1–2 min), ")+chalk.cyan("gpu off")+chalk.gray(" hands it back")),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(" selfcheck")+chalk.gray(" committee seat: rerun the whole notebook fresh, measure peak GPU memory → capsule size, file the report")),console.log(chalk.cyan(" upload <f>")+chalk.gray(" send a file to the box (committee seat: files next to the notebook go up on gpu on)")),console.log(chalk.gray(" try it: ")+chalk.cyan("icoa> ipynb mnist")+chalk.gray(" — the MNIST demo notebook (edit → run → train on the T4 → gpu off)")),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()):re(),void Ze();if("guide"===l||"/guide"===l)return Qe(),void Ze();if("python"===l||"python3"===l)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 Ze();if("open"===l&&""===i)return _e&&se(_e)?console.log(chalk.gray(" reopening ")+chalk.cyan(_e)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ze();if("cells"===l||"ls"===l)return(()=>{if(Me=!0,0===Pe.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);Pe.cells.forEach((o,t)=>{const n=Z(o),l="✓"===n?chalk.green(n.padEnd(2)):"✗"===n?chalk.red(n.padEnd(2)):"md"===n?chalk.magenta(n.padEnd(2)):chalk.gray(n.padEnd(2));console.log(`${chalk.cyan(String(t+1).padStart(4))} ${l} ${chalk.white(B(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 Ze();if("show"===l)return(e=>{const o=so(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 A(O(o.cell.source)))console.log(e);Se(o.cell,Pe.path?y(Pe.path):process.cwd(),T),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 ──")),xe(o.cell.result,T)),console.log()}})(i),void Ze();if("edit"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ").toLowerCase();return""===t||"all"===t?po(o,e=>(e=>{Re.pause();const o=k(Q(Pe.cells),".py",e,"notebook");if(Re.resume(),null===o)return void console.log(chalk.yellow(" editor cancelled or failed — notebook unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const t=F(o,Pe.cells);if(t.same)return void console.log(chalk.gray(" no changes."));if(0===t.cells.length&&Pe.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${Pe.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));Pe.cells=t.cells,Pe.dirty=!0;const n=[];t.changed.length&&n.push(`${t.changed.length} changed (${t.changed.join(", ")})`),t.added.length&&n.push(`${t.added.length} added (${t.added.join(", ")})`),t.deleted&&n.push(`${t.deleted} deleted`),t.reordered&&n.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${Pe.cells.length} cells`)+chalk.gray(` · ${n.join(" · ")}`));const l=[...t.changed,...t.added].filter(e=>"code"===Pe.cells[e-1].kind).sort((e,o)=>e-o);if(l.length){const e=l[0],o=l[l.length-1];console.log(chalk.gray(" unchanged cells kept their output · run what changed: ")+chalk.cyan(e===o?`run ${e}`:`run ${e}-${o}`)+chalk.gray(" · or ")+chalk.cyan("run all"))}})(e)):so(t)&&po(o,e=>((e,o)=>{const t=so(e);if(!t)return;Re.pause();const n=k(t.cell.source,"markdown"===t.cell.kind?".md":".py",o);if(Re.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=n.replace(/\s+$/,"");l!==t.cell.source?(t.cell.source=l,t.cell.result=null,t.cell.rawOutputs=void 0,t.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${t.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${t.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(t,e)),void Ze()}if("add"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ");return po(o,e=>((e,o)=>{const t=e.trim().toLowerCase(),n="md"===t||"markdown"===t||"text"===t||"txt"===t;if(t&&!n&&"py"!==t&&"code"!==t&&"python"!==t)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Re.pause();const l=k(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py",o);Re.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Pe.cells.push({kind:n?"markdown":"code",source:r,result:null}),Pe.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Pe.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Pe.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(t,e)),void Ze()}if("editor"===l&&/^[\w-]*$/.test(i))return(e=>{const o=e.trim().toLowerCase(),t=$(uo());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(t)+chalk.gray(` (${go()?"saved":yo()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),n=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(n?` ${ho[e]}`:" not installed here")+(e===t?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 b({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const n=_(o);if(!n)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=$(n);go()&&$(go())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(n.cmd)?(b({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${t===l?"default":t}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(i),void Ze();if("reload"===l&&""===i)return Pe.path&&e(Pe.path)?mo()&&"reload"!==He?(He="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."))):(He=null,fo(!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 Ze();if("load"===l&&!/^[=(.[]/.test(i)||"open"===l&&""!==i){if(!i)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ze();const o=J(i,a()),t=d(o)?o:h(process.cwd(),o);if(e(t))if(Pe.dirty&&"load"!==He)He="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(l)+chalk.yellow(" again to discard them."));else{He=null;const e=je(t);Pe.cells=e.doc.cells,Pe.path=e.doc.path,Pe.dirty=!1,Pe.mtimeMs=e.doc.mtimeMs,Pe.diskSig=e.doc.diskSig,We=void 0,Te=ve(Pe.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(t)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ze()}if("del"===l||"delete"===l)return(e=>{const o=so(e);o&&(Pe.cells.splice(o.idx-1,1),Pe.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Pe.cells.length} left.`)+(o.idx<=Pe.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(i),void Ze();if(("md"===l||"py"===l)&&/^\d+$/.test(i))return((e,o)=>{const t=so(e);if(!t)return;const n="markdown"===o?"markdown":"Python";t.cell.kind!==o?(t.cell.kind=o,t.cell.result=null,t.cell.rawOutputs=void 0,t.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${t.idx} → ${n}`)+chalk.gray(" — ")+chalk.cyan(`run ${t.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${t.idx} is already ${n}.`))})(i,"md"===l?"markdown":"code"),void Ze();if("gpu"===l)return Ve=!0,await ao(i),Ve=!1,void Ze();if("download"===l||"dl"===l)return Ve=!0,await ro(i),Ve=!1,void Ze();if("selfcheck"===l||"self-check"===l)return Ve=!0,await(async()=>{const e=Oe;if(!e||!Ie)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===Pe.cells.filter(e=>"code"===e.kind).length)return void console.log(chalk.yellow(" nothing to check — the notebook has no code cells."));console.log(chalk.bold.cyan(" 🔬 selfcheck")+chalk.gray(` · fresh kernel · ${te[e.tier]} · every code cell from the top`));const o=Ae;if(await no(e,!0),Ae===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const t=Date.now(),n=[];let l=!1;for(let e=0;e<Pe.cells.length;e++){const o=Pe.cells[e];if("code"!==o.kind)continue;const t=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${t} … `));try{o.result=await Ae.execute(o.source)}catch(e){n.push({n:t,ok:!1,ms:Date.now()-r,error:e instanceof Error?e.message:String(e)}),console.log(chalk.red("kernel error")),l=!0;break}Pe.dirty=!0;const a=Date.now()-r,s=o.result.outputs.find(e=>"error"===e.kind);if(n.push({n:t,ok:o.result.ok,ms:a,error:s&&"error"===s.kind?`${s.ename}: ${s.evalue}`:void 0}),console.log(o.result.ok?chalk.green(`ok ${(a/1e3).toFixed(1)} s`):chalk.red(`raised ${(a/1e3).toFixed(1)} s`)),!o.result.ok){xe(o.result,T),l=!0;break}}const r=Date.now()-t,a=["import json as _j, os as _o, sys as _s, hashlib as _h, platform as _p",'_r = {"python": _s.version.split()[0], "platform": _p.platform()}',"try:"," import torch as _t",' _r["torch"] = _t.__version__'," if _t.cuda.is_available():",' _r["gpu"] = _t.cuda.get_device_name(0)',' _r["peak_gib"] = round(_t.cuda.max_memory_allocated() / 2**30, 3)',' _r["reserved_gib"] = round(_t.cuda.max_memory_reserved() / 2**30, 3)',"except Exception as _e:",' _r["torch"] = "n/a: %s" % _e','for _m in ("sklearn", "numpy", "pandas", "transformers"):'," try:"," _r[_m] = __import__(_m).__version__"," except Exception:"," pass",'_r["fence"] = _o.environ.get("CUDA_MPS_PINNED_DEVICE_MEM_LIMIT")','_r["units"] = _o.environ.get("ICOA_GPU_UNITS")','_r["files"] = {}','for _f in sorted(_o.listdir(".")):',' if _o.path.isfile(_f) and not _f.startswith("."):'," _sz = _o.path.getsize(_f)"," _d = _h.sha256()",' with open(_f, "rb") as _fh:',' for _c in iter(lambda: _fh.read(1 << 20), b""):'," _d.update(_c)",' _r["files"][_f] = {"bytes": _sz, "sha256": _d.hexdigest()[:16]}','print("ICOA_SELFCHECK " + _j.dumps(_r))'].join("\n");let s={};try{const e=(await Ae.execute(a)).outputs.filter(e=>"stream"===e.kind).map(e=>"stream"===e.kind?e.text:"").join("").split("\n").find(e=>e.startsWith("ICOA_SELFCHECK "));e&&(s=JSON.parse(e.slice(15)))}catch{}const i="number"==typeof s.peak_gib?s.peak_gib:null,c=null===i?null:i<3?1:i<6.5?2:i<10?3:0,y={sid:e.sid,tier:e.tier,notebook:Pe.path?g(Pe.path):null,cells:n,ok:!l,wall_ms:r,env:s,peak_gib:i,units:c,ts:Math.floor(Date.now()/1e3)};console.log(),console.log((l?chalk.bold.red(" ✗ selfcheck: a cell raised"):chalk.bold.green(" ✓ selfcheck: every cell ran"))+chalk.gray(` · ${(r/1e3).toFixed(0)} s wall on a shared box (not a time limit)`)),null!==i?console.log(chalk.white(` peak GPU memory ${i.toFixed(2)} GiB`)+(c?chalk.green(` → ${c} capsule unit${c>1?"s":""}`)+chalk.gray(` (fence ${3.5*c} GiB, allocator cap ${(3.5*c-.5).toFixed(1)})`):chalk.red(" → exceeds 3 units (10 GiB cap) — the task must shrink"))):console.log(chalk.gray(" no GPU memory figure (torch not imported or no CUDA) — CPU task, or add a torch import.")),(s.gpu||s.torch)&&console.log(chalk.gray(` ${s.gpu??"no GPU"} · torch ${s.torch??"?"} · sklearn ${s.sklearn??"?"} · numpy ${s.numpy??"?"}`));const d=s.files??{},u=Object.keys(d);u.length>0&&console.log(chalk.gray(` ${u.length} data file${1===u.length?"":"s"} fingerprinted: ${u.slice(0,6).join(", ")}${u.length>6?", …":""}`));try{const o=await fetch(`${ie("ICOA_GPUTASK_SERVER").replace(/\/$/,"")}/api/icoa/gputask/selfcheck`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,report:y}),signal:AbortSignal.timeout(2e4)});console.log(o.ok?chalk.gray(" report filed with the committee ✓"):chalk.yellow(` report not filed (http ${o.status}) — keep the numbers above.`))}catch{console.log(chalk.yellow(" report not filed (offline) — keep the numbers above."))}})(),Ve=!1,void Ze();if("upload"===l||"up"===l||"put"===l)return Ve=!0,await(async e=>{if(!Ie)return void console.log(chalk.gray(" local kernel — files are already here. ")+chalk.cyan("gpu on")+chalk.gray(" first."));const o=e.trim();if(!o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("upload <file>")+chalk.gray(" (≤ 20 MB; lands in the box work dir)"));const t=J(o,a()),l=d(t)?t:h(Pe.path?y(Pe.path):process.cwd(),t);let r;try{r=n(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${Ie.outDir}/${g(l)}`;try{const e=await Ae.putFile(s,r);console.log(chalk.green(" ✓ uploaded ")+chalk.white(s)+chalk.gray(` (${e} bytes)`))}catch(e){console.log(chalk.yellow(" upload failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),Ve=!1,void Ze();if("check"===l||"submit"===l||"kaggle"===l){const e=await import("./kaggle.js"),o=i.split(/\s+/).filter(Boolean),t="kaggle"===l?(o[0]||"").toLowerCase():l,n=("kaggle"===l?o[1]:o[0])||ve(Pe.path)||void 0;Ve=!0;try{if(("submit"===t||"check"===t)&&Ie&&!await ro("submission.csv",!0))return Ve=!1,void Ze();if("submit"===t){const o=s("sha256").update(Pe.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(n,{code_sha:o,...Oe?{sid:Oe.sid}:{},...Pe.path?{notebook:g(Pe.path)}:{}})}else"check"===t?await e.runKaggleCheck(n):"final"===t?await e.runKaggleFinal(n,o.slice(2)):"board"===t?await e.runKaggleBoard(n):"guide"===t?await e.runKaggleGuide(n):await e.runKaggle("kaggle"===l?o[0]:n)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ve=!1,void Ze()}if("board"===l){const{runBoard:e}=await import("./board.js"),o=i.split(/\s+/).filter(Boolean);Ve=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ve=!1,void Ze()}if("ai"===l||"/ai"===l)return Ve=!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=Pe.cells.length-1;e>=0;e--)if((Pe.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Pe.cells.length;if(0===Pe.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=so(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 t of e.result?.outputs??[])"stream"===t.kind||"result"===t.kind?o.push(t.text):"error"===t.kind&&(o.push(`${t.ename}: ${t.evalue}`),o.push(t.traceback.map(e=>e.replace(ge,"")).join("\n")));return o.join("\n").replace(ge,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Pe.path||!ve(Pe.path))return"";try{const e=JSON.parse(n(u(y(Pe.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return io(o,350)}catch{return""}})(),c=ye(),g=c?"你在帮一个 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.",d=g.length+l.length+120,h=Math.max(400,f-d-i.length),p=io(a.cell.source,Math.floor(.6*h)),w=s?(b=s,k=h-p.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[g,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${p}`,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"),_=c;console.log(),co||(co=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(ye()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${ye()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(ye()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(ye()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${f} chars`)+chalk.gray(_?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(_?" · 含输出":" · output included"):"")+($?chalk.yellow(_?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),z(`ipynb: ai ${a.idx}${l?` — ${l}`:""}`);const x=await m(v);if(console.log(),!x.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(x.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of A(x.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${_?"<你的问题>":"<your question>"}`)+chalk.gray(_?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(_?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(_?" 再跑一次":" run it again")),console.log(chalk.gray(_?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(i),Ve=!1,void Ze();if("run"===l)return Ve=!0,await(async e=>{if(!ce&&!Oe&&!Ie)return void console.log(chalk.yellow(" No kernel here yet — ")+chalk.cyan("gpu on")+chalk.yellow(" connects your committee seat (or ")+chalk.cyan("aienv setup")+chalk.yellow(" for a local one)."));const o=H(e,Pe.cells.length);if(o)for(const e of o){const t=Pe.cells[e-1];if("markdown"!==t.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(B(t,50))+chalk.gray(" ──"));try{t.result=await Ae.execute(t.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void pe()}if(Pe.dirty=!0,xe(t.result,T),wo(t,e),!t.result.ok){const t=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${t?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(ye()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(ye()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void pe()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(O(t.source)))console.log(e);Se(t,Pe.path?y(Pe.path):process.cwd(),T),console.log()}}else console.log(0===Pe.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"))})(i),Ve=!1,void Ze();if("save"===l)return(e=>{if(0===Pe.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?d(e.trim())?e.trim():h(process.cwd(),e.trim()):Pe.path?Pe.path.endsWith(".ipynb")?Pe.path:`${Pe.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const t=o===Pe.path?Ce(o):void 0;if(void 0!==t&&void 0!==Pe.mtimeMs&&t!==Pe.mtimeMs&&"save"!==He)return He="save",console.log(chalk.yellow(` ${g(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"));He=null;try{r(o,X(Pe.cells)),Pe.path=o,De=!0,Pe.dirty=!1,Pe.mtimeMs=Ce(o),Pe.diskSig=Ee(Pe.cells),We=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Pe.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),void Ze();if(""===t)return void Ze()}if(Fe.length>0&&ue.has(t.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(t.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ze();if(Fe.push(o),!G(Fe))return 1!==Fe.length||Je||(Je=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ze();const l=Fe.join("\n").replace(/\s+$/,"");if(Fe.length=0,""!==l.trim()){Ve=!0;try{const e=await Ae.execute(l);Pe.cells.push({kind:"code",source:l,result:e}),Pe.dirty=!0,xe(e,T);const o=wo(Pe.cells[Pe.cells.length-1],Pe.cells.length);e.ok||o||pe()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),pe()}Ve=!1,Ze()}else Ze()};Re.on("line",e=>{bo(e)}),Le||Re.on("close",async()=>{await Ae.shutdown().catch(()=>{}),process.exit(0)}),Ze(),await oo}
1
+ import{existsSync as e,mkdirSync as o,readdirSync as t,readFileSync as n,statSync as l,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{createHash as s}from"node:crypto";import{Interface as i,createInterface as c}from"node:readline";import{basename as g,dirname as y,isAbsolute as d,join as u,resolve as h}from"node:path";import chalk from"chalk";import{aienvPaths as p}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as f,askIoaiOneShot as m}from"./ai4ioai.js";import{getConfig as w,saveConfig as b}from"../lib/config.js";import{editTextInEditor as k,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as E,parseLeaseResponse as S,queueLine as C,windowLine as j}from"../lib/gpu.js";import{shouldExecuteCell as G}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{isPng as I,mdImages as N,mdWithoutImages as O,thumbForTerminal as T}from"../lib/term-image.js";import{NotebookKernel as M,buildRemoteBridgeCommand as D}from"../lib/kernel.js";import{getMainRl as q,setMainRl as L}from"../lib/main-rl.js";import{logCommand as z}from"../lib/logger.js";import{startLogSync as R,stopLogSync as K}from"../lib/log-sync.js";import{cellPreview as B,fromWholeEditText as F,mergeReloadedCells as W,normalizePathArg as J,parseIpynb as V,parsePercentPy as Y,parseRunRange as H,serializeIpynb as X,statusChar as Z,toWholeEditText as Q}from"../lib/notebook-doc.js";import{committeeLease as ee,readCommitteeSession as oe,TIER_LABEL as te}from"../lib/gputask-session.js";import{enterPanel as ne,leavePanel as le,printHelp as re}from"../lib/guide-panel.js";import{lazyFile as ae}from"../lib/lazy-assets.js";import{openFile as se}from"../lib/open-file.js";import{serviceBase as ie,siteBase as ce}from"../lib/site.js";const ge=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function ye(){return(w().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 de(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const ue=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),he=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function pe(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const fe=ce();function me(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):fe}function we(){return u(a(),".icoa","gpu-key")}function be(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(we(),"utf-8").trim()||null}catch{return null}}async function ke(e,o,t){try{const n=await fetch(`${me()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{key:o,task:t}:{key:o}),signal:AbortSignal.timeout(2e4)});return S(await n.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function ve(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let $e=0,_e=null;function xe(e,o){for(const t of e.outputs)if("stream"===t.kind){const e=t.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===t.name?chalk.yellow(e):chalk.white(e))}else if("result"===t.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(t.text));else if("error"===t.kind){console.log(chalk.bold.red(` ${t.ename}: ${t.evalue}`));for(const e of t.traceback)console.log(chalk.gray(` ${e.replace(ge,"")}`))}else"display"===t.kind&&Pe(t.data,o)}function Pe(e,t){if(e["image/png"])try{o(t,{recursive:!0}),$e+=1;const n=u(t,`figure-${$e}.png`),l=Buffer.from(e["image/png"],"base64");r(n,l),_e=n;for(const e of T(l))console.log(e);return console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(n)),void(process.env.ICOA_NO_OPEN||console.log(chalk.gray(" type ")+chalk.cyan("open")+chalk.gray(" for the full-size picture")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}function Ee(t,a,s){for(const i of N(t.source)){const c=i.alt||g(i.target.split("?")[0])||"image";let y=null,p="png";try{if(i.target.startsWith("attachment:")){const e=t.attachments?.[decodeURIComponent(i.target.slice(11))],o=e?Object.keys(e).find(e=>e.startsWith("image/")):void 0;e&&o&&(y=Buffer.from(e[o],"base64"),p="image/jpeg"===o?"jpg":o.slice(6).replace("svg+xml","svg"))}else if(i.target.startsWith("data:image/")){const e=/^data:image\/([a-z0-9+.-]+);base64,(.+)$/i.exec(i.target);e&&(y=Buffer.from(e[2],"base64"),p="jpeg"===e[1]?"jpg":e[1].replace("svg+xml","svg"))}else{if(/^https?:/i.test(i.target)){console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+chalk.gray(` — web image, not fetched: ${i.target}`));continue}{const o=d(i.target)?i.target:h(a,decodeURIComponent(i.target));e(o)&&l(o).size<=31457280&&(y=n(o),p=(o.split(".").pop()||"png").toLowerCase())}}}catch{y=null}if(!y){console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+chalk.gray(` — image not found: ${i.target.slice(0,60)}`));continue}let f="";try{o(s,{recursive:!0}),$e+=1,f=u(s,`figure-${$e}.${p.replace(/[^a-z0-9]/g,"")||"png"}`),r(f,y),_e=f}catch{f=""}const m=I(y)?T(y):[];for(const e of m)console.log(e);console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+(f?chalk.gray(" → ")+chalk.cyan(f):"")+chalk.gray(m.length?" (type ":" (no in-terminal preview for this format — type ")+chalk.cyan("open")+chalk.gray(" for full size)"))}}function Se(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function Ce(e){if(e)try{return l(e).mtimeMs}catch{return}}function je(o){const t=J(o,a()),l=d(t)?t:h(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")?V(e):Y(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:Ce(l),diskSig:Se(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.")}}}const Ge={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(S){const I=S?.trim().toLowerCase().replace(/-demo$/,"");if(I&&Ge[I]){const t=await async function(t){const l=Ge[t],a=u(process.cwd(),"icoa-lab"),s=u(a,g(l));if(e(s))return console.log(chalk.gray(" Using your copy ")+chalk.cyan(s)+chalk.gray(" (edits kept — delete the file to start from the original).")),s;process.stdout.write(chalk.gray(" Fetching the demo notebook…"));const i=await ae(l);if(!i)return console.log(chalk.yellow(" not available right now.")),console.log(chalk.gray(" It needs one online moment — try ")+chalk.cyan(`ipynb ${t}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,n(i))}catch(e){return console.log(chalk.yellow(` could not write ${s}: ${e instanceof Error?e.message:String(e)}`)),null}return console.log(chalk.green(" saved ")+chalk.cyan(s)),s}(I);if(!t)return;S=t}const N=p(a()),T=u(a(),".icoa","ipynb-out");de();const ce=e(N.python),fe=oe();if(!ce&&!fe)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).")),console.log(chalk.gray(" (Committee seat holders: open the seat with ")+chalk.cyan("gpufortask")+chalk.gray(" and the notebook runs there instead.)")),void console.log();const $e=S?je(S):null,Pe=$e?$e.doc:{cells:[],path:null,dirty:!1},Ue=()=>Pe.path?y(Pe.path):void 0;let Ae=new M({venvPython:N.python,venvRoot:N.root,cwd:Ue()}),Ie=null,Ne=null,Oe=null,Te=ve(Pe.path);if(ce){process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Ae.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."))}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — cells run on your committee seat: type ")+chalk.bold.green("gpu on")+chalk.gray("."));$e&&console.log($e.note);let Me=!1,De=!1;ne({id:"ipynb",title:{en:"Notebook",zh:"Notebook 笔记本"},what:{en:"A Jupyter notebook inside the terminal: cells run one by one in a live Python kernel. You are already inside it — never type python file.ipynb here.",zh:"终端里的 Jupyter notebook:cell 在常驻 Python 内核里逐格运行。你已经在 notebook 里面了 —— 不要再敲 python file.ipynb。"},steps:[{verb:"cells",what:{en:"list the cells (md = explanation, ○ = not run yet)",zh:"列出所有 cell(md = 讲解,○ = 还没跑)"},done:()=>Me},{verb:"run all",what:{en:"run every cell top to bottom; stops at the first error",zh:"从头到尾跑每一格;遇到第一个报错就停"},done:()=>Pe.cells.some(e=>null!==e.result)},{verb:"edit",what:{en:"open the WHOLE notebook in your editor (edit 3 = one cell)",zh:"整本在编辑器里打开(edit 3 = 只开第 3 格)"},done:()=>Pe.dirty},{verb:"save",what:{en:"write it back to disk as a real .ipynb",zh:"存回磁盘,标准 .ipynb"},done:()=>De},{verb:"gpu on",what:{en:"run the cells on a GPU box (a T4 starts for you, ~1–2 min); gpu off hands it back",zh:"把 cell 搬到 GPU 上跑(T4 按需开机约 1–2 分钟);gpu off 归还"},done:()=>null!==Ie,optional:!0},{verb:"ai 4",what:{en:"ask the tutor why cell 4 did that (ai = the last error)",zh:"问导师第 4 格为什么这样(裸 ai = 最后一个报错)"},optional:!0}],notes:[{en:"Plain Python typed at the prompt runs as a new cell (a blank line ends a block). help all = every command.",zh:"直接敲 Python 就是新的一格(空行结束多行块)。help all = 全部命令。"}],leave:{verb:"quit",what:{en:"leave the notebook",zh:"离开 notebook"}},guide:()=>Qe()});const qe=q(),Le=null!==qe,ze=Le?qe.listeners("line").slice():[];Le&&qe.removeAllListeners("line");const Re=Le?qe:c({input:process.stdin,output:process.stdout,terminal:!0});Le||L(Re);const Ke=Le?Re.prompt:null,Be=Le?Re.getPrompt():"";Le&&(Re.prompt=i.prototype.prompt),Le||R();const Fe=[];let We,Je=!1,Ve=!1,Ye=!1,He=null,Xe=null;const Ze=()=>{if(Xe)return Re.setPrompt(chalk.bold.cyan(` editor 1-${Xe.options.length} > `)),void Re.prompt();const e=Ie?"icoa ipynb ⚡gpu":"icoa ipynb";Re.setPrompt(chalk.bold.cyan(Fe.length?`${e} ...> `:`${e}> `)),Re.prompt()},Qe=()=>{const o=Pe.path?y(Pe.path):process.cwd(),t=ve(Pe.path);let l="",r=!1;try{const e=JSON.parse(n(u(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Pe.cells.filter(e=>null!==e.result).length,s=e(u(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Pe.path?g(Pe.path):"new empty notebook")+chalk.gray(` · ${Pe.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Ie?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(t?" — trains the baseline, writes submission.csv":" — runs every cell top to bottom")),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()};let eo=()=>{};const oo=new Promise(e=>{eo=e}),to=async()=>{if(Ae=new M({venvPython:N.python,venvRoot:N.root,cwd:Ue()}),e(N.python)){process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Ae.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"))}}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — ")+chalk.cyan("gpu on")+chalk.gray(" reconnects to your seat."))},no=async(e,t=!1)=>{const n=ee(e),l=E(n);if(l.length>0)return console.log(chalk.red(" committee seat file rejected: ")+chalk.gray(l.join(", "))),!1;const s=u(a(),".icoa","gputask","key");try{o(u(a(),".icoa","gputask"),{recursive:!0}),r(s,e.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),!1}const i=Pe.path?g(y(Pe.path)):"work",c=`${n.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=D(n.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new M({spawnSpec:{command:"ssh",args:P(n,s,d)},readyTimeoutMs:9e4});t||process.stdout.write(chalk.gray(` Connecting to your seat (${e.host})…`));try{await h.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" The box may be rebuilding (Spot reclaim) — ")+chalk.cyan("gpufortask")+chalk.gray(" shows the seat state; ")+chalk.cyan("gpu on")+chalk.gray(" again once it is ready.")),!1}await Ae.shutdown().catch(()=>{}),Ae=h,Ie={...n,outDir:c},Oe=e,Ne=Date.now(),h.onUnexpectedExit=()=>{Ae===h&&(console.log(),console.log(chalk.bold.yellow(" ⚠ The GPU box went away (Spot reclaim or seat ended).")),console.log(chalk.gray(" Files are kept on the seat; variables are gone. ")+chalk.cyan("gpu on")+chalk.gray(" in 1–2 min reconnects (the seat is rebuilt automatically).")),Ie=null,Oe=null,Ne=null,to().then(()=>Ze()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${te[e.tier]} · cells run in ${c}`));const p=await lo();return p>0&&console.log(chalk.gray(` ${p} small file${1===p?"":"s"} from this notebook's folder sent to the box.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to rerun there · ")+chalk.cyan("upload <file>")+chalk.gray(" sends more · ")+chalk.cyan("download <file>")+chalk.gray(" brings results back · ")+chalk.cyan("gpu off")+chalk.gray(" returns to the local kernel (seat stays).")),!0},lo=async()=>{if(!Pe.path||!Ie?.outDir)return 0;const e=y(Pe.path);let o=[];try{o=t(e)}catch{return 0}let r=0;for(const t of o){if(t.startsWith("."))continue;const o=u(e,t);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await Ae.putFile(`${Ie.outDir}/${t}`,n(o)),r++}catch{}}return r},ro=async(e,t=!1)=>{if(!Ie)return t||console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed).")),!1;const n=e.trim()||"submission.csv",l=n.startsWith("/")?n:`${Ie.outDir}/${n}`;let a;try{a=await Ae.fetchFile(l)}catch(e){return console.log(chalk.yellow(` could not fetch ${l}: `)+chalk.gray(e instanceof Error?e.message:String(e))),console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)")),!1}const s=Te?u(process.cwd(),"icoa-kaggle",Te):process.cwd(),i=u(s,g(n));try{o(s,{recursive:!0}),r(i,a)}catch{return console.log(chalk.yellow(" could not write the file here — check directory permissions.")),!1}return console.log(chalk.green(" ✓ downloaded ")+chalk.white(i)+chalk.gray(` (${a.length} bytes)`)),!t&&Te&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Te}`)+chalk.gray(" · score it: ")+chalk.cyan("submit")),!0},ao=async e=>{const[t,...n]=e.trim().split(/\s+/),l=(t??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ie)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=oe();if(e)return void await(async e=>{await no(e)})(e);const t=be();if(!t)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)."));Te||(Te=ve(Pe.path));const n=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await ke("lease",t,Te??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-n)/1e3)} s`;for(;"queued"===l.state&&s<(l.bootStage||i?60:24);)l.bootStage&&(i=!0),0===s&&console.log(),process.stdout.write(`\r ${chalk.yellow(C(l))} `),await new Promise(e=>setTimeout(e,5e3)),l=await ke("status",t),s++;if("queued"===l.state)return console.log(),void(i?(console.log(chalk.yellow(` The GPU box is still starting (${c()} so far) — your place is held.`)),console.log(chalk.gray(" Keep editing; ")+chalk.cyan("gpu on")+chalk.gray(" again in a minute picks it up."))):(console.log(chalk.yellow(" Still queued — your place is held server-side.")),console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."))));if(i&&"ready"===l.state&&(console.log(),console.log(chalk.green(` ✓ GPU box ready in ${c()}`)+chalk.gray(` · ${l.gpuName??"GPU"}${l.zone?` · ${l.zone}`:""} · built just for this session`))),"ready"!==l.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${l.message??"no lease granted"}`));const g=E(l);if("local"!==l.transport||process.env.ICOA_GPU_SERVER||g.push("local transport from a non-dev broker"),g.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(g.join(", "))),void await ke("release",t);const y=Te?`${l.dataRoot}/${Te}`:l.dataRoot,d=D(l.python,{ICOA_KAGGLE_DATA:y,ICOA_KAGGLE_OUT:l.outDir},l.outDir);let h;if("local"===l.transport)h={command:"/bin/sh",args:["-c",d]};else{const e=u(a(),".icoa","gpu","lease-key");try{o(u(a(),".icoa","gpu"),{recursive:!0}),r(e,l.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await ke("release",t)}h={command:"ssh",args:P(l,e,d)}}const p=new M({spawnSpec:h,readyTimeoutMs:9e4}),f=Date.now();process.stdout.write(chalk.gray(" connecting…"));try{await p.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),void await ke("release",t)}await Ae.shutdown().catch(()=>{}),Ae=p,Ie=l,Ne=Date.now();const m=Math.round((l.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected")+chalk.gray(` (${Math.round((Date.now()-f)/1e3)} s).`)),console.log(chalk.gray(` Cells now run on the ${l.gpuName?`${l.gpuName} `:""}GPU box · ${m}m left on this lease.`));const w=j(l.windowCloseEpoch);w&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${w}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),Te&&console.log(chalk.gray(` Dataset is already on the box (${Te}) — 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"===l||"disconnect"===l?await(async()=>{if(Ie&&Oe){const e=Ne?Math.round((Date.now()-Ne)/1e3):0;return await Ae.shutdown().catch(()=>{}),Ie=null,Oe=null,Ne=null,console.log(chalk.green(` ⚡ Back to the local kernel after ${Math.floor(e/60)} m ${e%60} s`)+chalk.gray(" — the seat stays open (files kept); ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now.")),void await to()}if(!Ie)return void console.log(chalk.gray(" not on a GPU kernel."));const e=be(),o=void 0!==Ie.gpuName,t=Ne?Math.round((Date.now()-Ne)/1e3):0;await Ae.shutdown().catch(()=>{}),e&&await ke("release",e),Ie=null,Ne=null;const n=Math.floor(t/60),l=n>0?`${n} m ${t%60} s`:`${t} s`;console.log(chalk.green(` ⚡ GPU lease released after ${l}`)+chalk.gray(" — billing for you stopped.")),o&&console.log(chalk.gray(" The box recycles itself now that nobody holds it (")+chalk.cyan("gpu queue")+chalk.gray(" shows 0 boxes once it is gone); the next ")+chalk.cyan("gpu on")+chalk.gray(" builds a fresh one.")),await to()})():"status"===l||""===l?await(async()=>{const e=oe();if(e)return console.log(chalk.green(` ⚡ committee seat · ${te[e.tier]} · ${e.host}`)+chalk.gray(Oe?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=be();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const t=await ke("status",o);if("ready"===t.state){const e=Math.round((t.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Ie?" (this notebook is connected)":" (not connected here — gpu on)"));const o=j(t.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===t.state?console.log(chalk.yellow(` ${C(t)}`)):"none"===t.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${t.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=be();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const t=await fetch(`${me()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),n=await t.json();o=n.data??n}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 t="number"==typeof o.boxes?o.boxes:0,n="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(` · ${t} box${1===t?"":"es"} · ${n} free`));const a=j("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(0===t?" (no box up — gpu on starts a T4 for you, ~1–2 min)":" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",t="number"==typeof e.time_left_sec?e.time_left_sec:0,n=Math.floor(t/60),l=String(t%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${n}:${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:"?",t="number"==typeof e.position?e.position:"?",n=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${t} `)+chalk.white(o.padEnd(8))+n)}console.log()})():"key"===l?(e=>{const t=e.trim();if(t)try{o(u(a(),".icoa"),{recursive:!0}),r(we(),`${t}\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(` (${we()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(n.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>"))},so=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Pe.cells.length?(console.log(0===Pe.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Pe.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Pe.cells[o-1],idx:o}},io=(e,o)=>{if(e.length<=o)return e;const t=Math.floor(.6*o);return`${e.slice(0,t)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-t))}`};let co=!1;const go=()=>{const e=w().notebookEditor;return e?_(e):null},yo=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),uo=()=>go()??x(),ho={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"},po=(e,o)=>{if(e){const t=_(e);return t?v(t.cmd)?(o(t),!0):(console.log(chalk.yellow(` ${$(t)} 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(go()||yo())return o(uo()),!0;const t=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return t.length<2||!process.stdin.isTTY?(o(x()),!0):((e=>{console.log(),console.log(chalk.bold.white(" Which editor should edit / add open?")+chalk.gray(" (asked once)")),e.forEach((e,o)=>{const t=$(e);console.log(chalk.cyan(` ${o+1} ${t.padEnd(5)}`)+chalk.gray(` ${ho[t]??""}`)+("nano"===t?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(t),Xe={resume:o,tries:0,options:t},!1)},fo=e=>{if(!Pe.path)return!1;let o;try{const e=n(Pe.path,"utf8");o=Pe.path.endsWith(".ipynb")?V(e):Y(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=W(Pe.cells,o);return Pe.cells=t.cells,Pe.dirty=!1,Pe.mtimeMs=Ce(Pe.path),Pe.diskSig=Se(o),We=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Pe.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},mo=()=>void 0!==Pe.diskSig?Se(Pe.cells)!==Pe.diskSig:Pe.dirty,wo=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!U(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)),bo=async o=>{if(o.trim()&&z(`ipynb: ${o.trim()}`),Ve)return void(o.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Xe){const e=Xe,t=o.trim().toLowerCase(),n=_(t),l=/^\d+$/.test(t)?e.options[Number(t)-1]:n?e.options.find(e=>$(e)===$(n)):void 0;return l?(Xe=null,b({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===t||["q","quit","back","cancel","exit"].includes(t)?(Xe=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Xe=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=>$(e)).join(" / "))),void Ze()}let t=o.trim();if(0===Fe.length&&/^icoa\s+[a-z/]/i.test(t)&&(t=t.replace(/^icoa\s+/i,"")),0===Fe.length){const o=t.split(/\s+/),l=(o[0]??"").toLowerCase(),i=t.slice(o[0]?.length??0).trim();if("quit"!==l&&"exit"!==l&&"q"!==l&&(Ye=!1),He&&l!==He&&(He=null),he.has(l)&&(()=>{if(!Pe.path||void 0===Pe.mtimeMs)return;const e=Ce(Pe.path);if(void 0!==e&&e!==Pe.mtimeMs){if(mo()){if(We===e)return;return We=e,console.log(chalk.yellow(` ⚠ ${g(Pe.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"))}fo(!0)}})(),"quit"===l||"exit"===l||"back"===l||"q"===l||"menu"===l)return Pe.dirty&&!Ye?(Ye=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ze()):void await(async()=>{if(le("ipynb"),Re.removeAllListeners("line"),Le||K(),console.log(),Ie&&Oe)Ie=null,console.log(chalk.gray(" ⚡ Committee seat stays open (files kept) — ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now, or it closes after 40 min idle."));else if(Ie){const e=be();e&&await ke("release",e),Ie=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Ae.shutdown().catch(()=>{}),Le){Ke&&(Re.prompt=Ke),Re.setPrompt(Be);for(const e of ze)Re.on("line",e);Re.prompt(),eo()}else L(null),eo(),Re.close()})();if("clear"===l||"cls"===l)return console.clear(),de(),void Ze();if("restart"===l)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Ae.shutdown().catch(()=>{});try{await Ae.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 Ze();if("help"===l||"?"===l)return/^(all|commands|full)$/i.test(i.trim())?(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(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),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(ye()?" 问 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 GPU box — a GCP T4 starts for you on demand (~1–2 min), ")+chalk.cyan("gpu off")+chalk.gray(" hands it back")),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(" selfcheck")+chalk.gray(" committee seat: rerun the whole notebook fresh, measure peak GPU memory → capsule size, file the report")),console.log(chalk.cyan(" upload <f>")+chalk.gray(" send a file to the box (committee seat: files next to the notebook go up on gpu on)")),console.log(chalk.gray(" try it: ")+chalk.cyan("icoa> ipynb mnist")+chalk.gray(" — the MNIST demo notebook (edit → run → train on the T4 → gpu off)")),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(" the last figure, full size, 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()):re(),void Ze();if("guide"===l||"/guide"===l)return Qe(),void Ze();if("python"===l||"python3"===l)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 Ze();if("open"===l&&""===i)return _e&&process.env.ICOA_NO_OPEN?console.log(chalk.gray(" open is switched off here — the picture above is the view; the file is ")+chalk.cyan(_e)):_e&&se(_e)?console.log(chalk.gray(" opening ")+chalk.cyan(_e)):_e?console.log(chalk.gray(" no image viewer here — the file is ")+chalk.cyan(_e)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ze();if("cells"===l||"ls"===l)return(()=>{if(Me=!0,0===Pe.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);Pe.cells.forEach((o,t)=>{const n=Z(o),l="✓"===n?chalk.green(n.padEnd(2)):"✗"===n?chalk.red(n.padEnd(2)):"md"===n?chalk.magenta(n.padEnd(2)):chalk.gray(n.padEnd(2));console.log(`${chalk.cyan(String(t+1).padStart(4))} ${l} ${chalk.white(B(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 Ze();if("show"===l)return(e=>{const o=so(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 A(O(o.cell.source)))console.log(e);Ee(o.cell,Pe.path?y(Pe.path):process.cwd(),T),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 ──")),xe(o.cell.result,T)),console.log()}})(i),void Ze();if("edit"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ").toLowerCase();return""===t||"all"===t?po(o,e=>(e=>{Re.pause();const o=k(Q(Pe.cells),".py",e,"notebook");if(Re.resume(),null===o)return void console.log(chalk.yellow(" editor cancelled or failed — notebook unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const t=F(o,Pe.cells);if(t.same)return void console.log(chalk.gray(" no changes."));if(0===t.cells.length&&Pe.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${Pe.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));Pe.cells=t.cells,Pe.dirty=!0;const n=[];t.changed.length&&n.push(`${t.changed.length} changed (${t.changed.join(", ")})`),t.added.length&&n.push(`${t.added.length} added (${t.added.join(", ")})`),t.deleted&&n.push(`${t.deleted} deleted`),t.reordered&&n.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${Pe.cells.length} cells`)+chalk.gray(` · ${n.join(" · ")}`));const l=[...t.changed,...t.added].filter(e=>"code"===Pe.cells[e-1].kind).sort((e,o)=>e-o);if(l.length){const e=l[0],o=l[l.length-1];console.log(chalk.gray(" unchanged cells kept their output · run what changed: ")+chalk.cyan(e===o?`run ${e}`:`run ${e}-${o}`)+chalk.gray(" · or ")+chalk.cyan("run all"))}})(e)):so(t)&&po(o,e=>((e,o)=>{const t=so(e);if(!t)return;Re.pause();const n=k(t.cell.source,"markdown"===t.cell.kind?".md":".py",o);if(Re.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=n.replace(/\s+$/,"");l!==t.cell.source?(t.cell.source=l,t.cell.result=null,t.cell.rawOutputs=void 0,t.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${t.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${t.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(t,e)),void Ze()}if("add"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ");return po(o,e=>((e,o)=>{const t=e.trim().toLowerCase(),n="md"===t||"markdown"===t||"text"===t||"txt"===t;if(t&&!n&&"py"!==t&&"code"!==t&&"python"!==t)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Re.pause();const l=k(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py",o);Re.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Pe.cells.push({kind:n?"markdown":"code",source:r,result:null}),Pe.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Pe.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Pe.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(t,e)),void Ze()}if("editor"===l&&/^[\w-]*$/.test(i))return(e=>{const o=e.trim().toLowerCase(),t=$(uo());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(t)+chalk.gray(` (${go()?"saved":yo()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),n=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(n?` ${ho[e]}`:" not installed here")+(e===t?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 b({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const n=_(o);if(!n)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=$(n);go()&&$(go())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(n.cmd)?(b({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${t===l?"default":t}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(i),void Ze();if("reload"===l&&""===i)return Pe.path&&e(Pe.path)?mo()&&"reload"!==He?(He="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."))):(He=null,fo(!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 Ze();if("load"===l&&!/^[=(.[]/.test(i)||"open"===l&&""!==i){if(!i)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ze();const o=J(i,a()),t=d(o)?o:h(process.cwd(),o);if(e(t))if(Pe.dirty&&"load"!==He)He="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(l)+chalk.yellow(" again to discard them."));else{He=null;const e=je(t);Pe.cells=e.doc.cells,Pe.path=e.doc.path,Pe.dirty=!1,Pe.mtimeMs=e.doc.mtimeMs,Pe.diskSig=e.doc.diskSig,We=void 0,Te=ve(Pe.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(t)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ze()}if("del"===l||"delete"===l)return(e=>{const o=so(e);o&&(Pe.cells.splice(o.idx-1,1),Pe.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Pe.cells.length} left.`)+(o.idx<=Pe.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(i),void Ze();if(("md"===l||"py"===l)&&/^\d+$/.test(i))return((e,o)=>{const t=so(e);if(!t)return;const n="markdown"===o?"markdown":"Python";t.cell.kind!==o?(t.cell.kind=o,t.cell.result=null,t.cell.rawOutputs=void 0,t.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${t.idx} → ${n}`)+chalk.gray(" — ")+chalk.cyan(`run ${t.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${t.idx} is already ${n}.`))})(i,"md"===l?"markdown":"code"),void Ze();if("gpu"===l)return Ve=!0,await ao(i),Ve=!1,void Ze();if("download"===l||"dl"===l)return Ve=!0,await ro(i),Ve=!1,void Ze();if("selfcheck"===l||"self-check"===l)return Ve=!0,await(async()=>{const e=Oe;if(!e||!Ie)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===Pe.cells.filter(e=>"code"===e.kind).length)return void console.log(chalk.yellow(" nothing to check — the notebook has no code cells."));console.log(chalk.bold.cyan(" 🔬 selfcheck")+chalk.gray(` · fresh kernel · ${te[e.tier]} · every code cell from the top`));const o=Ae;if(await no(e,!0),Ae===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const t=Date.now(),n=[];let l=!1;for(let e=0;e<Pe.cells.length;e++){const o=Pe.cells[e];if("code"!==o.kind)continue;const t=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${t} … `));try{o.result=await Ae.execute(o.source)}catch(e){n.push({n:t,ok:!1,ms:Date.now()-r,error:e instanceof Error?e.message:String(e)}),console.log(chalk.red("kernel error")),l=!0;break}Pe.dirty=!0;const a=Date.now()-r,s=o.result.outputs.find(e=>"error"===e.kind);if(n.push({n:t,ok:o.result.ok,ms:a,error:s&&"error"===s.kind?`${s.ename}: ${s.evalue}`:void 0}),console.log(o.result.ok?chalk.green(`ok ${(a/1e3).toFixed(1)} s`):chalk.red(`raised ${(a/1e3).toFixed(1)} s`)),!o.result.ok){xe(o.result,T),l=!0;break}}const r=Date.now()-t,a=["import json as _j, os as _o, sys as _s, hashlib as _h, platform as _p",'_r = {"python": _s.version.split()[0], "platform": _p.platform()}',"try:"," import torch as _t",' _r["torch"] = _t.__version__'," if _t.cuda.is_available():",' _r["gpu"] = _t.cuda.get_device_name(0)',' _r["peak_gib"] = round(_t.cuda.max_memory_allocated() / 2**30, 3)',' _r["reserved_gib"] = round(_t.cuda.max_memory_reserved() / 2**30, 3)',"except Exception as _e:",' _r["torch"] = "n/a: %s" % _e','for _m in ("sklearn", "numpy", "pandas", "transformers"):'," try:"," _r[_m] = __import__(_m).__version__"," except Exception:"," pass",'_r["fence"] = _o.environ.get("CUDA_MPS_PINNED_DEVICE_MEM_LIMIT")','_r["units"] = _o.environ.get("ICOA_GPU_UNITS")','_r["files"] = {}','for _f in sorted(_o.listdir(".")):',' if _o.path.isfile(_f) and not _f.startswith("."):'," _sz = _o.path.getsize(_f)"," _d = _h.sha256()",' with open(_f, "rb") as _fh:',' for _c in iter(lambda: _fh.read(1 << 20), b""):'," _d.update(_c)",' _r["files"][_f] = {"bytes": _sz, "sha256": _d.hexdigest()[:16]}','print("ICOA_SELFCHECK " + _j.dumps(_r))'].join("\n");let s={};try{const e=(await Ae.execute(a)).outputs.filter(e=>"stream"===e.kind).map(e=>"stream"===e.kind?e.text:"").join("").split("\n").find(e=>e.startsWith("ICOA_SELFCHECK "));e&&(s=JSON.parse(e.slice(15)))}catch{}const i="number"==typeof s.peak_gib?s.peak_gib:null,c=null===i?null:i<3?1:i<6.5?2:i<10?3:0,y={sid:e.sid,tier:e.tier,notebook:Pe.path?g(Pe.path):null,cells:n,ok:!l,wall_ms:r,env:s,peak_gib:i,units:c,ts:Math.floor(Date.now()/1e3)};console.log(),console.log((l?chalk.bold.red(" ✗ selfcheck: a cell raised"):chalk.bold.green(" ✓ selfcheck: every cell ran"))+chalk.gray(` · ${(r/1e3).toFixed(0)} s wall on a shared box (not a time limit)`)),null!==i?console.log(chalk.white(` peak GPU memory ${i.toFixed(2)} GiB`)+(c?chalk.green(` → ${c} capsule unit${c>1?"s":""}`)+chalk.gray(` (fence ${3.5*c} GiB, allocator cap ${(3.5*c-.5).toFixed(1)})`):chalk.red(" → exceeds 3 units (10 GiB cap) — the task must shrink"))):console.log(chalk.gray(" no GPU memory figure (torch not imported or no CUDA) — CPU task, or add a torch import.")),(s.gpu||s.torch)&&console.log(chalk.gray(` ${s.gpu??"no GPU"} · torch ${s.torch??"?"} · sklearn ${s.sklearn??"?"} · numpy ${s.numpy??"?"}`));const d=s.files??{},u=Object.keys(d);u.length>0&&console.log(chalk.gray(` ${u.length} data file${1===u.length?"":"s"} fingerprinted: ${u.slice(0,6).join(", ")}${u.length>6?", …":""}`));try{const o=await fetch(`${ie("ICOA_GPUTASK_SERVER").replace(/\/$/,"")}/api/icoa/gputask/selfcheck`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,report:y}),signal:AbortSignal.timeout(2e4)});console.log(o.ok?chalk.gray(" report filed with the committee ✓"):chalk.yellow(` report not filed (http ${o.status}) — keep the numbers above.`))}catch{console.log(chalk.yellow(" report not filed (offline) — keep the numbers above."))}})(),Ve=!1,void Ze();if("upload"===l||"up"===l||"put"===l)return Ve=!0,await(async e=>{if(!Ie)return void console.log(chalk.gray(" local kernel — files are already here. ")+chalk.cyan("gpu on")+chalk.gray(" first."));const o=e.trim();if(!o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("upload <file>")+chalk.gray(" (≤ 20 MB; lands in the box work dir)"));const t=J(o,a()),l=d(t)?t:h(Pe.path?y(Pe.path):process.cwd(),t);let r;try{r=n(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${Ie.outDir}/${g(l)}`;try{const e=await Ae.putFile(s,r);console.log(chalk.green(" ✓ uploaded ")+chalk.white(s)+chalk.gray(` (${e} bytes)`))}catch(e){console.log(chalk.yellow(" upload failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),Ve=!1,void Ze();if("check"===l||"submit"===l||"kaggle"===l){const e=await import("./kaggle.js"),o=i.split(/\s+/).filter(Boolean),t="kaggle"===l?(o[0]||"").toLowerCase():l,n=("kaggle"===l?o[1]:o[0])||ve(Pe.path)||void 0;Ve=!0;try{if(("submit"===t||"check"===t)&&Ie&&!await ro("submission.csv",!0))return Ve=!1,void Ze();if("submit"===t){const o=s("sha256").update(Pe.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(n,{code_sha:o,...Oe?{sid:Oe.sid}:{},...Pe.path?{notebook:g(Pe.path)}:{}})}else"check"===t?await e.runKaggleCheck(n):"final"===t?await e.runKaggleFinal(n,o.slice(2)):"board"===t?await e.runKaggleBoard(n):"guide"===t?await e.runKaggleGuide(n):await e.runKaggle("kaggle"===l?o[0]:n)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ve=!1,void Ze()}if("board"===l){const{runBoard:e}=await import("./board.js"),o=i.split(/\s+/).filter(Boolean);Ve=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ve=!1,void Ze()}if("ai"===l||"/ai"===l)return Ve=!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=Pe.cells.length-1;e>=0;e--)if((Pe.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Pe.cells.length;if(0===Pe.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=so(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 t of e.result?.outputs??[])"stream"===t.kind||"result"===t.kind?o.push(t.text):"error"===t.kind&&(o.push(`${t.ename}: ${t.evalue}`),o.push(t.traceback.map(e=>e.replace(ge,"")).join("\n")));return o.join("\n").replace(ge,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Pe.path||!ve(Pe.path))return"";try{const e=JSON.parse(n(u(y(Pe.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return io(o,350)}catch{return""}})(),c=ye(),g=c?"你在帮一个 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.",d=g.length+l.length+120,h=Math.max(400,f-d-i.length),p=io(a.cell.source,Math.floor(.6*h)),w=s?(b=s,k=h-p.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[g,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${p}`,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"),_=c;console.log(),co||(co=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(ye()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${ye()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(ye()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(ye()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${f} chars`)+chalk.gray(_?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(_?" · 含输出":" · output included"):"")+($?chalk.yellow(_?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),z(`ipynb: ai ${a.idx}${l?` — ${l}`:""}`);const x=await m(v);if(console.log(),!x.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(x.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of A(x.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${_?"<你的问题>":"<your question>"}`)+chalk.gray(_?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(_?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(_?" 再跑一次":" run it again")),console.log(chalk.gray(_?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(i),Ve=!1,void Ze();if("run"===l)return Ve=!0,await(async e=>{if(!ce&&!Oe&&!Ie)return void console.log(chalk.yellow(" No kernel here yet — ")+chalk.cyan("gpu on")+chalk.yellow(" connects your committee seat (or ")+chalk.cyan("aienv setup")+chalk.yellow(" for a local one)."));const o=H(e,Pe.cells.length);if(o)for(const e of o){const t=Pe.cells[e-1];if("markdown"!==t.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(B(t,50))+chalk.gray(" ──"));try{t.result=await Ae.execute(t.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void pe()}if(Pe.dirty=!0,xe(t.result,T),wo(t,e),!t.result.ok){const t=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${t?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(ye()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(ye()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void pe()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(O(t.source)))console.log(e);Ee(t,Pe.path?y(Pe.path):process.cwd(),T),console.log()}}else console.log(0===Pe.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"))})(i),Ve=!1,void Ze();if("save"===l)return(e=>{if(0===Pe.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?d(e.trim())?e.trim():h(process.cwd(),e.trim()):Pe.path?Pe.path.endsWith(".ipynb")?Pe.path:`${Pe.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const t=o===Pe.path?Ce(o):void 0;if(void 0!==t&&void 0!==Pe.mtimeMs&&t!==Pe.mtimeMs&&"save"!==He)return He="save",console.log(chalk.yellow(` ${g(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"));He=null;try{r(o,X(Pe.cells)),Pe.path=o,De=!0,Pe.dirty=!1,Pe.mtimeMs=Ce(o),Pe.diskSig=Se(Pe.cells),We=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Pe.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),void Ze();if(""===t)return void Ze()}if(Fe.length>0&&ue.has(t.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(t.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ze();if(Fe.push(o),!G(Fe))return 1!==Fe.length||Je||(Je=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ze();const l=Fe.join("\n").replace(/\s+$/,"");if(Fe.length=0,""!==l.trim()){Ve=!0;try{const e=await Ae.execute(l);Pe.cells.push({kind:"code",source:l,result:e}),Pe.dirty=!0,xe(e,T);const o=wo(Pe.cells[Pe.cells.length-1],Pe.cells.length);e.ok||o||pe()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),pe()}Ve=!1,Ze()}else Ze()};Re.on("line",e=>{bo(e)}),Le||Re.on("close",async()=>{await Ae.shutdown().catch(()=>{}),process.exit(0)}),Ze(),await oo}
@@ -1 +1 @@
1
- import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as p}from"../lib/kaggle.js";import{mediaHelpLines as m,sprintTaskForComp as f}from"../lib/sprint-meta.js";import{siteBase as k}from"../lib/site.js";const w=k();function $(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):w}async function v(o){try{const e=await fetch($()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function _(o,e){try{const n=await fetch($()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}async function S(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function j(){return(a().language||"en").toLowerCase().startsWith("zh")}function A(o,e){return j()?o:e}function x(){console.log(),console.log(chalk.yellow(A(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(A(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function E(o){return s(process.cwd(),"icoa-kaggle",o)}function G(o,e){const n=[];let t="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const r of o){const o=s(r)?2:1;if(l+o>e){const o=t.lastIndexOf(" ");if(!s(r)&&" "!==r&&o>e/3){const e=t.slice(o+1);n.push(t.slice(0,o)),t=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else n.push(t),t="",l=0;if(" "===r&&""===t)continue}t+=r,l+=o}return""!==t.trim()&&n.push(t),n}function P(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(A(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(A(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(A(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(A(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),console.log(chalk.gray(A(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board")),void console.log(chalk.gray(A(" 在 notebook 里可直接敲 "," inside the notebook just type "))+chalk.cyan("submit")+chalk.gray(A(" —— 不用退出来"," — no need to leave")))):"nitro"===o?.judge?(console.log(chalk.bold.white(A(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(A(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(A(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(A(" 注册后提交"," and submit there"))),void console.log(chalk.gray(A(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(A(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(A(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(A(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(A(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(A(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(A(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(A(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(A(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(n){const t=r(),a=async o=>await t.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(A(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(A(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(A("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(A("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await v("/api/icoa/kaggle/tasks");if(!t)return x();const r=h(t);if(0===r.length)return console.log(chalk.yellow(A(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=n?r.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(A(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(A(" 正在开放的练习赛:"," Live practice competitions:"))),r.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!c;o++){const o=(await a(chalk.cyan(A(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&r[e-1]||r.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(A(` 输 1-${r.length} 之间的序号,或者一个 id,比如 "${r[0].comp_id}"。`,` Try a number 1-${r.length} or an id like "${r[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(i(`kaggle: download ${u}`),c.needs_gpu)return void await async function(n,t){const r=E(n);if(console.log(),console.log(chalk.white(` ${t.title}`)+chalk.gray(` · ${t.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),t.description){console.log();for(const o of G(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(A(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(A(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const a=await v(`/api/icoa/kaggle/${n}/starter`),i=a?.data?.starter??a?.starter;if("string"!=typeof i||0===i.length)return x();const c=s(r,"starter.ipynb");let g=!1;try{e(r,{recursive:!0}),o(c)?g=!0:l(c,i),l(s(r,"meta.json"),`${JSON.stringify(t,null,2)}\n`)}catch{return void console.log(chalk.yellow(A(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?A(" (保留了你原来那本)"," (kept your existing one)"):A(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(A("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(A(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(A(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(A(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(A(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(A(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(A(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(A(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(A(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(A(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(t.kaggle_url)),console.log())}(u,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of G(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(A(" 正在下载数据…"," Downloading data…")));let b=null;const p=y(c);if(p){const[o,e,n]=await Promise.all([S(p.train),S(p.test),S(p.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await v(`/api/icoa/kaggle/${u}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return x();const m=E(u),k={...c,...b.meta??{}};try{e(m,{recursive:!0}),l(s(m,"train.csv"),b.train),l(s(m,"test.csv"),b.test),l(s(m,"sample_submission.csv"),b.sample_submission),l(s(m,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const w=s(m,"starter.ipynb");let $=!1;if(o(w))$=!0;else{const o=await v(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l(w,e):l(w,g(d(m,k)))}const _="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",j="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(m,"train.csv"))+chalk.gray(` (${_})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(m,"test.csv"))+chalk.gray(` (${j})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(m,"sample_submission.csv")));const P=f(u),I="none"===(P?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white(w)+chalk.gray($?" (kept your existing one)":I?A(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),N(u,k,w),console.log()}finally{t.close()}}function I(o){const e=j();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function N(o,e,n){const t=f(o),l=t?m(t,j()):[];if(l.length>0){for(const o of l)for(const e of G(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(e?.needs_gpu)console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"));else{const l=t?.media?.pack,s="none"===(t?.baseline||"").trim();console.log(chalk.bold.white(l?A(" 接下来 4 步:"," Your move — 4 steps:"):A(" 接下来 3 步:"," Your move — 3 steps:")));let r=1;l&&console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(A(` → 把${I(t?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${I(t?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(s?A(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${r++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${r}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${r}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${r}. upload it on Kaggle yourself — then beat the baseline.`))}console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick ")+chalk.bold.white("🧠 Learn")+chalk.gray(" → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),P(e)}export async function runKaggleGuide(e){console.log();const t=C(e,"guide");if(!t)return;const l=E(t);let r=null;try{r=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{r=null}i(`kaggle: guide ${t}`);const a=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${r?.title??t} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),N(t,r,a),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function C(e,n){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),r=o(l)?t(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===r.length)return r[0];if(0===r.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of r)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const t=C(e,"check");if(!t)return;const l=E(t),r=s(l,"submission.csv"),a=s(l,"sample_submission.csv");try{if(JSON.parse(n(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(a))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(a))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=p(n(r,"utf-8"),n(a,"utf-8"));i(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(r)),console.log(),P(u),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e,t){console.log();const l=C(e,"submit");if(!l)return;const a=E(l),c=s(a,"submission.csv"),g=s(a,"sample_submission.csv");let d=null;try{d=JSON.parse(n(s(a,"meta.json"),"utf-8"))}catch{d=null}if("local-eval"===d?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),P(d),void console.log();if(!d||!o(g))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==d.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),P(d),void console.log();if(!o(c))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(a,"starter.ipynb")}`)),void console.log();const y=n(c,"utf-8"),h=p(y,n(g,"utf-8"));if(!h.ok){i(`kaggle: submit ${l} → local-reject: ${h.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of h.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let m=u()?.token??"";if(!m){const o=r();try{m=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!m)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}const f=Date.now();let k,w=null;process.stdout.isTTY?(process.stdout.write(chalk.gray(" ⚖ scoring on the server… 0.0s")),w=setInterval(()=>{process.stdout.write(chalk.gray(`\r ⚖ scoring on the server… ${((Date.now()-f)/1e3).toFixed(1)}s `))},200)):console.log(chalk.gray(" Scoring on the server…"));try{k=await _(`/api/icoa/kaggle/${l}/submit`,{token:m,submission_csv:y,...t?{job:t}:{}})}finally{w&&(clearInterval(w),process.stdout.write(`\r ${chalk.gray(`⚖ scored in ${((Date.now()-f)/1e3).toFixed(1)}s`)}${" ".repeat(12)}\n`))}const $=b(k);if(i(`kaggle: submit ${l} → ${$.ok?`${$.metric}=${$.score}${$.deduped?" (deduped)":""} rank=${$.rank??"-"}`:$.reason??"error"}`),console.log(),$.ok){const o=`${$.metric}: ${Number($.score).toFixed(4).replace(/\.?0+$/,"")}`,e="public"===$.leaderboard?chalk.gray(" (public leaderboard — the private split is revealed after the event)"):"";$.deduped&&$.sameCode?(console.log(chalk.bold.white(` ✓ same code as before — ${o}`)+e),console.log(chalk.gray(" The notebook code is unchanged, so this is the earlier result; it does not count as a submission."))):$.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)+e),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)+e),"number"==typeof $.rank&&"number"==typeof $.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${$.rank}`)+chalk.gray(` of ${$.fieldSize}`))),"number"==typeof $.used&&"number"==typeof $.cap&&console.log(chalk.gray(` ⚖ submissions used ${$.used}/${$.cap}`)),$.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`kaggle board ${l}`)+chalk.gray(" (or ")+chalk.cyan(`board ${$.boardEvent} ${l}`)+chalk.gray(")")),$.submissionId&&"public"===$.leaderboard&&console.log(chalk.gray(` id ${$.submissionId} · pick the two that count on the private board: `)+chalk.cyan(`kaggle final ${l} ${$.submissionId}`)+chalk.gray(" [<id2>] (unpicked = public best + last)"))}else switch($.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of $.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export async function runKaggleFinal(o,e=[]){console.log();const n=C(o,"final");if(!n)return;const t=u()?.token??"";if(!t)return console.log(chalk.gray(" A learn token identifies you on the board — open Learn once with your token first.")),void console.log();const l=await _(`/api/icoa/kaggle/${n}/final`,{token:t,ids:e.slice(0,2)})??{},s=l.data??l??{};if("string"==typeof s.reason){if("bad_id"===s.reason){console.log(chalk.bold.red(` ✗ ${String(s.error)}`));const o=Array.isArray(s.yours)?s.yours:[];o.length>0&&console.log(chalk.gray(` your scored ids: ${o.join(", ")}`))}else"bad_token"===s.reason?console.log(chalk.bold.red(" ✗ that learn token was not accepted")):console.log(chalk.yellow(` ${String(s.error??s.reason)}`));return void console.log()}if(!Array.isArray(s.final))return console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const r=s.final;if(s.chosen&&r.length>0){console.log(chalk.bold.green(" ✓ your final picks for the private board:"));for(const o of r)console.log(chalk.white(` ${o.id}`)+chalk.gray(` public ${Number(o.score).toFixed(4)}`))}else console.log(chalk.white(" No picks yet — the auto rule applies: ")+chalk.gray(String(s.rule_if_unchosen??"public best + last")));const a=Array.isArray(s.yours)?s.yours:[];a.length>0&&(console.log(chalk.gray(` your last ${a.length} scored: `)+a.map(o=>`${o.id} ${Number(o.score).toFixed(4)}`).join(chalk.gray(" · "))),console.log(chalk.gray(" change: ")+chalk.cyan(`kaggle final ${n} <id> [<id>]`))),i(`kaggle: final ${n} → ${r.map(o=>o.id).join(",")||"auto"}`),console.log()}const K=o=>"number"==typeof o?o.toFixed(4):" – ";export async function runKaggleBoard(o){console.log();const e=o?.trim()||C(void 0,"board");if(!e)return;const n=u()?.token??"",t=await _(`/api/icoa/kaggle/${e}/board`,n?{token:n}:{})??{},l=t.data??t??{};if(!Array.isArray(l.public))return"unknown_comp"===l.reason?console.log(chalk.bold.red(` ✗ no competition called ${e}`)):console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const s=l.public,r="public"===l.leaderboard,a="number"==typeof l.public_fraction?Math.round(100*l.public_fraction):null;if(console.log(chalk.bold.white(` 🏆 ${String(l.title??e)}`)+chalk.gray(` · ${r?`public leaderboard (${a??"?"}% of the test set)`:"leaderboard (whole test set)"} · ${String(l.metric??"")}`)),l.closed&&console.log(chalk.yellow(" ⏹ closed — no more submissions are accepted")),0===s.length)console.log(chalk.gray(" nobody has scored yet — be the first: ")+chalk.cyan(`kaggle submit ${e}`));else{console.log(chalk.gray(" # who score subs"));for(const o of s){const e=` ${String(o.rank).padStart(3)} ${o.who.padEnd(9)} ${K(o.score)} ${String(o.n).padStart(3)}`;console.log(o.you?chalk.bold.green(`${e} ◀ you`):chalk.white(e))}}if(Array.isArray(l.private)){const o=l.private;console.log(),console.log(chalk.bold.white(" 🔒 private leaderboard — FINAL")+chalk.gray(r?` (the other ${100-(a??0)}% of the test set)`:"")),console.log(chalk.gray(" # who private public sub id code seat picked"));for(const e of o){const o=` ${String(e.rank).padStart(3)} ${e.who.padEnd(9)} ${K(e.score)} ${K(e.public_score)} ${(e.sub_id??"-").padEnd(12)} ${(e.code_sha??"-").padEnd(12)} ${(e.job_sid??"-").padEnd(20)} ${e.how??""}`;console.log(e.you?chalk.bold.green(`${o} ◀ you`):chalk.white(o))}console.log(chalk.gray(" picked = chosen (kaggle final) or auto (public best + last) · code = sha of the notebook cells that made it"))}else r&&(console.log(chalk.gray(" (private split is revealed by the organiser after the event — then it shows here)")),n&&console.log(chalk.gray(" pick the two that count: ")+chalk.cyan(`kaggle final ${e} <id> [<id>]`)));i(`kaggle: board ${e} → ${s.length} rows${Array.isArray(l.private)?" + private":""}`),console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit" / "board" / "final"').argument("[comp]",'competition id (with "check" / "submit" / "board" / "final")').argument("[ids...]",'submission ids (with "final")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit & board & final").action(async(o,e,n=[])=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"board"===o?await runKaggleBoard(e):"final"===o?await runKaggleFinal(e,n):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as d}from"../lib/learn-state.js";import{buildStarterCells as u,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as p}from"../lib/kaggle.js";import{mediaHelpLines as m,sprintTaskForComp as f}from"../lib/sprint-meta.js";import{siteBase as k}from"../lib/site.js";const w=k();function $(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):w}async function v(o){try{const e=await fetch($()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function _(o,e){try{const n=await fetch($()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}async function S(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function j(){return(a().language||"en").toLowerCase().startsWith("zh")}function A(o,e){return j()?o:e}function x(){console.log(),console.log(chalk.yellow(A(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(A(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function E(o){return s(process.cwd(),"icoa-kaggle",o)}function G(o,e){const n=[];let t="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const r of o){const o=s(r)?2:1;if(l+o>e){const o=t.lastIndexOf(" ");if(!s(r)&&" "!==r&&o>e/3){const e=t.slice(o+1);n.push(t.slice(0,o)),t=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else n.push(t),t="",l=0;if(" "===r&&""===t)continue}t+=r,l+=o}return""!==t.trim()&&n.push(t),n}function P(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(A(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(A(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(A(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(A(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),console.log(chalk.gray(A(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board")),void console.log(chalk.gray(A(" 在 notebook 里可直接敲 "," inside the notebook just type "))+chalk.cyan("submit")+chalk.gray(A(" —— 不用退出来"," — no need to leave")))):"nitro"===o?.judge?(console.log(chalk.bold.white(A(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(A(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(A(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(A(" 注册后提交"," and submit there"))),void console.log(chalk.gray(A(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(A(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(A(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(A(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(A(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(A(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(A(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(A(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(A(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(n){const t=r(),a=async o=>await t.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(A(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(A(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(A("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(A("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await v("/api/icoa/kaggle/tasks");if(!t)return x();const r=h(t);if(0===r.length)return console.log(chalk.yellow(A(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=n?r.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(A(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(A(" 正在开放的练习赛:"," Live practice competitions:"))),r.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!c;o++){const o=(await a(chalk.cyan(A(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&r[e-1]||r.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(A(` 输 1-${r.length} 之间的序号,或者一个 id,比如 "${r[0].comp_id}"。`,` Try a number 1-${r.length} or an id like "${r[0].comp_id}".`)))}if(!c)return}const d=c.comp_id;if(i(`kaggle: download ${d}`),c.needs_gpu)return void await async function(n,t){const r=E(n);if(console.log(),console.log(chalk.white(` ${t.title}`)+chalk.gray(` · ${t.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),t.description){console.log();for(const o of G(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(A(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(A(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const a=await v(`/api/icoa/kaggle/${n}/starter`),i=a?.data?.starter??a?.starter;if("string"!=typeof i||0===i.length)return x();const c=s(r,"starter.ipynb");let g=!1;try{e(r,{recursive:!0}),o(c)?g=!0:l(c,i),l(s(r,"meta.json"),`${JSON.stringify(t,null,2)}\n`)}catch{return void console.log(chalk.yellow(A(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?A(" (保留了你原来那本)"," (kept your existing one)"):A(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(A("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(A(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(A(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(A(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(A(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(A(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(A(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(A(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(A(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(A(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(t.kaggle_url)),console.log())}(d,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of G(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(A(" 正在下载数据…"," Downloading data…")));let b=null;const p=y(c);if(p){const[o,e,n]=await Promise.all([S(p.train),S(p.test),S(p.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await v(`/api/icoa/kaggle/${d}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return x();const m=E(d),k={...c,...b.meta??{}};try{e(m,{recursive:!0}),l(s(m,"train.csv"),b.train),l(s(m,"test.csv"),b.test),l(s(m,"sample_submission.csv"),b.sample_submission),l(s(m,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const w=s(m,"starter.ipynb");let $=!1;if(o(w))$=!0;else{const o=await v(`/api/icoa/kaggle/${d}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l(w,e):l(w,g(u(m,k)))}const _="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",j="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(m,"train.csv"))+chalk.gray(` (${_})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(m,"test.csv"))+chalk.gray(` (${j})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(m,"sample_submission.csv")));const P=f(d),I="none"===(P?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white(w)+chalk.gray($?" (kept your existing one)":I?A(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),N(d,k,w),console.log()}finally{t.close()}}function I(o){const e=j();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function N(o,e,n){const t=f(o),l=t?m(t,j()):[];if(l.length>0){for(const o of l)for(const e of G(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(e?.needs_gpu)console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"));else{const l=t?.media?.pack,s="none"===(t?.baseline||"").trim();console.log(chalk.bold.white(l?A(" 接下来 4 步:"," Your move — 4 steps:"):A(" 接下来 3 步:"," Your move — 3 steps:")));let r=1;l&&console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(A(` → 把${I(t?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${I(t?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(s?A(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${r++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${r}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${r}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${r}. upload it on Kaggle yourself — then beat the baseline.`))}console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick ")+chalk.bold.white("🧠 Learn")+chalk.gray(" → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),P(e)}export async function runKaggleGuide(e){console.log();const t=C(e,"guide");if(!t)return;const l=E(t);let r=null;try{r=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{r=null}i(`kaggle: guide ${t}`);const a=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${r?.title??t} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),N(t,r,a),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function C(e,n){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),r=o(l)?t(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===r.length)return r[0];if(0===r.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of r)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const t=C(e,"check");if(!t)return;const l=E(t),r=s(l,"submission.csv"),a=s(l,"sample_submission.csv");try{if(JSON.parse(n(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(a))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(a))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=p(n(r,"utf-8"),n(a,"utf-8"));i(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let d=null;try{d=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{d=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(r)),console.log(),P(d),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e,t){console.log();const l=C(e,"submit");if(!l)return;const a=E(l),c=s(a,"submission.csv"),g=s(a,"sample_submission.csv");let u=null;try{u=JSON.parse(n(s(a,"meta.json"),"utf-8"))}catch{u=null}if("local-eval"===u?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),P(u),void console.log();if(!u||!o(g))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==u.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),P(u),void console.log();if(!o(c))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(a,"starter.ipynb")}`)),void console.log();const y=n(c,"utf-8"),h=p(y,n(g,"utf-8"));if(!h.ok){i(`kaggle: submit ${l} → local-reject: ${h.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of h.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let m=d()?.token??"";if(!m){const o=r();try{m=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!m)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}const f=Date.now();let k,w=null;process.stdout.isTTY?(process.stdout.write(chalk.gray(" ⚖ scoring on the server… 0.0s")),w=setInterval(()=>{process.stdout.write(chalk.gray(`\r ⚖ scoring on the server… ${((Date.now()-f)/1e3).toFixed(1)}s `))},200)):console.log(chalk.gray(" Scoring on the server…"));try{k=await _(`/api/icoa/kaggle/${l}/submit`,{token:m,submission_csv:y,...t?{job:t}:{}})}finally{w&&(clearInterval(w),process.stdout.write(`\r ${chalk.gray(`⚖ scored in ${((Date.now()-f)/1e3).toFixed(1)}s`)}${" ".repeat(12)}\n`))}const $=b(k);if(i(`kaggle: submit ${l} → ${$.ok?`${$.metric}=${$.score}${$.deduped?" (deduped)":""} rank=${$.rank??"-"}`:$.reason??"error"}`),console.log(),$.ok){const o=`${$.metric}: ${Number($.score).toFixed(4).replace(/\.?0+$/,"")}`,e="public"===$.leaderboard?chalk.gray(" (public leaderboard — the private split is revealed after the event)"):"";if($.deduped&&$.sameCode?(console.log(chalk.bold.white(` ✓ same code as before — ${o}`)+e),console.log(chalk.gray(" The notebook code is unchanged, so this is the earlier result; it does not count as a submission."))):$.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)+e),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)+e),"number"==typeof $.rank&&"number"==typeof $.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${$.rank}`)+chalk.gray(` of ${$.fieldSize}`))),$.parts&&$.parts.length>0){const o=Math.max(...$.parts.map(([o])=>o.length));for(const[e,n]of $.parts)console.log(chalk.gray(` ${e.padEnd(o)} `)+chalk.white(n.toFixed(4)))}"number"==typeof $.used&&"number"==typeof $.cap&&console.log(chalk.gray(` ⚖ submissions used ${$.used}/${$.cap}`)),$.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`kaggle board ${l}`)+chalk.gray(" (or ")+chalk.cyan(`board ${$.boardEvent} ${l}`)+chalk.gray(")")),$.submissionId&&"public"===$.leaderboard&&console.log(chalk.gray(` id ${$.submissionId} · pick the two that count on the private board: `)+chalk.cyan(`kaggle final ${l} ${$.submissionId}`)+chalk.gray(" [<id2>] (unpicked = public best + last)"))}else switch($.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of $.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export async function runKaggleFinal(o,e=[]){console.log();const n=C(o,"final");if(!n)return;const t=d()?.token??"";if(!t)return console.log(chalk.gray(" A learn token identifies you on the board — open Learn once with your token first.")),void console.log();const l=await _(`/api/icoa/kaggle/${n}/final`,{token:t,ids:e.slice(0,2)})??{},s=l.data??l??{};if("string"==typeof s.reason){if("bad_id"===s.reason){console.log(chalk.bold.red(` ✗ ${String(s.error)}`));const o=Array.isArray(s.yours)?s.yours:[];o.length>0&&console.log(chalk.gray(` your scored ids: ${o.join(", ")}`))}else"bad_token"===s.reason?console.log(chalk.bold.red(" ✗ that learn token was not accepted")):console.log(chalk.yellow(` ${String(s.error??s.reason)}`));return void console.log()}if(!Array.isArray(s.final))return console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const r=s.final;if(s.chosen&&r.length>0){console.log(chalk.bold.green(" ✓ your final picks for the private board:"));for(const o of r)console.log(chalk.white(` ${o.id}`)+chalk.gray(` public ${Number(o.score).toFixed(4)}`))}else console.log(chalk.white(" No picks yet — the auto rule applies: ")+chalk.gray(String(s.rule_if_unchosen??"public best + last")));const a=Array.isArray(s.yours)?s.yours:[];a.length>0&&(console.log(chalk.gray(` your last ${a.length} scored: `)+a.map(o=>`${o.id} ${Number(o.score).toFixed(4)}`).join(chalk.gray(" · "))),console.log(chalk.gray(" change: ")+chalk.cyan(`kaggle final ${n} <id> [<id>]`))),i(`kaggle: final ${n} → ${r.map(o=>o.id).join(",")||"auto"}`),console.log()}const K=o=>"number"==typeof o?o.toFixed(4):" – ";export async function runKaggleBoard(o){console.log();const e=o?.trim()||C(void 0,"board");if(!e)return;const n=d()?.token??"",t=await _(`/api/icoa/kaggle/${e}/board`,n?{token:n}:{})??{},l=t.data??t??{};if(!Array.isArray(l.public))return"unknown_comp"===l.reason?console.log(chalk.bold.red(` ✗ no competition called ${e}`)):console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const s=l.public,r="public"===l.leaderboard,a="number"==typeof l.public_fraction?Math.round(100*l.public_fraction):null;if(console.log(chalk.bold.white(` 🏆 ${String(l.title??e)}`)+chalk.gray(` · ${r?`public leaderboard (${a??"?"}% of the test set)`:"leaderboard (whole test set)"} · ${String(l.metric??"")}`)),l.closed&&console.log(chalk.yellow(" ⏹ closed — no more submissions are accepted")),0===s.length)console.log(chalk.gray(" nobody has scored yet — be the first: ")+chalk.cyan(`kaggle submit ${e}`));else{console.log(chalk.gray(" # who score subs"));for(const o of s){const e=` ${String(o.rank).padStart(3)} ${o.who.padEnd(9)} ${K(o.score)} ${String(o.n).padStart(3)}`;console.log(o.you?chalk.bold.green(`${e} ◀ you`):chalk.white(e))}}if(Array.isArray(l.private)){const o=l.private;console.log(),console.log(chalk.bold.white(" 🔒 private leaderboard — FINAL")+chalk.gray(r?` (the other ${100-(a??0)}% of the test set)`:"")),console.log(chalk.gray(" # who private public sub id code seat picked"));for(const e of o){const o=` ${String(e.rank).padStart(3)} ${e.who.padEnd(9)} ${K(e.score)} ${K(e.public_score)} ${(e.sub_id??"-").padEnd(12)} ${(e.code_sha??"-").padEnd(12)} ${(e.job_sid??"-").padEnd(20)} ${e.how??""}`;console.log(e.you?chalk.bold.green(`${o} ◀ you`):chalk.white(o))}console.log(chalk.gray(" picked = chosen (kaggle final) or auto (public best + last) · code = sha of the notebook cells that made it"))}else r&&(console.log(chalk.gray(" (private split is revealed by the organiser after the event — then it shows here)")),n&&console.log(chalk.gray(" pick the two that count: ")+chalk.cyan(`kaggle final ${e} <id> [<id>]`)));i(`kaggle: board ${e} → ${s.length} rows${Array.isArray(l.private)?" + private":""}`),console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit" / "board" / "final"').argument("[comp]",'competition id (with "check" / "submit" / "board" / "final")').argument("[ids...]",'submission ids (with "final")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit & board & final").action(async(o,e,n=[])=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"board"===o?await runKaggleBoard(e):"final"===o?await runKaggleFinal(e,n):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
@@ -1 +1 @@
1
- import{createHash as e}from"node:crypto";import{appendFileSync as t,existsSync as s,mkdirSync as n,readdirSync as r,readFileSync as a,statSync as o,writeFileSync as i}from"node:fs";import{basename as c,join as l,resolve as u}from"node:path";import{gzipSync as d}from"node:zlib";import chalk from"chalk";import{renderPanel as h}from"../lib/guide-panel.js";import{logCommand as f}from"../lib/logger.js";import{parseIpynb as m,serializeIpynb as b}from"../lib/notebook-doc.js";import{BASELINE_FILE as p,INLINE_LIMIT_BYTES as g,LOWER_IS_BETTER as w,METRICS as v,metricGroups as y,TASK_FILES as k,baselineCells as $,capsulePlan as S,checkTask as _,parseTaskMeta as B,scoreSubmission as j,studentBundle as z,tarArchive as A,validName as x,verdictLines as G}from"../lib/setter.js";import{getCliVersion as N}from"../lib/version.js";const O=(e="")=>console.log(e),C=e=>console.log(chalk.red(` ✗ ${e}`)),F=e=>console.log(chalk.green(` ✓ ${e}`)),J=e=>console.log(chalk.gray(` ${e}`)),q=(e,t)=>console.log(chalk.gray(" ▸ next, type: ")+chalk.bold.green(e)+chalk.gray(` ${t}`));function P(e){if(e){const t=u(e);return s(l(t,"task.json"))?t:null}const t=process.cwd();if(s(l(t,"task.json")))return t;try{const e=r(t).filter(e=>!e.startsWith(".")&&s(l(t,e,"task.json")));if(1===e.length)return l(t,e[0])}catch{}return null}function M(e,t){const n=l(e,t);if(s(n)){if(o(n).size>419430400)throw new Error(`${t} is over 400 MB — too large to check here; tell the organiser, this one goes through the dataset bucket`);return a(n,"utf-8")}}function L(e){const{meta:t,problems:s}=B(M(e,"task.json")??"");for(const e of s)C(e);return t}function T(e,t){return _(t,{train:M(e,"train.csv"),testA:M(e,"test_a.csv"),labelsA:M(e,"labels_a.csv"),testB:M(e,"test_b.csv"),labelsB:M(e,"labels_b.csv")})}function U(e,s,r){try{n(l(e,".setter"),{recursive:!0}),t(l(e,".setter","ledger.jsonl"),`${JSON.stringify({at:(new Date).toISOString(),cli:N(),action:s,...r})}\n`)}catch{}}function D(e){try{return a(l(e,".setter","ledger.jsonl"),"utf-8").split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{return[]}}const I=e=>Number.isFinite(e)?e.toFixed(4):String(e),E=e=>e>=1048576?`${(e/1024/1024).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`;function V(){const e={classes:"label = a class · submit the predicted class","probability of 1":"label = 0 or 1 · submit the probability of 1",numbers:"label = a number · submit a number"};O();for(const t of y()){O(chalk.bold.white(` ${t.kind}`)+chalk.gray(` · ${e[t.kind]}`));for(const e of t.names){const t=w.has(e)?"lower is better ":"higher is better";O(chalk.cyan(` ${e.padEnd(18)}`)+chalk.gray(`${t} ${W[e]??""}`))}}O(),J('use one: setter new <name> <metric> · or edit "metric" in task.json'),J("a metric that is not here (several values per row, images, text): tell the organiser"),O()}const W={balanced_accuracy:"mean recall per class",macro_f1:"F1 per class, plain mean",weighted_f1:"F1 per class, weighted by class size",mcc:"Matthews correlation",f1:"labels 0 / 1, F1 of class 1",qwk:"whole-number grades, quadratic weighted kappa",auc:"area under the ROC curve",ap:"average precision (area under precision–recall)",logloss:"binary cross-entropy",brier:"mean squared error of the probability",rmsle:"labels 0 or more",mape:"avoid when labels can be 0",smape:"symmetric percentage error, 0 to 2",r2:"coefficient of determination",pearson:"linear correlation",spearman:"rank correlation"};function H(e){try{return JSON.parse(a(e,"utf-8"))}catch{return null}}export async function runSetter(t=[]){const[y,..._]=t,B=(y||"").toLowerCase();f(`setter ${B}`.trim());try{""===B||"help"===B||"?"===B||"guide"===B||"status"===B?function(e){O();for(const t of h(function(e){const t=t=>!!e&&s(l(e,t));return{id:"setter",title:{en:"Problem setter",zh:"命题工具"},what:{en:"Build one task folder and test it yourself, start to finish, on this machine: the data checks, the files a contestant gets, the A and B scores of your own solutions. Nothing leaves your computer until you hand the archive over.",zh:"在这台机器上把一道题从头到尾自己测完:数据检查、学生拿到的文件、你自己的解在 A 榜和 B 榜上的分数。在你亲手把压缩包交出去之前,没有任何东西离开你的电脑。"},steps:[{verb:"setter new my-task",what:{en:"make the folder: task.json and a baseline notebook that already runs",zh:"建文件夹:task.json 和一份能直接跑的 baseline notebook"},done:()=>t("task.json")},{verb:"setter check",what:{en:"after you put train.csv, test_a.csv + labels_a.csv, test_b.csv + labels_b.csv in it: the builder's checks",zh:"把 train.csv、test_a.csv + labels_a.csv、test_b.csv + labels_b.csv 放进去之后:跑建赛脚本的那套检查"},done:()=>t(".setter/check.json")},{verb:"setter student",what:{en:"write student/ — exactly what a contestant downloads",zh:"生成 student/ —— 学生下载到的就是这些"},done:()=>t("student/test.csv")},{verb:"ipynb",what:{en:"open student/baseline.ipynb and run all, as a contestant would — it writes submission.csv",zh:"打开 student/baseline.ipynb 敲 run all,像学生一样跑 —— 它会写出 submission.csv"},done:()=>t("student/submission.csv")},{verb:"setter score",what:{en:"A score, B score and the difference (setter score ref.csv for another solution)",zh:"A 榜分、B 榜分和差值(setter score ref.csv 给另一份解算分)"},done:()=>t(".setter/scores.json")},{verb:"setter plan 3 1.8",what:{en:"GPU tasks: minutes and peak GiB of your reference run → capsule size, seats per card",zh:"GPU 题:参考解的分钟数和峰值显存 → 胶囊档位、每张卡坐几人"},optional:!0,done:()=>t(".setter/plan.json")},{verb:"setter pack",what:{en:"one archive + report to send to the organiser",zh:"打成一个压缩包 + 报告,发给组织者"},done:()=>!!e&&r(e).some(e=>e.endsWith("-handin.tar.gz"))}],notes:[{en:`${v.length} metrics — setter metrics lists them. Files are plain CSV: commas, no quotes. Publishing stays with the organiser.`,zh:`${v.length} 个指标,敲 setter metrics 看全表。文件是普通 CSV:逗号分隔,不带引号。发布由组织者来做。`}],leave:{verb:"menu",what:{en:"main menu",zh:"主菜单"}}}}(e),"full"))O(t);J(e?`task folder: ${e}`:"no task folder here yet — setter new <name> makes one in the current directory"),O()}(P(_[0])):"new"===B||"init"===B||"create"===B?function(e,t){if(!e||!x(e))return C("give the task a short name: 3–40 characters of a–z, 0–9 and -"),void J("example: setter new sydney-rain (add a metric: setter new sydney-rain rmse)");const r=(t||"accuracy").toLowerCase();if(!v.includes(r))return C(`metric "${t}" is not one the judge has`),void V();const a=u(e);if(s(a))return C(`${e}/ already exists — nothing was changed`),void q("setter check",`(inside ${e}/, or: setter check ${e})`);n(a,{recursive:!0});const o={name:e,title:e,metric:r,label:"label",id:"id",per_day:5};i(l(a,"task.json"),`${JSON.stringify({...o,description:""},null,2)}\n`),i(l(a,p),b($(o).map(e=>({...e,result:null})))),F(`made ${e}/ with task.json and ${p}`),J('now put your data in it (plain CSV, an "id" column in every file):'),J(" train.csv id + features + label"),J(" test_a.csv labels_a.csv the public-board rows, and id,label for them"),J(" test_b.csv labels_b.csv the private-board rows, and id,label for them"),J('edit task.json if your label column is not called "label" or the title should read better.'),q("setter check",`(inside ${e}/, or: setter check ${e})`)}(_[0],_[1]):"metrics"===B||"metric"===B?V():"check"===B||"verify"===B||"validate"===B?function(e){const t=P(e);if(!t)return C("no task folder found (a folder with task.json)"),q("setter new my-task","makes one here"),null;const r=L(t);if(!r)return null;let a;try{a=T(t,r)}catch(e){return C(e.message),null}if(O(),O(chalk.bold.white(` ${r.title}`)+chalk.gray(` · ${r.name} · metric ${r.metric} · predict "${r.label}"`)),!a.ok){for(const e of a.problems)C(e);return J("fix the first line above and run setter check again — nothing was written."),null}if(F(`train ${a.nTrain} rows · A ${a.nA} rows · B ${a.nB} rows · ${a.features.length} feature columns`),a.classes.length){const e=a.classes.reduce((e,[,t])=>e+t,0);J(`classes in train: ${a.classes.map(([t,s])=>`${t} ${(100*s/e).toFixed(1)}%`).join(" · ")}`)}for(const e of a.warnings)O(chalk.yellow(` ⚠ ${e}`));const c=["train.csv","test_a.csv","test_b.csv"].reduce((e,s)=>e+o(l(t,s)).size,0);c>g?O(chalk.yellow(` ⚠ data is ${E(c)} — over the ${E(g)} a competition carries inline; the organiser will host it in the dataset bucket`)):J(`data size ${E(c)} — fits the inline bundle`),s(l(t,p))||O(chalk.yellow(` ⚠ no ${p} yet — every task ships a baseline the contestants start from`)),n(l(t,".setter"),{recursive:!0}),i(l(t,".setter","check.json"),`${JSON.stringify({at:(new Date).toISOString(),cli:N(),n_train:a.nTrain,n_a:a.nA,n_b:a.nB,features:a.features.length,warnings:a.warnings,data_bytes:c},null,2)}\n`),U(t,"check",{n_train:a.nTrain,n_a:a.nA,n_b:a.nB,features:a.features.length,data_bytes:c,warnings:a.warnings.length}),q("setter student","writes student/ — what a contestant downloads")}(_[0]):"student"===B||"bundle"===B||"build"===B?function(e){const t=P(e);if(!t)return void C("no task folder found — setter new my-task makes one");const r=L(t);if(!r)return;let o;try{o=T(t,r)}catch(e){return void C(e.message)}if(!o.ok){for(const e of o.problems)C(e);return void q("setter check","shows the same problems with the fix")}const u=l(t,"student");n(u,{recursive:!0});const d=z(r,o);i(l(u,"train.csv"),d.train),i(l(u,"test.csv"),d.test),i(l(u,"sample_submission.csv"),d.sample);const h=l(t,p);s(h)&&i(l(u,p),a(h)),U(t,"student",{rows:o.nA+o.nB,baseline:s(h)}),F(`student/ written: train.csv · test.csv (${o.nA+o.nB} rows, A and B mixed) · sample_submission.csv${s(h)?` · ${p}`:""}`),J("no labels and no A/B list are in student/ — it is safe to show to a tester."),s(h)?q(`ipynb ${l(c(t),"student",p)}`,"then run all — it writes student/submission.csv"):O(chalk.yellow(` ⚠ put your ${p} in the task folder and run setter student again`))}(_[0]):"score"===B||"grade"===B?function(t){let r,o;for(const e of t)s(l(u(e),"task.json"))?r=e:o=e;const d=P(r);if(!d)return void C("no task folder found — setter new my-task makes one");const h=L(d);if(!h)return;const f=o?s(u(o))?u(o):l(d,o):l(d,"student","submission.csv");if(!s(f))return C(`no submission at ${f}`),void q(`ipynb ${l(c(d),"student",p)}`,"run all writes student/submission.csv");let m;try{m=T(d,h)}catch(e){return void C(e.message)}if(!m.ok){for(const e of m.problems)C(e);return}const b=a(f,"utf-8"),g=j(h,m,b);if(!g.ok){for(const e of g.problems)C(e);return}const v=w.has(h.metric)?"lower is better":"higher is better";O(),O(chalk.bold.white(` ${c(f)}`)+chalk.gray(` · ${h.metric} (${v})`)),O(chalk.white(` A public board ${String(m.nA).padStart(7)} rows `)+chalk.bold.white(I(g.a))),O(chalk.white(` B private board ${String(m.nB).padStart(7)} rows `)+chalk.bold.white(I(g.b))),O(chalk.gray(` all ${String(m.nA+m.nB).padStart(7)} rows ${I(g.all)} A looks ${g.gap>=0?"better":"worse"} than B by ${I(Math.abs(g.gap))}`));const y=l(d,".setter","scores.json");let k=[];try{k=JSON.parse(a(y,"utf-8"))}catch{k=[]}const $=f.startsWith(d)?f.slice(d.length+1):f,S={file:$,sha:e("sha256").update(b).digest("hex").slice(0,16),a:g.a,b:g.b,all:g.all,gap:g.gap,at:(new Date).toISOString()};k=[...k.filter(e=>e.file!==$),S],U(d,"score",{file:$,sha:S.sha,metric:h.metric,a:g.a,b:g.b,all:g.all}),n(l(d,".setter"),{recursive:!0}),i(y,`${JSON.stringify(k,null,2)}\n`);const _=k.find(e=>e.file===l("student","submission.csv")),B=k.filter(e=>e!==_),z=w.has(h.metric),A=B.sort((e,t)=>z?e.b-t.b:t.b-e.b)[0];if(_){const e=e=>({ok:!0,problems:[],a:e.a,b:e.b,all:e.all,gap:e.gap,nMissing:0});O();for(const t of G(h,e(_),A?e(A):null))J(`· ${t}`);return A?void q("setter pack","one archive + report for the organiser"):void q("setter score ref.csv","score your own better solution too — that shows how much room contestants have")}J("· this is not the baseline run (student/submission.csv) — score that one too to see the room between them"),q(`ipynb ${l(c(d),"student",p)}`,"then run all, then setter score")}(_):"plan"===B||"capsule"===B||"capacity"===B?function(e){const t=P(),s="cpu"===e[0]?.toLowerCase(),r=e.filter(e=>"cpu"!==e.toLowerCase()).map(Number),a=r[0],o=s?0:r[1],c=s?r[1]:r[2];if(!Number.isFinite(a)||a<=0||!s&&(!Number.isFinite(o)||o<=0))return C("give the two numbers your reference run measured: minutes and peak GPU memory in GiB"),J("example: setter plan 3 1.8 200 (3 minutes, 1.8 GiB peak, 200 contestants at once)"),J(" setter plan cpu 2 200 (a task that needs no GPU)"),void J("where the numbers come from: run the reference on a seat (gpufortask → ipynb → gpu on) and type selfcheck.");const u=S(o,a,!s,Number.isFinite(c)?c:void 0);if(O(),"cpu"===u.tier)F(`CPU task · ${a} min per run — contestants run it on their own machine, no seat needed`);else{if(!u.fits)return void C(`peak ${o} GiB does not fit the largest capsule (cap ${u.capGib} GiB) — shrink the batch or the model; a task every card can run beats one that only fits the biggest`);F(`${u.squares}-square capsule · peak ${o} GiB under the ${u.capGib} GiB cap · ${a} min per run`),O(chalk.white(" card seats at once runs per card-hour")+(u.cards?chalk.white(` cards for ${c} at once`):""));for(const[e,t]of[["l4","L4 24 GB"],["ada","Ada 20 GB"],["t4","T4 16 GB"]])u.perCard[e]?O(chalk.white(` ${t} ${String(u.perCard[e]).padStart(6)} ${String(u.runsPerCardHour?.[e]??"-").padStart(6)}`)+(u.cards?chalk.white(` ${String(u.cards[e]).padStart(6)}`):"")):O(chalk.gray(` ${t} — (a 3-square task runs on L4 only, so every contestant gets the same card)`));J("every contestant of one task gets the same capsule size on the same card type — that is what makes the times comparable."),J("a planning estimate from fixed capsule sizes; the organiser calibrates the real number on the fleet before the event.")}t&&(n(l(t,".setter"),{recursive:!0}),i(l(t,".setter","plan.json"),`${JSON.stringify({minutes:a,peak_gib:o,contestants:c??null,...u},null,2)}\n`),U(t,"plan",{minutes:a,peak_gib:o,squares:u.squares,tier:u.tier}),J("saved with the task — setter pack carries it to the organiser."))}(_):"pack"===B||"handin"===B||"hand-in"===B||"package"===B?function(t){const n=P(t);if(!n)return void C("no task folder found — setter new my-task makes one");const r=L(n);if(!r)return;let o;try{o=T(n,r)}catch(e){return void C(e.message)}if(!o.ok){for(const e of o.problems)C(e);return void q("setter check","the archive is only made from a folder that passes")}if(!s(l(n,p)))return void C(`${p} is missing — every task ships a baseline`);try{m(a(l(n,p),"utf-8"))}catch(e){return void C(`${p} does not open as a notebook: ${e.message}`)}let u=[];try{u=JSON.parse(a(l(n,".setter","scores.json"),"utf-8"))}catch{u=[]}u.some(e=>e.file===l("student","submission.csv"))||O(chalk.yellow(" ⚠ the baseline has not been scored — the organiser will ask for it; run it and setter score first if you can"));const h=[...k];for(const e of["description.md","ref.csv","reference.ipynb"])s(l(n,e))&&h.push(e);const f=h.map(e=>({name:`${r.name}/${e}`,data:new Uint8Array(a(l(n,e)))})),b={task:r,packed_at:(new Date).toISOString(),cli:N(),rows:{train:o.nTrain,a:o.nA,b:o.nB},features:o.features.length,warnings:o.warnings,scores:u,capsule:H(l(n,".setter","plan.json")),ledger:D(n),files:f.map(t=>({name:t.name,bytes:t.data.length,sha256:e("sha256").update(t.data).digest("hex")}))};f.push({name:`${r.name}/setter-report.json`,data:(new TextEncoder).encode(`${JSON.stringify(b,null,2)}\n`)});const g=l(n,`${r.name}-handin.tar.gz`),w=d(A(f));i(g,w),F(`${c(g)} · ${E(w.length)} · ${f.length} files`),J(g),O(chalk.yellow(" ⚠ this archive contains the B labels — send it only to the organiser, never to a shared channel.")),J("the organiser runs the same checks again, builds the competition, and you then walk it as a contestant: kaggle <name>.")}(_[0]):(C(`setter does not know "${y}"`),J("it knows: new · check · student · score · plan · pack (bare setter shows the steps)"))}catch(e){C(e.message)}}export function registerSetterCommand(e){e.command("setter [args...]").description("Problem setter: build a task folder and test it end to end locally (new · check · student · score · pack)").action(async(e=[])=>{await runSetter(e)})}
1
+ import{createHash as e}from"node:crypto";import{appendFileSync as t,existsSync as s,mkdirSync as r,readdirSync as n,readFileSync as a,statSync as o,writeFileSync as i}from"node:fs";import{basename as c,join as l,resolve as u}from"node:path";import{gzipSync as h}from"node:zlib";import chalk from"chalk";import{renderPanel as d}from"../lib/guide-panel.js";import{logCommand as m}from"../lib/logger.js";import{parseIpynb as f,serializeIpynb as b}from"../lib/notebook-doc.js";import{printNoPython312 as p,probePython as g}from"../lib/python-setup.js";import{BASELINE_FILE as w,CUSTOM as y,CUSTOM_WORDS as k,HELPER_FILE as $,INLINE_LIMIT_BYTES as v,LOWER_IS_BETTER as _,METRICS as S,metricGroups as j,SCORER_FILE as B,TASK_FILES as z,baselineCells as A,capsulePlan as x,checkTask as O,parseTaskMeta as N,perfectSubmission as G,predColumns as C,readSubmission as F,scoreSubmission as M,scorerTemplate as J,studentBundle as P,tarArchive as q,validName as E,verdictLines as L,withScorerColumns as T}from"../lib/setter.js";import{helperSource as U,runScorer as I}from"../lib/setter-scorer.js";import{getCliVersion as D}from"../lib/version.js";const H=(e="")=>console.log(e),R=e=>console.log(chalk.red(` ✗ ${e}`)),V=e=>console.log(chalk.green(` ✓ ${e}`)),W=e=>console.log(chalk.gray(` ${e}`)),K=(e,t)=>console.log(chalk.gray(" ▸ next, type: ")+chalk.bold.green(e)+chalk.gray(` ${t}`));function Q(e){if(e){const t=u(e);return s(l(t,"task.json"))?t:null}const t=process.cwd();if(s(l(t,"task.json")))return t;try{const e=n(t).filter(e=>!e.startsWith(".")&&s(l(t,e,"task.json")));if(1===e.length)return l(t,e[0])}catch{}return null}function X(e,t){const r=l(e,t);if(s(r)){if(o(r).size>419430400)throw new Error(`${t} is over 400 MB — too large to check here; tell the organiser, this one goes through the dataset bucket`);return a(r,"utf-8")}}function Y(e){const{meta:t,problems:r}=N(X(e,"task.json")??"");for(const e of r)R(e);if(!t)return null;if(t.metric===y&&!function(e){let t=!0;return s(l(e,B))||(R(`${B} is missing — a weighted task is scored by it`),W("setter new <another-name> weighted makes a fresh one you can copy over"),t=!1),s(l(e,$))||(R(`${$} is missing — ${B} imports its metrics from it`),W(`setter new <another-name> weighted makes a fresh one you can copy over (do not edit ${$})`),t=!1),t}(e))return null;const n=T(t,X(e,B));for(const e of n.problems)R(e);return n.problems.length?null:n.meta}const Z=e=>e.metric===y,ee=e=>Z(e)?`weighted score (${B})`:e.metric;function te(e,t,s){const r=g();if(!r.ok||!r.cmd)return p(!1),W(`${B} runs on Python 3.12 on this machine — after python setup, run this again.`),null;const n=I(e,t,s,r.cmd);if(!n.ok){R(n.error??`${B} failed`);for(const e of n.detail??[])H(chalk.gray(` ${e}`));return null}if(n.columns&&n.columns.join(",")!==C(t).join(","))return R(`${B} COLUMNS is ${n.columns.join(", ")} but this tool read ${C(t).join(", ")} — write it as one plain line: COLUMNS = ["a", "b"]`),null;for(const[e,t]of[["A",n.a],["B",n.b],["all rows",n.all]])if(!Number.isFinite(t.score))return R(`${B} returned a score that is not a finite number (${e}) — check for a division by zero`),null;return n}function se(e,t){return O(t,{train:X(e,"train.csv"),testA:X(e,"test_a.csv"),labelsA:X(e,"labels_a.csv"),testB:X(e,"test_b.csv"),labelsB:X(e,"labels_b.csv")})}function re(e,s,n){try{r(l(e,".setter"),{recursive:!0}),t(l(e,".setter","ledger.jsonl"),`${JSON.stringify({at:(new Date).toISOString(),cli:D(),action:s,...n})}\n`)}catch{}}function ne(e){try{return a(l(e,".setter","ledger.jsonl"),"utf-8").split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{return[]}}const ae=e=>Number.isFinite(e)?e.toFixed(4):String(e),oe=e=>e>=1048576?`${(e/1024/1024).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`;function ie(){const e={classes:"label = a class · submit the predicted class","probability of 1":"label = 0 or 1 · submit the probability of 1",numbers:"label = a number · submit a number"};H();for(const t of j()){H(chalk.bold.white(` ${t.kind}`)+chalk.gray(` · ${e[t.kind]}`));for(const e of t.names){const t=_.has(e)?"lower is better ":"higher is better";H(chalk.cyan(` ${e.padEnd(18)}`)+chalk.gray(`${t} ${ce[e]??""}`))}}H(),W('use one: setter new <name> <metric> · or edit "metric" in task.json'),W("a metric that is not here (images, text, ranked lists): tell the organiser"),H(),H(chalk.bold.white(" Several metrics with weights?")),H(chalk.bold.cyan(" setter new <name> weighted")),H()}const ce={balanced_accuracy:"mean recall per class",macro_f1:"F1 per class, plain mean",weighted_f1:"F1 per class, weighted by class size",mcc:"Matthews correlation",f1:"labels 0 / 1, F1 of class 1",qwk:"whole-number grades, quadratic weighted kappa",auc:"area under the ROC curve",ap:"average precision (area under precision–recall)",logloss:"binary cross-entropy",brier:"mean squared error of the probability",rmsle:"labels 0 or more",mape:"avoid when labels can be 0",smape:"symmetric percentage error, 0 to 2",r2:"coefficient of determination",pearson:"linear correlation",spearman:"rank correlation"};function le(e){try{return JSON.parse(a(e,"utf-8"))}catch{return null}}export async function runSetter(t=[]){const[p,...g]=t,j=(p||"").toLowerCase();m(`setter ${j}`.trim());try{""===j||"help"===j||"?"===j||"guide"===j||"status"===j?function(e){H();for(const t of d(function(e){const t=t=>!!e&&s(l(e,t));return{id:"setter",title:{en:"Problem setter",zh:"命题工具"},what:{en:"Build one task folder and test it yourself, start to finish, on this machine: the data checks, the files a contestant gets, the A and B scores of your own solutions. Nothing leaves your computer until you hand the archive over.",zh:"在这台机器上把一道题从头到尾自己测完:数据检查、学生拿到的文件、你自己的解在 A 榜和 B 榜上的分数。在你亲手把压缩包交出去之前,没有任何东西离开你的电脑。"},steps:[{verb:"setter new my-task",what:{en:"make the folder: task.json and a baseline notebook that already runs",zh:"建文件夹:task.json 和一份能直接跑的 baseline notebook"},done:()=>t("task.json")},{verb:"setter check",what:{en:"after you put train.csv, test_a.csv + labels_a.csv, test_b.csv + labels_b.csv in it: the builder's checks",zh:"把 train.csv、test_a.csv + labels_a.csv、test_b.csv + labels_b.csv 放进去之后:跑建赛脚本的那套检查"},done:()=>t(".setter/check.json")},{verb:"setter student",what:{en:"write student/ — exactly what a contestant downloads",zh:"生成 student/ —— 学生下载到的就是这些"},done:()=>t("student/test.csv")},{verb:"ipynb",what:{en:"open student/baseline.ipynb and run all, as a contestant would — it writes submission.csv",zh:"打开 student/baseline.ipynb 敲 run all,像学生一样跑 —— 它会写出 submission.csv"},done:()=>t("student/submission.csv")},{verb:"setter score",what:{en:"A score, B score and the difference (setter score ref.csv for another solution)",zh:"A 榜分、B 榜分和差值(setter score ref.csv 给另一份解算分)"},done:()=>t(".setter/scores.json")},{verb:"setter plan 3 1.8",what:{en:"GPU tasks: minutes and peak GiB of your reference run → capsule size, seats per card",zh:"GPU 题:参考解的分钟数和峰值显存 → 胶囊档位、每张卡坐几人"},optional:!0,done:()=>t(".setter/plan.json")},{verb:"setter pack",what:{en:"one archive + report to send to the organiser",zh:"打成一个压缩包 + 报告,发给组织者"},done:()=>!!e&&n(e).some(e=>e.endsWith("-handin.tar.gz"))}],notes:[{en:`${S.length} metrics — setter metrics lists them. Several metrics with weights: setter new my-task weighted. Files are plain CSV: commas, no quotes. Publishing stays with the organiser.`,zh:`${S.length} 个指标,敲 setter metrics 看全表。多个指标加权:setter new my-task weighted。文件是普通 CSV:逗号分隔,不带引号。发布由组织者来做。`}],leave:{verb:"menu",what:{en:"main menu",zh:"主菜单"}}}}(e),"full"))H(t);W(e?`task folder: ${e}`:"no task folder here yet — setter new <name> makes one in the current directory"),H()}(Q(g[0])):"new"===j||"init"===j||"create"===j?function(e,t){if(!e||!E(e))return R("give the task a short name: 3–40 characters of a–z, 0–9 and -"),void W("example: setter new sydney-rain (add a metric: setter new sydney-rain rmse)");const n=(t||"accuracy").toLowerCase(),a=k.includes(n)?y:n;if(a!==y&&!S.includes(a))return R(`metric "${t}" is not one the judge has`),void ie();const o=u(e);if(s(o))return R(`${e}/ already exists — nothing was changed`),void K("setter check",`(inside ${e}/, or: setter check ${e})`);const c={name:e,title:e,metric:a,label:"label",id:"id",per_day:5},h=a===y?U():"";if(r(o,{recursive:!0}),i(l(o,"task.json"),`${JSON.stringify({...c,description:""},null,2)}\n`),i(l(o,w),b(A(c).map(e=>({...e,result:null})))),a===y)return i(l(o,B),J()),i(l(o,$),h),V(`made ${e}/ with task.json, ${B}, ${$} and ${w}`),W(`1. put your data in ${e}/ : train.csv · test_a.csv + labels_a.csv · test_b.csv + labels_b.csv`),W(`2. open ${e}/${B} → list your metrics and weights (three marked places, nothing else)`),void K("setter check",`(inside ${e}/, or: setter check ${e}) — it runs your scorer`);V(`made ${e}/ with task.json and ${w}`),W('now put your data in it (plain CSV, an "id" column in every file):'),W(" train.csv id + features + label"),W(" test_a.csv labels_a.csv the public-board rows, and id,label for them"),W(" test_b.csv labels_b.csv the private-board rows, and id,label for them"),W('edit task.json if your label column is not called "label" or the title should read better.'),K("setter check",`(inside ${e}/, or: setter check ${e})`)}(g[0],g[1]):"metrics"===j||"metric"===j?ie():"check"===j||"verify"===j||"validate"===j?function(t){const n=Q(t);if(!n)return R("no task folder found (a folder with task.json)"),K("setter new my-task","makes one here"),null;const c=Y(n);if(!c)return null;let u,h;try{u=se(n,c)}catch(e){return R(e.message),null}if(H(),H(chalk.bold.white(` ${c.title}`)+chalk.gray(` · ${c.name} · metric ${ee(c)} · predict ${C(c).map(e=>`"${e}"`).join(", ")}`)),!u.ok){for(const e of u.problems)R(e);return W("fix the first line above and run setter check again — nothing was written."),null}if(V(`train ${u.nTrain} rows · A ${u.nA} rows · B ${u.nB} rows · ${u.features.length} feature columns`),u.classes.length){const e=u.classes.reduce((e,[,t])=>e+t,0);W(`classes in train: ${u.classes.map(([t,s])=>`${t} ${(100*s/e).toFixed(1)}%`).join(" · ")}`)}if(Z(c)){const t=te(n,c,G(c,u));if(!t)return null;const s=te(n,c,P(c,u).sample);if(!s)return null;const r=t.higher?"higher is better":"lower is better",o=`perfect ${ae(t.all.score)} · sample fill ${ae(s.all.score)}`;if(!(t.higher?t.all.score>s.all.score:t.all.score<s.all.score))return R(`${B} runs, but ${o} (${r}) — a perfect submission must score strictly better`),W("check the weights, the columns each metric reads, and HIGHER_IS_BETTER — nothing was written."),null;V(`${B} runs · ${o} (${r})`);const i=Object.keys(t.all.parts);i.length&&W(`parts: ${i.join(" · ")}`),h={sha:e("sha256").update(a(l(n,B))).digest("hex").slice(0,16),higher_is_better:t.higher,perfect:t.all.score,sample_fill:s.all.score,parts:i}}for(const e of u.warnings)H(chalk.yellow(` ⚠ ${e}`));const d=["train.csv","test_a.csv","test_b.csv"].reduce((e,t)=>e+o(l(n,t)).size,0);d>v?H(chalk.yellow(` ⚠ data is ${oe(d)} — over the ${oe(v)} a competition carries inline; the organiser will host it in the dataset bucket`)):W(`data size ${oe(d)} — fits the inline bundle`),s(l(n,w))||H(chalk.yellow(` ⚠ no ${w} yet — every task ships a baseline the contestants start from`)),r(l(n,".setter"),{recursive:!0}),i(l(n,".setter","check.json"),`${JSON.stringify({at:(new Date).toISOString(),cli:D(),n_train:u.nTrain,n_a:u.nA,n_b:u.nB,features:u.features.length,warnings:u.warnings,data_bytes:d,...h?{scorer:h}:{}},null,2)}\n`),re(n,"check",{n_train:u.nTrain,n_a:u.nA,n_b:u.nB,features:u.features.length,data_bytes:d,warnings:u.warnings.length,...h?{scorer:h}:{}}),K("setter student","writes student/ — what a contestant downloads")}(g[0]):"student"===j||"bundle"===j||"build"===j?function(e){const t=Q(e);if(!t)return void R("no task folder found — setter new my-task makes one");const n=Y(t);if(!n)return;let o;try{o=se(t,n)}catch(e){return void R(e.message)}if(!o.ok){for(const e of o.problems)R(e);return void K("setter check","shows the same problems with the fix")}const u=l(t,"student");r(u,{recursive:!0});const h=P(n,o);i(l(u,"train.csv"),h.train),i(l(u,"test.csv"),h.test),i(l(u,"sample_submission.csv"),h.sample);const d=l(t,w);s(d)&&i(l(u,w),a(d)),re(t,"student",{rows:o.nA+o.nB,baseline:s(d)}),V(`student/ written: train.csv · test.csv (${o.nA+o.nB} rows, A and B mixed) · sample_submission.csv${s(d)?` · ${w}`:""}`),W("no labels and no A/B list are in student/ — it is safe to show to a tester."),s(d)?K(`ipynb ${l(c(t),"student",w)}`,"then run all — it writes student/submission.csv"):H(chalk.yellow(` ⚠ put your ${w} in the task folder and run setter student again`))}(g[0]):"score"===j||"grade"===j?function(t){let n,o;for(const e of t)s(l(u(e),"task.json"))?n=e:o=e;const h=Q(n);if(!h)return void R("no task folder found — setter new my-task makes one");const d=Y(h);if(!d)return;const m=o?s(u(o))?u(o):l(h,o):l(h,"student","submission.csv");if(!s(m))return R(`no submission at ${m}`),void K(`ipynb ${l(c(h),"student",w)}`,"run all writes student/submission.csv");let f;try{f=se(h,d)}catch(e){return void R(e.message)}if(!f.ok){for(const e of f.problems)R(e);return}const b=a(m,"utf-8");let p,g=null;if(Z(d)){const e=F(d,f,b);if(!e.ok){for(const t of e.problems)R(t);return}if(g=te(h,d,b),!g)return;const[t,s]=[g.a.score,g.b.score];p={ok:!0,problems:[],a:t,b:s,all:g.all.score,gap:g.higher?t-s:s-t,nMissing:0}}else if(p=M(d,f,b),!p.ok){for(const e of p.problems)R(e);return}const y=g?!g.higher:_.has(d.metric),k=y?"lower is better":"higher is better";let $;if(H(),H(chalk.bold.white(` ${c(m)}`)+chalk.gray(` · ${ee(d)} (${k})`)),H(chalk.white(` A public board ${String(f.nA).padStart(7)} rows `)+chalk.bold.white(ae(p.a))),H(chalk.white(` B private board ${String(f.nB).padStart(7)} rows `)+chalk.bold.white(ae(p.b))),H(chalk.gray(` all ${String(f.nA+f.nB).padStart(7)} rows ${ae(p.all)} A looks ${p.gap>=0?"better":"worse"} than B by ${ae(Math.abs(p.gap))}`)),g&&Object.keys(g.all.parts).length){$={};const e=Object.keys(g.all.parts),t=Math.max(4,...e.map(e=>e.length));H(),H(chalk.gray(` ${"part".padEnd(t)} A B`));for(const s of e){const e={a:g.a.parts[s],b:g.b.parts[s],all:g.all.parts[s]};$[s]=e,H(chalk.white(` ${s.padEnd(t)} ${ae(e.a).padStart(8)} ${ae(e.b).padStart(8)}`))}}const v=l(h,".setter","scores.json");let S=[];try{S=JSON.parse(a(v,"utf-8"))}catch{S=[]}const j=m.startsWith(h)?m.slice(h.length+1):m,B={file:j,sha:e("sha256").update(b).digest("hex").slice(0,16),a:p.a,b:p.b,all:p.all,gap:p.gap,at:(new Date).toISOString(),...g?{higher_is_better:g.higher}:{},...$?{parts:$}:{}};S=[...S.filter(e=>e.file!==j),B],re(h,"score",{file:j,sha:B.sha,metric:d.metric,a:p.a,b:p.b,all:p.all,...g?{higher_is_better:g.higher}:{},...$?{parts:$}:{}}),r(l(h,".setter"),{recursive:!0}),i(v,`${JSON.stringify(S,null,2)}\n`);const z=S.find(e=>e.file===l("student","submission.csv")),A=S.filter(e=>e!==z).sort((e,t)=>y?e.b-t.b:t.b-e.b)[0];if(z){const e=e=>({ok:!0,problems:[],a:e.a,b:e.b,all:e.all,gap:e.gap,nMissing:0});H();for(const t of L(d,e(z),A?e(A):null,g?g.higher:void 0))W(`· ${t}`);return A?void K("setter pack","one archive + report for the organiser"):void K("setter score ref.csv","score your own better solution too — that shows how much room contestants have")}W("· this is not the baseline run (student/submission.csv) — score that one too to see the room between them"),K(`ipynb ${l(c(h),"student",w)}`,"then run all, then setter score")}(g):"plan"===j||"capsule"===j||"capacity"===j?function(e){const t=Q(),s="cpu"===e[0]?.toLowerCase(),n=e.filter(e=>"cpu"!==e.toLowerCase()).map(Number),a=n[0],o=s?0:n[1],c=s?n[1]:n[2];if(!Number.isFinite(a)||a<=0||!s&&(!Number.isFinite(o)||o<=0))return R("give the two numbers your reference run measured: minutes and peak GPU memory in GiB"),W("example: setter plan 3 1.8 200 (3 minutes, 1.8 GiB peak, 200 contestants at once)"),W(" setter plan cpu 2 200 (a task that needs no GPU)"),void W("where the numbers come from: run the reference on a seat (gpufortask → ipynb → gpu on) and type selfcheck.");const u=x(o,a,!s,Number.isFinite(c)?c:void 0);if(H(),"cpu"===u.tier)V(`CPU task · ${a} min per run — contestants run it on their own machine, no seat needed`);else{if(!u.fits)return void R(`peak ${o} GiB does not fit the largest capsule (cap ${u.capGib} GiB) — shrink the batch or the model; a task every card can run beats one that only fits the biggest`);V(`${u.squares}-square capsule · peak ${o} GiB under the ${u.capGib} GiB cap · ${a} min per run`),H(chalk.white(" card seats at once runs per card-hour")+(u.cards?chalk.white(` cards for ${c} at once`):""));for(const[e,t]of[["l4","L4 24 GB"],["ada","Ada 20 GB"],["t4","T4 16 GB"]])u.perCard[e]?H(chalk.white(` ${t} ${String(u.perCard[e]).padStart(6)} ${String(u.runsPerCardHour?.[e]??"-").padStart(6)}`)+(u.cards?chalk.white(` ${String(u.cards[e]).padStart(6)}`):"")):H(chalk.gray(` ${t} — (a 3-square task runs on L4 only, so every contestant gets the same card)`));W("every contestant of one task gets the same capsule size on the same card type — that is what makes the times comparable."),W("a planning estimate from fixed capsule sizes; the organiser calibrates the real number on the fleet before the event.")}t&&(r(l(t,".setter"),{recursive:!0}),i(l(t,".setter","plan.json"),`${JSON.stringify({minutes:a,peak_gib:o,contestants:c??null,...u},null,2)}\n`),re(t,"plan",{minutes:a,peak_gib:o,squares:u.squares,tier:u.tier}),W("saved with the task — setter pack carries it to the organiser."))}(g):"pack"===j||"handin"===j||"hand-in"===j||"package"===j?function(t){const r=Q(t);if(!r)return void R("no task folder found — setter new my-task makes one");const n=Y(r);if(!n)return;let o;try{o=se(r,n)}catch(e){return void R(e.message)}if(!o.ok){for(const e of o.problems)R(e);return void K("setter check","the archive is only made from a folder that passes")}if(!s(l(r,w)))return void R(`${w} is missing — every task ships a baseline`);try{f(a(l(r,w),"utf-8"))}catch(e){return void R(`${w} does not open as a notebook: ${e.message}`)}let u=[];try{u=JSON.parse(a(l(r,".setter","scores.json"),"utf-8"))}catch{u=[]}u.some(e=>e.file===l("student","submission.csv"))||H(chalk.yellow(" ⚠ the baseline has not been scored — the organiser will ask for it; run it and setter score first if you can"));const d=[...z];Z(n)&&d.push(B,$);for(const e of["description.md","ref.csv","reference.ipynb"])s(l(r,e))&&d.push(e);const m=d.map(e=>({name:`${n.name}/${e}`,data:new Uint8Array(a(l(r,e)))})),b={task:n,packed_at:(new Date).toISOString(),cli:D(),rows:{train:o.nTrain,a:o.nA,b:o.nB},features:o.features.length,warnings:o.warnings,scores:u,capsule:le(l(r,".setter","plan.json")),ledger:ne(r),files:m.map(t=>({name:t.name,bytes:t.data.length,sha256:e("sha256").update(t.data).digest("hex")}))};m.push({name:`${n.name}/setter-report.json`,data:(new TextEncoder).encode(`${JSON.stringify(b,null,2)}\n`)});const p=l(r,`${n.name}-handin.tar.gz`),g=h(q(m));i(p,g),V(`${c(p)} · ${oe(g.length)} · ${m.length} files`),W(p),H(chalk.yellow(" ⚠ this archive contains the B labels — send it only to the organiser, never to a shared channel.")),W("the organiser runs the same checks again, builds the competition, and you then walk it as a contestant: kaggle <name>.")}(g[0]):(R(`setter does not know "${p}"`),W("it knows: new · metrics · check · student · score · plan · pack (bare setter shows the steps)"))}catch(e){R(e.message)}}export function registerSetterCommand(e){e.command("setter [args...]").description("Problem setter: build a task folder and test it end to end locally (new · check · student · score · pack)").action(async(e=[])=>{await runSetter(e)})}