icoa-cli 2.19.655 → 2.19.657
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/duck-contest.js +1 -0
- package/dist/commands/duck-cup.js +1 -1
- package/dist/commands/duck.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/lib/duck-trace-run.js +51 -0
- package/dist/lib/duck-trace.js +1 -0
- package/dist/lib/mujoco-setup.js +1 -1
- package/dist/lib/update-check.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,51 @@
|
|
|
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
|
|
2
|
+
engine = sys.argv[sys.argv.index('--engine') + 1]
|
|
3
|
+
path = sys.argv[sys.argv.index('--file') + 1]
|
|
4
|
+
sid = sys.argv[sys.argv.index('--scenario') + 1]
|
|
5
|
+
sys.path.insert(0, engine)
|
|
6
|
+
os.environ.setdefault('OMP_NUM_THREADS', '1')
|
|
7
|
+
os.environ.setdefault('MUJOCO_GL', 'disable')
|
|
8
|
+
def emit(o):
|
|
9
|
+
sys.stdout.write(json.dumps(o) + '\n')
|
|
10
|
+
src = open(path, encoding='utf-8', errors='replace').read()
|
|
11
|
+
try:
|
|
12
|
+
compile(src, 'control.py', 'exec')
|
|
13
|
+
except SyntaxError as e:
|
|
14
|
+
emit({'ok': False, 'error': 'syntax', 'line': e.lineno, 'message': str(e.msg), 'text': (e.text or '').strip()}); sys.exit()
|
|
15
|
+
try:
|
|
16
|
+
from duckkit import ControlError, Scenario, run_file
|
|
17
|
+
from scenarios import score
|
|
18
|
+
except Exception as e:
|
|
19
|
+
emit({'ok': False, 'error': 'engine', 'message': '%s: %s' % (type(e).__name__, e)}); sys.exit()
|
|
20
|
+
t0 = time.time()
|
|
21
|
+
buf, real = io.StringIO(), sys.stdout
|
|
22
|
+
sys.stdout = buf
|
|
23
|
+
try:
|
|
24
|
+
sc = Scenario.load(sid)
|
|
25
|
+
log = run_file(path, sc)
|
|
26
|
+
res = score(sc, log)
|
|
27
|
+
except ControlError as e:
|
|
28
|
+
sys.stdout = real; emit({'ok': False, 'error': 'control', 'message': str(e)}); sys.exit()
|
|
29
|
+
except Exception as e:
|
|
30
|
+
sys.stdout = real
|
|
31
|
+
tb = traceback.extract_tb(sys.exc_info()[2])
|
|
32
|
+
st = [f for f in tb if f.filename.endswith(path)]
|
|
33
|
+
emit({'ok': False, 'error': 'runtime', 'line': st[-1].lineno if st else None,
|
|
34
|
+
'message': '%s: %s' % (type(e).__name__, str(e)[:200])}); sys.exit()
|
|
35
|
+
finally:
|
|
36
|
+
sys.stdout = real
|
|
37
|
+
n = len(log.t)
|
|
38
|
+
every = max(1, int(round(n / max(1.0, sc.seconds * 10.0))))
|
|
39
|
+
gx = log.gx if len(log.gx) == n else [0.0] * n
|
|
40
|
+
head = log.head_cmd if len(log.head_cmd) == n else [0.0] * n
|
|
41
|
+
pts = [[round(float(log.t[k]), 2), round(float(log.xy[k][0]), 3), round(float(log.xy[k][1]), 3),
|
|
42
|
+
round(math.degrees(float(log.yaw[k]))), round(float(gx[k]), 3), round(float(head[k]), 3)]
|
|
43
|
+
for k in range(0, n, every)]
|
|
44
|
+
prints = buf.getvalue().splitlines()
|
|
45
|
+
emit({'ok': True, 'pass': bool(res['pass']), 'value': res['value'], 'detail': res['detail'],
|
|
46
|
+
'fallen_at': res.get('fallen_at'), 'seconds': sc.seconds, 'time_ms': int((time.time() - t0) * 1000),
|
|
47
|
+
'prints': prints[:40], 'prints_total': len(prints),
|
|
48
|
+
'trace': {'samples': pts, 'seconds': sc.seconds, 'fallen_at': log.fallen_at,
|
|
49
|
+
'walls': [{'pos': list(w['pos'][:2]), 'size': list(w['size'][:2])} for w in sc.walls],
|
|
50
|
+
'markers': [list(m['pos'][:2]) for m in sc.markers], 'goal': dict(sc.goal)}})
|
|
51
|
+
`,c=i(n(),".icoa","duck","trace_run.py");export function runWithTrace(d,m,p,g,f=18e4){t(i(n(),".icoa","duck"),{recursive:!0}),s(c)&&r(c,"utf-8")===l||o(c,l);const u=e(d,[c,"--engine",m,"--file",a(p),"--scenario",g],{encoding:"utf-8",timeout:f,cwd:m,env:{...process.env,PYTHONDONTWRITEBYTECODE:"1",OMP_NUM_THREADS:"1",MUJOCO_GL:"disable"}}),y=String(u.stdout??"").trim().split("\n").pop()||"";try{return JSON.parse(y)}catch{return{ok:!1,error:"engine",message:String(u.stderr??"").trim().split("\n").slice(-3).join(" ")||`exit ${u.status}`}}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import chalk from"chalk";const t=()=>{const t=process.env.LC_ALL||process.env.LANG||"";return"C"!==t&&"POSIX"!==t},a=t=>new Promise(a=>setTimeout(a,t));export function traceKind(t){const a=String(t.goal?.type??"");return"bow"===a?"bow":"nod"===a?"nod":"stand"===a?"stand":"top"}export function topFrame(a,e,o=56,n=15){const s=a.samples,r=[0,...s.map(t=>t[1]),...a.markers.map(t=>t[0])],l=[0,...s.map(t=>t[2]),...a.markers.map(t=>t[1])];for(const t of a.walls)r.push(t.pos[0]-t.size[0],t.pos[0]+t.size[0]),l.push(t.pos[1]-t.size[1],t.pos[1]+t.size[1]);const p=a.goal;Array.isArray(p.goal)&&(r.push(p.goal[0]),l.push(p.goal[1]));const i=.15;let c=Math.min(...r)-i,h=Math.max(...r)+i,m=Math.min(...l)-i,d=Math.max(...l)+i;const f=(h-c)/o,g=(d-m)/n,u=Math.max(f,g/2,.02),y=(c+h)/2,w=(m+d)/2;c=y-u*o/2,h=y+u*o/2,m=w-u*n,d=w+u*n;const x=Array.from({length:n},()=>Array(o).fill(" ")),M=(t,a,e,s=!0)=>{const r=((t,a)=>{const e=Math.floor((t-c)/(h-c)*o),s=Math.floor((d-a)/(d-m)*n);return s>=0&&s<n&&e>=0&&e<o?[s,e]:null})(t,a);r&&(s||" "===x[r[0]][r[1]])&&(x[r[0]][r[1]]=e)};for(const t of a.walls){const a=Math.max(2,Math.round(2*t.size[1]/(2*u)));for(let e=0;e<=a;e++)M(t.pos[0],t.pos[1]-t.size[1]+2*t.size[1]*e/a,"#")}a.markers.forEach((t,a)=>{M(t[0],t[1],String((a+1)%10))}),Array.isArray(p.goal)&&!a.markers.length&&M(p.goal[0],p.goal[1],"G");const b=t()?"·":".",$=s.filter(t=>t[0]<=e+1e-9);for(const t of $.slice(0,-1))M(t[1],t[2],b,!1);M(0,0,"S");const _=null!=a.fallen_at&&e>=a.fallen_at,A=$[$.length-1];A&&M(A[1],A[2],_?"X":"D");const k=t=>"#"===t?chalk.white(t):"S"===t?chalk.green(t):"D"===t?chalk.bold.yellow(t):"X"===t?chalk.bold.red(t):t===b?chalk.cyan(t):/[0-9G]/.test(t)?chalk.magenta(t):t,v=chalk.gray(` +${"-".repeat(o)}+`);return[v,...x.map(t=>chalk.gray(" |")+t.map(k).join("")+chalk.gray("|")),v]}export function stripFrame(a,e,o=56,n=9){const s=traceKind(a),r=t=>"nod"===s?t[5]:t[4],l=a.goal,p="bow"===s?[{v:l.gx_high??.18,label:"down line"},{v:l.gx_low??.08,label:"up line"}]:"nod"===s?[{v:(l.amp_min??.4)/2,label:"down line"},{v:-(l.amp_min??.4)/2,label:"up line"}]:[],i=a.samples.map(r),c=Math.min(...i,...p.map(t=>t.v))-.05,h=Math.max(...i,...p.map(t=>t.v))+.05,m=t=>Math.max(0,Math.min(n-1,Math.round((h-t)/(h-c)*(n-1)))),d=Array.from({length:n},()=>Array(o).fill(" ")),f=new Map;for(const t of p){const a=m(t.v);f.set(a,t.label);for(let t=0;t<o;t++)d[a][t]="-"}const g=t()?"●":"o";for(const t of a.samples){if(t[0]>e+1e-9)break;const n=Math.min(o-1,Math.floor(t[0]/Math.max(a.seconds,.1)*o));d[m(r(t))][n]=null!=a.fallen_at&&t[0]>=a.fallen_at?"X":g}const u="nod"===s?"head":"body lean",y=[chalk.gray(` ${u} ↑`)];return d.forEach((t,a)=>{const e=t.map(t=>"-"===t?chalk.gray(t):"X"===t?chalk.bold.red(t):chalk.cyan(t)).join("");y.push(chalk.gray(" |")+e+(f.has(a)?chalk.gray(` ${f.get(a)}`):""))}),y.push(chalk.gray(` +${"-".repeat(o)}> time`)),y.push(chalk.gray(` 0 s${" ".repeat(Math.max(1,o-8))}${a.seconds} s`)),y}export async function playTrace(t){if(!t?.samples?.length)return;const e=traceKind(t),o=a=>{const o="top"===e?topFrame(t,a):stripFrame(t,a),n=t.samples.filter(t=>t[0]<=a+1e-9).pop()??t.samples[0],s=null!=t.fallen_at&&a>=t.fallen_at,r="top"===e?` t=${a.toFixed(1).padStart(4)} s x ${n[1].toFixed(2)} m y ${n[2].toFixed(2)} m heading ${n[3]}°`:` t=${a.toFixed(1).padStart(4)} s`;return[...o,chalk.white(r)+(s?chalk.red(` fell at ${t.fallen_at} s`):"")]},n=t.samples[t.samples.length-1][0];if(!process.stdout.isTTY){for(const t of o(n))console.log(t);return}let s=0;for(let t=1;t<=30;t++){const e=o(n*t/30);process.stdout.write((s?`[${s}A`:"")+e.map(t=>`[2K${t}`).join("\n")+"\n"),s=e.length,t<30&&await a(100)}}export function traceLegend(a){const e=traceKind(a);return"top"===e?" S start · D the duck · X fell · # wall · 1 2 3 markers · G goal · "+(t()?"·":".")+" its path":"bow"===e?" each bow = the dots go above the down line, then back under the up line":"nod"===e?" each nod = the head goes past the down line, then past the up line":" the duck should stay standing the whole time"}
|
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
|
|
1
|
+
import chalk from"chalk";import{execSync as o}from"node:child_process";import{existsSync as n,mkdirSync as e,readFileSync as r,rmSync as t,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 y,provisionPython312 as d,resetPythonProbe as g}from"./python-setup.js";const h=`${p.major}.${p.minor}`;export const MUJOCO_PACKAGES=[{name:"numpy",module:"numpy",spec:"numpy>=1.26",role:"vectors"},{name:"mujoco",module:"mujoco",spec:"mujoco>=3.2",role:"physics + rendering"},{name:"onnxruntime",module:"onnxruntime",spec:"onnxruntime>=1.18",role:"runs the walking policy"}];export function mujocoPaths(o,n=process.platform){const e="win32"===n?c:a,r=e.join(o,".icoa","mujoco");if("win32"===n){const o=e.join(r,"Scripts");return{root:r,binDir:o,python:e.join(o,"python.exe"),marker:e.join(r,"icoa-mujoco.json")}}const t=e.join(r,"bin");return{root:r,binDir:t,python:e.join(t,"python"),marker:e.join(r,"icoa-mujoco.json")}}let f;export function probeMujoco(e=!1){if(f&&!e)return f;const r=mujocoPaths(s()),t={ok:!1,venv:n(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),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 n=o(`"${r.python}" -`,{input:a,encoding:"utf-8",stdio:["pipe","pipe","ignore"],timeout:2e4}).trim(),e=JSON.parse(n.split("\n").pop()??"{}");for(const o of i)e[o]?t.versions[o]=e[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(n=>o.versions[n.module]).map(n=>`${n.name} ${o.versions[n.module]}`).join(" · ")}export function mujocoDoorLine(o,n=!1,e){const r=e??probeMujoco(),t=n?"":"🦆 ";return r.ok?chalk.gray(` ${t}${mujocoVersionsLine(r)} · `)+chalk.gray(o?"本机可跑仿真":"sim runs locally"):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(n){try{return o(`"${n}" -m pip --version`,{stdio:"ignore",timeout:15e3}),!0}catch{return!1}}function j(o){const n=(o?.stderr?.toString()??"").split("\n").map(o=>o.trim()).filter(Boolean);return n.length?n[n.length-1].slice(0,120):""}export async function provisionMujoco(r={}){const c=o=>{r.quiet||console.log(o)},p=s(),f=mujocoPaths(p);let $=y(!0,{hostOnly:!0});if(!$.ok){if(c(chalk.gray(` No Python ${h} here — installing one first (stage 0, no sudo) …`)),!await d({quiet:r.quiet}))return c(chalk.red(` ✗ Could not get a Python ${h}`)+chalk.gray(" — try ")+chalk.bold.cyan("python setup")),!1;if(g(),$=y(!0,{hostOnly:!0}),!$.ok||!$.cmd)return!1}const x=$.cmd;c(chalk.green(` ✓ Python ${$.version}`)+chalk.gray(` · ${x}`));const b=u(p),O="win32"!==process.platform&&x.replace(/"/g,"")!==b,C=async()=>{if(c(chalk.gray(" This Python 3.12 has no venv/pip (a system build) — switching to the ICOA one …")),!n(b)&&!await d({quiet:r.quiet}))return!1;try{t(f.root,{recursive:!0,force:!0}),o(`"${b}" -m venv "${f.root}"`,{stdio:["ignore","ignore","pipe"]})}catch{return!1}return!!v(f.python)&&(c(chalk.green(" ✓ venv recreated")+chalk.gray(` · ${b}`)),!0)};let w=!1;if(r.force&&n(f.root)){c(chalk.gray(" --force: recreating the venv …")),w=!0;try{o(`${x.includes(" ")?x:`"${x}"`} -m venv --clear "${f.root}"`,{stdio:["ignore","ignore","pipe"]})}catch{}}if(n(f.python))c(w?chalk.green(" ✓ venv recreated"):chalk.green(" ✓ venv exists")+chalk.gray(" — reusing"));else{c(chalk.gray(` Creating venv → ${f.root}`));try{e(a.join(p,".icoa"),{recursive:!0}),o(`${x.includes(" ")?x:`"${x}"`} -m venv "${f.root}"`,{stdio:["ignore","ignore","pipe"]})}catch(o){if(!O||!await C())return c(chalk.red(" ✗ Could not create the venv")+chalk.gray(j(o)?` (${j(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}v(f.python)&&c(chalk.green(" ✓ venv created"))}if(!v(f.python)){c(chalk.gray(" Bootstrapping pip …"));try{o(`"${f.python}" -m ensurepip --upgrade`,{stdio:["ignore","ignore","pipe"]})}catch{}if(!(v(f.python)||O&&await C()))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 A=MUJOCO_PACKAGES.filter(o=>!M.versions[o.module]).length?await l(f.python):void 0;A&&c(chalk.gray(` ${A.line}`));for(const o of MUJOCO_PACKAGES)if(M.versions[o.module])c(chalk.green(` ✓ ${o.name} ${M.versions[o.module]}`)+chalk.gray(" (already installed)"));else{c(chalk.cyan(` ⬇ ${o.name}`)+chalk.gray(` ${o.spec} — ${o.role}`));try{m(f.python,o.spec,A,{extra:"-q --only-binary=:all:",onRetry:n=>c(chalk.yellow(` ~ ${o.name}: that source failed — trying ${n.host} …`))})}catch(n){c(chalk.red(` ✗ ${o.name} failed to install`)+chalk.gray(j(n)?` (${j(n)})`:"")),P++}}const k=probeMujoco(!0);for(const o of MUJOCO_PACKAGES)M.versions[o.module]||(k.versions[o.module]?c(chalk.green(` ✓ ${o.name} ${k.versions[o.module]} installed`)):P||c(chalk.red(` ✗ ${o.name} installed but does not import`)));if(!k.ok)return!1;const J={version:1,hostPython:(function(n){try{return o(`${n} --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(J,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 a.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(n){for(const r of glCandidates()){const t={...process.env,MUJOCO_GL:r};"osmesa"===r&&(t.PYOPENGL_PLATFORM="osmesa");try{const s=o(`"${n}" -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{e(a.dirname($()),{recursive:!0}),i($(),JSON.stringify({version:1,python:s||n,backend:r}))}catch{}return r}catch{}}try{t($(),{force:!0})}catch{}return null}export function renderLines(o,n=process.platform){if(o)return[chalk.green(` ✓ Pictures: MuJoCo can draw here (${o})`)+chalk.gray(" — the duck sandbox shows video")];const e=[chalk.yellow(" ⚠ Pictures: MuJoCo cannot draw on this machine")+chalk.gray(" — the sim still runs, the duck sandbox shows text only.")];return"linux"===n&&e.push(chalk.gray(" Fix: ")+chalk.cyan("sudo apt install -y libosmesa6")+chalk.gray(" then ")+chalk.bold.cyan("mujoco setup")+chalk.gray(" again.")),e}
|
package/dist/lib/update-check.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as e,writeFileSync as o,existsSync as t,accessSync as n,realpathSync as r,constants as
|
|
1
|
+
import{readFileSync as e,writeFileSync as o,existsSync as t,accessSync as n,realpathSync as r,rmSync as s,constants as i}from"node:fs";import{join as a,dirname as l,basename as c,sep as u}from"node:path";import{fileURLToPath as g}from"node:url";import{homedir as p,platform as d}from"node:os";import{spawnSync as f}from"node:child_process";import chalk from"chalk";import{getIcoaDir as m}from"./config.js";const y=l(g(import.meta.url)),h=a(y,"..",".."),v=y,w=v.startsWith(p()+u)||v.includes(`${u}.nvm${u}`)||v.includes(`${u}.fnm${u}`)||v.includes(`${u}.volta${u}`),k="win32"===d()||"darwin"===d()||w?"":"sudo ",$=(e,o)=>`${o??""!==k?"sudo ":""}npm install -g icoa-cli@${e}`,b=["https://registry.npmjs.org","https://registry.npmmirror.com"];function C(){return JSON.parse(e(a(h,"package.json"),"utf-8")).version}function E(e,o){const t=e.split(".").map(Number),n=o.split(".").map(Number);for(let e=0;e<Math.max(t.length,n.length);e++){const o=t[e]??0,r=n[e]??0;if(o>r)return!0;if(o<r)return!1}return!1}function T(){return a(m(),"update-check.json")}function x(){try{return t(T())?JSON.parse(e(T(),"utf-8")):null}catch{return null}}function A(e){try{const t={lastCheck:Date.now(),latestVersion:e.version,registries:e.registries};o(T(),JSON.stringify(t,null,2))}catch{}}async function N(e){const o=await Promise.all(b.map(async o=>{const t=Date.now(),n=new AbortController,r=setTimeout(()=>n.abort(),e);try{const e=await fetch(`${o}/icoa-cli/latest`,{signal:n.signal,headers:{Accept:"application/json"}});return e.ok?{reg:o,version:(await e.json()).version??null,ms:Date.now()-t}:{reg:o,version:null,ms:1/0}}catch{return{reg:o,version:null,ms:1/0}}finally{clearTimeout(r)}}));let t=null;for(const e of o)!e.version||t&&!E(e.version,t)||(t=e.version);if(!t)return null;const n=[...o].sort((e,o)=>(e.version===t?0:1)-(o.version===t?0:1)||e.ms-o.ms);return{version:t,registries:n.map(e=>e.reg)}}function O(){const e=x();return e?.latestVersion?{version:e.latestVersion,registries:e.registries?.length?e.registries:b}:null}let S=null;export function startBootCheck(){S??=N(2e3).then(e=>(e&&A(e),e??O()))}export function checkForUpdates(){setTimeout(async()=>{try{await async function(e){const o=x();if(o?.latestVersion&&Date.now()-o.lastCheck<e.maxAgeMs)return{version:o.latestVersion,registries:o.registries?.length?o.registries:b};const t=await N(e.timeoutMs);return t&&A(t),t}({maxAgeMs:6e5,timeoutMs:5e3})}catch{}},0)}export function printUpdateHint(){try{const e=C(),o=O();if(!o||!E(o.version,e))return;console.log(chalk.yellow(` ⬆ v${o.version} is out`)+chalk.gray(` (you have v${e}) — type `)+(U().ok?chalk.bold.cyan("upgrade"):chalk.cyan($(o.version)))),console.log()}catch{}}let M=null;function U(){return M||(M=(()=>{if("win32"===d())return{ok:!1,reason:"native Windows install"};let e;try{e=r(h)}catch{return{ok:!1,reason:"cannot resolve install directory"}}const o=l(e);if("node_modules"!==c(o)||"lib"!==c(l(o)))return{ok:!1,reason:"not an npm global install (dev tree?)"};const t=l(l(o));let s;try{s=r(a(l(process.execPath),"npm"))}catch{return{ok:!1,reason:"npm not found next to node"}}let u=!1;for(const r of[e,o,a(t,"bin")])try{n(r,i.W_OK)}catch{u=!0}return u&&0!==f("sudo",["-V"],{stdio:"ignore"}).status?{ok:!1,reason:"needs sudo, and sudo is not available"}:{ok:!0,npm:[process.execPath,s],prefix:t,needsSudo:u}})(),M)}function _(e){return e.split("\n").map(e=>e.replace(/^npm (error|ERR!)\s*/,"").trim()).filter(e=>e&&!/^at |^\{|^\}|^A complete log|^errno|^syscall|^path|^dest|^code:/.test(e)).slice(0,3)}function R(e,o,t,n){console.log(chalk.yellow(" ⚠ icoa cannot upgrade itself here")+chalk.gray(` — ${t}.`)),console.log(chalk.white(" Run this in your shell instead: ")+chalk.bold.cyan($(o,n))),console.log(chalk.gray(" then ")+chalk.cyan("hash -r")+chalk.gray(" and ")+chalk.cyan("icoa --version")+chalk.gray(` (now v${e})`))}export async function runUpgrade(e){const o=C();e.ask&&startBootCheck();const t=e.ask?await S:await N(8e3);if(!t)return e.ask||(console.log(chalk.yellow(" ⚠ could not reach the npm registry")+chalk.gray(` — you are on v${o}.`)),console.log(chalk.gray(" Check the network (")+chalk.cyan("doctor")+chalk.gray(") and try again."))),"offline";if(e.ask||A(t),!E(t.version,o))return e.ask||console.log(chalk.green(` ✅ icoa v${o} is the latest version.`)),"current";const n=U();if(!n.ok)return e.ask?function(e,o){const t=function(e,o){const t=e.split(".").map(Number),n=o.split(".").map(Number);return t[0]!==n[0]||t[1]!==n[1]?-1:(t[2]??0)-(n[2]??0)}(o,e),n=t>0?chalk.gray(` (${t} version${1===t?"":"s"} behind)`):"",r=chalk.yellow(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");if(console.log(),console.log(r),console.log(chalk.bold.yellow(" ⬆ New version available!")),console.log(),console.log(chalk.white(" Current: ")+chalk.gray(`v${e}`)),console.log(chalk.white(" Latest: ")+chalk.bold.green(`v${o}`)+n),console.log(),U().ok)console.log(chalk.white(" Update: ")+chalk.gray("type ")+chalk.bold.cyan("upgrade")+chalk.gray(" at icoa>")),console.log(chalk.gray(" or in your shell: ")+chalk.cyan($(o)));else{console.log(chalk.white(" Update: ")+chalk.bold.cyan($(o)));const e="darwin"===d()?"Cmd+C":"win32"===d()?"Ctrl+C":"Ctrl+Shift+C";console.log(chalk.gray(` ↑ select & ${e} to copy — typos break it`))}console.log(r),console.log()}(o,t.version):R(o,t.version,n.reason),"skipped";if(e.ask){console.log(),console.log(chalk.bold.yellow(" ⬆ New version: ")+chalk.gray(`v${o}`)+chalk.white(" → ")+chalk.bold.green(`v${t.version}`));const{default:e}=await import("@inquirer/confirm");let n=!0;try{n=await e({message:"Upgrade now? (Enter = yes, n = later)",default:!0})}catch{n=!1}if(!n)return console.log(chalk.gray(" Later — type ")+chalk.cyan("upgrade")+chalk.gray(" at icoa> any time.")),"skipped"}const r=function(e,o,t){const n=process.stdin;try{n.isTTY&&n.setRawMode&&n.setRawMode(!1)}catch{}const r=()=>"win32"!==d()&&!0===process.stdin.isTTY&&0===f("sudo",["-V"],{stdio:"ignore"}).status;let i=e.needsSudo,a=e.needsSudo;const l=()=>console.log(chalk.gray(" icoa is installed with admin rights — sudo will ask for your computer password."));i&&l();let c=!1;for(const n of t){let t=!1;for(;;){console.log(chalk.gray(` ⬇ icoa-cli@${o} from ${n.replace(/^https:\/\//,"")}${t?" (refreshing)":""} …`));const u=[e.npm[1],"install","-g",`icoa-cli@${o}`,`--prefix=${e.prefix}`,`--registry=${n}/`,...t?["--prefer-online"]:[],"--no-fund","--no-progress","--no-audit","--loglevel=error","--fetch-timeout=30000","--fetch-retries=1"],g={stdio:["inherit","inherit","pipe"],encoding:"utf-8"},p=i?f("sudo",[e.npm[0],...u],g):f(e.npm[0],u,g);let d="";try{d=C()}catch{}if(d===o)return{ok:!0,perm:a};const m=p.stderr||"";for(const e of _(m))console.log(chalk.gray(` ${e}`));if(i&&/^sudo: |incorrect password|not in the sudoers/m.test(m))return{ok:!1,perm:!0};if(/\b(EACCES|EPERM)\b/.test(m)){if(a=!0,i||!r())return{ok:!1,perm:a};i=!0,l();continue}if(!t&&/\b(ETARGET|notarget)\b|No matching version/i.test(m)){t=!0;continue}const y=/rename '([^']+)' -> '([^']+)'/.exec(m);if(!c&&/\bENOTEMPTY\b/.test(m)&&y){const[,e,o]=y,t=e.replace(/[/\\]icoa-cli$/,"");if(t!==e&&o.startsWith(t)&&/[/\\]\.icoa-cli-[A-Za-z0-9]+$/.test(o)){c=!0,console.log(chalk.gray(` removing a leftover from an earlier upgrade: ${o}`)),i?f("sudo",["rm","-rf",o],{stdio:"inherit"}):s(o,{recursive:!0,force:!0});continue}}console.log(chalk.yellow(" ⚠ that source did not work")+chalk.gray(0===p.status?` (npm finished but icoa is still v${d||"?"})`:` (npm exit ${p.status})`));break}}return{ok:!1,perm:a}}(n,t.version,t.registries);return r.ok?(console.log(chalk.green(` ✅ upgraded to v${t.version}`)),"upgraded"):(console.log(chalk.red(` ✗ upgrade failed — still v${o}.`)),R(o,t.version,r.perm?"icoa is installed with admin rights":"every source failed",r.perm||void 0),"failed")}export function bootUpgradeEligible(e){return!0===process.stdin.isTTY&&"1"===process.env.ICOA_SUPERVISED&&"1"!==process.env.ICOA_RELAUNCH&&"1"!==process.env.ICOA_NO_UPDATE&&!process.env.ICOA_TEST_BOOT_MODE&&!e}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icoa-cli",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.657",
|
|
4
4
|
"description": "ICOA CLI — AI-native competition runtime of the International Cyber Olympiad in AI: learn, practise, and compete in AI & cybersecurity from the terminal (AI4CTF · CTF4AI · CTF4EAI)",
|
|
5
5
|
"author": "Charlie Zhu",
|
|
6
6
|
"type": "module",
|