icoa-cli 2.19.689 → 2.19.690
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/ipynb.js +1 -1
- package/dist/lib/gemini.js +1 -1
- package/dist/lib/guide-panel.js +1 -1
- package/dist/repl.js +1 -1
- package/package.json +1 -1
package/dist/commands/ipynb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as o,readdirSync as n,readFileSync as t,statSync as l,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{createHash as s}from"node:crypto";import{Interface as i,createInterface as c}from"node:readline";import{basename as g,dirname as y,isAbsolute as d,join as u,resolve as h}from"node:path";import chalk from"chalk";import{aienvPaths as p}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as f,askIoaiOneShot as m}from"./ai4ioai.js";import{getConfig as w,saveConfig as b}from"../lib/config.js";import{editTextInEditor as k,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as S,parseLeaseResponse as E,queueLine as C,windowLine as G}from"../lib/gpu.js";import{shouldExecuteCell as j}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{NotebookKernel as I,buildRemoteBridgeCommand as N}from"../lib/kernel.js";import{getMainRl as 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}
|
|
1
|
+
import{existsSync as e,mkdirSync as o,readdirSync as n,readFileSync as t,statSync as l,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{createHash as s}from"node:crypto";import{Interface as i,createInterface as c}from"node:readline";import{basename as g,dirname as y,isAbsolute as d,join as u,resolve as h}from"node:path";import chalk from"chalk";import{aienvPaths as p}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as f,askIoaiOneShot as m}from"./ai4ioai.js";import{getConfig as w,saveConfig as b}from"../lib/config.js";import{editTextInEditor as k,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as S,parseLeaseResponse as E,queueLine as C,windowLine as G}from"../lib/gpu.js";import{shouldExecuteCell as j}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{NotebookKernel as I,buildRemoteBridgeCommand as N}from"../lib/kernel.js";import{getMainRl as T,setMainRl as O}from"../lib/main-rl.js";import{logCommand as M}from"../lib/logger.js";import{startLogSync as D,stopLogSync as q}from"../lib/log-sync.js";import{cellPreview as L,fromWholeEditText as z,mergeReloadedCells as K,normalizePathArg as R,parseIpynb as B,parsePercentPy as F,parseRunRange as W,serializeIpynb as J,statusChar as V,toWholeEditText as Y}from"../lib/notebook-doc.js";import{committeeLease as H,readCommitteeSession as X,TIER_LABEL as Z}from"../lib/gputask-session.js";import{enterPanel as Q,leavePanel as ee,printHelp as oe}from"../lib/guide-panel.js";import{lazyFile as ne}from"../lib/lazy-assets.js";import{openFile as te}from"../lib/open-file.js";const le=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function re(){return(w().language||"en").toLowerCase().startsWith("zh")}export function registerIpynbCommand(e){e.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async e=>{await runIpynb(e)})}function ae(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const se=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),ie=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function ce(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const ge="https://practice.icoa2026.au";function ye(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):ge}function de(){return u(a(),".icoa","gpu-key")}function ue(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return t(de(),"utf-8").trim()||null}catch{return null}}async function he(e,o,n){try{const t=await fetch(`${ye()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await t.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function pe(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let fe=0,me=null;function we(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(le,"")}`))}else"display"===n.kind&&be(n.data,o)}function be(e,n){if(e["image/png"])try{o(n,{recursive:!0}),fe+=1;const t=u(n,`figure-${fe}.png`);return r(t,Buffer.from(e["image/png"],"base64")),me=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(te(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}function ke(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function ve(e){if(e)try{return l(e).mtimeMs}catch{return}}function $e(o){const n=R(o,a()),l=d(n)?n:h(process.cwd(),n);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=t(l,"utf8"),o=l.endsWith(".ipynb")?B(e):F(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:ve(l),diskSig:ke(o)},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}const _e={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const ge=E?.trim().toLowerCase().replace(/-demo$/,"");if(ge&&_e[ge]){const n=await async function(n){const l=_e[n],a=u(process.cwd(),"icoa-lab"),s=u(a,g(l));if(e(s))return console.log(chalk.gray(" Using your copy ")+chalk.cyan(s)+chalk.gray(" (edits kept — delete the file to start from the original).")),s;process.stdout.write(chalk.gray(" Fetching the demo notebook…"));const i=await ne(l);if(!i)return console.log(chalk.yellow(" not available right now.")),console.log(chalk.gray(" It needs one online moment — try ")+chalk.cyan(`ipynb ${n}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,t(i))}catch(e){return console.log(chalk.yellow(` could not write ${s}: ${e instanceof Error?e.message:String(e)}`)),null}return console.log(chalk.green(" saved ")+chalk.cyan(s)),s}(ge);if(!n)return;E=n}const fe=p(a()),be=u(a(),".icoa","ipynb-out");if(ae(),!e(fe.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const xe=E?$e(E):null,Pe=xe?xe.doc:{cells:[],path:null,dirty:!1};let Se=new I({venvPython:fe.python,venvRoot:fe.root}),Ee=null,Ce=null,Ge=null,je=pe(Pe.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Se.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),xe&&console.log(xe.note);let Ue=!1,Ae=!1;Q({id:"ipynb",title:{en:"Notebook",zh:"Notebook 笔记本"},what:{en:"A Jupyter notebook inside the terminal: cells run one by one in a live Python kernel. You are already inside it — never type python file.ipynb here.",zh:"终端里的 Jupyter notebook:cell 在常驻 Python 内核里逐格运行。你已经在 notebook 里面了 —— 不要再敲 python file.ipynb。"},steps:[{verb:"cells",what:{en:"list the cells (md = explanation, ○ = not run yet)",zh:"列出所有 cell(md = 讲解,○ = 还没跑)"},done:()=>Ue},{verb:"run all",what:{en:"run every cell top to bottom; stops at the first error",zh:"从头到尾跑每一格;遇到第一个报错就停"},done:()=>Pe.cells.some(e=>null!==e.result)},{verb:"edit",what:{en:"open the WHOLE notebook in your editor (edit 3 = one cell)",zh:"整本在编辑器里打开(edit 3 = 只开第 3 格)"},done:()=>Pe.dirty},{verb:"save",what:{en:"write it back to disk as a real .ipynb",zh:"存回磁盘,标准 .ipynb"},done:()=>Ae},{verb:"gpu on",what:{en:"run the cells on a GPU box (a T4 starts for you, ~1–2 min); gpu off hands it back",zh:"把 cell 搬到 GPU 上跑(T4 按需开机约 1–2 分钟);gpu off 归还"},done:()=>null!==Ee,optional:!0},{verb:"ai 4",what:{en:"ask the tutor why cell 4 did that (ai = the last error)",zh:"问导师第 4 格为什么这样(裸 ai = 最后一个报错)"},optional:!0}],notes:[{en:"Plain Python typed at the prompt runs as a new cell (a blank line ends a block). help all = every command.",zh:"直接敲 Python 就是新的一格(空行结束多行块)。help all = 全部命令。"}],leave:{verb:"quit",what:{en:"leave the notebook",zh:"离开 notebook"}},guide:()=>Je()});const Ie=T(),Ne=null!==Ie,Te=Ne?Ie.listeners("line").slice():[];Ne&&Ie.removeAllListeners("line");const Oe=Ne?Ie:c({input:process.stdin,output:process.stdout,terminal:!0});Ne||O(Oe);const Me=Ne?Oe.prompt:null,De=Ne?Oe.getPrompt():"";Ne&&(Oe.prompt=i.prototype.prompt),Ne||D();const qe=[];let Le,ze=!1,Ke=!1,Re=!1,Be=null,Fe=null;const We=()=>{if(Fe)return Oe.setPrompt(chalk.bold.cyan(` editor 1-${Fe.options.length} > `)),void Oe.prompt();const e=Ee?"icoa ipynb ⚡gpu":"icoa ipynb";Oe.setPrompt(chalk.bold.cyan(qe.length?`${e} ...> `:`${e}> `)),Oe.prompt()},Je=()=>{const o=Pe.path?y(Pe.path):process.cwd(),n=pe(Pe.path);let l="",r=!1;try{const e=JSON.parse(t(u(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Pe.cells.filter(e=>null!==e.result).length,s=e(u(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(Pe.path?g(Pe.path):"new empty notebook")+chalk.gray(` · ${Pe.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),Ee?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(n?" — trains the baseline, writes submission.csv":" — runs every cell top to bottom")),n&&"icoa-holdout"===l?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("submit")+chalk.gray(" — scored + ranked right here, no need to leave (")+chalk.cyan("board")+chalk.gray(" shows standings)")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):n&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):n?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()};let Ve=()=>{};const Ye=new Promise(e=>{Ve=e}),He=async()=>{Se=new I({venvPython:fe.python,venvRoot:fe.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Se.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}},Xe=async(e,n=!1)=>{const t=H(e),l=S(t);if(l.length>0)return console.log(chalk.red(" committee seat file rejected: ")+chalk.gray(l.join(", "))),!1;const s=u(a(),".icoa","gputask","key");try{o(u(a(),".icoa","gputask"),{recursive:!0}),r(s,e.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),!1}const i=Pe.path?g(y(Pe.path)):"work",c=`${t.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=N(t.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new I({spawnSpec:{command:"ssh",args:P(t,s,d)},readyTimeoutMs:9e4});n||process.stdout.write(chalk.gray(` Connecting to your seat (${e.host})…`));try{await h.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" The box may be rebuilding (Spot reclaim) — ")+chalk.cyan("gpufortask")+chalk.gray(" shows the seat state; ")+chalk.cyan("gpu on")+chalk.gray(" again once it is ready.")),!1}await Se.shutdown().catch(()=>{}),Se=h,Ee={...t,outDir:c},Ge=e,Ce=Date.now(),h.onUnexpectedExit=()=>{Se===h&&(console.log(),console.log(chalk.bold.yellow(" ⚠ The GPU box went away (Spot reclaim or seat ended).")),console.log(chalk.gray(" Files are kept on the seat; variables are gone. ")+chalk.cyan("gpu on")+chalk.gray(" in 1–2 min reconnects (the seat is rebuilt automatically).")),Ee=null,Ge=null,Ce=null,He().then(()=>We()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${Z[e.tier]} · cells run in ${c}`));const p=await Ze();return p>0&&console.log(chalk.gray(` ${p} small file${1===p?"":"s"} from this notebook's folder sent to the box.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to rerun there · ")+chalk.cyan("upload <file>")+chalk.gray(" sends more · ")+chalk.cyan("download <file>")+chalk.gray(" brings results back · ")+chalk.cyan("gpu off")+chalk.gray(" returns to the local kernel (seat stays).")),!0},Ze=async()=>{if(!Pe.path||!Ee?.outDir)return 0;const e=y(Pe.path);let o=[];try{o=n(e)}catch{return 0}let r=0;for(const n of o){if(n.startsWith("."))continue;const o=u(e,n);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await Se.putFile(`${Ee.outDir}/${n}`,t(o)),r++}catch{}}return r},Qe=async e=>{const[n,...t]=e.trim().split(/\s+/),l=(n??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ee)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=X();if(e)return void await(async e=>{await Xe(e)})(e);const n=ue();if(!n)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));je||(je=pe(Pe.path));const t=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await he("lease",n,je??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-t)/1e3)} s`;for(;"queued"===l.state&&s<(l.bootStage||i?60:24);)l.bootStage&&(i=!0),0===s&&console.log(),process.stdout.write(`\r ${chalk.yellow(C(l))} `),await new Promise(e=>setTimeout(e,5e3)),l=await he("status",n),s++;if("queued"===l.state)return console.log(),void(i?(console.log(chalk.yellow(` The GPU box is still starting (${c()} so far) — your place is held.`)),console.log(chalk.gray(" Keep editing; ")+chalk.cyan("gpu on")+chalk.gray(" again in a minute picks it up."))):(console.log(chalk.yellow(" Still queued — your place is held server-side.")),console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."))));if(i&&"ready"===l.state&&(console.log(),console.log(chalk.green(` ✓ GPU box ready in ${c()}`)+chalk.gray(` · ${l.gpuName??"GPU"}${l.zone?` · ${l.zone}`:""} · built just for this session`))),"ready"!==l.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${l.message??"no lease granted"}`));const g=S(l);if("local"!==l.transport||process.env.ICOA_GPU_SERVER||g.push("local transport from a non-dev broker"),g.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(g.join(", "))),void await he("release",n);const y=je?`${l.dataRoot}/${je}`:l.dataRoot,d=N(l.python,{ICOA_KAGGLE_DATA:y,ICOA_KAGGLE_OUT:l.outDir},l.outDir);let h;if("local"===l.transport)h={command:"/bin/sh",args:["-c",d]};else{const e=u(a(),".icoa","gpu","lease-key");try{o(u(a(),".icoa","gpu"),{recursive:!0}),r(e,l.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await he("release",n)}h={command:"ssh",args:P(l,e,d)}}const p=new I({spawnSpec:h,readyTimeoutMs:9e4}),f=Date.now();process.stdout.write(chalk.gray(" connecting…"));try{await p.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),void await he("release",n)}await Se.shutdown().catch(()=>{}),Se=p,Ee=l,Ce=Date.now();const m=Math.round((l.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected")+chalk.gray(` (${Math.round((Date.now()-f)/1e3)} s).`)),console.log(chalk.gray(` Cells now run on the ${l.gpuName?`${l.gpuName} `:""}GPU box · ${m}m left on this lease.`));const w=G(l.windowCloseEpoch);w&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${w}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),je&&console.log(chalk.gray(` Dataset is already on the box (${je}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===l||"disconnect"===l?await(async()=>{if(Ee&&Ge){const e=Ce?Math.round((Date.now()-Ce)/1e3):0;return await Se.shutdown().catch(()=>{}),Ee=null,Ge=null,Ce=null,console.log(chalk.green(` ⚡ Back to the local kernel after ${Math.floor(e/60)} m ${e%60} s`)+chalk.gray(" — the seat stays open (files kept); ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now.")),void await He()}if(!Ee)return void console.log(chalk.gray(" not on a GPU kernel."));const e=ue(),o=void 0!==Ee.gpuName,n=Ce?Math.round((Date.now()-Ce)/1e3):0;await Se.shutdown().catch(()=>{}),e&&await he("release",e),Ee=null,Ce=null;const t=Math.floor(n/60),l=t>0?`${t} m ${n%60} s`:`${n} s`;console.log(chalk.green(` ⚡ GPU lease released after ${l}`)+chalk.gray(" — billing for you stopped.")),o&&console.log(chalk.gray(" The box recycles itself now that nobody holds it (")+chalk.cyan("gpu queue")+chalk.gray(" shows 0 boxes once it is gone); the next ")+chalk.cyan("gpu on")+chalk.gray(" builds a fresh one.")),await He()})():"status"===l||""===l?await(async()=>{const e=X();if(e)return console.log(chalk.green(` ⚡ committee seat · ${Z[e.tier]} · ${e.host}`)+chalk.gray(Ge?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=ue();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const n=await he("status",o);if("ready"===n.state){const e=Math.round((n.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Ee?" (this notebook is connected)":" (not connected here — gpu on)"));const o=G(n.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===n.state?console.log(chalk.yellow(` ${C(n)}`)):"none"===n.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${n.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=ue();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${ye()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await n.json();o=t.data??t}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,t="number"==typeof o.free?o.free:0,l=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${t} free`));const a=G("number"==typeof o.window_close_epoch?o.window_close_epoch:void 0);a&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${a}.`)),console.log(chalk.bold.white(" ▶ running now:")),0===l.length&&console.log(chalk.gray(0===n?" (no box up — gpu on starts a T4 for you, ~1–2 min)":" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,t=Math.floor(n/60),l=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${t}:${l} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",t=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+t)}console.log()})():"key"===l?(e=>{const n=e.trim();if(n)try{o(u(a(),".icoa"),{recursive:!0}),r(de(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${de()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(t.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},eo=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Pe.cells.length?(console.log(0===Pe.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Pe.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Pe.cells[o-1],idx:o}},oo=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let no=!1;const to=()=>{const e=w().notebookEditor;return e?_(e):null},lo=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),ro=()=>to()??x(),ao={nano:"easiest — Ctrl+O save, Ctrl+X exit",code:"VS Code window — save, close the tab to come back",vi:"i to type, Esc then :wq to save and exit"},so=(e,o)=>{if(e){const n=_(e);return n?v(n.cmd)?(o(n),!0):(console.log(chalk.yellow(` ${$(n)} is not installed on this computer.`)+chalk.gray(" See the choices: ")+chalk.cyan("editor")),!0):(console.log(chalk.yellow(` unknown editor "${e}" — use `)+chalk.cyan("nano")+chalk.yellow(", ")+chalk.cyan("code")+chalk.yellow(" or ")+chalk.cyan("vi")),!0)}if(to()||lo())return o(ro()),!0;const n=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return n.length<2||!process.stdin.isTTY?(o(x()),!0):((e=>{console.log(),console.log(chalk.bold.white(" Which editor should edit / add open?")+chalk.gray(" (asked once)")),e.forEach((e,o)=>{const n=$(e);console.log(chalk.cyan(` ${o+1} ${n.padEnd(5)}`)+chalk.gray(` ${ao[n]??""}`)+("nano"===n?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(n),Fe={resume:o,tries:0,options:n},!1)},io=e=>{if(!Pe.path)return!1;let o;try{const e=t(Pe.path,"utf8");o=Pe.path.endsWith(".ipynb")?B(e):F(e)}catch(e){return console.log(chalk.yellow(" could not re-read the file: ")+chalk.gray(e instanceof Error?e.message:String(e))),!1}const n=K(Pe.cells,o);return Pe.cells=n.cells,Pe.dirty=!1,Pe.mtimeMs=ve(Pe.path),Pe.diskSig=ke(o),Le=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Pe.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${n.cells.length} cells, ${n.changed} changed`)+chalk.gray(n.kept?`, ${n.kept} kept their output.`:".")),console.log(chalk.gray(" variables stay in the kernel — run just the cells you changed, or ")+chalk.cyan("run all")),!0},co=()=>void 0!==Pe.diskSig?ke(Pe.cells)!==Pe.diskSig:Pe.dirty,go=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!U(e.source)||(console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(").")),0)),yo=async n=>{if(n.trim()&&M(`ipynb: ${n.trim()}`),Ke)return void(n.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Fe){const e=Fe,o=n.trim().toLowerCase(),t=_(o),l=/^\d+$/.test(o)?e.options[Number(o)-1]:t?e.options.find(e=>$(e)===$(t)):void 0;return l?(Fe=null,b({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===o||["q","quit","back","cancel","exit"].includes(o)?(Fe=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Fe=null,console.log(chalk.gray(" no editor chosen — nothing changed. Choose later with ")+chalk.cyan("editor nano"))):console.log(chalk.yellow(` type a number 1-${e.options.length}, or a name: `)+chalk.cyan(e.options.map(e=>$(e)).join(" / "))),void We()}let l=n.trim();if(0===qe.length&&/^icoa\s+[a-z/]/i.test(l)&&(l=l.replace(/^icoa\s+/i,"")),0===qe.length){const n=l.split(/\s+/),i=(n[0]??"").toLowerCase(),c=l.slice(n[0]?.length??0).trim();if("quit"!==i&&"exit"!==i&&"q"!==i&&(Re=!1),Be&&i!==Be&&(Be=null),ie.has(i)&&(()=>{if(!Pe.path||void 0===Pe.mtimeMs)return;const e=ve(Pe.path);if(void 0!==e&&e!==Pe.mtimeMs){if(co()){if(Le===e)return;return Le=e,console.log(chalk.yellow(` ⚠ ${g(Pe.path)} changed in your editor, and this notebook has unsaved changes too.`)),void console.log(chalk.gray(" take the file: ")+chalk.cyan("reload")+chalk.gray(" · keep these and overwrite the file: ")+chalk.cyan("save"))}io(!0)}})(),"quit"===i||"exit"===i||"back"===i||"q"===i||"menu"===i)return Pe.dirty&&!Re?(Re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void We()):void await(async()=>{if(ee("ipynb"),Oe.removeAllListeners("line"),Ne||q(),console.log(),Ee&&Ge)Ee=null,console.log(chalk.gray(" ⚡ Committee seat stays open (files kept) — ")+chalk.cyan("gpufortask")+chalk.gray(" → ")+chalk.cyan("stop")+chalk.gray(" ends it now, or it closes after 40 min idle."));else if(Ee){const e=ue();e&&await he("release",e),Ee=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Se.shutdown().catch(()=>{}),Ne){Me&&(Oe.prompt=Me),Oe.setPrompt(De);for(const e of Te)Oe.on("line",e);Oe.prompt(),Ve()}else O(null),Ve(),Oe.close()})();if("clear"===i||"cls"===i)return console.clear(),ae(),void We();if("restart"===i)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Se.shutdown().catch(()=>{});try{await Se.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void We();if("help"===i||"?"===i)return/^(all|commands|full)$/i.test(c.trim())?(console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor vi")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(re()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" load <file>")+chalk.gray(" open another .ipynb / .py (drag the file into this window)")),console.log(chalk.cyan(" reload")+chalk.gray(" re-read the file — or just save in Jupyter / VS Code: the next run picks it up")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a GPU box — a GCP T4 starts for you on demand (~1–2 min), ")+chalk.cyan("gpu off")+chalk.gray(" hands it back")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" selfcheck")+chalk.gray(" committee seat: rerun the whole notebook fresh, measure peak GPU memory → capsule size, file the report")),console.log(chalk.cyan(" upload <f>")+chalk.gray(" send a file to the box (committee seat: files next to the notebook go up on gpu on)")),console.log(chalk.gray(" try it: ")+chalk.cyan("icoa> ipynb mnist")+chalk.gray(" — the MNIST demo notebook (edit → run → train on the T4 → gpu off)")),console.log(chalk.cyan(" check / submit")+chalk.gray(" verify / score your submission.csv — right here, no quit needed")),console.log(chalk.cyan(" board")+chalk.gray(" live standings for this competition")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log()):oe(),void We();if("guide"===i||"/guide"===i)return Je(),void We();if("python"===i||"python3"===i)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void We();if("open"===i&&""===c)return me&&te(me)?console.log(chalk.gray(" reopening ")+chalk.cyan(me)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void We();if("cells"===i||"ls"===i)return(()=>{if(Ue=!0,0===Pe.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);Pe.cells.forEach((o,n)=>{const t=V(o),l="✓"===t?chalk.green(t.padEnd(2)):"✗"===t?chalk.red(t.padEnd(2)):"md"===t?chalk.magenta(t.padEnd(2)):chalk.gray(t.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${l} ${chalk.white(L(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void We();if("show"===i)return(e=>{const o=eo(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of A(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),we(o.cell.result,be)),console.log()}})(c),void We();if("edit"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ").toLowerCase();return""===n||"all"===n?so(o,e=>(e=>{Oe.pause();const o=k(Y(Pe.cells),".py",e,"notebook");if(Oe.resume(),null===o)return void console.log(chalk.yellow(" editor cancelled or failed — notebook unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const n=z(o,Pe.cells);if(n.same)return void console.log(chalk.gray(" no changes."));if(0===n.cells.length&&Pe.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${Pe.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));Pe.cells=n.cells,Pe.dirty=!0;const t=[];n.changed.length&&t.push(`${n.changed.length} changed (${n.changed.join(", ")})`),n.added.length&&t.push(`${n.added.length} added (${n.added.join(", ")})`),n.deleted&&t.push(`${n.deleted} deleted`),n.reordered&&t.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${Pe.cells.length} cells`)+chalk.gray(` · ${t.join(" · ")}`));const l=[...n.changed,...n.added].filter(e=>"code"===Pe.cells[e-1].kind).sort((e,o)=>e-o);if(l.length){const e=l[0],o=l[l.length-1];console.log(chalk.gray(" unchanged cells kept their output · run what changed: ")+chalk.cyan(e===o?`run ${e}`:`run ${e}-${o}`)+chalk.gray(" · or ")+chalk.cyan("run all"))}})(e)):eo(n)&&so(o,e=>((e,o)=>{const n=eo(e);if(!n)return;Oe.pause();const t=k(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(Oe.resume(),null===t)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=t.replace(/\s+$/,"");l!==n.cell.source?(n.cell.source=l,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(n,e)),void We()}if("add"===i){const e=c.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ");return so(o,e=>((e,o)=>{const n=e.trim().toLowerCase(),t="md"===n||"markdown"===n||"text"===n||"txt"===n;if(n&&!t&&"py"!==n&&"code"!==n&&"python"!==n)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Oe.pause();const l=k(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);Oe.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Pe.cells.push({kind:t?"markdown":"code",source:r,result:null}),Pe.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${Pe.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Pe.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void We()}if("editor"===i&&/^[\w-]*$/.test(c))return(e=>{const o=e.trim().toLowerCase(),n=$(ro());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${to()?"saved":lo()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),t=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(t?` ${ao[e]}`:" not installed here")+(e===n?chalk.green(" ← now"):""))}return console.log(chalk.gray(" one edit only: ")+chalk.cyan("edit 3 nano")+chalk.gray(" · back to $EDITOR / vi: ")+chalk.cyan("editor default")),void console.log()}if("default"===o||"reset"===o||"off"===o)return b({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const t=_(o);if(!t)return void console.log(chalk.yellow(` unknown editor "${o}" — `)+chalk.cyan("editor nano")+chalk.yellow(" · ")+chalk.cyan("editor code")+chalk.yellow(" · ")+chalk.cyan("editor vi"));const l=$(t);to()&&$(to())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(t.cmd)?(b({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${n===l?"default":n}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(c),void We();if("reload"===i&&""===c)return Pe.path&&e(Pe.path)?co()&&"reload"!==Be?(Be="reload",console.log(chalk.yellow(" unsaved changes here will be replaced by the file — ")+chalk.cyan("reload")+chalk.yellow(" again to go ahead, or ")+chalk.cyan("save")+chalk.yellow(" first."))):(Be=null,io(!1)):console.log(chalk.gray(" nothing to reload — this notebook has no file yet (")+chalk.cyan("save")+chalk.gray(" first, or ")+chalk.cyan("load <file>")+chalk.gray(").")),void We();if("load"===i&&!/^[=(.[]/.test(c)||"open"===i&&""!==c){if(!c)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void We();const o=R(c,a()),n=d(o)?o:h(process.cwd(),o);if(e(n))if(Pe.dirty&&"load"!==Be)Be="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(i)+chalk.yellow(" again to discard them."));else{Be=null;const e=$e(n);Pe.cells=e.doc.cells,Pe.path=e.doc.path,Pe.dirty=!1,Pe.mtimeMs=e.doc.mtimeMs,Pe.diskSig=e.doc.diskSig,Le=void 0,je=pe(Pe.path),console.log(e.note),console.log(chalk.gray(" the kernel keeps its variables — ")+chalk.cyan("restart")+chalk.gray(" for a clean start."))}else console.log(chalk.yellow(" no such file: ")+chalk.white(n)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void We()}if("del"===i||"delete"===i)return(e=>{const o=eo(e);o&&(Pe.cells.splice(o.idx-1,1),Pe.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Pe.cells.length} left.`)+(o.idx<=Pe.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(c),void We();if(("md"===i||"py"===i)&&/^\d+$/.test(c))return((e,o)=>{const n=eo(e);if(!n)return;const t="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${t}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${t}.`))})(c,"md"===i?"markdown":"code"),void We();if("gpu"===i)return Ke=!0,await Qe(c),Ke=!1,void We();if("download"===i||"dl"===i)return Ke=!0,await(async e=>{if(!Ee)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${Ee.outDir}/${n}`;let l;try{l=await Se.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=je?u(process.cwd(),"icoa-kaggle",je):process.cwd(),s=u(a,g(n));try{o(a,{recursive:!0}),r(s,l)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(s)+chalk.gray(` (${l.length} bytes)`)),je&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${je}`)+chalk.gray(" — then upload on Kaggle yourself."))})(c),Ke=!1,void We();if("selfcheck"===i||"self-check"===i)return Ke=!0,await(async()=>{const e=Ge;if(!e||!Ee)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===Pe.cells.filter(e=>"code"===e.kind).length)return void console.log(chalk.yellow(" nothing to check — the notebook has no code cells."));console.log(chalk.bold.cyan(" 🔬 selfcheck")+chalk.gray(` · fresh kernel · ${Z[e.tier]} · every code cell from the top`));const o=Se;if(await Xe(e,!0),Se===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const n=Date.now(),t=[];let l=!1;for(let e=0;e<Pe.cells.length;e++){const o=Pe.cells[e];if("code"!==o.kind)continue;const n=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${n} … `));try{o.result=await Se.execute(o.source)}catch(e){t.push({n:n,ok:!1,ms:Date.now()-r,error:e instanceof Error?e.message:String(e)}),console.log(chalk.red("kernel error")),l=!0;break}Pe.dirty=!0;const a=Date.now()-r,s=o.result.outputs.find(e=>"error"===e.kind);if(t.push({n:n,ok:o.result.ok,ms:a,error:s&&"error"===s.kind?`${s.ename}: ${s.evalue}`:void 0}),console.log(o.result.ok?chalk.green(`ok ${(a/1e3).toFixed(1)} s`):chalk.red(`raised ${(a/1e3).toFixed(1)} s`)),!o.result.ok){we(o.result,be),l=!0;break}}const r=Date.now()-n,a=["import json as _j, os as _o, sys as _s, hashlib as _h, platform as _p",'_r = {"python": _s.version.split()[0], "platform": _p.platform()}',"try:"," import torch as _t",' _r["torch"] = _t.__version__'," if _t.cuda.is_available():",' _r["gpu"] = _t.cuda.get_device_name(0)',' _r["peak_gib"] = round(_t.cuda.max_memory_allocated() / 2**30, 3)',' _r["reserved_gib"] = round(_t.cuda.max_memory_reserved() / 2**30, 3)',"except Exception as _e:",' _r["torch"] = "n/a: %s" % _e','for _m in ("sklearn", "numpy", "pandas", "transformers"):'," try:"," _r[_m] = __import__(_m).__version__"," except Exception:"," pass",'_r["fence"] = _o.environ.get("CUDA_MPS_PINNED_DEVICE_MEM_LIMIT")','_r["units"] = _o.environ.get("ICOA_GPU_UNITS")','_r["files"] = {}','for _f in sorted(_o.listdir(".")):',' if _o.path.isfile(_f) and not _f.startswith("."):'," _sz = _o.path.getsize(_f)"," _d = _h.sha256()",' with open(_f, "rb") as _fh:',' for _c in iter(lambda: _fh.read(1 << 20), b""):'," _d.update(_c)",' _r["files"][_f] = {"bytes": _sz, "sha256": _d.hexdigest()[:16]}','print("ICOA_SELFCHECK " + _j.dumps(_r))'].join("\n");let s={};try{const e=(await Se.execute(a)).outputs.filter(e=>"stream"===e.kind).map(e=>"stream"===e.kind?e.text:"").join("").split("\n").find(e=>e.startsWith("ICOA_SELFCHECK "));e&&(s=JSON.parse(e.slice(15)))}catch{}const i="number"==typeof s.peak_gib?s.peak_gib:null,c=null===i?null:i<3?1:i<6.5?2:i<10?3:0,y={sid:e.sid,tier:e.tier,notebook:Pe.path?g(Pe.path):null,cells:t,ok:!l,wall_ms:r,env:s,peak_gib:i,units:c,ts:Math.floor(Date.now()/1e3)};console.log(),console.log((l?chalk.bold.red(" ✗ selfcheck: a cell raised"):chalk.bold.green(" ✓ selfcheck: every cell ran"))+chalk.gray(` · ${(r/1e3).toFixed(0)} s wall on a shared box (not a time limit)`)),null!==i?console.log(chalk.white(` peak GPU memory ${i.toFixed(2)} GiB`)+(c?chalk.green(` → ${c} capsule unit${c>1?"s":""}`)+chalk.gray(` (fence ${3.5*c} GiB, allocator cap ${(3.5*c-.5).toFixed(1)})`):chalk.red(" → exceeds 3 units (10 GiB cap) — the task must shrink"))):console.log(chalk.gray(" no GPU memory figure (torch not imported or no CUDA) — CPU task, or add a torch import.")),(s.gpu||s.torch)&&console.log(chalk.gray(` ${s.gpu??"no GPU"} · torch ${s.torch??"?"} · sklearn ${s.sklearn??"?"} · numpy ${s.numpy??"?"}`));const d=s.files??{},u=Object.keys(d);u.length>0&&console.log(chalk.gray(` ${u.length} data file${1===u.length?"":"s"} fingerprinted: ${u.slice(0,6).join(", ")}${u.length>6?", …":""}`));try{const o=await fetch(`${(process.env.ICOA_GPUTASK_SERVER||"https://practice.icoa2026.au").replace(/\/$/,"")}/api/icoa/gputask/selfcheck`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,report:y}),signal:AbortSignal.timeout(2e4)});console.log(o.ok?chalk.gray(" report filed with the committee ✓"):chalk.yellow(` report not filed (http ${o.status}) — keep the numbers above.`))}catch{console.log(chalk.yellow(" report not filed (offline) — keep the numbers above."))}})(),Ke=!1,void We();if("upload"===i||"up"===i||"put"===i)return Ke=!0,await(async e=>{if(!Ee)return void console.log(chalk.gray(" local kernel — files are already here. ")+chalk.cyan("gpu on")+chalk.gray(" first."));const o=e.trim();if(!o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("upload <file>")+chalk.gray(" (≤ 20 MB; lands in the box work dir)"));const n=R(o,a()),l=d(n)?n:h(Pe.path?y(Pe.path):process.cwd(),n);let r;try{r=t(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${Ee.outDir}/${g(l)}`;try{const e=await Se.putFile(s,r);console.log(chalk.green(" ✓ uploaded ")+chalk.white(s)+chalk.gray(` (${e} bytes)`))}catch(e){console.log(chalk.yellow(" upload failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(c),Ke=!1,void We();if("check"===i||"submit"===i||"kaggle"===i){const e=await import("./kaggle.js"),o=c.split(/\s+/).filter(Boolean),n="kaggle"===i?(o[0]||"").toLowerCase():i,t=("kaggle"===i?o[1]:o[0])||pe(Pe.path)||void 0;Ke=!0;try{if("submit"===n){const o=s("sha256").update(Pe.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(t,{code_sha:o,...Ge?{sid:Ge.sid}:{},...Pe.path?{notebook:g(Pe.path)}:{}})}else"check"===n?await e.runKaggleCheck(t):"final"===n?await e.runKaggleFinal(t,o.slice(2)):"guide"===n?await e.runKaggleGuide(t):await e.runKaggle("kaggle"===i?o[0]:t)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ke=!1,void We()}if("board"===i){const{runBoard:e}=await import("./board.js"),o=c.split(/\s+/).filter(Boolean);Ke=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ke=!1,void We()}if("ai"===i||"/ai"===i)return Ke=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),n=o.length>0&&/^\d+$/.test(o[0]),l=(n?o.slice(1):o).join(" ").trim(),r=n?Number(o[0]):(()=>{for(let e=Pe.cells.length-1;e>=0;e--)if((Pe.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Pe.cells.length;if(0===Pe.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=eo(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(le,"")).join("\n")));return o.join("\n").replace(le,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Pe.path||!pe(Pe.path))return"";try{const e=JSON.parse(t(u(y(Pe.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return oo(o,350)}catch{return""}})(),c=re(),g=c?"你在帮一个 IOAI 选手调试 notebook。先说清楚这一格为什么会这样,再给出最小改动。用中文回答,简洁,给可直接粘回去的代码。":"You are helping an IOAI contestant debug a notebook cell. Say why it behaves this way, then give the smallest fix. Be concise and give code that can be pasted straight back.",d=g.length+l.length+120,h=Math.max(400,f-d-i.length),p=oo(a.cell.source,Math.floor(.6*h)),w=s?(b=s,k=h-p.length,b.length<=k?b:`…(${b.length-k} chars elided)…\n${b.slice(-k)}`):"";var b,k;const v=[g,i?`\n[task]\n${i}`:"",`\n[cell ${a.idx} code]\n${p}`,w?`\n[cell ${a.idx} output]\n${w}`:"\n(this cell has not been run yet)",l?`\n[question]\n${l}`:""].filter(Boolean).join("\n"),$=v.includes("chars elided"),_=c;console.log(),no||(no=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(re()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${re()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(re()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(re()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${f} chars`)+chalk.gray(_?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(_?" · 含输出":" · output included"):"")+($?chalk.yellow(_?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),M(`ipynb: ai ${a.idx}${l?` — ${l}`:""}`);const x=await m(v);if(console.log(),!x.ok)return console.log(chalk.yellow(" AI 现在连不上 —— ")+chalk.gray(x.text)),console.log(chalk.gray(" 过一会儿再试,或用 ")+chalk.cyan("ai4ioai")+chalk.gray(" 单开一个会话。")),void console.log();for(const e of A(x.text))console.log(e);console.log(),console.log(chalk.gray(" ")+chalk.cyan(`ai ${a.idx} ${_?"<你的问题>":"<your question>"}`)+chalk.gray(_?" 追问 · ":" follow up · ")+chalk.cyan(`edit ${a.idx}`)+chalk.gray(_?" 改这一格 · ":" edit it · ")+chalk.cyan(`run ${a.idx}`)+chalk.gray(_?" 再跑一次":" run it again")),console.log(chalk.gray(_?" 这是调试助手(超限自动裁剪);想练现场那堵墙用 ":" This is the debugging aid (it trims to fit). To train against the real wall: ")+chalk.cyan("ai4ioai")),console.log()})(c),Ke=!1,void We();if("run"===i)return Ke=!0,await(async e=>{const o=W(e,Pe.cells.length);if(o)for(const e of o){const n=Pe.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(L(n,50))+chalk.gray(" ──"));try{n.result=await Se.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void ce()}if(Pe.dirty=!0,we(n.result,be),go(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(re()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(re()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void ce()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(n.source))console.log(e);console.log()}}else console.log(0===Pe.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(c),Ke=!1,void We();if("save"===i)return(e=>{if(0===Pe.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?d(e.trim())?e.trim():h(process.cwd(),e.trim()):Pe.path?Pe.path.endsWith(".ipynb")?Pe.path:`${Pe.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===Pe.path?ve(o):void 0;if(void 0!==n&&void 0!==Pe.mtimeMs&&n!==Pe.mtimeMs&&"save"!==Be)return Be="save",console.log(chalk.yellow(` ${g(o)} was changed in your editor after this notebook read it.`)),void console.log(chalk.gray(" ")+chalk.cyan("save")+chalk.gray(" again to overwrite those changes · ")+chalk.cyan("reload")+chalk.gray(" to take the file instead"));Be=null;try{r(o,J(Pe.cells)),Pe.path=o,Ae=!0,Pe.dirty=!1,Pe.mtimeMs=ve(o),Pe.diskSig=ke(Pe.cells),Le=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Pe.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(c),void We();if(""===l)return void We()}if(qe.length>0&&se.has(l.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(l.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void We();if(qe.push(n),!j(qe))return 1!==qe.length||ze||(ze=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void We();const i=qe.join("\n").replace(/\s+$/,"");if(qe.length=0,""!==i.trim()){Ke=!0;try{const e=await Se.execute(i);Pe.cells.push({kind:"code",source:i,result:e}),Pe.dirty=!0,we(e,be);const o=go(Pe.cells[Pe.cells.length-1],Pe.cells.length);e.ok||o||ce()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),ce()}Ke=!1,We()}else We()};Oe.on("line",e=>{yo(e)}),Ne||Oe.on("close",async()=>{await Se.shutdown().catch(()=>{}),process.exit(0)}),We(),await Ye}
|
package/dist/lib/gemini.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{readFileSync as e}from"node:fs";import{dirname as t,join as n}from"node:path";import{fileURLToPath as o}from"node:url";import{getConfig as a,saveConfig as r}from"./config.js";import{getRealExamState as s}from"./exam-state.js";import{EXAM_SERVER as i}from"./exam-server.js";const c=t(o(import.meta.url));let l=null;function u(){if(l)return l;try{const t=JSON.parse(e(n(c,"..","..","package.json"),"utf-8"));l=t.version||"unknown"}catch{l="unknown"}return l}export async function translateText(e,t){throw new Error("Local AI model path has been disabled (2026-04-24). ICOA provides all AI server-side — no API key setup needed. Use `ai4ctf` (chat) or `exam` (with integrated help/hint) instead.")}export function setApiKey(e){r({geminiApiKey:e})}export async function createChatSession(e,t){const n=a();let o=t||"You are an AI teammate in the ICOA cybersecurity CTF competition (International Cyber Olympiad in AI
|
|
1
|
+
import chalk from"chalk";import{readFileSync as e}from"node:fs";import{dirname as t,join as n}from"node:path";import{fileURLToPath as o}from"node:url";import{getConfig as a,saveConfig as r}from"./config.js";import{getRealExamState as s}from"./exam-state.js";import{EXAM_SERVER as i}from"./exam-server.js";const c=t(o(import.meta.url));let l=null;function u(){if(l)return l;try{const t=JSON.parse(e(n(c,"..","..","package.json"),"utf-8"));l=t.version||"unknown"}catch{l="unknown"}return l}export async function translateText(e,t){throw new Error("Local AI model path has been disabled (2026-04-24). ICOA provides all AI server-side — no API key setup needed. Use `ai4ctf` (chat) or `exam` (with integrated help/hint) instead.")}export function setApiKey(e){r({geminiApiKey:e})}export async function createChatSession(e,t){const n=a();let o=t||"You are an AI teammate in the ICOA cybersecurity CTF competition (International Cyber Olympiad in AI).\n\nYou're a friendly, knowledgeable cybersecurity partner — like a fellow competitor sitting next to the user. Be conversational, encouraging, and collaborative.\n\nRULES:\n- Help the competitor think through challenges, brainstorm approaches, explain concepts\n- You MAY discuss vulnerability types, tools, techniques, and methodologies\n- You MAY suggest approaches and help debug code\n- Do NOT provide complete working exploits or full solution scripts\n- Do NOT provide flags or flag fragments\n- Never output anything matching flag format: icoa{...}\n- If you don't know something, say so honestly\n- Keep responses concise unless the user asks for detail\n- When the user opens a challenge, use the context to give relevant advice";e&&(o+=`\n\nThe competitor is currently working on:\nChallenge: ${e.name}\nCategory: ${e.category}`),o+='\n\nINTEGRITY — give method, not the produced answer:\n- You may name the tool/command/technique (e.g. "this is base64; run base64 -d on the file").\n- Do NOT perform a solution step for the competitor and hand back its result: never decode,\n decrypt, deobfuscate, run, execute, or compute over data they paste or that is attached,\n and then reveal the produced value. They must run it themselves and read the output.\n- Do NOT reveal the exact final answer, and never output icoa{...} / flag{...} in any case.\n- If asked to "just give the answer" / "solve it" / "decode this and tell me", refuse and\n nudge them to do the step themselves.';const r=n.ctfdUrl||"https://practice.icoa2026.au",c=n.deviceFingerprint||"",l=n.geminiModel||"gemini-2.5-flash-lite",p=[];return{async sendMessage(e){p.push({role:"user",text:e});const t=s(),a={systemPrompt:o,messages:p,model:l,maxTokens:2048,deviceFingerprint:c};t?.session?.token&&(a.examToken=t.session.token);const d={"Content-Type":"application/json","User-Agent":`icoa-cli/${u()}`,"X-Device-Fingerprint":c};!a.examToken&&n.ctfdUrl&&n.token&&n.userName&&(a.account=n.userName,d.Authorization=`Token ${n.token}`);const h=e=>new Promise(t=>setTimeout(t,e)),m=[2e3,5e3],g=a.examToken?i:r;let f=null,y=null;for(let e=0;e<=m.length&&(f=await fetch(`${g}/api/icoa/ai/chat`,{method:"POST",headers:d,body:JSON.stringify(a),signal:AbortSignal.timeout(6e4)}),!f.ok&&429===f.status);e++)e<m.length?await h(m[e]):y=f;if(!f)throw new Error("AI proxy: no response");if(!f.ok){const e=(await f.json().catch(()=>({message:"AI proxy error"}))).message||`AI proxy returned ${f.status}`;if(401===f.status)throw new Error(`${chalk.yellow("⚠ ")}Exam token expired. Re-enter via \`exam <token>\`.`);if(403===f.status)throw new Error(chalk.yellow("⚠ ")+e);if(429===f.status)throw new Error(chalk.yellow("⏳ ")+e+chalk.gray(" (retried twice — quota burst, try again in ~30s)"));throw new Error(e)}const w=await f.json(),v=function(e){return e.replace(/icoa\{[^}]*\}/gi,"[FLAG REDACTED]")}(w.data?.text||""),k=w.data?.tokensUsed||0,x="number"==typeof w.data?.accountSpent?w.data.accountSpent:void 0,b="number"==typeof w.data?.accountCap?w.data.accountCap:void 0;return p.push({role:"model",text:v}),{text:v,tokensUsed:k,accountSpent:x,accountCap:b}}}}
|
package/dist/lib/guide-panel.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as r}from"node:fs";import{homedir as o}from"node:os";import{dirname as s,join as c}from"node:path";import chalk from"chalk";import{getConfig as i}from"./config.js";export function uiLang(){const e=(i().language||"en").toLowerCase();return e.startsWith("zh")?"zh":e.startsWith("th")?"th":"en"}export function tx(e,t=uiLang()){return"string"==typeof e?e:("zh"===t?e.zh:"th"===t?e.th:void 0)??e.en}export function asciiOnly(){if("1"===process.env.ICOA_ASCII)return!0;const e=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"";return""!==e&&!/utf-?8/i.test(e)}export function dw(e){let t=0;for(const n of e.replace(u,"")){const e=n.codePointAt(0)??0;3633===e||e>=3636&&e<=3642||e>=3655&&e<=3662||(t+=e>65535||e>=11904&&e<=42191||e>=44032&&e<=55203||e>=63744&&e<=64255?2:1)}return t}function a(e,t){const n=dw(e);return n>=t
|
|
1
|
+
import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as r}from"node:fs";import{homedir as o}from"node:os";import{dirname as s,join as c}from"node:path";import chalk from"chalk";import{getConfig as i}from"./config.js";export function uiLang(){const e=(i().language||"en").toLowerCase();return e.startsWith("zh")?"zh":e.startsWith("th")?"th":"en"}export function tx(e,t=uiLang()){return"string"==typeof e?e:("zh"===t?e.zh:"th"===t?e.th:void 0)??e.en}export function asciiOnly(){if("1"===process.env.ICOA_ASCII)return!0;const e=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"";return""!==e&&!/utf-?8/i.test(e)}export function dw(e){let t=0;for(const n of e.replace(u,"")){const e=n.codePointAt(0)??0;3633===e||e>=3636&&e<=3642||e>=3655&&e<=3662||(t+=e>65535||e>=11904&&e<=42191||e>=44032&&e<=55203||e>=63744&&e<=64255?2:1)}return t}function a(e,t){const n=dw(e);return n>=t?`${e} `:e+" ".repeat(t-n)}export function wrapText(e,t){const n=[];for(const r of e.split("\n")){const e=r.match(/[⺀-가-힣豈-]|\S+\s*|\s+/g)??[];let o="";for(const r of e){const e=/^[,.;:!?)\]}、。,;:!?)】」』…]/.test(r);o&&!e&&dw(o)+dw(r.trimEnd())>t&&(n.push(o.trimEnd()),o=""),o+=r}n.push(o.trimEnd())}return n}const u=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function l(){return process.env.ICOA_SEEN_FILE||c(o(),".icoa","seen-surfaces.json")}function p(){try{const e=JSON.parse(n(l(),"utf8"));return e&&"object"==typeof e?e:{}}catch{return{}}}export function seenBefore(e){return"1"!==process.env.ICOA_FRESH&&e in p()}export function markSeen(n){if("1"!==process.env.ICOA_FRESH)try{const o=l(),c=p();if(c[n])return;c[n]=(new Date).toISOString(),e(s(o))||t(s(o),{recursive:!0}),r(o,`${JSON.stringify(c,null,1)}\n`)}catch{}}const f={readMe:{en:"read me first",zh:"先读这个",th:"อ่านก่อน"},next:{en:"next, type:",zh:"下一步敲:",th:"ขั้นต่อไป พิมพ์:"},help:{en:"help = these steps",zh:"help = 这些步骤",th:"help = ขั้นตอนนี้"},guide:{en:"guide = full sheet",zh:"guide = 完整说明",th:"guide = คู่มือเต็ม"},leave:{en:"leave",zh:"离开",th:"ออก"},done:{en:"all steps done — explore, or",zh:"步骤都做完了 —— 自由探索,或",th:"ทำครบแล้ว — ลองเล่น หรือ"},optional:{en:"optional",zh:"可选",th:"ไม่บังคับ"}};export function currentNext(e){if(e.next)return e.next();for(const t of e.steps)if(!(t.optional||t.done&&t.done()))return t.verb;return null}export function renderPanel(e,t,n){const r=n?.lang??uiLang(),o=n?.ascii??asciiOnly(),s=e=>tx(e,r),c=o?"":"📖 ",i=o?"":"🧭 ",u=o?">":"▸",l=o?"<-":"↩",p=currentNext(e),h=e.helpWord??"help",$=e.leave??{verb:"back",what:f.leave},d=`${c}${s(e.title)}`;if("compact"===t){const t=p?`${chalk.gray(` ${u} ${s(f.next)} `)}${chalk.bold.green(p)}`:`${chalk.gray(` ${u} ${s(f.done)} `)}${chalk.cyan($.verb)}`,n=s(f.help).replace(/^help/,h),r=` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${n}${e.guide?` · ${s(f.guide)}`:""}`)}`;if(dw(r)<=80)return[r];const o=` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${n}`)}`;return[dw(o)<=80?o:` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${h}`)}`]}const g=[];g.push(` ${chalk.bold.white(d)}${chalk.gray(` — ${s(f.readMe)}`)}`);for(const t of wrapText(s(e.what),76))g.push(chalk.gray(` ${t}`));const x=Math.min(18,Math.max(6,...e.steps.map(e=>dw(e.verb))))+2;e.steps.forEach((e,t)=>{const n=null!==p&&e.verb===p,r=!n&&!0===e.done?.(),c=n?chalk.bold.green(o?"> ":"▸ "):r?chalk.green(o?"[x]":"✅"):e.optional?chalk.gray(o?" - ":" ·"):chalk.gray(o?"[ ]":"○ "),i=n?chalk.bold.green(a(e.verb,x)):chalk.cyan(a(e.verb,x)),u=wrapText(s(e.what)+(e.optional?chalk.gray(` (${s(f.optional)})`):""),68-x);g.push(` ${chalk.white(String(t+1).padStart(2))} ${c} ${i}${chalk.gray(u[0]??"")}`);for(const e of u.slice(1))g.push(`${" ".repeat(10+x)}${chalk.gray(e)}`)});for(const t of e.notes??[])for(const e of wrapText(s(t),74))g.push(chalk.gray(` ${e}`));const y=p?` ${chalk.bold.green(`${u} ${s(f.next)} ${p}`)}`:` ${chalk.gray(`${u} ${s(f.done)} `)}${chalk.cyan($.verb)}`;return g.push(`${y}${chalk.gray(` ${l} ${$.verb} · ${i}${h}${e.guide?" · guide":""}`)}`),g}export function footerLine(e,t){const n=t?.lang??uiLang(),r=t?.ascii??asciiOnly(),o=e=>tx(e,n),s=r?">":"▸",c=r?"<-":"↩",i=r?"":"🧭 ",a=currentNext(e),u=e.leave??{verb:"back",what:f.leave};return` ${a?chalk.bold.green(`${s} ${o(f.next)} ${a}`):`${chalk.gray(`${s} ${o(f.done)} `)}${chalk.cyan(u.verb)}`}${chalk.gray(` ${c} ${u.verb} · ${i}${e.helpWord??"help"}`)}`}const h=[];export function currentSurface(){return h.length?h[h.length-1]:null}export function enterPanel(e,t){const n=currentSurface();n&&n.id===e.id&&h.pop(),h.push(e);const r=t?.mode??(seenBefore(e.id)?"compact":"full");if(!t?.quiet){console.log();for(const t of renderPanel(e,r))console.log(t);console.log()}return markSeen(e.id),r}export function leavePanel(e){if(!e)return void h.pop();const t=h.map(e=>e.id).lastIndexOf(e);t>=0&&h.splice(t,1)}export function printHelp(){const e=currentSurface();if(!e)return!1;console.log();for(const t of renderPanel(e,"full"))console.log(t);return console.log(),!0}export function printGuide(){const e=currentSurface();return!!e&&(e.guide?(console.log(),e.guide(),console.log(),!0):printHelp())}const $=new Set(["help","/help","?","/?","h","帮助","帮助我","ช่วย"]),d=new Set(["guide","/guide","howto","how","说明","怎么玩","คู่มือ"]);export function isHelpWord(e){return $.has(e.trim().toLowerCase())}export function isGuideWord(e){return d.has(e.trim().toLowerCase())}
|