icoa-cli 2.19.418 → 2.19.419

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{spawn as o}from"node:child_process";import{createHash as e}from"node:crypto";import{createReadStream as n,createWriteStream as t,existsSync as a,mkdirSync as r,renameSync as l,rmSync as s,statSync as i}from"node:fs";import{Readable as c}from"node:stream";import{pipeline as d}from"node:stream/promises";import{join as g}from"node:path";import chalk from"chalk";function u(){if(process.env.ICOA_AIDATA_DIR)return process.env.ICOA_AIDATA_DIR;const o="/data/aiproblems";try{if(a(o)&&i(o).isDirectory())return o}catch{}return g(process.cwd(),"icoa-aidata")}function y(o){return g(u(),o.platform,o.id)}function h(o){return o>=1024?`${(o/1024).toFixed(1)}G`:`${o}M`}function f(e,n){return new Promise(t=>{const a=o(e,n,{stdio:"ignore",shell:!1});a.on("error",()=>t(!1)),a.on("close",o=>t(0===o))})}export async function runTeleload(o){const i=await async function(){try{const o=await fetch(process.env.ICOA_TELELOAD_MANIFEST||"https://icoa-datasets.sg-sin-1.linodeobjects.com/aidata/manifest.json",{signal:AbortSignal.timeout(3e4)});if(!o.ok)return null;const e=await o.json(),n=Array.isArray(e?.packs)?e.packs:null;return n?n.slice().sort((o,e)=>o.n-e.n):null}catch{return null}}();if(!i)return console.log(),console.log(chalk.yellow(" Could not reach the dataset node right now.")),console.log(chalk.gray(" Check your connection and try again — nothing was changed.")),void console.log();if(0===i.length)return console.log(),console.log(chalk.gray(" No on-demand datasets are published yet — everything ships inside this machine.")),void console.log();const p=(o??"").trim().replace(/^#/,"");if(""===p)return function(o){console.log(),console.log(chalk.bold.cyan(" ⬇ TELELOAD")+chalk.gray(" · big datasets, pulled straight from the data node")),console.log();for(const e of o){const o=a(y(e))?chalk.green("✓ here"):chalk.gray("⬇ not yet");console.log(` ${chalk.bold.white(String(e.n))}. ${chalk.white(e.id.padEnd(34))}`+chalk.gray(`${h(e.unpacked_mb).padStart(6)} `)+o)}console.log(),console.log(chalk.gray(" Pull one with ")+chalk.cyan("teleload <number>")+chalk.gray(" (e.g. ")+chalk.cyan("teleload 2")+chalk.gray(")")),console.log(chalk.gray(" Everything smaller than 0.6 G already ships inside this machine — no pull needed.")),console.log()}(i);const m=Number.parseInt(p,10);let w=Number.isFinite(m)?i.find(o=>o.n===m):void 0;if(!w){const o=p.toLowerCase();w=i.find(e=>e.id.toLowerCase()===o)??i.find(e=>e.id.toLowerCase().includes(o))}if(!w){console.log(),console.log(chalk.yellow(` No dataset called "${p}".`)),console.log(chalk.gray(" These are the ones you can pull:"));for(const o of i)console.log(chalk.gray(` ${o.n}. ${o.id}`));return console.log(chalk.gray(" Try ")+chalk.cyan(`teleload ${i[0].n}`)+chalk.gray(" — or just ")+chalk.cyan("teleload")+chalk.gray(" to see sizes.")),void console.log()}await async function(o){const i=y(o);if(a(i))return console.log(),console.log(chalk.green(` ✓ ${o.id} is already here`)+chalk.gray(` (${i})`)),console.log(chalk.gray(" Nothing to do. ")+chalk.cyan("teleload")+chalk.gray(" lists the rest.")),void console.log();const p=g(u(),o.platform);r(p,{recursive:!0});const m=g(p,`.${o.id}.tar.zst.part`);if(console.log(),console.log(chalk.bold.white(` ⬇ ${o.id}`)+chalk.gray(` · ${h(o.tar_mb)} packed → ${h(o.unpacked_mb)} on disk · ${o.n_files} files`)),console.log(chalk.gray(" Straight from the Singapore data node — nothing goes through your laptop.")),console.log(),!await async function(o,e){const n=Date.now();let a=0;const r=1048576*o.tar_mb;let l=0;const s=(o=!1)=>{const e=r>0?Math.min(100,Math.round(a/r*100)):0,t=(Date.now()-n)/1e3,l=t>0?a/1048576/t:0,s=Math.round(e/5),i=` ${"█".repeat(s)+"░".repeat(20-s)} ${String(e).padStart(3)}% · ${l.toFixed(1)} MB/s`;process.stdout.write(`\r${chalk.cyan(i)}${o?"\n":""}`)};try{const n=await fetch(o.url,{signal:AbortSignal.timeout(36e5)});if(!n.ok||!n.body)return!1;const r=t(e),i=c.fromWeb(n.body);return i.on("data",o=>{a+=o.length;const e=Date.now();e-l>250&&(l=e,s())}),await d(i,r),s(!0),!0}catch{return process.stdout.write("\n"),!1}}(o,m))return s(m,{force:!0}),console.log(chalk.yellow(" ✗ Download failed.")+chalk.gray(" Nothing was changed — just run it again.")),void console.log();process.stdout.write(chalk.gray(" checking the file is intact… "));const w=await(v=m,new Promise((o,t)=>{const a=e("sha256"),r=n(v);r.on("data",o=>{a.update(o)}),r.on("end",()=>o(a.digest("hex"))),r.on("error",t)})).catch(()=>"");var v;if(o.sha256&&w!==o.sha256)return s(m,{force:!0}),console.log(chalk.yellow("✗")),console.log(chalk.yellow(" The file arrived damaged and was discarded.")+chalk.gray(" Run it again.")),void console.log();console.log(chalk.green("✓")),process.stdout.write(chalk.gray(" unpacking… "));const b=g(p,`.${o.id}.staging`);s(b,{recursive:!0,force:!0});const $=await async function(o,e){if(r(e,{recursive:!0}),await f("tar",["-xf",o,"-C",e]))return!0;if(await f("tar",["--zstd","-xf",o,"-C",e]))return!0;if(await f("tar",["-I","unzstd","-xf",o,"-C",e]))return!0;const n=`${o}.plain`;if(await f("zstd",["-d","-f","-o",n,o])){const o=await f("tar",["-xf",n,"-C",e]);return s(n,{force:!0}),o}return!1}(m,b);if(s(m,{force:!0}),!$)return s(b,{recursive:!0,force:!0}),console.log(chalk.yellow("✗")),console.log(chalk.yellow(" Could not unpack the archive.")+chalk.gray(" Run it again.")),void console.log();const k=g(b,o.id);try{l(a(k)?k:b,i)}catch{return console.log(chalk.yellow("✗")),console.log(chalk.yellow(" Could not move the data into place.")+chalk.gray(" Check disk space.")),void console.log()}s(b,{recursive:!0,force:!0}),console.log(chalk.green("✓")),console.log(),console.log(chalk.green(" 🎁 ready: ")+chalk.white(i)),console.log(chalk.gray(" Open it in a notebook — the path above is the dataset root.")),console.log(chalk.gray(" ")+chalk.cyan("teleload")+chalk.gray(" lists what else is available.")),console.log()}(w)}export function registerTeleloadCommand(o){o.command("teleload").argument("[pack]","pack number (or id) from `teleload`").description("Pull a big dataset from the data node onto this machine").action(async o=>{await runTeleload(o)})}
1
+ import{spawn as o}from"node:child_process";import{createHash as e}from"node:crypto";import{createReadStream as t,createWriteStream as n,existsSync as r,mkdirSync as a,renameSync as s,rmSync as l,statSync as i}from"node:fs";import{Readable as c}from"node:stream";import{pipeline as d}from"node:stream/promises";import{join as g}from"node:path";import chalk from"chalk";function u(){if(process.env.ICOA_AIDATA_DIR)return process.env.ICOA_AIDATA_DIR;const o="/data/aiproblems";try{if(r(o)&&i(o).isDirectory())return o}catch{}return g(process.cwd(),"icoa-aidata")}function f(o){return g(u(),o.platform,o.id)}function h(o){return o>=1024?`${(o/1024).toFixed(1)}G`:`${o}M`}function y(e,t){return new Promise(n=>{const r=o(e,t,{stdio:"ignore",shell:!1});r.on("error",()=>n(!1)),r.on("close",o=>n(0===o))})}async function p(o){const i=f(o);if(r(i))return console.log(),console.log(chalk.green(` ✓ ${o.id} is already here`)+chalk.gray(` (${i})`)),console.log(chalk.gray(" Nothing to do. ")+chalk.cyan("teleload")+chalk.gray(" lists the rest.")),void console.log();const p=g(u(),o.platform);a(p,{recursive:!0});const m=g(p,`.${o.id}.tar.zst.part`);if(console.log(),console.log(chalk.bold.white(` ⬇ ${o.id}`)+chalk.gray(` · ${h(o.tar_mb)} packed → ${h(o.unpacked_mb)} on disk · ${o.n_files} files`)),console.log(chalk.gray(" Straight from the Singapore data node — nothing goes through your laptop.")),console.log(),!await async function(o,e){const t=Date.now();let r=0,a=1048576*o.tar_mb,s=0;const l=Boolean(process.stdout.isTTY);let i=-1;const g=(o=!1)=>{const e=a>0?Math.min(100,Math.round(r/a*100)):0,n=(Date.now()-t)/1e3,s=n>0?r/1048576/n:0,c=r/1048576,d=a/1048576,g=n>=3&&r>=4194304&&s>0&&a>r?(a-r)/1048576/s:0;if(!l){const t=Math.floor(e/25);return void((t>i||o)&&(i=t,console.log(chalk.cyan(` ${String(e).padStart(3)}% · ${c.toFixed(0)}/${d.toFixed(0)} MB · ${s.toFixed(1)} MB/s`))))}const u=Math.round(e/5),f="█".repeat(u)+"░".repeat(20-u),h=o?"":` · ${function(o){if(!Number.isFinite(o)||o<=0)return"--";const e=Math.floor(o/60),t=Math.round(o%60);return e>0?`${e}m${String(t).padStart(2,"0")}s`:`${t}s`}(g)} left`,y=` ${f} ${String(e).padStart(3)}% · ${c.toFixed(0)}/${d.toFixed(0)} MB · ${s.toFixed(1)} MB/s${h}`;process.stdout.write(`\r${chalk.cyan(y)}${" ".repeat(12)}${o?"\n":""}`)};try{const t=await fetch(o.url,{signal:AbortSignal.timeout(36e5)});if(!t.ok||!t.body)return!1;const l=Number(t.headers.get("content-length"));Number.isFinite(l)&&l>0&&(a=l);const i=n(e),u=c.fromWeb(t.body);return u.on("data",o=>{r+=o.length;const e=Date.now();e-s>250&&(s=e,g())}),await d(u,i),g(!0),!0}catch{return process.stdout.write("\n"),!1}}(o,m))return l(m,{force:!0}),console.log(chalk.yellow(" ✗ Download failed.")+chalk.gray(" Nothing was changed — just run it again.")),void console.log();process.stdout.write(chalk.gray(" checking the file is intact… "));const w=await($=m,new Promise((o,n)=>{const r=e("sha256"),a=t($);a.on("data",o=>{r.update(o)}),a.on("end",()=>o(r.digest("hex"))),a.on("error",n)})).catch(()=>"");var $;if(o.sha256&&w!==o.sha256)return l(m,{force:!0}),console.log(chalk.yellow("✗")),console.log(chalk.yellow(" The file arrived damaged and was discarded.")+chalk.gray(" Run it again.")),void console.log();console.log(chalk.green("✓")),process.stdout.write(chalk.gray(" unpacking… "));const b=g(p,`.${o.id}.staging`);l(b,{recursive:!0,force:!0});const v=await async function(o,e){if(a(e,{recursive:!0}),await y("tar",["-xf",o,"-C",e]))return!0;if(await y("tar",["--zstd","-xf",o,"-C",e]))return!0;if(await y("tar",["-I","unzstd","-xf",o,"-C",e]))return!0;const t=`${o}.plain`;if(await y("zstd",["-d","-f","-o",t,o])){const o=await y("tar",["-xf",t,"-C",e]);return l(t,{force:!0}),o}return!1}(m,b);if(l(m,{force:!0}),!v)return l(b,{recursive:!0,force:!0}),console.log(chalk.yellow("✗")),console.log(chalk.yellow(" Could not unpack the archive.")+chalk.gray(" Run it again.")),void console.log();const k=g(b,o.id);try{s(r(k)?k:b,i)}catch{return console.log(chalk.yellow("✗")),console.log(chalk.yellow(" Could not move the data into place.")+chalk.gray(" Check disk space.")),void console.log()}l(b,{recursive:!0,force:!0}),console.log(chalk.green("✓")),console.log(),console.log(chalk.green(" 🎁 ready: ")+chalk.white(i)),console.log(chalk.gray(" Open it in a notebook — the path above is the dataset root.")),console.log(chalk.gray(" ")+chalk.cyan("teleload")+chalk.gray(" lists what else is available.")),console.log()}export async function runTeleload(o){const e=await async function(){try{const o=await fetch(process.env.ICOA_TELELOAD_MANIFEST||"https://icoa-datasets.sg-sin-1.linodeobjects.com/aidata/manifest.json",{signal:AbortSignal.timeout(3e4)});if(!o.ok)return null;const e=await o.json(),t=Array.isArray(e?.packs)?e.packs:null;return t?t.slice().sort((o,e)=>o.n-e.n):null}catch{return null}}();if(!e)return console.log(),console.log(chalk.yellow(" Could not reach the dataset node right now.")),console.log(chalk.gray(" Check your connection and try again — nothing was changed.")),void console.log();if(0===e.length)return console.log(),console.log(chalk.gray(" No on-demand datasets are published yet — everything ships inside this machine.")),void console.log();const t=(o??"").trim().replace(/^#/,"");if(""===t)return function(o){console.log(),console.log(chalk.bold.cyan(" ⬇ TELELOAD")+chalk.gray(" · big datasets, pulled straight from the data node")),console.log();for(const e of o){const o=r(f(e))?chalk.green("✓ here"):chalk.gray("⬇ not yet");console.log(` ${chalk.bold.white(String(e.n))}. ${chalk.white(e.id.padEnd(34))}`+chalk.gray(`${h(e.unpacked_mb).padStart(6)} `)+o)}console.log(),console.log(chalk.gray(" Pull one with ")+chalk.cyan("teleload <number>")+chalk.gray(" (e.g. ")+chalk.cyan("teleload 2")+chalk.gray(")")),console.log(chalk.gray(" Everything smaller than 0.6 G already ships inside this machine — no pull needed.")),console.log()}(e);const n=Number.parseInt(t,10);let a=Number.isFinite(n)?e.find(o=>o.n===n):void 0;if(!a){const o=t.toLowerCase();a=e.find(e=>e.id.toLowerCase()===o)??e.find(e=>e.id.toLowerCase().includes(o))}if(!a){console.log(),console.log(chalk.yellow(` No dataset called "${t}".`)),console.log(chalk.gray(" These are the ones you can pull:"));for(const o of e)console.log(chalk.gray(` ${o.n}. ${o.id}`));return console.log(chalk.gray(" Try ")+chalk.cyan(`teleload ${e[0].n}`)+chalk.gray(" — or just ")+chalk.cyan("teleload")+chalk.gray(" to see sizes.")),void console.log()}await p(a)}export function registerTeleloadCommand(o){o.command("teleload").argument("[pack]","pack number (or id) from `teleload`").description("Pull a big dataset from the data node onto this machine").action(async o=>{await runTeleload(o)})}
@@ -26,6 +26,7 @@ export type LearnInputResolution = {
26
26
  } | {
27
27
  kind: 'token';
28
28
  token: string;
29
+ from?: string;
29
30
  } | {
30
31
  kind: 'ambiguous';
31
32
  hint: string;
@@ -1 +1 @@
1
- const t={ai4ctf:"AI4CTFDEMO01",ctf4ai:"CTF4AIDEMO01",ctf4eai:"LEARNDEMO01","ai4ctf-12":"AI4CTFDEMO01","ctf4ai-12":"CTF4AIDEMO01","ctf4eai-12":"LEARNDEMO01","ioai-jr":"IOAIJRDEMO01","ioai-jr-48":"IOAIJRDEMO01",ioaijr:"IOAIJRDEMO01",junior:"IOAIJRDEMO01",jr:"IOAIJRDEMO01",ioaijrdemo:"IOAIJRDEMO01",ctf4vla:"LEARNDEMO01",vla:"LEARNDEMO01",embodied:"LEARNDEMO01",ai4ctfdemo:"AI4CTFDEMO01",ctf4aidemo:"CTF4AIDEMO01",learndemo:"LEARNDEMO01"},e={1:"AI4CTFDEMO01",2:"CTF4AIDEMO01",3:"LEARNDEMO01"},i=/^[A-Z]{2}[A-Z0-9]{6,}$/,o=/^(AI4CTFDEMO\d+|CTF4AIDEMO\d+|LEARNDEMO\d+)$/;export function resolveLearnInput(n){const a=n.trim();if(!a)return{kind:"back"};if(/^(back|b|quit|q|exit|menu|home)$/i.test(a))return{kind:"back"};const r=a.replace(/^\s*(?:[/>])?\s*(?:icoa\s+)?learn\s+/i,"").trim();if(!r)return{kind:"ambiguous",hint:"Type just the token (e.g. LEARNDEMO01) or one of: ai4ctf / ctf4ai / ctf4eai"};if(e[r])return{kind:"token",token:e[r]};const c=r.toLowerCase();if(t[c])return{kind:"token",token:t[c]};if("demo"===c||"demos"===c)return{kind:"ambiguous",hint:"Which demo? Type: 1 (ai4ctf) / 2 (ctf4ai) / 3 (ctf4eai)"};if(/\s/.test(r))return{kind:"unknown",hint:`Don't recognize "${a}". Try a track name (ai4ctf / ctf4ai / ctf4eai / junior), 1/2/3, a demo id like LEARNDEMO01, or paste your token (2 letters + 8 chars). Blank to go back.`};const E=r.toUpperCase();return o.test(E)||i.test(E)||/^[A-Z0-9]{8,}$/.test(E)?{kind:"token",token:E}:{kind:"unknown",hint:`Don't recognize "${a}". Try one of: ai4ctf / ctf4ai / ctf4eai (for the free demos), 1/2/3, or paste your AC/CA/EA/EI/IO/IA + 8 chars cohort token. Blank to go back.`}}
1
+ const e={ai4ctf:"AI4CTFDEMO01",ctf4ai:"CTF4AIDEMO01",ctf4eai:"LEARNDEMO01","ai4ctf-12":"AI4CTFDEMO01","ctf4ai-12":"CTF4AIDEMO01","ctf4eai-12":"LEARNDEMO01","ioai-jr":"IOAIJRDEMO01","ioai-jr-48":"IOAIJRDEMO01",ioaijr:"IOAIJRDEMO01",junior:"IOAIJRDEMO01",jr:"IOAIJRDEMO01",ioaijrdemo:"IOAIJRDEMO01",ctf4vla:"LEARNDEMO01",vla:"LEARNDEMO01",embodied:"LEARNDEMO01",ai4ctfdemo:"AI4CTFDEMO01",ctf4aidemo:"CTF4AIDEMO01",learndemo:"LEARNDEMO01"},t={1:"AI4CTFDEMO01",2:"CTF4AIDEMO01",3:"LEARNDEMO01"},o=/^[A-Z0-9]{2,}DEMO\d+$/,i={biology:"BIODEMO01",bio:"BIODEMO01",coretools:"COREDEMO01","core-tools":"COREDEMO01",core:"COREDEMO01",worldmodel:"WMDEMO01","world-model":"WMDEMO01",wm:"WMDEMO01",arsenal:"ARSDEMO01",cybersec:"CYBERDEMO01",sc:"CYBERDEMO01",neuroscience:"NEURODEMO01",informatics:"IOIPYDEMO01",physics:"PHYSICSDEMO01",chemistry:"CHEMDEMO01",economics:"ECONDEMO01"};export function resolveLearnInput(n){const r=n.trim();if(!r)return{kind:"back"};if(/^(back|b|quit|q|exit|menu|home)$/i.test(r))return{kind:"back"};const a=r.replace(/^\s*(?:[/>])?\s*(?:icoa\s+)?learn\s+/i,"").trim();if(!a)return{kind:"ambiguous",hint:"Type just the token (e.g. LEARNDEMO01) or one of: ai4ctf / ctf4ai / ctf4eai"};if(t[a])return{kind:"token",token:t[a]};const E=a.toLowerCase();if(e[E])return{kind:"token",token:e[E]};if(i[E])return{kind:"token",token:i[E]};if("demo"===E||"demos"===E)return{kind:"ambiguous",hint:"Which demo? Type: 1 (ai4ctf) / 2 (ctf4ai) / 3 (ctf4eai)"};if(/\s/.test(a))return{kind:"unknown",hint:`Don't recognize "${r}". Try a track name (ai4ctf / ctf4ai / ctf4eai / junior), 1/2/3, a demo id like LEARNDEMO01, or paste your token (2 letters + 8 chars). Blank to go back.`};const c=a.toUpperCase();return o.test(c)||/^[A-Z]{2}[A-Z0-9]{8}$/.test(c)?{kind:"token",token:c}:/^[a-z][a-z0-9-]{2,15}$/.test(E)&&!E.includes("demo")?{kind:"token",token:`${E.replace(/-/g,"").toUpperCase()}DEMO01`,from:E}:/^[A-Z0-9]{8,}$/.test(c)&&/\d/.test(c)?{kind:"token",token:c}:{kind:"unknown",hint:`Don't recognize "${r}". Try a track name (e.g. ai4ctf, biology, ioipy), a demo id like LEARNDEMO01, or paste your cohort token (2 letters + 8 characters). Blank to go back.`}}
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{distance as n}from"fastest-levenshtein";import{isConnected as l,getConfig as a,saveConfig as s}from"./lib/config.js";import{ensureLangCache as r}from"./lib/translations-fetcher.js";import{loadUiPack as i}from"./lib/i18n.js";import{isActivated as c,activateToken as g,isFreeCommand as y,isDeviceMatch as m,recordExit as d,recordResume as u,isFirstRunOrUpgrade as p,markVersionSeen as h}from"./lib/access.js";import{setReplMode as w}from"./lib/ui.js";import{returnToMainMenu as f,printMenuHint as b,menuHintInline as x}from"./lib/menu-nav.js";import{setMainRl as v}from"./lib/main-rl.js";import{shellSplit as k}from"./lib/shell-split.js";import{isChatActive as C,handleChatMessage as A}from"./commands/ai4ctf.js";import{renderToolMan as I}from"./lib/tool-man.js";import{isCtf4aiActive as $,handleCtf4aiMessage as T}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as E,handleCtf4VlaMessage as S}from"./commands/ctf4vla.js";import{isDemo2Active as O}from"./commands/demo2.js";import{isCardDeckActive as j}from"./lib/card-engine.js";import{loadDemo2Progress as N}from"./lib/demo2-progress.js";import{hasAnySimHistory as L,lastArmAt as D,lastBundledAt as P,lastSimAt as R}from"./lib/sim-cooldown.js";import{getExamState as q,getRealExamState as F,getDemoState as U,practicalChatCommand as M}from"./lib/exam-state.js";import{resolveResumePoint as _}from"./lib/resume.js";import{buildStatusLine as B}from"./lib/statusline.js";import{startBgTask as W,startAsyncTask as Q,listBgTasks as Y,getBgTask as X,drainCompleted as z,killAllBgTasks as J,runningCount as V}from"./lib/bgtasks.js";import{computeStart as G,renderStart as H}from"./commands/challenge.js";import{addDraft as Z,listDrafts as K,removeDraft as oo,clearDrafts as eo}from"./lib/drafts.js";import{resetTerminalTheme as to}from"./lib/theme.js";import{ensureSandbox as no,runInSandbox as lo,isDockerAvailable as ao}from"./lib/sandbox.js";import{checkShellRisk as so,logShellAudit as ro,getActiveCwd as io}from"./lib/exam-sandbox.js";import{logCommand as co}from"./lib/logger.js";import{startLogSync as go,stopLogSync as yo}from"./lib/log-sync.js";import{installInputDynamics as mo,uninstallInputDynamics as uo,stripPasteMarkers as po}from"./lib/input-dynamics.js";import{startBroadcastPoll as ho,stopBroadcastPoll as wo,showBroadcast as fo,isCompetitionJoined as bo,isMelCompetition as xo,isLeaderAccount as vo,isLeaderSession as ko,fetchPublicScoreboard as Co,isCommsActive as Ao}from"./lib/comms.js";import{enterMemoScreen as Io,enterJuryScreen as $o}from"./commands/comms.js";import{existsSync as To,mkdirSync as Eo,readFileSync as So,writeFileSync as Oo}from"node:fs";import{join as jo}from"node:path";import{homedir as No}from"node:os";const Lo="# 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",Do=Date.now();function Po(){return xo()?chalk.yellow("icoa 2026> "):F()?chalk.cyan("icoa exam> "):function(){const o=U();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=Do}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const Ro=jo(No(),"icoa-workspace"),qo=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),Fo="__REPL_NO_EXIT__",Uo="2.5.1",Mo=["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","kaggle","teleload","guide","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","learn","demo2","demo4","demo5","ctf4eai","ctf4vla","theme","sim","arena","eai","board","learn-pull","doctor","bg","tasks","drafts","help","menu","quit","q","exit","back","resume","clear","cls"];export function nearestCommand(o,e=2){const t=o.trim().toLowerCase();if(!t)return null;let l={word:"",dist:Number.POSITIVE_INFINITY};for(const o of Mo){const e=n(t,o);e<l.dist&&(l={word:o,dist:e})}return l.dist>0&&l.dist<=e?l.word:null}const _o={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 Bo(o){const e=o.replace(/^\s+/,"");if(/^\/\S*$/.test(e)){const o=e.slice(1).toLowerCase();return[Mo.filter(e=>e.startsWith(o)).map(o=>`/${o}`),e]}const t=e.split(/\s+/);if(t.length<=1){const o=(t[0]??"").toLowerCase();return[Mo.filter(e=>e.startsWith(o)).slice(),o]}if(2===t.length){const o=_o[t[0].toLowerCase()];if(o){const e=t[1].toLowerCase();return[o.filter(o=>o.startsWith(e)).slice(),e]}}return[[],o]}async function Wo(o){const e=_();if(!e)return null;const t=process.exit;process.exit=()=>{throw new Error(Fo)};try{await o.parseAsync(["node","icoa",...e.command])}catch(o){if(!(o instanceof Error&&o.message===Fo))throw o}finally{process.exit=t}return e}function Qo(){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,n){process.env.ICOA_INSIDE_REPL="1";let k=!1;if(xo()){const o=a().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)||(s({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:"",joinedAt:""}),k=!0)}const U=a(),Do=l(),_o=process.exit.bind(process),zo=c();if(U.language&&"en"!==U.language&&(await r(U.language,{silent:!0}),i(U.language)),U.demoCleanedForVersion!==Uo){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{}s({demoCleanedForVersion:Uo})}const{select:Jo,confirm:Vo}=await import("@inquirer/prompts"),Go=U.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("free demo or team 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;const e=process.env.ICOA_TEST_BOOT_MODE;if(e&&["instant","learn","selection","olympiad"].includes(e))o=e;else 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}if("about"!==o)Ko=o;else{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 · 20+ languages")),console.log(),console.log(chalk.bold.white(" Three Frontiers of AI Security")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" AI as teammate — 5 CTF disciplines, 5-hour endurance round")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" AI as target — the AI system itself is the objective")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" Embodied-AI Arena — probe robot policies in live simulation")}`),console.log(),console.log(chalk.bold.white(" First Edition — Sydney 2026 ")+chalk.green.bold("✓ held")),console.log(chalk.gray(" · Jun 27 - Jul 2, 2026 · University of Technology Sydney")),console.log(chalk.gray(" · 65 competitors · 20 countries & regions (10 on-site, 10 remote)")),console.log(chalk.gray(" · 36 awards — 6 Gold · 11 Silver · 17 Bronze · 2 Honorable Mentions")),console.log(chalk.gray(" · Champion: Oleg Uteshev · Embodied-AI Arena Gold: Kingsley Lim (AU)")),console.log(chalk.gray(" · Founding Charter signed — ICOA is now a permanent institution")),console.log(),console.log(chalk.bold.white(" Next: ICOA 2027")+chalk.gray(" — 20 more countries already accredited")),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")+chalk.gray(" · press: ")+chalk.cyan.underline("https://icoa2026.au/press/")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log();try{const{input:o}=await import("@inquirer/prompts"),e=()=>o({message:chalk.gray("Press Enter to return..."),theme:{prefix:"",style:{message:o=>o}}}),t=Date.now();await e(),Date.now()-t<200&&await e()}catch{}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&&s({mode:Ko}),console.log(),"olympiad"===Ko&&p(Uo)){h(Uo),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(n){const o=u();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(),Qo();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=P()>0||R()>0,e=D()>0,t=L(),n=N(),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(),b(),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(" Three 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(chalk.bold.green(" kaggle")+chalk.gray(" ML practice — train a model, real board ")+chalk.bold.magenta("📊 data-science")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(", ")+chalk.bold.cyan("demo2")+chalk.gray(" or ")+chalk.bold.cyan("kaggle")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),s({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=async()=>{try{await o({message:chalk.bold.yellow("Press Enter to return to the menu"),theme:{prefix:"",style:{message:o=>o}}})}catch{}},l=3;for(let a=1;a<=l;a++){const r=await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}),i=r.trim().toLowerCase();if("ai4ioai"===i||"/ai4ioai"===i){const{runAi4ioaiStandalone:o}=await import("./commands/ai4ioai.js");return await o(),await n(),s({mode:"selection"}),void f()}if("ioailab"===i||"/ioailab"===i){const{runIoailabStandalone:o}=await import("./commands/ioailab.js");return await o(),await n(),s({mode:"selection"}),void f()}const c=t(r);if("back"===c.kind)break;if("ambiguous"===c.kind||"unknown"===c.kind){if(console.log(),console.log(chalk.yellow(` ${c.hint}`)),console.log(),a===l){console.log(chalk.gray(` That was attempt ${l} of ${l} — going back to the menu.`)),console.log(chalk.gray(" Your token comes from your country team leader; the free demos need no token.")),console.log(),await n();break}continue}if(!/^[A-Z0-9]+DEMO01$/i.test(c.token)&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(c.token)){console.log(),console.log(chalk.gray(" Checking token…"));const{validateEAToken:o}=await import("./lib/learn-curricula.js"),e=await o(c.token);if(!e.ok){if(console.log(),console.log(chalk.red(` ✗ Token check failed: ${e.message||"validation failed"}`)+(e.code?chalk.gray(` [${e.code}]`):"")),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer. Ask the coordinator who issued")),console.log(chalk.gray(" it to move it to this device, then try again."))):"expired"===e.code?console.log(chalk.gray(" This learn token has expired — ask your coordinator for a new one.")):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)"))),console.log(),a<l){console.log(chalk.gray(" Try again — or press Enter to go back.")),console.log();continue}await n();break}}console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${c.token}`)),console.log(),s({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";const{setLearnSessionStarted:g}=await import("./lib/learn-outcome.js");g(!1);try{await e.parseAsync(["node","icoa","learn",c.token])}catch(o){console.log(),console.log(chalk.red(` ✗ learn failed to start: ${o instanceof Error?o.message:String(o)}`)),console.log()}finally{delete process.env.ICOA_LEARN_EMBEDDED}await n();break}}catch{}return s({mode:"selection"}),void f()}"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(),Do?(console.log(chalk.green(` Logged in as ${U.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(),b(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),zo&&!m()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):Do?(console.log(chalk.green.bold(` Welcome back, ${U.userName}!`)),console.log(chalk.gray(` Connected to ${U.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(" · ")+x()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):zo?(To(Ro)||Eo(Ro,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${Ro}`)),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 · ")+x()+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 · ")+x()+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:Po(),terminal:!0,completer:Bo});v(oe),mo(!1!==a().bracketedPaste);let ee=!1;if(w(!0),go(),k&&(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()),xo()){const o=a().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()&&(s({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()}bo()&&ho(()=>oe.prompt());let te=null;const ne=oe.prompt.bind(oe);oe.prompt=o=>{if(!(C()||$()||E()||O()||j()||Ao()||(oe.setPrompt(Po()),o)))try{for(const o of z()){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=B();o&&o!==te?(console.log(o),te=o):o||(te=null)}catch{}ne(o)};const le=_();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 n=po(o.trim());if(!n)return oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Po()),void oe.prompt();if(/^icoa\s+\S/i.test(n)&&(n=n.replace(/^icoa\s+/i,"")),n.startsWith("/")&&!n.startsWith("//")){const o=n.slice(1).split(/\s+/)[0].toLowerCase(),t=n.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($())return void(o?await T(o):console.log(chalk.gray(" You are already in the CTF4AI target chat — just type your message.")));if(E())return void(o?await S(o):console.log(chalk.gray(" You are already in the Embodied-AI chat — just type your message.")));co(o?`/ai ${o}`:"/ai");const t=process.exit;process.exit=()=>{throw new Error(Fo)};try{await e.parseAsync(["node","icoa","ai4ctf"])}catch(o){if(!(o instanceof Error&&o.message===Fo))throw o}finally{process.exit=t}o&&C()&&await A(o)}(t,e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Po()),void oe.prompt();!(C()||$()||E()||O()||j()||Ao())&&Mo.includes(o)&&(n=n.slice(1))}if("resume"===n.toLowerCase()){const o=_();return o?(co(`resume → ${o.command.join(" ")}`),ee=!0,await Wo(e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Po()),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()||$()||E()||O()||j();if(!s&&("bg"===n.toLowerCase()||/^bg\s/i.test(n))){const o=n.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=io(),t=so(o);ro({cwd:e,input:`bg ${o}`,riskFlags:t}),t.length>0&&F()&&console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`));const l=W(o,e);return console.log(),console.log(chalk.cyan(` ▸ background task #${l.id} started`)+chalk.gray(` (${V()} running)`)),console.log(chalk.gray(" ")+chalk.white(o)),console.log(chalk.gray(" view: ")+chalk.cyan("tasks")+chalk.gray(" · output: ")+chalk.cyan(`tasks ${l.id}`)),console.log(),void oe.prompt()}if(!s&&("tasks"===n.toLowerCase()||/^tasks\s/i.test(n))){const o=n.replace(/^tasks\s*/i,"").trim(),e=Y();if(console.log(),o){const e=X(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(n)&&/^challenge\s+start\s+/i.test(n)){const o=n.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(!l())return console.log(),console.log(chalk.red(" Not connected. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" first.")),console.log(),void oe.prompt();co(`challenge start ${t}${e?" --new":""} & (background)`);const a=Q(`challenge start ${t}`,()=>G(t,e),o=>H(t,o));return console.log(),console.log(chalk.cyan(` ▸ background task #${a.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&&n.startsWith("#")){const o=n.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=q(),t=e?.session?.examId??null,l=e?e._lastQ||1:null,a=Z(o,t,l);return co(`draft #${a.id} (not submitted)`),console.log(),console.log(chalk.green(` ✎ draft #${a.id} saved`)+(l?chalk.gray(` (Q${l})`):"")+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"===n.toLowerCase()||/^drafts\s/i.test(n))){const o=n.replace(/^drafts\s*/i,"").trim().toLowerCase();if("clear"===o){const o=eo();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=oo(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=q(),l=K(t?.session?.examId??null);if(console.log(),0===l.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 l){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"===n||"menu confirm"===n)return F()&&"menu confirm"!==n?(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 f(oe);if(C()){ee=!0;const o=await A(n);return ee=!1,"exit"===o&&oe.setPrompt(Po()),void oe.prompt()}if($()){ee=!0;const o=await T(n);return ee=!1,"exit"!==o&&"solved"!==o||oe.setPrompt(Po()),void oe.prompt()}if(E()){ee=!0;const o=await S(n);return ee=!1,"exit"===o&&oe.setPrompt(Po()),oe.setPrompt(E()?chalk.bold.cyan("icoa ctf4eai> "):Po()),void oe.prompt()}if(co(n),"exit"===n)return q()?(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&&Qo(),void oe.prompt());if("quit"===n||"q"===n||"quit confirm"===n){const o=q();return o&&"demo-free"!==o.session.examId&&"quit confirm"!==n?(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)."))),yo(),uo(),wo(),J(),d(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),to(),void _o(0))}if("back"===n){const o=q(),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=a();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?Qo():console.log(chalk.gray(" Already at main menu."))}return void oe.prompt()}if("help"===n||"?"===n){if(q()){ee=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return ee=!1,void oe.prompt()}return Xo(c(),Ko),void oe.prompt()}if("man"===n||"manual"===n)return Xo(c(),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(n))return I(n.replace(/^(?:man|manual)\s+/i,"")),void oe.prompt();if("more help"===n.toLowerCase()&&q()){ee=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return ee=!1,void oe.prompt()}if("continue"===n.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(n.trim())){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim()])}catch{}return ee=!1,void oe.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(n.trim())){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim().toUpperCase()])}catch{}return ee=!1,void oe.prompt()}const r=n.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 i=n.match(/^exam\s+([A-Z]{2,3})$/i);if(i){ee=!0;try{await e.parseAsync(["node","icoa","exam","list",i[1]])}catch{}return ee=!1,void oe.prompt()}if("clear"===n||"cls"===n)return console.clear(),void oe.prompt();if("news"===n)return bo()?fo():console.log(chalk.gray(" No competition joined. Use ")+chalk.white("join <url>")+chalk.gray(".")),void oe.prompt();if("memo"===n){if(!bo())return console.log(chalk.gray(" Join a competition first: ")+chalk.white("join <url>")),void oe.prompt();ee=!0;try{await Io()}catch{}return void(ee=!1)}const u=ko()||vo(a().userName||"");if("jury"===n&&u){ee=!0;try{await $o()}catch{}return void(ee=!1)}if(u&&ko()&&"scoreboard"===n.split(/\s+/)[0]){ee=!0;try{const o=await Co();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(u&&xo()){const o=n.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(n.startsWith("activate ")){const o=n.slice(9).trim(),e=g(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"===n)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void oe.prompt();const p=q();if(p){const o=n.toUpperCase().trim(),t=o=>{const e=p.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},l=o=>{const e=p.questions.find(e=>e.number===o);return"short_answer"===e?.type},a=o=>{const e="demo-free"!==p.session.examId,t=p.questions.find(e=>e.number===o),n=M(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 n=p._lastQ||1;if(t(n))return a(n),void oe.prompt();if(l(n))return console.log(),console.log(chalk.yellow(` Q${n} 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 ${n} 42`)+chalk.gray(")")),console.log(),void oe.prompt();ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(n),o])}catch{}return ee=!1,void oe.prompt()}if(/^-?\d+$/.test(o)){const t=p._lastQ||1;if(l(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 a(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=n.split(/\s+/)[0].toLowerCase(),w=/^python3?(\.\d+)?$/.test(h),b="ls"===h||"pwd"===h||"tmux"===h,x=n.startsWith("!")||h.startsWith("!")||w||b,v=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"]),k=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${n}`)),console.log()};if("embodied"===Ko&&!x&&!["doctor","demo2","learn","exam","ctf4eai","ctf4vla","eai","arena","lang","ref","setup","env","aienv","ipynb","kaggle","teleload","guide","sim"].includes(h))return v.has(h)?(k(),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","demo4","demo5","retry","nations","next","prev","continue","setup","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","aienv","ipynb","kaggle","teleload","guide","sim"].includes(h)){if(v.has(h))return k(),void oe.prompt();if(console.log(chalk.gray(" Not available in Selection mode.")),p){const o=p._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","tmux"].includes(h))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void oe.prompt();if(!("olympiad"!==Ko||c()&&m()||y(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","kaggle","teleload","guide","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","submit","learn","demo2","demo4","demo5","ctf4eai","ctf4vla","theme","sim","arena","eai","board","learn-pull","doctor"].includes(h)){if("tmux"===h)try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("env setup")+chalk.gray(" (full toolkit) or ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(".")),console.log(),void oe.prompt()}if(qo.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(`!${n}`)),console.log(),void oe.prompt();if(/(?:^|\s)(?:\/(?!home\/|Users\/|tmp\/)|\.\.\/|~\/)/.test(n)&&!n.startsWith("cd ")){const o=/(?:^|\s)\/(?!home\/\w+\/icoa-workspace|Users\/\w+\/icoa-workspace|tmp\/)/.test(n),e=/\.\./.test(n);if(o||e)return console.log(chalk.red(" Blocked: access outside workspace is not allowed.")),console.log(chalk.gray(` Workspace: ${Ro}`)),console.log(),void oe.prompt()}let o=n.startsWith("!")?n.slice(1).trim():n;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=io(),l=so(n);ro({cwd:e,input:n,riskFlags:l}),l.length>0&&F()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${l.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=jo(No(),".icoa");To(o)||Eo(o,{recursive:!0});const e=jo(o,"python-startup.py");let t="";if(To(e))try{t=So(e,"utf-8")}catch{}return t!==Lo&&Oo(e,Lo),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 ao()&&await no()?await lo(o,oe):await Yo(o,oe,e)}catch{console.log(chalk.yellow(` Command failed: ${h}`))}return ee=!1,console.log(),void oe.prompt()}ee=!0;const N=n.trim(),L=N.toLowerCase();let D,P=null,R="";if(p)if("submit"===L)P="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)?(P="flag",R=o):o&&/^[ABCDE]$/i.test(o)&&(P="flag",R=o.toUpperCase())}else/^ICOA\{[^}]+\}$/i.test(N)&&(P="flag",R=N);D="final"===P?["exam","submit"]:"flag"===P?["exam","answer",String(p?._lastQ||1),R]:mapCommand(n);const U="ctf"===D[0]&&"join"===D[1];U&&oe.pause(),process.exit=()=>{throw new Error(Fo)};try{await e.parseAsync(["node","icoa",...D])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===Fo);else if(e.includes("commander.unknownCommand")){const o=nearestCommand(h.split(/\s+/)[0]||h);console.log(chalk.yellow(` Unknown command: ${h}.`)),o&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(o)+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=_o,ee=!1,U&&oe.resume()}C()?oe.setPrompt(chalk.magenta("icoa ai4ctf> ")):$()?oe.setPrompt(chalk.red("icoa ctf4ai> ")):E()&&oe.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),oe.prompt()}),oe.on("SIGINT",()=>{if(console.log(),C()||$())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(q()){const o="demo-free"!==q().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",()=>{yo(),uo(),wo(),J(),d(),to(),_o(0)}),"1"===process.env.ICOA_AUTO_RESUME&&(delete process.env.ICOA_AUTO_RESUME,_()&&(ee=!0,await Wo(e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Po()),oe.prompt()))}function Yo(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",e=>{if(127===e){const e=nearestCommand(o.trim().split(/\s+/)[0]??"");e&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(e)+chalk.gray("?"))}i()}),r.on("error",i)})}export function mapCommand(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 k(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=k(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]:[t,...n]}function Xo(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{distance as n}from"fastest-levenshtein";import{isConnected as l,getConfig as a,saveConfig as s}from"./lib/config.js";import{ensureLangCache as r}from"./lib/translations-fetcher.js";import{loadUiPack as i}from"./lib/i18n.js";import{isActivated as c,activateToken as g,isFreeCommand as y,isDeviceMatch as m,recordExit as d,recordResume as p,isFirstRunOrUpgrade as u,markVersionSeen as h}from"./lib/access.js";import{setReplMode as w}from"./lib/ui.js";import{returnToMainMenu as f,printMenuHint as b,menuHintInline as x}from"./lib/menu-nav.js";import{setMainRl as v}from"./lib/main-rl.js";import{shellSplit as k}from"./lib/shell-split.js";import{isChatActive as C,handleChatMessage as A}from"./commands/ai4ctf.js";import{renderToolMan as I}from"./lib/tool-man.js";import{isCtf4aiActive as $,handleCtf4aiMessage as T}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as E,handleCtf4VlaMessage as S}from"./commands/ctf4vla.js";import{isDemo2Active as O}from"./commands/demo2.js";import{isCardDeckActive as j}from"./lib/card-engine.js";import{loadDemo2Progress as N}from"./lib/demo2-progress.js";import{hasAnySimHistory as L,lastArmAt as D,lastBundledAt as P,lastSimAt as R}from"./lib/sim-cooldown.js";import{getExamState as q,getRealExamState as F,getDemoState as U,practicalChatCommand as M}from"./lib/exam-state.js";import{resolveResumePoint as _}from"./lib/resume.js";import{buildStatusLine as B}from"./lib/statusline.js";import{startBgTask as W,startAsyncTask as Q,listBgTasks as Y,getBgTask as X,drainCompleted as z,killAllBgTasks as V,runningCount as J}from"./lib/bgtasks.js";import{computeStart as H,renderStart as Z}from"./commands/challenge.js";import{addDraft as G,listDrafts as K,removeDraft as oo,clearDrafts as eo}from"./lib/drafts.js";import{resetTerminalTheme as to}from"./lib/theme.js";import{ensureSandbox as no,runInSandbox as lo,isDockerAvailable as ao}from"./lib/sandbox.js";import{checkShellRisk as so,logShellAudit as ro,getActiveCwd as io}from"./lib/exam-sandbox.js";import{logCommand as co}from"./lib/logger.js";import{startLogSync as go,stopLogSync as yo}from"./lib/log-sync.js";import{installInputDynamics as mo,uninstallInputDynamics as po,stripPasteMarkers as uo}from"./lib/input-dynamics.js";import{startBroadcastPoll as ho,stopBroadcastPoll as wo,showBroadcast as fo,isCompetitionJoined as bo,isMelCompetition as xo,isLeaderAccount as vo,isLeaderSession as ko,fetchPublicScoreboard as Co,isCommsActive as Ao}from"./lib/comms.js";import{enterMemoScreen as Io,enterJuryScreen as $o}from"./commands/comms.js";import{existsSync as To,mkdirSync as Eo,readFileSync as So,writeFileSync as Oo}from"node:fs";import{join as jo}from"node:path";import{homedir as No}from"node:os";const Lo="# 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",Do=Date.now();function Po(){return xo()?chalk.yellow("icoa 2026> "):F()?chalk.cyan("icoa exam> "):function(){const o=U();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=Do}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const Ro=jo(No(),"icoa-workspace"),qo=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),Fo="__REPL_NO_EXIT__",Uo="2.5.1",Mo=["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","kaggle","teleload","guide","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","learn","demo2","demo4","demo5","ctf4eai","ctf4vla","theme","sim","arena","eai","board","learn-pull","doctor","bg","tasks","drafts","help","menu","quit","q","exit","back","resume","clear","cls"];export function nearestCommand(o,e=2){const t=o.trim().toLowerCase();if(!t)return null;let l={word:"",dist:Number.POSITIVE_INFINITY};for(const o of Mo){const e=n(t,o);e<l.dist&&(l={word:o,dist:e})}return l.dist>0&&l.dist<=e?l.word:null}const _o={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"]},Bo=new Set(["answer","demo","demo-retry","help","list","mark","more-help","nations","next","prev","q","reset","result","review","setup","start","submit","token","unmark","status","time"]);function Wo(o){const e=o.replace(/^\s+/,"");if(/^\/\S*$/.test(e)){const o=e.slice(1).toLowerCase();return[Mo.filter(e=>e.startsWith(o)).map(o=>`/${o}`),e]}const t=e.split(/\s+/);if(t.length<=1){const o=(t[0]??"").toLowerCase();return[Mo.filter(e=>e.startsWith(o)).slice(),o]}if(2===t.length){const o=_o[t[0].toLowerCase()];if(o){const e=t[1].toLowerCase();return[o.filter(o=>o.startsWith(e)).slice(),e]}}return[[],o]}async function Qo(o){const e=_();if(!e)return null;const t=process.exit;process.exit=()=>{throw new Error(Fo)};try{await o.parseAsync(["node","icoa",...e.command])}catch(o){if(!(o instanceof Error&&o.message===Fo))throw o}finally{process.exit=t}return e}function Yo(){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,n){process.env.ICOA_INSIDE_REPL="1";let k=!1;if(xo()){const o=a().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)||(s({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:"",joinedAt:""}),k=!0)}const U=a(),Do=l(),_o=process.exit.bind(process),Vo=c();if(U.language&&"en"!==U.language&&(await r(U.language,{silent:!0}),i(U.language)),U.demoCleanedForVersion!==Uo){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{}s({demoCleanedForVersion:Uo})}const{select:Jo,confirm:Ho}=await import("@inquirer/prompts"),Zo=U.mode||"",Go=""===Zo?"instant":["instant","learn","selection","olympiad"].includes(Zo)?Zo:"selection",Ko=[{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("free demo or team 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"}];""===Zo&&(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 oe="";for(;!oe;){let o;const e=process.env.ICOA_TEST_BOOT_MODE;if(e&&["instant","learn","selection","olympiad"].includes(e))o=e;else try{o=await Jo({message:"Mode",choices:Ko,default:Go||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}if("about"!==o)oe=o;else{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 · 20+ languages")),console.log(),console.log(chalk.bold.white(" Three Frontiers of AI Security")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" AI as teammate — 5 CTF disciplines, 5-hour endurance round")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" AI as target — the AI system itself is the objective")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" Embodied-AI Arena — probe robot policies in live simulation")}`),console.log(),console.log(chalk.bold.white(" First Edition — Sydney 2026 ")+chalk.green.bold("✓ held")),console.log(chalk.gray(" · Jun 27 - Jul 2, 2026 · University of Technology Sydney")),console.log(chalk.gray(" · 65 competitors · 20 countries & regions (10 on-site, 10 remote)")),console.log(chalk.gray(" · 36 awards — 6 Gold · 11 Silver · 17 Bronze · 2 Honorable Mentions")),console.log(chalk.gray(" · Champion: Oleg Uteshev · Embodied-AI Arena Gold: Kingsley Lim (AU)")),console.log(chalk.gray(" · Founding Charter signed — ICOA is now a permanent institution")),console.log(),console.log(chalk.bold.white(" Next: ICOA 2027")+chalk.gray(" — 20 more countries already accredited")),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")+chalk.gray(" · press: ")+chalk.cyan.underline("https://icoa2026.au/press/")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log();try{const{input:o}=await import("@inquirer/prompts"),e=()=>o({message:chalk.gray("Press Enter to return..."),theme:{prefix:"",style:{message:o=>o}}}),t=Date.now();await e(),Date.now()-t<200&&await e()}catch{}console.clear()}}if("olympiad"===oe&&"olympiad"!==Go){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await Ho({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(oe="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(oe!==Go&&s({mode:oe}),console.log(),"olympiad"===oe&&u(Uo)){h(Uo),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(n){const o=p();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"===oe)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),Yo();else if("embodied"===oe)!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=P()>0||R()>0,e=D()>0,t=L(),n=N(),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(),b(),console.log()}();else if("instant"===oe)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Three 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(chalk.bold.green(" kaggle")+chalk.gray(" ML practice — train a model, real board ")+chalk.bold.magenta("📊 data-science")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(", ")+chalk.bold.cyan("demo2")+chalk.gray(" or ")+chalk.bold.cyan("kaggle")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),s({mode:"selection"}),oe="selection";else{if("learn"===oe){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=async()=>{try{await o({message:chalk.bold.yellow("Press Enter to return to the menu"),theme:{prefix:"",style:{message:o=>o}}})}catch{}},l=3;for(let a=1;a<=l;a++){const r=await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}),i=r.trim().toLowerCase();if("ai4ioai"===i||"/ai4ioai"===i){const{runAi4ioaiStandalone:o}=await import("./commands/ai4ioai.js");return await o(),await n(),s({mode:"selection"}),void f()}if("ioailab"===i||"/ioailab"===i){const{runIoailabStandalone:o}=await import("./commands/ioailab.js");return await o(),await n(),s({mode:"selection"}),void f()}const c=t(r);if("back"===c.kind)break;if("ambiguous"===c.kind||"unknown"===c.kind){if(console.log(),console.log(chalk.yellow(` ${c.hint}`)),console.log(),a===l){console.log(chalk.gray(` That was attempt ${l} of ${l} — going back to the menu.`)),console.log(chalk.gray(" Your token comes from your country team leader; the free demos need no token.")),console.log(),await n();break}continue}if(c.from){const{loadCurriculumById:o}=await import("./lib/learn-curricula.js");if(!await o(c.token,c.token)){if(console.log(),console.log(chalk.yellow(` No free demo for "${c.from}".`)),console.log(chalk.gray(" Free demos exist for most tracks — try ")+chalk.bold.green("ai4ctf")+chalk.gray(", ")+chalk.bold.green("biology")+chalk.gray(", ")+chalk.bold.green("ioipy")+chalk.gray(". With a cohort token, paste the token itself.")),console.log(),a===l){await n();break}continue}}if(!/^[A-Z0-9]+DEMO01$/i.test(c.token)&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(c.token)){console.log(),console.log(chalk.gray(" Checking token…"));const{validateEAToken:o}=await import("./lib/learn-curricula.js"),e=await o(c.token);if(!e.ok){if(console.log(),console.log(chalk.red(` ✗ Token check failed: ${e.message||"validation failed"}`)+(e.code?chalk.gray(` [${e.code}]`):"")),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer. Ask the coordinator who issued")),console.log(chalk.gray(" it to move it to this device, then try again."))):"expired"===e.code?console.log(chalk.gray(" This learn token has expired — ask your coordinator for a new one.")):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)"))),console.log(),a<l){console.log(chalk.gray(" Try again — or press Enter to go back.")),console.log();continue}await n();break}}console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${c.token}`)),console.log(),s({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";const{setLearnSessionStarted:g}=await import("./lib/learn-outcome.js");g(!1);try{await e.parseAsync(["node","icoa","learn",c.token])}catch(o){console.log(),console.log(chalk.red(` ✗ learn failed to start: ${o instanceof Error?o.message:String(o)}`)),console.log()}finally{delete process.env.ICOA_LEARN_EMBEDDED}await n();break}}catch{}return s({mode:"selection"}),void f()}"organizer"===oe?(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(),Do?(console.log(chalk.green(` Logged in as ${U.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(),b(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),Vo&&!m()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):Do?(console.log(chalk.green.bold(` Welcome back, ${U.userName}!`)),console.log(chalk.gray(` Connected to ${U.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(" · ")+x()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):Vo?(To(Ro)||Eo(Ro,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${Ro}`)),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 · ")+x()+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 · ")+x()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}const ee=o=>{o.exitOverride(),o.configureOutput({writeErr:o=>{const e=o.replace(/^error:\s*/i,"").trim();e&&console.log(chalk.yellow(` ${e}`))},writeOut:o=>{console.log(o)}});for(const e of o.commands)ee(e)};ee(e);const te=o({input:process.stdin,output:process.stdout,prompt:Po(),terminal:!0,completer:Wo});v(te),mo(!1!==a().bracketedPaste);let ne=!1;if(w(!0),go(),k&&(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()),xo()){const o=a().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=>{te.question(chalk.white(" > "),e=>o(e.trim()))})).toLowerCase()&&(s({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()}bo()&&ho(()=>te.prompt());let le=null;const ae=te.prompt.bind(te);te.prompt=o=>{if(!(C()||$()||E()||O()||j()||Ao()||(te.setPrompt(Po()),o)))try{for(const o of z()){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=B();o&&o!==le?(console.log(o),le=o):o||(le=null)}catch{}ae(o)};const se=_();se&&(console.log(chalk.cyan(" ↻ Continue where you left off: ")+chalk.white(se.label)+(se.urgent?chalk.yellow(" (exam timer running)"):"")),console.log(chalk.gray(" type ")+chalk.cyan("resume")+chalk.gray(" to jump back in.")),console.log()),te.prompt(),te.on("line",async o=>{if(ne)return;let n=uo(o.trim());if(!n)return te.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Po()),void te.prompt();if(/^icoa\s+\S/i.test(n)&&(n=n.replace(/^icoa\s+/i,"")),n.startsWith("/")&&!n.startsWith("//")){const o=n.slice(1).split(/\s+/)[0].toLowerCase(),t=n.slice(1+o.length).trim();if("ai"===o)return ne=!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($())return void(o?await T(o):console.log(chalk.gray(" You are already in the CTF4AI target chat — just type your message.")));if(E())return void(o?await S(o):console.log(chalk.gray(" You are already in the Embodied-AI chat — just type your message.")));co(o?`/ai ${o}`:"/ai");const t=process.exit;process.exit=()=>{throw new Error(Fo)};try{await e.parseAsync(["node","icoa","ai4ctf"])}catch(o){if(!(o instanceof Error&&o.message===Fo))throw o}finally{process.exit=t}o&&C()&&await A(o)}(t,e),ne=!1,te.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Po()),void te.prompt();!(C()||$()||E()||O()||j()||Ao())&&Mo.includes(o)&&(n=n.slice(1))}if("resume"===n.toLowerCase()){const o=_();return o?(co(`resume → ${o.command.join(" ")}`),ne=!0,await Qo(e),ne=!1,te.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Po()),void te.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 te.prompt())}const s=C()||$()||E()||O()||j();if(!s&&("bg"===n.toLowerCase()||/^bg\s/i.test(n))){const o=n.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 te.prompt();const e=io(),t=so(o);ro({cwd:e,input:`bg ${o}`,riskFlags:t}),t.length>0&&F()&&console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`));const l=W(o,e);return console.log(),console.log(chalk.cyan(` ▸ background task #${l.id} started`)+chalk.gray(` (${J()} running)`)),console.log(chalk.gray(" ")+chalk.white(o)),console.log(chalk.gray(" view: ")+chalk.cyan("tasks")+chalk.gray(" · output: ")+chalk.cyan(`tasks ${l.id}`)),console.log(),void te.prompt()}if(!s&&("tasks"===n.toLowerCase()||/^tasks\s/i.test(n))){const o=n.replace(/^tasks\s*/i,"").trim(),e=Y();if(console.log(),o){const e=X(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 te.prompt()}if(!s&&/&\s*$/.test(n)&&/^challenge\s+start\s+/i.test(n)){const o=n.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 te.prompt();if(!l())return console.log(),console.log(chalk.red(" Not connected. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" first.")),console.log(),void te.prompt();co(`challenge start ${t}${e?" --new":""} & (background)`);const a=Q(`challenge start ${t}`,()=>H(t,e),o=>Z(t,o));return console.log(),console.log(chalk.cyan(` ▸ background task #${a.id}: `)+chalk.white(`starting ${t}`)+chalk.gray(" — you can keep working; the connection info appears here when it is ready.")),console.log(),void te.prompt()}if(!s&&n.startsWith("#")){const o=n.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 te.prompt();const e=q(),t=e?.session?.examId??null,l=e?e._lastQ||1:null,a=G(o,t,l);return co(`draft #${a.id} (not submitted)`),console.log(),console.log(chalk.green(` ✎ draft #${a.id} saved`)+(l?chalk.gray(` (Q${l})`):"")+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 te.prompt()}if(!s&&("drafts"===n.toLowerCase()||/^drafts\s/i.test(n))){const o=n.replace(/^drafts\s*/i,"").trim().toLowerCase();if("clear"===o){const o=eo();return console.log(),console.log(chalk.gray(` Cleared ${o} draft${1===o?"":"s"}.`)),console.log(),void te.prompt()}const e=o.match(/^(?:rm|remove|del|delete)\s+(\d+)$/);if(e){const o=oo(Number(e[1]));return console.log(),console.log(o?chalk.gray(` Removed draft #${e[1]}.`):chalk.yellow(` No draft #${e[1]}.`)),console.log(),void te.prompt()}const t=q(),l=K(t?.session?.examId??null);if(console.log(),0===l.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 l){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 te.prompt()}if("menu"===n||"menu confirm"===n)return F()&&"menu confirm"!==n?(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 te.prompt()):void f(te);if(C()){ne=!0;const o=await A(n);return ne=!1,"exit"===o&&te.setPrompt(Po()),void te.prompt()}if($()){ne=!0;const o=await T(n);return ne=!1,"exit"!==o&&"solved"!==o||te.setPrompt(Po()),void te.prompt()}if(E()){ne=!0;const o=await S(n);return ne=!1,"exit"===o&&te.setPrompt(Po()),te.setPrompt(E()?chalk.bold.cyan("icoa ctf4eai> "):Po()),void te.prompt()}if(co(n),"exit"===n)return q()?(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 te.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"===oe&&Yo(),void te.prompt());if("quit"===n||"q"===n||"quit confirm"===n){const o=q();return o&&"demo-free"!==o.session.examId&&"quit confirm"!==n?(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 te.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)."))),yo(),po(),wo(),V(),d(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),to(),void _o(0))}if("back"===n){const o=q(),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=a();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"===oe?Yo():console.log(chalk.gray(" Already at main menu."))}return void te.prompt()}if("help"===n||"?"===n){if(q()){ne=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return ne=!1,void te.prompt()}return zo(c(),oe),void te.prompt()}if("man"===n||"manual"===n)return zo(c(),oe),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 te.prompt();if(/^(?:man|manual)\s+\S/i.test(n))return I(n.replace(/^(?:man|manual)\s+/i,"")),void te.prompt();if("more help"===n.toLowerCase()&&q()){ne=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return ne=!1,void te.prompt()}if("continue"===n.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 te.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(n.trim())){ne=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim()])}catch{}return ne=!1,void te.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(n.trim())){ne=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim().toUpperCase()])}catch{}return ne=!1,void te.prompt()}const r=n.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(r){ne=!0;try{await e.parseAsync(["node","icoa","exam","token",r[1].toUpperCase()])}catch{}return ne=!1,void te.prompt()}const i=n.match(/^exam\s+([A-Z]{2,3})$/i);if(i){ne=!0;try{await e.parseAsync(["node","icoa","exam","list",i[1]])}catch{}return ne=!1,void te.prompt()}const p=n.match(/^exam\s+(\S+)$/i);if(p&&!Bo.has(p[1].toLowerCase())){const o=p[1].toUpperCase(),{normalizeTokenBody:t}=await import("./lib/token-format.js"),n=t(o),l=/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/;if(console.log(),l.test(n)){console.log(chalk.yellow(` Corrected look-alike characters: ${o} → ${n}`)),ne=!0;try{await e.parseAsync(["node","icoa","exam","token",n])}catch{}return ne=!1,void te.prompt()}return console.log(chalk.red(` ✗ Not a valid exam token: ${o}`)),console.log(),console.log(chalk.gray(" An exam token is ")+chalk.bold.white("2 letters + 8 characters")+chalk.gray(" (e.g. ")+chalk.bold.yellow("AUHXP7SWMM")+chalk.gray(`) — yours is ${o.length}.`)),console.log(chalk.gray(" Check for 0/O, 1/I/L, V/U mix-ups, or ask your country team leader.")),console.log(),console.log(chalk.gray(" No token yet? Try ")+chalk.bold.green("demo")+chalk.gray(" (free practice paper) or ")+chalk.bold.green("exam nations")+chalk.gray(" to see participating countries.")),console.log(),void te.prompt()}if("clear"===n||"cls"===n)return console.clear(),void te.prompt();if("news"===n)return bo()?fo():console.log(chalk.gray(" No competition joined. Use ")+chalk.white("join <url>")+chalk.gray(".")),void te.prompt();if("memo"===n){if(!bo())return console.log(chalk.gray(" Join a competition first: ")+chalk.white("join <url>")),void te.prompt();ne=!0;try{await Io()}catch{}return void(ne=!1)}const u=ko()||vo(a().userName||"");if("jury"===n&&u){ne=!0;try{await $o()}catch{}return void(ne=!1)}if(u&&ko()&&"scoreboard"===n.split(/\s+/)[0]){ne=!0;try{const o=await Co();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 ne=!1,void te.prompt()}if(u&&xo()){const o=n.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 te.prompt()}if(n.startsWith("activate ")){const o=n.slice(9).trim(),e=g(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 te.prompt()}if("activate"===n)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void te.prompt();const h=q();if(h){const o=n.toUpperCase().trim(),t=o=>{const e=h.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},l=o=>{const e=h.questions.find(e=>e.number===o);return"short_answer"===e?.type},a=o=>{const e="demo-free"!==h.session.examId,t=h.questions.find(e=>e.number===o),n=M(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 n=h._lastQ||1;if(t(n))return a(n),void te.prompt();if(l(n))return console.log(),console.log(chalk.yellow(` Q${n} 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 ${n} 42`)+chalk.gray(")")),console.log(),void te.prompt();ne=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(n),o])}catch{}return ne=!1,void te.prompt()}if(/^-?\d+$/.test(o)){const t=h._lastQ||1;if(l(t)){ne=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(t),o])}catch{}return ne=!1,void te.prompt()}}const s=o.match(/^(\d+)\s+([ABCDE]|-?\d+)$/);if(s){const o=parseInt(s[1],10);if(t(o))return a(o),void te.prompt();ne=!0;try{await e.parseAsync(["node","icoa","exam","answer",s[1],s[2]])}catch{}return ne=!1,void te.prompt()}}const w=n.split(/\s+/)[0].toLowerCase(),b=/^python3?(\.\d+)?$/.test(w),x="ls"===w||"pwd"===w||"tmux"===w,v=n.startsWith("!")||w.startsWith("!")||b||x,k=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"]),N=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${n}`)),console.log()};if("embodied"===oe&&!v&&!["doctor","demo2","learn","exam","ctf4eai","ctf4vla","eai","arena","lang","ref","setup","env","aienv","ipynb","kaggle","teleload","guide","sim"].includes(w))return k.has(w)?(N(),void te.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 te.prompt());if("selection"===oe&&!v&&!["doctor","exam","demo","demo2","demo4","demo5","retry","nations","next","prev","continue","setup","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","aienv","ipynb","kaggle","teleload","guide","sim"].includes(w)){if(k.has(w))return N(),void te.prompt();if(console.log(chalk.gray(" Not available in Selection mode.")),h){const o=h._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 te.prompt()}if("organizer"===oe&&!["doctor","join","exam","demo","retry","next","prev","logout","setup","lang","ref","ctf","mark","unmark","review","submit","tmux"].includes(w))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void te.prompt();if(!("olympiad"!==oe||c()&&m()||y(w)))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 te.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","kaggle","teleload","guide","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","submit","learn","demo2","demo4","demo5","ctf4eai","ctf4vla","theme","sim","arena","eai","board","learn-pull","doctor"].includes(w)){if("tmux"===w)try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("env setup")+chalk.gray(" (full toolkit) or ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(".")),console.log(),void te.prompt()}if(qo.has(w))return console.log(chalk.yellow(` "${w}" 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(`!${n}`)),console.log(),void te.prompt();if(/(?:^|\s)(?:\/(?!home\/|Users\/|tmp\/)|\.\.\/|~\/)/.test(n)&&!n.startsWith("cd ")){const o=/(?:^|\s)\/(?!home\/\w+\/icoa-workspace|Users\/\w+\/icoa-workspace|tmp\/)/.test(n),e=/\.\./.test(n);if(o||e)return console.log(chalk.red(" Blocked: access outside workspace is not allowed.")),console.log(chalk.gray(` Workspace: ${Ro}`)),console.log(),void te.prompt()}let o=n.startsWith("!")?n.slice(1).trim():n;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=io(),l=so(n);ro({cwd:e,input:n,riskFlags:l}),l.length>0&&F()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${l.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=jo(No(),".icoa");To(o)||Eo(o,{recursive:!0});const e=jo(o,"python-startup.py");let t="";if(To(e))try{t=So(e,"utf-8")}catch{}return t!==Lo&&Oo(e,Lo),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()),ne=!0;try{await ao()&&await no()?await lo(o,te):await Xo(o,te,e)}catch{console.log(chalk.yellow(` Command failed: ${w}`))}return ne=!1,console.log(),void te.prompt()}ne=!0;const L=n.trim(),D=L.toLowerCase();let P,R=null,U="";if(h)if("submit"===D)R="final";else if(D.startsWith("submit ")){let o=L.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)?(R="flag",U=o):o&&/^[ABCDE]$/i.test(o)&&(R="flag",U=o.toUpperCase())}else/^ICOA\{[^}]+\}$/i.test(L)&&(R="flag",U=L);P="final"===R?["exam","submit"]:"flag"===R?["exam","answer",String(h?._lastQ||1),U]:mapCommand(n);const B="ctf"===P[0]&&"join"===P[1];B&&te.pause(),process.exit=()=>{throw new Error(Fo)};try{await e.parseAsync(["node","icoa",...P])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===Fo);else if(e.includes("commander.unknownCommand")){const o=nearestCommand(w.split(/\s+/)[0]||w);console.log(chalk.yellow(` Unknown command: ${w}.`)),o&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(o)+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"===w||"flag"===w?(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: ${w}`)),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=_o,ne=!1,B&&te.resume()}C()?te.setPrompt(chalk.magenta("icoa ai4ctf> ")):$()?te.setPrompt(chalk.red("icoa ctf4ai> ")):E()&&te.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),te.prompt()}),te.on("SIGINT",()=>{if(console.log(),C()||$())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(q()){const o="demo-free"!==q().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(),te.prompt()}),te.on("close",()=>{yo(),po(),wo(),V(),d(),to(),_o(0)}),"1"===process.env.ICOA_AUTO_RESUME&&(delete process.env.ICOA_AUTO_RESUME,_()&&(ne=!0,await Qo(e),ne=!1,te.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Po()),te.prompt()))}function Xo(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",e=>{if(127===e){const e=nearestCommand(o.trim().split(/\s+/)[0]??"");e&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(e)+chalk.gray("?"))}i()}),r.on("error",i)})}export function mapCommand(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 k(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=k(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]:[t,...n]}function zo(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())}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.418",
3
+ "version": "2.19.419",
4
4
  "description": "ICOA CLI — The world's first CLI-native cyber & AI security olympiad terminal: AI4CTF (Day 1), CTF4AI (Day 2), VLA4CTF (Pioneer Round — embodied AI)",
5
5
  "type": "module",
6
6
  "bin": {