icoa-cli 2.19.709 → 2.19.710

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 t,readFileSync as n,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 j}from"../lib/gpu.js";import{shouldExecuteCell as G}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{isPng as I,mdImages as N,mdWithoutImages as O,thumbForTerminal as T}from"../lib/term-image.js";import{NotebookKernel as M,buildRemoteBridgeCommand as D}from"../lib/kernel.js";import{getMainRl as q,setMainRl as L}from"../lib/main-rl.js";import{logCommand as z}from"../lib/logger.js";import{startLogSync as R,stopLogSync as K}from"../lib/log-sync.js";import{cellPreview as B,fromWholeEditText as F,mergeReloadedCells as W,normalizePathArg as J,parseIpynb as V,parsePercentPy as Y,parseRunRange as H,serializeIpynb as X,statusChar as Z,toWholeEditText as Q}from"../lib/notebook-doc.js";import{committeeLease as ee,readCommitteeSession as oe,TIER_LABEL as te}from"../lib/gputask-session.js";import{enterPanel as ne,leavePanel as le,printHelp as re}from"../lib/guide-panel.js";import{lazyFile as ae}from"../lib/lazy-assets.js";import{openFile as se}from"../lib/open-file.js";import{serviceBase as ie,siteBase as ce}from"../lib/site.js";const ge=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function ye(){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 de(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const ue=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),he=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function pe(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const fe=ce();function me(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):fe}function we(){return u(a(),".icoa","gpu-key")}function be(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(we(),"utf-8").trim()||null}catch{return null}}async function ke(e,o,t){try{const n=await fetch(`${me()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{key:o,task:t}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await n.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function ve(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let $e=0,_e=null;function xe(e,o){for(const t of e.outputs)if("stream"===t.kind){const e=t.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===t.name?chalk.yellow(e):chalk.white(e))}else if("result"===t.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(t.text));else if("error"===t.kind){console.log(chalk.bold.red(` ${t.ename}: ${t.evalue}`));for(const e of t.traceback)console.log(chalk.gray(` ${e.replace(ge,"")}`))}else"display"===t.kind&&Pe(t.data,o)}function Pe(e,t){if(e["image/png"])try{o(t,{recursive:!0}),$e+=1;const n=u(t,`figure-${$e}.png`),l=Buffer.from(e["image/png"],"base64");r(n,l),_e=n;for(const e of T(l))console.log(e);return console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(n)),void(se(n)?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 Se(t,a,s){for(const i of N(t.source)){const c=i.alt||g(i.target.split("?")[0])||"image";let y=null,p="png";try{if(i.target.startsWith("attachment:")){const e=t.attachments?.[decodeURIComponent(i.target.slice(11))],o=e?Object.keys(e).find(e=>e.startsWith("image/")):void 0;e&&o&&(y=Buffer.from(e[o],"base64"),p="image/jpeg"===o?"jpg":o.slice(6).replace("svg+xml","svg"))}else if(i.target.startsWith("data:image/")){const e=/^data:image\/([a-z0-9+.-]+);base64,(.+)$/i.exec(i.target);e&&(y=Buffer.from(e[2],"base64"),p="jpeg"===e[1]?"jpg":e[1].replace("svg+xml","svg"))}else{if(/^https?:/i.test(i.target)){console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+chalk.gray(` — web image, not fetched: ${i.target}`));continue}{const o=d(i.target)?i.target:h(a,decodeURIComponent(i.target));e(o)&&l(o).size<=31457280&&(y=n(o),p=(o.split(".").pop()||"png").toLowerCase())}}}catch{y=null}if(!y){console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+chalk.gray(` — image not found: ${i.target.slice(0,60)}`));continue}let f="";try{o(s,{recursive:!0}),$e+=1,f=u(s,`figure-${$e}.${p.replace(/[^a-z0-9]/g,"")||"png"}`),r(f,y),_e=f}catch{f=""}const m=I(y)?T(y):[];for(const e of m)console.log(e);console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+(f?chalk.gray(" → ")+chalk.cyan(f):"")+chalk.gray(m.length?" (type ":" (no in-terminal preview for this format — type ")+chalk.cyan("open")+chalk.gray(" for full size)"))}}function Ee(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function Ce(e){if(e)try{return l(e).mtimeMs}catch{return}}function je(o){const t=J(o,a()),l=d(t)?t:h(process.cwd(),t);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=n(l,"utf8"),o=l.endsWith(".ipynb")?V(e):Y(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:Ce(l),diskSig:Ee(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 Ge={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const I=E?.trim().toLowerCase().replace(/-demo$/,"");if(I&&Ge[I]){const t=await async function(t){const l=Ge[t],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 ae(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 ${t}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,n(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}(I);if(!t)return;E=t}const N=p(a()),T=u(a(),".icoa","ipynb-out");de();const ce=e(N.python),fe=oe();if(!ce&&!fe)return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),console.log(chalk.gray(" (Committee seat holders: open the seat with ")+chalk.cyan("gpufortask")+chalk.gray(" and the notebook runs there instead.)")),void console.log();const $e=E?je(E):null,Pe=$e?$e.doc:{cells:[],path:null,dirty:!1},Ue=()=>Pe.path?y(Pe.path):void 0;let Ae=new M({venvPython:N.python,venvRoot:N.root,cwd:Ue()}),Ie=null,Ne=null,Oe=null,Te=ve(Pe.path);if(ce){process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Ae.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready."))}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — cells run on your committee seat: type ")+chalk.bold.green("gpu on")+chalk.gray("."));$e&&console.log($e.note);let Me=!1,De=!1;ne({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:()=>Me},{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:()=>De},{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!==Ie,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:()=>Qe()});const qe=q(),Le=null!==qe,ze=Le?qe.listeners("line").slice():[];Le&&qe.removeAllListeners("line");const Re=Le?qe:c({input:process.stdin,output:process.stdout,terminal:!0});Le||L(Re);const Ke=Le?Re.prompt:null,Be=Le?Re.getPrompt():"";Le&&(Re.prompt=i.prototype.prompt),Le||R();const Fe=[];let We,Je=!1,Ve=!1,Ye=!1,He=null,Xe=null;const Ze=()=>{if(Xe)return Re.setPrompt(chalk.bold.cyan(` editor 1-${Xe.options.length} > `)),void Re.prompt();const e=Ie?"icoa ipynb ⚡gpu":"icoa ipynb";Re.setPrompt(chalk.bold.cyan(Fe.length?`${e} ...> `:`${e}> `)),Re.prompt()},Qe=()=>{const o=Pe.path?y(Pe.path):process.cwd(),t=ve(Pe.path);let l="",r=!1;try{const e=JSON.parse(n(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"))),Ie?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(t?" — trains the baseline, writes submission.csv":" — runs every cell top to bottom")),t&&"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."))):t&&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."))):t?(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 eo=()=>{};const oo=new Promise(e=>{eo=e}),to=async()=>{if(Ae=new M({venvPython:N.python,venvRoot:N.root,cwd:Ue()}),e(N.python)){process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Ae.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — ")+chalk.cyan("gpu on")+chalk.gray(" reconnects to your seat."))},no=async(e,t=!1)=>{const n=ee(e),l=S(n);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=`${n.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=D(n.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new M({spawnSpec:{command:"ssh",args:P(n,s,d)},readyTimeoutMs:9e4});t||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 Ae.shutdown().catch(()=>{}),Ae=h,Ie={...n,outDir:c},Oe=e,Ne=Date.now(),h.onUnexpectedExit=()=>{Ae===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).")),Ie=null,Oe=null,Ne=null,to().then(()=>Ze()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${te[e.tier]} · cells run in ${c}`));const p=await lo();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},lo=async()=>{if(!Pe.path||!Ie?.outDir)return 0;const e=y(Pe.path);let o=[];try{o=t(e)}catch{return 0}let r=0;for(const t of o){if(t.startsWith("."))continue;const o=u(e,t);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await Ae.putFile(`${Ie.outDir}/${t}`,n(o)),r++}catch{}}return r},ro=async(e,t=!1)=>{if(!Ie)return t||console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed).")),!1;const n=e.trim()||"submission.csv",l=n.startsWith("/")?n:`${Ie.outDir}/${n}`;let a;try{a=await Ae.fetchFile(l)}catch(e){return console.log(chalk.yellow(` could not fetch ${l}: `)+chalk.gray(e instanceof Error?e.message:String(e))),console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)")),!1}const s=Te?u(process.cwd(),"icoa-kaggle",Te):process.cwd(),i=u(s,g(n));try{o(s,{recursive:!0}),r(i,a)}catch{return console.log(chalk.yellow(" could not write the file here — check directory permissions.")),!1}return console.log(chalk.green(" ✓ downloaded ")+chalk.white(i)+chalk.gray(` (${a.length} bytes)`)),!t&&Te&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Te}`)+chalk.gray(" · score it: ")+chalk.cyan("submit")),!0},ao=async e=>{const[t,...n]=e.trim().split(/\s+/),l=(t??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ie)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=oe();if(e)return void await(async e=>{await no(e)})(e);const t=be();if(!t)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)."));Te||(Te=ve(Pe.path));const n=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await ke("lease",t,Te??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-n)/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 ke("status",t),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 ke("release",t);const y=Te?`${l.dataRoot}/${Te}`:l.dataRoot,d=D(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 ke("release",t)}h={command:"ssh",args:P(l,e,d)}}const p=new M({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 ke("release",t)}await Ae.shutdown().catch(()=>{}),Ae=p,Ie=l,Ne=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=j(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.")),Te&&console.log(chalk.gray(` Dataset is already on the box (${Te}) — 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(Ie&&Oe){const e=Ne?Math.round((Date.now()-Ne)/1e3):0;return await Ae.shutdown().catch(()=>{}),Ie=null,Oe=null,Ne=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 to()}if(!Ie)return void console.log(chalk.gray(" not on a GPU kernel."));const e=be(),o=void 0!==Ie.gpuName,t=Ne?Math.round((Date.now()-Ne)/1e3):0;await Ae.shutdown().catch(()=>{}),e&&await ke("release",e),Ie=null,Ne=null;const n=Math.floor(t/60),l=n>0?`${n} m ${t%60} s`:`${t} 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 to()})():"status"===l||""===l?await(async()=>{const e=oe();if(e)return console.log(chalk.green(` ⚡ committee seat · ${te[e.tier]} · ${e.host}`)+chalk.gray(Oe?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=be();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const t=await ke("status",o);if("ready"===t.state){const e=Math.round((t.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Ie?" (this notebook is connected)":" (not connected here — gpu on)"));const o=j(t.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===t.state?console.log(chalk.yellow(` ${C(t)}`)):"none"===t.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${t.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=be();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const t=await fetch(`${me()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),n=await t.json();o=n.data??n}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 t="number"==typeof o.boxes?o.boxes:0,n="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(` · ${t} box${1===t?"":"es"} · ${n} free`));const a=j("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===t?" (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:"?",t="number"==typeof e.time_left_sec?e.time_left_sec:0,n=Math.floor(t/60),l=String(t%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${n}:${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:"?",t="number"==typeof e.position?e.position:"?",n=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${t} `)+chalk.white(o.padEnd(8))+n)}console.log()})():"key"===l?(e=>{const t=e.trim();if(t)try{o(u(a(),".icoa"),{recursive:!0}),r(we(),`${t}\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(` (${we()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(n.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>"))},so=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}},io=(e,o)=>{if(e.length<=o)return e;const t=Math.floor(.6*o);return`${e.slice(0,t)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-t))}`};let co=!1;const go=()=>{const e=w().notebookEditor;return e?_(e):null},yo=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),uo=()=>go()??x(),ho={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"},po=(e,o)=>{if(e){const t=_(e);return t?v(t.cmd)?(o(t),!0):(console.log(chalk.yellow(` ${$(t)} 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(go()||yo())return o(uo()),!0;const t=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return t.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 t=$(e);console.log(chalk.cyan(` ${o+1} ${t.padEnd(5)}`)+chalk.gray(` ${ho[t]??""}`)+("nano"===t?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(t),Xe={resume:o,tries:0,options:t},!1)},fo=e=>{if(!Pe.path)return!1;let o;try{const e=n(Pe.path,"utf8");o=Pe.path.endsWith(".ipynb")?V(e):Y(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 t=W(Pe.cells,o);return Pe.cells=t.cells,Pe.dirty=!1,Pe.mtimeMs=Ce(Pe.path),Pe.diskSig=Ee(o),We=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Pe.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${t.cells.length} cells, ${t.changed} changed`)+chalk.gray(t.kept?`, ${t.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},mo=()=>void 0!==Pe.diskSig?Ee(Pe.cells)!==Pe.diskSig:Pe.dirty,wo=(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)),bo=async o=>{if(o.trim()&&z(`ipynb: ${o.trim()}`),Ve)return void(o.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Xe){const e=Xe,t=o.trim().toLowerCase(),n=_(t),l=/^\d+$/.test(t)?e.options[Number(t)-1]:n?e.options.find(e=>$(e)===$(n)):void 0;return l?(Xe=null,b({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===t||["q","quit","back","cancel","exit"].includes(t)?(Xe=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Xe=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 Ze()}let t=o.trim();if(0===Fe.length&&/^icoa\s+[a-z/]/i.test(t)&&(t=t.replace(/^icoa\s+/i,"")),0===Fe.length){const o=t.split(/\s+/),l=(o[0]??"").toLowerCase(),i=t.slice(o[0]?.length??0).trim();if("quit"!==l&&"exit"!==l&&"q"!==l&&(Ye=!1),He&&l!==He&&(He=null),he.has(l)&&(()=>{if(!Pe.path||void 0===Pe.mtimeMs)return;const e=Ce(Pe.path);if(void 0!==e&&e!==Pe.mtimeMs){if(mo()){if(We===e)return;return We=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"))}fo(!0)}})(),"quit"===l||"exit"===l||"back"===l||"q"===l||"menu"===l)return Pe.dirty&&!Ye?(Ye=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ze()):void await(async()=>{if(le("ipynb"),Re.removeAllListeners("line"),Le||K(),console.log(),Ie&&Oe)Ie=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(Ie){const e=be();e&&await ke("release",e),Ie=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Ae.shutdown().catch(()=>{}),Le){Ke&&(Re.prompt=Ke),Re.setPrompt(Be);for(const e of ze)Re.on("line",e);Re.prompt(),eo()}else L(null),eo(),Re.close()})();if("clear"===l||"cls"===l)return console.clear(),de(),void Ze();if("restart"===l)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Ae.shutdown().catch(()=>{});try{await Ae.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 Ze();if("help"===l||"?"===l)return/^(all|commands|full)$/i.test(i.trim())?(console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor vi")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(ye()?" 问 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()):re(),void Ze();if("guide"===l||"/guide"===l)return Qe(),void Ze();if("python"===l||"python3"===l)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void Ze();if("open"===l&&""===i)return _e&&se(_e)?console.log(chalk.gray(" reopening ")+chalk.cyan(_e)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ze();if("cells"===l||"ls"===l)return(()=>{if(Me=!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,t)=>{const n=Z(o),l="✓"===n?chalk.green(n.padEnd(2)):"✗"===n?chalk.red(n.padEnd(2)):"md"===n?chalk.magenta(n.padEnd(2)):chalk.gray(n.padEnd(2));console.log(`${chalk.cyan(String(t+1).padStart(4))} ${l} ${chalk.white(B(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 Ze();if("show"===l)return(e=>{const o=so(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(o.cell.source)))console.log(e);Se(o.cell,Pe.path?y(Pe.path):process.cwd(),T),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 ──")),xe(o.cell.result,T)),console.log()}})(i),void Ze();if("edit"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ").toLowerCase();return""===t||"all"===t?po(o,e=>(e=>{Re.pause();const o=k(Q(Pe.cells),".py",e,"notebook");if(Re.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 t=F(o,Pe.cells);if(t.same)return void console.log(chalk.gray(" no changes."));if(0===t.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=t.cells,Pe.dirty=!0;const n=[];t.changed.length&&n.push(`${t.changed.length} changed (${t.changed.join(", ")})`),t.added.length&&n.push(`${t.added.length} added (${t.added.join(", ")})`),t.deleted&&n.push(`${t.deleted} deleted`),t.reordered&&n.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${Pe.cells.length} cells`)+chalk.gray(` · ${n.join(" · ")}`));const l=[...t.changed,...t.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)):so(t)&&po(o,e=>((e,o)=>{const t=so(e);if(!t)return;Re.pause();const n=k(t.cell.source,"markdown"===t.cell.kind?".md":".py",o);if(Re.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=n.replace(/\s+$/,"");l!==t.cell.source?(t.cell.source=l,t.cell.result=null,t.cell.rawOutputs=void 0,t.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${t.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${t.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(t,e)),void Ze()}if("add"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ");return po(o,e=>((e,o)=>{const t=e.trim().toLowerCase(),n="md"===t||"markdown"===t||"text"===t||"txt"===t;if(t&&!n&&"py"!==t&&"code"!==t&&"python"!==t)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Re.pause();const l=k(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py",o);Re.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Pe.cells.push({kind:n?"markdown":"code",source:r,result:null}),Pe.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Pe.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Pe.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(t,e)),void Ze()}if("editor"===l&&/^[\w-]*$/.test(i))return(e=>{const o=e.trim().toLowerCase(),t=$(uo());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(t)+chalk.gray(` (${go()?"saved":yo()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),n=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(n?` ${ho[e]}`:" not installed here")+(e===t?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 n=_(o);if(!n)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=$(n);go()&&$(go())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(n.cmd)?(b({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${t===l?"default":t}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(i),void Ze();if("reload"===l&&""===i)return Pe.path&&e(Pe.path)?mo()&&"reload"!==He?(He="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."))):(He=null,fo(!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 Ze();if("load"===l&&!/^[=(.[]/.test(i)||"open"===l&&""!==i){if(!i)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ze();const o=J(i,a()),t=d(o)?o:h(process.cwd(),o);if(e(t))if(Pe.dirty&&"load"!==He)He="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(l)+chalk.yellow(" again to discard them."));else{He=null;const e=je(t);Pe.cells=e.doc.cells,Pe.path=e.doc.path,Pe.dirty=!1,Pe.mtimeMs=e.doc.mtimeMs,Pe.diskSig=e.doc.diskSig,We=void 0,Te=ve(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(t)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ze()}if("del"===l||"delete"===l)return(e=>{const o=so(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(" 重看一眼"):"")))})(i),void Ze();if(("md"===l||"py"===l)&&/^\d+$/.test(i))return((e,o)=>{const t=so(e);if(!t)return;const n="markdown"===o?"markdown":"Python";t.cell.kind!==o?(t.cell.kind=o,t.cell.result=null,t.cell.rawOutputs=void 0,t.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${t.idx} → ${n}`)+chalk.gray(" — ")+chalk.cyan(`run ${t.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${t.idx} is already ${n}.`))})(i,"md"===l?"markdown":"code"),void Ze();if("gpu"===l)return Ve=!0,await ao(i),Ve=!1,void Ze();if("download"===l||"dl"===l)return Ve=!0,await ro(i),Ve=!1,void Ze();if("selfcheck"===l||"self-check"===l)return Ve=!0,await(async()=>{const e=Oe;if(!e||!Ie)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 · ${te[e.tier]} · every code cell from the top`));const o=Ae;if(await no(e,!0),Ae===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const t=Date.now(),n=[];let l=!1;for(let e=0;e<Pe.cells.length;e++){const o=Pe.cells[e];if("code"!==o.kind)continue;const t=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${t} … `));try{o.result=await Ae.execute(o.source)}catch(e){n.push({n:t,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(n.push({n:t,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){xe(o.result,T),l=!0;break}}const r=Date.now()-t,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 Ae.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:n,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(`${ie("ICOA_GPUTASK_SERVER").replace(/\/$/,"")}/api/icoa/gputask/selfcheck`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,report:y}),signal:AbortSignal.timeout(2e4)});console.log(o.ok?chalk.gray(" report filed with the committee ✓"):chalk.yellow(` report not filed (http ${o.status}) — keep the numbers above.`))}catch{console.log(chalk.yellow(" report not filed (offline) — keep the numbers above."))}})(),Ve=!1,void Ze();if("upload"===l||"up"===l||"put"===l)return Ve=!0,await(async e=>{if(!Ie)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 t=J(o,a()),l=d(t)?t:h(Pe.path?y(Pe.path):process.cwd(),t);let r;try{r=n(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${Ie.outDir}/${g(l)}`;try{const e=await Ae.putFile(s,r);console.log(chalk.green(" ✓ uploaded ")+chalk.white(s)+chalk.gray(` (${e} bytes)`))}catch(e){console.log(chalk.yellow(" upload failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),Ve=!1,void Ze();if("check"===l||"submit"===l||"kaggle"===l){const e=await import("./kaggle.js"),o=i.split(/\s+/).filter(Boolean),t="kaggle"===l?(o[0]||"").toLowerCase():l,n=("kaggle"===l?o[1]:o[0])||ve(Pe.path)||void 0;Ve=!0;try{if(("submit"===t||"check"===t)&&Ie&&!await ro("submission.csv",!0))return Ve=!1,void Ze();if("submit"===t){const o=s("sha256").update(Pe.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(n,{code_sha:o,...Oe?{sid:Oe.sid}:{},...Pe.path?{notebook:g(Pe.path)}:{}})}else"check"===t?await e.runKaggleCheck(n):"final"===t?await e.runKaggleFinal(n,o.slice(2)):"guide"===t?await e.runKaggleGuide(n):await e.runKaggle("kaggle"===l?o[0]:n)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ve=!1,void Ze()}if("board"===l){const{runBoard:e}=await import("./board.js"),o=i.split(/\s+/).filter(Boolean);Ve=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ve=!1,void Ze()}if("ai"===l||"/ai"===l)return Ve=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),t=o.length>0&&/^\d+$/.test(o[0]),l=(t?o.slice(1):o).join(" ").trim(),r=t?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=so(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 t of e.result?.outputs??[])"stream"===t.kind||"result"===t.kind?o.push(t.text):"error"===t.kind&&(o.push(`${t.ename}: ${t.evalue}`),o.push(t.traceback.map(e=>e.replace(ge,"")).join("\n")));return o.join("\n").replace(ge,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Pe.path||!ve(Pe.path))return"";try{const e=JSON.parse(n(u(y(Pe.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return io(o,350)}catch{return""}})(),c=ye(),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=io(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(),co||(co=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(ye()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${ye()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(ye()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(ye()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — 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"):"")),z(`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()})(i),Ve=!1,void Ze();if("run"===l)return Ve=!0,await(async e=>{if(!ce&&!Oe&&!Ie)return void console.log(chalk.yellow(" No kernel here yet — ")+chalk.cyan("gpu on")+chalk.yellow(" connects your committee seat (or ")+chalk.cyan("aienv setup")+chalk.yellow(" for a local one)."));const o=H(e,Pe.cells.length);if(o)for(const e of o){const t=Pe.cells[e-1];if("markdown"!==t.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(B(t,50))+chalk.gray(" ──"));try{t.result=await Ae.execute(t.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void pe()}if(Pe.dirty=!0,xe(t.result,T),wo(t,e),!t.result.ok){const t=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${t?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(ye()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(ye()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void pe()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(O(t.source)))console.log(e);Se(t,Pe.path?y(Pe.path):process.cwd(),T),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"))})(i),Ve=!1,void Ze();if("save"===l)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 t=o===Pe.path?Ce(o):void 0;if(void 0!==t&&void 0!==Pe.mtimeMs&&t!==Pe.mtimeMs&&"save"!==He)return He="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"));He=null;try{r(o,X(Pe.cells)),Pe.path=o,De=!0,Pe.dirty=!1,Pe.mtimeMs=Ce(o),Pe.diskSig=Ee(Pe.cells),We=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)))}})(i),void Ze();if(""===t)return void Ze()}if(Fe.length>0&&ue.has(t.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(t.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ze();if(Fe.push(o),!G(Fe))return 1!==Fe.length||Je||(Je=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ze();const l=Fe.join("\n").replace(/\s+$/,"");if(Fe.length=0,""!==l.trim()){Ve=!0;try{const e=await Ae.execute(l);Pe.cells.push({kind:"code",source:l,result:e}),Pe.dirty=!0,xe(e,T);const o=wo(Pe.cells[Pe.cells.length-1],Pe.cells.length);e.ok||o||pe()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),pe()}Ve=!1,Ze()}else Ze()};Re.on("line",e=>{bo(e)}),Le||Re.on("close",async()=>{await Ae.shutdown().catch(()=>{}),process.exit(0)}),Ze(),await oo}
1
+ import{existsSync as e,mkdirSync as o,readdirSync as t,readFileSync as n,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 j}from"../lib/gpu.js";import{shouldExecuteCell as G}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{isPng as I,mdImages as N,mdWithoutImages as O,thumbForTerminal as T}from"../lib/term-image.js";import{NotebookKernel as M,buildRemoteBridgeCommand as D}from"../lib/kernel.js";import{getMainRl as q,setMainRl as L}from"../lib/main-rl.js";import{logCommand as z}from"../lib/logger.js";import{startLogSync as R,stopLogSync as K}from"../lib/log-sync.js";import{cellPreview as B,fromWholeEditText as F,mergeReloadedCells as W,normalizePathArg as J,parseIpynb as V,parsePercentPy as Y,parseRunRange as H,serializeIpynb as X,statusChar as Z,toWholeEditText as Q}from"../lib/notebook-doc.js";import{committeeLease as ee,readCommitteeSession as oe,TIER_LABEL as te}from"../lib/gputask-session.js";import{enterPanel as ne,leavePanel as le,printHelp as re}from"../lib/guide-panel.js";import{lazyFile as ae}from"../lib/lazy-assets.js";import{openFile as se}from"../lib/open-file.js";import{serviceBase as ie,siteBase as ce}from"../lib/site.js";const ge=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function ye(){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 de(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const ue=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),he=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function pe(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const fe=ce();function me(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):fe}function we(){return u(a(),".icoa","gpu-key")}function be(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(we(),"utf-8").trim()||null}catch{return null}}async function ke(e,o,t){try{const n=await fetch(`${me()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{key:o,task:t}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await n.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function ve(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let $e=0,_e=null;function xe(e,o){for(const t of e.outputs)if("stream"===t.kind){const e=t.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===t.name?chalk.yellow(e):chalk.white(e))}else if("result"===t.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(t.text));else if("error"===t.kind){console.log(chalk.bold.red(` ${t.ename}: ${t.evalue}`));for(const e of t.traceback)console.log(chalk.gray(` ${e.replace(ge,"")}`))}else"display"===t.kind&&Pe(t.data,o)}function Pe(e,t){if(e["image/png"])try{o(t,{recursive:!0}),$e+=1;const n=u(t,`figure-${$e}.png`),l=Buffer.from(e["image/png"],"base64");r(n,l),_e=n;for(const e of T(l))console.log(e);return console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(n)),void(se(n)?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 Se(t,a,s){for(const i of N(t.source)){const c=i.alt||g(i.target.split("?")[0])||"image";let y=null,p="png";try{if(i.target.startsWith("attachment:")){const e=t.attachments?.[decodeURIComponent(i.target.slice(11))],o=e?Object.keys(e).find(e=>e.startsWith("image/")):void 0;e&&o&&(y=Buffer.from(e[o],"base64"),p="image/jpeg"===o?"jpg":o.slice(6).replace("svg+xml","svg"))}else if(i.target.startsWith("data:image/")){const e=/^data:image\/([a-z0-9+.-]+);base64,(.+)$/i.exec(i.target);e&&(y=Buffer.from(e[2],"base64"),p="jpeg"===e[1]?"jpg":e[1].replace("svg+xml","svg"))}else{if(/^https?:/i.test(i.target)){console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+chalk.gray(` — web image, not fetched: ${i.target}`));continue}{const o=d(i.target)?i.target:h(a,decodeURIComponent(i.target));e(o)&&l(o).size<=31457280&&(y=n(o),p=(o.split(".").pop()||"png").toLowerCase())}}}catch{y=null}if(!y){console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+chalk.gray(` — image not found: ${i.target.slice(0,60)}`));continue}let f="";try{o(s,{recursive:!0}),$e+=1,f=u(s,`figure-${$e}.${p.replace(/[^a-z0-9]/g,"")||"png"}`),r(f,y),_e=f}catch{f=""}const m=I(y)?T(y):[];for(const e of m)console.log(e);console.log(chalk.magenta(" 🖼 ")+chalk.white(c)+(f?chalk.gray(" → ")+chalk.cyan(f):"")+chalk.gray(m.length?" (type ":" (no in-terminal preview for this format — type ")+chalk.cyan("open")+chalk.gray(" for full size)"))}}function Ee(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function Ce(e){if(e)try{return l(e).mtimeMs}catch{return}}function je(o){const t=J(o,a()),l=d(t)?t:h(process.cwd(),t);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=n(l,"utf8"),o=l.endsWith(".ipynb")?V(e):Y(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:Ce(l),diskSig:Ee(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 Ge={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const I=E?.trim().toLowerCase().replace(/-demo$/,"");if(I&&Ge[I]){const t=await async function(t){const l=Ge[t],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 ae(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 ${t}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,n(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}(I);if(!t)return;E=t}const N=p(a()),T=u(a(),".icoa","ipynb-out");de();const ce=e(N.python),fe=oe();if(!ce&&!fe)return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),console.log(chalk.gray(" (Committee seat holders: open the seat with ")+chalk.cyan("gpufortask")+chalk.gray(" and the notebook runs there instead.)")),void console.log();const $e=E?je(E):null,Pe=$e?$e.doc:{cells:[],path:null,dirty:!1},Ue=()=>Pe.path?y(Pe.path):void 0;let Ae=new M({venvPython:N.python,venvRoot:N.root,cwd:Ue()}),Ie=null,Ne=null,Oe=null,Te=ve(Pe.path);if(ce){process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Ae.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready."))}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — cells run on your committee seat: type ")+chalk.bold.green("gpu on")+chalk.gray("."));$e&&console.log($e.note);let Me=!1,De=!1;ne({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:()=>Me},{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:()=>De},{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!==Ie,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:()=>Qe()});const qe=q(),Le=null!==qe,ze=Le?qe.listeners("line").slice():[];Le&&qe.removeAllListeners("line");const Re=Le?qe:c({input:process.stdin,output:process.stdout,terminal:!0});Le||L(Re);const Ke=Le?Re.prompt:null,Be=Le?Re.getPrompt():"";Le&&(Re.prompt=i.prototype.prompt),Le||R();const Fe=[];let We,Je=!1,Ve=!1,Ye=!1,He=null,Xe=null;const Ze=()=>{if(Xe)return Re.setPrompt(chalk.bold.cyan(` editor 1-${Xe.options.length} > `)),void Re.prompt();const e=Ie?"icoa ipynb ⚡gpu":"icoa ipynb";Re.setPrompt(chalk.bold.cyan(Fe.length?`${e} ...> `:`${e}> `)),Re.prompt()},Qe=()=>{const o=Pe.path?y(Pe.path):process.cwd(),t=ve(Pe.path);let l="",r=!1;try{const e=JSON.parse(n(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"))),Ie?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(t?" — trains the baseline, writes submission.csv":" — runs every cell top to bottom")),t&&"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."))):t&&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."))):t?(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 eo=()=>{};const oo=new Promise(e=>{eo=e}),to=async()=>{if(Ae=new M({venvPython:N.python,venvRoot:N.root,cwd:Ue()}),e(N.python)){process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Ae.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}}else console.log(chalk.gray(" No local Python env here (")+chalk.cyan("aienv setup")+chalk.gray(") — ")+chalk.cyan("gpu on")+chalk.gray(" reconnects to your seat."))},no=async(e,t=!1)=>{const n=ee(e),l=S(n);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=`${n.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=D(n.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new M({spawnSpec:{command:"ssh",args:P(n,s,d)},readyTimeoutMs:9e4});t||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 Ae.shutdown().catch(()=>{}),Ae=h,Ie={...n,outDir:c},Oe=e,Ne=Date.now(),h.onUnexpectedExit=()=>{Ae===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).")),Ie=null,Oe=null,Ne=null,to().then(()=>Ze()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${te[e.tier]} · cells run in ${c}`));const p=await lo();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},lo=async()=>{if(!Pe.path||!Ie?.outDir)return 0;const e=y(Pe.path);let o=[];try{o=t(e)}catch{return 0}let r=0;for(const t of o){if(t.startsWith("."))continue;const o=u(e,t);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await Ae.putFile(`${Ie.outDir}/${t}`,n(o)),r++}catch{}}return r},ro=async(e,t=!1)=>{if(!Ie)return t||console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed).")),!1;const n=e.trim()||"submission.csv",l=n.startsWith("/")?n:`${Ie.outDir}/${n}`;let a;try{a=await Ae.fetchFile(l)}catch(e){return console.log(chalk.yellow(` could not fetch ${l}: `)+chalk.gray(e instanceof Error?e.message:String(e))),console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)")),!1}const s=Te?u(process.cwd(),"icoa-kaggle",Te):process.cwd(),i=u(s,g(n));try{o(s,{recursive:!0}),r(i,a)}catch{return console.log(chalk.yellow(" could not write the file here — check directory permissions.")),!1}return console.log(chalk.green(" ✓ downloaded ")+chalk.white(i)+chalk.gray(` (${a.length} bytes)`)),!t&&Te&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Te}`)+chalk.gray(" · score it: ")+chalk.cyan("submit")),!0},ao=async e=>{const[t,...n]=e.trim().split(/\s+/),l=(t??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ie)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=oe();if(e)return void await(async e=>{await no(e)})(e);const t=be();if(!t)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)."));Te||(Te=ve(Pe.path));const n=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await ke("lease",t,Te??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-n)/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 ke("status",t),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 ke("release",t);const y=Te?`${l.dataRoot}/${Te}`:l.dataRoot,d=D(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 ke("release",t)}h={command:"ssh",args:P(l,e,d)}}const p=new M({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 ke("release",t)}await Ae.shutdown().catch(()=>{}),Ae=p,Ie=l,Ne=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=j(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.")),Te&&console.log(chalk.gray(` Dataset is already on the box (${Te}) — 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(Ie&&Oe){const e=Ne?Math.round((Date.now()-Ne)/1e3):0;return await Ae.shutdown().catch(()=>{}),Ie=null,Oe=null,Ne=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 to()}if(!Ie)return void console.log(chalk.gray(" not on a GPU kernel."));const e=be(),o=void 0!==Ie.gpuName,t=Ne?Math.round((Date.now()-Ne)/1e3):0;await Ae.shutdown().catch(()=>{}),e&&await ke("release",e),Ie=null,Ne=null;const n=Math.floor(t/60),l=n>0?`${n} m ${t%60} s`:`${t} 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 to()})():"status"===l||""===l?await(async()=>{const e=oe();if(e)return console.log(chalk.green(` ⚡ committee seat · ${te[e.tier]} · ${e.host}`)+chalk.gray(Oe?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=be();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const t=await ke("status",o);if("ready"===t.state){const e=Math.round((t.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(Ie?" (this notebook is connected)":" (not connected here — gpu on)"));const o=j(t.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===t.state?console.log(chalk.yellow(` ${C(t)}`)):"none"===t.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${t.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=be();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const t=await fetch(`${me()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),n=await t.json();o=n.data??n}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 t="number"==typeof o.boxes?o.boxes:0,n="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(` · ${t} box${1===t?"":"es"} · ${n} free`));const a=j("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===t?" (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:"?",t="number"==typeof e.time_left_sec?e.time_left_sec:0,n=Math.floor(t/60),l=String(t%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${n}:${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:"?",t="number"==typeof e.position?e.position:"?",n=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${t} `)+chalk.white(o.padEnd(8))+n)}console.log()})():"key"===l?(e=>{const t=e.trim();if(t)try{o(u(a(),".icoa"),{recursive:!0}),r(we(),`${t}\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(` (${we()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(n.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>"))},so=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}},io=(e,o)=>{if(e.length<=o)return e;const t=Math.floor(.6*o);return`${e.slice(0,t)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-t))}`};let co=!1;const go=()=>{const e=w().notebookEditor;return e?_(e):null},yo=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),uo=()=>go()??x(),ho={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"},po=(e,o)=>{if(e){const t=_(e);return t?v(t.cmd)?(o(t),!0):(console.log(chalk.yellow(` ${$(t)} 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(go()||yo())return o(uo()),!0;const t=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return t.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 t=$(e);console.log(chalk.cyan(` ${o+1} ${t.padEnd(5)}`)+chalk.gray(` ${ho[t]??""}`)+("nano"===t?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(t),Xe={resume:o,tries:0,options:t},!1)},fo=e=>{if(!Pe.path)return!1;let o;try{const e=n(Pe.path,"utf8");o=Pe.path.endsWith(".ipynb")?V(e):Y(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 t=W(Pe.cells,o);return Pe.cells=t.cells,Pe.dirty=!1,Pe.mtimeMs=Ce(Pe.path),Pe.diskSig=Ee(o),We=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Pe.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${t.cells.length} cells, ${t.changed} changed`)+chalk.gray(t.kept?`, ${t.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},mo=()=>void 0!==Pe.diskSig?Ee(Pe.cells)!==Pe.diskSig:Pe.dirty,wo=(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)),bo=async o=>{if(o.trim()&&z(`ipynb: ${o.trim()}`),Ve)return void(o.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Xe){const e=Xe,t=o.trim().toLowerCase(),n=_(t),l=/^\d+$/.test(t)?e.options[Number(t)-1]:n?e.options.find(e=>$(e)===$(n)):void 0;return l?(Xe=null,b({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===t||["q","quit","back","cancel","exit"].includes(t)?(Xe=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Xe=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 Ze()}let t=o.trim();if(0===Fe.length&&/^icoa\s+[a-z/]/i.test(t)&&(t=t.replace(/^icoa\s+/i,"")),0===Fe.length){const o=t.split(/\s+/),l=(o[0]??"").toLowerCase(),i=t.slice(o[0]?.length??0).trim();if("quit"!==l&&"exit"!==l&&"q"!==l&&(Ye=!1),He&&l!==He&&(He=null),he.has(l)&&(()=>{if(!Pe.path||void 0===Pe.mtimeMs)return;const e=Ce(Pe.path);if(void 0!==e&&e!==Pe.mtimeMs){if(mo()){if(We===e)return;return We=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"))}fo(!0)}})(),"quit"===l||"exit"===l||"back"===l||"q"===l||"menu"===l)return Pe.dirty&&!Ye?(Ye=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ze()):void await(async()=>{if(le("ipynb"),Re.removeAllListeners("line"),Le||K(),console.log(),Ie&&Oe)Ie=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(Ie){const e=be();e&&await ke("release",e),Ie=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Ae.shutdown().catch(()=>{}),Le){Ke&&(Re.prompt=Ke),Re.setPrompt(Be);for(const e of ze)Re.on("line",e);Re.prompt(),eo()}else L(null),eo(),Re.close()})();if("clear"===l||"cls"===l)return console.clear(),de(),void Ze();if("restart"===l)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Ae.shutdown().catch(()=>{});try{await Ae.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 Ze();if("help"===l||"?"===l)return/^(all|commands|full)$/i.test(i.trim())?(console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor · ")+chalk.cyan("edit N nano")+chalk.gray(" this once")),console.log(chalk.cyan(" edit")+chalk.gray(' the whole notebook at once — "# %%" lines split cells; move, add, merge,')+chalk.gray(" delete; unchanged cells keep their output")),console.log(chalk.cyan(" editor")+chalk.gray(" choose the editor: ")+chalk.cyan("editor nano")+chalk.gray(" · ")+chalk.cyan("editor code")+chalk.gray(" · ")+chalk.cyan("editor vi")),console.log(chalk.cyan(" add")+chalk.gray(" write a new Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),console.log(chalk.cyan(" ai [N] [问题]")+chalk.gray(ye()?" 问 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()):re(),void Ze();if("guide"===l||"/guide"===l)return Qe(),void Ze();if("python"===l||"python3"===l)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void Ze();if("open"===l&&""===i)return _e&&se(_e)?console.log(chalk.gray(" reopening ")+chalk.cyan(_e)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ze();if("cells"===l||"ls"===l)return(()=>{if(Me=!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,t)=>{const n=Z(o),l="✓"===n?chalk.green(n.padEnd(2)):"✗"===n?chalk.red(n.padEnd(2)):"md"===n?chalk.magenta(n.padEnd(2)):chalk.gray(n.padEnd(2));console.log(`${chalk.cyan(String(t+1).padStart(4))} ${l} ${chalk.white(B(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 Ze();if("show"===l)return(e=>{const o=so(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(o.cell.source)))console.log(e);Se(o.cell,Pe.path?y(Pe.path):process.cwd(),T),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 ──")),xe(o.cell.result,T)),console.log()}})(i),void Ze();if("edit"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ").toLowerCase();return""===t||"all"===t?po(o,e=>(e=>{Re.pause();const o=k(Q(Pe.cells),".py",e,"notebook");if(Re.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 t=F(o,Pe.cells);if(t.same)return void console.log(chalk.gray(" no changes."));if(0===t.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=t.cells,Pe.dirty=!0;const n=[];t.changed.length&&n.push(`${t.changed.length} changed (${t.changed.join(", ")})`),t.added.length&&n.push(`${t.added.length} added (${t.added.join(", ")})`),t.deleted&&n.push(`${t.deleted} deleted`),t.reordered&&n.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${Pe.cells.length} cells`)+chalk.gray(` · ${n.join(" · ")}`));const l=[...t.changed,...t.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)):so(t)&&po(o,e=>((e,o)=>{const t=so(e);if(!t)return;Re.pause();const n=k(t.cell.source,"markdown"===t.cell.kind?".md":".py",o);if(Re.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=n.replace(/\s+$/,"");l!==t.cell.source?(t.cell.source=l,t.cell.result=null,t.cell.rawOutputs=void 0,t.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${t.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${t.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(t,e)),void Ze()}if("add"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ");return po(o,e=>((e,o)=>{const t=e.trim().toLowerCase(),n="md"===t||"markdown"===t||"text"===t||"txt"===t;if(t&&!n&&"py"!==t&&"code"!==t&&"python"!==t)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));Re.pause();const l=k(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py",o);Re.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Pe.cells.push({kind:n?"markdown":"code",source:r,result:null}),Pe.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${Pe.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Pe.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(t,e)),void Ze()}if("editor"===l&&/^[\w-]*$/.test(i))return(e=>{const o=e.trim().toLowerCase(),t=$(uo());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(t)+chalk.gray(` (${go()?"saved":yo()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),n=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(n?` ${ho[e]}`:" not installed here")+(e===t?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 n=_(o);if(!n)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=$(n);go()&&$(go())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(n.cmd)?(b({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${t===l?"default":t}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(i),void Ze();if("reload"===l&&""===i)return Pe.path&&e(Pe.path)?mo()&&"reload"!==He?(He="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."))):(He=null,fo(!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 Ze();if("load"===l&&!/^[=(.[]/.test(i)||"open"===l&&""!==i){if(!i)return console.log(chalk.gray(" usage: ")+chalk.cyan("load <file.ipynb>")+chalk.gray(" — tip: drag the file into this window, then Enter.")),void Ze();const o=J(i,a()),t=d(o)?o:h(process.cwd(),o);if(e(t))if(Pe.dirty&&"load"!==He)He="load",console.log(chalk.yellow(" unsaved changes in this notebook — ")+chalk.cyan("save")+chalk.yellow(" first, or the same ")+chalk.cyan(l)+chalk.yellow(" again to discard them."));else{He=null;const e=je(t);Pe.cells=e.doc.cells,Pe.path=e.doc.path,Pe.dirty=!1,Pe.mtimeMs=e.doc.mtimeMs,Pe.diskSig=e.doc.diskSig,We=void 0,Te=ve(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(t)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ze()}if("del"===l||"delete"===l)return(e=>{const o=so(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(" 重看一眼"):"")))})(i),void Ze();if(("md"===l||"py"===l)&&/^\d+$/.test(i))return((e,o)=>{const t=so(e);if(!t)return;const n="markdown"===o?"markdown":"Python";t.cell.kind!==o?(t.cell.kind=o,t.cell.result=null,t.cell.rawOutputs=void 0,t.cell.rawExecCount=void 0,Pe.dirty=!0,console.log(chalk.green(` ✓ cell ${t.idx} → ${n}`)+chalk.gray(" — ")+chalk.cyan(`run ${t.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${t.idx} is already ${n}.`))})(i,"md"===l?"markdown":"code"),void Ze();if("gpu"===l)return Ve=!0,await ao(i),Ve=!1,void Ze();if("download"===l||"dl"===l)return Ve=!0,await ro(i),Ve=!1,void Ze();if("selfcheck"===l||"self-check"===l)return Ve=!0,await(async()=>{const e=Oe;if(!e||!Ie)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 · ${te[e.tier]} · every code cell from the top`));const o=Ae;if(await no(e,!0),Ae===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const t=Date.now(),n=[];let l=!1;for(let e=0;e<Pe.cells.length;e++){const o=Pe.cells[e];if("code"!==o.kind)continue;const t=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${t} … `));try{o.result=await Ae.execute(o.source)}catch(e){n.push({n:t,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(n.push({n:t,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){xe(o.result,T),l=!0;break}}const r=Date.now()-t,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 Ae.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:n,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(`${ie("ICOA_GPUTASK_SERVER").replace(/\/$/,"")}/api/icoa/gputask/selfcheck`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,report:y}),signal:AbortSignal.timeout(2e4)});console.log(o.ok?chalk.gray(" report filed with the committee ✓"):chalk.yellow(` report not filed (http ${o.status}) — keep the numbers above.`))}catch{console.log(chalk.yellow(" report not filed (offline) — keep the numbers above."))}})(),Ve=!1,void Ze();if("upload"===l||"up"===l||"put"===l)return Ve=!0,await(async e=>{if(!Ie)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 t=J(o,a()),l=d(t)?t:h(Pe.path?y(Pe.path):process.cwd(),t);let r;try{r=n(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${Ie.outDir}/${g(l)}`;try{const e=await Ae.putFile(s,r);console.log(chalk.green(" ✓ uploaded ")+chalk.white(s)+chalk.gray(` (${e} bytes)`))}catch(e){console.log(chalk.yellow(" upload failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),Ve=!1,void Ze();if("check"===l||"submit"===l||"kaggle"===l){const e=await import("./kaggle.js"),o=i.split(/\s+/).filter(Boolean),t="kaggle"===l?(o[0]||"").toLowerCase():l,n=("kaggle"===l?o[1]:o[0])||ve(Pe.path)||void 0;Ve=!0;try{if(("submit"===t||"check"===t)&&Ie&&!await ro("submission.csv",!0))return Ve=!1,void Ze();if("submit"===t){const o=s("sha256").update(Pe.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(n,{code_sha:o,...Oe?{sid:Oe.sid}:{},...Pe.path?{notebook:g(Pe.path)}:{}})}else"check"===t?await e.runKaggleCheck(n):"final"===t?await e.runKaggleFinal(n,o.slice(2)):"board"===t?await e.runKaggleBoard(n):"guide"===t?await e.runKaggleGuide(n):await e.runKaggle("kaggle"===l?o[0]:n)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ve=!1,void Ze()}if("board"===l){const{runBoard:e}=await import("./board.js"),o=i.split(/\s+/).filter(Boolean);Ve=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Ve=!1,void Ze()}if("ai"===l||"/ai"===l)return Ve=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),t=o.length>0&&/^\d+$/.test(o[0]),l=(t?o.slice(1):o).join(" ").trim(),r=t?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=so(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 t of e.result?.outputs??[])"stream"===t.kind||"result"===t.kind?o.push(t.text):"error"===t.kind&&(o.push(`${t.ename}: ${t.evalue}`),o.push(t.traceback.map(e=>e.replace(ge,"")).join("\n")));return o.join("\n").replace(ge,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Pe.path||!ve(Pe.path))return"";try{const e=JSON.parse(n(u(y(Pe.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return io(o,350)}catch{return""}})(),c=ye(),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=io(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(),co||(co=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(ye()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${f} ${ye()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(ye()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(ye()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — 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"):"")),z(`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()})(i),Ve=!1,void Ze();if("run"===l)return Ve=!0,await(async e=>{if(!ce&&!Oe&&!Ie)return void console.log(chalk.yellow(" No kernel here yet — ")+chalk.cyan("gpu on")+chalk.yellow(" connects your committee seat (or ")+chalk.cyan("aienv setup")+chalk.yellow(" for a local one)."));const o=H(e,Pe.cells.length);if(o)for(const e of o){const t=Pe.cells[e-1];if("markdown"!==t.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(B(t,50))+chalk.gray(" ──"));try{t.result=await Ae.execute(t.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void pe()}if(Pe.dirty=!0,xe(t.result,T),wo(t,e),!t.result.ok){const t=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${t?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(ye()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(ye()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void pe()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(O(t.source)))console.log(e);Se(t,Pe.path?y(Pe.path):process.cwd(),T),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"))})(i),Ve=!1,void Ze();if("save"===l)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 t=o===Pe.path?Ce(o):void 0;if(void 0!==t&&void 0!==Pe.mtimeMs&&t!==Pe.mtimeMs&&"save"!==He)return He="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"));He=null;try{r(o,X(Pe.cells)),Pe.path=o,De=!0,Pe.dirty=!1,Pe.mtimeMs=Ce(o),Pe.diskSig=Ee(Pe.cells),We=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)))}})(i),void Ze();if(""===t)return void Ze()}if(Fe.length>0&&ue.has(t.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(t.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ze();if(Fe.push(o),!G(Fe))return 1!==Fe.length||Je||(Je=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ze();const l=Fe.join("\n").replace(/\s+$/,"");if(Fe.length=0,""!==l.trim()){Ve=!0;try{const e=await Ae.execute(l);Pe.cells.push({kind:"code",source:l,result:e}),Pe.dirty=!0,xe(e,T);const o=wo(Pe.cells[Pe.cells.length-1],Pe.cells.length);e.ok||o||pe()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),pe()}Ve=!1,Ze()}else Ze()};Re.on("line",e=>{bo(e)}),Le||Re.on("close",async()=>{await Ae.shutdown().catch(()=>{}),process.exit(0)}),Ze(),await oo}
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 h}from"./commands/env.js";import{registerAienvCommand as f}from"./commands/aienv.js";import{registerPythonCommands as u}from"./commands/python.js";import{registerMujocoCommands as y}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{registerAi4StartupCommand as S}from"./commands/ai4startup.js";import{registerGpuForTaskCommand as L}from"./commands/gpufortask.js";import{registerSetterCommand as R}from"./commands/setter.js";import{registerSimCommand as O}from"./commands/sim.js";import{registerArenaCommand as N}from"./commands/arena.js";import{registerKaggleCommand as U}from"./commands/kaggle.js";import{registerSprintCommand as F}from"./commands/sprint.js";import{registerTeleloadCommand as P}from"./commands/teleload.js";import{registerBoardCommand as M}from"./commands/board.js";import{registerTypeCommand as G}from"./commands/type.js";import{registerBattleCommand as H}from"./commands/battle.js";import{registerWmCommand as W}from"./commands/wm.js";import{getConfig as D,saveConfig as Y}from"./lib/config.js";import{registerMicroduckCommand as V}from"./commands/microduck.js";import{startRepl as J}from"./repl.js";import{RELAUNCH_CODE as X}from"./lib/menu-nav.js";import{setTerminalTheme as q}from"./lib/theme.js";import{cleanupTerminal as z}from"./lib/terminal-cleanup.js";import{checkForUpdates as K,runUpgrade as B,bootUpgradeEligible as Q,startBootCheck as Z,printUpdateHint as oo}from"./lib/update-check.js";import{detectIcoaInstalls as eo,isWindowsBuildInWslShell as no}from"./lib/platform.js";import{ICOA_BIG as so}from"./lib/banner.js";import{readFileSync as ro}from"node:fs";import{fileURLToPath as to}from"node:url";import{dirname as io,join as lo}from"node:path";import{setDefaultResultOrder as ao}from"node:dns";import{setDefaultAutoSelectFamilyAttemptTimeout as mo}from"node:net";ao("ipv4first"),mo(4e3);const co=io(to(import.meta.url)),go=JSON.parse(ro(lo(co,"..","package.json"),"utf-8")).version,po=chalk.cyan(" ─────────────────────────────────────────────────────"),ho=`\n${po}\n\n${so.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${go}`)}\n\n${po}\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!==X){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===X);z(),process.exit(e??0)}}const fo=new o;if(fo.name("icoa").version(go).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=D();q("high-contrast"===e.themeVariant?"high-contrast":"dark");const n=!!o.resume||!!o.continue,s=Q(n)&&process.argv.length<=2;s?Z():K(),function(){const o=eo();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(ho),s?"upgraded"===await B({ask:!0})&&(console.log(chalk.gray(" restarting icoa …")),process.exit(X)):oo(),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 J(fo,n)}),e(fo),n(fo),s(fo),r(fo),t(fo),i(fo),l(fo),a(fo),m(fo),c(fo),g(fo),d(fo),p(fo),h(fo),f(fo),u(fo),y(fo),w(fo),j(fo),b(fo),v(fo),T(fo),$(fo),E(fo),A(fo),x(fo),_(fo),I(fo),k(fo),C(fo),S(fo),L(fo),R(fo),O(fo),N(fo),U(fo),P(fo),F(fo),M(fo),W(fo),G(fo),H(fo),V(fo),fo.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=D().geminiModel||"gemini-2.5-flash-lite";o?(Y({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)))}fo.hook("preAction",()=>{!function(){if(!no())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()}()}),fo.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{registerEntryCommand as m}from"./commands/entry.js";import{registerUpgradeCommand as c}from"./commands/upgrade.js";import{registerNoteCommand as g}from"./commands/note.js";import{registerLogCommand as d}from"./commands/log.js";import{registerLangCommand as p}from"./commands/lang.js";import{registerSetupCommand as h}from"./commands/setup.js";import{registerEnvCommand as f}from"./commands/env.js";import{registerAienvCommand as y}from"./commands/aienv.js";import{registerPythonCommands as u}from"./commands/python.js";import{registerMujocoCommands as w}from"./commands/mujoco.js";import{registerDuckCommand as j}from"./commands/duck.js";import{registerIpynbCommand as b}from"./commands/ipynb.js";import{registerAi4ctfCommand as v}from"./commands/ai4ctf.js";import{registerExamCommand as T}from"./commands/exam.js";import{registerCtf4aiDemoCommand as $}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as E}from"./commands/theme.js";import{registerLearnCommand as A}from"./commands/learn.js";import{registerCtf4VlaCommand as x}from"./commands/ctf4vla.js";import{registerDemo2Command as _}from"./commands/demo2.js";import{registerDemo3Command as I}from"./commands/demo3.js";import{registerDemo4Command as k}from"./commands/demo4.js";import{registerDemo5Command as C}from"./commands/demo5.js";import{registerGfssmCommand as S}from"./commands/gfssm.js";import{registerAi4StartupCommand as L}from"./commands/ai4startup.js";import{registerGpuForTaskCommand as R}from"./commands/gpufortask.js";import{registerSetterCommand as O}from"./commands/setter.js";import{registerSimCommand as N}from"./commands/sim.js";import{registerArenaCommand as U}from"./commands/arena.js";import{registerKaggleCommand as F}from"./commands/kaggle.js";import{registerSprintCommand as P}from"./commands/sprint.js";import{registerTeleloadCommand as M}from"./commands/teleload.js";import{registerBoardCommand as G}from"./commands/board.js";import{registerTypeCommand as H}from"./commands/type.js";import{registerBattleCommand as W}from"./commands/battle.js";import{registerWmCommand as D}from"./commands/wm.js";import{getConfig as Y,saveConfig as V}from"./lib/config.js";import{registerMicroduckCommand as J}from"./commands/microduck.js";import{startRepl as X}from"./repl.js";import{RELAUNCH_CODE as q}from"./lib/menu-nav.js";import{setTerminalTheme as z}from"./lib/theme.js";import{cleanupTerminal as K}from"./lib/terminal-cleanup.js";import{checkForUpdates as B,runUpgrade as Q,bootUpgradeEligible as Z,startBootCheck as oo,printUpdateHint as eo}from"./lib/update-check.js";import{detectIcoaInstalls as no,isWindowsBuildInWslShell as so}from"./lib/platform.js";import{ICOA_BIG as ro}from"./lib/banner.js";import{readFileSync as to}from"node:fs";import{fileURLToPath as io}from"node:url";import{dirname as lo,join as ao}from"node:path";import{setDefaultResultOrder as mo}from"node:dns";import{setDefaultAutoSelectFamilyAttemptTimeout as co}from"node:net";mo("ipv4first"),co(4e3);const go=lo(io(import.meta.url)),po=JSON.parse(to(ao(go,"..","package.json"),"utf-8")).version,ho=chalk.cyan(" ─────────────────────────────────────────────────────"),fo=`\n${ho}\n\n${ro.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${po}`)}\n\n${ho}\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!==q){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===q);K(),process.exit(e??0)}}const yo=new o;if(yo.name("icoa").version(po).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=Y();z("high-contrast"===e.themeVariant?"high-contrast":"dark");const n=!!o.resume||!!o.continue,s=Z(n)&&process.argv.length<=2;s?oo():B(),function(){const o=no();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(fo),s?"upgraded"===await Q({ask:!0})&&(console.log(chalk.gray(" restarting icoa …")),process.exit(q)):eo(),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 X(yo,n)}),e(yo),n(yo),s(yo),r(yo),t(yo),i(yo),l(yo),a(yo),m(yo),c(yo),g(yo),d(yo),p(yo),h(yo),f(yo),y(yo),u(yo),w(yo),j(yo),b(yo),v(yo),T(yo),$(yo),E(yo),A(yo),x(yo),_(yo),I(yo),k(yo),C(yo),S(yo),L(yo),R(yo),O(yo),N(yo),U(yo),F(yo),M(yo),P(yo),G(yo),D(yo),H(yo),W(yo),J(yo),yo.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=Y().geminiModel||"gemini-2.5-flash-lite";o?(V({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)))}yo.hook("preAction",()=>{!function(){if(!so())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()}()}),yo.parse();
@@ -1 +1 @@
1
- import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as a,existsSync as c}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb","kaggle","tmux"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const o=r();if(o.deviceFingerprint)return o.deviceFingerprint;const u=s(),d=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(c("/etc/machine-id"))return a("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}(),p=t("sha256").update(`${d}|${u}`).digest("hex");try{i({deviceFingerprint:p})}catch{}return p}const x="token-bindings";export async function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=e.trim().toUpperCase(),r=getDeviceFingerprint(),a=u(o(),"token-bindings.json"),c=d(s(),x),{data:g,verdict:h}=p(a,c);m(x,h);const v=g||{},w=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),y=v[w];if(y&&y!==r)return"already_bound";try{const{httpFetch:t}=await import("./http.js"),{EXAM_SERVER:e}=await import("./exam-server.js"),i=await t(`${e}/api/icoa/env-activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:n,fingerprint:r}),timeoutMs:1e4,idempotent:!0});if(!i.ok)return"network";const o=await i.json(),s=o?.data?.status;if("already_bound"===s)return"already_bound";if("ok"!==s)return"invalid"}catch{return"network"}return v[w]=r,f(a,v,c),i({accessToken:n,deviceFingerprint:r}),"ok"}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const h=()=>u(o(),"session-state.json"),v="session-state";function w(){return d(s(),v)}function y(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function A(){const{data:t,verdict:e}=p(h(),w());return m(v,e),t?{...y(),...t}:y()}function S(t){const e={...A(),...t};f(h(),e,w())}export function recordExit(){const t=A();t.lastExitAt=(new Date).toISOString(),t.exitCount++,S(t)}export function recordResume(){const t=A();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,S(t),{awaySeconds:r,exitCount:t.exitCount}}
1
+ import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as a,existsSync as c}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","entry","aienv","ipynb","kaggle","tmux"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const o=r();if(o.deviceFingerprint)return o.deviceFingerprint;const u=s(),d=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(c("/etc/machine-id"))return a("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}(),p=t("sha256").update(`${d}|${u}`).digest("hex");try{i({deviceFingerprint:p})}catch{}return p}const x="token-bindings";export async function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=e.trim().toUpperCase(),r=getDeviceFingerprint(),a=u(o(),"token-bindings.json"),c=d(s(),x),{data:g,verdict:h}=p(a,c);m(x,h);const v=g||{},w=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),y=v[w];if(y&&y!==r)return"already_bound";try{const{httpFetch:t}=await import("./http.js"),{EXAM_SERVER:e}=await import("./exam-server.js"),i=await t(`${e}/api/icoa/env-activate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:n,fingerprint:r}),timeoutMs:1e4,idempotent:!0});if(!i.ok)return"network";const o=await i.json(),s=o?.data?.status;if("already_bound"===s)return"already_bound";if("ok"!==s)return"invalid"}catch{return"network"}return v[w]=r,f(a,v,c),i({accessToken:n,deviceFingerprint:r}),"ok"}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const h=()=>u(o(),"session-state.json"),v="session-state";function w(){return d(s(),v)}function y(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function A(){const{data:t,verdict:e}=p(h(),w());return m(v,e),t?{...y(),...t}:y()}function S(t){const e={...A(),...t};f(h(),e,w())}export function recordExit(){const t=A();t.lastExitAt=(new Date).toISOString(),t.exitCount++,S(t)}export function recordResume(){const t=A();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,S(t),{awaySeconds:r,exitCount:t.exitCount}}
@@ -1 +1 @@
1
- export const REGISTRY=[{name:"join",mapsTo:["ctf","join"],rest:!0,help:{order:0,section:"Competition",label:"join <url>",text:"Connect to CTFd"}},{name:"activate",mapsTo:["ctf","activate"],rest:!0},{name:"challenges",mapsTo:["ctf","challenges"],help:{order:1,section:"Competition",label:"challenges (ch)",text:"List challenges by category"}},{name:"ch",mapsTo:["ctf","challenges"]},{name:"open",mapsTo:["ctf","open"],rest:!0,help:{order:2,section:"Competition",label:"open <id>",text:"Read challenge + get next steps"}},{name:"submit",mapsTo:["ctf","submit"],rest:!0,help:{order:3,section:"Competition",label:"submit <id> <flag>",text:"Submit a flag"}},{name:"flag",mapsTo:["ctf","submit"],rest:!0},{name:"scoreboard",mapsTo:["ctf","scoreboard"],rest:!0,help:{order:4,section:"Competition",label:"scoreboard (sb)",text:"Live rankings"}},{name:"sb",mapsTo:["ctf","scoreboard"],rest:!0},{name:"status",mapsTo:["ctf","status"],help:{order:5,section:"Competition",label:"status",text:"Your score & timer"}},{name:"time",mapsTo:["ctf","time"],help:{order:6,section:"Competition",label:"time",text:"Countdown timer"}},{name:"ref",help:{order:8,section:"Tools",label:"ref [topic]",text:"Quick reference (linux, web, crypto...)"}},{name:"shell",help:{order:9,section:"Tools",label:"shell",text:"Interactive CTF shell (sandbox if present, else host)"}},{name:"files",help:{order:10,section:"Tools",label:"files <id>",text:"Download challenge files"}},{name:"view"},{name:"connect",help:{order:11,section:"Tools",label:"connect <id>",text:"Connect to remote target"}},{name:"challenge",subs:["start","stop","status"]},{name:"note",help:{order:12,section:"Tools",label:"note [text]",text:"Add a logbook entry (in-exam: tags current Q)"}},{name:"notes"},{name:"logbook",help:{order:13,section:"Tools",label:"logbook [n]",text:"View your logbook (in-exam: filter by Q)"}},{name:"log",help:{order:14,section:"Tools",label:"log",text:"Session history"}},{name:"man"},{name:"manual"},{name:"lang",help:{order:21,section:"System",label:"lang [code]",text:"Switch language (15 supported)"}},{name:"setup"},{name:"env"},{name:"aienv"},{name:"python",subs:["setup","status"]},{name:"mujoco",subs:["setup","status"]},{name:"mojoco",mapsTo:["mujoco"],rest:!0},{name:"ipynb"},{name:"kaggle"},{name:"teleload"},{name:"pandahelpme31"},{name:"gpufortask"},{name:"setter"},{name:"guide"},{name:"ai4ctf",help:{order:7,section:"AI Teammate",label:"ai4ctf",text:"Free-chat with your AI teammate"}},{name:"model"},{name:"ctf",subs:["challenges","open","submit","scoreboard","status","join","logout","time"]},{name:"exam",subs:["list","start","q","answer","submit","review","result","next","prev","mark","unmark","help"]},{name:"demo",mapsTo:["exam","demo"]},{name:"retry",mapsTo:["exam","demo-retry"]},{name:"nations",mapsTo:["exam","nations"]},{name:"next",mapsTo:["exam","next"]},{name:"prev",mapsTo:["exam","prev"]},{name:"continue"},{name:"logout",mapsTo:["ctf","logout"],help:{order:22,section:"System",label:"logout",text:"Disconnect"}},{name:"ctf4ai"},{name:"mark",mapsTo:["exam","mark"],rest:!0},{name:"unmark",mapsTo:["exam","unmark"],rest:!0},{name:"review",mapsTo:["exam","review"]},{name:"learn",subs:["start","continue"]},{name:"demo2"},{name:"demo3"},{name:"demo4"},{name:"demo5"},{name:"gfssm"},{name:"ai4startup"},{name:"ctf4eai"},{name:"ctf4vla"},{name:"theme"},{name:"sim"},{name:"arena",subs:["eai"]},{name:"eai"},{name:"wm"},{name:"microduck"},{name:"battle",subs:["edit","syntax","play","replay","submit","status","bots"]},{name:"duck",subs:["edit","syntax","run","replay","submit","board","scenarios","status"]},{name:"type",subs:["15","30","60","words","python","shell","history"],help:{order:15,section:"Tools",label:"type [30]",text:"Typing speed trainer — WPM, live colours, no token"}},{name:"board"},{name:"learn-pull"},{name:"doctor",help:{order:19,section:"System",label:"doctor",text:"Self-check: version, Python, network/firewall, server"}},{name:"upgrade",help:{order:20,section:"System",label:"upgrade",text:"Install the newest icoa and restart into it"}},{name:"update"},{name:"bg",nav:!0,help:{order:17,section:"System",label:"bg <command>",text:"Run a shell command in the background"}},{name:"tasks",nav:!0,help:{order:18,section:"System",label:"tasks [id]",text:"Background task panel / view output"}},{name:"drafts",nav:!0,help:{order:16,section:"System",label:"drafts",text:"Review staged draft answers"}},{name:"help",nav:!0},{name:"menu",nav:!0},{name:"quit",nav:!0},{name:"q",nav:!0},{name:"exit",nav:!0,help:{order:24,section:"System",label:"exit",text:"Quit (session saved)"}},{name:"back",nav:!0},{name:"resume",nav:!0,help:{order:15,section:"System",label:"resume",text:"Continue your last learn card / exam"}},{name:"clear",nav:!0,help:{order:23,section:"System",label:"clear",text:"Clear screen"}},{name:"cls",nav:!0}];export const surface=()=>REGISTRY.map(e=>e.name);export const dispatchable=()=>REGISTRY.filter(e=>!e.nav).map(e=>e.name);export function shortcutFor(e,t){const a=REGISTRY.find(t=>t.name===e&&t.mapsTo);return a?.mapsTo?a.rest?[...a.mapsTo,...t]:[...a.mapsTo]:null}export const subcommandsOf=e=>REGISTRY.find(t=>t.name===e)?.subs;export const helpRows=e=>REGISTRY.filter(t=>t.help?.section===e).sort((e,t)=>e.help.order-t.help.order).map(e=>({label:e.help.label,text:e.help.text}));
1
+ export const REGISTRY=[{name:"join",mapsTo:["ctf","join"],rest:!0,help:{order:0,section:"Competition",label:"join <url>",text:"Connect to CTFd"}},{name:"activate",mapsTo:["ctf","activate"],rest:!0},{name:"challenges",mapsTo:["ctf","challenges"],help:{order:1,section:"Competition",label:"challenges (ch)",text:"List challenges by category"}},{name:"ch",mapsTo:["ctf","challenges"]},{name:"open",mapsTo:["ctf","open"],rest:!0,help:{order:2,section:"Competition",label:"open <id>",text:"Read challenge + get next steps"}},{name:"submit",mapsTo:["ctf","submit"],rest:!0,help:{order:3,section:"Competition",label:"submit <id> <flag>",text:"Submit a flag"}},{name:"flag",mapsTo:["ctf","submit"],rest:!0},{name:"scoreboard",mapsTo:["ctf","scoreboard"],rest:!0,help:{order:4,section:"Competition",label:"scoreboard (sb)",text:"Live rankings"}},{name:"sb",mapsTo:["ctf","scoreboard"],rest:!0},{name:"status",mapsTo:["ctf","status"],help:{order:5,section:"Competition",label:"status",text:"Your score & timer"}},{name:"time",mapsTo:["ctf","time"],help:{order:6,section:"Competition",label:"time",text:"Countdown timer"}},{name:"ref",help:{order:8,section:"Tools",label:"ref [topic]",text:"Quick reference (linux, web, crypto...)"}},{name:"shell",help:{order:9,section:"Tools",label:"shell",text:"Interactive CTF shell (sandbox if present, else host)"}},{name:"files",help:{order:10,section:"Tools",label:"files <id>",text:"Download challenge files"}},{name:"view"},{name:"connect",help:{order:11,section:"Tools",label:"connect <id>",text:"Connect to remote target"}},{name:"challenge",subs:["start","stop","status"]},{name:"note",help:{order:12,section:"Tools",label:"note [text]",text:"Add a logbook entry (in-exam: tags current Q)"}},{name:"notes"},{name:"logbook",help:{order:13,section:"Tools",label:"logbook [n]",text:"View your logbook (in-exam: filter by Q)"}},{name:"log",help:{order:14,section:"Tools",label:"log",text:"Session history"}},{name:"man"},{name:"manual"},{name:"lang",help:{order:21,section:"System",label:"lang [code]",text:"Switch language (15 supported)"}},{name:"setup"},{name:"env"},{name:"aienv"},{name:"python",subs:["setup","status"]},{name:"mujoco",subs:["setup","status"]},{name:"mojoco",mapsTo:["mujoco"],rest:!0},{name:"ipynb"},{name:"kaggle"},{name:"teleload"},{name:"pandahelpme31"},{name:"gpufortask"},{name:"setter"},{name:"guide"},{name:"ai4ctf",help:{order:7,section:"AI Teammate",label:"ai4ctf",text:"Free-chat with your AI teammate"}},{name:"model"},{name:"ctf",subs:["challenges","open","submit","scoreboard","status","join","logout","time"]},{name:"exam",subs:["list","start","q","answer","submit","review","result","next","prev","mark","unmark","help"]},{name:"demo",mapsTo:["exam","demo"]},{name:"retry",mapsTo:["exam","demo-retry"]},{name:"nations",mapsTo:["exam","nations"]},{name:"next",mapsTo:["exam","next"]},{name:"prev",mapsTo:["exam","prev"]},{name:"continue"},{name:"logout",mapsTo:["ctf","logout"],help:{order:22,section:"System",label:"logout",text:"Disconnect"}},{name:"ctf4ai"},{name:"mark",mapsTo:["exam","mark"],rest:!0},{name:"unmark",mapsTo:["exam","unmark"],rest:!0},{name:"review",mapsTo:["exam","review"]},{name:"learn",subs:["start","continue"]},{name:"demo2"},{name:"demo3"},{name:"demo4"},{name:"demo5"},{name:"gfssm"},{name:"ai4startup"},{name:"ctf4eai"},{name:"ctf4vla"},{name:"theme"},{name:"sim"},{name:"arena",subs:["eai"]},{name:"eai"},{name:"wm"},{name:"microduck"},{name:"battle",subs:["edit","syntax","play","replay","submit","status","bots"]},{name:"duck",subs:["edit","syntax","run","replay","submit","board","scenarios","status"]},{name:"type",subs:["15","30","60","words","python","shell","history"],help:{order:15,section:"Tools",label:"type [30]",text:"Typing speed trainer — WPM, live colours, no token"}},{name:"board"},{name:"learn-pull"},{name:"doctor",help:{order:19,section:"System",label:"doctor",text:"Self-check: version, Python, network/firewall, server"}},{name:"entry",subs:["hk","direct","auto"]},{name:"upgrade",help:{order:20,section:"System",label:"upgrade",text:"Install the newest icoa and restart into it"}},{name:"update"},{name:"bg",nav:!0,help:{order:17,section:"System",label:"bg <command>",text:"Run a shell command in the background"}},{name:"tasks",nav:!0,help:{order:18,section:"System",label:"tasks [id]",text:"Background task panel / view output"}},{name:"drafts",nav:!0,help:{order:16,section:"System",label:"drafts",text:"Review staged draft answers"}},{name:"help",nav:!0},{name:"menu",nav:!0},{name:"quit",nav:!0},{name:"q",nav:!0},{name:"exit",nav:!0,help:{order:24,section:"System",label:"exit",text:"Quit (session saved)"}},{name:"back",nav:!0},{name:"resume",nav:!0,help:{order:15,section:"System",label:"resume",text:"Continue your last learn card / exam"}},{name:"clear",nav:!0,help:{order:23,section:"System",label:"clear",text:"Clear screen"}},{name:"cls",nav:!0}];export const surface=()=>REGISTRY.map(e=>e.name);export const dispatchable=()=>REGISTRY.filter(e=>!e.nav).map(e=>e.name);export function shortcutFor(e,t){const a=REGISTRY.find(t=>t.name===e&&t.mapsTo);return a?.mapsTo?a.rest?[...a.mapsTo,...t]:[...a.mapsTo]:null}export const subcommandsOf=e=>REGISTRY.find(t=>t.name===e)?.subs;export const helpRows=e=>REGISTRY.filter(t=>t.help?.section===e).sort((e,t)=>e.help.order-t.help.order).map(e=>({label:e.help.label,text:e.help.text}));
package/dist/lib/site.js CHANGED
@@ -1 +1 @@
1
- import{existsSync as e,readFileSync as t}from"node:fs";import{homedir as o}from"node:os";import{join as r}from"node:path";export const PRACTICE_BASE="https://practice.icoa2026.au";export const MAX_PROFILE_DAYS=21;const s=/^(localhost|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|[a-z0-9-]+\.(lan|local|internal)$)/i;export function validateProfile(e,t=new Date){if(!e||"object"!=typeof e)return{ok:!1,reason:"not an object"};const o=e;if("string"!=typeof o.base||!o.base)return{ok:!1,reason:"missing base"};let r;try{r=new URL(o.base)}catch{return{ok:!1,reason:"base is not a URL"}}if("https:"!==r.protocol&&("http:"!==r.protocol||!s.test(r.hostname)))return{ok:!1,reason:"base must be https (http only for a LAN address)"};if(void 0!==o.assets){if("string"!=typeof o.assets)return{ok:!1,reason:"assets must be a string"};try{new URL(o.assets)}catch{return{ok:!1,reason:"assets is not a URL"}}}if("string"!=typeof o.expires)return{ok:!1,reason:"missing expires"};const n=Date.parse(o.expires);return Number.isNaN(n)?{ok:!1,reason:"expires is not a date"}:n<=t.getTime()?{ok:!1,reason:"expired"}:n-t.getTime()>18144e5?{ok:!1,reason:"expires more than 21 days ahead"}:{ok:!0,profile:{name:"string"==typeof o.name&&o.name?o.name:r.host,base:o.base.replace(/\/+$/,""),assets:"string"==typeof o.assets?o.assets.replace(/\/+$/,""):void 0,freeze:!0===o.freeze,expires:o.expires}}}let n;export function loadSite(){if(n)return n;const s=process.env.ICOA_SITE_FILE||r(o(),".icoa","site.json");if(!e(s))return n={ok:!1,reason:"none",path:null},n;try{const e=validateProfile(JSON.parse(t(s,"utf8")));n=e.ok?{ok:!0,profile:e.profile,path:s}:{ok:!1,reason:e.reason,path:s}}catch{n={ok:!1,reason:"unreadable JSON",path:s}}return n}export function _resetSiteCache(){n=void 0}function a(){const e=loadSite();return e.ok?e.profile:null}export function siteBase(){return a()?.base??PRACTICE_BASE}export function assetsRoot(){const e=a();return e?e.assets??e.base:PRACTICE_BASE}export function serviceBase(e){const t=e?process.env[e]:void 0;return t&&t.trim()||siteBase()}export function siteFrozen(){return!0===a()?.freeze}export function describeSite(){const e=loadSite();return e.ok?`venue profile "${e.profile.name}" → ${e.profile.base}${e.profile.freeze?" (client frozen)":""} · until ${e.profile.expires}`:e.path?`venue profile at ${e.path} ignored (${e.reason}) — using ${PRACTICE_BASE}`:null}
1
+ import{existsSync as e,mkdirSync as t,readFileSync as r,unlinkSync as n,writeFileSync as o}from"node:fs";import{homedir as s}from"node:os";import{join as a}from"node:path";export const PRACTICE_BASE="https://practice.icoa2026.au";export const MAX_PROFILE_DAYS=21;export const ENTRIES={direct:{base:PRACTICE_BASE,label:"straight to Singapore"},hk:{base:"https://icoa-official.org",label:"Hong Kong relay"}};const i=/^(localhost|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|[a-z0-9-]+\.(lan|local|internal)$)/i;export function validateProfile(e,t=new Date){if(!e||"object"!=typeof e)return{ok:!1,reason:"not an object"};const r=e;if("string"!=typeof r.base||!r.base)return{ok:!1,reason:"missing base"};let n;try{n=new URL(r.base)}catch{return{ok:!1,reason:"base is not a URL"}}if("https:"!==n.protocol&&("http:"!==n.protocol||!i.test(n.hostname)))return{ok:!1,reason:"base must be https (http only for a LAN address)"};if(void 0!==r.assets){if("string"!=typeof r.assets)return{ok:!1,reason:"assets must be a string"};try{new URL(r.assets)}catch{return{ok:!1,reason:"assets is not a URL"}}}if("string"!=typeof r.expires)return{ok:!1,reason:"missing expires"};const o=Date.parse(r.expires);return Number.isNaN(o)?{ok:!1,reason:"expires is not a date"}:o<=t.getTime()?{ok:!1,reason:"expired"}:o-t.getTime()>18144e5?{ok:!1,reason:"expires more than 21 days ahead"}:{ok:!0,profile:{name:"string"==typeof r.name&&r.name?r.name:n.host,base:r.base.replace(/\/+$/,""),assets:"string"==typeof r.assets?r.assets.replace(/\/+$/,""):void 0,freeze:!0===r.freeze,expires:r.expires}}}let c,p,u;export function loadSite(){if(c)return c;const t=process.env.ICOA_SITE_FILE||a(s(),".icoa","site.json");if(!e(t))return c={ok:!1,reason:"none",path:null},c;try{const e=validateProfile(JSON.parse(r(t,"utf8")));c=e.ok?{ok:!0,profile:e.profile,path:t}:{ok:!1,reason:e.reason,path:t}}catch{c={ok:!1,reason:"unreadable JSON",path:t}}return c}export function _resetSiteCache(){c=void 0}function f(){const e=loadSite();return e.ok?e.profile:null}function l(){return process.env.ICOA_ENTRY_FILE||a(s(),".icoa","entry.json")}export function currentEntry(){if(p)return p;let e="direct";try{const t=JSON.parse(r(l(),"utf8"));"string"==typeof t.entry&&Object.hasOwn(ENTRIES,t.entry)&&(e=t.entry)}catch{}return p=e,u??=e,e}export function entryNeedsRestart(){const e=u??currentEntry();return currentEntry()!==e}export function setEntry(e,r="user"){const s=l();if("direct"===e)try{n(s)}catch{}else t(a(s,".."),{recursive:!0}),o(s,`${JSON.stringify({entry:e,by:r,set_at:(new Date).toISOString()})}\n`);currentEntry(),p=void 0}export function _resetEntryCache(){p=void 0,u=void 0}export function siteBase(){return f()?.base??ENTRIES[currentEntry()].base}export function assetsRoot(){const e=f();return e?e.assets??e.base:ENTRIES[currentEntry()].base}export function serviceBase(e){const t=e?process.env[e]:void 0;return t&&t.trim()||siteBase()}export function siteFrozen(){return!0===f()?.freeze}export function describeSite(){const e=loadSite();if(e.ok)return`venue profile "${e.profile.name}" → ${e.profile.base}${e.profile.freeze?" (client frozen)":""} · until ${e.profile.expires}`;const t=currentEntry(),r="direct"===t?"":` · entry "${t}" (${ENTRIES[t].label}) → ${ENTRIES[t].base}`;return e.path?`venue profile at ${e.path} ignored (${e.reason}) — using ${ENTRIES[t].base}${r}`:"direct"!==t?`entry "${t}" — ${ENTRIES[t].label} → ${ENTRIES[t].base} · \`entry direct\` to undo`:null}