icoa-cli 2.19.703 → 2.19.704
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/ai4startup.js +1 -0
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/duck.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/commands.js +1 -1
- package/dist/lib/deck.js +1 -0
- package/dist/lib/duck-trace-run.js +11 -2
- package/dist/lib/guide-panel.js +1 -1
- package/dist/lib/headless-pdf.js +1 -0
- package/dist/lib/venture-sync.js +1 -0
- package/dist/lib/venture.js +1 -0
- package/dist/repl.js +1 -1
- package/package.json +1 -1
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{appendExitLog as n}from"./lib/exit-log.js";import{dispatchable as a,helpRows as l,shortcutFor as s,subcommandsOf as r,surface as i}from"./lib/commands.js";import{distance as c}from"fastest-levenshtein";import{isConnected as g,getConfig as m,saveConfig as d}from"./lib/config.js";import{selectionSetupLine as y}from"./lib/python-setup.js";import{isExamSetupComplete as u}from"./lib/exam-setup.js";import{detectCaps as p}from"./lib/render-card.js";import{ensureLangCache as h}from"./lib/translations-fetcher.js";import{loadUiPack as w}from"./lib/i18n.js";import{isActivated as f,activateToken as b,isFreeCommand as k,isDeviceMatch as v,recordExit as x,recordResume as C,isFirstRunOrUpgrade as A,markVersionSeen as $}from"./lib/access.js";import{setReplMode as I}from"./lib/ui.js";import{returnToMainMenu as T,printMenuHint as E,menuHintInline as S,registerRealExit as j}from"./lib/menu-nav.js";import{setMainRl as O}from"./lib/main-rl.js";import{shellSplit as L}from"./lib/shell-split.js";import{isChatActive as N,handleChatMessage as z}from"./commands/ai4ctf.js";import{isMicroduckWord as D}from"./commands/microduck.js";import{renderToolMan as P}from"./lib/tool-man.js";import{isCtf4aiActive as M,handleCtf4aiMessage as F}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as _,handleCtf4VlaMessage as U}from"./commands/ctf4vla.js";import{isDemo2Active as R}from"./commands/demo2.js";import{isSprintActive as q}from"./commands/sprint.js";import{isCardDeckActive as W}from"./lib/card-engine.js";import{hasAnySimHistory as B,lastArmAt as Z,lastBundledAt as Y,lastSimAt as X}from"./lib/sim-cooldown.js";import{getExamState as Q,getRealExamState as H,getDemoState as V,practicalChatCommand as J}from"./lib/exam-state.js";import{resolveResumePoint as G}from"./lib/resume.js";import{buildStatusLine as K}from"./lib/statusline.js";import{startBgTask as oo,startAsyncTask as eo,listBgTasks as to,getBgTask as no,drainCompleted as ao,killAllBgTasks as lo,runningCount as so}from"./lib/bgtasks.js";import{computeStart as ro,renderStart as io}from"./commands/challenge.js";import{addDraft as co,listDrafts as go,removeDraft as mo,clearDrafts as yo}from"./lib/drafts.js";import{resetTerminalTheme as uo}from"./lib/theme.js";import{ensureSandbox as po,runInSandbox as ho,isDockerAvailable as wo}from"./lib/sandbox.js";import{checkShellRisk as fo,logShellAudit as bo,getActiveCwd as ko}from"./lib/exam-sandbox.js";import{logCommand as vo}from"./lib/logger.js";import{startLogSync as xo,stopLogSync as Co}from"./lib/log-sync.js";import{installInputDynamics as Ao,uninstallInputDynamics as $o,stripTerminalMarkers as Io,rearmFocusMode as To}from"./lib/input-dynamics.js";import{startBroadcastPoll as Eo,stopBroadcastPoll as So,showBroadcast as jo,isCompetitionJoined as Oo,isMelCompetition as Lo,isLeaderAccount as No,isLeaderSession as zo,fetchPublicScoreboard as Do,isCommsActive as Po}from"./lib/comms.js";import{enterMemoScreen as Mo,enterJuryScreen as Fo}from"./commands/comms.js";import{examGuidance as _o}from"./commands/exam.js";import{currentSurface as Uo,enterPanel as Ro,isGuideWord as qo,isHelpWord as Wo,leavePanel as Bo,printGuide as Zo,printHelp as Yo}from"./lib/guide-panel.js";import{getDemoStats as Xo}from"./lib/demo-stats.js";import{existsSync as Qo,mkdirSync as Ho,readFileSync as Vo,writeFileSync as Jo}from"node:fs";import{join as Go}from"node:path";import{homedir as Ko}from"node:os";const oe="# 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",ee=Date.now();function te(o){const e=()=>ue(f(),o),t={verb:"menu",what:{en:"back to the start menu",zh:"回到开机选单"}};return"embodied"===o?{id:"root",title:{en:"ctf4eai — Embodied AI Security",zh:"ctf4eai — 具身 AI 安全"},what:{en:"Robots, physics, real attack surfaces. Four free steps, in order; each one is a word you type here.",zh:"机器人、物理、真实攻击面。四个免费步骤按顺序来,每一步就是在这里敲一个词。"},steps:[{verb:"sim",what:{en:"9-robot group dance — instant, no setup",zh:"9 机器人群舞 —— 即开即看"},done:()=>Y()>0||X()>0},{verb:"sim arm",what:{en:"drive a 6-joint arm yourself",zh:"自己驱动 6 关节机械臂"},done:()=>Z()>0},{verb:"demo2",what:{en:"~8 min interactive intro with a live MuJoCo sim",zh:"约 8 分钟互动入门 + 实时 MuJoCo 仿真"}},{verb:"learn LEARNDEMO01",what:{en:"free 11-card intro course (paste as-is)",zh:"免费 11 卡入门课(原样粘贴)"}},{verb:"learn <token>",what:{en:"your full EA course token from your team",zh:"队里发的完整 EA 课程 token"},optional:!0}],leave:t,guide:e}:"organizer"===o?{id:"root",title:{en:"Partner console",zh:"合作方控制台"},what:{en:"Manage exams for your country or region.",zh:"管理你所在国家 / 地区的考试。"},steps:[{verb:"join <url>",what:{en:"connect to the exam server",zh:"连接考试服务器"},done:()=>g()},{verb:"exam list",what:{en:"see the papers available to you",zh:"查看可用考卷"}},{verb:"logout",what:{en:"disconnect",zh:"断开连接"},optional:!0}],leave:t,guide:e}:Lo()||"olympiad"===o&&f()&&g()?{id:"root",title:{en:"Competition",zh:"比赛"},what:{en:"You are signed in to the live competition. Pick a challenge, read it, submit the flag you find.",zh:"已登录正式比赛。挑一道题、读题、提交找到的 flag。"},steps:[{verb:"challenges",what:{en:"list every challenge with its id and points",zh:"列出所有题目(编号 + 分值)"}},{verb:"open 1",what:{en:"read challenge 1 (any id from the list)",zh:"读第 1 题(列表里的任意编号)"}},{verb:"submit 1 ICOA{...}",what:{en:"submit the flag for that challenge",zh:"提交那道题的 flag"}},{verb:"ai4ctf",what:{en:"chat with your AI teammate when stuck",zh:"卡住时和 AI 队友聊"},optional:!0},{verb:"memo",what:{en:"report a problem to the organizers (one-way)",zh:"向组织者报告问题(单向)"},optional:!0},{verb:"scoreboard",what:{en:"live rankings",zh:"实时榜单"},optional:!0}],notes:[{en:"logout = sign out of this account · man <tool> = how to use a CTF tool",zh:"logout = 退出账号 · man <tool> = 某个 CTF 工具怎么用"}],leave:t,guide:e}:"olympiad"===o?f()?{id:"root",title:{en:"Finals tier",zh:"决赛层"},what:{en:"Activated. Connect to the competition server, then solve challenges with your tools and AI teammate.",zh:"已激活。先连接比赛服务器,再用工具和 AI 队友解题。"},steps:[{verb:"env",what:{en:"check your tools (env setup installs what is missing)",zh:"检查工具(env setup 补装缺的)"},optional:!0},{verb:"join <url>",what:{en:"connect to the competition server",zh:"连接比赛服务器"},done:()=>g()},{verb:"challenges",what:{en:"browse and pick a challenge",zh:"浏览并挑一道题"}},{verb:"ai4ctf",what:{en:"chat with your AI teammate when stuck",zh:"卡住时和 AI 队友聊"},optional:!0}],leave:t,guide:e}:{id:"root",title:{en:"Finals tier",zh:"决赛层"},what:{en:"The full sandbox with 90+ CTF tools. It unlocks with your competition token.",zh:"带 90 多个 CTF 工具的完整沙箱,用比赛 token 解锁。"},steps:[{verb:"activate <token>",what:{en:"unlock with the competition token you were given",zh:"用发给你的比赛 token 解锁"}},{verb:"env",what:{en:"see which of the 90+ tools are installed",zh:"看 90 多个工具装了哪些"},optional:!0},{verb:"ref linux",what:{en:"quick reference while you wait",zh:"等待时看速查表"},optional:!0}],leave:t,guide:e}:{id:"root",title:{en:"ICOA",zh:"ICOA"},what:{en:"The icoa> prompt: type one of these words and press Enter. Nothing here needs an account; a token opens the real courses and exams.",zh:"icoa> 提示符:敲下面任一个词回车。这里不需要账号;有 token 才进正式课程和考试。"},steps:[{verb:"demo",what:{en:"10 sample exam questions — no token, no timer",zh:"10 道样题 —— 免 token、无计时"},done:()=>{try{return Xo().attempts>0}catch{return!1}}},{verb:"demo3",what:{en:"olympiad replay — real solutions, step by step",zh:"奥赛回放 —— 真题解法逐步看"}},{verb:"kaggle",what:{en:"ML practice — train a model, real leaderboard",zh:"ML 练习 —— 训模型、上真榜"}},{verb:"learn <token>",what:{en:"open your course with the token from your coach",zh:"用老师给的 token 打开课程"},done:()=>Qo(Go(Ko(),".icoa","learn-state.json"))},{verb:"exam <token>",what:{en:"sit a country exam with your exam token",zh:"用考试 token 进入国家考试"}},{verb:"lang zh",what:{en:"switch the interface language (lang en to go back)",zh:"切换界面语言(lang en 切回英文)"},optional:!0}],leave:t,guide:e}}function ne(){return Lo()?chalk.yellow("icoa 2026> "):H()?chalk.cyan("icoa exam> "):function(){const o=V();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=ee}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const ae=Go(Ko(),"icoa-workspace"),le=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),se="__REPL_NO_EXIT__",re="2.5.1",ie=i();export function nearestCommand(o,e=2){const t=o.trim().toLowerCase();if(!t)return null;let n={word:"",dist:Number.POSITIVE_INFINITY};for(const o of ie){const e=c(t,o);e<n.dist&&(n={word:o,dist:e})}return n.dist>0&&n.dist<=e?n.word:null}const ce=new Set(["answer","demo","demo-retry","help","list","mark","more-help","nations","next","prev","q","reset","result","review","setup","start","submit","token","unmark","status","time"]);function ge(o){const e=o.replace(/^\s+/,"");if(/^\/\S*$/.test(e)){const o=e.slice(1).toLowerCase();return[ie.filter(e=>e.startsWith(o)).map(o=>`/${o}`),e]}const t=e.split(/\s+/);if(t.length<=1){const o=(t[0]??"").toLowerCase();return[ie.filter(e=>e.startsWith(o)).slice(),o]}if(2===t.length){const o=r(t[0].toLowerCase());if(o){const e=t[1].toLowerCase();return[o.filter(o=>o.startsWith(e)).slice(),e]}}return[[],o]}async function me(o){const e=G();if(!e)return null;const t=process.exit;process.exit=()=>{throw new Error(se)};try{await o.parseAsync(["node","icoa",...e.command])}catch(o){if(!(o instanceof Error&&o.message===se))throw o}finally{process.exit=t}return e}function de(){console.log(),console.log(` ${chalk.cyan.bold("🎯 ICOA · 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.white("DUxxxxxxxx")+chalk.gray(" → Duck Cup (type the token from your seat card)")),console.log(" "+chalk.white("BAxxxxxxxx")+chalk.gray(" → BattleAI Cup (your BattleAI 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"));try{console.log(),console.log(y(u(),"T0"===p().tier))}catch{}console.log()}export async function startRepl(e,l){process.env.ICOA_INSIDE_REPL="1";let s=!1;if(Lo()){const o=m().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)||(d({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:"",joinedAt:""}),s=!0)}const r=m(),i=g(),c=process.exit.bind(process);j(c);const y=f();if(r.language&&"en"!==r.language&&(await h(r.language,{silent:!0}),w(r.language)),r.demoCleanedForVersion!==re){try{const{existsSync:o,unlinkSync:e}=await import("node:fs"),{join:t}=await import("node:path"),{getIcoaDir:n}=await import("./lib/config.js"),a=t(n(),"demo-state.json");o(a)&&e(a)}catch{}d({demoCleanedForVersion:re})}const{default:u}=await import("@inquirer/select"),{default:p}=await import("@inquirer/confirm"),L=r.mode||"",V=""===L?"instant":"selection"===L?"learn":["instant","learn","olympiad"].includes(L)?L:"learn",To=[{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("team token · skill up")}`,value:"learn"},{name:` ${chalk.bold("🎯 National Selection")} ${chalk.gray("—")} ${chalk.gray("country exam token · aim for finals")}`,value:"selection"},{name:` ${chalk.bold("🏆 International Olympiad")} ${chalk.gray("—")} ${chalk.gray("finals stage · full sandbox")}`,value:"olympiad"},{name:` ${chalk.gray("ℹ️ About ICOA")} ${chalk.gray("·")} ${chalk.gray("what this is · how to join")}`,value:"about"}];""===L&&(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("help")+chalk.gray(" at any prompt for guidance · ")+chalk.bold.cyan("menu")+chalk.gray(" from anywhere to return here.")),console.log();let Xo="";for(;!Xo;){let o;const e=process.env.ICOA_TEST_BOOT_MODE;if(e&&["instant","learn","selection","olympiad"].includes(e))o=e;else try{o=await u({message:"Mode",choices:To,default:V||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}if("about"!==o)Xo=o;else{console.clear(),console.log(),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(chalk.bold.yellow(" ICOA")+chalk.white(" — AI-Native CLI OS for Cyber & AI Security")),console.log(chalk.gray(" Olympiad & Competition · K-12 to University")),console.log(chalk.cyan(" ───────────────────────────────────────────────────")),console.log(),console.log(chalk.bold.white(" What Makes ICOA Different")),console.log(chalk.gray(" · AI-native AI teammate, AI adversary, AI translation")),console.log(chalk.gray(" · CLI OS Complete competition environment in terminal")),console.log(chalk.gray(" · 100 tools z3, radare2, nmap, sleuthkit, tshark... pre-configured")),console.log(chalk.gray(" · Global scale 15,000+ concurrent exams · 20+ languages")),console.log(),console.log(chalk.bold.white(" Three Frontiers of AI Security")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" AI as teammate — 5 CTF disciplines, 5-hour endurance round")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" AI as target — the AI system itself is the objective")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" Embodied-AI Arena — probe robot policies in live simulation")}`),console.log(),console.log(chalk.bold.white(" First Edition — Sydney 2026 ")+chalk.green.bold("✓ held")),console.log(chalk.gray(" · Jun 27 - Jul 2, 2026 · University of Technology Sydney")),console.log(chalk.gray(" · 65 competitors · 20 countries & regions (10 on-site, 10 remote)")),console.log(chalk.gray(" · 36 awards — 6 Gold · 11 Silver · 17 Bronze · 2 Honorable Mentions")),console.log(chalk.gray(" · Champion: Oleg Uteshev · Embodied-AI Arena Gold: Kingsley Lim (AU)")),console.log(chalk.gray(" · Founding Charter signed — ICOA is now a permanent institution")),console.log(),console.log(chalk.bold.white(" Next: ICOA 2027")+chalk.gray(" — 20 more countries already accredited")),console.log(),console.log(chalk.bold.white(" Organized by")+chalk.gray(" ASRA (Australia) · ICO Foundation Inc")),console.log(chalk.bold.white(" Contact ")+chalk.cyan(" australia@icoa2026.au · accreditation@icoa2026.au")),console.log(chalk.bold.white(" Website ")+chalk.cyan.underline(" https://icoa2026.au")+chalk.gray(" · press: ")+chalk.cyan.underline("https://icoa2026.au/press/")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log();try{const{default:o}=await import("@inquirer/input"),e=()=>o({message:chalk.gray("Press Enter to return..."),theme:{prefix:"",style:{message:o=>o}}}),t=Date.now();let n=await e();Date.now()-t<200&&(n=await e());const a=n.trim().toLowerCase();if("config"===a||"wizard"===a){const{runSetupWizard:o}=await import("./commands/setup.js");await o(),await e()}else if("setup"===a||"/setup"===a){const{runSetupVerb:o}=await import("./commands/setup.js");await o(""),await e()}}catch{}console.clear()}}if("olympiad"===Xo&&"olympiad"!==V){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await p({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(Xo="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(Xo!==V&&d({mode:Xo}),console.log(),"olympiad"===Xo&&A(re)){$(re),console.log(chalk.gray(" Checking competition environment..."));const{execSync:o}=await import("node:child_process"),e=[{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(l){const o=C();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"===Xo)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),de();else if("embodied"===Xo)!function(){console.log(chalk.cyan.bold(" [🤖 ctf4eai — Embodied AI Security]")),console.log(),console.log(chalk.bold.cyan(" CTF4EAI")+chalk.gray(" — ICOA's ")+chalk.bold.white("Pioneer Round")),console.log(chalk.gray(" an independent parallel track alongside the scored main events: ")+chalk.green("AI4CTF")+chalk.gray(" and ")+chalk.red("CTF4AI")),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=Y()>0||X()>0,e=Z()>0,t=B();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(),E(),console.log()}();else if("instant"===Xo)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Four free demos — type one and press Enter:")),console.log(),console.log(chalk.bold.green(" demo ")+chalk.gray(" Paper A/B/C sample — 10 MCQs, no timer ")+chalk.bold.cyan("🎯 selection-style")),console.log(chalk.bold.green(" demo2 ")+chalk.gray(" Embodied-AI mini-demo — robots & MuJoCo ")+chalk.bold.yellow("🤖 hands-on")),console.log(chalk.bold.green(" demo3 ")+chalk.gray(" Olympiad replay — 6 real AIO solutions ")+chalk.bold.green("⚔ step by step")),console.log(chalk.bold.green(" kaggle")+chalk.gray(" ML practice — train a model, real board ")+chalk.bold.magenta("📊 data-science")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(", ")+chalk.bold.cyan("demo2")+chalk.gray(", ")+chalk.bold.cyan("demo3")+chalk.gray(" or ")+chalk.bold.cyan("kaggle")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),d({mode:"selection"}),Xo="selection";else{if("learn"===Xo){console.log(chalk.cyan.bold(" [🧠 Learn]")),console.log();const o=await(async()=>{try{const o=await import("./lib/learn-state.js");try{const{fetchProfilesForLocalTokens:e}=await import("./lib/learn-door.js"),t=await e(o.listLearnSessions().map(o=>o.token),{staleOk:!0});for(const e of t)o.adoptLinkedSessions(e.tokens)}catch{}return{sessions:o.listLearnSessions(),listMax:o.CONTINUE_LIST_MAX}}catch{return{sessions:[],listMax:5}}})(),t=o.sessions,a=o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o)?`${o.slice(0,2)}••••••${o.slice(-2)}`:o,l=o=>{const e=new Date(o);if(Number.isNaN(e.getTime()))return"";const t=o=>new Date(o.getFullYear(),o.getMonth(),o.getDate()).getTime(),n=Math.round((t(new Date)-t(e))/864e5);return n<0?"":0===n?"today":1===n?"yesterday":n<30?`${n} days ago`:"a while back"},s=e=>{const n=e?t:t.slice(0,o.listMax),s=o=>Math.max(...n.map(e=>o(e).length)),r=s(o=>o.curriculumId),i=s(o=>`card ${o.currentCard}/${o.totalCards}`),c=s(o=>l(o.lastSeenAt));return n.forEach((o,e)=>{const t=o.token===o.curriculumId?"":` ${a(o.token)}`;console.log(chalk.green(` ${e+1} `)+chalk.bold.white(o.curriculumId.padEnd(r))+chalk.yellow(` ${`card ${o.currentCard}/${o.totalCards}`.padEnd(i)}`)+chalk.gray(` ${l(o.lastSeenAt).padEnd(c)}${t}`))}),n.length};if(1===t.length){const o=t[0],e=l(o.lastSeenAt);console.log(chalk.green(" ▸ Continue ")+chalk.bold.white(o.curriculumId)+chalk.gray(" · ")+chalk.yellow(`card ${o.currentCard}/${o.totalCards}`)+chalk.gray(`${e?` · ${e}`:""} · ${a(o.token)}`)),console.log(chalk.gray(" type ")+chalk.bold.green("c")+chalk.gray(" or ")+chalk.bold.green("continue")+chalk.gray(" to resume · Enter to go back")),console.log()}else if(t.length>1){console.log(chalk.green(" ▸ Continue"));const o=s(!1);t.length>o&&console.log(chalk.gray(` +${t.length-o} more — type `)+chalk.bold.green("c all")+chalk.gray(" to list them")),console.log(chalk.gray(" type ")+chalk.bold.green("c")+chalk.gray(" to resume 1 · ")+chalk.bold.green("c 2")+chalk.gray(" to switch · Enter to go back")),console.log()}{const{doorStoryLines:o,doorWelcomeLines:e,fetchProfilesForLocalTokens:n}=await import("./lib/learn-door.js"),{learnW:a}=await import("./lib/learn-render.js");let l=null;if(t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token))){const s=await n(t.map(o=>o.token),{staleOk:!0}),r=s[0]??null,i=new Set(s.flatMap(o=>o.tokens.filter(o=>o.credits?.completed).map(o=>o.curriculum_id))).size;l=r?o(r,a(),i):e(a(),!0)}else l=e(a(),!1);for(const o of l)console.log(o);try{const{pythonDoorLine:o}=await import("./lib/python-setup.js"),{detectCaps:e}=await import("./lib/render-card.js"),t=(m().language||"en").toLowerCase().startsWith("zh");console.log(o(t,"T0"===e().tier))}catch{}console.log()}try{const{default:o}=await import("@inquirer/input"),{resolveLearnInput:n}=await import("./lib/learn-input.js"),a={id:"learn-door",title:{en:"Learn — your course token",zh:"Learn —— 课程 token"},what:{en:"Paste the 10-character token your coach gave you and the course opens right here. Nothing to install first.",zh:"把老师发给你的 10 位 token 粘贴进来,课程就在这里打开。不用先安装任何东西。"},steps:[...t.length>0?[{verb:"c",what:{en:"continue the course you opened last time (c 2 = the second one)",zh:"继续上次打开的课程(c 2 = 第二门)"}}]:[],{verb:"<your token>",what:{en:"paste the 10 letters/digits from your coach and press Enter (O/0 and I/1 mix-ups are fixed for you)",zh:"粘贴老师给的 10 位字母数字后回车(O/0、I/1 混淆会自动纠正)"},done:()=>t.length>0}],notes:[{en:"No token yet? Ask your coach. Also answered here: me · story · certificate · python setup",zh:"还没有 token?问老师。这里还能敲:me · story · certificate · python setup"}],leave:{verb:"Enter",what:{en:"an empty line goes back to the menu",zh:"空行回到选单"}}};Ro(a);const l=async()=>{try{await o({message:chalk.bold.yellow("Press Enter to return to the menu"),theme:{prefix:"",style:{message:o=>o}}})}catch{}},r=3;let i=null,c=null;for(let a=1;a<=r;a++){const g=await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}),m=g.trim().toLowerCase();if(Wo(m)||qo(m)){Yo(),a--;continue}if("ai4ioai"===m||"/ai4ioai"===m){const{runAi4ioaiStandalone:o}=await import("./commands/ai4ioai.js");return await o(),await l(),d({mode:"selection"}),void T()}if(D(g)){const{runMicroduck:o}=await import("./commands/microduck.js");return await o(),await l(),d({mode:"selection"}),void T()}if(["pandahelpme31","/pandahelpme31","panda help me 31","pandahelpme"].includes(m)){const{runSprint:o}=await import("./commands/sprint.js");return await o(),d({mode:"selection"}),void T()}if("wm"===m||"/wm"===m||m.startsWith("wm ")){const{runWm:o}=await import("./commands/wm.js");return await o(g.trim().split(/\s+/).slice(1).join(" ")||void 0),d({mode:"selection"}),void T()}if("ioailab"===m||"/ioailab"===m){const{runIoailabStandalone:o}=await import("./commands/ioailab.js");return await o(),await l(),d({mode:"selection"}),void T()}if("me"===m||"/me"===m||"profile"===m||"/profile"===m){const o=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));if(o){const{fetchLearnProfile:e,renderLearnProfile:t}=await import("./lib/learn-profile.js"),{learnW:n}=await import("./lib/learn-render.js");console.log(chalk.gray(` Loading your profile (${o.token.slice(0,2)}••••••${o.token.slice(-2)})…`));const a=await e(o.token);"ok"===a.kind?t(a.profile,!1,n(),"prompt"):"offline"===a.kind?console.log(chalk.yellow(" Cannot reach the learn server — try me again online.")):console.log(chalk.yellow(` ${"demo"===a.kind?"No profile for a demo token":a.message}`)),console.log()}else console.log(),console.log(chalk.yellow(" No profile yet — open a course with your token first, then type me.")),console.log();a--;continue}const y=m.match(/^\/?setup(?:\s+(\S.*))?$/);if(y){const{runSetupVerb:o}=await import("./commands/setup.js");await o(y[1]??"",{inLearn:!0}),a--;continue}const u=m.match(/^\/?python(?:3)?(?:\s+(setup|install|status))?$/);if(u){const{runSetup:o,printStatus:e}=await import("./commands/python.js");"setup"===u[1]||"install"===u[1]?await o():e(),a--;continue}if(/^\/?(upgrade|update)$/.test(m)){const{runUpgrade:o}=await import("./lib/update-check.js");if("upgraded"===await o({ask:!1}))return console.log(chalk.gray(" restarting icoa …")),void T();a--;continue}const p=m.match(/^\/?m[ou]joco(?:\s+(setup|install|status))?$/);if(p){const{runMujocoSetup:o,printMujocoStatus:e}=await import("./commands/mujoco.js");"setup"===p[1]||"install"===p[1]?await o():e(),a--;continue}const h=m.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(h){const{certificateLines:e,dropProfileCache:n}=await import("./lib/learn-door.js"),{certifiable:l,certificateIntroLines:s,sameName:r,issueCertificate:i,announceCertificate:c}=await import("./lib/learn-certificate.js"),{fetchProfilesForLocalTokens:g}=await import("./lib/learn-door.js"),m=await g(t.map(o=>o.token)),d=m[0]??null,y=new Set,u=m.flatMap(o=>l(o)).filter(o=>!y.has(o.curriculum_id)&&y.add(o.curriculum_id)),p=(h[2]??"").toLowerCase();console.log();const w=p?u.find(o=>o.curriculum_id.toLowerCase()===p||o.curriculum_id.toLowerCase().startsWith(p)):1===u.length?u[0]:void 0;if(0===u.length||!w&&!p){for(const o of e(d,!1))console.log(o);u.length>1&&console.log(chalk.gray(" type ")+chalk.bold.green("certificate <track>")+chalk.gray(" to issue one.")),console.log(),a--;continue}if(!w){console.log(chalk.yellow(` No finished track matches "${p}". `)+chalk.gray("Finished: "+u.map(o=>o.curriculum_id).join(", "))),console.log(),a--;continue}for(const o of s(w,!1))console.log(o);console.log();const f=async e=>(await o({message:chalk.bold.cyan(e),theme:{prefix:"",style:{message:o=>o}}})).trim(),b=await f("Name on the certificate:");if(!b){console.log(chalk.gray(" Cancelled — nothing issued.")),console.log(),a--;continue}if(!r(b,await f("Type it once more:"))){console.log(chalk.yellow(" The two names differ — nothing issued. Type certificate to try again.")),console.log(),a--;continue}console.log(chalk.gray(" Issuing… (the name is sent once, never stored)")),c(await i(w.token,w.curriculum_id,b),!1),n(),a--;continue}const w=m.match(/^\/?(story|credits)(?:\s+(\S+))?$/);if(w){const{fetchLearnProfile:o}=await import("./lib/learn-profile.js"),{buildCreditLines:e,rollCredits:n,storyListLines:l}=await import("./lib/learn-credits.js"),{learnW:s}=await import("./lib/learn-render.js"),r=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));if(console.log(),r){const a=await o(r.token,"credits"===w[1]?"credits":"story");if("ok"!==a.kind)console.log(chalk.yellow(" Cannot reach the learn server — try story again online."));else{const o=(w[2]??"").toLowerCase(),r=a.profile;let i;if(o){const e=Number(o);i=Number.isInteger(e)&&e>=1&&e<=r.tokens.length?r.tokens[e-1]:r.tokens.find(e=>e.curriculum_id.toLowerCase()===o||e.curriculum_id.toLowerCase().startsWith(o))}else"credits"===w[1]&&(i=r.tokens.find(o=>o.credits?.completed));if(i){if(await n(e(i,r,i.curriculum_id,{},!1,s(),!1),()=>!1,180),i.credits?.completed&&!i.credits.credits_rolled_at){const{postCreditsRolled:o}=await import("./lib/learn-profile.js");o(i.token,i.curriculum_id)}}else{o&&console.log(chalk.yellow(` No story for "${o}".`));for(const o of l(r,!1))console.log(o);const e=new Set(r.tokens.map(o=>o.token.toUpperCase())),n=t.filter(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token)&&!e.has(o.token.toUpperCase()));n.length>0&&console.log(chalk.gray(` +${n.length} more course${1===n.length?"":"s"} on this computer not linked yet — open one and type `)+chalk.bold.green("link")+chalk.gray(" to join them."))}}}else console.log(chalk.yellow(" No story yet — open a course with your token first."));console.log(),a--;continue}{const{TEAM_RE:e,runTeamMeeting:n}=await import("./lib/learn-team.js");if(e.test(m)){const e=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));if(console.log(),e){const t=async e=>{try{return(await o({message:e,theme:{prefix:"",style:{message:o=>o}}})).trim()}catch{return null}};await n(e.token,t),console.log()}else console.log(chalk.yellow(" Team meeting needs your FTC course token — open the course with it first, then type teammeeting.")),console.log();a--;continue}}{const{CHECK_RE:o,runLearnCheck:e}=await import("./lib/learn-check.js"),n=m.match(o);if(n){const o=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));console.log(),o?(await e(o.token,n[1]??""),console.log()):(console.log(chalk.yellow(" check needs your own course token — open a course with it first, then type check <TOKEN>.")),console.log()),a--;continue}}{const{CLASS_RE:o,runLearnClass:e}=await import("./lib/learn-class.js"),n=m.match(o);if(n){const o=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));console.log(),o?(await e(o.token,n[1]??""),console.log()):(console.log(chalk.yellow(" class needs your own course token — open a course with it first, then type class.")),console.log()),a--;continue}}const{FOCUS_LOG_RE:f,fetchFocusLog:b,renderFocusLog:k}=await import("./lib/learn-focus-log.js");if(f.test(m)){const o=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));if(console.log(),o){const{detectCaps:e}=await import("./lib/render-card.js"),t=await b(o.token);if("ok"===t.kind)for(const o of k(t.log,!1,"T0"===e().tier,"Enter to go back"))console.log(o);else console.log(chalk.yellow("offline"===t.kind?" Offline — the focus log lives on the server; try again when connected.":"demo"===t.kind?" Demo tokens are shared — no focus log. Use your own token.":` Could not load the focus log: ${t.message}`));console.log()}else console.log(chalk.yellow(" No focus log yet — open a course with your token first, then type focus log.")),console.log();a--;continue}const v=m.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(v){const{FOCUS_MAX:o,FOCUS_MIN:e,FOCUS_STEP:t,getStudyTimer:n,parseFocusMinutes:l}=await import("./lib/learn-study-timer.js"),s=n(),r=(v[2]??"").trim();if(console.log(),s.showPending());else if("off"===r||"stop"===r||"end"===r||"cancel"===r)s.stop()?(await new Promise(o=>setTimeout(o,300)),s.showPending()):console.log(chalk.gray(" No focus session running. Start one: ")+chalk.bold.green("focus 30"));else if(s.active)console.log(chalk.yellow(" ⏱ ")+chalk.white(`focus running · ${s.remainingMin()} min left`)+chalk.gray(" · paste a token and keep going, or ")+chalk.bold.green("focus off"));else if(""===r||"?"===r||"help"===r)console.log(chalk.bold.white(" ⏱ Focus session")),console.log(chalk.gray(` How long? (${e}–${o}, steps of ${t}) e.g. `)+chalk.bold.green("focus 30")),console.log(chalk.gray(" Start it here, then open any course — every course you visit counts."));else{const n=l(r);if(n){if("ok"!==n.note){const a="min"===n.note?`min is ${e}`:"max"===n.note?`max is ${o}`:`rounded to the nearest ${t}`;console.log(chalk.gray(` you typed ${r} → ${a}, using ${n.min}`))}s.start(n.min),console.log(chalk.yellow(" ⏱ ")+chalk.bold.white(`Focus ${n.min} min — go`)+chalk.gray(" · now paste your token (any course counts) · soft reminder every 10 min · end early: ")+chalk.bold.green("focus off"))}else console.log(chalk.yellow(` Didn't understand "${r}". `)+chalk.gray("Type minutes, e.g. ")+chalk.bold.green("focus 30"))}console.log(),a--;continue}if(/^(doctor|\/doctor)$/i.test(g.trim())){const{runDoctor:o}=await import("./commands/doctor.js");await o(),console.log(),console.log(chalk.gray(" Paste your token to try again, or press Enter to go back.")),console.log(),a--;continue}if(/^\/?move$/.test(m)){if(a--,!i){console.log(),console.log(chalk.gray(" move brings your courses to this computer. Type one of your tokens first —")+chalk.gray(" if it says it is bound to another computer, type ")+chalk.bold.green("move")+chalk.gray(".")),console.log();continue}const{runMove:e}=await import("./lib/learn-move.js"),t=await e(i,e=>o({message:chalk.gray(e.trimStart()),theme:{prefix:" ",style:{message:o=>o}}}));if(console.log(),!t)continue;c=i,i=null}let x=n(c??g);if(c=null,"back"===x.kind)break;if("continue"===x.kind){if(0===t.length){if(console.log(),console.log(chalk.yellow(" Nothing to continue — no previous session on this computer.")),console.log(chalk.gray(" Paste your cohort token to start.")),console.log(),a===r){await l();break}continue}const{which:o}=x;let e=t[0];if("all"===o){console.log(),s(!0),console.log(),a-=1;continue}if("number"==typeof o){if(o<1||o>t.length){if(console.log(),console.log(chalk.yellow(` You have ${t.length} course${t.length>1?"s":""} in progress — pick 1${t.length>1?`-${t.length}`:""}, or type part of its name.`)),console.log(),a===r){await l();break}continue}e=t[o-1]}else if("string"==typeof o){const n=t.filter(e=>e.curriculumId.toLowerCase().includes(o)||e.token.toLowerCase().includes(o));if(1!==n.length){if(console.log(),console.log(chalk.yellow(0===n.length?` No course in progress matches "${o}".`:` "${o}" matches ${n.length} of your courses — be more specific, or use its number.`)),console.log(),s(!0),console.log(),a===r){await l();break}continue}e=n[0]}x={kind:"token",token:e.token}}if("ambiguous"===x.kind||"unknown"===x.kind){if(console.log(),console.log(chalk.yellow(` ${x.hint}`)),console.log(),a===r){console.log(chalk.gray(` That was attempt ${r} of ${r} — going back to the menu.`)),console.log(chalk.gray(" Your token comes from your country team leader.")),console.log(),await l();break}continue}if(x.from){const{loadCurriculumById:o}=await import("./lib/learn-curricula.js");if(!await o(x.token,x.token)){if(console.log(),console.log(chalk.yellow(` "${x.from}" is not a token.`)),console.log(chalk.gray(" Paste the token your team leader gave you (2 letters + 8 characters).")),console.log(),a===r){await l();break}continue}}if(!/^[A-Z0-9]+DEMO01$/i.test(x.token)&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(x.token)){console.log(),console.log(chalk.gray(" Checking token…"));const{validateEAToken:o}=await import("./lib/learn-curricula.js");let e=await o(x.token);if(!e.ok){const{normalizeTokenBody:t}=await import("./lib/token-format.js"),n=t(x.token);if(n!==x.token.trim().toUpperCase()){const t=await o(n);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${x.token} → ${n}`)),e=t,x={...x,token:n})}}if(!e.ok){if(console.log(),console.log(chalk.red(` ✗ Token check failed: ${e.message||"validation failed"}`)+(e.code?chalk.gray(` [${e.code}]`):"")),"device_bound"===e.code)i=x.token,console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.white(" 🧭 New or reinstalled computer? Type ")+chalk.bold.green("move")+chalk.white(" — all your courses come here, progress kept."));else if("expired"===e.code)console.log(chalk.gray(" This learn token has expired — ask your coordinator for a new one."));else if("network"===e.code){console.log(chalk.yellow(" Your token was not checked — this computer could not reach the ICOA server.")),console.log(chalk.gray(" (Your browser opening Google or practice.icoa2026.au does not count: icoa")),console.log(chalk.gray(" connects on its own, without the browser, and can be blocked separately.)")),console.log();for(const o of e.advice??[])console.log(chalk.gray(` ${o}`));(e.advice?.length??0)>0&&console.log(),console.log(chalk.gray(" ▸ Type ")+chalk.cyan("doctor")+chalk.gray(" right here — it names the exact fault and the fix.")),console.log(chalk.gray(" If it does not, send its output to your coordinator."))}else console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)")),console.log(chalk.gray(" · Token expired or revoked"));if(console.log(),a<r){console.log(chalk.gray(" Try again — or press Enter to go back.")),console.log();continue}await l();break}}console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${x.token}`)),console.log(),d({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";const{setLearnSessionStarted:C}=await import("./lib/learn-outcome.js");C(!1);try{await e.parseAsync(["node","icoa","learn",x.token])}catch(o){console.log(),console.log(chalk.red(` ✗ learn failed to start: ${o instanceof Error?o.message:String(o)}`)),console.log()}finally{delete process.env.ICOA_LEARN_EMBEDDED}await l();break}}catch(o){n("learn-token-prompt-cancel",o instanceof Error?`${o.name}: ${o.message}`:String(o))}return Bo("learn-door"),d({mode:"selection"}),void T()}"organizer"===Xo?(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")),console.log(chalk.bold.magenta(" The World's First AI-Native CLI Operating System")),console.log(chalk.bold.magenta(" for K-12 AI & Cyber Olympiads and International AI Hackathons")),console.log(chalk.gray(" ICOA 2026: Sydney, Australia · ICOA 2027: July 2027")),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(),i?(console.log(chalk.green(` Logged in as ${r.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(),E(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),y&&!v()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):i?(console.log(chalk.green.bold(` Welcome back, ${r.userName}!`)),console.log(chalk.gray(` Connected to ${r.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 90+ 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(" · ")+S()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):y?(Qo(ae)||Ho(ae,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${ae}`)),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 90+ 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 · ")+S()+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 · 90+ CTF tools · 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 90+ 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 · ")+S()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}const ee=o=>{o.exitOverride(),o.configureOutput({writeErr:o=>{const e=o.replace(/^error:\s*/i,"").trim();e&&console.log(chalk.yellow(` ${e}`))},writeOut:o=>{console.log(o)}});for(const e of o.commands)ee(e)};ee(e);const pe=o({input:process.stdin,output:process.stdout,prompt:ne(),terminal:!0,completer:ge});O(pe),Ao(!1!==m().bracketedPaste);let he=!1;if(I(!0),xo(),s&&(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()),Lo()){const o=m().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=>{pe.question(chalk.white(" > "),e=>o(e.trim()))})).toLowerCase()&&(d({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()}Oo()&&Eo(()=>pe.prompt());let we=null;const fe=pe.prompt.bind(pe);pe.prompt=o=>{if(!(N()||M()||_()||R()||W()||Po()||q()||(pe.setPrompt(ne()),o)))try{for(const o of ao()){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=K();o&&o!==we?(console.log(o),we=o):o||(we=null)}catch{}fe(o)};const be=G();be&&(console.log(chalk.cyan(" ↻ Continue where you left off: ")+chalk.white(be.label)+(be.urgent?chalk.yellow(" (exam timer running)"):"")),console.log(chalk.gray(" type ")+chalk.cyan("resume")+chalk.gray(" to jump back in.")),console.log()),Ro(te(Xo)),pe.prompt(),pe.on("line",async o=>{if(he)return;let n=Io(o.trim());if(!n)return pe.setPrompt(N()?chalk.magenta("icoa ai4ctf> "):ne()),void pe.prompt();if(/^icoa\s+\S/i.test(n)&&(n=n.replace(/^icoa\s+/i,"")),n.startsWith("/")&&!n.startsWith("//")){const o=n.slice(1).split(/\s+/)[0].toLowerCase(),t=n.slice(1+o.length).trim();if("ai"===o)return he=!0,await async function(o,e){if(N())return void(o?await z(o):console.log(chalk.gray(" You are already in the AI chat — just type your message.")));if(M())return void(o?await F(o):console.log(chalk.gray(" You are already in the CTF4AI target chat — just type your message.")));if(_())return void(o?await U(o):console.log(chalk.gray(" You are already in the Embodied-AI chat — just type your message.")));vo(o?`/ai ${o}`:"/ai");const t=process.exit;process.exit=()=>{throw new Error(se)};try{await e.parseAsync(["node","icoa","ai4ctf"])}catch(o){if(!(o instanceof Error&&o.message===se))throw o}finally{process.exit=t}o&&N()&&await z(o)}(t,e),he=!1,pe.setPrompt(N()?chalk.magenta("icoa ai4ctf> "):ne()),void pe.prompt();const a=N()||M()||_()||R()||W()||Po();a||"help"!==o&&"?"!==o||t?!a&&ie.includes(o)&&(n=n.slice(1)):n="?"}if("resume"===n.toLowerCase()){const o=G();return o?(vo(`resume → ${o.command.join(" ")}`),he=!0,await me(e),he=!1,pe.setPrompt(N()?chalk.magenta("icoa ai4ctf> "):ne()),void pe.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(" (free demo).")),console.log(),void pe.prompt())}const l=N()||M()||_()||R()||W();if(!l&&("bg"===n.toLowerCase()||/^bg\s/i.test(n))){const o=n.replace(/^bg\s*/i,"").trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("bg <command>")+chalk.gray(" — run a non-interactive shell command in the background.")),console.log(chalk.gray(" e.g. ")+chalk.cyan("bg nmap -p- 10.0.0.5")+chalk.gray(" · view: ")+chalk.cyan("tasks")),console.log(),void pe.prompt();const e=ko(),t=fo(o);bo({cwd:e,input:`bg ${o}`,riskFlags:t}),t.length>0&&H()&&console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`));const a=oo(o,e);return console.log(),console.log(chalk.cyan(` ▸ background task #${a.id} started`)+chalk.gray(` (${so()} running)`)),console.log(chalk.gray(" ")+chalk.white(o)),console.log(chalk.gray(" view: ")+chalk.cyan("tasks")+chalk.gray(" · output: ")+chalk.cyan(`tasks ${a.id}`)),console.log(),void pe.prompt()}if(!l&&("tasks"===n.toLowerCase()||/^tasks\s/i.test(n))){const o=n.replace(/^tasks\s*/i,"").trim(),e=to();if(console.log(),o){const e=no(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),a=o.cmd.length>48?`${o.cmd.slice(0,45)}…`:o.cmd;console.log(` ${e} `+chalk.white(`#${o.id}`)+chalk.gray(` ${n} `)+chalk.white(a))}console.log(chalk.gray(" output: ")+chalk.cyan("tasks <id>"))}return console.log(),void pe.prompt()}if(!l&&/&\s*$/.test(n)&&/^challenge\s+start\s+/i.test(n)){const o=n.replace(/\s*&\s*$/,"").trim().replace(/^challenge\s+start\s+/i,"").trim().split(/\s+/),e=o.some(o=>"-n"===o||"--new"===o),t=o.find(o=>"-n"!==o&&"--new"!==o);if(!t)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("challenge start <id> &")),console.log(),void pe.prompt();if(!g())return console.log(),console.log(chalk.red(" Not connected. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" first.")),console.log(),void pe.prompt();vo(`challenge start ${t}${e?" --new":""} & (background)`);const a=eo(`challenge start ${t}`,()=>ro(t,e),o=>io(t,o));return console.log(),console.log(chalk.cyan(` ▸ background task #${a.id}: `)+chalk.white(`starting ${t}`)+chalk.gray(" — you can keep working; the connection info appears here when it is ready.")),console.log(),void pe.prompt()}if(!l&&n.startsWith("#")){const o=n.slice(1).trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("#<candidate answer>")+chalk.gray(" — stage a flag/answer WITHOUT submitting it. Review with ")+chalk.cyan("drafts")+chalk.gray(".")),console.log(),void pe.prompt();const e=Q(),t=e?.session?.examId??null,a=e?e._lastQ||1:null,l=co(o,t,a);return vo(`draft #${l.id} (not submitted)`),console.log(),console.log(chalk.green(` ✎ draft #${l.id} saved`)+(a?chalk.gray(` (Q${a})`):"")+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 pe.prompt()}if(!l&&("drafts"===n.toLowerCase()||/^drafts\s/i.test(n))){const o=n.replace(/^drafts\s*/i,"").trim().toLowerCase();if("clear"===o){const o=yo();return console.log(),console.log(chalk.gray(` Cleared ${o} draft${1===o?"":"s"}.`)),console.log(),void pe.prompt()}const e=o.match(/^(?:rm|remove|del|delete)\s+(\d+)$/);if(e){const o=mo(Number(e[1]));return console.log(),console.log(o?chalk.gray(` Removed draft #${e[1]}.`):chalk.yellow(` No draft #${e[1]}.`)),console.log(),void pe.prompt()}const t=Q(),a=go(t?.session?.examId??null);if(console.log(),0===a.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 a){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 pe.prompt()}if("menu"===n||"menu confirm"===n)return H()&&"menu confirm"!==n?(console.log(),console.log(chalk.yellow(" Real exam active. Progress is auto-saved.")),console.log(chalk.gray(" To return to main menu anyway, type ")+chalk.white("menu confirm")),console.log(),void pe.prompt()):void T(pe);if(N()){he=!0;const o=await z(n);return he=!1,"exit"===o&&pe.setPrompt(ne()),void pe.prompt()}if(M()){he=!0;const o=await F(n);return he=!1,"exit"!==o&&"solved"!==o||pe.setPrompt(ne()),void pe.prompt()}if(_()){he=!0;const o=await U(n);return he=!1,"exit"===o&&pe.setPrompt(ne()),pe.setPrompt(_()?chalk.bold.cyan("icoa ctf4eai> "):ne()),void pe.prompt()}if(vo(n),"exit"===n)return Q()?(console.log(),console.log(chalk.yellow(" ⚠ An exam is in progress.")),console.log(chalk.white(" To return to menu without losing progress, type: ")+chalk.bold.cyan("back")),console.log(chalk.white(" To fully close ICOA CLI, type: ")+chalk.bold.cyan("quit")),console.log(chalk.gray(" Your progress is auto-saved either way.")),console.log(),void pe.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"===Xo&&de(),void pe.prompt());if("quit"===n||"q"===n||"quit confirm"===n){const o=Q();return o&&"demo-free"!==o.session.examId&&"quit confirm"!==n?(console.log(),console.log(chalk.yellow(" ⚠ A real exam is in progress.")),console.log(chalk.gray(" Your answers are auto-saved on the server, but the exam timer keeps ticking")),console.log(chalk.gray(" on the server side even if you close the CLI.")),console.log(),console.log(chalk.white(" To leave the CLI but keep the exam alive, type: ")+chalk.bold.cyan("back")),console.log(chalk.gray(" (recommended — you can resume with ")+chalk.cyan("exam q 1")+chalk.gray(" after relaunching icoa)")),console.log(),console.log(chalk.white(" To really close ICOA CLI, type: ")+chalk.bold.cyan("quit confirm")),console.log(),void pe.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(),$o(),So(),lo(),x(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),uo(),void c(0))}if("back"===n){const o=Q(),e=o&&"demo-free"!==o.session.examId,t=o&&"demo-free"===o.session.examId&&(()=>{const e=new Date(o.session.startedAt||0).getTime();return Date.now()-e<18e5})();if(e)console.log(),console.log(chalk.gray(" Exam paused. Your progress is saved.")),console.log(chalk.white(" Resume: exam q 1")+chalk.gray(" · ")+chalk.white("exam review")+chalk.gray(" · ")+chalk.white("exam submit")),console.log();else if(t){const e=Object.keys(o.answers).length,t=o.session.questionCount;console.log(),console.log(chalk.gray(` Demo paused (${e}/${t} answered). Resume with: `)+chalk.white("exam q 1")),console.log(chalk.gray(" Or type ")+chalk.white("demo")+chalk.gray(" to restart.")),console.log()}else{if(o&&"demo-free"===o.session.examId){const{clearExamState:o}=await import("./lib/exam-state.js");o("demo-free"),Bo("exam-demo")}const e=m();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"===Xo?de():console.log(chalk.gray(" Already at main menu."))}return void pe.prompt()}if("help"===n||"?"===n||"guide"===n||"help all"===n.toLowerCase()){const o="guide"===n||"help all"===n.toLowerCase();if(Q()){if("help"===n){he=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return he=!1,void pe.prompt()}return _o(o?"guide":"help"),void pe.prompt()}return"root"!==Uo()?.id&&Ro(te(Xo),{quiet:!0}),o?Zo():Yo(),void pe.prompt()}if("man"===n||"manual"===n)return ue(f(),Xo),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 pe.prompt();if(/^(?:man|manual)\s+\S/i.test(n))return P(n.replace(/^(?:man|manual)\s+/i,"")),void pe.prompt();if("more help"===n.toLowerCase()&&Q()){he=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return he=!1,void pe.prompt()}if("continue"===n.toLowerCase())return console.log(),console.log(chalk.green.bold(" ═══ AI4CTF — AI as Your Teammate ═══")),console.log(),console.log(chalk.white(" In AI4CTF, you solve cybersecurity challenges")),console.log(chalk.white(" with AI by your side.")),console.log(),console.log(chalk.white(" In this demo, your AI teammate gives help at 3 levels:")),console.log(chalk.yellow(" hint a")+chalk.gray(" General guidance")),console.log(chalk.yellow(" hint b")+chalk.gray(" Deep analysis")),console.log(chalk.yellow(" hint c")+chalk.gray(" Critical assist")),console.log(),console.log(chalk.white(" Try it now! Type: ")+chalk.bold.green("ai4ctf")),console.log(chalk.gray(' Chat freely with your AI teammate. Type "exit" when done.')),console.log(),console.log(chalk.gray(" After ai4ctf, try: ")+chalk.bold.red("ctf4ai")+chalk.gray(' — trick the AI into saying "koala"')),console.log(),void pe.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(n.trim())){he=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim()])}catch{}return he=!1,void pe.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(n.trim())){he=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim().toUpperCase()])}catch{}return he=!1,void pe.prompt()}const s=n.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(s){he=!0;try{await e.parseAsync(["node","icoa","exam","token",s[1].toUpperCase()])}catch{}return he=!1,void pe.prompt()}const r=n.match(/^exam\s+([A-Z]{2,3})$/i);if(r){he=!0;try{await e.parseAsync(["node","icoa","exam","list",r[1]])}catch{}return he=!1,void pe.prompt()}const i=n.match(/^exam\s+(\S+)$/i);if(i&&!ce.has(i[1].toLowerCase())){const o=i[1].toUpperCase(),{normalizeTokenBody:t}=await import("./lib/token-format.js"),n=t(o),a=/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/;if(console.log(),a.test(n)){console.log(chalk.yellow(` Corrected look-alike characters: ${o} → ${n}`)),he=!0;try{await e.parseAsync(["node","icoa","exam","token",n])}catch{}return he=!1,void pe.prompt()}return console.log(chalk.red(` ✗ Not a valid exam token: ${o}`)),console.log(),console.log(chalk.gray(" An exam token is ")+chalk.bold.white("2 letters + 8 characters")+chalk.gray(" (e.g. ")+chalk.bold.yellow("AUHXP7SWMM")+chalk.gray(`) — yours is ${o.length}.`)),console.log(chalk.gray(" Check for 0/O, 1/I/L, V/U mix-ups, or ask your country team leader.")),console.log(),console.log(chalk.gray(" No token yet? Try ")+chalk.bold.green("demo")+chalk.gray(" (free practice paper) or ")+chalk.bold.green("exam nations")+chalk.gray(" to see participating countries.")),console.log(),void pe.prompt()}if("clear"===n||"cls"===n)return console.clear(),void pe.prompt();if("news"===n)return Oo()?jo():console.log(chalk.gray(" No competition joined. Use ")+chalk.white("join <url>")+chalk.gray(".")),void pe.prompt();if("memo"===n){if(!Oo())return console.log(chalk.gray(" Join a competition first: ")+chalk.white("join <url>")),void pe.prompt();he=!0;try{await Mo()}catch{}return void(he=!1)}const d=zo()||No(m().userName||"");if("jury"===n&&d){he=!0;try{await Fo()}catch{}return void(he=!1)}if(d&&zo()&&"scoreboard"===n.split(/\s+/)[0]){he=!0;try{const o=await Do();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 he=!1,void pe.prompt()}if(d&&Lo()){const o=n.split(/\s+/)[0];if(["challenges","open","submit","hint"].includes(o))return console.log(),console.log(chalk.yellow(" Team-leader account — the challenge bracket is not available here.")),console.log(chalk.gray(" Available: ")+chalk.white("scoreboard")+chalk.gray(" · ")+chalk.white("news")+chalk.gray(" · ")+chalk.white("jury")+chalk.gray(" · ")+chalk.white("time")+chalk.gray(" · ")+chalk.white("status")+chalk.gray(" · ")+chalk.white("logout")),console.log(),void pe.prompt()}if(n.startsWith("activate ")){const o=n.slice(9).trim(),e=await b(o);return"ok"===e?console.log(chalk.green(" Access granted! Token bound to this device.")):"network"===e?(console.log(),console.log(chalk.red(" Could not reach the activation server.")),console.log(chalk.gray(" Activation needs internet once — check your connection to ")+chalk.cyan("practice.icoa2026.au")+chalk.gray(" and run the same command again."))):"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 pe.prompt()}if("activate"===n)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void pe.prompt();const y=Q();if(y){const o=n.toUpperCase().trim(),t=o=>{const e=y.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},a=o=>{const e=y.questions.find(e=>e.number===o);return"short_answer"===e?.type},l=o=>{const e="demo-free"!==y.session.examId,t=y.questions.find(e=>e.number===o),n=J(t?.type,e);console.log(),console.log(chalk.yellow(` Q${o} is a practical question — letters (A/B/C/D) don't apply here.`)),n?(console.log(chalk.white(" Enter the AI chat for this question: ")+chalk.bold.cyan(n)),console.log(chalk.gray(" Or submit a flag directly: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`))):console.log(chalk.gray(" Submit a flag: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`)),console.log()};if(/^[ABCDE]$/.test(o)){const n=y._lastQ||1;if(t(n))return l(n),void pe.prompt();if(a(n))return console.log(),console.log(chalk.yellow(` Q${n} is a short-answer question — type a number, not a letter.`)),console.log(chalk.gray(" Example: ")+chalk.green("42")+chalk.gray(" (or ")+chalk.green(`exam answer ${n} 42`)+chalk.gray(")")),console.log(),void pe.prompt();he=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(n),o])}catch{}return he=!1,void pe.prompt()}if(/^-?\d+$/.test(o)){const t=y._lastQ||1;if(a(t)){he=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(t),o])}catch{}return he=!1,void pe.prompt()}}const s=o.match(/^(\d+)\s+([ABCDE]|-?\d+)$/);if(s){const o=parseInt(s[1],10);if(t(o))return l(o),void pe.prompt();he=!0;try{await e.parseAsync(["node","icoa","exam","answer",s[1],s[2]])}catch{}return he=!1,void pe.prompt()}}const u=n.split(/\s+/)[0].toLowerCase(),p=/^python3?(\.\d+)?$/.test(u),h="ls"===u||"pwd"===u||"tmux"===u,w=n.startsWith("!")||u.startsWith("!")||p||h,C=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"]),A=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${n}`)),console.log()};if("py"===u||"pylist"===u)return console.log(chalk.yellow(` ${u} is the learn-card Python scratchpad — it lives inside learn.`)),console.log(chalk.gray(" Open your course first: ")+chalk.bold.cyan("learn <TOKEN>")+chalk.gray(" (or bare ")+chalk.bold.cyan("learn")+chalk.gray(" for the demo), then type ")+chalk.bold.cyan("py"===u?"/py":"/pylist")+chalk.gray(" on any card.")),console.log(),void pe.prompt();if("embodied"===Xo&&!w&&!["doctor","upgrade","update","type","demo2","demo3","learn","exam","ctf4eai","ctf4vla","eai","arena","lang","ref","env","aienv","ipynb","kaggle","teleload","pandahelpme31","microduck","guide","board","sim"].includes(u))return C.has(u)?(A(),void pe.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 pe.prompt());if("selection"===Xo&&!w&&!["doctor","upgrade","update","type","battle","duck","python","mujoco","mojoco","setup","exam","demo","demo2","demo3","demo4","demo5","gfssm","retry","nations","next","prev","continue","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","aienv","ipynb","kaggle","teleload","pandahelpme31","microduck","gpufortask","guide","board","sim"].includes(u)){if(C.has(u))return A(),void pe.prompt();if(a().includes(u))console.log(chalk.gray(` ${u} isn't available on this screen.`));else{console.log(chalk.yellow(` Unknown command: ${u}`));const o=nearestCommand(u);o&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(o)+chalk.gray("?"))}if(y){const o=y._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: ")+chalk.bold.cyan("learn <TOKEN>")+chalk.gray(" · ")+chalk.bold.cyan("exam <CC>xxxxxxxx")+chalk.gray(" · ")+chalk.bold.cyan("demo")+chalk.gray(" · ")+chalk.bold.cyan("help")+chalk.gray(" · ")+chalk.bold.cyan("menu"));return console.log(),void pe.prompt()}if("organizer"===Xo&&!["doctor","upgrade","update","join","exam","demo","retry","next","prev","logout","lang","ref","ctf","mark","unmark","review","submit","tmux"].includes(u))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void pe.prompt();if(!("olympiad"!==Xo||f()&&v()||k(u)))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 pe.prompt();if(!a().includes(u)){if("tmux"===u)try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("env setup")+chalk.gray(" (full toolkit) or ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(".")),console.log(),void pe.prompt()}if(le.has(u))return console.log(chalk.yellow(` "${u}" is a shell command — the ICOA prompt isn't a shell.`)),console.log(chalk.gray(" In real-exam mode, prefix with ! to run inside the sandbox: ")+chalk.cyan(`!${n}`)),console.log(),void pe.prompt();if(/(?:^|\s)(?:\/(?!home\/|Users\/|tmp\/)|\.\.\/|~\/)/.test(n)&&!n.startsWith("cd ")){const o=/(?:^|\s)\/(?!home\/\w+\/icoa-workspace|Users\/\w+\/icoa-workspace|tmp\/)/.test(n),e=/\.\./.test(n);if(o||e)return console.log(chalk.red(" Blocked: access outside workspace is not allowed.")),console.log(chalk.gray(` Workspace: ${ae}`)),console.log(),void pe.prompt()}let o=n.startsWith("!")?n.slice(1).trim():n;if("darwin"===process.platform){const e="/opt/homebrew/opt/python@3.12/bin/python3.12";o=o.replace(/^python3?\s/,`${e} `).replace(/^(python3|python)$/,e)}else if("win32"===process.platform){const e=(()=>{try{return t("py -3 --version",{stdio:["ignore","ignore","ignore"],timeout:1500}),"py -3"}catch{}return"python"})();o=o.replace(/^python3?(\.\d+)?\s/,`${e} `).replace(/^python3?(\.\d+)?$/,e)}else{const e=(()=>{try{return t("which python3.12",{stdio:"ignore"}),"python3.12"}catch{return"python3"}})();o=o.replace(/^python\s/,`${e} `).replace(/^python$/,e)}const e=ko(),a=fo(n);bo({cwd:e,input:n,riskFlags:a}),a.length>0&&H()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${a.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=Go(Ko(),".icoa");Qo(o)||Ho(o,{recursive:!0});const e=Go(o,"python-startup.py");let t="";if(Qo(e))try{t=Vo(e,"utf-8")}catch{}return t!==oe&&Jo(e,oe),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()),he=!0;try{await wo()&&await po()?await ho(o,pe):await ye(o,pe,e)}catch{console.log(chalk.yellow(` Command failed: ${u}`))}return he=!1,console.log(),void pe.prompt()}he=!0;const $=n.trim(),I=$.toLowerCase();let E,S=null,j="";if(y)if("submit"===I)S="final";else if(I.startsWith("submit ")){let o=$.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)?(S="flag",j=o):o&&/^[ABCDE]$/i.test(o)&&(S="flag",j=o.toUpperCase())}else/^ICOA\{[^}]+\}$/i.test($)&&(S="flag",j=$);E="final"===S?["exam","submit"]:"flag"===S?["exam","answer",String(y?._lastQ||1),j]:mapCommand(n);const O="ctf"===E[0]&&"join"===E[1];O&&pe.pause(),process.exit=()=>{throw new Error(se)};try{await e.parseAsync(["node","icoa",...E])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===se);else if(e.includes("commander.unknownCommand")){const o=nearestCommand(u.split(/\s+/)[0]||u);console.log(chalk.yellow(` Unknown command: ${u}.`)),o&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(o)+chalk.gray("?")),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for the full command list."))}else e.includes("commander.missingArgument")||"commander.missingArgument"===o?.code?"submit"===u||"flag"===u?(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: ${u}`)),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=c,he=!1,O&&pe.resume()}O&&g()&&Ro(te(Xo),{mode:"full"}),N()?pe.setPrompt(chalk.magenta("icoa ai4ctf> ")):M()?pe.setPrompt(chalk.red("icoa ctf4ai> ")):_()&&pe.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),pe.prompt()}),pe.on("SIGINT",()=>{if(console.log(),N()||M())console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still in the AI chat.")),console.log(chalk.white(" Type ")+chalk.bold.cyan("exit")+chalk.white(" to leave the chat and return to the menu."));else if(Q()){const o="demo-free"!==Q().session.examId;console.log(chalk.yellow(" Ctrl+C did NOT close ICOA CLI.")),console.log(chalk.gray(` Your ${o?"exam":"demo"} is paused and every answer is auto-saved.`)),console.log(),console.log(chalk.white(" Resume: ")+chalk.cyan("exam q 1")+chalk.gray(" · Back to menu: ")+chalk.cyan("back")+chalk.gray(" · Close CLI: ")+chalk.cyan(o?"quit confirm":"quit"))}else console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still at the ")+chalk.cyan("icoa>")+chalk.yellow(" prompt.")),console.log(chalk.gray(" Keep typing — ")+chalk.cyan("help")+chalk.gray(" lists commands. (Only ")+chalk.cyan("quit")+chalk.gray(" or Ctrl+D actually close the CLI.)"));console.log(),pe.prompt()}),pe.on("close",()=>{n("main-rl-close",`stdin.isTTY=${!0===process.stdin.isTTY}`),console.log(),console.log(chalk.gray(" input closed — leaving icoa. Run icoa --resume to continue.")),Co(),$o(),So(),lo(),x(),uo(),c(0)}),"1"===process.env.ICOA_AUTO_RESUME&&(delete process.env.ICOA_AUTO_RESUME,G()&&(he=!0,await me(e),he=!1,pe.setPrompt(N()?chalk.magenta("icoa ai4ctf> "):ne()),pe.prompt()))}function ye(o,t,n){return new Promise(a=>{const l=process.stdin,s=!!l.isTTY&&!!l.isRaw;if(t.pause(),l.isTTY&&"function"==typeof l.setRawMode)try{l.setRawMode(!1)}catch{}const r=e(o,{shell:!0,stdio:"inherit",cwd:n||process.cwd()}),i=()=>{if(l.isTTY&&"function"==typeof l.setRawMode&&s)try{l.setRawMode(!0)}catch{}To(),t.resume(),a()};r.on("close",e=>{if(127===e){const e=nearestCommand(o.trim().split(/\s+/)[0]??"");e&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(e)+chalk.gray("?"))}i()}),r.on("error",i)})}export function mapCommand(o){const e=o.split(/\s+/),t=e[0].toLowerCase(),n=e.slice(1);if("demo"===t&&"3"===n[0])return["demo3",...n.slice(1,3)];if("aienv"===t&&["run","python","py"].includes((n[0]??"").toLowerCase()))return L(o);if("ipynb"===t&&n.length>=1)return["ipynb",L(o).slice(1).join(" ")];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=L(o);return["connect",e[1]??n[0],e.slice(2).join(" ")]}return s(t,n)||[t,...n]}function ue(o,e="olympiad"){if(console.log(),"selection"===e||"organizer"===e)return 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();if(!o)return 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();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();for(const o of["Competition","AI Teammate","Tools","System"]){console.log(chalk.bold.white(` ${o}`));for(const e of l(o))console.log(chalk.white(` ${e.label.padEnd(20)}`)+chalk.gray(e.text)),"System"===o&&"resume"===e.label&&console.log(chalk.white(" #<candidate> ")+chalk.gray("Stage a draft answer (never auto-submits)"));"Tools"===o&&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()}}
|
|
1
|
+
import{createInterface as o}from"node:readline";import{spawn as e,execSync as t}from"node:child_process";import chalk from"chalk";import{appendExitLog as n}from"./lib/exit-log.js";import{dispatchable as a,helpRows as l,shortcutFor as s,subcommandsOf as r,surface as i}from"./lib/commands.js";import{distance as c}from"fastest-levenshtein";import{isConnected as g,getConfig as m,saveConfig as d}from"./lib/config.js";import{selectionSetupLine as y}from"./lib/python-setup.js";import{isExamSetupComplete as u}from"./lib/exam-setup.js";import{detectCaps as p}from"./lib/render-card.js";import{ensureLangCache as h}from"./lib/translations-fetcher.js";import{loadUiPack as w}from"./lib/i18n.js";import{isActivated as f,activateToken as b,isFreeCommand as k,isDeviceMatch as v,recordExit as x,recordResume as C,isFirstRunOrUpgrade as A,markVersionSeen as $}from"./lib/access.js";import{setReplMode as I}from"./lib/ui.js";import{returnToMainMenu as T,printMenuHint as E,menuHintInline as S,registerRealExit as j}from"./lib/menu-nav.js";import{setMainRl as O}from"./lib/main-rl.js";import{shellSplit as L}from"./lib/shell-split.js";import{isChatActive as N,handleChatMessage as z}from"./commands/ai4ctf.js";import{isMicroduckWord as D}from"./commands/microduck.js";import{renderToolMan as P}from"./lib/tool-man.js";import{isCtf4aiActive as M,handleCtf4aiMessage as F}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as _,handleCtf4VlaMessage as U}from"./commands/ctf4vla.js";import{isDemo2Active as R}from"./commands/demo2.js";import{isSprintActive as q}from"./commands/sprint.js";import{isCardDeckActive as W}from"./lib/card-engine.js";import{hasAnySimHistory as B,lastArmAt as Z,lastBundledAt as Y,lastSimAt as X}from"./lib/sim-cooldown.js";import{getExamState as Q,getRealExamState as H,getDemoState as V,practicalChatCommand as J}from"./lib/exam-state.js";import{resolveResumePoint as G}from"./lib/resume.js";import{buildStatusLine as K}from"./lib/statusline.js";import{startBgTask as oo,startAsyncTask as eo,listBgTasks as to,getBgTask as no,drainCompleted as ao,killAllBgTasks as lo,runningCount as so}from"./lib/bgtasks.js";import{computeStart as ro,renderStart as io}from"./commands/challenge.js";import{addDraft as co,listDrafts as go,removeDraft as mo,clearDrafts as yo}from"./lib/drafts.js";import{resetTerminalTheme as uo}from"./lib/theme.js";import{ensureSandbox as po,runInSandbox as ho,isDockerAvailable as wo}from"./lib/sandbox.js";import{checkShellRisk as fo,logShellAudit as bo,getActiveCwd as ko}from"./lib/exam-sandbox.js";import{logCommand as vo}from"./lib/logger.js";import{startLogSync as xo,stopLogSync as Co}from"./lib/log-sync.js";import{installInputDynamics as Ao,uninstallInputDynamics as $o,stripTerminalMarkers as Io,rearmFocusMode as To}from"./lib/input-dynamics.js";import{startBroadcastPoll as Eo,stopBroadcastPoll as So,showBroadcast as jo,isCompetitionJoined as Oo,isMelCompetition as Lo,isLeaderAccount as No,isLeaderSession as zo,fetchPublicScoreboard as Do,isCommsActive as Po}from"./lib/comms.js";import{enterMemoScreen as Mo,enterJuryScreen as Fo}from"./commands/comms.js";import{examGuidance as _o}from"./commands/exam.js";import{currentSurface as Uo,enterPanel as Ro,isGuideWord as qo,isHelpWord as Wo,leavePanel as Bo,printGuide as Zo,printHelp as Yo}from"./lib/guide-panel.js";import{getDemoStats as Xo}from"./lib/demo-stats.js";import{existsSync as Qo,mkdirSync as Ho,readFileSync as Vo,writeFileSync as Jo}from"node:fs";import{join as Go}from"node:path";import{homedir as Ko}from"node:os";const oe="# 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",ee=Date.now();function te(o){const e=()=>ue(f(),o),t={verb:"menu",what:{en:"back to the start menu",zh:"回到开机选单"}};return"embodied"===o?{id:"root",title:{en:"ctf4eai — Embodied AI Security",zh:"ctf4eai — 具身 AI 安全"},what:{en:"Robots, physics, real attack surfaces. Four free steps, in order; each one is a word you type here.",zh:"机器人、物理、真实攻击面。四个免费步骤按顺序来,每一步就是在这里敲一个词。"},steps:[{verb:"sim",what:{en:"9-robot group dance — instant, no setup",zh:"9 机器人群舞 —— 即开即看"},done:()=>Y()>0||X()>0},{verb:"sim arm",what:{en:"drive a 6-joint arm yourself",zh:"自己驱动 6 关节机械臂"},done:()=>Z()>0},{verb:"demo2",what:{en:"~8 min interactive intro with a live MuJoCo sim",zh:"约 8 分钟互动入门 + 实时 MuJoCo 仿真"}},{verb:"learn LEARNDEMO01",what:{en:"free 11-card intro course (paste as-is)",zh:"免费 11 卡入门课(原样粘贴)"}},{verb:"learn <token>",what:{en:"your full EA course token from your team",zh:"队里发的完整 EA 课程 token"},optional:!0}],leave:t,guide:e}:"organizer"===o?{id:"root",title:{en:"Partner console",zh:"合作方控制台"},what:{en:"Manage exams for your country or region.",zh:"管理你所在国家 / 地区的考试。"},steps:[{verb:"join <url>",what:{en:"connect to the exam server",zh:"连接考试服务器"},done:()=>g()},{verb:"exam list",what:{en:"see the papers available to you",zh:"查看可用考卷"}},{verb:"logout",what:{en:"disconnect",zh:"断开连接"},optional:!0}],leave:t,guide:e}:Lo()||"olympiad"===o&&f()&&g()?{id:"root",title:{en:"Competition",zh:"比赛"},what:{en:"You are signed in to the live competition. Pick a challenge, read it, submit the flag you find.",zh:"已登录正式比赛。挑一道题、读题、提交找到的 flag。"},steps:[{verb:"challenges",what:{en:"list every challenge with its id and points",zh:"列出所有题目(编号 + 分值)"}},{verb:"open 1",what:{en:"read challenge 1 (any id from the list)",zh:"读第 1 题(列表里的任意编号)"}},{verb:"submit 1 ICOA{...}",what:{en:"submit the flag for that challenge",zh:"提交那道题的 flag"}},{verb:"ai4ctf",what:{en:"chat with your AI teammate when stuck",zh:"卡住时和 AI 队友聊"},optional:!0},{verb:"memo",what:{en:"report a problem to the organizers (one-way)",zh:"向组织者报告问题(单向)"},optional:!0},{verb:"scoreboard",what:{en:"live rankings",zh:"实时榜单"},optional:!0}],notes:[{en:"logout = sign out of this account · man <tool> = how to use a CTF tool",zh:"logout = 退出账号 · man <tool> = 某个 CTF 工具怎么用"}],leave:t,guide:e}:"olympiad"===o?f()?{id:"root",title:{en:"Finals tier",zh:"决赛层"},what:{en:"Activated. Connect to the competition server, then solve challenges with your tools and AI teammate.",zh:"已激活。先连接比赛服务器,再用工具和 AI 队友解题。"},steps:[{verb:"env",what:{en:"check your tools (env setup installs what is missing)",zh:"检查工具(env setup 补装缺的)"},optional:!0},{verb:"join <url>",what:{en:"connect to the competition server",zh:"连接比赛服务器"},done:()=>g()},{verb:"challenges",what:{en:"browse and pick a challenge",zh:"浏览并挑一道题"}},{verb:"ai4ctf",what:{en:"chat with your AI teammate when stuck",zh:"卡住时和 AI 队友聊"},optional:!0}],leave:t,guide:e}:{id:"root",title:{en:"Finals tier",zh:"决赛层"},what:{en:"The full sandbox with 90+ CTF tools. It unlocks with your competition token.",zh:"带 90 多个 CTF 工具的完整沙箱,用比赛 token 解锁。"},steps:[{verb:"activate <token>",what:{en:"unlock with the competition token you were given",zh:"用发给你的比赛 token 解锁"}},{verb:"env",what:{en:"see which of the 90+ tools are installed",zh:"看 90 多个工具装了哪些"},optional:!0},{verb:"ref linux",what:{en:"quick reference while you wait",zh:"等待时看速查表"},optional:!0}],leave:t,guide:e}:{id:"root",title:{en:"ICOA",zh:"ICOA"},what:{en:"The icoa> prompt: type one of these words and press Enter. Nothing here needs an account; a token opens the real courses and exams.",zh:"icoa> 提示符:敲下面任一个词回车。这里不需要账号;有 token 才进正式课程和考试。"},steps:[{verb:"demo",what:{en:"10 sample exam questions — no token, no timer",zh:"10 道样题 —— 免 token、无计时"},done:()=>{try{return Xo().attempts>0}catch{return!1}}},{verb:"demo3",what:{en:"olympiad replay — real solutions, step by step",zh:"奥赛回放 —— 真题解法逐步看"}},{verb:"kaggle",what:{en:"ML practice — train a model, real leaderboard",zh:"ML 练习 —— 训模型、上真榜"}},{verb:"learn <token>",what:{en:"open your course with the token from your coach",zh:"用老师给的 token 打开课程"},done:()=>Qo(Go(Ko(),".icoa","learn-state.json"))},{verb:"exam <token>",what:{en:"sit a country exam with your exam token",zh:"用考试 token 进入国家考试"}},{verb:"lang zh",what:{en:"switch the interface language (lang en to go back)",zh:"切换界面语言(lang en 切回英文)"},optional:!0}],leave:t,guide:e}}function ne(){return Lo()?chalk.yellow("icoa 2026> "):H()?chalk.cyan("icoa exam> "):function(){const o=V();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=ee}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const ae=Go(Ko(),"icoa-workspace"),le=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),se="__REPL_NO_EXIT__",re="2.5.1",ie=i();export function nearestCommand(o,e=2){const t=o.trim().toLowerCase();if(!t)return null;let n={word:"",dist:Number.POSITIVE_INFINITY};for(const o of ie){const e=c(t,o);e<n.dist&&(n={word:o,dist:e})}return n.dist>0&&n.dist<=e?n.word:null}const ce=new Set(["answer","demo","demo-retry","help","list","mark","more-help","nations","next","prev","q","reset","result","review","setup","start","submit","token","unmark","status","time"]);function ge(o){const e=o.replace(/^\s+/,"");if(/^\/\S*$/.test(e)){const o=e.slice(1).toLowerCase();return[ie.filter(e=>e.startsWith(o)).map(o=>`/${o}`),e]}const t=e.split(/\s+/);if(t.length<=1){const o=(t[0]??"").toLowerCase();return[ie.filter(e=>e.startsWith(o)).slice(),o]}if(2===t.length){const o=r(t[0].toLowerCase());if(o){const e=t[1].toLowerCase();return[o.filter(o=>o.startsWith(e)).slice(),e]}}return[[],o]}async function me(o){const e=G();if(!e)return null;const t=process.exit;process.exit=()=>{throw new Error(se)};try{await o.parseAsync(["node","icoa",...e.command])}catch(o){if(!(o instanceof Error&&o.message===se))throw o}finally{process.exit=t}return e}function de(){console.log(),console.log(` ${chalk.cyan.bold("🎯 ICOA · 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.white("DUxxxxxxxx")+chalk.gray(" → Duck Cup (type the token from your seat card)")),console.log(" "+chalk.white("BAxxxxxxxx")+chalk.gray(" → BattleAI Cup (your BattleAI 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"));try{console.log(),console.log(y(u(),"T0"===p().tier))}catch{}console.log()}export async function startRepl(e,l){process.env.ICOA_INSIDE_REPL="1";let s=!1;if(Lo()){const o=m().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)||(d({ctfdUrl:"",token:"",sessionCookie:"",userId:null,userName:"",teamId:null,country:"",joinedAt:""}),s=!0)}const r=m(),i=g(),c=process.exit.bind(process);j(c);const y=f();if(r.language&&"en"!==r.language&&(await h(r.language,{silent:!0}),w(r.language)),r.demoCleanedForVersion!==re){try{const{existsSync:o,unlinkSync:e}=await import("node:fs"),{join:t}=await import("node:path"),{getIcoaDir:n}=await import("./lib/config.js"),a=t(n(),"demo-state.json");o(a)&&e(a)}catch{}d({demoCleanedForVersion:re})}const{default:u}=await import("@inquirer/select"),{default:p}=await import("@inquirer/confirm"),L=r.mode||"",V=""===L?"instant":"selection"===L?"learn":["instant","learn","olympiad"].includes(L)?L:"learn",To=[{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("team token · skill up")}`,value:"learn"},{name:` ${chalk.bold("🎯 National Selection")} ${chalk.gray("—")} ${chalk.gray("country exam token · aim for finals")}`,value:"selection"},{name:` ${chalk.bold("🏆 International Olympiad")} ${chalk.gray("—")} ${chalk.gray("finals stage · full sandbox")}`,value:"olympiad"},{name:` ${chalk.gray("ℹ️ About ICOA")} ${chalk.gray("·")} ${chalk.gray("what this is · how to join")}`,value:"about"}];""===L&&(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("help")+chalk.gray(" at any prompt for guidance · ")+chalk.bold.cyan("menu")+chalk.gray(" from anywhere to return here.")),console.log();let Xo="";for(;!Xo;){let o;const e=process.env.ICOA_TEST_BOOT_MODE;if(e&&["instant","learn","selection","olympiad"].includes(e))o=e;else try{o=await u({message:"Mode",choices:To,default:V||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}if("about"!==o)Xo=o;else{console.clear(),console.log(),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(chalk.bold.yellow(" ICOA")+chalk.white(" — AI-Native CLI OS for Cyber & AI Security")),console.log(chalk.gray(" Olympiad & Competition · K-12 to University")),console.log(chalk.cyan(" ───────────────────────────────────────────────────")),console.log(),console.log(chalk.bold.white(" What Makes ICOA Different")),console.log(chalk.gray(" · AI-native AI teammate, AI adversary, AI translation")),console.log(chalk.gray(" · CLI OS Complete competition environment in terminal")),console.log(chalk.gray(" · 100 tools z3, radare2, nmap, sleuthkit, tshark... pre-configured")),console.log(chalk.gray(" · Global scale 15,000+ concurrent exams · 20+ languages")),console.log(),console.log(chalk.bold.white(" Three Frontiers of AI Security")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" AI as teammate — 5 CTF disciplines, 5-hour endurance round")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" AI as target — the AI system itself is the objective")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" Embodied-AI Arena — probe robot policies in live simulation")}`),console.log(),console.log(chalk.bold.white(" First Edition — Sydney 2026 ")+chalk.green.bold("✓ held")),console.log(chalk.gray(" · Jun 27 - Jul 2, 2026 · University of Technology Sydney")),console.log(chalk.gray(" · 65 competitors · 20 countries & regions (10 on-site, 10 remote)")),console.log(chalk.gray(" · 36 awards — 6 Gold · 11 Silver · 17 Bronze · 2 Honorable Mentions")),console.log(chalk.gray(" · Champion: Oleg Uteshev · Embodied-AI Arena Gold: Kingsley Lim (AU)")),console.log(chalk.gray(" · Founding Charter signed — ICOA is now a permanent institution")),console.log(),console.log(chalk.bold.white(" Next: ICOA 2027")+chalk.gray(" — 20 more countries already accredited")),console.log(),console.log(chalk.bold.white(" Organized by")+chalk.gray(" ASRA (Australia) · ICO Foundation Inc")),console.log(chalk.bold.white(" Contact ")+chalk.cyan(" australia@icoa2026.au · accreditation@icoa2026.au")),console.log(chalk.bold.white(" Website ")+chalk.cyan.underline(" https://icoa2026.au")+chalk.gray(" · press: ")+chalk.cyan.underline("https://icoa2026.au/press/")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log();try{const{default:o}=await import("@inquirer/input"),e=()=>o({message:chalk.gray("Press Enter to return..."),theme:{prefix:"",style:{message:o=>o}}}),t=Date.now();let n=await e();Date.now()-t<200&&(n=await e());const a=n.trim().toLowerCase();if("config"===a||"wizard"===a){const{runSetupWizard:o}=await import("./commands/setup.js");await o(),await e()}else if("setup"===a||"/setup"===a){const{runSetupVerb:o}=await import("./commands/setup.js");await o(""),await e()}}catch{}console.clear()}}if("olympiad"===Xo&&"olympiad"!==V){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await p({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(Xo="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(Xo!==V&&d({mode:Xo}),console.log(),"olympiad"===Xo&&A(re)){$(re),console.log(chalk.gray(" Checking competition environment..."));const{execSync:o}=await import("node:child_process"),e=[{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(l){const o=C();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"===Xo)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),de();else if("embodied"===Xo)!function(){console.log(chalk.cyan.bold(" [🤖 ctf4eai — Embodied AI Security]")),console.log(),console.log(chalk.bold.cyan(" CTF4EAI")+chalk.gray(" — ICOA's ")+chalk.bold.white("Pioneer Round")),console.log(chalk.gray(" an independent parallel track alongside the scored main events: ")+chalk.green("AI4CTF")+chalk.gray(" and ")+chalk.red("CTF4AI")),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=Y()>0||X()>0,e=Z()>0,t=B();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(),E(),console.log()}();else if("instant"===Xo)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Four free demos — type one and press Enter:")),console.log(),console.log(chalk.bold.green(" demo ")+chalk.gray(" Paper A/B/C sample — 10 MCQs, no timer ")+chalk.bold.cyan("🎯 selection-style")),console.log(chalk.bold.green(" demo2 ")+chalk.gray(" Embodied-AI mini-demo — robots & MuJoCo ")+chalk.bold.yellow("🤖 hands-on")),console.log(chalk.bold.green(" demo3 ")+chalk.gray(" Olympiad replay — 6 real AIO solutions ")+chalk.bold.green("⚔ step by step")),console.log(chalk.bold.green(" kaggle")+chalk.gray(" ML practice — train a model, real board ")+chalk.bold.magenta("📊 data-science")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(", ")+chalk.bold.cyan("demo2")+chalk.gray(", ")+chalk.bold.cyan("demo3")+chalk.gray(" or ")+chalk.bold.cyan("kaggle")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),d({mode:"selection"}),Xo="selection";else{if("learn"===Xo){console.log(chalk.cyan.bold(" [🧠 Learn]")),console.log();const o=await(async()=>{try{const o=await import("./lib/learn-state.js");try{const{fetchProfilesForLocalTokens:e}=await import("./lib/learn-door.js"),t=await e(o.listLearnSessions().map(o=>o.token),{staleOk:!0});for(const e of t)o.adoptLinkedSessions(e.tokens)}catch{}return{sessions:o.listLearnSessions(),listMax:o.CONTINUE_LIST_MAX}}catch{return{sessions:[],listMax:5}}})(),t=o.sessions,a=o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o)?`${o.slice(0,2)}••••••${o.slice(-2)}`:o,l=o=>{const e=new Date(o);if(Number.isNaN(e.getTime()))return"";const t=o=>new Date(o.getFullYear(),o.getMonth(),o.getDate()).getTime(),n=Math.round((t(new Date)-t(e))/864e5);return n<0?"":0===n?"today":1===n?"yesterday":n<30?`${n} days ago`:"a while back"},s=e=>{const n=e?t:t.slice(0,o.listMax),s=o=>Math.max(...n.map(e=>o(e).length)),r=s(o=>o.curriculumId),i=s(o=>`card ${o.currentCard}/${o.totalCards}`),c=s(o=>l(o.lastSeenAt));return n.forEach((o,e)=>{const t=o.token===o.curriculumId?"":` ${a(o.token)}`;console.log(chalk.green(` ${e+1} `)+chalk.bold.white(o.curriculumId.padEnd(r))+chalk.yellow(` ${`card ${o.currentCard}/${o.totalCards}`.padEnd(i)}`)+chalk.gray(` ${l(o.lastSeenAt).padEnd(c)}${t}`))}),n.length};if(1===t.length){const o=t[0],e=l(o.lastSeenAt);console.log(chalk.green(" ▸ Continue ")+chalk.bold.white(o.curriculumId)+chalk.gray(" · ")+chalk.yellow(`card ${o.currentCard}/${o.totalCards}`)+chalk.gray(`${e?` · ${e}`:""} · ${a(o.token)}`)),console.log(chalk.gray(" type ")+chalk.bold.green("c")+chalk.gray(" or ")+chalk.bold.green("continue")+chalk.gray(" to resume · Enter to go back")),console.log()}else if(t.length>1){console.log(chalk.green(" ▸ Continue"));const o=s(!1);t.length>o&&console.log(chalk.gray(` +${t.length-o} more — type `)+chalk.bold.green("c all")+chalk.gray(" to list them")),console.log(chalk.gray(" type ")+chalk.bold.green("c")+chalk.gray(" to resume 1 · ")+chalk.bold.green("c 2")+chalk.gray(" to switch · Enter to go back")),console.log()}{const{doorStoryLines:o,doorWelcomeLines:e,fetchProfilesForLocalTokens:n}=await import("./lib/learn-door.js"),{learnW:a}=await import("./lib/learn-render.js");let l=null;if(t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token))){const s=await n(t.map(o=>o.token),{staleOk:!0}),r=s[0]??null,i=new Set(s.flatMap(o=>o.tokens.filter(o=>o.credits?.completed).map(o=>o.curriculum_id))).size;l=r?o(r,a(),i):e(a(),!0)}else l=e(a(),!1);for(const o of l)console.log(o);try{const{pythonDoorLine:o}=await import("./lib/python-setup.js"),{detectCaps:e}=await import("./lib/render-card.js"),t=(m().language||"en").toLowerCase().startsWith("zh");console.log(o(t,"T0"===e().tier))}catch{}console.log()}try{const{default:o}=await import("@inquirer/input"),{resolveLearnInput:n}=await import("./lib/learn-input.js"),a={id:"learn-door",title:{en:"Learn — your course token",zh:"Learn —— 课程 token"},what:{en:"Paste the 10-character token your coach gave you and the course opens right here. Nothing to install first.",zh:"把老师发给你的 10 位 token 粘贴进来,课程就在这里打开。不用先安装任何东西。"},steps:[...t.length>0?[{verb:"c",what:{en:"continue the course you opened last time (c 2 = the second one)",zh:"继续上次打开的课程(c 2 = 第二门)"}}]:[],{verb:"<your token>",what:{en:"paste the 10 letters/digits from your coach and press Enter (O/0 and I/1 mix-ups are fixed for you)",zh:"粘贴老师给的 10 位字母数字后回车(O/0、I/1 混淆会自动纠正)"},done:()=>t.length>0}],notes:[{en:"No token yet? Ask your coach. Also answered here: me · story · certificate · python setup",zh:"还没有 token?问老师。这里还能敲:me · story · certificate · python setup"}],leave:{verb:"Enter",what:{en:"an empty line goes back to the menu",zh:"空行回到选单"}}};Ro(a);const l=async()=>{try{await o({message:chalk.bold.yellow("Press Enter to return to the menu"),theme:{prefix:"",style:{message:o=>o}}})}catch{}},r=3;let i=null,c=null;for(let a=1;a<=r;a++){const g=await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}),m=g.trim().toLowerCase();if(Wo(m)||qo(m)){Yo(),a--;continue}if("ai4ioai"===m||"/ai4ioai"===m){const{runAi4ioaiStandalone:o}=await import("./commands/ai4ioai.js");return await o(),await l(),d({mode:"selection"}),void T()}if(D(g)){const{runMicroduck:o}=await import("./commands/microduck.js");return await o(),await l(),d({mode:"selection"}),void T()}if(["pandahelpme31","/pandahelpme31","panda help me 31","pandahelpme"].includes(m)){const{runSprint:o}=await import("./commands/sprint.js");return await o(),d({mode:"selection"}),void T()}if("wm"===m||"/wm"===m||m.startsWith("wm ")){const{runWm:o}=await import("./commands/wm.js");return await o(g.trim().split(/\s+/).slice(1).join(" ")||void 0),d({mode:"selection"}),void T()}if("ioailab"===m||"/ioailab"===m){const{runIoailabStandalone:o}=await import("./commands/ioailab.js");return await o(),await l(),d({mode:"selection"}),void T()}if("me"===m||"/me"===m||"profile"===m||"/profile"===m){const o=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));if(o){const{fetchLearnProfile:e,renderLearnProfile:t}=await import("./lib/learn-profile.js"),{learnW:n}=await import("./lib/learn-render.js");console.log(chalk.gray(` Loading your profile (${o.token.slice(0,2)}••••••${o.token.slice(-2)})…`));const a=await e(o.token);"ok"===a.kind?t(a.profile,!1,n(),"prompt"):"offline"===a.kind?console.log(chalk.yellow(" Cannot reach the learn server — try me again online.")):console.log(chalk.yellow(` ${"demo"===a.kind?"No profile for a demo token":a.message}`)),console.log()}else console.log(),console.log(chalk.yellow(" No profile yet — open a course with your token first, then type me.")),console.log();a--;continue}const y=m.match(/^\/?setup(?:\s+(\S.*))?$/);if(y){const{runSetupVerb:o}=await import("./commands/setup.js");await o(y[1]??"",{inLearn:!0}),a--;continue}const u=m.match(/^\/?python(?:3)?(?:\s+(setup|install|status))?$/);if(u){const{runSetup:o,printStatus:e}=await import("./commands/python.js");"setup"===u[1]||"install"===u[1]?await o():e(),a--;continue}if(/^\/?(upgrade|update)$/.test(m)){const{runUpgrade:o}=await import("./lib/update-check.js");if("upgraded"===await o({ask:!1}))return console.log(chalk.gray(" restarting icoa …")),void T();a--;continue}const p=m.match(/^\/?m[ou]joco(?:\s+(setup|install|status))?$/);if(p){const{runMujocoSetup:o,printMujocoStatus:e}=await import("./commands/mujoco.js");"setup"===p[1]||"install"===p[1]?await o():e(),a--;continue}const h=m.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(h){const{certificateLines:e,dropProfileCache:n}=await import("./lib/learn-door.js"),{certifiable:l,certificateIntroLines:s,sameName:r,issueCertificate:i,announceCertificate:c}=await import("./lib/learn-certificate.js"),{fetchProfilesForLocalTokens:g}=await import("./lib/learn-door.js"),m=await g(t.map(o=>o.token)),d=m[0]??null,y=new Set,u=m.flatMap(o=>l(o)).filter(o=>!y.has(o.curriculum_id)&&y.add(o.curriculum_id)),p=(h[2]??"").toLowerCase();console.log();const w=p?u.find(o=>o.curriculum_id.toLowerCase()===p||o.curriculum_id.toLowerCase().startsWith(p)):1===u.length?u[0]:void 0;if(0===u.length||!w&&!p){for(const o of e(d,!1))console.log(o);u.length>1&&console.log(chalk.gray(" type ")+chalk.bold.green("certificate <track>")+chalk.gray(" to issue one.")),console.log(),a--;continue}if(!w){console.log(chalk.yellow(` No finished track matches "${p}". `)+chalk.gray("Finished: "+u.map(o=>o.curriculum_id).join(", "))),console.log(),a--;continue}for(const o of s(w,!1))console.log(o);console.log();const f=async e=>(await o({message:chalk.bold.cyan(e),theme:{prefix:"",style:{message:o=>o}}})).trim(),b=await f("Name on the certificate:");if(!b){console.log(chalk.gray(" Cancelled — nothing issued.")),console.log(),a--;continue}if(!r(b,await f("Type it once more:"))){console.log(chalk.yellow(" The two names differ — nothing issued. Type certificate to try again.")),console.log(),a--;continue}console.log(chalk.gray(" Issuing… (the name is sent once, never stored)")),c(await i(w.token,w.curriculum_id,b),!1),n(),a--;continue}const w=m.match(/^\/?(story|credits)(?:\s+(\S+))?$/);if(w){const{fetchLearnProfile:o}=await import("./lib/learn-profile.js"),{buildCreditLines:e,rollCredits:n,storyListLines:l}=await import("./lib/learn-credits.js"),{learnW:s}=await import("./lib/learn-render.js"),r=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));if(console.log(),r){const a=await o(r.token,"credits"===w[1]?"credits":"story");if("ok"!==a.kind)console.log(chalk.yellow(" Cannot reach the learn server — try story again online."));else{const o=(w[2]??"").toLowerCase(),r=a.profile;let i;if(o){const e=Number(o);i=Number.isInteger(e)&&e>=1&&e<=r.tokens.length?r.tokens[e-1]:r.tokens.find(e=>e.curriculum_id.toLowerCase()===o||e.curriculum_id.toLowerCase().startsWith(o))}else"credits"===w[1]&&(i=r.tokens.find(o=>o.credits?.completed));if(i){if(await n(e(i,r,i.curriculum_id,{},!1,s(),!1),()=>!1,180),i.credits?.completed&&!i.credits.credits_rolled_at){const{postCreditsRolled:o}=await import("./lib/learn-profile.js");o(i.token,i.curriculum_id)}}else{o&&console.log(chalk.yellow(` No story for "${o}".`));for(const o of l(r,!1))console.log(o);const e=new Set(r.tokens.map(o=>o.token.toUpperCase())),n=t.filter(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token)&&!e.has(o.token.toUpperCase()));n.length>0&&console.log(chalk.gray(` +${n.length} more course${1===n.length?"":"s"} on this computer not linked yet — open one and type `)+chalk.bold.green("link")+chalk.gray(" to join them."))}}}else console.log(chalk.yellow(" No story yet — open a course with your token first."));console.log(),a--;continue}{const{TEAM_RE:e,runTeamMeeting:n}=await import("./lib/learn-team.js");if(e.test(m)){const e=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));if(console.log(),e){const t=async e=>{try{return(await o({message:e,theme:{prefix:"",style:{message:o=>o}}})).trim()}catch{return null}};await n(e.token,t),console.log()}else console.log(chalk.yellow(" Team meeting needs your FTC course token — open the course with it first, then type teammeeting.")),console.log();a--;continue}}{const{CHECK_RE:o,runLearnCheck:e}=await import("./lib/learn-check.js"),n=m.match(o);if(n){const o=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));console.log(),o?(await e(o.token,n[1]??""),console.log()):(console.log(chalk.yellow(" check needs your own course token — open a course with it first, then type check <TOKEN>.")),console.log()),a--;continue}}{const{CLASS_RE:o,runLearnClass:e}=await import("./lib/learn-class.js"),n=m.match(o);if(n){const o=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));console.log(),o?(await e(o.token,n[1]??""),console.log()):(console.log(chalk.yellow(" class needs your own course token — open a course with it first, then type class.")),console.log()),a--;continue}}const{FOCUS_LOG_RE:f,fetchFocusLog:b,renderFocusLog:k}=await import("./lib/learn-focus-log.js");if(f.test(m)){const o=t.find(o=>/^[A-Z]{2}[A-Z0-9]{8}$/i.test(o.token)&&!/DEMO01$/i.test(o.token));if(console.log(),o){const{detectCaps:e}=await import("./lib/render-card.js"),t=await b(o.token);if("ok"===t.kind)for(const o of k(t.log,!1,"T0"===e().tier,"Enter to go back"))console.log(o);else console.log(chalk.yellow("offline"===t.kind?" Offline — the focus log lives on the server; try again when connected.":"demo"===t.kind?" Demo tokens are shared — no focus log. Use your own token.":` Could not load the focus log: ${t.message}`));console.log()}else console.log(chalk.yellow(" No focus log yet — open a course with your token first, then type focus log.")),console.log();a--;continue}const v=m.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(v){const{FOCUS_MAX:o,FOCUS_MIN:e,FOCUS_STEP:t,getStudyTimer:n,parseFocusMinutes:l}=await import("./lib/learn-study-timer.js"),s=n(),r=(v[2]??"").trim();if(console.log(),s.showPending());else if("off"===r||"stop"===r||"end"===r||"cancel"===r)s.stop()?(await new Promise(o=>setTimeout(o,300)),s.showPending()):console.log(chalk.gray(" No focus session running. Start one: ")+chalk.bold.green("focus 30"));else if(s.active)console.log(chalk.yellow(" ⏱ ")+chalk.white(`focus running · ${s.remainingMin()} min left`)+chalk.gray(" · paste a token and keep going, or ")+chalk.bold.green("focus off"));else if(""===r||"?"===r||"help"===r)console.log(chalk.bold.white(" ⏱ Focus session")),console.log(chalk.gray(` How long? (${e}–${o}, steps of ${t}) e.g. `)+chalk.bold.green("focus 30")),console.log(chalk.gray(" Start it here, then open any course — every course you visit counts."));else{const n=l(r);if(n){if("ok"!==n.note){const a="min"===n.note?`min is ${e}`:"max"===n.note?`max is ${o}`:`rounded to the nearest ${t}`;console.log(chalk.gray(` you typed ${r} → ${a}, using ${n.min}`))}s.start(n.min),console.log(chalk.yellow(" ⏱ ")+chalk.bold.white(`Focus ${n.min} min — go`)+chalk.gray(" · now paste your token (any course counts) · soft reminder every 10 min · end early: ")+chalk.bold.green("focus off"))}else console.log(chalk.yellow(` Didn't understand "${r}". `)+chalk.gray("Type minutes, e.g. ")+chalk.bold.green("focus 30"))}console.log(),a--;continue}if(/^(doctor|\/doctor)$/i.test(g.trim())){const{runDoctor:o}=await import("./commands/doctor.js");await o(),console.log(),console.log(chalk.gray(" Paste your token to try again, or press Enter to go back.")),console.log(),a--;continue}if(/^\/?move$/.test(m)){if(a--,!i){console.log(),console.log(chalk.gray(" move brings your courses to this computer. Type one of your tokens first —")+chalk.gray(" if it says it is bound to another computer, type ")+chalk.bold.green("move")+chalk.gray(".")),console.log();continue}const{runMove:e}=await import("./lib/learn-move.js"),t=await e(i,e=>o({message:chalk.gray(e.trimStart()),theme:{prefix:" ",style:{message:o=>o}}}));if(console.log(),!t)continue;c=i,i=null}let x=n(c??g);if(c=null,"back"===x.kind)break;if("continue"===x.kind){if(0===t.length){if(console.log(),console.log(chalk.yellow(" Nothing to continue — no previous session on this computer.")),console.log(chalk.gray(" Paste your cohort token to start.")),console.log(),a===r){await l();break}continue}const{which:o}=x;let e=t[0];if("all"===o){console.log(),s(!0),console.log(),a-=1;continue}if("number"==typeof o){if(o<1||o>t.length){if(console.log(),console.log(chalk.yellow(` You have ${t.length} course${t.length>1?"s":""} in progress — pick 1${t.length>1?`-${t.length}`:""}, or type part of its name.`)),console.log(),a===r){await l();break}continue}e=t[o-1]}else if("string"==typeof o){const n=t.filter(e=>e.curriculumId.toLowerCase().includes(o)||e.token.toLowerCase().includes(o));if(1!==n.length){if(console.log(),console.log(chalk.yellow(0===n.length?` No course in progress matches "${o}".`:` "${o}" matches ${n.length} of your courses — be more specific, or use its number.`)),console.log(),s(!0),console.log(),a===r){await l();break}continue}e=n[0]}x={kind:"token",token:e.token}}if("ambiguous"===x.kind||"unknown"===x.kind){if(console.log(),console.log(chalk.yellow(` ${x.hint}`)),console.log(),a===r){console.log(chalk.gray(` That was attempt ${r} of ${r} — going back to the menu.`)),console.log(chalk.gray(" Your token comes from your country team leader.")),console.log(),await l();break}continue}if(x.from){const{loadCurriculumById:o}=await import("./lib/learn-curricula.js");if(!await o(x.token,x.token)){if(console.log(),console.log(chalk.yellow(` "${x.from}" is not a token.`)),console.log(chalk.gray(" Paste the token your team leader gave you (2 letters + 8 characters).")),console.log(),a===r){await l();break}continue}}if(!/^[A-Z0-9]+DEMO01$/i.test(x.token)&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(x.token)){console.log(),console.log(chalk.gray(" Checking token…"));const{validateEAToken:o}=await import("./lib/learn-curricula.js");let e=await o(x.token);if(!e.ok){const{normalizeTokenBody:t}=await import("./lib/token-format.js"),n=t(x.token);if(n!==x.token.trim().toUpperCase()){const t=await o(n);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${x.token} → ${n}`)),e=t,x={...x,token:n})}}if(!e.ok){if(console.log(),console.log(chalk.red(` ✗ Token check failed: ${e.message||"validation failed"}`)+(e.code?chalk.gray(` [${e.code}]`):"")),"device_bound"===e.code)i=x.token,console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.white(" 🧭 New or reinstalled computer? Type ")+chalk.bold.green("move")+chalk.white(" — all your courses come here, progress kept."));else if("expired"===e.code)console.log(chalk.gray(" This learn token has expired — ask your coordinator for a new one."));else if("network"===e.code){console.log(chalk.yellow(" Your token was not checked — this computer could not reach the ICOA server.")),console.log(chalk.gray(" (Your browser opening Google or practice.icoa2026.au does not count: icoa")),console.log(chalk.gray(" connects on its own, without the browser, and can be blocked separately.)")),console.log();for(const o of e.advice??[])console.log(chalk.gray(` ${o}`));(e.advice?.length??0)>0&&console.log(),console.log(chalk.gray(" ▸ Type ")+chalk.cyan("doctor")+chalk.gray(" right here — it names the exact fault and the fix.")),console.log(chalk.gray(" If it does not, send its output to your coordinator."))}else console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)")),console.log(chalk.gray(" · Token expired or revoked"));if(console.log(),a<r){console.log(chalk.gray(" Try again — or press Enter to go back.")),console.log();continue}await l();break}}console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${x.token}`)),console.log(),d({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";const{setLearnSessionStarted:C}=await import("./lib/learn-outcome.js");C(!1);try{await e.parseAsync(["node","icoa","learn",x.token])}catch(o){console.log(),console.log(chalk.red(` ✗ learn failed to start: ${o instanceof Error?o.message:String(o)}`)),console.log()}finally{delete process.env.ICOA_LEARN_EMBEDDED}await l();break}}catch(o){n("learn-token-prompt-cancel",o instanceof Error?`${o.name}: ${o.message}`:String(o))}return Bo("learn-door"),d({mode:"selection"}),void T()}"organizer"===Xo?(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")),console.log(chalk.bold.magenta(" The World's First AI-Native CLI Operating System")),console.log(chalk.bold.magenta(" for K-12 AI & Cyber Olympiads and International AI Hackathons")),console.log(chalk.gray(" ICOA 2026: Sydney, Australia · ICOA 2027: July 2027")),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(),i?(console.log(chalk.green(` Logged in as ${r.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(),E(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),y&&!v()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):i?(console.log(chalk.green.bold(` Welcome back, ${r.userName}!`)),console.log(chalk.gray(` Connected to ${r.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 90+ 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(" · ")+S()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):y?(Qo(ae)||Ho(ae,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${ae}`)),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 90+ 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 · ")+S()+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 · 90+ CTF tools · 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 90+ 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 · ")+S()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}const ee=o=>{o.exitOverride(),o.configureOutput({writeErr:o=>{const e=o.replace(/^error:\s*/i,"").trim();e&&console.log(chalk.yellow(` ${e}`))},writeOut:o=>{console.log(o)}});for(const e of o.commands)ee(e)};ee(e);const pe=o({input:process.stdin,output:process.stdout,prompt:ne(),terminal:!0,completer:ge});O(pe),Ao(!1!==m().bracketedPaste);let he=!1;if(I(!0),xo(),s&&(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()),Lo()){const o=m().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=>{pe.question(chalk.white(" > "),e=>o(e.trim()))})).toLowerCase()&&(d({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()}Oo()&&Eo(()=>pe.prompt());let we=null;const fe=pe.prompt.bind(pe);pe.prompt=o=>{if(!(N()||M()||_()||R()||W()||Po()||q()||(pe.setPrompt(ne()),o)))try{for(const o of ao()){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=K();o&&o!==we?(console.log(o),we=o):o||(we=null)}catch{}fe(o)};const be=G();be&&(console.log(chalk.cyan(" ↻ Continue where you left off: ")+chalk.white(be.label)+(be.urgent?chalk.yellow(" (exam timer running)"):"")),console.log(chalk.gray(" type ")+chalk.cyan("resume")+chalk.gray(" to jump back in.")),console.log()),Ro(te(Xo)),pe.prompt(),pe.on("line",async o=>{if(he)return;let n=Io(o.trim());if(!n)return pe.setPrompt(N()?chalk.magenta("icoa ai4ctf> "):ne()),void pe.prompt();if(/^icoa\s+\S/i.test(n)&&(n=n.replace(/^icoa\s+/i,"")),n.startsWith("/")&&!n.startsWith("//")){const o=n.slice(1).split(/\s+/)[0].toLowerCase(),t=n.slice(1+o.length).trim();if("ai"===o)return he=!0,await async function(o,e){if(N())return void(o?await z(o):console.log(chalk.gray(" You are already in the AI chat — just type your message.")));if(M())return void(o?await F(o):console.log(chalk.gray(" You are already in the CTF4AI target chat — just type your message.")));if(_())return void(o?await U(o):console.log(chalk.gray(" You are already in the Embodied-AI chat — just type your message.")));vo(o?`/ai ${o}`:"/ai");const t=process.exit;process.exit=()=>{throw new Error(se)};try{await e.parseAsync(["node","icoa","ai4ctf"])}catch(o){if(!(o instanceof Error&&o.message===se))throw o}finally{process.exit=t}o&&N()&&await z(o)}(t,e),he=!1,pe.setPrompt(N()?chalk.magenta("icoa ai4ctf> "):ne()),void pe.prompt();const a=N()||M()||_()||R()||W()||Po();a||"help"!==o&&"?"!==o||t?!a&&ie.includes(o)&&(n=n.slice(1)):n="?"}if("resume"===n.toLowerCase()){const o=G();return o?(vo(`resume → ${o.command.join(" ")}`),he=!0,await me(e),he=!1,pe.setPrompt(N()?chalk.magenta("icoa ai4ctf> "):ne()),void pe.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(" (free demo).")),console.log(),void pe.prompt())}const l=N()||M()||_()||R()||W();if(!l&&("bg"===n.toLowerCase()||/^bg\s/i.test(n))){const o=n.replace(/^bg\s*/i,"").trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("bg <command>")+chalk.gray(" — run a non-interactive shell command in the background.")),console.log(chalk.gray(" e.g. ")+chalk.cyan("bg nmap -p- 10.0.0.5")+chalk.gray(" · view: ")+chalk.cyan("tasks")),console.log(),void pe.prompt();const e=ko(),t=fo(o);bo({cwd:e,input:`bg ${o}`,riskFlags:t}),t.length>0&&H()&&console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`));const a=oo(o,e);return console.log(),console.log(chalk.cyan(` ▸ background task #${a.id} started`)+chalk.gray(` (${so()} running)`)),console.log(chalk.gray(" ")+chalk.white(o)),console.log(chalk.gray(" view: ")+chalk.cyan("tasks")+chalk.gray(" · output: ")+chalk.cyan(`tasks ${a.id}`)),console.log(),void pe.prompt()}if(!l&&("tasks"===n.toLowerCase()||/^tasks\s/i.test(n))){const o=n.replace(/^tasks\s*/i,"").trim(),e=to();if(console.log(),o){const e=no(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),a=o.cmd.length>48?`${o.cmd.slice(0,45)}…`:o.cmd;console.log(` ${e} `+chalk.white(`#${o.id}`)+chalk.gray(` ${n} `)+chalk.white(a))}console.log(chalk.gray(" output: ")+chalk.cyan("tasks <id>"))}return console.log(),void pe.prompt()}if(!l&&/&\s*$/.test(n)&&/^challenge\s+start\s+/i.test(n)){const o=n.replace(/\s*&\s*$/,"").trim().replace(/^challenge\s+start\s+/i,"").trim().split(/\s+/),e=o.some(o=>"-n"===o||"--new"===o),t=o.find(o=>"-n"!==o&&"--new"!==o);if(!t)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("challenge start <id> &")),console.log(),void pe.prompt();if(!g())return console.log(),console.log(chalk.red(" Not connected. ")+chalk.gray("Run ")+chalk.cyan("join <url>")+chalk.gray(" first.")),console.log(),void pe.prompt();vo(`challenge start ${t}${e?" --new":""} & (background)`);const a=eo(`challenge start ${t}`,()=>ro(t,e),o=>io(t,o));return console.log(),console.log(chalk.cyan(` ▸ background task #${a.id}: `)+chalk.white(`starting ${t}`)+chalk.gray(" — you can keep working; the connection info appears here when it is ready.")),console.log(),void pe.prompt()}if(!l&&n.startsWith("#")){const o=n.slice(1).trim();if(!o)return console.log(),console.log(chalk.gray(" Usage: ")+chalk.cyan("#<candidate answer>")+chalk.gray(" — stage a flag/answer WITHOUT submitting it. Review with ")+chalk.cyan("drafts")+chalk.gray(".")),console.log(),void pe.prompt();const e=Q(),t=e?.session?.examId??null,a=e?e._lastQ||1:null,l=co(o,t,a);return vo(`draft #${l.id} (not submitted)`),console.log(),console.log(chalk.green(` ✎ draft #${l.id} saved`)+(a?chalk.gray(` (Q${a})`):"")+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 pe.prompt()}if(!l&&("drafts"===n.toLowerCase()||/^drafts\s/i.test(n))){const o=n.replace(/^drafts\s*/i,"").trim().toLowerCase();if("clear"===o){const o=yo();return console.log(),console.log(chalk.gray(` Cleared ${o} draft${1===o?"":"s"}.`)),console.log(),void pe.prompt()}const e=o.match(/^(?:rm|remove|del|delete)\s+(\d+)$/);if(e){const o=mo(Number(e[1]));return console.log(),console.log(o?chalk.gray(` Removed draft #${e[1]}.`):chalk.yellow(` No draft #${e[1]}.`)),console.log(),void pe.prompt()}const t=Q(),a=go(t?.session?.examId??null);if(console.log(),0===a.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 a){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 pe.prompt()}if("menu"===n||"menu confirm"===n)return H()&&"menu confirm"!==n?(console.log(),console.log(chalk.yellow(" Real exam active. Progress is auto-saved.")),console.log(chalk.gray(" To return to main menu anyway, type ")+chalk.white("menu confirm")),console.log(),void pe.prompt()):void T(pe);if(N()){he=!0;const o=await z(n);return he=!1,"exit"===o&&pe.setPrompt(ne()),void pe.prompt()}if(M()){he=!0;const o=await F(n);return he=!1,"exit"!==o&&"solved"!==o||pe.setPrompt(ne()),void pe.prompt()}if(_()){he=!0;const o=await U(n);return he=!1,"exit"===o&&pe.setPrompt(ne()),pe.setPrompt(_()?chalk.bold.cyan("icoa ctf4eai> "):ne()),void pe.prompt()}if(vo(n),"exit"===n)return Q()?(console.log(),console.log(chalk.yellow(" ⚠ An exam is in progress.")),console.log(chalk.white(" To return to menu without losing progress, type: ")+chalk.bold.cyan("back")),console.log(chalk.white(" To fully close ICOA CLI, type: ")+chalk.bold.cyan("quit")),console.log(chalk.gray(" Your progress is auto-saved either way.")),console.log(),void pe.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"===Xo&&de(),void pe.prompt());if("quit"===n||"q"===n||"quit confirm"===n){const o=Q();return o&&"demo-free"!==o.session.examId&&"quit confirm"!==n?(console.log(),console.log(chalk.yellow(" ⚠ A real exam is in progress.")),console.log(chalk.gray(" Your answers are auto-saved on the server, but the exam timer keeps ticking")),console.log(chalk.gray(" on the server side even if you close the CLI.")),console.log(),console.log(chalk.white(" To leave the CLI but keep the exam alive, type: ")+chalk.bold.cyan("back")),console.log(chalk.gray(" (recommended — you can resume with ")+chalk.cyan("exam q 1")+chalk.gray(" after relaunching icoa)")),console.log(),console.log(chalk.white(" To really close ICOA CLI, type: ")+chalk.bold.cyan("quit confirm")),console.log(),void pe.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(),$o(),So(),lo(),x(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),uo(),void c(0))}if("back"===n){const o=Q(),e=o&&"demo-free"!==o.session.examId,t=o&&"demo-free"===o.session.examId&&(()=>{const e=new Date(o.session.startedAt||0).getTime();return Date.now()-e<18e5})();if(e)console.log(),console.log(chalk.gray(" Exam paused. Your progress is saved.")),console.log(chalk.white(" Resume: exam q 1")+chalk.gray(" · ")+chalk.white("exam review")+chalk.gray(" · ")+chalk.white("exam submit")),console.log();else if(t){const e=Object.keys(o.answers).length,t=o.session.questionCount;console.log(),console.log(chalk.gray(` Demo paused (${e}/${t} answered). Resume with: `)+chalk.white("exam q 1")),console.log(chalk.gray(" Or type ")+chalk.white("demo")+chalk.gray(" to restart.")),console.log()}else{if(o&&"demo-free"===o.session.examId){const{clearExamState:o}=await import("./lib/exam-state.js");o("demo-free"),Bo("exam-demo")}const e=m();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"===Xo?de():console.log(chalk.gray(" Already at main menu."))}return void pe.prompt()}if("help"===n||"?"===n||"guide"===n||"help all"===n.toLowerCase()){const o="guide"===n||"help all"===n.toLowerCase();if(Q()){if("help"===n){he=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return he=!1,void pe.prompt()}return _o(o?"guide":"help"),void pe.prompt()}return"root"!==Uo()?.id&&Ro(te(Xo),{quiet:!0}),o?Zo():Yo(),void pe.prompt()}if("man"===n||"manual"===n)return ue(f(),Xo),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 pe.prompt();if(/^(?:man|manual)\s+\S/i.test(n))return P(n.replace(/^(?:man|manual)\s+/i,"")),void pe.prompt();if("more help"===n.toLowerCase()&&Q()){he=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return he=!1,void pe.prompt()}if("continue"===n.toLowerCase())return console.log(),console.log(chalk.green.bold(" ═══ AI4CTF — AI as Your Teammate ═══")),console.log(),console.log(chalk.white(" In AI4CTF, you solve cybersecurity challenges")),console.log(chalk.white(" with AI by your side.")),console.log(),console.log(chalk.white(" In this demo, your AI teammate gives help at 3 levels:")),console.log(chalk.yellow(" hint a")+chalk.gray(" General guidance")),console.log(chalk.yellow(" hint b")+chalk.gray(" Deep analysis")),console.log(chalk.yellow(" hint c")+chalk.gray(" Critical assist")),console.log(),console.log(chalk.white(" Try it now! Type: ")+chalk.bold.green("ai4ctf")),console.log(chalk.gray(' Chat freely with your AI teammate. Type "exit" when done.')),console.log(),console.log(chalk.gray(" After ai4ctf, try: ")+chalk.bold.red("ctf4ai")+chalk.gray(' — trick the AI into saying "koala"')),console.log(),void pe.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(n.trim())){he=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim()])}catch{}return he=!1,void pe.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(n.trim())){he=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim().toUpperCase()])}catch{}return he=!1,void pe.prompt()}const s=n.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(s){he=!0;try{await e.parseAsync(["node","icoa","exam","token",s[1].toUpperCase()])}catch{}return he=!1,void pe.prompt()}const r=n.match(/^exam\s+([A-Z]{2,3})$/i);if(r){he=!0;try{await e.parseAsync(["node","icoa","exam","list",r[1]])}catch{}return he=!1,void pe.prompt()}const i=n.match(/^exam\s+(\S+)$/i);if(i&&!ce.has(i[1].toLowerCase())){const o=i[1].toUpperCase(),{normalizeTokenBody:t}=await import("./lib/token-format.js"),n=t(o),a=/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/;if(console.log(),a.test(n)){console.log(chalk.yellow(` Corrected look-alike characters: ${o} → ${n}`)),he=!0;try{await e.parseAsync(["node","icoa","exam","token",n])}catch{}return he=!1,void pe.prompt()}return console.log(chalk.red(` ✗ Not a valid exam token: ${o}`)),console.log(),console.log(chalk.gray(" An exam token is ")+chalk.bold.white("2 letters + 8 characters")+chalk.gray(" (e.g. ")+chalk.bold.yellow("AUHXP7SWMM")+chalk.gray(`) — yours is ${o.length}.`)),console.log(chalk.gray(" Check for 0/O, 1/I/L, V/U mix-ups, or ask your country team leader.")),console.log(),console.log(chalk.gray(" No token yet? Try ")+chalk.bold.green("demo")+chalk.gray(" (free practice paper) or ")+chalk.bold.green("exam nations")+chalk.gray(" to see participating countries.")),console.log(),void pe.prompt()}if("clear"===n||"cls"===n)return console.clear(),void pe.prompt();if("news"===n)return Oo()?jo():console.log(chalk.gray(" No competition joined. Use ")+chalk.white("join <url>")+chalk.gray(".")),void pe.prompt();if("memo"===n){if(!Oo())return console.log(chalk.gray(" Join a competition first: ")+chalk.white("join <url>")),void pe.prompt();he=!0;try{await Mo()}catch{}return void(he=!1)}const d=zo()||No(m().userName||"");if("jury"===n&&d){he=!0;try{await Fo()}catch{}return void(he=!1)}if(d&&zo()&&"scoreboard"===n.split(/\s+/)[0]){he=!0;try{const o=await Do();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 he=!1,void pe.prompt()}if(d&&Lo()){const o=n.split(/\s+/)[0];if(["challenges","open","submit","hint"].includes(o))return console.log(),console.log(chalk.yellow(" Team-leader account — the challenge bracket is not available here.")),console.log(chalk.gray(" Available: ")+chalk.white("scoreboard")+chalk.gray(" · ")+chalk.white("news")+chalk.gray(" · ")+chalk.white("jury")+chalk.gray(" · ")+chalk.white("time")+chalk.gray(" · ")+chalk.white("status")+chalk.gray(" · ")+chalk.white("logout")),console.log(),void pe.prompt()}if(n.startsWith("activate ")){const o=n.slice(9).trim(),e=await b(o);return"ok"===e?console.log(chalk.green(" Access granted! Token bound to this device.")):"network"===e?(console.log(),console.log(chalk.red(" Could not reach the activation server.")),console.log(chalk.gray(" Activation needs internet once — check your connection to ")+chalk.cyan("practice.icoa2026.au")+chalk.gray(" and run the same command again."))):"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 pe.prompt()}if("activate"===n)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void pe.prompt();const y=Q();if(y){const o=n.toUpperCase().trim(),t=o=>{const e=y.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},a=o=>{const e=y.questions.find(e=>e.number===o);return"short_answer"===e?.type},l=o=>{const e="demo-free"!==y.session.examId,t=y.questions.find(e=>e.number===o),n=J(t?.type,e);console.log(),console.log(chalk.yellow(` Q${o} is a practical question — letters (A/B/C/D) don't apply here.`)),n?(console.log(chalk.white(" Enter the AI chat for this question: ")+chalk.bold.cyan(n)),console.log(chalk.gray(" Or submit a flag directly: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`))):console.log(chalk.gray(" Submit a flag: ")+chalk.green(`exam answer ${o} ICOA{your_flag}`)),console.log()};if(/^[ABCDE]$/.test(o)){const n=y._lastQ||1;if(t(n))return l(n),void pe.prompt();if(a(n))return console.log(),console.log(chalk.yellow(` Q${n} is a short-answer question — type a number, not a letter.`)),console.log(chalk.gray(" Example: ")+chalk.green("42")+chalk.gray(" (or ")+chalk.green(`exam answer ${n} 42`)+chalk.gray(")")),console.log(),void pe.prompt();he=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(n),o])}catch{}return he=!1,void pe.prompt()}if(/^-?\d+$/.test(o)){const t=y._lastQ||1;if(a(t)){he=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(t),o])}catch{}return he=!1,void pe.prompt()}}const s=o.match(/^(\d+)\s+([ABCDE]|-?\d+)$/);if(s){const o=parseInt(s[1],10);if(t(o))return l(o),void pe.prompt();he=!0;try{await e.parseAsync(["node","icoa","exam","answer",s[1],s[2]])}catch{}return he=!1,void pe.prompt()}}const u=n.split(/\s+/)[0].toLowerCase(),p=/^python3?(\.\d+)?$/.test(u),h="ls"===u||"pwd"===u||"tmux"===u,w=n.startsWith("!")||u.startsWith("!")||p||h,C=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"]),A=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${n}`)),console.log()};if("py"===u||"pylist"===u)return console.log(chalk.yellow(` ${u} is the learn-card Python scratchpad — it lives inside learn.`)),console.log(chalk.gray(" Open your course first: ")+chalk.bold.cyan("learn <TOKEN>")+chalk.gray(" (or bare ")+chalk.bold.cyan("learn")+chalk.gray(" for the demo), then type ")+chalk.bold.cyan("py"===u?"/py":"/pylist")+chalk.gray(" on any card.")),console.log(),void pe.prompt();if("embodied"===Xo&&!w&&!["doctor","upgrade","update","type","demo2","demo3","learn","exam","ctf4eai","ctf4vla","eai","arena","lang","ref","env","aienv","ipynb","kaggle","teleload","pandahelpme31","microduck","guide","board","sim"].includes(u))return C.has(u)?(A(),void pe.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 pe.prompt());if("selection"===Xo&&!w&&!["doctor","upgrade","update","type","battle","duck","python","mujoco","mojoco","setup","exam","demo","demo2","demo3","demo4","demo5","gfssm","ai4startup","retry","nations","next","prev","continue","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","aienv","ipynb","kaggle","teleload","pandahelpme31","microduck","gpufortask","guide","board","sim"].includes(u)){if(C.has(u))return A(),void pe.prompt();if(a().includes(u))console.log(chalk.gray(` ${u} isn't available on this screen.`));else{console.log(chalk.yellow(` Unknown command: ${u}`));const o=nearestCommand(u);o&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(o)+chalk.gray("?"))}if(y){const o=y._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: ")+chalk.bold.cyan("learn <TOKEN>")+chalk.gray(" · ")+chalk.bold.cyan("exam <CC>xxxxxxxx")+chalk.gray(" · ")+chalk.bold.cyan("demo")+chalk.gray(" · ")+chalk.bold.cyan("help")+chalk.gray(" · ")+chalk.bold.cyan("menu"));return console.log(),void pe.prompt()}if("organizer"===Xo&&!["doctor","upgrade","update","join","exam","demo","retry","next","prev","logout","lang","ref","ctf","mark","unmark","review","submit","tmux"].includes(u))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void pe.prompt();if(!("olympiad"!==Xo||f()&&v()||k(u)))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 pe.prompt();if(!a().includes(u)){if("tmux"===u)try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("env setup")+chalk.gray(" (full toolkit) or ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(".")),console.log(),void pe.prompt()}if(le.has(u))return console.log(chalk.yellow(` "${u}" is a shell command — the ICOA prompt isn't a shell.`)),console.log(chalk.gray(" In real-exam mode, prefix with ! to run inside the sandbox: ")+chalk.cyan(`!${n}`)),console.log(),void pe.prompt();if(/(?:^|\s)(?:\/(?!home\/|Users\/|tmp\/)|\.\.\/|~\/)/.test(n)&&!n.startsWith("cd ")){const o=/(?:^|\s)\/(?!home\/\w+\/icoa-workspace|Users\/\w+\/icoa-workspace|tmp\/)/.test(n),e=/\.\./.test(n);if(o||e)return console.log(chalk.red(" Blocked: access outside workspace is not allowed.")),console.log(chalk.gray(` Workspace: ${ae}`)),console.log(),void pe.prompt()}let o=n.startsWith("!")?n.slice(1).trim():n;if("darwin"===process.platform){const e="/opt/homebrew/opt/python@3.12/bin/python3.12";o=o.replace(/^python3?\s/,`${e} `).replace(/^(python3|python)$/,e)}else if("win32"===process.platform){const e=(()=>{try{return t("py -3 --version",{stdio:["ignore","ignore","ignore"],timeout:1500}),"py -3"}catch{}return"python"})();o=o.replace(/^python3?(\.\d+)?\s/,`${e} `).replace(/^python3?(\.\d+)?$/,e)}else{const e=(()=>{try{return t("which python3.12",{stdio:"ignore"}),"python3.12"}catch{return"python3"}})();o=o.replace(/^python\s/,`${e} `).replace(/^python$/,e)}const e=ko(),a=fo(n);bo({cwd:e,input:n,riskFlags:a}),a.length>0&&H()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${a.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=Go(Ko(),".icoa");Qo(o)||Ho(o,{recursive:!0});const e=Go(o,"python-startup.py");let t="";if(Qo(e))try{t=Vo(e,"utf-8")}catch{}return t!==oe&&Jo(e,oe),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()),he=!0;try{await wo()&&await po()?await ho(o,pe):await ye(o,pe,e)}catch{console.log(chalk.yellow(` Command failed: ${u}`))}return he=!1,console.log(),void pe.prompt()}he=!0;const $=n.trim(),I=$.toLowerCase();let E,S=null,j="";if(y)if("submit"===I)S="final";else if(I.startsWith("submit ")){let o=$.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)?(S="flag",j=o):o&&/^[ABCDE]$/i.test(o)&&(S="flag",j=o.toUpperCase())}else/^ICOA\{[^}]+\}$/i.test($)&&(S="flag",j=$);E="final"===S?["exam","submit"]:"flag"===S?["exam","answer",String(y?._lastQ||1),j]:mapCommand(n);const O="ctf"===E[0]&&"join"===E[1];O&&pe.pause(),process.exit=()=>{throw new Error(se)};try{await e.parseAsync(["node","icoa",...E])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===se);else if(e.includes("commander.unknownCommand")){const o=nearestCommand(u.split(/\s+/)[0]||u);console.log(chalk.yellow(` Unknown command: ${u}.`)),o&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(o)+chalk.gray("?")),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for the full command list."))}else e.includes("commander.missingArgument")||"commander.missingArgument"===o?.code?"submit"===u||"flag"===u?(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: ${u}`)),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=c,he=!1,O&&pe.resume()}O&&g()&&Ro(te(Xo),{mode:"full"}),N()?pe.setPrompt(chalk.magenta("icoa ai4ctf> ")):M()?pe.setPrompt(chalk.red("icoa ctf4ai> ")):_()&&pe.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),pe.prompt()}),pe.on("SIGINT",()=>{if(console.log(),N()||M())console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still in the AI chat.")),console.log(chalk.white(" Type ")+chalk.bold.cyan("exit")+chalk.white(" to leave the chat and return to the menu."));else if(Q()){const o="demo-free"!==Q().session.examId;console.log(chalk.yellow(" Ctrl+C did NOT close ICOA CLI.")),console.log(chalk.gray(` Your ${o?"exam":"demo"} is paused and every answer is auto-saved.`)),console.log(),console.log(chalk.white(" Resume: ")+chalk.cyan("exam q 1")+chalk.gray(" · Back to menu: ")+chalk.cyan("back")+chalk.gray(" · Close CLI: ")+chalk.cyan(o?"quit confirm":"quit"))}else console.log(chalk.yellow(" Ctrl+C did not close ICOA CLI — you are still at the ")+chalk.cyan("icoa>")+chalk.yellow(" prompt.")),console.log(chalk.gray(" Keep typing — ")+chalk.cyan("help")+chalk.gray(" lists commands. (Only ")+chalk.cyan("quit")+chalk.gray(" or Ctrl+D actually close the CLI.)"));console.log(),pe.prompt()}),pe.on("close",()=>{n("main-rl-close",`stdin.isTTY=${!0===process.stdin.isTTY}`),console.log(),console.log(chalk.gray(" input closed — leaving icoa. Run icoa --resume to continue.")),Co(),$o(),So(),lo(),x(),uo(),c(0)}),"1"===process.env.ICOA_AUTO_RESUME&&(delete process.env.ICOA_AUTO_RESUME,G()&&(he=!0,await me(e),he=!1,pe.setPrompt(N()?chalk.magenta("icoa ai4ctf> "):ne()),pe.prompt()))}function ye(o,t,n){return new Promise(a=>{const l=process.stdin,s=!!l.isTTY&&!!l.isRaw;if(t.pause(),l.isTTY&&"function"==typeof l.setRawMode)try{l.setRawMode(!1)}catch{}const r=e(o,{shell:!0,stdio:"inherit",cwd:n||process.cwd()}),i=()=>{if(l.isTTY&&"function"==typeof l.setRawMode&&s)try{l.setRawMode(!0)}catch{}To(),t.resume(),a()};r.on("close",e=>{if(127===e){const e=nearestCommand(o.trim().split(/\s+/)[0]??"");e&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(e)+chalk.gray("?"))}i()}),r.on("error",i)})}export function mapCommand(o){const e=o.split(/\s+/),t=e[0].toLowerCase(),n=e.slice(1);if("demo"===t&&"3"===n[0])return["demo3",...n.slice(1,3)];if("aienv"===t&&["run","python","py"].includes((n[0]??"").toLowerCase()))return L(o);if("ipynb"===t&&n.length>=1)return["ipynb",L(o).slice(1).join(" ")];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=L(o);return["connect",e[1]??n[0],e.slice(2).join(" ")]}return s(t,n)||[t,...n]}function ue(o,e="olympiad"){if(console.log(),"selection"===e||"organizer"===e)return 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();if(!o)return 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();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();for(const o of["Competition","AI Teammate","Tools","System"]){console.log(chalk.bold.white(` ${o}`));for(const e of l(o))console.log(chalk.white(` ${e.label.padEnd(20)}`)+chalk.gray(e.text)),"System"===o&&"resume"===e.label&&console.log(chalk.white(" #<candidate> ")+chalk.gray("Stage a draft answer (never auto-submits)"));"Tools"===o&&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()}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icoa-cli",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.704",
|
|
4
4
|
"description": "ICOA CLI — AI-native competition runtime of the International Cyber Olympiad in AI: learn, practise, and compete in AI & cybersecurity from the terminal (AI4CTF · CTF4AI · CTF4EAI)",
|
|
5
5
|
"author": "Charlie Zhu",
|
|
6
6
|
"type": "module",
|