icoa-cli 2.19.688 → 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.
@@ -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}
@@ -1 +1 @@
1
- import chalk from"chalk";import e from"@inquirer/input";import o from"@inquirer/select";import{getConfig as n,saveConfig as t}from"../lib/config.js";import{setApiKey as i}from"../lib/gemini.js";import{printSuccess as r,printError as a,printInfo as s,printHeader as c,printKeyValue as l}from"../lib/ui.js";import{logCommand as u}from"../lib/logger.js";import{envToolCounts as p}from"./env.js";import{defaultProbes as g,ladder as m,needsFor as d,nextRung as v,renderLadder as y}from"../lib/setup-ladder.js";const f=["python","mujoco","aienv","exam","env"];let h=null;export function registerSetupCommand(e){h=e,e.command("setup [what...]").description("Setup ladder: what this machine has, what to install (setup python|mujoco|aienv|exam|env|all)").action(async(e=[])=>{await runSetupVerb(e.join(" "))})}export async function runSetupVerb(e,o={}){const t=e.trim().toLowerCase();if("config"===t||"wizard"===t||"settings"===t)return void await runSetupWizard();u(`setup ${t||"ladder"}`);const i=(n().language||"en").toLowerCase().startsWith("zh");if(""===t||"status"===t||"ladder"===t||"help"===t||"?"===t)return void printSetupLadder({...o,probeEnv:!1});if("all"===t){const e=m(g({probeEnv:p})),n=d(o.curriculumId).filter(o=>"ok"!==e.find(e=>e.id===o)?.state);if(!o.curriculumId)return console.log(chalk.gray(i?" 不在课程里,不知道你需要哪几段 —— 用 setup <段名> 逐段装。":" Not inside a course, so I cannot tell which rungs you need — use setup <rung> one at a time.")),void printSetupLadder({...o,probeEnv:!1});if(0===n.length)return void console.log(chalk.green(i?" ✓ 这门课需要的都装好了。":" ✓ Everything this course needs is installed."));console.log(chalk.gray(i?` 按顺序安装:${n.join(" → ")}`:` Installing in order: ${n.join(" → ")}`));for(const e of n)await w(e);return void printSetupLadder({...o,probeEnv:!1})}const r=f.find(e=>e===t||`${e} setup`===t||t===`${e}-setup`)??("mojoco"===t?"mujoco":"ai"===t||"ml"===t?"aienv":"tools"===t||"ctf"===t?"env":null);r?(await w(r),printSetupLadder({...o,probeEnv:"env"===r})):console.log(chalk.yellow(i?` 不认识「${e.trim()}」。`:` Unknown rung "${e.trim()}".`)+chalk.gray(" setup python · mujoco · aienv · exam · env · all"))}export function printSetupLadder(e={}){const o=(n().language||"en").toLowerCase().startsWith("zh"),t=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"",i=""!==t&&!/utf-?8/i.test(t),r=e.probeEnv?p:void 0,a=m(g({probeEnv:r}));console.log();for(const n of y(a,{curriculumId:e.curriculumId,zh:o,ascii:i,inLearn:e.inLearn}))console.log(n);console.log()}export function nextSetupRung(e){return v(m(g()),d(e))?.id??null}async function w(e){switch(e){case"python":{const{runSetup:e}=await import("./python.js");return void await e()}case"mujoco":{const{runMujocoSetup:e}=await import("./mujoco.js");return void await e()}case"aienv":{const{runAienvSetup:e}=await import("./aienv.js");return void await e(!1)}case"exam":case"env":return h?void await h.parseAsync(["node","icoa",e,"setup"]):void console.log(chalk.yellow(` type: ${e} setup`))}}export async function runSetupWizard(){{u("setup");const p=n();c("ICOA CLI Setup"),console.log(),console.log(chalk.gray(" Tip: press ")+chalk.cyan("Ctrl+C")+chalk.gray(" any time to cancel setup and return to the ")+chalk.cyan("icoa>")+chalk.gray(" prompt — nothing is saved until you confirm.")),console.log(),l("CTFd URL",p.ctfdUrl||chalk.gray("Not configured")),l("CTFd Token",p.token?chalk.green("Configured"):chalk.gray("Not configured")),l("Gemini API Key",p.geminiApiKey||process.env.GEMINI_API_KEY?chalk.green("Configured"):chalk.gray("Not configured")),l("Language",p.language),l("Mode",p.mode||chalk.gray("Not set")),l("Session ID",`${p.sessionId.substring(0,8)}...`),console.log();try{switch(await o({message:"What would you like to configure?",choices:[{name:"Switch Mode",value:"mode"},{name:"Gemini API Key",value:"gemini"},{name:"CTFd Connection",value:"ctfd"},{name:"View All Settings",value:"view"},{name:"Exit",value:"exit"}]})){case"mode":{const e=await o({message:"Select mode:",choices:[{name:"National Selection — demo, exam, lightweight",value:"selection"},{name:"International Olympiad — Full CTF with AI assistance",value:"olympiad"},{name:"National/Regional Partner — Organizer management",value:"organizer"}]});t({mode:e}),r(`Mode switched to: ${e}. Restart ICOA CLI to apply.`);break}case"gemini":{console.log(),s("Get your API key from: https://aistudio.google.com/apikey"),console.log();const o=await e({message:"Enter Gemini API Key:"});o.trim()?(i(o.trim()),r("Gemini API key saved.")):a("No key provided.");break}case"ctfd":s('Use "join <url>" to connect to a CTFd instance.');break;case"view":{console.log(),c("Full Configuration");const e=n();for(const[o,n]of Object.entries(e))l(o,"token"===o&&n||"geminiApiKey"===o&&n?`${n.toString().substring(0,8)}...`:String(n??"null"));console.log();break}}console.log(),console.log(chalk.gray(" Setup complete. You are back at the ")+chalk.cyan("icoa>")+chalk.gray(" prompt.")),console.log()}catch(e){if("ExitPromptError"===e?.name)return console.log(),console.log(chalk.gray(" Setup cancelled. You are back at the ")+chalk.cyan("icoa>")+chalk.gray(" prompt. Nothing was saved.")),void console.log();throw e}}}
1
+ import chalk from"chalk";import e from"@inquirer/input";import o from"@inquirer/select";import{getConfig as n,saveConfig as t}from"../lib/config.js";import{setApiKey as i}from"../lib/gemini.js";import{printSuccess as r,printError as a,printInfo as s,printHeader as c,printKeyValue as l}from"../lib/ui.js";import{logCommand as u}from"../lib/logger.js";import{envToolCounts as p}from"./env.js";import{defaultProbes as g,ladder as m,needsFor as d,nextRung as v,renderLadder as y}from"../lib/setup-ladder.js";const f=["python","mujoco","aienv","env"];let h=null;export function registerSetupCommand(e){h=e,e.command("setup [what...]").description("Setup ladder: what this machine has, what to install (setup python|mujoco|aienv|env|all)").action(async(e=[])=>{await runSetupVerb(e.join(" "))})}export async function runSetupVerb(e,o={}){const t=e.trim().toLowerCase();if("config"===t||"wizard"===t||"settings"===t)return void await runSetupWizard();u(`setup ${t||"ladder"}`);const i=(n().language||"en").toLowerCase().startsWith("zh");if(""===t||"status"===t||"ladder"===t||"help"===t||"?"===t)return void printSetupLadder({...o,probeEnv:!1});if("all"===t){const e=m(g({probeEnv:p})),n=d(o.curriculumId).filter(o=>"ok"!==e.find(e=>e.id===o)?.state);if(!o.curriculumId)return console.log(chalk.gray(i?" 不在课程里,不知道你需要哪几段 —— 用 setup <段名> 逐段装。":" Not inside a course, so I cannot tell which rungs you need — use setup <rung> one at a time.")),void printSetupLadder({...o,probeEnv:!1});if(0===n.length)return void console.log(chalk.green(i?" ✓ 这门课需要的都装好了。":" ✓ Everything this course needs is installed."));console.log(chalk.gray(i?` 按顺序安装:${n.join(" → ")}`:` Installing in order: ${n.join(" → ")}`));for(const e of n)await w(e);return void printSetupLadder({...o,probeEnv:!1})}const r=f.find(e=>e===t||`${e} setup`===t||t===`${e}-setup`)??("mojoco"===t?"mujoco":"ai"===t||"ml"===t?"aienv":"tools"===t||"ctf"===t?"env":null);r?(await w(r),printSetupLadder({...o,probeEnv:"env"===r})):console.log(chalk.yellow(i?` 不认识「${e.trim()}」。`:` Unknown rung "${e.trim()}".`)+chalk.gray(" setup python · mujoco · aienv · env · all"))}export function printSetupLadder(e={}){const o=(n().language||"en").toLowerCase().startsWith("zh"),t=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"",i=""!==t&&!/utf-?8/i.test(t),r=e.probeEnv?p:void 0,a=m(g({probeEnv:r}));console.log();for(const n of y(a,{curriculumId:e.curriculumId,zh:o,ascii:i,inLearn:e.inLearn}))console.log(n);console.log()}export function nextSetupRung(e){return v(m(g()),d(e))?.id??null}async function w(e){switch(e){case"python":{const{runSetup:e}=await import("./python.js");return void await e()}case"mujoco":{const{runMujocoSetup:e}=await import("./mujoco.js");return void await e()}case"aienv":{const{runAienvSetup:e}=await import("./aienv.js");return void await e(!1)}case"env":return h?void await h.parseAsync(["node","icoa",e,"setup"]):void console.log(chalk.yellow(` type: ${e} setup`))}}export async function runSetupWizard(){{u("setup");const p=n();c("ICOA CLI Setup"),console.log(),console.log(chalk.gray(" Tip: press ")+chalk.cyan("Ctrl+C")+chalk.gray(" any time to cancel setup and return to the ")+chalk.cyan("icoa>")+chalk.gray(" prompt — nothing is saved until you confirm.")),console.log(),l("CTFd URL",p.ctfdUrl||chalk.gray("Not configured")),l("CTFd Token",p.token?chalk.green("Configured"):chalk.gray("Not configured")),l("Gemini API Key",p.geminiApiKey||process.env.GEMINI_API_KEY?chalk.green("Configured"):chalk.gray("Not configured")),l("Language",p.language),l("Mode",p.mode||chalk.gray("Not set")),l("Session ID",`${p.sessionId.substring(0,8)}...`),console.log();try{switch(await o({message:"What would you like to configure?",choices:[{name:"Switch Mode",value:"mode"},{name:"Gemini API Key",value:"gemini"},{name:"CTFd Connection",value:"ctfd"},{name:"View All Settings",value:"view"},{name:"Exit",value:"exit"}]})){case"mode":{const e=await o({message:"Select mode:",choices:[{name:"National Selection — demo, exam, lightweight",value:"selection"},{name:"International Olympiad — Full CTF with AI assistance",value:"olympiad"},{name:"National/Regional Partner — Organizer management",value:"organizer"}]});t({mode:e}),r(`Mode switched to: ${e}. Restart ICOA CLI to apply.`);break}case"gemini":{console.log(),s("Get your API key from: https://aistudio.google.com/apikey"),console.log();const o=await e({message:"Enter Gemini API Key:"});o.trim()?(i(o.trim()),r("Gemini API key saved.")):a("No key provided.");break}case"ctfd":s('Use "join <url>" to connect to a CTFd instance.');break;case"view":{console.log(),c("Full Configuration");const e=n();for(const[o,n]of Object.entries(e))l(o,"token"===o&&n||"geminiApiKey"===o&&n?`${n.toString().substring(0,8)}...`:String(n??"null"));console.log();break}}console.log(),console.log(chalk.gray(" Setup complete. You are back at the ")+chalk.cyan("icoa>")+chalk.gray(" prompt.")),console.log()}catch(e){if("ExitPromptError"===e?.name)return console.log(),console.log(chalk.gray(" Setup cancelled. You are back at the ")+chalk.cyan("icoa>")+chalk.gray(" prompt. Nothing was saved.")),void console.log();throw e}}}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as l}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerUpgradeCommand as m}from"./commands/upgrade.js";import{registerNoteCommand as c}from"./commands/note.js";import{registerLogCommand as g}from"./commands/log.js";import{registerLangCommand as d}from"./commands/lang.js";import{registerSetupCommand as p}from"./commands/setup.js";import{registerEnvCommand as y}from"./commands/env.js";import{registerAienvCommand as h}from"./commands/aienv.js";import{registerPythonCommands as f}from"./commands/python.js";import{registerMujocoCommands as u}from"./commands/mujoco.js";import{registerDuckCommand as w}from"./commands/duck.js";import{registerIpynbCommand as b}from"./commands/ipynb.js";import{registerAi4ctfCommand as j}from"./commands/ai4ctf.js";import{registerExamCommand as v}from"./commands/exam.js";import{registerCtf4aiDemoCommand as $}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as T}from"./commands/theme.js";import{registerLearnCommand as A}from"./commands/learn.js";import{registerCtf4VlaCommand as I}from"./commands/ctf4vla.js";import{registerDemo2Command as E}from"./commands/demo2.js";import{registerDemo3Command as C}from"./commands/demo3.js";import{registerDemo4Command as x}from"./commands/demo4.js";import{registerDemo5Command as _}from"./commands/demo5.js";import{registerGfssmCommand as k}from"./commands/gfssm.js";import{registerGpuForTaskCommand as S}from"./commands/gpufortask.js";import{registerSimCommand as L}from"./commands/sim.js";import{registerArenaCommand as R}from"./commands/arena.js";import{registerKaggleCommand as O}from"./commands/kaggle.js";import{registerSprintCommand as F}from"./commands/sprint.js";import{registerTeleloadCommand as N}from"./commands/teleload.js";import{registerBoardCommand as U}from"./commands/board.js";import{registerTypeCommand as P}from"./commands/type.js";import{registerBattleCommand as M}from"./commands/battle.js";import{registerWmCommand as D}from"./commands/wm.js";import{getConfig as G,saveConfig as W}from"./lib/config.js";import{registerMicroduckCommand as H}from"./commands/microduck.js";import{startRepl as Y}from"./repl.js";import{RELAUNCH_CODE as J}from"./lib/menu-nav.js";import{setTerminalTheme as V}from"./lib/theme.js";import{cleanupTerminal as X}from"./lib/terminal-cleanup.js";import{checkForUpdates as q,runUpgrade as z,bootUpgradeEligible as K,startBootCheck as B,printUpdateHint as Q}from"./lib/update-check.js";import{detectIcoaInstalls as Z,isWindowsBuildInWslShell as oo}from"./lib/platform.js";import{ICOA_BIG as eo}from"./lib/banner.js";import{readFileSync as no}from"node:fs";import{fileURLToPath as so}from"node:url";import{dirname as ro,join as to}from"node:path";import{setDefaultResultOrder as io}from"node:dns";import{setDefaultAutoSelectFamilyAttemptTimeout as lo}from"node:net";io("ipv4first"),lo(4e3);const ao=ro(so(import.meta.url)),mo=JSON.parse(no(to(ao,"..","package.json"),"utf-8")).version,co=chalk.cyan(" ─────────────────────────────────────────────────────"),go=`\n${co}\n\n${eo.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${mo}`)}\n\n${co}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=n?process.argv.slice(1,2):process.argv.slice(1),r=o(process.execPath,s,{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(r.signal){const{appendExitLog:o}=await import("./lib/exit-log.js");o("worker-signal",`signal=${r.signal}`),console.log(),console.log(chalk.yellow(` ⚠ icoa was stopped by signal ${r.signal}`)+chalk.gray(" — another process killed it (not a crash). Run icoa --resume to continue.")),e=0;break}if(e=r.status,0!==e&&e!==J){const{appendExitLog:o}=await import("./lib/exit-log.js");o("worker-exit",`code=${e}`);const n=null!==e&&e>128?e-128:0;console.log(),console.log(n?chalk.yellow(` ⚠ icoa was stopped by signal ${n}`)+chalk.gray(" — another process killed it (not a crash). Run icoa --resume to continue."):chalk.yellow(` ⚠ icoa exited unexpectedly (code ${e})`)+chalk.gray(" — see ~/.icoa/exit.log · run icoa --resume to continue."))}n=!0}while(e===J);X(),process.exit(e??0)}}const po=new o;if(po.name("icoa").version(mo).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=G();V("high-contrast"===e.themeVariant?"high-contrast":"dark");const n=!!o.resume||!!o.continue,s=K(n)&&process.argv.length<=2;s?B():q(),function(){const o=Z();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const r=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(r))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${r||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();if(console.log(go),s?"upgraded"===await z({ask:!0})&&(console.log(chalk.gray(" restarting icoa …")),process.exit(J)):Q(),process.argv.length<=2||n)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),n||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void Y(po,n)}),e(po),n(po),s(po),r(po),t(po),i(po),l(po),a(po),m(po),c(po),g(po),d(po),p(po),y(po),h(po),f(po),u(po),w(po),b(po),j(po),v(po),$(po),T(po),A(po),I(po),E(po),C(po),x(po),_(po),k(po),S(po),L(po),R(po),O(po),N(po),F(po),U(po),D(po),P(po),M(po),H(po),po.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=G().geminiModel||"gemini-2.5-flash-lite";o?(W({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}po.hook("preAction",()=>{!function(){if(!oo())return;const o="─".repeat(Math.max(24,Math.min(52,(process.stdout.columns||80)-4)));console.log(),console.log(chalk.yellow(` ${o}`)),console.log(chalk.yellow.bold(" ⚠ You ARE inside Ubuntu — but this icoa")),console.log(chalk.yellow.bold(" is the WINDOWS build.")),console.log(),console.log(chalk.gray(" WSL appends the Windows PATH, so ")+chalk.cyan("icoa")),console.log(chalk.gray(" found the Windows copy first. Almost")),console.log(chalk.gray(" nothing will work: no vi, no python3,")),console.log(chalk.gray(" env setup cannot install.")),console.log(),console.log(chalk.gray(" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.white(" Fix — inside Ubuntu, check npm is Linux FIRST:")),console.log(` ${chalk.bold.cyan("which npm")}${chalk.gray(" → must not be /mnt/c/...")}`),console.log(` ${chalk.bold.cyan("sudo npm install -g icoa-cli")}`),console.log(` ${chalk.bold.cyan("hash -r")}${chalk.gray(" → bash caches the old path")}`),console.log(chalk.gray(" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(chalk.yellow(` ${o}`)),console.log()}()}),po.parse();
2
+ import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as l}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerUpgradeCommand as m}from"./commands/upgrade.js";import{registerNoteCommand as c}from"./commands/note.js";import{registerLogCommand as g}from"./commands/log.js";import{registerLangCommand as d}from"./commands/lang.js";import{registerSetupCommand as p}from"./commands/setup.js";import{registerEnvCommand as h}from"./commands/env.js";import{registerAienvCommand as f}from"./commands/aienv.js";import{registerPythonCommands as y}from"./commands/python.js";import{registerMujocoCommands as u}from"./commands/mujoco.js";import{registerDuckCommand as w}from"./commands/duck.js";import{registerIpynbCommand as j}from"./commands/ipynb.js";import{registerAi4ctfCommand as b}from"./commands/ai4ctf.js";import{registerExamCommand as v}from"./commands/exam.js";import{registerCtf4aiDemoCommand as T}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as $}from"./commands/theme.js";import{registerLearnCommand as E}from"./commands/learn.js";import{registerCtf4VlaCommand as A}from"./commands/ctf4vla.js";import{registerDemo2Command as x}from"./commands/demo2.js";import{registerDemo3Command as _}from"./commands/demo3.js";import{registerDemo4Command as I}from"./commands/demo4.js";import{registerDemo5Command as k}from"./commands/demo5.js";import{registerGfssmCommand as C}from"./commands/gfssm.js";import{registerGpuForTaskCommand as S}from"./commands/gpufortask.js";import{registerSimCommand as L}from"./commands/sim.js";import{registerArenaCommand as R}from"./commands/arena.js";import{registerKaggleCommand as O}from"./commands/kaggle.js";import{registerSprintCommand as N}from"./commands/sprint.js";import{registerTeleloadCommand as U}from"./commands/teleload.js";import{registerBoardCommand as F}from"./commands/board.js";import{registerTypeCommand as P}from"./commands/type.js";import{registerBattleCommand as M}from"./commands/battle.js";import{registerWmCommand as G}from"./commands/wm.js";import{getConfig as H,saveConfig as W}from"./lib/config.js";import{registerMicroduckCommand as D}from"./commands/microduck.js";import{startRepl as Y}from"./repl.js";import{RELAUNCH_CODE as V}from"./lib/menu-nav.js";import{setTerminalTheme as J}from"./lib/theme.js";import{cleanupTerminal as X}from"./lib/terminal-cleanup.js";import{checkForUpdates as q,runUpgrade as z,bootUpgradeEligible as K,startBootCheck as B,printUpdateHint as Q}from"./lib/update-check.js";import{detectIcoaInstalls as Z,isWindowsBuildInWslShell as oo}from"./lib/platform.js";import{ICOA_BIG as eo}from"./lib/banner.js";import{readFileSync as no}from"node:fs";import{fileURLToPath as so}from"node:url";import{dirname as ro,join as to}from"node:path";import{setDefaultResultOrder as io}from"node:dns";import{setDefaultAutoSelectFamilyAttemptTimeout as lo}from"node:net";io("ipv4first"),lo(4e3);const ao=ro(so(import.meta.url)),mo=JSON.parse(no(to(ao,"..","package.json"),"utf-8")).version,co=chalk.cyan(" ─────────────────────────────────────────────────────"),go=`\n${co}\n\n${eo.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for K-12 AI & Cyber Olympiads and International AI Hackathons")}\n\n ${chalk.bold.white("ICOA 2026:")} ${chalk.white("Sydney, Australia")}\n ${chalk.bold.white("ICOA 2027:")} ${chalk.white("July 2027")} ${chalk.gray("· host city to be announced")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${mo}`)}\n\n${co}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=n?process.argv.slice(1,2):process.argv.slice(1),r=o(process.execPath,s,{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(r.signal){const{appendExitLog:o}=await import("./lib/exit-log.js");o("worker-signal",`signal=${r.signal}`),console.log(),console.log(chalk.yellow(` ⚠ icoa was stopped by signal ${r.signal}`)+chalk.gray(" — another process killed it (not a crash). Run icoa --resume to continue.")),e=0;break}if(e=r.status,0!==e&&e!==V){const{appendExitLog:o}=await import("./lib/exit-log.js");o("worker-exit",`code=${e}`);const n=null!==e&&e>128?e-128:0;console.log(),console.log(n?chalk.yellow(` ⚠ icoa was stopped by signal ${n}`)+chalk.gray(" — another process killed it (not a crash). Run icoa --resume to continue."):chalk.yellow(` ⚠ icoa exited unexpectedly (code ${e})`)+chalk.gray(" — see ~/.icoa/exit.log · run icoa --resume to continue."))}n=!0}while(e===V);X(),process.exit(e??0)}}const po=new o;if(po.name("icoa").version(mo).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=H();J("high-contrast"===e.themeVariant?"high-contrast":"dark");const n=!!o.resume||!!o.continue,s=K(n)&&process.argv.length<=2;s?B():q(),function(){const o=Z();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const r=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(r))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${r||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();if(console.log(go),s?"upgraded"===await z({ask:!0})&&(console.log(chalk.gray(" restarting icoa …")),process.exit(V)):Q(),process.argv.length<=2||n)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),n||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void Y(po,n)}),e(po),n(po),s(po),r(po),t(po),i(po),l(po),a(po),m(po),c(po),g(po),d(po),p(po),h(po),f(po),y(po),u(po),w(po),j(po),b(po),v(po),T(po),$(po),E(po),A(po),x(po),_(po),I(po),k(po),C(po),S(po),L(po),R(po),O(po),U(po),N(po),F(po),G(po),P(po),M(po),D(po),po.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=H().geminiModel||"gemini-2.5-flash-lite";o?(W({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}po.hook("preAction",()=>{!function(){if(!oo())return;const o="─".repeat(Math.max(24,Math.min(52,(process.stdout.columns||80)-4)));console.log(),console.log(chalk.yellow(` ${o}`)),console.log(chalk.yellow.bold(" ⚠ You ARE inside Ubuntu — but this icoa")),console.log(chalk.yellow.bold(" is the WINDOWS build.")),console.log(),console.log(chalk.gray(" WSL appends the Windows PATH, so ")+chalk.cyan("icoa")),console.log(chalk.gray(" found the Windows copy first. Almost")),console.log(chalk.gray(" nothing will work: no vi, no python3,")),console.log(chalk.gray(" env setup cannot install.")),console.log(),console.log(chalk.gray(" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.white(" Fix — inside Ubuntu, check npm is Linux FIRST:")),console.log(` ${chalk.bold.cyan("which npm")}${chalk.gray(" → must not be /mnt/c/...")}`),console.log(` ${chalk.bold.cyan("sudo npm install -g icoa-cli")}`),console.log(` ${chalk.bold.cyan("hash -r")}${chalk.gray(" → bash caches the old path")}`),console.log(chalk.gray(" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(chalk.yellow(` ${o}`)),console.log()}()}),po.parse();
@@ -1 +1 @@
1
- import chalk from"chalk";export const ICOA_BIG=["██╗ ██████╗ ██████╗ █████╗","██║██╔════╝██╔═══██╗██╔══██╗","██║██║ ██║ ██║███████║","██║██║ ██║ ██║██╔══██║","██║╚██████╗╚██████╔╝██║ ██║","╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝"];export function icoaBannerLines(o=" "){return(process.stdout.columns||80)<60?[o+chalk.bold.white("I C O A")+chalk.gray(" 2026")]:ICOA_BIG.map(t=>o+chalk.bold.white(t))}
1
+ import chalk from"chalk";export const ICOA_BIG=["██╗ ██████╗ ██████╗ █████╗","██║██╔════╝██╔═══██╗██╔══██╗","██║██║ ██║ ██║███████║","██║██║ ██║ ██║██╔══██║","██║╚██████╗╚██████╔╝██║ ██║","╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝"];export function icoaBannerLines(o=" "){return(process.stdout.columns||80)<60?[o+chalk.bold.white("I C O A")]:ICOA_BIG.map(t=>o+chalk.bold.white(t))}
@@ -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 2026, Sydney).\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}}}}
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}}}}
@@ -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?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())}
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())}
@@ -1 +1 @@
1
- import chalk from"chalk";import{execSync as t}from"node:child_process";import{createHash as o}from"node:crypto";import{createWriteStream as e,existsSync as r,mkdirSync as n,mkdtempSync as s,renameSync as a,rmSync as i}from"node:fs";import{homedir as c}from"node:os";import{join as l}from"node:path";import{Readable as h,Transform as u}from"node:stream";import{pipeline as d}from"node:stream/promises";import{icoaStandalonePython as p,parsePyVersion as y,REQUIRED_PY as m,resolveHostPython as f,resolveRunPython as g}from"./aienv.js";import{httpFetch as w}from"./http.js";import{lazyJson as $}from"./lazy-assets.js";function b(o){try{return t(`${o} --version 2>&1`,{encoding:"utf-8",timeout:4e3}).trim()}catch{return null}}let v,x;export function probePython(t=!1,o={}){const e=o.hostOnly?x:v;if(e&&!t)return e;const r=c(),n=o.hostOnly?(()=>{const t=f(b,process.platform,r);return t?{...t,source:"host"}:null})():g(b,process.platform,r);if(n){const t=(b(n.cmd.includes(" ")?n.cmd:`"${n.cmd}"`)??"").replace(/^Python\s+/i,"")||`${n.version.major}.${n.version.minor}`,e=p(r,process.platform),s="aienv"===n.source?"aienv":n.cmd===e?"icoa":"system",a={ok:!0,version:t,cmd:n.cmd,source:s};return o.hostOnly?x=a:v=a,a}let s;for(const t of["python3","python"]){const o=b(t);if(y(o)){s=(o??"").replace(/^Python\s+/i,"").trim();break}}const a={ok:!1,otherVersion:s};return o.hostOnly?x=a:v=a,a}export function resetPythonProbe(){v=void 0,x=void 0}const P=`${m.major}.${m.minor}`;export function pythonDoorLine(t,o=!1,e){const r=e??probePython(),n=o?"":"🐍 ";if(r.ok){const o="aienv"===r.source?t?"aienv 环境":"aienv venv":"icoa"===r.source?t?"icoa 装的":"installed by icoa":t?"系统自带":"system";return chalk.gray(` ${n}Python ${r.version} · ${o} · `)+chalk.gray(t?"本机可跑代码":"code runs locally")}return r.otherVersion?chalk.gray(` ${n}Python ${r.otherVersion} — `)+chalk.gray(t?`课程按 ${P} 校准 · `:`courses are calibrated on ${P} · `)+chalk.bold.green("python setup")+chalk.gray(t?` 装并存的 ${P}(免 sudo,不动系统 python3)`:" adds one side-by-side (no sudo, system python3 untouched)"):chalk.gray(` ${n}`+(t?"没有 Python — 读卡答题不需要它 · ":"No Python — reading and answering cards works without it · "))+chalk.bold.green("python setup")+chalk.gray(t?" 让 /py 里能跑代码":" when you want to run code in /py")}export function selectionSetupLine(t,o=!1,e){const r=e??probePython(!1,{hostOnly:!0}),n=o?"":"🐍 ",s=chalk.gray(" (Paper C · SIMOC are MCQ-only — neither is needed)");return r.ok?t?chalk.gray(` ${n}Python ${r.version} · `)+chalk.green("exam toolkit ready"):chalk.gray(` ${n}Python ${r.version} · toolkit not installed · `)+chalk.bold.green("exam setup")+chalk.gray(" (13 packages, ~150 MB)")+s:chalk.gray(` ${n}`+(r.otherVersion?`Python ${r.otherVersion} — the exam runs on ${P} · `:`No Python ${P} yet · `))+chalk.bold.green("exam setup")+chalk.gray(" installs it (~20 s) plus the toolkit (~150 MB)")+s}export function printNoPython312(t,o={}){const e=probePython();console.log(chalk.yellow(t?e.otherVersion?` 这台机器只有 Python ${e.otherVersion} — 课程和判分机都在 ${P} 线上。`:` 找不到 Python ${P} — 不是你的代码有问题。`:e.otherVersion?` This machine has Python ${e.otherVersion} only — courses and the judge both run on the ${P} line.`:` Python ${P} not found — this is not your code.`)),console.log(chalk.gray(t?" 装一份并存的(免 sudo,二十秒,不动系统 python3): ":" Add one side-by-side (no sudo, ~20 s, system python3 untouched): ")+chalk.bold.cyan("python setup")),o.judgeIsServerSide&&console.log(chalk.gray(t?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()}export function standaloneTriple(t=process.platform,o=""){const e=o.toLowerCase(),r="aarch64"===e||"arm64"===e,n="x86_64"===e||"amd64"===e||"x64"===e;return"darwin"===t?r?"aarch64-apple-darwin":n?"x86_64-apple-darwin":"":"win32"===t?r?"aarch64-pc-windows-msvc":n?"x86_64-pc-windows-msvc":"":r?"aarch64-unknown-linux-gnu":n?"x86_64-unknown-linux-gnu":""}export function pickStandaloneAsset(t,o){const e=`${m.major}\\.${m.minor}`,r=new RegExp(`^cpython-${e}\\.\\d+\\+\\d+-${o}-install_only_stripped\\.tar\\.gz$`),n=new RegExp(`^cpython-${e}\\.\\d+\\+\\d+-${o}-install_only\\.tar\\.gz$`);return t.find(t=>r.test(t.name))??t.find(t=>n.test(t.name))}export function isAllowedAssetUrl(t){return/^https:\/\/github\.com\/astral-sh\/python-build-standalone\/releases\/download\/[\w.%+-]+\/cpython-3\.12\.[\w.%+-]+\.tar\.gz$/.test(t)}const k=/^[0-9a-f]{64}$/;export function candidatesFromManifest(t,o){const e=t?.assets?.[o];if(!e||"string"!=typeof e.path||!function(t,o){const e=`${m.major}\\.${m.minor}`;return new RegExp(`^\\d{8}/cpython-${e}\\.\\d+\\+\\d+-${o}-install_only(_stripped)?\\.tar\\.gz$`).test(t)}(e.path,o))return[];const r="string"==typeof e.sha256&&k.test(e.sha256)?e.sha256:void 0,n=e.path.slice(e.path.indexOf("/")+1),s=[];for(const o of Array.isArray(t.mirrors)?t.mirrors:[]){if("string"!=typeof o||!/^https:\/\/[\w.-]+(\/[\w./%-]*)?$/.test(o))continue;const t=`${o.replace(/\/+$/,"")}/${e.path.replace(/\+/g,"%2B")}`;s.push({url:t,name:n,via:new URL(t).host,sha256:r})}return"string"==typeof e.github&&isAllowedAssetUrl(e.github)&&s.push({url:e.github,name:n,via:"github.com",sha256:r}),s}const j="win32"===process.platform?"tar.exe":"tar";async function A(t,r,n,s){const a=new AbortController;let i=Date.now();const c=setInterval(()=>{Date.now()-i>6e4&&a.abort(new Error("no data for 60 s"))},5e3);try{const c=await w(t,{timeoutMs:3e4,retries:0,signal:a.signal,headers:{"User-Agent":"icoa-cli"}});if(!c.ok)throw new Error(`HTTP ${c.status}`);if(!c.body)throw new Error("empty body");const l=Number(c.headers.get("content-length")??0),p=o("sha256");let y=0;const m=new u({transform(t,o,e){p.update(t),y+=t.length,i=Date.now(),s?.(y,l),e(null,t)}});if(await d(h.fromWeb(c.body),m,e(r)),n&&p.digest("hex")!==n)throw new Error("sha256 mismatch")}catch(t){const o=t.cause;if(a.signal.aborted&&o instanceof Error)throw o;throw t}finally{clearInterval(c)}}const _=["https://icoa-assets.oss-cn-hongkong.aliyuncs.com/python312/manifest.json","https://icoa-datasets.sg-sin-1.linodeobjects.com/python312/manifest.json"];async function E(t){const o=new AbortController,e=setTimeout(()=>o.abort(),6e3),r=Date.now();let n=0;try{const e=await w(t,{timeoutMs:6e3,retries:0,signal:o.signal,headers:{"User-Agent":"icoa-cli",Range:"bytes=0-524287"}});if(!e.ok||!e.body)return 0;const r=e.body.getReader();for(;;){const{done:t,value:o}=await r.read();if(t)break;if(n+=o.length,n>=524288)break}}catch{}finally{clearTimeout(e)}const s=Math.max(1,Date.now()-r);return n>0?1e3*n/s:0}export function orderBySpeed(t,o){const e=t.filter(t=>"github.com"===t.via),r=t.filter(t=>"github.com"!==t.via);return[...r.filter(t=>(o.get(t.url)??0)>0).sort((t,e)=>(o.get(e.url)??0)-(o.get(t.url)??0)),...r.filter(t=>!((o.get(t.url)??0)>0)),...e]}function M(t){return`${(t/1e6).toFixed(t>=1e6?1:2)} MB/s`}export async function provisionPython312(o={}){const e=c(),h=l(e,".icoa","python312"),u=p(e,process.platform),d=t=>{o.quiet||console.log(t)};if(!o.force&&r(u)){const t=b(`"${u}"`);if(t&&new RegExp(`^Python ${m.major}\\.${m.minor}\\.`).test(t))return d(chalk.green(` ✓ ${t}`)+chalk.gray(` → ${u}`)),resetPythonProbe(),!0}const y=function(){if("win32"===process.platform)return"arm64"===process.arch?"aarch64":"x86_64";try{return t("uname -m",{encoding:"utf-8"}).trim()}catch{return"arm64"===process.arch?"aarch64":"x86_64"}}(),f=standaloneTriple(process.platform,y);if(!f)return d(chalk.yellow(` ~ No prebuilt Python ${P} for '${y||"unknown"}' on this platform.`)),!1;if(!function(){try{return t(`${j} --version`,{stdio:"ignore",timeout:4e3}),!0}catch{return!1}}())return d(chalk.red(" ✗ `tar` is not installed")+chalk.gray(" — needed to unpack the download.")),"linux"===process.platform&&d(chalk.gray(" Install it: ")+chalk.cyan("sudo apt install -y tar")),!1;let g=await $("python312/manifest.json",8e3,{force:!0});for(const t of _){if(candidatesFromManifest(g,f).length)break;try{const o=await w(t,{timeoutMs:8e3,retries:0,headers:{"User-Agent":"icoa-cli"}});o.ok&&(g=await o.json())}catch{}}let v=candidatesFromManifest(g,f);if(0===v.length)try{const t=await w("https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest",{headers:{"User-Agent":"icoa-cli",Accept:"application/vnd.github+json"}});if(!t.ok)throw new Error(`GitHub API ${t.status}`);const o=pickStandaloneAsset((await t.json()).assets??[],f);if(!o)throw new Error(`no CPython ${P} build for ${f} in the latest release`);if(!isAllowedAssetUrl(o.browser_download_url))throw new Error("asset URL failed the allowlist check");v=[{url:o.browser_download_url,name:o.name,via:"github.com"}]}catch(t){return d(chalk.red(` ✗ Could not resolve a standalone Python ${P}`)+chalk.gray(` (mirror list unreachable · ${t.message})`)),!1}const x=v[0].name.match(/^cpython-(\d+\.\d+\.\d+)/)?.[1]??P,k=v.filter(t=>"github.com"!==t.via);if(k.length>=2){d(chalk.gray(` Testing ${k.length} download sources …`));const t=await Promise.all(k.map(async t=>[t.url,await E(t.url)])),o=new Map(t);v=orderBySpeed(v,o);const e=v[0],r=o.get(e.url)??0;d(r>0?chalk.gray(` Fastest: ${e.via} (${M(r)})`):chalk.gray(" No source answered the speed test — trying each in turn."))}const C=!o.quiet&&!0===process.stdout.isTTY;let T=0,R=0;const S=(t,o)=>{if(!C)return;const e=Date.now();if(e-T<500&&t<o)return;T=e;const r=t/Math.max(1,e-R)*1e3,n=o?` / ${(o/1e6).toFixed(1)}`:"";process.stdout.write(chalk.gray(`\r ↓ ${(t/1e6).toFixed(1)}${n} MB · ${M(r)} `))},U=()=>{C&&T&&process.stdout.write("\r"+" ".repeat(60)+"\r"),T=0};let V="";try{n(l(e,".icoa"),{recursive:!0}),V=s(l(e,".icoa",".py312-"));const o=l(V,"py.tgz"),r=[];let c=!1;for(const t of v){d(chalk.gray(` Fetching CPython ${x} for ${f} via ${t.via} …`)),R=Date.now();try{await A(t.url,o,t.sha256,S),U(),c=!0;break}catch(o){U();const e=o.message.split("\n")[0].slice(0,80);r.push(`${t.via}: ${e}`),d(chalk.gray(` ~ ${t.via} did not work (${e}) — trying the next source`))}}if(!c)throw new Error(`no source reachable — ${r.join(" · ")}`);t(`${j} -xzf "${o}" -C "${V}"`,{stdio:["ignore","ignore","pipe"]}),i(h,{recursive:!0,force:!0}),a(l(V,"python"),h);const p=t(`"${u}" --version`,{encoding:"utf-8"}).trim();if(!new RegExp(`^Python ${m.major}\\.${m.minor}\\.`).test(p))throw new Error(`unexpected version: ${p}`);return resetPythonProbe(),d(chalk.green(` ✓ ${p} installed`)+chalk.gray(` → ${u} (system python3 untouched)`)),!0}catch(t){const o=String(t.stderr??t.message).trim().split("\n").pop();return d(chalk.red(` ✗ Python ${P} install failed`)+chalk.gray(o?` (${o})`:"")),!1}finally{V&&i(V,{recursive:!0,force:!0})}}
1
+ import chalk from"chalk";import{execSync as t}from"node:child_process";import{createHash as o}from"node:crypto";import{createWriteStream as e,existsSync as r,mkdirSync as n,mkdtempSync as s,renameSync as a,rmSync as i}from"node:fs";import{homedir as c}from"node:os";import{join as l}from"node:path";import{Readable as h,Transform as u}from"node:stream";import{pipeline as d}from"node:stream/promises";import{icoaStandalonePython as p,parsePyVersion as y,REQUIRED_PY as f,resolveHostPython as m,resolveRunPython as g}from"./aienv.js";import{httpFetch as w}from"./http.js";import{lazyJson as $}from"./lazy-assets.js";function b(o){try{return t(`${o} --version 2>&1`,{encoding:"utf-8",timeout:4e3}).trim()}catch{return null}}let v,x;export function probePython(t=!1,o={}){const e=o.hostOnly?x:v;if(e&&!t)return e;const r=c(),n=o.hostOnly?(()=>{const t=m(b,process.platform,r);return t?{...t,source:"host"}:null})():g(b,process.platform,r);if(n){const t=(b(n.cmd.includes(" ")?n.cmd:`"${n.cmd}"`)??"").replace(/^Python\s+/i,"")||`${n.version.major}.${n.version.minor}`,e=p(r,process.platform),s="aienv"===n.source?"aienv":n.cmd===e?"icoa":"system",a={ok:!0,version:t,cmd:n.cmd,source:s};return o.hostOnly?x=a:v=a,a}let s;for(const t of["python3","python"]){const o=b(t);if(y(o)){s=(o??"").replace(/^Python\s+/i,"").trim();break}}const a={ok:!1,otherVersion:s};return o.hostOnly?x=a:v=a,a}export function resetPythonProbe(){v=void 0,x=void 0}const P=`${f.major}.${f.minor}`;export function pythonDoorLine(t,o=!1,e){const r=e??probePython(),n=o?"":"🐍 ";if(r.ok){const o="aienv"===r.source?t?"aienv 环境":"aienv venv":"icoa"===r.source?t?"icoa 装的":"installed by icoa":t?"系统自带":"system";return chalk.gray(` ${n}Python ${r.version} · ${o} · `)+chalk.gray(t?"本机可跑代码":"code runs locally")}return r.otherVersion?chalk.gray(` ${n}Python ${r.otherVersion} — `)+chalk.gray(t?`课程按 ${P} 校准 · `:`courses are calibrated on ${P} · `)+chalk.bold.green("python setup")+chalk.gray(t?` 装并存的 ${P}(免 sudo,不动系统 python3)`:" adds one side-by-side (no sudo, system python3 untouched)"):chalk.gray(` ${n}`+(t?"没有 Python — 读卡答题不需要它 · ":"No Python — reading and answering cards works without it · "))+chalk.bold.green("python setup")+chalk.gray(t?" 让 /py 里能跑代码":" when you want to run code in /py")}export function selectionSetupLine(t,o=!1,e){const r=e??probePython(!1,{hostOnly:!0}),n=o?"":"🐍 ",s=chalk.gray(" (Paper C · SIMOC are MCQ-only — not needed)");return r.ok?chalk.gray(` ${n}Python ${r.version} · `)+chalk.green("ready for code questions")+chalk.gray(" · ")+chalk.cyan("setup")+chalk.gray(" = the whole ladder"):chalk.gray(` ${n}`+(r.otherVersion?`Python ${r.otherVersion} — the exam runs on ${P} · `:`No Python ${P} yet · `))+chalk.bold.green("python setup")+chalk.gray(" installs it (~20 s, no sudo)")+s}export function printNoPython312(t,o={}){const e=probePython();console.log(chalk.yellow(t?e.otherVersion?` 这台机器只有 Python ${e.otherVersion} — 课程和判分机都在 ${P} 线上。`:` 找不到 Python ${P} — 不是你的代码有问题。`:e.otherVersion?` This machine has Python ${e.otherVersion} only — courses and the judge both run on the ${P} line.`:` Python ${P} not found — this is not your code.`)),console.log(chalk.gray(t?" 装一份并存的(免 sudo,二十秒,不动系统 python3): ":" Add one side-by-side (no sudo, ~20 s, system python3 untouched): ")+chalk.bold.cyan("python setup")),o.judgeIsServerSide&&console.log(chalk.gray(t?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()}export function standaloneTriple(t=process.platform,o=""){const e=o.toLowerCase(),r="aarch64"===e||"arm64"===e,n="x86_64"===e||"amd64"===e||"x64"===e;return"darwin"===t?r?"aarch64-apple-darwin":n?"x86_64-apple-darwin":"":"win32"===t?r?"aarch64-pc-windows-msvc":n?"x86_64-pc-windows-msvc":"":r?"aarch64-unknown-linux-gnu":n?"x86_64-unknown-linux-gnu":""}export function pickStandaloneAsset(t,o){const e=`${f.major}\\.${f.minor}`,r=new RegExp(`^cpython-${e}\\.\\d+\\+\\d+-${o}-install_only_stripped\\.tar\\.gz$`),n=new RegExp(`^cpython-${e}\\.\\d+\\+\\d+-${o}-install_only\\.tar\\.gz$`);return t.find(t=>r.test(t.name))??t.find(t=>n.test(t.name))}export function isAllowedAssetUrl(t){return/^https:\/\/github\.com\/astral-sh\/python-build-standalone\/releases\/download\/[\w.%+-]+\/cpython-3\.12\.[\w.%+-]+\.tar\.gz$/.test(t)}const k=/^[0-9a-f]{64}$/;export function candidatesFromManifest(t,o){const e=t?.assets?.[o];if(!e||"string"!=typeof e.path||!function(t,o){const e=`${f.major}\\.${f.minor}`;return new RegExp(`^\\d{8}/cpython-${e}\\.\\d+\\+\\d+-${o}-install_only(_stripped)?\\.tar\\.gz$`).test(t)}(e.path,o))return[];const r="string"==typeof e.sha256&&k.test(e.sha256)?e.sha256:void 0,n=e.path.slice(e.path.indexOf("/")+1),s=[];for(const o of Array.isArray(t.mirrors)?t.mirrors:[]){if("string"!=typeof o||!/^https:\/\/[\w.-]+(\/[\w./%-]*)?$/.test(o))continue;const t=`${o.replace(/\/+$/,"")}/${e.path.replace(/\+/g,"%2B")}`;s.push({url:t,name:n,via:new URL(t).host,sha256:r})}return"string"==typeof e.github&&isAllowedAssetUrl(e.github)&&s.push({url:e.github,name:n,via:"github.com",sha256:r}),s}const j="win32"===process.platform?"tar.exe":"tar";async function A(t,r,n,s){const a=new AbortController;let i=Date.now();const c=setInterval(()=>{Date.now()-i>6e4&&a.abort(new Error("no data for 60 s"))},5e3);try{const c=await w(t,{timeoutMs:3e4,retries:0,signal:a.signal,headers:{"User-Agent":"icoa-cli"}});if(!c.ok)throw new Error(`HTTP ${c.status}`);if(!c.body)throw new Error("empty body");const l=Number(c.headers.get("content-length")??0),p=o("sha256");let y=0;const f=new u({transform(t,o,e){p.update(t),y+=t.length,i=Date.now(),s?.(y,l),e(null,t)}});if(await d(h.fromWeb(c.body),f,e(r)),n&&p.digest("hex")!==n)throw new Error("sha256 mismatch")}catch(t){const o=t.cause;if(a.signal.aborted&&o instanceof Error)throw o;throw t}finally{clearInterval(c)}}const _=["https://icoa-assets.oss-cn-hongkong.aliyuncs.com/python312/manifest.json","https://icoa-datasets.sg-sin-1.linodeobjects.com/python312/manifest.json"];async function E(t){const o=new AbortController,e=setTimeout(()=>o.abort(),6e3),r=Date.now();let n=0;try{const e=await w(t,{timeoutMs:6e3,retries:0,signal:o.signal,headers:{"User-Agent":"icoa-cli",Range:"bytes=0-524287"}});if(!e.ok||!e.body)return 0;const r=e.body.getReader();for(;;){const{done:t,value:o}=await r.read();if(t)break;if(n+=o.length,n>=524288)break}}catch{}finally{clearTimeout(e)}const s=Math.max(1,Date.now()-r);return n>0?1e3*n/s:0}export function orderBySpeed(t,o){const e=t.filter(t=>"github.com"===t.via),r=t.filter(t=>"github.com"!==t.via);return[...r.filter(t=>(o.get(t.url)??0)>0).sort((t,e)=>(o.get(e.url)??0)-(o.get(t.url)??0)),...r.filter(t=>!((o.get(t.url)??0)>0)),...e]}function M(t){return`${(t/1e6).toFixed(t>=1e6?1:2)} MB/s`}export async function provisionPython312(o={}){const e=c(),h=l(e,".icoa","python312"),u=p(e,process.platform),d=t=>{o.quiet||console.log(t)};if(!o.force&&r(u)){const t=b(`"${u}"`);if(t&&new RegExp(`^Python ${f.major}\\.${f.minor}\\.`).test(t))return d(chalk.green(` ✓ ${t}`)+chalk.gray(` → ${u}`)),resetPythonProbe(),!0}const y=function(){if("win32"===process.platform)return"arm64"===process.arch?"aarch64":"x86_64";try{return t("uname -m",{encoding:"utf-8"}).trim()}catch{return"arm64"===process.arch?"aarch64":"x86_64"}}(),m=standaloneTriple(process.platform,y);if(!m)return d(chalk.yellow(` ~ No prebuilt Python ${P} for '${y||"unknown"}' on this platform.`)),!1;if(!function(){try{return t(`${j} --version`,{stdio:"ignore",timeout:4e3}),!0}catch{return!1}}())return d(chalk.red(" ✗ `tar` is not installed")+chalk.gray(" — needed to unpack the download.")),"linux"===process.platform&&d(chalk.gray(" Install it: ")+chalk.cyan("sudo apt install -y tar")),!1;let g=await $("python312/manifest.json",8e3,{force:!0});for(const t of _){if(candidatesFromManifest(g,m).length)break;try{const o=await w(t,{timeoutMs:8e3,retries:0,headers:{"User-Agent":"icoa-cli"}});o.ok&&(g=await o.json())}catch{}}let v=candidatesFromManifest(g,m);if(0===v.length)try{const t=await w("https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest",{headers:{"User-Agent":"icoa-cli",Accept:"application/vnd.github+json"}});if(!t.ok)throw new Error(`GitHub API ${t.status}`);const o=pickStandaloneAsset((await t.json()).assets??[],m);if(!o)throw new Error(`no CPython ${P} build for ${m} in the latest release`);if(!isAllowedAssetUrl(o.browser_download_url))throw new Error("asset URL failed the allowlist check");v=[{url:o.browser_download_url,name:o.name,via:"github.com"}]}catch(t){return d(chalk.red(` ✗ Could not resolve a standalone Python ${P}`)+chalk.gray(` (mirror list unreachable · ${t.message})`)),!1}const x=v[0].name.match(/^cpython-(\d+\.\d+\.\d+)/)?.[1]??P,k=v.filter(t=>"github.com"!==t.via);if(k.length>=2){d(chalk.gray(` Testing ${k.length} download sources …`));const t=await Promise.all(k.map(async t=>[t.url,await E(t.url)])),o=new Map(t);v=orderBySpeed(v,o);const e=v[0],r=o.get(e.url)??0;d(r>0?chalk.gray(` Fastest: ${e.via} (${M(r)})`):chalk.gray(" No source answered the speed test — trying each in turn."))}const C=!o.quiet&&!0===process.stdout.isTTY;let T=0,R=0;const S=(t,o)=>{if(!C)return;const e=Date.now();if(e-T<500&&t<o)return;T=e;const r=t/Math.max(1,e-R)*1e3,n=o?` / ${(o/1e6).toFixed(1)}`:"";process.stdout.write(chalk.gray(`\r ↓ ${(t/1e6).toFixed(1)}${n} MB · ${M(r)} `))},U=()=>{C&&T&&process.stdout.write("\r"+" ".repeat(60)+"\r"),T=0};let V="";try{n(l(e,".icoa"),{recursive:!0}),V=s(l(e,".icoa",".py312-"));const o=l(V,"py.tgz"),r=[];let c=!1;for(const t of v){d(chalk.gray(` Fetching CPython ${x} for ${m} via ${t.via} …`)),R=Date.now();try{await A(t.url,o,t.sha256,S),U(),c=!0;break}catch(o){U();const e=o.message.split("\n")[0].slice(0,80);r.push(`${t.via}: ${e}`),d(chalk.gray(` ~ ${t.via} did not work (${e}) — trying the next source`))}}if(!c)throw new Error(`no source reachable — ${r.join(" · ")}`);t(`${j} -xzf "${o}" -C "${V}"`,{stdio:["ignore","ignore","pipe"]}),i(h,{recursive:!0,force:!0}),a(l(V,"python"),h);const p=t(`"${u}" --version`,{encoding:"utf-8"}).trim();if(!new RegExp(`^Python ${f.major}\\.${f.minor}\\.`).test(p))throw new Error(`unexpected version: ${p}`);return resetPythonProbe(),d(chalk.green(` ✓ ${p} installed`)+chalk.gray(` → ${u} (system python3 untouched)`)),!0}catch(t){const o=String(t.stderr??t.message).trim().split("\n").pop();return d(chalk.red(` ✗ Python ${P} install failed`)+chalk.gray(o?` (${o})`:"")),!1}finally{V&&i(V,{recursive:!0,force:!0})}}
@@ -1 +1 @@
1
- import{existsSync as e}from"node:fs";import{homedir as t}from"node:os";import chalk from"chalk";import{aienvPaths as o}from"./aienv.js";import{isExamSetupComplete as n}from"./exam-setup.js";import{mujocoVersionsLine as i,probeMujoco as s}from"./mujoco-setup.js";import{probePython as a}from"./python-setup.js";const r=[{id:"python",step:"0",verb:"python setup",size:"~30 MB · 20 s",sudo:!1,what:{en:"Python 3.12 — run code in /py, arena /run and notebooks",zh:"Python 3.12 —— /py、赛场 /run、notebook 本机跑代码"}},{id:"mujoco",step:"0b",verb:"mujoco setup",size:"~45 MB",sudo:!1,what:{en:"MuJoCo robot sim — the duck cards move on this machine",zh:"MuJoCo 机器人仿真 —— 鸭子卡在本机动起来"}},{id:"aienv",step:"1",verb:"aienv setup",size:"~300 MB",sudo:!1,what:{en:"numpy / pandas / matplotlib venv — plot cards, EDA labs, ipynb",zh:"numpy / pandas / matplotlib 环境 —— 出图卡、EDA、ipynb"}},{id:"exam",step:"2",verb:"exam setup",size:"~150 MB",sudo:!1,what:{en:"exam practical toolkit — National Selection papers A / B only",zh:"考试实操工具包 —— 只有国家选拔 A / B 卷需要"}},{id:"env",step:"3",verb:"env setup",size:"~500 MB · sudo",sudo:!0,what:{en:"110 CTF tools — CTF finals, ctf4ai, ai4ctf",zh:"110 个 CTF 工具 —— CTF 决赛、ctf4ai、ai4ctf"}}];export function defaultProbes(r={}){return{python:()=>{const e=a(!0),t="aienv"===e.source?"aienv venv":"icoa"===e.source?"installed by icoa":"on this machine";return e.ok?{ok:!0,detail:`Python ${e.version} · ${t}`}:{ok:!1,detail:e.otherVersion?`only Python ${e.otherVersion} here (courses run on 3.12)`:void 0}},mujoco:()=>{const e=s();return{ok:e.ok,detail:e.ok?i(e):void 0}},aienv:()=>{const n=o(t());return{ok:e(n.marker)&&e(n.python),detail:e(n.root)?n.root:void 0}},exam:()=>({ok:n()}),env:r.probeEnv}}export function ladder(e){return r.map(t=>{let o,n="missing";if("env"===t.id){const t=e.env?.()??null;t?(n=t.installed>=.8*t.total?"ok":t.installed>0?"partial":"missing",o=`${t.installed} / ${t.total} tools`):o=void 0}else{const i=e[t.id]?.();i&&(n=i.ok?"ok":"missing",o=i.detail)}return{...t,state:n,detail:o}})}export function needsFor(e){const t=(e??"").toLowerCase();return t?["oc-","selective-","coach","saamb","fllfu","fllfd","typing","shabc","coretools","cbabc","outabc","cadabc","datacol","physics-48","chemistry-48","biology-48","aifound","ioai-jr","iaio-jr"].some(e=>t.startsWith(e))?[]:t.startsWith("mduck")?["python","mujoco"]:["ioai","iaio","math4ai","aimo","worldmodel","ai4sci","ai4quant","ai4sports","neuro","biology","chemistry","physics","econ","pst-"].some(e=>t.startsWith(e))?["python","aienv"]:["ai4ctf","ctf4ai","ctf4eai","sc-","embodied","eai-"].some(e=>t.startsWith(e))?["python","env"]:["python"]:[]}export function nextRung(e,t){for(const o of t){const t=e.find(e=>e.id===o);if(t&&"ok"!==t.state)return t}return null}export function renderLadder(e,t={}){const o=!0===t.zh,n=!0===t.ascii,i=needsFor(t.curriculumId),s=nextRung(e,i),a=n?"[x]":"✅",r=n?"[ ]":"○ ",u=n?"[~]":"◐ ",d=n?">":"▸",c=n?"":"🧰 ",p=[];p.push(` ${chalk.bold.white(`${c}${o?"安装阶梯":"Setup ladder"}`)}${chalk.gray(o?" — 这台机器有什么、这门课要什么、该敲什么":" — what this machine has, what this course needs, what to type")}`),p.push(chalk.gray(" ─────────────────────────────────────────────")),t.curriculumId?p.push(0===i.length?chalk.gray(o?` ${t.curriculumId}:读卡和答题不需要安装任何东西。`:` ${t.curriculumId}: reading cards and answering needs nothing installed.`):chalk.gray(o?` ${t.curriculumId} 需要:`:` ${t.curriculumId} needs: `)+chalk.white(i.map(e=>`${e} setup`).join(" · "))):p.push(chalk.gray(o?" 读卡和答题不需要安装任何东西;跑代码才要下面的。":" Reading cards and answering needs none of this; running code does.")),p.push("");for(const t of e){const e=s?.id===t.id,n=i.includes(t.id),c="ok"===t.state?chalk.green(a):"partial"===t.state?chalk.yellow(u):e?chalk.bold.green(`${d} `):chalk.gray(r),h=e?chalk.bold.green(t.verb.padEnd(14)):chalk.cyan(t.verb.padEnd(14)),l=n?chalk.white(o?" ← 这门课要":" ← this course"):"";p.push(` ${chalk.white(t.step.padStart(2))} ${c} ${h}${chalk.gray(`${t.size}${t.sudo?"":o?" · 免 sudo":" · no sudo"}`)}${l}`);const m=o?t.what.zh:t.what.en,y=t.detail?chalk.gray(` · ${t.detail}`):"env"===t.id&&"missing"===t.state?chalk.gray(o?" · 未探测(setup env 会查)":" · not probed (setup env checks)"):"";p.push(` ${chalk.gray(m)}${y}`)}p.push("");const h=t.inLearn?o?"在这里直接敲":"type it right here":o?"在 icoa> 敲":"type it at icoa>";return s?p.push(` ${chalk.bold.green(`${d} ${o?"下一步敲:":"next, type:"} setup ${s.id}`)}${chalk.gray(` (${h} · ${o?"或":"or"} ${s.verb})`)}`):i.length>0&&p.push(` ${chalk.green(a)} ${chalk.white(o?"这门课需要的都装好了。":"Everything this course needs is installed.")}`),p.push(chalk.gray(` setup all = ${o?"把这门课缺的按顺序装完":"install every missing rung this course needs, in order"} · setup <python|mujoco|aienv|exam|env>`)),p}
1
+ import{existsSync as e}from"node:fs";import{homedir as t}from"node:os";import chalk from"chalk";import{aienvPaths as o}from"./aienv.js";import{mujocoVersionsLine as n,probeMujoco as i}from"./mujoco-setup.js";import{probePython as s}from"./python-setup.js";const r=[{id:"python",step:"0",verb:"python setup",size:"~30 MB · 20 s",sudo:!1,what:{en:"Python 3.12 — run code in /py, arena /run and notebooks",zh:"Python 3.12 —— /py、赛场 /run、notebook 本机跑代码"}},{id:"mujoco",step:"0b",verb:"mujoco setup",size:"~45 MB",sudo:!1,what:{en:"MuJoCo robot sim — the duck cards move on this machine",zh:"MuJoCo 机器人仿真 —— 鸭子卡在本机动起来"}},{id:"aienv",step:"1",verb:"aienv setup",size:"~300 MB",sudo:!1,what:{en:"numpy / pandas / matplotlib venv — plot cards, EDA labs, ipynb",zh:"numpy / pandas / matplotlib 环境 —— 出图卡、EDA、ipynb"}},{id:"env",step:"2",verb:"env setup",size:"~500 MB · sudo",sudo:!0,what:{en:"~100 CTF tools (no pwn / web) — CTF finals, ctf4ai, ai4ctf",zh:"约 100 个 CTF 工具(不含 pwn / web)—— CTF 决赛、ctf4ai、ai4ctf"}}];export function defaultProbes(r={}){return{python:()=>{const e=s(!0),t="aienv"===e.source?"aienv venv":"icoa"===e.source?"installed by icoa":"on this machine";return e.ok?{ok:!0,detail:`Python ${e.version} · ${t}`}:{ok:!1,detail:e.otherVersion?`only Python ${e.otherVersion} here (courses run on 3.12)`:void 0}},mujoco:()=>{const e=i();return{ok:e.ok,detail:e.ok?n(e):void 0}},aienv:()=>{const n=o(t());return{ok:e(n.marker)&&e(n.python),detail:e(n.root)?n.root:void 0}},env:r.probeEnv}}export function ladder(e){return r.map(t=>{let o,n="missing";if("env"===t.id){const t=e.env?.()??null;t?(n=t.installed>=.8*t.total?"ok":t.installed>0?"partial":"missing",o=`${t.installed} / ${t.total} tools`):o=void 0}else{const i=e[t.id]?.();i&&(n=i.ok?"ok":"missing",o=i.detail)}return{...t,state:n,detail:o}})}export function needsFor(e){const t=(e??"").toLowerCase();return t?["oc-","selective-","coach","saamb","fllfu","fllfd","typing","shabc","coretools","cbabc","outabc","cadabc","datacol","physics-48","chemistry-48","biology-48","aifound","ioai-jr","iaio-jr"].some(e=>t.startsWith(e))?[]:t.startsWith("mduck")?["python","mujoco"]:["ioai","iaio","math4ai","aimo","worldmodel","ai4sci","ai4quant","ai4sports","neuro","biology","chemistry","physics","econ","pst-"].some(e=>t.startsWith(e))?["python","aienv"]:["ai4ctf","ctf4ai","ctf4eai","sc-","embodied","eai-"].some(e=>t.startsWith(e))?["python","env"]:["python"]:[]}export function nextRung(e,t){for(const o of t){const t=e.find(e=>e.id===o);if(t&&"ok"!==t.state)return t}return null}export function renderLadder(e,t={}){const o=!0===t.zh,n=!0===t.ascii,i=needsFor(t.curriculumId),s=nextRung(e,i),r=n?"[x]":"✅",a=n?"[ ]":"○ ",u=n?"[~]":"◐ ",d=n?">":"▸",c=n?"":"🧰 ",p=[];p.push(` ${chalk.bold.white(`${c}${o?"安装阶梯":"Setup ladder"}`)}${chalk.gray(o?" — 这台机器有什么、这门课要什么、该敲什么":" — what this machine has, what this course needs, what to type")}`),p.push(chalk.gray(" ─────────────────────────────────────────────")),t.curriculumId?p.push(0===i.length?chalk.gray(o?` ${t.curriculumId}:读卡和答题不需要安装任何东西。`:` ${t.curriculumId}: reading cards and answering needs nothing installed.`):chalk.gray(o?` ${t.curriculumId} 需要:`:` ${t.curriculumId} needs: `)+chalk.white(i.map(e=>`${e} setup`).join(" · "))):p.push(chalk.gray(o?" 读卡和答题不需要安装任何东西;跑代码才要下面的。":" Reading cards and answering needs none of this; running code does.")),p.push("");for(const t of e){const e=s?.id===t.id,n=i.includes(t.id),c="ok"===t.state?chalk.green(r):"partial"===t.state?chalk.yellow(u):e?chalk.bold.green(`${d} `):chalk.gray(a),h=e?chalk.bold.green(t.verb.padEnd(14)):chalk.cyan(t.verb.padEnd(14)),l=n?chalk.white(o?" ← 这门课要":" ← this course"):"";p.push(` ${chalk.white(t.step.padStart(2))} ${c} ${h}${chalk.gray(`${t.size}${t.sudo?"":o?" · 免 sudo":" · no sudo"}`)}${l}`);const m=o?t.what.zh:t.what.en,y=t.detail?chalk.gray(` · ${t.detail}`):"env"===t.id&&"missing"===t.state?chalk.gray(o?" · 未探测(setup env 会查)":" · not probed (setup env checks)"):"";p.push(` ${chalk.gray(m)}${y}`)}p.push("");const h=t.inLearn?o?"在这里直接敲":"type it right here":o?"在 icoa> 敲":"type it at icoa>";return s?p.push(` ${chalk.bold.green(`${d} ${o?"下一步敲:":"next, type:"} setup ${s.id}`)}${chalk.gray(` (${h} · ${o?"或":"or"} ${s.verb})`)}`):i.length>0&&p.push(` ${chalk.green(r)} ${chalk.white(o?"这门课需要的都装好了。":"Everything this course needs is installed.")}`),p.push(chalk.gray(` setup all = ${o?"把这门课缺的按顺序装完":"install every missing rung this course needs, in order"} · setup <python|mujoco|aienv|env>`)),p}