icoa-cli 2.19.373 → 2.19.374

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.
@@ -1 +1 @@
1
- import{createHash as t,randomUUID as e}from"node:crypto";import{execSync as n}from"node:child_process";import{platform as r}from"node:os";import{getConfig as i,saveConfig as o,getIcoaDir as c}from"./config.js";import{readFileSync as s,writeFileSync as a,existsSync as u}from"node:fs";import{join as f}from"node:path";const p=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return i().lastVersion!==t}export function markVersionSeen(t){o({lastVersion:t})}const l=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb"]);export function isActivated(){return!!i().accessToken}export function getDeviceFingerprint(){const c=i();if(c.deviceFingerprint)return c.deviceFingerprint;let a=c.installSalt;a||(a=e(),o({installSalt:a}));const f=function(){try{if("darwin"===r()){const t=n("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===r()){if(u("/etc/machine-id"))return s("/etc/machine-id","utf-8").trim()}else if("win32"===r())return n('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${f}|${a}`).digest("hex")}export function activateToken(e){if(!function(t){return p.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=f(c(),"token-bindings.json");let i={};if(u(r))try{i=JSON.parse(s(r,"utf-8"))}catch{}const l=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),d=i[l];return d&&d!==n?"already_bound":(i[l]=n,a(r,JSON.stringify(i,null,2)),o({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=i();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return l.has(t.toLowerCase())}const d=()=>f(c(),"session-state.json");function m(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function g(){const t=d();if(!u(t))return m();try{return{...m(),...JSON.parse(s(t,"utf-8"))}}catch{return m()}}function x(t){const e={...g(),...t};a(d(),JSON.stringify(e,null,2))}export function recordExit(){const t=g();t.lastExitAt=(new Date).toISOString(),t.exitCount++,x(t)}export function recordResume(){const t=g();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,x(t),{awaySeconds:r,exitCount:t.exitCount}}
1
+ import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
@@ -4,4 +4,5 @@ export declare function saveConfig(config: Partial<IcoaConfig>): void;
4
4
  export declare function getBudget(): HintBudget;
5
5
  export declare function saveBudget(budget: HintBudget): void;
6
6
  export declare function getIcoaDir(): string;
7
+ export declare function getInstallSalt(): string;
7
8
  export declare function isConnected(): boolean;
@@ -1 +1 @@
1
- import{mkdirSync as t,readFileSync as n,writeFileSync as o,existsSync as r,chmodSync as e,statSync as i}from"node:fs";import{join as c}from"node:path";import{homedir as f}from"node:os";import{randomUUID as s}from"node:crypto";import{DEFAULT_CONFIG as u,DEFAULT_BUDGET as g}from"../types/index.js";const p=c(f(),".icoa"),d=c(p,"config.json"),m=c(p,"budget.json");function a(t,n){o(t,n);try{e(t,384)}catch{}}function y(t){try{63&i(t).mode&&e(t,384)}catch{}}function l(){r(p)||t(p,{recursive:!0,mode:448})}export function getConfig(){if(l(),!r(d)){const t={...u,sessionId:s()};return a(d,JSON.stringify(t,null,2)),t}y(d);try{const t=n(d,"utf-8");return{...u,...JSON.parse(t)}}catch{return{...u,sessionId:s()}}}export function saveConfig(t){l();const n={...getConfig(),...t};a(d,JSON.stringify(n,null,2))}export function getBudget(){if(l(),!r(m))return a(m,JSON.stringify(g,null,2)),{...g};y(m);try{const t=n(m,"utf-8");return{...g,...JSON.parse(t)}}catch{return{...g}}}export function saveBudget(t){l(),a(m,JSON.stringify(t,null,2))}export function getIcoaDir(){return l(),p}export function isConnected(){const t=getConfig();return!(!t.ctfdUrl||!t.token)}
1
+ import{mkdirSync as t,readFileSync as n,writeFileSync as o,existsSync as e,chmodSync as r,statSync as i}from"node:fs";import{join as l}from"node:path";import{homedir as s}from"node:os";import{randomUUID as a}from"node:crypto";import{DEFAULT_CONFIG as c,DEFAULT_BUDGET as f}from"../types/index.js";import{deriveFileKey as u,writeSignedFile as g,readSignedFile as d,verifyObject as p,recordVerdict as S}from"./secure-store.js";const m=l(s(),".icoa"),y=l(m,"config.json"),x=l(m,"budget.json"),C="config",h="budget";function v(){e(m)||t(m,{recursive:!0,mode:448})}export function getConfig(){if(v(),!e(y)){const t={...c,sessionId:a(),installSalt:a()};try{g(y,t,u(t.installSalt,C))}catch{}return t}let t;!function(t){try{63&i(t).mode&&r(t,384)}catch{}}(y);try{t=JSON.parse(n(y,"utf-8"))}catch{return S(C,"corrupt"),{...c,sessionId:a()}}let l="string"==typeof t.installSalt?t.installSalt:void 0;if(!l){l=a(),t={...t,installSalt:l};try{!function(t,n){o(t,n);try{r(t,384)}catch{}}(y,JSON.stringify(t,null,2))}catch{}}const s=u(l,C),f=p(t,s);S(C,f);const d={...c,...t};return delete d._sig,d}export function saveConfig(t){v();const n={...getConfig(),...t};n.installSalt||(n.installSalt=a()),g(y,n,u(n.installSalt,C))}export function getBudget(){v();const t=u(getInstallSalt(),h),{data:n,verdict:o}=d(x,t);return S(h,o),n?{...f,...n}:(g(x,{...f},t),{...f})}export function saveBudget(t){v(),g(x,t,u(getInstallSalt(),h))}export function getIcoaDir(){return v(),m}export function getInstallSalt(){const t=getConfig();if(t.installSalt)return t.installSalt;const n=a();return saveConfig({installSalt:n}),n}export function isConnected(){const t=getConfig();return!(!t.ctfdUrl||!t.token)}
@@ -1 +1 @@
1
- import{mkdirSync as t,readFileSync as e,unlinkSync as r,writeFileSync as o}from"node:fs";import{join as n}from"node:path";import{homedir as a}from"node:os";const s=n(a(),".icoa","demo2-progress.json");export function loadDemo2Progress(){let t,r;try{t=e(s,"utf-8")}catch{return null}try{r=JSON.parse(t)}catch{return clearDemo2Progress(),null}if("number"!=typeof r.nextCardIndex||"number"!=typeof r.totalCards||"string"!=typeof r.lang||"number"!=typeof r.startedAt)return clearDemo2Progress(),null;const o=r.completedAt??r.startedAt;return"number"==typeof o&&Date.now()-o>6048e5?(clearDemo2Progress(),null):{nextCardIndex:r.nextCardIndex,totalCards:r.totalCards,lang:r.lang,startedAt:r.startedAt,completedAt:"number"==typeof r.completedAt?r.completedAt:void 0}}export function saveDemo2Progress(e){!function(){try{t(n(a(),".icoa"),{recursive:!0})}catch{}}();try{o(s,JSON.stringify(e))}catch{}}export function clearDemo2Progress(){try{r(s)}catch{}}export function markCardDone(t,e,r,o){saveDemo2Progress({nextCardIndex:t+1,totalCards:e,lang:r,startedAt:o})}export function markDemo2Complete(t,e,r){saveDemo2Progress({nextCardIndex:t,totalCards:t,lang:e,startedAt:r,completedAt:Date.now()})}
1
+ import{unlinkSync as e}from"node:fs";import{join as t}from"node:path";import{getIcoaDir as r,getInstallSalt as o}from"./config.js";import{deriveFileKey as n,readSignedFile as s,writeSignedFile as a,recordVerdict as d}from"./secure-store.js";const m="demo2-progress";function l(){return t(r(),"demo2-progress.json")}function c(){return n(o(),m)}export function loadDemo2Progress(){const{data:e,verdict:t}=s(l(),c());if(d(m,t),"corrupt"===t)return clearDemo2Progress(),null;if(!e)return null;const r=e;if("number"!=typeof r.nextCardIndex||"number"!=typeof r.totalCards||"string"!=typeof r.lang||"number"!=typeof r.startedAt)return clearDemo2Progress(),null;const o=r.completedAt??r.startedAt;return"number"==typeof o&&Date.now()-o>6048e5?(clearDemo2Progress(),null):{nextCardIndex:r.nextCardIndex,totalCards:r.totalCards,lang:r.lang,startedAt:r.startedAt,completedAt:"number"==typeof r.completedAt?r.completedAt:void 0}}export function saveDemo2Progress(e){try{a(l(),e,c())}catch{}}export function clearDemo2Progress(){try{e(l())}catch{}}export function markCardDone(e,t,r,o){saveDemo2Progress({nextCardIndex:e+1,totalCards:t,lang:r,startedAt:o})}export function markDemo2Complete(e,t,r){saveDemo2Progress({nextCardIndex:e,totalCards:e,lang:t,startedAt:r,completedAt:Date.now()})}
@@ -1 +1 @@
1
- import{readFileSync as t,writeFileSync as e,existsSync as n,unlinkSync as a,mkdirSync as r,chmodSync as o}from"node:fs";import{execFileSync as i}from"node:child_process";import{join as s}from"node:path";import{homedir as c}from"node:os";import{getIcoaDir as u}from"./config.js";export function practicalChatCommand(t,e){return e?"ctf4ai"===t?"ctf4ai":"ai4ctf"===t?"ai4ctf":"vla"===t?"ctf4eai":null:null}export function materializeAttachedData(t,a){if(!a)return null;let o;try{const i=getRealExamState(),u=i?.session?.workspaceDir,f=u&&n(u)?u:s(c(),"icoa-workspace");r(f,{recursive:!0}),o=s(f,`q${t}.txt`),e(o,a,"utf-8")}catch{return null}try{return i("docker",["cp",o,`icoa-sandbox:/home/competitor/challenges/q${t}.txt`],{stdio:"ignore",timeout:3e3}),`challenges/q${t}.txt`}catch{return o}}function f(){return s(u(),"exam-state.json")}function l(){return s(u(),"demo-state.json")}function m(t){return"demo-free"===t?l():f()}export function getRealExamState(){const e=f();if(!n(e))return null;try{const n=JSON.parse(t(e,"utf-8"));if("demo-free"===n?.session?.examId){try{a(e)}catch{}return null}return n}catch{return null}}export function getDemoState(){const e=l();if(!n(e))return null;try{return JSON.parse(t(e,"utf-8"))}catch{return null}}export function getExamState(){return getRealExamState()||getDemoState()}export function saveExamState(t){const n=m(t.session.examId);e(n,JSON.stringify(t,null,2));try{o(n,384)}catch{}}export function clearExamState(t){if(t){const e=m(t);n(e)&&a(e)}else{const t=getExamState();if(t){const e=m(t.session.examId);n(e)&&a(e)}}}function d(t){if(!t.session.durationMinutes)return null;const{deadlineServerMs:e,clockOffsetMs:n}=t.session;if("number"==typeof e&&"number"==typeof n)return new Date(e-n);const a=t.session.confirmedAt||t.session.startedAt,r=new Date(a).getTime();return new Date(r+60*t.session.durationMinutes*1e3)}export function getExamDeadline(){const t=getExamState();return t?d(t):null}export function getRealExamDeadline(){const t=getRealExamState();return t?d(t):null}let p=!1;export async function refetchQuestionDataIfStale(){const t=getRealExamState();if(!t)return null;if(p)return t;const e=t.session.token;if(!e)return t;if(!t.questions.some(t=>{if("ai4ctf"!==t.type&&"ctf4ai"!==t.type)return!1;const e=String(t.description||"");return(e.includes("attachedData")||/base64 blob/i.test(e))&&!t.attachedData}))return t;p=!0;try{const{getConfig:n}=await import("./config.js"),a=n(),r=a.ctfdUrl||"https://practice.icoa2026.au",o=a.language||"en",i=await fetch(`${r}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,deviceHash:"",lang:o}),signal:AbortSignal.timeout(8e3)});if(!i.ok)return t;const s=await i.json(),c=s?.data?.questions||[];if(0===c.length)return t;const u=new Map;for(const t of c)u.set(t.number,t);let f=0;for(const e of t.questions){const t=u.get(e.number);t&&(t.attachedData&&!e.attachedData&&(e.attachedData=t.attachedData,f++),t.description&&(!e.description||t.description.length>e.description.length)&&(e.description=t.description))}return f>0&&saveExamState(t),t}catch{return t}}
1
+ import{writeFileSync as t,existsSync as e,unlinkSync as n,mkdirSync as a}from"node:fs";import{execFileSync as o}from"node:child_process";import{join as r}from"node:path";import{homedir as i}from"node:os";import{getIcoaDir as s,getInstallSalt as c}from"./config.js";import{deriveFileKey as u,readSignedFile as f,writeSignedFile as m,recordVerdict as l}from"./secure-store.js";export function practicalChatCommand(t,e){return e?"ctf4ai"===t?"ctf4ai":"ai4ctf"===t?"ai4ctf":"vla"===t?"ctf4eai":null:null}export function materializeAttachedData(n,s){if(!s)return null;let c;try{const o=getRealExamState(),u=o?.session?.workspaceDir,f=u&&e(u)?u:r(i(),"icoa-workspace");a(f,{recursive:!0}),c=r(f,`q${n}.txt`),t(c,s,"utf-8")}catch{return null}try{return o("docker",["cp",c,`icoa-sandbox:/home/competitor/challenges/q${n}.txt`],{stdio:"ignore",timeout:3e3}),`challenges/q${n}.txt`}catch{return c}}function d(){return r(s(),"exam-state.json")}function p(){return r(s(),"demo-state.json")}function x(t){return"demo-free"===t?p():d()}export function getRealExamState(){const t=d(),{data:e,verdict:a}=f(t,u(c(),"exam-state"));if(l("exam-state",a),!e)return null;if("demo-free"===e?.session?.examId){try{n(t)}catch{}return null}return e}export function getDemoState(){const t=p(),{data:e,verdict:n}=f(t,u(c(),"demo-state"));return l("demo-state",n),e}export function getExamState(){return getRealExamState()||getDemoState()}export function saveExamState(t){const e=t.session.examId,n=x(e);m(n,t,u(c(),function(t){return"demo-free"===t?"demo-state":"exam-state"}(e)))}export function clearExamState(t){if(t){const a=x(t);e(a)&&n(a)}else{const t=getExamState();if(t){const a=x(t.session.examId);e(a)&&n(a)}}}function g(t){if(!t.session.durationMinutes)return null;const{deadlineServerMs:e,clockOffsetMs:n}=t.session;if("number"==typeof e&&"number"==typeof n)return new Date(e-n);const a=t.session.confirmedAt||t.session.startedAt,o=new Date(a).getTime();return new Date(o+60*t.session.durationMinutes*1e3)}export function getExamDeadline(){const t=getExamState();return t?g(t):null}export function getRealExamDeadline(){const t=getRealExamState();return t?g(t):null}let h=!1;export async function refetchQuestionDataIfStale(){const t=getRealExamState();if(!t)return null;if(h)return t;const e=t.session.token;if(!e)return t;if(!t.questions.some(t=>{if("ai4ctf"!==t.type&&"ctf4ai"!==t.type)return!1;const e=String(t.description||"");return(e.includes("attachedData")||/base64 blob/i.test(e))&&!t.attachedData}))return t;h=!0;try{const{getConfig:n}=await import("./config.js"),a=n(),o=a.ctfdUrl||"https://practice.icoa2026.au",r=a.language||"en",i=await fetch(`${o}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,deviceHash:"",lang:r}),signal:AbortSignal.timeout(8e3)});if(!i.ok)return t;const s=await i.json(),c=s?.data?.questions||[];if(0===c.length)return t;const u=new Map;for(const t of c)u.set(t.number,t);let f=0;for(const e of t.questions){const t=u.get(e.number);t&&(t.attachedData&&!e.attachedData&&(e.attachedData=t.attachedData,f++),t.description&&(!e.description||t.description.length>e.description.length)&&(e.description=t.description))}return f>0&&saveExamState(t),t}catch{return t}}
@@ -0,0 +1,9 @@
1
+ import type { InputDynamics } from '../types/index.js';
2
+ export declare function classifyBurst(interKeyMs: number[]): {
3
+ maxBurst: number;
4
+ suspectPaste: boolean;
5
+ };
6
+ export declare function stripPasteMarkers(line: string): string;
7
+ export declare function installInputDynamics(enableBracketed?: boolean): void;
8
+ export declare function uninstallInputDynamics(): void;
9
+ export declare function consumeLineDynamics(): InputDynamics | undefined;
@@ -0,0 +1 @@
1
+ let s=!1,t=0,e=null,n=[];function a(){return{start:Date.now(),keys:0,backspaces:0,pastes:0,pasteChars:0}}export function classifyBurst(s){let t=1,e=1;for(let n=1;n<s.length;n++)s[n]<5?(t++,t>e&&(e=t)):t=1;return{maxBurst:e,suspectPaste:e>=8}}export function stripPasteMarkers(s){return s.replace(/\x1b?\[20[01]~/g,"")}function r(s,r){e||(e=a());const c=Date.now();t&&n.push(c-t),t=c,e.keys++,"backspace"===r?.name&&e.backspaces++}function c(s){const t=s.toString("latin1");let n=t.indexOf("[200~");for(;-1!==n;){e||(e=a()),e.pastes++;const s=t.indexOf("[201~",n);-1!==s&&(e.pasteChars+=s-(n+6)),n=t.indexOf("[200~",n+6)}}export function installInputDynamics(a=!0){if(!s&&(s=!0,e=null,n=[],t=0,process.stdin.on("keypress",r),process.stdin.on("data",c),a&&process.stdout.isTTY))try{process.stdout.write("[?2004h")}catch{}}export function uninstallInputDynamics(){if(s&&(s=!1,process.stdin.removeListener("keypress",r),process.stdin.removeListener("data",c),process.stdout.isTTY))try{process.stdout.write("[?2004l")}catch{}}export function consumeLineDynamics(){if(!e)return;const{maxBurst:s,suspectPaste:a}=classifyBurst(n),r={ms:Date.now()-e.start,keys:e.keys,backspaces:e.backspaces,pastes:e.pastes,pasteChars:e.pasteChars,maxBurst:s,suspectPaste:a||e.pastes>0};return e=null,n=[],t=0,r}
@@ -1,3 +1,19 @@
1
+ /**
2
+ * Pure payload builder — no I/O, no network. Extracted from
3
+ * `postIntegritySnapshot` so the SCRUBBED shape (and the secret-exclusion
4
+ * invariant: config.accessToken / config.token never enter this object) is
5
+ * unit-testable without a live server or filesystem.
6
+ */
7
+ export declare function buildSnapshotPayload(cfg: {
8
+ deviceFingerprint?: string;
9
+ installSalt?: string;
10
+ }, budget: {
11
+ tokensUsed: number;
12
+ tokenCap: number;
13
+ }, extras?: {
14
+ simCooldown?: unknown;
15
+ tokenBindings?: unknown;
16
+ }): Record<string, unknown>;
1
17
  /**
2
18
  * Fire a scrubbed integrity snapshot to the server. Best-effort, non-blocking,
3
19
  * and self-swallowing — callers may `await` it inside an existing try/catch
@@ -1 +1 @@
1
- import{readFileSync as t}from"node:fs";import{join as n}from"node:path";import{homedir as o}from"node:os";import{getConfig as e,getBudget as i}from"./config.js";import{getCliVersion as r}from"./version.js";function s(n){try{return JSON.parse(t(n,"utf-8"))}catch{return null}}export async function postIntegritySnapshot(){try{const t=e();if("live"!==t.competitionState)return;const a=t.ctfdUrl;if(!a)return;const c=n(o(),".icoa"),p=i(),d={deviceFingerprint:t.deviceFingerprint||"",installSalt:t.installSalt||"",budget:{tokensUsed:p.tokensUsed,tokenCap:p.tokenCap},simCooldown:s(n(c,"sim-cooldown.json")),tokenBindings:s(n(c,"token-bindings.json"))},m={"Content-Type":"application/json","User-Agent":`icoa-cli/${r()}`,"X-Device-Fingerprint":t.deviceFingerprint||""};t.token&&t.userName&&(d.account=t.userName,m.Authorization=`Token ${t.token}`),await fetch(`${a}/api/icoa/snapshot`,{method:"POST",headers:m,body:JSON.stringify(d),signal:AbortSignal.timeout(8e3)})}catch{}}
1
+ import{readFileSync as n}from"node:fs";import{join as o}from"node:path";import{homedir as t}from"node:os";import{getConfig as i,getBudget as e}from"./config.js";import{getCliVersion as r}from"./version.js";import{collectVerdicts as s}from"./secure-store.js";function a(o){try{return JSON.parse(n(o,"utf-8"))}catch{return null}}export function buildSnapshotPayload(n,o,t){return{deviceFingerprint:n.deviceFingerprint||"",installSalt:n.installSalt||"",budget:{tokensUsed:o.tokensUsed,tokenCap:o.tokenCap},simCooldown:t?.simCooldown??null,tokenBindings:t?.tokenBindings??null,integrity:s()}}export async function postIntegritySnapshot(){try{const n=i();if("live"!==n.competitionState)return;const s=n.ctfdUrl;if(!s)return;const c=o(t(),".icoa"),l=buildSnapshotPayload(n,e(),{simCooldown:a(o(c,"sim-cooldown.json")),tokenBindings:a(o(c,"token-bindings.json"))}),p={"Content-Type":"application/json","User-Agent":`icoa-cli/${r()}`,"X-Device-Fingerprint":n.deviceFingerprint||""};n.token&&n.userName&&(l.account=n.userName,p.Authorization=`Token ${n.token}`),await fetch(`${s}/api/icoa/snapshot`,{method:"POST",headers:p,body:JSON.stringify(l),signal:AbortSignal.timeout(8e3)})}catch{}}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as t,readFileSync as r,writeFileSync as a}from"node:fs";import{homedir as n}from"node:os";import{join as o}from"node:path";const s=o(n(),".icoa"),c=o(s,"learn-state.json");export function loadLearnState(){if(!e(c))return null;try{return JSON.parse(r(c,"utf-8"))}catch{return null}}export function saveLearnState(r){e(s)||t(s,{recursive:!0}),r.lastSeenAt=(new Date).toISOString(),a(c,JSON.stringify(r,null,2))}export function newLearnState(e,t,r){const a=(new Date).toISOString();return{token:e,curriculumId:t,currentCard:1,totalCards:r,startedAt:a,lastSeenAt:a,streakDays:1,longestStreak:1,cardsCompleted:[],mcqResults:{},checkResults:{},practicalsCompleted:[],bookmarks:[],achievements:[],totalSecondsActive:0}}export function updateStreak(e){const t=new Date(e.lastSeenAt),r=new Date,a=Math.floor(t.getTime()/864e5),n=Math.floor(r.getTime()/864e5)-a;0!==n&&(1===n?(e.streakDays+=1,e.streakDays>e.longestStreak&&(e.longestStreak=e.streakDays)):e.streakDays=1)}export function markCardComplete(e,t){e.cardsCompleted.includes(t)||e.cardsCompleted.push(t)}export function recordMCQ(e,t,r){e.mcqResults[String(t)]=r}export function recordCheck(e,t,r){e.checkResults||(e.checkResults={}),e.checkResults[String(t)]=r}export function markPracticalComplete(e,t){e.practicalsCompleted.includes(t)||e.practicalsCompleted.push(t)}export function addAchievement(e,t){e.achievements.includes(t)||e.achievements.push(t)}
1
+ import{join as e}from"node:path";import{getIcoaDir as t,getInstallSalt as r}from"./config.js";import{deriveFileKey as a,readSignedFile as n,writeSignedFile as o,recordVerdict as s}from"./secure-store.js";const c="learn-state";function i(){return e(t(),"learn-state.json")}function l(){return a(r(),c)}export function loadLearnState(){const{data:e,verdict:t}=n(i(),l());return s(c,t),e}export function saveLearnState(e){e.lastSeenAt=(new Date).toISOString(),o(i(),e,l())}export function newLearnState(e,t,r){const a=(new Date).toISOString();return{token:e,curriculumId:t,currentCard:1,totalCards:r,startedAt:a,lastSeenAt:a,streakDays:1,longestStreak:1,cardsCompleted:[],mcqResults:{},checkResults:{},practicalsCompleted:[],bookmarks:[],achievements:[],totalSecondsActive:0}}export function updateStreak(e){const t=new Date(e.lastSeenAt),r=new Date,a=Math.floor(t.getTime()/864e5),n=Math.floor(r.getTime()/864e5)-a;0!==n&&(1===n?(e.streakDays+=1,e.streakDays>e.longestStreak&&(e.longestStreak=e.streakDays)):e.streakDays=1)}export function markCardComplete(e,t){e.cardsCompleted.includes(t)||e.cardsCompleted.push(t)}export function recordMCQ(e,t,r){e.mcqResults[String(t)]=r}export function recordCheck(e,t,r){e.checkResults||(e.checkResults={}),e.checkResults[String(t)]=r}export function markPracticalComplete(e,t){e.practicalsCompleted.includes(t)||e.practicalsCompleted.push(t)}export function addAchievement(e,t){e.achievements.includes(t)||e.achievements.push(t)}
@@ -1 +1 @@
1
- import{readFileSync as t,existsSync as n,writeFileSync as e,chmodSync as s}from"node:fs";import{join as i}from"node:path";import{getIcoaDir as o,getConfig as c}from"./config.js";import{getDeviceFingerprint as r}from"./access.js";import{getCliVersion as a}from"./version.js";const l=()=>i(o(),"sync-state.json");let u=null;function f(t){const n=l();e(n,JSON.stringify(t,null,2));try{s(n,384)}catch{}}async function y(){const e=c(),s=e.ctfdUrl||"https://practice.icoa2026.au",u=i(o(),"session.log");if(!n(u))return;const y=function(){const e=l();if(!n(e))return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0};try{const n=JSON.parse(t(e,"utf-8"));return{lastSyncedLine:n.lastSyncedLine??0,lastSyncAt:n.lastSyncAt??null,syncCount:n.syncCount??0,failCount:n.failCount??0,seq:n.seq??0}}catch{return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0}}}(),d=t(u,"utf-8").trim().split("\n").filter(Boolean);d.length<y.lastSyncedLine&&(y.lastSyncedLine=0);const p=d.slice(y.lastSyncedLine);if(0===p.length)return;const S={"Content-Type":"application/json"};let m;if(e.token)S.Authorization=`Token ${e.token}`,m=`user:${e.userId??"unknown"}`;else{const t=e.deviceFingerprint||r();S["X-Device-Fingerprint"]=t,m=`demo:${t.slice(0,12)}`}const g=y.seq??0,h=p.map((t,n)=>{let e;try{e=JSON.parse(t)}catch{e={raw:t}}return{...e,_seq:g+n+1}}),C=a(),I=h.map(t=>({...t,_cli:C})),L={identity:m,userId:e.userId,userName:e.userName,teamId:e.teamId,sessionId:e.sessionId,deviceFingerprint:e.deviceFingerprint||r(),lang:e.language||"en",clientVersion:C,timestamp:(new Date).toISOString(),seqRange:{from:g+1,to:g+h.length},entries:I};try{const t=new URL("/api/icoa/audit",s).href;(await fetch(t,{method:"POST",headers:S,body:JSON.stringify(L),signal:AbortSignal.timeout(1e4)})).ok?(y.lastSyncedLine=d.length,y.lastSyncAt=(new Date).toISOString(),y.syncCount++,y.seq=g+h.length,f(y)):(y.failCount++,f(y))}catch{y.failCount++,f(y)}}export function startLogSync(){setTimeout(()=>y(),5e3),u=setInterval(()=>y(),3e4)}export function stopLogSync(){u&&(clearInterval(u),u=null),y()}
1
+ import{readFileSync as t,existsSync as n,writeFileSync as e,chmodSync as s}from"node:fs";import{join as i}from"node:path";import{getIcoaDir as o,getConfig as a,getInstallSalt as c}from"./config.js";import{getDeviceFingerprint as r}from"./access.js";import{getCliVersion as l}from"./version.js";const u=()=>i(o(),"sync-state.json");let f=null;function y(t){const n=u();e(n,JSON.stringify(t,null,2));try{s(n,384)}catch{}}async function d(){const e=a(),s=e.ctfdUrl||"https://practice.icoa2026.au",f=i(o(),"session.log");if(!n(f))return;const d=function(){const e=u();if(!n(e))return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0};try{const n=JSON.parse(t(e,"utf-8"));return{lastSyncedLine:n.lastSyncedLine??0,lastSyncAt:n.lastSyncAt??null,syncCount:n.syncCount??0,failCount:n.failCount??0,seq:n.seq??0}}catch{return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0}}}(),S=t(f,"utf-8").trim().split("\n").filter(Boolean);S.length<d.lastSyncedLine&&(d.lastSyncedLine=0);const p=S.slice(d.lastSyncedLine);if(0===p.length)return;const m={"Content-Type":"application/json"};let g;if(e.token)m.Authorization=`Token ${e.token}`,g=`user:${e.userId??"unknown"}`;else{const t=e.deviceFingerprint||r();m["X-Device-Fingerprint"]=t,g=`demo:${t.slice(0,12)}`}const h=d.seq??0,C=p.map((t,n)=>{let e;try{e=JSON.parse(t)}catch{e={raw:t}}return{...e,_seq:h+n+1}}),I=l(),L=C.map(t=>({...t,_cli:I})),q={identity:g,userId:e.userId,userName:e.userName,teamId:e.teamId,sessionId:e.sessionId,deviceFingerprint:e.deviceFingerprint||r(),installSalt:e.installSalt||c(),lang:e.language||"en",clientVersion:I,timestamp:(new Date).toISOString(),seqRange:{from:h+1,to:h+C.length},entries:L};try{const t=new URL("/api/icoa/audit",s).href;(await fetch(t,{method:"POST",headers:m,body:JSON.stringify(q),signal:AbortSignal.timeout(1e4)})).ok?(d.lastSyncedLine=S.length,d.lastSyncAt=(new Date).toISOString(),d.syncCount++,d.seq=h+C.length,y(d)):(d.failCount++,y(d))}catch{d.failCount++,y(d)}}export function startLogSync(){setTimeout(()=>d(),5e3),f=setInterval(()=>d(),3e4)}export function stopLogSync(){f&&(clearInterval(f),f=null),d()}
@@ -1,4 +1,12 @@
1
1
  import type { LogEntry } from '../types/index.js';
2
+ /** Test-only: force the next currentLastMac() call to re-seed from the log
3
+ * tail, simulating a fresh process picking up an existing session.log. */
4
+ export declare function __resetChainHeadForTest(): void;
5
+ export declare function chainMac(prevMac: string, entry: object, key: Buffer): string;
6
+ export declare function verifyChain(entries: Array<Record<string, unknown>>, startMac: string, key: Buffer): {
7
+ ok: boolean;
8
+ brokenAt: number;
9
+ };
2
10
  export declare function logCommand(command: string): void;
3
11
  export declare function logSubmission(challengeId: number, flag: string): void;
4
12
  export declare function getSessionLog(): LogEntry[];
@@ -1 +1 @@
1
- import{appendFileSync as t,readFileSync as n,existsSync as o}from"node:fs";import{join as e}from"node:path";import{getConfig as i,getIcoaDir as s}from"./config.js";function r(){return e(s(),"session.log")}function m(n){try{t(r(),`${JSON.stringify(n)}\n`)}catch{}}export function logCommand(t){const n=i();m({timestamp:(new Date).toISOString(),level:"command",input:t,sessionId:n.sessionId})}export function logSubmission(t,n){const o=i();m({timestamp:(new Date).toISOString(),level:"submit",input:n,challengeId:t,sessionId:o.sessionId})}export function getSessionLog(){const t=r();if(!o(t))return[];try{return n(t,"utf-8").trim().split("\n").filter(Boolean).map(t=>JSON.parse(t))}catch{return[]}}
1
+ import{appendFileSync as t,readFileSync as n,existsSync as e}from"node:fs";import{join as o}from"node:path";import{createHmac as r}from"node:crypto";import{getConfig as i,getIcoaDir as s,getInstallSalt as c}from"./config.js";import{deriveFileKey as a,canonicalize as u}from"./secure-store.js";import{consumeLineDynamics as l}from"./input-dynamics.js";function m(){return o(s(),"session.log")}let f=null;export function __resetChainHeadForTest(){f=null}export function chainMac(t,n,e){const o={...n};return delete o._mac,r("sha256",e).update(t).update("\n").update(u(o)).digest("hex")}export function verifyChain(t,n,e){let o=n;for(let n=0;n<t.length;n++){const r=chainMac(o,t[n],e);if(t[n]._mac!==r)return{ok:!1,brokenAt:n};o=r}return{ok:!0,brokenAt:-1}}function p(e){try{const o=a(c(),"session-log"),r=chainMac(function(){if(null!==f)return f;try{const t=n(m(),"utf-8").split("\n").filter(t=>t.trim().length>0),e=t[t.length-1],o=JSON.parse(e);f=o._mac??""}catch{f=""}return f}(),e,o),i={...e,_mac:r};t(m(),`${JSON.stringify(i)}\n`),f=r}catch{try{t(m(),`${JSON.stringify(e)}\n`)}catch{}f=null}}export function logCommand(t){const n=i();p({timestamp:(new Date).toISOString(),level:"command",input:t,sessionId:n.sessionId,dyn:l()})}export function logSubmission(t,n){const e=i();p({timestamp:(new Date).toISOString(),level:"submit",input:n,challengeId:t,sessionId:e.sessionId,dyn:l()})}export function getSessionLog(){const t=m();if(!e(t))return[];try{return n(t,"utf-8").trim().split("\n").filter(Boolean).map(t=>JSON.parse(t))}catch{return[]}}
@@ -0,0 +1,18 @@
1
+ export type IntegrityVerdict = 'ok' | 'tampered' | 'unsigned' | 'absent' | 'corrupt';
2
+ export interface SigBlock {
3
+ v: 1;
4
+ alg: 'HS256';
5
+ mac: string;
6
+ ts: string;
7
+ }
8
+ export declare function deriveFileKey(installSalt: string, fileId: string): Buffer;
9
+ export declare function canonicalize(obj: unknown): string;
10
+ export declare function signObject(payload: object, key: Buffer): SigBlock;
11
+ export declare function verifyObject(payloadWithSig: object, key: Buffer): IntegrityVerdict;
12
+ export declare function writeSignedFile(path: string, payload: object, key: Buffer): void;
13
+ export declare function readSignedFile<T>(path: string, key: Buffer): {
14
+ data: T | null;
15
+ verdict: IntegrityVerdict;
16
+ };
17
+ export declare function recordVerdict(fileId: string, verdict: IntegrityVerdict): void;
18
+ export declare function collectVerdicts(): Record<string, IntegrityVerdict>;
@@ -0,0 +1 @@
1
+ import{writeFileSync as e,readFileSync as t,existsSync as r,chmodSync as n}from"node:fs";import{hkdfSync as o,createHmac as i,timingSafeEqual as c}from"node:crypto";export function deriveFileKey(e,t){const r=o("sha256",Buffer.from(e,"utf-8"),Buffer.from("icoa-secure-store-v1"),Buffer.from(t),32);return Buffer.from(r)}export function canonicalize(e){const t=new Set,r=e=>{if(null===e||"object"!=typeof e)return e;if(t.has(e))return null;let n;if(t.add(e),Array.isArray(e))n=e.map(r);else{const t=e,o={};for(const e of Object.keys(t).sort())"_sig"!==e&&(o[e]=r(t[e]));n=o}return t.delete(e),n};return JSON.stringify(r(e))}function f(e,t){return i("sha256",t).update(canonicalize(e)).digest("hex")}export function signObject(e,t){return{v:1,alg:"HS256",mac:f(e,t),ts:(new Date).toISOString()}}export function verifyObject(e,t){const r=e._sig;if(!r||"string"!=typeof r.mac)return"unsigned";const n=f(e,t),o=Buffer.from(r.mac,"hex"),i=Buffer.from(n,"hex");return o.length!==i.length?"tampered":c(o,i)?"ok":"tampered"}export function writeSignedFile(t,r,o){const i={...r};delete i._sig;const c=signObject(i,o);e(t,JSON.stringify({...i,_sig:c},null,2));try{n(t,384)}catch{}}export function readSignedFile(e,n){if(!r(e))return{data:null,verdict:"absent"};let o;try{o=JSON.parse(t(e,"utf-8"))}catch{return{data:null,verdict:"corrupt"}}const i=verifyObject(o,n),c={...o};return delete c._sig,{data:c,verdict:i}}const u=new Map,s={ok:0,absent:0,unsigned:1,corrupt:2,tampered:3};export function recordVerdict(e,t){if(0===s[t])return;const r=u.get(e);(!r||s[t]>s[r])&&u.set(e,t)}export function collectVerdicts(){return Object.fromEntries(u)}
@@ -1 +1 @@
1
- import{mkdirSync as t,readFileSync as n,writeFileSync as o}from"node:fs";import{join as r}from"node:path";import{homedir as e}from"node:os";export const COOLDOWN_SECONDS=60;const l=r(e(),".icoa","sim-cooldown.json");function a(){try{const t=n(l,"utf-8"),o=JSON.parse(t);return"object"==typeof o&&null!==o?o:{}}catch{return{}}}function s(n){try{t(r(e(),".icoa"),{recursive:!0});const s={...a(),...n};o(l,JSON.stringify(s))}catch{}}export function lastSimAt(){const t=a();return"number"==typeof t.lastCallAt?t.lastCallAt:0}export function markSimAt(t){s({lastCallAt:t})}export function cooldownRemaining(){const t=(Date.now()-lastSimAt())/1e3;return Math.max(0,Math.ceil(60-t))}export function lastBundledAt(){const t=a();return"number"==typeof t.lastBundledAt?t.lastBundledAt:0}export function markBundledAt(t){s({lastBundledAt:t})}export function lastArmAt(){const t=a();return"number"==typeof t.lastArmAt?t.lastArmAt:0}export function markArmAt(t){s({lastArmAt:t})}export function hasAnySimHistory(){const t=a();return"number"==typeof t.lastBundledAt&&t.lastBundledAt>0||"number"==typeof t.lastCallAt&&t.lastCallAt>0||"number"==typeof t.lastArmAt&&t.lastArmAt>0}
1
+ import{join as t}from"node:path";import{getIcoaDir as n,getInstallSalt as o}from"./config.js";import{deriveFileKey as r,readSignedFile as e,writeSignedFile as l,recordVerdict as a}from"./secure-store.js";export const COOLDOWN_SECONDS=60;const s="sim-cooldown";function u(){return t(n(),"sim-cooldown.json")}function c(){return r(o(),s)}function m(){try{const{data:t,verdict:n}=e(u(),c());return a(s,n),t||{}}catch{return{}}}function A(t){try{const n={...m(),...t};l(u(),n,c())}catch{}}export function lastSimAt(){const t=m();return"number"==typeof t.lastCallAt?t.lastCallAt:0}export function markSimAt(t){A({lastCallAt:t})}export function cooldownRemaining(){const t=(Date.now()-lastSimAt())/1e3;return Math.max(0,Math.ceil(60-t))}export function lastBundledAt(){const t=m();return"number"==typeof t.lastBundledAt?t.lastBundledAt:0}export function markBundledAt(t){A({lastBundledAt:t})}export function lastArmAt(){const t=m();return"number"==typeof t.lastArmAt?t.lastArmAt:0}export function markArmAt(t){A({lastArmAt:t})}export function hasAnySimHistory(){const t=m();return"number"==typeof t.lastBundledAt&&t.lastBundledAt>0||"number"==typeof t.lastCallAt&&t.lastCallAt>0||"number"==typeof t.lastArmAt&&t.lastArmAt>0}
package/dist/repl.js CHANGED
@@ -1 +1 @@
1
- import{createInterface as o}from"node:readline";import{spawn as e,execSync as t}from"node:child_process";import chalk from"chalk";import{isConnected as n,getConfig as l,saveConfig as a}from"./lib/config.js";import{ensureLangCache as s}from"./lib/translations-fetcher.js";import{loadUiPack as r}from"./lib/i18n.js";import{isActivated as i,activateToken as c,isFreeCommand as g,isDeviceMatch as y,recordExit as m,recordResume as d,isFirstRunOrUpgrade as p,markVersionSeen as u}from"./lib/access.js";import{setReplMode as h}from"./lib/ui.js";import{returnToMainMenu as w,printMenuHint as f,menuHintInline as b}from"./lib/menu-nav.js";import{setMainRl as x}from"./lib/main-rl.js";import{shellSplit as v}from"./lib/shell-split.js";import{isChatActive as C,handleChatMessage as A}from"./commands/ai4ctf.js";import{renderToolMan as k}from"./lib/tool-man.js";import{isCtf4aiActive as I,handleCtf4aiMessage as $}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as T,handleCtf4VlaMessage as E}from"./commands/ctf4vla.js";import{isDemo2Active as S}from"./commands/demo2.js";import{loadDemo2Progress as O}from"./lib/demo2-progress.js";import{hasAnySimHistory as j,lastArmAt as N,lastBundledAt as L,lastSimAt as D}from"./lib/sim-cooldown.js";import{getExamState as R,getRealExamState as P,getDemoState as q,practicalChatCommand as F}from"./lib/exam-state.js";import{resolveResumePoint as M}from"./lib/resume.js";import{buildStatusLine as U}from"./lib/statusline.js";import{startBgTask as _,startAsyncTask as B,listBgTasks as W,getBgTask as Q,drainCompleted as Y,killAllBgTasks as z,runningCount as X}from"./lib/bgtasks.js";import{computeStart as J,renderStart as V}from"./commands/challenge.js";import{addDraft as G,listDrafts as H,removeDraft as Z,clearDrafts as K}from"./lib/drafts.js";import{resetTerminalTheme as oo}from"./lib/theme.js";import{ensureSandbox as eo,runInSandbox as to,isDockerAvailable as no}from"./lib/sandbox.js";import{checkShellRisk as lo,logShellAudit as ao,getActiveCwd as so}from"./lib/exam-sandbox.js";import{logCommand as ro}from"./lib/logger.js";import{startLogSync as io,stopLogSync as co}from"./lib/log-sync.js";import{startBroadcastPoll as go,stopBroadcastPoll as yo,showBroadcast as mo,isCompetitionJoined as po,isMelCompetition as uo,isLeaderAccount as ho,isLeaderSession as wo,fetchPublicScoreboard as fo,isCommsActive as bo}from"./lib/comms.js";import{enterMemoScreen as xo,enterJuryScreen as vo}from"./commands/comms.js";import{existsSync as Co,mkdirSync as Ao,readFileSync as ko,writeFileSync as Io}from"node:fs";import{join as $o}from"node:path";import{homedir as To}from"node:os";const Eo="# ICOA exam interactive startup — auto-loaded by PYTHONSTARTUP\nimport base64, struct, hashlib, re, json, os, sys, binascii\ntry: import requests\nexcept ImportError: pass\ntry: from Crypto.Cipher import AES\nexcept ImportError: pass\ntry: from Crypto.Util.Padding import pad, unpad\nexcept ImportError: pass\ntry: from pwn import xor, p32, u32, p64, u64\nexcept ImportError: pass\ntry: import bs4\nexcept ImportError: pass\ntry: import numpy as np\nexcept ImportError: pass\ntry: from PIL import Image\nexcept ImportError: pass\n",So=Date.now();function Oo(){return uo()?chalk.yellow("icoa 2026> "):P()?chalk.cyan("icoa exam> "):function(){const o=q();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=So}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const jo=$o(To(),"icoa-workspace"),No=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),Lo="__REPL_NO_EXIT__",Do="2.5.1",Ro=["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","learn","demo2","ctf4eai","ctf4vla","theme","sim","arena","eai","learn-pull","doctor","bg","tasks","drafts","help","menu","quit","q","exit","back","resume"],Po={exam:["list","start","q","answer","submit","review","result","next","prev","mark","unmark","help"],ctf:["challenges","open","submit","scoreboard","status","join","logout","time"],challenge:["start","stop","status"],arena:["eai"],learn:["start","continue"]};function qo(o){const e=o.replace(/^\s+/,"");if(/^\/\S*$/.test(e)){const o=e.slice(1).toLowerCase();return[Ro.filter(e=>e.startsWith(o)).map(o=>`/${o}`),e]}const t=e.split(/\s+/);if(t.length<=1){const o=(t[0]??"").toLowerCase();return[Ro.filter(e=>e.startsWith(o)).slice(),o]}if(2===t.length){const o=Po[t[0].toLowerCase()];if(o){const e=t[1].toLowerCase();return[o.filter(o=>o.startsWith(e)).slice(),e]}}return[[],o]}async function Fo(o){const e=M();if(!e)return null;const t=process.exit;process.exit=()=>{throw new Error(Lo)};try{await o.parseAsync(["node","icoa",...e.command])}catch(o){if(!(o instanceof Error&&o.message===Lo))throw o}finally{process.exit=t}return e}function Mo(){console.log(),console.log(` ${chalk.cyan.bold("🎯 ICOA 2026 · National Selection")}`),console.log(),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("ACxxxxxxxx")+chalk.gray(" → ai4ctf-12 (AI as your CTF teammate)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("CAxxxxxxxx")+chalk.gray(" → ctf4ai-12 (red-team software AI)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("EAxxxxxxxx")+chalk.gray(" → ctf4eai-12 (red-team embodied AI)")),console.log(" "+chalk.bold.cyan("exam ")+chalk.white("<CC>xxxxxxxx")+chalk.gray(" → Paper A/B/C/D/E (country exam token)")),console.log(" "+chalk.bold.cyan("demo")+chalk.gray(" → free practice")),console.log(" "+chalk.bold.cyan("lang")+chalk.white(" es")+chalk.gray(" → switch language")),console.log(" "+chalk.gray("help · menu · quit")),console.log()}export async function startRepl(e,q){process.env.ICOA_INSIDE_REPL="1";let So=!1;if(uo()){const o=l().joinedAt,e=o=>new Intl.DateTimeFormat("en-CA",{timeZone:"Australia/Sydney",year:"numeric",month:"2-digit",day:"2-digit"}).format(o);o&&e(new Date(o))===e(new Date)||(a({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:"",joinedAt:""}),So=!0)}const Po=l(),Bo=n(),Wo=process.exit.bind(process),Qo=i();if(Po.language&&"en"!==Po.language&&(await s(Po.language,{silent:!0}),r(Po.language)),Po.demoCleanedForVersion!==Do){try{const{existsSync:o,unlinkSync:e}=await import("node:fs"),{join:t}=await import("node:path"),{getIcoaDir:n}=await import("./lib/config.js"),l=t(n(),"demo-state.json");o(l)&&e(l)}catch{}a({demoCleanedForVersion:Do})}const{select:Yo,confirm:zo}=await import("@inquirer/prompts"),Xo=Po.mode||"",Jo=""===Xo?"instant":["instant","learn","selection","olympiad"].includes(Xo)?Xo:"selection",Vo=[{name:` ${chalk.bold("⚡ Try ICOA in 30 seconds")} ${chalk.gray("—")} ${chalk.gray("watch · no token needed")}`,value:"instant"},{name:` ${chalk.bold("🧠 Learn")} ${chalk.gray("—")} ${chalk.gray("AC / CA / EA token · skill up")}`,value:"learn"},{name:` ${chalk.bold("🎯 National Selection")} ${chalk.gray("—")} ${chalk.gray("country exam token · aim for finals")}`,value:"selection"},{name:` ${chalk.bold("🏆 International Olympiad")} ${chalk.gray("—")} ${chalk.gray("finals stage · Sydney 2026 · full sandbox")}`,value:"olympiad"},{name:` ${chalk.gray("ℹ️ About ICOA")} ${chalk.gray("·")} ${chalk.gray("what this is · how to join")}`,value:"about"}];""===Xo&&(console.log(chalk.green(" 👋 First time here? ")+chalk.white("Just press ")+chalk.bold.cyan("Enter")+chalk.white(" — you’ll see ICOA in 30 seconds, no signup needed.")),console.log()),console.log(chalk.gray(" Type ")+chalk.bold.cyan("menu")+chalk.gray(" from anywhere to return here.")),console.log();let Go="";for(;!Go;){let o;try{o=await Yo({message:"Mode",choices:Vo,default:Jo||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}"about"!==o?Go=o:(console.clear(),console.log(),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(chalk.bold.yellow(" ICOA")+chalk.white(" — AI-Native CLI OS for Cyber & AI Security")),console.log(chalk.gray(" Olympiad & Competition · K-12 to University")),console.log(chalk.cyan(" ───────────────────────────────────────────────────")),console.log(),console.log(chalk.bold.white(" What Makes ICOA Different")),console.log(chalk.gray(" · AI-native AI teammate, AI adversary, AI translation")),console.log(chalk.gray(" · CLI OS Complete competition environment in terminal")),console.log(chalk.gray(" · 110 tools pwntools, z3, gdb, nmap, sleuthkit... pre-configured")),console.log(chalk.gray(" · Global scale 15,000+ concurrent exams · 15 languages")),console.log(),console.log(chalk.bold.white(" Competition Format (2-day standard + 1-day Pioneer)")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" [Day 1] AI as teammate — speed track, dynamic decay + top-3 bonus")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" [Day 2] AI as target — knowledge track, static value per challenge")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" [Pioneer / Practical Round] Embodied AI — VLA + world models + sim-to-real")}`),console.log(),console.log(chalk.bold.white(" Scoring (in brief)")),console.log(chalk.gray(" · Standard medals: AI4CTF + CTF4AI combined · 1/12 Gold · 2/12 Silver · 3/12 Bronze")),console.log(chalk.gray(" · HMA: top 50% on either day, total below bronze cutoff")),console.log(chalk.gray(" · CTF4EAI: separate 15-finalist pool, G/S/B + 12 Finalist Awards")),console.log(),console.log(chalk.white(" Sydney, Australia")+chalk.gray(" · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.bold.white(" Organized by")+chalk.gray(" ASRA (Australia) · ICO Foundation Inc")),console.log(chalk.bold.white(" Contact ")+chalk.cyan(" australia@icoa2026.au · accreditation@icoa2026.au")),console.log(chalk.bold.white(" Website ")+chalk.cyan.underline(" https://icoa2026.au")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(),console.log(chalk.gray(" Press ")+chalk.yellow("Enter")+chalk.gray(" to return...")),await new Promise(o=>{const e=t=>{process.stdin.removeListener("data",e),process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!1),process.stdin.pause(),o()};process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.once("data",e)}),console.clear())}if("olympiad"===Go&&"olympiad"!==Jo){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await zo({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(Go="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(Go!==Jo&&a({mode:Go}),console.log(),"olympiad"===Go&&p(Do)){u(Do),console.log(chalk.gray(" Checking competition environment..."));const{execSync:o}=await import("node:child_process"),e=[{name:"pwntools",cmd:'python3 -c "import pwn"'},{name:"z3-solver",cmd:'python3 -c "import z3"'},{name:"numpy",cmd:'python3 -c "import numpy"'},{name:"requests",cmd:'python3 -c "import requests"'}];let t=0;for(const n of e)try{o(n.cmd,{stdio:"ignore"})}catch{t++}t>0?(console.log(chalk.yellow(` ${t} core competition libraries missing.`)),console.log(chalk.gray(" Run ")+chalk.white("env setup")+chalk.gray(" when you are ready to install them.")),console.log()):(console.log(chalk.green(" All core libraries ready.")),console.log())}if(q){const o=d();if(o){const e=Math.floor(o.awaySeconds/60),t=o.awaySeconds%60;console.log(chalk.yellow(` Session resumed. Away: ${e}m ${t}s | Total exits: ${o.exitCount}`)),console.log()}}if("selection"===Go)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),Mo();else if("embodied"===Go)!function(){console.log(chalk.cyan.bold(" [🤖 ctf4eai — Embodied AI Security]")),console.log(),console.log(chalk.bold.cyan(" CTF4EAI")+chalk.gray(" — ICOA 2026's ")+chalk.bold.white("Pioneer Round")),console.log(chalk.gray(" an independent parallel track alongside the scored main events: ")+chalk.green("AI4CTF")+chalk.gray(" (Day 1) and ")+chalk.red("CTF4AI")+chalk.gray(" (Day 2)")),console.log(),console.log(chalk.white(" Embodied AI is at its ImageNet moment.")),console.log(chalk.gray(" VLA models, MuJoCo physics, real robot arms.")),console.log(chalk.gray(" Real models, real physics, real attack surfaces.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const o=L()>0||D()>0,e=N()>0,t=j(),n=O(),l=null!==n&&"number"==typeof n.completedAt&&n.nextCardIndex>=n.totalCards,a=null!==n&&!l;if(l)console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (demo2 ✓ · sim")+(e?chalk.gray(" ✓ · sim arm ✓)"):chalk.gray(")")));else if(a){const o=`${n.nextCardIndex} / ${n.totalCards}`;console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" (last left at card ")+chalk.bold.yellow(o)+chalk.gray(")"))}else o&&e?console.log(chalk.bold.yellow(" Next up: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (sim ✓ · sim arm ✓)")):t?console.log(chalk.bold.yellow(" Next up: ")+(e?chalk.bold.cyan("① sim")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2"):chalk.bold.cyan("② sim arm")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2"))+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")):console.log(chalk.bold.yellow(" First time? Try in order: ")+chalk.bold.cyan("① sim")+chalk.gray(" → ")+chalk.bold.cyan("② sim arm")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01"));console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.bold.green(" sim")+chalk.gray(" ")+chalk.bold.cyan("①")+chalk.gray(" ")+chalk.bold.yellow("★ INSTANT")+chalk.gray(" — 9-robot group dance, no wait, no setup")),console.log(chalk.bold.green(" sim arm")+chalk.gray(" ")+chalk.bold.cyan("②")+chalk.gray(" interactive 6-DOF arm sandbox — type joint values, watch")),console.log(chalk.bold.green(" demo2")+chalk.gray(" ")+chalk.bold.cyan("③")+chalk.gray(" ~8 min interactive intro + live MuJoCo sim")),console.log(chalk.bold.green(" learn LEARNDEMO01")+chalk.gray(" ")+chalk.bold.cyan("④")+chalk.gray(" free 11-card intro (paste this command as-is)")),console.log(chalk.bold.green(" learn ")+chalk.bold.yellow("EA")+chalk.gray(" + 8 chars full 96 / 360 curriculum (team-issued)")),console.log(chalk.bold.green(" exam ")+chalk.bold.yellow("PDxxxxxxxx")+chalk.gray(" Paper D (CTF4EAI) — national selection contestants")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),console.log(chalk.gray(" Three open tiers: ")+chalk.green("free 11")+chalk.gray(" · ")+chalk.yellow("registered 100")+chalk.gray(" · ")+chalk.bold.magenta("national team 480")+chalk.gray(" (PhD-ready)")),console.log(chalk.gray(" Country team contact: ")+chalk.cyan("australia@icoa2026.au")),console.log(),f(),console.log()}();else if("instant"===Go)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Two free tastes — just type the word and press Enter:")),console.log(),console.log(chalk.bold.green(" demo ")+chalk.gray(" Paper A/B/C taste — 10 MCQs, no timer ")+chalk.bold.cyan("🎯 selection-style")),console.log(chalk.bold.green(" demo2")+chalk.gray(" Embodied-AI mini-demo — robots & MuJoCo ")+chalk.bold.yellow("🤖 hands-on")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(" or ")+chalk.bold.cyan("demo2")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),a({mode:"selection"}),Go="selection";else{if("learn"===Go){console.log(chalk.cyan.bold(" [🧠 Learn]")),console.log(),console.log(chalk.gray(" Three tracks · same difficulty curve.")),console.log(),console.log(chalk.white(" Free 12-card demos — paste the full command:")),console.log(),console.log(chalk.gray(" 🤝 ai4ctf AI as your teammate ")+chalk.bold.yellow("learn AI4CTFDEMO01")),console.log(chalk.gray(" 🔓 ctf4ai AI as your target ")+chalk.bold.yellow("learn CTF4AIDEMO01")),console.log(chalk.gray(" 🤖 ctf4eai Embodied AI Security ")+chalk.bold.yellow("learn LEARNDEMO01")),console.log(),console.log(chalk.gray(" Got a cohort token? Type ")+chalk.bold.yellow("learn <TOKEN>")+chalk.gray(" (e.g. ")+chalk.bold.yellow("learn EAABCD1234")+chalk.gray(").")),console.log();try{const{input:o}=await import("@inquirer/prompts"),{resolveLearnInput:t}=await import("./lib/learn-input.js");console.log(chalk.gray(" Enter a token (or just press Enter to go back).")),console.log();const n=t(await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}));if("token"===n.kind){console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${n.token}`)),console.log(),a({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";try{await e.parseAsync(["node","icoa","learn",n.token])}finally{delete process.env.ICOA_LEARN_EMBEDDED}}else"ambiguous"!==n.kind&&"unknown"!==n.kind||(console.log(),console.log(chalk.yellow(" "+n.hint)),console.log(chalk.gray(" Returning to main menu — pick 🧠 Learn again to retry.")),console.log())}catch{}return a({mode:"selection"}),void w()}"organizer"===Go?(console.log(chalk.yellow.bold(" [National/Regional Partner]")),console.log(),console.log(chalk.bold.white(" ██╗ ██████╗ ██████╗ █████╗")),console.log(chalk.bold.white(" ██║██╔════╝██╔═══██╗██╔══██╗")),console.log(chalk.bold.white(" ██║██║ ██║ ██║███████║")),console.log(chalk.bold.white(" ██║██║ ██║ ██║██╔══██║")),console.log(chalk.bold.white(" ██║╚██████╗╚██████╔╝██║ ██║")),console.log(chalk.bold.white(" ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝")),console.log(),console.log(chalk.yellow(" International Cyber Olympiad in AI 2026")),console.log(chalk.bold.magenta(" The World's First AI-Native CLI Operating System")),console.log(chalk.bold.magenta(" for Cybersecurity & AI Security Competition")),console.log(chalk.bold.magenta(" and Olympiad for K-12")),console.log(chalk.gray(" Sydney, Australia · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.white(" Vision")),console.log(chalk.gray(" Building a global pipeline for youth cyber & AI")),console.log(chalk.gray(" security talent through education and competition.")),console.log(),console.log(chalk.white(" Capacity")),console.log(chalk.gray(" 15,000+ concurrent online examinations")),console.log(chalk.gray(" National selection, training, and education support")),console.log(),console.log(chalk.white(" Olympic Spirit")),console.log(chalk.gray(" Excellence · Friendship · Respect")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" New country accreditation & support:")),console.log(chalk.cyan(" australia@icoa2026.au")),console.log(chalk.cyan(" accreditation@icoa2026.au")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),Bo?(console.log(chalk.green(` Logged in as ${Po.userName}`)),console.log(chalk.white(" exam list")+chalk.gray(" Manage exams")),console.log(chalk.white(" logout")+chalk.gray(" Disconnect"))):console.log(chalk.white(" join <url>")+chalk.gray(" Connect to manage exams")),console.log(),f(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),Qo&&!y()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):Bo?(console.log(chalk.green.bold(` Welcome back, ${Po.userName}!`)),console.log(chalk.gray(` Connected to ${Po.ctfdUrl}`)),console.log(chalk.gray(" Not you? Type ")+chalk.cyan("logout")+chalk.gray(" to switch accounts")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Ready to compete? Start here:")),console.log(),console.log(chalk.bold.cyan(" challenges")+chalk.gray(" Browse challenges by category")),console.log(chalk.white(" status")+chalk.gray(" Your score & timer")),console.log(chalk.white(" scoreboard")+chalk.gray(" Live rankings")),console.log(chalk.white(" memo")+chalk.gray(" Report an issue to organizers (one-way)")),console.log(),console.log(chalk.gray(" Tool environment:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.bold.yellow(" ★ ")+chalk.bold.cyan("man <tool>")+chalk.gray(" How to USE a tool (steghide, nmap…) · ")+chalk.cyan("man tools")+chalk.gray(" = list")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("help")+chalk.gray(" · ")+b()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):Qo?(Co(jo)||Ao(jo,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${jo}`)),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Get started:")),console.log(),console.log(chalk.white(" Step 1 ")+chalk.bold.cyan("join <url>")+chalk.gray(" Connect to competition server")),console.log(chalk.white(" Step 2 ")+chalk.bold.cyan("challenges")+chalk.gray(" Browse & solve challenges")),console.log(chalk.white(" Step 3 ")+chalk.bold.cyan("ai4ctf")+chalk.gray(" Ask AI when stuck")),console.log(),console.log(chalk.gray(" Before Step 1 — make sure your tools are ready:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.bold.yellow(" ★ ")+chalk.bold.cyan("man <tool>")+chalk.gray(" How to USE a tool (steghide, nmap…) · ")+chalk.cyan("man tools")+chalk.gray(" = list")),console.log(),console.log(chalk.gray(" Also: ")+chalk.white("help")+chalk.gray(" all commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+b()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()):(console.log(chalk.bold.yellow(" 🏆 You reached the finals tier.")),console.log(chalk.gray(" Full sandbox · 110 CTF tools · Sydney 2026 · this is where finalists compete.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" To begin, activate your competition token:")),console.log(),console.log(chalk.bold.cyan(" activate <token>")),console.log(),console.log(chalk.gray(" While waiting, explore:")),console.log(chalk.white(" ref linux")+chalk.gray(" Quick reference for Linux")),console.log(chalk.white(" ref web")+chalk.gray(" Quick reference for Web")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.white(" help")+chalk.gray(" All available commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+b()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}e.exitOverride(),e.configureOutput({writeErr:()=>{},writeOut:o=>{console.log(o)}});const Ho=o({input:process.stdin,output:process.stdout,prompt:Oo(),terminal:!0,completer:qo});x(Ho);let Zo=!1;if(h(!0),io(),So&&(console.log(),console.log(chalk.yellow(" ⏱ A new competition day has started (Sydney time).")),console.log(chalk.gray(" For fairness, yesterday’s sign-in has been cleared. Type ")+chalk.cyan("join <url>")+chalk.gray(" to sign in with your account.")),console.log()),uo()){const o=l().userName||"this account";console.log(),console.log(chalk.yellow(" ⚠ This machine is signed in as ")+chalk.bold.white(o)+chalk.yellow(".")),console.log(chalk.gray(" Press ")+chalk.cyan("Enter")+chalk.gray(` to continue as ${o}, or type `)+chalk.cyan("logout")+chalk.gray(" to switch accounts.")),"logout"===(await new Promise(o=>{Ho.question(chalk.white(" > "),e=>o(e.trim()))})).toLowerCase()&&(a({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:""}),console.log(),console.log(chalk.green(" ✓ Logged out. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" to sign in with your own account."))),console.log()}po()&&go(()=>Ho.prompt());let Ko=null;const oe=Ho.prompt.bind(Ho);Ho.prompt=o=>{if(!(C()||I()||T()||S()||bo()||(Ho.setPrompt(Oo()),o)))try{for(const o of Y()){const e="done"===o.status,t=o.cmd.length>40?`${o.cmd.slice(0,37)}…`:o.cmd,n=o.render?"":chalk.gray(" (")+chalk.white(t)+chalk.gray(") — ")+chalk.cyan(`tasks ${o.id}`);if(console.log((e?chalk.green(" ✓"):chalk.red(" ✗"))+chalk.white(` background task #${o.id} ${o.status}`)+n),o.render)try{o.render()}catch{}}const o=U();o&&o!==Ko?(console.log(o),Ko=o):o||(Ko=null)}catch{}oe(o)};const ee=M();ee&&(console.log(chalk.cyan(" ↻ Continue where you left off: ")+chalk.white(ee.label)+(ee.urgent?chalk.yellow(" (exam timer running)"):"")),console.log(chalk.gray(" type ")+chalk.cyan("resume")+chalk.gray(" to jump back in.")),console.log()),Ho.prompt(),Ho.on("line",async o=>{if(Zo)return;let a=o.trim();if(!a)return Ho.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Oo()),void Ho.prompt();if(a.startsWith("/")&&!a.startsWith("//")){const o=a.slice(1).split(/\s+/)[0].toLowerCase(),t=a.slice(1+o.length).trim();if("ai"===o)return Zo=!0,await async function(o,e){if(C())return void(o?await A(o):console.log(chalk.gray(" You are already in the AI chat — just type your message.")));if(I())return void(o?await $(o):console.log(chalk.gray(" You are already in the CTF4AI target chat — just type your message.")));if(T())return void(o?await E(o):console.log(chalk.gray(" You are already in the Embodied-AI chat — just type your message.")));ro(o?`/ai ${o}`:"/ai");const t=process.exit;process.exit=()=>{throw new Error(Lo)};try{await e.parseAsync(["node","icoa","ai4ctf"])}catch(o){if(!(o instanceof Error&&o.message===Lo))throw o}finally{process.exit=t}o&&C()&&await A(o)}(t,e),Zo=!1,Ho.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Oo()),void Ho.prompt();!(C()||I()||T()||S()||bo())&&Ro.includes(o)&&(a=a.slice(1))}if("resume"===a.toLowerCase()){const o=M();return o?(ro(`resume → ${o.command.join(" ")}`),Zo=!0,await Fo(e),Zo=!1,Ho.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Oo()),void Ho.prompt()):(console.log(),console.log(chalk.gray(" Nothing to resume yet — start with ")+chalk.cyan("learn")+chalk.gray(" (curriculum) or ")+chalk.cyan("demo")+chalk.gray(" (taste).")),console.log(),void Ho.prompt())}const s=C()||I()||T()||S();if(!s&&("bg"===a.toLowerCase()||/^bg\s/i.test(a))){const o=a.replace(/^bg\s*/i,"").trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("bg <command>")+chalk.gray(" — run a non-interactive shell command in the background.")),console.log(chalk.gray(" e.g. ")+chalk.cyan("bg nmap -p- 10.0.0.5")+chalk.gray(" · view: ")+chalk.cyan("tasks")),console.log(),void Ho.prompt();const e=so(),t=lo(o);ao({cwd:e,input:`bg ${o}`,riskFlags:t}),t.length>0&&P()&&console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`));const n=_(o,e);return console.log(),console.log(chalk.cyan(` ▸ background task #${n.id} started`)+chalk.gray(` (${X()} running)`)),console.log(chalk.gray(" ")+chalk.white(o)),console.log(chalk.gray(" view: ")+chalk.cyan("tasks")+chalk.gray(" · output: ")+chalk.cyan(`tasks ${n.id}`)),console.log(),void Ho.prompt()}if(!s&&("tasks"===a.toLowerCase()||/^tasks\s/i.test(a))){const o=a.replace(/^tasks\s*/i,"").trim(),e=W();if(console.log(),o){const e=Q(Number(o));if(!e||Number.isNaN(Number(o)))console.log(chalk.yellow(` No background task #${o}.`)+chalk.gray(" Type ")+chalk.cyan("tasks")+chalk.gray(" to list them."));else{const o="running"===e.status?chalk.yellow:"done"===e.status?chalk.green:chalk.red;console.log(o(` #${e.id} [${e.status}]`)+chalk.white(` ${e.cmd}`)+(null!==e.exitCode?chalk.gray(` (exit ${e.exitCode})`):"")),console.log(chalk.gray(" ─────────────────────────────────────────────"));const t=e.output.trim();if(t)for(const o of t.split("\n"))console.log(chalk.gray(" ")+chalk.white(o));else console.log(chalk.gray(" (no output yet)"))}}else if(0===e.length)console.log(chalk.gray(" No background tasks. Start one with ")+chalk.cyan("bg <command>")+chalk.gray("."));else{console.log(chalk.bold.white(" Background tasks"));for(const o of e){const e="running"===o.status?chalk.yellow("●"):"done"===o.status?chalk.green("✓"):chalk.red("✗"),t=Math.round(((o.endedAt??Date.now())-o.startedAt)/1e3),n=(o.endedAt?`${t}s`:`${t}s…`).padStart(5),l=o.cmd.length>48?`${o.cmd.slice(0,45)}…`:o.cmd;console.log(` ${e} `+chalk.white(`#${o.id}`)+chalk.gray(` ${n} `)+chalk.white(l))}console.log(chalk.gray(" output: ")+chalk.cyan("tasks <id>"))}return console.log(),void Ho.prompt()}if(!s&&/&\s*$/.test(a)&&/^challenge\s+start\s+/i.test(a)){const o=a.replace(/\s*&\s*$/,"").trim().replace(/^challenge\s+start\s+/i,"").trim().split(/\s+/),e=o.some(o=>"-n"===o||"--new"===o),t=o.find(o=>"-n"!==o&&"--new"!==o);if(!t)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("challenge start <id> &")),console.log(),void Ho.prompt();if(!n())return console.log(),console.log(chalk.red(" Not connected. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" first.")),console.log(),void Ho.prompt();ro(`challenge start ${t}${e?" --new":""} & (background)`);const l=B(`challenge start ${t}`,()=>J(t,e),o=>V(t,o));return console.log(),console.log(chalk.cyan(` ▸ background task #${l.id}: `)+chalk.white(`starting ${t}`)+chalk.gray(" — you can keep working; the connection info appears here when it is ready.")),console.log(),void Ho.prompt()}if(!s&&a.startsWith("#")){const o=a.slice(1).trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("#<candidate answer>")+chalk.gray(" — stage a flag/answer WITHOUT submitting it. Review with ")+chalk.cyan("drafts")+chalk.gray(".")),console.log(),void Ho.prompt();const e=R(),t=e?.session?.examId??null,n=e?e._lastQ||1:null,l=G(o,t,n);return ro(`draft #${l.id} (not submitted)`),console.log(),console.log(chalk.green(` ✎ draft #${l.id} saved`)+(n?chalk.gray(` (Q${n})`):"")+chalk.yellow(" — NOT submitted.")),console.log(chalk.gray(" review with ")+chalk.cyan("drafts")+chalk.gray("; when sure, submit it the normal way.")),console.log(),void Ho.prompt()}if(!s&&("drafts"===a.toLowerCase()||/^drafts\s/i.test(a))){const o=a.replace(/^drafts\s*/i,"").trim().toLowerCase();if("clear"===o){const o=K();return console.log(),console.log(chalk.gray(` Cleared ${o} draft${1===o?"":"s"}.`)),console.log(),void Ho.prompt()}const e=o.match(/^(?:rm|remove|del|delete)\s+(\d+)$/);if(e){const o=Z(Number(e[1]));return console.log(),console.log(o?chalk.gray(` Removed draft #${e[1]}.`):chalk.yellow(` No draft #${e[1]}.`)),console.log(),void Ho.prompt()}const t=R(),n=H(t?.session?.examId??null);if(console.log(),0===n.length)console.log(chalk.gray(" No drafts yet. Stage a candidate with ")+chalk.cyan("#ICOA{maybe_this}")+chalk.gray(" — it won’t submit."));else{console.log(chalk.bold.white(" Draft answers")+chalk.gray(" (staged — not submitted)"));for(const o of n){const e=o.q?chalk.cyan(`Q${o.q}`.padStart(4)):chalk.gray(" · ");console.log(chalk.gray(` #${o.id}`)+` ${e} `+chalk.white(o.text.length>56?`${o.text.slice(0,53)}…`:o.text))}console.log(chalk.gray(" remove: ")+chalk.cyan("drafts rm <id>")+chalk.gray(" · clear all: ")+chalk.cyan("drafts clear"))}return console.log(),void Ho.prompt()}if("menu"===a||"menu confirm"===a)return P()&&"menu confirm"!==a?(console.log(),console.log(chalk.yellow(" Real exam active. Progress is auto-saved.")),console.log(chalk.gray(" To return to main menu anyway, type ")+chalk.white("menu confirm")),console.log(),void Ho.prompt()):void w(Ho);if(C()){Zo=!0;const o=await A(a);return Zo=!1,"exit"===o&&Ho.setPrompt(Oo()),void Ho.prompt()}if(I()){Zo=!0;const o=await $(a);return Zo=!1,"exit"!==o&&"solved"!==o||Ho.setPrompt(Oo()),void Ho.prompt()}if(T()){Zo=!0;const o=await E(a);return Zo=!1,"exit"===o&&Ho.setPrompt(Oo()),Ho.setPrompt(T()?chalk.bold.cyan("icoa ctf4eai> "):Oo()),void Ho.prompt()}if(ro(a),"exit"===a)return R()?(console.log(),console.log(chalk.yellow(" ⚠ An exam is in progress.")),console.log(chalk.white(" To return to menu without losing progress, type: ")+chalk.bold.cyan("back")),console.log(chalk.white(" To fully close ICOA CLI, type: ")+chalk.bold.cyan("quit")),console.log(chalk.gray(" Your progress is auto-saved either way.")),console.log(),void Ho.prompt()):(console.log(),console.log(chalk.gray(" ")+chalk.white("exit")+chalk.gray(" returns to the main menu. To fully close ICOA CLI, type ")+chalk.bold.cyan("quit")+chalk.gray(".")),"selection"===Go&&Mo(),void Ho.prompt());if("quit"===a||"q"===a||"quit confirm"===a){const o=R();return o&&"demo-free"!==o.session.examId&&"quit confirm"!==a?(console.log(),console.log(chalk.yellow(" ⚠ A real exam is in progress.")),console.log(chalk.gray(" Your answers are auto-saved on the server, but the exam timer keeps ticking")),console.log(chalk.gray(" on the server side even if you close the CLI.")),console.log(),console.log(chalk.white(" To leave the CLI but keep the exam alive, type: ")+chalk.bold.cyan("back")),console.log(chalk.gray(" (recommended — you can resume with ")+chalk.cyan("exam q 1")+chalk.gray(" after relaunching icoa)")),console.log(),console.log(chalk.white(" To really close ICOA CLI, type: ")+chalk.bold.cyan("quit confirm")),console.log(),void Ho.prompt()):(o&&"demo-free"===o.session.examId&&(console.log(),console.log(chalk.gray(" Demo paused. Resume with: ")+chalk.white("demo")+chalk.gray(" (fresh) or ")+chalk.white("exam q 1")+chalk.gray(" (continue)."))),co(),yo(),z(),m(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),oo(),void Wo(0))}if("back"===a){const o=R(),e=o&&"demo-free"!==o.session.examId,t=o&&"demo-free"===o.session.examId&&(()=>{const e=new Date(o.session.startedAt||0).getTime();return Date.now()-e<18e5})();if(e)console.log(),console.log(chalk.gray(" Exam paused. Your progress is saved.")),console.log(chalk.white(" Resume: exam q 1")+chalk.gray(" · ")+chalk.white("exam review")+chalk.gray(" · ")+chalk.white("exam submit")),console.log();else if(t){const e=Object.keys(o.answers).length,t=o.session.questionCount;console.log(),console.log(chalk.gray(` Demo paused (${e}/${t} answered). Resume with: `)+chalk.white("exam q 1")),console.log(chalk.gray(" Or type ")+chalk.white("demo")+chalk.gray(" to restart.")),console.log()}else{if(o&&"demo-free"===o.session.examId){const{clearExamState:o}=await import("./lib/exam-state.js");o("demo-free")}const e=l();fetch("https://practice.icoa2026.au/api/icoa/demo-stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"post-report-back",lang:e.language||"en",timestamp:(new Date).toISOString()}),signal:AbortSignal.timeout(5e3)}).catch(()=>{}),"selection"===Go?Mo():console.log(chalk.gray(" Already at main menu."))}return void Ho.prompt()}if("help"===a||"?"===a){if(R()){Zo=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return Zo=!1,void Ho.prompt()}return _o(i(),Go),void Ho.prompt()}if("man"===a||"manual"===a)return _o(i(),Go),console.log(),console.log(chalk.bold.yellow(" ★ Stuck on a tool? ")+chalk.bold.cyan("man <tool>")+chalk.gray(" e.g. ")+chalk.cyan("man steghide")+chalk.gray(" · ")+chalk.cyan("man tools")+chalk.gray(" = full list")),void Ho.prompt();if(/^(?:man|manual)\s+\S/i.test(a))return k(a.replace(/^(?:man|manual)\s+/i,"")),void Ho.prompt();if("more help"===a.toLowerCase()&&R()){Zo=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return Zo=!1,void Ho.prompt()}if("continue"===a.toLowerCase())return console.log(),console.log(chalk.green.bold(" ═══ AI4CTF — AI as Your Teammate ═══")),console.log(),console.log(chalk.white(" In AI4CTF, you solve cybersecurity challenges")),console.log(chalk.white(" with AI by your side.")),console.log(),console.log(chalk.white(" In this demo, your AI teammate gives help at 3 levels:")),console.log(chalk.yellow(" hint a")+chalk.gray(" General guidance")),console.log(chalk.yellow(" hint b")+chalk.gray(" Deep analysis")),console.log(chalk.yellow(" hint c")+chalk.gray(" Critical assist")),console.log(),console.log(chalk.white(" Try it now! Type: ")+chalk.bold.green("ai4ctf")),console.log(chalk.gray(' Chat freely with your AI teammate. Type "exit" when done.')),console.log(),console.log(chalk.gray(" After ai4ctf, try: ")+chalk.bold.red("ctf4ai")+chalk.gray(' — trick the AI into saying "koala"')),console.log(),void Ho.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(a.trim())){Zo=!0;try{await e.parseAsync(["node","icoa","exam","token",a.trim()])}catch{}return Zo=!1,void Ho.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(a.trim())){Zo=!0;try{await e.parseAsync(["node","icoa","exam","token",a.trim().toUpperCase()])}catch{}return Zo=!1,void Ho.prompt()}const r=a.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(r){Zo=!0;try{await e.parseAsync(["node","icoa","exam","token",r[1].toUpperCase()])}catch{}return Zo=!1,void Ho.prompt()}const d=a.match(/^exam\s+([A-Z]{2,3})$/i);if(d){Zo=!0;try{await e.parseAsync(["node","icoa","exam","list",d[1]])}catch{}return Zo=!1,void Ho.prompt()}if("clear"===a||"cls"===a)return console.clear(),void Ho.prompt();if("news"===a)return po()?mo():console.log(chalk.gray(" No competition joined. Use ")+chalk.white("join <url>")+chalk.gray(".")),void Ho.prompt();if("memo"===a){if(!po())return console.log(chalk.gray(" Join a competition first: ")+chalk.white("join <url>")),void Ho.prompt();Zo=!0;try{await xo()}catch{}return void(Zo=!1)}const p=wo()||ho(l().userName||"");if("jury"===a&&p){Zo=!0;try{await vo()}catch{}return void(Zo=!1)}if(p&&wo()&&"scoreboard"===a.split(/\s+/)[0]){Zo=!0;try{const o=await fo();if(console.log(),0===o.length)console.log(chalk.gray(" Scoreboard is empty."));else{console.log(chalk.bold.white(" Scoreboard"));for(const e of o.slice(0,50))console.log(chalk.gray(` ${String(e.pos).padStart(3)}. `)+chalk.white(e.name.padEnd(28).slice(0,28))+chalk.cyan(String(e.score)))}console.log()}catch{}return Zo=!1,void Ho.prompt()}if(p&&uo()){const o=a.split(/\s+/)[0];if(["challenges","open","submit","hint"].includes(o))return console.log(),console.log(chalk.yellow(" Team-leader account — the challenge bracket is not available here.")),console.log(chalk.gray(" Available: ")+chalk.white("scoreboard")+chalk.gray(" · ")+chalk.white("news")+chalk.gray(" · ")+chalk.white("jury")+chalk.gray(" · ")+chalk.white("time")+chalk.gray(" · ")+chalk.white("status")+chalk.gray(" · ")+chalk.white("logout")),console.log(),void Ho.prompt()}if(a.startsWith("activate ")){const o=a.slice(9).trim(),e=c(o);return"ok"===e?console.log(chalk.green(" Access granted! Token bound to this device.")):"already_bound"===e?(console.log(),console.log(chalk.red(" Token already activated on a different device.")),console.log(chalk.gray(" Each token binds to the first device that uses it. If you lost the device,")),console.log(chalk.gray(" contact your proctor to have the token re-issued for a new device."))):(console.log(),console.log(chalk.red(" Token not recognized.")),console.log(chalk.gray(" Possible reasons:")),console.log(chalk.white(" • ")+chalk.gray("Typo — access tokens are case-insensitive and look like ")+chalk.cyan("ICOA-XXXX-XXXX-XXXX")+chalk.gray(" (4-char hex groups, e.g. ICOA-385E-27F2-B21B)")),console.log(chalk.white(" • ")+chalk.gray("Expired — ask your proctor or organizer for a fresh token")),console.log(chalk.white(" • ")+chalk.gray("Network — verify connection to ")+chalk.cyan("practice.icoa2026.au")),console.log(chalk.gray(" Still stuck? type ")+chalk.cyan("help")+chalk.gray(" or try ")+chalk.cyan("exam demo")+chalk.gray(" for a free practice round."))),console.log(),void Ho.prompt()}if("activate"===a)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void Ho.prompt();const u=R();if(u){const o=a.toUpperCase().trim(),t=o=>{const e=u.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},n=o=>{const e=u.questions.find(e=>e.number===o);return"short_answer"===e?.type},l=o=>{const e="demo-free"!==u.session.examId,t=u.questions.find(e=>e.number===o),n=F(t?.type,e);console.log(),console.log(chalk.yellow(` Q${o} is a practical question — letters (A/B/C/D) don't apply here.`)),n?(console.log(chalk.white(" Enter the AI chat for this question: ")+chalk.bold.cyan(n)),console.log(chalk.gray(" Or submit a flag directly: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`))):console.log(chalk.gray(" Submit a flag: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`)),console.log()};if(/^[ABCDE]$/.test(o)){const a=u._lastQ||1;if(t(a))return l(a),void Ho.prompt();if(n(a))return console.log(),console.log(chalk.yellow(` Q${a} is a short-answer question — type a number, not a letter.`)),console.log(chalk.gray(" Example: ")+chalk.green("42")+chalk.gray(" (or ")+chalk.green(`exam answer ${a} 42`)+chalk.gray(")")),console.log(),void Ho.prompt();Zo=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(a),o])}catch{}return Zo=!1,void Ho.prompt()}if(/^-?\d+$/.test(o)){const t=u._lastQ||1;if(n(t)){Zo=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(t),o])}catch{}return Zo=!1,void Ho.prompt()}}const s=o.match(/^(\d+)\s+([ABCDE]|-?\d+)$/);if(s){const o=parseInt(s[1],10);if(t(o))return l(o),void Ho.prompt();Zo=!0;try{await e.parseAsync(["node","icoa","exam","answer",s[1],s[2]])}catch{}return Zo=!1,void Ho.prompt()}}const h=a.split(/\s+/)[0].toLowerCase(),f=/^python3?(\.\d+)?$/.test(h),b="ls"===h||"pwd"===h,x=a.startsWith("!")||h.startsWith("!")||f||b,O=new Set(["nano","vi","vim","emacs","pico","ed","code","cat","less","more","head","tail","ls","pwd","cd","base64","xxd","hexdump","od","openssl","md5sum","sha256sum","grep","find","awk","sed","strings","file","curl","wget","nc","ping","nmap","echo","bash","sh","zsh","pip","pip3","node","npm"]),j=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${a}`)),console.log()};if("embodied"===Go&&!x&&!["doctor","demo2","learn","exam","ctf4eai","ctf4vla","eai","arena","lang","ref","setup","env","aienv","ipynb","sim"].includes(h))return O.has(h)?(j(),void Ho.prompt()):(console.log(chalk.gray(" Not available in Embodied AI Security mode.")),console.log(chalk.white(" Try ")+chalk.bold.cyan("demo2")+chalk.gray(" (intro) · ")+chalk.bold.cyan("learn")+chalk.gray(" (curriculum) · ")+chalk.bold.cyan("exam <PD-token>")+chalk.gray(" (Paper D)")),console.log(),void Ho.prompt());if("selection"===Go&&!x&&!["doctor","exam","demo","demo2","retry","nations","next","prev","continue","setup","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","aienv","ipynb","sim"].includes(h)){if(O.has(h))return j(),void Ho.prompt();if(console.log(chalk.gray(" Not available in Selection mode.")),u){const o=u._lastQ||1;console.log(chalk.white(` Resume exam: exam q ${o}`)+chalk.gray(" · ")+chalk.white("A/B/C/D")+chalk.gray(" to answer"))}else console.log(chalk.gray(" Try: demo · setup to switch mode"));return console.log(),void Ho.prompt()}if("organizer"===Go&&!["doctor","join","exam","demo","retry","next","prev","logout","setup","lang","ref","ctf","mark","unmark","review","submit"].includes(h))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void Ho.prompt();if(!("olympiad"!==Go||i()&&y()||g(h)))return console.log(chalk.yellow(" Restricted mode. ")+chalk.gray("Enter your access token:")),console.log(chalk.white(" activate <token>")),console.log(),console.log(chalk.gray(" Free commands: ")+chalk.white("ref [topic]")+chalk.gray(", ")+chalk.white("help")+chalk.gray(", ")+chalk.white("exit")),console.log(),void Ho.prompt();if(!["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","submit","learn","demo2","ctf4eai","ctf4vla","theme","sim","arena","eai","learn-pull","doctor"].includes(h)){if(No.has(h))return console.log(chalk.yellow(` "${h}" is a shell command — the ICOA prompt isn't a shell.`)),console.log(chalk.gray(" In real-exam mode, prefix with ! to run inside the sandbox: ")+chalk.cyan(`!${a}`)),console.log(),void Ho.prompt();if(/(?:^|\s)(?:\/(?!home\/|Users\/|tmp\/)|\.\.\/|~\/)/.test(a)&&!a.startsWith("cd ")){const o=/(?:^|\s)\/(?!home\/\w+\/icoa-workspace|Users\/\w+\/icoa-workspace|tmp\/)/.test(a),e=/\.\./.test(a);if(o||e)return console.log(chalk.red(" Blocked: access outside workspace is not allowed.")),console.log(chalk.gray(` Workspace: ${jo}`)),console.log(),void Ho.prompt()}let o=a.startsWith("!")?a.slice(1).trim():a;if("darwin"===process.platform){const e="/opt/homebrew/opt/python@3.12/bin/python3.12";o=o.replace(/^python3?\s/,`${e} `).replace(/^(python3|python)$/,e)}else if("win32"===process.platform){const e=(()=>{try{return t("py -3 --version",{stdio:["ignore","ignore","ignore"],timeout:1500}),"py -3"}catch{}return"python"})();o=o.replace(/^python3?(\.\d+)?\s/,`${e} `).replace(/^python3?(\.\d+)?$/,e)}else{const e=(()=>{try{return t("which python3.12",{stdio:"ignore"}),"python3.12"}catch{return"python3"}})();o=o.replace(/^python\s/,`${e} `).replace(/^python$/,e)}const e=so(),n=lo(a);ao({cwd:e,input:a,riskFlags:n}),n.length>0&&P()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${n.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=$o(To(),".icoa");Co(o)||Ao(o,{recursive:!0});const e=$o(o,"python-startup.py");let t="";if(Co(e))try{t=ko(e,"utf-8")}catch{}return t!==Eo&&Io(e,Eo),e}()}" ${o}`,console.log(),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log(chalk.bold.white(" Python ready — ICOA exam toolkit pre-loaded")),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log(),console.log(chalk.white(" Already imported: ")+chalk.gray("base64, struct, hashlib, re, json, binascii")),console.log(chalk.white(" Also available: ")+chalk.gray("requests, bs4, numpy, PIL.Image, AES, pad/unpad, xor, p32/u32/p64/u64")),console.log(),console.log(chalk.yellow(" Quick examples:")),console.log(chalk.gray(' base64.b64decode("aGVsbG8=") ')+chalk.gray("# decode base64")),console.log(chalk.gray(' bytes.fromhex("48656c6c6f") ')+chalk.gray("# hex → bytes")),console.log(chalk.gray(' "ICOA{x}".encode() ')+chalk.gray("# str → bytes")),console.log(chalk.gray(" [chr(c) for c in [73,67,79,65]] ")+chalk.gray("# ASCII codes")),console.log(chalk.gray(' xor(bytes.fromhex("0a2b"), b"IC") ')+chalk.gray("# pwntools XOR")),console.log(),console.log(chalk.gray(" Exit: ")+chalk.white("exit()")+chalk.gray(" or Ctrl-D")),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log()),Zo=!0;try{await no()&&await eo()?await to(o,Ho):await Uo(o,Ho,e)}catch{console.log(chalk.yellow(` Command failed: ${h}`))}return Zo=!1,console.log(),void Ho.prompt()}Zo=!0;const N=a.trim(),L=N.toLowerCase();let D,q=null,U="";if(u)if("submit"===L)q="final";else if(L.startsWith("submit ")){let o=N.slice(7).trim();/^submit\s+/i.test(o)&&(o=o.replace(/^submit\s+/i,"").trim()),o=o.replace(/^["'`]+|["'`]+$/g,"").trim(),o&&/^ICOA\{[^}]*\}?$/i.test(o)?(q="flag",U=o):o&&/^[ABCDE]$/i.test(o)&&(q="flag",U=o.toUpperCase())}else/^ICOA\{[^}]+\}$/i.test(N)&&(q="flag",U=N);D="final"===q?["exam","submit"]:"flag"===q?["exam","answer",String(u?._lastQ||1),U]:function(o){const e=o.split(/\s+/),t=e[0].toLowerCase(),n=e.slice(1);if("aienv"===t&&["run","python","py"].includes((n[0]??"").toLowerCase()))return v(o);if(("submit"===t||"flag"===t)&&n.length>=2)return["ctf","submit",n[0],n.slice(1).join(" ").trim().replace(/^["'`]+|["'`]+$/g,"")];if("connect"===t&&n.length>=2){const e=v(o);return["connect",e[1]??n[0],e.slice(2).join(" ")]}const l={demo:["exam","demo"],retry:["exam","demo-retry"],nations:["exam","nations"],next:["exam","next"],prev:["exam","prev"],mark:["exam","mark",...n],unmark:["exam","unmark",...n],review:["exam","review"],logout:["ctf","logout"],join:["ctf","join",...n],activate:["ctf","activate",...n],challenges:["ctf","challenges"],ch:["ctf","challenges"],open:["ctf","open",...n],submit:["ctf","submit",...n],flag:["ctf","submit",...n],scoreboard:["ctf","scoreboard",...n],sb:["ctf","scoreboard",...n],status:["ctf","status"],time:["ctf","time"]};return l[t]?l[t]:["ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","ctf4ai","doctor"].includes(t)?[t,...n]:e}(a);const Y="ctf"===D[0]&&"join"===D[1];Y&&Ho.pause(),process.exit=()=>{throw new Error(Lo)};try{await e.parseAsync(["node","icoa",...D])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===Lo);else if(e.includes("commander.unknownCommand")){const{distance:o}=await import("fastest-levenshtein"),e=["ctf","ref","shell","files","view","connect","challenge","note","notes","logbook","log","manual","lang","setup","env","aienv","ipynb","ai4ctf","exam","ctf4ai","theme","eai","clear","cls","quit","exit","back","menu","help","continue","activate","demo","challenges","status","scoreboard","join","logout"],t=h.split(/\s+/)[0]||h;let n={word:"",dist:1/0};for(const l of e){const e=o(t.toLowerCase(),l);e<n.dist&&(n={word:l,dist:e})}console.log(chalk.yellow(` Unknown command: ${h}.`)),n.dist>0&&n.dist<=2&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(n.word)+chalk.gray("?")),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for the full command list."))}else e.includes("commander.missingArgument")||"commander.missingArgument"===o?.code?"submit"===h||"flag"===h?(console.log(chalk.yellow(" Incomplete — usage: ")+chalk.cyan("submit <challenge#> <flag>")),console.log(chalk.gray(" Put the number AND the flag on one line, e.g. ")+chalk.cyan("submit 44 pecan{...}"))):(console.log(chalk.yellow(` Incomplete command: ${h}`)),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for usage."))):e.includes("commander.")||(e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ETIMEDOUT"))&&console.log(chalk.yellow(" Network error. Check your connection."))}finally{process.exit=Wo,Zo=!1,Y&&Ho.resume()}C()?Ho.setPrompt(chalk.magenta("icoa ai4ctf> ")):I()?Ho.setPrompt(chalk.red("icoa ctf4ai> ")):T()&&Ho.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),Ho.prompt()}),Ho.on("SIGINT",()=>{if(console.log(),C()||I())console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still in the AI chat.")),console.log(chalk.white(" Type ")+chalk.bold.cyan("exit")+chalk.white(" to leave the chat and return to the menu."));else if(R()){const o="demo-free"!==R().session.examId;console.log(chalk.yellow(" Ctrl+C did NOT close ICOA CLI.")),console.log(chalk.gray(` Your ${o?"exam":"demo"} is paused and every answer is auto-saved.`)),console.log(),console.log(chalk.white(" Resume: ")+chalk.cyan("exam q 1")+chalk.gray(" · Back to menu: ")+chalk.cyan("back")+chalk.gray(" · Close CLI: ")+chalk.cyan(o?"quit confirm":"quit"))}else console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still at the ")+chalk.cyan("icoa>")+chalk.yellow(" prompt.")),console.log(chalk.gray(" Keep typing — ")+chalk.cyan("help")+chalk.gray(" lists commands. (Only ")+chalk.cyan("quit")+chalk.gray(" or Ctrl+D actually close the CLI.)"));console.log(),Ho.prompt()}),Ho.on("close",()=>{co(),yo(),z(),m(),oo(),Wo(0)}),"1"===process.env.ICOA_AUTO_RESUME&&(delete process.env.ICOA_AUTO_RESUME,M()&&(Zo=!0,await Fo(e),Zo=!1,Ho.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Oo()),Ho.prompt()))}function Uo(o,t,n){return new Promise(l=>{const a=process.stdin,s=!!a.isTTY&&!!a.isRaw;if(t.pause(),a.isTTY&&"function"==typeof a.setRawMode)try{a.setRawMode(!1)}catch{}const r=e(o,{shell:!0,stdio:"inherit",cwd:n||process.cwd()}),i=()=>{if(a.isTTY&&"function"==typeof a.setRawMode&&s)try{a.setRawMode(!0)}catch{}t.resume(),l()};r.on("close",i),r.on("error",i)})}function _o(o,e="olympiad"){return console.log(),"selection"===e||"organizer"===e?(console.log(chalk.bold.white(" Exam")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to exam server")),console.log(chalk.white(" exam list ")+chalk.gray("Available exams")),console.log(chalk.white(" exam start <id> ")+chalk.gray("Begin an exam")),console.log(chalk.white(" exam q [n] ")+chalk.gray("View questions")),console.log(chalk.white(" exam answer <n> <X> ")+chalk.gray("Answer question")),console.log(chalk.white(" exam review ")+chalk.gray("Review all answers")),console.log(chalk.white(" exam submit ")+chalk.gray("Submit for grading")),console.log(chalk.white(" exam result ")+chalk.gray("View your score")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" setup ")+chalk.gray("Settings / switch mode")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log()):o?(console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(chalk.bold.white(" How it works")),console.log(),console.log(chalk.gray(" 1. Browse ")+chalk.white("challenges")+chalk.gray(" and pick one")),console.log(chalk.gray(" 2. ")+chalk.white("open <id>")+chalk.gray(" to read the challenge")),console.log(chalk.gray(" 3. Use ")+chalk.white("ai4ctf")+chalk.gray(" to chat with AI when stuck")),console.log(chalk.gray(" 4. ")+chalk.white("submit <id> <flag>")+chalk.gray(" to score points")),console.log(chalk.gray(" 5. Check ")+chalk.white("scoreboard")+chalk.gray(" to track your rank")),console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(),console.log(chalk.bold.white(" Competition")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to CTFd")),console.log(chalk.white(" challenges (ch) ")+chalk.gray("List challenges by category")),console.log(chalk.white(" open <id> ")+chalk.gray("Read challenge + get next steps")),console.log(chalk.white(" submit <id> <flag> ")+chalk.gray("Submit a flag")),console.log(chalk.white(" scoreboard (sb) ")+chalk.gray("Live rankings")),console.log(chalk.white(" status ")+chalk.gray("Your score & timer")),console.log(chalk.white(" time ")+chalk.gray("Countdown timer")),console.log(),console.log(chalk.bold.white(" AI Teammate")),console.log(chalk.white(" ai4ctf ")+chalk.gray("Free-chat with your AI teammate")),console.log(),console.log(chalk.bold.white(" Tools")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference (linux, web, crypto...)")),console.log(chalk.white(" shell ")+chalk.gray("Interactive CTF shell (sandbox if present, else host)")),console.log(chalk.white(" files <id> ")+chalk.gray("Download challenge files")),console.log(chalk.white(" connect <id> ")+chalk.gray("Connect to remote target")),console.log(chalk.white(" note [text] ")+chalk.gray("Add a logbook entry (in-exam: tags current Q)")),console.log(chalk.white(" logbook [n] ")+chalk.gray("View your logbook (in-exam: filter by Q)")),console.log(chalk.white(" log ")+chalk.gray("Session history")),console.log(chalk.white(" man <tool> ")+chalk.bold.yellow("★ ")+chalk.gray("How to use a tool (steghide, nmap…); ")+chalk.cyan("man tools")+chalk.gray(" = list. Bare ")+chalk.cyan("man")+chalk.gray(" = this list.")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" resume ")+chalk.gray("Continue your last learn card / exam")),console.log(chalk.white(" #<candidate> ")+chalk.gray("Stage a draft answer (never auto-submits)")),console.log(chalk.white(" drafts ")+chalk.gray("Review staged draft answers")),console.log(chalk.white(" bg <command> ")+chalk.gray("Run a shell command in the background")),console.log(chalk.white(" tasks [id] ")+chalk.gray("Background task panel / view output")),console.log(chalk.white(" doctor ")+chalk.gray("Self-check: version, Python, server, tools")),console.log(chalk.white(" setup ")+chalk.gray("Configure settings")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language (15 supported)")),console.log(chalk.white(" logout ")+chalk.gray("Disconnect")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit (session saved)")),void console.log()):(console.log(chalk.bold.yellow(" Restricted Mode — activate with a token to unlock all commands")),console.log(),console.log(chalk.white(" activate <token> ")+chalk.gray("Unlock full access")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log())}
1
+ import{createInterface as o}from"node:readline";import{spawn as e,execSync as t}from"node:child_process";import chalk from"chalk";import{isConnected as n,getConfig as l,saveConfig as a}from"./lib/config.js";import{ensureLangCache as s}from"./lib/translations-fetcher.js";import{loadUiPack as r}from"./lib/i18n.js";import{isActivated as i,activateToken as c,isFreeCommand as g,isDeviceMatch as y,recordExit as m,recordResume as d,isFirstRunOrUpgrade as p,markVersionSeen as u}from"./lib/access.js";import{setReplMode as h}from"./lib/ui.js";import{returnToMainMenu as w,printMenuHint as f,menuHintInline as b}from"./lib/menu-nav.js";import{setMainRl as x}from"./lib/main-rl.js";import{shellSplit as v}from"./lib/shell-split.js";import{isChatActive as C,handleChatMessage as A}from"./commands/ai4ctf.js";import{renderToolMan as k}from"./lib/tool-man.js";import{isCtf4aiActive as I,handleCtf4aiMessage as $}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as T,handleCtf4VlaMessage as E}from"./commands/ctf4vla.js";import{isDemo2Active as S}from"./commands/demo2.js";import{loadDemo2Progress as O}from"./lib/demo2-progress.js";import{hasAnySimHistory as j,lastArmAt as N,lastBundledAt as L,lastSimAt as D}from"./lib/sim-cooldown.js";import{getExamState as R,getRealExamState as P,getDemoState as q,practicalChatCommand as F}from"./lib/exam-state.js";import{resolveResumePoint as M}from"./lib/resume.js";import{buildStatusLine as U}from"./lib/statusline.js";import{startBgTask as _,startAsyncTask as B,listBgTasks as W,getBgTask as Q,drainCompleted as Y,killAllBgTasks as z,runningCount as X}from"./lib/bgtasks.js";import{computeStart as J,renderStart as V}from"./commands/challenge.js";import{addDraft as G,listDrafts as H,removeDraft as Z,clearDrafts as K}from"./lib/drafts.js";import{resetTerminalTheme as oo}from"./lib/theme.js";import{ensureSandbox as eo,runInSandbox as to,isDockerAvailable as no}from"./lib/sandbox.js";import{checkShellRisk as lo,logShellAudit as ao,getActiveCwd as so}from"./lib/exam-sandbox.js";import{logCommand as ro}from"./lib/logger.js";import{startLogSync as io,stopLogSync as co}from"./lib/log-sync.js";import{installInputDynamics as go,uninstallInputDynamics as yo,stripPasteMarkers as mo}from"./lib/input-dynamics.js";import{startBroadcastPoll as po,stopBroadcastPoll as uo,showBroadcast as ho,isCompetitionJoined as wo,isMelCompetition as fo,isLeaderAccount as bo,isLeaderSession as xo,fetchPublicScoreboard as vo,isCommsActive as Co}from"./lib/comms.js";import{enterMemoScreen as Ao,enterJuryScreen as ko}from"./commands/comms.js";import{existsSync as Io,mkdirSync as $o,readFileSync as To,writeFileSync as Eo}from"node:fs";import{join as So}from"node:path";import{homedir as Oo}from"node:os";const jo="# ICOA exam interactive startup — auto-loaded by PYTHONSTARTUP\nimport base64, struct, hashlib, re, json, os, sys, binascii\ntry: import requests\nexcept ImportError: pass\ntry: from Crypto.Cipher import AES\nexcept ImportError: pass\ntry: from Crypto.Util.Padding import pad, unpad\nexcept ImportError: pass\ntry: from pwn import xor, p32, u32, p64, u64\nexcept ImportError: pass\ntry: import bs4\nexcept ImportError: pass\ntry: import numpy as np\nexcept ImportError: pass\ntry: from PIL import Image\nexcept ImportError: pass\n",No=Date.now();function Lo(){return fo()?chalk.yellow("icoa 2026> "):P()?chalk.cyan("icoa exam> "):function(){const o=q();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=No}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const Do=So(Oo(),"icoa-workspace"),Ro=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),Po="__REPL_NO_EXIT__",qo="2.5.1",Fo=["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","learn","demo2","ctf4eai","ctf4vla","theme","sim","arena","eai","learn-pull","doctor","bg","tasks","drafts","help","menu","quit","q","exit","back","resume"],Mo={exam:["list","start","q","answer","submit","review","result","next","prev","mark","unmark","help"],ctf:["challenges","open","submit","scoreboard","status","join","logout","time"],challenge:["start","stop","status"],arena:["eai"],learn:["start","continue"]};function Uo(o){const e=o.replace(/^\s+/,"");if(/^\/\S*$/.test(e)){const o=e.slice(1).toLowerCase();return[Fo.filter(e=>e.startsWith(o)).map(o=>`/${o}`),e]}const t=e.split(/\s+/);if(t.length<=1){const o=(t[0]??"").toLowerCase();return[Fo.filter(e=>e.startsWith(o)).slice(),o]}if(2===t.length){const o=Mo[t[0].toLowerCase()];if(o){const e=t[1].toLowerCase();return[o.filter(o=>o.startsWith(e)).slice(),e]}}return[[],o]}async function _o(o){const e=M();if(!e)return null;const t=process.exit;process.exit=()=>{throw new Error(Po)};try{await o.parseAsync(["node","icoa",...e.command])}catch(o){if(!(o instanceof Error&&o.message===Po))throw o}finally{process.exit=t}return e}function Bo(){console.log(),console.log(` ${chalk.cyan.bold("🎯 ICOA 2026 · National Selection")}`),console.log(),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("ACxxxxxxxx")+chalk.gray(" → ai4ctf-12 (AI as your CTF teammate)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("CAxxxxxxxx")+chalk.gray(" → ctf4ai-12 (red-team software AI)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("EAxxxxxxxx")+chalk.gray(" → ctf4eai-12 (red-team embodied AI)")),console.log(" "+chalk.bold.cyan("exam ")+chalk.white("<CC>xxxxxxxx")+chalk.gray(" → Paper A/B/C/D/E (country exam token)")),console.log(" "+chalk.bold.cyan("demo")+chalk.gray(" → free practice")),console.log(" "+chalk.bold.cyan("lang")+chalk.white(" es")+chalk.gray(" → switch language")),console.log(" "+chalk.gray("help · menu · quit")),console.log()}export async function startRepl(e,q){process.env.ICOA_INSIDE_REPL="1";let No=!1;if(fo()){const o=l().joinedAt,e=o=>new Intl.DateTimeFormat("en-CA",{timeZone:"Australia/Sydney",year:"numeric",month:"2-digit",day:"2-digit"}).format(o);o&&e(new Date(o))===e(new Date)||(a({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:"",joinedAt:""}),No=!0)}const Mo=l(),Yo=n(),zo=process.exit.bind(process),Xo=i();if(Mo.language&&"en"!==Mo.language&&(await s(Mo.language,{silent:!0}),r(Mo.language)),Mo.demoCleanedForVersion!==qo){try{const{existsSync:o,unlinkSync:e}=await import("node:fs"),{join:t}=await import("node:path"),{getIcoaDir:n}=await import("./lib/config.js"),l=t(n(),"demo-state.json");o(l)&&e(l)}catch{}a({demoCleanedForVersion:qo})}const{select:Jo,confirm:Vo}=await import("@inquirer/prompts"),Go=Mo.mode||"",Ho=""===Go?"instant":["instant","learn","selection","olympiad"].includes(Go)?Go:"selection",Zo=[{name:` ${chalk.bold("⚡ Try ICOA in 30 seconds")} ${chalk.gray("—")} ${chalk.gray("watch · no token needed")}`,value:"instant"},{name:` ${chalk.bold("🧠 Learn")} ${chalk.gray("—")} ${chalk.gray("AC / CA / EA token · skill up")}`,value:"learn"},{name:` ${chalk.bold("🎯 National Selection")} ${chalk.gray("—")} ${chalk.gray("country exam token · aim for finals")}`,value:"selection"},{name:` ${chalk.bold("🏆 International Olympiad")} ${chalk.gray("—")} ${chalk.gray("finals stage · Sydney 2026 · full sandbox")}`,value:"olympiad"},{name:` ${chalk.gray("ℹ️ About ICOA")} ${chalk.gray("·")} ${chalk.gray("what this is · how to join")}`,value:"about"}];""===Go&&(console.log(chalk.green(" 👋 First time here? ")+chalk.white("Just press ")+chalk.bold.cyan("Enter")+chalk.white(" — you’ll see ICOA in 30 seconds, no signup needed.")),console.log()),console.log(chalk.gray(" Type ")+chalk.bold.cyan("menu")+chalk.gray(" from anywhere to return here.")),console.log();let Ko="";for(;!Ko;){let o;try{o=await Jo({message:"Mode",choices:Zo,default:Ho||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}"about"!==o?Ko=o:(console.clear(),console.log(),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(chalk.bold.yellow(" ICOA")+chalk.white(" — AI-Native CLI OS for Cyber & AI Security")),console.log(chalk.gray(" Olympiad & Competition · K-12 to University")),console.log(chalk.cyan(" ───────────────────────────────────────────────────")),console.log(),console.log(chalk.bold.white(" What Makes ICOA Different")),console.log(chalk.gray(" · AI-native AI teammate, AI adversary, AI translation")),console.log(chalk.gray(" · CLI OS Complete competition environment in terminal")),console.log(chalk.gray(" · 110 tools pwntools, z3, gdb, nmap, sleuthkit... pre-configured")),console.log(chalk.gray(" · Global scale 15,000+ concurrent exams · 15 languages")),console.log(),console.log(chalk.bold.white(" Competition Format (2-day standard + 1-day Pioneer)")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" [Day 1] AI as teammate — speed track, dynamic decay + top-3 bonus")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" [Day 2] AI as target — knowledge track, static value per challenge")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" [Pioneer / Practical Round] Embodied AI — VLA + world models + sim-to-real")}`),console.log(),console.log(chalk.bold.white(" Scoring (in brief)")),console.log(chalk.gray(" · Standard medals: AI4CTF + CTF4AI combined · 1/12 Gold · 2/12 Silver · 3/12 Bronze")),console.log(chalk.gray(" · HMA: top 50% on either day, total below bronze cutoff")),console.log(chalk.gray(" · CTF4EAI: separate 15-finalist pool, G/S/B + 12 Finalist Awards")),console.log(),console.log(chalk.white(" Sydney, Australia")+chalk.gray(" · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.bold.white(" Organized by")+chalk.gray(" ASRA (Australia) · ICO Foundation Inc")),console.log(chalk.bold.white(" Contact ")+chalk.cyan(" australia@icoa2026.au · accreditation@icoa2026.au")),console.log(chalk.bold.white(" Website ")+chalk.cyan.underline(" https://icoa2026.au")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(),console.log(chalk.gray(" Press ")+chalk.yellow("Enter")+chalk.gray(" to return...")),await new Promise(o=>{const e=t=>{process.stdin.removeListener("data",e),process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!1),process.stdin.pause(),o()};process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.once("data",e)}),console.clear())}if("olympiad"===Ko&&"olympiad"!==Ho){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await Vo({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(Ko="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(Ko!==Ho&&a({mode:Ko}),console.log(),"olympiad"===Ko&&p(qo)){u(qo),console.log(chalk.gray(" Checking competition environment..."));const{execSync:o}=await import("node:child_process"),e=[{name:"pwntools",cmd:'python3 -c "import pwn"'},{name:"z3-solver",cmd:'python3 -c "import z3"'},{name:"numpy",cmd:'python3 -c "import numpy"'},{name:"requests",cmd:'python3 -c "import requests"'}];let t=0;for(const n of e)try{o(n.cmd,{stdio:"ignore"})}catch{t++}t>0?(console.log(chalk.yellow(` ${t} core competition libraries missing.`)),console.log(chalk.gray(" Run ")+chalk.white("env setup")+chalk.gray(" when you are ready to install them.")),console.log()):(console.log(chalk.green(" All core libraries ready.")),console.log())}if(q){const o=d();if(o){const e=Math.floor(o.awaySeconds/60),t=o.awaySeconds%60;console.log(chalk.yellow(` Session resumed. Away: ${e}m ${t}s | Total exits: ${o.exitCount}`)),console.log()}}if("selection"===Ko)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),Bo();else if("embodied"===Ko)!function(){console.log(chalk.cyan.bold(" [🤖 ctf4eai — Embodied AI Security]")),console.log(),console.log(chalk.bold.cyan(" CTF4EAI")+chalk.gray(" — ICOA 2026's ")+chalk.bold.white("Pioneer Round")),console.log(chalk.gray(" an independent parallel track alongside the scored main events: ")+chalk.green("AI4CTF")+chalk.gray(" (Day 1) and ")+chalk.red("CTF4AI")+chalk.gray(" (Day 2)")),console.log(),console.log(chalk.white(" Embodied AI is at its ImageNet moment.")),console.log(chalk.gray(" VLA models, MuJoCo physics, real robot arms.")),console.log(chalk.gray(" Real models, real physics, real attack surfaces.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const o=L()>0||D()>0,e=N()>0,t=j(),n=O(),l=null!==n&&"number"==typeof n.completedAt&&n.nextCardIndex>=n.totalCards,a=null!==n&&!l;if(l)console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (demo2 ✓ · sim")+(e?chalk.gray(" ✓ · sim arm ✓)"):chalk.gray(")")));else if(a){const o=`${n.nextCardIndex} / ${n.totalCards}`;console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" (last left at card ")+chalk.bold.yellow(o)+chalk.gray(")"))}else o&&e?console.log(chalk.bold.yellow(" Next up: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (sim ✓ · sim arm ✓)")):t?console.log(chalk.bold.yellow(" Next up: ")+(e?chalk.bold.cyan("① sim")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2"):chalk.bold.cyan("② sim arm")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2"))+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")):console.log(chalk.bold.yellow(" First time? Try in order: ")+chalk.bold.cyan("① sim")+chalk.gray(" → ")+chalk.bold.cyan("② sim arm")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01"));console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.bold.green(" sim")+chalk.gray(" ")+chalk.bold.cyan("①")+chalk.gray(" ")+chalk.bold.yellow("★ INSTANT")+chalk.gray(" — 9-robot group dance, no wait, no setup")),console.log(chalk.bold.green(" sim arm")+chalk.gray(" ")+chalk.bold.cyan("②")+chalk.gray(" interactive 6-DOF arm sandbox — type joint values, watch")),console.log(chalk.bold.green(" demo2")+chalk.gray(" ")+chalk.bold.cyan("③")+chalk.gray(" ~8 min interactive intro + live MuJoCo sim")),console.log(chalk.bold.green(" learn LEARNDEMO01")+chalk.gray(" ")+chalk.bold.cyan("④")+chalk.gray(" free 11-card intro (paste this command as-is)")),console.log(chalk.bold.green(" learn ")+chalk.bold.yellow("EA")+chalk.gray(" + 8 chars full 96 / 360 curriculum (team-issued)")),console.log(chalk.bold.green(" exam ")+chalk.bold.yellow("PDxxxxxxxx")+chalk.gray(" Paper D (CTF4EAI) — national selection contestants")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),console.log(chalk.gray(" Three open tiers: ")+chalk.green("free 11")+chalk.gray(" · ")+chalk.yellow("registered 100")+chalk.gray(" · ")+chalk.bold.magenta("national team 480")+chalk.gray(" (PhD-ready)")),console.log(chalk.gray(" Country team contact: ")+chalk.cyan("australia@icoa2026.au")),console.log(),f(),console.log()}();else if("instant"===Ko)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Two free tastes — just type the word and press Enter:")),console.log(),console.log(chalk.bold.green(" demo ")+chalk.gray(" Paper A/B/C taste — 10 MCQs, no timer ")+chalk.bold.cyan("🎯 selection-style")),console.log(chalk.bold.green(" demo2")+chalk.gray(" Embodied-AI mini-demo — robots & MuJoCo ")+chalk.bold.yellow("🤖 hands-on")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(" or ")+chalk.bold.cyan("demo2")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),a({mode:"selection"}),Ko="selection";else{if("learn"===Ko){console.log(chalk.cyan.bold(" [🧠 Learn]")),console.log(),console.log(chalk.gray(" Three tracks · same difficulty curve.")),console.log(),console.log(chalk.white(" Free 12-card demos — paste the full command:")),console.log(),console.log(chalk.gray(" 🤝 ai4ctf AI as your teammate ")+chalk.bold.yellow("learn AI4CTFDEMO01")),console.log(chalk.gray(" 🔓 ctf4ai AI as your target ")+chalk.bold.yellow("learn CTF4AIDEMO01")),console.log(chalk.gray(" 🤖 ctf4eai Embodied AI Security ")+chalk.bold.yellow("learn LEARNDEMO01")),console.log(),console.log(chalk.gray(" Got a cohort token? Type ")+chalk.bold.yellow("learn <TOKEN>")+chalk.gray(" (e.g. ")+chalk.bold.yellow("learn EAABCD1234")+chalk.gray(").")),console.log();try{const{input:o}=await import("@inquirer/prompts"),{resolveLearnInput:t}=await import("./lib/learn-input.js");console.log(chalk.gray(" Enter a token (or just press Enter to go back).")),console.log();const n=t(await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}));if("token"===n.kind){console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${n.token}`)),console.log(),a({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";try{await e.parseAsync(["node","icoa","learn",n.token])}finally{delete process.env.ICOA_LEARN_EMBEDDED}}else"ambiguous"!==n.kind&&"unknown"!==n.kind||(console.log(),console.log(chalk.yellow(" "+n.hint)),console.log(chalk.gray(" Returning to main menu — pick 🧠 Learn again to retry.")),console.log())}catch{}return a({mode:"selection"}),void w()}"organizer"===Ko?(console.log(chalk.yellow.bold(" [National/Regional Partner]")),console.log(),console.log(chalk.bold.white(" ██╗ ██████╗ ██████╗ █████╗")),console.log(chalk.bold.white(" ██║██╔════╝██╔═══██╗██╔══██╗")),console.log(chalk.bold.white(" ██║██║ ██║ ██║███████║")),console.log(chalk.bold.white(" ██║██║ ██║ ██║██╔══██║")),console.log(chalk.bold.white(" ██║╚██████╗╚██████╔╝██║ ██║")),console.log(chalk.bold.white(" ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝")),console.log(),console.log(chalk.yellow(" International Cyber Olympiad in AI 2026")),console.log(chalk.bold.magenta(" The World's First AI-Native CLI Operating System")),console.log(chalk.bold.magenta(" for Cybersecurity & AI Security Competition")),console.log(chalk.bold.magenta(" and Olympiad for K-12")),console.log(chalk.gray(" Sydney, Australia · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.white(" Vision")),console.log(chalk.gray(" Building a global pipeline for youth cyber & AI")),console.log(chalk.gray(" security talent through education and competition.")),console.log(),console.log(chalk.white(" Capacity")),console.log(chalk.gray(" 15,000+ concurrent online examinations")),console.log(chalk.gray(" National selection, training, and education support")),console.log(),console.log(chalk.white(" Olympic Spirit")),console.log(chalk.gray(" Excellence · Friendship · Respect")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" New country accreditation & support:")),console.log(chalk.cyan(" australia@icoa2026.au")),console.log(chalk.cyan(" accreditation@icoa2026.au")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),Yo?(console.log(chalk.green(` Logged in as ${Mo.userName}`)),console.log(chalk.white(" exam list")+chalk.gray(" Manage exams")),console.log(chalk.white(" logout")+chalk.gray(" Disconnect"))):console.log(chalk.white(" join <url>")+chalk.gray(" Connect to manage exams")),console.log(),f(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),Xo&&!y()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):Yo?(console.log(chalk.green.bold(` Welcome back, ${Mo.userName}!`)),console.log(chalk.gray(` Connected to ${Mo.ctfdUrl}`)),console.log(chalk.gray(" Not you? Type ")+chalk.cyan("logout")+chalk.gray(" to switch accounts")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Ready to compete? Start here:")),console.log(),console.log(chalk.bold.cyan(" challenges")+chalk.gray(" Browse challenges by category")),console.log(chalk.white(" status")+chalk.gray(" Your score & timer")),console.log(chalk.white(" scoreboard")+chalk.gray(" Live rankings")),console.log(chalk.white(" memo")+chalk.gray(" Report an issue to organizers (one-way)")),console.log(),console.log(chalk.gray(" Tool environment:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.bold.yellow(" ★ ")+chalk.bold.cyan("man <tool>")+chalk.gray(" How to USE a tool (steghide, nmap…) · ")+chalk.cyan("man tools")+chalk.gray(" = list")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("help")+chalk.gray(" · ")+b()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):Xo?(Io(Do)||$o(Do,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${Do}`)),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Get started:")),console.log(),console.log(chalk.white(" Step 1 ")+chalk.bold.cyan("join <url>")+chalk.gray(" Connect to competition server")),console.log(chalk.white(" Step 2 ")+chalk.bold.cyan("challenges")+chalk.gray(" Browse & solve challenges")),console.log(chalk.white(" Step 3 ")+chalk.bold.cyan("ai4ctf")+chalk.gray(" Ask AI when stuck")),console.log(),console.log(chalk.gray(" Before Step 1 — make sure your tools are ready:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.bold.yellow(" ★ ")+chalk.bold.cyan("man <tool>")+chalk.gray(" How to USE a tool (steghide, nmap…) · ")+chalk.cyan("man tools")+chalk.gray(" = list")),console.log(),console.log(chalk.gray(" Also: ")+chalk.white("help")+chalk.gray(" all commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+b()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()):(console.log(chalk.bold.yellow(" 🏆 You reached the finals tier.")),console.log(chalk.gray(" Full sandbox · 110 CTF tools · Sydney 2026 · this is where finalists compete.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" To begin, activate your competition token:")),console.log(),console.log(chalk.bold.cyan(" activate <token>")),console.log(),console.log(chalk.gray(" While waiting, explore:")),console.log(chalk.white(" ref linux")+chalk.gray(" Quick reference for Linux")),console.log(chalk.white(" ref web")+chalk.gray(" Quick reference for Web")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.white(" help")+chalk.gray(" All available commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+b()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}e.exitOverride(),e.configureOutput({writeErr:()=>{},writeOut:o=>{console.log(o)}});const oe=o({input:process.stdin,output:process.stdout,prompt:Lo(),terminal:!0,completer:Uo});x(oe),go(!1!==l().bracketedPaste);let ee=!1;if(h(!0),io(),No&&(console.log(),console.log(chalk.yellow(" ⏱ A new competition day has started (Sydney time).")),console.log(chalk.gray(" For fairness, yesterday’s sign-in has been cleared. Type ")+chalk.cyan("join <url>")+chalk.gray(" to sign in with your account.")),console.log()),fo()){const o=l().userName||"this account";console.log(),console.log(chalk.yellow(" ⚠ This machine is signed in as ")+chalk.bold.white(o)+chalk.yellow(".")),console.log(chalk.gray(" Press ")+chalk.cyan("Enter")+chalk.gray(` to continue as ${o}, or type `)+chalk.cyan("logout")+chalk.gray(" to switch accounts.")),"logout"===(await new Promise(o=>{oe.question(chalk.white(" > "),e=>o(e.trim()))})).toLowerCase()&&(a({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:""}),console.log(),console.log(chalk.green(" ✓ Logged out. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" to sign in with your own account."))),console.log()}wo()&&po(()=>oe.prompt());let te=null;const ne=oe.prompt.bind(oe);oe.prompt=o=>{if(!(C()||I()||T()||S()||Co()||(oe.setPrompt(Lo()),o)))try{for(const o of Y()){const e="done"===o.status,t=o.cmd.length>40?`${o.cmd.slice(0,37)}…`:o.cmd,n=o.render?"":chalk.gray(" (")+chalk.white(t)+chalk.gray(") — ")+chalk.cyan(`tasks ${o.id}`);if(console.log((e?chalk.green(" ✓"):chalk.red(" ✗"))+chalk.white(` background task #${o.id} ${o.status}`)+n),o.render)try{o.render()}catch{}}const o=U();o&&o!==te?(console.log(o),te=o):o||(te=null)}catch{}ne(o)};const le=M();le&&(console.log(chalk.cyan(" ↻ Continue where you left off: ")+chalk.white(le.label)+(le.urgent?chalk.yellow(" (exam timer running)"):"")),console.log(chalk.gray(" type ")+chalk.cyan("resume")+chalk.gray(" to jump back in.")),console.log()),oe.prompt(),oe.on("line",async o=>{if(ee)return;let a=mo(o.trim());if(!a)return oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt();if(a.startsWith("/")&&!a.startsWith("//")){const o=a.slice(1).split(/\s+/)[0].toLowerCase(),t=a.slice(1+o.length).trim();if("ai"===o)return ee=!0,await async function(o,e){if(C())return void(o?await A(o):console.log(chalk.gray(" You are already in the AI chat — just type your message.")));if(I())return void(o?await $(o):console.log(chalk.gray(" You are already in the CTF4AI target chat — just type your message.")));if(T())return void(o?await E(o):console.log(chalk.gray(" You are already in the Embodied-AI chat — just type your message.")));ro(o?`/ai ${o}`:"/ai");const t=process.exit;process.exit=()=>{throw new Error(Po)};try{await e.parseAsync(["node","icoa","ai4ctf"])}catch(o){if(!(o instanceof Error&&o.message===Po))throw o}finally{process.exit=t}o&&C()&&await A(o)}(t,e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt();!(C()||I()||T()||S()||Co())&&Fo.includes(o)&&(a=a.slice(1))}if("resume"===a.toLowerCase()){const o=M();return o?(ro(`resume → ${o.command.join(" ")}`),ee=!0,await _o(e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt()):(console.log(),console.log(chalk.gray(" Nothing to resume yet — start with ")+chalk.cyan("learn")+chalk.gray(" (curriculum) or ")+chalk.cyan("demo")+chalk.gray(" (taste).")),console.log(),void oe.prompt())}const s=C()||I()||T()||S();if(!s&&("bg"===a.toLowerCase()||/^bg\s/i.test(a))){const o=a.replace(/^bg\s*/i,"").trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("bg <command>")+chalk.gray(" — run a non-interactive shell command in the background.")),console.log(chalk.gray(" e.g. ")+chalk.cyan("bg nmap -p- 10.0.0.5")+chalk.gray(" · view: ")+chalk.cyan("tasks")),console.log(),void oe.prompt();const e=so(),t=lo(o);ao({cwd:e,input:`bg ${o}`,riskFlags:t}),t.length>0&&P()&&console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`));const n=_(o,e);return console.log(),console.log(chalk.cyan(` ▸ background task #${n.id} started`)+chalk.gray(` (${X()} running)`)),console.log(chalk.gray(" ")+chalk.white(o)),console.log(chalk.gray(" view: ")+chalk.cyan("tasks")+chalk.gray(" · output: ")+chalk.cyan(`tasks ${n.id}`)),console.log(),void oe.prompt()}if(!s&&("tasks"===a.toLowerCase()||/^tasks\s/i.test(a))){const o=a.replace(/^tasks\s*/i,"").trim(),e=W();if(console.log(),o){const e=Q(Number(o));if(!e||Number.isNaN(Number(o)))console.log(chalk.yellow(` No background task #${o}.`)+chalk.gray(" Type ")+chalk.cyan("tasks")+chalk.gray(" to list them."));else{const o="running"===e.status?chalk.yellow:"done"===e.status?chalk.green:chalk.red;console.log(o(` #${e.id} [${e.status}]`)+chalk.white(` ${e.cmd}`)+(null!==e.exitCode?chalk.gray(` (exit ${e.exitCode})`):"")),console.log(chalk.gray(" ─────────────────────────────────────────────"));const t=e.output.trim();if(t)for(const o of t.split("\n"))console.log(chalk.gray(" ")+chalk.white(o));else console.log(chalk.gray(" (no output yet)"))}}else if(0===e.length)console.log(chalk.gray(" No background tasks. Start one with ")+chalk.cyan("bg <command>")+chalk.gray("."));else{console.log(chalk.bold.white(" Background tasks"));for(const o of e){const e="running"===o.status?chalk.yellow("●"):"done"===o.status?chalk.green("✓"):chalk.red("✗"),t=Math.round(((o.endedAt??Date.now())-o.startedAt)/1e3),n=(o.endedAt?`${t}s`:`${t}s…`).padStart(5),l=o.cmd.length>48?`${o.cmd.slice(0,45)}…`:o.cmd;console.log(` ${e} `+chalk.white(`#${o.id}`)+chalk.gray(` ${n} `)+chalk.white(l))}console.log(chalk.gray(" output: ")+chalk.cyan("tasks <id>"))}return console.log(),void oe.prompt()}if(!s&&/&\s*$/.test(a)&&/^challenge\s+start\s+/i.test(a)){const o=a.replace(/\s*&\s*$/,"").trim().replace(/^challenge\s+start\s+/i,"").trim().split(/\s+/),e=o.some(o=>"-n"===o||"--new"===o),t=o.find(o=>"-n"!==o&&"--new"!==o);if(!t)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("challenge start <id> &")),console.log(),void oe.prompt();if(!n())return console.log(),console.log(chalk.red(" Not connected. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" first.")),console.log(),void oe.prompt();ro(`challenge start ${t}${e?" --new":""} & (background)`);const l=B(`challenge start ${t}`,()=>J(t,e),o=>V(t,o));return console.log(),console.log(chalk.cyan(` ▸ background task #${l.id}: `)+chalk.white(`starting ${t}`)+chalk.gray(" — you can keep working; the connection info appears here when it is ready.")),console.log(),void oe.prompt()}if(!s&&a.startsWith("#")){const o=a.slice(1).trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("#<candidate answer>")+chalk.gray(" — stage a flag/answer WITHOUT submitting it. Review with ")+chalk.cyan("drafts")+chalk.gray(".")),console.log(),void oe.prompt();const e=R(),t=e?.session?.examId??null,n=e?e._lastQ||1:null,l=G(o,t,n);return ro(`draft #${l.id} (not submitted)`),console.log(),console.log(chalk.green(` ✎ draft #${l.id} saved`)+(n?chalk.gray(` (Q${n})`):"")+chalk.yellow(" — NOT submitted.")),console.log(chalk.gray(" review with ")+chalk.cyan("drafts")+chalk.gray("; when sure, submit it the normal way.")),console.log(),void oe.prompt()}if(!s&&("drafts"===a.toLowerCase()||/^drafts\s/i.test(a))){const o=a.replace(/^drafts\s*/i,"").trim().toLowerCase();if("clear"===o){const o=K();return console.log(),console.log(chalk.gray(` Cleared ${o} draft${1===o?"":"s"}.`)),console.log(),void oe.prompt()}const e=o.match(/^(?:rm|remove|del|delete)\s+(\d+)$/);if(e){const o=Z(Number(e[1]));return console.log(),console.log(o?chalk.gray(` Removed draft #${e[1]}.`):chalk.yellow(` No draft #${e[1]}.`)),console.log(),void oe.prompt()}const t=R(),n=H(t?.session?.examId??null);if(console.log(),0===n.length)console.log(chalk.gray(" No drafts yet. Stage a candidate with ")+chalk.cyan("#ICOA{maybe_this}")+chalk.gray(" — it won’t submit."));else{console.log(chalk.bold.white(" Draft answers")+chalk.gray(" (staged — not submitted)"));for(const o of n){const e=o.q?chalk.cyan(`Q${o.q}`.padStart(4)):chalk.gray(" · ");console.log(chalk.gray(` #${o.id}`)+` ${e} `+chalk.white(o.text.length>56?`${o.text.slice(0,53)}…`:o.text))}console.log(chalk.gray(" remove: ")+chalk.cyan("drafts rm <id>")+chalk.gray(" · clear all: ")+chalk.cyan("drafts clear"))}return console.log(),void oe.prompt()}if("menu"===a||"menu confirm"===a)return P()&&"menu confirm"!==a?(console.log(),console.log(chalk.yellow(" Real exam active. Progress is auto-saved.")),console.log(chalk.gray(" To return to main menu anyway, type ")+chalk.white("menu confirm")),console.log(),void oe.prompt()):void w(oe);if(C()){ee=!0;const o=await A(a);return ee=!1,"exit"===o&&oe.setPrompt(Lo()),void oe.prompt()}if(I()){ee=!0;const o=await $(a);return ee=!1,"exit"!==o&&"solved"!==o||oe.setPrompt(Lo()),void oe.prompt()}if(T()){ee=!0;const o=await E(a);return ee=!1,"exit"===o&&oe.setPrompt(Lo()),oe.setPrompt(T()?chalk.bold.cyan("icoa ctf4eai> "):Lo()),void oe.prompt()}if(ro(a),"exit"===a)return R()?(console.log(),console.log(chalk.yellow(" ⚠ An exam is in progress.")),console.log(chalk.white(" To return to menu without losing progress, type: ")+chalk.bold.cyan("back")),console.log(chalk.white(" To fully close ICOA CLI, type: ")+chalk.bold.cyan("quit")),console.log(chalk.gray(" Your progress is auto-saved either way.")),console.log(),void oe.prompt()):(console.log(),console.log(chalk.gray(" ")+chalk.white("exit")+chalk.gray(" returns to the main menu. To fully close ICOA CLI, type ")+chalk.bold.cyan("quit")+chalk.gray(".")),"selection"===Ko&&Bo(),void oe.prompt());if("quit"===a||"q"===a||"quit confirm"===a){const o=R();return o&&"demo-free"!==o.session.examId&&"quit confirm"!==a?(console.log(),console.log(chalk.yellow(" ⚠ A real exam is in progress.")),console.log(chalk.gray(" Your answers are auto-saved on the server, but the exam timer keeps ticking")),console.log(chalk.gray(" on the server side even if you close the CLI.")),console.log(),console.log(chalk.white(" To leave the CLI but keep the exam alive, type: ")+chalk.bold.cyan("back")),console.log(chalk.gray(" (recommended — you can resume with ")+chalk.cyan("exam q 1")+chalk.gray(" after relaunching icoa)")),console.log(),console.log(chalk.white(" To really close ICOA CLI, type: ")+chalk.bold.cyan("quit confirm")),console.log(),void oe.prompt()):(o&&"demo-free"===o.session.examId&&(console.log(),console.log(chalk.gray(" Demo paused. Resume with: ")+chalk.white("demo")+chalk.gray(" (fresh) or ")+chalk.white("exam q 1")+chalk.gray(" (continue)."))),co(),yo(),uo(),z(),m(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),oo(),void zo(0))}if("back"===a){const o=R(),e=o&&"demo-free"!==o.session.examId,t=o&&"demo-free"===o.session.examId&&(()=>{const e=new Date(o.session.startedAt||0).getTime();return Date.now()-e<18e5})();if(e)console.log(),console.log(chalk.gray(" Exam paused. Your progress is saved.")),console.log(chalk.white(" Resume: exam q 1")+chalk.gray(" · ")+chalk.white("exam review")+chalk.gray(" · ")+chalk.white("exam submit")),console.log();else if(t){const e=Object.keys(o.answers).length,t=o.session.questionCount;console.log(),console.log(chalk.gray(` Demo paused (${e}/${t} answered). Resume with: `)+chalk.white("exam q 1")),console.log(chalk.gray(" Or type ")+chalk.white("demo")+chalk.gray(" to restart.")),console.log()}else{if(o&&"demo-free"===o.session.examId){const{clearExamState:o}=await import("./lib/exam-state.js");o("demo-free")}const e=l();fetch("https://practice.icoa2026.au/api/icoa/demo-stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"post-report-back",lang:e.language||"en",timestamp:(new Date).toISOString()}),signal:AbortSignal.timeout(5e3)}).catch(()=>{}),"selection"===Ko?Bo():console.log(chalk.gray(" Already at main menu."))}return void oe.prompt()}if("help"===a||"?"===a){if(R()){ee=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return ee=!1,void oe.prompt()}return Qo(i(),Ko),void oe.prompt()}if("man"===a||"manual"===a)return Qo(i(),Ko),console.log(),console.log(chalk.bold.yellow(" ★ Stuck on a tool? ")+chalk.bold.cyan("man <tool>")+chalk.gray(" e.g. ")+chalk.cyan("man steghide")+chalk.gray(" · ")+chalk.cyan("man tools")+chalk.gray(" = full list")),void oe.prompt();if(/^(?:man|manual)\s+\S/i.test(a))return k(a.replace(/^(?:man|manual)\s+/i,"")),void oe.prompt();if("more help"===a.toLowerCase()&&R()){ee=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return ee=!1,void oe.prompt()}if("continue"===a.toLowerCase())return console.log(),console.log(chalk.green.bold(" ═══ AI4CTF — AI as Your Teammate ═══")),console.log(),console.log(chalk.white(" In AI4CTF, you solve cybersecurity challenges")),console.log(chalk.white(" with AI by your side.")),console.log(),console.log(chalk.white(" In this demo, your AI teammate gives help at 3 levels:")),console.log(chalk.yellow(" hint a")+chalk.gray(" General guidance")),console.log(chalk.yellow(" hint b")+chalk.gray(" Deep analysis")),console.log(chalk.yellow(" hint c")+chalk.gray(" Critical assist")),console.log(),console.log(chalk.white(" Try it now! Type: ")+chalk.bold.green("ai4ctf")),console.log(chalk.gray(' Chat freely with your AI teammate. Type "exit" when done.')),console.log(),console.log(chalk.gray(" After ai4ctf, try: ")+chalk.bold.red("ctf4ai")+chalk.gray(' — trick the AI into saying "koala"')),console.log(),void oe.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(a.trim())){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",a.trim()])}catch{}return ee=!1,void oe.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(a.trim())){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",a.trim().toUpperCase()])}catch{}return ee=!1,void oe.prompt()}const r=a.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(r){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",r[1].toUpperCase()])}catch{}return ee=!1,void oe.prompt()}const d=a.match(/^exam\s+([A-Z]{2,3})$/i);if(d){ee=!0;try{await e.parseAsync(["node","icoa","exam","list",d[1]])}catch{}return ee=!1,void oe.prompt()}if("clear"===a||"cls"===a)return console.clear(),void oe.prompt();if("news"===a)return wo()?ho():console.log(chalk.gray(" No competition joined. Use ")+chalk.white("join <url>")+chalk.gray(".")),void oe.prompt();if("memo"===a){if(!wo())return console.log(chalk.gray(" Join a competition first: ")+chalk.white("join <url>")),void oe.prompt();ee=!0;try{await Ao()}catch{}return void(ee=!1)}const p=xo()||bo(l().userName||"");if("jury"===a&&p){ee=!0;try{await ko()}catch{}return void(ee=!1)}if(p&&xo()&&"scoreboard"===a.split(/\s+/)[0]){ee=!0;try{const o=await vo();if(console.log(),0===o.length)console.log(chalk.gray(" Scoreboard is empty."));else{console.log(chalk.bold.white(" Scoreboard"));for(const e of o.slice(0,50))console.log(chalk.gray(` ${String(e.pos).padStart(3)}. `)+chalk.white(e.name.padEnd(28).slice(0,28))+chalk.cyan(String(e.score)))}console.log()}catch{}return ee=!1,void oe.prompt()}if(p&&fo()){const o=a.split(/\s+/)[0];if(["challenges","open","submit","hint"].includes(o))return console.log(),console.log(chalk.yellow(" Team-leader account — the challenge bracket is not available here.")),console.log(chalk.gray(" Available: ")+chalk.white("scoreboard")+chalk.gray(" · ")+chalk.white("news")+chalk.gray(" · ")+chalk.white("jury")+chalk.gray(" · ")+chalk.white("time")+chalk.gray(" · ")+chalk.white("status")+chalk.gray(" · ")+chalk.white("logout")),console.log(),void oe.prompt()}if(a.startsWith("activate ")){const o=a.slice(9).trim(),e=c(o);return"ok"===e?console.log(chalk.green(" Access granted! Token bound to this device.")):"already_bound"===e?(console.log(),console.log(chalk.red(" Token already activated on a different device.")),console.log(chalk.gray(" Each token binds to the first device that uses it. If you lost the device,")),console.log(chalk.gray(" contact your proctor to have the token re-issued for a new device."))):(console.log(),console.log(chalk.red(" Token not recognized.")),console.log(chalk.gray(" Possible reasons:")),console.log(chalk.white(" • ")+chalk.gray("Typo — access tokens are case-insensitive and look like ")+chalk.cyan("ICOA-XXXX-XXXX-XXXX")+chalk.gray(" (4-char hex groups, e.g. ICOA-385E-27F2-B21B)")),console.log(chalk.white(" • ")+chalk.gray("Expired — ask your proctor or organizer for a fresh token")),console.log(chalk.white(" • ")+chalk.gray("Network — verify connection to ")+chalk.cyan("practice.icoa2026.au")),console.log(chalk.gray(" Still stuck? type ")+chalk.cyan("help")+chalk.gray(" or try ")+chalk.cyan("exam demo")+chalk.gray(" for a free practice round."))),console.log(),void oe.prompt()}if("activate"===a)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void oe.prompt();const u=R();if(u){const o=a.toUpperCase().trim(),t=o=>{const e=u.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},n=o=>{const e=u.questions.find(e=>e.number===o);return"short_answer"===e?.type},l=o=>{const e="demo-free"!==u.session.examId,t=u.questions.find(e=>e.number===o),n=F(t?.type,e);console.log(),console.log(chalk.yellow(` Q${o} is a practical question — letters (A/B/C/D) don't apply here.`)),n?(console.log(chalk.white(" Enter the AI chat for this question: ")+chalk.bold.cyan(n)),console.log(chalk.gray(" Or submit a flag directly: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`))):console.log(chalk.gray(" Submit a flag: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`)),console.log()};if(/^[ABCDE]$/.test(o)){const a=u._lastQ||1;if(t(a))return l(a),void oe.prompt();if(n(a))return console.log(),console.log(chalk.yellow(` Q${a} is a short-answer question — type a number, not a letter.`)),console.log(chalk.gray(" Example: ")+chalk.green("42")+chalk.gray(" (or ")+chalk.green(`exam answer ${a} 42`)+chalk.gray(")")),console.log(),void oe.prompt();ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(a),o])}catch{}return ee=!1,void oe.prompt()}if(/^-?\d+$/.test(o)){const t=u._lastQ||1;if(n(t)){ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(t),o])}catch{}return ee=!1,void oe.prompt()}}const s=o.match(/^(\d+)\s+([ABCDE]|-?\d+)$/);if(s){const o=parseInt(s[1],10);if(t(o))return l(o),void oe.prompt();ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",s[1],s[2]])}catch{}return ee=!1,void oe.prompt()}}const h=a.split(/\s+/)[0].toLowerCase(),f=/^python3?(\.\d+)?$/.test(h),b="ls"===h||"pwd"===h,x=a.startsWith("!")||h.startsWith("!")||f||b,O=new Set(["nano","vi","vim","emacs","pico","ed","code","cat","less","more","head","tail","ls","pwd","cd","base64","xxd","hexdump","od","openssl","md5sum","sha256sum","grep","find","awk","sed","strings","file","curl","wget","nc","ping","nmap","echo","bash","sh","zsh","pip","pip3","node","npm"]),j=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${a}`)),console.log()};if("embodied"===Ko&&!x&&!["doctor","demo2","learn","exam","ctf4eai","ctf4vla","eai","arena","lang","ref","setup","env","aienv","ipynb","sim"].includes(h))return O.has(h)?(j(),void oe.prompt()):(console.log(chalk.gray(" Not available in Embodied AI Security mode.")),console.log(chalk.white(" Try ")+chalk.bold.cyan("demo2")+chalk.gray(" (intro) · ")+chalk.bold.cyan("learn")+chalk.gray(" (curriculum) · ")+chalk.bold.cyan("exam <PD-token>")+chalk.gray(" (Paper D)")),console.log(),void oe.prompt());if("selection"===Ko&&!x&&!["doctor","exam","demo","demo2","retry","nations","next","prev","continue","setup","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","aienv","ipynb","sim"].includes(h)){if(O.has(h))return j(),void oe.prompt();if(console.log(chalk.gray(" Not available in Selection mode.")),u){const o=u._lastQ||1;console.log(chalk.white(` Resume exam: exam q ${o}`)+chalk.gray(" · ")+chalk.white("A/B/C/D")+chalk.gray(" to answer"))}else console.log(chalk.gray(" Try: demo · setup to switch mode"));return console.log(),void oe.prompt()}if("organizer"===Ko&&!["doctor","join","exam","demo","retry","next","prev","logout","setup","lang","ref","ctf","mark","unmark","review","submit"].includes(h))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void oe.prompt();if(!("olympiad"!==Ko||i()&&y()||g(h)))return console.log(chalk.yellow(" Restricted mode. ")+chalk.gray("Enter your access token:")),console.log(chalk.white(" activate <token>")),console.log(),console.log(chalk.gray(" Free commands: ")+chalk.white("ref [topic]")+chalk.gray(", ")+chalk.white("help")+chalk.gray(", ")+chalk.white("exit")),console.log(),void oe.prompt();if(!["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","submit","learn","demo2","ctf4eai","ctf4vla","theme","sim","arena","eai","learn-pull","doctor"].includes(h)){if(Ro.has(h))return console.log(chalk.yellow(` "${h}" is a shell command — the ICOA prompt isn't a shell.`)),console.log(chalk.gray(" In real-exam mode, prefix with ! to run inside the sandbox: ")+chalk.cyan(`!${a}`)),console.log(),void oe.prompt();if(/(?:^|\s)(?:\/(?!home\/|Users\/|tmp\/)|\.\.\/|~\/)/.test(a)&&!a.startsWith("cd ")){const o=/(?:^|\s)\/(?!home\/\w+\/icoa-workspace|Users\/\w+\/icoa-workspace|tmp\/)/.test(a),e=/\.\./.test(a);if(o||e)return console.log(chalk.red(" Blocked: access outside workspace is not allowed.")),console.log(chalk.gray(` Workspace: ${Do}`)),console.log(),void oe.prompt()}let o=a.startsWith("!")?a.slice(1).trim():a;if("darwin"===process.platform){const e="/opt/homebrew/opt/python@3.12/bin/python3.12";o=o.replace(/^python3?\s/,`${e} `).replace(/^(python3|python)$/,e)}else if("win32"===process.platform){const e=(()=>{try{return t("py -3 --version",{stdio:["ignore","ignore","ignore"],timeout:1500}),"py -3"}catch{}return"python"})();o=o.replace(/^python3?(\.\d+)?\s/,`${e} `).replace(/^python3?(\.\d+)?$/,e)}else{const e=(()=>{try{return t("which python3.12",{stdio:"ignore"}),"python3.12"}catch{return"python3"}})();o=o.replace(/^python\s/,`${e} `).replace(/^python$/,e)}const e=so(),n=lo(a);ao({cwd:e,input:a,riskFlags:n}),n.length>0&&P()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${n.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=So(Oo(),".icoa");Io(o)||$o(o,{recursive:!0});const e=So(o,"python-startup.py");let t="";if(Io(e))try{t=To(e,"utf-8")}catch{}return t!==jo&&Eo(e,jo),e}()}" ${o}`,console.log(),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log(chalk.bold.white(" Python ready — ICOA exam toolkit pre-loaded")),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log(),console.log(chalk.white(" Already imported: ")+chalk.gray("base64, struct, hashlib, re, json, binascii")),console.log(chalk.white(" Also available: ")+chalk.gray("requests, bs4, numpy, PIL.Image, AES, pad/unpad, xor, p32/u32/p64/u64")),console.log(),console.log(chalk.yellow(" Quick examples:")),console.log(chalk.gray(' base64.b64decode("aGVsbG8=") ')+chalk.gray("# decode base64")),console.log(chalk.gray(' bytes.fromhex("48656c6c6f") ')+chalk.gray("# hex → bytes")),console.log(chalk.gray(' "ICOA{x}".encode() ')+chalk.gray("# str → bytes")),console.log(chalk.gray(" [chr(c) for c in [73,67,79,65]] ")+chalk.gray("# ASCII codes")),console.log(chalk.gray(' xor(bytes.fromhex("0a2b"), b"IC") ')+chalk.gray("# pwntools XOR")),console.log(),console.log(chalk.gray(" Exit: ")+chalk.white("exit()")+chalk.gray(" or Ctrl-D")),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log()),ee=!0;try{await no()&&await eo()?await to(o,oe):await Wo(o,oe,e)}catch{console.log(chalk.yellow(` Command failed: ${h}`))}return ee=!1,console.log(),void oe.prompt()}ee=!0;const N=a.trim(),L=N.toLowerCase();let D,q=null,U="";if(u)if("submit"===L)q="final";else if(L.startsWith("submit ")){let o=N.slice(7).trim();/^submit\s+/i.test(o)&&(o=o.replace(/^submit\s+/i,"").trim()),o=o.replace(/^["'`]+|["'`]+$/g,"").trim(),o&&/^ICOA\{[^}]*\}?$/i.test(o)?(q="flag",U=o):o&&/^[ABCDE]$/i.test(o)&&(q="flag",U=o.toUpperCase())}else/^ICOA\{[^}]+\}$/i.test(N)&&(q="flag",U=N);D="final"===q?["exam","submit"]:"flag"===q?["exam","answer",String(u?._lastQ||1),U]:function(o){const e=o.split(/\s+/),t=e[0].toLowerCase(),n=e.slice(1);if("aienv"===t&&["run","python","py"].includes((n[0]??"").toLowerCase()))return v(o);if(("submit"===t||"flag"===t)&&n.length>=2)return["ctf","submit",n[0],n.slice(1).join(" ").trim().replace(/^["'`]+|["'`]+$/g,"")];if("connect"===t&&n.length>=2){const e=v(o);return["connect",e[1]??n[0],e.slice(2).join(" ")]}const l={demo:["exam","demo"],retry:["exam","demo-retry"],nations:["exam","nations"],next:["exam","next"],prev:["exam","prev"],mark:["exam","mark",...n],unmark:["exam","unmark",...n],review:["exam","review"],logout:["ctf","logout"],join:["ctf","join",...n],activate:["ctf","activate",...n],challenges:["ctf","challenges"],ch:["ctf","challenges"],open:["ctf","open",...n],submit:["ctf","submit",...n],flag:["ctf","submit",...n],scoreboard:["ctf","scoreboard",...n],sb:["ctf","scoreboard",...n],status:["ctf","status"],time:["ctf","time"]};return l[t]?l[t]:["ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","ctf4ai","doctor"].includes(t)?[t,...n]:e}(a);const Y="ctf"===D[0]&&"join"===D[1];Y&&oe.pause(),process.exit=()=>{throw new Error(Po)};try{await e.parseAsync(["node","icoa",...D])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===Po);else if(e.includes("commander.unknownCommand")){const{distance:o}=await import("fastest-levenshtein"),e=["ctf","ref","shell","files","view","connect","challenge","note","notes","logbook","log","manual","lang","setup","env","aienv","ipynb","ai4ctf","exam","ctf4ai","theme","eai","clear","cls","quit","exit","back","menu","help","continue","activate","demo","challenges","status","scoreboard","join","logout"],t=h.split(/\s+/)[0]||h;let n={word:"",dist:1/0};for(const l of e){const e=o(t.toLowerCase(),l);e<n.dist&&(n={word:l,dist:e})}console.log(chalk.yellow(` Unknown command: ${h}.`)),n.dist>0&&n.dist<=2&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(n.word)+chalk.gray("?")),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for the full command list."))}else e.includes("commander.missingArgument")||"commander.missingArgument"===o?.code?"submit"===h||"flag"===h?(console.log(chalk.yellow(" Incomplete — usage: ")+chalk.cyan("submit <challenge#> <flag>")),console.log(chalk.gray(" Put the number AND the flag on one line, e.g. ")+chalk.cyan("submit 44 pecan{...}"))):(console.log(chalk.yellow(` Incomplete command: ${h}`)),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for usage."))):e.includes("commander.")||(e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ETIMEDOUT"))&&console.log(chalk.yellow(" Network error. Check your connection."))}finally{process.exit=zo,ee=!1,Y&&oe.resume()}C()?oe.setPrompt(chalk.magenta("icoa ai4ctf> ")):I()?oe.setPrompt(chalk.red("icoa ctf4ai> ")):T()&&oe.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),oe.prompt()}),oe.on("SIGINT",()=>{if(console.log(),C()||I())console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still in the AI chat.")),console.log(chalk.white(" Type ")+chalk.bold.cyan("exit")+chalk.white(" to leave the chat and return to the menu."));else if(R()){const o="demo-free"!==R().session.examId;console.log(chalk.yellow(" Ctrl+C did NOT close ICOA CLI.")),console.log(chalk.gray(` Your ${o?"exam":"demo"} is paused and every answer is auto-saved.`)),console.log(),console.log(chalk.white(" Resume: ")+chalk.cyan("exam q 1")+chalk.gray(" · Back to menu: ")+chalk.cyan("back")+chalk.gray(" · Close CLI: ")+chalk.cyan(o?"quit confirm":"quit"))}else console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still at the ")+chalk.cyan("icoa>")+chalk.yellow(" prompt.")),console.log(chalk.gray(" Keep typing — ")+chalk.cyan("help")+chalk.gray(" lists commands. (Only ")+chalk.cyan("quit")+chalk.gray(" or Ctrl+D actually close the CLI.)"));console.log(),oe.prompt()}),oe.on("close",()=>{co(),yo(),uo(),z(),m(),oo(),zo(0)}),"1"===process.env.ICOA_AUTO_RESUME&&(delete process.env.ICOA_AUTO_RESUME,M()&&(ee=!0,await _o(e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),oe.prompt()))}function Wo(o,t,n){return new Promise(l=>{const a=process.stdin,s=!!a.isTTY&&!!a.isRaw;if(t.pause(),a.isTTY&&"function"==typeof a.setRawMode)try{a.setRawMode(!1)}catch{}const r=e(o,{shell:!0,stdio:"inherit",cwd:n||process.cwd()}),i=()=>{if(a.isTTY&&"function"==typeof a.setRawMode&&s)try{a.setRawMode(!0)}catch{}t.resume(),l()};r.on("close",i),r.on("error",i)})}function Qo(o,e="olympiad"){return console.log(),"selection"===e||"organizer"===e?(console.log(chalk.bold.white(" Exam")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to exam server")),console.log(chalk.white(" exam list ")+chalk.gray("Available exams")),console.log(chalk.white(" exam start <id> ")+chalk.gray("Begin an exam")),console.log(chalk.white(" exam q [n] ")+chalk.gray("View questions")),console.log(chalk.white(" exam answer <n> <X> ")+chalk.gray("Answer question")),console.log(chalk.white(" exam review ")+chalk.gray("Review all answers")),console.log(chalk.white(" exam submit ")+chalk.gray("Submit for grading")),console.log(chalk.white(" exam result ")+chalk.gray("View your score")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" setup ")+chalk.gray("Settings / switch mode")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log()):o?(console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(chalk.bold.white(" How it works")),console.log(),console.log(chalk.gray(" 1. Browse ")+chalk.white("challenges")+chalk.gray(" and pick one")),console.log(chalk.gray(" 2. ")+chalk.white("open <id>")+chalk.gray(" to read the challenge")),console.log(chalk.gray(" 3. Use ")+chalk.white("ai4ctf")+chalk.gray(" to chat with AI when stuck")),console.log(chalk.gray(" 4. ")+chalk.white("submit <id> <flag>")+chalk.gray(" to score points")),console.log(chalk.gray(" 5. Check ")+chalk.white("scoreboard")+chalk.gray(" to track your rank")),console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(),console.log(chalk.bold.white(" Competition")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to CTFd")),console.log(chalk.white(" challenges (ch) ")+chalk.gray("List challenges by category")),console.log(chalk.white(" open <id> ")+chalk.gray("Read challenge + get next steps")),console.log(chalk.white(" submit <id> <flag> ")+chalk.gray("Submit a flag")),console.log(chalk.white(" scoreboard (sb) ")+chalk.gray("Live rankings")),console.log(chalk.white(" status ")+chalk.gray("Your score & timer")),console.log(chalk.white(" time ")+chalk.gray("Countdown timer")),console.log(),console.log(chalk.bold.white(" AI Teammate")),console.log(chalk.white(" ai4ctf ")+chalk.gray("Free-chat with your AI teammate")),console.log(),console.log(chalk.bold.white(" Tools")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference (linux, web, crypto...)")),console.log(chalk.white(" shell ")+chalk.gray("Interactive CTF shell (sandbox if present, else host)")),console.log(chalk.white(" files <id> ")+chalk.gray("Download challenge files")),console.log(chalk.white(" connect <id> ")+chalk.gray("Connect to remote target")),console.log(chalk.white(" note [text] ")+chalk.gray("Add a logbook entry (in-exam: tags current Q)")),console.log(chalk.white(" logbook [n] ")+chalk.gray("View your logbook (in-exam: filter by Q)")),console.log(chalk.white(" log ")+chalk.gray("Session history")),console.log(chalk.white(" man <tool> ")+chalk.bold.yellow("★ ")+chalk.gray("How to use a tool (steghide, nmap…); ")+chalk.cyan("man tools")+chalk.gray(" = list. Bare ")+chalk.cyan("man")+chalk.gray(" = this list.")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" resume ")+chalk.gray("Continue your last learn card / exam")),console.log(chalk.white(" #<candidate> ")+chalk.gray("Stage a draft answer (never auto-submits)")),console.log(chalk.white(" drafts ")+chalk.gray("Review staged draft answers")),console.log(chalk.white(" bg <command> ")+chalk.gray("Run a shell command in the background")),console.log(chalk.white(" tasks [id] ")+chalk.gray("Background task panel / view output")),console.log(chalk.white(" doctor ")+chalk.gray("Self-check: version, Python, server, tools")),console.log(chalk.white(" setup ")+chalk.gray("Configure settings")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language (15 supported)")),console.log(chalk.white(" logout ")+chalk.gray("Disconnect")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit (session saved)")),void console.log()):(console.log(chalk.bold.yellow(" Restricted Mode — activate with a token to unlock all commands")),console.log(),console.log(chalk.white(" activate <token> ")+chalk.gray("Unlock full access")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log())}