icoa-cli 2.19.656 → 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.
@@ -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=>`${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"}
@@ -1 +1 @@
1
- import{readFileSync as e,writeFileSync as o,existsSync as t,accessSync as n,realpathSync as r,constants as s}from"node:fs";import{join as i,dirname as a,basename as l,sep as c}from"node:path";import{fileURLToPath as u}from"node:url";import{homedir as g,platform as p}from"node:os";import{spawnSync as d}from"node:child_process";import chalk from"chalk";import{getIcoaDir as f}from"./config.js";const m=a(u(import.meta.url)),y=i(m,"..",".."),h=m,v=h.startsWith(g()+c)||h.includes(`${c}.nvm${c}`)||h.includes(`${c}.fnm${c}`)||h.includes(`${c}.volta${c}`),w="win32"===p()||"darwin"===p()||v?"":"sudo ",k=(e,o)=>`${o??""!==w?"sudo ":""}npm install -g icoa-cli@${e}`,$=["https://registry.npmjs.org","https://registry.npmmirror.com"];function b(){return JSON.parse(e(i(y,"package.json"),"utf-8")).version}function C(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 x(){return i(f(),"update-check.json")}function E(){try{return t(x())?JSON.parse(e(x(),"utf-8")):null}catch{return null}}function T(e){try{const t={lastCheck:Date.now(),latestVersion:e.version,registries:e.registries};o(x(),JSON.stringify(t,null,2))}catch{}}async function A(e){const o=await Promise.all($.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&&!C(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 N(){const e=E();return e?.latestVersion?{version:e.latestVersion,registries:e.registries?.length?e.registries:$}:null}let O=null;export function startBootCheck(){O??=A(2e3).then(e=>(e&&T(e),e??N()))}export function checkForUpdates(){setTimeout(async()=>{try{await async function(e){const o=E();if(o?.latestVersion&&Date.now()-o.lastCheck<e.maxAgeMs)return{version:o.latestVersion,registries:o.registries?.length?o.registries:$};const t=await A(e.timeoutMs);return t&&T(t),t}({maxAgeMs:6e5,timeoutMs:5e3})}catch{}},0)}export function printUpdateHint(){try{const e=b(),o=N();if(!o||!C(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(k(o.version)))),console.log()}catch{}}let S=null;function U(){return S||(S=(()=>{if("win32"===p())return{ok:!1,reason:"native Windows install"};let e;try{e=r(y)}catch{return{ok:!1,reason:"cannot resolve install directory"}}const o=a(e);if("node_modules"!==l(o)||"lib"!==l(a(o)))return{ok:!1,reason:"not an npm global install (dev tree?)"};const t=a(a(o));let c;try{c=r(i(a(process.execPath),"npm"))}catch{return{ok:!1,reason:"npm not found next to node"}}let u=!1;for(const r of[e,o,i(t,"bin")])try{n(r,s.W_OK)}catch{u=!0}return u&&0!==d("sudo",["-V"],{stdio:"ignore"}).status?{ok:!1,reason:"needs sudo, and sudo is not available"}:{ok:!0,npm:[process.execPath,c],prefix:t,needsSudo:u}})(),S)}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 M(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(k(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=b();e.ask&&startBootCheck();const t=e.ask?await O:await A(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||T(t),!C(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(k(o)));else{console.log(chalk.white(" Update: ")+chalk.bold.cyan(k(o)));const e="darwin"===p()?"Cmd+C":"win32"===p()?"Ctrl+C":"Ctrl+Shift+C";console.log(chalk.gray(` ↑ select & ${e} to copy — typos break it`))}console.log(r),console.log()}(o,t.version):M(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"!==p()&&!0===process.stdin.isTTY&&0===d("sudo",["-V"],{stdio:"ignore"}).status;let s=e.needsSudo,i=e.needsSudo;const a=()=>console.log(chalk.gray(" icoa is installed with admin rights — sudo will ask for your computer password."));s&&a();for(const n of t){let t=!1;for(;;){console.log(chalk.gray(` ⬇ icoa-cli@${o} from ${n.replace(/^https:\/\//,"")}${t?" (refreshing)":""} …`));const l=[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"],c={stdio:["inherit","inherit","pipe"],encoding:"utf-8"},u=s?d("sudo",[e.npm[0],...l],c):d(e.npm[0],l,c);let g="";try{g=b()}catch{}if(g===o)return{ok:!0,perm:i};const p=u.stderr||"";for(const e of _(p))console.log(chalk.gray(` ${e}`));if(s&&/^sudo: |incorrect password|not in the sudoers/m.test(p))return{ok:!1,perm:!0};if(/\b(EACCES|EPERM)\b/.test(p)){if(i=!0,s||!r())return{ok:!1,perm:i};s=!0,a()}else{if(t||!/\b(ETARGET|notarget)\b|No matching version/i.test(p)){console.log(chalk.yellow(" ⚠ that source did not work")+chalk.gray(0===u.status?` (npm finished but icoa is still v${g||"?"})`:` (npm exit ${u.status})`));break}t=!0}}}return{ok:!1,perm:i}}(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}.`)),M(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}
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.656",
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",