icoa-cli 2.19.701 → 2.19.703
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/aienv.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/env.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/shell.js +1 -1
- package/dist/lib/aienv.js +1 -1
- package/dist/lib/mujoco-setup.js +1 -1
- package/dist/lib/python-setup.js +1 -1
- package/dist/lib/wheelhouse.js +1 -0
- package/dist/repl.js +1 -1
- package/package.json +1 -1
package/dist/commands/shell.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execSync as o,spawnSync as e}from"node:child_process";import chalk from"chalk";import{printInfo as n,printSuccess as r}from"../lib/ui.js";import{logCommand as s}from"../lib/logger.js";import{getActiveCwd as i}from"../lib/exam-sandbox.js";import{isDockerRunning as l}from"../lib/docker-probe.js";export function resolveShellLaunch(o){return o.dockerAvailable?{mode:"docker",command:"docker"}:{mode:"host",command:"win32"===o.platform?o.comspecEnv||"cmd.exe":o.shellEnv||"/bin/bash"}}export{SANDBOX_IMAGES,resolveSandboxImage}from"../lib/sandbox.js";import{SANDBOX_IMAGES as t,resolveSandboxImage as a}from"../lib/sandbox.js";export function buildSandboxRunArgs(o){return["run","--rm","-it","--name",o.containerName,"--network=host","-v",`${o.cwd}:/work`,"-w","/work","-v","icoa-aienv:/root/.icoa",o.image,"/bin/bash"]}function c(){const e=i(),{command:s}=resolveShellLaunch({dockerAvailable:!1,platform:process.platform,shellEnv:process.env.SHELL,comspecEnv:process.env.COMSPEC});n("Docker not found — opening a host shell."),console.log(chalk.gray(" All
|
|
1
|
+
import{execSync as o,spawnSync as e}from"node:child_process";import chalk from"chalk";import{printInfo as n,printSuccess as r}from"../lib/ui.js";import{logCommand as s}from"../lib/logger.js";import{getActiveCwd as i}from"../lib/exam-sandbox.js";import{isDockerRunning as l}from"../lib/docker-probe.js";export function resolveShellLaunch(o){return o.dockerAvailable?{mode:"docker",command:"docker"}:{mode:"host",command:"win32"===o.platform?o.comspecEnv||"cmd.exe":o.shellEnv||"/bin/bash"}}export{SANDBOX_IMAGES,resolveSandboxImage}from"../lib/sandbox.js";import{SANDBOX_IMAGES as t,resolveSandboxImage as a}from"../lib/sandbox.js";export function buildSandboxRunArgs(o){return["run","--rm","-it","--name",o.containerName,"--network=host","-v",`${o.cwd}:/work`,"-w","/work","-v","icoa-aienv:/root/.icoa",o.image,"/bin/bash"]}function c(){const e=i(),{command:s}=resolveShellLaunch({dockerAvailable:!1,platform:process.platform,shellEnv:process.env.SHELL,comspecEnv:process.env.COMSPEC});n("Docker not found — opening a host shell."),console.log(chalk.gray(" All the CTF tools run on your host. If any are missing, run ")+chalk.cyan("env setup")+chalk.gray(".")),console.log(chalk.gray(" Type 'exit' to return to ICOA CLI.")),console.log();try{o(s,{stdio:"inherit",cwd:e}),console.log(),r("Shell session ended.")}catch{console.log(),n("Shell session ended.")}}export function registerShellCommand(d){d.command("shell").description("Open an interactive CTF shell (Docker sandbox if available, else host)").action(async()=>{if(s("shell"),!await l())return void c();const d=a(e=>{try{return o(`docker image inspect ${e}`,{stdio:"ignore"}),!0}catch{return!1}},e=>{n(`Pulling ${e}...`);try{return o(`docker pull ${e}`,{stdio:"inherit"}),!0}catch{return!1}});if(null===d)return n("Could not pull a sandbox image — using your host shell instead."),void c();const m=i();r("Launching sandbox..."),console.log(chalk.gray(" Your folder is mounted at ")+chalk.cyan("/work")+chalk.gray(" — files there persist on your host.")),d===t[0]?console.log(chalk.gray(" ML venv: ")+chalk.cyan("~/.icoa/aienv/bin/python")+chalk.gray(" (sklearn / jupyter / mujoco) — its pip installs persist across sessions.")):console.log(chalk.gray(" This image has no ML venv — get the newer one with ")+chalk.cyan(`docker pull ${t[0]}`)),console.log(chalk.gray(" Type 'exit' to return to ICOA CLI.")),console.log();const u=`icoa-sandbox-${Date.now()}`,h=e("docker",buildSandboxRunArgs({cwd:m,image:d,containerName:u}),{stdio:"inherit"});console.log(),h.error?n("Sandbox session ended."):r("Sandbox session ended.")})}
|
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.
|
|
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}`}"`}
|
package/dist/lib/mujoco-setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{execSync as o}from"node:child_process";import{existsSync as e,mkdirSync as n,readFileSync as
|
|
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}
|
package/dist/lib/python-setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{execSync as t}from"node:child_process";import{createHash as o}from"node:crypto";import{createWriteStream as e,existsSync as r,mkdirSync as n,mkdtempSync as s,renameSync as a,rmSync as i}from"node:fs";import{homedir as c}from"node:os";import{join as l}from"node:path";import{Readable as h,Transform as u}from"node:stream";import{pipeline as d}from"node:stream/promises";import{icoaStandalonePython as p,parsePyVersion as y,REQUIRED_PY as 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 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}
|