icoa-cli 2.19.705 → 2.19.706
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/gpufortask.js +1 -1
- package/dist/commands/ipynb.js +1 -1
- package/dist/commands/kaggle.js +1 -1
- package/dist/lib/gputask-session.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
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{enterPanel as r,leavePanel as l,printGuide as c,printHelp as d}from"../lib/guide-panel.js";import{clearCommitteeSession as u,readCommitteeSession as p,TIER_LABEL as g,writeCommitteeSession as y}from"../lib/gputask-session.js";import{getMainRl as h}from"../lib/main-rl.js";const f=(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"");let m=[],k=null,w=null,b=[];function $(o){return new Promise(t=>{const n=h();if(n){const e=b.shift();return void 0!==e?(process.stdout.write(`${o}${e}\n`),void t(e)):(w=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 z="en";const v={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=>v[e]?.[z]??e;async function P(e,o){try{const t=await fetch(`${f}/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 G(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{y(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 T(e){return`$${(e??0).toFixed(2)}`}function U(e){const o=e.user??"?";console.log(),console.log(chalk.bold.green(` ${_("readyTitle")}`)+chalk.gray(` ${g[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}",T(e.today_usd)).replace("{B}",T(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 C(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}",T(e.today_usd)).replace("{B}",T(e.daily_cap_usd??5))}`))}let A=!1;const S={id:"gpufortask",title:{en:"Committee GPU seat",zh:"命题组 GPU 席位"},what:{en:"Your seat on a shared GCP GPU box is ready. Work happens in a notebook: open one at icoa> with ipynb, type gpu on there, and its cells run on the box. This screen only watches the seat.",zh:"你在共享 GCP GPU 箱上的席位已就绪。活在 notebook 里干:在 icoa> 用 ipynb 打开一本,在里面敲 gpu on,格子就在箱上跑。这个界面只看席位。"},steps:[{verb:"status",what:{en:"seat state, idle clock, GPU usage, spend",zh:"席位状态、闲置计时、GPU 占用、花费"},done:()=>A},{verb:"stop",what:{en:"end the seat now (asks y/n; files are synced first)",zh:"立即结束席位(先问 y/n;文件先同步)"}},{verb:"lang zh",what:{en:"switch this screen to Chinese (lang en = back)",zh:"切英文:lang en"},optional:!0}],notes:[{en:"quit only leaves this screen — the seat keeps running until 40 min idle; gpufortask brings you back.",zh:"quit 只是离开这个界面 —— 席位会一直保留到闲置 40 分钟;再敲 gpufortask 接回。"}],leave:{verb:"quit",what:{en:"leave this screen (seat stays)",zh:"离开界面(席位保留)"}},guide:()=>console.log(chalk.gray(` ${_("footer")}`))};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(){z="en",A=!1,function(){const e=h();e&&(m=e.listeners("line").slice(),e.removeAllListeners("line"),k=e.prompt.bind(e),e.prompt=o.prototype.prompt.bind(e),e.on("line",e=>{const o=w;w=null,o?o(e):b.push(e)}))}();try{console.log(),console.log(chalk.cyan.bold(` ${_("banner")}`)),console.log(chalk.gray(` ${_("langTip")}`)),console.log();const e=i(),o=p();let n="";for(let s=0;s<3;){const a=(await $(chalk.cyan(` ${_("tokenAsk")}`)+(o?chalk.gray(`[${o.token}] `):""))).trim(),i=a.toLowerCase();if("lang zh"===i){z="zh";continue}if("lang en"===i){z="en";continue}if("quit"===i||"back"===i)return;const r=""===a&&o?o.token:a.toUpperCase().replace(/\s+/g,"");if(!r)continue;const l=await P("status",{token:r,fp:e});if(null===l)return void console.log(chalk.yellow(` ${_("netErr")}`));if("token_device_mismatch"!==l.error){if(!l.error){if(n=r,"none"!==l.state)return console.log(chalk.gray(` ${_("already")}`)),void await t(n,e,l);o&&u(),l.last_ended&&console.log(chalk.gray(` (your previous seat ended: ${l.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 $(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 z="en";else z="zh"}let a="spot";for(;;){const e=(await $(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 z="en";else z="zh"}const r=await P("start",{token:n,fp:e,tier:s,mode:a});if(null===r)return void console.log(chalk.yellow(` ${_("netErr")}`));if("all_seats_busy"===r.error)return void console.log(chalk.yellow(` ${_("seatsBusy")}`));if("daily_cap"===r.error)return void console.log(chalk.yellow(` ${_("dailyCap")}`));if("ctl_unavailable"===r.error)return void console.log(chalk.yellow(` ${_("ctlDown")}`)+chalk.gray(r.detail?` (${r.detail})`:""));if("session_already_active"===r.error){const o=await P("status",{token:n,fp:e});return void(o&&await t(n,e,o))}if(r.error)return void console.log(chalk.yellow(` ${_("failed")}${r.error}`));r.cap_warning&&console.log(chalk.yellow(` ${_("capWarn")}`)),console.log(chalk.gray(` ${_("deploying")}`)),await t(n,e,r)}finally{l(S.id),function(){const e=h();if(e){e.removeAllListeners("line"),k&&(e.prompt=k);for(const o of m)e.on("line",o);m=[],k=null,w=null,b=[]}}()}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}`)),u(),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 r=await P("status",{token:e,fp:o});if(null===r){if(a++,a<=5){console.log(chalk.gray(` (broker did not answer — retrying ${a}/5)`));continue}n=null;break}a=0,n=r}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(G(o,s)||console.log(chalk.yellow(" could not save the session file under ~/.icoa/gputask — gpu on will not find this seat.")),U(s),r(S);;){const n=(await $(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 P("status",{token:o,fp:t});if(n)if("ready"===n.state)n.host&&n.key_pem&&G(o,n),A=!0,C(n);else{if("preempted"!==n.state&&"provisioning"!==n.state&&"creating"!==n.state)return console.log(chalk.gray(` ${_("ended")} (${n.end_reason??n.state})`)),void u();{console.log(chalk.yellow(` ${_("stPreempted")}`));const s=await e(o,t,n);if(!s)return;G(o,s),U(s)}}else console.log(chalk.yellow(` ${_("netErr")}`));continue}if("stop"===n||"end"===n||"destroy"===n||"release"===n){const e=(await $(chalk.yellow(` ${_("stopAsk")}`))).trim().toLowerCase();if("y"===e||"yes"===e)return await P("stop",{token:o,fp:t}),u(),void console.log(chalk.green(` ${_("stopping")}`));continue}"help"!==n&&"/help"!==n&&"?"!==n?"help all"!==n&&"guide"!==n?console.log(chalk.gray(` ${_("footer")}`)):c():d()}else z=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
|
+
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{enterPanel as r,leavePanel as l,printGuide as c,printHelp as d}from"../lib/guide-panel.js";import{clearCommitteeSession as u,readCommitteeSession as p,TIER_LABEL as y,isCommitteeTier as g,writeCommitteeSession as h}from"../lib/gputask-session.js";import{getMainRl as f}from"../lib/main-rl.js";const m=(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"");let k=[],w=null,$=null,b=[];function z(o){return new Promise(t=>{const n=f();if(n){const e=b.shift();return void 0!==e?(process.stdout.write(`${o}${e}\n`),void t(e)):($=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 v="en";const _={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。"},tierMenu:{en:["Seat? (Enter = 1)"," [1] T4 capsule 3.5 GiB — default; tasks that peak under 3 GiB"," [2] T4 double 7 GiB — 2-unit tasks"," [3] T4 whole 16 GB — one card to yourself (LLM-size)"," [4] L4 capsule 3.5 GiB — same fence, faster card"," [5] L4 double 7 GiB"," [6] L4 whole 24 GB"," [7] CPU only 2 vCPU · 6 GB"].join("\n"),zh:["席位?(回车 = 1)"," [1] T4 胶囊 3.5 GiB — 默认;峰值 3 GiB 以内的题"," [2] T4 双格 7 GiB — 2 格题"," [3] T4 整卡 16 GB — 一张卡独占(LLM 题)"," [4] L4 胶囊 3.5 GiB — 同样的围栏,更快的卡"," [5] L4 双格 7 GiB"," [6] L4 整卡 24 GB"," [7] 只要 CPU 2 vCPU · 6 GB"].join("\n")},tierAsk:{en:" > ",zh:" > "},tierBad:{en:"Please type 1–7 (Enter = 1).",zh:"请输入 1–7(回车 = 1)。"},dailyCapFleet:{en:"The committee's GPU budget for today is used up (A$30/day, resets at Sydney midnight). Seats already running are not affected — try again tomorrow, or ask the coordinator.",zh:"命题组今天的 GPU 预算已用完(每天 A$30,悉尼午夜重置)。在跑的席位不受影响 — 明天再试,或联系协调人。"},fleet:{en:"committee fleet today: {A} of {B} (A$30/day)",zh:"命题组今日车队花费:{A} / {B}(每天 A$30)"},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 — 没有限制,纯提示 🙂"}},G=e=>_[e]?.[v]??e;async function P(e,o){try{const t=await fetch(`${m}/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 C(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{h(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 T(e){return`$${(e??0).toFixed(2)}`}function U(e){const o=e.user??"?";console.log(),console.log(chalk.bold.green(` ${G("readyTitle")}`)+chalk.gray(` ${y[e.tier??"t4"]} · ${e.zone??""} · ${"ondemand"===e.mode?"on-demand":"Spot"}`)),console.log(),console.log(chalk.white(` ${G("how1")}`)),console.log(chalk.bold.cyan(" icoa> ipynb ~/Desktop/task.ipynb")+chalk.gray(` ${G("how2")}`)),console.log(chalk.bold.cyan(" icoa ipynb> gpu on")+chalk.gray(` ${G("how3")}`)),console.log(chalk.bold.cyan(" icoa ipynb> upload data.csv")+chalk.gray(` ${G("how4")}`)),console.log(),console.log(chalk.gray(` ${G("advanced")}`)),console.log(chalk.gray(` ssh -i ~/.icoa/gputask/key ${o}@${e.host??"?"}`)),console.log(),console.log(chalk.yellow(` ${G("clock").replace("{U}",o)}`)),console.log(chalk.gray(` ${G("spend").replace("{A}",T(e.today_usd)).replace("{B}",T(e.daily_cap_usd??5))}`)+chalk.gray(` · ${e.rate??"?"}/h`)),e.fleet_cap_usd&&console.log(chalk.gray(` ${B(e)}`)),e.weekly_soft_over&&console.log(chalk.gray(` ${G("weekly").replace("{H}",String(e.weekly_hours??0))}`)),console.log(),console.log(chalk.gray(` ${G("footer")}`))}function A(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(`${G("busy")} (${n.why})`):chalk.yellow(`${G("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(` ${G("spend").replace("{A}",T(e.today_usd)).replace("{B}",T(e.daily_cap_usd??5))}`)),e.fleet_cap_usd&&console.log(chalk.gray(` ${B(e)}`))}function B(e){return G("fleet").replace("{A}",T(e.fleet_today_usd)).replace("{B}",T(e.fleet_cap_usd))}export function parseTierChoice(e){const o=e.trim().toLowerCase(),t={"":"t4",1:"t4",2:"t4x2",3:"t4full",4:"l4",5:"l4x2",6:"l4full",7:"cpu"};if(o in t)return t[o];if(g(o))return o;if(o.includes("cpu"))return"cpu";const n=o.includes("l4")?"l4":"t4";return o.includes("whole")||o.includes("full")||o.includes("整卡")?`${n}full`:o.includes("double")||o.includes("x2")||o.includes("双格")||o.includes("2 格")||o.includes("7")?`${n}x2`:o.includes("capsule")||o.includes("胶囊")||"t4"===o||"l4"===o?n:null}let S=!1;const x={id:"gpufortask",title:{en:"Committee GPU seat",zh:"命题组 GPU 席位"},what:{en:"Your seat on a shared GCP GPU box is ready. Work happens in a notebook: open one at icoa> with ipynb, type gpu on there, and its cells run on the box. This screen only watches the seat.",zh:"你在共享 GCP GPU 箱上的席位已就绪。活在 notebook 里干:在 icoa> 用 ipynb 打开一本,在里面敲 gpu on,格子就在箱上跑。这个界面只看席位。"},steps:[{verb:"status",what:{en:"seat state, idle clock, GPU usage, spend",zh:"席位状态、闲置计时、GPU 占用、花费"},done:()=>S},{verb:"stop",what:{en:"end the seat now (asks y/n; files are synced first)",zh:"立即结束席位(先问 y/n;文件先同步)"}},{verb:"lang zh",what:{en:"switch this screen to Chinese (lang en = back)",zh:"切英文:lang en"},optional:!0}],notes:[{en:"quit only leaves this screen — the seat keeps running until 40 min idle; gpufortask brings you back.",zh:"quit 只是离开这个界面 —— 席位会一直保留到闲置 40 分钟;再敲 gpufortask 接回。"}],leave:{verb:"quit",what:{en:"leave this screen (seat stays)",zh:"离开界面(席位保留)"}},guide:()=>console.log(chalk.gray(` ${G("footer")}`))};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(){v="en",S=!1,function(){const e=f();e&&(k=e.listeners("line").slice(),e.removeAllListeners("line"),w=e.prompt.bind(e),e.prompt=o.prototype.prompt.bind(e),e.on("line",e=>{const o=$;$=null,o?o(e):b.push(e)}))}();try{console.log(),console.log(chalk.cyan.bold(` ${G("banner")}`)),console.log(chalk.gray(` ${G("langTip")}`)),console.log();const e=i(),o=p();let n="";for(let s=0;s<3;){const a=(await z(chalk.cyan(` ${G("tokenAsk")}`)+(o?chalk.gray(`[${o.token}] `):""))).trim(),i=a.toLowerCase();if("lang zh"===i){v="zh";continue}if("lang en"===i){v="en";continue}if("quit"===i||"back"===i)return;const r=""===a&&o?o.token:a.toUpperCase().replace(/\s+/g,"");if(!r)continue;const l=await P("status",{token:r,fp:e});if(null===l)return void console.log(chalk.yellow(` ${G("netErr")}`));if("token_device_mismatch"!==l.error){if(!l.error){if(n=r,"none"!==l.state)return console.log(chalk.gray(` ${G("already")}`)),void await t(n,e,l);o&&u(),l.last_ended&&console.log(chalk.gray(` (your previous seat ended: ${l.last_ended} — files were kept)`));break}console.log(chalk.yellow(` ${G("tokenBad")}`)),s++}else console.log(chalk.yellow(` ${G("tokenDevice")}`)),s++}if(!n)return void console.log(chalk.yellow(` ${G("tokenGiveUp")}`));let s="";for(console.log(chalk.cyan(` ${G("tierMenu").split("\n").join("\n ")}`));!s;){const e=(await z(chalk.cyan(G("tierAsk")))).trim().toLowerCase();if("lang zh"===e){v="zh";continue}if("lang en"===e){v="en";continue}if("quit"===e||"back"===e)return;const o=parseTierChoice(e);o?s=o:console.log(chalk.yellow(` ${G("tierBad")}`))}let a="spot";for(;;){const e=(await z(chalk.cyan(` ${G("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 v="en";else v="zh"}const r=await P("start",{token:n,fp:e,tier:s,mode:a});if(null===r)return void console.log(chalk.yellow(` ${G("netErr")}`));if("all_seats_busy"===r.error)return void console.log(chalk.yellow(` ${G("seatsBusy")}`));if("daily_cap"===r.error)return void console.log(chalk.yellow(` ${G("dailyCap")}`));if("daily_cap_fleet"===r.error)return console.log(chalk.yellow(` ${G("dailyCapFleet")}`)),void console.log(chalk.gray(` ${B(r)}`));if("ctl_unavailable"===r.error)return void console.log(chalk.yellow(` ${G("ctlDown")}`)+chalk.gray(r.detail?` (${r.detail})`:""));if("session_already_active"===r.error){const o=await P("status",{token:n,fp:e});return void(o&&await t(n,e,o))}if(r.error)return void console.log(chalk.yellow(` ${G("failed")}${r.error}`));r.cap_warning&&console.log(chalk.yellow(` ${G("capWarn")}`)),console.log(chalk.gray(` ${G("deploying")}`)),await t(n,e,r)}finally{l(x.id),function(){const e=f();if(e){e.removeAllListeners("line"),w&&(e.prompt=w);for(const o of k)e.on("line",o);k=[],w=null,$=null,b=[]}}()}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(` ${G("failed")}${n.end_reason??n.state}`)),u(),null;const t="creating"===n.state?G("stCreating"):"preempted"===n.state?G("stPreempted"):G("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 r=await P("status",{token:e,fp:o});if(null===r){if(a++,a<=5){console.log(chalk.gray(` (broker did not answer — retrying ${a}/5)`));continue}n=null;break}a=0,n=r}return n||(console.log(chalk.yellow(` ${G("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(C(o,s)||console.log(chalk.yellow(" could not save the session file under ~/.icoa/gputask — gpu on will not find this seat.")),U(s),r(x);;){const n=(await z(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(` ${G("quitNote")}`));if("status"===n||"s"===n||"time"===n||"stats"===n||"top"===n){const n=await P("status",{token:o,fp:t});if(n)if("ready"===n.state)n.host&&n.key_pem&&C(o,n),S=!0,A(n);else{if("preempted"!==n.state&&"provisioning"!==n.state&&"creating"!==n.state)return console.log(chalk.gray(` ${G("ended")} (${n.end_reason??n.state})`)),void u();{console.log(chalk.yellow(` ${G("stPreempted")}`));const s=await e(o,t,n);if(!s)return;C(o,s),U(s)}}else console.log(chalk.yellow(` ${G("netErr")}`));continue}if("stop"===n||"end"===n||"destroy"===n||"release"===n){const e=(await z(chalk.yellow(` ${G("stopAsk")}`))).trim().toLowerCase();if("y"===e||"yes"===e)return await P("stop",{token:o,fp:t}),u(),void console.log(chalk.green(` ${G("stopping")}`));continue}"help"!==n&&"/help"!==n&&"?"!==n?"help all"!==n&&"guide"!==n?console.log(chalk.gray(` ${G("footer")}`)):c():d()}else v=n.endsWith("zh")?"zh":"en",console.log(chalk.gray(` ${G("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))}})}
|
package/dist/commands/ipynb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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 b}from"../lib/config.js";import{editTextInEditor as k,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as S,parseLeaseResponse as E,queueLine as C,windowLine as 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 T,setMainRl as O}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 z,mergeReloadedCells as K,normalizePathArg as R,parseIpynb as B,parsePercentPy as F,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{enterPanel as Q,leavePanel as ee,printHelp as oe}from"../lib/guide-panel.js";import{lazyFile as ne}from"../lib/lazy-assets.js";import{openFile as te}from"../lib/open-file.js";const le=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function re(){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 ae(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const se=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),ie=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function ce(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const ge="https://practice.icoa2026.au";function ye(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):ge}function de(){return u(a(),".icoa","gpu-key")}function ue(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return t(de(),"utf-8").trim()||null}catch{return null}}async function he(e,o,n){try{const t=await fetch(`${ye()}/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 pe(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let fe=0,me=null;function we(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(le,"")}`))}else"display"===n.kind&&be(n.data,o)}function be(e,n){if(e["image/png"])try{o(n,{recursive:!0}),fe+=1;const t=u(n,`figure-${fe}.png`);return r(t,Buffer.from(e["image/png"],"base64")),me=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(te(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 ke(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function ve(e){if(e)try{return l(e).mtimeMs}catch{return}}function $e(o){const n=R(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")?B(e):F(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:ve(l),diskSig:ke(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 _e={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const ge=E?.trim().toLowerCase().replace(/-demo$/,"");if(ge&&_e[ge]){const n=await async function(n){const l=_e[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 ne(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}(ge);if(!n)return;E=n}const fe=p(a()),be=u(a(),".icoa","ipynb-out");if(ae(),!e(fe.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 xe=E?$e(E):null,Pe=xe?xe.doc:{cells:[],path:null,dirty:!1};let Se=new I({venvPython:fe.python,venvRoot:fe.root}),Ee=null,Ce=null,Ge=null,je=pe(Pe.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Se.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.")),xe&&console.log(xe.note);let Ue=!1,Ae=!1;Q({id:"ipynb",title:{en:"Notebook",zh:"Notebook 笔记本"},what:{en:"A Jupyter notebook inside the terminal: cells run one by one in a live Python kernel. You are already inside it — never type python file.ipynb here.",zh:"终端里的 Jupyter notebook:cell 在常驻 Python 内核里逐格运行。你已经在 notebook 里面了 —— 不要再敲 python file.ipynb。"},steps:[{verb:"cells",what:{en:"list the cells (md = explanation, ○ = not run yet)",zh:"列出所有 cell(md = 讲解,○ = 还没跑)"},done:()=>Ue},{verb:"run all",what:{en:"run every cell top to bottom; stops at the first error",zh:"从头到尾跑每一格;遇到第一个报错就停"},done:()=>Pe.cells.some(e=>null!==e.result)},{verb:"edit",what:{en:"open the WHOLE notebook in your editor (edit 3 = one cell)",zh:"整本在编辑器里打开(edit 3 = 只开第 3 格)"},done:()=>Pe.dirty},{verb:"save",what:{en:"write it back to disk as a real .ipynb",zh:"存回磁盘,标准 .ipynb"},done:()=>Ae},{verb:"gpu on",what:{en:"run the cells on a GPU box (a T4 starts for you, ~1–2 min); gpu off hands it back",zh:"把 cell 搬到 GPU 上跑(T4 按需开机约 1–2 分钟);gpu off 归还"},done:()=>null!==Ee,optional:!0},{verb:"ai 4",what:{en:"ask the tutor why cell 4 did that (ai = the last error)",zh:"问导师第 4 格为什么这样(裸 ai = 最后一个报错)"},optional:!0}],notes:[{en:"Plain Python typed at the prompt runs as a new cell (a blank line ends a block). help all = every command.",zh:"直接敲 Python 就是新的一格(空行结束多行块)。help all = 全部命令。"}],leave:{verb:"quit",what:{en:"leave the notebook",zh:"离开 notebook"}},guide:()=>Je()});const Ie=T(),Ne=null!==Ie,Te=Ne?Ie.listeners("line").slice():[];Ne&&Ie.removeAllListeners("line");const Oe=Ne?Ie:c({input:process.stdin,output:process.stdout,terminal:!0});Ne||O(Oe);const Me=Ne?Oe.prompt:null,De=Ne?Oe.getPrompt():"";Ne&&(Oe.prompt=i.prototype.prompt),Ne||D();const qe=[];let Le,ze=!1,Ke=!1,Re=!1,Be=null,Fe=null;const We=()=>{if(Fe)return Oe.setPrompt(chalk.bold.cyan(` editor 1-${Fe.options.length} > `)),void Oe.prompt();const e=Ee?"icoa ipynb ⚡gpu":"icoa ipynb";Oe.setPrompt(chalk.bold.cyan(qe.length?`${e} ...> `:`${e}> `)),Oe.prompt()},Je=()=>{const o=Pe.path?y(Pe.path):process.cwd(),n=pe(Pe.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=Pe.cells.filter(e=>null!==e.result).length,s=e(u(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Pe.path?g(Pe.path):"new empty notebook")+chalk.gray(` · ${Pe.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Ee?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(n?" — trains the baseline, writes submission.csv":" — runs every cell top to bottom")),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()};let Ve=()=>{};const Ye=new Promise(e=>{Ve=e}),He=async()=>{Se=new I({venvPython:fe.python,venvRoot:fe.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Se.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"))}},Xe=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=Pe.path?g(y(Pe.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 Se.shutdown().catch(()=>{}),Se=h,Ee={...t,outDir:c},Ge=e,Ce=Date.now(),h.onUnexpectedExit=()=>{Se===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).")),Ee=null,Ge=null,Ce=null,He().then(()=>We()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${Z[e.tier]} · cells run in ${c}`));const p=await Ze();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},Ze=async()=>{if(!Pe.path||!Ee?.outDir)return 0;const e=y(Pe.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 Se.putFile(`${Ee.outDir}/${n}`,t(o)),r++}catch{}}return r},Qe=async e=>{const[n,...t]=e.trim().split(/\s+/),l=(n??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ee)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 Xe(e)})(e);const n=ue();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)."));je||(je=pe(Pe.path));const t=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await he("lease",n,je??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 he("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 he("release",n);const y=je?`${l.dataRoot}/${je}`: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 he("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 he("release",n)}await Se.shutdown().catch(()=>{}),Se=p,Ee=l,Ce=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.")),je&&console.log(chalk.gray(` Dataset is already on the box (${je}) — 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(Ee&&Ge){const e=Ce?Math.round((Date.now()-Ce)/1e3):0;return await Se.shutdown().catch(()=>{}),Ee=null,Ge=null,Ce=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 He()}if(!Ee)return void console.log(chalk.gray(" not on a GPU kernel."));const e=ue(),o=void 0!==Ee.gpuName,n=Ce?Math.round((Date.now()-Ce)/1e3):0;await Se.shutdown().catch(()=>{}),e&&await he("release",e),Ee=null,Ce=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 He()})():"status"===l||""===l?await(async()=>{const e=X();if(e)return console.log(chalk.green(` ⚡ committee seat · ${Z[e.tier]} · ${e.host}`)+chalk.gray(Ge?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=ue();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const n=await he("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(Ee?" (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=ue();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(`${ye()}/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(0===n?" (no box up — gpu on starts a T4 for you, ~1–2 min)":" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",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(de(),`${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(` (${de()})`))}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>"))},eo=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Pe.cells.length?(console.log(0===Pe.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Pe.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Pe.cells[o-1],idx:o}},oo=(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 no=!1;const to=()=>{const e=w().notebookEditor;return e?_(e):null},lo=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),ro=()=>to()??x(),ao={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"},so=(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(to()||lo())return o(ro()),!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(` ${ao[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),Fe={resume:o,tries:0,options:n},!1)},io=e=>{if(!Pe.path)return!1;let o;try{const e=t(Pe.path,"utf8");o=Pe.path.endsWith(".ipynb")?B(e):F(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=K(Pe.cells,o);return Pe.cells=n.cells,Pe.dirty=!1,Pe.mtimeMs=ve(Pe.path),Pe.diskSig=ke(o),Le=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Pe.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},co=()=>void 0!==Pe.diskSig?ke(Pe.cells)!==Pe.diskSig:Pe.dirty,go=(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)),yo=async n=>{if(n.trim()&&M(`ipynb: ${n.trim()}`),Ke)return void(n.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Fe){const e=Fe,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?(Fe=null,b({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)?(Fe=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Fe=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 We()}let l=n.trim();if(0===qe.length&&/^icoa\s+[a-z/]/i.test(l)&&(l=l.replace(/^icoa\s+/i,"")),0===qe.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&&(Re=!1),Be&&i!==Be&&(Be=null),ie.has(i)&&(()=>{if(!Pe.path||void 0===Pe.mtimeMs)return;const e=ve(Pe.path);if(void 0!==e&&e!==Pe.mtimeMs){if(co()){if(Le===e)return;return Le=e,console.log(chalk.yellow(` ⚠ ${g(Pe.path)} changed in your editor, and this notebook has unsaved changes too.`)),void console.log(chalk.gray(" take the file: ")+chalk.cyan("reload")+chalk.gray(" · keep these and overwrite the file: ")+chalk.cyan("save"))}io(!0)}})(),"quit"===i||"exit"===i||"back"===i||"q"===i||"menu"===i)return Pe.dirty&&!Re?(Re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void We()):void await(async()=>{if(ee("ipynb"),Oe.removeAllListeners("line"),Ne||q(),console.log(),Ee&&Ge)Ee=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(Ee){const e=ue();e&&await he("release",e),Ee=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Se.shutdown().catch(()=>{}),Ne){Me&&(Oe.prompt=Me),Oe.setPrompt(De);for(const e of Te)Oe.on("line",e);Oe.prompt(),Ve()}else O(null),Ve(),Oe.close()})();if("clear"===i||"cls"===i)return console.clear(),ae(),void We();if("restart"===i)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Se.shutdown().catch(()=>{});try{await Se.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 We();if("help"===i||"?"===i)return/^(all|commands|full)$/i.test(c.trim())?(console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor vi")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(re()?" 问 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()):oe(),void We();if("guide"===i||"/guide"===i)return Je(),void We();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 We();if("open"===i&&""===c)return me&&te(me)?console.log(chalk.gray(" reopening ")+chalk.cyan(me)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void We();if("cells"===i||"ls"===i)return(()=>{if(Ue=!0,0===Pe.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);Pe.cells.forEach((o,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 We();if("show"===i)return(e=>{const o=eo(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 ──")),we(o.cell.result,be)),console.log()}})(c),void We();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?so(o,e=>(e=>{Oe.pause();const o=k(Y(Pe.cells),".py",e,"notebook");if(Oe.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=z(o,Pe.cells);if(n.same)return void console.log(chalk.gray(" no changes."));if(0===n.cells.length&&Pe.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${Pe.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));Pe.cells=n.cells,Pe.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 — ${Pe.cells.length} cells`)+chalk.gray(` · ${t.join(" · ")}`));const l=[...n.changed,...n.added].filter(e=>"code"===Pe.cells[e-1].kind).sort((e,o)=>e-o);if(l.length){const e=l[0],o=l[l.length-1];console.log(chalk.gray(" unchanged cells kept their output · run what changed: ")+chalk.cyan(e===o?`run ${e}`:`run ${e}-${o}`)+chalk.gray(" · or ")+chalk.cyan("run all"))}})(e)):eo(n)&&so(o,e=>((e,o)=>{const n=eo(e);if(!n)return;Oe.pause();const t=k(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(Oe.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,Pe.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 We()}if("add"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ");return so(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)"));Oe.pause();const l=k(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);Oe.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Pe.cells.push({kind:t?"markdown":"code",source:r,result:null}),Pe.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${Pe.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Pe.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void We()}if("editor"===i&&/^[\w-]*$/.test(c))return(e=>{const o=e.trim().toLowerCase(),n=$(ro());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${to()?"saved":lo()?"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?` ${ao[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 b({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const 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);to()&&$(to())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(t.cmd)?(b({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 We();if("reload"===i&&""===c)return Pe.path&&e(Pe.path)?co()&&"reload"!==Be?(Be="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."))):(Be=null,io(!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 We();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 We();const o=R(c,a()),n=d(o)?o:h(process.cwd(),o);if(e(n))if(Pe.dirty&&"load"!==Be)Be="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{Be=null;const e=$e(n);Pe.cells=e.doc.cells,Pe.path=e.doc.path,Pe.dirty=!1,Pe.mtimeMs=e.doc.mtimeMs,Pe.diskSig=e.doc.diskSig,Le=void 0,je=pe(Pe.path),console.log(e.note),console.log(chalk.gray(" the kernel keeps its variables — ")+chalk.cyan("restart")+chalk.gray(" for a clean start."))}else console.log(chalk.yellow(" no such file: ")+chalk.white(n)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void We()}if("del"===i||"delete"===i)return(e=>{const o=eo(e);o&&(Pe.cells.splice(o.idx-1,1),Pe.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Pe.cells.length} left.`)+(o.idx<=Pe.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(c),void We();if(("md"===i||"py"===i)&&/^\d+$/.test(c))return((e,o)=>{const n=eo(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,Pe.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 We();if("gpu"===i)return Ke=!0,await Qe(c),Ke=!1,void We();if("download"===i||"dl"===i)return Ke=!0,await(async e=>{if(!Ee)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:`${Ee.outDir}/${n}`;let l;try{l=await Se.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=je?u(process.cwd(),"icoa-kaggle",je):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)`)),je&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${je}`)+chalk.gray(" — then upload on Kaggle yourself."))})(c),Ke=!1,void We();if("selfcheck"===i||"self-check"===i)return Ke=!0,await(async()=>{const e=Ge;if(!e||!Ee)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===Pe.cells.filter(e=>"code"===e.kind).length)return void console.log(chalk.yellow(" nothing to check — the notebook has no code cells."));console.log(chalk.bold.cyan(" 🔬 selfcheck")+chalk.gray(` · fresh kernel · ${Z[e.tier]} · every code cell from the top`));const o=Se;if(await Xe(e,!0),Se===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<Pe.cells.length;e++){const o=Pe.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 Se.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}Pe.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){we(o.result,be),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 Se.execute(a)).outputs.filter(e=>"stream"===e.kind).map(e=>"stream"===e.kind?e.text:"").join("").split("\n").find(e=>e.startsWith("ICOA_SELFCHECK "));e&&(s=JSON.parse(e.slice(15)))}catch{}const i="number"==typeof s.peak_gib?s.peak_gib:null,c=null===i?null:i<3?1:i<6.5?2:i<10?3:0,y={sid:e.sid,tier:e.tier,notebook:Pe.path?g(Pe.path):null,cells: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."))}})(),Ke=!1,void We();if("upload"===i||"up"===i||"put"===i)return Ke=!0,await(async e=>{if(!Ee)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=R(o,a()),l=d(n)?n:h(Pe.path?y(Pe.path):process.cwd(),n);let r;try{r=t(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${Ee.outDir}/${g(l)}`;try{const e=await Se.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),Ke=!1,void We();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])||pe(Pe.path)||void 0;Ke=!0;try{if("submit"===n){const o=s("sha256").update(Pe.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(t,{code_sha:o,...Ge?{sid:Ge.sid}:{},...Pe.path?{notebook:g(Pe.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 Ke=!1,void We()}if("board"===i){const{runBoard:e}=await import("./board.js"),o=c.split(/\s+/).filter(Boolean);Ke=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ke=!1,void We()}if("ai"===i||"/ai"===i)return Ke=!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=Pe.cells.length-1;e>=0;e--)if((Pe.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Pe.cells.length;if(0===Pe.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=eo(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(le,"")).join("\n")));return o.join("\n").replace(le,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Pe.path||!pe(Pe.path))return"";try{const e=JSON.parse(t(u(y(Pe.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return oo(o,350)}catch{return""}})(),c=re(),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=oo(a.cell.source,Math.floor(.6*h)),w=s?(b=s,k=h-p.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[g,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${p}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",l?`\n[question]\n${l}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),_=c;console.log(),no||(no=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(re()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${re()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(re()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(re()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — 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),Ke=!1,void We();if("run"===i)return Ke=!0,await(async e=>{const o=W(e,Pe.cells.length);if(o)for(const e of o){const n=Pe.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 Se.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void ce()}if(Pe.dirty=!0,we(n.result,be),go(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(re()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(re()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void ce()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(n.source))console.log(e);console.log()}}else console.log(0===Pe.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(c),Ke=!1,void We();if("save"===i)return(e=>{if(0===Pe.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?d(e.trim())?e.trim():h(process.cwd(),e.trim()):Pe.path?Pe.path.endsWith(".ipynb")?Pe.path:`${Pe.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===Pe.path?ve(o):void 0;if(void 0!==n&&void 0!==Pe.mtimeMs&&n!==Pe.mtimeMs&&"save"!==Be)return Be="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"));Be=null;try{r(o,J(Pe.cells)),Pe.path=o,Ae=!0,Pe.dirty=!1,Pe.mtimeMs=ve(o),Pe.diskSig=ke(Pe.cells),Le=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Pe.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(c),void We();if(""===l)return void We()}if(qe.length>0&&se.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 We();if(qe.push(n),!j(qe))return 1!==qe.length||ze||(ze=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void We();const i=qe.join("\n").replace(/\s+$/,"");if(qe.length=0,""!==i.trim()){Ke=!0;try{const e=await Se.execute(i);Pe.cells.push({kind:"code",source:i,result:e}),Pe.dirty=!0,we(e,be);const o=go(Pe.cells[Pe.cells.length-1],Pe.cells.length);e.ok||o||ce()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),ce()}Ke=!1,We()}else We()};Oe.on("line",e=>{yo(e)}),Ne||Oe.on("close",async()=>{await Se.shutdown().catch(()=>{}),process.exit(0)}),We(),await Ye}
|
|
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 m,askIoaiOneShot as f}from"./ai4ioai.js";import{getConfig as w,saveConfig as b}from"../lib/config.js";import{editTextInEditor as k,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as S,parseLeaseResponse as E,queueLine as C,windowLine as 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 T,setMainRl as O}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 z,mergeReloadedCells as R,normalizePathArg as K,parseIpynb as B,parsePercentPy as F,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{enterPanel as Q,leavePanel as ee,printHelp as oe}from"../lib/guide-panel.js";import{lazyFile as ne}from"../lib/lazy-assets.js";import{openFile as te}from"../lib/open-file.js";const le=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function re(){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 ae(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const se=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),ie=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function ce(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const ge="https://practice.icoa2026.au";function ye(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):ge}function de(){return u(a(),".icoa","gpu-key")}function ue(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return t(de(),"utf-8").trim()||null}catch{return null}}async function he(e,o,n){try{const t=await fetch(`${ye()}/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 pe(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let me=0,fe=null;function we(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(le,"")}`))}else"display"===n.kind&&be(n.data,o)}function be(e,n){if(e["image/png"])try{o(n,{recursive:!0}),me+=1;const t=u(n,`figure-${me}.png`);return r(t,Buffer.from(e["image/png"],"base64")),fe=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(te(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 ke(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function ve(e){if(e)try{return l(e).mtimeMs}catch{return}}function $e(o){const n=K(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")?B(e):F(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:ve(l),diskSig:ke(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 _e={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const ge=E?.trim().toLowerCase().replace(/-demo$/,"");if(ge&&_e[ge]){const n=await async function(n){const l=_e[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 ne(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}(ge);if(!n)return;E=n}const me=p(a()),be=u(a(),".icoa","ipynb-out");ae();const xe=e(me.python),Pe=X();if(!xe&&!Pe)return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),console.log(chalk.gray(" (Committee seat holders: open the seat with ")+chalk.cyan("gpufortask")+chalk.gray(" and the notebook runs there instead.)")),void console.log();const Se=E?$e(E):null,Ee=Se?Se.doc:{cells:[],path:null,dirty:!1};let Ce=new I({venvPython:me.python,venvRoot:me.root}),Ge=null,je=null,Ue=null,Ae=pe(Ee.path);if(xe){process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Ce.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready."))}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — cells run on your committee seat: type ")+chalk.bold.green("gpu on")+chalk.gray("."));Se&&console.log(Se.note);let Ie=!1,Ne=!1;Q({id:"ipynb",title:{en:"Notebook",zh:"Notebook 笔记本"},what:{en:"A Jupyter notebook inside the terminal: cells run one by one in a live Python kernel. You are already inside it — never type python file.ipynb here.",zh:"终端里的 Jupyter notebook:cell 在常驻 Python 内核里逐格运行。你已经在 notebook 里面了 —— 不要再敲 python file.ipynb。"},steps:[{verb:"cells",what:{en:"list the cells (md = explanation, ○ = not run yet)",zh:"列出所有 cell(md = 讲解,○ = 还没跑)"},done:()=>Ie},{verb:"run all",what:{en:"run every cell top to bottom; stops at the first error",zh:"从头到尾跑每一格;遇到第一个报错就停"},done:()=>Ee.cells.some(e=>null!==e.result)},{verb:"edit",what:{en:"open the WHOLE notebook in your editor (edit 3 = one cell)",zh:"整本在编辑器里打开(edit 3 = 只开第 3 格)"},done:()=>Ee.dirty},{verb:"save",what:{en:"write it back to disk as a real .ipynb",zh:"存回磁盘,标准 .ipynb"},done:()=>Ne},{verb:"gpu on",what:{en:"run the cells on a GPU box (a T4 starts for you, ~1–2 min); gpu off hands it back",zh:"把 cell 搬到 GPU 上跑(T4 按需开机约 1–2 分钟);gpu off 归还"},done:()=>null!==Ge,optional:!0},{verb:"ai 4",what:{en:"ask the tutor why cell 4 did that (ai = the last error)",zh:"问导师第 4 格为什么这样(裸 ai = 最后一个报错)"},optional:!0}],notes:[{en:"Plain Python typed at the prompt runs as a new cell (a blank line ends a block). help all = every command.",zh:"直接敲 Python 就是新的一格(空行结束多行块)。help all = 全部命令。"}],leave:{verb:"quit",what:{en:"leave the notebook",zh:"离开 notebook"}},guide:()=>Ye()});const Te=T(),Oe=null!==Te,Me=Oe?Te.listeners("line").slice():[];Oe&&Te.removeAllListeners("line");const De=Oe?Te:c({input:process.stdin,output:process.stdout,terminal:!0});Oe||O(De);const qe=Oe?De.prompt:null,Le=Oe?De.getPrompt():"";Oe&&(De.prompt=i.prototype.prompt),Oe||D();const ze=[];let Re,Ke=!1,Be=!1,Fe=!1,We=null,Je=null;const Ve=()=>{if(Je)return De.setPrompt(chalk.bold.cyan(` editor 1-${Je.options.length} > `)),void De.prompt();const e=Ge?"icoa ipynb ⚡gpu":"icoa ipynb";De.setPrompt(chalk.bold.cyan(ze.length?`${e} ...> `:`${e}> `)),De.prompt()},Ye=()=>{const o=Ee.path?y(Ee.path):process.cwd(),n=pe(Ee.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=Ee.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(Ee.path?g(Ee.path):"new empty notebook")+chalk.gray(` · ${Ee.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Ge?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(n?" — trains the baseline, writes submission.csv":" — runs every cell top to bottom")),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()};let He=()=>{};const Xe=new Promise(e=>{He=e}),Ze=async()=>{if(Ce=new I({venvPython:me.python,venvRoot:me.root}),e(me.python)){process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Ce.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — ")+chalk.cyan("gpu on")+chalk.gray(" reconnects to your seat."))},Qe=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=Ee.path?g(y(Ee.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 Ce.shutdown().catch(()=>{}),Ce=h,Ge={...t,outDir:c},Ue=e,je=Date.now(),h.onUnexpectedExit=()=>{Ce===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).")),Ge=null,Ue=null,je=null,Ze().then(()=>Ve()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${Z[e.tier]} · cells run in ${c}`));const p=await eo();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},eo=async()=>{if(!Ee.path||!Ge?.outDir)return 0;const e=y(Ee.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 Ce.putFile(`${Ge.outDir}/${n}`,t(o)),r++}catch{}}return r},oo=async(e,n=!1)=>{if(!Ge)return n||console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed).")),!1;const t=e.trim()||"submission.csv",l=t.startsWith("/")?t:`${Ge.outDir}/${t}`;let a;try{a=await Ce.fetchFile(l)}catch(e){return console.log(chalk.yellow(` could not fetch ${l}: `)+chalk.gray(e instanceof Error?e.message:String(e))),console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)")),!1}const s=Ae?u(process.cwd(),"icoa-kaggle",Ae):process.cwd(),i=u(s,g(t));try{o(s,{recursive:!0}),r(i,a)}catch{return console.log(chalk.yellow(" could not write the file here — check directory permissions.")),!1}return console.log(chalk.green(" ✓ downloaded ")+chalk.white(i)+chalk.gray(` (${a.length} bytes)`)),!n&&Ae&&"submission.csv"===g(t)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Ae}`)+chalk.gray(" · score it: ")+chalk.cyan("submit")),!0},no=async e=>{const[n,...t]=e.trim().split(/\s+/),l=(n??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ge)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 Qe(e)})(e);const n=ue();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)."));Ae||(Ae=pe(Ee.path));const t=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await he("lease",n,Ae??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 he("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 he("release",n);const y=Ae?`${l.dataRoot}/${Ae}`: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 he("release",n)}h={command:"ssh",args:P(l,e,d)}}const p=new I({spawnSpec:h,readyTimeoutMs:9e4}),m=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 he("release",n)}await Ce.shutdown().catch(()=>{}),Ce=p,Ge=l,je=Date.now();const f=Math.round((l.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected")+chalk.gray(` (${Math.round((Date.now()-m)/1e3)} s).`)),console.log(chalk.gray(` Cells now run on the ${l.gpuName?`${l.gpuName} `:""}GPU box · ${f}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.")),Ae&&console.log(chalk.gray(` Dataset is already on the box (${Ae}) — 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(Ge&&Ue){const e=je?Math.round((Date.now()-je)/1e3):0;return await Ce.shutdown().catch(()=>{}),Ge=null,Ue=null,je=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 Ze()}if(!Ge)return void console.log(chalk.gray(" not on a GPU kernel."));const e=ue(),o=void 0!==Ge.gpuName,n=je?Math.round((Date.now()-je)/1e3):0;await Ce.shutdown().catch(()=>{}),e&&await he("release",e),Ge=null,je=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 Ze()})():"status"===l||""===l?await(async()=>{const e=X();if(e)return console.log(chalk.green(` ⚡ committee seat · ${Z[e.tier]} · ${e.host}`)+chalk.gray(Ue?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=ue();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const n=await he("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(Ge?" (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=ue();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(`${ye()}/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(0===n?" (no box up — gpu on starts a T4 for you, ~1–2 min)":" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",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(de(),`${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(` (${de()})`))}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>"))},to=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Ee.cells.length?(console.log(0===Ee.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Ee.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Ee.cells[o-1],idx:o}},lo=(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 ro=!1;const ao=()=>{const e=w().notebookEditor;return e?_(e):null},so=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),io=()=>ao()??x(),co={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"},go=(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(ao()||so())return o(io()),!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(` ${co[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),Je={resume:o,tries:0,options:n},!1)},yo=e=>{if(!Ee.path)return!1;let o;try{const e=t(Ee.path,"utf8");o=Ee.path.endsWith(".ipynb")?B(e):F(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(Ee.cells,o);return Ee.cells=n.cells,Ee.dirty=!1,Ee.mtimeMs=ve(Ee.path),Ee.diskSig=ke(o),Re=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Ee.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},uo=()=>void 0!==Ee.diskSig?ke(Ee.cells)!==Ee.diskSig:Ee.dirty,ho=(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)),po=async o=>{if(o.trim()&&M(`ipynb: ${o.trim()}`),Be)return void(o.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Je){const e=Je,n=o.trim().toLowerCase(),t=_(n),l=/^\d+$/.test(n)?e.options[Number(n)-1]:t?e.options.find(e=>$(e)===$(t)):void 0;return l?(Je=null,b({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===n||["q","quit","back","cancel","exit"].includes(n)?(Je=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Je=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 Ve()}let n=o.trim();if(0===ze.length&&/^icoa\s+[a-z/]/i.test(n)&&(n=n.replace(/^icoa\s+/i,"")),0===ze.length){const o=n.split(/\s+/),l=(o[0]??"").toLowerCase(),i=n.slice(o[0]?.length??0).trim();if("quit"!==l&&"exit"!==l&&"q"!==l&&(Fe=!1),We&&l!==We&&(We=null),ie.has(l)&&(()=>{if(!Ee.path||void 0===Ee.mtimeMs)return;const e=ve(Ee.path);if(void 0!==e&&e!==Ee.mtimeMs){if(uo()){if(Re===e)return;return Re=e,console.log(chalk.yellow(` ⚠ ${g(Ee.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"))}yo(!0)}})(),"quit"===l||"exit"===l||"back"===l||"q"===l||"menu"===l)return Ee.dirty&&!Fe?(Fe=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ve()):void await(async()=>{if(ee("ipynb"),De.removeAllListeners("line"),Oe||q(),console.log(),Ge&&Ue)Ge=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(Ge){const e=ue();e&&await he("release",e),Ge=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Ce.shutdown().catch(()=>{}),Oe){qe&&(De.prompt=qe),De.setPrompt(Le);for(const e of Me)De.on("line",e);De.prompt(),He()}else O(null),He(),De.close()})();if("clear"===l||"cls"===l)return console.clear(),ae(),void Ve();if("restart"===l)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Ce.shutdown().catch(()=>{});try{await Ce.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 Ve();if("help"===l||"?"===l)return/^(all|commands|full)$/i.test(i.trim())?(console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor vi")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(re()?" 问 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()):oe(),void Ve();if("guide"===l||"/guide"===l)return Ye(),void Ve();if("python"===l||"python3"===l)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void Ve();if("open"===l&&""===i)return fe&&te(fe)?console.log(chalk.gray(" reopening ")+chalk.cyan(fe)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ve();if("cells"===l||"ls"===l)return(()=>{if(Ie=!0,0===Ee.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);Ee.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 Ve();if("show"===l)return(e=>{const o=to(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 ──")),we(o.cell.result,be)),console.log()}})(i),void Ve();if("edit"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ").toLowerCase();return""===n||"all"===n?go(o,e=>(e=>{De.pause();const o=k(Y(Ee.cells),".py",e,"notebook");if(De.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=z(o,Ee.cells);if(n.same)return void console.log(chalk.gray(" no changes."));if(0===n.cells.length&&Ee.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${Ee.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));Ee.cells=n.cells,Ee.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 — ${Ee.cells.length} cells`)+chalk.gray(` · ${t.join(" · ")}`));const l=[...n.changed,...n.added].filter(e=>"code"===Ee.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)):to(n)&&go(o,e=>((e,o)=>{const n=to(e);if(!n)return;De.pause();const t=k(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(De.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,Ee.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 Ve()}if("add"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ");return go(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)"));De.pause();const l=k(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);De.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Ee.cells.push({kind:t?"markdown":"code",source:r,result:null}),Ee.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${Ee.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Ee.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void Ve()}if("editor"===l&&/^[\w-]*$/.test(i))return(e=>{const o=e.trim().toLowerCase(),n=$(io());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${ao()?"saved":so()?"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?` ${co[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 b({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const 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);ao()&&$(ao())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(t.cmd)?(b({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.`))})(i),void Ve();if("reload"===l&&""===i)return Ee.path&&e(Ee.path)?uo()&&"reload"!==We?(We="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."))):(We=null,yo(!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 Ve();if("load"===l&&!/^[=(.[]/.test(i)||"open"===l&&""!==i){if(!i)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ve();const o=K(i,a()),n=d(o)?o:h(process.cwd(),o);if(e(n))if(Ee.dirty&&"load"!==We)We="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(l)+chalk.yellow(" again to discard them."));else{We=null;const e=$e(n);Ee.cells=e.doc.cells,Ee.path=e.doc.path,Ee.dirty=!1,Ee.mtimeMs=e.doc.mtimeMs,Ee.diskSig=e.doc.diskSig,Re=void 0,Ae=pe(Ee.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 Ve()}if("del"===l||"delete"===l)return(e=>{const o=to(e);o&&(Ee.cells.splice(o.idx-1,1),Ee.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Ee.cells.length} left.`)+(o.idx<=Ee.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(i),void Ve();if(("md"===l||"py"===l)&&/^\d+$/.test(i))return((e,o)=>{const n=to(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,Ee.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}.`))})(i,"md"===l?"markdown":"code"),void Ve();if("gpu"===l)return Be=!0,await no(i),Be=!1,void Ve();if("download"===l||"dl"===l)return Be=!0,await oo(i),Be=!1,void Ve();if("selfcheck"===l||"self-check"===l)return Be=!0,await(async()=>{const e=Ue;if(!e||!Ge)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===Ee.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=Ce;if(await Qe(e,!0),Ce===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<Ee.cells.length;e++){const o=Ee.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 Ce.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}Ee.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){we(o.result,be),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 Ce.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:Ee.path?g(Ee.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."))}})(),Be=!1,void Ve();if("upload"===l||"up"===l||"put"===l)return Be=!0,await(async e=>{if(!Ge)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=K(o,a()),l=d(n)?n:h(Ee.path?y(Ee.path):process.cwd(),n);let r;try{r=t(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${Ge.outDir}/${g(l)}`;try{const e=await Ce.putFile(s,r);console.log(chalk.green(" ✓ uploaded ")+chalk.white(s)+chalk.gray(` (${e} bytes)`))}catch(e){console.log(chalk.yellow(" upload failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),Be=!1,void Ve();if("check"===l||"submit"===l||"kaggle"===l){const e=await import("./kaggle.js"),o=i.split(/\s+/).filter(Boolean),n="kaggle"===l?(o[0]||"").toLowerCase():l,t=("kaggle"===l?o[1]:o[0])||pe(Ee.path)||void 0;Be=!0;try{if(("submit"===n||"check"===n)&&Ge&&!await oo("submission.csv",!0))return Be=!1,void Ve();if("submit"===n){const o=s("sha256").update(Ee.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(t,{code_sha:o,...Ue?{sid:Ue.sid}:{},...Ee.path?{notebook:g(Ee.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"===l?o[0]:t)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Be=!1,void Ve()}if("board"===l){const{runBoard:e}=await import("./board.js"),o=i.split(/\s+/).filter(Boolean);Be=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Be=!1,void Ve()}if("ai"===l||"/ai"===l)return Be=!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=Ee.cells.length-1;e>=0;e--)if((Ee.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Ee.cells.length;if(0===Ee.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=to(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(le,"")).join("\n")));return o.join("\n").replace(le,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Ee.path||!pe(Ee.path))return"";try{const e=JSON.parse(t(u(y(Ee.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return lo(o,350)}catch{return""}})(),c=re(),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,m-d-i.length),p=lo(a.cell.source,Math.floor(.6*h)),w=s?(b=s,k=h-p.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[g,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${p}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",l?`\n[question]\n${l}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),_=c;console.log(),ro||(ro=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(re()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${m} ${re()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(re()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(re()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${m} 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 f(v);if(console.log(),!x.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(x.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of A(x.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${_?"<你的问题>":"<your question>"}`)+chalk.gray(_?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(_?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(_?" 再跑一次":" run it again")),console.log(chalk.gray(_?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(i),Be=!1,void Ve();if("run"===l)return Be=!0,await(async e=>{if(!xe&&!Ue&&!Ge)return void console.log(chalk.yellow(" No kernel here yet — ")+chalk.cyan("gpu on")+chalk.yellow(" connects your committee seat (or ")+chalk.cyan("aienv setup")+chalk.yellow(" for a local one)."));const o=W(e,Ee.cells.length);if(o)for(const e of o){const n=Ee.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 Ce.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void ce()}if(Ee.dirty=!0,we(n.result,be),ho(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(re()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(re()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void ce()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(n.source))console.log(e);console.log()}}else console.log(0===Ee.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(i),Be=!1,void Ve();if("save"===l)return(e=>{if(0===Ee.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()):Ee.path?Ee.path.endsWith(".ipynb")?Ee.path:`${Ee.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===Ee.path?ve(o):void 0;if(void 0!==n&&void 0!==Ee.mtimeMs&&n!==Ee.mtimeMs&&"save"!==We)return We="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"));We=null;try{r(o,J(Ee.cells)),Ee.path=o,Ne=!0,Ee.dirty=!1,Ee.mtimeMs=ve(o),Ee.diskSig=ke(Ee.cells),Re=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Ee.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),void Ve();if(""===n)return void Ve()}if(ze.length>0&&se.has(n.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(n.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ve();if(ze.push(o),!j(ze))return 1!==ze.length||Ke||(Ke=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ve();const l=ze.join("\n").replace(/\s+$/,"");if(ze.length=0,""!==l.trim()){Be=!0;try{const e=await Ce.execute(l);Ee.cells.push({kind:"code",source:l,result:e}),Ee.dirty=!0,we(e,be);const o=ho(Ee.cells[Ee.cells.length-1],Ee.cells.length);e.ok||o||ce()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),ce()}Be=!1,Ve()}else Ve()};De.on("line",e=>{po(e)}),Oe||De.on("close",async()=>{await Ce.shutdown().catch(()=>{}),process.exit(0)}),Ve(),await Xe}
|
package/dist/commands/kaggle.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as 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
|
+
import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as p}from"../lib/kaggle.js";import{mediaHelpLines as m,sprintTaskForComp as f}from"../lib/sprint-meta.js";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 _(){return(a().language||"en").toLowerCase().startsWith("zh")}function S(o,e){return _()?o:e}function j(){console.log(),console.log(chalk.yellow(S(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(S(" 检查一下网络,或者过一会儿再试。"," 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 E(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(S(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(S(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(S(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(S(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),console.log(chalk.gray(S(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board")),void console.log(chalk.gray(S(" 在 notebook 里可直接敲 "," inside the notebook just type "))+chalk.cyan("submit")+chalk.gray(S(" —— 不用退出来"," — no need to leave")))):"nitro"===o?.judge?(console.log(chalk.bold.white(S(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(S(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(S(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(S(" 注册后提交"," and submit there"))),void console.log(chalk.gray(S(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(S(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(S(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(S(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(S(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(S(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(S(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(S(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(S(" —— 它是弱模型,把问题问准是这次要练的本事。"," — 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(S(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(S(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(S("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(S("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await w("/api/icoa/kaggle/tasks");if(!t)return j();const r=h(t);if(0===r.length)return console.log(chalk.yellow(S(" 现在还没有上线的练习赛 —— 过一会儿再来。"," 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(S(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(S(" 正在开放的练习赛:"," 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(S(" 选一个(序号或 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(S(` 输 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(S(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(S(" (数据留在 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 j();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(S(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?S(" (保留了你原来那本)"," (kept your existing one)"):S(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(S("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(S(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(S(" 这是 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(S(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(S(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(S(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(S(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(S(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(S(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(S(" 去 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(S(" 正在下载数据…"," Downloading data…")));let b=null;const p=y(c);if(p){const[o,e,n]=await Promise.all([v(p.train),v(p.test),v(p.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 j();const m=A(u),k={...c,...b.meta??{}};try{e(m,{recursive:!0}),l(s(m,"train.csv"),b.train),l(s(m,"test.csv"),b.test),l(s(m,"sample_submission.csv"),b.sample_submission),l(s(m,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const $=s(m,"starter.ipynb");let _=!1;if(o($))_=!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(m,k)))}const E="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",G="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(m,"train.csv"))+chalk.gray(` (${E})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(m,"test.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(m,"sample_submission.csv")));const I=f(u),N="none"===(I?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white($)+chalk.gray(_?" (kept your existing one)":N?S(" (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(),P(u,k,$),console.log()}finally{t.close()}}function G(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 P(o,e,n){const t=f(o),l=t?m(t,_()):[];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?S(" 接下来 4 步:"," Your move — 4 steps:"):S(" 接下来 3 步:"," Your move — 3 steps:")));let r=1;l&&console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(S(` → 把${G(t?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${G(t?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(s?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(),E(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(),P(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=p(n(r,"utf-8"),n(a,"utf-8"));i(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(r)),console.log(),E(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.")),E(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(),E(d),void console.log();if(!o(c))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(a,"starter.ipynb")}`)),void console.log();const y=n(c,"utf-8"),h=p(y,n(g,"utf-8"));if(!h.ok){i(`kaggle: submit ${l} → local-reject: ${h.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of h.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let m=u()?.token??"";if(!m){const o=r();try{m=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!m)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}const f=Date.now();let k,w=null;process.stdout.isTTY?(process.stdout.write(chalk.gray(" ⚖ scoring on the server… 0.0s")),w=setInterval(()=>{process.stdout.write(chalk.gray(`\r ⚖ scoring on the server… ${((Date.now()-f)/1e3).toFixed(1)}s `))},200)):console.log(chalk.gray(" Scoring on the server…"));try{k=await $(`/api/icoa/kaggle/${l}/submit`,{token:m,submission_csv:y,...t?{job:t}:{}})}finally{w&&(clearInterval(w),process.stdout.write(`\r ${chalk.gray(`⚖ scored in ${((Date.now()-f)/1e3).toFixed(1)}s`)}${" ".repeat(12)}\n`))}const 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(`kaggle board ${l}`)+chalk.gray(" (or ")+chalk.cyan(`board ${v.boardEvent} ${l}`)+chalk.gray(")")),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()}const N=o=>"number"==typeof o?o.toFixed(4):" – ";export async function runKaggleBoard(o){console.log();const e=o?.trim()||I(void 0,"board");if(!e)return;const n=u()?.token??"",t=await $(`/api/icoa/kaggle/${e}/board`,n?{token:n}:{})??{},l=t.data??t??{};if(!Array.isArray(l.public))return"unknown_comp"===l.reason?console.log(chalk.bold.red(` ✗ no competition called ${e}`)):console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const s=l.public,r="public"===l.leaderboard,a="number"==typeof l.public_fraction?Math.round(100*l.public_fraction):null;if(console.log(chalk.bold.white(` 🏆 ${String(l.title??e)}`)+chalk.gray(` · ${r?`public leaderboard (${a??"?"}% of the test set)`:"leaderboard (whole test set)"} · ${String(l.metric??"")}`)),l.closed&&console.log(chalk.yellow(" ⏹ closed — no more submissions are accepted")),0===s.length)console.log(chalk.gray(" nobody has scored yet — be the first: ")+chalk.cyan(`kaggle submit ${e}`));else{console.log(chalk.gray(" # who score subs"));for(const o of s){const e=` ${String(o.rank).padStart(3)} ${o.who.padEnd(9)} ${N(o.score)} ${String(o.n).padStart(3)}`;console.log(o.you?chalk.bold.green(`${e} ◀ you`):chalk.white(e))}}if(Array.isArray(l.private)){const o=l.private;console.log(),console.log(chalk.bold.white(" 🔒 private leaderboard — FINAL")+chalk.gray(r?` (the other ${100-(a??0)}% of the test set)`:"")),console.log(chalk.gray(" # who private public sub id code seat picked"));for(const e of o){const o=` ${String(e.rank).padStart(3)} ${e.who.padEnd(9)} ${N(e.score)} ${N(e.public_score)} ${(e.sub_id??"-").padEnd(12)} ${(e.code_sha??"-").padEnd(12)} ${(e.job_sid??"-").padEnd(20)} ${e.how??""}`;console.log(e.you?chalk.bold.green(`${o} ◀ you`):chalk.white(o))}console.log(chalk.gray(" picked = chosen (kaggle final) or auto (public best + last) · code = sha of the notebook cells that made it"))}else r&&(console.log(chalk.gray(" (private split is revealed by the organiser after the event — then it shows here)")),n&&console.log(chalk.gray(" pick the two that count: ")+chalk.cyan(`kaggle final ${e} <id> [<id>]`)));i(`kaggle: board ${e} → ${s.length} rows${Array.isArray(l.private)?" + private":""}`),console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit" / "board" / "final"').argument("[comp]",'competition id (with "check" / "submit" / "board" / "final")').argument("[ids...]",'submission ids (with "final")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit & board & final").action(async(o,e,n=[])=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"board"===o?await runKaggleBoard(e):"final"===o?await runKaggleFinal(e,n):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as e,mkdirSync as t,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 const COMMITTEE_TIERS=["t4","t4x2","t4full","l4","l4x2","l4full","cpu"];export function isCommitteeTier(e){return"string"==typeof e&&COMMITTEE_TIERS.includes(e)}export function sessionFilePath(e=n()){return i(e,".icoa","gputask","session.json")}export function parseCommitteeSession(e){let t;try{t=JSON.parse(e)}catch{return null}const o=e=>"string"==typeof t[e]&&""!==t[e]?t[e]:null,r=o("sid"),s=o("token"),n=o("host"),i=o("user"),u=o("python"),l=o("outDir"),p=o("keyPem"),c=o("tier");return r&&s&&n&&i&&u&&l&&p&&isCommitteeTier(c)?{sid:r,token:s,tier:c,host:n,port:"number"==typeof t.port&&Number.isInteger(t.port)?t.port:22,user:i,python:u,outDir:l,keyPem:p,seenAt:"number"==typeof t.seenAt?t.seenAt:0}:null}export function readCommitteeSession(t=n()){const r=sessionFilePath(t);if(!e(r))return null;try{return parseCommitteeSession(o(r,"utf-8"))}catch{return null}}export function writeCommitteeSession(e,o=n()){const r=sessionFilePath(o);t(i(o,".icoa","gputask"),{recursive:!0}),s(r,`${JSON.stringify(e,null,1)}\n`,{mode:384})}export function clearCommitteeSession(e=n()){try{r(sessionFilePath(e),{force:!0})}catch{}}export function committeeLease(e){return{state:"ready",transport:"ssh",host:e.host,port:e.port,user:e.user,python:e.python,dataRoot:`/home/${e.user}`,outDir:e.outDir,keyPem:e.keyPem,timeLeftSec:0}}export const TIER_LABEL={t4:"T4 capsule · 3.5 GiB fence · 2 vCPU · 6 GB",t4x2:"T4 double capsule · 7 GiB fence · 4 vCPU · 12 GB",t4full:"T4 whole card · 16 GB · 8 vCPU · 30 GB",l4:"L4 capsule · 3.5 GiB fence · 2 vCPU · 6 GB",l4x2:"L4 double capsule · 7 GiB fence · 4 vCPU · 12 GB",l4full:"L4 whole card · 24 GB · 8 vCPU · 32 GB",cpu:"CPU slot · 2 vCPU · 6 GB"};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icoa-cli",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.706",
|
|
4
4
|
"description": "ICOA CLI — AI-native competition runtime of the International Cyber Olympiad in AI: learn, practise, and compete in AI & cybersecurity from the terminal (AI4CTF · CTF4AI · CTF4EAI)",
|
|
5
5
|
"author": "Charlie Zhu",
|
|
6
6
|
"type": "module",
|