icoa-cli 2.19.379 → 2.19.381

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ import type { Command } from 'commander';
2
+ export declare function runKaggle(compArg?: string): Promise<void>;
3
+ export declare function runKaggleCheck(compArg?: string): Promise<void>;
4
+ export declare function registerKaggleCommand(program: Command): void;
@@ -0,0 +1 @@
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as l,writeFileSync as t}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as i}from"../lib/repl-asker.js";import{openFile as a}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{buildStarterCells as r,parseKaggleTaskList as g,validateSubmissionText as u}from"../lib/kaggle.js";async function m(o){try{const e=await fetch((process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au")+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}function y(){console.log(),console.log(chalk.yellow(" The practice server is not reachable right now.")),console.log(chalk.gray(" Check your connection, or try again later.")),console.log()}function p(o){return s(process.cwd(),"icoa-kaggle",o)}function d(o){console.log(chalk.bold.white(" Submit on Kaggle (manual, your own account):")),o?.kaggle_url?(console.log(chalk.gray(" 1. open ")+chalk.cyan(o.kaggle_url)),console.log(chalk.gray(" 2. Submit Predictions → upload ")+chalk.white("submission.csv")),console.log(chalk.gray(" 3. read your score, improve the MODEL cell, re-run, repeat."))):(console.log(chalk.gray(" (placeholder dataset — no live Kaggle page yet; when the real")),console.log(chalk.gray(" competition dataset lands, its submission link will appear here.)")))}export async function runKaggle(n){const l=i(),a=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · train locally · submit on Kaggle yourself")),console.log(chalk.gray(" Small real-format datasets, a runnable starter notebook, your own CPU.")),console.log();const l=await m("/api/icoa/kaggle/tasks");if(!l)return y();const i=g(l);if(0===i.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let u=n?i.find(o=>o.comp_id===n):void 0;if(n&&!u&&console.log(chalk.yellow(` No competition called "${n}".`)),!u){console.log(chalk.white(" Live practice competitions:")),i.forEach((o,e)=>{console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`))});for(let o=0;o<3&&!u;o++){const o=(await a(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);u=!Number.isNaN(e)&&i[e-1]||i.find(e=>e.comp_id===o.toLowerCase())||void 0,u||console.log(chalk.gray(` Try a number 1-${i.length} or an id like "${i[0].comp_id}".`))}if(!u)return}const b=u.comp_id;console.log(),console.log(chalk.white(` ${u.title}`)+chalk.gray(` · ${u.metric}`)),console.log(chalk.gray(" Downloading data…"));const f=await m(`/api/icoa/kaggle/${b}/data`),h=f?.data??f;if(!h?.train||!h?.test||!h?.sample_submission)return y();const w=p(b),k={...u,...h.meta??{}};try{e(w,{recursive:!0}),t(s(w,"train.csv"),h.train),t(s(w,"test.csv"),h.test),t(s(w,"sample_submission.csv"),h.sample_submission),t(s(w,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const v=s(w,"starter.ipynb");let $=!1;o(v)?$=!0:t(v,c(r(w,k)));const _="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",K="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(w,"train.csv"))+chalk.gray(` (${_})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(w,"test.csv"))+chalk.gray(` (${K})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(w,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(v)+chalk.gray($?" (kept your existing one)":" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${v}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${b}`)),console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline.")),console.log(),d(k),console.log()}finally{l.close()}}export async function runKaggleCheck(e){console.log();let t=e;if(!t){const e=s(process.cwd(),"icoa-kaggle"),n=o(e)?l(e,{withFileTypes:!0}).filter(n=>n.isDirectory()&&o(s(e,n.name,"sample_submission.csv"))).map(o=>o.name):[];if(1!==n.length){if(0===n.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),void console.log();console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of n)console.log(chalk.gray(" kaggle check ")+chalk.cyan(o));return void console.log()}t=n[0]}const i=p(t),c=s(i,"submission.csv"),r=s(i,"sample_submission.csv");if(!o(r))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(c))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(i,"starter.ipynb")}`)),void console.log();const g=u(n(c,"utf-8"),n(r,"utf-8"));let m=null;try{m=JSON.parse(n(s(i,"meta.json"),"utf-8"))}catch{m=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv is Kaggle-ready")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(c)),console.log(),d(m),a(i);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" to validate submission.csv').argument("[comp]",'competition id (with "check")').description("Kaggle-style ML practice — dataset + starter notebook, submit on Kaggle yourself").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):await runKaggle(o)})}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as a}from"./commands/challenge.js";import{registerDoctorCommand as l}from"./commands/doctor.js";import{registerNoteCommand as m}from"./commands/note.js";import{registerLogCommand as c}from"./commands/log.js";import{registerLangCommand as d}from"./commands/lang.js";import{registerSetupCommand as g}from"./commands/setup.js";import{registerEnvCommand as p}from"./commands/env.js";import{registerAienvCommand as y}from"./commands/aienv.js";import{registerIpynbCommand as f}from"./commands/ipynb.js";import{registerAi4ctfCommand as h}from"./commands/ai4ctf.js";import{registerExamCommand as u}from"./commands/exam.js";import{registerCtf4aiDemoCommand as w}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as T}from"./commands/theme.js";import{registerLearnCommand as b}from"./commands/learn.js";import{registerCtf4VlaCommand as v}from"./commands/ctf4vla.js";import{registerDemo2Command as j}from"./commands/demo2.js";import{registerSimCommand as A}from"./commands/sim.js";import{registerArenaCommand as I}from"./commands/arena.js";import{registerBoardCommand as $}from"./commands/board.js";import{getConfig as C,saveConfig as E}from"./lib/config.js";import{startRepl as _}from"./repl.js";import{RELAUNCH_CODE as S}from"./lib/menu-nav.js";import{setTerminalTheme as x}from"./lib/theme.js";import{checkForUpdates as O}from"./lib/update-check.js";import{detectIcoaInstalls as L}from"./lib/platform.js";import{ICOA_BIG as N}from"./lib/banner.js";import{readFileSync as R}from"node:fs";import{fileURLToPath as k}from"node:url";import{dirname as F,join as U}from"node:path";const P=F(k(import.meta.url)),M=JSON.parse(R(U(P,"..","package.json"),"utf-8")).version,G=chalk.cyan(" ─────────────────────────────────────────────────────"),D=`\n${G}\n\n${N.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${M}`)}\n\n${G}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=o(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(s.signal){e=0;break}e=s.status,n=!0}while(e===S);process.exit(e??0)}}const H=new o;if(H.name("icoa").version(M).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=C();x("high-contrast"===e.themeVariant?"high-contrast":"dark"),O(),function(){const o=L();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();console.log(D);const s=!!o.resume||!!o.continue;if(process.argv.length<=2||s)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),s||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void _(H,s)}),e(H),n(H),s(H),r(H),t(H),i(H),a(H),l(H),m(H),c(H),d(H),g(H),p(H),y(H),f(H),h(H),u(H),w(H),T(H),b(H),v(H),j(H),A(H),I(H),$(H),H.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=C().geminiModel||"gemini-2.5-flash-lite";o?(E({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}H.parse();
2
+ import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as a}from"./commands/challenge.js";import{registerDoctorCommand as l}from"./commands/doctor.js";import{registerNoteCommand as m}from"./commands/note.js";import{registerLogCommand as c}from"./commands/log.js";import{registerLangCommand as g}from"./commands/lang.js";import{registerSetupCommand as d}from"./commands/setup.js";import{registerEnvCommand as p}from"./commands/env.js";import{registerAienvCommand as y}from"./commands/aienv.js";import{registerIpynbCommand as f}from"./commands/ipynb.js";import{registerAi4ctfCommand as h}from"./commands/ai4ctf.js";import{registerExamCommand as u}from"./commands/exam.js";import{registerCtf4aiDemoCommand as w}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as T}from"./commands/theme.js";import{registerLearnCommand as b}from"./commands/learn.js";import{registerCtf4VlaCommand as v}from"./commands/ctf4vla.js";import{registerDemo2Command as j}from"./commands/demo2.js";import{registerSimCommand as A}from"./commands/sim.js";import{registerArenaCommand as I}from"./commands/arena.js";import{registerKaggleCommand as $}from"./commands/kaggle.js";import{registerBoardCommand as C}from"./commands/board.js";import{getConfig as E,saveConfig as _}from"./lib/config.js";import{startRepl as S}from"./repl.js";import{RELAUNCH_CODE as x}from"./lib/menu-nav.js";import{setTerminalTheme as O}from"./lib/theme.js";import{checkForUpdates as L}from"./lib/update-check.js";import{detectIcoaInstalls as k}from"./lib/platform.js";import{ICOA_BIG as N}from"./lib/banner.js";import{readFileSync as R}from"node:fs";import{fileURLToPath as F}from"node:url";import{dirname as U,join as P}from"node:path";const M=U(F(import.meta.url)),G=JSON.parse(R(P(M,"..","package.json"),"utf-8")).version,D=chalk.cyan(" ─────────────────────────────────────────────────────"),H=`\n${D}\n\n${N.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${G}`)}\n\n${D}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=o(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(s.signal){e=0;break}e=s.status,n=!0}while(e===x);process.exit(e??0)}}const J=new o;if(J.name("icoa").version(G).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=E();O("high-contrast"===e.themeVariant?"high-contrast":"dark"),L(),function(){const o=k();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();console.log(H);const s=!!o.resume||!!o.continue;if(process.argv.length<=2||s)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),s||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void S(J,s)}),e(J),n(J),s(J),r(J),t(J),i(J),a(J),l(J),m(J),c(J),g(J),d(J),p(J),y(J),f(J),h(J),u(J),w(J),T(J),b(J),v(J),j(J),A(J),I(J),$(J),C(J),J.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=E().geminiModel||"gemini-2.5-flash-lite";o?(_({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}J.parse();
@@ -1 +1 @@
1
- import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
1
+ import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb","kaggle"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * kaggle — pure core behind `icoa kaggle` (Kaggle-style practice arena, M0).
3
+ *
4
+ * The student loop this powers: download a competition dataset that the ICOA
5
+ * server hosts (never bundled into npm — Thin-Client plane 3), open a starter
6
+ * notebook in `icoa ipynb`, run all cells on the LOCAL CPU kernel to produce
7
+ * `submission.csv`, then submit it on kaggle.com manually (their own account —
8
+ * no Kaggle API, no shared-account ToS risk).
9
+ *
10
+ * Unlike the arena starter (MODEL cell deliberately blank — that part is
11
+ * judged server-side), the Kaggle starter ships a WORKING baseline: nothing
12
+ * here is graded by us, Kaggle is the judge, and M0's whole point is that the
13
+ * chain runs end-to-end without edits. The student then improves the model.
14
+ *
15
+ * Pure module: no I/O, no chalk — everything unit-testable.
16
+ */
17
+ import type { NbCell } from './notebook-doc.js';
18
+ export interface KaggleTask {
19
+ comp_id: string;
20
+ title: string;
21
+ metric: string;
22
+ kaggle_url?: string | null;
23
+ licence?: string;
24
+ attribution?: string;
25
+ }
26
+ export interface KaggleMeta extends KaggleTask {
27
+ id_col?: string;
28
+ target_col?: string;
29
+ n_train?: number;
30
+ n_test?: number;
31
+ }
32
+ /** Extract the task list from a server response ({success,data:{tasks}} or bare). */
33
+ export declare function parseKaggleTaskList(resp: unknown): KaggleTask[];
34
+ /**
35
+ * Build the starter notebook cells for a competition. The data dir is baked in
36
+ * as an absolute path so the notebook runs from anywhere; the submission cell
37
+ * uses the meta's id/target column names so its output matches
38
+ * sample_submission.csv byte-for-byte in shape.
39
+ */
40
+ export declare function buildStarterCells(dir: string, meta: KaggleMeta): NbCell[];
41
+ export interface SubmissionVerdict {
42
+ ok: boolean;
43
+ problems: string[];
44
+ }
45
+ /**
46
+ * Validate a submission CSV against sample_submission.csv the way Kaggle's
47
+ * uploader would: same header, same row count, same id set (any order), no
48
+ * empty cells. Both files are program-generated simple CSVs (no quoting), so
49
+ * naive comma-splitting is safe here.
50
+ */
51
+ export declare function validateSubmissionText(submission: string, sample: string): SubmissionVerdict;
@@ -0,0 +1 @@
1
+ export function parseKaggleTaskList(e){const t=e??{},i=(t.data??t).tasks;if(!Array.isArray(i))return[];const r=[];for(const e of i){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&r.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0})}return r}export function buildStarterCells(e,t){const i=t.id_col??"id",r=t.target_col??"target",a=(s=t.metric,/rmse|mse|mae|error/i.test(s));var s;const o=e=>({kind:"markdown",source:e,result:null}),n=e=>({kind:"code",source:e.join("\n"),result:null}),l=[`# ${t.title}`,"",`Kaggle-style practice — metric: **${t.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${r}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell","and re-run — your score is whatever Kaggle says it is.",...t.licence?["",`**Data licence:** ${t.licence}`]:[],...t.attribution?[`**Attribution:** ${t.attribution}`]:[]].join("\n"),c=n(["# setup — load the data (leave as is)","import pandas as pd","from sklearn.model_selection import train_test_split",a?"from sklearn.metrics import mean_squared_error":"from sklearn.metrics import accuracy_score","",`DIR = r"${e}"`,'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")',`features = [c for c in train.columns if c not in ("${i}", "${r}")]`,`X, y = train[features], train["${r}"]`,"X_test = test[features]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"train {train.shape} · test {test.shape} · {len(features)} features")']),m=n(a?["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import Ridge","model = Ridge()"]:["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import LogisticRegression","model = LogisticRegression(max_iter=2000)"]),u=n(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)",a?'print("val RMSE:", round(mean_squared_error(y_val, model.predict(X_val)) ** 0.5, 4))':'print("val accuracy:", round(accuracy_score(y_val, model.predict(X_val)), 4))']),p=n(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = DIR + "/submission.csv"',`pd.DataFrame({"${i}": test["${i}"], "${r}": pred}).to_csv(out, index=False)`,'print("wrote", out)','print("format check: icoa kaggle check")']),d=t.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${t.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This is a placeholder practice dataset — it has no live Kaggle page yet._","When the real competition dataset lands, this cell will link straight to","its Kaggle submission page. The loop is identical: upload `submission.csv`,","read the score, improve the MODEL cell, repeat."];return[o(l),c,m,u,p,o(d.join("\n"))]}export function validateSubmissionText(e,t){const i=[],r=e.trim().split(/\r?\n/),a=t.trim().split(/\r?\n/),s=r[0]??"",o=a[0]??"";s.trim()!==o.trim()&&i.push(`header mismatch: expected "${o}", got "${s}"`);const n=r.slice(1).filter(e=>""!==e.trim()),l=a.slice(1).filter(e=>""!==e.trim());n.length!==l.length&&i.push(`row count mismatch: expected ${l.length}, got ${n.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),m=c(n),u=c(l),p=[...u].filter(e=>!m.has(e)),d=[...m].filter(e=>!u.has(e));if(p.length>0||d.length>0){const e=[];p.length>0&&e.push(`${p.length} missing (e.g. ${p[0]})`),d.length>0&&e.push(`${d.length} unknown (e.g. ${d[0]})`),i.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<n.length;e++)if(n[e].split(",").some(e=>""===e.trim())){i.push(`empty cell in data row ${e+1}`);break}return{ok:0===i.length,problems:i}}
package/dist/repl.js CHANGED
@@ -1 +1 @@
1
- import{createInterface as o}from"node:readline";import{spawn as e,execSync as t}from"node:child_process";import chalk from"chalk";import{isConnected as n,getConfig as l,saveConfig as a}from"./lib/config.js";import{ensureLangCache as s}from"./lib/translations-fetcher.js";import{loadUiPack as r}from"./lib/i18n.js";import{isActivated as i,activateToken as c,isFreeCommand as g,isDeviceMatch as y,recordExit as m,recordResume as d,isFirstRunOrUpgrade as p,markVersionSeen as u}from"./lib/access.js";import{setReplMode as h}from"./lib/ui.js";import{returnToMainMenu as w,printMenuHint as f,menuHintInline as b}from"./lib/menu-nav.js";import{setMainRl as x}from"./lib/main-rl.js";import{shellSplit as v}from"./lib/shell-split.js";import{isChatActive as C,handleChatMessage as A}from"./commands/ai4ctf.js";import{renderToolMan as k}from"./lib/tool-man.js";import{isCtf4aiActive as I,handleCtf4aiMessage as $}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as T,handleCtf4VlaMessage as E}from"./commands/ctf4vla.js";import{isDemo2Active as S}from"./commands/demo2.js";import{loadDemo2Progress as O}from"./lib/demo2-progress.js";import{hasAnySimHistory as j,lastArmAt as N,lastBundledAt as L,lastSimAt as D}from"./lib/sim-cooldown.js";import{getExamState as R,getRealExamState as P,getDemoState as q,practicalChatCommand as F}from"./lib/exam-state.js";import{resolveResumePoint as M}from"./lib/resume.js";import{buildStatusLine as U}from"./lib/statusline.js";import{startBgTask as _,startAsyncTask as B,listBgTasks as W,getBgTask as Q,drainCompleted as Y,killAllBgTasks as z,runningCount as X}from"./lib/bgtasks.js";import{computeStart as J,renderStart as V}from"./commands/challenge.js";import{addDraft as G,listDrafts as H,removeDraft as Z,clearDrafts as K}from"./lib/drafts.js";import{resetTerminalTheme as oo}from"./lib/theme.js";import{ensureSandbox as eo,runInSandbox as to,isDockerAvailable as no}from"./lib/sandbox.js";import{checkShellRisk as lo,logShellAudit as ao,getActiveCwd as so}from"./lib/exam-sandbox.js";import{logCommand as ro}from"./lib/logger.js";import{startLogSync as io,stopLogSync as co}from"./lib/log-sync.js";import{installInputDynamics as go,uninstallInputDynamics as yo,stripPasteMarkers as mo}from"./lib/input-dynamics.js";import{startBroadcastPoll as po,stopBroadcastPoll as uo,showBroadcast as ho,isCompetitionJoined as wo,isMelCompetition as fo,isLeaderAccount as bo,isLeaderSession as xo,fetchPublicScoreboard as vo,isCommsActive as Co}from"./lib/comms.js";import{enterMemoScreen as Ao,enterJuryScreen as ko}from"./commands/comms.js";import{existsSync as Io,mkdirSync as $o,readFileSync as To,writeFileSync as Eo}from"node:fs";import{join as So}from"node:path";import{homedir as Oo}from"node:os";const jo="# ICOA exam interactive startup — auto-loaded by PYTHONSTARTUP\nimport base64, struct, hashlib, re, json, os, sys, binascii\ntry: import requests\nexcept ImportError: pass\ntry: from Crypto.Cipher import AES\nexcept ImportError: pass\ntry: from Crypto.Util.Padding import pad, unpad\nexcept ImportError: pass\ntry: from pwn import xor, p32, u32, p64, u64\nexcept ImportError: pass\ntry: import bs4\nexcept ImportError: pass\ntry: import numpy as np\nexcept ImportError: pass\ntry: from PIL import Image\nexcept ImportError: pass\n",No=Date.now();function Lo(){return fo()?chalk.yellow("icoa 2026> "):P()?chalk.cyan("icoa exam> "):function(){const o=q();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=No}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const Do=So(Oo(),"icoa-workspace"),Ro=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),Po="__REPL_NO_EXIT__",qo="2.5.1",Fo=["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","learn","demo2","ctf4eai","ctf4vla","theme","sim","arena","eai","board","learn-pull","doctor","bg","tasks","drafts","help","menu","quit","q","exit","back","resume"],Mo={exam:["list","start","q","answer","submit","review","result","next","prev","mark","unmark","help"],ctf:["challenges","open","submit","scoreboard","status","join","logout","time"],challenge:["start","stop","status"],arena:["eai"],learn:["start","continue"]};function Uo(o){const e=o.replace(/^\s+/,"");if(/^\/\S*$/.test(e)){const o=e.slice(1).toLowerCase();return[Fo.filter(e=>e.startsWith(o)).map(o=>`/${o}`),e]}const t=e.split(/\s+/);if(t.length<=1){const o=(t[0]??"").toLowerCase();return[Fo.filter(e=>e.startsWith(o)).slice(),o]}if(2===t.length){const o=Mo[t[0].toLowerCase()];if(o){const e=t[1].toLowerCase();return[o.filter(o=>o.startsWith(e)).slice(),e]}}return[[],o]}async function _o(o){const e=M();if(!e)return null;const t=process.exit;process.exit=()=>{throw new Error(Po)};try{await o.parseAsync(["node","icoa",...e.command])}catch(o){if(!(o instanceof Error&&o.message===Po))throw o}finally{process.exit=t}return e}function Bo(){console.log(),console.log(` ${chalk.cyan.bold("🎯 ICOA 2026 · National Selection")}`),console.log(),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("ACxxxxxxxx")+chalk.gray(" → ai4ctf-12 (AI as your CTF teammate)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("CAxxxxxxxx")+chalk.gray(" → ctf4ai-12 (red-team software AI)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("EAxxxxxxxx")+chalk.gray(" → ctf4eai-12 (red-team embodied AI)")),console.log(" "+chalk.bold.cyan("exam ")+chalk.white("<CC>xxxxxxxx")+chalk.gray(" → Paper A/B/C/D/E (country exam token)")),console.log(" "+chalk.bold.cyan("demo")+chalk.gray(" → free practice")),console.log(" "+chalk.bold.cyan("lang")+chalk.white(" es")+chalk.gray(" → switch language")),console.log(" "+chalk.gray("help · menu · quit")),console.log()}export async function startRepl(e,q){process.env.ICOA_INSIDE_REPL="1";let No=!1;if(fo()){const o=l().joinedAt,e=o=>new Intl.DateTimeFormat("en-CA",{timeZone:"Australia/Sydney",year:"numeric",month:"2-digit",day:"2-digit"}).format(o);o&&e(new Date(o))===e(new Date)||(a({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:"",joinedAt:""}),No=!0)}const Mo=l(),Yo=n(),zo=process.exit.bind(process),Xo=i();if(Mo.language&&"en"!==Mo.language&&(await s(Mo.language,{silent:!0}),r(Mo.language)),Mo.demoCleanedForVersion!==qo){try{const{existsSync:o,unlinkSync:e}=await import("node:fs"),{join:t}=await import("node:path"),{getIcoaDir:n}=await import("./lib/config.js"),l=t(n(),"demo-state.json");o(l)&&e(l)}catch{}a({demoCleanedForVersion:qo})}const{select:Jo,confirm:Vo}=await import("@inquirer/prompts"),Go=Mo.mode||"",Ho=""===Go?"instant":["instant","learn","selection","olympiad"].includes(Go)?Go:"selection",Zo=[{name:` ${chalk.bold("⚡ Try ICOA in 30 seconds")} ${chalk.gray("—")} ${chalk.gray("watch · no token needed")}`,value:"instant"},{name:` ${chalk.bold("🧠 Learn")} ${chalk.gray("—")} ${chalk.gray("AC / CA / EA token · skill up")}`,value:"learn"},{name:` ${chalk.bold("🎯 National Selection")} ${chalk.gray("—")} ${chalk.gray("country exam token · aim for finals")}`,value:"selection"},{name:` ${chalk.bold("🏆 International Olympiad")} ${chalk.gray("—")} ${chalk.gray("finals stage · Sydney 2026 · full sandbox")}`,value:"olympiad"},{name:` ${chalk.gray("ℹ️ About ICOA")} ${chalk.gray("·")} ${chalk.gray("what this is · how to join")}`,value:"about"}];""===Go&&(console.log(chalk.green(" 👋 First time here? ")+chalk.white("Just press ")+chalk.bold.cyan("Enter")+chalk.white(" — you’ll see ICOA in 30 seconds, no signup needed.")),console.log()),console.log(chalk.gray(" Type ")+chalk.bold.cyan("menu")+chalk.gray(" from anywhere to return here.")),console.log();let Ko="";for(;!Ko;){let o;try{o=await Jo({message:"Mode",choices:Zo,default:Ho||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}"about"!==o?Ko=o:(console.clear(),console.log(),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(chalk.bold.yellow(" ICOA")+chalk.white(" — AI-Native CLI OS for Cyber & AI Security")),console.log(chalk.gray(" Olympiad & Competition · K-12 to University")),console.log(chalk.cyan(" ───────────────────────────────────────────────────")),console.log(),console.log(chalk.bold.white(" What Makes ICOA Different")),console.log(chalk.gray(" · AI-native AI teammate, AI adversary, AI translation")),console.log(chalk.gray(" · CLI OS Complete competition environment in terminal")),console.log(chalk.gray(" · 110 tools pwntools, z3, gdb, nmap, sleuthkit... pre-configured")),console.log(chalk.gray(" · Global scale 15,000+ concurrent exams · 15 languages")),console.log(),console.log(chalk.bold.white(" Competition Format (2-day standard + 1-day Pioneer)")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" [Day 1] AI as teammate — speed track, dynamic decay + top-3 bonus")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" [Day 2] AI as target — knowledge track, static value per challenge")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" [Pioneer / Practical Round] Embodied AI — VLA + world models + sim-to-real")}`),console.log(),console.log(chalk.bold.white(" Scoring (in brief)")),console.log(chalk.gray(" · Standard medals: AI4CTF + CTF4AI combined · 1/12 Gold · 2/12 Silver · 3/12 Bronze")),console.log(chalk.gray(" · HMA: top 50% on either day, total below bronze cutoff")),console.log(chalk.gray(" · CTF4EAI: separate 15-finalist pool, G/S/B + 12 Finalist Awards")),console.log(),console.log(chalk.white(" Sydney, Australia")+chalk.gray(" · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.bold.white(" Organized by")+chalk.gray(" ASRA (Australia) · ICO Foundation Inc")),console.log(chalk.bold.white(" Contact ")+chalk.cyan(" australia@icoa2026.au · accreditation@icoa2026.au")),console.log(chalk.bold.white(" Website ")+chalk.cyan.underline(" https://icoa2026.au")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(),console.log(chalk.gray(" Press ")+chalk.yellow("Enter")+chalk.gray(" to return...")),await new Promise(o=>{const e=t=>{process.stdin.removeListener("data",e),process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!1),process.stdin.pause(),o()};process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.once("data",e)}),console.clear())}if("olympiad"===Ko&&"olympiad"!==Ho){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await Vo({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(Ko="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(Ko!==Ho&&a({mode:Ko}),console.log(),"olympiad"===Ko&&p(qo)){u(qo),console.log(chalk.gray(" Checking competition environment..."));const{execSync:o}=await import("node:child_process"),e=[{name:"pwntools",cmd:'python3 -c "import pwn"'},{name:"z3-solver",cmd:'python3 -c "import z3"'},{name:"numpy",cmd:'python3 -c "import numpy"'},{name:"requests",cmd:'python3 -c "import requests"'}];let t=0;for(const n of e)try{o(n.cmd,{stdio:"ignore"})}catch{t++}t>0?(console.log(chalk.yellow(` ${t} core competition libraries missing.`)),console.log(chalk.gray(" Run ")+chalk.white("env setup")+chalk.gray(" when you are ready to install them.")),console.log()):(console.log(chalk.green(" All core libraries ready.")),console.log())}if(q){const o=d();if(o){const e=Math.floor(o.awaySeconds/60),t=o.awaySeconds%60;console.log(chalk.yellow(` Session resumed. Away: ${e}m ${t}s | Total exits: ${o.exitCount}`)),console.log()}}if("selection"===Ko)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),Bo();else if("embodied"===Ko)!function(){console.log(chalk.cyan.bold(" [🤖 ctf4eai — Embodied AI Security]")),console.log(),console.log(chalk.bold.cyan(" CTF4EAI")+chalk.gray(" — ICOA 2026's ")+chalk.bold.white("Pioneer Round")),console.log(chalk.gray(" an independent parallel track alongside the scored main events: ")+chalk.green("AI4CTF")+chalk.gray(" (Day 1) and ")+chalk.red("CTF4AI")+chalk.gray(" (Day 2)")),console.log(),console.log(chalk.white(" Embodied AI is at its ImageNet moment.")),console.log(chalk.gray(" VLA models, MuJoCo physics, real robot arms.")),console.log(chalk.gray(" Real models, real physics, real attack surfaces.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const o=L()>0||D()>0,e=N()>0,t=j(),n=O(),l=null!==n&&"number"==typeof n.completedAt&&n.nextCardIndex>=n.totalCards,a=null!==n&&!l;if(l)console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (demo2 ✓ · sim")+(e?chalk.gray(" ✓ · sim arm ✓)"):chalk.gray(")")));else if(a){const o=`${n.nextCardIndex} / ${n.totalCards}`;console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" (last left at card ")+chalk.bold.yellow(o)+chalk.gray(")"))}else o&&e?console.log(chalk.bold.yellow(" Next up: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (sim ✓ · sim arm ✓)")):t?console.log(chalk.bold.yellow(" Next up: ")+(e?chalk.bold.cyan("① sim")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2"):chalk.bold.cyan("② sim arm")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2"))+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")):console.log(chalk.bold.yellow(" First time? Try in order: ")+chalk.bold.cyan("① sim")+chalk.gray(" → ")+chalk.bold.cyan("② sim arm")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01"));console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.bold.green(" sim")+chalk.gray(" ")+chalk.bold.cyan("①")+chalk.gray(" ")+chalk.bold.yellow("★ INSTANT")+chalk.gray(" — 9-robot group dance, no wait, no setup")),console.log(chalk.bold.green(" sim arm")+chalk.gray(" ")+chalk.bold.cyan("②")+chalk.gray(" interactive 6-DOF arm sandbox — type joint values, watch")),console.log(chalk.bold.green(" demo2")+chalk.gray(" ")+chalk.bold.cyan("③")+chalk.gray(" ~8 min interactive intro + live MuJoCo sim")),console.log(chalk.bold.green(" learn LEARNDEMO01")+chalk.gray(" ")+chalk.bold.cyan("④")+chalk.gray(" free 11-card intro (paste this command as-is)")),console.log(chalk.bold.green(" learn ")+chalk.bold.yellow("EA")+chalk.gray(" + 8 chars full 96 / 360 curriculum (team-issued)")),console.log(chalk.bold.green(" exam ")+chalk.bold.yellow("PDxxxxxxxx")+chalk.gray(" Paper D (CTF4EAI) — national selection contestants")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),console.log(chalk.gray(" Three open tiers: ")+chalk.green("free 11")+chalk.gray(" · ")+chalk.yellow("registered 100")+chalk.gray(" · ")+chalk.bold.magenta("national team 480")+chalk.gray(" (PhD-ready)")),console.log(chalk.gray(" Country team contact: ")+chalk.cyan("australia@icoa2026.au")),console.log(),f(),console.log()}();else if("instant"===Ko)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Two free tastes — just type the word and press Enter:")),console.log(),console.log(chalk.bold.green(" demo ")+chalk.gray(" Paper A/B/C taste — 10 MCQs, no timer ")+chalk.bold.cyan("🎯 selection-style")),console.log(chalk.bold.green(" demo2")+chalk.gray(" Embodied-AI mini-demo — robots & MuJoCo ")+chalk.bold.yellow("🤖 hands-on")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(" or ")+chalk.bold.cyan("demo2")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),a({mode:"selection"}),Ko="selection";else{if("learn"===Ko){console.log(chalk.cyan.bold(" [🧠 Learn]")),console.log(),console.log(chalk.gray(" Three tracks · same difficulty curve.")),console.log(),console.log(chalk.white(" Free 12-card demos — paste the full command:")),console.log(),console.log(chalk.gray(" 🤝 ai4ctf AI as your teammate ")+chalk.bold.yellow("learn AI4CTFDEMO01")),console.log(chalk.gray(" 🔓 ctf4ai AI as your target ")+chalk.bold.yellow("learn CTF4AIDEMO01")),console.log(chalk.gray(" 🤖 ctf4eai Embodied AI Security ")+chalk.bold.yellow("learn LEARNDEMO01")),console.log(),console.log(chalk.gray(" Got a cohort token? Type ")+chalk.bold.yellow("learn <TOKEN>")+chalk.gray(" (e.g. ")+chalk.bold.yellow("learn EAABCD1234")+chalk.gray(").")),console.log();try{const{input:o}=await import("@inquirer/prompts"),{resolveLearnInput:t}=await import("./lib/learn-input.js");console.log(chalk.gray(" Enter a token (or just press Enter to go back).")),console.log();const n=await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}),l=n.trim().toLowerCase();if("ai4ioai"===l||"/ai4ioai"===l){const{runAi4ioaiStandalone:o}=await import("./commands/ai4ioai.js");return await o(),a({mode:"selection"}),void w()}const s=t(n);if("token"===s.kind){console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${s.token}`)),console.log(),a({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";try{await e.parseAsync(["node","icoa","learn",s.token])}finally{delete process.env.ICOA_LEARN_EMBEDDED}}else"ambiguous"!==s.kind&&"unknown"!==s.kind||(console.log(),console.log(chalk.yellow(" "+s.hint)),console.log(chalk.gray(" Returning to main menu — pick 🧠 Learn again to retry.")),console.log())}catch{}return a({mode:"selection"}),void w()}"organizer"===Ko?(console.log(chalk.yellow.bold(" [National/Regional Partner]")),console.log(),console.log(chalk.bold.white(" ██╗ ██████╗ ██████╗ █████╗")),console.log(chalk.bold.white(" ██║██╔════╝██╔═══██╗██╔══██╗")),console.log(chalk.bold.white(" ██║██║ ██║ ██║███████║")),console.log(chalk.bold.white(" ██║██║ ██║ ██║██╔══██║")),console.log(chalk.bold.white(" ██║╚██████╗╚██████╔╝██║ ██║")),console.log(chalk.bold.white(" ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝")),console.log(),console.log(chalk.yellow(" International Cyber Olympiad in AI 2026")),console.log(chalk.bold.magenta(" The World's First AI-Native CLI Operating System")),console.log(chalk.bold.magenta(" for Cybersecurity & AI Security Competition")),console.log(chalk.bold.magenta(" and Olympiad for K-12")),console.log(chalk.gray(" Sydney, Australia · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.white(" Vision")),console.log(chalk.gray(" Building a global pipeline for youth cyber & AI")),console.log(chalk.gray(" security talent through education and competition.")),console.log(),console.log(chalk.white(" Capacity")),console.log(chalk.gray(" 15,000+ concurrent online examinations")),console.log(chalk.gray(" National selection, training, and education support")),console.log(),console.log(chalk.white(" Olympic Spirit")),console.log(chalk.gray(" Excellence · Friendship · Respect")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" New country accreditation & support:")),console.log(chalk.cyan(" australia@icoa2026.au")),console.log(chalk.cyan(" accreditation@icoa2026.au")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),Yo?(console.log(chalk.green(` Logged in as ${Mo.userName}`)),console.log(chalk.white(" exam list")+chalk.gray(" Manage exams")),console.log(chalk.white(" logout")+chalk.gray(" Disconnect"))):console.log(chalk.white(" join <url>")+chalk.gray(" Connect to manage exams")),console.log(),f(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),Xo&&!y()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):Yo?(console.log(chalk.green.bold(` Welcome back, ${Mo.userName}!`)),console.log(chalk.gray(` Connected to ${Mo.ctfdUrl}`)),console.log(chalk.gray(" Not you? Type ")+chalk.cyan("logout")+chalk.gray(" to switch accounts")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Ready to compete? Start here:")),console.log(),console.log(chalk.bold.cyan(" challenges")+chalk.gray(" Browse challenges by category")),console.log(chalk.white(" status")+chalk.gray(" Your score & timer")),console.log(chalk.white(" scoreboard")+chalk.gray(" Live rankings")),console.log(chalk.white(" memo")+chalk.gray(" Report an issue to organizers (one-way)")),console.log(),console.log(chalk.gray(" Tool environment:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.bold.yellow(" ★ ")+chalk.bold.cyan("man <tool>")+chalk.gray(" How to USE a tool (steghide, nmap…) · ")+chalk.cyan("man tools")+chalk.gray(" = list")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("help")+chalk.gray(" · ")+b()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):Xo?(Io(Do)||$o(Do,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${Do}`)),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Get started:")),console.log(),console.log(chalk.white(" Step 1 ")+chalk.bold.cyan("join <url>")+chalk.gray(" Connect to competition server")),console.log(chalk.white(" Step 2 ")+chalk.bold.cyan("challenges")+chalk.gray(" Browse & solve challenges")),console.log(chalk.white(" Step 3 ")+chalk.bold.cyan("ai4ctf")+chalk.gray(" Ask AI when stuck")),console.log(),console.log(chalk.gray(" Before Step 1 — make sure your tools are ready:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.bold.yellow(" ★ ")+chalk.bold.cyan("man <tool>")+chalk.gray(" How to USE a tool (steghide, nmap…) · ")+chalk.cyan("man tools")+chalk.gray(" = list")),console.log(),console.log(chalk.gray(" Also: ")+chalk.white("help")+chalk.gray(" all commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+b()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()):(console.log(chalk.bold.yellow(" 🏆 You reached the finals tier.")),console.log(chalk.gray(" Full sandbox · 110 CTF tools · Sydney 2026 · this is where finalists compete.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" To begin, activate your competition token:")),console.log(),console.log(chalk.bold.cyan(" activate <token>")),console.log(),console.log(chalk.gray(" While waiting, explore:")),console.log(chalk.white(" ref linux")+chalk.gray(" Quick reference for Linux")),console.log(chalk.white(" ref web")+chalk.gray(" Quick reference for Web")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.white(" help")+chalk.gray(" All available commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+b()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}e.exitOverride(),e.configureOutput({writeErr:()=>{},writeOut:o=>{console.log(o)}});const oe=o({input:process.stdin,output:process.stdout,prompt:Lo(),terminal:!0,completer:Uo});x(oe),go(!1!==l().bracketedPaste);let ee=!1;if(h(!0),io(),No&&(console.log(),console.log(chalk.yellow(" ⏱ A new competition day has started (Sydney time).")),console.log(chalk.gray(" For fairness, yesterday’s sign-in has been cleared. Type ")+chalk.cyan("join <url>")+chalk.gray(" to sign in with your account.")),console.log()),fo()){const o=l().userName||"this account";console.log(),console.log(chalk.yellow(" ⚠ This machine is signed in as ")+chalk.bold.white(o)+chalk.yellow(".")),console.log(chalk.gray(" Press ")+chalk.cyan("Enter")+chalk.gray(` to continue as ${o}, or type `)+chalk.cyan("logout")+chalk.gray(" to switch accounts.")),"logout"===(await new Promise(o=>{oe.question(chalk.white(" > "),e=>o(e.trim()))})).toLowerCase()&&(a({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:""}),console.log(),console.log(chalk.green(" ✓ Logged out. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" to sign in with your own account."))),console.log()}wo()&&po(()=>oe.prompt());let te=null;const ne=oe.prompt.bind(oe);oe.prompt=o=>{if(!(C()||I()||T()||S()||Co()||(oe.setPrompt(Lo()),o)))try{for(const o of Y()){const e="done"===o.status,t=o.cmd.length>40?`${o.cmd.slice(0,37)}…`:o.cmd,n=o.render?"":chalk.gray(" (")+chalk.white(t)+chalk.gray(") — ")+chalk.cyan(`tasks ${o.id}`);if(console.log((e?chalk.green(" ✓"):chalk.red(" ✗"))+chalk.white(` background task #${o.id} ${o.status}`)+n),o.render)try{o.render()}catch{}}const o=U();o&&o!==te?(console.log(o),te=o):o||(te=null)}catch{}ne(o)};const le=M();le&&(console.log(chalk.cyan(" ↻ Continue where you left off: ")+chalk.white(le.label)+(le.urgent?chalk.yellow(" (exam timer running)"):"")),console.log(chalk.gray(" type ")+chalk.cyan("resume")+chalk.gray(" to jump back in.")),console.log()),oe.prompt(),oe.on("line",async o=>{if(ee)return;let a=mo(o.trim());if(!a)return oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt();if(a.startsWith("/")&&!a.startsWith("//")){const o=a.slice(1).split(/\s+/)[0].toLowerCase(),t=a.slice(1+o.length).trim();if("ai"===o)return ee=!0,await async function(o,e){if(C())return void(o?await A(o):console.log(chalk.gray(" You are already in the AI chat — just type your message.")));if(I())return void(o?await $(o):console.log(chalk.gray(" You are already in the CTF4AI target chat — just type your message.")));if(T())return void(o?await E(o):console.log(chalk.gray(" You are already in the Embodied-AI chat — just type your message.")));ro(o?`/ai ${o}`:"/ai");const t=process.exit;process.exit=()=>{throw new Error(Po)};try{await e.parseAsync(["node","icoa","ai4ctf"])}catch(o){if(!(o instanceof Error&&o.message===Po))throw o}finally{process.exit=t}o&&C()&&await A(o)}(t,e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt();!(C()||I()||T()||S()||Co())&&Fo.includes(o)&&(a=a.slice(1))}if("resume"===a.toLowerCase()){const o=M();return o?(ro(`resume → ${o.command.join(" ")}`),ee=!0,await _o(e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt()):(console.log(),console.log(chalk.gray(" Nothing to resume yet — start with ")+chalk.cyan("learn")+chalk.gray(" (curriculum) or ")+chalk.cyan("demo")+chalk.gray(" (taste).")),console.log(),void oe.prompt())}const s=C()||I()||T()||S();if(!s&&("bg"===a.toLowerCase()||/^bg\s/i.test(a))){const o=a.replace(/^bg\s*/i,"").trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("bg <command>")+chalk.gray(" — run a non-interactive shell command in the background.")),console.log(chalk.gray(" e.g. ")+chalk.cyan("bg nmap -p- 10.0.0.5")+chalk.gray(" · view: ")+chalk.cyan("tasks")),console.log(),void oe.prompt();const e=so(),t=lo(o);ao({cwd:e,input:`bg ${o}`,riskFlags:t}),t.length>0&&P()&&console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`));const n=_(o,e);return console.log(),console.log(chalk.cyan(` ▸ background task #${n.id} started`)+chalk.gray(` (${X()} running)`)),console.log(chalk.gray(" ")+chalk.white(o)),console.log(chalk.gray(" view: ")+chalk.cyan("tasks")+chalk.gray(" · output: ")+chalk.cyan(`tasks ${n.id}`)),console.log(),void oe.prompt()}if(!s&&("tasks"===a.toLowerCase()||/^tasks\s/i.test(a))){const o=a.replace(/^tasks\s*/i,"").trim(),e=W();if(console.log(),o){const e=Q(Number(o));if(!e||Number.isNaN(Number(o)))console.log(chalk.yellow(` No background task #${o}.`)+chalk.gray(" Type ")+chalk.cyan("tasks")+chalk.gray(" to list them."));else{const o="running"===e.status?chalk.yellow:"done"===e.status?chalk.green:chalk.red;console.log(o(` #${e.id} [${e.status}]`)+chalk.white(` ${e.cmd}`)+(null!==e.exitCode?chalk.gray(` (exit ${e.exitCode})`):"")),console.log(chalk.gray(" ─────────────────────────────────────────────"));const t=e.output.trim();if(t)for(const o of t.split("\n"))console.log(chalk.gray(" ")+chalk.white(o));else console.log(chalk.gray(" (no output yet)"))}}else if(0===e.length)console.log(chalk.gray(" No background tasks. Start one with ")+chalk.cyan("bg <command>")+chalk.gray("."));else{console.log(chalk.bold.white(" Background tasks"));for(const o of e){const e="running"===o.status?chalk.yellow("●"):"done"===o.status?chalk.green("✓"):chalk.red("✗"),t=Math.round(((o.endedAt??Date.now())-o.startedAt)/1e3),n=(o.endedAt?`${t}s`:`${t}s…`).padStart(5),l=o.cmd.length>48?`${o.cmd.slice(0,45)}…`:o.cmd;console.log(` ${e} `+chalk.white(`#${o.id}`)+chalk.gray(` ${n} `)+chalk.white(l))}console.log(chalk.gray(" output: ")+chalk.cyan("tasks <id>"))}return console.log(),void oe.prompt()}if(!s&&/&\s*$/.test(a)&&/^challenge\s+start\s+/i.test(a)){const o=a.replace(/\s*&\s*$/,"").trim().replace(/^challenge\s+start\s+/i,"").trim().split(/\s+/),e=o.some(o=>"-n"===o||"--new"===o),t=o.find(o=>"-n"!==o&&"--new"!==o);if(!t)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("challenge start <id> &")),console.log(),void oe.prompt();if(!n())return console.log(),console.log(chalk.red(" Not connected. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" first.")),console.log(),void oe.prompt();ro(`challenge start ${t}${e?" --new":""} & (background)`);const l=B(`challenge start ${t}`,()=>J(t,e),o=>V(t,o));return console.log(),console.log(chalk.cyan(` ▸ background task #${l.id}: `)+chalk.white(`starting ${t}`)+chalk.gray(" — you can keep working; the connection info appears here when it is ready.")),console.log(),void oe.prompt()}if(!s&&a.startsWith("#")){const o=a.slice(1).trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("#<candidate answer>")+chalk.gray(" — stage a flag/answer WITHOUT submitting it. Review with ")+chalk.cyan("drafts")+chalk.gray(".")),console.log(),void oe.prompt();const e=R(),t=e?.session?.examId??null,n=e?e._lastQ||1:null,l=G(o,t,n);return ro(`draft #${l.id} (not submitted)`),console.log(),console.log(chalk.green(` ✎ draft #${l.id} saved`)+(n?chalk.gray(` (Q${n})`):"")+chalk.yellow(" — NOT submitted.")),console.log(chalk.gray(" review with ")+chalk.cyan("drafts")+chalk.gray("; when sure, submit it the normal way.")),console.log(),void oe.prompt()}if(!s&&("drafts"===a.toLowerCase()||/^drafts\s/i.test(a))){const o=a.replace(/^drafts\s*/i,"").trim().toLowerCase();if("clear"===o){const o=K();return console.log(),console.log(chalk.gray(` Cleared ${o} draft${1===o?"":"s"}.`)),console.log(),void oe.prompt()}const e=o.match(/^(?:rm|remove|del|delete)\s+(\d+)$/);if(e){const o=Z(Number(e[1]));return console.log(),console.log(o?chalk.gray(` Removed draft #${e[1]}.`):chalk.yellow(` No draft #${e[1]}.`)),console.log(),void oe.prompt()}const t=R(),n=H(t?.session?.examId??null);if(console.log(),0===n.length)console.log(chalk.gray(" No drafts yet. Stage a candidate with ")+chalk.cyan("#ICOA{maybe_this}")+chalk.gray(" — it won’t submit."));else{console.log(chalk.bold.white(" Draft answers")+chalk.gray(" (staged — not submitted)"));for(const o of n){const e=o.q?chalk.cyan(`Q${o.q}`.padStart(4)):chalk.gray(" · ");console.log(chalk.gray(` #${o.id}`)+` ${e} `+chalk.white(o.text.length>56?`${o.text.slice(0,53)}…`:o.text))}console.log(chalk.gray(" remove: ")+chalk.cyan("drafts rm <id>")+chalk.gray(" · clear all: ")+chalk.cyan("drafts clear"))}return console.log(),void oe.prompt()}if("menu"===a||"menu confirm"===a)return P()&&"menu confirm"!==a?(console.log(),console.log(chalk.yellow(" Real exam active. Progress is auto-saved.")),console.log(chalk.gray(" To return to main menu anyway, type ")+chalk.white("menu confirm")),console.log(),void oe.prompt()):void w(oe);if(C()){ee=!0;const o=await A(a);return ee=!1,"exit"===o&&oe.setPrompt(Lo()),void oe.prompt()}if(I()){ee=!0;const o=await $(a);return ee=!1,"exit"!==o&&"solved"!==o||oe.setPrompt(Lo()),void oe.prompt()}if(T()){ee=!0;const o=await E(a);return ee=!1,"exit"===o&&oe.setPrompt(Lo()),oe.setPrompt(T()?chalk.bold.cyan("icoa ctf4eai> "):Lo()),void oe.prompt()}if(ro(a),"exit"===a)return R()?(console.log(),console.log(chalk.yellow(" ⚠ An exam is in progress.")),console.log(chalk.white(" To return to menu without losing progress, type: ")+chalk.bold.cyan("back")),console.log(chalk.white(" To fully close ICOA CLI, type: ")+chalk.bold.cyan("quit")),console.log(chalk.gray(" Your progress is auto-saved either way.")),console.log(),void oe.prompt()):(console.log(),console.log(chalk.gray(" ")+chalk.white("exit")+chalk.gray(" returns to the main menu. To fully close ICOA CLI, type ")+chalk.bold.cyan("quit")+chalk.gray(".")),"selection"===Ko&&Bo(),void oe.prompt());if("quit"===a||"q"===a||"quit confirm"===a){const o=R();return o&&"demo-free"!==o.session.examId&&"quit confirm"!==a?(console.log(),console.log(chalk.yellow(" ⚠ A real exam is in progress.")),console.log(chalk.gray(" Your answers are auto-saved on the server, but the exam timer keeps ticking")),console.log(chalk.gray(" on the server side even if you close the CLI.")),console.log(),console.log(chalk.white(" To leave the CLI but keep the exam alive, type: ")+chalk.bold.cyan("back")),console.log(chalk.gray(" (recommended — you can resume with ")+chalk.cyan("exam q 1")+chalk.gray(" after relaunching icoa)")),console.log(),console.log(chalk.white(" To really close ICOA CLI, type: ")+chalk.bold.cyan("quit confirm")),console.log(),void oe.prompt()):(o&&"demo-free"===o.session.examId&&(console.log(),console.log(chalk.gray(" Demo paused. Resume with: ")+chalk.white("demo")+chalk.gray(" (fresh) or ")+chalk.white("exam q 1")+chalk.gray(" (continue)."))),co(),yo(),uo(),z(),m(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),oo(),void zo(0))}if("back"===a){const o=R(),e=o&&"demo-free"!==o.session.examId,t=o&&"demo-free"===o.session.examId&&(()=>{const e=new Date(o.session.startedAt||0).getTime();return Date.now()-e<18e5})();if(e)console.log(),console.log(chalk.gray(" Exam paused. Your progress is saved.")),console.log(chalk.white(" Resume: exam q 1")+chalk.gray(" · ")+chalk.white("exam review")+chalk.gray(" · ")+chalk.white("exam submit")),console.log();else if(t){const e=Object.keys(o.answers).length,t=o.session.questionCount;console.log(),console.log(chalk.gray(` Demo paused (${e}/${t} answered). Resume with: `)+chalk.white("exam q 1")),console.log(chalk.gray(" Or type ")+chalk.white("demo")+chalk.gray(" to restart.")),console.log()}else{if(o&&"demo-free"===o.session.examId){const{clearExamState:o}=await import("./lib/exam-state.js");o("demo-free")}const e=l();fetch("https://practice.icoa2026.au/api/icoa/demo-stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"post-report-back",lang:e.language||"en",timestamp:(new Date).toISOString()}),signal:AbortSignal.timeout(5e3)}).catch(()=>{}),"selection"===Ko?Bo():console.log(chalk.gray(" Already at main menu."))}return void oe.prompt()}if("help"===a||"?"===a){if(R()){ee=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return ee=!1,void oe.prompt()}return Qo(i(),Ko),void oe.prompt()}if("man"===a||"manual"===a)return Qo(i(),Ko),console.log(),console.log(chalk.bold.yellow(" ★ Stuck on a tool? ")+chalk.bold.cyan("man <tool>")+chalk.gray(" e.g. ")+chalk.cyan("man steghide")+chalk.gray(" · ")+chalk.cyan("man tools")+chalk.gray(" = full list")),void oe.prompt();if(/^(?:man|manual)\s+\S/i.test(a))return k(a.replace(/^(?:man|manual)\s+/i,"")),void oe.prompt();if("more help"===a.toLowerCase()&&R()){ee=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return ee=!1,void oe.prompt()}if("continue"===a.toLowerCase())return console.log(),console.log(chalk.green.bold(" ═══ AI4CTF — AI as Your Teammate ═══")),console.log(),console.log(chalk.white(" In AI4CTF, you solve cybersecurity challenges")),console.log(chalk.white(" with AI by your side.")),console.log(),console.log(chalk.white(" In this demo, your AI teammate gives help at 3 levels:")),console.log(chalk.yellow(" hint a")+chalk.gray(" General guidance")),console.log(chalk.yellow(" hint b")+chalk.gray(" Deep analysis")),console.log(chalk.yellow(" hint c")+chalk.gray(" Critical assist")),console.log(),console.log(chalk.white(" Try it now! Type: ")+chalk.bold.green("ai4ctf")),console.log(chalk.gray(' Chat freely with your AI teammate. Type "exit" when done.')),console.log(),console.log(chalk.gray(" After ai4ctf, try: ")+chalk.bold.red("ctf4ai")+chalk.gray(' — trick the AI into saying "koala"')),console.log(),void oe.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(a.trim())){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",a.trim()])}catch{}return ee=!1,void oe.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(a.trim())){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",a.trim().toUpperCase()])}catch{}return ee=!1,void oe.prompt()}const r=a.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(r){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",r[1].toUpperCase()])}catch{}return ee=!1,void oe.prompt()}const d=a.match(/^exam\s+([A-Z]{2,3})$/i);if(d){ee=!0;try{await e.parseAsync(["node","icoa","exam","list",d[1]])}catch{}return ee=!1,void oe.prompt()}if("clear"===a||"cls"===a)return console.clear(),void oe.prompt();if("news"===a)return wo()?ho():console.log(chalk.gray(" No competition joined. Use ")+chalk.white("join <url>")+chalk.gray(".")),void oe.prompt();if("memo"===a){if(!wo())return console.log(chalk.gray(" Join a competition first: ")+chalk.white("join <url>")),void oe.prompt();ee=!0;try{await Ao()}catch{}return void(ee=!1)}const p=xo()||bo(l().userName||"");if("jury"===a&&p){ee=!0;try{await ko()}catch{}return void(ee=!1)}if(p&&xo()&&"scoreboard"===a.split(/\s+/)[0]){ee=!0;try{const o=await vo();if(console.log(),0===o.length)console.log(chalk.gray(" Scoreboard is empty."));else{console.log(chalk.bold.white(" Scoreboard"));for(const e of o.slice(0,50))console.log(chalk.gray(` ${String(e.pos).padStart(3)}. `)+chalk.white(e.name.padEnd(28).slice(0,28))+chalk.cyan(String(e.score)))}console.log()}catch{}return ee=!1,void oe.prompt()}if(p&&fo()){const o=a.split(/\s+/)[0];if(["challenges","open","submit","hint"].includes(o))return console.log(),console.log(chalk.yellow(" Team-leader account — the challenge bracket is not available here.")),console.log(chalk.gray(" Available: ")+chalk.white("scoreboard")+chalk.gray(" · ")+chalk.white("news")+chalk.gray(" · ")+chalk.white("jury")+chalk.gray(" · ")+chalk.white("time")+chalk.gray(" · ")+chalk.white("status")+chalk.gray(" · ")+chalk.white("logout")),console.log(),void oe.prompt()}if(a.startsWith("activate ")){const o=a.slice(9).trim(),e=c(o);return"ok"===e?console.log(chalk.green(" Access granted! Token bound to this device.")):"already_bound"===e?(console.log(),console.log(chalk.red(" Token already activated on a different device.")),console.log(chalk.gray(" Each token binds to the first device that uses it. If you lost the device,")),console.log(chalk.gray(" contact your proctor to have the token re-issued for a new device."))):(console.log(),console.log(chalk.red(" Token not recognized.")),console.log(chalk.gray(" Possible reasons:")),console.log(chalk.white(" • ")+chalk.gray("Typo — access tokens are case-insensitive and look like ")+chalk.cyan("ICOA-XXXX-XXXX-XXXX")+chalk.gray(" (4-char hex groups, e.g. ICOA-385E-27F2-B21B)")),console.log(chalk.white(" • ")+chalk.gray("Expired — ask your proctor or organizer for a fresh token")),console.log(chalk.white(" • ")+chalk.gray("Network — verify connection to ")+chalk.cyan("practice.icoa2026.au")),console.log(chalk.gray(" Still stuck? type ")+chalk.cyan("help")+chalk.gray(" or try ")+chalk.cyan("exam demo")+chalk.gray(" for a free practice round."))),console.log(),void oe.prompt()}if("activate"===a)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void oe.prompt();const u=R();if(u){const o=a.toUpperCase().trim(),t=o=>{const e=u.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},n=o=>{const e=u.questions.find(e=>e.number===o);return"short_answer"===e?.type},l=o=>{const e="demo-free"!==u.session.examId,t=u.questions.find(e=>e.number===o),n=F(t?.type,e);console.log(),console.log(chalk.yellow(` Q${o} is a practical question — letters (A/B/C/D) don't apply here.`)),n?(console.log(chalk.white(" Enter the AI chat for this question: ")+chalk.bold.cyan(n)),console.log(chalk.gray(" Or submit a flag directly: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`))):console.log(chalk.gray(" Submit a flag: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`)),console.log()};if(/^[ABCDE]$/.test(o)){const a=u._lastQ||1;if(t(a))return l(a),void oe.prompt();if(n(a))return console.log(),console.log(chalk.yellow(` Q${a} is a short-answer question — type a number, not a letter.`)),console.log(chalk.gray(" Example: ")+chalk.green("42")+chalk.gray(" (or ")+chalk.green(`exam answer ${a} 42`)+chalk.gray(")")),console.log(),void oe.prompt();ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(a),o])}catch{}return ee=!1,void oe.prompt()}if(/^-?\d+$/.test(o)){const t=u._lastQ||1;if(n(t)){ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(t),o])}catch{}return ee=!1,void oe.prompt()}}const s=o.match(/^(\d+)\s+([ABCDE]|-?\d+)$/);if(s){const o=parseInt(s[1],10);if(t(o))return l(o),void oe.prompt();ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",s[1],s[2]])}catch{}return ee=!1,void oe.prompt()}}const h=a.split(/\s+/)[0].toLowerCase(),f=/^python3?(\.\d+)?$/.test(h),b="ls"===h||"pwd"===h,x=a.startsWith("!")||h.startsWith("!")||f||b,O=new Set(["nano","vi","vim","emacs","pico","ed","code","cat","less","more","head","tail","ls","pwd","cd","base64","xxd","hexdump","od","openssl","md5sum","sha256sum","grep","find","awk","sed","strings","file","curl","wget","nc","ping","nmap","echo","bash","sh","zsh","pip","pip3","node","npm"]),j=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${a}`)),console.log()};if("embodied"===Ko&&!x&&!["doctor","demo2","learn","exam","ctf4eai","ctf4vla","eai","arena","lang","ref","setup","env","aienv","ipynb","sim"].includes(h))return O.has(h)?(j(),void oe.prompt()):(console.log(chalk.gray(" Not available in Embodied AI Security mode.")),console.log(chalk.white(" Try ")+chalk.bold.cyan("demo2")+chalk.gray(" (intro) · ")+chalk.bold.cyan("learn")+chalk.gray(" (curriculum) · ")+chalk.bold.cyan("exam <PD-token>")+chalk.gray(" (Paper D)")),console.log(),void oe.prompt());if("selection"===Ko&&!x&&!["doctor","exam","demo","demo2","retry","nations","next","prev","continue","setup","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","aienv","ipynb","sim"].includes(h)){if(O.has(h))return j(),void oe.prompt();if(console.log(chalk.gray(" Not available in Selection mode.")),u){const o=u._lastQ||1;console.log(chalk.white(` Resume exam: exam q ${o}`)+chalk.gray(" · ")+chalk.white("A/B/C/D")+chalk.gray(" to answer"))}else console.log(chalk.gray(" Try: demo · setup to switch mode"));return console.log(),void oe.prompt()}if("organizer"===Ko&&!["doctor","join","exam","demo","retry","next","prev","logout","setup","lang","ref","ctf","mark","unmark","review","submit"].includes(h))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void oe.prompt();if(!("olympiad"!==Ko||i()&&y()||g(h)))return console.log(chalk.yellow(" Restricted mode. ")+chalk.gray("Enter your access token:")),console.log(chalk.white(" activate <token>")),console.log(),console.log(chalk.gray(" Free commands: ")+chalk.white("ref [topic]")+chalk.gray(", ")+chalk.white("help")+chalk.gray(", ")+chalk.white("exit")),console.log(),void oe.prompt();if(!["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","submit","learn","demo2","ctf4eai","ctf4vla","theme","sim","arena","eai","board","learn-pull","doctor"].includes(h)){if(Ro.has(h))return console.log(chalk.yellow(` "${h}" is a shell command — the ICOA prompt isn't a shell.`)),console.log(chalk.gray(" In real-exam mode, prefix with ! to run inside the sandbox: ")+chalk.cyan(`!${a}`)),console.log(),void oe.prompt();if(/(?:^|\s)(?:\/(?!home\/|Users\/|tmp\/)|\.\.\/|~\/)/.test(a)&&!a.startsWith("cd ")){const o=/(?:^|\s)\/(?!home\/\w+\/icoa-workspace|Users\/\w+\/icoa-workspace|tmp\/)/.test(a),e=/\.\./.test(a);if(o||e)return console.log(chalk.red(" Blocked: access outside workspace is not allowed.")),console.log(chalk.gray(` Workspace: ${Do}`)),console.log(),void oe.prompt()}let o=a.startsWith("!")?a.slice(1).trim():a;if("darwin"===process.platform){const e="/opt/homebrew/opt/python@3.12/bin/python3.12";o=o.replace(/^python3?\s/,`${e} `).replace(/^(python3|python)$/,e)}else if("win32"===process.platform){const e=(()=>{try{return t("py -3 --version",{stdio:["ignore","ignore","ignore"],timeout:1500}),"py -3"}catch{}return"python"})();o=o.replace(/^python3?(\.\d+)?\s/,`${e} `).replace(/^python3?(\.\d+)?$/,e)}else{const e=(()=>{try{return t("which python3.12",{stdio:"ignore"}),"python3.12"}catch{return"python3"}})();o=o.replace(/^python\s/,`${e} `).replace(/^python$/,e)}const e=so(),n=lo(a);ao({cwd:e,input:a,riskFlags:n}),n.length>0&&P()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${n.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=So(Oo(),".icoa");Io(o)||$o(o,{recursive:!0});const e=So(o,"python-startup.py");let t="";if(Io(e))try{t=To(e,"utf-8")}catch{}return t!==jo&&Eo(e,jo),e}()}" ${o}`,console.log(),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log(chalk.bold.white(" Python ready — ICOA exam toolkit pre-loaded")),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log(),console.log(chalk.white(" Already imported: ")+chalk.gray("base64, struct, hashlib, re, json, binascii")),console.log(chalk.white(" Also available: ")+chalk.gray("requests, bs4, numpy, PIL.Image, AES, pad/unpad, xor, p32/u32/p64/u64")),console.log(),console.log(chalk.yellow(" Quick examples:")),console.log(chalk.gray(' base64.b64decode("aGVsbG8=") ')+chalk.gray("# decode base64")),console.log(chalk.gray(' bytes.fromhex("48656c6c6f") ')+chalk.gray("# hex → bytes")),console.log(chalk.gray(' "ICOA{x}".encode() ')+chalk.gray("# str → bytes")),console.log(chalk.gray(" [chr(c) for c in [73,67,79,65]] ")+chalk.gray("# ASCII codes")),console.log(chalk.gray(' xor(bytes.fromhex("0a2b"), b"IC") ')+chalk.gray("# pwntools XOR")),console.log(),console.log(chalk.gray(" Exit: ")+chalk.white("exit()")+chalk.gray(" or Ctrl-D")),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log()),ee=!0;try{await no()&&await eo()?await to(o,oe):await Wo(o,oe,e)}catch{console.log(chalk.yellow(` Command failed: ${h}`))}return ee=!1,console.log(),void oe.prompt()}ee=!0;const N=a.trim(),L=N.toLowerCase();let D,q=null,U="";if(u)if("submit"===L)q="final";else if(L.startsWith("submit ")){let o=N.slice(7).trim();/^submit\s+/i.test(o)&&(o=o.replace(/^submit\s+/i,"").trim()),o=o.replace(/^["'`]+|["'`]+$/g,"").trim(),o&&/^ICOA\{[^}]*\}?$/i.test(o)?(q="flag",U=o):o&&/^[ABCDE]$/i.test(o)&&(q="flag",U=o.toUpperCase())}else/^ICOA\{[^}]+\}$/i.test(N)&&(q="flag",U=N);D="final"===q?["exam","submit"]:"flag"===q?["exam","answer",String(u?._lastQ||1),U]:function(o){const e=o.split(/\s+/),t=e[0].toLowerCase(),n=e.slice(1);if("aienv"===t&&["run","python","py"].includes((n[0]??"").toLowerCase()))return v(o);if(("submit"===t||"flag"===t)&&n.length>=2)return["ctf","submit",n[0],n.slice(1).join(" ").trim().replace(/^["'`]+|["'`]+$/g,"")];if("connect"===t&&n.length>=2){const e=v(o);return["connect",e[1]??n[0],e.slice(2).join(" ")]}const l={demo:["exam","demo"],retry:["exam","demo-retry"],nations:["exam","nations"],next:["exam","next"],prev:["exam","prev"],mark:["exam","mark",...n],unmark:["exam","unmark",...n],review:["exam","review"],logout:["ctf","logout"],join:["ctf","join",...n],activate:["ctf","activate",...n],challenges:["ctf","challenges"],ch:["ctf","challenges"],open:["ctf","open",...n],submit:["ctf","submit",...n],flag:["ctf","submit",...n],scoreboard:["ctf","scoreboard",...n],sb:["ctf","scoreboard",...n],status:["ctf","status"],time:["ctf","time"]};return l[t]?l[t]:["ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","ai4ctf","model","ctf","exam","ctf4ai","doctor"].includes(t)?[t,...n]:e}(a);const Y="ctf"===D[0]&&"join"===D[1];Y&&oe.pause(),process.exit=()=>{throw new Error(Po)};try{await e.parseAsync(["node","icoa",...D])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===Po);else if(e.includes("commander.unknownCommand")){const{distance:o}=await import("fastest-levenshtein"),e=["ctf","ref","shell","files","view","connect","challenge","note","notes","logbook","log","manual","lang","setup","env","aienv","ipynb","ai4ctf","exam","ctf4ai","theme","eai","board","clear","cls","quit","exit","back","menu","help","continue","activate","demo","challenges","status","scoreboard","join","logout"],t=h.split(/\s+/)[0]||h;let n={word:"",dist:1/0};for(const l of e){const e=o(t.toLowerCase(),l);e<n.dist&&(n={word:l,dist:e})}console.log(chalk.yellow(` Unknown command: ${h}.`)),n.dist>0&&n.dist<=2&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(n.word)+chalk.gray("?")),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for the full command list."))}else e.includes("commander.missingArgument")||"commander.missingArgument"===o?.code?"submit"===h||"flag"===h?(console.log(chalk.yellow(" Incomplete — usage: ")+chalk.cyan("submit <challenge#> <flag>")),console.log(chalk.gray(" Put the number AND the flag on one line, e.g. ")+chalk.cyan("submit 44 pecan{...}"))):(console.log(chalk.yellow(` Incomplete command: ${h}`)),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for usage."))):e.includes("commander.")||(e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ETIMEDOUT"))&&console.log(chalk.yellow(" Network error. Check your connection."))}finally{process.exit=zo,ee=!1,Y&&oe.resume()}C()?oe.setPrompt(chalk.magenta("icoa ai4ctf> ")):I()?oe.setPrompt(chalk.red("icoa ctf4ai> ")):T()&&oe.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),oe.prompt()}),oe.on("SIGINT",()=>{if(console.log(),C()||I())console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still in the AI chat.")),console.log(chalk.white(" Type ")+chalk.bold.cyan("exit")+chalk.white(" to leave the chat and return to the menu."));else if(R()){const o="demo-free"!==R().session.examId;console.log(chalk.yellow(" Ctrl+C did NOT close ICOA CLI.")),console.log(chalk.gray(` Your ${o?"exam":"demo"} is paused and every answer is auto-saved.`)),console.log(),console.log(chalk.white(" Resume: ")+chalk.cyan("exam q 1")+chalk.gray(" · Back to menu: ")+chalk.cyan("back")+chalk.gray(" · Close CLI: ")+chalk.cyan(o?"quit confirm":"quit"))}else console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still at the ")+chalk.cyan("icoa>")+chalk.yellow(" prompt.")),console.log(chalk.gray(" Keep typing — ")+chalk.cyan("help")+chalk.gray(" lists commands. (Only ")+chalk.cyan("quit")+chalk.gray(" or Ctrl+D actually close the CLI.)"));console.log(),oe.prompt()}),oe.on("close",()=>{co(),yo(),uo(),z(),m(),oo(),zo(0)}),"1"===process.env.ICOA_AUTO_RESUME&&(delete process.env.ICOA_AUTO_RESUME,M()&&(ee=!0,await _o(e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),oe.prompt()))}function Wo(o,t,n){return new Promise(l=>{const a=process.stdin,s=!!a.isTTY&&!!a.isRaw;if(t.pause(),a.isTTY&&"function"==typeof a.setRawMode)try{a.setRawMode(!1)}catch{}const r=e(o,{shell:!0,stdio:"inherit",cwd:n||process.cwd()}),i=()=>{if(a.isTTY&&"function"==typeof a.setRawMode&&s)try{a.setRawMode(!0)}catch{}t.resume(),l()};r.on("close",i),r.on("error",i)})}function Qo(o,e="olympiad"){return console.log(),"selection"===e||"organizer"===e?(console.log(chalk.bold.white(" Exam")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to exam server")),console.log(chalk.white(" exam list ")+chalk.gray("Available exams")),console.log(chalk.white(" exam start <id> ")+chalk.gray("Begin an exam")),console.log(chalk.white(" exam q [n] ")+chalk.gray("View questions")),console.log(chalk.white(" exam answer <n> <X> ")+chalk.gray("Answer question")),console.log(chalk.white(" exam review ")+chalk.gray("Review all answers")),console.log(chalk.white(" exam submit ")+chalk.gray("Submit for grading")),console.log(chalk.white(" exam result ")+chalk.gray("View your score")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" setup ")+chalk.gray("Settings / switch mode")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log()):o?(console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(chalk.bold.white(" How it works")),console.log(),console.log(chalk.gray(" 1. Browse ")+chalk.white("challenges")+chalk.gray(" and pick one")),console.log(chalk.gray(" 2. ")+chalk.white("open <id>")+chalk.gray(" to read the challenge")),console.log(chalk.gray(" 3. Use ")+chalk.white("ai4ctf")+chalk.gray(" to chat with AI when stuck")),console.log(chalk.gray(" 4. ")+chalk.white("submit <id> <flag>")+chalk.gray(" to score points")),console.log(chalk.gray(" 5. Check ")+chalk.white("scoreboard")+chalk.gray(" to track your rank")),console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(),console.log(chalk.bold.white(" Competition")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to CTFd")),console.log(chalk.white(" challenges (ch) ")+chalk.gray("List challenges by category")),console.log(chalk.white(" open <id> ")+chalk.gray("Read challenge + get next steps")),console.log(chalk.white(" submit <id> <flag> ")+chalk.gray("Submit a flag")),console.log(chalk.white(" scoreboard (sb) ")+chalk.gray("Live rankings")),console.log(chalk.white(" status ")+chalk.gray("Your score & timer")),console.log(chalk.white(" time ")+chalk.gray("Countdown timer")),console.log(),console.log(chalk.bold.white(" AI Teammate")),console.log(chalk.white(" ai4ctf ")+chalk.gray("Free-chat with your AI teammate")),console.log(),console.log(chalk.bold.white(" Tools")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference (linux, web, crypto...)")),console.log(chalk.white(" shell ")+chalk.gray("Interactive CTF shell (sandbox if present, else host)")),console.log(chalk.white(" files <id> ")+chalk.gray("Download challenge files")),console.log(chalk.white(" connect <id> ")+chalk.gray("Connect to remote target")),console.log(chalk.white(" note [text] ")+chalk.gray("Add a logbook entry (in-exam: tags current Q)")),console.log(chalk.white(" logbook [n] ")+chalk.gray("View your logbook (in-exam: filter by Q)")),console.log(chalk.white(" log ")+chalk.gray("Session history")),console.log(chalk.white(" man <tool> ")+chalk.bold.yellow("★ ")+chalk.gray("How to use a tool (steghide, nmap…); ")+chalk.cyan("man tools")+chalk.gray(" = list. Bare ")+chalk.cyan("man")+chalk.gray(" = this list.")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" resume ")+chalk.gray("Continue your last learn card / exam")),console.log(chalk.white(" #<candidate> ")+chalk.gray("Stage a draft answer (never auto-submits)")),console.log(chalk.white(" drafts ")+chalk.gray("Review staged draft answers")),console.log(chalk.white(" bg <command> ")+chalk.gray("Run a shell command in the background")),console.log(chalk.white(" tasks [id] ")+chalk.gray("Background task panel / view output")),console.log(chalk.white(" doctor ")+chalk.gray("Self-check: version, Python, server, tools")),console.log(chalk.white(" setup ")+chalk.gray("Configure settings")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language (15 supported)")),console.log(chalk.white(" logout ")+chalk.gray("Disconnect")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit (session saved)")),void console.log()):(console.log(chalk.bold.yellow(" Restricted Mode — activate with a token to unlock all commands")),console.log(),console.log(chalk.white(" activate <token> ")+chalk.gray("Unlock full access")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log())}
1
+ import{createInterface as o}from"node:readline";import{spawn as e,execSync as t}from"node:child_process";import chalk from"chalk";import{isConnected as n,getConfig as l,saveConfig as a}from"./lib/config.js";import{ensureLangCache as s}from"./lib/translations-fetcher.js";import{loadUiPack as r}from"./lib/i18n.js";import{isActivated as i,activateToken as c,isFreeCommand as g,isDeviceMatch as y,recordExit as m,recordResume as d,isFirstRunOrUpgrade as p,markVersionSeen as u}from"./lib/access.js";import{setReplMode as h}from"./lib/ui.js";import{returnToMainMenu as w,printMenuHint as f,menuHintInline as b}from"./lib/menu-nav.js";import{setMainRl as x}from"./lib/main-rl.js";import{shellSplit as v}from"./lib/shell-split.js";import{isChatActive as C,handleChatMessage as A}from"./commands/ai4ctf.js";import{renderToolMan as k}from"./lib/tool-man.js";import{isCtf4aiActive as I,handleCtf4aiMessage as $}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as T,handleCtf4VlaMessage as E}from"./commands/ctf4vla.js";import{isDemo2Active as S}from"./commands/demo2.js";import{loadDemo2Progress as O}from"./lib/demo2-progress.js";import{hasAnySimHistory as j,lastArmAt as N,lastBundledAt as L,lastSimAt as D}from"./lib/sim-cooldown.js";import{getExamState as R,getRealExamState as P,getDemoState as q,practicalChatCommand as F}from"./lib/exam-state.js";import{resolveResumePoint as M}from"./lib/resume.js";import{buildStatusLine as U}from"./lib/statusline.js";import{startBgTask as _,startAsyncTask as B,listBgTasks as W,getBgTask as Q,drainCompleted as Y,killAllBgTasks as z,runningCount as X}from"./lib/bgtasks.js";import{computeStart as J,renderStart as V}from"./commands/challenge.js";import{addDraft as G,listDrafts as H,removeDraft as Z,clearDrafts as K}from"./lib/drafts.js";import{resetTerminalTheme as oo}from"./lib/theme.js";import{ensureSandbox as eo,runInSandbox as to,isDockerAvailable as no}from"./lib/sandbox.js";import{checkShellRisk as lo,logShellAudit as ao,getActiveCwd as so}from"./lib/exam-sandbox.js";import{logCommand as ro}from"./lib/logger.js";import{startLogSync as io,stopLogSync as co}from"./lib/log-sync.js";import{installInputDynamics as go,uninstallInputDynamics as yo,stripPasteMarkers as mo}from"./lib/input-dynamics.js";import{startBroadcastPoll as po,stopBroadcastPoll as uo,showBroadcast as ho,isCompetitionJoined as wo,isMelCompetition as fo,isLeaderAccount as bo,isLeaderSession as xo,fetchPublicScoreboard as vo,isCommsActive as Co}from"./lib/comms.js";import{enterMemoScreen as Ao,enterJuryScreen as ko}from"./commands/comms.js";import{existsSync as Io,mkdirSync as $o,readFileSync as To,writeFileSync as Eo}from"node:fs";import{join as So}from"node:path";import{homedir as Oo}from"node:os";const jo="# ICOA exam interactive startup — auto-loaded by PYTHONSTARTUP\nimport base64, struct, hashlib, re, json, os, sys, binascii\ntry: import requests\nexcept ImportError: pass\ntry: from Crypto.Cipher import AES\nexcept ImportError: pass\ntry: from Crypto.Util.Padding import pad, unpad\nexcept ImportError: pass\ntry: from pwn import xor, p32, u32, p64, u64\nexcept ImportError: pass\ntry: import bs4\nexcept ImportError: pass\ntry: import numpy as np\nexcept ImportError: pass\ntry: from PIL import Image\nexcept ImportError: pass\n",No=Date.now();function Lo(){return fo()?chalk.yellow("icoa 2026> "):P()?chalk.cyan("icoa exam> "):function(){const o=q();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=No}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const Do=So(Oo(),"icoa-workspace"),Ro=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),Po="__REPL_NO_EXIT__",qo="2.5.1",Fo=["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","kaggle","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","learn","demo2","ctf4eai","ctf4vla","theme","sim","arena","eai","board","learn-pull","doctor","bg","tasks","drafts","help","menu","quit","q","exit","back","resume"],Mo={exam:["list","start","q","answer","submit","review","result","next","prev","mark","unmark","help"],ctf:["challenges","open","submit","scoreboard","status","join","logout","time"],challenge:["start","stop","status"],arena:["eai"],learn:["start","continue"]};function Uo(o){const e=o.replace(/^\s+/,"");if(/^\/\S*$/.test(e)){const o=e.slice(1).toLowerCase();return[Fo.filter(e=>e.startsWith(o)).map(o=>`/${o}`),e]}const t=e.split(/\s+/);if(t.length<=1){const o=(t[0]??"").toLowerCase();return[Fo.filter(e=>e.startsWith(o)).slice(),o]}if(2===t.length){const o=Mo[t[0].toLowerCase()];if(o){const e=t[1].toLowerCase();return[o.filter(o=>o.startsWith(e)).slice(),e]}}return[[],o]}async function _o(o){const e=M();if(!e)return null;const t=process.exit;process.exit=()=>{throw new Error(Po)};try{await o.parseAsync(["node","icoa",...e.command])}catch(o){if(!(o instanceof Error&&o.message===Po))throw o}finally{process.exit=t}return e}function Bo(){console.log(),console.log(` ${chalk.cyan.bold("🎯 ICOA 2026 · National Selection")}`),console.log(),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("ACxxxxxxxx")+chalk.gray(" → ai4ctf-12 (AI as your CTF teammate)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("CAxxxxxxxx")+chalk.gray(" → ctf4ai-12 (red-team software AI)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("EAxxxxxxxx")+chalk.gray(" → ctf4eai-12 (red-team embodied AI)")),console.log(" "+chalk.bold.cyan("exam ")+chalk.white("<CC>xxxxxxxx")+chalk.gray(" → Paper A/B/C/D/E (country exam token)")),console.log(" "+chalk.bold.cyan("demo")+chalk.gray(" → free practice")),console.log(" "+chalk.bold.cyan("lang")+chalk.white(" es")+chalk.gray(" → switch language")),console.log(" "+chalk.gray("help · menu · quit")),console.log()}export async function startRepl(e,q){process.env.ICOA_INSIDE_REPL="1";let No=!1;if(fo()){const o=l().joinedAt,e=o=>new Intl.DateTimeFormat("en-CA",{timeZone:"Australia/Sydney",year:"numeric",month:"2-digit",day:"2-digit"}).format(o);o&&e(new Date(o))===e(new Date)||(a({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:"",joinedAt:""}),No=!0)}const Mo=l(),Yo=n(),zo=process.exit.bind(process),Xo=i();if(Mo.language&&"en"!==Mo.language&&(await s(Mo.language,{silent:!0}),r(Mo.language)),Mo.demoCleanedForVersion!==qo){try{const{existsSync:o,unlinkSync:e}=await import("node:fs"),{join:t}=await import("node:path"),{getIcoaDir:n}=await import("./lib/config.js"),l=t(n(),"demo-state.json");o(l)&&e(l)}catch{}a({demoCleanedForVersion:qo})}const{select:Jo,confirm:Vo}=await import("@inquirer/prompts"),Go=Mo.mode||"",Ho=""===Go?"instant":["instant","learn","selection","olympiad"].includes(Go)?Go:"selection",Zo=[{name:` ${chalk.bold("⚡ Try ICOA in 30 seconds")} ${chalk.gray("—")} ${chalk.gray("watch · no token needed")}`,value:"instant"},{name:` ${chalk.bold("🧠 Learn")} ${chalk.gray("—")} ${chalk.gray("AC / CA / EA token · skill up")}`,value:"learn"},{name:` ${chalk.bold("🎯 National Selection")} ${chalk.gray("—")} ${chalk.gray("country exam token · aim for finals")}`,value:"selection"},{name:` ${chalk.bold("🏆 International Olympiad")} ${chalk.gray("—")} ${chalk.gray("finals stage · Sydney 2026 · full sandbox")}`,value:"olympiad"},{name:` ${chalk.gray("ℹ️ About ICOA")} ${chalk.gray("·")} ${chalk.gray("what this is · how to join")}`,value:"about"}];""===Go&&(console.log(chalk.green(" 👋 First time here? ")+chalk.white("Just press ")+chalk.bold.cyan("Enter")+chalk.white(" — you’ll see ICOA in 30 seconds, no signup needed.")),console.log()),console.log(chalk.gray(" Type ")+chalk.bold.cyan("menu")+chalk.gray(" from anywhere to return here.")),console.log();let Ko="";for(;!Ko;){let o;try{o=await Jo({message:"Mode",choices:Zo,default:Ho||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}"about"!==o?Ko=o:(console.clear(),console.log(),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(chalk.bold.yellow(" ICOA")+chalk.white(" — AI-Native CLI OS for Cyber & AI Security")),console.log(chalk.gray(" Olympiad & Competition · K-12 to University")),console.log(chalk.cyan(" ───────────────────────────────────────────────────")),console.log(),console.log(chalk.bold.white(" What Makes ICOA Different")),console.log(chalk.gray(" · AI-native AI teammate, AI adversary, AI translation")),console.log(chalk.gray(" · CLI OS Complete competition environment in terminal")),console.log(chalk.gray(" · 110 tools pwntools, z3, gdb, nmap, sleuthkit... pre-configured")),console.log(chalk.gray(" · Global scale 15,000+ concurrent exams · 15 languages")),console.log(),console.log(chalk.bold.white(" Competition Format (2-day standard + 1-day Pioneer)")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" [Day 1] AI as teammate — speed track, dynamic decay + top-3 bonus")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" [Day 2] AI as target — knowledge track, static value per challenge")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" [Pioneer / Practical Round] Embodied AI — VLA + world models + sim-to-real")}`),console.log(),console.log(chalk.bold.white(" Scoring (in brief)")),console.log(chalk.gray(" · Standard medals: AI4CTF + CTF4AI combined · 1/12 Gold · 2/12 Silver · 3/12 Bronze")),console.log(chalk.gray(" · HMA: top 50% on either day, total below bronze cutoff")),console.log(chalk.gray(" · CTF4EAI: separate 15-finalist pool, G/S/B + 12 Finalist Awards")),console.log(),console.log(chalk.white(" Sydney, Australia")+chalk.gray(" · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.bold.white(" Organized by")+chalk.gray(" ASRA (Australia) · ICO Foundation Inc")),console.log(chalk.bold.white(" Contact ")+chalk.cyan(" australia@icoa2026.au · accreditation@icoa2026.au")),console.log(chalk.bold.white(" Website ")+chalk.cyan.underline(" https://icoa2026.au")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(),console.log(chalk.gray(" Press ")+chalk.yellow("Enter")+chalk.gray(" to return...")),await new Promise(o=>{const e=t=>{process.stdin.removeListener("data",e),process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!1),process.stdin.pause(),o()};process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.once("data",e)}),console.clear())}if("olympiad"===Ko&&"olympiad"!==Ho){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await Vo({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(Ko="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(Ko!==Ho&&a({mode:Ko}),console.log(),"olympiad"===Ko&&p(qo)){u(qo),console.log(chalk.gray(" Checking competition environment..."));const{execSync:o}=await import("node:child_process"),e=[{name:"pwntools",cmd:'python3 -c "import pwn"'},{name:"z3-solver",cmd:'python3 -c "import z3"'},{name:"numpy",cmd:'python3 -c "import numpy"'},{name:"requests",cmd:'python3 -c "import requests"'}];let t=0;for(const n of e)try{o(n.cmd,{stdio:"ignore"})}catch{t++}t>0?(console.log(chalk.yellow(` ${t} core competition libraries missing.`)),console.log(chalk.gray(" Run ")+chalk.white("env setup")+chalk.gray(" when you are ready to install them.")),console.log()):(console.log(chalk.green(" All core libraries ready.")),console.log())}if(q){const o=d();if(o){const e=Math.floor(o.awaySeconds/60),t=o.awaySeconds%60;console.log(chalk.yellow(` Session resumed. Away: ${e}m ${t}s | Total exits: ${o.exitCount}`)),console.log()}}if("selection"===Ko)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),Bo();else if("embodied"===Ko)!function(){console.log(chalk.cyan.bold(" [🤖 ctf4eai — Embodied AI Security]")),console.log(),console.log(chalk.bold.cyan(" CTF4EAI")+chalk.gray(" — ICOA 2026's ")+chalk.bold.white("Pioneer Round")),console.log(chalk.gray(" an independent parallel track alongside the scored main events: ")+chalk.green("AI4CTF")+chalk.gray(" (Day 1) and ")+chalk.red("CTF4AI")+chalk.gray(" (Day 2)")),console.log(),console.log(chalk.white(" Embodied AI is at its ImageNet moment.")),console.log(chalk.gray(" VLA models, MuJoCo physics, real robot arms.")),console.log(chalk.gray(" Real models, real physics, real attack surfaces.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const o=L()>0||D()>0,e=N()>0,t=j(),n=O(),l=null!==n&&"number"==typeof n.completedAt&&n.nextCardIndex>=n.totalCards,a=null!==n&&!l;if(l)console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (demo2 ✓ · sim")+(e?chalk.gray(" ✓ · sim arm ✓)"):chalk.gray(")")));else if(a){const o=`${n.nextCardIndex} / ${n.totalCards}`;console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" (last left at card ")+chalk.bold.yellow(o)+chalk.gray(")"))}else o&&e?console.log(chalk.bold.yellow(" Next up: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (sim ✓ · sim arm ✓)")):t?console.log(chalk.bold.yellow(" Next up: ")+(e?chalk.bold.cyan("① sim")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2"):chalk.bold.cyan("② sim arm")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2"))+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")):console.log(chalk.bold.yellow(" First time? Try in order: ")+chalk.bold.cyan("① sim")+chalk.gray(" → ")+chalk.bold.cyan("② sim arm")+chalk.gray(" → ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01"));console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.bold.green(" sim")+chalk.gray(" ")+chalk.bold.cyan("①")+chalk.gray(" ")+chalk.bold.yellow("★ INSTANT")+chalk.gray(" — 9-robot group dance, no wait, no setup")),console.log(chalk.bold.green(" sim arm")+chalk.gray(" ")+chalk.bold.cyan("②")+chalk.gray(" interactive 6-DOF arm sandbox — type joint values, watch")),console.log(chalk.bold.green(" demo2")+chalk.gray(" ")+chalk.bold.cyan("③")+chalk.gray(" ~8 min interactive intro + live MuJoCo sim")),console.log(chalk.bold.green(" learn LEARNDEMO01")+chalk.gray(" ")+chalk.bold.cyan("④")+chalk.gray(" free 11-card intro (paste this command as-is)")),console.log(chalk.bold.green(" learn ")+chalk.bold.yellow("EA")+chalk.gray(" + 8 chars full 96 / 360 curriculum (team-issued)")),console.log(chalk.bold.green(" exam ")+chalk.bold.yellow("PDxxxxxxxx")+chalk.gray(" Paper D (CTF4EAI) — national selection contestants")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),console.log(chalk.gray(" Three open tiers: ")+chalk.green("free 11")+chalk.gray(" · ")+chalk.yellow("registered 100")+chalk.gray(" · ")+chalk.bold.magenta("national team 480")+chalk.gray(" (PhD-ready)")),console.log(chalk.gray(" Country team contact: ")+chalk.cyan("australia@icoa2026.au")),console.log(),f(),console.log()}();else if("instant"===Ko)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Two free tastes — just type the word and press Enter:")),console.log(),console.log(chalk.bold.green(" demo ")+chalk.gray(" Paper A/B/C taste — 10 MCQs, no timer ")+chalk.bold.cyan("🎯 selection-style")),console.log(chalk.bold.green(" demo2")+chalk.gray(" Embodied-AI mini-demo — robots & MuJoCo ")+chalk.bold.yellow("🤖 hands-on")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(" or ")+chalk.bold.cyan("demo2")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),a({mode:"selection"}),Ko="selection";else{if("learn"===Ko){console.log(chalk.cyan.bold(" [🧠 Learn]")),console.log(),console.log(chalk.gray(" Three tracks · same difficulty curve.")),console.log(),console.log(chalk.white(" Free 12-card demos — paste the full command:")),console.log(),console.log(chalk.gray(" 🤝 ai4ctf AI as your teammate ")+chalk.bold.yellow("learn AI4CTFDEMO01")),console.log(chalk.gray(" 🔓 ctf4ai AI as your target ")+chalk.bold.yellow("learn CTF4AIDEMO01")),console.log(chalk.gray(" 🤖 ctf4eai Embodied AI Security ")+chalk.bold.yellow("learn LEARNDEMO01")),console.log(),console.log(chalk.gray(" Got a cohort token? Type ")+chalk.bold.yellow("learn <TOKEN>")+chalk.gray(" (e.g. ")+chalk.bold.yellow("learn EAABCD1234")+chalk.gray(").")),console.log();try{const{input:o}=await import("@inquirer/prompts"),{resolveLearnInput:t}=await import("./lib/learn-input.js");console.log(chalk.gray(" Enter a token (or just press Enter to go back).")),console.log();const n=await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}),l=n.trim().toLowerCase();if("ai4ioai"===l||"/ai4ioai"===l){const{runAi4ioaiStandalone:o}=await import("./commands/ai4ioai.js");return await o(),a({mode:"selection"}),void w()}const s=t(n);if("token"===s.kind){console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${s.token}`)),console.log(),a({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";try{await e.parseAsync(["node","icoa","learn",s.token])}finally{delete process.env.ICOA_LEARN_EMBEDDED}}else"ambiguous"!==s.kind&&"unknown"!==s.kind||(console.log(),console.log(chalk.yellow(" "+s.hint)),console.log(chalk.gray(" Returning to main menu — pick 🧠 Learn again to retry.")),console.log())}catch{}return a({mode:"selection"}),void w()}"organizer"===Ko?(console.log(chalk.yellow.bold(" [National/Regional Partner]")),console.log(),console.log(chalk.bold.white(" ██╗ ██████╗ ██████╗ █████╗")),console.log(chalk.bold.white(" ██║██╔════╝██╔═══██╗██╔══██╗")),console.log(chalk.bold.white(" ██║██║ ██║ ██║███████║")),console.log(chalk.bold.white(" ██║██║ ██║ ██║██╔══██║")),console.log(chalk.bold.white(" ██║╚██████╗╚██████╔╝██║ ██║")),console.log(chalk.bold.white(" ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝")),console.log(),console.log(chalk.yellow(" International Cyber Olympiad in AI 2026")),console.log(chalk.bold.magenta(" The World's First AI-Native CLI Operating System")),console.log(chalk.bold.magenta(" for Cybersecurity & AI Security Competition")),console.log(chalk.bold.magenta(" and Olympiad for K-12")),console.log(chalk.gray(" Sydney, Australia · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.white(" Vision")),console.log(chalk.gray(" Building a global pipeline for youth cyber & AI")),console.log(chalk.gray(" security talent through education and competition.")),console.log(),console.log(chalk.white(" Capacity")),console.log(chalk.gray(" 15,000+ concurrent online examinations")),console.log(chalk.gray(" National selection, training, and education support")),console.log(),console.log(chalk.white(" Olympic Spirit")),console.log(chalk.gray(" Excellence · Friendship · Respect")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" New country accreditation & support:")),console.log(chalk.cyan(" australia@icoa2026.au")),console.log(chalk.cyan(" accreditation@icoa2026.au")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),Yo?(console.log(chalk.green(` Logged in as ${Mo.userName}`)),console.log(chalk.white(" exam list")+chalk.gray(" Manage exams")),console.log(chalk.white(" logout")+chalk.gray(" Disconnect"))):console.log(chalk.white(" join <url>")+chalk.gray(" Connect to manage exams")),console.log(),f(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),Xo&&!y()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):Yo?(console.log(chalk.green.bold(` Welcome back, ${Mo.userName}!`)),console.log(chalk.gray(` Connected to ${Mo.ctfdUrl}`)),console.log(chalk.gray(" Not you? Type ")+chalk.cyan("logout")+chalk.gray(" to switch accounts")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Ready to compete? Start here:")),console.log(),console.log(chalk.bold.cyan(" challenges")+chalk.gray(" Browse challenges by category")),console.log(chalk.white(" status")+chalk.gray(" Your score & timer")),console.log(chalk.white(" scoreboard")+chalk.gray(" Live rankings")),console.log(chalk.white(" memo")+chalk.gray(" Report an issue to organizers (one-way)")),console.log(),console.log(chalk.gray(" Tool environment:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.bold.yellow(" ★ ")+chalk.bold.cyan("man <tool>")+chalk.gray(" How to USE a tool (steghide, nmap…) · ")+chalk.cyan("man tools")+chalk.gray(" = list")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("help")+chalk.gray(" · ")+b()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):Xo?(Io(Do)||$o(Do,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${Do}`)),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Get started:")),console.log(),console.log(chalk.white(" Step 1 ")+chalk.bold.cyan("join <url>")+chalk.gray(" Connect to competition server")),console.log(chalk.white(" Step 2 ")+chalk.bold.cyan("challenges")+chalk.gray(" Browse & solve challenges")),console.log(chalk.white(" Step 3 ")+chalk.bold.cyan("ai4ctf")+chalk.gray(" Ask AI when stuck")),console.log(),console.log(chalk.gray(" Before Step 1 — make sure your tools are ready:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.bold.yellow(" ★ ")+chalk.bold.cyan("man <tool>")+chalk.gray(" How to USE a tool (steghide, nmap…) · ")+chalk.cyan("man tools")+chalk.gray(" = list")),console.log(),console.log(chalk.gray(" Also: ")+chalk.white("help")+chalk.gray(" all commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+b()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()):(console.log(chalk.bold.yellow(" 🏆 You reached the finals tier.")),console.log(chalk.gray(" Full sandbox · 110 CTF tools · Sydney 2026 · this is where finalists compete.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" To begin, activate your competition token:")),console.log(),console.log(chalk.bold.cyan(" activate <token>")),console.log(),console.log(chalk.gray(" While waiting, explore:")),console.log(chalk.white(" ref linux")+chalk.gray(" Quick reference for Linux")),console.log(chalk.white(" ref web")+chalk.gray(" Quick reference for Web")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.white(" help")+chalk.gray(" All available commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+b()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}e.exitOverride(),e.configureOutput({writeErr:()=>{},writeOut:o=>{console.log(o)}});const oe=o({input:process.stdin,output:process.stdout,prompt:Lo(),terminal:!0,completer:Uo});x(oe),go(!1!==l().bracketedPaste);let ee=!1;if(h(!0),io(),No&&(console.log(),console.log(chalk.yellow(" ⏱ A new competition day has started (Sydney time).")),console.log(chalk.gray(" For fairness, yesterday’s sign-in has been cleared. Type ")+chalk.cyan("join <url>")+chalk.gray(" to sign in with your account.")),console.log()),fo()){const o=l().userName||"this account";console.log(),console.log(chalk.yellow(" ⚠ This machine is signed in as ")+chalk.bold.white(o)+chalk.yellow(".")),console.log(chalk.gray(" Press ")+chalk.cyan("Enter")+chalk.gray(` to continue as ${o}, or type `)+chalk.cyan("logout")+chalk.gray(" to switch accounts.")),"logout"===(await new Promise(o=>{oe.question(chalk.white(" > "),e=>o(e.trim()))})).toLowerCase()&&(a({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:""}),console.log(),console.log(chalk.green(" ✓ Logged out. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" to sign in with your own account."))),console.log()}wo()&&po(()=>oe.prompt());let te=null;const ne=oe.prompt.bind(oe);oe.prompt=o=>{if(!(C()||I()||T()||S()||Co()||(oe.setPrompt(Lo()),o)))try{for(const o of Y()){const e="done"===o.status,t=o.cmd.length>40?`${o.cmd.slice(0,37)}…`:o.cmd,n=o.render?"":chalk.gray(" (")+chalk.white(t)+chalk.gray(") — ")+chalk.cyan(`tasks ${o.id}`);if(console.log((e?chalk.green(" ✓"):chalk.red(" ✗"))+chalk.white(` background task #${o.id} ${o.status}`)+n),o.render)try{o.render()}catch{}}const o=U();o&&o!==te?(console.log(o),te=o):o||(te=null)}catch{}ne(o)};const le=M();le&&(console.log(chalk.cyan(" ↻ Continue where you left off: ")+chalk.white(le.label)+(le.urgent?chalk.yellow(" (exam timer running)"):"")),console.log(chalk.gray(" type ")+chalk.cyan("resume")+chalk.gray(" to jump back in.")),console.log()),oe.prompt(),oe.on("line",async o=>{if(ee)return;let a=mo(o.trim());if(!a)return oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt();if(a.startsWith("/")&&!a.startsWith("//")){const o=a.slice(1).split(/\s+/)[0].toLowerCase(),t=a.slice(1+o.length).trim();if("ai"===o)return ee=!0,await async function(o,e){if(C())return void(o?await A(o):console.log(chalk.gray(" You are already in the AI chat — just type your message.")));if(I())return void(o?await $(o):console.log(chalk.gray(" You are already in the CTF4AI target chat — just type your message.")));if(T())return void(o?await E(o):console.log(chalk.gray(" You are already in the Embodied-AI chat — just type your message.")));ro(o?`/ai ${o}`:"/ai");const t=process.exit;process.exit=()=>{throw new Error(Po)};try{await e.parseAsync(["node","icoa","ai4ctf"])}catch(o){if(!(o instanceof Error&&o.message===Po))throw o}finally{process.exit=t}o&&C()&&await A(o)}(t,e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt();!(C()||I()||T()||S()||Co())&&Fo.includes(o)&&(a=a.slice(1))}if("resume"===a.toLowerCase()){const o=M();return o?(ro(`resume → ${o.command.join(" ")}`),ee=!0,await _o(e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),void oe.prompt()):(console.log(),console.log(chalk.gray(" Nothing to resume yet — start with ")+chalk.cyan("learn")+chalk.gray(" (curriculum) or ")+chalk.cyan("demo")+chalk.gray(" (taste).")),console.log(),void oe.prompt())}const s=C()||I()||T()||S();if(!s&&("bg"===a.toLowerCase()||/^bg\s/i.test(a))){const o=a.replace(/^bg\s*/i,"").trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("bg <command>")+chalk.gray(" — run a non-interactive shell command in the background.")),console.log(chalk.gray(" e.g. ")+chalk.cyan("bg nmap -p- 10.0.0.5")+chalk.gray(" · view: ")+chalk.cyan("tasks")),console.log(),void oe.prompt();const e=so(),t=lo(o);ao({cwd:e,input:`bg ${o}`,riskFlags:t}),t.length>0&&P()&&console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`));const n=_(o,e);return console.log(),console.log(chalk.cyan(` ▸ background task #${n.id} started`)+chalk.gray(` (${X()} running)`)),console.log(chalk.gray(" ")+chalk.white(o)),console.log(chalk.gray(" view: ")+chalk.cyan("tasks")+chalk.gray(" · output: ")+chalk.cyan(`tasks ${n.id}`)),console.log(),void oe.prompt()}if(!s&&("tasks"===a.toLowerCase()||/^tasks\s/i.test(a))){const o=a.replace(/^tasks\s*/i,"").trim(),e=W();if(console.log(),o){const e=Q(Number(o));if(!e||Number.isNaN(Number(o)))console.log(chalk.yellow(` No background task #${o}.`)+chalk.gray(" Type ")+chalk.cyan("tasks")+chalk.gray(" to list them."));else{const o="running"===e.status?chalk.yellow:"done"===e.status?chalk.green:chalk.red;console.log(o(` #${e.id} [${e.status}]`)+chalk.white(` ${e.cmd}`)+(null!==e.exitCode?chalk.gray(` (exit ${e.exitCode})`):"")),console.log(chalk.gray(" ─────────────────────────────────────────────"));const t=e.output.trim();if(t)for(const o of t.split("\n"))console.log(chalk.gray(" ")+chalk.white(o));else console.log(chalk.gray(" (no output yet)"))}}else if(0===e.length)console.log(chalk.gray(" No background tasks. Start one with ")+chalk.cyan("bg <command>")+chalk.gray("."));else{console.log(chalk.bold.white(" Background tasks"));for(const o of e){const e="running"===o.status?chalk.yellow("●"):"done"===o.status?chalk.green("✓"):chalk.red("✗"),t=Math.round(((o.endedAt??Date.now())-o.startedAt)/1e3),n=(o.endedAt?`${t}s`:`${t}s…`).padStart(5),l=o.cmd.length>48?`${o.cmd.slice(0,45)}…`:o.cmd;console.log(` ${e} `+chalk.white(`#${o.id}`)+chalk.gray(` ${n} `)+chalk.white(l))}console.log(chalk.gray(" output: ")+chalk.cyan("tasks <id>"))}return console.log(),void oe.prompt()}if(!s&&/&\s*$/.test(a)&&/^challenge\s+start\s+/i.test(a)){const o=a.replace(/\s*&\s*$/,"").trim().replace(/^challenge\s+start\s+/i,"").trim().split(/\s+/),e=o.some(o=>"-n"===o||"--new"===o),t=o.find(o=>"-n"!==o&&"--new"!==o);if(!t)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("challenge start <id> &")),console.log(),void oe.prompt();if(!n())return console.log(),console.log(chalk.red(" Not connected. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" first.")),console.log(),void oe.prompt();ro(`challenge start ${t}${e?" --new":""} & (background)`);const l=B(`challenge start ${t}`,()=>J(t,e),o=>V(t,o));return console.log(),console.log(chalk.cyan(` ▸ background task #${l.id}: `)+chalk.white(`starting ${t}`)+chalk.gray(" — you can keep working; the connection info appears here when it is ready.")),console.log(),void oe.prompt()}if(!s&&a.startsWith("#")){const o=a.slice(1).trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("#<candidate answer>")+chalk.gray(" — stage a flag/answer WITHOUT submitting it. Review with ")+chalk.cyan("drafts")+chalk.gray(".")),console.log(),void oe.prompt();const e=R(),t=e?.session?.examId??null,n=e?e._lastQ||1:null,l=G(o,t,n);return ro(`draft #${l.id} (not submitted)`),console.log(),console.log(chalk.green(` ✎ draft #${l.id} saved`)+(n?chalk.gray(` (Q${n})`):"")+chalk.yellow(" — NOT submitted.")),console.log(chalk.gray(" review with ")+chalk.cyan("drafts")+chalk.gray("; when sure, submit it the normal way.")),console.log(),void oe.prompt()}if(!s&&("drafts"===a.toLowerCase()||/^drafts\s/i.test(a))){const o=a.replace(/^drafts\s*/i,"").trim().toLowerCase();if("clear"===o){const o=K();return console.log(),console.log(chalk.gray(` Cleared ${o} draft${1===o?"":"s"}.`)),console.log(),void oe.prompt()}const e=o.match(/^(?:rm|remove|del|delete)\s+(\d+)$/);if(e){const o=Z(Number(e[1]));return console.log(),console.log(o?chalk.gray(` Removed draft #${e[1]}.`):chalk.yellow(` No draft #${e[1]}.`)),console.log(),void oe.prompt()}const t=R(),n=H(t?.session?.examId??null);if(console.log(),0===n.length)console.log(chalk.gray(" No drafts yet. Stage a candidate with ")+chalk.cyan("#ICOA{maybe_this}")+chalk.gray(" — it won’t submit."));else{console.log(chalk.bold.white(" Draft answers")+chalk.gray(" (staged — not submitted)"));for(const o of n){const e=o.q?chalk.cyan(`Q${o.q}`.padStart(4)):chalk.gray(" · ");console.log(chalk.gray(` #${o.id}`)+` ${e} `+chalk.white(o.text.length>56?`${o.text.slice(0,53)}…`:o.text))}console.log(chalk.gray(" remove: ")+chalk.cyan("drafts rm <id>")+chalk.gray(" · clear all: ")+chalk.cyan("drafts clear"))}return console.log(),void oe.prompt()}if("menu"===a||"menu confirm"===a)return P()&&"menu confirm"!==a?(console.log(),console.log(chalk.yellow(" Real exam active. Progress is auto-saved.")),console.log(chalk.gray(" To return to main menu anyway, type ")+chalk.white("menu confirm")),console.log(),void oe.prompt()):void w(oe);if(C()){ee=!0;const o=await A(a);return ee=!1,"exit"===o&&oe.setPrompt(Lo()),void oe.prompt()}if(I()){ee=!0;const o=await $(a);return ee=!1,"exit"!==o&&"solved"!==o||oe.setPrompt(Lo()),void oe.prompt()}if(T()){ee=!0;const o=await E(a);return ee=!1,"exit"===o&&oe.setPrompt(Lo()),oe.setPrompt(T()?chalk.bold.cyan("icoa ctf4eai> "):Lo()),void oe.prompt()}if(ro(a),"exit"===a)return R()?(console.log(),console.log(chalk.yellow(" ⚠ An exam is in progress.")),console.log(chalk.white(" To return to menu without losing progress, type: ")+chalk.bold.cyan("back")),console.log(chalk.white(" To fully close ICOA CLI, type: ")+chalk.bold.cyan("quit")),console.log(chalk.gray(" Your progress is auto-saved either way.")),console.log(),void oe.prompt()):(console.log(),console.log(chalk.gray(" ")+chalk.white("exit")+chalk.gray(" returns to the main menu. To fully close ICOA CLI, type ")+chalk.bold.cyan("quit")+chalk.gray(".")),"selection"===Ko&&Bo(),void oe.prompt());if("quit"===a||"q"===a||"quit confirm"===a){const o=R();return o&&"demo-free"!==o.session.examId&&"quit confirm"!==a?(console.log(),console.log(chalk.yellow(" ⚠ A real exam is in progress.")),console.log(chalk.gray(" Your answers are auto-saved on the server, but the exam timer keeps ticking")),console.log(chalk.gray(" on the server side even if you close the CLI.")),console.log(),console.log(chalk.white(" To leave the CLI but keep the exam alive, type: ")+chalk.bold.cyan("back")),console.log(chalk.gray(" (recommended — you can resume with ")+chalk.cyan("exam q 1")+chalk.gray(" after relaunching icoa)")),console.log(),console.log(chalk.white(" To really close ICOA CLI, type: ")+chalk.bold.cyan("quit confirm")),console.log(),void oe.prompt()):(o&&"demo-free"===o.session.examId&&(console.log(),console.log(chalk.gray(" Demo paused. Resume with: ")+chalk.white("demo")+chalk.gray(" (fresh) or ")+chalk.white("exam q 1")+chalk.gray(" (continue)."))),co(),yo(),uo(),z(),m(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),oo(),void zo(0))}if("back"===a){const o=R(),e=o&&"demo-free"!==o.session.examId,t=o&&"demo-free"===o.session.examId&&(()=>{const e=new Date(o.session.startedAt||0).getTime();return Date.now()-e<18e5})();if(e)console.log(),console.log(chalk.gray(" Exam paused. Your progress is saved.")),console.log(chalk.white(" Resume: exam q 1")+chalk.gray(" · ")+chalk.white("exam review")+chalk.gray(" · ")+chalk.white("exam submit")),console.log();else if(t){const e=Object.keys(o.answers).length,t=o.session.questionCount;console.log(),console.log(chalk.gray(` Demo paused (${e}/${t} answered). Resume with: `)+chalk.white("exam q 1")),console.log(chalk.gray(" Or type ")+chalk.white("demo")+chalk.gray(" to restart.")),console.log()}else{if(o&&"demo-free"===o.session.examId){const{clearExamState:o}=await import("./lib/exam-state.js");o("demo-free")}const e=l();fetch("https://practice.icoa2026.au/api/icoa/demo-stats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"post-report-back",lang:e.language||"en",timestamp:(new Date).toISOString()}),signal:AbortSignal.timeout(5e3)}).catch(()=>{}),"selection"===Ko?Bo():console.log(chalk.gray(" Already at main menu."))}return void oe.prompt()}if("help"===a||"?"===a){if(R()){ee=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return ee=!1,void oe.prompt()}return Qo(i(),Ko),void oe.prompt()}if("man"===a||"manual"===a)return Qo(i(),Ko),console.log(),console.log(chalk.bold.yellow(" ★ Stuck on a tool? ")+chalk.bold.cyan("man <tool>")+chalk.gray(" e.g. ")+chalk.cyan("man steghide")+chalk.gray(" · ")+chalk.cyan("man tools")+chalk.gray(" = full list")),void oe.prompt();if(/^(?:man|manual)\s+\S/i.test(a))return k(a.replace(/^(?:man|manual)\s+/i,"")),void oe.prompt();if("more help"===a.toLowerCase()&&R()){ee=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return ee=!1,void oe.prompt()}if("continue"===a.toLowerCase())return console.log(),console.log(chalk.green.bold(" ═══ AI4CTF — AI as Your Teammate ═══")),console.log(),console.log(chalk.white(" In AI4CTF, you solve cybersecurity challenges")),console.log(chalk.white(" with AI by your side.")),console.log(),console.log(chalk.white(" In this demo, your AI teammate gives help at 3 levels:")),console.log(chalk.yellow(" hint a")+chalk.gray(" General guidance")),console.log(chalk.yellow(" hint b")+chalk.gray(" Deep analysis")),console.log(chalk.yellow(" hint c")+chalk.gray(" Critical assist")),console.log(),console.log(chalk.white(" Try it now! Type: ")+chalk.bold.green("ai4ctf")),console.log(chalk.gray(' Chat freely with your AI teammate. Type "exit" when done.')),console.log(),console.log(chalk.gray(" After ai4ctf, try: ")+chalk.bold.red("ctf4ai")+chalk.gray(' — trick the AI into saying "koala"')),console.log(),void oe.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(a.trim())){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",a.trim()])}catch{}return ee=!1,void oe.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(a.trim())){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",a.trim().toUpperCase()])}catch{}return ee=!1,void oe.prompt()}const r=a.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(r){ee=!0;try{await e.parseAsync(["node","icoa","exam","token",r[1].toUpperCase()])}catch{}return ee=!1,void oe.prompt()}const d=a.match(/^exam\s+([A-Z]{2,3})$/i);if(d){ee=!0;try{await e.parseAsync(["node","icoa","exam","list",d[1]])}catch{}return ee=!1,void oe.prompt()}if("clear"===a||"cls"===a)return console.clear(),void oe.prompt();if("news"===a)return wo()?ho():console.log(chalk.gray(" No competition joined. Use ")+chalk.white("join <url>")+chalk.gray(".")),void oe.prompt();if("memo"===a){if(!wo())return console.log(chalk.gray(" Join a competition first: ")+chalk.white("join <url>")),void oe.prompt();ee=!0;try{await Ao()}catch{}return void(ee=!1)}const p=xo()||bo(l().userName||"");if("jury"===a&&p){ee=!0;try{await ko()}catch{}return void(ee=!1)}if(p&&xo()&&"scoreboard"===a.split(/\s+/)[0]){ee=!0;try{const o=await vo();if(console.log(),0===o.length)console.log(chalk.gray(" Scoreboard is empty."));else{console.log(chalk.bold.white(" Scoreboard"));for(const e of o.slice(0,50))console.log(chalk.gray(` ${String(e.pos).padStart(3)}. `)+chalk.white(e.name.padEnd(28).slice(0,28))+chalk.cyan(String(e.score)))}console.log()}catch{}return ee=!1,void oe.prompt()}if(p&&fo()){const o=a.split(/\s+/)[0];if(["challenges","open","submit","hint"].includes(o))return console.log(),console.log(chalk.yellow(" Team-leader account — the challenge bracket is not available here.")),console.log(chalk.gray(" Available: ")+chalk.white("scoreboard")+chalk.gray(" · ")+chalk.white("news")+chalk.gray(" · ")+chalk.white("jury")+chalk.gray(" · ")+chalk.white("time")+chalk.gray(" · ")+chalk.white("status")+chalk.gray(" · ")+chalk.white("logout")),console.log(),void oe.prompt()}if(a.startsWith("activate ")){const o=a.slice(9).trim(),e=c(o);return"ok"===e?console.log(chalk.green(" Access granted! Token bound to this device.")):"already_bound"===e?(console.log(),console.log(chalk.red(" Token already activated on a different device.")),console.log(chalk.gray(" Each token binds to the first device that uses it. If you lost the device,")),console.log(chalk.gray(" contact your proctor to have the token re-issued for a new device."))):(console.log(),console.log(chalk.red(" Token not recognized.")),console.log(chalk.gray(" Possible reasons:")),console.log(chalk.white(" • ")+chalk.gray("Typo — access tokens are case-insensitive and look like ")+chalk.cyan("ICOA-XXXX-XXXX-XXXX")+chalk.gray(" (4-char hex groups, e.g. ICOA-385E-27F2-B21B)")),console.log(chalk.white(" • ")+chalk.gray("Expired — ask your proctor or organizer for a fresh token")),console.log(chalk.white(" • ")+chalk.gray("Network — verify connection to ")+chalk.cyan("practice.icoa2026.au")),console.log(chalk.gray(" Still stuck? type ")+chalk.cyan("help")+chalk.gray(" or try ")+chalk.cyan("exam demo")+chalk.gray(" for a free practice round."))),console.log(),void oe.prompt()}if("activate"===a)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void oe.prompt();const u=R();if(u){const o=a.toUpperCase().trim(),t=o=>{const e=u.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},n=o=>{const e=u.questions.find(e=>e.number===o);return"short_answer"===e?.type},l=o=>{const e="demo-free"!==u.session.examId,t=u.questions.find(e=>e.number===o),n=F(t?.type,e);console.log(),console.log(chalk.yellow(` Q${o} is a practical question — letters (A/B/C/D) don't apply here.`)),n?(console.log(chalk.white(" Enter the AI chat for this question: ")+chalk.bold.cyan(n)),console.log(chalk.gray(" Or submit a flag directly: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`))):console.log(chalk.gray(" Submit a flag: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`)),console.log()};if(/^[ABCDE]$/.test(o)){const a=u._lastQ||1;if(t(a))return l(a),void oe.prompt();if(n(a))return console.log(),console.log(chalk.yellow(` Q${a} is a short-answer question — type a number, not a letter.`)),console.log(chalk.gray(" Example: ")+chalk.green("42")+chalk.gray(" (or ")+chalk.green(`exam answer ${a} 42`)+chalk.gray(")")),console.log(),void oe.prompt();ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(a),o])}catch{}return ee=!1,void oe.prompt()}if(/^-?\d+$/.test(o)){const t=u._lastQ||1;if(n(t)){ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(t),o])}catch{}return ee=!1,void oe.prompt()}}const s=o.match(/^(\d+)\s+([ABCDE]|-?\d+)$/);if(s){const o=parseInt(s[1],10);if(t(o))return l(o),void oe.prompt();ee=!0;try{await e.parseAsync(["node","icoa","exam","answer",s[1],s[2]])}catch{}return ee=!1,void oe.prompt()}}const h=a.split(/\s+/)[0].toLowerCase(),f=/^python3?(\.\d+)?$/.test(h),b="ls"===h||"pwd"===h,x=a.startsWith("!")||h.startsWith("!")||f||b,O=new Set(["nano","vi","vim","emacs","pico","ed","code","cat","less","more","head","tail","ls","pwd","cd","base64","xxd","hexdump","od","openssl","md5sum","sha256sum","grep","find","awk","sed","strings","file","curl","wget","nc","ping","nmap","echo","bash","sh","zsh","pip","pip3","node","npm"]),j=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${a}`)),console.log()};if("embodied"===Ko&&!x&&!["doctor","demo2","learn","exam","ctf4eai","ctf4vla","eai","arena","lang","ref","setup","env","aienv","ipynb","kaggle","sim"].includes(h))return O.has(h)?(j(),void oe.prompt()):(console.log(chalk.gray(" Not available in Embodied AI Security mode.")),console.log(chalk.white(" Try ")+chalk.bold.cyan("demo2")+chalk.gray(" (intro) · ")+chalk.bold.cyan("learn")+chalk.gray(" (curriculum) · ")+chalk.bold.cyan("exam <PD-token>")+chalk.gray(" (Paper D)")),console.log(),void oe.prompt());if("selection"===Ko&&!x&&!["doctor","exam","demo","demo2","retry","nations","next","prev","continue","setup","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","aienv","ipynb","kaggle","sim"].includes(h)){if(O.has(h))return j(),void oe.prompt();if(console.log(chalk.gray(" Not available in Selection mode.")),u){const o=u._lastQ||1;console.log(chalk.white(` Resume exam: exam q ${o}`)+chalk.gray(" · ")+chalk.white("A/B/C/D")+chalk.gray(" to answer"))}else console.log(chalk.gray(" Try: demo · setup to switch mode"));return console.log(),void oe.prompt()}if("organizer"===Ko&&!["doctor","join","exam","demo","retry","next","prev","logout","setup","lang","ref","ctf","mark","unmark","review","submit"].includes(h))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void oe.prompt();if(!("olympiad"!==Ko||i()&&y()||g(h)))return console.log(chalk.yellow(" Restricted mode. ")+chalk.gray("Enter your access token:")),console.log(chalk.white(" activate <token>")),console.log(),console.log(chalk.gray(" Free commands: ")+chalk.white("ref [topic]")+chalk.gray(", ")+chalk.white("help")+chalk.gray(", ")+chalk.white("exit")),console.log(),void oe.prompt();if(!["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","kaggle","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","submit","learn","demo2","ctf4eai","ctf4vla","theme","sim","arena","eai","board","learn-pull","doctor"].includes(h)){if(Ro.has(h))return console.log(chalk.yellow(` "${h}" is a shell command — the ICOA prompt isn't a shell.`)),console.log(chalk.gray(" In real-exam mode, prefix with ! to run inside the sandbox: ")+chalk.cyan(`!${a}`)),console.log(),void oe.prompt();if(/(?:^|\s)(?:\/(?!home\/|Users\/|tmp\/)|\.\.\/|~\/)/.test(a)&&!a.startsWith("cd ")){const o=/(?:^|\s)\/(?!home\/\w+\/icoa-workspace|Users\/\w+\/icoa-workspace|tmp\/)/.test(a),e=/\.\./.test(a);if(o||e)return console.log(chalk.red(" Blocked: access outside workspace is not allowed.")),console.log(chalk.gray(` Workspace: ${Do}`)),console.log(),void oe.prompt()}let o=a.startsWith("!")?a.slice(1).trim():a;if("darwin"===process.platform){const e="/opt/homebrew/opt/python@3.12/bin/python3.12";o=o.replace(/^python3?\s/,`${e} `).replace(/^(python3|python)$/,e)}else if("win32"===process.platform){const e=(()=>{try{return t("py -3 --version",{stdio:["ignore","ignore","ignore"],timeout:1500}),"py -3"}catch{}return"python"})();o=o.replace(/^python3?(\.\d+)?\s/,`${e} `).replace(/^python3?(\.\d+)?$/,e)}else{const e=(()=>{try{return t("which python3.12",{stdio:"ignore"}),"python3.12"}catch{return"python3"}})();o=o.replace(/^python\s/,`${e} `).replace(/^python$/,e)}const e=so(),n=lo(a);ao({cwd:e,input:a,riskFlags:n}),n.length>0&&P()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${n.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=So(Oo(),".icoa");Io(o)||$o(o,{recursive:!0});const e=So(o,"python-startup.py");let t="";if(Io(e))try{t=To(e,"utf-8")}catch{}return t!==jo&&Eo(e,jo),e}()}" ${o}`,console.log(),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log(chalk.bold.white(" Python ready — ICOA exam toolkit pre-loaded")),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log(),console.log(chalk.white(" Already imported: ")+chalk.gray("base64, struct, hashlib, re, json, binascii")),console.log(chalk.white(" Also available: ")+chalk.gray("requests, bs4, numpy, PIL.Image, AES, pad/unpad, xor, p32/u32/p64/u64")),console.log(),console.log(chalk.yellow(" Quick examples:")),console.log(chalk.gray(' base64.b64decode("aGVsbG8=") ')+chalk.gray("# decode base64")),console.log(chalk.gray(' bytes.fromhex("48656c6c6f") ')+chalk.gray("# hex → bytes")),console.log(chalk.gray(' "ICOA{x}".encode() ')+chalk.gray("# str → bytes")),console.log(chalk.gray(" [chr(c) for c in [73,67,79,65]] ")+chalk.gray("# ASCII codes")),console.log(chalk.gray(' xor(bytes.fromhex("0a2b"), b"IC") ')+chalk.gray("# pwntools XOR")),console.log(),console.log(chalk.gray(" Exit: ")+chalk.white("exit()")+chalk.gray(" or Ctrl-D")),console.log(chalk.cyan(" ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")),console.log()),ee=!0;try{await no()&&await eo()?await to(o,oe):await Wo(o,oe,e)}catch{console.log(chalk.yellow(` Command failed: ${h}`))}return ee=!1,console.log(),void oe.prompt()}ee=!0;const N=a.trim(),L=N.toLowerCase();let D,q=null,U="";if(u)if("submit"===L)q="final";else if(L.startsWith("submit ")){let o=N.slice(7).trim();/^submit\s+/i.test(o)&&(o=o.replace(/^submit\s+/i,"").trim()),o=o.replace(/^["'`]+|["'`]+$/g,"").trim(),o&&/^ICOA\{[^}]*\}?$/i.test(o)?(q="flag",U=o):o&&/^[ABCDE]$/i.test(o)&&(q="flag",U=o.toUpperCase())}else/^ICOA\{[^}]+\}$/i.test(N)&&(q="flag",U=N);D="final"===q?["exam","submit"]:"flag"===q?["exam","answer",String(u?._lastQ||1),U]:function(o){const e=o.split(/\s+/),t=e[0].toLowerCase(),n=e.slice(1);if("aienv"===t&&["run","python","py"].includes((n[0]??"").toLowerCase()))return v(o);if(("submit"===t||"flag"===t)&&n.length>=2)return["ctf","submit",n[0],n.slice(1).join(" ").trim().replace(/^["'`]+|["'`]+$/g,"")];if("connect"===t&&n.length>=2){const e=v(o);return["connect",e[1]??n[0],e.slice(2).join(" ")]}const l={demo:["exam","demo"],retry:["exam","demo-retry"],nations:["exam","nations"],next:["exam","next"],prev:["exam","prev"],mark:["exam","mark",...n],unmark:["exam","unmark",...n],review:["exam","review"],logout:["ctf","logout"],join:["ctf","join",...n],activate:["ctf","activate",...n],challenges:["ctf","challenges"],ch:["ctf","challenges"],open:["ctf","open",...n],submit:["ctf","submit",...n],flag:["ctf","submit",...n],scoreboard:["ctf","scoreboard",...n],sb:["ctf","scoreboard",...n],status:["ctf","status"],time:["ctf","time"]};return l[t]?l[t]:["ref","shell","files","view","connect","challenge","note","notes","logbook","log","man","manual","lang","setup","env","aienv","ipynb","kaggle","ai4ctf","model","ctf","exam","ctf4ai","doctor"].includes(t)?[t,...n]:e}(a);const Y="ctf"===D[0]&&"join"===D[1];Y&&oe.pause(),process.exit=()=>{throw new Error(Po)};try{await e.parseAsync(["node","icoa",...D])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===Po);else if(e.includes("commander.unknownCommand")){const{distance:o}=await import("fastest-levenshtein"),e=["ctf","ref","shell","files","view","connect","challenge","note","notes","logbook","log","manual","lang","setup","env","aienv","ipynb","kaggle","ai4ctf","exam","ctf4ai","theme","eai","board","clear","cls","quit","exit","back","menu","help","continue","activate","demo","challenges","status","scoreboard","join","logout"],t=h.split(/\s+/)[0]||h;let n={word:"",dist:1/0};for(const l of e){const e=o(t.toLowerCase(),l);e<n.dist&&(n={word:l,dist:e})}console.log(chalk.yellow(` Unknown command: ${h}.`)),n.dist>0&&n.dist<=2&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(n.word)+chalk.gray("?")),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for the full command list."))}else e.includes("commander.missingArgument")||"commander.missingArgument"===o?.code?"submit"===h||"flag"===h?(console.log(chalk.yellow(" Incomplete — usage: ")+chalk.cyan("submit <challenge#> <flag>")),console.log(chalk.gray(" Put the number AND the flag on one line, e.g. ")+chalk.cyan("submit 44 pecan{...}"))):(console.log(chalk.yellow(` Incomplete command: ${h}`)),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for usage."))):e.includes("commander.")||(e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ETIMEDOUT"))&&console.log(chalk.yellow(" Network error. Check your connection."))}finally{process.exit=zo,ee=!1,Y&&oe.resume()}C()?oe.setPrompt(chalk.magenta("icoa ai4ctf> ")):I()?oe.setPrompt(chalk.red("icoa ctf4ai> ")):T()&&oe.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),oe.prompt()}),oe.on("SIGINT",()=>{if(console.log(),C()||I())console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still in the AI chat.")),console.log(chalk.white(" Type ")+chalk.bold.cyan("exit")+chalk.white(" to leave the chat and return to the menu."));else if(R()){const o="demo-free"!==R().session.examId;console.log(chalk.yellow(" Ctrl+C did NOT close ICOA CLI.")),console.log(chalk.gray(` Your ${o?"exam":"demo"} is paused and every answer is auto-saved.`)),console.log(),console.log(chalk.white(" Resume: ")+chalk.cyan("exam q 1")+chalk.gray(" · Back to menu: ")+chalk.cyan("back")+chalk.gray(" · Close CLI: ")+chalk.cyan(o?"quit confirm":"quit"))}else console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still at the ")+chalk.cyan("icoa>")+chalk.yellow(" prompt.")),console.log(chalk.gray(" Keep typing — ")+chalk.cyan("help")+chalk.gray(" lists commands. (Only ")+chalk.cyan("quit")+chalk.gray(" or Ctrl+D actually close the CLI.)"));console.log(),oe.prompt()}),oe.on("close",()=>{co(),yo(),uo(),z(),m(),oo(),zo(0)}),"1"===process.env.ICOA_AUTO_RESUME&&(delete process.env.ICOA_AUTO_RESUME,M()&&(ee=!0,await _o(e),ee=!1,oe.setPrompt(C()?chalk.magenta("icoa ai4ctf> "):Lo()),oe.prompt()))}function Wo(o,t,n){return new Promise(l=>{const a=process.stdin,s=!!a.isTTY&&!!a.isRaw;if(t.pause(),a.isTTY&&"function"==typeof a.setRawMode)try{a.setRawMode(!1)}catch{}const r=e(o,{shell:!0,stdio:"inherit",cwd:n||process.cwd()}),i=()=>{if(a.isTTY&&"function"==typeof a.setRawMode&&s)try{a.setRawMode(!0)}catch{}t.resume(),l()};r.on("close",i),r.on("error",i)})}function Qo(o,e="olympiad"){return console.log(),"selection"===e||"organizer"===e?(console.log(chalk.bold.white(" Exam")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to exam server")),console.log(chalk.white(" exam list ")+chalk.gray("Available exams")),console.log(chalk.white(" exam start <id> ")+chalk.gray("Begin an exam")),console.log(chalk.white(" exam q [n] ")+chalk.gray("View questions")),console.log(chalk.white(" exam answer <n> <X> ")+chalk.gray("Answer question")),console.log(chalk.white(" exam review ")+chalk.gray("Review all answers")),console.log(chalk.white(" exam submit ")+chalk.gray("Submit for grading")),console.log(chalk.white(" exam result ")+chalk.gray("View your score")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" setup ")+chalk.gray("Settings / switch mode")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log()):o?(console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(chalk.bold.white(" How it works")),console.log(),console.log(chalk.gray(" 1. Browse ")+chalk.white("challenges")+chalk.gray(" and pick one")),console.log(chalk.gray(" 2. ")+chalk.white("open <id>")+chalk.gray(" to read the challenge")),console.log(chalk.gray(" 3. Use ")+chalk.white("ai4ctf")+chalk.gray(" to chat with AI when stuck")),console.log(chalk.gray(" 4. ")+chalk.white("submit <id> <flag>")+chalk.gray(" to score points")),console.log(chalk.gray(" 5. Check ")+chalk.white("scoreboard")+chalk.gray(" to track your rank")),console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(),console.log(chalk.bold.white(" Competition")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to CTFd")),console.log(chalk.white(" challenges (ch) ")+chalk.gray("List challenges by category")),console.log(chalk.white(" open <id> ")+chalk.gray("Read challenge + get next steps")),console.log(chalk.white(" submit <id> <flag> ")+chalk.gray("Submit a flag")),console.log(chalk.white(" scoreboard (sb) ")+chalk.gray("Live rankings")),console.log(chalk.white(" status ")+chalk.gray("Your score & timer")),console.log(chalk.white(" time ")+chalk.gray("Countdown timer")),console.log(),console.log(chalk.bold.white(" AI Teammate")),console.log(chalk.white(" ai4ctf ")+chalk.gray("Free-chat with your AI teammate")),console.log(),console.log(chalk.bold.white(" Tools")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference (linux, web, crypto...)")),console.log(chalk.white(" shell ")+chalk.gray("Interactive CTF shell (sandbox if present, else host)")),console.log(chalk.white(" files <id> ")+chalk.gray("Download challenge files")),console.log(chalk.white(" connect <id> ")+chalk.gray("Connect to remote target")),console.log(chalk.white(" note [text] ")+chalk.gray("Add a logbook entry (in-exam: tags current Q)")),console.log(chalk.white(" logbook [n] ")+chalk.gray("View your logbook (in-exam: filter by Q)")),console.log(chalk.white(" log ")+chalk.gray("Session history")),console.log(chalk.white(" man <tool> ")+chalk.bold.yellow("★ ")+chalk.gray("How to use a tool (steghide, nmap…); ")+chalk.cyan("man tools")+chalk.gray(" = list. Bare ")+chalk.cyan("man")+chalk.gray(" = this list.")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" resume ")+chalk.gray("Continue your last learn card / exam")),console.log(chalk.white(" #<candidate> ")+chalk.gray("Stage a draft answer (never auto-submits)")),console.log(chalk.white(" drafts ")+chalk.gray("Review staged draft answers")),console.log(chalk.white(" bg <command> ")+chalk.gray("Run a shell command in the background")),console.log(chalk.white(" tasks [id] ")+chalk.gray("Background task panel / view output")),console.log(chalk.white(" doctor ")+chalk.gray("Self-check: version, Python, server, tools")),console.log(chalk.white(" setup ")+chalk.gray("Configure settings")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language (15 supported)")),console.log(chalk.white(" logout ")+chalk.gray("Disconnect")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit (session saved)")),void console.log()):(console.log(chalk.bold.yellow(" Restricted Mode — activate with a token to unlock all commands")),console.log(),console.log(chalk.white(" activate <token> ")+chalk.gray("Unlock full access")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log())}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.379",
3
+ "version": "2.19.381",
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": {