icoa-cli 2.19.683 → 2.19.684

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{createInterface as e,Interface as o}from"node:readline";import chalk from"chalk";import{getDeviceFingerprint as t}from"../lib/access.js";import{getMainRl as n}from"../lib/main-rl.js";const s=(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"");let i=[],a=null,l=null;function r(o){return new Promise(t=>{const s=n();if(s)return l=t,s.setPrompt(o),void s.prompt();const i=e({input:process.stdin,output:process.stdout});i.question(o,e=>{i.close(),t(e)})})}let c="en";const g={banner:{en:"[🧪 Committee GPU sandbox — clean 40-pkg IOAI environment]",zh:"[🧪 命题组 GPU 沙箱 — 纯净 40 包 IOAI 标准环境]"},langTip:{en:"Tip: type lang zh anytime to switch to 中文 (default English).",zh:"提示:随时输入 lang en 切回英文。"},tokenAsk:{en:"Enter your committee access token: ",zh:"请输入命题组访问 token:"},tokenBad:{en:"Token not recognised — check for typos and try again.",zh:"token 无效 — 请检查拼写后重试。"},tokenDevice:{en:"This token is bound to another computer. One token = one device — use your own token on this machine.",zh:"这枚 token 已绑定在另一台电脑上。一枚 token 只绑一台设备 — 请在本机使用你自己的 token。"},tokenGiveUp:{en:"Three failed attempts — ask your coordinator to verify your token.",zh:"连续三次失败 — 请联系协调人核对你的 token。"},hoursAsk:{en:"Session length? [1] 1 hour [2] 2 hours [3] 3 hours [5] 5 hours: ",zh:"选择时长? [1] 1 小时 [2] 2 小时 [3] 3 小时 [5] 5 小时:"},hoursBad:{en:"Please type 1, 2, 3 or 5.",zh:"请输入 1、2、3 或 5。"},seatsBusy:{en:"All 3 committee seats are in use right now — try again in a little while.",zh:"3 个并发席位当前全部占用 — 请稍后再试。"},already:{en:"You already have an active session — reconnecting to it.",zh:"你已有一个进行中的 session — 正在接回。"},deploying:{en:"⏳ Deploying a clean v2 box (pure 40-pkg IOAI standard env, RTX 4000 Ada) — about 13 min…",zh:"⏳ 正在部署纯净 v2 箱(40 包 IOAI 标准环境,RTX 4000 Ada)— 约 13 分钟…"},stCreating:{en:"creating the instance…",zh:"正在创建实例…"},stBooting:{en:"image restored — booting + kernel fix…",zh:"镜像展开完成 — 启动中 + 内核修正…"},stVerifying:{en:"box is up — verifying the 40-package environment…",zh:"机器已启动 — 正在校验 40 包环境…"},failed:{en:"Deployment failed: ",zh:"部署失败:"},readyTitle:{en:"✓ Your GPU box is ready (RTX 4000 Ada · 20 GB VRAM · 8 vCPU · 32 GB RAM · 512 GB disk)",zh:"✓ GPU 箱已就绪 (RTX 4000 Ada · 20 GB 显存 · 8 vCPU · 32 GB 内存 · 512 GB 磁盘)"},loginHow:{en:"Log in (password shown once — testing use, fine to display):",zh:"登录方式(密码一次性、每次不同 — 测试用,明示无妨):"},pkgsOk:{en:"✓ 40/40 IOAI-standard packages verified (per the IOAI 2026 official environment list):",zh:"✓ 40/40 个 IOAI 标准包校验通过(依据 IOAI 2026 官方环境清单):"},pkgsFree:{en:"You may pip-install anything on top — egress is open, the venv is writable, you are root.",zh:"可以随意 pip 安装任何包 — 外网开放、venv 可写、root 权限。"},killLine1:{en:"⏱ Auto-destroy at ",zh:"⏱ 自动销毁时间:"},killLine2:{en:"Everything on the box is DELETED then — copy out anything you need before that.",zh:"届时机器上的一切数据将被删除 — 需要的文件请提前拷出。"},footer:{en:"Commands: status time left · stats live GPU/RAM/disk usage · stop end early · lang zh · quit leave (box keeps running)",zh:"命令:status 剩余时间 · stats 显存/内存/磁盘占用率 · stop 提前结束 · lang en · quit 退出(机器继续运行)"},weekly:{en:"Heads-up: the committee has used {H}h of GPU since Monday — no limit, just so you know. Thanks for all the work! 🙂",zh:"小提示:命题组本周一以来累计已用 {H} 小时 GPU — 没有限制,纯提示。辛苦了 🙂"},warn10:{en:"⚠ 10 minutes left — the box auto-destroys soon. Copy out anything you need NOW.",zh:"⚠ 剩余 10 分钟 — 机器即将自动销毁,请立刻拷出需要的数据。"},stopAsk:{en:"End the session and destroy the box now? Everything on it is lost. (y/n): ",zh:"确认立即结束并销毁机器?数据将全部丢失。(y/n):"},stopping:{en:"Stopping — the box will be destroyed within a minute.",zh:"正在结束 — 机器将在一分钟内销毁。"},quitNote:{en:"Leaving this screen — your box KEEPS RUNNING until its auto-destroy time. Type gpufortask to reconnect.",zh:"已退出此界面 — 机器会继续运行到自动销毁时间。再次输入 gpufortask 可接回。"},destroyed:{en:"Session ended — the box has been destroyed.",zh:"session 已结束 — 机器已销毁。"},noStats:{en:"No utilisation sample yet — try again in ~30 s.",zh:"还没有采样数据 — 约 30 秒后再试。"},minLeft:{en:"min left",zh:"分钟剩余"},netErr:{en:"Cannot reach the broker right now — check your network and try again.",zh:"暂时连不上服务器 — 请检查网络后重试。"}},u=e=>g[e]?.[c]??e;async function d(e,o){try{const t=await fetch(`${s}/api/icoa/gputask/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(15e3)}),n=await t.json();return n.data??n}catch{return null}}function y(e){const o=e.stats;if(!o)return void console.log(chalk.gray(` ${u("noStats")}`));const t=Math.max(0,Math.round(Date.now()/1e3-Number(o.at||0)));console.log(chalk.bold.cyan("zh"===c?" 实时占用":" Live utilisation")+chalk.gray(` (${t}s ago)`)),console.log(chalk.white(` GPU ${String(o.gpu_util_pct).padStart(3)}%`)+chalk.gray(" · ")+chalk.white(`VRAM ${o.vram_used_mb}/${o.vram_total_mb} MB`)+chalk.gray(" · ")+chalk.white(`${o.temp_c}°C · ${o.power_w} W`)),console.log(chalk.white(` RAM ${o.ram_used_mb}/${o.ram_total_mb} MB`)+chalk.gray(" · ")+chalk.white(`disk ${o.disk_used}/${o.disk_total} (${o.disk_pct})`)),console.log(chalk.bold.cyan("zh"===c?" RTX 4000 Ada 规格":" RTX 4000 Ada — card specs")),console.log(chalk.gray(" CUDA cores 6144 · Compute Capability 8.9 (sm_89) · FP32 ~26.7 TFLOPS")),console.log(chalk.gray(" VRAM 20 GB GDDR6 ECC · bandwidth ~360 GB/s · TDP 130 W · CUDA 12.6 (cu126 wheels)")),console.log(chalk.gray("zh"===c?" 整机:8 vCPU · 32 GB 内存 · 512 GB 磁盘 · Ubuntu 25.10 · Python 3.13":" Box: 8 vCPU · 32 GB RAM · 512 GB disk · Ubuntu 25.10 · Python 3.13"))}function h(e){console.log(),console.log(chalk.bold.green(` ${u("readyTitle")}`)),console.log(),console.log(chalk.white(` ${u("loginHow")}`)),console.log(chalk.bold.cyan(` ssh root@${e.ip}`)),console.log(chalk.bold.white(" password: ")+chalk.bold.yellow(e.root_pass??"?")),console.log(),console.log(chalk.green(` ${u("pkgsOk")}`)),function(e){const o=Math.min(process.stdout.columns||120,120),t=o>=100?3:o>=66?2:1,n=Math.floor((o-4)/t)-2,s=Math.ceil(e.length/t);for(let o=0;o<s;o++){let i=" ";for(let a=0;a<t;a++){const t=e[a*s+o];t&&(i+=t.padEnd(n).slice(0,n)+" ")}console.log(chalk.white(i.trimEnd()))}}(e.pkgs??[]),console.log(chalk.gray(` ${u("pkgsFree")}`)),console.log();const o=Math.round((e.seconds_left??0)/60);var t;console.log(chalk.yellow(` ${u("killLine1")}${t=e.kill_at??0,new Intl.DateTimeFormat("en-AU",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"Australia/Sydney"}).format(new Date(1e3*t))} Sydney · ${o} ${u("minLeft")}`)),console.log(chalk.yellow(` ${u("killLine2")}`)),e.weekly_soft_over&&(console.log(),console.log(chalk.gray(` ${u("weekly").replace("{H}",String(e.weekly_hours??0))}`))),console.log(),console.log(chalk.gray(` ${u("footer")}`))}export function registerGpuForTaskCommand(e){e.command("gpufortask",{hidden:!0}).description("Committee GPU sandbox — clean 40-pkg IOAI environment (hidden)").action(async()=>{try{await async function(){c="en",function(){const e=n();e&&(i=e.listeners("line").slice(),e.removeAllListeners("line"),a=e.prompt.bind(e),e.prompt=o.prototype.prompt.bind(e),e.on("line",e=>{const o=l;l=null,o&&o(e)}))}();let e=null;try{console.log(),console.log(chalk.cyan.bold(` ${u("banner")}`)),console.log(chalk.gray(` ${u("langTip")}`)),console.log();const e=t();let o="";for(let t=0;t<3;){const n=(await r(chalk.cyan(` ${u("tokenAsk")}`))).trim(),i=n.toLowerCase();if("lang zh"===i){c="zh";continue}if("lang en"===i){c="en";continue}if("quit"===i||"back"===i||""===n){if(""===n)continue;return}const a=n.toUpperCase().replace(/\s+/g,""),l=await d("status",{token:a,fp:e});if(null===l)return void console.log(chalk.yellow(` ${u("netErr")}`));if("token_device_mismatch"!==l.error){if(!l.error){if(o=a,"none"!==l.state)return console.log(chalk.gray(` ${u("already")}`)),void await s(o,e,l);break}console.log(chalk.yellow(` ${u("tokenBad")}`)),t++}else console.log(chalk.yellow(` ${u("tokenDevice")}`)),t++}if(!o)return void console.log(chalk.yellow(` ${u("tokenGiveUp")}`));let n=0;for(;0===n;){const e=(await r(chalk.cyan(` ${u("hoursAsk")}`))).trim().toLowerCase();if("lang zh"===e){c="zh";continue}if("lang en"===e){c="en";continue}if("quit"===e||"back"===e)return;const o=Number.parseInt(e.replace(/\D/g,""),10);[1,2,3,5].includes(o)?n=o:console.log(chalk.yellow(` ${u("hoursBad")}`))}const i=await d("start",{token:o,fp:e,hours:n});if(null===i)return void console.log(chalk.yellow(` ${u("netErr")}`));if("all_seats_busy"===i.error)return void console.log(chalk.yellow(` ${u("seatsBusy")}`));if("session_already_active"===i.error){const t=await d("status",{token:o,fp:e});return void(t&&await s(o,e,t))}console.log(chalk.gray(` ${u("deploying")}`)),await s(o,e,i)}finally{e&&clearInterval(e),function(){const e=n();if(e){e.removeAllListeners("line"),a&&(e.prompt=a);for(const o of i)e.on("line",o);i=[],a=null,l=null}}()}async function s(o,t,n){let s=n,i="";const a=Date.now();for(;s&&"ready"!==s.state;){if("failed"===s.state||"destroyed"===s.state)return void console.log(chalk.red(` ${u("failed")}${s.fail_reason??s.state}`));const e="pending"===s.state||"creating"===s.state?u("stCreating"):"booting"===s.state?u("stBooting"):u("stVerifying");if(e!==i){const o=Math.round((Date.now()-a)/6e4);console.log(chalk.gray(` [${o}m] ${e}`)),i=e}await new Promise(e=>setTimeout(e,1e4)),s=await d("status",{token:o,fp:t})}if(!s)return void console.log(chalk.yellow(` ${u("netErr")}`));h(s);let l=!1;for(e=setInterval(async()=>{const e=await d("status",{token:o,fp:t});e&&!l&&"ready"===e.state&&(e.seconds_left??0)>0&&(e.seconds_left??0)<=600&&(l=!0,console.log(),console.log(chalk.bold.yellow(` ${u("warn10")}`)))},6e4);;){const e=(await r(chalk.cyan("icoa gpufortask> "))).trim().toLowerCase();if(""!==e)if("lang zh"!==e)if("lang en"!==e){if("quit"===e||"back"===e||"exit"===e)return void console.log(chalk.gray(` ${u("quitNote")}`));if("status"===e||"s"===e||"time"===e){const e=await d("status",{token:o,fp:t});if(e){if("ready"!==e.state)return void console.log(chalk.gray(` ${u("destroyed")}`));h(e)}else console.log(chalk.yellow(` ${u("netErr")}`));continue}if("stats"===e||"stat"===e||"usage"===e||"top"===e){const e=await d("status",{token:o,fp:t});if(e){if("ready"!==e.state)return void console.log(chalk.gray(` ${u("destroyed")}`));y(e)}else console.log(chalk.yellow(` ${u("netErr")}`));continue}if("stop"===e||"end"===e||"destroy"===e){const e=(await r(chalk.yellow(` ${u("stopAsk")}`))).trim().toLowerCase();if("y"===e||"yes"===e)return await d("stop",{token:o,fp:t}),void console.log(chalk.green(` ${u("stopping")}`));continue}console.log(chalk.gray(` ${u("footer")}`))}else c="en",console.log(chalk.gray(` ${u("footer")}`));else c="zh",console.log(chalk.gray(` ${u("footer")}`))}}}()}catch(e){const o=e instanceof Error?e.message:String(e);if("__REPL_NO_EXIT__"===o)throw e;console.log(chalk.yellow("\n gpufortask ended: "+o))}})}
1
+ import{createInterface as e,Interface as o}from"node:readline";import{mkdirSync as t,writeFileSync as n}from"node:fs";import{homedir as s}from"node:os";import{join as a}from"node:path";import chalk from"chalk";import{getDeviceFingerprint as i}from"../lib/access.js";import{clearCommitteeSession as r,readCommitteeSession as l,TIER_LABEL as c,writeCommitteeSession as d}from"../lib/gputask-session.js";import{getMainRl as u}from"../lib/main-rl.js";const p=(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"");let g=[],y=null,h=null,f=[];function m(o){return new Promise(t=>{const n=u();if(n){const e=f.shift();return void 0!==e?(process.stdout.write(`${o}${e}\n`),void t(e)):(h=t,n.setPrompt(o),void n.prompt())}const s=e({input:process.stdin,output:process.stdout});s.question(o,e=>{s.close(),t(e)})})}let k="en";const w={banner:{en:"[🧪 Committee GPU sandbox — GCP T4 · IOAI standard environment]",zh:"[🧪 命题组 GPU 沙箱 — GCP T4 · IOAI 标准环境]"},langTip:{en:"Tip: type lang zh anytime to switch to 中文 (default English).",zh:"提示:随时输入 lang en 切回英文。"},tokenAsk:{en:"Enter your committee access token: ",zh:"请输入命题组访问 token:"},tokenBad:{en:"Token not recognised — check for typos and try again.",zh:"token 无效 — 请检查拼写后重试。"},tokenDevice:{en:"This token is bound to another computer. One token = one device — use your own token on this machine.",zh:"这枚 token 已绑定在另一台电脑上。一枚 token 只绑一台设备 — 请在本机使用你自己的 token。"},tokenGiveUp:{en:"Three failed attempts — ask your coordinator to verify your token.",zh:"连续三次失败 — 请联系协调人核对你的 token。"},tierAsk:{en:"Seat? [1] T4 capsule 3.5 GiB (default, fits tasks ≤ 3 GiB) [2] T4 whole card 16 GB [3] CPU only: ",zh:"席位? [1] T4 胶囊 3.5 GiB(默认,题目 ≤ 3 GiB 用这个) [2] T4 整卡 16 GB [3] 只要 CPU:"},tierBad:{en:"Please type 1, 2 or 3 (Enter = 1).",zh:"请输入 1、2 或 3(回车 = 1)。"},modeAsk:{en:"Spot box (cheapest; the cloud may reclaim it — we rebuild in 1–2 min, files kept). Enter = Spot, type ondemand for a guaranteed box: ",zh:"Spot 箱(最便宜;云可能收回 — 我们 1–2 分钟内重建,文件不丢)。回车 = Spot,输入 ondemand 要一台不会被收回的:"},seatsBusy:{en:"All committee seats are in use right now — try again in a little while.",zh:"席位当前全部占用 — 请稍后再试。"},dailyCap:{en:"Today's spend is over the US$5/day cap — on-demand is off; a Spot seat is still fine.",zh:"今天花费已超每日 5 美元上限 — 按需关闭;Spot 席位仍可用。"},capWarn:{en:"Note: today's spend is over the US$5/day cap — Spot only from here.",zh:"注意:今天花费已超每日 5 美元上限 — 之后只给 Spot。"},ctlDown:{en:"The box builder is not reachable right now — tell the coordinator; try again in a few minutes.",zh:"建箱机暂时联系不上 — 请告知协调人;几分钟后再试。"},already:{en:"You already have an active seat — reconnecting to it.",zh:"你已有一个进行中的席位 — 正在接回。"},deploying:{en:"⚡ Starting your box — about 1–2 minutes (a fresh T4 if none has a free seat)…",zh:"⚡ 正在开机 — 约 1–2 分钟(没有空位时会新起一台 T4)…"},stCreating:{en:"creating the box…",zh:"正在建箱…"},stProvisioning:{en:"box is up — adding your user and fence…",zh:"机器已启动 — 正在建你的用户与围栏…"},stPreempted:{en:"⚠ the cloud reclaimed the GPU — rebuilding on another box (1–2 min). Files are kept; variables need a re-run.",zh:"⚠ 云收回了这台 GPU — 正在换一台重建(1–2 分钟)。文件都在,变量要重跑。"},failed:{en:"Could not start a seat: ",zh:"开机失败:"},readyTitle:{en:"✓ Your seat is ready",zh:"✓ 席位已就绪"},how1:{en:"How to use it (the notebook runs its cells on the box):",zh:"怎么用(notebook 的格子在箱上跑):"},how2:{en:"open your notebook",zh:"打开你的 notebook"},how3:{en:"cells now run on the box · same-folder files sync automatically",zh:"格子改在箱上跑 · 同目录文件自动同步"},how4:{en:"send one file to the box (data, weights)",zh:"把一个文件送上箱(数据、权重)"},advanced:{en:"Advanced — your own user, no sudo, others cannot see your files:",zh:"进阶 — 你自己的用户,无 sudo,别人看不见你的文件:"},clock:{en:"⏱ Ends after 40 min idle · files in /home/{U} are kept and restored next time",zh:"⏱ 闲置 40 分钟自动结束 · /home/{U} 的文件会保留,下次恢复"},spend:{en:"today's spend {A} of {B}",zh:"今日花费 {A} / {B}"},footer:{en:"Commands: status seat + GPU usage · stop end now · lang zh · quit leave (seat stays until idle)",zh:"命令:status 席位与 GPU 占用 · stop 立即结束 · lang en · quit 退出(席位到闲置为止)"},stopAsk:{en:"End the seat now? Your files are synced first and restored next time. (y/n): ",zh:"确认立即结束?文件会先同步保存,下次恢复。(y/n):"},stopping:{en:"Stopping — files syncing, seat released within a minute.",zh:"正在结束 — 文件同步中,一分钟内释放席位。"},quitNote:{en:"Leaving this screen — the seat KEEPS RUNNING until 40 min idle. Type gpufortask to come back.",zh:"已退出此界面 — 席位会一直保留到闲置 40 分钟。再次输入 gpufortask 可接回。"},ended:{en:"Seat ended",zh:"席位已结束"},netErr:{en:"Cannot reach the broker right now — check your network and try again.",zh:"暂时连不上服务器 — 请检查网络后重试。"},idle:{en:"idle",zh:"闲置"},busy:{en:"busy",zh:"忙"},weekly:{en:"Heads-up: the committee has used {H}h of GPU since Monday — no limit, just so you know. 🙂",zh:"小提示:命题组本周一以来累计已用 {H} 小时 GPU — 没有限制,纯提示 🙂"}},$=e=>w[e]?.[k]??e;async function b(e,o){try{const t=await fetch(`${p}/api/icoa/gputask/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(25e3)}),n=await t.json();return n.data??n}catch{return null}}function z(e,o){if(!(o.sid&&o.tier&&o.host&&o.user&&o.python&&o.out_dir&&o.key_pem))return null;const i={sid:o.sid,token:e,tier:o.tier,host:o.host,port:o.port??22,user:o.user,python:o.python,outDir:o.out_dir,keyPem:o.key_pem,seenAt:Math.floor(Date.now()/1e3)};try{d(i),t(a(s(),".icoa","gputask"),{recursive:!0}),n(a(s(),".icoa","gputask","key"),o.key_pem,{mode:384})}catch{return null}return i}function v(e){return`$${(e??0).toFixed(2)}`}function _(e){const o=e.user??"?";console.log(),console.log(chalk.bold.green(` ${$("readyTitle")}`)+chalk.gray(` ${c[e.tier??"t4"]} · ${e.zone??""} · ${"ondemand"===e.mode?"on-demand":"Spot"}`)),console.log(),console.log(chalk.white(` ${$("how1")}`)),console.log(chalk.bold.cyan(" icoa> ipynb ~/Desktop/task.ipynb")+chalk.gray(` ${$("how2")}`)),console.log(chalk.bold.cyan(" icoa ipynb> gpu on")+chalk.gray(` ${$("how3")}`)),console.log(chalk.bold.cyan(" icoa ipynb> upload data.csv")+chalk.gray(` ${$("how4")}`)),console.log(),console.log(chalk.gray(` ${$("advanced")}`)),console.log(chalk.gray(` ssh -i ~/.icoa/gputask/key ${o}@${e.host??"?"}`)),console.log(),console.log(chalk.yellow(` ${$("clock").replace("{U}",o)}`)),console.log(chalk.gray(` ${$("spend").replace("{A}",v(e.today_usd)).replace("{B}",v(e.daily_cap_usd??5))}`)+chalk.gray(` · ${e.rate??"?"}/h`)),e.weekly_soft_over&&console.log(chalk.gray(` ${$("weekly").replace("{H}",String(e.weekly_hours??0))}`)),console.log(),console.log(chalk.gray(` ${$("footer")}`))}function P(e){const o=e.idle_min??0,t=e.idle_limit_min??40;console.log(chalk.bold.cyan(" seat ")+chalk.white(`${e.state}`)+chalk.gray(` · ${e.tier} · ${e.mode} · ${e.zone??""} · ${Math.round(e.minutes??0)} min`));const n=e.busy;console.log(chalk.gray(" you: ")+(n?.busy?chalk.green(`${$("busy")} (${n.why})`):chalk.yellow(`${$("idle")} ${o}/${t} min`))+(n?.home_kb?chalk.gray(` · home ${Math.round(n.home_kb/1024)} MB`):"")),e.gpu&&"number"==typeof e.gpu.util&&console.log(chalk.gray(` card: GPU ${e.gpu.util}% · VRAM ${e.gpu.mem_used_mb}/${e.gpu.mem_total_mb} MB (whole card, all seats)`)),e.preempt_count&&console.log(chalk.gray(` reclaimed ${e.preempt_count}× today${e.note?` · ${e.note}`:""}`)),console.log(chalk.gray(` ${$("spend").replace("{A}",v(e.today_usd)).replace("{B}",v(e.daily_cap_usd??5))}`))}export function registerGpuForTaskCommand(e){e.command("gpufortask",{hidden:!0}).description("Committee GPU sandbox — GCP T4 capsule, IOAI standard environment (hidden)").action(async()=>{try{await async function(){k="en",function(){const e=u();e&&(g=e.listeners("line").slice(),e.removeAllListeners("line"),y=e.prompt.bind(e),e.prompt=o.prototype.prompt.bind(e),e.on("line",e=>{const o=h;h=null,o?o(e):f.push(e)}))}();try{console.log(),console.log(chalk.cyan.bold(` ${$("banner")}`)),console.log(chalk.gray(` ${$("langTip")}`)),console.log();const e=i(),o=l();let n="";for(let s=0;s<3;){const a=(await m(chalk.cyan(` ${$("tokenAsk")}`)+(o?chalk.gray(`[${o.token}] `):""))).trim(),i=a.toLowerCase();if("lang zh"===i){k="zh";continue}if("lang en"===i){k="en";continue}if("quit"===i||"back"===i)return;const l=""===a&&o?o.token:a.toUpperCase().replace(/\s+/g,"");if(!l)continue;const c=await b("status",{token:l,fp:e});if(null===c)return void console.log(chalk.yellow(` ${$("netErr")}`));if("token_device_mismatch"!==c.error){if(!c.error){if(n=l,"none"!==c.state)return console.log(chalk.gray(` ${$("already")}`)),void await t(n,e,c);o&&r(),c.last_ended&&console.log(chalk.gray(` (your previous seat ended: ${c.last_ended} — files were kept)`));break}console.log(chalk.yellow(` ${$("tokenBad")}`)),s++}else console.log(chalk.yellow(` ${$("tokenDevice")}`)),s++}if(!n)return void console.log(chalk.yellow(` ${$("tokenGiveUp")}`));let s="";for(;!s;){const e=(await m(chalk.cyan(` ${$("tierAsk")}`))).trim().toLowerCase();if("lang zh"!==e)if("lang en"!==e){if("quit"===e||"back"===e)return;""===e||"1"===e||e.includes("capsule")||e.includes("胶囊")?s="t4":"2"===e||e.includes("whole")||e.includes("full")||e.includes("整卡")?s="t4full":"3"===e||e.includes("cpu")?s="cpu":console.log(chalk.yellow(` ${$("tierBad")}`))}else k="en";else k="zh"}let a="spot";for(;;){const e=(await m(chalk.cyan(` ${$("modeAsk")}`))).trim().toLowerCase();if("lang zh"!==e)if("lang en"!==e){if("quit"===e||"back"===e)return;if(""===e||"spot"===e||"s"===e)break;if(e.startsWith("on")||"od"===e||"demand"===e||"按需"===e){a="ondemand";break}}else k="en";else k="zh"}const c=await b("start",{token:n,fp:e,tier:s,mode:a});if(null===c)return void console.log(chalk.yellow(` ${$("netErr")}`));if("all_seats_busy"===c.error)return void console.log(chalk.yellow(` ${$("seatsBusy")}`));if("daily_cap"===c.error)return void console.log(chalk.yellow(` ${$("dailyCap")}`));if("ctl_unavailable"===c.error)return void console.log(chalk.yellow(` ${$("ctlDown")}`)+chalk.gray(c.detail?` (${c.detail})`:""));if("session_already_active"===c.error){const o=await b("status",{token:n,fp:e});return void(o&&await t(n,e,o))}if(c.error)return void console.log(chalk.yellow(` ${$("failed")}${c.error}`));c.cap_warning&&console.log(chalk.yellow(` ${$("capWarn")}`)),console.log(chalk.gray(` ${$("deploying")}`)),await t(n,e,c)}finally{!function(){const e=u();if(e){e.removeAllListeners("line"),y&&(e.prompt=y);for(const o of g)e.on("line",o);g=[],y=null,h=null,f=[]}}()}async function e(e,o,t){let n=t,s="",a=0;const i=Date.now();for(;n&&"ready"!==n.state;){if("failed"===n.state||"ended"===n.state||"none"===n.state||"stopping"===n.state)return console.log(chalk.red(` ${$("failed")}${n.end_reason??n.state}`)),r(),null;const t="creating"===n.state?$("stCreating"):"preempted"===n.state?$("stPreempted"):$("stProvisioning");if(t!==s){const e=Math.round((Date.now()-i)/1e3);console.log(chalk.gray(` [${e}s] `)+("preempted"===n.state?chalk.yellow(t):chalk.gray(t))),s=t}if(Date.now()-i>72e4)return console.log(chalk.yellow(` still starting after ${Math.round(12)} min — type gpufortask again later; the seat is held.`)),null;await new Promise(e=>setTimeout(e,5e3));const l=await b("status",{token:e,fp:o});if(null===l){if(a++,a<=5){console.log(chalk.gray(` (broker did not answer — retrying ${a}/5)`));continue}n=null;break}a=0,n=l}return n||(console.log(chalk.yellow(` ${$("netErr")}`)),console.log(chalk.gray(" The seat is still being built server-side — type gpufortask again in a minute to pick it up.")),null)}async function t(o,t,n){const s=await e(o,t,n);if(s)for(z(o,s)||console.log(chalk.yellow(" could not save the session file under ~/.icoa/gputask — gpu on will not find this seat.")),_(s);;){const n=(await m(chalk.cyan("icoa gpufortask> "))).trim().toLowerCase();if(""!==n)if("lang zh"!==n&&"lang en"!==n){if("quit"===n||"back"===n||"exit"===n||"menu"===n)return void console.log(chalk.gray(` ${$("quitNote")}`));if("status"===n||"s"===n||"time"===n||"stats"===n||"top"===n){const n=await b("status",{token:o,fp:t});if(n)if("ready"===n.state)n.host&&n.key_pem&&z(o,n),P(n);else{if("preempted"!==n.state&&"provisioning"!==n.state&&"creating"!==n.state)return console.log(chalk.gray(` ${$("ended")} (${n.end_reason??n.state})`)),void r();{console.log(chalk.yellow(` ${$("stPreempted")}`));const s=await e(o,t,n);if(!s)return;z(o,s),_(s)}}else console.log(chalk.yellow(` ${$("netErr")}`));continue}if("stop"===n||"end"===n||"destroy"===n||"release"===n){const e=(await m(chalk.yellow(` ${$("stopAsk")}`))).trim().toLowerCase();if("y"===e||"yes"===e)return await b("stop",{token:o,fp:t}),r(),void console.log(chalk.green(` ${$("stopping")}`));continue}console.log(chalk.gray(` ${$("footer")}`))}else k=n.endsWith("zh")?"zh":"en",console.log(chalk.gray(` ${$("footer")}`))}}}()}catch(e){const o=e instanceof Error?e.message:String(e);if("__REPL_NO_EXIT__"===o)throw e;console.log(chalk.yellow("\n gpufortask ended: "+o))}})}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as o,readFileSync as n,statSync as t,writeFileSync as l}from"node:fs";import{homedir as r}from"node:os";import{Interface as a,createInterface as s}from"node:readline";import{basename as i,dirname as c,isAbsolute as g,join as y,resolve as d}from"node:path";import chalk from"chalk";import{aienvPaths as u}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as h,askIoaiOneShot as p}from"./ai4ioai.js";import{getConfig as m,saveConfig as f}from"../lib/config.js";import{editTextInEditor as w,editorInstalled as b,editorLabel as k,namedEditor as v,resolveEditor as $}from"../lib/editor-spawn.js";import{buildSshArgs as x,leaseConnectProblems as P,parseLeaseResponse as E,queueLine as S,windowLine as C}from"../lib/gpu.js";import{shouldExecuteCell as G}from"../lib/ipynb-input.js";import{looksLikeMarkdown as j,renderMarkdown as I}from"../lib/md-term.js";import{NotebookKernel as A,buildRemoteBridgeCommand as N}from"../lib/kernel.js";import{getMainRl as U,setMainRl as O}from"../lib/main-rl.js";import{logCommand as q}from"../lib/logger.js";import{startLogSync as T,stopLogSync as L}from"../lib/log-sync.js";import{cellPreview as M,mergeReloadedCells as _,normalizePathArg as R,parseIpynb as D,parsePercentPy as K,parseRunRange as B,serializeIpynb as W,statusChar as J}from"../lib/notebook-doc.js";import{openFile as V}from"../lib/open-file.js";const Y=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function z(){return(m().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(e){e.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async e=>{await runIpynb(e)})}function F(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const X=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),H=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function Q(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const Z="https://practice.icoa2026.au";function ee(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):Z}function oe(){return y(r(),".icoa","gpu-key")}function ne(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(oe(),"utf-8").trim()||null}catch{return null}}async function te(e,o,n){try{const t=await fetch(`${ee()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await t.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function le(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let re=0,ae=null;function se(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(Y,"")}`))}else"display"===n.kind&&ie(n.data,o)}function ie(e,n){if(e["image/png"])try{o(n,{recursive:!0}),re+=1;const t=y(n,`figure-${re}.png`);return l(t,Buffer.from(e["image/png"],"base64")),ae=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(V(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}function ce(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function ge(e){if(e)try{return t(e).mtimeMs}catch{return}}function ye(o){const t=R(o,r()),l=g(t)?t:d(process.cwd(),t);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?D(e):K(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:ge(l),diskSig:ce(o)},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}export async function runIpynb(t){const E=u(r()),Z=y(r(),".icoa","ipynb-out");if(F(),!e(E.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const re=t?ye(t):null,ie=re?re.doc:{cells:[],path:null,dirty:!1};let de=new A({venvPython:E.python,venvRoot:E.root}),ue=null,he=le(ie.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await de.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),re&&console.log(re.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const pe=U(),me=null!==pe,fe=me?pe.listeners("line").slice():[];me&&pe.removeAllListeners("line");const we=me?pe:s({input:process.stdin,output:process.stdout,terminal:!0});me||O(we);const be=me?we.prompt:null,ke=me?we.getPrompt():"";me&&(we.prompt=a.prototype.prompt),me||T();const ve=[];let $e,xe=!1,Pe=!1,Ee=!1,Se=null,Ce=null;const Ge=()=>{if(Ce)return we.setPrompt(chalk.bold.cyan(` editor 1-${Ce.options.length} > `)),void we.prompt();const e=ue?"icoa ipynb ⚡gpu":"icoa ipynb";we.setPrompt(chalk.bold.cyan(ve.length?`${e} ...> `:`${e}> `)),we.prompt()};let je=()=>{};const Ie=new Promise(e=>{je=e}),Ae=async e=>{const[n,...t]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(ue)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=ne();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));he||(he=le(ie.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await te("lease",e,he??void 0),t=0;for(;"queued"===n.state&&t<24;)0===t&&console.log(),process.stdout.write(`\r ${chalk.yellow(S(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await te("status",e),t++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=P(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await te("release",e);const s=he?`${n.dataRoot}/${he}`:n.dataRoot,i=N(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let c;if("local"===n.transport)c={command:"/bin/sh",args:["-c",i]};else{const t=y(r(),".icoa","gpu","lease-key");try{o(y(r(),".icoa","gpu"),{recursive:!0}),l(t,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await te("release",e)}c={command:"ssh",args:x(n,t,i)}}const g=new A({spawnSpec:c,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await te("release",e)}await de.shutdown().catch(()=>{}),de=g,ue=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`));const u=C(n.windowCloseEpoch);u&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${u}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),he&&console.log(chalk.gray(` Dataset is already on the box (${he}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await(async()=>{if(!ue)return void console.log(chalk.gray(" not on a GPU kernel."));const e=ne();await de.shutdown().catch(()=>{}),e&&await te("release",e),ue=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{de=new A({venvPython:E.python,venvRoot:E.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await de.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()})():"status"===a||""===a?await(async()=>{const e=ne();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await te("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(ue?" (this notebook is connected)":" (not connected here — gpu on)"));const n=C(o.windowCloseEpoch);n&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${n}.`))}else"queued"===o.state?console.log(chalk.yellow(` ${S(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=ne();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${ee()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await n.json();o=t.data??t}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,t="number"==typeof o.free?o.free:0,l=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${t} free`));const a=C("number"==typeof o.window_close_epoch?o.window_close_epoch:void 0);a&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${a}.`)),console.log(chalk.bold.white(" ▶ running now:")),0===l.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,t=Math.floor(n/60),l=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${t}:${l} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",t=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+t)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(r(),".icoa"),{recursive:!0}),l(oe(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${oe()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(t.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},Ne=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>ie.cells.length?(console.log(0===ie.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${ie.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:ie.cells[o-1],idx:o}},Ue=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let Oe=!1;const qe=()=>{const e=m().notebookEditor;return e?v(e):null},Te=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),Le=()=>qe()??$(),Me={nano:"easiest — Ctrl+O save, Ctrl+X exit",code:"VS Code window — save, close the tab to come back",vi:"i to type, Esc then :wq to save and exit"},_e=(e,o)=>{if(e){const n=v(e);return n?b(n.cmd)?(o(n),!0):(console.log(chalk.yellow(` ${k(n)} is not installed on this computer.`)+chalk.gray(" See the choices: ")+chalk.cyan("editor")),!0):(console.log(chalk.yellow(` unknown editor "${e}" — use `)+chalk.cyan("nano")+chalk.yellow(", ")+chalk.cyan("code")+chalk.yellow(" or ")+chalk.cyan("vi")),!0)}if(qe()||Te())return o(Le()),!0;const n=["nano","code","vi"].map(e=>v(e)).filter(e=>null!==e&&b(e.cmd));return n.length<2||!process.stdin.isTTY?(o($()),!0):((e=>{console.log(),console.log(chalk.bold.white(" Which editor should edit / add open?")+chalk.gray(" (asked once)")),e.forEach((e,o)=>{const n=k(e);console.log(chalk.cyan(` ${o+1} ${n.padEnd(5)}`)+chalk.gray(` ${Me[n]??""}`)+("nano"===n?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(n),Ce={resume:o,tries:0,options:n},!1)},Re=e=>{if(!ie.path)return!1;let o;try{const e=n(ie.path,"utf8");o=ie.path.endsWith(".ipynb")?D(e):K(e)}catch(e){return console.log(chalk.yellow(" could not re-read the file: ")+chalk.gray(e instanceof Error?e.message:String(e))),!1}const t=_(ie.cells,o);return ie.cells=t.cells,ie.dirty=!1,ie.mtimeMs=ge(ie.path),ie.diskSig=ce(o),$e=void 0,console.log(chalk.gray(` ↻ reloaded ${i(ie.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${t.cells.length} cells, ${t.changed} changed`)+chalk.gray(t.kept?`, ${t.kept} kept their output.`:".")),console.log(chalk.gray(" variables stay in the kernel — run just the cells you changed, or ")+chalk.cyan("run all")),!0},De=()=>void 0!==ie.diskSig?ce(ie.cells)!==ie.diskSig:ie.dirty,Ke=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!j(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),Be=async t=>{if(t.trim()&&q(`ipynb: ${t.trim()}`),Pe)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Ce){const e=Ce,o=t.trim().toLowerCase(),n=v(o),l=/^\d+$/.test(o)?e.options[Number(o)-1]:n?e.options.find(e=>k(e)===k(n)):void 0;return l?(Ce=null,f({notebookEditor:k(l)}),console.log(chalk.green(` ✓ edit / add will open ${k(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===o||["q","quit","back","cancel","exit"].includes(o)?(Ce=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Ce=null,console.log(chalk.gray(" no editor chosen — nothing changed. Choose later with ")+chalk.cyan("editor nano"))):console.log(chalk.yellow(` type a number 1-${e.options.length}, or a name: `)+chalk.cyan(e.options.map(e=>k(e)).join(" / "))),void Ge()}let a=t.trim();if(0===ve.length&&/^icoa\s+[a-z/]/i.test(a)&&(a=a.replace(/^icoa\s+/i,"")),0===ve.length){const t=a.split(/\s+/),s=(t[0]??"").toLowerCase(),u=a.slice(t[0]?.length??0).trim();if("quit"!==s&&"exit"!==s&&"q"!==s&&(Ee=!1),Se&&s!==Se&&(Se=null),H.has(s)&&(()=>{if(!ie.path||void 0===ie.mtimeMs)return;const e=ge(ie.path);if(void 0!==e&&e!==ie.mtimeMs){if(De()){if($e===e)return;return $e=e,console.log(chalk.yellow(` ⚠ ${i(ie.path)} changed in your editor, and this notebook has unsaved changes too.`)),void console.log(chalk.gray(" take the file: ")+chalk.cyan("reload")+chalk.gray(" · keep these and overwrite the file: ")+chalk.cyan("save"))}Re(!0)}})(),"quit"===s||"exit"===s||"back"===s||"q"===s||"menu"===s)return ie.dirty&&!Ee?(Ee=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ge()):void await(async()=>{if(we.removeAllListeners("line"),me||L(),console.log(),ue){const e=ne();e&&await te("release",e),ue=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await de.shutdown().catch(()=>{}),me){be&&(we.prompt=be),we.setPrompt(ke);for(const e of fe)we.on("line",e);we.prompt(),je()}else O(null),je(),we.close()})();if("clear"===s||"cls"===s)return console.clear(),F(),void Ge();if("restart"===s)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await de.shutdown().catch(()=>{});try{await de.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void Ge();if("help"===s||"?"===s)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor vi")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(z()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" load <file>")+chalk.gray(" open another .ipynb / .py (drag the file into this window)")),console.log(chalk.cyan(" reload")+chalk.gray(" re-read the file — or just save in Jupyter / VS Code: the next run picks it up")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" check / submit")+chalk.gray(" verify / score your submission.csv — right here, no quit needed")),console.log(chalk.cyan(" board")+chalk.gray(" live standings for this competition")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void Ge();if("guide"===s||"/guide"===s)return(()=>{const o=ie.path?c(ie.path):process.cwd(),t=le(ie.path);let l="",r=!1;try{const e=JSON.parse(n(y(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=ie.cells.filter(e=>null!==e.result).length,s=e(y(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(ie.path?i(ie.path):"new empty notebook")+chalk.gray(` · ${ie.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),ue?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),t&&"icoa-holdout"===l?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("submit")+chalk.gray(" — scored + ranked right here, no need to leave (")+chalk.cyan("board")+chalk.gray(" shows standings)")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):t&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):t?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void Ge();if("python"===s||"python3"===s)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void Ge();if("open"===s&&""===u)return ae&&V(ae)?console.log(chalk.gray(" reopening ")+chalk.cyan(ae)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ge();if("cells"===s||"ls"===s)return(()=>{if(0===ie.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);ie.cells.forEach((o,n)=>{const t=J(o),l="✓"===t?chalk.green(t.padEnd(2)):"✗"===t?chalk.red(t.padEnd(2)):"md"===t?chalk.magenta(t.padEnd(2)):chalk.gray(t.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${l} ${chalk.white(M(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void Ge();if("show"===s)return(e=>{const o=Ne(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of I(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),se(o.cell.result,Z)),console.log()}})(u),void Ge();if("edit"===s){const[e,o]=u.split(/\s+/);return Ne(e??"")&&_e(o,o=>((e,o)=>{const n=Ne(e);if(!n)return;we.pause();const t=w(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(we.resume(),null===t)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=t.replace(/\s+$/,"");l!==n.cell.source?(n.cell.source=l,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,ie.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(e,o)),void Ge()}if("add"===s){const e=u.split(/\s+/).filter(Boolean),o=e.find(e=>null!==v(e)),n=e.filter(e=>e!==o).join(" ");return _e(o,e=>((e,o)=>{const n=e.trim().toLowerCase(),t="md"===n||"markdown"===n||"text"===n||"txt"===n;if(n&&!t&&"py"!==n&&"code"!==n&&"python"!==n)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));we.pause();const l=w(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);we.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(ie.cells.push({kind:t?"markdown":"code",source:r,result:null}),ie.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${ie.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${ie.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void Ge()}if("editor"===s&&/^[\w-]*$/.test(u))return(e=>{const o=e.trim().toLowerCase(),n=k(Le());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${qe()?"saved":Te()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=v(e),t=b(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(t?` ${Me[e]}`:" not installed here")+(e===n?chalk.green(" ← now"):""))}return console.log(chalk.gray(" one edit only: ")+chalk.cyan("edit 3 nano")+chalk.gray(" · back to $EDITOR / vi: ")+chalk.cyan("editor default")),void console.log()}if("default"===o||"reset"===o||"off"===o)return f({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${k($())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const t=v(o);if(!t)return void console.log(chalk.yellow(` unknown editor "${o}" — `)+chalk.cyan("editor nano")+chalk.yellow(" · ")+chalk.cyan("editor code")+chalk.yellow(" · ")+chalk.cyan("editor vi"));const l=k(t);qe()&&k(qe())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):b(t.cmd)?(f({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${n===l?"default":n}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(u),void Ge();if("reload"===s&&""===u)return ie.path&&e(ie.path)?De()&&"reload"!==Se?(Se="reload",console.log(chalk.yellow(" unsaved changes here will be replaced by the file — ")+chalk.cyan("reload")+chalk.yellow(" again to go ahead, or ")+chalk.cyan("save")+chalk.yellow(" first."))):(Se=null,Re(!1)):console.log(chalk.gray(" nothing to reload — this notebook has no file yet (")+chalk.cyan("save")+chalk.gray(" first, or ")+chalk.cyan("load <file>")+chalk.gray(").")),void Ge();if("load"===s&&!/^[=(.[]/.test(u)||"open"===s&&""!==u){if(!u)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ge();const o=R(u,r()),n=g(o)?o:d(process.cwd(),o);if(e(n))if(ie.dirty&&"load"!==Se)Se="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(s)+chalk.yellow(" again to discard them."));else{Se=null;const e=ye(n);ie.cells=e.doc.cells,ie.path=e.doc.path,ie.dirty=!1,ie.mtimeMs=e.doc.mtimeMs,ie.diskSig=e.doc.diskSig,$e=void 0,he=le(ie.path),console.log(e.note),console.log(chalk.gray(" the kernel keeps its variables — ")+chalk.cyan("restart")+chalk.gray(" for a clean start."))}else console.log(chalk.yellow(" no such file: ")+chalk.white(n)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ge()}if("del"===s||"delete"===s)return(e=>{const o=Ne(e);o&&(ie.cells.splice(o.idx-1,1),ie.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${ie.cells.length} left.`)+(o.idx<=ie.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(u),void Ge();if(("md"===s||"py"===s)&&/^\d+$/.test(u))return((e,o)=>{const n=Ne(e);if(!n)return;const t="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,ie.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${t}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${t}.`))})(u,"md"===s?"markdown":"code"),void Ge();if("gpu"===s)return Pe=!0,await Ae(u),Pe=!1,void Ge();if("download"===s||"dl"===s)return Pe=!0,await(async e=>{if(!ue)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${ue.outDir}/${n}`;let r;try{r=await de.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=he?y(process.cwd(),"icoa-kaggle",he):process.cwd(),s=y(a,i(n));try{o(a,{recursive:!0}),l(s,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(s)+chalk.gray(` (${r.length} bytes)`)),he&&"submission.csv"===i(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${he}`)+chalk.gray(" — then upload on Kaggle yourself."))})(u),Pe=!1,void Ge();if("check"===s||"submit"===s||"kaggle"===s){const e=await import("./kaggle.js"),o=u.split(/\s+/).filter(Boolean),n="kaggle"===s?(o[0]||"").toLowerCase():s,t=("kaggle"===s?o[1]:o[0])||le(ie.path)||void 0;Pe=!0;try{"submit"===n?await e.runKaggleSubmit(t):"check"===n?await e.runKaggleCheck(t):"guide"===n?await e.runKaggleGuide(t):await e.runKaggle("kaggle"===s?o[0]:t)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Pe=!1,void Ge()}if("board"===s){const{runBoard:e}=await import("./board.js"),o=u.split(/\s+/).filter(Boolean);Pe=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Pe=!1,void Ge()}if("ai"===s||"/ai"===s)return Pe=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),t=o.length>0&&/^\d+$/.test(o[0]),l=(t?o.slice(1):o).join(" ").trim(),r=t?Number(o[0]):(()=>{for(let e=ie.cells.length-1;e>=0;e--)if((ie.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??ie.cells.length;if(0===ie.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=Ne(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(Y,"")).join("\n")));return o.join("\n").replace(Y,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!ie.path||!le(ie.path))return"";try{const e=JSON.parse(n(y(c(ie.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return Ue(o,350)}catch{return""}})(),g=z(),d=g?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",u=d.length+l.length+120,m=Math.max(400,h-u-i.length),f=Ue(a.cell.source,Math.floor(.6*m)),w=s?(b=s,k=m-f.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[d,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${f}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",l?`\n[question]\n${l}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),x=g;console.log(),Oe||(Oe=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(z()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${h} ${z()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(z()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(z()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${h} chars`)+chalk.gray(x?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(x?" · 含输出":" · output included"):"")+($?chalk.yellow(x?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),q(`ipynb: ai ${a.idx}${l?` — ${l}`:""}`);const P=await p(v);if(console.log(),!P.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(P.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of I(P.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${x?"<你的问题>":"<your question>"}`)+chalk.gray(x?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(x?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(x?" 再跑一次":" run it again")),console.log(chalk.gray(x?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(u),Pe=!1,void Ge();if("run"===s)return Pe=!0,await(async e=>{const o=B(e,ie.cells.length);if(o)for(const e of o){const n=ie.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(M(n,50))+chalk.gray(" ──"));try{n.result=await de.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void Q()}if(ie.dirty=!0,se(n.result,Z),Ke(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(z()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(z()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void Q()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of I(n.source))console.log(e);console.log()}}else console.log(0===ie.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(u),Pe=!1,void Ge();if("save"===s)return(e=>{if(0===ie.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?g(e.trim())?e.trim():d(process.cwd(),e.trim()):ie.path?ie.path.endsWith(".ipynb")?ie.path:`${ie.path.replace(/\.[^./]+$/,"")}.ipynb`:d(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===ie.path?ge(o):void 0;if(void 0!==n&&void 0!==ie.mtimeMs&&n!==ie.mtimeMs&&"save"!==Se)return Se="save",console.log(chalk.yellow(` ${i(o)} was changed in your editor after this notebook read it.`)),void console.log(chalk.gray(" ")+chalk.cyan("save")+chalk.gray(" again to overwrite those changes · ")+chalk.cyan("reload")+chalk.gray(" to take the file instead"));Se=null;try{l(o,W(ie.cells)),ie.path=o,ie.dirty=!1,ie.mtimeMs=ge(o),ie.diskSig=ce(ie.cells),$e=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${ie.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(u),void Ge();if(""===a)return void Ge()}if(ve.length>0&&X.has(a.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(a.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ge();if(ve.push(t),!G(ve))return 1!==ve.length||xe||(xe=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ge();const s=ve.join("\n").replace(/\s+$/,"");if(ve.length=0,""!==s.trim()){Pe=!0;try{const e=await de.execute(s);ie.cells.push({kind:"code",source:s,result:e}),ie.dirty=!0,se(e,Z);const o=Ke(ie.cells[ie.cells.length-1],ie.cells.length);e.ok||o||Q()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),Q()}Pe=!1,Ge()}else Ge()};we.on("line",e=>{Be(e)}),me||we.on("close",async()=>{await de.shutdown().catch(()=>{}),process.exit(0)}),Ge(),await Ie}
1
+ import{existsSync as e,mkdirSync as o,readdirSync as n,readFileSync as t,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 k}from"../lib/config.js";import{editTextInEditor as b,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 G}from"../lib/gpu.js";import{shouldExecuteCell as j}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{NotebookKernel as I,buildRemoteBridgeCommand as N}from"../lib/kernel.js";import{getMainRl as O,setMainRl as T}from"../lib/main-rl.js";import{logCommand as M}from"../lib/logger.js";import{startLogSync as D,stopLogSync as q}from"../lib/log-sync.js";import{cellPreview as L,fromWholeEditText as K,mergeReloadedCells as R,normalizePathArg as B,parseIpynb as F,parsePercentPy as z,parseRunRange as W,serializeIpynb as J,statusChar as V,toWholeEditText as Y}from"../lib/notebook-doc.js";import{committeeLease as H,readCommitteeSession as X,TIER_LABEL as Z}from"../lib/gputask-session.js";import{lazyFile as Q}from"../lib/lazy-assets.js";import{openFile as ee}from"../lib/open-file.js";const oe=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function ne(){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 te(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const le=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),re=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function ae(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const se="https://practice.icoa2026.au";function ie(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):se}function ce(){return u(a(),".icoa","gpu-key")}function ge(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return t(ce(),"utf-8").trim()||null}catch{return null}}async function ye(e,o,n){try{const t=await fetch(`${ie()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await t.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function de(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let ue=0,he=null;function pe(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(oe,"")}`))}else"display"===n.kind&&fe(n.data,o)}function fe(e,n){if(e["image/png"])try{o(n,{recursive:!0}),ue+=1;const t=u(n,`figure-${ue}.png`);return r(t,Buffer.from(e["image/png"],"base64")),he=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(ee(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}function me(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function we(e){if(e)try{return l(e).mtimeMs}catch{return}}function ke(o){const n=B(o,a()),l=d(n)?n:h(process.cwd(),n);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=t(l,"utf8"),o=l.endsWith(".ipynb")?F(e):z(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:we(l),diskSig:me(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 be={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const se=E?.trim().toLowerCase().replace(/-demo$/,"");if(se&&be[se]){const n=await async function(n){const l=be[n],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 Q(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 ${n}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,t(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}(se);if(!n)return;E=n}const ue=p(a()),fe=u(a(),".icoa","ipynb-out");if(te(),!e(ue.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const ve=E?ke(E):null,$e=ve?ve.doc:{cells:[],path:null,dirty:!1};let _e=new I({venvPython:ue.python,venvRoot:ue.root}),xe=null,Pe=null,Se=null,Ee=de($e.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await _e.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.")),ve&&console.log(ve.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" one cell · ")+chalk.cyan("edit")+chalk.gray(" whole notebook · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const Ce=O(),Ge=null!==Ce,je=Ge?Ce.listeners("line").slice():[];Ge&&Ce.removeAllListeners("line");const Ue=Ge?Ce:c({input:process.stdin,output:process.stdout,terminal:!0});Ge||T(Ue);const Ae=Ge?Ue.prompt:null,Ie=Ge?Ue.getPrompt():"";Ge&&(Ue.prompt=i.prototype.prompt),Ge||D();const Ne=[];let Oe,Te=!1,Me=!1,De=!1,qe=null,Le=null;const Ke=()=>{if(Le)return Ue.setPrompt(chalk.bold.cyan(` editor 1-${Le.options.length} > `)),void Ue.prompt();const e=xe?"icoa ipynb ⚡gpu":"icoa ipynb";Ue.setPrompt(chalk.bold.cyan(Ne.length?`${e} ...> `:`${e}> `)),Ue.prompt()};let Re=()=>{};const Be=new Promise(e=>{Re=e}),Fe=async()=>{_e=new I({venvPython:ue.python,venvRoot:ue.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await _e.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"))}},ze=async(e,n=!1)=>{const t=H(e),l=S(t);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=$e.path?g(y($e.path)):"work",c=`${t.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=N(t.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new I({spawnSpec:{command:"ssh",args:P(t,s,d)},readyTimeoutMs:9e4});n||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 _e.shutdown().catch(()=>{}),_e=h,xe={...t,outDir:c},Se=e,Pe=Date.now(),h.onUnexpectedExit=()=>{_e===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).")),xe=null,Se=null,Pe=null,Fe().then(()=>Ke()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${Z[e.tier]} · cells run in ${c}`));const p=await We();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},We=async()=>{if(!$e.path||!xe?.outDir)return 0;const e=y($e.path);let o=[];try{o=n(e)}catch{return 0}let r=0;for(const n of o){if(n.startsWith("."))continue;const o=u(e,n);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await _e.putFile(`${xe.outDir}/${n}`,t(o)),r++}catch{}}return r},Je=async e=>{const[n,...t]=e.trim().split(/\s+/),l=(n??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(xe)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=X();if(e)return void await(async e=>{await ze(e)})(e);const n=ge();if(!n)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));Ee||(Ee=de($e.path));const t=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await ye("lease",n,Ee??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-t)/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 ye("status",n),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 ye("release",n);const y=Ee?`${l.dataRoot}/${Ee}`:l.dataRoot,d=N(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 ye("release",n)}h={command:"ssh",args:P(l,e,d)}}const p=new I({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 ye("release",n)}await _e.shutdown().catch(()=>{}),_e=p,xe=l,Pe=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=G(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.")),Ee&&console.log(chalk.gray(` Dataset is already on the box (${Ee}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===l||"disconnect"===l?await(async()=>{if(xe&&Se){const e=Pe?Math.round((Date.now()-Pe)/1e3):0;return await _e.shutdown().catch(()=>{}),xe=null,Se=null,Pe=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 Fe()}if(!xe)return void console.log(chalk.gray(" not on a GPU kernel."));const e=ge(),o=void 0!==xe.gpuName,n=Pe?Math.round((Date.now()-Pe)/1e3):0;await _e.shutdown().catch(()=>{}),e&&await ye("release",e),xe=null,Pe=null;const t=Math.floor(n/60),l=t>0?`${t} m ${n%60} s`:`${n} 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 Fe()})():"status"===l||""===l?await(async()=>{const e=X();if(e)return console.log(chalk.green(` ⚡ committee seat · ${Z[e.tier]} · ${e.host}`)+chalk.gray(Se?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=ge();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const n=await ye("status",o);if("ready"===n.state){const e=Math.round((n.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(xe?" (this notebook is connected)":" (not connected here — gpu on)"));const o=G(n.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===n.state?console.log(chalk.yellow(` ${C(n)}`)):"none"===n.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${n.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=ge();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${ie()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await n.json();o=t.data??t}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,t="number"==typeof o.free?o.free:0,l=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${t} free`));const a=G("number"==typeof o.window_close_epoch?o.window_close_epoch:void 0);a&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${a}.`)),console.log(chalk.bold.white(" ▶ running now:")),0===l.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,t=Math.floor(n/60),l=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${t}:${l} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",t=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+t)}console.log()})():"key"===l?(e=>{const n=e.trim();if(n)try{o(u(a(),".icoa"),{recursive:!0}),r(ce(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${ce()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(t.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},Ve=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>$e.cells.length?(console.log(0===$e.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${$e.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:$e.cells[o-1],idx:o}},Ye=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let He=!1;const Xe=()=>{const e=w().notebookEditor;return e?_(e):null},Ze=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),Qe=()=>Xe()??x(),eo={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"},oo=(e,o)=>{if(e){const n=_(e);return n?v(n.cmd)?(o(n),!0):(console.log(chalk.yellow(` ${$(n)} is not installed on this computer.`)+chalk.gray(" See the choices: ")+chalk.cyan("editor")),!0):(console.log(chalk.yellow(` unknown editor "${e}" — use `)+chalk.cyan("nano")+chalk.yellow(", ")+chalk.cyan("code")+chalk.yellow(" or ")+chalk.cyan("vi")),!0)}if(Xe()||Ze())return o(Qe()),!0;const n=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return n.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 n=$(e);console.log(chalk.cyan(` ${o+1} ${n.padEnd(5)}`)+chalk.gray(` ${eo[n]??""}`)+("nano"===n?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(n),Le={resume:o,tries:0,options:n},!1)},no=e=>{if(!$e.path)return!1;let o;try{const e=t($e.path,"utf8");o=$e.path.endsWith(".ipynb")?F(e):z(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 n=R($e.cells,o);return $e.cells=n.cells,$e.dirty=!1,$e.mtimeMs=we($e.path),$e.diskSig=me(o),Oe=void 0,console.log(chalk.gray(` ↻ reloaded ${g($e.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${n.cells.length} cells, ${n.changed} changed`)+chalk.gray(n.kept?`, ${n.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},to=()=>void 0!==$e.diskSig?me($e.cells)!==$e.diskSig:$e.dirty,lo=(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)),ro=async n=>{if(n.trim()&&M(`ipynb: ${n.trim()}`),Me)return void(n.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Le){const e=Le,o=n.trim().toLowerCase(),t=_(o),l=/^\d+$/.test(o)?e.options[Number(o)-1]:t?e.options.find(e=>$(e)===$(t)):void 0;return l?(Le=null,k({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===o||["q","quit","back","cancel","exit"].includes(o)?(Le=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Le=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 Ke()}let l=n.trim();if(0===Ne.length&&/^icoa\s+[a-z/]/i.test(l)&&(l=l.replace(/^icoa\s+/i,"")),0===Ne.length){const n=l.split(/\s+/),i=(n[0]??"").toLowerCase(),c=l.slice(n[0]?.length??0).trim();if("quit"!==i&&"exit"!==i&&"q"!==i&&(De=!1),qe&&i!==qe&&(qe=null),re.has(i)&&(()=>{if(!$e.path||void 0===$e.mtimeMs)return;const e=we($e.path);if(void 0!==e&&e!==$e.mtimeMs){if(to()){if(Oe===e)return;return Oe=e,console.log(chalk.yellow(` ⚠ ${g($e.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"))}no(!0)}})(),"quit"===i||"exit"===i||"back"===i||"q"===i||"menu"===i)return $e.dirty&&!De?(De=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ke()):void await(async()=>{if(Ue.removeAllListeners("line"),Ge||q(),console.log(),xe&&Se)xe=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(xe){const e=ge();e&&await ye("release",e),xe=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await _e.shutdown().catch(()=>{}),Ge){Ae&&(Ue.prompt=Ae),Ue.setPrompt(Ie);for(const e of je)Ue.on("line",e);Ue.prompt(),Re()}else T(null),Re(),Ue.close()})();if("clear"===i||"cls"===i)return console.clear(),te(),void Ke();if("restart"===i)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await _e.shutdown().catch(()=>{});try{await _e.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 Ke();if("help"===i||"?"===i)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" 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(ne()?" 问 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(),void Ke();if("guide"===i||"/guide"===i)return(()=>{const o=$e.path?y($e.path):process.cwd(),n=de($e.path);let l="",r=!1;try{const e=JSON.parse(t(u(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=$e.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($e.path?g($e.path):"new empty notebook")+chalk.gray(` · ${$e.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),xe?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),n&&"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."))):n&&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."))):n?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void Ke();if("python"===i||"python3"===i)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 Ke();if("open"===i&&""===c)return he&&ee(he)?console.log(chalk.gray(" reopening ")+chalk.cyan(he)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ke();if("cells"===i||"ls"===i)return(()=>{if(0===$e.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);$e.cells.forEach((o,n)=>{const t=V(o),l="✓"===t?chalk.green(t.padEnd(2)):"✗"===t?chalk.red(t.padEnd(2)):"md"===t?chalk.magenta(t.padEnd(2)):chalk.gray(t.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${l} ${chalk.white(L(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 Ke();if("show"===i)return(e=>{const o=Ve(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.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),pe(o.cell.result,fe)),console.log()}})(c),void Ke();if("edit"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ").toLowerCase();return""===n||"all"===n?oo(o,e=>(e=>{Ue.pause();const o=b(Y($e.cells),".py",e,"notebook");if(Ue.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 n=K(o,$e.cells);if(n.same)return void console.log(chalk.gray(" no changes."));if(0===n.cells.length&&$e.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${$e.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));$e.cells=n.cells,$e.dirty=!0;const t=[];n.changed.length&&t.push(`${n.changed.length} changed (${n.changed.join(", ")})`),n.added.length&&t.push(`${n.added.length} added (${n.added.join(", ")})`),n.deleted&&t.push(`${n.deleted} deleted`),n.reordered&&t.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${$e.cells.length} cells`)+chalk.gray(` · ${t.join(" · ")}`));const l=[...n.changed,...n.added].filter(e=>"code"===$e.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)):Ve(n)&&oo(o,e=>((e,o)=>{const n=Ve(e);if(!n)return;Ue.pause();const t=b(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(Ue.resume(),null===t)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=t.replace(/\s+$/,"");l!==n.cell.source?(n.cell.source=l,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,$e.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(n,e)),void Ke()}if("add"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ");return oo(o,e=>((e,o)=>{const n=e.trim().toLowerCase(),t="md"===n||"markdown"===n||"text"===n||"txt"===n;if(n&&!t&&"py"!==n&&"code"!==n&&"python"!==n)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Ue.pause();const l=b(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);Ue.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?($e.cells.push({kind:t?"markdown":"code",source:r,result:null}),$e.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${$e.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${$e.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void Ke()}if("editor"===i&&/^[\w-]*$/.test(c))return(e=>{const o=e.trim().toLowerCase(),n=$(Qe());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${Xe()?"saved":Ze()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),t=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(t?` ${eo[e]}`:" not installed here")+(e===n?chalk.green(" ← now"):""))}return console.log(chalk.gray(" one edit only: ")+chalk.cyan("edit 3 nano")+chalk.gray(" · back to $EDITOR / vi: ")+chalk.cyan("editor default")),void console.log()}if("default"===o||"reset"===o||"off"===o)return k({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const t=_(o);if(!t)return void console.log(chalk.yellow(` unknown editor "${o}" — `)+chalk.cyan("editor nano")+chalk.yellow(" · ")+chalk.cyan("editor code")+chalk.yellow(" · ")+chalk.cyan("editor vi"));const l=$(t);Xe()&&$(Xe())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(t.cmd)?(k({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${n===l?"default":n}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(c),void Ke();if("reload"===i&&""===c)return $e.path&&e($e.path)?to()&&"reload"!==qe?(qe="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."))):(qe=null,no(!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 Ke();if("load"===i&&!/^[=(.[]/.test(c)||"open"===i&&""!==c){if(!c)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ke();const o=B(c,a()),n=d(o)?o:h(process.cwd(),o);if(e(n))if($e.dirty&&"load"!==qe)qe="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(i)+chalk.yellow(" again to discard them."));else{qe=null;const e=ke(n);$e.cells=e.doc.cells,$e.path=e.doc.path,$e.dirty=!1,$e.mtimeMs=e.doc.mtimeMs,$e.diskSig=e.doc.diskSig,Oe=void 0,Ee=de($e.path),console.log(e.note),console.log(chalk.gray(" the kernel keeps its variables — ")+chalk.cyan("restart")+chalk.gray(" for a clean start."))}else console.log(chalk.yellow(" no such file: ")+chalk.white(n)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ke()}if("del"===i||"delete"===i)return(e=>{const o=Ve(e);o&&($e.cells.splice(o.idx-1,1),$e.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${$e.cells.length} left.`)+(o.idx<=$e.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(c),void Ke();if(("md"===i||"py"===i)&&/^\d+$/.test(c))return((e,o)=>{const n=Ve(e);if(!n)return;const t="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,$e.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${t}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${t}.`))})(c,"md"===i?"markdown":"code"),void Ke();if("gpu"===i)return Me=!0,await Je(c),Me=!1,void Ke();if("download"===i||"dl"===i)return Me=!0,await(async e=>{if(!xe)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${xe.outDir}/${n}`;let l;try{l=await _e.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=Ee?u(process.cwd(),"icoa-kaggle",Ee):process.cwd(),s=u(a,g(n));try{o(a,{recursive:!0}),r(s,l)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(s)+chalk.gray(` (${l.length} bytes)`)),Ee&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Ee}`)+chalk.gray(" — then upload on Kaggle yourself."))})(c),Me=!1,void Ke();if("selfcheck"===i||"self-check"===i)return Me=!0,await(async()=>{const e=Se;if(!e||!xe)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===$e.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 · ${Z[e.tier]} · every code cell from the top`));const o=_e;if(await ze(e,!0),_e===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const n=Date.now(),t=[];let l=!1;for(let e=0;e<$e.cells.length;e++){const o=$e.cells[e];if("code"!==o.kind)continue;const n=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${n} … `));try{o.result=await _e.execute(o.source)}catch(e){t.push({n:n,ok:!1,ms:Date.now()-r,error:e instanceof Error?e.message:String(e)}),console.log(chalk.red("kernel error")),l=!0;break}$e.dirty=!0;const a=Date.now()-r,s=o.result.outputs.find(e=>"error"===e.kind);if(t.push({n:n,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){pe(o.result,fe),l=!0;break}}const r=Date.now()-n,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 _e.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:$e.path?g($e.path):null,cells:t,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(`${(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").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."))}})(),Me=!1,void Ke();if("upload"===i||"up"===i||"put"===i)return Me=!0,await(async e=>{if(!xe)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 n=B(o,a()),l=d(n)?n:h($e.path?y($e.path):process.cwd(),n);let r;try{r=t(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${xe.outDir}/${g(l)}`;try{const e=await _e.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)))}})(c),Me=!1,void Ke();if("check"===i||"submit"===i||"kaggle"===i){const e=await import("./kaggle.js"),o=c.split(/\s+/).filter(Boolean),n="kaggle"===i?(o[0]||"").toLowerCase():i,t=("kaggle"===i?o[1]:o[0])||de($e.path)||void 0;Me=!0;try{if("submit"===n){const o=s("sha256").update($e.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(t,{code_sha:o,...Se?{sid:Se.sid}:{},...$e.path?{notebook:g($e.path)}:{}})}else"check"===n?await e.runKaggleCheck(t):"final"===n?await e.runKaggleFinal(t,o.slice(2)):"guide"===n?await e.runKaggleGuide(t):await e.runKaggle("kaggle"===i?o[0]:t)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Me=!1,void Ke()}if("board"===i){const{runBoard:e}=await import("./board.js"),o=c.split(/\s+/).filter(Boolean);Me=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Me=!1,void Ke()}if("ai"===i||"/ai"===i)return Me=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),n=o.length>0&&/^\d+$/.test(o[0]),l=(n?o.slice(1):o).join(" ").trim(),r=n?Number(o[0]):(()=>{for(let e=$e.cells.length-1;e>=0;e--)if(($e.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??$e.cells.length;if(0===$e.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=Ve(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(oe,"")).join("\n")));return o.join("\n").replace(oe,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!$e.path||!de($e.path))return"";try{const e=JSON.parse(t(u(y($e.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return Ye(o,350)}catch{return""}})(),c=ne(),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=Ye(a.cell.source,Math.floor(.6*h)),w=s?(k=s,b=h-p.length,k.length<=b?k:`…(${k.length-b} chars elided)…\n${k.slice(-b)}`):"";var k,b;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(),He||(He=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(ne()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${ne()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(ne()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(ne()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — 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"):"")),M(`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()})(c),Me=!1,void Ke();if("run"===i)return Me=!0,await(async e=>{const o=W(e,$e.cells.length);if(o)for(const e of o){const n=$e.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(L(n,50))+chalk.gray(" ──"));try{n.result=await _e.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void ae()}if($e.dirty=!0,pe(n.result,fe),lo(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(ne()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(ne()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void ae()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(n.source))console.log(e);console.log()}}else console.log(0===$e.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"))})(c),Me=!1,void Ke();if("save"===i)return(e=>{if(0===$e.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()):$e.path?$e.path.endsWith(".ipynb")?$e.path:`${$e.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===$e.path?we(o):void 0;if(void 0!==n&&void 0!==$e.mtimeMs&&n!==$e.mtimeMs&&"save"!==qe)return qe="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"));qe=null;try{r(o,J($e.cells)),$e.path=o,$e.dirty=!1,$e.mtimeMs=we(o),$e.diskSig=me($e.cells),Oe=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${$e.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(c),void Ke();if(""===l)return void Ke()}if(Ne.length>0&&le.has(l.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(l.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ke();if(Ne.push(n),!j(Ne))return 1!==Ne.length||Te||(Te=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ke();const i=Ne.join("\n").replace(/\s+$/,"");if(Ne.length=0,""!==i.trim()){Me=!0;try{const e=await _e.execute(i);$e.cells.push({kind:"code",source:i,result:e}),$e.dirty=!0,pe(e,fe);const o=lo($e.cells[$e.cells.length-1],$e.cells.length);e.ok||o||ae()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),ae()}Me=!1,Ke()}else Ke()};Ue.on("line",e=>{ro(e)}),Ge||Ue.on("close",async()=>{await _e.shutdown().catch(()=>{}),process.exit(0)}),Ke(),await Be}
@@ -1 +1 @@
1
- import{existsSync as o,mkdirSync as e,readFileSync as t,readdirSync as n,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as m,validateSubmissionText as b}from"../lib/kaggle.js";import{mediaHelpLines as p,sprintTaskForComp as f}from"../lib/sprint-meta.js";function k(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function w(o){try{const e=await fetch(k()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function v(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function $(){return(a().language||"en").toLowerCase().startsWith("zh")}function j(o,e){return $()?o:e}function _(){console.log(),console.log(chalk.yellow(j(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(j(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function S(o){return s(process.cwd(),"icoa-kaggle",o)}function G(o,e){const t=[];let n="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const r of o){const o=s(r)?2:1;if(l+o>e){const o=n.lastIndexOf(" ");if(!s(r)&&" "!==r&&o>e/3){const e=n.slice(o+1);t.push(n.slice(0,o)),n=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else t.push(n),n="",l=0;if(" "===r&&""===n)continue}n+=r,l+=o}return""!==n.trim()&&t.push(n),t}function P(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(j(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(j(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(j(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(j(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),console.log(chalk.gray(j(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board")),void console.log(chalk.gray(j(" 在 notebook 里可直接敲 "," inside the notebook just type "))+chalk.cyan("submit")+chalk.gray(j(" —— 不用退出来"," — no need to leave")))):"nitro"===o?.judge?(console.log(chalk.bold.white(j(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(j(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(j(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(j(" 注册后提交"," and submit there"))),void console.log(chalk.gray(j(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(j(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(j(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(j(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(j(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(j(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(j(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(j(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(j(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(t){const n=r(),a=async o=>await n.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(j(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(j(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(j("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(j("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const n=await w("/api/icoa/kaggle/tasks");if(!n)return _();const r=h(n);if(0===r.length)return console.log(chalk.yellow(j(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=t?r.find(o=>o.comp_id===t):void 0;if(t&&!c&&console.log(chalk.yellow(j(` 没有叫 "${t}" 的比赛。`,` No competition called "${t}".`))),!c){console.log(chalk.white(j(" 正在开放的练习赛:"," Live practice competitions:"))),r.forEach((o,e)=>{const t=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+t)});for(let o=0;o<3&&!c;o++){const o=(await a(chalk.cyan(j(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&r[e-1]||r.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(j(` 输 1-${r.length} 之间的序号,或者一个 id,比如 "${r[0].comp_id}"。`,` Try a number 1-${r.length} or an id like "${r[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(i(`kaggle: download ${u}`),c.needs_gpu)return void await async function(t,n){const r=S(t);if(console.log(),console.log(chalk.white(` ${n.title}`)+chalk.gray(` · ${n.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),n.description){console.log();for(const o of G(n.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(j(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(j(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const a=await w(`/api/icoa/kaggle/${t}/starter`),i=a?.data?.starter??a?.starter;if("string"!=typeof i||0===i.length)return _();const c=s(r,"starter.ipynb");let g=!1;try{e(r,{recursive:!0}),o(c)?g=!0:l(c,i),l(s(r,"meta.json"),`${JSON.stringify(n,null,2)}\n`)}catch{return void console.log(chalk.yellow(j(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?j(" (保留了你原来那本)"," (kept your existing one)"):j(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(j("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(j(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(j(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(j(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(j(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(j(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(j(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(j(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(j(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),n.kaggle_url&&(console.log(chalk.gray(j(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(n.kaggle_url)),console.log())}(u,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of G(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(j(" 正在下载数据…"," Downloading data…")));let m=null;const b=y(c);if(b){const[o,e,t]=await Promise.all([v(b.train),v(b.test),v(b.sample_submission)]);o&&e&&t&&(m={train:o,test:e,sample_submission:t})}if(!m){const o=await w(`/api/icoa/kaggle/${u}/data`);m=o?.data??o}if(!m?.train||!m?.test||!m?.sample_submission)return _();const p=S(u),k={...c,...m.meta??{}};try{e(p,{recursive:!0}),l(s(p,"train.csv"),m.train),l(s(p,"test.csv"),m.test),l(s(p,"sample_submission.csv"),m.sample_submission),l(s(p,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const $=s(p,"starter.ipynb");let P=!1;if(o($))P=!0;else{const o=await w(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l($,e):l($,g(d(p,k)))}const x="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",C="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(p,"train.csv"))+chalk.gray(` (${x})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(p,"test.csv"))+chalk.gray(` (${C})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(p,"sample_submission.csv")));const E=f(u),U="none"===(E?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white($)+chalk.gray(P?" (kept your existing one)":U?j(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),A(u,k,$),console.log()}finally{n.close()}}function x(o){const e=$();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function A(o,e,t){const n=f(o),l=n?p(n,$()):[];if(l.length>0){for(const o of l)for(const e of G(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(e?.needs_gpu)console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${t}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"));else{const l=n?.media?.pack,s="none"===(n?.baseline||"").trim();console.log(chalk.bold.white(l?j(" 接下来 4 步:"," Your move — 4 steps:"):j(" 接下来 3 步:"," Your move — 3 steps:")));let r=1;l&&console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(j(` → 把${x(n?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${x(n?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`icoa ipynb ${t}`)+chalk.gray(s?j(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${r++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${r}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${r}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${r}. upload it on Kaggle yourself — then beat the baseline.`))}console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick ")+chalk.bold.white("🧠 Learn")+chalk.gray(" → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),P(e)}export async function runKaggleGuide(e){console.log();const n=C(e,"guide");if(!n)return;const l=S(n);let r=null;try{r=JSON.parse(t(s(l,"meta.json"),"utf-8"))}catch{r=null}i(`kaggle: guide ${n}`);const a=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${r?.title??n} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),A(n,r,a),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function C(e,t){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),r=o(l)?n(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===r.length)return r[0];if(0===r.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of r)console.log(chalk.gray(` kaggle ${t} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const n=C(e,"check");if(!n)return;const l=S(n),r=s(l,"submission.csv"),a=s(l,"sample_submission.csv");try{if(JSON.parse(t(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(a))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(a))return console.log(chalk.yellow(` No data for "${n}" here — run `)+chalk.cyan(`kaggle ${n}`)+chalk.yellow(" first.")),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=b(t(r,"utf-8"),t(a,"utf-8"));i(`kaggle: check ${n} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(t(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(r)),console.log(),P(u),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const n=C(e,"submit");if(!n)return;const l=S(n),a=s(l,"submission.csv"),c=s(l,"sample_submission.csv");let g=null;try{g=JSON.parse(t(s(l,"meta.json"),"utf-8"))}catch{g=null}if("local-eval"===g?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),P(g),void console.log();if(!g||!o(c))return console.log(chalk.yellow(` No data for "${n}" here — run `)+chalk.cyan(`kaggle ${n}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==g.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),P(g),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const d=t(a,"utf-8"),y=b(d,t(c,"utf-8"));if(!y.ok){i(`kaggle: submit ${n} → local-reject: ${y.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of y.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let h=u()?.token??"";if(!h){const o=r();try{h=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!h)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}const p=Date.now();let f,w=null;process.stdout.isTTY?(process.stdout.write(chalk.gray(" ⚖ scoring on the server… 0.0s")),w=setInterval(()=>{process.stdout.write(chalk.gray(`\r ⚖ scoring on the server… ${((Date.now()-p)/1e3).toFixed(1)}s `))},200)):console.log(chalk.gray(" Scoring on the server…"));try{f=await async function(o,e){try{const t=await fetch(k()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await t.json()}catch{return null}}(`/api/icoa/kaggle/${n}/submit`,{token:h,submission_csv:d})}finally{w&&(clearInterval(w),process.stdout.write(`\r ${chalk.gray(`⚖ scored in ${((Date.now()-p)/1e3).toFixed(1)}s`)}${" ".repeat(12)}\n`))}const v=m(f);if(i(`kaggle: submit ${n} → ${v.ok?`${v.metric}=${v.score}${v.deduped?" (deduped)":""} rank=${v.rank??"-"}`:v.reason??"error"}`),console.log(),v.ok){const o=`${v.metric}: ${Number(v.score).toFixed(4).replace(/\.?0+$/,"")}`;v.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof v.rank&&"number"==typeof v.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${v.rank}`)+chalk.gray(` of ${v.fieldSize}`))),"number"==typeof v.used&&"number"==typeof v.cap&&console.log(chalk.gray(` ⚖ submissions used ${v.used}/${v.cap}`)),v.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${v.boardEvent} ${n}`))}else switch(v.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of v.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as m}from"../lib/kaggle.js";import{mediaHelpLines as p,sprintTaskForComp as f}from"../lib/sprint-meta.js";function k(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function w(o){try{const e=await fetch(k()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function $(o,e){try{const n=await fetch(k()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}async function v(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function j(){return(a().language||"en").toLowerCase().startsWith("zh")}function _(o,e){return j()?o:e}function S(){console.log(),console.log(chalk.yellow(_(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(_(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function A(o){return s(process.cwd(),"icoa-kaggle",o)}function x(o,e){const n=[];let t="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const r of o){const o=s(r)?2:1;if(l+o>e){const o=t.lastIndexOf(" ");if(!s(r)&&" "!==r&&o>e/3){const e=t.slice(o+1);n.push(t.slice(0,o)),t=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else n.push(t),t="",l=0;if(" "===r&&""===t)continue}t+=r,l+=o}return""!==t.trim()&&n.push(t),n}function G(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(_(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(_(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(_(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(_(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),console.log(chalk.gray(_(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board")),void console.log(chalk.gray(_(" 在 notebook 里可直接敲 "," inside the notebook just type "))+chalk.cyan("submit")+chalk.gray(_(" —— 不用退出来"," — no need to leave")))):"nitro"===o?.judge?(console.log(chalk.bold.white(_(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(_(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(_(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(_(" 注册后提交"," and submit there"))),void console.log(chalk.gray(_(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(_(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(_(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(_(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(_(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(_(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(_(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(_(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(_(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(n){const t=r(),a=async o=>await t.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(_(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(_(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(_("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(_("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await w("/api/icoa/kaggle/tasks");if(!t)return S();const r=h(t);if(0===r.length)return console.log(chalk.yellow(_(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=n?r.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(_(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(_(" 正在开放的练习赛:"," Live practice competitions:"))),r.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!c;o++){const o=(await a(chalk.cyan(_(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&r[e-1]||r.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(_(` 输 1-${r.length} 之间的序号,或者一个 id,比如 "${r[0].comp_id}"。`,` Try a number 1-${r.length} or an id like "${r[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(i(`kaggle: download ${u}`),c.needs_gpu)return void await async function(n,t){const r=A(n);if(console.log(),console.log(chalk.white(` ${t.title}`)+chalk.gray(` · ${t.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),t.description){console.log();for(const o of x(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(_(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(_(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const a=await w(`/api/icoa/kaggle/${n}/starter`),i=a?.data?.starter??a?.starter;if("string"!=typeof i||0===i.length)return S();const c=s(r,"starter.ipynb");let g=!1;try{e(r,{recursive:!0}),o(c)?g=!0:l(c,i),l(s(r,"meta.json"),`${JSON.stringify(t,null,2)}\n`)}catch{return void console.log(chalk.yellow(_(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?_(" (保留了你原来那本)"," (kept your existing one)"):_(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(_("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(_(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(_(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(_(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(_(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(_(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(_(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(_(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(_(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(_(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(t.kaggle_url)),console.log())}(u,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of x(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(_(" 正在下载数据…"," Downloading data…")));let b=null;const m=y(c);if(m){const[o,e,n]=await Promise.all([v(m.train),v(m.test),v(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await w(`/api/icoa/kaggle/${u}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return S();const p=A(u),k={...c,...b.meta??{}};try{e(p,{recursive:!0}),l(s(p,"train.csv"),b.train),l(s(p,"test.csv"),b.test),l(s(p,"sample_submission.csv"),b.sample_submission),l(s(p,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const $=s(p,"starter.ipynb");let j=!1;if(o($))j=!0;else{const o=await w(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l($,e):l($,g(d(p,k)))}const G="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",P="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(p,"train.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(p,"test.csv"))+chalk.gray(` (${P})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(p,"sample_submission.csv")));const I=f(u),N="none"===(I?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white($)+chalk.gray(j?" (kept your existing one)":N?_(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),C(u,k,$),console.log()}finally{t.close()}}function P(o){const e=j();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function C(o,e,n){const t=f(o),l=t?p(t,j()):[];if(l.length>0){for(const o of l)for(const e of x(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(e?.needs_gpu)console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"));else{const l=t?.media?.pack,s="none"===(t?.baseline||"").trim();console.log(chalk.bold.white(l?_(" 接下来 4 步:"," Your move — 4 steps:"):_(" 接下来 3 步:"," Your move — 3 steps:")));let r=1;l&&console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(_(` → 把${P(t?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${P(t?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(s?_(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${r++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${r}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${r}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${r}. upload it on Kaggle yourself — then beat the baseline.`))}console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick ")+chalk.bold.white("🧠 Learn")+chalk.gray(" → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),G(e)}export async function runKaggleGuide(e){console.log();const t=I(e,"guide");if(!t)return;const l=A(t);let r=null;try{r=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{r=null}i(`kaggle: guide ${t}`);const a=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${r?.title??t} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),C(t,r,a),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function I(e,n){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),r=o(l)?t(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===r.length)return r[0];if(0===r.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of r)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const t=I(e,"check");if(!t)return;const l=A(t),r=s(l,"submission.csv"),a=s(l,"sample_submission.csv");try{if(JSON.parse(n(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(a))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(a))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=m(n(r,"utf-8"),n(a,"utf-8"));i(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(r)),console.log(),G(u),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e,t){console.log();const l=I(e,"submit");if(!l)return;const a=A(l),c=s(a,"submission.csv"),g=s(a,"sample_submission.csv");let d=null;try{d=JSON.parse(n(s(a,"meta.json"),"utf-8"))}catch{d=null}if("local-eval"===d?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),G(d),void console.log();if(!d||!o(g))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==d.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),G(d),void console.log();if(!o(c))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(a,"starter.ipynb")}`)),void console.log();const y=n(c,"utf-8"),h=m(y,n(g,"utf-8"));if(!h.ok){i(`kaggle: submit ${l} → local-reject: ${h.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of h.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let p=u()?.token??"";if(!p){const o=r();try{p=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!p)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}const f=Date.now();let k,w=null;process.stdout.isTTY?(process.stdout.write(chalk.gray(" ⚖ scoring on the server… 0.0s")),w=setInterval(()=>{process.stdout.write(chalk.gray(`\r ⚖ scoring on the server… ${((Date.now()-f)/1e3).toFixed(1)}s `))},200)):console.log(chalk.gray(" Scoring on the server…"));try{k=await $(`/api/icoa/kaggle/${l}/submit`,{token:p,submission_csv:y,...t?{job:t}:{}})}finally{w&&(clearInterval(w),process.stdout.write(`\r ${chalk.gray(`⚖ scored in ${((Date.now()-f)/1e3).toFixed(1)}s`)}${" ".repeat(12)}\n`))}const v=b(k);if(i(`kaggle: submit ${l} → ${v.ok?`${v.metric}=${v.score}${v.deduped?" (deduped)":""} rank=${v.rank??"-"}`:v.reason??"error"}`),console.log(),v.ok){const o=`${v.metric}: ${Number(v.score).toFixed(4).replace(/\.?0+$/,"")}`,e="public"===v.leaderboard?chalk.gray(" (public leaderboard — the private split is revealed after the event)"):"";v.deduped&&v.sameCode?(console.log(chalk.bold.white(` ✓ same code as before — ${o}`)+e),console.log(chalk.gray(" The notebook code is unchanged, so this is the earlier result; it does not count as a submission."))):v.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)+e),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)+e),"number"==typeof v.rank&&"number"==typeof v.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${v.rank}`)+chalk.gray(` of ${v.fieldSize}`))),"number"==typeof v.used&&"number"==typeof v.cap&&console.log(chalk.gray(` ⚖ submissions used ${v.used}/${v.cap}`)),v.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${v.boardEvent} ${l}`)),v.submissionId&&"public"===v.leaderboard&&console.log(chalk.gray(` id ${v.submissionId} · pick the two that count on the private board: `)+chalk.cyan(`kaggle final ${l} ${v.submissionId}`)+chalk.gray(" [<id2>] (unpicked = public best + last)"))}else switch(v.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of v.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export async function runKaggleFinal(o,e=[]){console.log();const n=I(o,"final");if(!n)return;const t=u()?.token??"";if(!t)return console.log(chalk.gray(" A learn token identifies you on the board — open Learn once with your token first.")),void console.log();const l=await $(`/api/icoa/kaggle/${n}/final`,{token:t,ids:e.slice(0,2)})??{},s=l.data??l??{};if("string"==typeof s.reason){if("bad_id"===s.reason){console.log(chalk.bold.red(` ✗ ${String(s.error)}`));const o=Array.isArray(s.yours)?s.yours:[];o.length>0&&console.log(chalk.gray(` your scored ids: ${o.join(", ")}`))}else"bad_token"===s.reason?console.log(chalk.bold.red(" ✗ that learn token was not accepted")):console.log(chalk.yellow(` ${String(s.error??s.reason)}`));return void console.log()}if(!Array.isArray(s.final))return console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const r=s.final;if(s.chosen&&r.length>0){console.log(chalk.bold.green(" ✓ your final picks for the private board:"));for(const o of r)console.log(chalk.white(` ${o.id}`)+chalk.gray(` public ${Number(o.score).toFixed(4)}`))}else console.log(chalk.white(" No picks yet — the auto rule applies: ")+chalk.gray(String(s.rule_if_unchosen??"public best + last")));const a=Array.isArray(s.yours)?s.yours:[];a.length>0&&(console.log(chalk.gray(` your last ${a.length} scored: `)+a.map(o=>`${o.id} ${Number(o.score).toFixed(4)}`).join(chalk.gray(" · "))),console.log(chalk.gray(" change: ")+chalk.cyan(`kaggle final ${n} <id> [<id>]`))),i(`kaggle: final ${n} → ${r.map(o=>o.id).join(",")||"auto"}`),console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit" / "final")').argument("[ids...]",'submission ids (with "final")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit & final").action(async(o,e,n=[])=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"final"===o?await runKaggleFinal(e,n):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
@@ -1 +1 @@
1
- import{spawnSync as t}from"node:child_process";import{mkdtempSync as e,readFileSync as o,rmSync as r,writeFileSync as n}from"node:fs";import{tmpdir as s}from"node:os";import{join as i}from"node:path";import chalk from"chalk";import{getConfig as c}from"./config.js";import{rearmFocusMode as a}from"./input-dynamics.js";import{logCommand as d}from"./logger.js";import{startPasteProbe as p}from"./paste-probe.js";const m=["-c","set nocompatible","-c","set backspace=indent,eol,start","-c","silent! set complete=. completeopt=menu,menuone"],u=new Set(["vi","vim","vim.tiny","vim.basic","vimx"]),l=new Map;function f(e){const o=l.get(e);if(void 0!==o)return o;let r="";try{r=t(e,["--version"],{encoding:"utf8",timeout:2e3}).stdout??""}catch{r=""}return l.set(e,r),r}function v(t){return/VIM - Vi IMproved/.test(f(t))}export function probeVimInsertExpand(t){return/\+insert_expand/.test(f(t))}export function probeVimEval(t){const e=f(t);return/VIM - Vi IMproved/.test(e)&&/\+eval/.test(e)}export function buildEditorArgv(t,e,o=v){return function(t){const e=(t.split(/[\\/]/).pop()??"").toLowerCase().replace(/\.exe$/,"");return u.has(e)}(t.cmd)&&o(t.cmd)?[...t.args,...m,e]:[...t.args,e]}export function resolveEditor(t=process.env,e=process.platform){const o=(t.VISUAL??"").trim()||(t.EDITOR??"").trim();if(o){const t=o.split(/\s+/);return{cmd:t[0],args:t.slice(1)}}return"win32"===e?{cmd:"notepad",args:[]}:{cmd:"vi",args:[]}}export function namedEditor(t,e=process.platform){const o=t.trim().toLowerCase();return"nano"===o||"pico"===o?{cmd:"nano",args:[]}:"vi"===o||"vim"===o?{cmd:o,args:[]}:"code"===o||"vscode"===o||"vs-code"===o?{cmd:"code",args:["--wait"]}:"notepad"===o&&"win32"===e?{cmd:"notepad",args:[]}:null}export function editorLabel(t){return(t.cmd.split(/[\\/]/).pop()??t.cmd).replace(/\.exe$/i,"")}export function editorInstalled(e){try{return 0===("win32"===process.platform?t("where",[e],{stdio:"ignore",timeout:2e3}):t("sh",["-c",'command -v "$1" >/dev/null 2>&1',"sh",e],{stdio:"ignore",timeout:2e3})).status}catch{return!1}}export function editTextInEditor(m,u=".py",l){const f=e(i(s(),"icoa-cell-")),v=i(f,`cell${u}`);n(v,""===m||m.endsWith("\n")?m:`${m}\n`);const g=l??resolveEditor(),h=process.stdin,w=!!h.isTTY&&h.isRaw;try{h.isTTY&&h.setRawMode(!1);const e=Date.now(),r=p(g.cmd),n=buildEditorArgv(g,v);"vim"===r.kind&&console.log(chalk.gray((c().language||"en").toLowerCase().startsWith("zh")?" 注意:编辑器里的复制 / 粘贴会被记录(只记次数与字节数,不记内容)。":" Note: copy / paste in the editor is recorded (counts and sizes only, never the text)."));const s=t(g.cmd,[...n.slice(0,-1),...r.args,v],{stdio:"inherit"}),i=r.finish();if(s.error||0!==s.status)return null;const a=o(v,"utf8");try{d(`editor-session cell${u}`,{ms:Date.now()-e,bytesBefore:Buffer.byteLength(m,"utf8"),bytesAfter:Buffer.byteLength(a,"utf8"),paste:i})}catch{}return a}catch{return null}finally{h.isTTY&&w&&h.setRawMode(!0),a(),r(f,{recursive:!0,force:!0})}}
1
+ import{spawnSync as t}from"node:child_process";import{mkdtempSync as e,readFileSync as o,rmSync as r,writeFileSync as n}from"node:fs";import{tmpdir as s}from"node:os";import{join as i}from"node:path";import chalk from"chalk";import{getConfig as c}from"./config.js";import{rearmFocusMode as a}from"./input-dynamics.js";import{logCommand as d}from"./logger.js";import{startPasteProbe as p}from"./paste-probe.js";const m=["-c","set nocompatible","-c","set backspace=indent,eol,start","-c","silent! set complete=. completeopt=menu,menuone"],u=new Set(["vi","vim","vim.tiny","vim.basic","vimx"]),l=new Map;function f(e){const o=l.get(e);if(void 0!==o)return o;let r="";try{r=t(e,["--version"],{encoding:"utf8",timeout:2e3}).stdout??""}catch{r=""}return l.set(e,r),r}function v(t){return/VIM - Vi IMproved/.test(f(t))}export function probeVimInsertExpand(t){return/\+insert_expand/.test(f(t))}export function probeVimEval(t){const e=f(t);return/VIM - Vi IMproved/.test(e)&&/\+eval/.test(e)}export function buildEditorArgv(t,e,o=v){return function(t){const e=(t.split(/[\\/]/).pop()??"").toLowerCase().replace(/\.exe$/,"");return u.has(e)}(t.cmd)&&o(t.cmd)?[...t.args,...m,e]:[...t.args,e]}export function resolveEditor(t=process.env,e=process.platform){const o=(t.VISUAL??"").trim()||(t.EDITOR??"").trim();if(o){const t=o.split(/\s+/);return{cmd:t[0],args:t.slice(1)}}return"win32"===e?{cmd:"notepad",args:[]}:{cmd:"vi",args:[]}}export function namedEditor(t,e=process.platform){const o=t.trim().toLowerCase();return"nano"===o||"pico"===o?{cmd:"nano",args:[]}:"vi"===o||"vim"===o?{cmd:o,args:[]}:"code"===o||"vscode"===o||"vs-code"===o?{cmd:"code",args:["--wait"]}:"notepad"===o&&"win32"===e?{cmd:"notepad",args:[]}:null}export function editorLabel(t){return(t.cmd.split(/[\\/]/).pop()??t.cmd).replace(/\.exe$/i,"")}export function editorInstalled(e){try{return 0===("win32"===process.platform?t("where",[e],{stdio:"ignore",timeout:2e3}):t("sh",["-c",'command -v "$1" >/dev/null 2>&1',"sh",e],{stdio:"ignore",timeout:2e3})).status}catch{return!1}}export function editTextInEditor(m,u=".py",l,f="cell"){const v=e(i(s(),"icoa-cell-")),g=i(v,`${f}${u}`);n(g,""===m||m.endsWith("\n")?m:`${m}\n`);const h=l??resolveEditor(),w=process.stdin,x=!!w.isTTY&&w.isRaw;try{w.isTTY&&w.setRawMode(!1);const e=Date.now(),r=p(h.cmd),n=buildEditorArgv(h,g);"vim"===r.kind&&console.log(chalk.gray((c().language||"en").toLowerCase().startsWith("zh")?" 注意:编辑器里的复制 / 粘贴会被记录(只记次数与字节数,不记内容)。":" Note: copy / paste in the editor is recorded (counts and sizes only, never the text)."));const s=t(h.cmd,[...n.slice(0,-1),...r.args,g],{stdio:"inherit"}),i=r.finish();if(s.error||0!==s.status)return null;const a=o(g,"utf8");try{d(`editor-session cell${u}`,{ms:Date.now()-e,bytesBefore:Buffer.byteLength(m,"utf8"),bytesAfter:Buffer.byteLength(a,"utf8"),paste:i})}catch{}return a}catch{return null}finally{w.isTTY&&x&&w.setRawMode(!0),a(),r(v,{recursive:!0,force:!0})}}
package/dist/lib/gpu.js CHANGED
@@ -1 +1 @@
1
- const t=/^[a-zA-Z0-9][a-zA-Z0-9.-]*$/,e=/^[a-z_][a-z0-9_-]*$/,o=/^\/[A-Za-z0-9._/-]*$/;function s(t,e){return"string"==typeof t[e]&&""!==t[e]?t[e]:void 0}function r(t,e){return"number"==typeof t[e]&&Number.isFinite(t[e])?t[e]:void 0}export function parseLeaseResponse(t){const e=t??{},o=e.data??e,n=s(o,"state");return"ready"!==n&&"queued"!==n&&"none"!==n?{state:"error",message:s(o,"error")??s(o,"message")??"unexpected broker response"}:{state:n,transport:"local"===o.transport?"local":"ssh"===o.transport?"ssh":void 0,host:s(o,"host"),port:r(o,"port"),user:s(o,"user"),python:s(o,"python"),dataRoot:s(o,"data_root"),outDir:s(o,"out_dir"),keyPem:s(o,"key_pem"),timeLeftSec:r(o,"time_left_sec"),queuePosition:r(o,"queue_position"),estimatedWaitSec:r(o,"estimated_wait_sec"),windowCloseEpoch:r(o,"window_close_epoch"),message:s(o,"message")}}export function leaseConnectProblems(s){const r=[];return"ready"!==s.state&&r.push("lease is not ready"),s.python&&o.test(s.python)||r.push("bad python path"),s.dataRoot&&o.test(s.dataRoot)||r.push("bad data_root"),s.outDir&&o.test(s.outDir)||r.push("bad out_dir"),"ssh"===s.transport?(s.host&&t.test(s.host)||r.push("bad host"),s.user&&e.test(s.user)||r.push("bad user"),void 0!==s.port&&(!Number.isInteger(s.port)||s.port<1||s.port>65535)&&r.push("bad port"),s.keyPem||r.push("missing ssh key")):"local"!==s.transport&&r.push("unknown transport"),r}export function buildSshArgs(t,e,o){return["-i",e,"-p",String(t.port??22),"-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=15","-o","BatchMode=yes","-T",`${t.user}@${t.host}`,o]}export function windowLine(t){if(!t)return"";const e=1e3*t-Date.now();if(e<=0)return"";const o=Math.max(1,Math.round(e/6e4));return`open until ${new Intl.DateTimeFormat("en-AU",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"Australia/Sydney"}).format(new Date(1e3*t))} Sydney · ${o} min to close`}export function queueLine(t){return`⏳ GPU queue: #${t.queuePosition??0}${t.estimatedWaitSec?` · ~${Math.max(1,Math.round(t.estimatedWaitSec/60))} min`:""}`}
1
+ const t=/^[a-zA-Z0-9][a-zA-Z0-9.-]*$/,e=/^[a-z_][a-z0-9_-]*$/,o=/^\/[A-Za-z0-9._/-]*$/;function s(t,e){return"string"==typeof t[e]&&""!==t[e]?t[e]:void 0}function n(t,e){return"number"==typeof t[e]&&Number.isFinite(t[e])?t[e]:void 0}export function parseLeaseResponse(t){const e=t??{},o=e.data??e,r=s(o,"state");return"ready"!==r&&"queued"!==r&&"none"!==r?{state:"error",message:s(o,"error")??s(o,"message")??"unexpected broker response"}:{state:r,transport:"local"===o.transport?"local":"ssh"===o.transport?"ssh":void 0,host:s(o,"host"),port:n(o,"port"),user:s(o,"user"),python:s(o,"python"),dataRoot:s(o,"data_root"),outDir:s(o,"out_dir"),keyPem:s(o,"key_pem"),timeLeftSec:n(o,"time_left_sec"),queuePosition:n(o,"queue_position"),estimatedWaitSec:n(o,"estimated_wait_sec"),windowCloseEpoch:n(o,"window_close_epoch"),message:s(o,"message"),bootStage:["requested","creating","booting","ready"].find(t=>t===o.boot_stage),bootElapsedSec:n(o,"boot_elapsed_sec"),bootEtaSec:n(o,"boot_eta_sec"),gpuName:s(o,"gpu"),zone:s(o,"zone")}}export function leaseConnectProblems(s){const n=[];return"ready"!==s.state&&n.push("lease is not ready"),s.python&&o.test(s.python)||n.push("bad python path"),s.dataRoot&&o.test(s.dataRoot)||n.push("bad data_root"),s.outDir&&o.test(s.outDir)||n.push("bad out_dir"),"ssh"===s.transport?(s.host&&t.test(s.host)||n.push("bad host"),s.user&&e.test(s.user)||n.push("bad user"),void 0!==s.port&&(!Number.isInteger(s.port)||s.port<1||s.port>65535)&&n.push("bad port"),s.keyPem||n.push("missing ssh key")):"local"!==s.transport&&n.push("unknown transport"),n}export function buildSshArgs(t,e,o){return["-i",e,"-p",String(t.port??22),"-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=15","-o","BatchMode=yes","-T",`${t.user}@${t.host}`,o]}export function windowLine(t){if(!t)return"";const e=1e3*t-Date.now();if(e<=0)return"";const o=Math.max(1,Math.round(e/6e4));return`open until ${new Intl.DateTimeFormat("en-AU",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"Australia/Sydney"}).format(new Date(1e3*t))} Sydney · ${o} min to close`}const r={requested:"asking the cloud for a box",creating:"creating the box",booting:"booting · checking torch + CUDA",ready:"ready · handing it to you"};export function queueLine(t){return t.bootStage&&1===(t.queuePosition??1)?`⏳ GPU starting · ${t.gpuName??"GPU"} · ${t.bootElapsedSec??0} s${t.bootEtaSec?` / ~${t.bootEtaSec} s`:""} · ${r[t.bootStage]??t.bootStage}`:`⏳ GPU queue: #${t.queuePosition??0}${t.estimatedWaitSec?` · ~${Math.max(1,Math.round(t.estimatedWaitSec/60))} min`:""}`}
@@ -0,0 +1 @@
1
+ import{existsSync as t,mkdirSync as e,readFileSync as o,rmSync as r,writeFileSync as s}from"node:fs";import{homedir as n}from"node:os";import{join as i}from"node:path";export function sessionFilePath(t=n()){return i(t,".icoa","gputask","session.json")}export function parseCommitteeSession(t){let e;try{e=JSON.parse(t)}catch{return null}const o=t=>"string"==typeof e[t]&&""!==e[t]?e[t]:null,r=o("sid"),s=o("token"),n=o("host"),i=o("user"),u=o("python"),p=o("outDir"),c=o("keyPem"),m=o("tier");return r&&s&&n&&i&&u&&p&&c?"t4"!==m&&"t4full"!==m&&"cpu"!==m?null:{sid:r,token:s,tier:m,host:n,port:"number"==typeof e.port&&Number.isInteger(e.port)?e.port:22,user:i,python:u,outDir:p,keyPem:c,seenAt:"number"==typeof e.seenAt?e.seenAt:0}:null}export function readCommitteeSession(e=n()){const r=sessionFilePath(e);if(!t(r))return null;try{return parseCommitteeSession(o(r,"utf-8"))}catch{return null}}export function writeCommitteeSession(t,o=n()){const r=sessionFilePath(o);e(i(o,".icoa","gputask"),{recursive:!0}),s(r,`${JSON.stringify(t,null,1)}\n`,{mode:384})}export function clearCommitteeSession(t=n()){try{r(sessionFilePath(t),{force:!0})}catch{}}export function committeeLease(t){return{state:"ready",transport:"ssh",host:t.host,port:t.port,user:t.user,python:t.python,dataRoot:`/home/${t.user}`,outDir:t.outDir,keyPem:t.keyPem,timeLeftSec:0}}export const TIER_LABEL={t4:"T4 capsule · 3.5 GiB fence · 2 vCPU · 6 GB",t4full:"T4 whole card · 16 GB · 8 vCPU · 30 GB",cpu:"CPU slot · 2 vCPU · 6 GB"};