icoa-cli 2.19.708 → 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.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/entry.js +1 -0
- package/dist/commands/exam.js +1 -1
- package/dist/commands/ipynb.js +1 -1
- package/dist/commands/setter.js +1 -0
- package/dist/index.js +1 -1
- package/dist/lib/access.js +1 -1
- package/dist/lib/commands.js +1 -1
- package/dist/lib/kernel.js +2 -2
- package/dist/lib/setter.js +1 -0
- package/dist/lib/site.js +1 -1
- package/dist/repl.js +1 -1
- package/package.json +1 -1
package/dist/commands/ipynb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as o,readdirSync as 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};let Ue=new M({venvPython:N.python,venvRoot:N.root}),Ae=null,Ie=null,Ne=null,Oe=ve(Pe.path);if(ce){process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Ue.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 Te=!1,Me=!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:()=>Te},{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:()=>Me},{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!==Ae,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:()=>Ze()});const De=q(),qe=null!==De,Le=qe?De.listeners("line").slice():[];qe&&De.removeAllListeners("line");const ze=qe?De:c({input:process.stdin,output:process.stdout,terminal:!0});qe||L(ze);const Re=qe?ze.prompt:null,Ke=qe?ze.getPrompt():"";qe&&(ze.prompt=i.prototype.prompt),qe||R();const Be=[];let Fe,We=!1,Je=!1,Ve=!1,Ye=null,He=null;const Xe=()=>{if(He)return ze.setPrompt(chalk.bold.cyan(` editor 1-${He.options.length} > `)),void ze.prompt();const e=Ae?"icoa ipynb ⚡gpu":"icoa ipynb";ze.setPrompt(chalk.bold.cyan(Be.length?`${e} ...> `:`${e}> `)),ze.prompt()},Ze=()=>{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"))),Ae?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 Qe=()=>{};const eo=new Promise(e=>{Qe=e}),oo=async()=>{if(Ue=new M({venvPython:N.python,venvRoot:N.root}),e(N.python)){process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Ue.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."))},to=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 Ue.shutdown().catch(()=>{}),Ue=h,Ae={...n,outDir:c},Ne=e,Ie=Date.now(),h.onUnexpectedExit=()=>{Ue===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).")),Ae=null,Ne=null,Ie=null,oo().then(()=>Xe()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${te[e.tier]} · cells run in ${c}`));const p=await no();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},no=async()=>{if(!Pe.path||!Ae?.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 Ue.putFile(`${Ae.outDir}/${t}`,n(o)),r++}catch{}}return r},lo=async(e,t=!1)=>{if(!Ae)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:`${Ae.outDir}/${n}`;let a;try{a=await Ue.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=Oe?u(process.cwd(),"icoa-kaggle",Oe):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&&Oe&&"submission.csv"===g(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Oe}`)+chalk.gray(" · score it: ")+chalk.cyan("submit")),!0},ro=async e=>{const[t,...n]=e.trim().split(/\s+/),l=(t??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(Ae)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 to(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)."));Oe||(Oe=ve(Pe.path));const n=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await ke("lease",t,Oe??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=Oe?`${l.dataRoot}/${Oe}`: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 Ue.shutdown().catch(()=>{}),Ue=p,Ae=l,Ie=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.")),Oe&&console.log(chalk.gray(` Dataset is already on the box (${Oe}) — 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(Ae&&Ne){const e=Ie?Math.round((Date.now()-Ie)/1e3):0;return await Ue.shutdown().catch(()=>{}),Ae=null,Ne=null,Ie=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 oo()}if(!Ae)return void console.log(chalk.gray(" not on a GPU kernel."));const e=be(),o=void 0!==Ae.gpuName,t=Ie?Math.round((Date.now()-Ie)/1e3):0;await Ue.shutdown().catch(()=>{}),e&&await ke("release",e),Ae=null,Ie=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 oo()})():"status"===l||""===l?await(async()=>{const e=oe();if(e)return console.log(chalk.green(` ⚡ committee seat · ${te[e.tier]} · ${e.host}`)+chalk.gray(Ne?" (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(Ae?" (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>"))},ao=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}},so=(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 io=!1;const co=()=>{const e=w().notebookEditor;return e?_(e):null},go=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),yo=()=>co()??x(),uo={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"},ho=(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(co()||go())return o(yo()),!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(` ${uo[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),He={resume:o,tries:0,options:t},!1)},po=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),Fe=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},fo=()=>void 0!==Pe.diskSig?Ee(Pe.cells)!==Pe.diskSig:Pe.dirty,mo=(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)),wo=async o=>{if(o.trim()&&z(`ipynb: ${o.trim()}`),Je)return void(o.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(He){const e=He,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?(He=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)?(He=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(He=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 Xe()}let t=o.trim();if(0===Be.length&&/^icoa\s+[a-z/]/i.test(t)&&(t=t.replace(/^icoa\s+/i,"")),0===Be.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&&(Ve=!1),Ye&&l!==Ye&&(Ye=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(fo()){if(Fe===e)return;return Fe=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"))}po(!0)}})(),"quit"===l||"exit"===l||"back"===l||"q"===l||"menu"===l)return Pe.dirty&&!Ve?(Ve=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Xe()):void await(async()=>{if(le("ipynb"),ze.removeAllListeners("line"),qe||K(),console.log(),Ae&&Ne)Ae=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(Ae){const e=be();e&&await ke("release",e),Ae=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Ue.shutdown().catch(()=>{}),qe){Re&&(ze.prompt=Re),ze.setPrompt(Ke);for(const e of Le)ze.on("line",e);ze.prompt(),Qe()}else L(null),Qe(),ze.close()})();if("clear"===l||"cls"===l)return console.clear(),de(),void Xe();if("restart"===l)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Ue.shutdown().catch(()=>{});try{await Ue.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 Xe();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 Xe();if("guide"===l||"/guide"===l)return Ze(),void Xe();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 Xe();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 Xe();if("cells"===l||"ls"===l)return(()=>{if(Te=!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 Xe();if("show"===l)return(e=>{const o=ao(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 Xe();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?ho(o,e=>(e=>{ze.pause();const o=k(Q(Pe.cells),".py",e,"notebook");if(ze.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)):ao(t)&&ho(o,e=>((e,o)=>{const t=ao(e);if(!t)return;ze.pause();const n=k(t.cell.source,"markdown"===t.cell.kind?".md":".py",o);if(ze.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 Xe()}if("add"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),t=e.filter(e=>e!==o).join(" ");return ho(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)"));ze.pause();const l=k(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py",o);ze.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 Xe()}if("editor"===l&&/^[\w-]*$/.test(i))return(e=>{const o=e.trim().toLowerCase(),t=$(yo());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(t)+chalk.gray(` (${co()?"saved":go()?"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?` ${uo[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);co()&&$(co())===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 Xe();if("reload"===l&&""===i)return Pe.path&&e(Pe.path)?fo()&&"reload"!==Ye?(Ye="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."))):(Ye=null,po(!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 Xe();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 Xe();const o=J(i,a()),t=d(o)?o:h(process.cwd(),o);if(e(t))if(Pe.dirty&&"load"!==Ye)Ye="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{Ye=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,Fe=void 0,Oe=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 Xe()}if("del"===l||"delete"===l)return(e=>{const o=ao(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 Xe();if(("md"===l||"py"===l)&&/^\d+$/.test(i))return((e,o)=>{const t=ao(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 Xe();if("gpu"===l)return Je=!0,await ro(i),Je=!1,void Xe();if("download"===l||"dl"===l)return Je=!0,await lo(i),Je=!1,void Xe();if("selfcheck"===l||"self-check"===l)return Je=!0,await(async()=>{const e=Ne;if(!e||!Ae)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=Ue;if(await to(e,!0),Ue===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 Ue.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 Ue.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."))}})(),Je=!1,void Xe();if("upload"===l||"up"===l||"put"===l)return Je=!0,await(async e=>{if(!Ae)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=`${Ae.outDir}/${g(l)}`;try{const e=await Ue.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),Je=!1,void Xe();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;Je=!0;try{if(("submit"===t||"check"===t)&&Ae&&!await lo("submission.csv",!0))return Je=!1,void Xe();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,...Ne?{sid:Ne.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 Je=!1,void Xe()}if("board"===l){const{runBoard:e}=await import("./board.js"),o=i.split(/\s+/).filter(Boolean);Je=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Je=!1,void Xe()}if("ai"===l||"/ai"===l)return Je=!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=ao(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 so(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=so(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(),io||(io=!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),Je=!1,void Xe();if("run"===l)return Je=!0,await(async e=>{if(!ce&&!Ne&&!Ae)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 Ue.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),mo(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),Je=!1,void Xe();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"!==Ye)return Ye="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"));Ye=null;try{r(o,X(Pe.cells)),Pe.path=o,Me=!0,Pe.dirty=!1,Pe.mtimeMs=Ce(o),Pe.diskSig=Ee(Pe.cells),Fe=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 Xe();if(""===t)return void Xe()}if(Be.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 Xe();if(Be.push(o),!G(Be))return 1!==Be.length||We||(We=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Xe();const l=Be.join("\n").replace(/\s+$/,"");if(Be.length=0,""!==l.trim()){Je=!0;try{const e=await Ue.execute(l);Pe.cells.push({kind:"code",source:l,result:e}),Pe.dirty=!0,xe(e,T);const o=mo(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()}Je=!1,Xe()}else Xe()};ze.on("line",e=>{wo(e)}),qe||ze.on("close",async()=>{await Ue.shutdown().catch(()=>{}),process.exit(0)}),Xe(),await eo}
|
|
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}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as e}from"node:crypto";import{appendFileSync as t,existsSync as s,mkdirSync as n,readdirSync as r,readFileSync as a,statSync as o,writeFileSync as i}from"node:fs";import{basename as c,join as l,resolve as u}from"node:path";import{gzipSync as d}from"node:zlib";import chalk from"chalk";import{renderPanel as h}from"../lib/guide-panel.js";import{logCommand as f}from"../lib/logger.js";import{parseIpynb as m,serializeIpynb as b}from"../lib/notebook-doc.js";import{BASELINE_FILE as p,INLINE_LIMIT_BYTES as g,LOWER_IS_BETTER as w,METRICS as v,TASK_FILES as k,baselineCells as y,capsulePlan as $,checkTask as S,parseTaskMeta as B,scoreSubmission as j,studentBundle as _,tarArchive as z,validName as A,verdictLines as x}from"../lib/setter.js";import{getCliVersion as G}from"../lib/version.js";const N=(e="")=>console.log(e),O=e=>console.log(chalk.red(` ✗ ${e}`)),C=e=>console.log(chalk.green(` ✓ ${e}`)),J=e=>console.log(chalk.gray(` ${e}`)),P=(e,t)=>console.log(chalk.gray(" ▸ next, type: ")+chalk.bold.green(e)+chalk.gray(` ${t}`));function F(e){if(e){const t=u(e);return s(l(t,"task.json"))?t:null}const t=process.cwd();if(s(l(t,"task.json")))return t;try{const e=r(t).filter(e=>!e.startsWith(".")&&s(l(t,e,"task.json")));if(1===e.length)return l(t,e[0])}catch{}return null}function M(e,t){const n=l(e,t);if(s(n)){if(o(n).size>419430400)throw new Error(`${t} is over 400 MB — too large to check here; tell the organiser, this one goes through the dataset bucket`);return a(n,"utf-8")}}function q(e){const{meta:t,problems:s}=B(M(e,"task.json")??"");for(const e of s)O(e);return t}function L(e,t){return S(t,{train:M(e,"train.csv"),testA:M(e,"test_a.csv"),labelsA:M(e,"labels_a.csv"),testB:M(e,"test_b.csv"),labelsB:M(e,"labels_b.csv")})}function T(e,s,r){try{n(l(e,".setter"),{recursive:!0}),t(l(e,".setter","ledger.jsonl"),`${JSON.stringify({at:(new Date).toISOString(),cli:G(),action:s,...r})}\n`)}catch{}}function U(e){try{return a(l(e,".setter","ledger.jsonl"),"utf-8").split("\n").filter(e=>e.trim()).map(e=>JSON.parse(e))}catch{return[]}}const D=e=>Number.isFinite(e)?e.toFixed(4):String(e),I=e=>e>=1048576?`${(e/1024/1024).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`;function V(e){try{return JSON.parse(a(e,"utf-8"))}catch{return null}}export async function runSetter(t=[]){const[S,...B]=t,M=(S||"").toLowerCase();f(`setter ${M}`.trim());try{""===M||"help"===M||"?"===M||"guide"===M||"status"===M?function(e){N();for(const t of h(function(e){const t=t=>!!e&&s(l(e,t));return{id:"setter",title:{en:"Problem setter",zh:"命题工具"},what:{en:"Build one task folder and test it yourself, start to finish, on this machine: the data checks, the files a contestant gets, the A and B scores of your own solutions. Nothing leaves your computer until you hand the archive over.",zh:"在这台机器上把一道题从头到尾自己测完:数据检查、学生拿到的文件、你自己的解在 A 榜和 B 榜上的分数。在你亲手把压缩包交出去之前,没有任何东西离开你的电脑。"},steps:[{verb:"setter new my-task",what:{en:"make the folder: task.json and a baseline notebook that already runs",zh:"建文件夹:task.json 和一份能直接跑的 baseline notebook"},done:()=>t("task.json")},{verb:"setter check",what:{en:"after you put train.csv, test_a.csv + labels_a.csv, test_b.csv + labels_b.csv in it: the builder's checks",zh:"把 train.csv、test_a.csv + labels_a.csv、test_b.csv + labels_b.csv 放进去之后:跑建赛脚本的那套检查"},done:()=>t(".setter/check.json")},{verb:"setter student",what:{en:"write student/ — exactly what a contestant downloads",zh:"生成 student/ —— 学生下载到的就是这些"},done:()=>t("student/test.csv")},{verb:"ipynb",what:{en:"open student/baseline.ipynb and run all, as a contestant would — it writes submission.csv",zh:"打开 student/baseline.ipynb 敲 run all,像学生一样跑 —— 它会写出 submission.csv"},done:()=>t("student/submission.csv")},{verb:"setter score",what:{en:"A score, B score and the difference (setter score ref.csv for another solution)",zh:"A 榜分、B 榜分和差值(setter score ref.csv 给另一份解算分)"},done:()=>t(".setter/scores.json")},{verb:"setter plan 3 1.8",what:{en:"GPU tasks: minutes and peak GiB of your reference run → capsule size, seats per card",zh:"GPU 题:参考解的分钟数和峰值显存 → 胶囊档位、每张卡坐几人"},optional:!0,done:()=>t(".setter/plan.json")},{verb:"setter pack",what:{en:"one archive + report to send to the organiser",zh:"打成一个压缩包 + 报告,发给组织者"},done:()=>!!e&&r(e).some(e=>e.endsWith("-handin.tar.gz"))}],notes:[{en:`Metrics: ${v.join(" · ")}. Files are plain CSV: commas, no quotes. Publishing stays with the organiser.`,zh:`指标:${v.join(" · ")}。文件是普通 CSV:逗号分隔,不带引号。发布由组织者来做。`}],leave:{verb:"menu",what:{en:"main menu",zh:"主菜单"}}}}(e),"full"))N(t);J(e?`task folder: ${e}`:"no task folder here yet — setter new <name> makes one in the current directory"),N()}(F(B[0])):"new"===M||"init"===M||"create"===M?function(e,t){if(!e||!A(e))return O("give the task a short name: 3–40 characters of a–z, 0–9 and -"),void J("example: setter new sydney-rain (add a metric: setter new sydney-rain rmse)");const r=(t||"accuracy").toLowerCase();if(!v.includes(r))return void O(`metric "${t}" is not one the judge has — choose ${v.join(" / ")}`);const a=u(e);if(s(a))return O(`${e}/ already exists — nothing was changed`),void P("setter check",`(inside ${e}/, or: setter check ${e})`);n(a,{recursive:!0});const o={name:e,title:e,metric:r,label:"label",id:"id",per_day:5};i(l(a,"task.json"),`${JSON.stringify({...o,description:""},null,2)}\n`),i(l(a,p),b(y(o).map(e=>({...e,result:null})))),C(`made ${e}/ with task.json and ${p}`),J('now put your data in it (plain CSV, an "id" column in every file):'),J(" train.csv id + features + label"),J(" test_a.csv labels_a.csv the public-board rows, and id,label for them"),J(" test_b.csv labels_b.csv the private-board rows, and id,label for them"),J('edit task.json if your label column is not called "label" or the title should read better.'),P("setter check",`(inside ${e}/, or: setter check ${e})`)}(B[0],B[1]):"check"===M||"verify"===M||"validate"===M?function(e){const t=F(e);if(!t)return O("no task folder found (a folder with task.json)"),P("setter new my-task","makes one here"),null;const r=q(t);if(!r)return null;let a;try{a=L(t,r)}catch(e){return O(e.message),null}if(N(),N(chalk.bold.white(` ${r.title}`)+chalk.gray(` · ${r.name} · metric ${r.metric} · predict "${r.label}"`)),!a.ok){for(const e of a.problems)O(e);return J("fix the first line above and run setter check again — nothing was written."),null}if(C(`train ${a.nTrain} rows · A ${a.nA} rows · B ${a.nB} rows · ${a.features.length} feature columns`),a.classes.length){const e=a.classes.reduce((e,[,t])=>e+t,0);J(`classes in train: ${a.classes.map(([t,s])=>`${t} ${(100*s/e).toFixed(1)}%`).join(" · ")}`)}for(const e of a.warnings)N(chalk.yellow(` ⚠ ${e}`));const c=["train.csv","test_a.csv","test_b.csv"].reduce((e,s)=>e+o(l(t,s)).size,0);c>g?N(chalk.yellow(` ⚠ data is ${I(c)} — over the ${I(g)} a competition carries inline; the organiser will host it in the dataset bucket`)):J(`data size ${I(c)} — fits the inline bundle`),s(l(t,p))||N(chalk.yellow(` ⚠ no ${p} yet — every task ships a baseline the contestants start from`)),n(l(t,".setter"),{recursive:!0}),i(l(t,".setter","check.json"),`${JSON.stringify({at:(new Date).toISOString(),cli:G(),n_train:a.nTrain,n_a:a.nA,n_b:a.nB,features:a.features.length,warnings:a.warnings,data_bytes:c},null,2)}\n`),T(t,"check",{n_train:a.nTrain,n_a:a.nA,n_b:a.nB,features:a.features.length,data_bytes:c,warnings:a.warnings.length}),P("setter student","writes student/ — what a contestant downloads")}(B[0]):"student"===M||"bundle"===M||"build"===M?function(e){const t=F(e);if(!t)return void O("no task folder found — setter new my-task makes one");const r=q(t);if(!r)return;let o;try{o=L(t,r)}catch(e){return void O(e.message)}if(!o.ok){for(const e of o.problems)O(e);return void P("setter check","shows the same problems with the fix")}const u=l(t,"student");n(u,{recursive:!0});const d=_(r,o);i(l(u,"train.csv"),d.train),i(l(u,"test.csv"),d.test),i(l(u,"sample_submission.csv"),d.sample);const h=l(t,p);s(h)&&i(l(u,p),a(h)),T(t,"student",{rows:o.nA+o.nB,baseline:s(h)}),C(`student/ written: train.csv · test.csv (${o.nA+o.nB} rows, A and B mixed) · sample_submission.csv${s(h)?` · ${p}`:""}`),J("no labels and no A/B list are in student/ — it is safe to show to a tester."),s(h)?P(`ipynb ${l(c(t),"student",p)}`,"then run all — it writes student/submission.csv"):N(chalk.yellow(` ⚠ put your ${p} in the task folder and run setter student again`))}(B[0]):"score"===M||"grade"===M?function(t){let r,o;for(const e of t)s(l(u(e),"task.json"))?r=e:o=e;const d=F(r);if(!d)return void O("no task folder found — setter new my-task makes one");const h=q(d);if(!h)return;const f=o?s(u(o))?u(o):l(d,o):l(d,"student","submission.csv");if(!s(f))return O(`no submission at ${f}`),void P(`ipynb ${l(c(d),"student",p)}`,"run all writes student/submission.csv");let m;try{m=L(d,h)}catch(e){return void O(e.message)}if(!m.ok){for(const e of m.problems)O(e);return}const b=a(f,"utf-8"),g=j(h,m,b);if(!g.ok){for(const e of g.problems)O(e);return}const v=w.has(h.metric)?"lower is better":"higher is better";N(),N(chalk.bold.white(` ${c(f)}`)+chalk.gray(` · ${h.metric} (${v})`)),N(chalk.white(` A public board ${String(m.nA).padStart(7)} rows `)+chalk.bold.white(D(g.a))),N(chalk.white(` B private board ${String(m.nB).padStart(7)} rows `)+chalk.bold.white(D(g.b))),N(chalk.gray(` all ${String(m.nA+m.nB).padStart(7)} rows ${D(g.all)} A looks ${g.gap>=0?"better":"worse"} than B by ${D(Math.abs(g.gap))}`));const k=l(d,".setter","scores.json");let y=[];try{y=JSON.parse(a(k,"utf-8"))}catch{y=[]}const $=f.startsWith(d)?f.slice(d.length+1):f,S={file:$,sha:e("sha256").update(b).digest("hex").slice(0,16),a:g.a,b:g.b,all:g.all,gap:g.gap,at:(new Date).toISOString()};y=[...y.filter(e=>e.file!==$),S],T(d,"score",{file:$,sha:S.sha,metric:h.metric,a:g.a,b:g.b,all:g.all}),n(l(d,".setter"),{recursive:!0}),i(k,`${JSON.stringify(y,null,2)}\n`);const B=y.find(e=>e.file===l("student","submission.csv")),_=y.filter(e=>e!==B),z=w.has(h.metric),A=_.sort((e,t)=>z?e.b-t.b:t.b-e.b)[0];if(B){const e=e=>({ok:!0,problems:[],a:e.a,b:e.b,all:e.all,gap:e.gap,nMissing:0});N();for(const t of x(h,e(B),A?e(A):null))J(`· ${t}`);return A?void P("setter pack","one archive + report for the organiser"):void P("setter score ref.csv","score your own better solution too — that shows how much room contestants have")}J("· this is not the baseline run (student/submission.csv) — score that one too to see the room between them"),P(`ipynb ${l(c(d),"student",p)}`,"then run all, then setter score")}(B):"plan"===M||"capsule"===M||"capacity"===M?function(e){const t=F(),s="cpu"===e[0]?.toLowerCase(),r=e.filter(e=>"cpu"!==e.toLowerCase()).map(Number),a=r[0],o=s?0:r[1],c=s?r[1]:r[2];if(!Number.isFinite(a)||a<=0||!s&&(!Number.isFinite(o)||o<=0))return O("give the two numbers your reference run measured: minutes and peak GPU memory in GiB"),J("example: setter plan 3 1.8 200 (3 minutes, 1.8 GiB peak, 200 contestants at once)"),J(" setter plan cpu 2 200 (a task that needs no GPU)"),void J("where the numbers come from: run the reference on a seat (gpufortask → ipynb → gpu on) and type selfcheck.");const u=$(o,a,!s,Number.isFinite(c)?c:void 0);if(N(),"cpu"===u.tier)C(`CPU task · ${a} min per run — contestants run it on their own machine, no seat needed`);else{if(!u.fits)return void O(`peak ${o} GiB does not fit the largest capsule (cap ${u.capGib} GiB) — shrink the batch or the model; a task every card can run beats one that only fits the biggest`);C(`${u.squares}-square capsule · peak ${o} GiB under the ${u.capGib} GiB cap · ${a} min per run`),N(chalk.white(" card seats at once runs per card-hour")+(u.cards?chalk.white(` cards for ${c} at once`):""));for(const[e,t]of[["l4","L4 24 GB"],["ada","Ada 20 GB"],["t4","T4 16 GB"]])u.perCard[e]?N(chalk.white(` ${t} ${String(u.perCard[e]).padStart(6)} ${String(u.runsPerCardHour?.[e]??"-").padStart(6)}`)+(u.cards?chalk.white(` ${String(u.cards[e]).padStart(6)}`):"")):N(chalk.gray(` ${t} — (a 3-square task runs on L4 only, so every contestant gets the same card)`));J("every contestant of one task gets the same capsule size on the same card type — that is what makes the times comparable."),J("a planning estimate from fixed capsule sizes; the organiser calibrates the real number on the fleet before the event.")}t&&(n(l(t,".setter"),{recursive:!0}),i(l(t,".setter","plan.json"),`${JSON.stringify({minutes:a,peak_gib:o,contestants:c??null,...u},null,2)}\n`),T(t,"plan",{minutes:a,peak_gib:o,squares:u.squares,tier:u.tier}),J("saved with the task — setter pack carries it to the organiser."))}(B):"pack"===M||"handin"===M||"hand-in"===M||"package"===M?function(t){const n=F(t);if(!n)return void O("no task folder found — setter new my-task makes one");const r=q(n);if(!r)return;let o;try{o=L(n,r)}catch(e){return void O(e.message)}if(!o.ok){for(const e of o.problems)O(e);return void P("setter check","the archive is only made from a folder that passes")}if(!s(l(n,p)))return void O(`${p} is missing — every task ships a baseline`);try{m(a(l(n,p),"utf-8"))}catch(e){return void O(`${p} does not open as a notebook: ${e.message}`)}let u=[];try{u=JSON.parse(a(l(n,".setter","scores.json"),"utf-8"))}catch{u=[]}u.some(e=>e.file===l("student","submission.csv"))||N(chalk.yellow(" ⚠ the baseline has not been scored — the organiser will ask for it; run it and setter score first if you can"));const h=[...k];for(const e of["description.md","ref.csv","reference.ipynb"])s(l(n,e))&&h.push(e);const f=h.map(e=>({name:`${r.name}/${e}`,data:new Uint8Array(a(l(n,e)))})),b={task:r,packed_at:(new Date).toISOString(),cli:G(),rows:{train:o.nTrain,a:o.nA,b:o.nB},features:o.features.length,warnings:o.warnings,scores:u,capsule:V(l(n,".setter","plan.json")),ledger:U(n),files:f.map(t=>({name:t.name,bytes:t.data.length,sha256:e("sha256").update(t.data).digest("hex")}))};f.push({name:`${r.name}/setter-report.json`,data:(new TextEncoder).encode(`${JSON.stringify(b,null,2)}\n`)});const g=l(n,`${r.name}-handin.tar.gz`),w=d(z(f));i(g,w),C(`${c(g)} · ${I(w.length)} · ${f.length} files`),J(g),N(chalk.yellow(" ⚠ this archive contains the B labels — send it only to the organiser, never to a shared channel.")),J("the organiser runs the same checks again, builds the competition, and you then walk it as a contestant: kaggle <name>.")}(B[0]):(O(`setter does not know "${S}"`),J("it knows: new · check · student · score · plan · pack (bare setter shows the steps)"))}catch(e){O(e.message)}}export function registerSetterCommand(e){e.command("setter [args...]").description("Problem setter: build a task folder and test it end to end locally (new · check · student · score · pack)").action(async(e=[])=>{await runSetter(e)})}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as l}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerUpgradeCommand as m}from"./commands/upgrade.js";import{registerNoteCommand as c}from"./commands/note.js";import{registerLogCommand as g}from"./commands/log.js";import{registerLangCommand as d}from"./commands/lang.js";import{registerSetupCommand as p}from"./commands/setup.js";import{registerEnvCommand as 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{registerSimCommand as R}from"./commands/sim.js";import{registerArenaCommand as O}from"./commands/arena.js";import{registerKaggleCommand as N}from"./commands/kaggle.js";import{registerSprintCommand as U}from"./commands/sprint.js";import{registerTeleloadCommand as F}from"./commands/teleload.js";import{registerBoardCommand as P}from"./commands/board.js";import{registerTypeCommand as M}from"./commands/type.js";import{registerBattleCommand as G}from"./commands/battle.js";import{registerWmCommand as H}from"./commands/wm.js";import{getConfig as W,saveConfig as D}from"./lib/config.js";import{registerMicroduckCommand as Y}from"./commands/microduck.js";import{startRepl as V}from"./repl.js";import{RELAUNCH_CODE as J}from"./lib/menu-nav.js";import{setTerminalTheme as X}from"./lib/theme.js";import{cleanupTerminal as q}from"./lib/terminal-cleanup.js";import{checkForUpdates as z,runUpgrade as K,bootUpgradeEligible as B,startBootCheck as Q,printUpdateHint as Z}from"./lib/update-check.js";import{detectIcoaInstalls as oo,isWindowsBuildInWslShell as eo}from"./lib/platform.js";import{ICOA_BIG as no}from"./lib/banner.js";import{readFileSync as so}from"node:fs";import{fileURLToPath as ro}from"node:url";import{dirname as to,join as io}from"node:path";import{setDefaultResultOrder as lo}from"node:dns";import{setDefaultAutoSelectFamilyAttemptTimeout as ao}from"node:net";lo("ipv4first"),ao(4e3);const mo=to(ro(import.meta.url)),co=JSON.parse(so(io(mo,"..","package.json"),"utf-8")).version,go=chalk.cyan(" ─────────────────────────────────────────────────────"),po=`\n${go}\n\n${no.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${co}`)}\n\n${go}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=n?process.argv.slice(1,2):process.argv.slice(1),r=o(process.execPath,s,{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(r.signal){const{appendExitLog:o}=await import("./lib/exit-log.js");o("worker-signal",`signal=${r.signal}`),console.log(),console.log(chalk.yellow(` ⚠ icoa was stopped by signal ${r.signal}`)+chalk.gray(" — another process killed it (not a crash). Run icoa --resume to continue.")),e=0;break}if(e=r.status,0!==e&&e!==J){const{appendExitLog:o}=await import("./lib/exit-log.js");o("worker-exit",`code=${e}`);const n=null!==e&&e>128?e-128:0;console.log(),console.log(n?chalk.yellow(` ⚠ icoa was stopped by signal ${n}`)+chalk.gray(" — another process killed it (not a crash). Run icoa --resume to continue."):chalk.yellow(` ⚠ icoa exited unexpectedly (code ${e})`)+chalk.gray(" — see ~/.icoa/exit.log · run icoa --resume to continue."))}n=!0}while(e===J);q(),process.exit(e??0)}}const ho=new o;if(ho.name("icoa").version(co).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=W();X("high-contrast"===e.themeVariant?"high-contrast":"dark");const n=!!o.resume||!!o.continue,s=B(n)&&process.argv.length<=2;s?Q():z(),function(){const o=oo();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(po),s?"upgraded"===await K({ask:!0})&&(console.log(chalk.gray(" restarting icoa …")),process.exit(J)):Z(),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 V(ho,n)}),e(ho),n(ho),s(ho),r(ho),t(ho),i(ho),l(ho),a(ho),m(ho),c(ho),g(ho),d(ho),p(ho),h(ho),f(ho),u(ho),y(ho),w(ho),j(ho),b(ho),v(ho),T(ho),$(ho),E(ho),A(ho),x(ho),_(ho),I(ho),k(ho),C(ho),S(ho),L(ho),R(ho),O(ho),N(ho),F(ho),U(ho),P(ho),H(ho),M(ho),G(ho),Y(ho),ho.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=W().geminiModel||"gemini-2.5-flash-lite";o?(D({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)))}ho.hook("preAction",()=>{!function(){if(!eo())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()}()}),ho.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();
|
package/dist/lib/access.js
CHANGED
|
@@ -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}}
|
package/dist/lib/commands.js
CHANGED
|
@@ -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:"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/kernel.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{spawn as e}from"node:child_process";import{writeFileSync as
|
|
1
|
+
import{spawn as e}from"node:child_process";import{existsSync as t,writeFileSync as i}from"node:fs";import{join as r}from"node:path";import{foldCellOutputs as n,parseKernelEvent as s}from"./kernel-protocol.js";export const KERNEL_BRIDGE_PY=String.raw`import sys, os, json, queue, base64
|
|
2
2
|
|
|
3
3
|
def emit(o):
|
|
4
4
|
sys.stdout.write(json.dumps(o) + "\n")
|
|
@@ -118,4 +118,4 @@ def main():
|
|
|
118
118
|
os._exit(0)
|
|
119
119
|
|
|
120
120
|
main()
|
|
121
|
-
`;function
|
|
121
|
+
`;function o(e){return`'${e.replace(/'/g,"'\\''")}'`}export function buildRemoteBridgeCommand(e,t={},i){const r=Buffer.from(KERNEL_BRIDGE_PY,"utf-8").toString("base64"),n=["exec","env",...Object.entries(t).map(([e,t])=>`${e}=${o(t)}`),o(e),"-c",o(`exec(__import__("base64").b64decode("${r}").decode())`)].join(" ");return i?`mkdir -p ${o(i)} && cd ${o(i)} && ${n}`:n}export class NotebookKernel{proc=null;buf="";errTail="";nextId=1;ready=!1;pending=null;pendingFetch=null;onReady=null;onExit=null;opts;bridgePath;constructor(e){this.opts=e,this.bridgePath=e.venvRoot?r(e.venvRoot,"icoa-kernel-bridge.py"):null}start(){let r;if(this.shuttingDown=!1,this.buf="",this.errTail="",this.ready=!1,this.pending=null,this.pendingFetch=null,this.nextId=1,this.opts.spawnSpec)r=e(this.opts.spawnSpec.command,this.opts.spawnSpec.args,{stdio:["pipe","pipe","pipe"]});else{if(!this.opts.venvPython||!this.bridgePath)return Promise.reject(new Error("kernel needs venvPython+venvRoot or a spawnSpec"));i(this.bridgePath,KERNEL_BRIDGE_PY);const n=this.opts.cwd&&t(this.opts.cwd)?this.opts.cwd:void 0;r=e(this.opts.venvPython,[this.bridgePath],{stdio:["pipe","pipe","pipe"],...n?{cwd:n}:{}})}this.proc=r,r.stdout.setEncoding("utf-8"),r.stdout.on("data",e=>this.onStdout(e)),r.stderr.setEncoding("utf-8"),r.stderr.on("data",e=>{this.errTail=(this.errTail+e).slice(-600)}),r.on("exit",()=>{const e=this.ready;this.ready=!1,this.onExit?.();const t=this.pending;t&&(this.pending=null,t.resolve(n(t.events.concat([{type:"fatal",message:"kernel connection lost"},{type:"done",id:t.id,count:null}]))));const i=this.pendingFetch;i&&(this.pendingFetch=null,i.reject(new Error("kernel connection lost"))),e&&!this.shuttingDown&&this.onUnexpectedExit?.()}),r.on("error",()=>{this.ready=!1,this.proc=null,this.onExit?.()});const s=this.opts.readyTimeoutMs??6e4;return new Promise((e,t)=>{const i=e=>new Error(this.errTail?`${e} — ${this.errTail.trim()}`:e),r=setTimeout(()=>t(i("kernel did not become ready in time")),s);this.onReady=()=>{clearTimeout(r),e()},this.onExit=()=>{clearTimeout(r),this.ready||t(i("kernel process exited before ready"))}})}execute(e){if(!this.proc||!this.ready)return Promise.reject(new Error("kernel not ready"));if(this.pending)return Promise.reject(new Error("a cell is already executing"));const t=this.nextId++;return new Promise(i=>{this.pending={id:t,events:[],resolve:i},this.proc?.stdin.write(`${JSON.stringify({id:t,code:e})}\n`)})}fetchFile(e){if(!this.proc||!this.ready)return Promise.reject(new Error("kernel not ready"));if(this.pendingFetch)return Promise.reject(new Error("a fetch is already in flight"));const t=this.nextId++;return new Promise((i,r)=>{this.pendingFetch={id:t,resolve:i,reject:r},this.proc?.stdin.write(`${JSON.stringify({cmd:"fetch",id:t,path:e})}\n`)})}putFile(e,t){if(!this.proc||!this.ready)return Promise.reject(new Error("kernel not ready"));if(this.pendingFetch)return Promise.reject(new Error("a transfer is already in flight"));if(t.length>20971520)return Promise.reject(new Error("file exceeds the 20MB transfer cap"));const i=this.nextId++;return new Promise((r,n)=>{this.pendingFetch={id:i,resolve:e=>r(e.length),reject:n},this.proc?.stdin.write(`${JSON.stringify({cmd:"put",id:i,path:e,data:t.toString("base64")})}\n`)})}onUnexpectedExit=null;shuttingDown=!1;shutdown(){this.shuttingDown=!0;const e=this.proc;return e?new Promise(t=>{this.onExit=()=>t();try{e.stdin.write(`${JSON.stringify({cmd:"shutdown"})}\n`)}catch{e.kill()}setTimeout(()=>{this.proc&&(this.proc.kill(),t())},5e3)}):Promise.resolve()}onStdout(e){this.buf+=e;let t=this.buf.indexOf("\n");for(;-1!==t;){const e=this.buf.slice(0,t);this.buf=this.buf.slice(t+1),this.handleEvent(s(e)),t=this.buf.indexOf("\n")}}handleEvent(e){if(!e)return;if("ready"===e.type)return this.ready=!0,void this.onReady?.();if("file"===e.type||"file_error"===e.type||"put_ok"===e.type){const t=this.pendingFetch;if(!t||e.id!==t.id)return;return this.pendingFetch=null,void("file"===e.type?t.resolve(Buffer.from(e.data,"base64")):"put_ok"===e.type?t.resolve(Buffer.alloc(e.size)):t.reject(new Error(e.message)))}const t=this.pending;if(t){if("done"===e.type){if(e.id!==t.id)return;const i=n(t.events.concat(e));return this.pending=null,void t.resolve(i)}t.events.push(e)}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as e}from"node:crypto";export const METRICS=["accuracy","macro_f1","rmse","mse"];export const LOWER_IS_BETTER=new Set(["rmse","mse"]);export function parseCsv(e){const t=[],s=e.replace(/^/,"").split(/\r?\n/).filter(e=>""!==e.trim());if(0===s.length)return{table:{header:[],rows:[]},problems:["file is empty"]};e.includes('"')&&t.push('quoted fields (") are not supported — write plain comma-separated values');const n=s[0].split(",").map(e=>e.trim()),r=[];for(let e=1;e<s.length;e++){const a=s[e].split(",").map(e=>e.trim());if(a.length!==n.length){t.push(`row ${e+1} has ${a.length} fields, the header has ${n.length}`);break}r.push(a)}return{table:{header:n,rows:r},problems:t}}export function validName(e){return/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(e)}export function parseTaskMeta(e){let t;try{t=JSON.parse(e)}catch{return{meta:null,problems:["task.json is not valid JSON"]}}const s=[],n=String(t.name??""),r=String(t.metric??""),a=String(t.label??"");if(validName(n)||s.push("task.json name: 3–40 characters of a–z, 0–9 and -"),METRICS.includes(r)||s.push(`task.json metric: one of ${METRICS.join(" / ")}`),a||s.push("task.json label: the name of the column to predict"),s.length)return{meta:null,problems:s};const i=Number(t.per_day);return{meta:{name:n,title:String(t.title||n),metric:r,label:a,id:String(t.id||"id"),per_day:Number.isFinite(i)&&i>=1?Math.floor(i):5,description:"string"==typeof t.description?t.description:void 0},problems:[]}}const t={train:"train.csv",testA:"test_a.csv",labelsA:"labels_a.csv",testB:"test_b.csv",labelsB:"labels_b.csv"};export function checkTask(e,s){const n={ok:!1,problems:[],warnings:[],nTrain:0,nA:0,nB:0,features:[],classes:[]},r={};for(const e of Object.keys(t)){const a=s[e];if(void 0===a){n.problems.push(`${t[e]} is missing`);continue}const{table:i,problems:o}=parseCsv(a);for(const s of o)n.problems.push(`${t[e]}: ${s}`);r[e]=i}if(n.problems.length)return n;const a=r.train,i=e.id;if(!a.header.includes(i)||!a.header.includes(e.label))return n.problems.push(`train.csv needs both "${i}" and "${e.label}" columns — its header is ${a.header.join(", ")}`),n;const o=a.header.filter(t=>t!==e.label);n.features=o.filter(e=>e!==i);const l=a.header.indexOf(i),c=a.header.indexOf(e.label),d=new Set;for(const e of a.rows){if(d.has(e[l]))return n.problems.push(`train.csv: duplicate id ${e[l]}`),n;d.add(e[l])}const h=new Map,u=new Map,p={A:[],B:[]};for(const[s,a,l]of[["A","testA","labelsA"],["B","testB","labelsB"]]){const c=r[a],d=r[l],m=t[a],b=t[l];if(c.header.includes(e.label))return n.problems.push(`${m} carries the label column "${e.label}" — remove it, labels go in ${b}`),n;if(c.header.join(",")!==o.join(","))return n.problems.push(`${m} columns differ from train.csv minus the label — test: ${c.header.join(", ")} · train: ${o.join(", ")}`),n;if(2!==d.header.length||d.header[0]!==i||d.header[1]!==e.label)return n.problems.push(`${b} must have exactly two columns (${i}, ${e.label}) — got ${d.header.join(", ")}`),n;const f=new Set,g=c.header.indexOf(i);for(const e of c.rows){if(f.has(e[g]))return n.problems.push(`${m} has duplicate ids (${e[g]})`),n;f.add(e[g])}const $=new Map;for(const e of d.rows){if(""===e[0]||""===e[1])return n.problems.push(`${b}: empty id or label near id ${e[0]||"(blank)"}`),n;if($.has(e[0]))return n.problems.push(`${b}: duplicate id ${e[0]}`),n;$.set(e[0],e[1])}const w=[...f].filter(e=>$.has(e)).length;if(w!==f.size||w!==$.size)return n.problems.push(`${m}: ${f.size} ids in the test file, ${$.size} in ${b}, ${w} in both — they must be the same set`),n;for(const e of f){const t=u.get(e);if(t)return n.problems.push(`id ${e} is in both ${t} and ${m}`),n;u.set(e,m),h.set(e,$.get(e)),p[s].push(e)}}const m=[...u.keys()].filter(e=>d.has(e));if(m.length)return n.problems.push(`${m.length} train ids are reused in test (e.g. ${m.slice(0,3).join(", ")}) — ids must be unique across files`),n;if(n.nTrain=a.rows.length,n.nA=p.A.length,n.nB=p.B.length,0===n.nA||0===n.nB)return n.problems.push("one board is empty — both test_a.csv and test_b.csv need rows"),n;if(LOWER_IS_BETTER.has(e.metric)){const t=[...h.values()].find(e=>!Number.isFinite(Number(e)));if(void 0!==t)return n.problems.push(`metric ${e.metric} needs numeric labels — found "${t}"`),n}else{const t=new Map;for(const e of a.rows)t.set(e[c],(t.get(e[c])||0)+1);n.classes=[...t.entries()].sort((e,t)=>t[1]-e[1]).slice(0,12);const s=new Set(t.keys()),r=[...new Set(h.values())].filter(e=>!s.has(e));r.length&&n.warnings.push(`test labels contain ${r.length} value(s) never seen in train (e.g. ${r.slice(0,3).join(", ")})`),t.size>Math.max(50,n.nTrain/2)&&n.warnings.push(`${t.size} distinct label values with a classification metric — is "${e.label}" really a class?`)}return(n.nA<100||n.nB<100)&&n.warnings.push(`a board with under 100 rows (A ${n.nA}, B ${n.nB}) moves a lot on a single row`),n.nB<n.nA&&n.warnings.push(`B (${n.nB}) is smaller than A (${n.nA}) — the final ranking usually rests on the larger set`),n.ok=!0,n.parsed={train:a,testA:r.testA,testB:r.testB,labels:h,aIds:p.A,bIds:p.B},n}const s=(e,t)=>`${[e,...t].map(e=>e.join(",")).join("\n")}\n`;export function studentBundle(t,n){if(!n.ok||!n.parsed)throw new Error("check the task first");const{train:r,testA:a,testB:i}=n.parsed,o=a.header.indexOf(t.id),l=s=>e("sha256").update(`${t.name}:order:${s}`).digest("hex"),c=[...a.rows,...i.rows].sort((e,t)=>l(e[o])<l(t[o])?-1:1),d=r.header.indexOf(t.label),h=LOWER_IS_BETTER.has(t.metric)?"0":n.classes[0]?.[0]??r.rows[0]?.[d]??"0";return{train:s(r.header,r.rows),test:s(a.header,c),sample:s([t.id,t.label],c.map(e=>[e[o],h]))}}function n(e,t){if(0===t.size)return Number.POSITIVE_INFINITY;let s=0;for(const[n,r]of t){const t=e.get(n);s+=((void 0!==t&&""!==t.trim()&&Number.isFinite(Number(t))?Number(t):0)-Number(r))**2}return s/t.size}export function metricValue(e,t,s){return"accuracy"===e?function(e,t){if(0===t.size)return 0;let s=0;for(const[n,r]of t)(e.get(n)??"").trim()===r.trim()&&s++;return s/t.size}(t,s):"macro_f1"===e?function(e,t){const s=[...new Set([...t.values()].map(e=>e.trim()))].sort();if(0===s.length)return 0;let n=0;for(const r of s){let s=0,a=0,i=0;for(const[n,o]of t){const t=(e.get(n)??"").trim(),l=o.trim();t===r&&l===r?s++:t===r&&l!==r?a++:t!==r&&l===r&&i++}const o=2*s+a+i;n+=o?2*s/o:0}return n/s.length}(t,s):"mse"===e?n(t,s):Math.sqrt(n(t,s))}export function scoreSubmission(e,t,s){const n={ok:!1,problems:[],a:0,b:0,all:0,gap:0,nMissing:0};if(!t.ok||!t.parsed)return n.problems.push("check the task first"),n;const{table:r,problems:a}=parseCsv(s);if(a.length)return n.problems.push(...a),n;if(2!==r.header.length||r.header[0]!==e.id||r.header[1]!==e.label)return n.problems.push(`the submission needs exactly two columns: ${e.id},${e.label} — got ${r.header.join(",")}`),n;const i=new Map;for(const e of r.rows){if(i.has(e[0]))return n.problems.push(`duplicate id ${e[0]} in the submission`),n;i.set(e[0],e[1])}const{labels:o,aIds:l,bIds:c}=t.parsed,d=[...i.keys()].filter(e=>!o.has(e));if(d.length)return n.problems.push(`${d.length} ids are not in the test set (e.g. ${d.slice(0,3).join(", ")})`),n;if(n.nMissing=o.size-i.size,n.nMissing>0)return n.problems.push(`${n.nMissing} test rows have no prediction — the judge refuses an incomplete submission`),n;const h=e=>new Map(e.map(e=>[e,o.get(e)]));return n.a=metricValue(e.metric,i,h(l)),n.b=metricValue(e.metric,i,h(c)),n.all=metricValue(e.metric,i,o),n.gap=LOWER_IS_BETTER.has(e.metric)?n.b-n.a:n.a-n.b,n.ok=!0,n}export function verdictLines(e,t,s){const n=[],r=LOWER_IS_BETTER.has(e.metric),a=(e,t)=>r?e<t:e>t,i=Math.abs(t.gap);if(i/Math.max(Math.abs(t.all),1e-9)>.05?n.push(`A and B disagree by ${i.toFixed(4)} on the baseline — check that the two test sets come from the same distribution`):n.push(`A and B agree on the baseline (difference ${i.toFixed(4)})`),s){if(a(s.b,t.b)){const e=Math.abs(s.b-t.b);n.push(`room to climb on B: ${e.toFixed(4)} (baseline ${t.b.toFixed(4)} → reference ${s.b.toFixed(4)})`),e<2*i&&n.push("that room is smaller than twice the A/B difference — the ranking may come down to noise")}else n.push("the reference does NOT beat the baseline on B — contestants have nothing to climb");a(s.a,t.a)!==a(s.b,t.b)&&n.push("baseline and reference rank differently on A and on B — the public board would mislead")}return n}export function tarArchive(e){const t=[],s=new TextEncoder;for(const n of e){const e=new Uint8Array(512),r=(t,n,r)=>{e.set(s.encode(t).subarray(0,r),n)};if(s.encode(n.name).length>99)throw new Error(`file name too long for the archive: ${n.name}`);r(n.name,0,100),r("0000644\0",100,8),r("0000000\0",108,8),r("0000000\0",116,8),r(`${n.data.length.toString(8).padStart(11,"0")}\0`,124,12),r("00000000000\0",136,12),r(" ",148,8),r("0",156,1),r("ustar\0",257,6),r("00",263,2);let a=0;for(const t of e)a+=t;r(`${a.toString(8).padStart(6,"0")}\0 `,148,8),t.push(e,n.data);const i=(512-n.data.length%512)%512;i&&t.push(new Uint8Array(i))}t.push(new Uint8Array(1024));const n=t.reduce((e,t)=>e+t.length,0),r=new Uint8Array(n);let a=0;for(const e of t)r.set(e,a),a+=e.length;return r}export const BASELINE_FILE="baseline.ipynb";export const TASK_FILES=["task.json","train.csv","test_a.csv","labels_a.csv","test_b.csv","labels_b.csv",BASELINE_FILE];export const INLINE_LIMIT_BYTES=5242880;export function baselineCells(e){const t=LOWER_IS_BETTER.has(e.metric);return[{kind:"markdown",source:`# ${e.title}\n\nDescribe the task here: what one row is, what "${e.label}" means, and how a submission is scored (**${e.metric}**).\n\nThis notebook is the baseline every contestant starts from. Keep it short and make sure it runs top to bottom.`},{kind:"code",source:'import pandas as pd\n\ntrain = pd.read_csv("train.csv")\ntest = pd.read_csv("test.csv")\nprint(train.shape, test.shape)\ntrain.head()'},{kind:"code",source:t?`# Baseline: predict the training mean for every row.\npred = [train["${e.label}"].mean()] * len(test)`:`# Baseline: predict the most common class for every row.\npred = [train["${e.label}"].mode()[0]] * len(test)`},{kind:"code",source:`pd.DataFrame({"${e.id}": test["${e.id}"], "${e.label}": pred}).to_csv("submission.csv", index=False)\nprint("wrote submission.csv —", len(pred), "rows")`}]}export const SQUARE_GIB=3.5;export const CARD_UNITS={l4:6,ada:5,t4:4};export function capsulePlan(e,t,s,n){if(!s)return{tier:"cpu",squares:0,fits:!0,capGib:0,perCard:{l4:0,ada:0,t4:0}};const r=[1,2,3].find(t=>e<3.5*t-.5);if(!r)return{tier:"gpu",squares:3,fits:!1,capGib:10,perCard:{l4:0,ada:0,t4:0}};const a=(e,t)=>3===r&&"l4"!==t?0:Math.floor(e/r),i={l4:a(CARD_UNITS.l4,"l4"),ada:a(CARD_UNITS.ada,"ada"),t4:a(CARD_UNITS.t4,"t4")},o={tier:"gpu",squares:r,fits:!0,capGib:3.5*r-.5,perCard:i},l=e=>({l4:e(i.l4),ada:e(i.ada),t4:e(i.t4)});return n&&n>0&&(o.cards=l(e=>e?Math.ceil(n/e):0)),t>0&&(o.runsPerCardHour=l(e=>Math.floor(60*e/t))),o}
|