icoa-cli 2.19.684 → 2.19.686
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/battle.js +1 -1
- package/dist/commands/comms.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/demo3.js +1 -1
- package/dist/commands/duck-contest.js +1 -1
- package/dist/commands/duck-cup.js +1 -1
- package/dist/commands/duck.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/gfssm.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/learn.js +1 -1
- package/dist/commands/sim.js +1 -1
- package/dist/commands/sprint.js +1 -1
- package/dist/commands/wm.js +1 -1
- package/dist/lib/algo-replay.js +1 -1
- package/dist/lib/card-engine.js +1 -1
- package/dist/lib/guide-panel.js +1 -0
- package/dist/lib/learn-cup.js +1 -1
- package/dist/lib/learn-pvp.js +1 -1
- package/dist/lib/learn-team.js +1 -1
- package/dist/repl.js +1 -1
- package/package.json +1 -1
package/dist/commands/gfssm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFile as e}from"node:child_process";import{mkdir as o,writeFile as n}from"node:fs/promises";import{homedir as t}from"node:os";import{join as r}from"node:path";import{createInterface as s,Interface as i}from"node:readline";import chalk from"chalk";import{
|
|
1
|
+
import{execFile as e}from"node:child_process";import{mkdir as o,writeFile as n}from"node:fs/promises";import{homedir as t}from"node:os";import{join as r}from"node:path";import{createInterface as s,Interface as i}from"node:readline";import chalk from"chalk";import{enterPanel as a,isGuideWord as l,isHelpWord as c,leavePanel as d,printHelp as g}from"../lib/guide-panel.js";import{getMainRl as p}from"../lib/main-rl.js";const u=process.env.RENDER_BOX||"http://172.235.198.124:9098",f=r(t(),".icoa","render-out");let h=[],m=null,w=null;function y(e){return new Promise(o=>{const n=p();if(n)return w=o,n.setPrompt(e),void n.prompt();const t=s({input:process.stdin,output:process.stdout});t.question(e,e=>{t.close(),o(e)})})}function b(o,n){const t="darwin"===process.platform?"open":"xdg-open";e(t,[o],e=>{e&&console.log(chalk.yellow((n?" 用文件浏览器打开:":" Open in your file browser: ")+o))})}let v=null,G=null;function P(e){console.log(chalk.yellow(e?" ⏸ GPU 还没准备好 — 渲染箱不在线。":" ⏸ GPU not ready — the render box is offline right now.")),console.log(chalk.gray(e?" 晚点再来试;":" Try again later; ")+chalk.bold.green("back")+chalk.gray(e?" 回上一层。":" returns to the previous layer."))}async function z(e,t,s){let i;try{const o=await fetch(`${u}/render`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:e,seconds:5,base_job:s}),signal:AbortSignal.timeout(8e3)});if(!o.ok)return void P(t);i=(await o.json()).job,G=i}catch{return void P(t)}console.log(chalk.gray((t?" 任务 ":" job ")+i+(t?" 已提交,AI 正在写场景代码…":" queued — AI is writing the scene…")));const a=async()=>{try{return await(await fetch(`${u}/status/${i}`)).json()}catch{return null}},l=async e=>{try{await o(f,{recursive:!0});const e=Buffer.from(await(await fetch(`${u}/video/${i}`)).arrayBuffer());v=r(f,`gfssm-${i}.mp4`),await n(v,e)}catch(e){const o=e instanceof Error?e.message:String(e);return void console.log(chalk.red((t?" ✗ 下载失败:":" ✗ download failed: ")+o))}const s=((e.bytes||0)/1e6).toFixed(1);console.log(chalk.green((t?` ✅ 渲染完成(GPU ${e.render_s}s,${s}MB)→ `:` ✅ rendered (GPU ${e.render_s}s, ${s}MB) → `)+v)),b(v,t)},c=!0===process.stdout.isTTY,d=Date.now();let g=15;for(;;){for(let e=g;e>0;e--){if(Date.now()-d>48e4)return c&&process.stdout.write("\r[2K"),void console.log(chalk.red(t?" ✗ 等待超时。":" ✗ timed out."));const o=await a();if("error"===o?.state)return c&&process.stdout.write("\r[2K"),void console.log(chalk.red(" ✗ "+(o.detail||"render failed")));if("done"===o?.state)return c&&process.stdout.write("\r[2K"),void await l(o);const n=Math.floor((Date.now()-d)/1e3),r=S(o?.state,n,t),s="▓".repeat(Math.max(0,g-e)).padEnd(g,"░"),i=chalk.white(` ${r}`)+chalk.gray(" ")+chalk.cyan(s)+chalk.gray(` ${e}s`);c?process.stdout.write("\r[2K"+i):e===g&&console.log(i),await new Promise(e=>setTimeout(e,1e3))}const e=await a();if("error"===e?.state)return c&&process.stdout.write("\r[2K"),void console.log(chalk.red(" ✗ "+(e.detail||"render failed")));if("done"===e?.state)return c&&process.stdout.write("\r[2K"),void await l(e);c&&process.stdout.write("\r[2K"),console.log(chalk.gray(t?" 还没好,再等 5 秒…":" not yet — 5 more seconds…")),g=5}}function A(e){console.log(chalk.gray(e?" ▸ 描述新场景渲染 · 改 <改动> 微调上一段(如 改 加一个穹顶 / 改 0.8g) · open 重看 · quit 退出":" ▸ describe a scene · refine <change> tweaks the last clip (e.g. refine 0.8g) · open · quit"))}const E={generating:{zh:["🤖 AI 正在把你这句话翻译成 Blender 代码…","✍ 摆放几何体:球体、环、柱子、地面…","💡 设定材质、灯光和世界背景色…","🎥 规划相机轨道和每一帧的关键帧…"],en:["🤖 AI is turning your sentence into Blender code…","✍ placing primitives: spheres, torus, cylinders, ground…","💡 setting materials, lights, and the world background…","🎥 planning the camera path and keyframes…"]},rendering:{zh:["🎬 GPU 正在逐帧渲染(120 帧 = 5 秒 @24fps)…","✨ EEVEE 光栅化:每帧 16 次采样抗锯齿…","⚡ 这块 RTX 4000 Ada 每秒能渲十几帧…","📦 快好了,正在把帧合成 mp4…"],en:["🎬 the GPU is rendering frame by frame (120 frames = 5s)…","✨ EEVEE rasterizing: 16 samples per frame…","⚡ this RTX 4000 Ada renders ~10 frames a second…","📦 almost there — muxing the frames into mp4…"]},repairing:{zh:["🔧 渲染报了个小错,AI 正在自动修复…","🔧 把报错回喂给 AI,请它改一行再试…","🔧 自愈中(最多试 3 次)——这就是 AI 写代码的日常…"],en:["🔧 render hit a small bug — AI is auto-fixing it…","🔧 feeding the error back to the AI for a one-line fix…","🔧 self-healing (up to 3 tries) — the reality of AI codegen…"]},queued:{zh:["⏳ 前面还有任务,排队中…"],en:["⏳ another job is ahead — queued…"]}};function S(e,o,n){const t="queued"===e?"queued":"generating"===e?"generating":e&&e.startsWith("repairing")?"repairing":"rendering",r=E[t][n?"zh":"en"];return r[Math.floor(o/3)%r.length]}let x=!1,U=!1;const I={id:"gfssm",title:{en:"GFSSM Space Scholar",zh:"GFSSM 太空学者"},what:{en:"Describe a space scene in one line; a GPU turns it into a 5-second Blender clip and opens it. Everything you type is a scene description, except the commands below.",zh:"用一句话描述一个太空场景;GPU 把它渲成 5 秒 Blender 动画并打开。除了下面这些命令,你敲的一切都是场景描述。"},steps:[{verb:"a dome on Mars",what:{en:"describe a scene and press Enter — the render takes ~20–60 s",zh:"描述一个场景回车 —— 渲染约 20–60 秒"},done:()=>null!==G},{verb:"refine add a moon",what:{en:"tweak the last clip instead of starting over (改 … works too)",zh:"在上一段基础上微调(也可以敲 改 …)"},done:()=>x},{verb:"open",what:{en:"open the last clip again",zh:"再看一遍上一段"},done:()=>U,optional:!0},{verb:"lang zh",what:{en:"switch the prompts to Chinese (lang en back)",zh:"切成中文提示(lang en 切回)"},optional:!0}],notes:[{en:'help / ? = these steps. The render box is an on-demand GPU — if it is offline you will see "GPU not ready".',zh:"help / ? = 这些步骤。渲染箱是按需 GPU —— 离线时会显示「GPU 还没准备好」。"}],leave:{verb:"quit",what:{en:"leave the demo",zh:"离开演示"}}};export async function runGfssm(e="en"){const o=e.toLowerCase().startsWith("zh");!function(){const e=p();e&&(h=e.listeners("line").slice(),e.removeAllListeners("line"),m=e.prompt.bind(e),e.prompt=i.prototype.prompt.bind(e),e.on("line",e=>{const o=w;w=null,o&&o(e)}))}();try{for(function(e){console.clear(),console.log();const o=Math.max(24,Math.min(62,(process.stdout.columns||80)-4));console.log(chalk.cyan(" "+"═".repeat(o))),console.log(chalk.bold.white(" 🚀 GFSSM SPACE SCHOLAR — 一句话渲一段太空动画")),console.log(chalk.gray(" "+(e?"你描述场景,服务端 AI 变成 Blender 代码,GPU 渲成 5 秒 mp4":"you describe a scene; a GPU turns it into 5 seconds of Blender"))),console.log(chalk.cyan(" "+"═".repeat(o))),console.log(),e?(console.log(chalk.white(" 用一句话描述一个太空场景,回车提交。例如:")),console.log(chalk.gray(" · 一个旋转的斯坦福环空间站,金属外壳,深空背景,镜头缓缓掠过")),console.log(chalk.gray(" · 火星表面三个白色穹顶基地,中间一根发光信标,相机环绕一周")),console.log(chalk.gray(" · 一颗蓝色行星和它的两颗卫星,缓慢公转"))):(console.log(chalk.white(" Describe a space scene in one line, then Enter. For example:")),console.log(chalk.gray(" · a rotating Stanford-torus station, metal hull, deep space, camera drifts past")),console.log(chalk.gray(" · three white domes on Mars with a glowing beacon, camera orbits once")),console.log(chalk.gray(" · a blue planet and its two moons orbiting slowly"))),console.log()}(o),A(o),a(I);;){const e=(await y(chalk.bold.cyan("icoa gfssm> "))).trim();if(!e)continue;const n=e.toLowerCase();if(["quit","q","exit","menu","back"].includes(n))return void console.log(chalk.gray(o?"\n 已退出。\n":"\n Left the demo.\n"));if(c(e)||l(e)){g();continue}if("open"===n){v?(U=!0,b(v,o)):console.log(chalk.yellow(o?" 还没渲染过。先描述一个场景。":" Nothing rendered yet — describe a scene first."));continue}if(["zh","en","lang zh","lang en"].includes(n))return runGfssm(n.endsWith("zh")?"zh":"en");const t=e.match(/^(改|refine|more|微调)\s+(.+)/i);if(t){if(!G){console.log(chalk.yellow(o?" 还没有可微调的上一段。先描述一个场景。":" Nothing to refine yet — describe a scene first."));continue}console.log(chalk.gray(o?" 在上一段基础上修改…":" refining the last clip…")),x=!0,await z(t[2],o,G)}else await z(e,o,null);console.log(),A(o)}}finally{d("gfssm"),function(){const e=p();if(e){e.removeAllListeners("line"),m&&(e.prompt=m);for(const o of h)e.on("line",o);h=[],m=null,w=null}}()}}export function registerGfssmCommand(e){e.command("gfssm [lang]",{hidden:!0}).description("SPACE SCHOLAR — hidden natural-language render demo").action(async e=>{try{await runGfssm(e||"en")}catch(e){const o=e instanceof Error?e.message:String(e);if("__REPL_NO_EXIT__"===o)throw e;console.log(chalk.yellow("\n gfssm ended: "+o))}})}
|
|
@@ -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{clearCommitteeSession as r,readCommitteeSession as l,TIER_LABEL as c,writeCommitteeSession as d}from"../lib/gputask-session.js";import{getMainRl as u}from"../lib/main-rl.js";const p=(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"");let g=[],y=null,h=null,f=[];function m(o){return new Promise(t=>{const n=u();if(n){const e=f.shift();return void 0!==e?(process.stdout.write(`${o}${e}\n`),void t(e)):(h=t,n.setPrompt(o),void n.prompt())}const s=e({input:process.stdin,output:process.stdout});s.question(o,e=>{s.close(),t(e)})})}let k="en";const w={banner:{en:"[🧪 Committee GPU sandbox — GCP T4 · IOAI standard environment]",zh:"[🧪 命题组 GPU 沙箱 — GCP T4 · IOAI 标准环境]"},langTip:{en:"Tip: type lang zh anytime to switch to 中文 (default English).",zh:"提示:随时输入 lang en 切回英文。"},tokenAsk:{en:"Enter your committee access token: ",zh:"请输入命题组访问 token:"},tokenBad:{en:"Token not recognised — check for typos and try again.",zh:"token 无效 — 请检查拼写后重试。"},tokenDevice:{en:"This token is bound to another computer. One token = one device — use your own token on this machine.",zh:"这枚 token 已绑定在另一台电脑上。一枚 token 只绑一台设备 — 请在本机使用你自己的 token。"},tokenGiveUp:{en:"Three failed attempts — ask your coordinator to verify your token.",zh:"连续三次失败 — 请联系协调人核对你的 token。"},tierAsk:{en:"Seat? [1] T4 capsule 3.5 GiB (default, fits tasks ≤ 3 GiB) [2] T4 whole card 16 GB [3] CPU only: ",zh:"席位? [1] T4 胶囊 3.5 GiB(默认,题目 ≤ 3 GiB 用这个) [2] T4 整卡 16 GB [3] 只要 CPU:"},tierBad:{en:"Please type 1, 2 or 3 (Enter = 1).",zh:"请输入 1、2 或 3(回车 = 1)。"},modeAsk:{en:"Spot box (cheapest; the cloud may reclaim it — we rebuild in 1–2 min, files kept). Enter = Spot, type ondemand for a guaranteed box: ",zh:"Spot 箱(最便宜;云可能收回 — 我们 1–2 分钟内重建,文件不丢)。回车 = Spot,输入 ondemand 要一台不会被收回的:"},seatsBusy:{en:"All committee seats are in use right now — try again in a little while.",zh:"席位当前全部占用 — 请稍后再试。"},dailyCap:{en:"Today's spend is over the US$5/day cap — on-demand is off; a Spot seat is still fine.",zh:"今天花费已超每日 5 美元上限 — 按需关闭;Spot 席位仍可用。"},capWarn:{en:"Note: today's spend is over the US$5/day cap — Spot only from here.",zh:"注意:今天花费已超每日 5 美元上限 — 之后只给 Spot。"},ctlDown:{en:"The box builder is not reachable right now — tell the coordinator; try again in a few minutes.",zh:"建箱机暂时联系不上 — 请告知协调人;几分钟后再试。"},already:{en:"You already have an active seat — reconnecting to it.",zh:"你已有一个进行中的席位 — 正在接回。"},deploying:{en:"⚡ Starting your box — about 1–2 minutes (a fresh T4 if none has a free seat)…",zh:"⚡ 正在开机 — 约 1–2 分钟(没有空位时会新起一台 T4)…"},stCreating:{en:"creating the box…",zh:"正在建箱…"},stProvisioning:{en:"box is up — adding your user and fence…",zh:"机器已启动 — 正在建你的用户与围栏…"},stPreempted:{en:"⚠ the cloud reclaimed the GPU — rebuilding on another box (1–2 min). Files are kept; variables need a re-run.",zh:"⚠ 云收回了这台 GPU — 正在换一台重建(1–2 分钟)。文件都在,变量要重跑。"},failed:{en:"Could not start a seat: ",zh:"开机失败:"},readyTitle:{en:"✓ Your seat is ready",zh:"✓ 席位已就绪"},how1:{en:"How to use it (the notebook runs its cells on the box):",zh:"怎么用(notebook 的格子在箱上跑):"},how2:{en:"open your notebook",zh:"打开你的 notebook"},how3:{en:"cells now run on the box · same-folder files sync automatically",zh:"格子改在箱上跑 · 同目录文件自动同步"},how4:{en:"send one file to the box (data, weights)",zh:"把一个文件送上箱(数据、权重)"},advanced:{en:"Advanced — your own user, no sudo, others cannot see your files:",zh:"进阶 — 你自己的用户,无 sudo,别人看不见你的文件:"},clock:{en:"⏱ Ends after 40 min idle · files in /home/{U} are kept and restored next time",zh:"⏱ 闲置 40 分钟自动结束 · /home/{U} 的文件会保留,下次恢复"},spend:{en:"today's spend {A} of {B}",zh:"今日花费 {A} / {B}"},footer:{en:"Commands: status seat + GPU usage · stop end now · lang zh · quit leave (seat stays until idle)",zh:"命令:status 席位与 GPU 占用 · stop 立即结束 · lang en · quit 退出(席位到闲置为止)"},stopAsk:{en:"End the seat now? Your files are synced first and restored next time. (y/n): ",zh:"确认立即结束?文件会先同步保存,下次恢复。(y/n):"},stopping:{en:"Stopping — files syncing, seat released within a minute.",zh:"正在结束 — 文件同步中,一分钟内释放席位。"},quitNote:{en:"Leaving this screen — the seat KEEPS RUNNING until 40 min idle. Type gpufortask to come back.",zh:"已退出此界面 — 席位会一直保留到闲置 40 分钟。再次输入 gpufortask 可接回。"},ended:{en:"Seat ended",zh:"席位已结束"},netErr:{en:"Cannot reach the broker right now — check your network and try again.",zh:"暂时连不上服务器 — 请检查网络后重试。"},idle:{en:"idle",zh:"闲置"},busy:{en:"busy",zh:"忙"},weekly:{en:"Heads-up: the committee has used {H}h of GPU since Monday — no limit, just so you know. 🙂",zh:"小提示:命题组本周一以来累计已用 {H} 小时 GPU — 没有限制,纯提示 🙂"}},$=e=>w[e]?.[k]??e;async function b(e,o){try{const t=await fetch(`${p}/api/icoa/gputask/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(25e3)}),n=await t.json();return n.data??n}catch{return null}}function z(e,o){if(!(o.sid&&o.tier&&o.host&&o.user&&o.python&&o.out_dir&&o.key_pem))return null;const i={sid:o.sid,token:e,tier:o.tier,host:o.host,port:o.port??22,user:o.user,python:o.python,outDir:o.out_dir,keyPem:o.key_pem,seenAt:Math.floor(Date.now()/1e3)};try{d(i),t(a(s(),".icoa","gputask"),{recursive:!0}),n(a(s(),".icoa","gputask","key"),o.key_pem,{mode:384})}catch{return null}return i}function v(e){return`$${(e??0).toFixed(2)}`}function _(e){const o=e.user??"?";console.log(),console.log(chalk.bold.green(` ${$("readyTitle")}`)+chalk.gray(` ${c[e.tier??"t4"]} · ${e.zone??""} · ${"ondemand"===e.mode?"on-demand":"Spot"}`)),console.log(),console.log(chalk.white(` ${$("how1")}`)),console.log(chalk.bold.cyan(" icoa> ipynb ~/Desktop/task.ipynb")+chalk.gray(` ${$("how2")}`)),console.log(chalk.bold.cyan(" icoa ipynb> gpu on")+chalk.gray(` ${$("how3")}`)),console.log(chalk.bold.cyan(" icoa ipynb> upload data.csv")+chalk.gray(` ${$("how4")}`)),console.log(),console.log(chalk.gray(` ${$("advanced")}`)),console.log(chalk.gray(` ssh -i ~/.icoa/gputask/key ${o}@${e.host??"?"}`)),console.log(),console.log(chalk.yellow(` ${$("clock").replace("{U}",o)}`)),console.log(chalk.gray(` ${$("spend").replace("{A}",v(e.today_usd)).replace("{B}",v(e.daily_cap_usd??5))}`)+chalk.gray(` · ${e.rate??"?"}/h`)),e.weekly_soft_over&&console.log(chalk.gray(` ${$("weekly").replace("{H}",String(e.weekly_hours??0))}`)),console.log(),console.log(chalk.gray(` ${$("footer")}`))}function P(e){const o=e.idle_min??0,t=e.idle_limit_min??40;console.log(chalk.bold.cyan(" seat ")+chalk.white(`${e.state}`)+chalk.gray(` · ${e.tier} · ${e.mode} · ${e.zone??""} · ${Math.round(e.minutes??0)} min`));const n=e.busy;console.log(chalk.gray(" you: ")+(n?.busy?chalk.green(`${$("busy")} (${n.why})`):chalk.yellow(`${$("idle")} ${o}/${t} min`))+(n?.home_kb?chalk.gray(` · home ${Math.round(n.home_kb/1024)} MB`):"")),e.gpu&&"number"==typeof e.gpu.util&&console.log(chalk.gray(` card: GPU ${e.gpu.util}% · VRAM ${e.gpu.mem_used_mb}/${e.gpu.mem_total_mb} MB (whole card, all seats)`)),e.preempt_count&&console.log(chalk.gray(` reclaimed ${e.preempt_count}× today${e.note?` · ${e.note}`:""}`)),console.log(chalk.gray(` ${$("spend").replace("{A}",v(e.today_usd)).replace("{B}",v(e.daily_cap_usd??5))}`))}export function registerGpuForTaskCommand(e){e.command("gpufortask",{hidden:!0}).description("Committee GPU sandbox — GCP T4 capsule, IOAI standard environment (hidden)").action(async()=>{try{await async function(){k="en",function(){const e=u();e&&(g=e.listeners("line").slice(),e.removeAllListeners("line"),y=e.prompt.bind(e),e.prompt=o.prototype.prompt.bind(e),e.on("line",e=>{const o=h;h=null,o?o(e):f.push(e)}))}();try{console.log(),console.log(chalk.cyan.bold(` ${$("banner")}`)),console.log(chalk.gray(` ${$("langTip")}`)),console.log();const e=i(),o=l();let n="";for(let s=0;s<3;){const a=(await m(chalk.cyan(` ${$("tokenAsk")}`)+(o?chalk.gray(`[${o.token}] `):""))).trim(),i=a.toLowerCase();if("lang zh"===i){k="zh";continue}if("lang en"===i){k="en";continue}if("quit"===i||"back"===i)return;const l=""===a&&o?o.token:a.toUpperCase().replace(/\s+/g,"");if(!l)continue;const c=await b("status",{token:l,fp:e});if(null===c)return void console.log(chalk.yellow(` ${$("netErr")}`));if("token_device_mismatch"!==c.error){if(!c.error){if(n=l,"none"!==c.state)return console.log(chalk.gray(` ${$("already")}`)),void await t(n,e,c);o&&r(),c.last_ended&&console.log(chalk.gray(` (your previous seat ended: ${c.last_ended} — files were kept)`));break}console.log(chalk.yellow(` ${$("tokenBad")}`)),s++}else console.log(chalk.yellow(` ${$("tokenDevice")}`)),s++}if(!n)return void console.log(chalk.yellow(` ${$("tokenGiveUp")}`));let s="";for(;!s;){const e=(await m(chalk.cyan(` ${$("tierAsk")}`))).trim().toLowerCase();if("lang zh"!==e)if("lang en"!==e){if("quit"===e||"back"===e)return;""===e||"1"===e||e.includes("capsule")||e.includes("胶囊")?s="t4":"2"===e||e.includes("whole")||e.includes("full")||e.includes("整卡")?s="t4full":"3"===e||e.includes("cpu")?s="cpu":console.log(chalk.yellow(` ${$("tierBad")}`))}else k="en";else k="zh"}let a="spot";for(;;){const e=(await m(chalk.cyan(` ${$("modeAsk")}`))).trim().toLowerCase();if("lang zh"!==e)if("lang en"!==e){if("quit"===e||"back"===e)return;if(""===e||"spot"===e||"s"===e)break;if(e.startsWith("on")||"od"===e||"demand"===e||"按需"===e){a="ondemand";break}}else k="en";else k="zh"}const c=await b("start",{token:n,fp:e,tier:s,mode:a});if(null===c)return void console.log(chalk.yellow(` ${$("netErr")}`));if("all_seats_busy"===c.error)return void console.log(chalk.yellow(` ${$("seatsBusy")}`));if("daily_cap"===c.error)return void console.log(chalk.yellow(` ${$("dailyCap")}`));if("ctl_unavailable"===c.error)return void console.log(chalk.yellow(` ${$("ctlDown")}`)+chalk.gray(c.detail?` (${c.detail})`:""));if("session_already_active"===c.error){const o=await b("status",{token:n,fp:e});return void(o&&await t(n,e,o))}if(c.error)return void console.log(chalk.yellow(` ${$("failed")}${c.error}`));c.cap_warning&&console.log(chalk.yellow(` ${$("capWarn")}`)),console.log(chalk.gray(` ${$("deploying")}`)),await t(n,e,c)}finally{!function(){const e=u();if(e){e.removeAllListeners("line"),y&&(e.prompt=y);for(const o of g)e.on("line",o);g=[],y=null,h=null,f=[]}}()}async function e(e,o,t){let n=t,s="",a=0;const i=Date.now();for(;n&&"ready"!==n.state;){if("failed"===n.state||"ended"===n.state||"none"===n.state||"stopping"===n.state)return console.log(chalk.red(` ${$("failed")}${n.end_reason??n.state}`)),r(),null;const t="creating"===n.state?$("stCreating"):"preempted"===n.state?$("stPreempted"):$("stProvisioning");if(t!==s){const e=Math.round((Date.now()-i)/1e3);console.log(chalk.gray(` [${e}s] `)+("preempted"===n.state?chalk.yellow(t):chalk.gray(t))),s=t}if(Date.now()-i>72e4)return console.log(chalk.yellow(` still starting after ${Math.round(12)} min — type gpufortask again later; the seat is held.`)),null;await new Promise(e=>setTimeout(e,5e3));const l=await b("status",{token:e,fp:o});if(null===l){if(a++,a<=5){console.log(chalk.gray(` (broker did not answer — retrying ${a}/5)`));continue}n=null;break}a=0,n=l}return n||(console.log(chalk.yellow(` ${$("netErr")}`)),console.log(chalk.gray(" The seat is still being built server-side — type gpufortask again in a minute to pick it up.")),null)}async function t(o,t,n){const s=await e(o,t,n);if(s)for(z(o,s)||console.log(chalk.yellow(" could not save the session file under ~/.icoa/gputask — gpu on will not find this seat.")),_(s);;){const n=(await m(chalk.cyan("icoa gpufortask> "))).trim().toLowerCase();if(""!==n)if("lang zh"!==n&&"lang en"!==n){if("quit"===n||"back"===n||"exit"===n||"menu"===n)return void console.log(chalk.gray(` ${$("quitNote")}`));if("status"===n||"s"===n||"time"===n||"stats"===n||"top"===n){const n=await b("status",{token:o,fp:t});if(n)if("ready"===n.state)n.host&&n.key_pem&&z(o,n),P(n);else{if("preempted"!==n.state&&"provisioning"!==n.state&&"creating"!==n.state)return console.log(chalk.gray(` ${$("ended")} (${n.end_reason??n.state})`)),void r();{console.log(chalk.yellow(` ${$("stPreempted")}`));const s=await e(o,t,n);if(!s)return;z(o,s),_(s)}}else console.log(chalk.yellow(` ${$("netErr")}`));continue}if("stop"===n||"end"===n||"destroy"===n||"release"===n){const e=(await m(chalk.yellow(` ${$("stopAsk")}`))).trim().toLowerCase();if("y"===e||"yes"===e)return await b("stop",{token:o,fp:t}),r(),void console.log(chalk.green(` ${$("stopping")}`));continue}console.log(chalk.gray(` ${$("footer")}`))}else k=n.endsWith("zh")?"zh":"en",console.log(chalk.gray(` ${$("footer")}`))}}}()}catch(e){const o=e instanceof Error?e.message:String(e);if("__REPL_NO_EXIT__"===o)throw e;console.log(chalk.yellow("\n gpufortask ended: "+o))}})}
|
|
1
|
+
import{createInterface as e,Interface as o}from"node:readline";import{mkdirSync as t,writeFileSync as n}from"node:fs";import{homedir as s}from"node:os";import{join as a}from"node:path";import chalk from"chalk";import{getDeviceFingerprint as i}from"../lib/access.js";import{enterPanel as r,leavePanel as l,printGuide as c,printHelp as d}from"../lib/guide-panel.js";import{clearCommitteeSession as u,readCommitteeSession as p,TIER_LABEL as g,writeCommitteeSession as y}from"../lib/gputask-session.js";import{getMainRl as h}from"../lib/main-rl.js";const f=(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"");let m=[],k=null,w=null,b=[];function $(o){return new Promise(t=>{const n=h();if(n){const e=b.shift();return void 0!==e?(process.stdout.write(`${o}${e}\n`),void t(e)):(w=t,n.setPrompt(o),void n.prompt())}const s=e({input:process.stdin,output:process.stdout});s.question(o,e=>{s.close(),t(e)})})}let z="en";const v={banner:{en:"[🧪 Committee GPU sandbox — GCP T4 · IOAI standard environment]",zh:"[🧪 命题组 GPU 沙箱 — GCP T4 · IOAI 标准环境]"},langTip:{en:"Tip: type lang zh anytime to switch to 中文 (default English).",zh:"提示:随时输入 lang en 切回英文。"},tokenAsk:{en:"Enter your committee access token: ",zh:"请输入命题组访问 token:"},tokenBad:{en:"Token not recognised — check for typos and try again.",zh:"token 无效 — 请检查拼写后重试。"},tokenDevice:{en:"This token is bound to another computer. One token = one device — use your own token on this machine.",zh:"这枚 token 已绑定在另一台电脑上。一枚 token 只绑一台设备 — 请在本机使用你自己的 token。"},tokenGiveUp:{en:"Three failed attempts — ask your coordinator to verify your token.",zh:"连续三次失败 — 请联系协调人核对你的 token。"},tierAsk:{en:"Seat? [1] T4 capsule 3.5 GiB (default, fits tasks ≤ 3 GiB) [2] T4 whole card 16 GB [3] CPU only: ",zh:"席位? [1] T4 胶囊 3.5 GiB(默认,题目 ≤ 3 GiB 用这个) [2] T4 整卡 16 GB [3] 只要 CPU:"},tierBad:{en:"Please type 1, 2 or 3 (Enter = 1).",zh:"请输入 1、2 或 3(回车 = 1)。"},modeAsk:{en:"Spot box (cheapest; the cloud may reclaim it — we rebuild in 1–2 min, files kept). Enter = Spot, type ondemand for a guaranteed box: ",zh:"Spot 箱(最便宜;云可能收回 — 我们 1–2 分钟内重建,文件不丢)。回车 = Spot,输入 ondemand 要一台不会被收回的:"},seatsBusy:{en:"All committee seats are in use right now — try again in a little while.",zh:"席位当前全部占用 — 请稍后再试。"},dailyCap:{en:"Today's spend is over the US$5/day cap — on-demand is off; a Spot seat is still fine.",zh:"今天花费已超每日 5 美元上限 — 按需关闭;Spot 席位仍可用。"},capWarn:{en:"Note: today's spend is over the US$5/day cap — Spot only from here.",zh:"注意:今天花费已超每日 5 美元上限 — 之后只给 Spot。"},ctlDown:{en:"The box builder is not reachable right now — tell the coordinator; try again in a few minutes.",zh:"建箱机暂时联系不上 — 请告知协调人;几分钟后再试。"},already:{en:"You already have an active seat — reconnecting to it.",zh:"你已有一个进行中的席位 — 正在接回。"},deploying:{en:"⚡ Starting your box — about 1–2 minutes (a fresh T4 if none has a free seat)…",zh:"⚡ 正在开机 — 约 1–2 分钟(没有空位时会新起一台 T4)…"},stCreating:{en:"creating the box…",zh:"正在建箱…"},stProvisioning:{en:"box is up — adding your user and fence…",zh:"机器已启动 — 正在建你的用户与围栏…"},stPreempted:{en:"⚠ the cloud reclaimed the GPU — rebuilding on another box (1–2 min). Files are kept; variables need a re-run.",zh:"⚠ 云收回了这台 GPU — 正在换一台重建(1–2 分钟)。文件都在,变量要重跑。"},failed:{en:"Could not start a seat: ",zh:"开机失败:"},readyTitle:{en:"✓ Your seat is ready",zh:"✓ 席位已就绪"},how1:{en:"How to use it (the notebook runs its cells on the box):",zh:"怎么用(notebook 的格子在箱上跑):"},how2:{en:"open your notebook",zh:"打开你的 notebook"},how3:{en:"cells now run on the box · same-folder files sync automatically",zh:"格子改在箱上跑 · 同目录文件自动同步"},how4:{en:"send one file to the box (data, weights)",zh:"把一个文件送上箱(数据、权重)"},advanced:{en:"Advanced — your own user, no sudo, others cannot see your files:",zh:"进阶 — 你自己的用户,无 sudo,别人看不见你的文件:"},clock:{en:"⏱ Ends after 40 min idle · files in /home/{U} are kept and restored next time",zh:"⏱ 闲置 40 分钟自动结束 · /home/{U} 的文件会保留,下次恢复"},spend:{en:"today's spend {A} of {B}",zh:"今日花费 {A} / {B}"},footer:{en:"Commands: status seat + GPU usage · stop end now · lang zh · quit leave (seat stays until idle)",zh:"命令:status 席位与 GPU 占用 · stop 立即结束 · lang en · quit 退出(席位到闲置为止)"},stopAsk:{en:"End the seat now? Your files are synced first and restored next time. (y/n): ",zh:"确认立即结束?文件会先同步保存,下次恢复。(y/n):"},stopping:{en:"Stopping — files syncing, seat released within a minute.",zh:"正在结束 — 文件同步中,一分钟内释放席位。"},quitNote:{en:"Leaving this screen — the seat KEEPS RUNNING until 40 min idle. Type gpufortask to come back.",zh:"已退出此界面 — 席位会一直保留到闲置 40 分钟。再次输入 gpufortask 可接回。"},ended:{en:"Seat ended",zh:"席位已结束"},netErr:{en:"Cannot reach the broker right now — check your network and try again.",zh:"暂时连不上服务器 — 请检查网络后重试。"},idle:{en:"idle",zh:"闲置"},busy:{en:"busy",zh:"忙"},weekly:{en:"Heads-up: the committee has used {H}h of GPU since Monday — no limit, just so you know. 🙂",zh:"小提示:命题组本周一以来累计已用 {H} 小时 GPU — 没有限制,纯提示 🙂"}},_=e=>v[e]?.[z]??e;async function P(e,o){try{const t=await fetch(`${f}/api/icoa/gputask/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:AbortSignal.timeout(25e3)}),n=await t.json();return n.data??n}catch{return null}}function G(e,o){if(!(o.sid&&o.tier&&o.host&&o.user&&o.python&&o.out_dir&&o.key_pem))return null;const i={sid:o.sid,token:e,tier:o.tier,host:o.host,port:o.port??22,user:o.user,python:o.python,outDir:o.out_dir,keyPem:o.key_pem,seenAt:Math.floor(Date.now()/1e3)};try{y(i),t(a(s(),".icoa","gputask"),{recursive:!0}),n(a(s(),".icoa","gputask","key"),o.key_pem,{mode:384})}catch{return null}return i}function T(e){return`$${(e??0).toFixed(2)}`}function U(e){const o=e.user??"?";console.log(),console.log(chalk.bold.green(` ${_("readyTitle")}`)+chalk.gray(` ${g[e.tier??"t4"]} · ${e.zone??""} · ${"ondemand"===e.mode?"on-demand":"Spot"}`)),console.log(),console.log(chalk.white(` ${_("how1")}`)),console.log(chalk.bold.cyan(" icoa> ipynb ~/Desktop/task.ipynb")+chalk.gray(` ${_("how2")}`)),console.log(chalk.bold.cyan(" icoa ipynb> gpu on")+chalk.gray(` ${_("how3")}`)),console.log(chalk.bold.cyan(" icoa ipynb> upload data.csv")+chalk.gray(` ${_("how4")}`)),console.log(),console.log(chalk.gray(` ${_("advanced")}`)),console.log(chalk.gray(` ssh -i ~/.icoa/gputask/key ${o}@${e.host??"?"}`)),console.log(),console.log(chalk.yellow(` ${_("clock").replace("{U}",o)}`)),console.log(chalk.gray(` ${_("spend").replace("{A}",T(e.today_usd)).replace("{B}",T(e.daily_cap_usd??5))}`)+chalk.gray(` · ${e.rate??"?"}/h`)),e.weekly_soft_over&&console.log(chalk.gray(` ${_("weekly").replace("{H}",String(e.weekly_hours??0))}`)),console.log(),console.log(chalk.gray(` ${_("footer")}`))}function C(e){const o=e.idle_min??0,t=e.idle_limit_min??40;console.log(chalk.bold.cyan(" seat ")+chalk.white(`${e.state}`)+chalk.gray(` · ${e.tier} · ${e.mode} · ${e.zone??""} · ${Math.round(e.minutes??0)} min`));const n=e.busy;console.log(chalk.gray(" you: ")+(n?.busy?chalk.green(`${_("busy")} (${n.why})`):chalk.yellow(`${_("idle")} ${o}/${t} min`))+(n?.home_kb?chalk.gray(` · home ${Math.round(n.home_kb/1024)} MB`):"")),e.gpu&&"number"==typeof e.gpu.util&&console.log(chalk.gray(` card: GPU ${e.gpu.util}% · VRAM ${e.gpu.mem_used_mb}/${e.gpu.mem_total_mb} MB (whole card, all seats)`)),e.preempt_count&&console.log(chalk.gray(` reclaimed ${e.preempt_count}× today${e.note?` · ${e.note}`:""}`)),console.log(chalk.gray(` ${_("spend").replace("{A}",T(e.today_usd)).replace("{B}",T(e.daily_cap_usd??5))}`))}let A=!1;const S={id:"gpufortask",title:{en:"Committee GPU seat",zh:"命题组 GPU 席位"},what:{en:"Your seat on a shared GCP GPU box is ready. Work happens in a notebook: open one at icoa> with ipynb, type gpu on there, and its cells run on the box. This screen only watches the seat.",zh:"你在共享 GCP GPU 箱上的席位已就绪。活在 notebook 里干:在 icoa> 用 ipynb 打开一本,在里面敲 gpu on,格子就在箱上跑。这个界面只看席位。"},steps:[{verb:"status",what:{en:"seat state, idle clock, GPU usage, spend",zh:"席位状态、闲置计时、GPU 占用、花费"},done:()=>A},{verb:"stop",what:{en:"end the seat now (asks y/n; files are synced first)",zh:"立即结束席位(先问 y/n;文件先同步)"}},{verb:"lang zh",what:{en:"switch this screen to Chinese (lang en = back)",zh:"切英文:lang en"},optional:!0}],notes:[{en:"quit only leaves this screen — the seat keeps running until 40 min idle; gpufortask brings you back.",zh:"quit 只是离开这个界面 —— 席位会一直保留到闲置 40 分钟;再敲 gpufortask 接回。"}],leave:{verb:"quit",what:{en:"leave this screen (seat stays)",zh:"离开界面(席位保留)"}},guide:()=>console.log(chalk.gray(` ${_("footer")}`))};export function registerGpuForTaskCommand(e){e.command("gpufortask",{hidden:!0}).description("Committee GPU sandbox — GCP T4 capsule, IOAI standard environment (hidden)").action(async()=>{try{await async function(){z="en",A=!1,function(){const e=h();e&&(m=e.listeners("line").slice(),e.removeAllListeners("line"),k=e.prompt.bind(e),e.prompt=o.prototype.prompt.bind(e),e.on("line",e=>{const o=w;w=null,o?o(e):b.push(e)}))}();try{console.log(),console.log(chalk.cyan.bold(` ${_("banner")}`)),console.log(chalk.gray(` ${_("langTip")}`)),console.log();const e=i(),o=p();let n="";for(let s=0;s<3;){const a=(await $(chalk.cyan(` ${_("tokenAsk")}`)+(o?chalk.gray(`[${o.token}] `):""))).trim(),i=a.toLowerCase();if("lang zh"===i){z="zh";continue}if("lang en"===i){z="en";continue}if("quit"===i||"back"===i)return;const r=""===a&&o?o.token:a.toUpperCase().replace(/\s+/g,"");if(!r)continue;const l=await P("status",{token:r,fp:e});if(null===l)return void console.log(chalk.yellow(` ${_("netErr")}`));if("token_device_mismatch"!==l.error){if(!l.error){if(n=r,"none"!==l.state)return console.log(chalk.gray(` ${_("already")}`)),void await t(n,e,l);o&&u(),l.last_ended&&console.log(chalk.gray(` (your previous seat ended: ${l.last_ended} — files were kept)`));break}console.log(chalk.yellow(` ${_("tokenBad")}`)),s++}else console.log(chalk.yellow(` ${_("tokenDevice")}`)),s++}if(!n)return void console.log(chalk.yellow(` ${_("tokenGiveUp")}`));let s="";for(;!s;){const e=(await $(chalk.cyan(` ${_("tierAsk")}`))).trim().toLowerCase();if("lang zh"!==e)if("lang en"!==e){if("quit"===e||"back"===e)return;""===e||"1"===e||e.includes("capsule")||e.includes("胶囊")?s="t4":"2"===e||e.includes("whole")||e.includes("full")||e.includes("整卡")?s="t4full":"3"===e||e.includes("cpu")?s="cpu":console.log(chalk.yellow(` ${_("tierBad")}`))}else z="en";else z="zh"}let a="spot";for(;;){const e=(await $(chalk.cyan(` ${_("modeAsk")}`))).trim().toLowerCase();if("lang zh"!==e)if("lang en"!==e){if("quit"===e||"back"===e)return;if(""===e||"spot"===e||"s"===e)break;if(e.startsWith("on")||"od"===e||"demand"===e||"按需"===e){a="ondemand";break}}else z="en";else z="zh"}const r=await P("start",{token:n,fp:e,tier:s,mode:a});if(null===r)return void console.log(chalk.yellow(` ${_("netErr")}`));if("all_seats_busy"===r.error)return void console.log(chalk.yellow(` ${_("seatsBusy")}`));if("daily_cap"===r.error)return void console.log(chalk.yellow(` ${_("dailyCap")}`));if("ctl_unavailable"===r.error)return void console.log(chalk.yellow(` ${_("ctlDown")}`)+chalk.gray(r.detail?` (${r.detail})`:""));if("session_already_active"===r.error){const o=await P("status",{token:n,fp:e});return void(o&&await t(n,e,o))}if(r.error)return void console.log(chalk.yellow(` ${_("failed")}${r.error}`));r.cap_warning&&console.log(chalk.yellow(` ${_("capWarn")}`)),console.log(chalk.gray(` ${_("deploying")}`)),await t(n,e,r)}finally{l(S.id),function(){const e=h();if(e){e.removeAllListeners("line"),k&&(e.prompt=k);for(const o of m)e.on("line",o);m=[],k=null,w=null,b=[]}}()}async function e(e,o,t){let n=t,s="",a=0;const i=Date.now();for(;n&&"ready"!==n.state;){if("failed"===n.state||"ended"===n.state||"none"===n.state||"stopping"===n.state)return console.log(chalk.red(` ${_("failed")}${n.end_reason??n.state}`)),u(),null;const t="creating"===n.state?_("stCreating"):"preempted"===n.state?_("stPreempted"):_("stProvisioning");if(t!==s){const e=Math.round((Date.now()-i)/1e3);console.log(chalk.gray(` [${e}s] `)+("preempted"===n.state?chalk.yellow(t):chalk.gray(t))),s=t}if(Date.now()-i>72e4)return console.log(chalk.yellow(` still starting after ${Math.round(12)} min — type gpufortask again later; the seat is held.`)),null;await new Promise(e=>setTimeout(e,5e3));const r=await P("status",{token:e,fp:o});if(null===r){if(a++,a<=5){console.log(chalk.gray(` (broker did not answer — retrying ${a}/5)`));continue}n=null;break}a=0,n=r}return n||(console.log(chalk.yellow(` ${_("netErr")}`)),console.log(chalk.gray(" The seat is still being built server-side — type gpufortask again in a minute to pick it up.")),null)}async function t(o,t,n){const s=await e(o,t,n);if(s)for(G(o,s)||console.log(chalk.yellow(" could not save the session file under ~/.icoa/gputask — gpu on will not find this seat.")),U(s),r(S);;){const n=(await $(chalk.cyan("icoa gpufortask> "))).trim().toLowerCase();if(""!==n)if("lang zh"!==n&&"lang en"!==n){if("quit"===n||"back"===n||"exit"===n||"menu"===n)return void console.log(chalk.gray(` ${_("quitNote")}`));if("status"===n||"s"===n||"time"===n||"stats"===n||"top"===n){const n=await P("status",{token:o,fp:t});if(n)if("ready"===n.state)n.host&&n.key_pem&&G(o,n),A=!0,C(n);else{if("preempted"!==n.state&&"provisioning"!==n.state&&"creating"!==n.state)return console.log(chalk.gray(` ${_("ended")} (${n.end_reason??n.state})`)),void u();{console.log(chalk.yellow(` ${_("stPreempted")}`));const s=await e(o,t,n);if(!s)return;G(o,s),U(s)}}else console.log(chalk.yellow(` ${_("netErr")}`));continue}if("stop"===n||"end"===n||"destroy"===n||"release"===n){const e=(await $(chalk.yellow(` ${_("stopAsk")}`))).trim().toLowerCase();if("y"===e||"yes"===e)return await P("stop",{token:o,fp:t}),u(),void console.log(chalk.green(` ${_("stopping")}`));continue}"help"!==n&&"/help"!==n&&"?"!==n?"help all"!==n&&"guide"!==n?console.log(chalk.gray(` ${_("footer")}`)):c():d()}else z=n.endsWith("zh")?"zh":"en",console.log(chalk.gray(` ${_("footer")}`))}}}()}catch(e){const o=e instanceof Error?e.message:String(e);if("__REPL_NO_EXIT__"===o)throw e;console.log(chalk.yellow("\n gpufortask ended: "+o))}})}
|
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 r}from"node:fs";import{homedir as a}from"node:os";import{join as s}from"node:path";import{Interface as i,createInterface as c}from"node:readline";import chalk from"chalk";import{editTextInEditor as l}from"../lib/editor-spawn.js";import{buildSshArgs as g,leaseConnectProblems as u,parseLeaseResponse as y,queueLine as d,windowLine as m}from"../lib/gpu.js";import{logCommand as f}from"../lib/logger.js";import{getMainRl as p}from"../lib/main-rl.js";import{openFile as h}from"../lib/open-file.js";import{printError as w}from"../lib/ui.js";const b=[{id:"pick-cube",env:"PrimeLite-PickCube-v0",blurb:"Robot arm picks a cube off the table (imitation-learning demo)"}],v=/^[a-z0-9-]{1,32}$/,k=/^MP4:(\/[A-Za-z0-9._/-]+\.mp4)\s*$/m,$=/^HDF5:(\/[A-Za-z0-9._/-]+\.hdf5)\s*$/m,x=/^CKPT:(\/[A-Za-z0-9._/-]+\.pth)\s*$/m,P=/^METRICS:(\{.*\})\s*$/m,_=/^algo(?:_used)?:\s*([a-z_]+)\s*$/im,U="/opt/ioailab-mj/work",A=`${U}/05_custom_agent.py`;function I(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}function G(){return s(a(),".icoa","gpu-key")}function S(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(G(),"utf-8").trim()||null}catch{return null}}function O(e){t(s(a(),".icoa"),{recursive:!0}),r(G(),`${e.trim()}\n`,{mode:384})}async function C(e,o,t){try{const n=await fetch(`${I()}/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 T(e){try{const o=await fetch(`${I()}/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 L=null,E=null,R=null,j=!1,q=!1,N=!1,Y=!1,M=!1,K=null;function V(){return s(a(),"icoa-ioailab","05_custom_agent.py")}function z(o,t,n,r){return new Promise(a=>{const s="local"===o.transport?{command:"/bin/sh",args:["-c",n]}:{command:"ssh",args:g(o,t,n)},i=e(s.command,s.args,{stdio:["ignore","pipe","pipe"]});let c="",l="";const u=setTimeout(()=>i.kill("SIGKILL"),r);i.stdout.on("data",e=>{c+=e.toString(),l+=e.toString();let o=l.indexOf("\n");for(;o>=0;){const e=l.slice(0,o).trimEnd();l=l.slice(o+1),e.length>0&&console.log(chalk.white(` ${e}`)),o=l.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(u),a({code:e??1,out:c})}),i.on("error",()=>{clearTimeout(u),a({code:127,out:c})})})}function D(o,t,n,a){return new Promise(s=>{const i=g(o,t,`cat ${n}`),c=e("ssh",i,{stdio:["ignore","pipe","pipe"]}),l=[],u=setTimeout(()=>c.kill("SIGKILL"),12e4);c.stdout.on("data",e=>l.push(e)),c.on("close",e=>{if(clearTimeout(u),0!==e||0===l.length)return s(!1);try{r(a,Buffer.concat(l)),s(!0)}catch{s(!1)}}),c.on("error",()=>{clearTimeout(u),s(!1)})})}async function F(o,t){if(!L)return!1;if("local"===L.transport)try{return r(t,n(o)),!0}catch{return!1}return function(o,t,r,a){return new Promise(s=>{let i;try{i=n(r)}catch{return s(!1)}const c=g(o,t,`mkdir -p ${U} && cat > ${a}`),l=e("ssh",c,{stdio:["pipe","ignore","pipe"]}),u=setTimeout(()=>l.kill("SIGKILL"),12e4);l.on("close",e=>{clearTimeout(u),s(0===e)}),l.on("error",()=>{clearTimeout(u),s(!1)}),l.stdin&&(l.stdin.on("error",()=>{}),l.stdin.write(i),l.stdin.end())})}(L,E,o,t)}function B(){return!(!L||"ssh"===L.transport&&!E)||(console.log(chalk.yellow(" No GPU box leased — ")+chalk.cyan("on")+chalk.gray(" first.")),!1)}function W(e,o,t){let n;for(let t=0;t<e.length;t++){const r=e[t];r===`--${o}`&&t+1<e.length?n=e[t+1]:r.startsWith(`--${o}=`)?n=r.slice(o.length+3):void 0===n&&/^[0-9]+$/.test(r)&&(n=r)}if(void 0===n)return t;const r=Number.parseInt(n,10);return Number.isFinite(r)?Math.min(999,Math.max(1,r)):t}async function J(e,o,t,n){if(!L||"ssh"===L.transport&&!E)return null;const r=b[0].id;return z(L,E??"",`sudo -n /usr/local/bin/ioailab-run ${r} ${e} --${o} ${t}`,n)}function Z(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 H(e,o){if(!function(e){const o=L?.outDir??"";return!(""===o||!e.startsWith(o))||e===U||e.startsWith(`${U}/`)}(e))return void console.log(chalk.red(" Rejected unexpected video path from the box."));const i=s(a(),"icoa-ioailab");t(i,{recursive:!0});const c=s(i,`${o}-${Date.now()}.mp4`);process.stdout.write(chalk.gray(" Pulling the rendered clip…")),("local"===L?.transport?(()=>{try{return r(c,n(e)),!0}catch{return!1}})():await D(L,E,e,c))?(R=c,console.log(chalk.green(" done.")),console.log(chalk.magenta(" 🎬 clip → ")+chalk.cyan(c)),h(c)?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 Q(e){const o=e.match(P);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(K=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 X(){let e;e=j?q?N?Y?"edit custom":"eval":"train":"mimic":"collect",console.log(chalk.gray(" Next: ")+chalk.cyan(e)+chalk.gray(" (")+chalk.cyan("guide")+chalk.gray(" = where you are)"))}function ee(){let e=!1;const o=[["collect",j],["mimic",q],["train",N],["eval",Y],["custom",M]].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(" "+(L?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"))),K&&"number"==typeof K.success_rate&&console.log(chalk.gray(" Last result: ")+chalk.green(`${(100*K.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 oe(e=!1){const o=S();o&&L&&await C("release",o),L&&!e&&console.log(chalk.gray(" GPU lease released.")),L=null,E=null,j=!1,q=!1,N=!1,Y=!1,M=!1,K=null}async function te(e){const i=e.trim();if(0===i.length)return"continue";const[c,...g]=i.split(/\s+/),y=c.toLowerCase();return f(`ioailab ${y}`),"exit"===y||"quit"===y||"q"===y||"back"===y||"menu"===y?(await oe(!0),console.log(chalk.gray(" Leaving IOAI Lab — any GPU lease was released.")),"exit"):("guide"===y||"help"===y||"/guide"===y||"?"===y?ee():"tasks"===y||"task"===y?function(){console.log();for(const e of b)console.log(chalk.cyan(` ${e.id.padEnd(12)}`)+chalk.gray(e.blurb));console.log()}():"key"===y?0===g.length?console.log(chalk.gray(" Usage: ")+chalk.cyan("key <your-access-key>")):(O(g[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(L)return void console.log(chalk.gray(" already holding a GPU lease — ")+chalk.cyan("status")+chalk.gray(" for time left."));const e=S();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 C("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 C("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=u(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 C("release",e);let c=null;if("ssh"===o.transport&&(c=function(e){const o=s(a(),".icoa","gpu","ioailab-lease-key");try{return t(s(a(),".icoa","gpu"),{recursive:!0}),r(o,e.keyPem,{mode:384}),o}catch{return null}}(o),!c))return console.log(chalk.red(" could not write the ssh key locally.")),void await C("release",e);L=o,E=c;const l=Math.round((o.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU box leased.")+chalk.gray(` ~${l}m on this lease.`));const g=m(o.windowCloseEpoch);g&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${g}.`)),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 oe():"status"===y||"queue"===y?await async function(){const e=S();if(!e)return void console.log(chalk.yellow(" No GPU access key saved — ")+chalk.cyan("key <k>")+chalk.gray(" first."));const o=await C("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=b.find(o=>o.id===e);if(!o||!v.test(e))return void console.log(chalk.yellow(` Unknown task "${e}" — `)+chalk.cyan("tasks")+chalk.gray(" lists what is available."));if(!B())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:r}=await z(L,E??"",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 a=r.match(k);a?await H(a[1],e):console.log(chalk.yellow(" Episode finished but no video path came back — box-side renderer issue."))}((g[0]??b[0].id).toLowerCase()):"collect"===y?await async function(e){if(!B())return;const o=W(e,"episodes",5);console.log(chalk.gray(` Collecting ${o} expert demo(s) on the ICOA-VLA arm (headless — takes a moment)…`));const t=await J("collect","episodes",o,72e4);if(!t)return;if(0!==t.code)return Z(t.code);const n=t.out.match($);n&&(j=!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 r=t.out.match(k);r&&await H(r[1],"collect"),X()}(g):"mimic"===y?await async function(e){if(!B())return;if(!j)return void console.log(chalk.yellow(" No demos yet — run ")+chalk.cyan("collect")+chalk.gray(" first."));const o=W(e,"episodes",36);console.log(chalk.gray(` Expanding your demos into ${o} training episode(s)…`));const t=await J("mimic","episodes",o,72e4);if(!t)return;if(0!==t.code)return Z(t.code);const n=t.out.match($);n&&(q=!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.")),X()}(g):"train"===y?await async function(e){if(!B())return;if(!q)return void console.log(chalk.yellow(" No training set yet — run ")+chalk.cyan("mimic")+chalk.gray(" first."));const o=W(e,"epochs",20),t=54e5,n=L?.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 r=await J("train","epochs",o,t);if(!r)return;if(0!==r.code)return Z(r.code);const a=r.out.match(x);a&&(N=!0,console.log(chalk.green(" ✓ checkpoint saved → ")+chalk.gray(a[1])));const s=r.out.match(_);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.")),X()}(g):"eval"===y?await async function(e){if(!B())return;if(!N)return void console.log(chalk.yellow(" No trained policy yet — run ")+chalk.cyan("train")+chalk.gray(" first."));const o=W(e,"episodes",20);console.log(chalk.gray(` Running YOUR trained policy for ${o} episode(s)…`));const t=await J("eval","episodes",o,72e4);if(!t)return;if(0!==t.code)return Z(t.code);Q(t.out),Y=!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(k);n&&await H(n[1],"eval"),X()}(g):"custom"===y?await async function(e){if(!B())return;const t=V();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 F(t,A);if(console.log(n?chalk.green(" done."):chalk.red(" failed.")),!n)return;const r=W(e,"episodes",9);console.log(chalk.gray(` Running YOUR agent for ${r} episode(s)…`));const a=await J("custom","episodes",r,72e4);if(!a)return;if(0!==a.code)return Z(a.code);Q(a.out),M=!0;const s=a.out.match(k);s?await H(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."))}(g):"edit"===y?"custom"===(g[0]??"").toLowerCase()?await async function(){if(!B())return;const e=s(a(),"icoa-ioailab");t(e,{recursive:!0});const i=V();o(i)||(process.stdout.write(chalk.gray(" Fetching the starter agent…")),await async function(e,o){if(!L)return!1;if("local"===L.transport)try{return r(o,n(e)),!0}catch{return!1}return D(L,E,e,o)}("/opt/ioailab-mj/examples/05_custom_agent.py",i)?console.log(chalk.green(" done.")):(r(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 c=n(i,"utf-8"),g=l(c,".py");if(null===g)return void console.log(chalk.yellow(" Editor cancelled — agent unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));r(i,g),process.stdout.write(chalk.gray(" Saving to the box…"));const u=await F(i,A);console.log(u?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?R&&h(R)?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=S();if(o){const e=await T(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 r=await T(n);if("ok"===r)return O(n),console.log(chalk.green(" ✓ Key accepted — saved to this device. You will not be asked again.")),!0;if("offline"===r)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.")),ee();const e=p(),o=null!==e,t=o?e.listeners("line").slice():[];o&&e.removeAllListeners("line");const n=o?e:c({input:process.stdin,output:process.stdout,terminal:!0}),r=o?n.prompt:null;o&&(n.prompt=i.prototype.prompt);const a=()=>{n.setPrompt(chalk.bold.magenta("icoa ioailab> ")),n.prompt()};return new Promise(e=>{const s=i=>{te(i).then(i=>{"exit"===i?((()=>{if(n.removeListener("line",s),o){r&&(n.prompt=r);for(const e of t)n.on("line",e)}else n.close()})(),e()):a()}).catch(e=>{w(`ioailab error: ${e instanceof Error?e.message:String(e)}`),a()})};n.on("line",s),a()})}
|
|
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()})}
|
package/dist/commands/ipynb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as o,readdirSync as n,readFileSync as t,statSync as l,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{createHash as s}from"node:crypto";import{Interface as i,createInterface as c}from"node:readline";import{basename as g,dirname as y,isAbsolute as d,join as u,resolve as h}from"node:path";import chalk from"chalk";import{aienvPaths as p}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as f,askIoaiOneShot as m}from"./ai4ioai.js";import{getConfig as w,saveConfig as k}from"../lib/config.js";import{editTextInEditor as b,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as S,parseLeaseResponse as E,queueLine as C,windowLine as G}from"../lib/gpu.js";import{shouldExecuteCell as j}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{NotebookKernel as I,buildRemoteBridgeCommand as N}from"../lib/kernel.js";import{getMainRl as O,setMainRl as T}from"../lib/main-rl.js";import{logCommand as M}from"../lib/logger.js";import{startLogSync as D,stopLogSync as q}from"../lib/log-sync.js";import{cellPreview as L,fromWholeEditText as K,mergeReloadedCells as R,normalizePathArg as B,parseIpynb as F,parsePercentPy as z,parseRunRange as W,serializeIpynb as J,statusChar as V,toWholeEditText as Y}from"../lib/notebook-doc.js";import{committeeLease as H,readCommitteeSession as X,TIER_LABEL as Z}from"../lib/gputask-session.js";import{lazyFile as Q}from"../lib/lazy-assets.js";import{openFile as ee}from"../lib/open-file.js";const oe=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function ne(){return(w().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(e){e.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async e=>{await runIpynb(e)})}function te(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const le=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),re=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function ae(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const se="https://practice.icoa2026.au";function ie(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):se}function ce(){return u(a(),".icoa","gpu-key")}function ge(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return t(ce(),"utf-8").trim()||null}catch{return null}}async function ye(e,o,n){try{const t=await fetch(`${ie()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await t.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function de(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let ue=0,he=null;function pe(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(oe,"")}`))}else"display"===n.kind&&fe(n.data,o)}function fe(e,n){if(e["image/png"])try{o(n,{recursive:!0}),ue+=1;const t=u(n,`figure-${ue}.png`);return r(t,Buffer.from(e["image/png"],"base64")),he=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(ee(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}function me(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function we(e){if(e)try{return l(e).mtimeMs}catch{return}}function ke(o){const n=B(o,a()),l=d(n)?n:h(process.cwd(),n);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=t(l,"utf8"),o=l.endsWith(".ipynb")?F(e):z(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:we(l),diskSig:me(o)},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}const be={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const se=E?.trim().toLowerCase().replace(/-demo$/,"");if(se&&be[se]){const n=await async function(n){const l=be[n],a=u(process.cwd(),"icoa-lab"),s=u(a,g(l));if(e(s))return console.log(chalk.gray(" Using your copy ")+chalk.cyan(s)+chalk.gray(" (edits kept — delete the file to start from the original).")),s;process.stdout.write(chalk.gray(" Fetching the demo notebook…"));const i=await Q(l);if(!i)return console.log(chalk.yellow(" not available right now.")),console.log(chalk.gray(" It needs one online moment — try ")+chalk.cyan(`ipynb ${n}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,t(i))}catch(e){return console.log(chalk.yellow(` could not write ${s}: ${e instanceof Error?e.message:String(e)}`)),null}return console.log(chalk.green(" saved ")+chalk.cyan(s)),s}(se);if(!n)return;E=n}const ue=p(a()),fe=u(a(),".icoa","ipynb-out");if(te(),!e(ue.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const ve=E?ke(E):null,$e=ve?ve.doc:{cells:[],path:null,dirty:!1};let _e=new I({venvPython:ue.python,venvRoot:ue.root}),xe=null,Pe=null,Se=null,Ee=de($e.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await _e.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),ve&&console.log(ve.note),console.log(chalk.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" one cell · ")+chalk.cyan("edit")+chalk.gray(" whole notebook · ")+chalk.cyan("add")+chalk.gray(" new cell · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const Ce=O(),Ge=null!==Ce,je=Ge?Ce.listeners("line").slice():[];Ge&&Ce.removeAllListeners("line");const Ue=Ge?Ce:c({input:process.stdin,output:process.stdout,terminal:!0});Ge||T(Ue);const Ae=Ge?Ue.prompt:null,Ie=Ge?Ue.getPrompt():"";Ge&&(Ue.prompt=i.prototype.prompt),Ge||D();const Ne=[];let Oe,Te=!1,Me=!1,De=!1,qe=null,Le=null;const Ke=()=>{if(Le)return Ue.setPrompt(chalk.bold.cyan(` editor 1-${Le.options.length} > `)),void Ue.prompt();const e=xe?"icoa ipynb ⚡gpu":"icoa ipynb";Ue.setPrompt(chalk.bold.cyan(Ne.length?`${e} ...> `:`${e}> `)),Ue.prompt()};let Re=()=>{};const Be=new Promise(e=>{Re=e}),Fe=async()=>{_e=new I({venvPython:ue.python,venvRoot:ue.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await _e.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}},ze=async(e,n=!1)=>{const t=H(e),l=S(t);if(l.length>0)return console.log(chalk.red(" committee seat file rejected: ")+chalk.gray(l.join(", "))),!1;const s=u(a(),".icoa","gputask","key");try{o(u(a(),".icoa","gputask"),{recursive:!0}),r(s,e.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),!1}const i=$e.path?g(y($e.path)):"work",c=`${t.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=N(t.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new I({spawnSpec:{command:"ssh",args:P(t,s,d)},readyTimeoutMs:9e4});n||process.stdout.write(chalk.gray(` Connecting to your seat (${e.host})…`));try{await h.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" The box may be rebuilding (Spot reclaim) — ")+chalk.cyan("gpufortask")+chalk.gray(" shows the seat state; ")+chalk.cyan("gpu on")+chalk.gray(" again once it is ready.")),!1}await _e.shutdown().catch(()=>{}),_e=h,xe={...t,outDir:c},Se=e,Pe=Date.now(),h.onUnexpectedExit=()=>{_e===h&&(console.log(),console.log(chalk.bold.yellow(" ⚠ The GPU box went away (Spot reclaim or seat ended).")),console.log(chalk.gray(" Files are kept on the seat; variables are gone. ")+chalk.cyan("gpu on")+chalk.gray(" in 1–2 min reconnects (the seat is rebuilt automatically).")),xe=null,Se=null,Pe=null,Fe().then(()=>Ke()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${Z[e.tier]} · cells run in ${c}`));const p=await We();return p>0&&console.log(chalk.gray(` ${p} small file${1===p?"":"s"} from this notebook's folder sent to the box.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to rerun there · ")+chalk.cyan("upload <file>")+chalk.gray(" sends more · ")+chalk.cyan("download <file>")+chalk.gray(" brings results back · ")+chalk.cyan("gpu off")+chalk.gray(" returns to the local kernel (seat stays).")),!0},We=async()=>{if(!$e.path||!xe?.outDir)return 0;const e=y($e.path);let o=[];try{o=n(e)}catch{return 0}let r=0;for(const n of o){if(n.startsWith("."))continue;const o=u(e,n);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await _e.putFile(`${xe.outDir}/${n}`,t(o)),r++}catch{}}return r},Je=async e=>{const[n,...t]=e.trim().split(/\s+/),l=(n??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(xe)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=X();if(e)return void await(async e=>{await ze(e)})(e);const n=ge();if(!n)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));Ee||(Ee=de($e.path));const t=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await ye("lease",n,Ee??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-t)/1e3)} s`;for(;"queued"===l.state&&s<(l.bootStage||i?60:24);)l.bootStage&&(i=!0),0===s&&console.log(),process.stdout.write(`\r ${chalk.yellow(C(l))} `),await new Promise(e=>setTimeout(e,5e3)),l=await ye("status",n),s++;if("queued"===l.state)return console.log(),void(i?(console.log(chalk.yellow(` The GPU box is still starting (${c()} so far) — your place is held.`)),console.log(chalk.gray(" Keep editing; ")+chalk.cyan("gpu on")+chalk.gray(" again in a minute picks it up."))):(console.log(chalk.yellow(" Still queued — your place is held server-side.")),console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."))));if(i&&"ready"===l.state&&(console.log(),console.log(chalk.green(` ✓ GPU box ready in ${c()}`)+chalk.gray(` · ${l.gpuName??"GPU"}${l.zone?` · ${l.zone}`:""} · built just for this session`))),"ready"!==l.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${l.message??"no lease granted"}`));const g=S(l);if("local"!==l.transport||process.env.ICOA_GPU_SERVER||g.push("local transport from a non-dev broker"),g.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(g.join(", "))),void await ye("release",n);const y=Ee?`${l.dataRoot}/${Ee}`:l.dataRoot,d=N(l.python,{ICOA_KAGGLE_DATA:y,ICOA_KAGGLE_OUT:l.outDir},l.outDir);let h;if("local"===l.transport)h={command:"/bin/sh",args:["-c",d]};else{const e=u(a(),".icoa","gpu","lease-key");try{o(u(a(),".icoa","gpu"),{recursive:!0}),r(e,l.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await ye("release",n)}h={command:"ssh",args:P(l,e,d)}}const p=new I({spawnSpec:h,readyTimeoutMs:9e4}),f=Date.now();process.stdout.write(chalk.gray(" connecting…"));try{await p.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),void await ye("release",n)}await _e.shutdown().catch(()=>{}),_e=p,xe=l,Pe=Date.now();const m=Math.round((l.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected")+chalk.gray(` (${Math.round((Date.now()-f)/1e3)} s).`)),console.log(chalk.gray(` Cells now run on the ${l.gpuName?`${l.gpuName} `:""}GPU box · ${m}m left on this lease.`));const w=G(l.windowCloseEpoch);w&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${w}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),Ee&&console.log(chalk.gray(` Dataset is already on the box (${Ee}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===l||"disconnect"===l?await(async()=>{if(xe&&Se){const e=Pe?Math.round((Date.now()-Pe)/1e3):0;return await _e.shutdown().catch(()=>{}),xe=null,Se=null,Pe=null,console.log(chalk.green(` ⚡ Back to the local kernel after ${Math.floor(e/60)} m ${e%60} s`)+chalk.gray(" — the seat stays open (files kept); ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now.")),void await Fe()}if(!xe)return void console.log(chalk.gray(" not on a GPU kernel."));const e=ge(),o=void 0!==xe.gpuName,n=Pe?Math.round((Date.now()-Pe)/1e3):0;await _e.shutdown().catch(()=>{}),e&&await ye("release",e),xe=null,Pe=null;const t=Math.floor(n/60),l=t>0?`${t} m ${n%60} s`:`${n} s`;console.log(chalk.green(` ⚡ GPU lease released after ${l}`)+chalk.gray(" — billing for you stopped.")),o&&console.log(chalk.gray(" The box recycles itself now that nobody holds it (")+chalk.cyan("gpu queue")+chalk.gray(" shows 0 boxes once it is gone); the next ")+chalk.cyan("gpu on")+chalk.gray(" builds a fresh one.")),await Fe()})():"status"===l||""===l?await(async()=>{const e=X();if(e)return console.log(chalk.green(` ⚡ committee seat · ${Z[e.tier]} · ${e.host}`)+chalk.gray(Se?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=ge();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const n=await ye("status",o);if("ready"===n.state){const e=Math.round((n.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(xe?" (this notebook is connected)":" (not connected here — gpu on)"));const o=G(n.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===n.state?console.log(chalk.yellow(` ${C(n)}`)):"none"===n.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${n.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=ge();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${ie()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await n.json();o=t.data??t}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,t="number"==typeof o.free?o.free:0,l=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${t} free`));const a=G("number"==typeof o.window_close_epoch?o.window_close_epoch:void 0);a&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${a}.`)),console.log(chalk.bold.white(" ▶ running now:")),0===l.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,t=Math.floor(n/60),l=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${t}:${l} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",t=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+t)}console.log()})():"key"===l?(e=>{const n=e.trim();if(n)try{o(u(a(),".icoa"),{recursive:!0}),r(ce(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${ce()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(t.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},Ve=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>$e.cells.length?(console.log(0===$e.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${$e.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:$e.cells[o-1],idx:o}},Ye=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let He=!1;const Xe=()=>{const e=w().notebookEditor;return e?_(e):null},Ze=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),Qe=()=>Xe()??x(),eo={nano:"easiest — Ctrl+O save, Ctrl+X exit",code:"VS Code window — save, close the tab to come back",vi:"i to type, Esc then :wq to save and exit"},oo=(e,o)=>{if(e){const n=_(e);return n?v(n.cmd)?(o(n),!0):(console.log(chalk.yellow(` ${$(n)} is not installed on this computer.`)+chalk.gray(" See the choices: ")+chalk.cyan("editor")),!0):(console.log(chalk.yellow(` unknown editor "${e}" — use `)+chalk.cyan("nano")+chalk.yellow(", ")+chalk.cyan("code")+chalk.yellow(" or ")+chalk.cyan("vi")),!0)}if(Xe()||Ze())return o(Qe()),!0;const n=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return n.length<2||!process.stdin.isTTY?(o(x()),!0):((e=>{console.log(),console.log(chalk.bold.white(" Which editor should edit / add open?")+chalk.gray(" (asked once)")),e.forEach((e,o)=>{const n=$(e);console.log(chalk.cyan(` ${o+1} ${n.padEnd(5)}`)+chalk.gray(` ${eo[n]??""}`)+("nano"===n?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(n),Le={resume:o,tries:0,options:n},!1)},no=e=>{if(!$e.path)return!1;let o;try{const e=t($e.path,"utf8");o=$e.path.endsWith(".ipynb")?F(e):z(e)}catch(e){return console.log(chalk.yellow(" could not re-read the file: ")+chalk.gray(e instanceof Error?e.message:String(e))),!1}const n=R($e.cells,o);return $e.cells=n.cells,$e.dirty=!1,$e.mtimeMs=we($e.path),$e.diskSig=me(o),Oe=void 0,console.log(chalk.gray(` ↻ reloaded ${g($e.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${n.cells.length} cells, ${n.changed} changed`)+chalk.gray(n.kept?`, ${n.kept} kept their output.`:".")),console.log(chalk.gray(" variables stay in the kernel — run just the cells you changed, or ")+chalk.cyan("run all")),!0},to=()=>void 0!==$e.diskSig?me($e.cells)!==$e.diskSig:$e.dirty,lo=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!U(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),ro=async n=>{if(n.trim()&&M(`ipynb: ${n.trim()}`),Me)return void(n.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Le){const e=Le,o=n.trim().toLowerCase(),t=_(o),l=/^\d+$/.test(o)?e.options[Number(o)-1]:t?e.options.find(e=>$(e)===$(t)):void 0;return l?(Le=null,k({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===o||["q","quit","back","cancel","exit"].includes(o)?(Le=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Le=null,console.log(chalk.gray(" no editor chosen — nothing changed. Choose later with ")+chalk.cyan("editor nano"))):console.log(chalk.yellow(` type a number 1-${e.options.length}, or a name: `)+chalk.cyan(e.options.map(e=>$(e)).join(" / "))),void Ke()}let l=n.trim();if(0===Ne.length&&/^icoa\s+[a-z/]/i.test(l)&&(l=l.replace(/^icoa\s+/i,"")),0===Ne.length){const n=l.split(/\s+/),i=(n[0]??"").toLowerCase(),c=l.slice(n[0]?.length??0).trim();if("quit"!==i&&"exit"!==i&&"q"!==i&&(De=!1),qe&&i!==qe&&(qe=null),re.has(i)&&(()=>{if(!$e.path||void 0===$e.mtimeMs)return;const e=we($e.path);if(void 0!==e&&e!==$e.mtimeMs){if(to()){if(Oe===e)return;return Oe=e,console.log(chalk.yellow(` ⚠ ${g($e.path)} changed in your editor, and this notebook has unsaved changes too.`)),void console.log(chalk.gray(" take the file: ")+chalk.cyan("reload")+chalk.gray(" · keep these and overwrite the file: ")+chalk.cyan("save"))}no(!0)}})(),"quit"===i||"exit"===i||"back"===i||"q"===i||"menu"===i)return $e.dirty&&!De?(De=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ke()):void await(async()=>{if(Ue.removeAllListeners("line"),Ge||q(),console.log(),xe&&Se)xe=null,console.log(chalk.gray(" ⚡ Committee seat stays open (files kept) — ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now, or it closes after 40 min idle."));else if(xe){const e=ge();e&&await ye("release",e),xe=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await _e.shutdown().catch(()=>{}),Ge){Ae&&(Ue.prompt=Ae),Ue.setPrompt(Ie);for(const e of je)Ue.on("line",e);Ue.prompt(),Re()}else T(null),Re(),Ue.close()})();if("clear"===i||"cls"===i)return console.clear(),te(),void Ke();if("restart"===i)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await _e.shutdown().catch(()=>{});try{await _e.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void Ke();if("help"===i||"?"===i)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor vi")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(ne()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" load <file>")+chalk.gray(" open another .ipynb / .py (drag the file into this window)")),console.log(chalk.cyan(" reload")+chalk.gray(" re-read the file — or just save in Jupyter / VS Code: the next run picks it up")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a GPU box — a GCP T4 starts for you on demand (~1–2 min), ")+chalk.cyan("gpu off")+chalk.gray(" hands it back")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" selfcheck")+chalk.gray(" committee seat: rerun the whole notebook fresh, measure peak GPU memory → capsule size, file the report")),console.log(chalk.cyan(" upload <f>")+chalk.gray(" send a file to the box (committee seat: files next to the notebook go up on gpu on)")),console.log(chalk.gray(" try it: ")+chalk.cyan("icoa> ipynb mnist")+chalk.gray(" — the MNIST demo notebook (edit → run → train on the T4 → gpu off)")),console.log(chalk.cyan(" check / submit")+chalk.gray(" verify / score your submission.csv — right here, no quit needed")),console.log(chalk.cyan(" board")+chalk.gray(" live standings for this competition")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void Ke();if("guide"===i||"/guide"===i)return(()=>{const o=$e.path?y($e.path):process.cwd(),n=de($e.path);let l="",r=!1;try{const e=JSON.parse(t(u(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=$e.cells.filter(e=>null!==e.result).length,s=e(u(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white($e.path?g($e.path):"new empty notebook")+chalk.gray(` · ${$e.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),xe?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),n&&"icoa-holdout"===l?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("submit")+chalk.gray(" — scored + ranked right here, no need to leave (")+chalk.cyan("board")+chalk.gray(" shows standings)")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):n&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):n?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void Ke();if("python"===i||"python3"===i)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void Ke();if("open"===i&&""===c)return he&&ee(he)?console.log(chalk.gray(" reopening ")+chalk.cyan(he)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ke();if("cells"===i||"ls"===i)return(()=>{if(0===$e.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);$e.cells.forEach((o,n)=>{const t=V(o),l="✓"===t?chalk.green(t.padEnd(2)):"✗"===t?chalk.red(t.padEnd(2)):"md"===t?chalk.magenta(t.padEnd(2)):chalk.gray(t.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${l} ${chalk.white(L(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void Ke();if("show"===i)return(e=>{const o=Ve(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of A(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),pe(o.cell.result,fe)),console.log()}})(c),void Ke();if("edit"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ").toLowerCase();return""===n||"all"===n?oo(o,e=>(e=>{Ue.pause();const o=b(Y($e.cells),".py",e,"notebook");if(Ue.resume(),null===o)return void console.log(chalk.yellow(" editor cancelled or failed — notebook unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const n=K(o,$e.cells);if(n.same)return void console.log(chalk.gray(" no changes."));if(0===n.cells.length&&$e.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${$e.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));$e.cells=n.cells,$e.dirty=!0;const t=[];n.changed.length&&t.push(`${n.changed.length} changed (${n.changed.join(", ")})`),n.added.length&&t.push(`${n.added.length} added (${n.added.join(", ")})`),n.deleted&&t.push(`${n.deleted} deleted`),n.reordered&&t.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${$e.cells.length} cells`)+chalk.gray(` · ${t.join(" · ")}`));const l=[...n.changed,...n.added].filter(e=>"code"===$e.cells[e-1].kind).sort((e,o)=>e-o);if(l.length){const e=l[0],o=l[l.length-1];console.log(chalk.gray(" unchanged cells kept their output · run what changed: ")+chalk.cyan(e===o?`run ${e}`:`run ${e}-${o}`)+chalk.gray(" · or ")+chalk.cyan("run all"))}})(e)):Ve(n)&&oo(o,e=>((e,o)=>{const n=Ve(e);if(!n)return;Ue.pause();const t=b(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(Ue.resume(),null===t)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=t.replace(/\s+$/,"");l!==n.cell.source?(n.cell.source=l,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,$e.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(n,e)),void Ke()}if("add"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ");return oo(o,e=>((e,o)=>{const n=e.trim().toLowerCase(),t="md"===n||"markdown"===n||"text"===n||"txt"===n;if(n&&!t&&"py"!==n&&"code"!==n&&"python"!==n)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Ue.pause();const l=b(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);Ue.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?($e.cells.push({kind:t?"markdown":"code",source:r,result:null}),$e.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${$e.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${$e.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void Ke()}if("editor"===i&&/^[\w-]*$/.test(c))return(e=>{const o=e.trim().toLowerCase(),n=$(Qe());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${Xe()?"saved":Ze()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),t=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(t?` ${eo[e]}`:" not installed here")+(e===n?chalk.green(" ← now"):""))}return console.log(chalk.gray(" one edit only: ")+chalk.cyan("edit 3 nano")+chalk.gray(" · back to $EDITOR / vi: ")+chalk.cyan("editor default")),void console.log()}if("default"===o||"reset"===o||"off"===o)return k({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const t=_(o);if(!t)return void console.log(chalk.yellow(` unknown editor "${o}" — `)+chalk.cyan("editor nano")+chalk.yellow(" · ")+chalk.cyan("editor code")+chalk.yellow(" · ")+chalk.cyan("editor vi"));const l=$(t);Xe()&&$(Xe())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(t.cmd)?(k({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${n===l?"default":n}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(c),void Ke();if("reload"===i&&""===c)return $e.path&&e($e.path)?to()&&"reload"!==qe?(qe="reload",console.log(chalk.yellow(" unsaved changes here will be replaced by the file — ")+chalk.cyan("reload")+chalk.yellow(" again to go ahead, or ")+chalk.cyan("save")+chalk.yellow(" first."))):(qe=null,no(!1)):console.log(chalk.gray(" nothing to reload — this notebook has no file yet (")+chalk.cyan("save")+chalk.gray(" first, or ")+chalk.cyan("load <file>")+chalk.gray(").")),void Ke();if("load"===i&&!/^[=(.[]/.test(c)||"open"===i&&""!==c){if(!c)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ke();const o=B(c,a()),n=d(o)?o:h(process.cwd(),o);if(e(n))if($e.dirty&&"load"!==qe)qe="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(i)+chalk.yellow(" again to discard them."));else{qe=null;const e=ke(n);$e.cells=e.doc.cells,$e.path=e.doc.path,$e.dirty=!1,$e.mtimeMs=e.doc.mtimeMs,$e.diskSig=e.doc.diskSig,Oe=void 0,Ee=de($e.path),console.log(e.note),console.log(chalk.gray(" the kernel keeps its variables — ")+chalk.cyan("restart")+chalk.gray(" for a clean start."))}else console.log(chalk.yellow(" no such file: ")+chalk.white(n)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ke()}if("del"===i||"delete"===i)return(e=>{const o=Ve(e);o&&($e.cells.splice(o.idx-1,1),$e.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${$e.cells.length} left.`)+(o.idx<=$e.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(c),void Ke();if(("md"===i||"py"===i)&&/^\d+$/.test(c))return((e,o)=>{const n=Ve(e);if(!n)return;const t="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,$e.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${t}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${t}.`))})(c,"md"===i?"markdown":"code"),void Ke();if("gpu"===i)return Me=!0,await Je(c),Me=!1,void Ke();if("download"===i||"dl"===i)return Me=!0,await(async e=>{if(!xe)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${xe.outDir}/${n}`;let l;try{l=await _e.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=Ee?u(process.cwd(),"icoa-kaggle",Ee):process.cwd(),s=u(a,g(n));try{o(a,{recursive:!0}),r(s,l)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(s)+chalk.gray(` (${l.length} bytes)`)),Ee&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Ee}`)+chalk.gray(" — then upload on Kaggle yourself."))})(c),Me=!1,void Ke();if("selfcheck"===i||"self-check"===i)return Me=!0,await(async()=>{const e=Se;if(!e||!xe)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===$e.cells.filter(e=>"code"===e.kind).length)return void console.log(chalk.yellow(" nothing to check — the notebook has no code cells."));console.log(chalk.bold.cyan(" 🔬 selfcheck")+chalk.gray(` · fresh kernel · ${Z[e.tier]} · every code cell from the top`));const o=_e;if(await ze(e,!0),_e===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const n=Date.now(),t=[];let l=!1;for(let e=0;e<$e.cells.length;e++){const o=$e.cells[e];if("code"!==o.kind)continue;const n=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${n} … `));try{o.result=await _e.execute(o.source)}catch(e){t.push({n:n,ok:!1,ms:Date.now()-r,error:e instanceof Error?e.message:String(e)}),console.log(chalk.red("kernel error")),l=!0;break}$e.dirty=!0;const a=Date.now()-r,s=o.result.outputs.find(e=>"error"===e.kind);if(t.push({n:n,ok:o.result.ok,ms:a,error:s&&"error"===s.kind?`${s.ename}: ${s.evalue}`:void 0}),console.log(o.result.ok?chalk.green(`ok ${(a/1e3).toFixed(1)} s`):chalk.red(`raised ${(a/1e3).toFixed(1)} s`)),!o.result.ok){pe(o.result,fe),l=!0;break}}const r=Date.now()-n,a=["import json as _j, os as _o, sys as _s, hashlib as _h, platform as _p",'_r = {"python": _s.version.split()[0], "platform": _p.platform()}',"try:"," import torch as _t",' _r["torch"] = _t.__version__'," if _t.cuda.is_available():",' _r["gpu"] = _t.cuda.get_device_name(0)',' _r["peak_gib"] = round(_t.cuda.max_memory_allocated() / 2**30, 3)',' _r["reserved_gib"] = round(_t.cuda.max_memory_reserved() / 2**30, 3)',"except Exception as _e:",' _r["torch"] = "n/a: %s" % _e','for _m in ("sklearn", "numpy", "pandas", "transformers"):'," try:"," _r[_m] = __import__(_m).__version__"," except Exception:"," pass",'_r["fence"] = _o.environ.get("CUDA_MPS_PINNED_DEVICE_MEM_LIMIT")','_r["units"] = _o.environ.get("ICOA_GPU_UNITS")','_r["files"] = {}','for _f in sorted(_o.listdir(".")):',' if _o.path.isfile(_f) and not _f.startswith("."):'," _sz = _o.path.getsize(_f)"," _d = _h.sha256()",' with open(_f, "rb") as _fh:',' for _c in iter(lambda: _fh.read(1 << 20), b""):'," _d.update(_c)",' _r["files"][_f] = {"bytes": _sz, "sha256": _d.hexdigest()[:16]}','print("ICOA_SELFCHECK " + _j.dumps(_r))'].join("\n");let s={};try{const e=(await _e.execute(a)).outputs.filter(e=>"stream"===e.kind).map(e=>"stream"===e.kind?e.text:"").join("").split("\n").find(e=>e.startsWith("ICOA_SELFCHECK "));e&&(s=JSON.parse(e.slice(15)))}catch{}const i="number"==typeof s.peak_gib?s.peak_gib:null,c=null===i?null:i<3?1:i<6.5?2:i<10?3:0,y={sid:e.sid,tier:e.tier,notebook:$e.path?g($e.path):null,cells:t,ok:!l,wall_ms:r,env:s,peak_gib:i,units:c,ts:Math.floor(Date.now()/1e3)};console.log(),console.log((l?chalk.bold.red(" ✗ selfcheck: a cell raised"):chalk.bold.green(" ✓ selfcheck: every cell ran"))+chalk.gray(` · ${(r/1e3).toFixed(0)} s wall on a shared box (not a time limit)`)),null!==i?console.log(chalk.white(` peak GPU memory ${i.toFixed(2)} GiB`)+(c?chalk.green(` → ${c} capsule unit${c>1?"s":""}`)+chalk.gray(` (fence ${3.5*c} GiB, allocator cap ${(3.5*c-.5).toFixed(1)})`):chalk.red(" → exceeds 3 units (10 GiB cap) — the task must shrink"))):console.log(chalk.gray(" no GPU memory figure (torch not imported or no CUDA) — CPU task, or add a torch import.")),(s.gpu||s.torch)&&console.log(chalk.gray(` ${s.gpu??"no GPU"} · torch ${s.torch??"?"} · sklearn ${s.sklearn??"?"} · numpy ${s.numpy??"?"}`));const d=s.files??{},u=Object.keys(d);u.length>0&&console.log(chalk.gray(` ${u.length} data file${1===u.length?"":"s"} fingerprinted: ${u.slice(0,6).join(", ")}${u.length>6?", …":""}`));try{const o=await fetch(`${(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"")}/api/icoa/gputask/selfcheck`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,report:y}),signal:AbortSignal.timeout(2e4)});console.log(o.ok?chalk.gray(" report filed with the committee ✓"):chalk.yellow(` report not filed (http ${o.status}) — keep the numbers above.`))}catch{console.log(chalk.yellow(" report not filed (offline) — keep the numbers above."))}})(),Me=!1,void Ke();if("upload"===i||"up"===i||"put"===i)return Me=!0,await(async e=>{if(!xe)return void console.log(chalk.gray(" local kernel — files are already here. ")+chalk.cyan("gpu on")+chalk.gray(" first."));const o=e.trim();if(!o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("upload <file>")+chalk.gray(" (≤ 20 MB; lands in the box work dir)"));const n=B(o,a()),l=d(n)?n:h($e.path?y($e.path):process.cwd(),n);let r;try{r=t(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${xe.outDir}/${g(l)}`;try{const e=await _e.putFile(s,r);console.log(chalk.green(" ✓ uploaded ")+chalk.white(s)+chalk.gray(` (${e} bytes)`))}catch(e){console.log(chalk.yellow(" upload failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(c),Me=!1,void Ke();if("check"===i||"submit"===i||"kaggle"===i){const e=await import("./kaggle.js"),o=c.split(/\s+/).filter(Boolean),n="kaggle"===i?(o[0]||"").toLowerCase():i,t=("kaggle"===i?o[1]:o[0])||de($e.path)||void 0;Me=!0;try{if("submit"===n){const o=s("sha256").update($e.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(t,{code_sha:o,...Se?{sid:Se.sid}:{},...$e.path?{notebook:g($e.path)}:{}})}else"check"===n?await e.runKaggleCheck(t):"final"===n?await e.runKaggleFinal(t,o.slice(2)):"guide"===n?await e.runKaggleGuide(t):await e.runKaggle("kaggle"===i?o[0]:t)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Me=!1,void Ke()}if("board"===i){const{runBoard:e}=await import("./board.js"),o=c.split(/\s+/).filter(Boolean);Me=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Me=!1,void Ke()}if("ai"===i||"/ai"===i)return Me=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),n=o.length>0&&/^\d+$/.test(o[0]),l=(n?o.slice(1):o).join(" ").trim(),r=n?Number(o[0]):(()=>{for(let e=$e.cells.length-1;e>=0;e--)if(($e.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??$e.cells.length;if(0===$e.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=Ve(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(oe,"")).join("\n")));return o.join("\n").replace(oe,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!$e.path||!de($e.path))return"";try{const e=JSON.parse(t(u(y($e.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return Ye(o,350)}catch{return""}})(),c=ne(),g=c?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",d=g.length+l.length+120,h=Math.max(400,f-d-i.length),p=Ye(a.cell.source,Math.floor(.6*h)),w=s?(k=s,b=h-p.length,k.length<=b?k:`…(${k.length-b} chars elided)…\n${k.slice(-b)}`):"";var k,b;const v=[g,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${p}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",l?`\n[question]\n${l}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),_=c;console.log(),He||(He=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(ne()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${ne()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(ne()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(ne()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${f} chars`)+chalk.gray(_?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(_?" · 含输出":" · output included"):"")+($?chalk.yellow(_?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),M(`ipynb: ai ${a.idx}${l?` — ${l}`:""}`);const x=await m(v);if(console.log(),!x.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(x.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of A(x.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${_?"<你的问题>":"<your question>"}`)+chalk.gray(_?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(_?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(_?" 再跑一次":" run it again")),console.log(chalk.gray(_?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(c),Me=!1,void Ke();if("run"===i)return Me=!0,await(async e=>{const o=W(e,$e.cells.length);if(o)for(const e of o){const n=$e.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(L(n,50))+chalk.gray(" ──"));try{n.result=await _e.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void ae()}if($e.dirty=!0,pe(n.result,fe),lo(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(ne()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(ne()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void ae()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(n.source))console.log(e);console.log()}}else console.log(0===$e.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(c),Me=!1,void Ke();if("save"===i)return(e=>{if(0===$e.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?d(e.trim())?e.trim():h(process.cwd(),e.trim()):$e.path?$e.path.endsWith(".ipynb")?$e.path:`${$e.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===$e.path?we(o):void 0;if(void 0!==n&&void 0!==$e.mtimeMs&&n!==$e.mtimeMs&&"save"!==qe)return qe="save",console.log(chalk.yellow(` ${g(o)} was changed in your editor after this notebook read it.`)),void console.log(chalk.gray(" ")+chalk.cyan("save")+chalk.gray(" again to overwrite those changes · ")+chalk.cyan("reload")+chalk.gray(" to take the file instead"));qe=null;try{r(o,J($e.cells)),$e.path=o,$e.dirty=!1,$e.mtimeMs=we(o),$e.diskSig=me($e.cells),Oe=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${$e.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(c),void Ke();if(""===l)return void Ke()}if(Ne.length>0&&le.has(l.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(l.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ke();if(Ne.push(n),!j(Ne))return 1!==Ne.length||Te||(Te=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ke();const i=Ne.join("\n").replace(/\s+$/,"");if(Ne.length=0,""!==i.trim()){Me=!0;try{const e=await _e.execute(i);$e.cells.push({kind:"code",source:i,result:e}),$e.dirty=!0,pe(e,fe);const o=lo($e.cells[$e.cells.length-1],$e.cells.length);e.ok||o||ae()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),ae()}Me=!1,Ke()}else Ke()};Ue.on("line",e=>{ro(e)}),Ge||Ue.on("close",async()=>{await _e.shutdown().catch(()=>{}),process.exit(0)}),Ke(),await Be}
|
|
1
|
+
import{existsSync as e,mkdirSync as o,readdirSync as n,readFileSync as t,statSync as l,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{createHash as s}from"node:crypto";import{Interface as i,createInterface as c}from"node:readline";import{basename as g,dirname as y,isAbsolute as d,join as u,resolve as h}from"node:path";import chalk from"chalk";import{aienvPaths as p}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as f,askIoaiOneShot as m}from"./ai4ioai.js";import{getConfig as w,saveConfig as b}from"../lib/config.js";import{editTextInEditor as k,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as S,parseLeaseResponse as E,queueLine as C,windowLine as G}from"../lib/gpu.js";import{shouldExecuteCell as j}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{NotebookKernel as I,buildRemoteBridgeCommand as N}from"../lib/kernel.js";import{getMainRl as O,setMainRl as T}from"../lib/main-rl.js";import{logCommand as M}from"../lib/logger.js";import{startLogSync as D,stopLogSync as q}from"../lib/log-sync.js";import{cellPreview as L,fromWholeEditText as z,mergeReloadedCells as K,normalizePathArg as R,parseIpynb as B,parsePercentPy as F,parseRunRange as W,serializeIpynb as J,statusChar as V,toWholeEditText as Y}from"../lib/notebook-doc.js";import{committeeLease as H,readCommitteeSession as X,TIER_LABEL as Z}from"../lib/gputask-session.js";import{enterPanel as Q,leavePanel as ee,printHelp as oe}from"../lib/guide-panel.js";import{lazyFile as ne}from"../lib/lazy-assets.js";import{openFile as te}from"../lib/open-file.js";const le=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function re(){return(w().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(e){e.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async e=>{await runIpynb(e)})}function ae(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const se=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),ie=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function ce(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const ge="https://practice.icoa2026.au";function ye(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):ge}function de(){return u(a(),".icoa","gpu-key")}function ue(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return t(de(),"utf-8").trim()||null}catch{return null}}async function he(e,o,n){try{const t=await fetch(`${ye()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await t.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function pe(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let fe=0,me=null;function we(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(le,"")}`))}else"display"===n.kind&&be(n.data,o)}function be(e,n){if(e["image/png"])try{o(n,{recursive:!0}),fe+=1;const t=u(n,`figure-${fe}.png`);return r(t,Buffer.from(e["image/png"],"base64")),me=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(te(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}function ke(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function ve(e){if(e)try{return l(e).mtimeMs}catch{return}}function $e(o){const n=R(o,a()),l=d(n)?n:h(process.cwd(),n);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=t(l,"utf8"),o=l.endsWith(".ipynb")?B(e):F(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:ve(l),diskSig:ke(o)},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}const _e={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const ge=E?.trim().toLowerCase().replace(/-demo$/,"");if(ge&&_e[ge]){const n=await async function(n){const l=_e[n],a=u(process.cwd(),"icoa-lab"),s=u(a,g(l));if(e(s))return console.log(chalk.gray(" Using your copy ")+chalk.cyan(s)+chalk.gray(" (edits kept — delete the file to start from the original).")),s;process.stdout.write(chalk.gray(" Fetching the demo notebook…"));const i=await ne(l);if(!i)return console.log(chalk.yellow(" not available right now.")),console.log(chalk.gray(" It needs one online moment — try ")+chalk.cyan(`ipynb ${n}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,t(i))}catch(e){return console.log(chalk.yellow(` could not write ${s}: ${e instanceof Error?e.message:String(e)}`)),null}return console.log(chalk.green(" saved ")+chalk.cyan(s)),s}(ge);if(!n)return;E=n}const fe=p(a()),be=u(a(),".icoa","ipynb-out");if(ae(),!e(fe.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const xe=E?$e(E):null,Pe=xe?xe.doc:{cells:[],path:null,dirty:!1};let Se=new I({venvPython:fe.python,venvRoot:fe.root}),Ee=null,Ce=null,Ge=null,je=pe(Pe.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Se.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),xe&&console.log(xe.note);let Ue=!1,Ae=!1;Q({id:"ipynb",title:{en:"Notebook",zh:"Notebook 笔记本"},what:{en:"A Jupyter notebook inside the terminal: cells run one by one in a live Python kernel. You are already inside it — never type python file.ipynb here.",zh:"终端里的 Jupyter notebook:cell 在常驻 Python 内核里逐格运行。你已经在 notebook 里面了 —— 不要再敲 python file.ipynb。"},steps:[{verb:"cells",what:{en:"list the cells (md = explanation, ○ = not run yet)",zh:"列出所有 cell(md = 讲解,○ = 还没跑)"},done:()=>Ue},{verb:"run all",what:{en:"run every cell top to bottom; stops at the first error",zh:"从头到尾跑每一格;遇到第一个报错就停"},done:()=>Pe.cells.some(e=>null!==e.result)},{verb:"edit",what:{en:"open the WHOLE notebook in your editor (edit 3 = one cell)",zh:"整本在编辑器里打开(edit 3 = 只开第 3 格)"},done:()=>Pe.dirty},{verb:"save",what:{en:"write it back to disk as a real .ipynb",zh:"存回磁盘,标准 .ipynb"},done:()=>Ae},{verb:"gpu on",what:{en:"run the cells on a GPU box (a T4 starts for you, ~1–2 min); gpu off hands it back",zh:"把 cell 搬到 GPU 上跑(T4 按需开机约 1–2 分钟);gpu off 归还"},done:()=>null!==Ee,optional:!0},{verb:"ai 4",what:{en:"ask the tutor why cell 4 did that (ai = the last error)",zh:"问导师第 4 格为什么这样(裸 ai = 最后一个报错)"},optional:!0}],notes:[{en:"Plain Python typed at the prompt runs as a new cell (a blank line ends a block). help all = every command.",zh:"直接敲 Python 就是新的一格(空行结束多行块)。help all = 全部命令。"}],leave:{verb:"quit",what:{en:"leave the notebook",zh:"离开 notebook"}},guide:()=>Je()});const Ie=O(),Ne=null!==Ie,Oe=Ne?Ie.listeners("line").slice():[];Ne&&Ie.removeAllListeners("line");const Te=Ne?Ie:c({input:process.stdin,output:process.stdout,terminal:!0});Ne||T(Te);const Me=Ne?Te.prompt:null,De=Ne?Te.getPrompt():"";Ne&&(Te.prompt=i.prototype.prompt),Ne||D();const qe=[];let Le,ze=!1,Ke=!1,Re=!1,Be=null,Fe=null;const We=()=>{if(Fe)return Te.setPrompt(chalk.bold.cyan(` editor 1-${Fe.options.length} > `)),void Te.prompt();const e=Ee?"icoa ipynb ⚡gpu":"icoa ipynb";Te.setPrompt(chalk.bold.cyan(qe.length?`${e} ...> `:`${e}> `)),Te.prompt()},Je=()=>{const o=Pe.path?y(Pe.path):process.cwd(),n=pe(Pe.path);let l="",r=!1;try{const e=JSON.parse(t(u(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Pe.cells.filter(e=>null!==e.result).length,s=e(u(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Pe.path?g(Pe.path):"new empty notebook")+chalk.gray(` · ${Pe.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Ee?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),n&&"icoa-holdout"===l?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("submit")+chalk.gray(" — scored + ranked right here, no need to leave (")+chalk.cyan("board")+chalk.gray(" shows standings)")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):n&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):n?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()};let Ve=()=>{};const Ye=new Promise(e=>{Ve=e}),He=async()=>{Se=new I({venvPython:fe.python,venvRoot:fe.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Se.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}},Xe=async(e,n=!1)=>{const t=H(e),l=S(t);if(l.length>0)return console.log(chalk.red(" committee seat file rejected: ")+chalk.gray(l.join(", "))),!1;const s=u(a(),".icoa","gputask","key");try{o(u(a(),".icoa","gputask"),{recursive:!0}),r(s,e.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),!1}const i=Pe.path?g(y(Pe.path)):"work",c=`${t.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=N(t.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new I({spawnSpec:{command:"ssh",args:P(t,s,d)},readyTimeoutMs:9e4});n||process.stdout.write(chalk.gray(` Connecting to your seat (${e.host})…`));try{await h.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" The box may be rebuilding (Spot reclaim) — ")+chalk.cyan("gpufortask")+chalk.gray(" shows the seat state; ")+chalk.cyan("gpu on")+chalk.gray(" again once it is ready.")),!1}await Se.shutdown().catch(()=>{}),Se=h,Ee={...t,outDir:c},Ge=e,Ce=Date.now(),h.onUnexpectedExit=()=>{Se===h&&(console.log(),console.log(chalk.bold.yellow(" ⚠ The GPU box went away (Spot reclaim or seat ended).")),console.log(chalk.gray(" Files are kept on the seat; variables are gone. ")+chalk.cyan("gpu on")+chalk.gray(" in 1–2 min reconnects (the seat is rebuilt automatically).")),Ee=null,Ge=null,Ce=null,He().then(()=>We()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${Z[e.tier]} · cells run in ${c}`));const p=await Ze();return p>0&&console.log(chalk.gray(` ${p} small file${1===p?"":"s"} from this notebook's folder sent to the box.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to rerun there · ")+chalk.cyan("upload <file>")+chalk.gray(" sends more · ")+chalk.cyan("download <file>")+chalk.gray(" brings results back · ")+chalk.cyan("gpu off")+chalk.gray(" returns to the local kernel (seat stays).")),!0},Ze=async()=>{if(!Pe.path||!Ee?.outDir)return 0;const e=y(Pe.path);let o=[];try{o=n(e)}catch{return 0}let r=0;for(const n of o){if(n.startsWith("."))continue;const o=u(e,n);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await Se.putFile(`${Ee.outDir}/${n}`,t(o)),r++}catch{}}return r},Qe=async e=>{const[n,...t]=e.trim().split(/\s+/),l=(n??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ee)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=X();if(e)return void await(async e=>{await Xe(e)})(e);const n=ue();if(!n)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));je||(je=pe(Pe.path));const t=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await he("lease",n,je??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-t)/1e3)} s`;for(;"queued"===l.state&&s<(l.bootStage||i?60:24);)l.bootStage&&(i=!0),0===s&&console.log(),process.stdout.write(`\r ${chalk.yellow(C(l))} `),await new Promise(e=>setTimeout(e,5e3)),l=await he("status",n),s++;if("queued"===l.state)return console.log(),void(i?(console.log(chalk.yellow(` The GPU box is still starting (${c()} so far) — your place is held.`)),console.log(chalk.gray(" Keep editing; ")+chalk.cyan("gpu on")+chalk.gray(" again in a minute picks it up."))):(console.log(chalk.yellow(" Still queued — your place is held server-side.")),console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."))));if(i&&"ready"===l.state&&(console.log(),console.log(chalk.green(` ✓ GPU box ready in ${c()}`)+chalk.gray(` · ${l.gpuName??"GPU"}${l.zone?` · ${l.zone}`:""} · built just for this session`))),"ready"!==l.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${l.message??"no lease granted"}`));const g=S(l);if("local"!==l.transport||process.env.ICOA_GPU_SERVER||g.push("local transport from a non-dev broker"),g.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(g.join(", "))),void await he("release",n);const y=je?`${l.dataRoot}/${je}`:l.dataRoot,d=N(l.python,{ICOA_KAGGLE_DATA:y,ICOA_KAGGLE_OUT:l.outDir},l.outDir);let h;if("local"===l.transport)h={command:"/bin/sh",args:["-c",d]};else{const e=u(a(),".icoa","gpu","lease-key");try{o(u(a(),".icoa","gpu"),{recursive:!0}),r(e,l.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await he("release",n)}h={command:"ssh",args:P(l,e,d)}}const p=new I({spawnSpec:h,readyTimeoutMs:9e4}),f=Date.now();process.stdout.write(chalk.gray(" connecting…"));try{await p.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),void await he("release",n)}await Se.shutdown().catch(()=>{}),Se=p,Ee=l,Ce=Date.now();const m=Math.round((l.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected")+chalk.gray(` (${Math.round((Date.now()-f)/1e3)} s).`)),console.log(chalk.gray(` Cells now run on the ${l.gpuName?`${l.gpuName} `:""}GPU box · ${m}m left on this lease.`));const w=G(l.windowCloseEpoch);w&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${w}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),je&&console.log(chalk.gray(` Dataset is already on the box (${je}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===l||"disconnect"===l?await(async()=>{if(Ee&&Ge){const e=Ce?Math.round((Date.now()-Ce)/1e3):0;return await Se.shutdown().catch(()=>{}),Ee=null,Ge=null,Ce=null,console.log(chalk.green(` ⚡ Back to the local kernel after ${Math.floor(e/60)} m ${e%60} s`)+chalk.gray(" — the seat stays open (files kept); ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now.")),void await He()}if(!Ee)return void console.log(chalk.gray(" not on a GPU kernel."));const e=ue(),o=void 0!==Ee.gpuName,n=Ce?Math.round((Date.now()-Ce)/1e3):0;await Se.shutdown().catch(()=>{}),e&&await he("release",e),Ee=null,Ce=null;const t=Math.floor(n/60),l=t>0?`${t} m ${n%60} s`:`${n} s`;console.log(chalk.green(` ⚡ GPU lease released after ${l}`)+chalk.gray(" — billing for you stopped.")),o&&console.log(chalk.gray(" The box recycles itself now that nobody holds it (")+chalk.cyan("gpu queue")+chalk.gray(" shows 0 boxes once it is gone); the next ")+chalk.cyan("gpu on")+chalk.gray(" builds a fresh one.")),await He()})():"status"===l||""===l?await(async()=>{const e=X();if(e)return console.log(chalk.green(` ⚡ committee seat · ${Z[e.tier]} · ${e.host}`)+chalk.gray(Ge?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=ue();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const n=await he("status",o);if("ready"===n.state){const e=Math.round((n.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Ee?" (this notebook is connected)":" (not connected here — gpu on)"));const o=G(n.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===n.state?console.log(chalk.yellow(` ${C(n)}`)):"none"===n.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${n.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=ue();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${ye()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await n.json();o=t.data??t}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,t="number"==typeof o.free?o.free:0,l=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${t} free`));const a=G("number"==typeof o.window_close_epoch?o.window_close_epoch:void 0);a&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${a}.`)),console.log(chalk.bold.white(" ▶ running now:")),0===l.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,t=Math.floor(n/60),l=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${t}:${l} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",t=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+t)}console.log()})():"key"===l?(e=>{const n=e.trim();if(n)try{o(u(a(),".icoa"),{recursive:!0}),r(de(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${de()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(t.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},eo=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Pe.cells.length?(console.log(0===Pe.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Pe.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Pe.cells[o-1],idx:o}},oo=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let no=!1;const to=()=>{const e=w().notebookEditor;return e?_(e):null},lo=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),ro=()=>to()??x(),ao={nano:"easiest — Ctrl+O save, Ctrl+X exit",code:"VS Code window — save, close the tab to come back",vi:"i to type, Esc then :wq to save and exit"},so=(e,o)=>{if(e){const n=_(e);return n?v(n.cmd)?(o(n),!0):(console.log(chalk.yellow(` ${$(n)} is not installed on this computer.`)+chalk.gray(" See the choices: ")+chalk.cyan("editor")),!0):(console.log(chalk.yellow(` unknown editor "${e}" — use `)+chalk.cyan("nano")+chalk.yellow(", ")+chalk.cyan("code")+chalk.yellow(" or ")+chalk.cyan("vi")),!0)}if(to()||lo())return o(ro()),!0;const n=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return n.length<2||!process.stdin.isTTY?(o(x()),!0):((e=>{console.log(),console.log(chalk.bold.white(" Which editor should edit / add open?")+chalk.gray(" (asked once)")),e.forEach((e,o)=>{const n=$(e);console.log(chalk.cyan(` ${o+1} ${n.padEnd(5)}`)+chalk.gray(` ${ao[n]??""}`)+("nano"===n?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(n),Fe={resume:o,tries:0,options:n},!1)},io=e=>{if(!Pe.path)return!1;let o;try{const e=t(Pe.path,"utf8");o=Pe.path.endsWith(".ipynb")?B(e):F(e)}catch(e){return console.log(chalk.yellow(" could not re-read the file: ")+chalk.gray(e instanceof Error?e.message:String(e))),!1}const n=K(Pe.cells,o);return Pe.cells=n.cells,Pe.dirty=!1,Pe.mtimeMs=ve(Pe.path),Pe.diskSig=ke(o),Le=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Pe.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${n.cells.length} cells, ${n.changed} changed`)+chalk.gray(n.kept?`, ${n.kept} kept their output.`:".")),console.log(chalk.gray(" variables stay in the kernel — run just the cells you changed, or ")+chalk.cyan("run all")),!0},co=()=>void 0!==Pe.diskSig?ke(Pe.cells)!==Pe.diskSig:Pe.dirty,go=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!U(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),yo=async n=>{if(n.trim()&&M(`ipynb: ${n.trim()}`),Ke)return void(n.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Fe){const e=Fe,o=n.trim().toLowerCase(),t=_(o),l=/^\d+$/.test(o)?e.options[Number(o)-1]:t?e.options.find(e=>$(e)===$(t)):void 0;return l?(Fe=null,b({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===o||["q","quit","back","cancel","exit"].includes(o)?(Fe=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Fe=null,console.log(chalk.gray(" no editor chosen — nothing changed. Choose later with ")+chalk.cyan("editor nano"))):console.log(chalk.yellow(` type a number 1-${e.options.length}, or a name: `)+chalk.cyan(e.options.map(e=>$(e)).join(" / "))),void We()}let l=n.trim();if(0===qe.length&&/^icoa\s+[a-z/]/i.test(l)&&(l=l.replace(/^icoa\s+/i,"")),0===qe.length){const n=l.split(/\s+/),i=(n[0]??"").toLowerCase(),c=l.slice(n[0]?.length??0).trim();if("quit"!==i&&"exit"!==i&&"q"!==i&&(Re=!1),Be&&i!==Be&&(Be=null),ie.has(i)&&(()=>{if(!Pe.path||void 0===Pe.mtimeMs)return;const e=ve(Pe.path);if(void 0!==e&&e!==Pe.mtimeMs){if(co()){if(Le===e)return;return Le=e,console.log(chalk.yellow(` ⚠ ${g(Pe.path)} changed in your editor, and this notebook has unsaved changes too.`)),void console.log(chalk.gray(" take the file: ")+chalk.cyan("reload")+chalk.gray(" · keep these and overwrite the file: ")+chalk.cyan("save"))}io(!0)}})(),"quit"===i||"exit"===i||"back"===i||"q"===i||"menu"===i)return Pe.dirty&&!Re?(Re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void We()):void await(async()=>{if(ee("ipynb"),Te.removeAllListeners("line"),Ne||q(),console.log(),Ee&&Ge)Ee=null,console.log(chalk.gray(" ⚡ Committee seat stays open (files kept) — ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now, or it closes after 40 min idle."));else if(Ee){const e=ue();e&&await he("release",e),Ee=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Se.shutdown().catch(()=>{}),Ne){Me&&(Te.prompt=Me),Te.setPrompt(De);for(const e of Oe)Te.on("line",e);Te.prompt(),Ve()}else T(null),Ve(),Te.close()})();if("clear"===i||"cls"===i)return console.clear(),ae(),void We();if("restart"===i)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Se.shutdown().catch(()=>{});try{await Se.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void We();if("help"===i||"?"===i)return/^(all|commands|full)$/i.test(c.trim())?(console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor vi")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(re()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" load <file>")+chalk.gray(" open another .ipynb / .py (drag the file into this window)")),console.log(chalk.cyan(" reload")+chalk.gray(" re-read the file — or just save in Jupyter / VS Code: the next run picks it up")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a GPU box — a GCP T4 starts for you on demand (~1–2 min), ")+chalk.cyan("gpu off")+chalk.gray(" hands it back")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" selfcheck")+chalk.gray(" committee seat: rerun the whole notebook fresh, measure peak GPU memory → capsule size, file the report")),console.log(chalk.cyan(" upload <f>")+chalk.gray(" send a file to the box (committee seat: files next to the notebook go up on gpu on)")),console.log(chalk.gray(" try it: ")+chalk.cyan("icoa> ipynb mnist")+chalk.gray(" — the MNIST demo notebook (edit → run → train on the T4 → gpu off)")),console.log(chalk.cyan(" check / submit")+chalk.gray(" verify / score your submission.csv — right here, no quit needed")),console.log(chalk.cyan(" board")+chalk.gray(" live standings for this competition")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log()):oe(),void We();if("guide"===i||"/guide"===i)return Je(),void We();if("python"===i||"python3"===i)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void We();if("open"===i&&""===c)return me&&te(me)?console.log(chalk.gray(" reopening ")+chalk.cyan(me)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void We();if("cells"===i||"ls"===i)return(()=>{if(Ue=!0,0===Pe.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);Pe.cells.forEach((o,n)=>{const t=V(o),l="✓"===t?chalk.green(t.padEnd(2)):"✗"===t?chalk.red(t.padEnd(2)):"md"===t?chalk.magenta(t.padEnd(2)):chalk.gray(t.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${l} ${chalk.white(L(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void We();if("show"===i)return(e=>{const o=eo(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of A(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),we(o.cell.result,be)),console.log()}})(c),void We();if("edit"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ").toLowerCase();return""===n||"all"===n?so(o,e=>(e=>{Te.pause();const o=k(Y(Pe.cells),".py",e,"notebook");if(Te.resume(),null===o)return void console.log(chalk.yellow(" editor cancelled or failed — notebook unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const n=z(o,Pe.cells);if(n.same)return void console.log(chalk.gray(" no changes."));if(0===n.cells.length&&Pe.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${Pe.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));Pe.cells=n.cells,Pe.dirty=!0;const t=[];n.changed.length&&t.push(`${n.changed.length} changed (${n.changed.join(", ")})`),n.added.length&&t.push(`${n.added.length} added (${n.added.join(", ")})`),n.deleted&&t.push(`${n.deleted} deleted`),n.reordered&&t.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${Pe.cells.length} cells`)+chalk.gray(` · ${t.join(" · ")}`));const l=[...n.changed,...n.added].filter(e=>"code"===Pe.cells[e-1].kind).sort((e,o)=>e-o);if(l.length){const e=l[0],o=l[l.length-1];console.log(chalk.gray(" unchanged cells kept their output · run what changed: ")+chalk.cyan(e===o?`run ${e}`:`run ${e}-${o}`)+chalk.gray(" · or ")+chalk.cyan("run all"))}})(e)):eo(n)&&so(o,e=>((e,o)=>{const n=eo(e);if(!n)return;Te.pause();const t=k(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(Te.resume(),null===t)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=t.replace(/\s+$/,"");l!==n.cell.source?(n.cell.source=l,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(n,e)),void We()}if("add"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ");return so(o,e=>((e,o)=>{const n=e.trim().toLowerCase(),t="md"===n||"markdown"===n||"text"===n||"txt"===n;if(n&&!t&&"py"!==n&&"code"!==n&&"python"!==n)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Te.pause();const l=k(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);Te.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Pe.cells.push({kind:t?"markdown":"code",source:r,result:null}),Pe.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${Pe.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Pe.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void We()}if("editor"===i&&/^[\w-]*$/.test(c))return(e=>{const o=e.trim().toLowerCase(),n=$(ro());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${to()?"saved":lo()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),t=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(t?` ${ao[e]}`:" not installed here")+(e===n?chalk.green(" ← now"):""))}return console.log(chalk.gray(" one edit only: ")+chalk.cyan("edit 3 nano")+chalk.gray(" · back to $EDITOR / vi: ")+chalk.cyan("editor default")),void console.log()}if("default"===o||"reset"===o||"off"===o)return b({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const t=_(o);if(!t)return void console.log(chalk.yellow(` unknown editor "${o}" — `)+chalk.cyan("editor nano")+chalk.yellow(" · ")+chalk.cyan("editor code")+chalk.yellow(" · ")+chalk.cyan("editor vi"));const l=$(t);to()&&$(to())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(t.cmd)?(b({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${n===l?"default":n}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(c),void We();if("reload"===i&&""===c)return Pe.path&&e(Pe.path)?co()&&"reload"!==Be?(Be="reload",console.log(chalk.yellow(" unsaved changes here will be replaced by the file — ")+chalk.cyan("reload")+chalk.yellow(" again to go ahead, or ")+chalk.cyan("save")+chalk.yellow(" first."))):(Be=null,io(!1)):console.log(chalk.gray(" nothing to reload — this notebook has no file yet (")+chalk.cyan("save")+chalk.gray(" first, or ")+chalk.cyan("load <file>")+chalk.gray(").")),void We();if("load"===i&&!/^[=(.[]/.test(c)||"open"===i&&""!==c){if(!c)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void We();const o=R(c,a()),n=d(o)?o:h(process.cwd(),o);if(e(n))if(Pe.dirty&&"load"!==Be)Be="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(i)+chalk.yellow(" again to discard them."));else{Be=null;const e=$e(n);Pe.cells=e.doc.cells,Pe.path=e.doc.path,Pe.dirty=!1,Pe.mtimeMs=e.doc.mtimeMs,Pe.diskSig=e.doc.diskSig,Le=void 0,je=pe(Pe.path),console.log(e.note),console.log(chalk.gray(" the kernel keeps its variables — ")+chalk.cyan("restart")+chalk.gray(" for a clean start."))}else console.log(chalk.yellow(" no such file: ")+chalk.white(n)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void We()}if("del"===i||"delete"===i)return(e=>{const o=eo(e);o&&(Pe.cells.splice(o.idx-1,1),Pe.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Pe.cells.length} left.`)+(o.idx<=Pe.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(c),void We();if(("md"===i||"py"===i)&&/^\d+$/.test(c))return((e,o)=>{const n=eo(e);if(!n)return;const t="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${t}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${t}.`))})(c,"md"===i?"markdown":"code"),void We();if("gpu"===i)return Ke=!0,await Qe(c),Ke=!1,void We();if("download"===i||"dl"===i)return Ke=!0,await(async e=>{if(!Ee)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${Ee.outDir}/${n}`;let l;try{l=await Se.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=je?u(process.cwd(),"icoa-kaggle",je):process.cwd(),s=u(a,g(n));try{o(a,{recursive:!0}),r(s,l)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(s)+chalk.gray(` (${l.length} bytes)`)),je&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${je}`)+chalk.gray(" — then upload on Kaggle yourself."))})(c),Ke=!1,void We();if("selfcheck"===i||"self-check"===i)return Ke=!0,await(async()=>{const e=Ge;if(!e||!Ee)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===Pe.cells.filter(e=>"code"===e.kind).length)return void console.log(chalk.yellow(" nothing to check — the notebook has no code cells."));console.log(chalk.bold.cyan(" 🔬 selfcheck")+chalk.gray(` · fresh kernel · ${Z[e.tier]} · every code cell from the top`));const o=Se;if(await Xe(e,!0),Se===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const n=Date.now(),t=[];let l=!1;for(let e=0;e<Pe.cells.length;e++){const o=Pe.cells[e];if("code"!==o.kind)continue;const n=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${n} … `));try{o.result=await Se.execute(o.source)}catch(e){t.push({n:n,ok:!1,ms:Date.now()-r,error:e instanceof Error?e.message:String(e)}),console.log(chalk.red("kernel error")),l=!0;break}Pe.dirty=!0;const a=Date.now()-r,s=o.result.outputs.find(e=>"error"===e.kind);if(t.push({n:n,ok:o.result.ok,ms:a,error:s&&"error"===s.kind?`${s.ename}: ${s.evalue}`:void 0}),console.log(o.result.ok?chalk.green(`ok ${(a/1e3).toFixed(1)} s`):chalk.red(`raised ${(a/1e3).toFixed(1)} s`)),!o.result.ok){we(o.result,be),l=!0;break}}const r=Date.now()-n,a=["import json as _j, os as _o, sys as _s, hashlib as _h, platform as _p",'_r = {"python": _s.version.split()[0], "platform": _p.platform()}',"try:"," import torch as _t",' _r["torch"] = _t.__version__'," if _t.cuda.is_available():",' _r["gpu"] = _t.cuda.get_device_name(0)',' _r["peak_gib"] = round(_t.cuda.max_memory_allocated() / 2**30, 3)',' _r["reserved_gib"] = round(_t.cuda.max_memory_reserved() / 2**30, 3)',"except Exception as _e:",' _r["torch"] = "n/a: %s" % _e','for _m in ("sklearn", "numpy", "pandas", "transformers"):'," try:"," _r[_m] = __import__(_m).__version__"," except Exception:"," pass",'_r["fence"] = _o.environ.get("CUDA_MPS_PINNED_DEVICE_MEM_LIMIT")','_r["units"] = _o.environ.get("ICOA_GPU_UNITS")','_r["files"] = {}','for _f in sorted(_o.listdir(".")):',' if _o.path.isfile(_f) and not _f.startswith("."):'," _sz = _o.path.getsize(_f)"," _d = _h.sha256()",' with open(_f, "rb") as _fh:',' for _c in iter(lambda: _fh.read(1 << 20), b""):'," _d.update(_c)",' _r["files"][_f] = {"bytes": _sz, "sha256": _d.hexdigest()[:16]}','print("ICOA_SELFCHECK " + _j.dumps(_r))'].join("\n");let s={};try{const e=(await Se.execute(a)).outputs.filter(e=>"stream"===e.kind).map(e=>"stream"===e.kind?e.text:"").join("").split("\n").find(e=>e.startsWith("ICOA_SELFCHECK "));e&&(s=JSON.parse(e.slice(15)))}catch{}const i="number"==typeof s.peak_gib?s.peak_gib:null,c=null===i?null:i<3?1:i<6.5?2:i<10?3:0,y={sid:e.sid,tier:e.tier,notebook:Pe.path?g(Pe.path):null,cells:t,ok:!l,wall_ms:r,env:s,peak_gib:i,units:c,ts:Math.floor(Date.now()/1e3)};console.log(),console.log((l?chalk.bold.red(" ✗ selfcheck: a cell raised"):chalk.bold.green(" ✓ selfcheck: every cell ran"))+chalk.gray(` · ${(r/1e3).toFixed(0)} s wall on a shared box (not a time limit)`)),null!==i?console.log(chalk.white(` peak GPU memory ${i.toFixed(2)} GiB`)+(c?chalk.green(` → ${c} capsule unit${c>1?"s":""}`)+chalk.gray(` (fence ${3.5*c} GiB, allocator cap ${(3.5*c-.5).toFixed(1)})`):chalk.red(" → exceeds 3 units (10 GiB cap) — the task must shrink"))):console.log(chalk.gray(" no GPU memory figure (torch not imported or no CUDA) — CPU task, or add a torch import.")),(s.gpu||s.torch)&&console.log(chalk.gray(` ${s.gpu??"no GPU"} · torch ${s.torch??"?"} · sklearn ${s.sklearn??"?"} · numpy ${s.numpy??"?"}`));const d=s.files??{},u=Object.keys(d);u.length>0&&console.log(chalk.gray(` ${u.length} data file${1===u.length?"":"s"} fingerprinted: ${u.slice(0,6).join(", ")}${u.length>6?", …":""}`));try{const o=await fetch(`${(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"")}/api/icoa/gputask/selfcheck`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,report:y}),signal:AbortSignal.timeout(2e4)});console.log(o.ok?chalk.gray(" report filed with the committee ✓"):chalk.yellow(` report not filed (http ${o.status}) — keep the numbers above.`))}catch{console.log(chalk.yellow(" report not filed (offline) — keep the numbers above."))}})(),Ke=!1,void We();if("upload"===i||"up"===i||"put"===i)return Ke=!0,await(async e=>{if(!Ee)return void console.log(chalk.gray(" local kernel — files are already here. ")+chalk.cyan("gpu on")+chalk.gray(" first."));const o=e.trim();if(!o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("upload <file>")+chalk.gray(" (≤ 20 MB; lands in the box work dir)"));const n=R(o,a()),l=d(n)?n:h(Pe.path?y(Pe.path):process.cwd(),n);let r;try{r=t(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${Ee.outDir}/${g(l)}`;try{const e=await Se.putFile(s,r);console.log(chalk.green(" ✓ uploaded ")+chalk.white(s)+chalk.gray(` (${e} bytes)`))}catch(e){console.log(chalk.yellow(" upload failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(c),Ke=!1,void We();if("check"===i||"submit"===i||"kaggle"===i){const e=await import("./kaggle.js"),o=c.split(/\s+/).filter(Boolean),n="kaggle"===i?(o[0]||"").toLowerCase():i,t=("kaggle"===i?o[1]:o[0])||pe(Pe.path)||void 0;Ke=!0;try{if("submit"===n){const o=s("sha256").update(Pe.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(t,{code_sha:o,...Ge?{sid:Ge.sid}:{},...Pe.path?{notebook:g(Pe.path)}:{}})}else"check"===n?await e.runKaggleCheck(t):"final"===n?await e.runKaggleFinal(t,o.slice(2)):"guide"===n?await e.runKaggleGuide(t):await e.runKaggle("kaggle"===i?o[0]:t)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ke=!1,void We()}if("board"===i){const{runBoard:e}=await import("./board.js"),o=c.split(/\s+/).filter(Boolean);Ke=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ke=!1,void We()}if("ai"===i||"/ai"===i)return Ke=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),n=o.length>0&&/^\d+$/.test(o[0]),l=(n?o.slice(1):o).join(" ").trim(),r=n?Number(o[0]):(()=>{for(let e=Pe.cells.length-1;e>=0;e--)if((Pe.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Pe.cells.length;if(0===Pe.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=eo(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(le,"")).join("\n")));return o.join("\n").replace(le,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Pe.path||!pe(Pe.path))return"";try{const e=JSON.parse(t(u(y(Pe.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return oo(o,350)}catch{return""}})(),c=re(),g=c?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",d=g.length+l.length+120,h=Math.max(400,f-d-i.length),p=oo(a.cell.source,Math.floor(.6*h)),w=s?(b=s,k=h-p.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[g,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${p}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",l?`\n[question]\n${l}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),_=c;console.log(),no||(no=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(re()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${re()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(re()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(re()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${f} chars`)+chalk.gray(_?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(_?" · 含输出":" · output included"):"")+($?chalk.yellow(_?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),M(`ipynb: ai ${a.idx}${l?` — ${l}`:""}`);const x=await m(v);if(console.log(),!x.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(x.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of A(x.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${_?"<你的问题>":"<your question>"}`)+chalk.gray(_?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(_?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(_?" 再跑一次":" run it again")),console.log(chalk.gray(_?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(c),Ke=!1,void We();if("run"===i)return Ke=!0,await(async e=>{const o=W(e,Pe.cells.length);if(o)for(const e of o){const n=Pe.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(L(n,50))+chalk.gray(" ──"));try{n.result=await Se.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void ce()}if(Pe.dirty=!0,we(n.result,be),go(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(re()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(re()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void ce()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(n.source))console.log(e);console.log()}}else console.log(0===Pe.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(c),Ke=!1,void We();if("save"===i)return(e=>{if(0===Pe.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?d(e.trim())?e.trim():h(process.cwd(),e.trim()):Pe.path?Pe.path.endsWith(".ipynb")?Pe.path:`${Pe.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===Pe.path?ve(o):void 0;if(void 0!==n&&void 0!==Pe.mtimeMs&&n!==Pe.mtimeMs&&"save"!==Be)return Be="save",console.log(chalk.yellow(` ${g(o)} was changed in your editor after this notebook read it.`)),void console.log(chalk.gray(" ")+chalk.cyan("save")+chalk.gray(" again to overwrite those changes · ")+chalk.cyan("reload")+chalk.gray(" to take the file instead"));Be=null;try{r(o,J(Pe.cells)),Pe.path=o,Ae=!0,Pe.dirty=!1,Pe.mtimeMs=ve(o),Pe.diskSig=ke(Pe.cells),Le=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Pe.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(c),void We();if(""===l)return void We()}if(qe.length>0&&se.has(l.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(l.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void We();if(qe.push(n),!j(qe))return 1!==qe.length||ze||(ze=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void We();const i=qe.join("\n").replace(/\s+$/,"");if(qe.length=0,""!==i.trim()){Ke=!0;try{const e=await Se.execute(i);Pe.cells.push({kind:"code",source:i,result:e}),Pe.dirty=!0,we(e,be);const o=go(Pe.cells[Pe.cells.length-1],Pe.cells.length);e.ok||o||ce()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),ce()}Ke=!1,We()}else We()};Te.on("line",e=>{yo(e)}),Ne||Te.on("close",async()=>{await Se.shutdown().catch(()=>{}),process.exit(0)}),We(),await Ye}
|