icoa-cli 2.19.702 → 2.19.704

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/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as l}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerUpgradeCommand as m}from"./commands/upgrade.js";import{registerNoteCommand as c}from"./commands/note.js";import{registerLogCommand as g}from"./commands/log.js";import{registerLangCommand as d}from"./commands/lang.js";import{registerSetupCommand as p}from"./commands/setup.js";import{registerEnvCommand as h}from"./commands/env.js";import{registerAienvCommand as f}from"./commands/aienv.js";import{registerPythonCommands as 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();
2
+ import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as l}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerUpgradeCommand as m}from"./commands/upgrade.js";import{registerNoteCommand as c}from"./commands/note.js";import{registerLogCommand as g}from"./commands/log.js";import{registerLangCommand as d}from"./commands/lang.js";import{registerSetupCommand as p}from"./commands/setup.js";import{registerEnvCommand as h}from"./commands/env.js";import{registerAienvCommand as f}from"./commands/aienv.js";import{registerPythonCommands as u}from"./commands/python.js";import{registerMujocoCommands as y}from"./commands/mujoco.js";import{registerDuckCommand as w}from"./commands/duck.js";import{registerIpynbCommand as j}from"./commands/ipynb.js";import{registerAi4ctfCommand as b}from"./commands/ai4ctf.js";import{registerExamCommand as v}from"./commands/exam.js";import{registerCtf4aiDemoCommand as T}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as $}from"./commands/theme.js";import{registerLearnCommand as E}from"./commands/learn.js";import{registerCtf4VlaCommand as A}from"./commands/ctf4vla.js";import{registerDemo2Command as x}from"./commands/demo2.js";import{registerDemo3Command as _}from"./commands/demo3.js";import{registerDemo4Command as I}from"./commands/demo4.js";import{registerDemo5Command as k}from"./commands/demo5.js";import{registerGfssmCommand as C}from"./commands/gfssm.js";import{registerAi4StartupCommand as S}from"./commands/ai4startup.js";import{registerGpuForTaskCommand as L}from"./commands/gpufortask.js";import{registerSimCommand as R}from"./commands/sim.js";import{registerArenaCommand as O}from"./commands/arena.js";import{registerKaggleCommand as N}from"./commands/kaggle.js";import{registerSprintCommand as U}from"./commands/sprint.js";import{registerTeleloadCommand as F}from"./commands/teleload.js";import{registerBoardCommand as P}from"./commands/board.js";import{registerTypeCommand as M}from"./commands/type.js";import{registerBattleCommand as G}from"./commands/battle.js";import{registerWmCommand as H}from"./commands/wm.js";import{getConfig as W,saveConfig as D}from"./lib/config.js";import{registerMicroduckCommand as Y}from"./commands/microduck.js";import{startRepl as V}from"./repl.js";import{RELAUNCH_CODE as J}from"./lib/menu-nav.js";import{setTerminalTheme as X}from"./lib/theme.js";import{cleanupTerminal as q}from"./lib/terminal-cleanup.js";import{checkForUpdates as z,runUpgrade as K,bootUpgradeEligible as B,startBootCheck as Q,printUpdateHint as Z}from"./lib/update-check.js";import{detectIcoaInstalls as oo,isWindowsBuildInWslShell as eo}from"./lib/platform.js";import{ICOA_BIG as no}from"./lib/banner.js";import{readFileSync as so}from"node:fs";import{fileURLToPath as ro}from"node:url";import{dirname as to,join as io}from"node:path";import{setDefaultResultOrder as lo}from"node:dns";import{setDefaultAutoSelectFamilyAttemptTimeout as ao}from"node:net";lo("ipv4first"),ao(4e3);const mo=to(ro(import.meta.url)),co=JSON.parse(so(io(mo,"..","package.json"),"utf-8")).version,go=chalk.cyan(" ─────────────────────────────────────────────────────"),po=`\n${go}\n\n${no.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for K-12 AI & Cyber Olympiads and International AI Hackathons")}\n\n ${chalk.bold.white("ICOA 2026:")} ${chalk.white("Sydney, Australia")}\n ${chalk.bold.white("ICOA 2027:")} ${chalk.white("July 2027")} ${chalk.gray("· host city to be announced")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${co}`)}\n\n${go}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=n?process.argv.slice(1,2):process.argv.slice(1),r=o(process.execPath,s,{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(r.signal){const{appendExitLog:o}=await import("./lib/exit-log.js");o("worker-signal",`signal=${r.signal}`),console.log(),console.log(chalk.yellow(` ⚠ icoa was stopped by signal ${r.signal}`)+chalk.gray(" — another process killed it (not a crash). Run icoa --resume to continue.")),e=0;break}if(e=r.status,0!==e&&e!==J){const{appendExitLog:o}=await import("./lib/exit-log.js");o("worker-exit",`code=${e}`);const n=null!==e&&e>128?e-128:0;console.log(),console.log(n?chalk.yellow(` ⚠ icoa was stopped by signal ${n}`)+chalk.gray(" — another process killed it (not a crash). Run icoa --resume to continue."):chalk.yellow(` ⚠ icoa exited unexpectedly (code ${e})`)+chalk.gray(" — see ~/.icoa/exit.log · run icoa --resume to continue."))}n=!0}while(e===J);q(),process.exit(e??0)}}const ho=new o;if(ho.name("icoa").version(co).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=W();X("high-contrast"===e.themeVariant?"high-contrast":"dark");const n=!!o.resume||!!o.continue,s=B(n)&&process.argv.length<=2;s?Q():z(),function(){const o=oo();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const r=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(r))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${r||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();if(console.log(po),s?"upgraded"===await K({ask:!0})&&(console.log(chalk.gray(" restarting icoa …")),process.exit(J)):Z(),process.argv.length<=2||n)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),n||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void V(ho,n)}),e(ho),n(ho),s(ho),r(ho),t(ho),i(ho),l(ho),a(ho),m(ho),c(ho),g(ho),d(ho),p(ho),h(ho),f(ho),u(ho),y(ho),w(ho),j(ho),b(ho),v(ho),T(ho),$(ho),E(ho),A(ho),x(ho),_(ho),I(ho),k(ho),C(ho),S(ho),L(ho),R(ho),O(ho),N(ho),F(ho),U(ho),P(ho),H(ho),M(ho),G(ho),Y(ho),ho.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=W().geminiModel||"gemini-2.5-flash-lite";o?(D({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}ho.hook("preAction",()=>{!function(){if(!eo())return;const o="─".repeat(Math.max(24,Math.min(52,(process.stdout.columns||80)-4)));console.log(),console.log(chalk.yellow(` ${o}`)),console.log(chalk.yellow.bold(" ⚠ You ARE inside Ubuntu — but this icoa")),console.log(chalk.yellow.bold(" is the WINDOWS build.")),console.log(),console.log(chalk.gray(" WSL appends the Windows PATH, so ")+chalk.cyan("icoa")),console.log(chalk.gray(" found the Windows copy first. Almost")),console.log(chalk.gray(" nothing will work: no vi, no python3,")),console.log(chalk.gray(" env setup cannot install.")),console.log(),console.log(chalk.gray(" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.white(" Fix — inside Ubuntu, check npm is Linux FIRST:")),console.log(` ${chalk.bold.cyan("which npm")}${chalk.gray(" → must not be /mnt/c/...")}`),console.log(` ${chalk.bold.cyan("sudo npm install -g icoa-cli")}`),console.log(` ${chalk.bold.cyan("hash -r")}${chalk.gray(" → bash caches the old path")}`),console.log(chalk.gray(" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(chalk.yellow(` ${o}`)),console.log()}()}),ho.parse();
package/dist/lib/aienv.js CHANGED
@@ -1 +1 @@
1
- import{posix as o,win32 as r}from"node:path";export const REQUIRED_PY={major:3,minor:12};export const AIENV_MARKER_VERSION=2;export const AIENV_PACKAGES=[{name:"jupyter_client",import:"jupyter_client",spec:"jupyter_client>=8.6",group:"core"},{name:"ipykernel",import:"ipykernel",spec:"ipykernel>=6.29",group:"core"},{name:"numpy",import:"numpy",spec:"numpy>=1.26",group:"data"},{name:"scipy",import:"scipy",spec:"scipy>=1.13",group:"data"},{name:"pandas",import:"pandas",spec:"pandas>=2.2",group:"data"},{name:"scikit-learn",import:"sklearn",spec:"scikit-learn>=1.4",group:"data"},{name:"matplotlib",import:"matplotlib",spec:"matplotlib>=3.8",group:"data"},{name:"scikit-image",import:"skimage",spec:"scikit-image>=0.23",group:"data"},{name:"Pillow",import:"PIL",spec:"Pillow>=10.2",group:"data",probe:"from PIL import Image"},{name:"imageio",import:"imageio",spec:"imageio>=2.34",group:"data"},{name:"requests",import:"requests",spec:"requests>=2.31",group:"data"},{name:"pyyaml",import:"yaml",spec:"pyyaml>=6.0",group:"data"},{name:"tqdm",import:"tqdm",spec:"tqdm>=4.66",group:"data"},{name:"torch",import:"torch",spec:"torch>=2.2",group:"deep",note:"large download (~2 GB)"},{name:"transformers",import:"transformers",spec:"transformers>=4.40",group:"deep"},{name:"datasets",import:"datasets",spec:"datasets>=2.19",group:"deep"},{name:"mujoco",import:"mujoco",spec:"mujoco==3.9.0",group:"physics",note:"CPU physics for the ctf4eai arena (~60 MB, version-pinned for fair judging)"}];export function packagesForGroups(o){const r=new Set(o);return AIENV_PACKAGES.filter(o=>r.has(o.group))}export function aienvPaths(n,t=process.platform){const e="win32"===t?r:o,p=e.join(n,".icoa","aienv");if("win32"===t){const o=e.join(p,"Scripts");return{root:p,binDir:o,python:e.join(o,"python.exe"),pip:e.join(o,"pip.exe"),marker:e.join(p,"icoa-aienv.json")}}const i=e.join(p,"bin");return{root:p,binDir:i,python:e.join(i,"python"),pip:e.join(i,"pip"),marker:e.join(p,"icoa-aienv.json")}}export function icoaStandalonePython(n,t=process.platform){const e="win32"===t?r:o;return"win32"===t?e.join(n,".icoa","python312","python.exe"):e.join(n,".icoa","python312","bin","python3.12")}export function hostPythonCandidates(o=process.platform,r){const n=r?[icoaStandalonePython(r,o)]:[];return"win32"===o?["py -3.12",...n,"python","py -3","py"]:"darwin"===o?["python3.12","/opt/homebrew/opt/python@3.12/bin/python3.12","/usr/local/opt/python@3.12/bin/python3.12",...n,"python3"]:["python3.12",...n,"python3"]}export function parsePyVersion(o){if(!o)return null;const r=o.match(/(\d+)\.(\d+)(?:\.\d+)?/);return r?{major:Number(r[1]),minor:Number(r[2])}:null}export function meetsMinPy(o,r){return o.major!==r.major?o.major>r.major:o.minor>=r.minor}export function resolveHostPython(o,r=process.platform,n){for(const t of hostPythonCandidates(r,n)){const r=parsePyVersion(o(t));if(r&&r.major===REQUIRED_PY.major&&r.minor===REQUIRED_PY.minor)return{cmd:t,version:r}}return null}export function resolveRunPython(o,r=process.platform,n){if(n){const t=aienvPaths(n,r).python,e=parsePyVersion(o(`"${t}"`));if(e&&e.major===REQUIRED_PY.major&&e.minor===REQUIRED_PY.minor)return{cmd:t,version:e,source:"aienv"}}const t=resolveHostPython(o,r,n);return t?{...t,source:"host"}:null}export function importCheckCmd(o,r){return`"${o}" -c "${r.probe??`import ${r.import}`}"`}
1
+ import{posix as o,win32 as r}from"node:path";export const REQUIRED_PY={major:3,minor:12};export const AIENV_MARKER_VERSION=2;export const AIENV_PACKAGES=[{name:"jupyter_client",import:"jupyter_client",spec:"jupyter_client>=8.6",group:"core"},{name:"ipykernel",import:"ipykernel",spec:"ipykernel>=6.29",group:"core"},{name:"numpy",import:"numpy",spec:"numpy>=1.26",group:"data"},{name:"scipy",import:"scipy",spec:"scipy>=1.13",group:"data"},{name:"pandas",import:"pandas",spec:"pandas>=2.2",group:"data"},{name:"scikit-learn",import:"sklearn",spec:"scikit-learn>=1.4",group:"data"},{name:"matplotlib",import:"matplotlib",spec:"matplotlib>=3.8",group:"data"},{name:"scikit-image",import:"skimage",spec:"scikit-image>=0.23",group:"data"},{name:"Pillow",import:"PIL",spec:"Pillow>=10.2",group:"data",probe:"from PIL import Image"},{name:"imageio",import:"imageio",spec:"imageio>=2.34",group:"data"},{name:"requests",import:"requests",spec:"requests>=2.31",group:"data"},{name:"pyyaml",import:"yaml",spec:"pyyaml>=6.0",group:"data"},{name:"tqdm",import:"tqdm",spec:"tqdm>=4.66",group:"data"},{name:"torch",import:"torch",spec:"torch>=2.2",group:"deep",note:"large download (~2 GB)"},{name:"transformers",import:"transformers",spec:"transformers>=4.40",group:"deep"},{name:"datasets",import:"datasets",spec:"datasets>=2.19",group:"deep"},{name:"mujoco",import:"mujoco",spec:"mujoco==3.10.0",group:"physics",note:"CPU physics for the ctf4eai arena (~60 MB, version-pinned for fair judging)"}];export function packagesForGroups(o){const r=new Set(o);return AIENV_PACKAGES.filter(o=>r.has(o.group))}export function aienvPaths(n,t=process.platform){const e="win32"===t?r:o,p=e.join(n,".icoa","aienv");if("win32"===t){const o=e.join(p,"Scripts");return{root:p,binDir:o,python:e.join(o,"python.exe"),pip:e.join(o,"pip.exe"),marker:e.join(p,"icoa-aienv.json")}}const i=e.join(p,"bin");return{root:p,binDir:i,python:e.join(i,"python"),pip:e.join(i,"pip"),marker:e.join(p,"icoa-aienv.json")}}export function icoaStandalonePython(n,t=process.platform){const e="win32"===t?r:o;return"win32"===t?e.join(n,".icoa","python312","python.exe"):e.join(n,".icoa","python312","bin","python3.12")}export function hostPythonCandidates(o=process.platform,r){const n=r?[icoaStandalonePython(r,o)]:[];return"win32"===o?["py -3.12",...n,"python","py -3","py"]:"darwin"===o?["python3.12","/opt/homebrew/opt/python@3.12/bin/python3.12","/usr/local/opt/python@3.12/bin/python3.12",...n,"python3"]:["python3.12",...n,"python3"]}export function parsePyVersion(o){if(!o)return null;const r=o.match(/(\d+)\.(\d+)(?:\.\d+)?/);return r?{major:Number(r[1]),minor:Number(r[2])}:null}export function meetsMinPy(o,r){return o.major!==r.major?o.major>r.major:o.minor>=r.minor}export function resolveHostPython(o,r=process.platform,n){for(const t of hostPythonCandidates(r,n)){const r=parsePyVersion(o(t));if(r&&r.major===REQUIRED_PY.major&&r.minor===REQUIRED_PY.minor)return{cmd:t,version:r}}return null}export function resolveRunPython(o,r=process.platform,n){if(n){const t=aienvPaths(n,r).python,e=parsePyVersion(o(`"${t}"`));if(e&&e.major===REQUIRED_PY.major&&e.minor===REQUIRED_PY.minor)return{cmd:t,version:e,source:"aienv"}}const t=resolveHostPython(o,r,n);return t?{...t,source:"host"}:null}export function importCheckCmd(o,r){return`"${o}" -c "${r.probe??`import ${r.import}`}"`}
@@ -1 +1 @@
1
- export const REGISTRY=[{name:"join",mapsTo:["ctf","join"],rest:!0,help:{order:0,section:"Competition",label:"join <url>",text:"Connect to CTFd"}},{name:"activate",mapsTo:["ctf","activate"],rest:!0},{name:"challenges",mapsTo:["ctf","challenges"],help:{order:1,section:"Competition",label:"challenges (ch)",text:"List challenges by category"}},{name:"ch",mapsTo:["ctf","challenges"]},{name:"open",mapsTo:["ctf","open"],rest:!0,help:{order:2,section:"Competition",label:"open <id>",text:"Read challenge + get next steps"}},{name:"submit",mapsTo:["ctf","submit"],rest:!0,help:{order:3,section:"Competition",label:"submit <id> <flag>",text:"Submit a flag"}},{name:"flag",mapsTo:["ctf","submit"],rest:!0},{name:"scoreboard",mapsTo:["ctf","scoreboard"],rest:!0,help:{order:4,section:"Competition",label:"scoreboard (sb)",text:"Live rankings"}},{name:"sb",mapsTo:["ctf","scoreboard"],rest:!0},{name:"status",mapsTo:["ctf","status"],help:{order:5,section:"Competition",label:"status",text:"Your score & timer"}},{name:"time",mapsTo:["ctf","time"],help:{order:6,section:"Competition",label:"time",text:"Countdown timer"}},{name:"ref",help:{order:8,section:"Tools",label:"ref [topic]",text:"Quick reference (linux, web, crypto...)"}},{name:"shell",help:{order:9,section:"Tools",label:"shell",text:"Interactive CTF shell (sandbox if present, else host)"}},{name:"files",help:{order:10,section:"Tools",label:"files <id>",text:"Download challenge files"}},{name:"view"},{name:"connect",help:{order:11,section:"Tools",label:"connect <id>",text:"Connect to remote target"}},{name:"challenge",subs:["start","stop","status"]},{name:"note",help:{order:12,section:"Tools",label:"note [text]",text:"Add a logbook entry (in-exam: tags current Q)"}},{name:"notes"},{name:"logbook",help:{order:13,section:"Tools",label:"logbook [n]",text:"View your logbook (in-exam: filter by Q)"}},{name:"log",help:{order:14,section:"Tools",label:"log",text:"Session history"}},{name:"man"},{name:"manual"},{name:"lang",help:{order:21,section:"System",label:"lang [code]",text:"Switch language (15 supported)"}},{name:"setup"},{name:"env"},{name:"aienv"},{name:"python",subs:["setup","status"]},{name:"mujoco",subs:["setup","status"]},{name:"mojoco",mapsTo:["mujoco"],rest:!0},{name:"ipynb"},{name:"kaggle"},{name:"teleload"},{name:"pandahelpme31"},{name:"gpufortask"},{name:"guide"},{name:"ai4ctf",help:{order:7,section:"AI Teammate",label:"ai4ctf",text:"Free-chat with your AI teammate"}},{name:"model"},{name:"ctf",subs:["challenges","open","submit","scoreboard","status","join","logout","time"]},{name:"exam",subs:["list","start","q","answer","submit","review","result","next","prev","mark","unmark","help"]},{name:"demo",mapsTo:["exam","demo"]},{name:"retry",mapsTo:["exam","demo-retry"]},{name:"nations",mapsTo:["exam","nations"]},{name:"next",mapsTo:["exam","next"]},{name:"prev",mapsTo:["exam","prev"]},{name:"continue"},{name:"logout",mapsTo:["ctf","logout"],help:{order:22,section:"System",label:"logout",text:"Disconnect"}},{name:"ctf4ai"},{name:"mark",mapsTo:["exam","mark"],rest:!0},{name:"unmark",mapsTo:["exam","unmark"],rest:!0},{name:"review",mapsTo:["exam","review"]},{name:"learn",subs:["start","continue"]},{name:"demo2"},{name:"demo3"},{name:"demo4"},{name:"demo5"},{name:"gfssm"},{name:"ctf4eai"},{name:"ctf4vla"},{name:"theme"},{name:"sim"},{name:"arena",subs:["eai"]},{name:"eai"},{name:"wm"},{name:"microduck"},{name:"battle",subs:["edit","syntax","play","replay","submit","status","bots"]},{name:"duck",subs:["edit","syntax","run","replay","submit","board","scenarios","status"]},{name:"type",subs:["15","30","60","words","python","shell","history"],help:{order:15,section:"Tools",label:"type [30]",text:"Typing speed trainer — WPM, live colours, no token"}},{name:"board"},{name:"learn-pull"},{name:"doctor",help:{order:19,section:"System",label:"doctor",text:"Self-check: version, Python, network/firewall, server"}},{name:"upgrade",help:{order:20,section:"System",label:"upgrade",text:"Install the newest icoa and restart into it"}},{name:"update"},{name:"bg",nav:!0,help:{order:17,section:"System",label:"bg <command>",text:"Run a shell command in the background"}},{name:"tasks",nav:!0,help:{order:18,section:"System",label:"tasks [id]",text:"Background task panel / view output"}},{name:"drafts",nav:!0,help:{order:16,section:"System",label:"drafts",text:"Review staged draft answers"}},{name:"help",nav:!0},{name:"menu",nav:!0},{name:"quit",nav:!0},{name:"q",nav:!0},{name:"exit",nav:!0,help:{order:24,section:"System",label:"exit",text:"Quit (session saved)"}},{name:"back",nav:!0},{name:"resume",nav:!0,help:{order:15,section:"System",label:"resume",text:"Continue your last learn card / exam"}},{name:"clear",nav:!0,help:{order:23,section:"System",label:"clear",text:"Clear screen"}},{name:"cls",nav:!0}];export const surface=()=>REGISTRY.map(e=>e.name);export const dispatchable=()=>REGISTRY.filter(e=>!e.nav).map(e=>e.name);export function shortcutFor(e,t){const a=REGISTRY.find(t=>t.name===e&&t.mapsTo);return a?.mapsTo?a.rest?[...a.mapsTo,...t]:[...a.mapsTo]:null}export const subcommandsOf=e=>REGISTRY.find(t=>t.name===e)?.subs;export const helpRows=e=>REGISTRY.filter(t=>t.help?.section===e).sort((e,t)=>e.help.order-t.help.order).map(e=>({label:e.help.label,text:e.help.text}));
1
+ export const REGISTRY=[{name:"join",mapsTo:["ctf","join"],rest:!0,help:{order:0,section:"Competition",label:"join <url>",text:"Connect to CTFd"}},{name:"activate",mapsTo:["ctf","activate"],rest:!0},{name:"challenges",mapsTo:["ctf","challenges"],help:{order:1,section:"Competition",label:"challenges (ch)",text:"List challenges by category"}},{name:"ch",mapsTo:["ctf","challenges"]},{name:"open",mapsTo:["ctf","open"],rest:!0,help:{order:2,section:"Competition",label:"open <id>",text:"Read challenge + get next steps"}},{name:"submit",mapsTo:["ctf","submit"],rest:!0,help:{order:3,section:"Competition",label:"submit <id> <flag>",text:"Submit a flag"}},{name:"flag",mapsTo:["ctf","submit"],rest:!0},{name:"scoreboard",mapsTo:["ctf","scoreboard"],rest:!0,help:{order:4,section:"Competition",label:"scoreboard (sb)",text:"Live rankings"}},{name:"sb",mapsTo:["ctf","scoreboard"],rest:!0},{name:"status",mapsTo:["ctf","status"],help:{order:5,section:"Competition",label:"status",text:"Your score & timer"}},{name:"time",mapsTo:["ctf","time"],help:{order:6,section:"Competition",label:"time",text:"Countdown timer"}},{name:"ref",help:{order:8,section:"Tools",label:"ref [topic]",text:"Quick reference (linux, web, crypto...)"}},{name:"shell",help:{order:9,section:"Tools",label:"shell",text:"Interactive CTF shell (sandbox if present, else host)"}},{name:"files",help:{order:10,section:"Tools",label:"files <id>",text:"Download challenge files"}},{name:"view"},{name:"connect",help:{order:11,section:"Tools",label:"connect <id>",text:"Connect to remote target"}},{name:"challenge",subs:["start","stop","status"]},{name:"note",help:{order:12,section:"Tools",label:"note [text]",text:"Add a logbook entry (in-exam: tags current Q)"}},{name:"notes"},{name:"logbook",help:{order:13,section:"Tools",label:"logbook [n]",text:"View your logbook (in-exam: filter by Q)"}},{name:"log",help:{order:14,section:"Tools",label:"log",text:"Session history"}},{name:"man"},{name:"manual"},{name:"lang",help:{order:21,section:"System",label:"lang [code]",text:"Switch language (15 supported)"}},{name:"setup"},{name:"env"},{name:"aienv"},{name:"python",subs:["setup","status"]},{name:"mujoco",subs:["setup","status"]},{name:"mojoco",mapsTo:["mujoco"],rest:!0},{name:"ipynb"},{name:"kaggle"},{name:"teleload"},{name:"pandahelpme31"},{name:"gpufortask"},{name:"guide"},{name:"ai4ctf",help:{order:7,section:"AI Teammate",label:"ai4ctf",text:"Free-chat with your AI teammate"}},{name:"model"},{name:"ctf",subs:["challenges","open","submit","scoreboard","status","join","logout","time"]},{name:"exam",subs:["list","start","q","answer","submit","review","result","next","prev","mark","unmark","help"]},{name:"demo",mapsTo:["exam","demo"]},{name:"retry",mapsTo:["exam","demo-retry"]},{name:"nations",mapsTo:["exam","nations"]},{name:"next",mapsTo:["exam","next"]},{name:"prev",mapsTo:["exam","prev"]},{name:"continue"},{name:"logout",mapsTo:["ctf","logout"],help:{order:22,section:"System",label:"logout",text:"Disconnect"}},{name:"ctf4ai"},{name:"mark",mapsTo:["exam","mark"],rest:!0},{name:"unmark",mapsTo:["exam","unmark"],rest:!0},{name:"review",mapsTo:["exam","review"]},{name:"learn",subs:["start","continue"]},{name:"demo2"},{name:"demo3"},{name:"demo4"},{name:"demo5"},{name:"gfssm"},{name:"ai4startup"},{name:"ctf4eai"},{name:"ctf4vla"},{name:"theme"},{name:"sim"},{name:"arena",subs:["eai"]},{name:"eai"},{name:"wm"},{name:"microduck"},{name:"battle",subs:["edit","syntax","play","replay","submit","status","bots"]},{name:"duck",subs:["edit","syntax","run","replay","submit","board","scenarios","status"]},{name:"type",subs:["15","30","60","words","python","shell","history"],help:{order:15,section:"Tools",label:"type [30]",text:"Typing speed trainer — WPM, live colours, no token"}},{name:"board"},{name:"learn-pull"},{name:"doctor",help:{order:19,section:"System",label:"doctor",text:"Self-check: version, Python, network/firewall, server"}},{name:"upgrade",help:{order:20,section:"System",label:"upgrade",text:"Install the newest icoa and restart into it"}},{name:"update"},{name:"bg",nav:!0,help:{order:17,section:"System",label:"bg <command>",text:"Run a shell command in the background"}},{name:"tasks",nav:!0,help:{order:18,section:"System",label:"tasks [id]",text:"Background task panel / view output"}},{name:"drafts",nav:!0,help:{order:16,section:"System",label:"drafts",text:"Review staged draft answers"}},{name:"help",nav:!0},{name:"menu",nav:!0},{name:"quit",nav:!0},{name:"q",nav:!0},{name:"exit",nav:!0,help:{order:24,section:"System",label:"exit",text:"Quit (session saved)"}},{name:"back",nav:!0},{name:"resume",nav:!0,help:{order:15,section:"System",label:"resume",text:"Continue your last learn card / exam"}},{name:"clear",nav:!0,help:{order:23,section:"System",label:"clear",text:"Clear screen"}},{name:"cls",nav:!0}];export const surface=()=>REGISTRY.map(e=>e.name);export const dispatchable=()=>REGISTRY.filter(e=>!e.nav).map(e=>e.name);export function shortcutFor(e,t){const a=REGISTRY.find(t=>t.name===e&&t.mapsTo);return a?.mapsTo?a.rest?[...a.mapsTo,...t]:[...a.mapsTo]:null}export const subcommandsOf=e=>REGISTRY.find(t=>t.name===e)?.subs;export const helpRows=e=>REGISTRY.filter(t=>t.help?.section===e).sort((e,t)=>e.help.order-t.help.order).map(e=>({label:e.help.label,text:e.help.text}));
@@ -0,0 +1 @@
1
+ import{marketCalc as e,SEG_N as t}from"./venture.js";export const CHARTS={segments:{en:`your user groups and their shares (box ${t})`,zh:`你的用户分类和占比(第 ${t} 格)`,slide:"user"},survey:{en:"last survey: would-buy in A and B",zh:"最近一次调研:A、B 两国会买比例",slide:"survey"},trend:{en:"would-buy across your surveys (needs 2+)",zh:"历次调研会买比例的变化(至少 2 次)",slide:"evidence"}};export const chartOn=(e,t)=>!1!==e.charts?.[t];export const TEMPLATES={problem:{en:"Problem first",zh:"先讲问题",order:["title","problem","user","alternatives","solution","why_now","value","evidence","survey","price","numbers","moat","risk","next","ask"]},story:{en:"Story first",zh:"先讲故事",order:["title","user","problem","solution","why_now","evidence","survey","alternatives","value","moat","price","numbers","risk","next","ask"]},evidence:{en:"Evidence first",zh:"先讲证据",order:["title","evidence","survey","problem","user","solution","why_now","value","alternatives","moat","price","numbers","risk","next","ask"]}};export const STYLES={night:{en:"Night (dark)",zh:"夜色(深色)"},paper:{en:"Paper (light)",zh:"纸张(浅色)"},bold:{en:"Bold (navy + yellow)",zh:"醒目(藏青 + 黄)"}};const n={title:{en:"",zh:""},problem:{en:"The problem",zh:"问题"},user:{en:"Who has it",zh:"谁有这个问题"},alternatives:{en:"What people do today",zh:"大家现在怎么凑合"},solution:{en:"Our solution",zh:"我们的方案"},value:{en:"Why it is better",zh:"为什么更好"},evidence:{en:"What we heard",zh:"我们听到了什么"},survey:{en:"Simulated survey",zh:"模拟调研"},price:{en:"Who pays, and how much",zh:"谁付钱、付多少"},risk:{en:"When the AI gets it wrong",zh:"AI 出错时"},next:{en:"Our next two weeks",zh:"接下来两周"},ask:{en:"Our ask",zh:"我们需要什么"},why_now:{en:"Why AI, why now",zh:"为什么是 AI、为什么是现在"},numbers:{en:"The numbers",zh:"算账"},moat:{en:"What they cannot copy",zh:"别人抄不走的"}},i={user:{en:"Meet the person",zh:"认识一下这个人"},problem:{en:"What goes wrong",zh:"哪里出了问题"}},r={problem:"problem",user:"user",alternatives:"alternatives",solution:"solution",value:"value",evidence:"evidence",price:"price",risk:"risk",next:"first_step",why_now:"ai_edge",numbers:"ai_cost",moat:"moat"};export const KIND_LABEL=n;const a={price:{en:"price",zh:"价格"},not_needed:{en:"don't need it",zh:"不需要"},already_have:{en:"already use something",zh:"已经有替代"},trust:{en:"trust",zh:"不信任"},privacy:{en:"privacy",zh:"隐私"},effort:{en:"too much effort",zh:"太麻烦"},quality:{en:"doubt it works",zh:"怀疑效果"},other:{en:"other",zh:"其他"}};export function newDeck(e="problem",t="night"){return{template:e,style:t,slides:TEMPLATES[e].order.map(e=>({kind:e,edits:0,own_chars:0,ai_chars:0})),created:(new Date).toISOString()}}export function retemplate(e,t){const n=new Map(e.slides.map(e=>[e.kind,e]));return{...e,template:t,slides:TEMPLATES[t].order.map(e=>n.get(e)??{kind:e,edits:0,own_chars:0,ai_chars:0})}}export function sentences(e,t=4){const n=(e??"").replace(/\s+/g," ").trim();return n?n.split(/(?<=[.!?。!?;;])(?!\d)\s*/).map(e=>e.trim()).filter(Boolean).slice(0,t).map(e=>e.length>180?`${e.slice(0,177)}…`:e):[]}export function renderSlide(t,s,o,l,c,d=[]){const p=s.slides[o];let u,h,m=("story"===s.template&&i[p.kind]||n[p.kind])[l],g=[];const f=r[p.kind];if("title"===p.kind)m=t.name||("zh"===l?"(给项目起个名字:name <名字>)":"(name your venture: name <name>)"),g=sentences(t.boxes.solution,1);else if(f){if(g=sentences(t.boxes[f]),"numbers"===p.kind){const n=e(t.market),i=t.market??{},r=e=>e.toLocaleString("en-US");null!==n.year&&g.push("zh"===l?`市场:${r(i.people)} 人 × ${i.price}/月 × 12 = 每年 ${r(n.year)}${i.source?`(${i.source})`:""}`:`Market: ${r(i.people)} people × ${i.price}/month × 12 = ${r(n.year)} a year${i.source?` (${i.source})`:""}`),null!==n.firstYear&&null!==n.firstYearUsers&&g.push("zh"===l?`第一年现实目标:${r(n.firstYearUsers)} 个用户(会买 ${i.buy}% × 能触达 ${i.reach}%)≈ ${r(n.firstYear)}`:`Realistic first year: ${r(n.firstYearUsers)} users (${i.buy}% would buy × ${i.reach}% reached) ≈ ${r(n.firstYear)}`),null!==n.margin&&g.push("zh"===l?`AI 成本每用户每月 ${i.cost},毛利约 ${n.margin}%`:`AI cost ${i.cost} per user a month — gross margin about ${n.margin}%`)}if("user"===p.kind&&t.segments.length)if(chartOn(s,"segments"))h={title:"zh"===l?"我们的用户分类(占比)":"Our user groups (share)",rows:t.segments.slice(0,6).map(e=>({label:e.source?`${e.name} (${e.source})`:e.name,value:e.share}))};else for(const e of t.segments.slice(0,4))g.push(`${e.name} — ${e.share}%${e.source?` (${e.source})`:""}`);if("evidence"===p.kind&&chartOn(s,"trend")&&d.length>=2){const e=d.slice(-5),t=d.length-e.length;h={title:"zh"===l?"历次模拟调研:目标人群会买比例":"Simulated surveys: target groups would buy",legend:"zh"===l?["A 国","B 国"]:["Country A","Country B"],rows:e.map((e,n)=>({label:"zh"===l?`第 ${t+n+1} 次`:`Survey ${t+n+1}`,value:e.buy_au,value2:e.buy_cn}))}}}else if("survey"===p.kind&&c){u=[];for(const[e,t]of[["AU","A"],["CN","B"]]){const n=c.countries[e];if(!n)continue;chartOn(s,"survey")&&u.push({label:"zh"===l?`${t} 国`:`Country ${t}`,target:n.buy_target,general:n.buy_general,control:n.control_buy,n:n.n});const i=n.ladder;i&&null!==i.stated&&g.push("zh"===l?`${t} 国会买:半价 ${i.half??"–"}% · 原价 ${i.stated}% · 两倍价 ${i.double??"–"}%`:`Country ${t} would buy: half price ${i.half??"–"}% · your price ${i.stated}% · double ${i.double??"–"}%`);const r=n.concerns[0];r&&g.push("zh"===l?`${t} 国不买的头号理由:${a[r.type]?.zh??r.type}(${r.pct}%)`:`Country ${t}: top reason for no — ${a[r.type]?.en??r.type} (${r.pct}%)`)}g.push("zh"===l?"模拟调研:合成受访者,不是真实顾客;每国约 100 人,±10 个百分点。":"Simulated survey: synthetic respondents, not real customers; ~100 per country, ±10 points.")}const v=void 0===p.title&&void 0===p.lines;void 0!==p.title&&(m=p.title),void 0!==p.lines&&(g=p.lines);const b=v?g.length||u?.length||h?"auto":"empty":"edited";return{kind:p.kind,title:m,lines:g,state:b,chart:u,bars:h,image:p.image}}export function emptyHint(e,t){if("survey"===e)return"zh"===t?"敲 survey 跑一次模拟调研,这页会自动填上。":"Run survey and this slide fills itself.";if("numbers"===e)return"zh"===t?"填卡片的「每个用户的 AI 成本」格,或者敲 market 算市场大小和毛利。":'Fill the "AI cost per user" box, or type market to work out market size and margin.';if("ask"===e)return"zh"===t?"写下你想要听众做什么(试用、介绍老师、给反馈……)。":"Write what you want from the audience (try it, introduce a teacher, give feedback…).";const n=r[e];return"zh"===t?`这页跟着你的卡片走 —— 先把卡片里对应的格子填上${n?`(${n})`:""},或者直接在这页打字。`:`This slide follows your card — fill in the matching box${n?` (${n})`:""}, or type on this slide directly.`}const s=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o={night:"--bg:#070b16;--deck:#0c1222;--panel:#121b32;--line:#25335a;--ink:#e8edfb;--muted:#93a0c4;--accent:#5cc8ff;--accent2:#f5c451;",paper:"--bg:#e9e6df;--deck:#fbfaf7;--panel:#f1eee7;--line:#d6d0c4;--ink:#1d2433;--muted:#5d6577;--accent:#1f6feb;--accent2:#c2410c;",bold:"--bg:#04102b;--deck:#0a1f4d;--panel:#11307a;--line:#2a4a9a;--ink:#ffffff;--muted:#b9c6ea;--accent:#ffd400;--accent2:#ff7a59;"};export function deckHtml(e,t,n,i,r=[],a=()=>null){const l=t.slides.map((a,s)=>renderSlide(e,t,s,n,i,r)),c=e.name||("zh"===n?"未命名项目":"Untitled venture"),d=(e,t,n)=>`<div class="row"><span class="lab">${s(e)}</span><span class="track"><span class="fill ${n}" style="width:${(e=>null===e?0:Math.max(0,Math.min(100,e)))(t)}%"></span></span><span class="val">${null===t?"–":`${t}%`}</span></div>`,p=l.map((e,t)=>{const i=`${t+1} / ${l.length}`;if("title"===e.kind)return`<section class="slide title"><div class="big">${s(e.title)}</div>${e.lines.map(e=>`<div class="sub">${s(e)}</div>`).join("")}<div class="foot">${s("zh"===n?"AI4Startup · 创业实验室":"AI4Startup · Venture Lab")}</div></section>`;const r=e.chart?.length?`<div class="chart">${e.chart.map(e=>`<div class="cty"><div class="cname">${s(e.label)} <small>n=${e.n}</small></div>${d("zh"===n?"目标人群会买":"Target groups would buy",e.target,"a")}${d("zh"===n?"普通人会买":"General public would buy",e.general,"b")}${d("zh"===n?"对照产品(几乎没人买)":"Known-flop product",e.control,"c")}</div>`).join("")}</div>`:"",o=e.bars?`<div class="bars"><div class="btitle">${s(e.bars.title)}${e.bars.legend?` <span class="lg"><i class="a"></i>${s(e.bars.legend[0])} <i class="c"></i>${s(e.bars.legend[1])}</span>`:""}</div>${e.bars.rows.map(e=>void 0===e.value2?d(e.label,e.value,"a"):`<div class="pair"><span class="lab">${s(e.label)}</span><span class="two">${d("",e.value,"a")}${d("",e.value2,"c")}</span></div>`).join("")}</div>`:"",p=e.lines.length?`<ul>${e.lines.map(e=>`<li>${s(e)}</li>`).join("")}</ul>`:r||o?"":`<p class="empty">${s(emptyHint(e.kind,n))}</p>`,u=e.image?a(e.image):null;return u?`<section class="slide img"><div class="kicker">${i}</div><div class="cols"><div class="txt"><h1>${s(e.title)}</h1>${r}${o}${p}</div><figure><img src="${s(u)}" alt=""><figcaption>${s("zh"===n?"AI 生成的插图":"AI-generated illustration")}</figcaption></figure></div><div class="foot">${s(c)}</div></section>`:`<section class="slide"><div class="kicker">${i}</div><h1>${s(e.title)}</h1>${r}${o}${p}<div class="foot">${s(c)}</div></section>`}).join("\n");return`<!doctype html>\n<html lang="${"zh"===n?"zh-CN":"en"}"><head><meta charset="utf-8">\n<meta name="viewport" content="width=device-width,initial-scale=1">\n<title>${s(c)} · pitch deck</title>\n<style>\n:root{${o[t.style]}}\n*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);\nfont-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei","Noto Sans CJK SC",sans-serif}\n#stage{position:fixed;inset:0;display:flex;align-items:center;justify-content:center}\n#canvas{width:1600px;height:900px;position:relative;transform-origin:center center}\n.slide{position:absolute;inset:0;background:var(--deck);border:1px solid var(--line);border-radius:18px;padding:90px 110px;display:none;overflow:hidden}\n.slide.on{display:block}\n.kicker{font:600 22px ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--accent);letter-spacing:.08em}\nh1{font-size:68px;line-height:1.1;margin:18px 0 40px;font-weight:750}\nul{margin:0;padding-left:1.1em;font-size:38px;line-height:1.45}li{margin:0 0 18px}li::marker{color:var(--accent)}\n.empty{font-size:30px;color:var(--muted);font-style:italic}\n.title{display:none;flex-direction:column;justify-content:center}.title.on{display:flex}\n.big{font-size:104px;font-weight:800;line-height:1.05;color:var(--ink)}.sub{font-size:40px;color:var(--muted);margin-top:28px;max-width:1250px}\n.foot{position:absolute;left:110px;right:110px;bottom:46px;font-size:20px;color:var(--muted);border-top:1px solid var(--line);padding-top:14px}\n.chart{display:flex;gap:60px;margin:-10px 0 34px}.cty{flex:1;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:22px 26px}\n.cname{font-size:30px;font-weight:700;margin-bottom:12px}.cname small{font-weight:400;color:var(--muted);font-size:20px}\n.row{display:flex;align-items:center;gap:14px;margin:10px 0;font-size:22px}.lab{width:300px;color:var(--muted)}\n.track{flex:1;height:22px;background:var(--line);border-radius:11px;overflow:hidden}.fill{display:block;height:100%}\n.cols{display:flex;gap:56px;align-items:flex-start}.cols .txt{flex:1;min-width:0}.cols ul{font-size:34px}\nfigure{margin:18px 0 0;width:560px;flex:none}figure img{width:560px;height:420px;object-fit:cover;border-radius:14px;border:1px solid var(--line);display:block}\nfigcaption{font-size:16px;color:var(--muted);margin-top:8px;text-align:right}\n.bars{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:18px 26px;margin:-10px 0 30px}\n.btitle{font-size:26px;font-weight:700;margin-bottom:6px}.lg{font-weight:400;font-size:20px;color:var(--muted);margin-left:18px}\n.lg i{display:inline-block;width:14px;height:14px;border-radius:3px;margin:0 6px 0 12px}.lg i.a{background:var(--accent)}.lg i.c{background:var(--accent2)}\n.pair{display:flex;align-items:center;gap:14px}.pair .two{flex:1}.pair .two .row{margin:4px 0}.pair .two .lab{display:none}\n.fill.a{background:var(--accent)}.fill.b{background:var(--muted)}.fill.c{background:var(--accent2)}.val{width:80px;text-align:right;font-family:ui-monospace,Menlo,monospace}\n#hud{position:fixed;right:18px;bottom:12px;font:13px ui-monospace,Menlo,monospace;color:var(--muted);opacity:.75}\n@media print{@page{size:1600px 900px;margin:0}html,body{background:#fff}#stage{position:static;display:block}\n#canvas{transform:none!important;width:auto;height:auto}.slide,.title{position:relative;display:block!important;width:1600px;height:900px;\npage-break-after:always;break-after:page;border-radius:0}.title{display:flex!important}#hud{display:none}}\n</style></head><body>\n<div id="stage"><div id="canvas">\n${p}\n</div></div>\n<div id="hud">← → / space · F ${"zh"===n?"全屏":"full screen"}</div>\n<script>\n(function(){var S=[].slice.call(document.querySelectorAll('.slide')),i=0,c=document.getElementById('canvas');\nfunction fit(){var k=Math.min(innerWidth/1600,innerHeight/900)*0.98;c.style.transform='scale('+k+')';}\nfunction show(n){i=Math.max(0,Math.min(S.length-1,n));S.forEach(function(s,j){s.classList.toggle('on',j===i);});location.hash=String(i+1);}\naddEventListener('resize',fit);\naddEventListener('keydown',function(e){var k=e.key;\nif(k==='ArrowRight'||k==='ArrowDown'||k===' '||k==='PageDown'||k==='Enter'){e.preventDefault();show(i+1);}\nelse if(k==='ArrowLeft'||k==='ArrowUp'||k==='PageUp'||k==='Backspace'){e.preventDefault();show(i-1);}\nelse if(k==='Home'){show(0);}else if(k==='End'){show(S.length-1);}\nelse if(k==='f'||k==='F'){if(!document.fullscreenElement)document.documentElement.requestFullscreen&&document.documentElement.requestFullscreen();else document.exitFullscreen();}});\naddEventListener('click',function(e){show(e.clientX>innerWidth/2?i+1:i-1);});\nfit();show((parseInt(location.hash.slice(1),10)||1)-1);})();\n<\/script></body></html>\n`}export function deckStats(e,t){const n=t.slides.map((n,i)=>renderSlide(e,t,i,"en",null));return{slides:t.slides.length,edited:n.filter(e=>"edited"===e.state).length,empty:n.filter(e=>"empty"===e.state&&"survey"!==e.kind).length,ownChars:t.slides.reduce((e,t)=>e+t.own_chars,0),aiChars:t.slides.reduce((e,t)=>e+t.ai_chars,0)}}
@@ -1,8 +1,10 @@
1
- import{spawnSync as e}from"node:child_process";import{existsSync as s,mkdirSync as t,readFileSync as r,writeFileSync as o}from"node:fs";import{homedir as n}from"node:os";import{join as i,resolve as a}from"node:path";const l=String.raw`import io, json, math, os, sys, time, traceback
1
+ import{spawnSync as e}from"node:child_process";import{existsSync as s,mkdirSync as t,readFileSync as r,writeFileSync as o}from"node:fs";import{homedir as i}from"node:os";import{join as n,resolve as a}from"node:path";const l=String.raw`import io, json, math, os, sys, time, traceback
2
2
  engine = sys.argv[sys.argv.index('--engine') + 1]
3
3
  path = sys.argv[sys.argv.index('--file') + 1]
4
4
  sid = sys.argv[sys.argv.index('--scenario') + 1]
5
5
  seed = int(sys.argv[sys.argv.index('--seed') + 1]) if '--seed' in sys.argv else None
6
+ policy = sys.argv[sys.argv.index('--policy') + 1] if '--policy' in sys.argv else None
7
+ backlash = '--backlash' in sys.argv
6
8
  sys.path.insert(0, engine)
7
9
  os.environ.setdefault('OMP_NUM_THREADS', '1')
8
10
  os.environ.setdefault('MUJOCO_GL', 'disable')
@@ -25,10 +27,17 @@ try:
25
27
  sc = Scenario.load(sid)
26
28
  if seed is not None:
27
29
  sc.seed = seed # another course: same map, different wobble (like the judge's hidden ones)
30
+ if policy: # 96-tier lab: a trained policy file (snap:N / variant:X / mine) walks instead
31
+ from duckkit import resolve_policy
32
+ sc.policies = dict(sc.policies, walk=resolve_policy(policy))
33
+ if backlash:
34
+ sc.backlash = True
28
35
  log = run_file(path, sc)
29
36
  res = score(sc, log)
30
37
  except ControlError as e:
31
38
  sys.stdout = real; emit({'ok': False, 'error': 'control', 'message': str(e)}); sys.exit()
39
+ except FileNotFoundError as e:
40
+ sys.stdout = real; emit({'ok': False, 'error': 'policy', 'message': str(e)}); sys.exit()
32
41
  except Exception as e:
33
42
  sys.stdout = real
34
43
  tb = traceback.extract_tb(sys.exc_info()[2])
@@ -51,4 +60,4 @@ emit({'ok': True, 'pass': bool(res['pass']), 'value': res['value'], 'detail': re
51
60
  'trace': {'samples': pts, 'seconds': sc.seconds, 'fallen_at': log.fallen_at,
52
61
  'walls': [{'pos': list(w['pos'][:2]), 'size': list(w['size'][:2])} for w in sc.walls],
53
62
  'markers': [list(m['pos'][:2]) for m in sc.markers], 'goal': dict(sc.goal)}})
54
- `,d=i(n(),".icoa","duck","trace_run.py");export function runWithTrace(c,m,g,p,f=18e4,u){t(i(n(),".icoa","duck"),{recursive:!0}),s(d)&&r(d,"utf-8")===l||o(d,l);const y=e(c,[d,"--engine",m,"--file",a(g),"--scenario",p,...null!=u?["--seed",String(u)]:[]],{encoding:"utf-8",timeout:f,cwd:m,env:{...process.env,PYTHONDONTWRITEBYTECODE:"1",OMP_NUM_THREADS:"1",MUJOCO_GL:"disable"}}),x=String(y.stdout??"").trim().split("\n").pop()||"";try{return JSON.parse(x)}catch{return{ok:!1,error:"engine",message:String(y.stderr??"").trim().split("\n").slice(-3).join(" ")||`exit ${y.status}`}}}
63
+ `,c=n(i(),".icoa","duck","trace_run.py");export function runWithTrace(d,p,m,g,y=18e4,f,u={}){t(n(i(),".icoa","duck"),{recursive:!0}),s(c)&&r(c,"utf-8")===l||o(c,l);const x=e(d,[c,"--engine",p,"--file",a(m),"--scenario",g,...null!=f?["--seed",String(f)]:[],...u.policy?["--policy",u.policy]:[],...u.backlash?["--backlash"]:[]],{encoding:"utf-8",timeout:y,cwd:p,env:{...process.env,PYTHONDONTWRITEBYTECODE:"1",OMP_NUM_THREADS:"1",MUJOCO_GL:"disable",...u.dir?{ICOA_DUCK_LAB:u.dir}:{}}}),k=String(x.stdout??"").trim().split("\n").pop()||"";try{return JSON.parse(k)}catch{return{ok:!1,error:"engine",message:String(x.stderr??"").trim().split("\n").slice(-3).join(" ")||`exit ${x.status}`}}}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as r}from"node:fs";import{homedir as o}from"node:os";import{dirname as s,join as c}from"node:path";import chalk from"chalk";import{getConfig as i}from"./config.js";export function uiLang(){const e=(i().language||"en").toLowerCase();return e.startsWith("zh")?"zh":e.startsWith("th")?"th":"en"}export function tx(e,t=uiLang()){return"string"==typeof e?e:("zh"===t?e.zh:"th"===t?e.th:void 0)??e.en}export function asciiOnly(){if("1"===process.env.ICOA_ASCII)return!0;const e=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"";return""!==e&&!/utf-?8/i.test(e)}export function dw(e){let t=0;for(const n of e.replace(u,"")){const e=n.codePointAt(0)??0;3633===e||e>=3636&&e<=3642||e>=3655&&e<=3662||(t+=e>65535||e>=11904&&e<=42191||e>=44032&&e<=55203||e>=63744&&e<=64255?2:1)}return t}function a(e,t){const n=dw(e);return n>=t?`${e} `:e+" ".repeat(t-n)}export function wrapText(e,t){const n=[];for(const r of e.split("\n")){const e=r.match(/[⺀-꓏가-힣豈-﫿]|\S+\s*|\s+/g)??[];let o="";for(const r of e){const e=/^[,.;:!?)\]}、。,;:!?)】」』…]/.test(r);o&&!e&&dw(o)+dw(r.trimEnd())>t&&(n.push(o.trimEnd()),o=""),o+=r}n.push(o.trimEnd())}return n}const u=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function l(){return process.env.ICOA_SEEN_FILE||c(o(),".icoa","seen-surfaces.json")}function p(){try{const e=JSON.parse(n(l(),"utf8"));return e&&"object"==typeof e?e:{}}catch{return{}}}export function seenBefore(e){return"1"!==process.env.ICOA_FRESH&&e in p()}export function markSeen(n){if("1"!==process.env.ICOA_FRESH)try{const o=l(),c=p();if(c[n])return;c[n]=(new Date).toISOString(),e(s(o))||t(s(o),{recursive:!0}),r(o,`${JSON.stringify(c,null,1)}\n`)}catch{}}const f={readMe:{en:"read me first",zh:"先读这个",th:"อ่านก่อน"},next:{en:"next, type:",zh:"下一步敲:",th:"ขั้นต่อไป พิมพ์:"},help:{en:"help = these steps",zh:"help = 这些步骤",th:"help = ขั้นตอนนี้"},guide:{en:"guide = full sheet",zh:"guide = 完整说明",th:"guide = คู่มือเต็ม"},leave:{en:"leave",zh:"离开",th:"ออก"},done:{en:"all steps done — explore, or",zh:"步骤都做完了 —— 自由探索,或",th:"ทำครบแล้ว — ลองเล่น หรือ"},optional:{en:"optional",zh:"可选",th:"ไม่บังคับ"}};export function currentNext(e){if(e.next)return e.next();for(const t of e.steps)if(!(t.optional||t.done&&t.done()))return t.verb;return null}export function renderPanel(e,t,n){const r=n?.lang??uiLang(),o=n?.ascii??asciiOnly(),s=e=>tx(e,r),c=o?"":"📖 ",i=o?"":"🧭 ",u=o?">":"▸",l=o?"<-":"↩",p=currentNext(e),h=e.helpWord??"help",$=e.leave??{verb:"back",what:f.leave},d=`${c}${s(e.title)}`;if("compact"===t){const t=p?`${chalk.gray(` ${u} ${s(f.next)} `)}${chalk.bold.green(p)}`:`${chalk.gray(` ${u} ${s(f.done)} `)}${chalk.cyan($.verb)}`,n=s(f.help).replace(/^help/,h),r=` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${n}${e.guide?` · ${s(f.guide)}`:""}`)}`;if(dw(r)<=80)return[r];const o=` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${n}`)}`;return[dw(o)<=80?o:` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${h}`)}`]}const g=[];g.push(` ${chalk.bold.white(d)}${chalk.gray(` — ${s(f.readMe)}`)}`);for(const t of wrapText(s(e.what),76))g.push(chalk.gray(` ${t}`));const x=Math.min(18,Math.max(6,...e.steps.map(e=>dw(e.verb))))+2;e.steps.forEach((e,t)=>{const n=null!==p&&e.verb===p,r=!n&&!0===e.done?.(),c=n?chalk.bold.green(o?"> ":"▸ "):r?chalk.green(o?"[x]":"✅"):e.optional?chalk.gray(o?" - ":" ·"):chalk.gray(o?"[ ]":"○ "),i=n?chalk.bold.green(a(e.verb,x)):chalk.cyan(a(e.verb,x)),u=wrapText(s(e.what)+(e.optional?chalk.gray(` (${s(f.optional)})`):""),68-x);g.push(` ${chalk.white(String(t+1).padStart(2))} ${c} ${i}${chalk.gray(u[0]??"")}`);for(const e of u.slice(1))g.push(`${" ".repeat(10+x)}${chalk.gray(e)}`)});for(const t of e.notes??[])for(const e of wrapText(s(t),74))g.push(chalk.gray(` ${e}`));const y=p?` ${chalk.bold.green(`${u} ${s(f.next)} ${p}`)}`:` ${chalk.gray(`${u} ${s(f.done)} `)}${chalk.cyan($.verb)}`;return g.push(`${y}${chalk.gray(` ${l} ${$.verb} · ${i}${h}${e.guide?" · guide":""}`)}`),g}export function footerLine(e,t){const n=t?.lang??uiLang(),r=t?.ascii??asciiOnly(),o=e=>tx(e,n),s=r?">":"▸",c=r?"<-":"↩",i=r?"":"🧭 ",a=currentNext(e),u=e.leave??{verb:"back",what:f.leave};return` ${a?chalk.bold.green(`${s} ${o(f.next)} ${a}`):`${chalk.gray(`${s} ${o(f.done)} `)}${chalk.cyan(u.verb)}`}${chalk.gray(` ${c} ${u.verb} · ${i}${e.helpWord??"help"}`)}`}const h=[];export function currentSurface(){return h.length?h[h.length-1]:null}export function enterPanel(e,t){const n=currentSurface();n&&n.id===e.id&&h.pop(),h.push(e);const r=t?.mode??(seenBefore(e.id)?"compact":"full");if(!t?.quiet){console.log();for(const t of renderPanel(e,r))console.log(t);console.log()}return markSeen(e.id),r}export function leavePanel(e){if(!e)return void h.pop();const t=h.map(e=>e.id).lastIndexOf(e);t>=0&&h.splice(t,1)}export function printHelp(){const e=currentSurface();if(!e)return!1;console.log();for(const t of renderPanel(e,"full"))console.log(t);return console.log(),!0}export function printGuide(){const e=currentSurface();return!!e&&(e.guide?(console.log(),e.guide(),console.log(),!0):printHelp())}const $=new Set(["help","/help","?","/?","h","帮助","帮助我","ช่วย"]),d=new Set(["guide","/guide","howto","how","说明","怎么玩","คู่มือ"]);export function isHelpWord(e){return $.has(e.trim().toLowerCase())}export function isGuideWord(e){return d.has(e.trim().toLowerCase())}
1
+ import{existsSync as e,mkdirSync as t,readFileSync as n,writeFileSync as r}from"node:fs";import{homedir as o}from"node:os";import{dirname as s,join as c}from"node:path";import chalk from"chalk";import{getConfig as i}from"./config.js";export function uiLang(){const e=(i().language||"en").toLowerCase();return e.startsWith("zh")?"zh":e.startsWith("th")?"th":"en"}export function tx(e,t=uiLang()){return"string"==typeof e?e:("zh"===t?e.zh:"th"===t?e.th:void 0)??e.en}export function asciiOnly(){if("1"===process.env.ICOA_ASCII)return!0;const e=process.env.LC_ALL||process.env.LC_CTYPE||process.env.LANG||"";return""!==e&&!/utf-?8/i.test(e)}export function dw(e){let t=0;for(const n of e.replace(u,"")){const e=n.codePointAt(0)??0;3633===e||e>=3636&&e<=3642||e>=3655&&e<=3662||(t+=e>65535||e>=11904&&e<=42191||e>=44032&&e<=55203||e>=63744&&e<=64255?2:1)}return t}function a(e,t){const n=dw(e);return n>=t?`${e} `:e+" ".repeat(t-n)}export function wrapText(e,t){const n=[];for(const r of e.split("\n")){const e=r.match(/[⺀-꓏가-힣豈-﫿]|[^\s⺀-꓏가-힣豈-﫿]+\s*|\s+/g)??[];let o="";for(const r of e){const e=/^[,.;:!?)\]}、。,;:!?)】」』…]/.test(r);o&&!e&&dw(o)+dw(r.trimEnd())>t&&(n.push(o.trimEnd()),o=""),o+=r}n.push(o.trimEnd())}return n}const u=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");function l(){return process.env.ICOA_SEEN_FILE||c(o(),".icoa","seen-surfaces.json")}function p(){try{const e=JSON.parse(n(l(),"utf8"));return e&&"object"==typeof e?e:{}}catch{return{}}}export function seenBefore(e){return"1"!==process.env.ICOA_FRESH&&e in p()}export function markSeen(n){if("1"!==process.env.ICOA_FRESH)try{const o=l(),c=p();if(c[n])return;c[n]=(new Date).toISOString(),e(s(o))||t(s(o),{recursive:!0}),r(o,`${JSON.stringify(c,null,1)}\n`)}catch{}}const f={readMe:{en:"read me first",zh:"先读这个",th:"อ่านก่อน"},next:{en:"next, type:",zh:"下一步敲:",th:"ขั้นต่อไป พิมพ์:"},help:{en:"help = these steps",zh:"help = 这些步骤",th:"help = ขั้นตอนนี้"},guide:{en:"guide = full sheet",zh:"guide = 完整说明",th:"guide = คู่มือเต็ม"},leave:{en:"leave",zh:"离开",th:"ออก"},done:{en:"all steps done — explore, or",zh:"步骤都做完了 —— 自由探索,或",th:"ทำครบแล้ว — ลองเล่น หรือ"},optional:{en:"optional",zh:"可选",th:"ไม่บังคับ"}};export function currentNext(e){if(e.next)return e.next();for(const t of e.steps)if(!(t.optional||t.done&&t.done()))return t.verb;return null}export function renderPanel(e,t,n){const r=n?.lang??uiLang(),o=n?.ascii??asciiOnly(),s=e=>tx(e,r),c=o?"":"📖 ",i=o?"":"🧭 ",u=o?">":"▸",l=o?"<-":"↩",p=currentNext(e),h=e.helpWord??"help",$=e.leave??{verb:"back",what:f.leave},d=`${c}${s(e.title)}`;if("compact"===t){const t=p?`${chalk.gray(` ${u} ${s(f.next)} `)}${chalk.bold.green(p)}`:`${chalk.gray(` ${u} ${s(f.done)} `)}${chalk.cyan($.verb)}`,n=s(f.help).replace(/^help/,h),r=` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${n}${e.guide?` · ${s(f.guide)}`:""}`)}`;if(dw(r)<=80)return[r];const o=` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${n}`)}`;return[dw(o)<=80?o:` ${chalk.bold.white(d)}${t}${chalk.gray(` · ${i}${h}`)}`]}const g=[];g.push(` ${chalk.bold.white(d)}${chalk.gray(` — ${s(f.readMe)}`)}`);for(const t of wrapText(s(e.what),76))g.push(chalk.gray(` ${t}`));const x=Math.min(18,Math.max(6,...e.steps.map(e=>dw(e.verb))))+2;e.steps.forEach((e,t)=>{const n=null!==p&&e.verb===p,r=!n&&!0===e.done?.(),c=n?chalk.bold.green(o?"> ":"▸ "):r?chalk.green(o?"[x]":"✅"):e.optional?chalk.gray(o?" - ":" ·"):chalk.gray(o?"[ ]":"○ "),i=n?chalk.bold.green(a(e.verb,x)):chalk.cyan(a(e.verb,x)),u=wrapText(s(e.what)+(e.optional?chalk.gray(` (${s(f.optional)})`):""),68-x);g.push(` ${chalk.white(String(t+1).padStart(2))} ${c} ${i}${chalk.gray(u[0]??"")}`);for(const e of u.slice(1))g.push(`${" ".repeat(10+x)}${chalk.gray(e)}`)});for(const t of e.notes??[])for(const e of wrapText(s(t),74))g.push(chalk.gray(` ${e}`));const y=p?` ${chalk.bold.green(`${u} ${s(f.next)} ${p}`)}`:` ${chalk.gray(`${u} ${s(f.done)} `)}${chalk.cyan($.verb)}`;return g.push(`${y}${chalk.gray(` ${l} ${$.verb} · ${i}${h}${e.guide?" · guide":""}`)}`),g}export function footerLine(e,t){const n=t?.lang??uiLang(),r=t?.ascii??asciiOnly(),o=e=>tx(e,n),s=r?">":"▸",c=r?"<-":"↩",i=r?"":"🧭 ",a=currentNext(e),u=e.leave??{verb:"back",what:f.leave};return` ${a?chalk.bold.green(`${s} ${o(f.next)} ${a}`):`${chalk.gray(`${s} ${o(f.done)} `)}${chalk.cyan(u.verb)}`}${chalk.gray(` ${c} ${u.verb} · ${i}${e.helpWord??"help"}`)}`}const h=[];export function currentSurface(){return h.length?h[h.length-1]:null}export function enterPanel(e,t){const n=currentSurface();n&&n.id===e.id&&h.pop(),h.push(e);const r=t?.mode??(seenBefore(e.id)?"compact":"full");if(!t?.quiet){console.log();for(const t of renderPanel(e,r))console.log(t);console.log()}return markSeen(e.id),r}export function leavePanel(e){if(!e)return void h.pop();const t=h.map(e=>e.id).lastIndexOf(e);t>=0&&h.splice(t,1)}export function printHelp(){const e=currentSurface();if(!e)return!1;console.log();for(const t of renderPanel(e,"full"))console.log(t);return console.log(),!0}export function printGuide(){const e=currentSurface();return!!e&&(e.guide?(console.log(),e.guide(),console.log(),!0):printHelp())}const $=new Set(["help","/help","?","/?","h","帮助","帮助我","ช่วย"]),d=new Set(["guide","/guide","howto","how","说明","怎么玩","คู่มือ"]);export function isHelpWord(e){return $.has(e.trim().toLowerCase())}export function isGuideWord(e){return d.has(e.trim().toLowerCase())}
@@ -0,0 +1 @@
1
+ import{spawnSync as o}from"node:child_process";import{existsSync as r,mkdtempSync as e,readFileSync as t,rmSync as n,statSync as s}from"node:fs";import{tmpdir as i}from"node:os";import{join as c}from"node:path";import{pathToFileURL as f}from"node:url";const a=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Chromium.app/Contents/MacOS/Chromium","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"],p=["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge","brave-browser"];export function findBrowser(){if(process.env.ICOA_NO_PDF)return null;if("darwin"===process.platform)return a.find(o=>r(o))??null;if("linux"===process.platform||function(){try{return/microsoft/i.test(t("/proc/version","utf8"))}catch{return!1}}())for(const r of p){const e=o("sh",["-c",`command -v ${r}`],{encoding:"utf8"}),t=(e.stdout||"").trim();if(0===e.status&&t)return t}return null}export function htmlToPdf(t,a,p=9e4){const m=findBrowser();if(!m)return{ok:!1,reason:"no-browser"};const u=e(c(i(),"icoa-pdf-"));try{n(a,{force:!0}),o(m,["--headless=new","--disable-gpu","--no-first-run","--no-default-browser-check","--no-pdf-header-footer",`--user-data-dir=${u}`,`--print-to-pdf=${a}`,f(t).href],{timeout:p,stdio:"ignore"});const e=r(a)&&s(a).size>1e4;return e?{ok:e,browser:m}:{ok:!1,browser:m,reason:"failed"}}catch{return{ok:!1,browser:m,reason:"failed"}}finally{try{n(u,{recursive:!0,force:!0})}catch{}}}
@@ -1 +1 @@
1
- import chalk from"chalk";import{execSync as o}from"node:child_process";import{existsSync as e,mkdirSync as n,readFileSync as r,rmSync as t,writeFileSync as i}from"node:fs";import{homedir as s}from"node:os";import{posix as c,win32 as a}from"node:path";import{icoaStandalonePython as u,REQUIRED_PY as p}from"./aienv.js";import{pipInstall as m,planPipSources as l}from"./pip-index.js";import{probePython as d,provisionPython312 as y,resetPythonProbe as g}from"./python-setup.js";const h=`${p.major}.${p.minor}`;export const MUJOCO_STANDARD="3.16.0";export const MUJOCO_PACKAGES=[{name:"numpy",module:"numpy",spec:"numpy>=1.26",role:"vectors"},{name:"mujoco",module:"mujoco",spec:"mujoco==3.16.0",role:"physics + rendering",pinned:"3.16.0"},{name:"onnxruntime",module:"onnxruntime",spec:"onnxruntime>=1.18",role:"runs the walking policy"}];export function mujocoPaths(o,e=process.platform){const n="win32"===e?a:c,r=n.join(o,".icoa","mujoco");if("win32"===e){const o=n.join(r,"Scripts");return{root:r,binDir:o,python:n.join(o,"python.exe"),marker:n.join(r,"icoa-mujoco.json")}}const t=n.join(r,"bin");return{root:r,binDir:t,python:n.join(t,"python"),marker:n.join(r,"icoa-mujoco.json")}}let f;export function probeMujoco(n=!1){if(f&&!n)return f;const r=mujocoPaths(s()),t={ok:!1,venv:e(r.python),python:r.python,versions:{},missing:[]};if(!t.venv)return t.missing=MUJOCO_PACKAGES.map(o=>o.module),f=t,t;const i=MUJOCO_PACKAGES.map(o=>o.module),c=["import json, importlib","out = {}",`for m in ${JSON.stringify(i)}:`," try:",' mod = importlib.import_module(m); out[m] = str(getattr(mod, "__version__", "?"))'," except Exception:"," out[m] = None","print(json.dumps(out))",""].join("\n");try{const e=o(`"${r.python}" -`,{input:c,encoding:"utf-8",stdio:["pipe","pipe","ignore"],timeout:2e4}).trim(),n=JSON.parse(e.split("\n").pop()??"{}");for(const o of i)n[o]?t.versions[o]=n[o]:t.missing.push(o)}catch{t.missing=i}return t.ok=0===t.missing.length,f=t,t}export function mujocoVersionsLine(o){return MUJOCO_PACKAGES.filter(e=>o.versions[e.module]).map(e=>`${e.name} ${o.versions[e.module]}`).join(" · ")}export function mujocoDoorLine(o,e=!1,n){const r=n??probeMujoco(),t=e?"":"🦆 ";if(r.ok){const e=r.versions.mujoco&&"3.16.0"!==r.versions.mujoco;return chalk.gray(` ${t}${mujocoVersionsLine(r)} · `)+chalk.gray(o?"本机可跑仿真":"sim runs locally")+(e?chalk.yellow(o?" · 判分机是 mujoco 3.16.0:":" · the judge runs mujoco 3.16.0: ")+chalk.bold.green("mujoco setup")+chalk.yellow(o?" 对齐":" to match"):"")}return r.venv?chalk.gray(` ${t}`+(o?`缺 ${r.missing.join(", ")} · `:`missing ${r.missing.join(", ")} · `))+chalk.bold.green("mujoco setup")+chalk.gray(o?" 补齐":" finishes the install"):chalk.gray(` ${t}${o?"没有 MuJoCo — 读卡答题不需要它,回放可由判分机送回 · ":"No MuJoCo — reading and answering cards works without it, replays can come from the judge · "}`)+chalk.bold.green("mujoco setup")+chalk.gray(o?" 让 run 在本机出图(~45 MB,免 sudo)":" to run the sim here (~45 MB, no sudo)")}function v(e){try{return o(`"${e}" -m pip --version`,{stdio:"ignore",timeout:15e3}),!0}catch{return!1}}function j(o){const e=(o?.stderr?.toString()??"").split("\n").map(o=>o.trim()).filter(Boolean);return e.length?e[e.length-1].slice(0,120):""}export async function provisionMujoco(r={}){const a=o=>{r.quiet||console.log(o)},p=s(),f=mujocoPaths(p);let $=d(!0,{hostOnly:!0});if(!$.ok){if(a(chalk.gray(` No Python ${h} here — installing one first (stage 0, no sudo) …`)),!await y({quiet:r.quiet}))return a(chalk.red(` ✗ Could not get a Python ${h}`)+chalk.gray(" — try ")+chalk.bold.cyan("python setup")),!1;if(g(),$=d(!0,{hostOnly:!0}),!$.ok||!$.cmd)return!1}const x=$.cmd;a(chalk.green(` ✓ Python ${$.version}`)+chalk.gray(` · ${x}`));const O=u(p),b="win32"!==process.platform&&x.replace(/"/g,"")!==O,w=async()=>{if(a(chalk.gray(" This Python 3.12 has no venv/pip (a system build) — switching to the ICOA one …")),!e(O)&&!await y({quiet:r.quiet}))return!1;try{t(f.root,{recursive:!0,force:!0}),o(`"${O}" -m venv "${f.root}"`,{stdio:["ignore","ignore","pipe"]})}catch{return!1}return!!v(f.python)&&(a(chalk.green(" ✓ venv recreated")+chalk.gray(` · ${O}`)),!0)};let C=!1;if(r.force&&e(f.root)){a(chalk.gray(" --force: recreating the venv …")),C=!0;try{o(`${x.includes(" ")?x:`"${x}"`} -m venv --clear "${f.root}"`,{stdio:["ignore","ignore","pipe"]})}catch{}}if(e(f.python))a(C?chalk.green(" ✓ venv recreated"):chalk.green(" ✓ venv exists")+chalk.gray(" — reusing"));else{a(chalk.gray(` Creating venv → ${f.root}`));try{n(c.join(p,".icoa"),{recursive:!0}),o(`${x.includes(" ")?x:`"${x}"`} -m venv "${f.root}"`,{stdio:["ignore","ignore","pipe"]})}catch(o){if(!b||!await w())return a(chalk.red(" ✗ Could not create the venv")+chalk.gray(j(o)?` (${j(o)})`:"")),"linux"===process.platform&&a(chalk.gray(" A distro 3.12 without venv? ")+chalk.bold.cyan("python setup")+chalk.gray(" installs one that has venv and pip built in.")),!1}v(f.python)&&a(chalk.green(" ✓ venv created"))}if(!v(f.python)){a(chalk.gray(" Bootstrapping pip …"));try{o(`"${f.python}" -m ensurepip --upgrade`,{stdio:["ignore","ignore","pipe"]})}catch{}if(!(v(f.python)||b&&await w()))return a(chalk.red(" ✗ The venv has no pip and it could not be bootstrapped.")),a(chalk.gray(" Fix: ")+chalk.bold.cyan("python setup")+chalk.gray(" then ")+chalk.bold.cyan("mujoco setup --force")),!1}const M=probeMujoco(!0);let P=0;const A=o=>!(!M.versions[o.module]||o.pinned&&M.versions[o.module]!==o.pinned),J=MUJOCO_PACKAGES.filter(o=>!A(o)).length?await l(f.python):void 0;J&&a(chalk.gray(` ${J.line}`));for(const o of MUJOCO_PACKAGES)if(A(o))a(chalk.green(` ✓ ${o.name} ${M.versions[o.module]}`)+chalk.gray(" (already installed)"));else{M.versions[o.module]?a(chalk.cyan(` ↻ ${o.name} ${M.versions[o.module]} → ${o.pinned}`)+chalk.gray(" — the judge's version; everyone runs the same one")):a(chalk.cyan(` ⬇ ${o.name}`)+chalk.gray(` ${o.spec} — ${o.role}`));try{m(f.python,o.spec,J,{extra:"-q --only-binary=:all:",onRetry:e=>a(chalk.yellow(` ~ ${o.name}: that source failed — trying ${e.host} …`))})}catch(e){a(chalk.red(` ✗ ${o.name} failed to install`)+chalk.gray(j(e)?` (${j(e)})`:"")),P++}}const _=probeMujoco(!0);for(const o of MUJOCO_PACKAGES)A(o)||(_.versions[o.module]?a(chalk.green(` ✓ ${o.name} ${_.versions[o.module]} installed`)):P||a(chalk.red(` ✗ ${o.name} installed but does not import`)));if(!_.ok)return!1;const k={version:1,hostPython:(function(e){try{return o(`${e} --version`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}}(x.includes(" ")?x:`"${x}"`)??$.version??h).replace(/^Python\s+/i,""),venvPython:f.python,packages:MUJOCO_PACKAGES.map(o=>o.name),created:(new Date).toISOString()};try{i(f.marker,`${JSON.stringify(k,null,2)}\n`)}catch{}return!0}export function glCandidates(o=process.platform){return"darwin"===o?["cgl","glfw"]:"linux"===o?["egl","glfw","osmesa"]:["glfw"]}function $(o=s()){return c.join(o,".icoa","duck","gl.json")}export function cachedGl(){try{const o=JSON.parse(r($(),"utf-8"));return 1===o.version?o.backend??null:void 0}catch{return}}export function probeRender(e){for(const r of glCandidates()){const t={...process.env,MUJOCO_GL:r};"osmesa"===r&&(t.PYOPENGL_PLATFORM="osmesa");try{const s=o(`"${e}" -c "import sys, mujoco; r = mujoco.Renderer(mujoco.MjModel.from_xml_string('<mujoco/>'), 8, 8); r.render(); print(sys.executable)"`,{env:t,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e4}).trim().split("\n").pop();try{n(c.dirname($()),{recursive:!0}),i($(),JSON.stringify({version:1,python:s||e,backend:r}))}catch{}return r}catch{}}try{t($(),{force:!0})}catch{}return null}export function renderLines(o,e=process.platform){if(o)return[chalk.green(` ✓ Pictures: MuJoCo can draw here (${o})`)+chalk.gray(" — the duck sandbox shows video")];const n=[chalk.yellow(" ⚠ Pictures: MuJoCo cannot draw on this machine")+chalk.gray(" — the sim still runs, the duck sandbox shows text only.")];return"linux"===e&&n.push(chalk.gray(" Fix: ")+chalk.cyan("sudo apt install -y libosmesa6")+chalk.gray(" then ")+chalk.bold.cyan("mujoco setup")+chalk.gray(" again.")),n}
1
+ import chalk from"chalk";import{execSync as o}from"node:child_process";import{existsSync as e,mkdirSync as n,readFileSync as t,rmSync as r,writeFileSync as i}from"node:fs";import{homedir as s}from"node:os";import{posix as a,win32 as c}from"node:path";import{icoaStandalonePython as u,REQUIRED_PY as p}from"./aienv.js";import{pipInstall as m,planPipSources as l}from"./pip-index.js";import{probePython as d,provisionPython312 as y,resetPythonProbe as g}from"./python-setup.js";import{installFromWheelhouse as h}from"./wheelhouse.js";const f=`${p.major}.${p.minor}`;export const MUJOCO_STANDARD="3.10.0";export const ONNXRUNTIME_STANDARD="1.23.2";export const NUMPY_STANDARD="2.5.2";export const MUJOCO_PACKAGES=[{name:"numpy",module:"numpy",spec:"numpy==2.5.2",role:"vectors",pinned:"2.5.2"},{name:"mujoco",module:"mujoco",spec:"mujoco==3.10.0",role:"physics + rendering",pinned:"3.10.0"},{name:"onnxruntime",module:"onnxruntime",spec:"onnxruntime==1.23.2",role:"runs the walking policy",pinned:"1.23.2"}];export function mujocoPaths(o,e=process.platform){const n="win32"===e?c:a,t=n.join(o,".icoa","mujoco");if("win32"===e){const o=n.join(t,"Scripts");return{root:t,binDir:o,python:n.join(o,"python.exe"),marker:n.join(t,"icoa-mujoco.json")}}const r=n.join(t,"bin");return{root:t,binDir:r,python:n.join(r,"python"),marker:n.join(t,"icoa-mujoco.json")}}let v;export function probeMujoco(n=!1){if(v&&!n)return v;const t=mujocoPaths(s()),r={ok:!1,venv:e(t.python),python:t.python,versions:{},missing:[]};if(!r.venv)return r.missing=MUJOCO_PACKAGES.map(o=>o.module),v=r,r;const i=MUJOCO_PACKAGES.map(o=>o.module),a=["import json, importlib","out = {}",`for m in ${JSON.stringify(i)}:`," try:",' mod = importlib.import_module(m); out[m] = str(getattr(mod, "__version__", "?"))'," except Exception:"," out[m] = None","print(json.dumps(out))",""].join("\n");try{const e=o(`"${t.python}" -`,{input:a,encoding:"utf-8",stdio:["pipe","pipe","ignore"],timeout:2e4}).trim(),n=JSON.parse(e.split("\n").pop()??"{}");for(const o of i)n[o]?r.versions[o]=n[o]:r.missing.push(o)}catch{r.missing=i}return r.ok=0===r.missing.length,v=r,r}export function mujocoVersionsLine(o){return MUJOCO_PACKAGES.filter(e=>o.versions[e.module]).map(e=>`${e.name} ${o.versions[e.module]}`).join(" · ")}export function mujocoDoorLine(o,e=!1,n){const t=n??probeMujoco(),r=e?"":"🦆 ";if(t.ok){const e=MUJOCO_PACKAGES.some(o=>o.pinned&&t.versions[o.module]&&t.versions[o.module]!==o.pinned);return chalk.gray(` ${r}${mujocoVersionsLine(t)} · `)+chalk.gray(o?"本机可跑仿真":"sim runs locally")+(e?chalk.yellow(o?" · 判分机是 mujoco 3.10.0:":" · the judge runs mujoco 3.10.0: ")+chalk.bold.green("mujoco setup")+chalk.yellow(o?" 对齐":" to match"):"")}return t.venv?chalk.gray(` ${r}`+(o?`缺 ${t.missing.join(", ")} · `:`missing ${t.missing.join(", ")} · `))+chalk.bold.green("mujoco setup")+chalk.gray(o?" 补齐":" finishes the install"):chalk.gray(` ${r}${o?"没有 MuJoCo — 读卡答题不需要它,回放可由判分机送回 · ":"No MuJoCo — reading and answering cards works without it, replays can come from the judge · "}`)+chalk.bold.green("mujoco setup")+chalk.gray(o?" 让 run 在本机出图(~45 MB,免 sudo)":" to run the sim here (~45 MB, no sudo)")}function j(e){try{return o(`"${e}" -m pip --version`,{stdio:"ignore",timeout:15e3}),!0}catch{return!1}}function $(o){const e=(o?.stderr?.toString()??"").split("\n").map(o=>o.trim()).filter(Boolean);return e.length?e[e.length-1].slice(0,120):""}export async function provisionMujoco(t={}){const c=o=>{t.quiet||console.log(o)},p=s(),v=mujocoPaths(p);let O=d(!0,{hostOnly:!0});if(!O.ok){if(c(chalk.gray(` No Python ${f} here — installing one first (stage 0, no sudo) …`)),!await y({quiet:t.quiet}))return c(chalk.red(` ✗ Could not get a Python ${f}`)+chalk.gray(" — try ")+chalk.bold.cyan("python setup")),!1;if(g(),O=d(!0,{hostOnly:!0}),!O.ok||!O.cmd)return!1}const x=O.cmd;c(chalk.green(` ✓ Python ${O.version}`)+chalk.gray(` · ${x}`));const C=u(p),b="win32"!==process.platform&&x.replace(/"/g,"")!==C,w=async()=>{if(c(chalk.gray(" This Python 3.12 has no venv/pip (a system build) — switching to the ICOA one …")),!e(C)&&!await y({quiet:t.quiet}))return!1;try{r(v.root,{recursive:!0,force:!0}),o(`"${C}" -m venv "${v.root}"`,{stdio:["ignore","ignore","pipe"]})}catch{return!1}return!!j(v.python)&&(c(chalk.green(" ✓ venv recreated")+chalk.gray(` · ${C}`)),!0)};let A=!1;if(t.force&&e(v.root)){c(chalk.gray(" --force: recreating the venv …")),A=!0;try{o(`${x.includes(" ")?x:`"${x}"`} -m venv --clear "${v.root}"`,{stdio:["ignore","ignore","pipe"]})}catch{}}if(e(v.python))c(A?chalk.green(" ✓ venv recreated"):chalk.green(" ✓ venv exists")+chalk.gray(" — reusing"));else{c(chalk.gray(` Creating venv → ${v.root}`));try{n(a.join(p,".icoa"),{recursive:!0}),o(`${x.includes(" ")?x:`"${x}"`} -m venv "${v.root}"`,{stdio:["ignore","ignore","pipe"]})}catch(o){if(!b||!await w())return c(chalk.red(" ✗ Could not create the venv")+chalk.gray($(o)?` (${$(o)})`:"")),"linux"===process.platform&&c(chalk.gray(" A distro 3.12 without venv? ")+chalk.bold.cyan("python setup")+chalk.gray(" installs one that has venv and pip built in.")),!1}j(v.python)&&c(chalk.green(" ✓ venv created"))}if(!j(v.python)){c(chalk.gray(" Bootstrapping pip …"));try{o(`"${v.python}" -m ensurepip --upgrade`,{stdio:["ignore","ignore","pipe"]})}catch{}if(!(j(v.python)||b&&await w()))return c(chalk.red(" ✗ The venv has no pip and it could not be bootstrapped.")),c(chalk.gray(" Fix: ")+chalk.bold.cyan("python setup")+chalk.gray(" then ")+chalk.bold.cyan("mujoco setup --force")),!1}const M=probeMujoco(!0);let P=0;const _=o=>!(!M.versions[o.module]||o.pinned&&M.versions[o.module]!==o.pinned),S=MUJOCO_PACKAGES.filter(o=>!_(o)),J=S.length>0&&await h(v.python,{groups:["mujoco"],pins:Object.fromEntries(MUJOCO_PACKAGES.map(o=>[o.name,o.pinned])),say:c}),k=S.length&&!J?await l(v.python):void 0;k&&c(chalk.gray(` ${k.line}`));for(const o of J?[]:MUJOCO_PACKAGES)if(_(o))c(chalk.green(` ✓ ${o.name} ${M.versions[o.module]}`)+chalk.gray(" (already installed)"));else{M.versions[o.module]?c(chalk.cyan(` ↻ ${o.name} ${M.versions[o.module]} → ${o.pinned}`)+chalk.gray(" — the judge's version; everyone runs the same one")):c(chalk.cyan(` ⬇ ${o.name}`)+chalk.gray(` ${o.spec} — ${o.role}`));try{m(v.python,o.spec,k,{extra:"-q --only-binary=:all:",onRetry:e=>c(chalk.yellow(` ~ ${o.name}: that source failed — trying ${e.host} …`))})}catch(e){c(chalk.red(` ✗ ${o.name} failed to install`)+chalk.gray($(e)?` (${$(e)})`:"")),P++}}const N=probeMujoco(!0);for(const o of MUJOCO_PACKAGES)_(o)||(N.versions[o.module]?c(chalk.green(` ✓ ${o.name} ${N.versions[o.module]} installed`)):P||c(chalk.red(` ✗ ${o.name} installed but does not import`)));if(!N.ok)return!1;const E={version:1,hostPython:(function(e){try{return o(`${e} --version`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}).trim()}catch{return null}}(x.includes(" ")?x:`"${x}"`)??O.version??f).replace(/^Python\s+/i,""),venvPython:v.python,packages:MUJOCO_PACKAGES.map(o=>o.name),created:(new Date).toISOString()};try{i(v.marker,`${JSON.stringify(E,null,2)}\n`)}catch{}return!0}export function glCandidates(o=process.platform){return"darwin"===o?["cgl","glfw"]:"linux"===o?["egl","glfw","osmesa"]:["glfw"]}function O(o=s()){return a.join(o,".icoa","duck","gl.json")}export function cachedGl(){try{const o=JSON.parse(t(O(),"utf-8"));return 1===o.version?o.backend??null:void 0}catch{return}}export function probeRender(e){for(const t of glCandidates()){const r={...process.env,MUJOCO_GL:t};"osmesa"===t&&(r.PYOPENGL_PLATFORM="osmesa");try{const s=o(`"${e}" -c "import sys, mujoco; r = mujoco.Renderer(mujoco.MjModel.from_xml_string('<mujoco/>'), 8, 8); r.render(); print(sys.executable)"`,{env:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e4}).trim().split("\n").pop();try{n(a.dirname(O()),{recursive:!0}),i(O(),JSON.stringify({version:1,python:s||e,backend:t}))}catch{}return t}catch{}}try{r(O(),{force:!0})}catch{}return null}export function renderLines(o,e=process.platform){if(o)return[chalk.green(` ✓ Pictures: MuJoCo can draw here (${o})`)+chalk.gray(" — the duck sandbox shows video")];const n=[chalk.yellow(" ⚠ Pictures: MuJoCo cannot draw on this machine")+chalk.gray(" — the sim still runs, the duck sandbox shows text only.")];return"linux"===e&&n.push(chalk.gray(" Fix: ")+chalk.cyan("sudo apt install -y libosmesa6")+chalk.gray(" then ")+chalk.bold.cyan("mujoco setup")+chalk.gray(" again.")),n}
@@ -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 f,resolveHostPython as m,resolveRunPython as g}from"./aienv.js";import{httpFetch as w}from"./http.js";import{lazyJson as $}from"./lazy-assets.js";function b(o){try{return t(`${o} --version 2>&1`,{encoding:"utf-8",timeout:4e3}).trim()}catch{return null}}let v,x;export function probePython(t=!1,o={}){const e=o.hostOnly?x:v;if(e&&!t)return e;const r=c(),n=o.hostOnly?(()=>{const t=m(b,process.platform,r);return t?{...t,source:"host"}:null})():g(b,process.platform,r);if(n){const t=(b(n.cmd.includes(" ")?n.cmd:`"${n.cmd}"`)??"").replace(/^Python\s+/i,"")||`${n.version.major}.${n.version.minor}`,e=p(r,process.platform),s="aienv"===n.source?"aienv":n.cmd===e?"icoa":"system",a={ok:!0,version:t,cmd:n.cmd,source:s};return o.hostOnly?x=a:v=a,a}let s;for(const t of["python3","python"]){const o=b(t);if(y(o)){s=(o??"").replace(/^Python\s+/i,"").trim();break}}const a={ok:!1,otherVersion:s};return o.hostOnly?x=a:v=a,a}export function resetPythonProbe(){v=void 0,x=void 0}const P=`${f.major}.${f.minor}`;export function pythonDoorLine(t,o=!1,e){const r=e??probePython(),n=o?"":"🐍 ";if(r.ok){const o="aienv"===r.source?t?"aienv 环境":"aienv venv":"icoa"===r.source?t?"icoa 装的":"installed by icoa":t?"系统自带":"system";return chalk.gray(` ${n}Python ${r.version} · ${o} · `)+chalk.gray(t?"本机可跑代码":"code runs locally")}return r.otherVersion?chalk.gray(` ${n}Python ${r.otherVersion} — `)+chalk.gray(t?`课程按 ${P} 校准 · `:`courses are calibrated on ${P} · `)+chalk.bold.green("python setup")+chalk.gray(t?` 装并存的 ${P}(免 sudo,不动系统 python3)`:" adds one side-by-side (no sudo, system python3 untouched)"):chalk.gray(` ${n}`+(t?"没有 Python — 读卡答题不需要它 · ":"No Python — reading and answering cards works without it · "))+chalk.bold.green("python setup")+chalk.gray(t?" 让 /py 里能跑代码":" when you want to run code in /py")}export function selectionSetupLine(t,o=!1,e){const r=e??probePython(!1,{hostOnly:!0}),n=o?"":"🐍 ",s=chalk.gray(" (Paper C · SIMOC are MCQ-only — not needed)");return r.ok?chalk.gray(` ${n}Python ${r.version} · `)+chalk.green("ready for code questions")+chalk.gray(" · ")+chalk.cyan("setup")+chalk.gray(" = the whole ladder"):chalk.gray(` ${n}`+(r.otherVersion?`Python ${r.otherVersion} — the exam runs on ${P} · `:`No Python ${P} yet · `))+chalk.bold.green("python setup")+chalk.gray(" installs it (~20 s, no sudo)")+s}export function printNoPython312(t,o={}){const e=probePython();console.log(chalk.yellow(t?e.otherVersion?` 这台机器只有 Python ${e.otherVersion} — 课程和判分机都在 ${P} 线上。`:` 找不到 Python ${P} — 不是你的代码有问题。`:e.otherVersion?` This machine has Python ${e.otherVersion} only — courses and the judge both run on the ${P} line.`:` Python ${P} not found — this is not your code.`)),console.log(chalk.gray(t?" 装一份并存的(免 sudo,二十秒,不动系统 python3): ":" Add one side-by-side (no sudo, ~20 s, system python3 untouched): ")+chalk.bold.cyan("python setup")),o.judgeIsServerSide&&console.log(chalk.gray(t?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()}export function standaloneTriple(t=process.platform,o=""){const e=o.toLowerCase(),r="aarch64"===e||"arm64"===e,n="x86_64"===e||"amd64"===e||"x64"===e;return"darwin"===t?r?"aarch64-apple-darwin":n?"x86_64-apple-darwin":"":"win32"===t?r?"aarch64-pc-windows-msvc":n?"x86_64-pc-windows-msvc":"":r?"aarch64-unknown-linux-gnu":n?"x86_64-unknown-linux-gnu":""}export function pickStandaloneAsset(t,o){const e=`${f.major}\\.${f.minor}`,r=new RegExp(`^cpython-${e}\\.\\d+\\+\\d+-${o}-install_only_stripped\\.tar\\.gz$`),n=new RegExp(`^cpython-${e}\\.\\d+\\+\\d+-${o}-install_only\\.tar\\.gz$`);return t.find(t=>r.test(t.name))??t.find(t=>n.test(t.name))}export function isAllowedAssetUrl(t){return/^https:\/\/github\.com\/astral-sh\/python-build-standalone\/releases\/download\/[\w.%+-]+\/cpython-3\.12\.[\w.%+-]+\.tar\.gz$/.test(t)}const k=/^[0-9a-f]{64}$/;export function candidatesFromManifest(t,o){const e=t?.assets?.[o];if(!e||"string"!=typeof e.path||!function(t,o){const e=`${f.major}\\.${f.minor}`;return new RegExp(`^\\d{8}/cpython-${e}\\.\\d+\\+\\d+-${o}-install_only(_stripped)?\\.tar\\.gz$`).test(t)}(e.path,o))return[];const r="string"==typeof e.sha256&&k.test(e.sha256)?e.sha256:void 0,n=e.path.slice(e.path.indexOf("/")+1),s=[];for(const o of Array.isArray(t.mirrors)?t.mirrors:[]){if("string"!=typeof o||!/^https:\/\/[\w.-]+(\/[\w./%-]*)?$/.test(o))continue;const t=`${o.replace(/\/+$/,"")}/${e.path.replace(/\+/g,"%2B")}`;s.push({url:t,name:n,via:new URL(t).host,sha256:r})}return"string"==typeof e.github&&isAllowedAssetUrl(e.github)&&s.push({url:e.github,name:n,via:"github.com",sha256:r}),s}const j="win32"===process.platform?"tar.exe":"tar";async function A(t,r,n,s){const a=new AbortController;let i=Date.now();const c=setInterval(()=>{Date.now()-i>6e4&&a.abort(new Error("no data for 60 s"))},5e3);try{const c=await w(t,{timeoutMs:3e4,retries:0,signal:a.signal,headers:{"User-Agent":"icoa-cli"}});if(!c.ok)throw new Error(`HTTP ${c.status}`);if(!c.body)throw new Error("empty body");const l=Number(c.headers.get("content-length")??0),p=o("sha256");let y=0;const f=new u({transform(t,o,e){p.update(t),y+=t.length,i=Date.now(),s?.(y,l),e(null,t)}});if(await d(h.fromWeb(c.body),f,e(r)),n&&p.digest("hex")!==n)throw new Error("sha256 mismatch")}catch(t){const o=t.cause;if(a.signal.aborted&&o instanceof Error)throw o;throw t}finally{clearInterval(c)}}const _=["https://icoa-assets.oss-cn-hongkong.aliyuncs.com/python312/manifest.json","https://icoa-datasets.sg-sin-1.linodeobjects.com/python312/manifest.json"];async function E(t){const o=new AbortController,e=setTimeout(()=>o.abort(),6e3),r=Date.now();let n=0;try{const e=await w(t,{timeoutMs:6e3,retries:0,signal:o.signal,headers:{"User-Agent":"icoa-cli",Range:"bytes=0-524287"}});if(!e.ok||!e.body)return 0;const r=e.body.getReader();for(;;){const{done:t,value:o}=await r.read();if(t)break;if(n+=o.length,n>=524288)break}}catch{}finally{clearTimeout(e)}const s=Math.max(1,Date.now()-r);return n>0?1e3*n/s:0}export function orderBySpeed(t,o){const e=t.filter(t=>"github.com"===t.via),r=t.filter(t=>"github.com"!==t.via);return[...r.filter(t=>(o.get(t.url)??0)>0).sort((t,e)=>(o.get(e.url)??0)-(o.get(t.url)??0)),...r.filter(t=>!((o.get(t.url)??0)>0)),...e]}function M(t){return`${(t/1e6).toFixed(t>=1e6?1:2)} MB/s`}export async function provisionPython312(o={}){const e=c(),h=l(e,".icoa","python312"),u=p(e,process.platform),d=t=>{o.quiet||console.log(t)};if(!o.force&&r(u)){const t=b(`"${u}"`);if(t&&new RegExp(`^Python ${f.major}\\.${f.minor}\\.`).test(t))return d(chalk.green(` ✓ ${t}`)+chalk.gray(` → ${u}`)),resetPythonProbe(),!0}const y=function(){if("win32"===process.platform)return"arm64"===process.arch?"aarch64":"x86_64";try{return t("uname -m",{encoding:"utf-8"}).trim()}catch{return"arm64"===process.arch?"aarch64":"x86_64"}}(),m=standaloneTriple(process.platform,y);if(!m)return d(chalk.yellow(` ~ No prebuilt Python ${P} for '${y||"unknown"}' on this platform.`)),!1;if(!function(){try{return t(`${j} --version`,{stdio:"ignore",timeout:4e3}),!0}catch{return!1}}())return d(chalk.red(" ✗ `tar` is not installed")+chalk.gray(" — needed to unpack the download.")),"linux"===process.platform&&d(chalk.gray(" Install it: ")+chalk.cyan("sudo apt install -y tar")),!1;let g=await $("python312/manifest.json",8e3,{force:!0});for(const t of _){if(candidatesFromManifest(g,m).length)break;try{const o=await w(t,{timeoutMs:8e3,retries:0,headers:{"User-Agent":"icoa-cli"}});o.ok&&(g=await o.json())}catch{}}let v=candidatesFromManifest(g,m);if(0===v.length)try{const t=await w("https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest",{headers:{"User-Agent":"icoa-cli",Accept:"application/vnd.github+json"}});if(!t.ok)throw new Error(`GitHub API ${t.status}`);const o=pickStandaloneAsset((await t.json()).assets??[],m);if(!o)throw new Error(`no CPython ${P} build for ${m} in the latest release`);if(!isAllowedAssetUrl(o.browser_download_url))throw new Error("asset URL failed the allowlist check");v=[{url:o.browser_download_url,name:o.name,via:"github.com"}]}catch(t){return d(chalk.red(` ✗ Could not resolve a standalone Python ${P}`)+chalk.gray(` (mirror list unreachable · ${t.message})`)),!1}const x=v[0].name.match(/^cpython-(\d+\.\d+\.\d+)/)?.[1]??P,k=v.filter(t=>"github.com"!==t.via);if(k.length>=2){d(chalk.gray(` Testing ${k.length} download sources …`));const t=await Promise.all(k.map(async t=>[t.url,await E(t.url)])),o=new Map(t);v=orderBySpeed(v,o);const e=v[0],r=o.get(e.url)??0;d(r>0?chalk.gray(` Fastest: ${e.via} (${M(r)})`):chalk.gray(" No source answered the speed test — trying each in turn."))}const C=!o.quiet&&!0===process.stdout.isTTY;let T=0,R=0;const S=(t,o)=>{if(!C)return;const e=Date.now();if(e-T<500&&t<o)return;T=e;const r=t/Math.max(1,e-R)*1e3,n=o?` / ${(o/1e6).toFixed(1)}`:"";process.stdout.write(chalk.gray(`\r ↓ ${(t/1e6).toFixed(1)}${n} MB · ${M(r)} `))},U=()=>{C&&T&&process.stdout.write("\r"+" ".repeat(60)+"\r"),T=0};let V="";try{n(l(e,".icoa"),{recursive:!0}),V=s(l(e,".icoa",".py312-"));const o=l(V,"py.tgz"),r=[];let c=!1;for(const t of v){d(chalk.gray(` Fetching CPython ${x} for ${m} via ${t.via} …`)),R=Date.now();try{await A(t.url,o,t.sha256,S),U(),c=!0;break}catch(o){U();const e=o.message.split("\n")[0].slice(0,80);r.push(`${t.via}: ${e}`),d(chalk.gray(` ~ ${t.via} did not work (${e}) — trying the next source`))}}if(!c)throw new Error(`no source reachable — ${r.join(" · ")}`);t(`${j} -xzf "${o}" -C "${V}"`,{stdio:["ignore","ignore","pipe"]}),i(h,{recursive:!0,force:!0}),a(l(V,"python"),h);const p=t(`"${u}" --version`,{encoding:"utf-8"}).trim();if(!new RegExp(`^Python ${f.major}\\.${f.minor}\\.`).test(p))throw new Error(`unexpected version: ${p}`);return resetPythonProbe(),d(chalk.green(` ✓ ${p} installed`)+chalk.gray(` → ${u} (system python3 untouched)`)),!0}catch(t){const o=String(t.stderr??t.message).trim().split("\n").pop();return d(chalk.red(` ✗ Python ${P} install failed`)+chalk.gray(o?` (${o})`:"")),!1}finally{V&&i(V,{recursive:!0,force:!0})}}
1
+ 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 A="win32"===process.platform?"tar.exe":"tar";export async function downloadTo(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)}}export const MANIFEST_FALLBACKS=["https://icoa-assets.oss-cn-hongkong.aliyuncs.com/python312/manifest.json","https://icoa-datasets.sg-sin-1.linodeobjects.com/python312/manifest.json"];async function j(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 _(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(`${A} --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 MANIFEST_FALLBACKS){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 j(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} (${_(r)})`):chalk.gray(" No source answered the speed test — trying each in turn."))}const E=!o.quiet&&!0===process.stdout.isTTY;let M=0,T=0;const S=(t,o)=>{if(!E)return;const e=Date.now();if(e-M<500&&t<o)return;M=e;const r=t/Math.max(1,e-T)*1e3,n=o?` / ${(o/1e6).toFixed(1)}`:"";process.stdout.write(chalk.gray(`\r ↓ ${(t/1e6).toFixed(1)}${n} MB · ${_(r)} `))},C=()=>{E&&M&&process.stdout.write("\r"+" ".repeat(60)+"\r"),M=0};let F="";try{n(l(e,".icoa"),{recursive:!0}),F=s(l(e,".icoa",".py312-"));const o=l(F,"py.tgz"),r=[];let c=!1;for(const t of v){d(chalk.gray(` Fetching CPython ${x} for ${m} via ${t.via} …`)),T=Date.now();try{await downloadTo(t.url,o,t.sha256,S),C(),c=!0;break}catch(o){C();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(`${A} -xzf "${o}" -C "${F}"`,{stdio:["ignore","ignore","pipe"]}),i(h,{recursive:!0,force:!0}),a(l(F,"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{F&&i(F,{recursive:!0,force:!0})}}
@@ -0,0 +1 @@
1
+ import{getDeviceFingerprint as e}from"./access.js";import{httpFetch as t}from"./http.js";import{LEARN_SERVER as n}from"./learn-curricula.js";import{getCliVersion as s}from"./version.js";import{pendingTrail as i,readSync as r,score as a,startupDir as o,writeSync as u}from"./venture.js";const c=()=>n.replace(/\/$/,"");function d(e){return{name:e.name,boxes:e.boxes,segments:e.segments,versions:e.versions,score:a(e),deck:e.deck,group:e.group??"starter",market:e.market,prd:e.prd}}let l=null,f=null;export function syncTrail(n,a=o()){return l?(f||(f=l.then(()=>(f=null,syncTrail(n,a)))),f):(l=(async()=>{let o=0;try{let l=i(a);do{const i=l.slice(0,200),f=await t(`${c()}/api/icoa/learn/startup/trail`,{method:"POST",headers:{"Content-Type":"application/json","X-ICOA-Client":s()},body:JSON.stringify({vid:n.vid,device_fingerprint:e(),events:i,card:d(n)}),timeoutMs:6e3,idempotent:!0});if(!f.ok)return{ok:!1,sent:o,pending:l.length};if(!(await f.json()).success)return{ok:!1,sent:o,pending:l.length};if(i.length){const e=Math.max(...i.map(e=>e.seq??0));u({last_seq:Math.max(r(a).last_seq,e),last_ok:(new Date).toISOString()},a),o+=i.length}else u({...r(a),last_ok:(new Date).toISOString()},a);l=l.slice(200)}while(l.length);return{ok:!0,sent:o,pending:0}}catch{return{ok:!1,sent:o,pending:i(a).length}}finally{l=null}})(),l)}export async function askCoach(n,i,r,a){try{const o=await t(`${c()}/api/icoa/learn/startup/ask`,{method:"POST",headers:{"Content-Type":"application/json","X-ICOA-Client":s()},body:JSON.stringify({vid:n.vid,device_fingerprint:e(),box:i,question:r,lang:a,card:d(n)}),timeoutMs:4e4}),u=await o.json().catch(()=>({}));if(429===o.status||503===o.status)return{kind:"limited",message:String(u.message||o.status)};if(!o.ok||!u.success)return{kind:"error",message:String(u.message||`HTTP ${o.status}`)};const l=Array.isArray(u.questions)?u.questions.map(e=>String(e)).filter(Boolean):[];return"off_topic"!==u.focus&&l.length?{kind:"ok",questions:l.slice(0,2),focus:String(u.focus||""),left:"number"==typeof u.left_today?u.left_today:null}:{kind:"off_topic"}}catch{return{kind:"offline"}}}async function g(n,i,r){const a=await t(`${c()}/api/icoa/learn/startup/${n}`,{method:"POST",headers:{"Content-Type":"application/json","X-ICOA-Client":s()},body:JSON.stringify({device_fingerprint:e(),...i}),timeoutMs:r}),o=await a.json().catch(()=>({}));return{status:a.status,ok:a.ok,d:o}}export async function planSurvey(e,t){try{const{status:n,ok:s,d:i}=await g("survey/plan",{vid:e.vid,card:d(e),lang:t},45e3);return 400===n&&"incomplete"===i.message?{kind:"incomplete",missing:Array.isArray(i.missing)?i.missing.map(String):[]}:429===n||503===n?{kind:"limited",message:String(i.message||n)}:s&&i.success?{kind:"ok",id:String(i.survey_id),plan:i.plan,n:Number(i.n_planned)||0,left:Number(i.left_today)||0}:{kind:"error",message:String(i.message||`HTTP ${n}`)}}catch{return{kind:"offline"}}}export async function runSurvey(e,t){try{const{status:n,ok:s,d:i}=await g("survey/run",{vid:e.vid,survey_id:t},15e3);return 429===n||503===n?{kind:"limited",message:String(i.message||n)}:s&&i.success?{kind:"running",left:"number"==typeof i.left_today?i.left_today:null}:{kind:"error",message:String(i.message||`HTTP ${n}`)}}catch{return{kind:"offline"}}}export async function surveyStatus(e,t){try{const{ok:n,d:s}=await g("survey/status",{vid:e.vid,survey_id:t},1e4);if(!n||!s.success)return null;const i=String(s.status);return{status:["planned","running","done","failed"].includes(i)?i:"unknown",done:Number(s.n_done)||0,planned:Number(s.n_planned)||0,results:s.results}}catch{return null}}export async function askSlide(n,i,r,a){try{const o=await t(`${c()}/api/icoa/learn/startup/ask`,{method:"POST",headers:{"Content-Type":"application/json","X-ICOA-Client":s()},body:JSON.stringify({vid:n.vid,device_fingerprint:e(),slide:i,question:r,lang:a,card:d(n)}),timeoutMs:4e4}),u=await o.json().catch(()=>({}));if(429===o.status||503===o.status)return{kind:"limited",message:String(u.message||o.status)};if(!o.ok||!u.success)return{kind:"error",message:String(u.message||`HTTP ${o.status}`)};const l=Array.isArray(u.questions)?u.questions.map(e=>String(e)).filter(Boolean):[];return"off_topic"!==u.focus&&l.length?{kind:"ok",questions:l.slice(0,2),focus:String(u.focus||""),left:"number"==typeof u.left_today?u.left_today:null}:{kind:"off_topic"}}catch{return{kind:"offline"}}}export async function askAdvisor(e,t,n,s){try{const{status:i,ok:r,d:a}=await g("ask",{vid:e.vid,mode:"advisor",question:t,lang:n,card:d(e),...s},4e4);return 429===i||503===i?{kind:"limited",message:String(a.message||i)}:r&&a.success?"off_topic"!==a.focus&&a.answer?{kind:"ok",answer:String(a.answer),check:String(a.check||""),left:"number"==typeof a.left_today?a.left_today:null}:{kind:"off_topic"}:{kind:"error",message:String(a.message||`HTTP ${i}`)}}catch{return{kind:"offline"}}}export async function askSuggest(e,t,n,s){try{const{status:i,ok:r,d:a}=await g("ask",{vid:e.vid,mode:"suggest",slide:t,question:n,lang:s,card:d(e)},4e4);if(429===i||503===i)return{kind:"limited",message:String(a.message||i)};if(!r||!a.success)return{kind:"error",message:String(a.message||`HTTP ${i}`)};const o=Array.isArray(a.lines)?a.lines.map(e=>String(e)).filter(Boolean):[];return"off_topic"===a.focus||!a.title&&!o.length?{kind:"off_topic"}:{kind:"ok",title:String(a.title||""),lines:o.slice(0,4),why:String(a.why||""),left:"number"==typeof a.left_today?a.left_today:null}}catch{return{kind:"offline"}}}export async function gradePqs(e){try{const{status:t,ok:n,d:s}=await g("pqs",{vid:e.vid},18e4);return 400===t&&"pqs_few"===s.code?{kind:"few",have:Number(s.have)||0,need:Number(s.need)||3}:429===t||503===t?{kind:"limited",message:String(s.message||t)}:n&&s.success?{kind:"ok",score:Number(s.score)||0,tier:String(s.tier||""),feedback:String(s.feedback||""),improve:String(s.improve||""),turns:Number(s.turns)||0,left:"number"==typeof s.left_today?s.left_today:null}:{kind:"error",message:String(s.message||`HTTP ${t}`)}}catch{return{kind:"offline"}}}export async function makeImage(e,t,n,s){try{const{status:i,ok:r,d:a}=await g("image",{vid:e.vid,slide:t,prompt:n,lang:s},15e4);return"blocked"===a.code?{kind:"blocked"}:429===i||503===i?{kind:"limited",message:String(a.message||i)}:r&&a.success&&"string"==typeof a.image?{kind:"ok",data:Buffer.from(a.image,"base64"),mime:String(a.mime||"image/jpeg"),sha:String(a.sha||"").replace(/[^a-f0-9]/g,"").slice(0,12)||`${Date.now()}`,left:"number"==typeof a.left_today?a.left_today:null}:{kind:"error",message:String(a.message||`HTTP ${i}`)}}catch{return{kind:"offline"}}}
@@ -0,0 +1 @@
1
+ import{randomBytes as e}from"node:crypto";import{appendFileSync as t,existsSync as n,mkdirSync as s,readFileSync as r,writeFileSync as o}from"node:fs";import{homedir as i}from"node:os";import{join as a}from"node:path";export function marketCalc(e){const t=e??{},n=["people","price","buy","reach","cost"].filter(e=>"number"!=typeof t[e]),s=void 0!==t.people&&void 0!==t.price?Math.round(t.people*t.price*12):null,r=void 0!==t.people&&void 0!==t.buy&&void 0!==t.reach?Math.round(t.people*t.buy*t.reach/1e4):null;return{year:s,firstYear:null!==r&&void 0!==t.price?Math.round(r*t.price*12):null,firstYearUsers:r,margin:void 0!==t.price&&void 0!==t.cost&&t.price>0?Math.round(100*(t.price-t.cost)/t.price):null,missing:n}}export const PRD_FIELDS={model:{en:"Which AI model or service, and why that one",zh:"用哪个 AI 模型或服务,为什么选它"},data:{en:"What data the AI needs, and where it comes from",zh:"AI 需要什么数据,从哪来"},eval:{en:"How you will know the AI got it right (a number)",zh:"怎么知道 AI 答对了(写一个数字)"},human:{en:"Where a person checks or confirms",zh:"哪里由人来检查或确认"},not:{en:"What the first version will NOT do",zh:"第一版不做什么"}};export function prdSheet(e){const t=e.boxes,n=(e,n,...s)=>({key:e,title:n,text:s.map(e=>(t[e]??"").trim()).filter(Boolean).join(" · "),fromCard:!0}),s=t=>({key:t,title:PRD_FIELDS[t],text:(e.prd?.[t]??"").trim(),fromCard:!1});return[n("who",{en:"Who and what hurts",zh:"给谁、痛在哪"},"user","problem"),n("ai",{en:"What the AI does, and why now",zh:"AI 做什么、为什么是现在"},"solution","ai_edge"),s("model"),s("data"),s("eval"),n("wrong",{en:"When the AI is wrong",zh:"AI 出错时"},"risk"),s("human"),n("first",{en:"First version: the two-week test",zh:"第一版:两周验证"},"first_step"),s("not")]}export const groupOf=e=>"ai"===e.group?"ai":"starter";export const BOXES=[{n:1,id:"problem",title:{en:"Problem",zh:"问题"},ask:{en:"Who has the problem, in what moment, and how much does it hurt?",zh:"谁遇到了这个问题?在什么场景?有多痛?"},example:{en:"e.g. Year 10 students lose 20 min every night finding which homework is due tomorrow.",zh:"例:十年级学生每晚花 20 分钟找「明天交哪些作业」。"},ring:{en:"Ring 1 · Pain",zh:"第 1 环 · 痛点"}},{n:2,id:"user",title:{en:"First users",zh:"第一批用户"},ask:{en:"Who exactly will use it first? Narrow enough that you could name one.",zh:"最先用它的到底是谁?具体到你能叫出一个人的名字。"},example:{en:"e.g. Year 10 students at my school who take 3+ electives.",zh:"例:我们学校选了 3 门以上选修课的十年级学生。"},ring:{en:"Ring 1 · Pain",zh:"第 1 环 · 痛点"}},{n:3,id:"alternatives",title:{en:"What they do today",zh:"他们现在怎么凑合"},ask:{en:'How do they cope right now? (There is always something — even "nothing" or a spreadsheet.)',zh:"他们现在是怎么解决的?(一定有办法 —— 哪怕是「忍着」或者一张表格。)"},example:{en:"e.g. Screenshots of the class group chat + a paper planner.",zh:"例:截图班级群 + 纸质计划本。"},ring:{en:"Ring 1 · Pain",zh:"第 1 环 · 痛点"}},{n:4,id:"solution",title:{en:"Solution",zh:"方案"},ask:{en:"What will you build, and which step does the AI do?",zh:"你要做什么?哪一步由 AI 来做?"},example:{en:"e.g. An AI that reads the school LMS every evening and sends one list.",zh:"例:每晚由 AI 读学校的学习平台,只发一张清单。"},ring:{en:"Ring 2 · AI edge",zh:"第 2 环 · AI 解法"}},{n:5,id:"ai_edge",title:{en:"Why AI, why now",zh:"为什么是 AI、为什么是现在"},ask:{en:"Take the AI away — does your product still work? Say which AI ability makes it possible, and why it was hard before.",zh:"把 AI 拿掉,产品还成立吗?说清是哪项 AI 能力让它做得成,以及为什么以前做不到。"},example:{en:"e.g. Without AI it is just a link list. An AI model can now read messy class pages and pull out due dates — two years ago that needed a person.",zh:"例:没有 AI 就只是一堆链接。现在的 AI 模型能读懂杂乱的班级页面、找出截止日期 —— 两年前这得靠人工。"},ring:{en:"Ring 2 · AI edge",zh:"第 2 环 · AI 解法"}},{n:6,id:"value",title:{en:"Unique value",zh:"独特价值"},ask:{en:"One sentence: why would they switch from what they do today?",zh:"一句话:他们为什么要放弃现在的办法来用你的?"},example:{en:"e.g. One list, zero searching — done in 10 seconds.",zh:"例:一张清单,不用找,10 秒看完。"},ring:{en:"Ring 2 · AI edge",zh:"第 2 环 · AI 解法"}},{n:7,id:"evidence",title:{en:"Evidence",zh:"证据"},ask:{en:'Who did you actually ask, how many, and what did they DO last time? (Facts, not "they would love it".)',zh:"你真的问过谁?几个人?他们上一次遇到时实际怎么做的?(要事实,不要「他们会喜欢」。)"},example:{en:"e.g. Asked 7 classmates; 5 missed a deadline last term because of it.",zh:"例:问了 7 个同学,5 个上学期因为这个错过了截止日期。"},ring:{en:"Ring 3 · Test",zh:"第 3 环 · 验证"}},{n:8,id:"segments",title:{en:"Who your users are (shares)",zh:"用户分布"},ask:{en:"Split your users into groups, give each a share (total 100%) and where the number comes from.",zh:"把用户分成几类,每类占多少(合计 100%),数字从哪来。"},example:{en:"e.g. seg Year 10 students 60% asked 7 classmates · seg parents 40% ABS 2021 census",zh:"例:seg 十年级学生 60% 问了7个同学 · seg 家长 40% ABS 2021 人口普查"},ring:{en:"Ring 3 · Test",zh:"第 3 环 · 验证"}},{n:9,id:"price",title:{en:"Who pays, how much",zh:"谁付钱、付多少"},ask:{en:"Who pays, how much, and how often? Write a number.",zh:"谁付钱?付多少?多久付一次?写一个数字。"},example:{en:"e.g. Parents, $3 a month; or the school, $500 a year.",zh:"例:家长每月 3 澳元;或者学校每年 500 澳元。"},ring:{en:"Ring 4 · Numbers",zh:"第 4 环 · 算账"}},{n:10,id:"ai_cost",title:{en:"AI cost per user",zh:"每个用户的 AI 成本"},ask:{en:"About how many AI calls does one user make a month, what does each cost, and how much of the price is left?",zh:"一个用户每月大约调用 AI 多少次、每次多少钱、扣掉之后价格里还剩多少?"},example:{en:"e.g. 30 calls a month × $0.002 = $0.06; price $4 ⇒ about $3.94 left before other costs.",zh:"例:每月 30 次 × 0.015 元 = 0.45 元;售价 25 元 ⇒ 扣掉后约剩 24.5 元(还没算其他成本)。"},ring:{en:"Ring 4 · Numbers",zh:"第 4 环 · 算账"}},{n:11,id:"moat",title:{en:"Moat",zh:"护城河"},ask:{en:"If next year's AI does your feature for free, what do you still have? Pick one — data that gets better with use, hard to switch away, a way to reach users, trust, something only you have — and give one piece of evidence.",zh:"如果明年的 AI 免费就能做你这个功能,你还剩什么?选一种 —— 越用越好的数据、用户换走很麻烦、接触用户的渠道、信任、只有你有的东西 —— 并给一条证据。"},example:{en:"e.g. Every correction a student makes teaches our list the school's page layout; 3 schools' layouts after one term.",zh:"例:学生每改一次,清单就更懂这所学校的页面格式;一个学期后我们有 3 所学校的格式。"},ring:{en:"Ring 5 · Moat",zh:"第 5 环 · 护城河"}},{n:12,id:"risk",title:{en:"When the AI gets it wrong",zh:"AI 出错时"},ask:{en:"When the AI is wrong, leaks something private, is tricked by a prompt or is misused — how will you notice, and what happens then?",zh:"AI 答错、泄露隐私、被提示词骗、被拿去做坏事时 —— 你怎么发现?之后怎么处理?"},example:{en:'e.g. If the AI misreads a due date, the student taps "wrong" and the teacher\'s page is shown instead.',zh:"例:AI 读错截止日期时,学生点「不对」,就直接显示老师的原页面。"},ring:{en:"Ring 6 · AI safety",zh:"第 6 环 · AI 安全"}},{n:13,id:"first_step",title:{en:"Two-week test",zh:"两周内的最小验证"},ask:{en:"The smallest experiment you can finish in two weeks — and the number that would count as success.",zh:"两周内能做完的最小实验 —— 以及多少算成功。"},example:{en:"e.g. Send a hand-made list to 10 classmates for 5 nights; success = 6 still read it on night 5.",zh:"例:手工整理清单发给 10 个同学,连续 5 晚;第 5 晚还有 6 人在看就算成功。"},ring:{en:"Ring 7 · Build",zh:"第 7 环 · 做出来"}}];export const SEG_N=BOXES.findIndex(e=>"segments"===e.id)+1;export const BOX_IDS=BOXES.filter(e=>"segments"!==e.id).map(e=>e.id);const h=/\d/,u=/\b(everyone|everybody|anyone|all (people|students|kids|parents))\b|所有人|大家|每个人|所有学生|任何人/i,l=/\b(would|will|might|probably|maybe|think|believe|love|like it|should)\b|会喜欢|应该会|可能|觉得|肯定会|愿意/i,d=/\b(asked|interviewed|talked|spoke|met|surveyed|watched|told me|last (time|week|month|term|year)|did)\b|问过|问了|访谈|聊过|调查|告诉我|上次|上学期|上周|上个月|观察/i,c=/^(none|nothing|no one|n\/a|没有|无|没人)[.。!!]?$/i,p=/\b(ai|a\.i\.|model|llm|gpt|machine learning|ml|neural|vision|speech|chatbot|agent)\b|人工智能|智能|模型|大模型|识别|生成|机器学习|算法/i,m=/\b(without|take (it|the ai) away|remove|now|today|recent|recently|newly|before|years? ago|202\d)\b|去掉|拿掉|没有 ?ai|没有人工智能|现在|最近|以前|过去|两年前|几年前|如今/i,g=/\b(better|smarter|our own|best|stronger) (ai|model|algorithm|technology|tech)\b|技术领先|算法更好|模型更好|更聪明|更强的 ?(ai|模型|算法)|自研(模型|算法)/i,y=/\b(check|review|human|teacher|parent|report|flag|fallback|confirm|verify|alert|log|tap|wrong)\b|人工|老师|家长|确认|检查|兜底|举报|回退|核对|报警|提醒|标记|不对/i;export function contentSize(e){return(e.match(/[㐀-鿿豈-﫿]/g)||[]).length/2+e.replace(/[㐀-鿿豈-﫿]/g," ").split(/\s+/).filter(Boolean).length}export function checkBox(e,t){const n=(t||"").trim();if(!n)return{status:"empty"};if("alternatives"===e&&c.test(n))return{status:"thin",hint:{en:'There is always an alternative — even "put up with it" or a spreadsheet. What do they do today?',zh:"一定有替代办法 —— 哪怕是「忍着」或者一张表格。他们今天到底怎么做?"}};if("user"===e&&u.test(n))return{status:"thin",hint:{en:'"Everyone" is nobody. Narrow it until you could name one real person.',zh:"「所有人」等于没有人。缩小到你能叫出一个真人的名字。"}};if(contentSize(n)<5)return{status:"thin",hint:{en:"Too short to judge — add one more concrete detail.",zh:"太短了,看不出来 —— 再加一个具体细节。"}};if("evidence"===e){if(!h.test(n))return{status:"thin",hint:{en:"How many people? Write the number.",zh:"问了几个人?写出数字。"}};if(l.test(n)&&!d.test(n))return{status:"thin",hint:{en:"That is a guess about the future. Ask what they DID last time, not what they would do.",zh:"这是对未来的猜测。问他们上一次实际做了什么,而不是会不会做。"}}}if("solution"===e&&!p.test(n))return{status:"thin",hint:{en:"Which step does the AI do? Name it — every idea here has to be AI-native.",zh:"哪一步由 AI 来做?写出来 —— 这里每个点子都必须是 AI 原生的。"}};if("ai_edge"===e){if(!p.test(n))return{status:"thin",hint:{en:"Name the AI ability (reading, seeing, listening, writing…).",zh:"写出是哪项 AI 能力(读、看、听、写……)。"}};if(!m.test(n))return{status:"thin",hint:{en:"Answer the test: what is left without AI — and why could nobody do this a few years ago?",zh:"回答这个测试:没有 AI 还剩什么?为什么几年前没人做得到?"}}}return"ai_cost"===e&&(n.match(/\d+(?:[.,]\d+)?/g)||[]).length<2?{status:"thin",hint:{en:"Write the numbers: calls a month × cost per call, then what is left of your price.",zh:"写出数字:每月调用次数 × 每次成本,再算价格里还剩多少。"}}:"moat"===e&&g.test(n)?{status:"thin",hint:{en:"A better AI is not a moat — everyone gets the next model. What do you have that a new model cannot give them?",zh:"「AI 更好」不是护城河 —— 下一代模型人人都能用。有什么是新模型给不了别人的?"}}:"risk"!==e||y.test(n)?"price"!==e||h.test(n)?"first_step"!==e||h.test(n)?{status:"solid"}:{status:"thin",hint:{en:'Add the number that counts as success (e.g. "6 of 10 still use it on day 5").',zh:"加上「多少算成功」的数字(例如「10 人里第 5 天还有 6 人在用」)。"}}:{status:"thin",hint:{en:"Write a number — and who pays it.",zh:"写一个数字 —— 以及谁来付。"}}:{status:"thin",hint:{en:"Say how you would notice the AI went wrong, and what the product does then.",zh:"说清你怎么发现 AI 出错了,以及产品之后怎么处理。"}}}export function segmentTotal(e){return Math.round(10*e.reduce((e,t)=>e+t.share,0))/10}export function checkSegments(e){if(!e.length)return{status:"empty"};const t=segmentTotal(e);return Math.abs(t-100)>1?{status:"thin",hint:{en:`Shares add up to ${t}% — make them 100%.`,zh:`合计 ${t}% —— 要凑成 100%。`}}:e.some(e=>e.source.trim().length<3)?{status:"thin",hint:{en:"Every group needs a source: a statistic, a survey, or the people you asked.",zh:"每一类都要写来源:统计数据、调查,或者你问过的人。"}}:e.length<2?{status:"thin",hint:{en:'Add at least one more group — even "everyone else" — so the survey has a comparison.',zh:"至少再加一类 —— 哪怕是「其他人」—— 调研才有对照。"}}:{status:"solid"}}export function statusOf(e,t){const n=BOXES[t-1];return"segments"===n.id?checkSegments(e.segments):checkBox(n.id,e.boxes[n.id])}export function solidCount(e){let t=0;for(let n=1;n<=BOXES.length;n++)"solid"===statusOf(e,n).status&&t++;return t}export function score(e){return Math.round(10*solidCount(e)/BOXES.length)}export function firstOpenBox(e){for(let t=1;t<=BOXES.length;t++)if("solid"!==statusOf(e,t).status)return t;return null}export function parseSegmentDetailed(e){const t=e.trim();if(!t)return{err:"no_share"};const n=t.includes("|")?"|":t.includes(",")||t.includes(",")?/[,,]/:null;if(n){const e=t.split(n).map(e=>e.trim());if(e.length>=2){const t=Number.parseFloat(e[1].replace("%",""));if(e[0]&&Number.isFinite(t)&&t>0&&t<=100)return{seg:{name:e[0],share:t,source:e.slice(2).join(" ").trim()}}}}const s=t.split(/\s+/),r=s.map((e,t)=>t>0&&(e=>{if(!/^\d+(\.\d+)?%?$/.test(e))return!1;const t=Number.parseFloat(e.replace("%",""));return t>0&&t<=100})(e)?t:-1).filter(e=>e>0);if(!r.length)return{err:"no_share"};const o=r.filter(e=>s[e].endsWith("%"));let i;if(o.length)i=o[0];else{if(1!==r.length)return{err:"ambiguous"};i=r[0]}const a=Number.parseFloat(s[i].replace("%",""));return{seg:{name:s.slice(0,i).join(" "),share:a,source:s.slice(i+1).join(" ")}}}export function parseSegment(e){const t=parseSegmentDetailed(e);return"seg"in t?t.seg:null}export function startupDir(){return process.env.ICOA_STARTUP_DIR||a(i(),".icoa","startup")}export function newVid(){return e(16).toString("hex")}export function emptyVenture(e=(new Date).toISOString()){return{v:1,vid:newVid(),name:"",boxes:{},segments:[],versions:0,created:e,updated:e}}export function loadVenture(e=startupDir()){const t=a(e,"venture.json");if(!n(t))return emptyVenture();try{const n=JSON.parse(r(t,"utf8"));if(n&&1===n.v&&"object"==typeof n.boxes&&Array.isArray(n.segments))return"string"==typeof n.vid&&/^[a-f0-9]{16,40}$/.test(n.vid)||(n.vid=newVid(),saveVenture(n,e)),n}catch{try{o(a(e,`venture.bad-${Date.now()}.json`),r(t))}catch{}}return emptyVenture()}export function saveVenture(e,t=startupDir()){s(t,{recursive:!0}),e.updated=(new Date).toISOString(),o(a(t,"venture.json"),JSON.stringify(e,null,2))}export function snapshot(e,t=startupDir()){const n=e.versions+1;return e.versions=n,s(a(t,"versions"),{recursive:!0}),saveVenture(e,t),o(a(t,"versions",`v${n}.json`),JSON.stringify(e,null,2)),n}let f=0;export function nextSeq(){return f=Math.max(Date.now(),f+1),f}export function appendTrail(e,n=startupDir()){try{s(n,{recursive:!0}),t(a(n,"trail.jsonl"),`${JSON.stringify({ts:(new Date).toISOString(),seq:nextSeq(),...e})}\n`)}catch{}}export function readTrail(e=startupDir()){const t=a(e,"trail.jsonl");if(!n(t))return[];const s=[];for(const e of r(t,"utf8").split("\n"))if(e.trim())try{s.push(JSON.parse(e))}catch{}return s}export function readSync(e=startupDir()){try{const t=JSON.parse(r(a(e,"sync.json"),"utf8"));if(t&&"number"==typeof t.last_seq)return t}catch{}return{last_seq:0}}export function writeSync(e,t=startupDir()){try{s(t,{recursive:!0}),o(a(t,"sync.json"),JSON.stringify(e))}catch{}}export function pendingTrail(e=startupDir()){const t=readSync(e).last_seq;return readTrail(e).filter(e=>"number"==typeof e.seq&&e.seq>t)}export function buildReport(e,t){const n=new Array(BOXES.length).fill(0);let s=0,r=0,o=0,i=0,a=null;const h=[];let u=0,l=0,d=0,c=0,p=0,m=0,g=0,y=0;const f=[];let v=0;for(const e of t)"image"===e.ev&&v++,"advise"===e.ev?p++:"suggest"===e.ev?m++:"drop"===e.ev?y++:"pqs"===e.ev&&"number"==typeof e.score&&f.push(e.score),"slide_edit"!==e.ev||"accept"!==e.mode&&"accept_line"!==e.mode||g++,"slide_edit"===e.ev?u++:"slide_ask"===e.ev?l++:"preview"===e.ev?d++:"export"===e.ev&&c++,"survey"===e.ev&&h.push({buy_au:e.buy_au??null,buy_cn:e.buy_cn??null}),"answer"===e.ev?(s++,e.box&&e.box>=1&&e.box<=BOXES.length&&n[e.box-1]++,"solid"===e.status&&"solid"!==e.prev_status&&i++):"undo"===e.ev?r++:"seg_add"===e.ev||"seg_del"===e.ev?(o++,n[SEG_N-1]++,"solid"===e.status&&"solid"!==e.prev_status&&i++):"save"===e.ev&&null===a&&"number"==typeof e.score&&(a=e.score);const w=t.map(e=>Date.parse(e.ts)).filter(e=>Number.isFinite(e)),b=w.length>1?Math.round((Math.max(...w)-Math.min(...w))/6e4):0;return{versions:e.versions,answers:s,undos:r,segChanges:o,improved:i,editsPerBox:n,minutes:b,scoreNow:score(e),scoreAtFirstSave:a,surveys:h,slideEdits:u,slideAsks:l,previews:d,exports:c,advises:p,suggests:m,accepts:g,drops:y,pqs:f,images:v}}export function saveSurvey(e,t,n=startupDir()){try{s(a(n,"surveys"),{recursive:!0}),o(a(n,"surveys",`${e}.json`),JSON.stringify(t)),o(a(n,"surveys","last.txt"),e)}catch{}}export function lastSurvey(e=startupDir()){try{const t=r(a(e,"surveys","last.txt"),"utf8").trim();return/^[a-f0-9]{12}$/.test(t)?JSON.parse(r(a(e,"surveys",`${t}.json`),"utf8")):null}catch{return null}}
@@ -0,0 +1 @@
1
+ import chalk from"chalk";import{execSync as e}from"node:child_process";import{createHash as t}from"node:crypto";import{mkdirSync as r,readFileSync as o,renameSync as n,rmSync as s,writeFileSync as i}from"node:fs";import{homedir as a}from"node:os";import{join as l}from"node:path";import{httpFetch as c}from"./http.js";import{lazyJson as f}from"./lazy-assets.js";import{downloadTo as p,MANIFEST_FALLBACKS as u}from"./python-setup.js";const h=u.map(e=>e.replace(/python312\/manifest\.json$/,"")),m=/^[0-9a-f]{64}$/,d=/^[A-Za-z0-9_.]+-[A-Za-z0-9_.!+]+(-\d[\w.]*)?-[\w.]+-[\w.]+-[\w.]+\.whl$/;export function lockPlatform(e=process.platform,t=process.arch){const r="arm64"===t?"arm64":"x64"===t?"x86_64":null;return r?"darwin"===e?`macos-${r}`:"linux"===e?"arm64"===r?"linux-aarch64":"linux-x86_64":"win32"===e&&"x86_64"===r?"windows-amd64":null:null}export function bucketRoots(e){const t=[];for(const r of Array.isArray(e)?e:[]){if("string"!=typeof r)continue;const e=/^(https:\/\/[\w.-]+\/)python312\/?$/.exec(r);e&&!t.includes(e[1])&&t.push(e[1])}return t}export function wheelsFor(e,t,r){const o=new Map;for(const n of t){const t=e.groups?.[n]?.platforms?.[r];if(!t)return`no ${n} wheels for ${r}`;if(t.unsupported||!Array.isArray(t.wheels))return`no prebuilt ${n} set for ${r}`;for(const e of t.wheels){const t=o.get(e.name);if(t&&t.version!==e.version)return`${e.name} ${t.version} vs ${e.version}`;o.set(e.name,e)}}return[...o.values()]}export function lockMatchesPins(e,t){for(const[r,o]of Object.entries(t)){const t=e.find(e=>e.name===r.toLowerCase());if(!t)return`${r} missing from the lock`;if(t.version!==o)return`lock has ${r} ${t.version}, client wants ${o}`}return null}export function wheelTags(e){const t=e.replace(/\.whl$/,"").split("-");if(t.length<5)return[];const[r,o,n]=t.slice(-3),s=[];for(const e of r.split("."))for(const t of o.split("."))for(const r of n.split("."))s.push(`${e}-${t}-${r}`);return s}export function pickFile(e,t){const r=new Map(t.map((e,t)=>[e,t]));let o=null,n=Number.POSITIVE_INFINITY;for(const t of e)if(d.test(t.file)&&m.test(t.sha256))for(const e of wheelTags(t.file)){const s=r.get(e);void 0!==s&&s<n&&(o=t,n=s)}return o}export function requirementsText(e){return`${e.map(({wheel:e,file:t})=>`${e.name}==${e.version} --hash=sha256:${t.sha256}`).join("\n")}\n`}async function g(e){const t=new AbortController,r=setTimeout(()=>t.abort(),5e3),o=Date.now();let n=0;try{const r=await c(`${e}wheels/lock.json`,{timeoutMs:5e3,retries:0,signal:t.signal,headers:{"User-Agent":"icoa-cli",Range:"bytes=0-262143"}});if(!r.ok||!r.body)return 0;const o=r.body.getReader();for(;;){const{done:e,value:t}=await o.read();if(e)break;if(n+=t.length,n>=262144)break}await o.cancel().catch(()=>{})}catch{}finally{clearTimeout(r)}return n>0?1e3*n/Math.max(1,Date.now()-o):0}export function orderRoots(e,t){const r=e=>t.get(e)??0;return[...e.filter(e=>r(e)>0).sort((e,t)=>r(t)-r(e)),...e.filter(e=>!(r(e)>0))]}function $(e){return(String(e?.stderr??"").trim().split("\n").filter(Boolean).pop()??"").slice(0,160)}export async function installFromWheelhouse(u,m){const{say:d}=m,w=e=>(d(chalk.gray(` ICOA mirror: ${e} — using the pip mirrors instead`)),!1),y=lockPlatform();if(!y)return w(`no prebuilt set for ${process.platform}/${process.arch}`);const x=await f("python312/manifest.json",8e3);let k=bucketRoots(x?.mirrors);for(const e of h)k.includes(e)||k.push(e);const b=new Map(await Promise.all(k.map(async e=>[e,await g(e)])));if(k=orderRoots(k,b),!((b.get(k[0])??0)>0))return w("none answered the speed test");const v=await async function(e){for(const t of e)try{const e=await c(`${t}wheels/lock.json`,{timeoutMs:15e3,retries:0,headers:{"User-Agent":"icoa-cli"}});if(!e.ok)continue;const r=await e.json();if(1===r?.schema&&r.groups)return r}catch{}return null}(k);if(!v)return w("lock file unreachable");const j=wheelsFor(v,m.groups,y);if("string"==typeof j)return w(j);const A=lockMatchesPins(j,m.pins);if(A)return w(A);const T=function(t){try{return e(`"${t}" -c "from pip._vendor.packaging.tags import sys_tags; print('\\n'.join(str(t) for t in sys_tags()))"`,{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:3e4}).split("\n").map(e=>e.trim()).filter(Boolean)}catch{return[]}}(u);if(!T.length)return w("could not read this Python's wheel tags");const _=[];for(const e of j){const t=pickFile(e.files,T);if(!t){const t=v.groups[m.groups[m.groups.length-1]]?.platforms?.[y]?.min_os;return w(`no ${e.name} ${e.version} wheel fits this system${t?` (needs ${t})`:""}`)}_.push({wheel:e,file:t})}const I=l(a(),".icoa","wheels");r(I,{recursive:!0});const M=_.filter(({file:e})=>function(e){try{return t("sha256").update(o(e)).digest("hex")}catch{return null}}(l(I,e.file))!==e.sha256),R=M.reduce((e,{file:t})=>e+(t.size??0),0)/1e6,F="string"==typeof v.mirror?.path&&v.mirror.path.includes("<file>")?v.mirror.path:"wheels/files/<file>";d(chalk.gray(` ICOA mirror: ${new URL(k[0]).host} (fastest of ${k.length}) · `)+chalk.white(M.length?`${M.length} file${1===M.length?"":"s"}, ${R.toFixed(0)} MB`:"all files already downloaded"));let P=0;for(const{wheel:e,file:t}of M){const r=l(I,t.file),o=`${r}.part`;let i=!1;for(const e of k)try{await p(`${e}${F.replace("<file>",encodeURIComponent(t.file))}`,o,t.sha256),n(o,r),i=!0;break}catch{s(o,{force:!0})}if(!i)return w(`${e.name} ${e.version} not downloadable from any mirror`);P++,process.stdout.isTTY&&process.stdout.write(chalk.gray(`\r ⬇ ${P}/${M.length} ${e.name}`.padEnd(60)))}M.length&&process.stdout.isTTY&&process.stdout.write(`\r${" ".repeat(62)}\r`);const C=l(I,`requirements-${m.groups.join("+")}.txt`);i(C,requirementsText(_));try{e(`"${u}" -m pip install --disable-pip-version-check -q --no-index --find-links "${I}" --only-binary=:all: --require-hashes -r "${C}"`,{stdio:["ignore","ignore","pipe"],timeout:9e5})}catch(e){return w("pip refused the set"+($(e)?` (${$(e)})`:""))}return d(chalk.green(` ✓ ${_.length} packages installed from the ICOA mirror`)+chalk.gray(" (sha256 verified)")),!0}