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