icoa-cli 2.19.707 → 2.19.708
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/ipynb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as o,readdirSync as n,readFileSync as t,statSync as l,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{createHash as s}from"node:crypto";import{Interface as i,createInterface as c}from"node:readline";import{basename as g,dirname as y,isAbsolute as d,join as u,resolve as h}from"node:path";import chalk from"chalk";import{aienvPaths as p}from"../lib/aienv.js";import{AI_MAX_INPUT_CHARS as m,askIoaiOneShot as f}from"./ai4ioai.js";import{getConfig as w,saveConfig as b}from"../lib/config.js";import{editTextInEditor as k,editorInstalled as v,editorLabel as $,namedEditor as _,resolveEditor as x}from"../lib/editor-spawn.js";import{buildSshArgs as P,leaseConnectProblems as S,parseLeaseResponse as E,queueLine as C,windowLine as G}from"../lib/gpu.js";import{shouldExecuteCell as j}from"../lib/ipynb-input.js";import{looksLikeMarkdown as U,renderMarkdown as A}from"../lib/md-term.js";import{NotebookKernel as I,buildRemoteBridgeCommand as N}from"../lib/kernel.js";import{getMainRl as T,setMainRl as O}from"../lib/main-rl.js";import{logCommand as M}from"../lib/logger.js";import{startLogSync as D,stopLogSync as q}from"../lib/log-sync.js";import{cellPreview as L,fromWholeEditText as z,mergeReloadedCells as R,normalizePathArg as K,parseIpynb as B,parsePercentPy as F,parseRunRange as W,serializeIpynb as J,statusChar as V,toWholeEditText as Y}from"../lib/notebook-doc.js";import{committeeLease as H,readCommitteeSession as X,TIER_LABEL as Z}from"../lib/gputask-session.js";import{enterPanel as Q,leavePanel as ee,printHelp as oe}from"../lib/guide-panel.js";import{lazyFile as ne}from"../lib/lazy-assets.js";import{openFile as te}from"../lib/open-file.js";import{serviceBase as le,siteBase as re}from"../lib/site.js";const ae=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function se(){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 ie(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const ce=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]),ge=new Set(["run","cells","ls","show","edit","add","del","delete","md","py","ai","/ai"]);function ye(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const de=re();function ue(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):de}function he(){return u(a(),".icoa","gpu-key")}function pe(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return t(he(),"utf-8").trim()||null}catch{return null}}async function me(e,o,n){try{const t=await fetch(`${ue()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return E(await t.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function fe(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let we=0,be=null;function ke(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(ae,"")}`))}else"display"===n.kind&&ve(n.data,o)}function ve(e,n){if(e["image/png"])try{o(n,{recursive:!0}),we+=1;const t=u(n,`figure-${we}.png`);return r(t,Buffer.from(e["image/png"],"base64")),be=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(te(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}function $e(e){return JSON.stringify(e.map(e=>[e.kind,e.source]))}function _e(e){if(e)try{return l(e).mtimeMs}catch{return}}function xe(o){const n=K(o,a()),l=d(n)?n:h(process.cwd(),n);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=t(l,"utf8"),o=l.endsWith(".ipynb")?B(e):F(e);return{doc:{cells:o,path:l,dirty:!1,mtimeMs:_e(l),diskSig:$e(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 Pe={mnist:"notebooks/mnist-demo.ipynb"};export async function runIpynb(E){const re=E?.trim().toLowerCase().replace(/-demo$/,"");if(re&&Pe[re]){const n=await async function(n){const l=Pe[n],a=u(process.cwd(),"icoa-lab"),s=u(a,g(l));if(e(s))return console.log(chalk.gray(" Using your copy ")+chalk.cyan(s)+chalk.gray(" (edits kept — delete the file to start from the original).")),s;process.stdout.write(chalk.gray(" Fetching the demo notebook…"));const i=await ne(l);if(!i)return console.log(chalk.yellow(" not available right now.")),console.log(chalk.gray(" It needs one online moment — try ")+chalk.cyan(`ipynb ${n}`)+chalk.gray(" again.")),null;try{o(a,{recursive:!0}),r(s,t(i))}catch(e){return console.log(chalk.yellow(` could not write ${s}: ${e instanceof Error?e.message:String(e)}`)),null}return console.log(chalk.green(" saved ")+chalk.cyan(s)),s}(re);if(!n)return;E=n}const de=p(a()),we=u(a(),".icoa","ipynb-out");ie();const ve=e(de.python),Se=X();if(!ve&&!Se)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 Ee=E?xe(E):null,Ce=Ee?Ee.doc:{cells:[],path:null,dirty:!1};let Ge=new I({venvPython:de.python,venvRoot:de.root}),je=null,Ue=null,Ae=null,Ie=fe(Ce.path);if(ve){process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await Ge.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("."));Ee&&console.log(Ee.note);let Ne=!1,Te=!1;Q({id:"ipynb",title:{en:"Notebook",zh:"Notebook 笔记本"},what:{en:"A Jupyter notebook inside the terminal: cells run one by one in a live Python kernel. You are already inside it — never type python file.ipynb here.",zh:"终端里的 Jupyter notebook:cell 在常驻 Python 内核里逐格运行。你已经在 notebook 里面了 —— 不要再敲 python file.ipynb。"},steps:[{verb:"cells",what:{en:"list the cells (md = explanation, ○ = not run yet)",zh:"列出所有 cell(md = 讲解,○ = 还没跑)"},done:()=>Ne},{verb:"run all",what:{en:"run every cell top to bottom; stops at the first error",zh:"从头到尾跑每一格;遇到第一个报错就停"},done:()=>Ce.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:()=>Ce.dirty},{verb:"save",what:{en:"write it back to disk as a real .ipynb",zh:"存回磁盘,标准 .ipynb"},done:()=>Te},{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!==je,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:()=>He()});const Oe=T(),Me=null!==Oe,De=Me?Oe.listeners("line").slice():[];Me&&Oe.removeAllListeners("line");const qe=Me?Oe:c({input:process.stdin,output:process.stdout,terminal:!0});Me||O(qe);const Le=Me?qe.prompt:null,ze=Me?qe.getPrompt():"";Me&&(qe.prompt=i.prototype.prompt),Me||D();const Re=[];let Ke,Be=!1,Fe=!1,We=!1,Je=null,Ve=null;const Ye=()=>{if(Ve)return qe.setPrompt(chalk.bold.cyan(` editor 1-${Ve.options.length} > `)),void qe.prompt();const e=je?"icoa ipynb ⚡gpu":"icoa ipynb";qe.setPrompt(chalk.bold.cyan(Re.length?`${e} ...> `:`${e}> `)),qe.prompt()},He=()=>{const o=Ce.path?y(Ce.path):process.cwd(),n=fe(Ce.path);let l="",r=!1;try{const e=JSON.parse(t(u(o,"meta.json"),"utf-8"));l=e.judge??"",r=!0===e.needs_gpu}catch{}const a=Ce.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(Ce.path?g(Ce.path):"new empty notebook")+chalk.gray(` · ${Ce.cells.length} cells (${a} run) · submission.csv: `)+(s?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),je?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(n?" — trains the baseline, writes submission.csv":" — runs every cell top to bottom")),n&&"icoa-holdout"===l?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("submit")+chalk.gray(" — scored + ranked right here, no need to leave (")+chalk.cyan("board")+chalk.gray(" shows standings)")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):n&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):n?(console.log(chalk.gray(" 2. ")+chalk.bold.cyan("check")+chalk.gray(" — verifies the file format, right here")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick 🧠 Learn → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()};let Xe=()=>{};const Ze=new Promise(e=>{Xe=e}),Qe=async()=>{if(Ge=new I({venvPython:de.python,venvRoot:de.root}),e(de.python)){process.stdout.write(chalk.gray(" Starting local kernel…"));try{await Ge.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."))},eo=async(e,n=!1)=>{const t=H(e),l=S(t);if(l.length>0)return console.log(chalk.red(" committee seat file rejected: ")+chalk.gray(l.join(", "))),!1;const s=u(a(),".icoa","gputask","key");try{o(u(a(),".icoa","gputask"),{recursive:!0}),r(s,e.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),!1}const i=Ce.path?g(y(Ce.path)):"work",c=`${t.outDir}/${i.replace(/[^A-Za-z0-9._-]/g,"_")||"work"}`,d=N(t.python,{ICOA_KAGGLE_DATA:c,ICOA_KAGGLE_OUT:c,ICOA_GPUTASK_SID:e.sid},c),h=new I({spawnSpec:{command:"ssh",args:P(t,s,d)},readyTimeoutMs:9e4});n||process.stdout.write(chalk.gray(` Connecting to your seat (${e.host})…`));try{await h.start()}catch(e){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" The box may be rebuilding (Spot reclaim) — ")+chalk.cyan("gpufortask")+chalk.gray(" shows the seat state; ")+chalk.cyan("gpu on")+chalk.gray(" again once it is ready.")),!1}await Ge.shutdown().catch(()=>{}),Ge=h,je={...t,outDir:c},Ae=e,Ue=Date.now(),h.onUnexpectedExit=()=>{Ge===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).")),je=null,Ae=null,Ue=null,Qe().then(()=>Ye()))},console.log(chalk.bold.green(" ⚡ connected.")),console.log(chalk.gray(` ${Z[e.tier]} · cells run in ${c}`));const p=await oo();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},oo=async()=>{if(!Ce.path||!je?.outDir)return 0;const e=y(Ce.path);let o=[];try{o=n(e)}catch{return 0}let r=0;for(const n of o){if(n.startsWith("."))continue;const o=u(e,n);let a;try{a=l(o)}catch{continue}if(a.isFile()&&!(a.size>5242880))try{await Ge.putFile(`${je.outDir}/${n}`,t(o)),r++}catch{}}return r},no=async(e,n=!1)=>{if(!je)return n||console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed).")),!1;const t=e.trim()||"submission.csv",l=t.startsWith("/")?t:`${je.outDir}/${t}`;let a;try{a=await Ge.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=Ie?u(process.cwd(),"icoa-kaggle",Ie):process.cwd(),i=u(s,g(t));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)`)),!n&&Ie&&"submission.csv"===g(t)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${Ie}`)+chalk.gray(" · score it: ")+chalk.cyan("submit")),!0},to=async e=>{const[n,...t]=e.trim().split(/\s+/),l=(n??"").toLowerCase();"on"===l||"connect"===l?await(async()=>{if(je)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=X();if(e)return void await(async e=>{await eo(e)})(e);const n=pe();if(!n)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));Ie||(Ie=fe(Ce.path));const t=Date.now();process.stdout.write(chalk.gray(" Requesting a GPU box…"));let l=await me("lease",n,Ie??void 0),s=0,i=!1;const c=()=>`${Math.round((Date.now()-t)/1e3)} s`;for(;"queued"===l.state&&s<(l.bootStage||i?60:24);)l.bootStage&&(i=!0),0===s&&console.log(),process.stdout.write(`\r ${chalk.yellow(C(l))} `),await new Promise(e=>setTimeout(e,5e3)),l=await me("status",n),s++;if("queued"===l.state)return console.log(),void(i?(console.log(chalk.yellow(` The GPU box is still starting (${c()} so far) — your place is held.`)),console.log(chalk.gray(" Keep editing; ")+chalk.cyan("gpu on")+chalk.gray(" again in a minute picks it up."))):(console.log(chalk.yellow(" Still queued — your place is held server-side.")),console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."))));if(i&&"ready"===l.state&&(console.log(),console.log(chalk.green(` ✓ GPU box ready in ${c()}`)+chalk.gray(` · ${l.gpuName??"GPU"}${l.zone?` · ${l.zone}`:""} · built just for this session`))),"ready"!==l.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${l.message??"no lease granted"}`));const g=S(l);if("local"!==l.transport||process.env.ICOA_GPU_SERVER||g.push("local transport from a non-dev broker"),g.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(g.join(", "))),void await me("release",n);const y=Ie?`${l.dataRoot}/${Ie}`:l.dataRoot,d=N(l.python,{ICOA_KAGGLE_DATA:y,ICOA_KAGGLE_OUT:l.outDir},l.outDir);let h;if("local"===l.transport)h={command:"/bin/sh",args:["-c",d]};else{const e=u(a(),".icoa","gpu","lease-key");try{o(u(a(),".icoa","gpu"),{recursive:!0}),r(e,l.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await me("release",n)}h={command:"ssh",args:P(l,e,d)}}const p=new I({spawnSpec:h,readyTimeoutMs:9e4}),m=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 me("release",n)}await Ge.shutdown().catch(()=>{}),Ge=p,je=l,Ue=Date.now();const f=Math.round((l.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected")+chalk.gray(` (${Math.round((Date.now()-m)/1e3)} s).`)),console.log(chalk.gray(` Cells now run on the ${l.gpuName?`${l.gpuName} `:""}GPU box · ${f}m left on this lease.`));const w=G(l.windowCloseEpoch);w&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${w}.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),Ie&&console.log(chalk.gray(` Dataset is already on the box (${Ie}) — 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(je&&Ae){const e=Ue?Math.round((Date.now()-Ue)/1e3):0;return await Ge.shutdown().catch(()=>{}),je=null,Ae=null,Ue=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 Qe()}if(!je)return void console.log(chalk.gray(" not on a GPU kernel."));const e=pe(),o=void 0!==je.gpuName,n=Ue?Math.round((Date.now()-Ue)/1e3):0;await Ge.shutdown().catch(()=>{}),e&&await me("release",e),je=null,Ue=null;const t=Math.floor(n/60),l=t>0?`${t} m ${n%60} s`:`${n} s`;console.log(chalk.green(` ⚡ GPU lease released after ${l}`)+chalk.gray(" — billing for you stopped.")),o&&console.log(chalk.gray(" The box recycles itself now that nobody holds it (")+chalk.cyan("gpu queue")+chalk.gray(" shows 0 boxes once it is gone); the next ")+chalk.cyan("gpu on")+chalk.gray(" builds a fresh one.")),await Qe()})():"status"===l||""===l?await(async()=>{const e=X();if(e)return console.log(chalk.green(` ⚡ committee seat · ${Z[e.tier]} · ${e.host}`)+chalk.gray(Ae?" (this notebook is connected)":" (not connected here — gpu on)")),void console.log(chalk.gray(" Seat state, usage and stop: ")+chalk.cyan("gpufortask"));const o=pe();if(!o)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const n=await me("status",o);if("ready"===n.state){const e=Math.round((n.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(je?" (this notebook is connected)":" (not connected here — gpu on)"));const o=G(n.windowCloseEpoch);o&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${o}.`))}else"queued"===n.state?console.log(chalk.yellow(` ${C(n)}`)):"none"===n.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${n.message??"GPU broker not reachable"}`))})():"queue"===l||"q"===l?await(async()=>{const e=pe();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${ue()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await n.json();o=t.data??t}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,t="number"==typeof o.free?o.free:0,l=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${t} free`));const a=G("number"==typeof o.window_close_epoch?o.window_close_epoch:void 0);a&&console.log(chalk.gray(` ⏱ Tonight's GPU window: ${a}.`)),console.log(chalk.bold.white(" ▶ running now:")),0===l.length&&console.log(chalk.gray(0===n?" (no box up — gpu on starts a T4 for you, ~1–2 min)":" (idle — gpu on takes a box immediately)"));for(const e of l){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,t=Math.floor(n/60),l=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${t}:${l} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",t=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+t)}console.log()})():"key"===l?(e=>{const n=e.trim();if(n)try{o(u(a(),".icoa"),{recursive:!0}),r(he(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${he()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(t.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},lo=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>Ce.cells.length?(console.log(0===Ce.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${Ce.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:Ce.cells[o-1],idx:o}},ro=(e,o)=>{if(e.length<=o)return e;const n=Math.floor(.6*o);return`${e.slice(0,n)}\n…(${e.length-o} chars elided)…\n${e.slice(-(o-n))}`};let ao=!1;const so=()=>{const e=w().notebookEditor;return e?_(e):null},io=()=>!(!(process.env.VISUAL??"").trim()&&!(process.env.EDITOR??"").trim()),co=()=>so()??x(),go={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"},yo=(e,o)=>{if(e){const n=_(e);return n?v(n.cmd)?(o(n),!0):(console.log(chalk.yellow(` ${$(n)} is not installed on this computer.`)+chalk.gray(" See the choices: ")+chalk.cyan("editor")),!0):(console.log(chalk.yellow(` unknown editor "${e}" — use `)+chalk.cyan("nano")+chalk.yellow(", ")+chalk.cyan("code")+chalk.yellow(" or ")+chalk.cyan("vi")),!0)}if(so()||io())return o(co()),!0;const n=["nano","code","vi"].map(e=>_(e)).filter(e=>null!==e&&v(e.cmd));return n.length<2||!process.stdin.isTTY?(o(x()),!0):((e=>{console.log(),console.log(chalk.bold.white(" Which editor should edit / add open?")+chalk.gray(" (asked once)")),e.forEach((e,o)=>{const n=$(e);console.log(chalk.cyan(` ${o+1} ${n.padEnd(5)}`)+chalk.gray(` ${go[n]??""}`)+("nano"===n?chalk.green(" (recommended)"):""))}),console.log(chalk.gray(` type 1-${e.length} or a name · Enter = cancel · change later with `)+chalk.cyan("editor"))})(n),Ve={resume:o,tries:0,options:n},!1)},uo=e=>{if(!Ce.path)return!1;let o;try{const e=t(Ce.path,"utf8");o=Ce.path.endsWith(".ipynb")?B(e):F(e)}catch(e){return console.log(chalk.yellow(" could not re-read the file: ")+chalk.gray(e instanceof Error?e.message:String(e))),!1}const n=R(Ce.cells,o);return Ce.cells=n.cells,Ce.dirty=!1,Ce.mtimeMs=_e(Ce.path),Ce.diskSig=$e(o),Ke=void 0,console.log(chalk.gray(` ↻ reloaded ${g(Ce.path)}${e?" (you changed it in your editor)":""} — `)+chalk.white(`${n.cells.length} cells, ${n.changed} changed`)+chalk.gray(n.kept?`, ${n.kept} kept their output.`:".")),console.log(chalk.gray(" variables stay in the kernel — run just the cells you changed, or ")+chalk.cyan("run all")),!0},ho=()=>void 0!==Ce.diskSig?$e(Ce.cells)!==Ce.diskSig:Ce.dirty,po=(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)),mo=async o=>{if(o.trim()&&M(`ipynb: ${o.trim()}`),Fe)return void(o.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));if(Ve){const e=Ve,n=o.trim().toLowerCase(),t=_(n),l=/^\d+$/.test(n)?e.options[Number(n)-1]:t?e.options.find(e=>$(e)===$(t)):void 0;return l?(Ve=null,b({notebookEditor:$(l)}),console.log(chalk.green(` ✓ edit / add will open ${$(l)}`)+chalk.gray(" · change any time: ")+chalk.cyan("editor")),e.resume(l)):""===n||["q","quit","back","cancel","exit"].includes(n)?(Ve=null,console.log(chalk.gray(" cancelled — nothing changed."))):++e.tries>=3?(Ve=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 Ye()}let n=o.trim();if(0===Re.length&&/^icoa\s+[a-z/]/i.test(n)&&(n=n.replace(/^icoa\s+/i,"")),0===Re.length){const o=n.split(/\s+/),l=(o[0]??"").toLowerCase(),i=n.slice(o[0]?.length??0).trim();if("quit"!==l&&"exit"!==l&&"q"!==l&&(We=!1),Je&&l!==Je&&(Je=null),ge.has(l)&&(()=>{if(!Ce.path||void 0===Ce.mtimeMs)return;const e=_e(Ce.path);if(void 0!==e&&e!==Ce.mtimeMs){if(ho()){if(Ke===e)return;return Ke=e,console.log(chalk.yellow(` ⚠ ${g(Ce.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"))}uo(!0)}})(),"quit"===l||"exit"===l||"back"===l||"q"===l||"menu"===l)return Ce.dirty&&!We?(We=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void Ye()):void await(async()=>{if(ee("ipynb"),qe.removeAllListeners("line"),Me||q(),console.log(),je&&Ae)je=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(je){const e=pe();e&&await me("release",e),je=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await Ge.shutdown().catch(()=>{}),Me){Le&&(qe.prompt=Le),qe.setPrompt(ze);for(const e of De)qe.on("line",e);qe.prompt(),Xe()}else O(null),Xe(),qe.close()})();if("clear"===l||"cls"===l)return console.clear(),ie(),void Ye();if("restart"===l)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await Ge.shutdown().catch(()=>{});try{await Ge.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 Ye();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(se()?" 问 AI 这一格(默认最近报错的那格;带上代码和 traceback)":" ask the AI about a cell (defaults to the last one that errored)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" load <file>")+chalk.gray(" open another .ipynb / .py (drag the file into this window)")),console.log(chalk.cyan(" reload")+chalk.gray(" re-read the file — or just save in Jupyter / VS Code: the next run picks it up")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" gpu on/off")+chalk.gray(" run cells on a GPU box — a GCP T4 starts for you on demand (~1–2 min), ")+chalk.cyan("gpu off")+chalk.gray(" hands it back")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),console.log(chalk.cyan(" selfcheck")+chalk.gray(" committee seat: rerun the whole notebook fresh, measure peak GPU memory → capsule size, file the report")),console.log(chalk.cyan(" upload <f>")+chalk.gray(" send a file to the box (committee seat: files next to the notebook go up on gpu on)")),console.log(chalk.gray(" try it: ")+chalk.cyan("icoa> ipynb mnist")+chalk.gray(" — the MNIST demo notebook (edit → run → train on the T4 → gpu off)")),console.log(chalk.cyan(" check / submit")+chalk.gray(" verify / score your submission.csv — right here, no quit needed")),console.log(chalk.cyan(" board")+chalk.gray(" live standings for this competition")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log()):oe(),void Ye();if("guide"===l||"/guide"===l)return He(),void Ye();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 Ye();if("open"===l&&""===i)return be&&te(be)?console.log(chalk.gray(" reopening ")+chalk.cyan(be)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void Ye();if("cells"===l||"ls"===l)return(()=>{if(Ne=!0,0===Ce.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);Ce.cells.forEach((o,n)=>{const t=V(o),l="✓"===t?chalk.green(t.padEnd(2)):"✗"===t?chalk.red(t.padEnd(2)):"md"===t?chalk.magenta(t.padEnd(2)):chalk.gray(t.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${l} ${chalk.white(L(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void Ye();if("show"===l)return(e=>{const o=lo(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of A(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),ke(o.cell.result,we)),console.log()}})(i),void Ye();if("edit"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ").toLowerCase();return""===n||"all"===n?yo(o,e=>(e=>{qe.pause();const o=k(Y(Ce.cells),".py",e,"notebook");if(qe.resume(),null===o)return void console.log(chalk.yellow(" editor cancelled or failed — notebook unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const n=z(o,Ce.cells);if(n.same)return void console.log(chalk.gray(" no changes."));if(0===n.cells.length&&Ce.cells.length>0)return void console.log(chalk.yellow(` the file came back empty — kept all ${Ce.cells.length} cells.`)+chalk.gray(" To remove cells one by one: ")+chalk.cyan("del N"));Ce.cells=n.cells,Ce.dirty=!0;const t=[];n.changed.length&&t.push(`${n.changed.length} changed (${n.changed.join(", ")})`),n.added.length&&t.push(`${n.added.length} added (${n.added.join(", ")})`),n.deleted&&t.push(`${n.deleted} deleted`),n.reordered&&t.push("reordered"),console.log(chalk.green(` ✓ notebook updated — ${Ce.cells.length} cells`)+chalk.gray(` · ${t.join(" · ")}`));const l=[...n.changed,...n.added].filter(e=>"code"===Ce.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)):lo(n)&&yo(o,e=>((e,o)=>{const n=lo(e);if(!n)return;qe.pause();const t=k(n.cell.source,"markdown"===n.cell.kind?".md":".py",o);if(qe.resume(),null===t)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (choose another editor: ")+chalk.cyan("editor")+chalk.gray(")"));const l=t.replace(/\s+$/,"");l!==n.cell.source?(n.cell.source=l,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Ce.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(n,e)),void Ye()}if("add"===l){const e=i.split(/\s+/).filter(Boolean),o=e.find(e=>null!==_(e)),n=e.filter(e=>e!==o).join(" ");return yo(o,e=>((e,o)=>{const n=e.trim().toLowerCase(),t="md"===n||"markdown"===n||"text"===n||"txt"===n;if(n&&!t&&"py"!==n&&"code"!==n&&"python"!==n)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));qe.pause();const l=k(t?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",t?".md":".py",o);qe.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(Ce.cells.push({kind:t?"markdown":"code",source:r,result:null}),Ce.dirty=!0,console.log(chalk.green(` ✓ added ${t?"markdown ":""}cell ${Ce.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${Ce.cells.length}`)+chalk.gray(t?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(n,e)),void Ye()}if("editor"===l&&/^[\w-]*$/.test(i))return(e=>{const o=e.trim().toLowerCase(),n=$(co());if(!o){console.log(),console.log(chalk.gray(" edit / add open: ")+chalk.bold.white(n)+chalk.gray(` (${so()?"saved":io()?"from $EDITOR":"default"})`));for(const e of["nano","code","vi"]){const o=_(e),t=v(o.cmd);console.log(chalk.cyan(` editor ${e.padEnd(5)}`)+chalk.gray(t?` ${go[e]}`:" not installed here")+(e===n?chalk.green(" ← now"):""))}return console.log(chalk.gray(" one edit only: ")+chalk.cyan("edit 3 nano")+chalk.gray(" · back to $EDITOR / vi: ")+chalk.cyan("editor default")),void console.log()}if("default"===o||"reset"===o||"off"===o)return b({notebookEditor:""}),void console.log(chalk.green(" ✓ edit / add now follow $EDITOR")+chalk.gray(` (here: ${$(x())})`)+chalk.gray(" · choose again: ")+chalk.cyan("editor nano"));const t=_(o);if(!t)return void console.log(chalk.yellow(` unknown editor "${o}" — `)+chalk.cyan("editor nano")+chalk.yellow(" · ")+chalk.cyan("editor code")+chalk.yellow(" · ")+chalk.cyan("editor vi"));const l=$(t);so()&&$(so())===l?console.log(chalk.gray(` already ${l} · back to $EDITOR / vi: `)+chalk.cyan("editor default")):v(t.cmd)?(b({notebookEditor:l}),console.log(chalk.green(` ✓ edit / add now open ${l}`)+chalk.gray(" · undo: ")+chalk.cyan(`editor ${n===l?"default":n}`))):console.log(chalk.yellow(` ${l} is not installed on this computer — nothing changed.`))})(i),void Ye();if("reload"===l&&""===i)return Ce.path&&e(Ce.path)?ho()&&"reload"!==Je?(Je="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."))):(Je=null,uo(!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 Ye();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 Ye();const o=K(i,a()),n=d(o)?o:h(process.cwd(),o);if(e(n))if(Ce.dirty&&"load"!==Je)Je="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{Je=null;const e=xe(n);Ce.cells=e.doc.cells,Ce.path=e.doc.path,Ce.dirty=!1,Ce.mtimeMs=e.doc.mtimeMs,Ce.diskSig=e.doc.diskSig,Ke=void 0,Ie=fe(Ce.path),console.log(e.note),console.log(chalk.gray(" the kernel keeps its variables — ")+chalk.cyan("restart")+chalk.gray(" for a clean start."))}else console.log(chalk.yellow(" no such file: ")+chalk.white(n)),console.log(chalk.gray(" tip: drag the file into this window instead of typing the path."));return void Ye()}if("del"===l||"delete"===l)return(e=>{const o=lo(e);o&&(Ce.cells.splice(o.idx-1,1),Ce.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${Ce.cells.length} left.`)+(o.idx<=Ce.cells.length?chalk.yellow(" ⚠ 后面的 cell 号已顺移")+chalk.gray(" — ")+chalk.cyan("cells")+chalk.gray(" 重看一眼"):"")))})(i),void Ye();if(("md"===l||"py"===l)&&/^\d+$/.test(i))return((e,o)=>{const n=lo(e);if(!n)return;const t="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,Ce.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${t}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${t}.`))})(i,"md"===l?"markdown":"code"),void Ye();if("gpu"===l)return Fe=!0,await to(i),Fe=!1,void Ye();if("download"===l||"dl"===l)return Fe=!0,await no(i),Fe=!1,void Ye();if("selfcheck"===l||"self-check"===l)return Fe=!0,await(async()=>{const e=Ae;if(!e||!je)return void console.log(chalk.yellow(" selfcheck runs on your committee seat — ")+chalk.cyan("gpu on")+chalk.yellow(" first."));if(0===Ce.cells.filter(e=>"code"===e.kind).length)return void console.log(chalk.yellow(" nothing to check — the notebook has no code cells."));console.log(chalk.bold.cyan(" 🔬 selfcheck")+chalk.gray(` · fresh kernel · ${Z[e.tier]} · every code cell from the top`));const o=Ge;if(await eo(e,!0),Ge===o)return void console.log(chalk.yellow(" could not open a fresh kernel on the seat."));const n=Date.now(),t=[];let l=!1;for(let e=0;e<Ce.cells.length;e++){const o=Ce.cells[e];if("code"!==o.kind)continue;const n=e+1,r=Date.now();process.stdout.write(chalk.gray(` cell ${n} … `));try{o.result=await Ge.execute(o.source)}catch(e){t.push({n:n,ok:!1,ms:Date.now()-r,error:e instanceof Error?e.message:String(e)}),console.log(chalk.red("kernel error")),l=!0;break}Ce.dirty=!0;const a=Date.now()-r,s=o.result.outputs.find(e=>"error"===e.kind);if(t.push({n:n,ok:o.result.ok,ms:a,error:s&&"error"===s.kind?`${s.ename}: ${s.evalue}`:void 0}),console.log(o.result.ok?chalk.green(`ok ${(a/1e3).toFixed(1)} s`):chalk.red(`raised ${(a/1e3).toFixed(1)} s`)),!o.result.ok){ke(o.result,we),l=!0;break}}const r=Date.now()-n,a=["import json as _j, os as _o, sys as _s, hashlib as _h, platform as _p",'_r = {"python": _s.version.split()[0], "platform": _p.platform()}',"try:"," import torch as _t",' _r["torch"] = _t.__version__'," if _t.cuda.is_available():",' _r["gpu"] = _t.cuda.get_device_name(0)',' _r["peak_gib"] = round(_t.cuda.max_memory_allocated() / 2**30, 3)',' _r["reserved_gib"] = round(_t.cuda.max_memory_reserved() / 2**30, 3)',"except Exception as _e:",' _r["torch"] = "n/a: %s" % _e','for _m in ("sklearn", "numpy", "pandas", "transformers"):'," try:"," _r[_m] = __import__(_m).__version__"," except Exception:"," pass",'_r["fence"] = _o.environ.get("CUDA_MPS_PINNED_DEVICE_MEM_LIMIT")','_r["units"] = _o.environ.get("ICOA_GPU_UNITS")','_r["files"] = {}','for _f in sorted(_o.listdir(".")):',' if _o.path.isfile(_f) and not _f.startswith("."):'," _sz = _o.path.getsize(_f)"," _d = _h.sha256()",' with open(_f, "rb") as _fh:',' for _c in iter(lambda: _fh.read(1 << 20), b""):'," _d.update(_c)",' _r["files"][_f] = {"bytes": _sz, "sha256": _d.hexdigest()[:16]}','print("ICOA_SELFCHECK " + _j.dumps(_r))'].join("\n");let s={};try{const e=(await Ge.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:Ce.path?g(Ce.path):null,cells:t,ok:!l,wall_ms:r,env:s,peak_gib:i,units:c,ts:Math.floor(Date.now()/1e3)};console.log(),console.log((l?chalk.bold.red(" ✗ selfcheck: a cell raised"):chalk.bold.green(" ✓ selfcheck: every cell ran"))+chalk.gray(` · ${(r/1e3).toFixed(0)} s wall on a shared box (not a time limit)`)),null!==i?console.log(chalk.white(` peak GPU memory ${i.toFixed(2)} GiB`)+(c?chalk.green(` → ${c} capsule unit${c>1?"s":""}`)+chalk.gray(` (fence ${3.5*c} GiB, allocator cap ${(3.5*c-.5).toFixed(1)})`):chalk.red(" → exceeds 3 units (10 GiB cap) — the task must shrink"))):console.log(chalk.gray(" no GPU memory figure (torch not imported or no CUDA) — CPU task, or add a torch import.")),(s.gpu||s.torch)&&console.log(chalk.gray(` ${s.gpu??"no GPU"} · torch ${s.torch??"?"} · sklearn ${s.sklearn??"?"} · numpy ${s.numpy??"?"}`));const d=s.files??{},u=Object.keys(d);u.length>0&&console.log(chalk.gray(` ${u.length} data file${1===u.length?"":"s"} fingerprinted: ${u.slice(0,6).join(", ")}${u.length>6?", …":""}`));try{const o=await fetch(`${le("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."))}})(),Fe=!1,void Ye();if("upload"===l||"up"===l||"put"===l)return Fe=!0,await(async e=>{if(!je)return void console.log(chalk.gray(" local kernel — files are already here. ")+chalk.cyan("gpu on")+chalk.gray(" first."));const o=e.trim();if(!o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("upload <file>")+chalk.gray(" (≤ 20 MB; lands in the box work dir)"));const n=K(o,a()),l=d(n)?n:h(Ce.path?y(Ce.path):process.cwd(),n);let r;try{r=t(l)}catch{return void console.log(chalk.yellow(` cannot read ${l}`))}const s=`${je.outDir}/${g(l)}`;try{const e=await Ge.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),Fe=!1,void Ye();if("check"===l||"submit"===l||"kaggle"===l){const e=await import("./kaggle.js"),o=i.split(/\s+/).filter(Boolean),n="kaggle"===l?(o[0]||"").toLowerCase():l,t=("kaggle"===l?o[1]:o[0])||fe(Ce.path)||void 0;Fe=!0;try{if(("submit"===n||"check"===n)&&je&&!await no("submission.csv",!0))return Fe=!1,void Ye();if("submit"===n){const o=s("sha256").update(Ce.cells.filter(e=>"code"===e.kind).map(e=>e.source).join("\n#%%\n")).digest("hex");await e.runKaggleSubmit(t,{code_sha:o,...Ae?{sid:Ae.sid}:{},...Ce.path?{notebook:g(Ce.path)}:{}})}else"check"===n?await e.runKaggleCheck(t):"final"===n?await e.runKaggleFinal(t,o.slice(2)):"guide"===n?await e.runKaggleGuide(t):await e.runKaggle("kaggle"===l?o[0]:t)}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Fe=!1,void Ye()}if("board"===l){const{runBoard:e}=await import("./board.js"),o=i.split(/\s+/).filter(Boolean);Fe=!0;try{await e(o[0],o[1])}catch(e){console.log(chalk.yellow(" That command failed: ")+chalk.gray(String(e)))}return Fe=!1,void Ye()}if("ai"===l||"/ai"===l)return Fe=!0,await(async e=>{const o=e.trim().split(/\s+/).filter(Boolean),n=o.length>0&&/^\d+$/.test(o[0]),l=(n?o.slice(1):o).join(" ").trim(),r=n?Number(o[0]):(()=>{for(let e=Ce.cells.length-1;e>=0;e--)if((Ce.cells[e].result?.outputs??[]).some(e=>"error"===e.kind))return e+1;return null})()??Ce.cells.length;if(0===Ce.cells.length)return void console.log(chalk.yellow(" 还没有 cell —— 先写点代码,或用 ")+chalk.cyan("add"));const a=lo(String(r));if(!a)return;if("markdown"===a.cell.kind)return void console.log(chalk.yellow(` cell ${a.idx} 是 markdown —— 挑一个代码格,比如 `)+chalk.cyan("ai 2"));const s=(e=>{const o=[];for(const n of e.result?.outputs??[])"stream"===n.kind||"result"===n.kind?o.push(n.text):"error"===n.kind&&(o.push(`${n.ename}: ${n.evalue}`),o.push(n.traceback.map(e=>e.replace(ae,"")).join("\n")));return o.join("\n").replace(ae,"").replace(/\n{3,}/g,"\n\n").trim()})(a.cell),i=(()=>{if(!Ce.path||!fe(Ce.path))return"";try{const e=JSON.parse(t(u(y(Ce.path),"meta.json"),"utf-8")),o=[e.title,e.metric?`metric: ${e.metric}`:"",e.description].filter(Boolean).join("\n");return ro(o,350)}catch{return""}})(),c=se(),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,m-d-i.length),p=ro(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(),ao||(ao=!0,console.log(chalk.gray(" ")+chalk.bold.white("IOAI 2026 ")+chalk.white("Gemma 3n E4B")+chalk.gray(" (32k) · ")+chalk.white(se()?"单轮无记忆":"single-turn, no memory")+chalk.gray(" · ")+chalk.white(`${m} ${se()?"字符/条":"chars/message"}`)+chalk.gray(" · ")+chalk.white(se()?"1000 token/回复":"1000 tokens/reply")),console.log(chalk.gray(se()?" —— 现场就是这个模型和这几条上限,在这里练的手感能原样带过去。":" — the onsite model and the onsite limits, so the habit transfers as-is."))),console.log(chalk.gray(` → cell ${a.idx} · ${v.length}/${m} chars`)+chalk.gray(_?" · 单轮(竞赛档模型)":" · single-turn (contest model)")+(s?chalk.gray(_?" · 含输出":" · output included"):"")+($?chalk.yellow(_?" ⚠ 上下文被裁过,加一句具体问题会更准":" ⚠ context trimmed — a specific question helps"):"")),M(`ipynb: ai ${a.idx}${l?` — ${l}`:""}`);const x=await f(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),Fe=!1,void Ye();if("run"===l)return Fe=!0,await(async e=>{if(!ve&&!Ae&&!je)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=W(e,Ce.cells.length);if(o)for(const e of o){const n=Ce.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(L(n,50))+chalk.gray(" ──"));try{n.result=await Ge.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void ye()}if(Ce.dirty=!0,ke(n.result,we),po(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),console.log(chalk.gray(se()?" 卡住了? ":" Stuck? ")+chalk.bold.cyan(`ai ${e}`)+chalk.gray(se()?" 把这一格的代码和报错一起问 AI(不用离开 notebook)":" sends this cell and its traceback to the AI — without leaving the notebook")),void ye()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of A(n.source))console.log(e);console.log()}}else console.log(0===Ce.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),Fe=!1,void Ye();if("save"===l)return(e=>{if(0===Ce.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()):Ce.path?Ce.path.endsWith(".ipynb")?Ce.path:`${Ce.path.replace(/\.[^./]+$/,"")}.ipynb`:h(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");const n=o===Ce.path?_e(o):void 0;if(void 0!==n&&void 0!==Ce.mtimeMs&&n!==Ce.mtimeMs&&"save"!==Je)return Je="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"));Je=null;try{r(o,J(Ce.cells)),Ce.path=o,Te=!0,Ce.dirty=!1,Ce.mtimeMs=_e(o),Ce.diskSig=$e(Ce.cells),Ke=void 0,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${Ce.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(i),void Ye();if(""===n)return void Ye()}if(Re.length>0&&ce.has(n.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(n.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void Ye();if(Re.push(o),!j(Re))return 1!==Re.length||Be||(Be=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void Ye();const l=Re.join("\n").replace(/\s+$/,"");if(Re.length=0,""!==l.trim()){Fe=!0;try{const e=await Ge.execute(l);Ce.cells.push({kind:"code",source:l,result:e}),Ce.dirty=!0,ke(e,we);const o=po(Ce.cells[Ce.cells.length-1],Ce.cells.length);e.ok||o||ye()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),ye()}Fe=!1,Ye()}else Ye()};qe.on("line",e=>{mo(e)}),Me||qe.on("close",async()=>{await Ge.shutdown().catch(()=>{}),process.exit(0)}),Ye(),await Ze}
|
|
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}
|
package/dist/lib/notebook-doc.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function parseIpynb(t){let e;try{e=JSON.parse(t)}catch{throw new Error("not valid JSON")}const n=e?.cells;if(!Array.isArray(n))throw new Error("not a Jupyter notebook (no cells array)");const r=[];for(const t of n){if(!t||"object"!=typeof t)continue;const e=t.cell_type;if("code"!==e&&"markdown"!==e)continue;const n=t.source,o={kind:e,source:(Array.isArray(n)?n.join(""):"string"==typeof n?n:"").replace(/\s+$/,""),result:null};if("code"===e){const e=t.outputs;Array.isArray(e)&&e.length>0&&(o.rawOutputs=e);const n=t.execution_count;o.rawExecCount="number"==typeof n?n:null}r.push(o)}return r}export function parsePercentPy(t){const e=[];let n=[];const r=()=>{const t=n.join("\n").replace(/^\n+/,"").replace(/\s+$/,"");t&&e.push({kind:"code",source:t,result:null}),n=[]};for(const e of t.split("\n"))/^#\s*%%/.test(e)?r():n.push(e);return r(),e}function t(t){if(t.result){const e=[];for(const n of t.result.outputs)"stream"===n.kind?e.push({output_type:"stream",name:n.name,text:n.text}):"result"===n.kind?e.push({output_type:"execute_result",execution_count:t.result.execCount,data:n.data??{"text/plain":n.text},metadata:{}}):"display"===n.kind?e.push({output_type:"display_data",data:n.data,metadata:{}}):e.push({output_type:"error",ename:n.ename,evalue:n.evalue,traceback:n.traceback});return{outputs:e,execution_count:t.result.execCount}}return{outputs:t.rawOutputs??[],execution_count:t.rawExecCount??null}}export function serializeIpynb(e){const n={nbformat:4,nbformat_minor:5,metadata:{kernelspec:{display_name:"Python 3",language:"python",name:"python3"},language_info:{name:"python",version:"3.12"}},cells:e.map(e=>"markdown"===e.kind?{cell_type:"markdown",metadata:{},source:e.source}:{cell_type:"code",metadata:{},source:e.source,...t(e)})};return`${JSON.stringify(n,null,1)}\n`}export function statusChar(t){return"markdown"===t.kind?"md":null===t.result?"○":t.result.ok?"✓":"✗"}export function cellPreview(t,e){const n=(t.source.split("\n").find(t=>""!==t.trim())??"").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}…`}export function parseRunRange(t,e){const n=t.trim().toLowerCase();if(!n)return null;if("all"===n)return Array.from({length:e},(t,e)=>e+1);const r=n.match(/^(\d+)(?:-(\d+))?$/);if(!r)return null;const o=Number(r[1]),s=r[2]?Number(r[2]):o;return o<1||s<o||s>e?null:Array.from({length:s-o+1},(t,e)=>o+e)}export function mergeReloadedCells(t,e){let n=0,r=0;return{cells:e.map((e,o)=>{const s=t[o];return s&&s.kind===e.kind&&s.source===e.source?(s.result&&n++,{...e,result:s.result}):(r++,e)}),kept:n,changed:r}}const e=['# Whole notebook · each "# %%" line starts a cell · save and close to apply','# new cell: add a line "# %%" (or "# %% markdown") · delete: remove a cell with its "# %%" line'],n=/^# %%(?:\s*\[(\d+)\])?(?:\s*(?:\[(markdown|md)\]|(markdown|md)))?\s*$/i;export function toWholeEditText(t){const n=[e.join("\n")];return t.forEach((t,e)=>{if("markdown"===t.kind){const r=t.source.split("\n").map(t=>""===t?"#":`# ${t}`).join("\n");n.push(`# %% [${e+1}] markdown\n${r}`)}else n.push(`# %% [${e+1}]\n${t.source}`)}),`${n.join("\n\n")}\n`}export function fromWholeEditText(t,r){const o=t.replace(/\r\n/g,"\n").split("\n");let s=0;for(;s<o.length&&(""===o[s].trim()||e.includes(o[s]));)s++;const a=[];let l=null;for(;s<o.length;s++){const t=o[s].match(n);t?(l={tag:t[1]?Number(t[1]):null,kind:t[2]||t[3]?"markdown":"code",body:[]},a.push(l)):(l||(l={tag:null,kind:"code",body:[]},a.push(l)),l.body.push(o[s]))}const u=new Set,c=[],i=[],d=[],p=[];for(const t of a){let e=t.body;"markdown"===t.kind&&(e=e.map(t=>t.startsWith("# ")?t.slice(2):t.startsWith("#")?t.slice(1):t));const n=e.join("\n").replace(/^\n+/,"").replace(/\s+$/,"");if(!n)continue;const o=c.length+1,s=null!==t.tag&&t.tag>=1&&t.tag<=r.length&&!u.has(t.tag)?r[t.tag-1]:null;s&&null!==t.tag&&u.add(t.tag),s&&s.kind===t.kind&&s.source===n?(c.push({...s}),p.push(t.tag)):(c.push({kind:t.kind,source:n,result:null}),(s?i:d).push(o))}return{cells:c,changed:i,added:d,deleted:r.length-u.size,reordered:p.some((t,e)=>e>0&&t<p[e-1]),same:c.length===r.length&&0===i.length&&0===d.length&&p.every((t,e)=>t===e+1)}}export function normalizePathArg(t,e,n=process.platform){let r=t.trim();return r.length>=2&&(r.startsWith("'")&&r.endsWith("'")||r.startsWith('"')&&r.endsWith('"'))?r=r.slice(1,-1):"win32"!==n&&(r=r.replace(/\\(.)/g,"$1")),"~"===r?e:r.startsWith("~/")?`${e}/${r.slice(2)}`:r}
|
|
1
|
+
export function parseIpynb(t){let e;try{e=JSON.parse(t)}catch{throw new Error("not valid JSON")}const n=e?.cells;if(!Array.isArray(n))throw new Error("not a Jupyter notebook (no cells array)");const r=[];for(const t of n){if(!t||"object"!=typeof t)continue;const e=t.cell_type;if("code"!==e&&"markdown"!==e)continue;const n=t.source,o={kind:e,source:(Array.isArray(n)?n.join(""):"string"==typeof n?n:"").replace(/\s+$/,""),result:null};if("code"===e){const e=t.outputs;Array.isArray(e)&&e.length>0&&(o.rawOutputs=e);const n=t.execution_count;o.rawExecCount="number"==typeof n?n:null}const s=t.attachments;"markdown"===e&&s&&"object"==typeof s&&Object.keys(s).length>0&&(o.attachments=s),r.push(o)}return r}export function parsePercentPy(t){const e=[];let n=[];const r=()=>{const t=n.join("\n").replace(/^\n+/,"").replace(/\s+$/,"");t&&e.push({kind:"code",source:t,result:null}),n=[]};for(const e of t.split("\n"))/^#\s*%%/.test(e)?r():n.push(e);return r(),e}function t(t){if(t.result){const e=[];for(const n of t.result.outputs)"stream"===n.kind?e.push({output_type:"stream",name:n.name,text:n.text}):"result"===n.kind?e.push({output_type:"execute_result",execution_count:t.result.execCount,data:n.data??{"text/plain":n.text},metadata:{}}):"display"===n.kind?e.push({output_type:"display_data",data:n.data,metadata:{}}):e.push({output_type:"error",ename:n.ename,evalue:n.evalue,traceback:n.traceback});return{outputs:e,execution_count:t.result.execCount}}return{outputs:t.rawOutputs??[],execution_count:t.rawExecCount??null}}export function serializeIpynb(e){const n={nbformat:4,nbformat_minor:5,metadata:{kernelspec:{display_name:"Python 3",language:"python",name:"python3"},language_info:{name:"python",version:"3.12"}},cells:e.map(e=>"markdown"===e.kind?{cell_type:"markdown",metadata:{},source:e.source,...e.attachments?{attachments:e.attachments}:{}}:{cell_type:"code",metadata:{},source:e.source,...t(e)})};return`${JSON.stringify(n,null,1)}\n`}export function statusChar(t){return"markdown"===t.kind?"md":null===t.result?"○":t.result.ok?"✓":"✗"}export function cellPreview(t,e){const n=(t.source.split("\n").find(t=>""!==t.trim())??"").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}…`}export function parseRunRange(t,e){const n=t.trim().toLowerCase();if(!n)return null;if("all"===n)return Array.from({length:e},(t,e)=>e+1);const r=n.match(/^(\d+)(?:-(\d+))?$/);if(!r)return null;const o=Number(r[1]),s=r[2]?Number(r[2]):o;return o<1||s<o||s>e?null:Array.from({length:s-o+1},(t,e)=>o+e)}export function mergeReloadedCells(t,e){let n=0,r=0;return{cells:e.map((e,o)=>{const s=t[o];return s&&s.kind===e.kind&&s.source===e.source?(s.result&&n++,{...e,result:s.result}):(r++,e)}),kept:n,changed:r}}const e=['# Whole notebook · each "# %%" line starts a cell · save and close to apply','# new cell: add a line "# %%" (or "# %% markdown") · delete: remove a cell with its "# %%" line'],n=/^# %%(?:\s*\[(\d+)\])?(?:\s*(?:\[(markdown|md)\]|(markdown|md)))?\s*$/i;export function toWholeEditText(t){const n=[e.join("\n")];return t.forEach((t,e)=>{if("markdown"===t.kind){const r=t.source.split("\n").map(t=>""===t?"#":`# ${t}`).join("\n");n.push(`# %% [${e+1}] markdown\n${r}`)}else n.push(`# %% [${e+1}]\n${t.source}`)}),`${n.join("\n\n")}\n`}export function fromWholeEditText(t,r){const o=t.replace(/\r\n/g,"\n").split("\n");let s=0;for(;s<o.length&&(""===o[s].trim()||e.includes(o[s]));)s++;const a=[];let l=null;for(;s<o.length;s++){const t=o[s].match(n);t?(l={tag:t[1]?Number(t[1]):null,kind:t[2]||t[3]?"markdown":"code",body:[]},a.push(l)):(l||(l={tag:null,kind:"code",body:[]},a.push(l)),l.body.push(o[s]))}const u=new Set,c=[],i=[],d=[],p=[];for(const t of a){let e=t.body;"markdown"===t.kind&&(e=e.map(t=>t.startsWith("# ")?t.slice(2):t.startsWith("#")?t.slice(1):t));const n=e.join("\n").replace(/^\n+/,"").replace(/\s+$/,"");if(!n)continue;const o=c.length+1,s=null!==t.tag&&t.tag>=1&&t.tag<=r.length&&!u.has(t.tag)?r[t.tag-1]:null;s&&null!==t.tag&&u.add(t.tag),s&&s.kind===t.kind&&s.source===n?(c.push({...s}),p.push(t.tag)):(c.push({kind:t.kind,source:n,result:null}),(s?i:d).push(o))}return{cells:c,changed:i,added:d,deleted:r.length-u.size,reordered:p.some((t,e)=>e>0&&t<p[e-1]),same:c.length===r.length&&0===i.length&&0===d.length&&p.every((t,e)=>t===e+1)}}export function normalizePathArg(t,e,n=process.platform){let r=t.trim();return r.length>=2&&(r.startsWith("'")&&r.endsWith("'")||r.startsWith('"')&&r.endsWith('"'))?r=r.slice(1,-1):"win32"!==n&&(r=r.replace(/\\(.)/g,"$1")),"~"===r?e:r.startsWith("~/")?`${e}/${r.slice(2)}`:r}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{inflateSync as t}from"node:zlib";import{colorMode as e,encodeFrame as n}from"./term-video.js";const r=[137,80,78,71,13,10,26,10];export function isPng(t){return t.length>8&&r.every((e,n)=>t[n]===e)}export function decodePng(e){try{if(!isPng(e))return null;const n=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=8,o=0,s=0,l=0,a=0,i=0,c=null,f=null;const u=[];for(;r+8<=e.length;){const t=n.getUint32(r),h=String.fromCharCode(e[r+4],e[r+5],e[r+6],e[r+7]),m=e.subarray(r+8,r+8+t);if("IHDR"===h)o=n.getUint32(r+8),s=n.getUint32(r+12),l=e[r+16],a=e[r+17],i=e[r+20];else if("PLTE"===h)c=m;else if("tRNS"===h)f=m;else if("IDAT"===h)u.push(m);else if("IEND"===h)break;r+=12+t}const h={0:1,2:3,3:1,4:2,6:4}[a];if(!o||!s||!h||0!==i||8!==l&&16!==l||o*s>4e7)return null;if(3===a&&(!c||8!==l))return null;const m=h*(l/8),g=o*m;let p=0;for(const t of u)p+=t.length;const d=new Uint8Array(p);let b=0;for(const t of u)d.set(t,b),b+=t.length;const M=t(d);if(M.length<(g+1)*s)return null;const w=new Uint8Array(g);let x=new Uint8Array(g);const y=new Uint8Array(o*s*4),A=l/8;for(let t=0;t<s;t++){const e=t*(g+1),n=M[e];for(let t=0;t<g;t++){const r=M[e+1+t],o=t>=m?w[t-m]:0,s=x[t],l=t>=m?x[t-m]:0;let a;if(0===n)a=r;else if(1===n)a=r+o;else if(2===n)a=r+s;else if(3===n)a=r+(o+s>>1);else{if(4!==n)return null;{const t=Math.abs(s-l),e=Math.abs(o-l),n=Math.abs(o+s-2*l);a=r+(t<=e&&t<=n?o:e<=n?s:l)}}w[t]=255&a}for(let e=0;e<o;e++){const n=e*m,r=4*(t*o+e);if(0===a)y[r]=y[r+1]=y[r+2]=w[n],y[r+3]=255;else if(2===a)y[r]=w[n],y[r+1]=w[n+A],y[r+2]=w[n+2*A],y[r+3]=255;else if(3===a){const t=3*w[n];y[r]=c[t]??0,y[r+1]=c[t+1]??0,y[r+2]=c[t+2]??0,y[r+3]=f&&w[n]<f.length?f[w[n]]:255}else 4===a?(y[r]=y[r+1]=y[r+2]=w[n],y[r+3]=w[n+A]):(y[r]=w[n],y[r+1]=w[n+A],y[r+2]=w[n+2*A],y[r+3]=w[n+3*A])}x=w.slice()}return{w:o,h:s,data:y}}catch{return null}}export function thumbSize(t,e,n,r=22){const o=Math.max(16,Math.min(100,n-6)),s=2*r,l=Math.min(o/t,s/e,4),a=Math.max(2,Math.round(t*l));let i=Math.max(2,Math.round(e*l));return i%2&&(i+=1),{w:a,h:i}}export function resample(t,e,n){const r=new Uint8Array(e*n*3);for(let o=0;o<n;o++){const s=Math.floor(o*t.h/n),l=Math.max(s+1,Math.floor((o+1)*t.h/n));for(let n=0;n<e;n++){const a=Math.floor(n*t.w/e),i=Math.max(a+1,Math.floor((n+1)*t.w/e));let c=0,f=0,u=0,h=0;for(let e=s;e<l&&e<t.h;e++)for(let n=a;n<i&&n<t.w;n++){const r=4*(e*t.w+n),o=t.data[r+3]/255;c+=t.data[r]*o+255*(1-o),f+=t.data[r+1]*o+255*(1-o),u+=t.data[r+2]*o+255*(1-o),h++}const m=3*(o*e+n);r[m]=h?Math.round(c/h):255,r[m+1]=h?Math.round(f/h):255,r[m+2]=h?Math.round(u/h):255}}return r}export function pngThumbLines(t,e,r,o=22){if("none"===r)return[];const s=decodePng(t);if(!s)return[];const{w:l,h:a}=thumbSize(s.w,s.h,e,o);return n(resample(s,l,a),0,l,a,r)}export function thumbForTerminal(t,n=22){const r=process.stdout.columns||80;return pngThumbLines(t,r,e(process.env,r,!!process.stdout.isTTY),n)}export function mdImages(t){const e=[];let n=!1;for(const r of t.split("\n"))if(/^\s*(```|~~~)/.test(r))n=!n;else if(!n){for(const t of r.matchAll(/!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?[^)]*\)/g))e.push({alt:t[1],target:t[2]});for(const t of r.matchAll(/<img\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi)){const n=/\balt\s*=\s*["']([^"']*)["']/i.exec(t[0]);e.push({alt:n?n[1]:"",target:t[1]})}}return e}export function mdWithoutImages(t){return t.replace(/!\[([^\]]*)\]\(\s*<?[^)\s>]+>?[^)]*\)/g,(t,e)=>`[image: ${e||"picture"}]`).replace(/<img\b[^>]*>/gi,t=>{const e=/\balt\s*=\s*["']([^"']*)["']/i.exec(t);return`[image: ${e?.[1]||"picture"}]`})}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icoa-cli",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.708",
|
|
4
4
|
"description": "ICOA CLI — AI-native competition runtime of the International Cyber Olympiad in AI: learn, practise, and compete in AI & cybersecurity from the terminal (AI4CTF · CTF4AI · CTF4EAI)",
|
|
5
5
|
"author": "Charlie Zhu",
|
|
6
6
|
"type": "module",
|