icoa-cli 2.19.714 → 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{sprintTaskForComp as e}from"./sprint-meta.js";export function parseKaggleTaskList(e){const t=e??{},s=(t.data??t).tasks;if(!Array.isArray(s))return[];const i=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&i.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",description:"string"==typeof t.description&&""!==t.description?t.description:void 0,kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0,data_base:"string"==typeof t.data_base&&""!==t.data_base?t.data_base:null,id_col:"string"==typeof t.id_col?t.id_col:void 0,target_col:"string"==typeof t.target_col?t.target_col:void 0,n_train:"number"==typeof t.n_train?t.n_train:void 0,n_test:"number"==typeof t.n_test?t.n_test:void 0,judge:"string"==typeof t.judge&&""!==t.judge?t.judge:void 0,board_event:"string"==typeof t.board_event&&""!==t.board_event?t.board_event:null,needs_gpu:!0===t.needs_gpu})}return i}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const s=t.replace(/\/$/,"");return{train:`${s}/train.csv`,test:`${s}/test.csv`,sample_submission:`${s}/sample_submission.csv`}}export function buildStarterCells(t,s){const i=s.id_col??"id",a=s.target_col??"target";var n;n=s.metric,/rmse|mse|mae|error/i.test(n);const o="icoa-holdout"===s.judge,r=e=>({kind:"markdown",source:e,result:null}),l=e=>({kind:"code",source:e.join("\n"),result:null}),c=[`# ${s.title}`,"",...s.description?[s.description,""]:[],`Kaggle-style practice — metric: **${s.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${a}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...o?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],"","**AI help:** split your terminal (`Ctrl-b %`), run `icoa` in the right pane","and type `ai4ioai` for a live Gemma 3n E4B. Ask it for feature ideas or bug fixes —","then verify every suggestion with the val score. A tip that lowers it, drop it.",...s.licence?["",`**Data licence:** ${s.licence}`]:[],...s.attribution?[`**Attribution:** ${s.attribution}`]:[]].join("\n"),p=l(["# setup — load the data (leave as is)","import os","import numpy as np","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.feature_extraction.text import TfidfVectorizer","from sklearn.model_selection import train_test_split","from sklearn.metrics import accuracy_score, mean_squared_error","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${t}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...s.data_base?[`DATA_BASE = "${s.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")','sub_fmt = pd.read_csv(DIR + "/sample_submission.csv")',"","# 🔴 The submission column names are NOT always the training column names.","# On tasks imported from other platforms the two genuinely differ: train.csv",'# labels the answer "class" or "result" while sample_submission.csv calls it','# "answer". Hard-coding the submission name here used to raise KeyError on the',"# very first cell. So trust the DATA: whatever column train has and test lacks","# is the thing to predict.",`SUB_ID, SUB_TARGET = "${i}", "${a}" # names the submission file wants`,"only_train = [c for c in train.columns if c not in test.columns]","TARGET = only_train[-1] if only_train else SUB_TARGET","shared = [c for c in train.columns if c in test.columns]","# Only treat a column as the row id when the submission actually names it AND",'# both files carry it. Falling back to "first shared column" silently spent a',"# real feature as an id on tasks whose id lives only in test.csv.","ID = SUB_ID if SUB_ID in shared else None",'assert TARGET in train.columns, f"cannot find the label column in {list(train.columns)}"',"","# Regression or classification? Decided from the labels, not from metadata —","# several tasks ship continuous labels, and handing those to a classifier",'# raises "Unknown label type: continuous".',"REG = is_numeric_dtype(train[TARGET]) and train[TARGET].nunique() > 20",'print(f"train {train.shape} · test {test.shape} · predicting {TARGET!r} "'," f\"({'regression' if REG else 'classification'})\")","# 前几行 —— 看一眼真实数据长什么样,比看列名有用得多","print(train.head(3).to_string(max_colwidth=24)[:700])"]),u=e(s.comp_id),d=u?.media,m="audio"===d?.kind?"scipy.io.wavfile.read(path) -> numpy, then scipy.signal for a spectrogram":"image"===d?.kind?"PIL.Image.open(path) -> numpy":"weights"===d?.kind?"torch.load(path, weights_only=True) — the model itself is the input here":"unpack the archive inside the pack, then read what is in it",h=l(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Category (<= 20 distinct): one-hot.","# Free text: TF-IDF — on a text task the sentences ARE the signal, and dropping",'# them as "high-cardinality" leaves nothing to train on (that used to crash the','# whole notebook with "No objects to concatenate").',"# only columns present in BOTH files — a train-only column cannot be a feature","# at prediction time, and indexing test with it raises KeyError.","feat = [c for c in shared if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","# Everything else is vectorised as text. Requiring a long average length here","# used to throw away high-cardinality SHORT strings — ingredient names, single","# words, category codes — which on several tasks are the entire signal, leaving","# the notebook with zero features.","txt = [c for c in feat if c not in num and c not in cat]","for c in num:"," med = Xtr_raw[c].median()"," Xtr_raw[c] = Xtr_raw[c].fillna(med)"," Xte_raw[c] = Xte_raw[c].fillna(med)","blocks_tr, blocks_te = [], []","if num or cat:"," d_tr = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)"," d_te = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",' d_tr, d_te = d_tr.align(d_te, join="left", axis=1, fill_value=0)'," blocks_tr.append(d_tr.to_numpy(dtype=float))"," blocks_te.append(d_te.to_numpy(dtype=float))","for c in txt:"," # fillna BEFORE astype(str): a real NaN reaching the vectoriser raises",' # "np.nan is an invalid document", and astype alone does not catch it.',' tr_txt = Xtr_raw[c].fillna("").astype(str)',' te_txt = Xte_raw[c].fillna("").astype(str)'," # min_df=1: on a short-token column (one ingredient per row) min_df=2 can"," # filter the vocabulary down to nothing."," long_col = tr_txt.str.len().mean() >= 12"," # Try the good settings, then a permissive fallback, then give up on THIS"," # column only. A column whose vocabulary prunes to nothing used to abort the",' # whole run with "After pruning, no terms remain".',' for kw in ({"min_df": 2 if long_col else 1,',' "analyzer": "word" if long_col else "char_wb"},',' {"min_df": 1, "analyzer": "char_wb"}):'," try:"," vec = TfidfVectorizer(max_features=3000, ngram_range=(1, 2), **kw)"," b_tr = vec.fit_transform(tr_txt).toarray()"," blocks_tr.append(b_tr)"," blocks_te.append(vec.transform(te_txt).toarray())"," break"," except ValueError as e:"," last = e"," else:",' print(f" skipped text column {c!r}: {last}")',"if not blocks_tr:"," raise SystemExit(",' f"No usable feature columns. The shared columns are {feat} — none of them "',' f"is numeric, categorical or text.\\n"',...d?[` "The signal for this task is in ${d.kind} files, not in the CSVs.\\n"`,` " 1. fetch them (${d.mb}MB): teleload ${d.pack}\\n"`,...d.glob?[` " files land at <pack dir>/${d.glob}\\n"`]:[],` " 2. replace this cell: ${m}\\n"`,' " build one feature row per file, then keep the rest of the notebook.\\n"']:[' f"Two kinds of task land here, and both are real work rather than a bug:\\n"',' f" 1. audio/image — train.csv only lists sample ids and labels and the "',' f"signal is in media files. Read them with scipy.io.wavfile (audio) or "',' f"PIL (images) and turn each file into a feature row.\\n"',' f" 2. train.csv and test.csv describe different things (a retrieval or "',' f"matching task). Read both files, work out what links a test row to a "',' f"train row, and build that mapping yourself.\\n"'],...d?[' f"columns — train={list(train.columns)} test={list(test.columns)}"']:[' f"Either way: replace this cell. train={list(train.columns)} "',' f"test={list(test.columns)}"']," )","X = np.hstack(blocks_tr)","X_test = np.hstack(blocks_te)","y = train[TARGET]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"{X.shape[1]} model-ready features "',' f"({len(num)} numeric, {len(cat)} one-hot, {len(txt)} TF-IDF text)")']),f=l(["# EDA — look at the labels before you model. Produces ONE figure:","# left = what you are predicting (class balance / value spread)","# right = what the FEATURES cell will have to work with","# icoa ipynb saves it as a .png and opens your image viewer (type `open` to reopen).","import matplotlib.pyplot as plt","try:"," fig, ax = plt.subplots(1, 2, figsize=(11, 4))"," if REG:",' vals = pd.to_numeric(train[TARGET], errors="coerce").dropna()'," ax[0].hist(vals, bins=30)",' ax[0].set_title(f"{TARGET} — {len(vals)} values, mean {vals.mean():.3g}")'," else:"," vc = train[TARGET].astype(str).value_counts().head(12)"," ax[0].bar(range(len(vc)), vc.values)"," ax[0].set_xticks(range(len(vc)))",' ax[0].set_xticklabels([s[:14] for s in vc.index], rotation=45, ha="right")',' # An imbalanced target is the single most common reason a "good"'," # accuracy means nothing — show the majority share right in the title."," top = vc.iloc[0] / len(train)",' ax[0].set_title(f"{TARGET} — {train[TARGET].nunique()} classes · biggest {top:.0%}")',' kinds = {"numeric": 0, "category": 0, "text": 0}'," for c in [c for c in shared if c not in (ID, TARGET)]:"," if is_numeric_dtype(train[c]):",' kinds["numeric"] += 1'," elif train[c].nunique() <= 20:",' kinds["category"] += 1'," else:",' kinds["text"] += 1'," miss = train.isna().mean()"," miss = miss[miss > 0].sort_values(ascending=False).head(10)"," if len(miss) > 0:"," ax[1].barh(range(len(miss)), miss.values)"," ax[1].set_yticks(range(len(miss)))"," ax[1].set_yticklabels([s[:16] for s in miss.index])",' ax[1].set_title("missing rate (top columns)")'," else:"," ax[1].bar(list(kinds), list(kinds.values()))",' ax[1].set_title(f"{sum(kinds.values())} usable columns · no missing values")'," plt.tight_layout()"," plt.show()",' print("columns by kind:", kinds)',"except Exception as e:"," # EDA is never allowed to stop the run — `run all` halts on the first"," # error, and a plotting hiccup must not cost the student their baseline.",' print("EDA skipped:", type(e).__name__, e)']),g=l(["# MODEL — a working baseline. Improve THIS cell to climb the board.","from sklearn.linear_model import LogisticRegression, Ridge","# REG was decided from the labels back in setup.","model = Ridge() if REG else LogisticRegression(max_iter=2000)"]),_=l(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)","p_val = model.predict(X_val)","if REG:",' print("val RMSE:", round(mean_squared_error(y_val, p_val) ** 0.5, 4))',"else:"," acc = accuracy_score(y_val, p_val)",' print("val accuracy:", round(acc, 4))'," if acc < 0.3:"," # A near-zero baseline is the expected result on several of these tasks,"," # not a broken notebook — say so, or the student reads it as a bug.",' print(" A score this low usually means the linear baseline cannot "',' "represent the pattern at all (combination rules, sequences, "',' "spelling). That IS the task: build features that expose it, "',' "or switch to a model that can. The chain itself works — "',' "submission.csv is written either way.")']),b=l(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',"# Copy the layout of sample_submission.csv and swap in the predictions, rather","# than rebuilding the file from column names. Some tasks want more than two","# columns (e.g. subtaskID,datapointID,answer) and a hand-built 2-column frame","# is rejected by the grader even when every prediction is right.","if len(sub_fmt) == len(pred):"," sub = sub_fmt.copy()"," sub[sub.columns[-1]] = pred","else:"," keys = {}"," if ID is not None and ID in test.columns:"," keys[SUB_ID] = test[ID]"," keys[SUB_TARGET] = pred"," sub = pd.DataFrame(keys)",' print(f"NOTE: sample_submission has {len(sub_fmt)} rows but test has "',' f"{len(pred)} — built the file from column names instead; "',' f"check it against the task page before submitting.")',"sub.to_csv(out, index=False)",'print("wrote", out, "·", list(sub.columns))',o?`print("score it: icoa kaggle submit ${s.comp_id}")`:'print("format check: icoa kaggle check")']),y=o?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${s.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:"nitro"===s.judge?["## Where this one gets scored","","This task comes from **judge.nitro-ai.org** and the answer key stays on","their server, so ICOA cannot score it for you. That does not make it a","practice stub — it is a real task, just judged elsewhere.","",`1. \`icoa kaggle check ${s.comp_id}\` — checks the FORMAT of`," `submission.csv` (headers, row count, ids). Format errors are the most"," common way a correct answer still scores zero.","2. Watch the **val score** printed above — that is your real feedback loop"," during the sprint, and it needs no account anywhere.","3. Want the official number? Register at judge.nitro-ai.org and submit"," there. Otherwise compare against the official solution, or ask"," `ai4ioai` to review your approach."]:s.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${s.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This dataset has no live Kaggle page linked yet._","The loop is identical: upload `submission.csv`, read the score, improve","the MODEL cell, repeat. Meanwhile the **val score** printed above is a","real signal you can work against with no account at all."];return[r(c),p,f,h,g,_,b,r(y.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},s=t.data??t,i=s&&"object"==typeof s?s:{};return"number"==typeof i.score&&"string"==typeof i.metric?{ok:!0,score:i.score,metric:i.metric,rank:"number"==typeof i.rank_at_time?i.rank_at_time:null,fieldSize:"number"==typeof i.field_size?i.field_size:null,deduped:!0===i.deduped,sameCode:!0===i.same_code,submissionId:"string"==typeof i.submission_id?i.submission_id:null,leaderboard:"string"==typeof i.leaderboard?i.leaderboard:null,boardEvent:"string"==typeof i.board_event?i.board_event:null,used:"number"==typeof i.submissions_used?i.submissions_used:null,cap:"number"==typeof i.submissions_cap?i.submissions_cap:null,parts:i.parts&&"object"==typeof i.parts?Object.entries(i.parts).filter(e=>"number"==typeof e[1]).slice(0,24):void 0}:"string"==typeof i.reason&&""!==i.reason?{ok:!1,reason:i.reason,error:"string"==typeof i.error?i.error:void 0,problems:Array.isArray(i.problems)?i.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const s=[],i=e.trim().split(/\r?\n/),a=t.trim().split(/\r?\n/),n=i[0]??"",o=a[0]??"";n.trim()!==o.trim()&&s.push(`header mismatch: expected "${o}", got "${n}"`);const r=i.slice(1).filter(e=>""!==e.trim()),l=a.slice(1).filter(e=>""!==e.trim());r.length!==l.length&&s.push(`row count mismatch: expected ${l.length}, got ${r.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),p=c(r),u=c(l),d=[...u].filter(e=>!p.has(e)),m=[...p].filter(e=>!u.has(e));if(d.length>0||m.length>0){const e=[];d.length>0&&e.push(`${d.length} missing (e.g. ${d[0]})`),m.length>0&&e.push(`${m.length} unknown (e.g. ${m[0]})`),s.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<r.length;e++)if(r[e].split(",").some(e=>""===e.trim())){s.push(`empty cell in data row ${e+1}`);break}return{ok:0===s.length,problems:s}}export function buildMediaStarterCells(e,t){const s=e=>({kind:"markdown",source:e,result:null}),i=e=>({kind:"code",source:e.join("\n"),result:null}),a=t.media?.kind??"archive",n=t.title??"ICOA sprint task",o=[`# ${t.seq?`${t.seq} · `:""}${n}`,"",...t.topic_cn?[t.topic_cn,""]:[],"This task ships **data, not a baseline** — the CSV starter cannot help here",`because the signal lives in the ${a} files you just pulled.`,"","Run all cells: they inventory the pack and draw one picture of what is inside,","so you start from evidence instead of from the folder name. The last cell says","what you have to build — that part is the task.","","**Reading the files:** on your laptop the notebook env has numpy / scipy /","pandas / scikit-learn / torch / transformers / Pillow — but NOT librosa,","torchaudio or soundfile. The GPU contest box has librosa and torchaudio too."].join("\n"),r=i(["# inventory — what is actually in this pack (counts, sizes, a few real names)","import os","import numpy as np",`DIR = os.environ.get("ICOA_PACK_DIR") or r"${e}"`,"by_ext, total, sample = {}, 0, {}","for root, _dirs, files in os.walk(DIR):"," for f in files:",' ext = os.path.splitext(f)[1].lower() or "(no ext)"'," p = os.path.join(root, f)"," by_ext[ext] = by_ext.get(ext, 0) + 1"," total += os.path.getsize(p)"," sample.setdefault(ext, p)",'print(f"{DIR}\\n{sum(by_ext.values())} files · {total/1048576:.0f} MB")',"for ext, n in sorted(by_ext.items(), key=lambda kv: -kv[1])[:8]:",' print(f" {ext:>10} {n:>6} e.g. {os.path.relpath(sample[ext], DIR)}")',"# 🔴 a leftover .zip means the pack still needs unpacking before you can read it",'zips = [p for e, p in sample.items() if e == ".zip"]',"if zips:",' print("\\nNOTE: there is still a .zip in here — unpack it first:")',' print(f" import zipfile; zipfile.ZipFile(r\\"{zips[0]}\\").extractall(DIR)")']),l=["# EDA — one picture of what is inside. icoa ipynb saves it as a .png and","# opens your image viewer (`open` reopens it).","import matplotlib.pyplot as plt","try:"];"image"===a?l.push(" from PIL import Image"," imgs = []"," for root, _d, files in os.walk(DIR):"," for f in sorted(files):",' if os.path.splitext(f)[1].lower() in (".jpg", ".jpeg", ".png"):'," imgs.append(os.path.join(root, f))"," if len(imgs) >= 9:"," break"," fig, axes = plt.subplots(3, 3, figsize=(7, 7))"," for ax, p in zip(axes.ravel(), imgs[:9]):"," ax.imshow(Image.open(p))"," ax.set_title(os.path.basename(p)[:18], fontsize=8)"," for ax in axes.ravel():",' ax.axis("off")',' plt.suptitle(f"{len(imgs)}+ images · first 9")'):"weights"===a?l.push(" import torch"," wfiles = []"," for root, _d, files in os.walk(DIR):"," for f in sorted(files):",' if os.path.splitext(f)[1].lower() in (".pt", ".pth"):'," wfiles.append(os.path.join(root, f))"," fig, ax = plt.subplots(1, max(1, min(2, len(wfiles))), figsize=(10, 4), squeeze=False)"," for i, p in enumerate(wfiles[:2]):"," # weights_only=True: never unpickle arbitrary objects from a data file",' obj = torch.load(p, map_location="cpu", weights_only=True)',' t = obj if hasattr(obj, "flatten") else list(obj.values())[0]'," v = np.asarray(t, dtype=float).ravel()"," ax[0][i].hist(v, bins=60)",' ax[0][i].set_title(f"{os.path.basename(p)} · shape {tuple(np.shape(t))}", fontsize=9)',' print(os.path.basename(p), "shape", tuple(np.shape(t)))'):l.push(" import pandas as pd"," csvs = []"," for root, _d, files in os.walk(DIR):"," for f in files:",' if f.lower().endswith(".csv"):'," csvs.append(os.path.join(root, f))"," csvs.sort(key=os.path.getsize, reverse=True)"," df = pd.read_csv(csvs[0])"," print(os.path.basename(csvs[0]), df.shape)"," print(df.head(3).to_string(max_colwidth=24)[:600])"," # the last low-cardinality column is the usual label; if there is none,"," # plot the row-length spread so the picture still says something true"," cand = [c for c in df.columns if df[c].nunique() <= 30]"," fig, ax = plt.subplots(figsize=(8, 4))"," if cand:"," vc = df[cand[-1]].astype(str).value_counts().head(12)"," ax.bar(range(len(vc)), vc.values)"," ax.set_xticks(range(len(vc)))",' ax.set_xticklabels([s[:14] for s in vc.index], rotation=45, ha="right")',' ax.set_title(f"{cand[-1]} — {df[cand[-1]].nunique()} values")'," else:"," ax.hist([len(str(x)) for x in df[df.columns[-1]]], bins=30)",' ax.set_title(f"length of {df.columns[-1]}")'),l.push(" plt.tight_layout()"," plt.show()","except Exception as e:"," # never stop the run on a plotting problem — `run all` halts on first error",' print("EDA skipped:", type(e).__name__, e)');const c=["## Your job","","There is no baseline to beat here — you build the first one. The shape of it:","","1. **turn each file into a row of numbers** — that is the whole trick","image"===a?" (`PIL.Image.open` → resize → `np.asarray` → flatten, or a pretrained encoder)":"weights"===a?" (`torch.load(..., weights_only=True)` → the tensors themselves ARE the features)":" (read the CSVs / unpack the archive, then vectorise the text columns)","2. keep a held-out fifth of the data and print a val score every time","3. write your predictions in exactly the format the task page asks for","","`add` makes a new code cell · `add md` a note cell · `run all` runs everything ·","a cell that raises offers `ai N`, which sends that cell and its traceback to the AI."].join("\n");return[s(o),r,i(l),s(c)]}
1
+ import{sprintTaskForComp as e}from"./sprint-meta.js";export function parseKaggleTaskList(e){const t=e??{},s=(t.data??t).tasks;if(!Array.isArray(s))return[];const i=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&i.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",description:"string"==typeof t.description&&""!==t.description?t.description:void 0,kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0,data_base:"string"==typeof t.data_base&&""!==t.data_base?t.data_base:null,id_col:"string"==typeof t.id_col?t.id_col:void 0,target_col:"string"==typeof t.target_col?t.target_col:void 0,n_train:"number"==typeof t.n_train?t.n_train:void 0,n_test:"number"==typeof t.n_test?t.n_test:void 0,judge:"string"==typeof t.judge&&""!==t.judge?t.judge:void 0,board_event:"string"==typeof t.board_event&&""!==t.board_event?t.board_event:null,needs_gpu:!0===t.needs_gpu})}return i}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const s=t.replace(/\/$/,"");return{train:`${s}/train.csv`,test:`${s}/test.csv`,sample_submission:`${s}/sample_submission.csv`}}export function buildStarterCells(t,s){const i=s.id_col??"id",a=s.target_col??"target";var n;n=s.metric,/rmse|mse|mae|error/i.test(n);const r="icoa-holdout"===s.judge,o=e=>({kind:"markdown",source:e,result:null}),l=e=>({kind:"code",source:e.join("\n"),result:null}),c=[`# ${s.title}`,"",...s.description?[s.description,""]:[],`Kaggle-style practice — metric: **${s.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${a}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...r?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],"","**AI help:** split your terminal (`Ctrl-b %`), run `icoa` in the right pane","and type `ai4ioai` for a live Gemma 3n E4B. Ask it for feature ideas or bug fixes —","then verify every suggestion with the val score. A tip that lowers it, drop it.",...s.licence?["",`**Data licence:** ${s.licence}`]:[],...s.attribution?[`**Attribution:** ${s.attribution}`]:[]].join("\n"),p=l(["# setup — load the data (leave as is)","import os","import numpy as np","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.feature_extraction.text import TfidfVectorizer","from sklearn.model_selection import train_test_split","from sklearn.metrics import accuracy_score, mean_squared_error","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${t}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...s.data_base?[`DATA_BASE = "${s.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")','sub_fmt = pd.read_csv(DIR + "/sample_submission.csv")',"","# 🔴 The submission column names are NOT always the training column names.","# On tasks imported from other platforms the two genuinely differ: train.csv",'# labels the answer "class" or "result" while sample_submission.csv calls it','# "answer". Hard-coding the submission name here used to raise KeyError on the',"# very first cell. So trust the DATA: whatever column train has and test lacks","# is the thing to predict.",`SUB_ID, SUB_TARGET = "${i}", "${a}" # names the submission file wants`,"only_train = [c for c in train.columns if c not in test.columns]","TARGET = only_train[-1] if only_train else SUB_TARGET","shared = [c for c in train.columns if c in test.columns]","# Only treat a column as the row id when the submission actually names it AND",'# both files carry it. Falling back to "first shared column" silently spent a',"# real feature as an id on tasks whose id lives only in test.csv.","ID = SUB_ID if SUB_ID in shared else None",'assert TARGET in train.columns, f"cannot find the label column in {list(train.columns)}"',"","# Regression or classification? Decided from the labels, not from metadata —","# several tasks ship continuous labels, and handing those to a classifier",'# raises "Unknown label type: continuous".',"REG = is_numeric_dtype(train[TARGET]) and train[TARGET].nunique() > 20",'print(f"train {train.shape} · test {test.shape} · predicting {TARGET!r} "'," f\"({'regression' if REG else 'classification'})\")","# 前几行 —— 看一眼真实数据长什么样,比看列名有用得多","print(train.head(3).to_string(max_colwidth=24)[:700])"]),u=e(s.comp_id),d=u?.media,m="audio"===d?.kind?"scipy.io.wavfile.read(path) -> numpy, then scipy.signal for a spectrogram":"image"===d?.kind?"PIL.Image.open(path) -> numpy":"weights"===d?.kind?"torch.load(path, weights_only=True) — the model itself is the input here":"unpack the archive inside the pack, then read what is in it",h=l(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Category (<= 20 distinct): one-hot.","# Free text: TF-IDF — on a text task the sentences ARE the signal, and dropping",'# them as "high-cardinality" leaves nothing to train on (that used to crash the','# whole notebook with "No objects to concatenate").',"# only columns present in BOTH files — a train-only column cannot be a feature","# at prediction time, and indexing test with it raises KeyError.","feat = [c for c in shared if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","# Everything else is vectorised as text. Requiring a long average length here","# used to throw away high-cardinality SHORT strings — ingredient names, single","# words, category codes — which on several tasks are the entire signal, leaving","# the notebook with zero features.","txt = [c for c in feat if c not in num and c not in cat]","for c in num:"," med = Xtr_raw[c].median()"," Xtr_raw[c] = Xtr_raw[c].fillna(med)"," Xte_raw[c] = Xte_raw[c].fillna(med)","blocks_tr, blocks_te = [], []","if num or cat:"," d_tr = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)"," d_te = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",' d_tr, d_te = d_tr.align(d_te, join="left", axis=1, fill_value=0)'," blocks_tr.append(d_tr.to_numpy(dtype=float))"," blocks_te.append(d_te.to_numpy(dtype=float))","for c in txt:"," # fillna BEFORE astype(str): a real NaN reaching the vectoriser raises",' # "np.nan is an invalid document", and astype alone does not catch it.',' tr_txt = Xtr_raw[c].fillna("").astype(str)',' te_txt = Xte_raw[c].fillna("").astype(str)'," # min_df=1: on a short-token column (one ingredient per row) min_df=2 can"," # filter the vocabulary down to nothing."," long_col = tr_txt.str.len().mean() >= 12"," # Try the good settings, then a permissive fallback, then give up on THIS"," # column only. A column whose vocabulary prunes to nothing used to abort the",' # whole run with "After pruning, no terms remain".',' for kw in ({"min_df": 2 if long_col else 1,',' "analyzer": "word" if long_col else "char_wb"},',' {"min_df": 1, "analyzer": "char_wb"}):'," try:"," vec = TfidfVectorizer(max_features=3000, ngram_range=(1, 2), **kw)"," b_tr = vec.fit_transform(tr_txt).toarray()"," blocks_tr.append(b_tr)"," blocks_te.append(vec.transform(te_txt).toarray())"," break"," except ValueError as e:"," last = e"," else:",' print(f" skipped text column {c!r}: {last}")',"if not blocks_tr:"," raise SystemExit(",' f"No usable feature columns. The shared columns are {feat} — none of them "',' f"is numeric, categorical or text.\\n"',...d?[` "The signal for this task is in ${d.kind} files, not in the CSVs.\\n"`,` " 1. fetch them (${d.mb}MB): teleload ${d.pack}\\n"`,...d.glob?[` " files land at <pack dir>/${d.glob}\\n"`]:[],` " 2. replace this cell: ${m}\\n"`,' " build one feature row per file, then keep the rest of the notebook.\\n"']:[' f"Two kinds of task land here, and both are real work rather than a bug:\\n"',' f" 1. audio/image — train.csv only lists sample ids and labels and the "',' f"signal is in media files. Read them with scipy.io.wavfile (audio) or "',' f"PIL (images) and turn each file into a feature row.\\n"',' f" 2. train.csv and test.csv describe different things (a retrieval or "',' f"matching task). Read both files, work out what links a test row to a "',' f"train row, and build that mapping yourself.\\n"'],...d?[' f"columns — train={list(train.columns)} test={list(test.columns)}"']:[' f"Either way: replace this cell. train={list(train.columns)} "',' f"test={list(test.columns)}"']," )","X = np.hstack(blocks_tr)","X_test = np.hstack(blocks_te)","y = train[TARGET]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"{X.shape[1]} model-ready features "',' f"({len(num)} numeric, {len(cat)} one-hot, {len(txt)} TF-IDF text)")']),f=l(["# EDA — look at the labels before you model. Produces ONE figure:","# left = what you are predicting (class balance / value spread)","# right = what the FEATURES cell will have to work with","# icoa ipynb shows it in the terminal and saves a .png (type `open` for the full-size picture).","import matplotlib.pyplot as plt","try:"," fig, ax = plt.subplots(1, 2, figsize=(11, 4))"," if REG:",' vals = pd.to_numeric(train[TARGET], errors="coerce").dropna()'," ax[0].hist(vals, bins=30)",' ax[0].set_title(f"{TARGET} — {len(vals)} values, mean {vals.mean():.3g}")'," else:"," vc = train[TARGET].astype(str).value_counts().head(12)"," ax[0].bar(range(len(vc)), vc.values)"," ax[0].set_xticks(range(len(vc)))",' ax[0].set_xticklabels([s[:14] for s in vc.index], rotation=45, ha="right")',' # An imbalanced target is the single most common reason a "good"'," # accuracy means nothing — show the majority share right in the title."," top = vc.iloc[0] / len(train)",' ax[0].set_title(f"{TARGET} — {train[TARGET].nunique()} classes · biggest {top:.0%}")',' kinds = {"numeric": 0, "category": 0, "text": 0}'," for c in [c for c in shared if c not in (ID, TARGET)]:"," if is_numeric_dtype(train[c]):",' kinds["numeric"] += 1'," elif train[c].nunique() <= 20:",' kinds["category"] += 1'," else:",' kinds["text"] += 1'," miss = train.isna().mean()"," miss = miss[miss > 0].sort_values(ascending=False).head(10)"," if len(miss) > 0:"," ax[1].barh(range(len(miss)), miss.values)"," ax[1].set_yticks(range(len(miss)))"," ax[1].set_yticklabels([s[:16] for s in miss.index])",' ax[1].set_title("missing rate (top columns)")'," else:"," ax[1].bar(list(kinds), list(kinds.values()))",' ax[1].set_title(f"{sum(kinds.values())} usable columns · no missing values")'," plt.tight_layout()"," plt.show()",' print("columns by kind:", kinds)',"except Exception as e:"," # EDA is never allowed to stop the run — `run all` halts on the first"," # error, and a plotting hiccup must not cost the student their baseline.",' print("EDA skipped:", type(e).__name__, e)']),g=l(["# MODEL — a working baseline. Improve THIS cell to climb the board.","from sklearn.linear_model import LogisticRegression, Ridge","# REG was decided from the labels back in setup.","model = Ridge() if REG else LogisticRegression(max_iter=2000)"]),_=l(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)","p_val = model.predict(X_val)","if REG:",' print("val RMSE:", round(mean_squared_error(y_val, p_val) ** 0.5, 4))',"else:"," acc = accuracy_score(y_val, p_val)",' print("val accuracy:", round(acc, 4))'," if acc < 0.3:"," # A near-zero baseline is the expected result on several of these tasks,"," # not a broken notebook — say so, or the student reads it as a bug.",' print(" A score this low usually means the linear baseline cannot "',' "represent the pattern at all (combination rules, sequences, "',' "spelling). That IS the task: build features that expose it, "',' "or switch to a model that can. The chain itself works — "',' "submission.csv is written either way.")']),b=l(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',"# Copy the layout of sample_submission.csv and swap in the predictions, rather","# than rebuilding the file from column names. Some tasks want more than two","# columns (e.g. subtaskID,datapointID,answer) and a hand-built 2-column frame","# is rejected by the grader even when every prediction is right.","if len(sub_fmt) == len(pred):"," sub = sub_fmt.copy()"," sub[sub.columns[-1]] = pred","else:"," keys = {}"," if ID is not None and ID in test.columns:"," keys[SUB_ID] = test[ID]"," keys[SUB_TARGET] = pred"," sub = pd.DataFrame(keys)",' print(f"NOTE: sample_submission has {len(sub_fmt)} rows but test has "',' f"{len(pred)} — built the file from column names instead; "',' f"check it against the task page before submitting.")',"sub.to_csv(out, index=False)",'print("wrote", out, "·", list(sub.columns))',r?`print("score it: icoa kaggle submit ${s.comp_id}")`:'print("format check: icoa kaggle check")']),y=r?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${s.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:"nitro"===s.judge?["## Where this one gets scored","","This task comes from **judge.nitro-ai.org** and the answer key stays on","their server, so ICOA cannot score it for you. That does not make it a","practice stub — it is a real task, just judged elsewhere.","",`1. \`icoa kaggle check ${s.comp_id}\` — checks the FORMAT of`," `submission.csv` (headers, row count, ids). Format errors are the most"," common way a correct answer still scores zero.","2. Watch the **val score** printed above — that is your real feedback loop"," during the sprint, and it needs no account anywhere.","3. Want the official number? Register at judge.nitro-ai.org and submit"," there. Otherwise compare against the official solution, or ask"," `ai4ioai` to review your approach."]:s.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${s.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This dataset has no live Kaggle page linked yet._","The loop is identical: upload `submission.csv`, read the score, improve","the MODEL cell, repeat. Meanwhile the **val score** printed above is a","real signal you can work against with no account at all."];return[o(c),p,f,h,g,_,b,o(y.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},s=t.data??t,i=s&&"object"==typeof s?s:{};return"number"==typeof i.score&&"string"==typeof i.metric?{ok:!0,score:i.score,metric:i.metric,rank:"number"==typeof i.rank_at_time?i.rank_at_time:null,fieldSize:"number"==typeof i.field_size?i.field_size:null,deduped:!0===i.deduped,sameCode:!0===i.same_code,submissionId:"string"==typeof i.submission_id?i.submission_id:null,leaderboard:"string"==typeof i.leaderboard?i.leaderboard:null,boardEvent:"string"==typeof i.board_event?i.board_event:null,used:"number"==typeof i.submissions_used?i.submissions_used:null,cap:"number"==typeof i.submissions_cap?i.submissions_cap:null,parts:i.parts&&"object"==typeof i.parts?Object.entries(i.parts).filter(e=>"number"==typeof e[1]).slice(0,24):void 0}:"string"==typeof i.reason&&""!==i.reason?{ok:!1,reason:i.reason,error:"string"==typeof i.error?i.error:void 0,problems:Array.isArray(i.problems)?i.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const s=[],i=e.trim().split(/\r?\n/),a=t.trim().split(/\r?\n/),n=i[0]??"",r=a[0]??"";n.trim()!==r.trim()&&s.push(`header mismatch: expected "${r}", got "${n}"`);const o=i.slice(1).filter(e=>""!==e.trim()),l=a.slice(1).filter(e=>""!==e.trim());o.length!==l.length&&s.push(`row count mismatch: expected ${l.length}, got ${o.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),p=c(o),u=c(l),d=[...u].filter(e=>!p.has(e)),m=[...p].filter(e=>!u.has(e));if(d.length>0||m.length>0){const e=[];d.length>0&&e.push(`${d.length} missing (e.g. ${d[0]})`),m.length>0&&e.push(`${m.length} unknown (e.g. ${m[0]})`),s.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<o.length;e++)if(o[e].split(",").some(e=>""===e.trim())){s.push(`empty cell in data row ${e+1}`);break}return{ok:0===s.length,problems:s}}export function buildMediaStarterCells(e,t){const s=e=>({kind:"markdown",source:e,result:null}),i=e=>({kind:"code",source:e.join("\n"),result:null}),a=t.media?.kind??"archive",n=t.title??"ICOA sprint task",r=[`# ${t.seq?`${t.seq} · `:""}${n}`,"",...t.topic_cn?[t.topic_cn,""]:[],"This task ships **data, not a baseline** — the CSV starter cannot help here",`because the signal lives in the ${a} files you just pulled.`,"","Run all cells: they inventory the pack and draw one picture of what is inside,","so you start from evidence instead of from the folder name. The last cell says","what you have to build — that part is the task.","","**Reading the files:** on your laptop the notebook env has numpy / scipy /","pandas / scikit-learn / torch / transformers / Pillow — but NOT librosa,","torchaudio or soundfile. The GPU contest box has librosa and torchaudio too."].join("\n"),o=i(["# inventory — what is actually in this pack (counts, sizes, a few real names)","import os","import numpy as np",`DIR = os.environ.get("ICOA_PACK_DIR") or r"${e}"`,"by_ext, total, sample = {}, 0, {}","for root, _dirs, files in os.walk(DIR):"," for f in files:",' ext = os.path.splitext(f)[1].lower() or "(no ext)"'," p = os.path.join(root, f)"," by_ext[ext] = by_ext.get(ext, 0) + 1"," total += os.path.getsize(p)"," sample.setdefault(ext, p)",'print(f"{DIR}\\n{sum(by_ext.values())} files · {total/1048576:.0f} MB")',"for ext, n in sorted(by_ext.items(), key=lambda kv: -kv[1])[:8]:",' print(f" {ext:>10} {n:>6} e.g. {os.path.relpath(sample[ext], DIR)}")',"# 🔴 a leftover .zip means the pack still needs unpacking before you can read it",'zips = [p for e, p in sample.items() if e == ".zip"]',"if zips:",' print("\\nNOTE: there is still a .zip in here — unpack it first:")',' print(f" import zipfile; zipfile.ZipFile(r\\"{zips[0]}\\").extractall(DIR)")']),l=["# EDA — one picture of what is inside. icoa ipynb shows it in the terminal and","# saves a .png (`open` shows it full size).","import matplotlib.pyplot as plt","try:"];"image"===a?l.push(" from PIL import Image"," imgs = []"," for root, _d, files in os.walk(DIR):"," for f in sorted(files):",' if os.path.splitext(f)[1].lower() in (".jpg", ".jpeg", ".png"):'," imgs.append(os.path.join(root, f))"," if len(imgs) >= 9:"," break"," fig, axes = plt.subplots(3, 3, figsize=(7, 7))"," for ax, p in zip(axes.ravel(), imgs[:9]):"," ax.imshow(Image.open(p))"," ax.set_title(os.path.basename(p)[:18], fontsize=8)"," for ax in axes.ravel():",' ax.axis("off")',' plt.suptitle(f"{len(imgs)}+ images · first 9")'):"weights"===a?l.push(" import torch"," wfiles = []"," for root, _d, files in os.walk(DIR):"," for f in sorted(files):",' if os.path.splitext(f)[1].lower() in (".pt", ".pth"):'," wfiles.append(os.path.join(root, f))"," fig, ax = plt.subplots(1, max(1, min(2, len(wfiles))), figsize=(10, 4), squeeze=False)"," for i, p in enumerate(wfiles[:2]):"," # weights_only=True: never unpickle arbitrary objects from a data file",' obj = torch.load(p, map_location="cpu", weights_only=True)',' t = obj if hasattr(obj, "flatten") else list(obj.values())[0]'," v = np.asarray(t, dtype=float).ravel()"," ax[0][i].hist(v, bins=60)",' ax[0][i].set_title(f"{os.path.basename(p)} · shape {tuple(np.shape(t))}", fontsize=9)',' print(os.path.basename(p), "shape", tuple(np.shape(t)))'):l.push(" import pandas as pd"," csvs = []"," for root, _d, files in os.walk(DIR):"," for f in files:",' if f.lower().endswith(".csv"):'," csvs.append(os.path.join(root, f))"," csvs.sort(key=os.path.getsize, reverse=True)"," df = pd.read_csv(csvs[0])"," print(os.path.basename(csvs[0]), df.shape)"," print(df.head(3).to_string(max_colwidth=24)[:600])"," # the last low-cardinality column is the usual label; if there is none,"," # plot the row-length spread so the picture still says something true"," cand = [c for c in df.columns if df[c].nunique() <= 30]"," fig, ax = plt.subplots(figsize=(8, 4))"," if cand:"," vc = df[cand[-1]].astype(str).value_counts().head(12)"," ax.bar(range(len(vc)), vc.values)"," ax.set_xticks(range(len(vc)))",' ax.set_xticklabels([s[:14] for s in vc.index], rotation=45, ha="right")',' ax.set_title(f"{cand[-1]} — {df[cand[-1]].nunique()} values")'," else:"," ax.hist([len(str(x)) for x in df[df.columns[-1]]], bins=30)",' ax.set_title(f"length of {df.columns[-1]}")'),l.push(" plt.tight_layout()"," plt.show()","except Exception as e:"," # never stop the run on a plotting problem — `run all` halts on first error",' print("EDA skipped:", type(e).__name__, e)');const c=["## Your job","","There is no baseline to beat here — you build the first one. The shape of it:","","1. **turn each file into a row of numbers** — that is the whole trick","image"===a?" (`PIL.Image.open` → resize → `np.asarray` → flatten, or a pretrained encoder)":"weights"===a?" (`torch.load(..., weights_only=True)` → the tensors themselves ARE the features)":" (read the CSVs / unpack the archive, then vectorise the text columns)","2. keep a held-out fifth of the data and print a val score every time","3. write your predictions in exactly the format the task page asks for","","`add` makes a new code cell · `add md` a note cell · `run all` runs everything ·","a cell that raises offers `ai N`, which sends that cell and its traceback to the AI."].join("\n");return[s(r),o,i(l),s(c)]}
@@ -1 +1 @@
1
- import{inflateSync as t}from"node:zlib";import{colorMode as e,encodeFrame as n}from"./term-video.js";const r=[137,80,78,71,13,10,26,10];export function isPng(t){return t.length>8&&r.every((e,n)=>t[n]===e)}export function decodePng(e){try{if(!isPng(e))return null;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=8,o=0,s=0,l=0,a=0,i=0,c=null,f=null;const u=[];for(;r+8<=e.length;){const t=n.getUint32(r),h=String.fromCharCode(e[r+4],e[r+5],e[r+6],e[r+7]),m=e.subarray(r+8,r+8+t);if("IHDR"===h)o=n.getUint32(r+8),s=n.getUint32(r+12),l=e[r+16],a=e[r+17],i=e[r+20];else if("PLTE"===h)c=m;else if("tRNS"===h)f=m;else if("IDAT"===h)u.push(m);else if("IEND"===h)break;r+=12+t}const h={0:1,2:3,3:1,4:2,6:4}[a];if(!o||!s||!h||0!==i||8!==l&&16!==l||o*s>4e7)return null;if(3===a&&(!c||8!==l))return null;const m=h*(l/8),g=o*m;let p=0;for(const t of u)p+=t.length;const d=new Uint8Array(p);let b=0;for(const t of u)d.set(t,b),b+=t.length;const M=t(d);if(M.length<(g+1)*s)return null;const w=new Uint8Array(g);let x=new Uint8Array(g);const y=new Uint8Array(o*s*4),A=l/8;for(let t=0;t<s;t++){const e=t*(g+1),n=M[e];for(let t=0;t<g;t++){const r=M[e+1+t],o=t>=m?w[t-m]:0,s=x[t],l=t>=m?x[t-m]:0;let a;if(0===n)a=r;else if(1===n)a=r+o;else if(2===n)a=r+s;else if(3===n)a=r+(o+s>>1);else{if(4!==n)return null;{const t=Math.abs(s-l),e=Math.abs(o-l),n=Math.abs(o+s-2*l);a=r+(t<=e&&t<=n?o:e<=n?s:l)}}w[t]=255&a}for(let e=0;e<o;e++){const n=e*m,r=4*(t*o+e);if(0===a)y[r]=y[r+1]=y[r+2]=w[n],y[r+3]=255;else if(2===a)y[r]=w[n],y[r+1]=w[n+A],y[r+2]=w[n+2*A],y[r+3]=255;else if(3===a){const t=3*w[n];y[r]=c[t]??0,y[r+1]=c[t+1]??0,y[r+2]=c[t+2]??0,y[r+3]=f&&w[n]<f.length?f[w[n]]:255}else 4===a?(y[r]=y[r+1]=y[r+2]=w[n],y[r+3]=w[n+A]):(y[r]=w[n],y[r+1]=w[n+A],y[r+2]=w[n+2*A],y[r+3]=w[n+3*A])}x=w.slice()}return{w:o,h:s,data:y}}catch{return null}}export function thumbSize(t,e,n,r=22){const o=Math.max(16,Math.min(100,n-6)),s=2*r,l=Math.min(o/t,s/e,4),a=Math.max(2,Math.round(t*l));let i=Math.max(2,Math.round(e*l));return i%2&&(i+=1),{w:a,h:i}}export function resample(t,e,n){const r=new Uint8Array(e*n*3);for(let o=0;o<n;o++){const s=Math.floor(o*t.h/n),l=Math.max(s+1,Math.floor((o+1)*t.h/n));for(let n=0;n<e;n++){const a=Math.floor(n*t.w/e),i=Math.max(a+1,Math.floor((n+1)*t.w/e));let c=0,f=0,u=0,h=0;for(let e=s;e<l&&e<t.h;e++)for(let n=a;n<i&&n<t.w;n++){const r=4*(e*t.w+n),o=t.data[r+3]/255;c+=t.data[r]*o+255*(1-o),f+=t.data[r+1]*o+255*(1-o),u+=t.data[r+2]*o+255*(1-o),h++}const m=3*(o*e+n);r[m]=h?Math.round(c/h):255,r[m+1]=h?Math.round(f/h):255,r[m+2]=h?Math.round(u/h):255}}return r}export function pngThumbLines(t,e,r,o=22){if("none"===r)return[];const s=decodePng(t);if(!s)return[];const{w:l,h:a}=thumbSize(s.w,s.h,e,o);return n(resample(s,l,a),0,l,a,r)}export function thumbForTerminal(t,n=22){const r=process.stdout.columns||80;return pngThumbLines(t,r,e(process.env,r,!!process.stdout.isTTY),n)}export function mdImages(t){const e=[];let n=!1;for(const r of t.split("\n"))if(/^\s*(```|~~~)/.test(r))n=!n;else if(!n){for(const t of r.matchAll(/!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?[^)]*\)/g))e.push({alt:t[1],target:t[2]});for(const t of r.matchAll(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi)){const n=/\balt\s*=\s*["']([^"']*)["']/i.exec(t[0]);e.push({alt:n?n[1]:"",target:t[1]})}}return e}export function mdWithoutImages(t){return t.replace(/!\[([^\]]*)\]\(\s*<?[^)\s>]+>?[^)]*\)/g,(t,e)=>`[image: ${e||"picture"}]`).replace(/<img\b[^>]*>/gi,t=>{const e=/\balt\s*=\s*["']([^"']*)["']/i.exec(t);return`[image: ${e?.[1]||"picture"}]`})}
1
+ import{inflateSync as t}from"node:zlib";import{colorMode as e,encodeFrame as n}from"./term-video.js";const r=[137,80,78,71,13,10,26,10];export function isPng(t){return t.length>8&&r.every((e,n)=>t[n]===e)}export function decodePng(e){try{if(!isPng(e))return null;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=8,o=0,s=0,l=0,i=0,a=0,c=null,u=null;const f=[];for(;r+8<=e.length;){const t=n.getUint32(r),h=String.fromCharCode(e[r+4],e[r+5],e[r+6],e[r+7]),m=e.subarray(r+8,r+8+t);if("IHDR"===h)o=n.getUint32(r+8),s=n.getUint32(r+12),l=e[r+16],i=e[r+17],a=e[r+20];else if("PLTE"===h)c=m;else if("tRNS"===h)u=m;else if("IDAT"===h)f.push(m);else if("IEND"===h)break;r+=12+t}const h={0:1,2:3,3:1,4:2,6:4}[i];if(!o||!s||!h||0!==a||8!==l&&16!==l||o*s>4e7)return null;if(3===i&&(!c||8!==l))return null;const m=h*(l/8),g=o*m;let p=0;for(const t of f)p+=t.length;const d=new Uint8Array(p);let M=0;for(const t of f)d.set(t,M),M+=t.length;const b=t(d);if(b.length<(g+1)*s)return null;const x=new Uint8Array(g);let w=new Uint8Array(g);const y=new Uint8Array(o*s*4),A=l/8;for(let t=0;t<s;t++){const e=t*(g+1),n=b[e];for(let t=0;t<g;t++){const r=b[e+1+t],o=t>=m?x[t-m]:0,s=w[t],l=t>=m?w[t-m]:0;let i;if(0===n)i=r;else if(1===n)i=r+o;else if(2===n)i=r+s;else if(3===n)i=r+(o+s>>1);else{if(4!==n)return null;{const t=Math.abs(s-l),e=Math.abs(o-l),n=Math.abs(o+s-2*l);i=r+(t<=e&&t<=n?o:e<=n?s:l)}}x[t]=255&i}for(let e=0;e<o;e++){const n=e*m,r=4*(t*o+e);if(0===i)y[r]=y[r+1]=y[r+2]=x[n],y[r+3]=255;else if(2===i)y[r]=x[n],y[r+1]=x[n+A],y[r+2]=x[n+2*A],y[r+3]=255;else if(3===i){const t=3*x[n];y[r]=c[t]??0,y[r+1]=c[t+1]??0,y[r+2]=c[t+2]??0,y[r+3]=u&&x[n]<u.length?u[x[n]]:255}else 4===i?(y[r]=y[r+1]=y[r+2]=x[n],y[r+3]=x[n+A]):(y[r]=x[n],y[r+1]=x[n+A],y[r+2]=x[n+2*A],y[r+3]=x[n+3*A])}w=x.slice()}return{w:o,h:s,data:y}}catch{return null}}export function thumbSize(t,e,n,r=22){const o=Math.max(16,Math.min(100,n-6)),s=2*r,l=Math.min(o/t,s/e,4),i=Math.max(2,Math.round(t*l));let a=Math.max(2,Math.round(e*l));return a%2&&(a+=1),{w:i,h:a}}export function resample(t,e,n){const r=new Uint8Array(e*n*3);for(let o=0;o<n;o++){const s=Math.floor(o*t.h/n),l=Math.max(s+1,Math.floor((o+1)*t.h/n));for(let n=0;n<e;n++){const i=Math.floor(n*t.w/e),a=Math.max(i+1,Math.floor((n+1)*t.w/e));let c=0,u=0,f=0,h=0;for(let e=s;e<l&&e<t.h;e++)for(let n=i;n<a&&n<t.w;n++){const r=4*(e*t.w+n),o=t.data[r+3]/255;c+=t.data[r]*o+255*(1-o),u+=t.data[r+1]*o+255*(1-o),f+=t.data[r+2]*o+255*(1-o),h++}const m=3*(o*e+n);r[m]=h?Math.round(c/h):255,r[m+1]=h?Math.round(u/h):255,r[m+2]=h?Math.round(f/h):255}}return r}export function pngThumbLines(t,e,r,o=22){if("none"===r)return[];const s=decodePng(t);if(!s)return[];const{w:l,h:i}=thumbSize(s.w,s.h,e,o);return n(resample(s,l,i),0,l,i,r)}export function thumbMode(t,n,r){const o=e(t,n,r);return"truecolor"===o&&"truecolor"!==t.ICOA_THUMB?"256":o}export function thumbForTerminal(t,e=22){const n=process.stdout.columns||80;return pngThumbLines(t,n,thumbMode(process.env,n,!!process.stdout.isTTY),e)}export function mdImages(t){const e=[];let n=!1;for(const r of t.split("\n"))if(/^\s*(```|~~~)/.test(r))n=!n;else if(!n){for(const t of r.matchAll(/!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?[^)]*\)/g))e.push({alt:t[1],target:t[2]});for(const t of r.matchAll(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi)){const n=/\balt\s*=\s*["']([^"']*)["']/i.exec(t[0]);e.push({alt:n?n[1]:"",target:t[1]})}}return e}export function mdWithoutImages(t){return t.replace(/!\[([^\]]*)\]\(\s*<?[^)\s>]+>?[^)]*\)/g,(t,e)=>`[image: ${e||"picture"}]`).replace(/<img\b[^>]*>/gi,t=>{const e=/\balt\s*=\s*["']([^"']*)["']/i.exec(t);return`[image: ${e?.[1]||"picture"}]`})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.714",
3
+ "version": "2.19.715",
4
4
  "description": "ICOA CLI — AI-native competition runtime of the International Cyber Olympiad in AI: learn, practise, and compete in AI & cybersecurity from the terminal (AI4CTF · CTF4AI · CTF4EAI)",
5
5
  "author": "Charlie Zhu",
6
6
  "type": "module",