icoa-cli 2.19.706 → 2.19.707
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/ai4ioai.js +1 -1
- package/dist/commands/arena-eai.js +1 -1
- package/dist/commands/arena.js +1 -1
- package/dist/commands/board.js +1 -1
- package/dist/commands/challenge.js +1 -1
- package/dist/commands/connect.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/demo2.js +1 -1
- package/dist/commands/doctor.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/gpufortask.js +1 -1
- package/dist/commands/ioailab.js +1 -1
- package/dist/commands/ipynb.js +1 -1
- package/dist/commands/kaggle.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/commands/sim.js +1 -1
- package/dist/lib/exam-outbox.js +1 -0
- package/dist/lib/exam-sandbox.js +1 -1
- package/dist/lib/exam-server.js +1 -1
- package/dist/lib/gemini.js +1 -1
- package/dist/lib/judge-wait.js +1 -1
- package/dist/lib/lazy-assets.js +1 -1
- package/dist/lib/learn-credits.js +1 -1
- package/dist/lib/learn-cup.js +1 -1
- package/dist/lib/learn-curricula.js +1 -1
- package/dist/lib/learn-door.js +1 -1
- package/dist/lib/learn-pvp.js +1 -1
- package/dist/lib/learn-study-timer.js +1 -1
- package/dist/lib/log-sync.js +1 -1
- package/dist/lib/site.js +1 -0
- package/dist/lib/translations-fetcher.js +1 -1
- package/dist/lib/update-check.js +1 -1
- package/dist/repl.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 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))}})}
|
|
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";import{serviceBase as m}from"../lib/site.js";const k=m("ICOA_GPUTASK_SERVER").replace(/\/$/,"");let w=[],$=null,b=null,z=[];function v(o){return new Promise(t=>{const n=f();if(n){const e=z.shift();return void 0!==e?(process.stdout.write(`${o}${e}\n`),void t(e)):(b=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 _="en";const G={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 — 没有限制,纯提示 🙂"}},P=e=>G[e]?.[_]??e;async function C(e,o){try{const t=await fetch(`${k}/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 T(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 U(e){return`$${(e??0).toFixed(2)}`}function A(e){const o=e.user??"?";console.log(),console.log(chalk.bold.green(` ${P("readyTitle")}`)+chalk.gray(` ${y[e.tier??"t4"]} · ${e.zone??""} · ${"ondemand"===e.mode?"on-demand":"Spot"}`)),console.log(),console.log(chalk.white(` ${P("how1")}`)),console.log(chalk.bold.cyan(" icoa> ipynb ~/Desktop/task.ipynb")+chalk.gray(` ${P("how2")}`)),console.log(chalk.bold.cyan(" icoa ipynb> gpu on")+chalk.gray(` ${P("how3")}`)),console.log(chalk.bold.cyan(" icoa ipynb> upload data.csv")+chalk.gray(` ${P("how4")}`)),console.log(),console.log(chalk.gray(` ${P("advanced")}`)),console.log(chalk.gray(` ssh -i ~/.icoa/gputask/key ${o}@${e.host??"?"}`)),console.log(),console.log(chalk.yellow(` ${P("clock").replace("{U}",o)}`)),console.log(chalk.gray(` ${P("spend").replace("{A}",U(e.today_usd)).replace("{B}",U(e.daily_cap_usd??5))}`)+chalk.gray(` · ${e.rate??"?"}/h`)),e.fleet_cap_usd&&console.log(chalk.gray(` ${S(e)}`)),e.weekly_soft_over&&console.log(chalk.gray(` ${P("weekly").replace("{H}",String(e.weekly_hours??0))}`)),console.log(),console.log(chalk.gray(` ${P("footer")}`))}function B(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(`${P("busy")} (${n.why})`):chalk.yellow(`${P("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(` ${P("spend").replace("{A}",U(e.today_usd)).replace("{B}",U(e.daily_cap_usd??5))}`)),e.fleet_cap_usd&&console.log(chalk.gray(` ${S(e)}`))}function S(e){return P("fleet").replace("{A}",U(e.fleet_today_usd)).replace("{B}",U(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 x=!1;const L={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:()=>x},{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(` ${P("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(){_="en",x=!1,function(){const e=f();e&&(w=e.listeners("line").slice(),e.removeAllListeners("line"),$=e.prompt.bind(e),e.prompt=o.prototype.prompt.bind(e),e.on("line",e=>{const o=b;b=null,o?o(e):z.push(e)}))}();try{console.log(),console.log(chalk.cyan.bold(` ${P("banner")}`)),console.log(chalk.gray(` ${P("langTip")}`)),console.log();const e=i(),o=p();let n="";for(let s=0;s<3;){const a=(await v(chalk.cyan(` ${P("tokenAsk")}`)+(o?chalk.gray(`[${o.token}] `):""))).trim(),i=a.toLowerCase();if("lang zh"===i){_="zh";continue}if("lang en"===i){_="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 C("status",{token:r,fp:e});if(null===l)return void console.log(chalk.yellow(` ${P("netErr")}`));if("token_device_mismatch"!==l.error){if(!l.error){if(n=r,"none"!==l.state)return console.log(chalk.gray(` ${P("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(` ${P("tokenBad")}`)),s++}else console.log(chalk.yellow(` ${P("tokenDevice")}`)),s++}if(!n)return void console.log(chalk.yellow(` ${P("tokenGiveUp")}`));let s="";for(console.log(chalk.cyan(` ${P("tierMenu").split("\n").join("\n ")}`));!s;){const e=(await v(chalk.cyan(P("tierAsk")))).trim().toLowerCase();if("lang zh"===e){_="zh";continue}if("lang en"===e){_="en";continue}if("quit"===e||"back"===e)return;const o=parseTierChoice(e);o?s=o:console.log(chalk.yellow(` ${P("tierBad")}`))}let a="spot";for(;;){const e=(await v(chalk.cyan(` ${P("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 _="en";else _="zh"}const r=await C("start",{token:n,fp:e,tier:s,mode:a});if(null===r)return void console.log(chalk.yellow(` ${P("netErr")}`));if("all_seats_busy"===r.error)return void console.log(chalk.yellow(` ${P("seatsBusy")}`));if("daily_cap"===r.error)return void console.log(chalk.yellow(` ${P("dailyCap")}`));if("daily_cap_fleet"===r.error)return console.log(chalk.yellow(` ${P("dailyCapFleet")}`)),void console.log(chalk.gray(` ${S(r)}`));if("ctl_unavailable"===r.error)return void console.log(chalk.yellow(` ${P("ctlDown")}`)+chalk.gray(r.detail?` (${r.detail})`:""));if("session_already_active"===r.error){const o=await C("status",{token:n,fp:e});return void(o&&await t(n,e,o))}if(r.error)return void console.log(chalk.yellow(` ${P("failed")}${r.error}`));r.cap_warning&&console.log(chalk.yellow(` ${P("capWarn")}`)),console.log(chalk.gray(` ${P("deploying")}`)),await t(n,e,r)}finally{l(L.id),function(){const e=f();if(e){e.removeAllListeners("line"),$&&(e.prompt=$);for(const o of w)e.on("line",o);w=[],$=null,b=null,z=[]}}()}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(` ${P("failed")}${n.end_reason??n.state}`)),u(),null;const t="creating"===n.state?P("stCreating"):"preempted"===n.state?P("stPreempted"):P("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 C("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(` ${P("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(T(o,s)||console.log(chalk.yellow(" could not save the session file under ~/.icoa/gputask — gpu on will not find this seat.")),A(s),r(L);;){const n=(await v(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(` ${P("quitNote")}`));if("status"===n||"s"===n||"time"===n||"stats"===n||"top"===n){const n=await C("status",{token:o,fp:t});if(n)if("ready"===n.state)n.host&&n.key_pem&&T(o,n),x=!0,B(n);else{if("preempted"!==n.state&&"provisioning"!==n.state&&"creating"!==n.state)return console.log(chalk.gray(` ${P("ended")} (${n.end_reason??n.state})`)),void u();{console.log(chalk.yellow(` ${P("stPreempted")}`));const s=await e(o,t,n);if(!s)return;T(o,s),A(s)}}else console.log(chalk.yellow(` ${P("netErr")}`));continue}if("stop"===n||"end"===n||"destroy"===n||"release"===n){const e=(await v(chalk.yellow(` ${P("stopAsk")}`))).trim().toLowerCase();if("y"===e||"yes"===e)return await C("stop",{token:o,fp:t}),u(),void console.log(chalk.green(` ${P("stopping")}`));continue}"help"!==n&&"/help"!==n&&"?"!==n?"help all"!==n&&"guide"!==n?console.log(chalk.gray(` ${P("footer")}`)):c():d()}else _=n.endsWith("zh")?"zh":"en",console.log(chalk.gray(` ${P("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/ioailab.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as e}from"node:child_process";import{existsSync as o,mkdirSync as t,readFileSync as n,writeFileSync as a}from"node:fs";import{homedir as r}from"node:os";import{join as s}from"node:path";import{Interface as i,createInterface as l}from"node:readline";import chalk from"chalk";import{editTextInEditor as c}from"../lib/editor-spawn.js";import{buildSshArgs as u,leaseConnectProblems as g,parseLeaseResponse as y,queueLine as d,windowLine as m}from"../lib/gpu.js";import{enterPanel as f,leavePanel as p,printGuide as h,printHelp as w}from"../lib/guide-panel.js";import{logCommand as b}from"../lib/logger.js";import{getMainRl as v}from"../lib/main-rl.js";import{openFile as k}from"../lib/open-file.js";import{printError as $}from"../lib/ui.js";const x=[{id:"pick-cube",env:"PrimeLite-PickCube-v0",blurb:"Robot arm picks a cube off the table (imitation-learning demo)"}],P=/^[a-z0-9-]{1,32}$/,I=/^MP4:(\/[A-Za-z0-9._/-]+\.mp4)\s*$/m,U=/^HDF5:(\/[A-Za-z0-9._/-]+\.hdf5)\s*$/m,_=/^CKPT:(\/[A-Za-z0-9._/-]+\.pth)\s*$/m,A=/^METRICS:(\{.*\})\s*$/m,G=/^algo(?:_used)?:\s*([a-z_]+)\s*$/im,O="/opt/ioailab-mj/work",S=`${O}/05_custom_agent.py`;function C(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}function L(){return s(r(),".icoa","gpu-key")}function T(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(L(),"utf-8").trim()||null}catch{return null}}function E(e){t(s(r(),".icoa"),{recursive:!0}),a(L(),`${e.trim()}\n`,{mode:384})}async function R(e,o,t){try{const n=await fetch(`${C()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{key:o,task:t}:{key:o}),signal:AbortSignal.timeout(2e4)});return y(await n.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}async function j(e){try{const o=await fetch(`${C()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await o.json();return t&&!0===t.success?"ok":"invalid"}catch{return"offline"}}let q=null,N=null,Y=null,M=!1,K=!1,V=!1,z=!1,D=!1,B=null;function F(){return s(r(),"icoa-ioailab","05_custom_agent.py")}function W(o,t,n,a){return new Promise(r=>{const s="local"===o.transport?{command:"/bin/sh",args:["-c",n]}:{command:"ssh",args:u(o,t,n)},i=e(s.command,s.args,{stdio:["ignore","pipe","pipe"]});let l="",c="";const g=setTimeout(()=>i.kill("SIGKILL"),a);i.stdout.on("data",e=>{l+=e.toString(),c+=e.toString();let o=c.indexOf("\n");for(;o>=0;){const e=c.slice(0,o).trimEnd();c=c.slice(o+1),e.length>0&&console.log(chalk.white(` ${e}`)),o=c.indexOf("\n")}}),i.stderr.on("data",e=>{const o=e.toString().trimEnd();o.length>0&&console.log(chalk.gray(` ${o}`))}),i.on("close",e=>{clearTimeout(g),r({code:e??1,out:l})}),i.on("error",()=>{clearTimeout(g),r({code:127,out:l})})})}function J(o,t,n,r){return new Promise(s=>{const i=u(o,t,`cat ${n}`),l=e("ssh",i,{stdio:["ignore","pipe","pipe"]}),c=[],g=setTimeout(()=>l.kill("SIGKILL"),12e4);l.stdout.on("data",e=>c.push(e)),l.on("close",e=>{if(clearTimeout(g),0!==e||0===c.length)return s(!1);try{a(r,Buffer.concat(c)),s(!0)}catch{s(!1)}}),l.on("error",()=>{clearTimeout(g),s(!1)})})}async function Z(o,t){if(!q)return!1;if("local"===q.transport)try{return a(t,n(o)),!0}catch{return!1}return function(o,t,a,r){return new Promise(s=>{let i;try{i=n(a)}catch{return s(!1)}const l=u(o,t,`mkdir -p ${O} && cat > ${r}`),c=e("ssh",l,{stdio:["pipe","ignore","pipe"]}),g=setTimeout(()=>c.kill("SIGKILL"),12e4);c.on("close",e=>{clearTimeout(g),s(0===e)}),c.on("error",()=>{clearTimeout(g),s(!1)}),c.stdin&&(c.stdin.on("error",()=>{}),c.stdin.write(i),c.stdin.end())})}(q,N,o,t)}function H(){return!(!q||"ssh"===q.transport&&!N)||(console.log(chalk.yellow(" No GPU box leased — ")+chalk.cyan("on")+chalk.gray(" first.")),!1)}function Q(e,o,t){let n;for(let t=0;t<e.length;t++){const a=e[t];a===`--${o}`&&t+1<e.length?n=e[t+1]:a.startsWith(`--${o}=`)?n=a.slice(o.length+3):void 0===n&&/^[0-9]+$/.test(a)&&(n=a)}if(void 0===n)return t;const a=Number.parseInt(n,10);return Number.isFinite(a)?Math.min(999,Math.max(1,a)):t}async function X(e,o,t,n){if(!q||"ssh"===q.transport&&!N)return null;const a=x[0].id;return W(q,N??"",`sudo -n /usr/local/bin/ioailab-run ${a} ${e} --${o} ${t}`,n)}function ee(e){4===e?console.log(chalk.yellow(" The box says an earlier step is missing — run it first (")+chalk.cyan("guide")+chalk.yellow(" shows where you are).")):2===e?console.log(chalk.red(" The box rejected the request (bad arguments).")):console.log(chalk.red(" Step failed on the box.")+chalk.gray(" (lease may have expired — ")+chalk.cyan("status")+chalk.gray(")"))}async function oe(e,o){if(!function(e){const o=q?.outDir??"";return!(""===o||!e.startsWith(o))||e===O||e.startsWith(`${O}/`)}(e))return void console.log(chalk.red(" Rejected unexpected video path from the box."));const i=s(r(),"icoa-ioailab");t(i,{recursive:!0});const l=s(i,`${o}-${Date.now()}.mp4`);process.stdout.write(chalk.gray(" Pulling the rendered clip…")),("local"===q?.transport?(()=>{try{return a(l,n(e)),!0}catch{return!1}})():await J(q,N,e,l))?(Y=l,console.log(chalk.green(" done.")),console.log(chalk.magenta(" 🎬 clip → ")+chalk.cyan(l)),k(l)?console.log(chalk.gray(" Opened in your video viewer. ")+chalk.cyan("watch")+chalk.gray(" reopens it any time.")):console.log(chalk.gray(" Open it with your video player."))):console.log(chalk.red(" failed."))}function te(e){const o=e.match(A);if(!o)return void console.log(chalk.yellow(" Finished, but no metrics came back from the box."));let t;try{t=JSON.parse(o[1])}catch{return void console.log(chalk.yellow(" (metrics came back in an unexpected format.)"))}if(B=t,"number"==typeof t.success_rate){const e="number"==typeof t.episodes?` over ${t.episodes} episode(s)`:"";console.log(chalk.bold.green(` ★ success rate: ${(100*t.success_rate).toFixed(1)}%`)+chalk.gray(e))}for(const[e,o]of Object.entries(t))"success_rate"!==e&&"episodes"!==e&&("number"!=typeof o&&"string"!=typeof o||console.log(chalk.gray(` ${e}: `)+chalk.white(String(o))))}function ne(){let e;e=M?K?V?z?"edit custom":"eval":"train":"mimic":"collect",console.log(chalk.gray(" Next: ")+chalk.cyan(e)+chalk.gray(" (")+chalk.cyan("guide")+chalk.gray(" = where you are)"))}const ae={id:"ioailab",title:"IOAI Lab",what:"A practice twin of the IOAI Team Challenge: lease a GPU box, then drive the contest workflow — record expert demos, expand them, train a diffusion policy on them, evaluate it, write your own agent. Videos open on this machine.",steps:[{verb:"on",what:"lease a GPU box (nothing installs here)",done:()=>null!==q},{verb:"collect",what:"record expert demos → watch the arm pick the cube",done:()=>M},{verb:"mimic",what:"expand your demos (pose-randomized, MimicGen-lite)",done:()=>K},{verb:"train",what:"robomimic Diffusion Policy on YOUR demos (GPU, scored)",done:()=>V},{verb:"eval",what:"run YOUR policy → success rate → watch",done:()=>z},{verb:"edit custom",what:"write your own BaseAgent, then custom runs it",done:()=>D},{verb:"watch",what:"replay the last clip",done:()=>null!==Y,optional:!0}],notes:["status = lease time left · off = release the box · tasks = the task list. Leaving releases the lease."],leave:{verb:"exit",what:"leave IOAI Lab (lease released)"},guide:()=>function(){let e=!1;const o=[["collect",M],["mimic",K],["train",V],["eval",z],["custom",D]].map(([o,t])=>t?`${o} ${chalk.green("✓")}`:e?`${o} ${chalk.gray("○")}`:(e=!0,`${o} ${chalk.yellow("…")}`));console.log(),console.log(chalk.bold.white(" ═══ 📖 IOAI Lab — the 5-step workflow ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+o.join(chalk.gray(" · "))),console.log(" "+(q?chalk.green("⚡ lease active")+chalk.gray(" (")+chalk.cyan("status")+chalk.gray(" for time left)"):chalk.gray("no lease — ")+chalk.cyan("on")+chalk.gray(" to lease a box"))),B&&"number"==typeof B.success_rate&&console.log(chalk.gray(" Last result: ")+chalk.green(`${(100*B.success_rate).toFixed(1)}% success`)),console.log(),console.log(chalk.bold.white(" Your move — drive the contest workflow:")),console.log(chalk.gray(" 1. ")+chalk.cyan("collect")+chalk.gray(" expert demos → watch the arm pick the cube")),console.log(chalk.gray(" 2. ")+chalk.cyan("mimic")+chalk.gray(" expand your demos (pose-randomized, MimicGen-lite)")),console.log(chalk.gray(" 3. ")+chalk.cyan("train")+chalk.gray(" robomimic Diffusion Policy on YOUR demos (GPU, scored)")),console.log(chalk.gray(" 4. ")+chalk.cyan("eval")+chalk.gray(" run YOUR policy → success rate → watch")),console.log(chalk.gray(" 5. ")+chalk.cyan("edit custom")+chalk.gray(" / ")+chalk.cyan("custom")+chalk.gray(" write your own BaseAgent → run it → watch")),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(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it to explain a step or debug your agent — then ")+chalk.bold.white("VERIFY")+chalk.gray(" by re-running ")+chalk.cyan("eval")+chalk.gray(".")),console.log(),console.log(chalk.cyan(" on")+chalk.gray("/")+chalk.cyan("off")+chalk.gray(" lease a box · ")+chalk.cyan("status")+chalk.gray(" time left · ")+chalk.cyan("watch")+chalk.gray(" replay last clip · ")+chalk.cyan("run")+chalk.gray(" quick showcase · ")+chalk.cyan("exit")+chalk.gray(" leave")),console.log()}()};async function re(e=!1){const o=T();o&&q&&await R("release",o),q&&!e&&console.log(chalk.gray(" GPU lease released.")),q=null,N=null,M=!1,K=!1,V=!1,z=!1,D=!1,B=null}async function se(e){const i=e.trim();if(0===i.length)return"continue";const[l,...u]=i.split(/\s+/),y=l.toLowerCase();return b(`ioailab ${y}`),"exit"===y||"quit"===y||"q"===y||"back"===y||"menu"===y?(await re(!0),p(ae.id),console.log(chalk.gray(" Leaving IOAI Lab — any GPU lease was released.")),"exit"):("help"===y||"/help"===y||"?"===y?/^(all|commands|full)$/i.test(u[0]??"")?h():w():"guide"===y||"/guide"===y?h():"tasks"===y||"task"===y?function(){console.log();for(const e of x)console.log(chalk.cyan(` ${e.id.padEnd(12)}`)+chalk.gray(e.blurb));console.log()}():"key"===y?0===u.length?console.log(chalk.gray(" Usage: ")+chalk.cyan("key <your-access-key>")):(E(u[0]),console.log(chalk.green(" ✓ GPU access key saved.")+chalk.gray(" Next: ")+chalk.cyan("on"))):"on"===y||"lease"===y||"gpu"===y?await async function(){if(q)return void console.log(chalk.gray(" already holding a GPU lease — ")+chalk.cyan("status")+chalk.gray(" for time left."));const e=T();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));process.stdout.write(chalk.gray(" Requesting a GPU box…"));let o=await R("lease",e,"ioailab"),n=0;for(;"queued"===o.state&&n<24;)0===n&&console.log(),process.stdout.write(`\r ${chalk.yellow(d(o))} `),await new Promise(e=>setTimeout(e,5e3)),o=await R("status",e),n++;if("queued"===o.state)return console.log(),void console.log(chalk.yellow(" Still queued — your place is held server-side. Try ")+chalk.cyan("on")+chalk.gray(" again in a few minutes."));if("ready"!==o.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${o.message??"no lease granted"}`));const i=g(o);if("local"!==o.transport||process.env.ICOA_GPU_SERVER||i.push("local transport from a non-dev broker"),i.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(i.join(", "))),void await R("release",e);let l=null;if("ssh"===o.transport&&(l=function(e){const o=s(r(),".icoa","gpu","ioailab-lease-key");try{return t(s(r(),".icoa","gpu"),{recursive:!0}),a(o,e.keyPem,{mode:384}),o}catch{return null}}(o),!l))return console.log(chalk.red(" could not write the ssh key locally.")),void await R("release",e);q=o,N=l;const c=Math.round((o.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU box leased.")+chalk.gray(` ~${c}m on this lease.`));const u=m(o.windowCloseEpoch);u&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${u}.`)),console.log(chalk.gray(" Next: ")+chalk.cyan("collect")+chalk.gray(" — start the 5-step chain (or ")+chalk.cyan("run")+chalk.gray(" for a quick one-shot showcase)."))}():"off"===y||"release"===y?await re():"status"===y||"queue"===y?await async function(){const e=T();if(!e)return void console.log(chalk.yellow(" No GPU access key saved — ")+chalk.cyan("key <k>")+chalk.gray(" first."));const o=await R("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ lease active · ~${e}m left.`));const t=m(o.windowCloseEpoch);t&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${t}.`))}else"queued"===o.state?console.log(` ${chalk.yellow(d(o))}`):console.log(chalk.gray(" no active lease — ")+chalk.cyan("on")+chalk.gray(" to request a box."))}():"run"===y?await async function(e){const o=x.find(o=>o.id===e);if(!o||!P.test(e))return void console.log(chalk.yellow(` Unknown task "${e}" — `)+chalk.cyan("tasks")+chalk.gray(" lists what is available."));if(!H())return;console.log(chalk.gray(` Running the ${o.id} task (ICOA-VLA arm) on the GPU box (headless — takes a moment)…`));const t=`sudo -n /usr/local/bin/ioailab-run ${e} 1`,{code:n,out:a}=await W(q,N??"",t,72e4);if(0!==n)return void console.log(chalk.red(" Episode failed on the box.")+chalk.gray(" (lease may have expired — ")+chalk.cyan("status")+chalk.gray(")"));const r=a.match(I);r?await oe(r[1],e):console.log(chalk.yellow(" Episode finished but no video path came back — box-side renderer issue."))}((u[0]??x[0].id).toLowerCase()):"collect"===y?await async function(e){if(!H())return;const o=Q(e,"episodes",5);console.log(chalk.gray(` Collecting ${o} expert demo(s) on the ICOA-VLA arm (headless — takes a moment)…`));const t=await X("collect","episodes",o,72e4);if(!t)return;if(0!==t.code)return ee(t.code);const n=t.out.match(U);n&&(M=!0,console.log(chalk.green(" ✓ expert demos recorded → ")+chalk.gray(n[1]))),console.log(chalk.gray(" The expert is a scripted reach→grasp→lift waypoint controller (our stand-in for")),console.log(chalk.gray(" the contest's motion planner) — a clean demonstration source, not a learned policy yet."));const a=t.out.match(I);a&&await oe(a[1],"collect"),ne()}(u):"mimic"===y?await async function(e){if(!H())return;if(!M)return void console.log(chalk.yellow(" No demos yet — run ")+chalk.cyan("collect")+chalk.gray(" first."));const o=Q(e,"episodes",36);console.log(chalk.gray(` Expanding your demos into ${o} training episode(s)…`));const t=await X("mimic","episodes",o,72e4);if(!t)return;if(0!==t.code)return ee(t.code);const n=t.out.match(U);n&&(K=!0,console.log(chalk.green(" ✓ training demos generated → ")+chalk.gray(n[1]))),console.log(chalk.gray(" MimicGen-lite: we randomize the cube pose and re-run the pose-conditioned expert —")),console.log(chalk.gray(" real rollouts, same robomimic schema, not the object-centric MimicGen the full sim uses.")),ne()}(u):"train"===y?await async function(e){if(!H())return;if(!K)return void console.log(chalk.yellow(" No training set yet — run ")+chalk.cyan("mimic")+chalk.gray(" first."));const o=Q(e,"epochs",20),t=54e5,n=q?.timeLeftSec??0;if(n>0&&1e3*n<t){const e=Math.round(n/60);console.log(chalk.yellow(` ⚠ your lease has ~${e}m left`)+chalk.gray(" — a long train may outlast it. ")+chalk.cyan("off")+chalk.gray("/")+chalk.cyan("on")+chalk.gray(" to refresh first if needed."))}console.log(chalk.gray(` Training a robomimic Diffusion Policy for ${o} epoch(s) on YOUR demos — the scored step (GPU)…`));const a=await X("train","epochs",o,t);if(!a)return;if(0!==a.code)return ee(a.code);const r=a.out.match(_);r&&(V=!0,console.log(chalk.green(" ✓ checkpoint saved → ")+chalk.gray(r[1])));const s=a.out.match(G);s&&/bc/i.test(s[1])?console.log(chalk.gray(" (behavior-cloning fallback — real diffusion pending on this box.)")):console.log(chalk.gray(" Same open robomimic Diffusion Policy the real contest uses — high-fidelity where it counts.")),ne()}(u):"eval"===y?await async function(e){if(!H())return;if(!V)return void console.log(chalk.yellow(" No trained policy yet — run ")+chalk.cyan("train")+chalk.gray(" first."));const o=Q(e,"episodes",20);console.log(chalk.gray(` Running YOUR trained policy for ${o} episode(s)…`));const t=await X("eval","episodes",o,72e4);if(!t)return;if(0!==t.code)return ee(t.code);te(t.out),z=!0,console.log(chalk.gray(" Your number reflects the practice arm + your demo count/epochs — it's the workflow signal,")),console.log(chalk.gray(" not a contest leaderboard score."));const n=t.out.match(I);n&&await oe(n[1],"eval"),ne()}(u):"custom"===y?await async function(e){if(!H())return;const t=F();if(!o(t))return void console.log(chalk.yellow(" No custom agent yet — ")+chalk.cyan("edit custom")+chalk.gray(" to write one first."));process.stdout.write(chalk.gray(" Uploading your agent…"));const n=await Z(t,S);if(console.log(n?chalk.green(" done."):chalk.red(" failed.")),!n)return;const a=Q(e,"episodes",9);console.log(chalk.gray(` Running YOUR agent for ${a} episode(s)…`));const r=await X("custom","episodes",a,72e4);if(!r)return;if(0!==r.code)return ee(r.code);te(r.out),D=!0;const s=r.out.match(I);s?await oe(s[1],"custom"):console.log(chalk.gray(" (no replay — for it to render, your agent must be constructible with no required args. Metrics above.)")),console.log(chalk.gray(" Iterate: ")+chalk.cyan("edit custom")+chalk.gray(" → ")+chalk.cyan("custom")+chalk.gray(" → watch, repeat."))}(u):"edit"===y?"custom"===(u[0]??"").toLowerCase()?await async function(){if(!H())return;const e=s(r(),"icoa-ioailab");t(e,{recursive:!0});const i=F();o(i)||(process.stdout.write(chalk.gray(" Fetching the starter agent…")),await async function(e,o){if(!q)return!1;if("local"===q.transport)try{return a(o,n(e)),!0}catch{return!1}return J(q,N,e,o)}("/opt/ioailab-mj/examples/05_custom_agent.py",i)?console.log(chalk.green(" done.")):(a(i,'"""05_custom_agent.py — your agent for the ICOA-VLA arm.\n\nSubclass BaseAgent and implement act(env, env_ids) -> array [rows, action_dim].\nKeep the constructor argument-free so the replay can render your agent\n(like the SinusoidAgent starter below). Then: edit custom -> custom -> watch.\n"""\nimport numpy as np\n\ntry:\n from icoa_ioailab.agents import BaseAgent\nexcept Exception: # resolved on the GPU box\n BaseAgent = object\n\n\nclass SinusoidAgent(BaseAgent):\n def __init__(self):\n self._t = 0\n\n def act(self, env, env_ids):\n rows = len(env_ids)\n dim = getattr(env, "action_dim", 7)\n self._t += 1\n cmd = 0.1 * np.sin(self._t * 0.2)\n return np.full((rows, dim), cmd, dtype=np.float32)\n'),console.log(chalk.gray(" using a local starter."))));const l=n(i,"utf-8"),u=c(l,".py");if(null===u)return void console.log(chalk.yellow(" Editor cancelled — agent unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));a(i,u),process.stdout.write(chalk.gray(" Saving to the box…"));const g=await Z(i,S);console.log(g?chalk.green(" done."):chalk.red(" failed.")),console.log(chalk.gray(" Saved → run ")+chalk.cyan("custom")+chalk.gray(" to try it."))}():console.log(chalk.gray(" Usage: ")+chalk.cyan("edit custom")+chalk.gray(" (write your own agent)")):"watch"===y||"open"===y?Y&&k(Y)?console.log(chalk.gray(" Reopened the last clip.")):console.log(chalk.gray(" No clip yet — ")+chalk.cyan("collect")+chalk.gray(" or ")+chalk.cyan("run")+chalk.gray(" first.")):console.log(chalk.yellow(` Unknown command "${y}" — `)+chalk.cyan("guide")+chalk.gray(" lists everything.")),"continue")}export async function runIoailabStandalone(){if(!await async function(){const{default:e}=await import("@inquirer/input"),o=T();if(o){const e=await j(o);if("ok"===e)return!0;if("offline"===e)return console.log(chalk.yellow(" Cannot reach the GPU service to verify your key right now — try again later.")),!1;console.log(chalk.yellow(" Your saved GPU key was not accepted. Enter a valid one below."))}else console.log(chalk.gray(" IOAI Lab is a paid GPU service. Enter the GPU access key issued with your purchase."));for(let o=0;o<3;o++){let t;try{t=await e({message:chalk.bold.magenta("icoa ioailab key>"),theme:{prefix:"",style:{message:e=>e}}})}catch{return!1}const n=t.trim();if(""===n||"exit"===n.toLowerCase()||"q"===n.toLowerCase())return!1;const a=await j(n);if("ok"===a)return E(n),console.log(chalk.green(" ✓ Key accepted — saved to this device. You will not be asked again.")),!0;if("offline"===a)return console.log(chalk.yellow(" Cannot reach the GPU service to verify — try again later.")),!1;console.log(chalk.red(` Key not recognised (${o<2?2-o+" tries left":"no tries left"}).`))}return!1}())return;console.log(),console.log(chalk.bold.magenta(" 🤖 IOAI Lab — Embodied AI practice twin (ICOA-VLA arm)")),console.log(chalk.gray(" The official Team-Challenge sim uses assets we can't hand out — so this is a")),console.log(chalk.gray(" practice twin: the same 5-step workflow, the same Python API, a real arm you drive.")),console.log(chalk.gray(" The scored part — training a diffusion policy from your own demos with robomimic")),console.log(chalk.gray(" (open source) — is byte-for-byte the framework the real contest uses.")),console.log(chalk.gray(" Runs on an ICOA GPU box — nothing installs here; the video opens locally.")),console.log(),console.log(chalk.white(" You will drive the exact contest workflow:")),console.log(" "+chalk.bold.cyan("collect")+chalk.gray(" → ")+chalk.bold.cyan("mimic")+chalk.gray(" → ")+chalk.bold.cyan("train")+chalk.gray(" → ")+chalk.bold.cyan("eval")+chalk.gray(" → ")+chalk.bold.cyan("custom")),console.log(chalk.gray(" v1 is a single task (pick-cube) on a MuJoCo arm; the real contest is multi-task on a")),console.log(chalk.gray(" higher-fidelity simulator — the learning core is the same.")),f(ae);const e=v(),o=null!==e,t=o?e.listeners("line").slice():[];o&&e.removeAllListeners("line");const n=o?e:l({input:process.stdin,output:process.stdout,terminal:!0}),a=o?n.prompt:null;o&&(n.prompt=i.prototype.prompt);const r=()=>{n.setPrompt(chalk.bold.magenta("icoa ioailab> ")),n.prompt()};return new Promise(e=>{const s=i=>{se(i).then(i=>{"exit"===i?((()=>{if(n.removeListener("line",s),o){a&&(n.prompt=a);for(const e of t)n.on("line",e)}else n.close()})(),e()):r()}).catch(e=>{$(`ioailab error: ${e instanceof Error?e.message:String(e)}`),r()})};n.on("line",s),r()})}
|
|
1
|
+
import{spawn as e}from"node:child_process";import{existsSync as o,mkdirSync as t,readFileSync as n,writeFileSync as a}from"node:fs";import{homedir as r}from"node:os";import{join as s}from"node:path";import{Interface as i,createInterface as l}from"node:readline";import chalk from"chalk";import{editTextInEditor as c}from"../lib/editor-spawn.js";import{buildSshArgs as u,leaseConnectProblems as g,parseLeaseResponse as y,queueLine as d,windowLine as m}from"../lib/gpu.js";import{enterPanel as f,leavePanel as p,printGuide as h,printHelp as w}from"../lib/guide-panel.js";import{logCommand as b}from"../lib/logger.js";import{getMainRl as v}from"../lib/main-rl.js";import{openFile as k}from"../lib/open-file.js";import{printError as $}from"../lib/ui.js";const x=W(),P=[{id:"pick-cube",env:"PrimeLite-PickCube-v0",blurb:"Robot arm picks a cube off the table (imitation-learning demo)"}],I=/^[a-z0-9-]{1,32}$/,U=/^MP4:(\/[A-Za-z0-9._/-]+\.mp4)\s*$/m,_=/^HDF5:(\/[A-Za-z0-9._/-]+\.hdf5)\s*$/m,A=/^CKPT:(\/[A-Za-z0-9._/-]+\.pth)\s*$/m,G=/^METRICS:(\{.*\})\s*$/m,O=/^algo(?:_used)?:\s*([a-z_]+)\s*$/im,S="/opt/ioailab-mj/work",C=`${S}/05_custom_agent.py`;function L(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):x}function T(){return s(r(),".icoa","gpu-key")}function E(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(T(),"utf-8").trim()||null}catch{return null}}function R(e){t(s(r(),".icoa"),{recursive:!0}),a(T(),`${e.trim()}\n`,{mode:384})}async function j(e,o,t){try{const n=await fetch(`${L()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{key:o,task:t}:{key:o}),signal:AbortSignal.timeout(2e4)});return y(await n.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}async function q(e){try{const o=await fetch(`${L()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await o.json();return t&&!0===t.success?"ok":"invalid"}catch{return"offline"}}let N=null,Y=null,M=null,K=!1,V=!1,z=!1,D=!1,B=!1,F=null;import{siteBase as W}from"../lib/site.js";function J(){return s(r(),"icoa-ioailab","05_custom_agent.py")}function Z(o,t,n,a){return new Promise(r=>{const s="local"===o.transport?{command:"/bin/sh",args:["-c",n]}:{command:"ssh",args:u(o,t,n)},i=e(s.command,s.args,{stdio:["ignore","pipe","pipe"]});let l="",c="";const g=setTimeout(()=>i.kill("SIGKILL"),a);i.stdout.on("data",e=>{l+=e.toString(),c+=e.toString();let o=c.indexOf("\n");for(;o>=0;){const e=c.slice(0,o).trimEnd();c=c.slice(o+1),e.length>0&&console.log(chalk.white(` ${e}`)),o=c.indexOf("\n")}}),i.stderr.on("data",e=>{const o=e.toString().trimEnd();o.length>0&&console.log(chalk.gray(` ${o}`))}),i.on("close",e=>{clearTimeout(g),r({code:e??1,out:l})}),i.on("error",()=>{clearTimeout(g),r({code:127,out:l})})})}function H(o,t,n,r){return new Promise(s=>{const i=u(o,t,`cat ${n}`),l=e("ssh",i,{stdio:["ignore","pipe","pipe"]}),c=[],g=setTimeout(()=>l.kill("SIGKILL"),12e4);l.stdout.on("data",e=>c.push(e)),l.on("close",e=>{if(clearTimeout(g),0!==e||0===c.length)return s(!1);try{a(r,Buffer.concat(c)),s(!0)}catch{s(!1)}}),l.on("error",()=>{clearTimeout(g),s(!1)})})}async function Q(o,t){if(!N)return!1;if("local"===N.transport)try{return a(t,n(o)),!0}catch{return!1}return function(o,t,a,r){return new Promise(s=>{let i;try{i=n(a)}catch{return s(!1)}const l=u(o,t,`mkdir -p ${S} && cat > ${r}`),c=e("ssh",l,{stdio:["pipe","ignore","pipe"]}),g=setTimeout(()=>c.kill("SIGKILL"),12e4);c.on("close",e=>{clearTimeout(g),s(0===e)}),c.on("error",()=>{clearTimeout(g),s(!1)}),c.stdin&&(c.stdin.on("error",()=>{}),c.stdin.write(i),c.stdin.end())})}(N,Y,o,t)}function X(){return!(!N||"ssh"===N.transport&&!Y)||(console.log(chalk.yellow(" No GPU box leased — ")+chalk.cyan("on")+chalk.gray(" first.")),!1)}function ee(e,o,t){let n;for(let t=0;t<e.length;t++){const a=e[t];a===`--${o}`&&t+1<e.length?n=e[t+1]:a.startsWith(`--${o}=`)?n=a.slice(o.length+3):void 0===n&&/^[0-9]+$/.test(a)&&(n=a)}if(void 0===n)return t;const a=Number.parseInt(n,10);return Number.isFinite(a)?Math.min(999,Math.max(1,a)):t}async function oe(e,o,t,n){if(!N||"ssh"===N.transport&&!Y)return null;const a=P[0].id;return Z(N,Y??"",`sudo -n /usr/local/bin/ioailab-run ${a} ${e} --${o} ${t}`,n)}function te(e){4===e?console.log(chalk.yellow(" The box says an earlier step is missing — run it first (")+chalk.cyan("guide")+chalk.yellow(" shows where you are).")):2===e?console.log(chalk.red(" The box rejected the request (bad arguments).")):console.log(chalk.red(" Step failed on the box.")+chalk.gray(" (lease may have expired — ")+chalk.cyan("status")+chalk.gray(")"))}async function ne(e,o){if(!function(e){const o=N?.outDir??"";return!(""===o||!e.startsWith(o))||e===S||e.startsWith(`${S}/`)}(e))return void console.log(chalk.red(" Rejected unexpected video path from the box."));const i=s(r(),"icoa-ioailab");t(i,{recursive:!0});const l=s(i,`${o}-${Date.now()}.mp4`);process.stdout.write(chalk.gray(" Pulling the rendered clip…")),("local"===N?.transport?(()=>{try{return a(l,n(e)),!0}catch{return!1}})():await H(N,Y,e,l))?(M=l,console.log(chalk.green(" done.")),console.log(chalk.magenta(" 🎬 clip → ")+chalk.cyan(l)),k(l)?console.log(chalk.gray(" Opened in your video viewer. ")+chalk.cyan("watch")+chalk.gray(" reopens it any time.")):console.log(chalk.gray(" Open it with your video player."))):console.log(chalk.red(" failed."))}function ae(e){const o=e.match(G);if(!o)return void console.log(chalk.yellow(" Finished, but no metrics came back from the box."));let t;try{t=JSON.parse(o[1])}catch{return void console.log(chalk.yellow(" (metrics came back in an unexpected format.)"))}if(F=t,"number"==typeof t.success_rate){const e="number"==typeof t.episodes?` over ${t.episodes} episode(s)`:"";console.log(chalk.bold.green(` ★ success rate: ${(100*t.success_rate).toFixed(1)}%`)+chalk.gray(e))}for(const[e,o]of Object.entries(t))"success_rate"!==e&&"episodes"!==e&&("number"!=typeof o&&"string"!=typeof o||console.log(chalk.gray(` ${e}: `)+chalk.white(String(o))))}function re(){let e;e=K?V?z?D?"edit custom":"eval":"train":"mimic":"collect",console.log(chalk.gray(" Next: ")+chalk.cyan(e)+chalk.gray(" (")+chalk.cyan("guide")+chalk.gray(" = where you are)"))}const se={id:"ioailab",title:"IOAI Lab",what:"A practice twin of the IOAI Team Challenge: lease a GPU box, then drive the contest workflow — record expert demos, expand them, train a diffusion policy on them, evaluate it, write your own agent. Videos open on this machine.",steps:[{verb:"on",what:"lease a GPU box (nothing installs here)",done:()=>null!==N},{verb:"collect",what:"record expert demos → watch the arm pick the cube",done:()=>K},{verb:"mimic",what:"expand your demos (pose-randomized, MimicGen-lite)",done:()=>V},{verb:"train",what:"robomimic Diffusion Policy on YOUR demos (GPU, scored)",done:()=>z},{verb:"eval",what:"run YOUR policy → success rate → watch",done:()=>D},{verb:"edit custom",what:"write your own BaseAgent, then custom runs it",done:()=>B},{verb:"watch",what:"replay the last clip",done:()=>null!==M,optional:!0}],notes:["status = lease time left · off = release the box · tasks = the task list. Leaving releases the lease."],leave:{verb:"exit",what:"leave IOAI Lab (lease released)"},guide:()=>function(){let e=!1;const o=[["collect",K],["mimic",V],["train",z],["eval",D],["custom",B]].map(([o,t])=>t?`${o} ${chalk.green("✓")}`:e?`${o} ${chalk.gray("○")}`:(e=!0,`${o} ${chalk.yellow("…")}`));console.log(),console.log(chalk.bold.white(" ═══ 📖 IOAI Lab — the 5-step workflow ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+o.join(chalk.gray(" · "))),console.log(" "+(N?chalk.green("⚡ lease active")+chalk.gray(" (")+chalk.cyan("status")+chalk.gray(" for time left)"):chalk.gray("no lease — ")+chalk.cyan("on")+chalk.gray(" to lease a box"))),F&&"number"==typeof F.success_rate&&console.log(chalk.gray(" Last result: ")+chalk.green(`${(100*F.success_rate).toFixed(1)}% success`)),console.log(),console.log(chalk.bold.white(" Your move — drive the contest workflow:")),console.log(chalk.gray(" 1. ")+chalk.cyan("collect")+chalk.gray(" expert demos → watch the arm pick the cube")),console.log(chalk.gray(" 2. ")+chalk.cyan("mimic")+chalk.gray(" expand your demos (pose-randomized, MimicGen-lite)")),console.log(chalk.gray(" 3. ")+chalk.cyan("train")+chalk.gray(" robomimic Diffusion Policy on YOUR demos (GPU, scored)")),console.log(chalk.gray(" 4. ")+chalk.cyan("eval")+chalk.gray(" run YOUR policy → success rate → watch")),console.log(chalk.gray(" 5. ")+chalk.cyan("edit custom")+chalk.gray(" / ")+chalk.cyan("custom")+chalk.gray(" write your own BaseAgent → run it → watch")),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(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it to explain a step or debug your agent — then ")+chalk.bold.white("VERIFY")+chalk.gray(" by re-running ")+chalk.cyan("eval")+chalk.gray(".")),console.log(),console.log(chalk.cyan(" on")+chalk.gray("/")+chalk.cyan("off")+chalk.gray(" lease a box · ")+chalk.cyan("status")+chalk.gray(" time left · ")+chalk.cyan("watch")+chalk.gray(" replay last clip · ")+chalk.cyan("run")+chalk.gray(" quick showcase · ")+chalk.cyan("exit")+chalk.gray(" leave")),console.log()}()};async function ie(e=!1){const o=E();o&&N&&await j("release",o),N&&!e&&console.log(chalk.gray(" GPU lease released.")),N=null,Y=null,K=!1,V=!1,z=!1,D=!1,B=!1,F=null}async function le(e){const i=e.trim();if(0===i.length)return"continue";const[l,...u]=i.split(/\s+/),y=l.toLowerCase();return b(`ioailab ${y}`),"exit"===y||"quit"===y||"q"===y||"back"===y||"menu"===y?(await ie(!0),p(se.id),console.log(chalk.gray(" Leaving IOAI Lab — any GPU lease was released.")),"exit"):("help"===y||"/help"===y||"?"===y?/^(all|commands|full)$/i.test(u[0]??"")?h():w():"guide"===y||"/guide"===y?h():"tasks"===y||"task"===y?function(){console.log();for(const e of P)console.log(chalk.cyan(` ${e.id.padEnd(12)}`)+chalk.gray(e.blurb));console.log()}():"key"===y?0===u.length?console.log(chalk.gray(" Usage: ")+chalk.cyan("key <your-access-key>")):(R(u[0]),console.log(chalk.green(" ✓ GPU access key saved.")+chalk.gray(" Next: ")+chalk.cyan("on"))):"on"===y||"lease"===y||"gpu"===y?await async function(){if(N)return void console.log(chalk.gray(" already holding a GPU lease — ")+chalk.cyan("status")+chalk.gray(" for time left."));const e=E();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));process.stdout.write(chalk.gray(" Requesting a GPU box…"));let o=await j("lease",e,"ioailab"),n=0;for(;"queued"===o.state&&n<24;)0===n&&console.log(),process.stdout.write(`\r ${chalk.yellow(d(o))} `),await new Promise(e=>setTimeout(e,5e3)),o=await j("status",e),n++;if("queued"===o.state)return console.log(),void console.log(chalk.yellow(" Still queued — your place is held server-side. Try ")+chalk.cyan("on")+chalk.gray(" again in a few minutes."));if("ready"!==o.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${o.message??"no lease granted"}`));const i=g(o);if("local"!==o.transport||process.env.ICOA_GPU_SERVER||i.push("local transport from a non-dev broker"),i.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(i.join(", "))),void await j("release",e);let l=null;if("ssh"===o.transport&&(l=function(e){const o=s(r(),".icoa","gpu","ioailab-lease-key");try{return t(s(r(),".icoa","gpu"),{recursive:!0}),a(o,e.keyPem,{mode:384}),o}catch{return null}}(o),!l))return console.log(chalk.red(" could not write the ssh key locally.")),void await j("release",e);N=o,Y=l;const c=Math.round((o.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU box leased.")+chalk.gray(` ~${c}m on this lease.`));const u=m(o.windowCloseEpoch);u&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${u}.`)),console.log(chalk.gray(" Next: ")+chalk.cyan("collect")+chalk.gray(" — start the 5-step chain (or ")+chalk.cyan("run")+chalk.gray(" for a quick one-shot showcase)."))}():"off"===y||"release"===y?await ie():"status"===y||"queue"===y?await async function(){const e=E();if(!e)return void console.log(chalk.yellow(" No GPU access key saved — ")+chalk.cyan("key <k>")+chalk.gray(" first."));const o=await j("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ lease active · ~${e}m left.`));const t=m(o.windowCloseEpoch);t&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${t}.`))}else"queued"===o.state?console.log(` ${chalk.yellow(d(o))}`):console.log(chalk.gray(" no active lease — ")+chalk.cyan("on")+chalk.gray(" to request a box."))}():"run"===y?await async function(e){const o=P.find(o=>o.id===e);if(!o||!I.test(e))return void console.log(chalk.yellow(` Unknown task "${e}" — `)+chalk.cyan("tasks")+chalk.gray(" lists what is available."));if(!X())return;console.log(chalk.gray(` Running the ${o.id} task (ICOA-VLA arm) on the GPU box (headless — takes a moment)…`));const t=`sudo -n /usr/local/bin/ioailab-run ${e} 1`,{code:n,out:a}=await Z(N,Y??"",t,72e4);if(0!==n)return void console.log(chalk.red(" Episode failed on the box.")+chalk.gray(" (lease may have expired — ")+chalk.cyan("status")+chalk.gray(")"));const r=a.match(U);r?await ne(r[1],e):console.log(chalk.yellow(" Episode finished but no video path came back — box-side renderer issue."))}((u[0]??P[0].id).toLowerCase()):"collect"===y?await async function(e){if(!X())return;const o=ee(e,"episodes",5);console.log(chalk.gray(` Collecting ${o} expert demo(s) on the ICOA-VLA arm (headless — takes a moment)…`));const t=await oe("collect","episodes",o,72e4);if(!t)return;if(0!==t.code)return te(t.code);const n=t.out.match(_);n&&(K=!0,console.log(chalk.green(" ✓ expert demos recorded → ")+chalk.gray(n[1]))),console.log(chalk.gray(" The expert is a scripted reach→grasp→lift waypoint controller (our stand-in for")),console.log(chalk.gray(" the contest's motion planner) — a clean demonstration source, not a learned policy yet."));const a=t.out.match(U);a&&await ne(a[1],"collect"),re()}(u):"mimic"===y?await async function(e){if(!X())return;if(!K)return void console.log(chalk.yellow(" No demos yet — run ")+chalk.cyan("collect")+chalk.gray(" first."));const o=ee(e,"episodes",36);console.log(chalk.gray(` Expanding your demos into ${o} training episode(s)…`));const t=await oe("mimic","episodes",o,72e4);if(!t)return;if(0!==t.code)return te(t.code);const n=t.out.match(_);n&&(V=!0,console.log(chalk.green(" ✓ training demos generated → ")+chalk.gray(n[1]))),console.log(chalk.gray(" MimicGen-lite: we randomize the cube pose and re-run the pose-conditioned expert —")),console.log(chalk.gray(" real rollouts, same robomimic schema, not the object-centric MimicGen the full sim uses.")),re()}(u):"train"===y?await async function(e){if(!X())return;if(!V)return void console.log(chalk.yellow(" No training set yet — run ")+chalk.cyan("mimic")+chalk.gray(" first."));const o=ee(e,"epochs",20),t=54e5,n=N?.timeLeftSec??0;if(n>0&&1e3*n<t){const e=Math.round(n/60);console.log(chalk.yellow(` ⚠ your lease has ~${e}m left`)+chalk.gray(" — a long train may outlast it. ")+chalk.cyan("off")+chalk.gray("/")+chalk.cyan("on")+chalk.gray(" to refresh first if needed."))}console.log(chalk.gray(` Training a robomimic Diffusion Policy for ${o} epoch(s) on YOUR demos — the scored step (GPU)…`));const a=await oe("train","epochs",o,t);if(!a)return;if(0!==a.code)return te(a.code);const r=a.out.match(A);r&&(z=!0,console.log(chalk.green(" ✓ checkpoint saved → ")+chalk.gray(r[1])));const s=a.out.match(O);s&&/bc/i.test(s[1])?console.log(chalk.gray(" (behavior-cloning fallback — real diffusion pending on this box.)")):console.log(chalk.gray(" Same open robomimic Diffusion Policy the real contest uses — high-fidelity where it counts.")),re()}(u):"eval"===y?await async function(e){if(!X())return;if(!z)return void console.log(chalk.yellow(" No trained policy yet — run ")+chalk.cyan("train")+chalk.gray(" first."));const o=ee(e,"episodes",20);console.log(chalk.gray(` Running YOUR trained policy for ${o} episode(s)…`));const t=await oe("eval","episodes",o,72e4);if(!t)return;if(0!==t.code)return te(t.code);ae(t.out),D=!0,console.log(chalk.gray(" Your number reflects the practice arm + your demo count/epochs — it's the workflow signal,")),console.log(chalk.gray(" not a contest leaderboard score."));const n=t.out.match(U);n&&await ne(n[1],"eval"),re()}(u):"custom"===y?await async function(e){if(!X())return;const t=J();if(!o(t))return void console.log(chalk.yellow(" No custom agent yet — ")+chalk.cyan("edit custom")+chalk.gray(" to write one first."));process.stdout.write(chalk.gray(" Uploading your agent…"));const n=await Q(t,C);if(console.log(n?chalk.green(" done."):chalk.red(" failed.")),!n)return;const a=ee(e,"episodes",9);console.log(chalk.gray(` Running YOUR agent for ${a} episode(s)…`));const r=await oe("custom","episodes",a,72e4);if(!r)return;if(0!==r.code)return te(r.code);ae(r.out),B=!0;const s=r.out.match(U);s?await ne(s[1],"custom"):console.log(chalk.gray(" (no replay — for it to render, your agent must be constructible with no required args. Metrics above.)")),console.log(chalk.gray(" Iterate: ")+chalk.cyan("edit custom")+chalk.gray(" → ")+chalk.cyan("custom")+chalk.gray(" → watch, repeat."))}(u):"edit"===y?"custom"===(u[0]??"").toLowerCase()?await async function(){if(!X())return;const e=s(r(),"icoa-ioailab");t(e,{recursive:!0});const i=J();o(i)||(process.stdout.write(chalk.gray(" Fetching the starter agent…")),await async function(e,o){if(!N)return!1;if("local"===N.transport)try{return a(o,n(e)),!0}catch{return!1}return H(N,Y,e,o)}("/opt/ioailab-mj/examples/05_custom_agent.py",i)?console.log(chalk.green(" done.")):(a(i,'"""05_custom_agent.py — your agent for the ICOA-VLA arm.\n\nSubclass BaseAgent and implement act(env, env_ids) -> array [rows, action_dim].\nKeep the constructor argument-free so the replay can render your agent\n(like the SinusoidAgent starter below). Then: edit custom -> custom -> watch.\n"""\nimport numpy as np\n\ntry:\n from icoa_ioailab.agents import BaseAgent\nexcept Exception: # resolved on the GPU box\n BaseAgent = object\n\n\nclass SinusoidAgent(BaseAgent):\n def __init__(self):\n self._t = 0\n\n def act(self, env, env_ids):\n rows = len(env_ids)\n dim = getattr(env, "action_dim", 7)\n self._t += 1\n cmd = 0.1 * np.sin(self._t * 0.2)\n return np.full((rows, dim), cmd, dtype=np.float32)\n'),console.log(chalk.gray(" using a local starter."))));const l=n(i,"utf-8"),u=c(l,".py");if(null===u)return void console.log(chalk.yellow(" Editor cancelled — agent unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));a(i,u),process.stdout.write(chalk.gray(" Saving to the box…"));const g=await Q(i,C);console.log(g?chalk.green(" done."):chalk.red(" failed.")),console.log(chalk.gray(" Saved → run ")+chalk.cyan("custom")+chalk.gray(" to try it."))}():console.log(chalk.gray(" Usage: ")+chalk.cyan("edit custom")+chalk.gray(" (write your own agent)")):"watch"===y||"open"===y?M&&k(M)?console.log(chalk.gray(" Reopened the last clip.")):console.log(chalk.gray(" No clip yet — ")+chalk.cyan("collect")+chalk.gray(" or ")+chalk.cyan("run")+chalk.gray(" first.")):console.log(chalk.yellow(` Unknown command "${y}" — `)+chalk.cyan("guide")+chalk.gray(" lists everything.")),"continue")}export async function runIoailabStandalone(){if(!await async function(){const{default:e}=await import("@inquirer/input"),o=E();if(o){const e=await q(o);if("ok"===e)return!0;if("offline"===e)return console.log(chalk.yellow(" Cannot reach the GPU service to verify your key right now — try again later.")),!1;console.log(chalk.yellow(" Your saved GPU key was not accepted. Enter a valid one below."))}else console.log(chalk.gray(" IOAI Lab is a paid GPU service. Enter the GPU access key issued with your purchase."));for(let o=0;o<3;o++){let t;try{t=await e({message:chalk.bold.magenta("icoa ioailab key>"),theme:{prefix:"",style:{message:e=>e}}})}catch{return!1}const n=t.trim();if(""===n||"exit"===n.toLowerCase()||"q"===n.toLowerCase())return!1;const a=await q(n);if("ok"===a)return R(n),console.log(chalk.green(" ✓ Key accepted — saved to this device. You will not be asked again.")),!0;if("offline"===a)return console.log(chalk.yellow(" Cannot reach the GPU service to verify — try again later.")),!1;console.log(chalk.red(` Key not recognised (${o<2?2-o+" tries left":"no tries left"}).`))}return!1}())return;console.log(),console.log(chalk.bold.magenta(" 🤖 IOAI Lab — Embodied AI practice twin (ICOA-VLA arm)")),console.log(chalk.gray(" The official Team-Challenge sim uses assets we can't hand out — so this is a")),console.log(chalk.gray(" practice twin: the same 5-step workflow, the same Python API, a real arm you drive.")),console.log(chalk.gray(" The scored part — training a diffusion policy from your own demos with robomimic")),console.log(chalk.gray(" (open source) — is byte-for-byte the framework the real contest uses.")),console.log(chalk.gray(" Runs on an ICOA GPU box — nothing installs here; the video opens locally.")),console.log(),console.log(chalk.white(" You will drive the exact contest workflow:")),console.log(" "+chalk.bold.cyan("collect")+chalk.gray(" → ")+chalk.bold.cyan("mimic")+chalk.gray(" → ")+chalk.bold.cyan("train")+chalk.gray(" → ")+chalk.bold.cyan("eval")+chalk.gray(" → ")+chalk.bold.cyan("custom")),console.log(chalk.gray(" v1 is a single task (pick-cube) on a MuJoCo arm; the real contest is multi-task on a")),console.log(chalk.gray(" higher-fidelity simulator — the learning core is the same.")),f(se);const e=v(),o=null!==e,t=o?e.listeners("line").slice():[];o&&e.removeAllListeners("line");const n=o?e:l({input:process.stdin,output:process.stdout,terminal:!0}),a=o?n.prompt:null;o&&(n.prompt=i.prototype.prompt);const r=()=>{n.setPrompt(chalk.bold.magenta("icoa ioailab> ")),n.prompt()};return new Promise(e=>{const s=i=>{le(i).then(i=>{"exit"===i?((()=>{if(n.removeListener("line",s),o){a&&(n.prompt=a);for(const e of t)n.on("line",e)}else n.close()})(),e()):r()}).catch(e=>{$(`ioailab error: ${e instanceof Error?e.message:String(e)}`),r()})};n.on("line",s),r()})}
|
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 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}
|
|
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";import{serviceBase as le,siteBase as re}from"../lib/site.js";const ae=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function se(){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 ie(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const ce=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),ge=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function ye(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const de=re();function ue(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):de}function he(){return u(a(),".icoa","gpu-key")}function pe(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return t(he(),"utf-8").trim()||null}catch{return null}}async function me(e,o,n){try{const t=await fetch(`${ue()}/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 fe(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let we=0,be=null;function ke(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(ae,"")}`))}else"display"===n.kind&&ve(n.data,o)}function ve(e,n){if(e["image/png"])try{o(n,{recursive:!0}),we+=1;const t=u(n,`figure-${we}.png`);return r(t,Buffer.from(e["image/png"],"base64")),be=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 $e(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function _e(e){if(e)try{return l(e).mtimeMs}catch{return}}function xe(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:_e(l),diskSig:$e(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 Pe={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const re=E?.trim().toLowerCase().replace(/-demo$/,"");if(re&&Pe[re]){const n=await async function(n){const l=Pe[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}(re);if(!n)return;E=n}const de=p(a()),we=u(a(),".icoa","ipynb-out");ie();const ve=e(de.python),Se=X();if(!ve&&!Se)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 Ee=E?xe(E):null,Ce=Ee?Ee.doc:{cells:[],path:null,dirty:!1};let Ge=new I({venvPython:de.python,venvRoot:de.root}),je=null,Ue=null,Ae=null,Ie=fe(Ce.path);if(ve){process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Ge.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("."));Ee&&console.log(Ee.note);let Ne=!1,Te=!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:()=>Ne},{verb:"run all",what:{en:"run every cell top to bottom; stops at the first error",zh:"从头到尾跑每一格;遇到第一个报错就停"},done:()=>Ce.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:()=>Ce.dirty},{verb:"save",what:{en:"write it back to disk as a real .ipynb",zh:"存回磁盘,标准 .ipynb"},done:()=>Te},{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!==je,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:()=>He()});const Oe=T(),Me=null!==Oe,De=Me?Oe.listeners("line").slice():[];Me&&Oe.removeAllListeners("line");const qe=Me?Oe:c({input:process.stdin,output:process.stdout,terminal:!0});Me||O(qe);const Le=Me?qe.prompt:null,ze=Me?qe.getPrompt():"";Me&&(qe.prompt=i.prototype.prompt),Me||D();const Re=[];let Ke,Be=!1,Fe=!1,We=!1,Je=null,Ve=null;const Ye=()=>{if(Ve)return qe.setPrompt(chalk.bold.cyan(` editor 1-${Ve.options.length} > `)),void qe.prompt();const e=je?"icoa ipynb ⚡gpu":"icoa ipynb";qe.setPrompt(chalk.bold.cyan(Re.length?`${e} ...> `:`${e}> `)),qe.prompt()},He=()=>{const o=Ce.path?y(Ce.path):process.cwd(),n=fe(Ce.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=Ce.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(Ce.path?g(Ce.path):"new empty notebook")+chalk.gray(` · ${Ce.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),je?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 Xe=()=>{};const Ze=new Promise(e=>{Xe=e}),Qe=async()=>{if(Ge=new I({venvPython:de.python,venvRoot:de.root}),e(de.python)){process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Ge.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."))},eo=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=Ce.path?g(y(Ce.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 Ge.shutdown().catch(()=>{}),Ge=h,je={...t,outDir:c},Ae=e,Ue=Date.now(),h.onUnexpectedExit=()=>{Ge===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).")),je=null,Ae=null,Ue=null,Qe().then(()=>Ye()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${Z[e.tier]} · cells run in ${c}`));const p=await oo();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},oo=async()=>{if(!Ce.path||!je?.outDir)return 0;const e=y(Ce.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 Ge.putFile(`${je.outDir}/${n}`,t(o)),r++}catch{}}return r},no=async(e,n=!1)=>{if(!je)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:`${je.outDir}/${t}`;let a;try{a=await Ge.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=Ie?u(process.cwd(),"icoa-kaggle",Ie):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&&Ie&&"submission.csv"===g(t)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Ie}`)+chalk.gray(" · score it: ")+chalk.cyan("submit")),!0},to=async e=>{const[n,...t]=e.trim().split(/\s+/),l=(n??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(je)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 eo(e)})(e);const n=pe();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)."));Ie||(Ie=fe(Ce.path));const t=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await me("lease",n,Ie??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 me("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 me("release",n);const y=Ie?`${l.dataRoot}/${Ie}`: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 me("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 me("release",n)}await Ge.shutdown().catch(()=>{}),Ge=p,je=l,Ue=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.")),Ie&&console.log(chalk.gray(` Dataset is already on the box (${Ie}) — 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(je&&Ae){const e=Ue?Math.round((Date.now()-Ue)/1e3):0;return await Ge.shutdown().catch(()=>{}),je=null,Ae=null,Ue=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 Qe()}if(!je)return void console.log(chalk.gray(" not on a GPU kernel."));const e=pe(),o=void 0!==je.gpuName,n=Ue?Math.round((Date.now()-Ue)/1e3):0;await Ge.shutdown().catch(()=>{}),e&&await me("release",e),je=null,Ue=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 Qe()})():"status"===l||""===l?await(async()=>{const e=X();if(e)return console.log(chalk.green(` ⚡ committee seat · ${Z[e.tier]} · ${e.host}`)+chalk.gray(Ae?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=pe();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const n=await me("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(je?" (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=pe();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(`${ue()}/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(he(),`${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(` (${he()})`))}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>"))},lo=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Ce.cells.length?(console.log(0===Ce.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Ce.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Ce.cells[o-1],idx:o}},ro=(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 ao=!1;const so=()=>{const e=w().notebookEditor;return e?_(e):null},io=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),co=()=>so()??x(),go={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"},yo=(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(so()||io())return o(co()),!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(` ${go[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),Ve={resume:o,tries:0,options:n},!1)},uo=e=>{if(!Ce.path)return!1;let o;try{const e=t(Ce.path,"utf8");o=Ce.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(Ce.cells,o);return Ce.cells=n.cells,Ce.dirty=!1,Ce.mtimeMs=_e(Ce.path),Ce.diskSig=$e(o),Ke=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Ce.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},ho=()=>void 0!==Ce.diskSig?$e(Ce.cells)!==Ce.diskSig:Ce.dirty,po=(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)),mo=async o=>{if(o.trim()&&M(`ipynb: ${o.trim()}`),Fe)return void(o.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Ve){const e=Ve,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?(Ve=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)?(Ve=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Ve=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 Ye()}let n=o.trim();if(0===Re.length&&/^icoa\s+[a-z/]/i.test(n)&&(n=n.replace(/^icoa\s+/i,"")),0===Re.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&&(We=!1),Je&&l!==Je&&(Je=null),ge.has(l)&&(()=>{if(!Ce.path||void 0===Ce.mtimeMs)return;const e=_e(Ce.path);if(void 0!==e&&e!==Ce.mtimeMs){if(ho()){if(Ke===e)return;return Ke=e,console.log(chalk.yellow(` ⚠ ${g(Ce.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"))}uo(!0)}})(),"quit"===l||"exit"===l||"back"===l||"q"===l||"menu"===l)return Ce.dirty&&!We?(We=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ye()):void await(async()=>{if(ee("ipynb"),qe.removeAllListeners("line"),Me||q(),console.log(),je&&Ae)je=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(je){const e=pe();e&&await me("release",e),je=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Ge.shutdown().catch(()=>{}),Me){Le&&(qe.prompt=Le),qe.setPrompt(ze);for(const e of De)qe.on("line",e);qe.prompt(),Xe()}else O(null),Xe(),qe.close()})();if("clear"===l||"cls"===l)return console.clear(),ie(),void Ye();if("restart"===l)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Ge.shutdown().catch(()=>{});try{await Ge.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 Ye();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(se()?" 问 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 Ye();if("guide"===l||"/guide"===l)return He(),void Ye();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 Ye();if("open"===l&&""===i)return be&&te(be)?console.log(chalk.gray(" reopening ")+chalk.cyan(be)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ye();if("cells"===l||"ls"===l)return(()=>{if(Ne=!0,0===Ce.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);Ce.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 Ye();if("show"===l)return(e=>{const o=lo(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 ──")),ke(o.cell.result,we)),console.log()}})(i),void Ye();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?yo(o,e=>(e=>{qe.pause();const o=k(Y(Ce.cells),".py",e,"notebook");if(qe.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,Ce.cells);if(n.same)return void console.log(chalk.gray(" no changes."));if(0===n.cells.length&&Ce.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${Ce.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));Ce.cells=n.cells,Ce.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 — ${Ce.cells.length} cells`)+chalk.gray(` · ${t.join(" · ")}`));const l=[...n.changed,...n.added].filter(e=>"code"===Ce.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)):lo(n)&&yo(o,e=>((e,o)=>{const n=lo(e);if(!n)return;qe.pause();const t=k(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(qe.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,Ce.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 Ye()}if("add"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ");return yo(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)"));qe.pause();const l=k(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);qe.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Ce.cells.push({kind:t?"markdown":"code",source:r,result:null}),Ce.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${Ce.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Ce.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void Ye()}if("editor"===l&&/^[\w-]*$/.test(i))return(e=>{const o=e.trim().toLowerCase(),n=$(co());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${so()?"saved":io()?"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?` ${go[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);so()&&$(so())===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 Ye();if("reload"===l&&""===i)return Ce.path&&e(Ce.path)?ho()&&"reload"!==Je?(Je="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."))):(Je=null,uo(!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 Ye();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 Ye();const o=K(i,a()),n=d(o)?o:h(process.cwd(),o);if(e(n))if(Ce.dirty&&"load"!==Je)Je="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{Je=null;const e=xe(n);Ce.cells=e.doc.cells,Ce.path=e.doc.path,Ce.dirty=!1,Ce.mtimeMs=e.doc.mtimeMs,Ce.diskSig=e.doc.diskSig,Ke=void 0,Ie=fe(Ce.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 Ye()}if("del"===l||"delete"===l)return(e=>{const o=lo(e);o&&(Ce.cells.splice(o.idx-1,1),Ce.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Ce.cells.length} left.`)+(o.idx<=Ce.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(i),void Ye();if(("md"===l||"py"===l)&&/^\d+$/.test(i))return((e,o)=>{const n=lo(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,Ce.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 Ye();if("gpu"===l)return Fe=!0,await to(i),Fe=!1,void Ye();if("download"===l||"dl"===l)return Fe=!0,await no(i),Fe=!1,void Ye();if("selfcheck"===l||"self-check"===l)return Fe=!0,await(async()=>{const e=Ae;if(!e||!je)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===Ce.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=Ge;if(await eo(e,!0),Ge===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<Ce.cells.length;e++){const o=Ce.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 Ge.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}Ce.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){ke(o.result,we),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 Ge.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:Ce.path?g(Ce.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(`${le("ICOA_GPUTASK_SERVER").replace(/\/$/,"")}/api/icoa/gputask/selfcheck`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,report:y}),signal:AbortSignal.timeout(2e4)});console.log(o.ok?chalk.gray(" report filed with the committee ✓"):chalk.yellow(` report not filed (http ${o.status}) — keep the numbers above.`))}catch{console.log(chalk.yellow(" report not filed (offline) — keep the numbers above."))}})(),Fe=!1,void Ye();if("upload"===l||"up"===l||"put"===l)return Fe=!0,await(async e=>{if(!je)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(Ce.path?y(Ce.path):process.cwd(),n);let r;try{r=t(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${je.outDir}/${g(l)}`;try{const e=await Ge.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),Fe=!1,void Ye();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])||fe(Ce.path)||void 0;Fe=!0;try{if(("submit"===n||"check"===n)&&je&&!await no("submission.csv",!0))return Fe=!1,void Ye();if("submit"===n){const o=s("sha256").update(Ce.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(t,{code_sha:o,...Ae?{sid:Ae.sid}:{},...Ce.path?{notebook:g(Ce.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 Fe=!1,void Ye()}if("board"===l){const{runBoard:e}=await import("./board.js"),o=i.split(/\s+/).filter(Boolean);Fe=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Fe=!1,void Ye()}if("ai"===l||"/ai"===l)return Fe=!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=Ce.cells.length-1;e>=0;e--)if((Ce.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Ce.cells.length;if(0===Ce.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=lo(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(ae,"")).join("\n")));return o.join("\n").replace(ae,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Ce.path||!fe(Ce.path))return"";try{const e=JSON.parse(t(u(y(Ce.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return ro(o,350)}catch{return""}})(),c=se(),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=ro(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(),ao||(ao=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(se()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${m} ${se()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(se()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(se()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — 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),Fe=!1,void Ye();if("run"===l)return Fe=!0,await(async e=>{if(!ve&&!Ae&&!je)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,Ce.cells.length);if(o)for(const e of o){const n=Ce.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 Ge.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void ye()}if(Ce.dirty=!0,ke(n.result,we),po(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(se()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(se()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void ye()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(n.source))console.log(e);console.log()}}else console.log(0===Ce.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),Fe=!1,void Ye();if("save"===l)return(e=>{if(0===Ce.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()):Ce.path?Ce.path.endsWith(".ipynb")?Ce.path:`${Ce.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===Ce.path?_e(o):void 0;if(void 0!==n&&void 0!==Ce.mtimeMs&&n!==Ce.mtimeMs&&"save"!==Je)return Je="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"));Je=null;try{r(o,J(Ce.cells)),Ce.path=o,Te=!0,Ce.dirty=!1,Ce.mtimeMs=_e(o),Ce.diskSig=$e(Ce.cells),Ke=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Ce.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),void Ye();if(""===n)return void Ye()}if(Re.length>0&&ce.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 Ye();if(Re.push(o),!j(Re))return 1!==Re.length||Be||(Be=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ye();const l=Re.join("\n").replace(/\s+$/,"");if(Re.length=0,""!==l.trim()){Fe=!0;try{const e=await Ge.execute(l);Ce.cells.push({kind:"code",source:l,result:e}),Ce.dirty=!0,ke(e,we);const o=po(Ce.cells[Ce.cells.length-1],Ce.cells.length);e.ok||o||ye()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),ye()}Fe=!1,Ye()}else Ye()};qe.on("line",e=>{mo(e)}),Me||qe.on("close",async()=>{await Ge.shutdown().catch(()=>{}),process.exit(0)}),Ye(),await Ze}
|