icoa-cli 2.19.250 → 2.19.252
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/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.d.ts +6 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/demo2.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/hint-client.js +1 -1
- package/dist/lib/learn-curricula.js +1 -1
- package/dist/repl.js +1 -1
- package/package.json +1 -1
package/dist/commands/learn.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{createInterface as e}from"node:readline";import{spawn as o}from"node:child_process";import{getMainRl as r}from"../lib/main-rl.js";import{existsSync as n}from"node:fs";import{dirname as l,join as t}from"node:path";import{fileURLToPath as a}from"node:url";import{loadCurriculumById as c,validateEAToken as s,syncProgress as i,syncCardFeedback as u}from"../lib/learn-curricula.js";import{getConfig as d,saveConfig as g}from"../lib/config.js";import{loadLearnState as m,saveLearnState as y,newLearnState as f,updateStreak as p,markCardComplete as h,recordMCQ as b,recordCheck as w,markPracticalComplete as k,addAchievement as C}from"../lib/learn-state.js";import{renderWelcome as v,renderKnowledgeCard as A,renderMCQCard as E,renderMCQFeedback as _,renderPracticalCard as I,renderPracticalSuccess as D,renderSimDemoCard as O,renderMilestone as S,renderStatus as P,renderPhaseComplete as $,renderCurriculumComplete as T}from"../lib/learn-render.js";import{printError as L}from"../lib/ui.js";export function registerLearnCommand(M){M.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async M=>{M&&M.trim()||(console.log(),console.log(chalk.gray(" No token given — starting free 11-card demo (")+chalk.bold.green("LEARNDEMO01")+chalk.gray(").")),console.log(chalk.gray(" Full curriculum: ")+chalk.bold.yellow("learn EA|EI|AC|CA|IO|IA + 8 chars")+chalk.gray(" — token from your country team leader.")),console.log(),M="LEARNDEMO01");const j=M.trim().toUpperCase();let x=null;const N=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(j),q=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(j);if(N)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),x=await c(j);else if(q){const e=d().ctfdUrl||"https://practice.icoa2026.au";console.log(),console.log(chalk.gray(" Validating token..."));const o=await s(j,e);if(!o.ok)return L(`Token validation failed: ${o.message}`),console.log(),console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token")),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${o.curriculumId} · status: ${o.status}`)),x=await c(o.curriculumId||"LEARNDEMO01"),!x)return L(`Failed to fetch curriculum '${o.curriculumId}' from server.`),console.log(chalk.gray(" This is usually a transient network issue. Try again in a minute.")),void console.log(chalk.gray(" If it persists, check ")+chalk.cyan(e)+chalk.gray(" is reachable."))}if(!x)return L(`Unknown learn token: ${j}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("LEARNDEMO01")+chalk.gray(" free 11-card demo (anyone can use)")),console.log(chalk.gray(" ")+chalk.bold.yellow("EA|EI|AC|CA|IO|IA")+chalk.gray(" + 8 chars full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Tracks: ")+chalk.cyan("EA")+chalk.gray("=ctf4eai · ")+chalk.cyan("AC")+chalk.gray("=ai4ctf · ")+chalk.cyan("CA")+chalk.gray("=ctf4ai · ")+chalk.cyan("IO")+chalk.gray("=ioai · ")+chalk.cyan("IA")+chalk.gray("=iaio")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log();let F=m(),R=!1;F&&F.token===j?p(F):(F=f(j,x.id,x.totalCards),R=!0),y(F),v(x,F,R);const U=r(),z=null!==U,B=z?U.listeners("line").slice():[];z&&U.removeAllListeners("line");const J=z?U:e({input:process.stdin,output:process.stdout,terminal:!0}),W=()=>{J.setPrompt(chalk.bold.cyan("icoa learn> ")),J.prompt()};W();let K=null,Q=null,Z=null,G=null,V=!1,H=0;const X=(d().language||"en").toLowerCase().startsWith("zh"),Y=[];let ee=null;const oe=new Promise(e=>{ee=e}),re=()=>{const e=ee;ee=null,e?.()},ne="1"===process.env.ICOA_LEARN_EMBEDDED,le=e=>x.cards.find(o=>o.number===e),te=e=>{const o=x.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const r=x.modules.find(e=>e.number===o.number+1);return $(x,F,o,r),!0},ae=()=>{V=!0,console.log(chalk.gray(X?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},ce=()=>{const e=le(F.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":A(e,x),e.check?(Z=e.number,H=Date.now()):(h(F,e.number),y(F));break;case"mcq":E(e,x),K=e.number;break;case"practical":I(e,x),Q=e.number;break;case"sim_demo":O(e,x),h(F,e.number),y(F);break;case"milestone":S(e,x),C(F,e.badge),h(F,e.number),y(F)}};J.on("line",async e=>{const r=e.trim().toLowerCase();if(null!==G){const o=e.trim(),r=G;if(G=null,""===o)console.log(chalk.gray(X?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=d(),n=H>0?Date.now()-H:void 0;Y.push(u(j,e.ctfdUrl||"https://practice.icoa2026.au",{curriculum_id:x.id,card_number:r,feedback_text:o,time_on_card_ms:n}).catch(()=>{})),console.log(chalk.green(X?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void W()}if(V)return V=!1,ce(),void W();if(r)if("menu"!==r&&"menu confirm"!==r)if("quit"!==r&&"exit"!==r&&"q"!==r){if("status"===r)return P(x,F),void W();if("lang"===r||r.startsWith("lang ")){const e=r.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(d().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void W();const o=x.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),l="en"===n||"zh"===n&&o,t=l?n:"en";return g({language:t}),l?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(t)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Z=null,K=null,Q=null,G=null,V=!1,ce(),void W()}if("sim"===r){const e=le(F.currentCard);return e&&"sim_demo"===e.type?(function(e){const r=function(){const e=l(a(import.meta.url)),o=[t(e,"..","..","panda","mujoco-launcher.py"),t(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(n(e))return e;return null}();if(!r)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const c={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${c})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),o("python3",[r,c,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void W()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void W())}if("bookmark"===r){const e=F.currentCard;return F.bookmarks.includes(e)||F.bookmarks.push(e),y(F),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void W()}if("e"===r)return G=F.currentCard,console.log(chalk.gray(X?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void W();if("back"===r||"b"===r)return F.currentCard>1&&(F.currentCard-=1),K=null,Q=null,Z=null,y(F),ce(),void W();if(r.startsWith("card ")){const e=r.slice(5).trim(),o=parseInt(e,10);return!Number.isInteger(o)||o<1||o>x.totalCards?(console.log(chalk.yellow(` Card number must be 1..${x.totalCards}. Try: `)+chalk.bold.green("card 1")),void W()):(F.currentCard=o,K=null,Q=null,Z=null,y(F),ce(),void W())}if(null!==Z&&["y","yes","n","no"].includes(r)){const e=le(Z);if(e&&"knowledge"===e.type&&e.check){const o=r.startsWith("y")?"y":"n",n=o===e.check.answer,l=Date.now()-H;h(F,e.number),w(F,e.number,{answer:o,correct:n,submittedAt:(new Date).toISOString()}),y(F);const{renderCheckFeedback:t}=await import("../lib/learn-render.js");t(e,o,n,!1);const a=d();if(Y.push(i(j,a.ctfdUrl||"https://practice.icoa2026.au",{card_number:e.number,event_type:"check_answered",check_answer:o,check_correct:n,time_on_card_ms:l}).catch(()=>{})),Z=null,e.solution&&e.solution.length>0)return void W();if(F.currentCard<x.totalCards){const e=F.currentCard;F.currentCard+=1,y(F),te(e)?ae():ce(),W()}else T(x,F),W();return}}if(null!==K&&["a","b","c","d"].includes(r)){const e=le(K);if(e&&"mcq"===e.type){const o=r.toUpperCase(),n=o===e.answer;b(F,e.number,{answer:o,correct:n,submittedAt:(new Date).toISOString()}),h(F,e.number),y(F),_(e,o,n,F);const l=d();return Y.push(i(j,l.ctfdUrl||"https://practice.icoa2026.au",{card_number:e.number,event_type:"mcq_answered",mcq_answer:o,mcq_correct:n}).catch(()=>{})),K=null,void(n?F.currentCard<x.totalCards?(F.currentCard+=1,y(F),ce()):(T(x,F),W()):W())}}if(null!==Q){if("done"===r){const e=le(Q);if(e&&"practical"===e.type)return k(F,e.number),h(F,e.number),y(F),D(e),Q=null,void W()}if("skip"===r)return h(F,Q),y(F),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Q=null,void W()}if("ok"===r||"next"===r||"continue"===r||"n"===r){if(null!==K)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void W();if(null!==Q)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void W();if(null!==Z)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void W();const e=F.currentCard;return F.currentCard+=1,y(F),F.currentCard>x.totalCards?T(x,F):te(e)?ae():ce(),void W()}if(null!==Z)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void W();if(null!==K)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void W();if(null!==Q)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void W();console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("quit")),W()}else if(Y.length>0&&await Promise.race([Promise.allSettled(Y),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${F.streakDays} day(s)`)),console.log(),z){J.removeAllListeners("line");for(const e of B)J.on("line",e);J.prompt(),re()}else J.removeAllListeners("line"),J.close();else if(Y.length>0&&await Promise.race([Promise.allSettled(Y),new Promise(e=>setTimeout(e,3e3))]),J.removeAllListeners("line"),z||!ne){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(z?J:void 0),re()}else J.close();else W()}),z||J.on("close",async()=>{Y.length>0&&await Promise.race([Promise.allSettled(Y),new Promise(e=>setTimeout(e,5e3))]),ne?re():process.exit(0)}),ce(),W(),await oe}),M.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(` Server: ${(()=>{try{return JSON.parse(require("node:fs").readFileSync(require("node:path").join(require("node:os").homedir(),".icoa","config.json"),"utf-8")).ctfdUrl||"https://practice.icoa2026.au"}catch{return"https://practice.icoa2026.au"}})()}`)),console.log();let r=0,n=0,l=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),t=await c(e),a=Date.now()-o;if(t){const e=t.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(t).length;l+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),r++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${r} cached`)+chalk.gray(` · ${n} failed · total ${(l/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
|
1
|
+
import chalk from"chalk";import{createInterface as e}from"node:readline";import{spawn as o}from"node:child_process";import{getMainRl as r}from"../lib/main-rl.js";import{existsSync as n}from"node:fs";import{dirname as l,join as t}from"node:path";import{fileURLToPath as a}from"node:url";import{loadCurriculumById as c,validateEAToken as s,syncProgress as i,syncCardFeedback as u}from"../lib/learn-curricula.js";import{getConfig as d,saveConfig as g}from"../lib/config.js";import{loadLearnState as m,saveLearnState as y,newLearnState as f,updateStreak as p,markCardComplete as h,recordMCQ as b,recordCheck as w,markPracticalComplete as k,addAchievement as C}from"../lib/learn-state.js";import{renderWelcome as v,renderKnowledgeCard as A,renderMCQCard as E,renderMCQFeedback as _,renderPracticalCard as I,renderPracticalSuccess as D,renderSimDemoCard as S,renderMilestone as O,renderStatus as $,renderPhaseComplete as P,renderCurriculumComplete as L}from"../lib/learn-render.js";import{printError as M}from"../lib/ui.js";export function registerLearnCommand(T){T.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async T=>{T&&T.trim()||(console.log(),console.log(chalk.gray(" No token given — starting free 11-card demo (")+chalk.bold.green("LEARNDEMO01")+chalk.gray(").")),console.log(chalk.gray(" Full curriculum: ")+chalk.bold.yellow("learn EA|EI|AC|CA|IO|IA + 8 chars")+chalk.gray(" — token from your country team leader.")),console.log(),T="LEARNDEMO01");const j=T.trim().toUpperCase();let x=null;const N=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(j),q=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(j);if(N)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),x=await c(j);else if(q){const e=d().ctfdUrl||"https://practice.icoa2026.au";console.log(),console.log(chalk.gray(" Validating token..."));const o=await s(j,e);if(!o.ok)return M(`Token validation failed: ${o.message}`),console.log(),console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token")),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${o.curriculumId} · status: ${o.status}`)),x=await c(o.curriculumId||"LEARNDEMO01"),!x)return M(`Failed to fetch curriculum '${o.curriculumId}' from server.`),console.log(chalk.gray(" The full curriculum is ~3 MB; on a slow connection the download")),console.log(chalk.gray(" can take a while. Stay on a stable link and run ")+chalk.bold.yellow(`learn ${j}`)+chalk.gray(" again")),console.log(chalk.gray(" — once it loads, it is cached and opens instantly next time.")),void console.log(chalk.gray(" If it keeps failing, check ")+chalk.cyan(e)+chalk.gray(" is reachable."))}if(!x)return M(`Unknown learn token: ${j}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("LEARNDEMO01")+chalk.gray(" free 11-card demo (anyone can use)")),console.log(chalk.gray(" ")+chalk.bold.yellow("EA|EI|AC|CA|IO|IA")+chalk.gray(" + 8 chars full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Tracks: ")+chalk.cyan("EA")+chalk.gray("=ctf4eai · ")+chalk.cyan("AC")+chalk.gray("=ai4ctf · ")+chalk.cyan("CA")+chalk.gray("=ctf4ai · ")+chalk.cyan("IO")+chalk.gray("=ioai · ")+chalk.cyan("IA")+chalk.gray("=iaio")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log();let F=m(),R=!1;F&&F.token===j?p(F):(F=f(j,x.id,x.totalCards),R=!0),y(F),v(x,F,R);const U=r(),z=null!==U,B=z?U.listeners("line").slice():[];z&&U.removeAllListeners("line");const J=z?U:e({input:process.stdin,output:process.stdout,terminal:!0}),W=()=>{J.setPrompt(chalk.bold.cyan("icoa learn> ")),J.prompt()};W();let K=null,Q=null,Z=null,G=null,V=!1,H=0;const X=(d().language||"en").toLowerCase().startsWith("zh"),Y=[];let ee=null;const oe=new Promise(e=>{ee=e}),re=()=>{const e=ee;ee=null,e?.()},ne="1"===process.env.ICOA_LEARN_EMBEDDED,le=e=>x.cards.find(o=>o.number===e),te=e=>{const o=x.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const r=x.modules.find(e=>e.number===o.number+1);return P(x,F,o,r),!0},ae=()=>{V=!0,console.log(chalk.gray(X?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},ce=()=>{const e=le(F.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":A(e,x),e.check?(Z=e.number,H=Date.now()):(h(F,e.number),y(F));break;case"mcq":E(e,x),K=e.number;break;case"practical":I(e,x),Q=e.number;break;case"sim_demo":S(e,x),h(F,e.number),y(F);break;case"milestone":O(e,x),C(F,e.badge),h(F,e.number),y(F)}};J.on("line",async e=>{const r=e.trim().toLowerCase();if(null!==G){const o=e.trim(),r=G;if(G=null,""===o)console.log(chalk.gray(X?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=d(),n=H>0?Date.now()-H:void 0;Y.push(u(j,e.ctfdUrl||"https://practice.icoa2026.au",{curriculum_id:x.id,card_number:r,feedback_text:o,time_on_card_ms:n}).catch(()=>{})),console.log(chalk.green(X?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void W()}if(V)return V=!1,ce(),void W();if(r)if("menu"!==r&&"menu confirm"!==r)if("quit"!==r&&"exit"!==r&&"q"!==r){if("status"===r)return $(x,F),void W();if("lang"===r||r.startsWith("lang ")){const e=r.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(d().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void W();const o=x.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),l="en"===n||"zh"===n&&o,t=l?n:"en";return g({language:t}),l?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(t)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Z=null,K=null,Q=null,G=null,V=!1,ce(),void W()}if("sim"===r){const e=le(F.currentCard);return e&&"sim_demo"===e.type?(function(e){const r=function(){const e=l(a(import.meta.url)),o=[t(e,"..","..","panda","mujoco-launcher.py"),t(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(n(e))return e;return null}();if(!r)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const c={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${c})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),o("python3",[r,c,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void W()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void W())}if("bookmark"===r){const e=F.currentCard;return F.bookmarks.includes(e)||F.bookmarks.push(e),y(F),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void W()}if("e"===r)return G=F.currentCard,console.log(chalk.gray(X?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void W();if("back"===r||"b"===r)return F.currentCard>1&&(F.currentCard-=1),K=null,Q=null,Z=null,y(F),ce(),void W();if(r.startsWith("card ")){const e=r.slice(5).trim(),o=parseInt(e,10);return!Number.isInteger(o)||o<1||o>x.totalCards?(console.log(chalk.yellow(` Card number must be 1..${x.totalCards}. Try: `)+chalk.bold.green("card 1")),void W()):(F.currentCard=o,K=null,Q=null,Z=null,y(F),ce(),void W())}if(null!==Z&&["y","yes","n","no"].includes(r)){const e=le(Z);if(e&&"knowledge"===e.type&&e.check){const o=r.startsWith("y")?"y":"n",n=o===e.check.answer,l=Date.now()-H;h(F,e.number),w(F,e.number,{answer:o,correct:n,submittedAt:(new Date).toISOString()}),y(F);const{renderCheckFeedback:t}=await import("../lib/learn-render.js");t(e,o,n,!1);const a=d();if(Y.push(i(j,a.ctfdUrl||"https://practice.icoa2026.au",{card_number:e.number,event_type:"check_answered",check_answer:o,check_correct:n,time_on_card_ms:l}).catch(()=>{})),Z=null,e.solution&&e.solution.length>0)return void W();if(F.currentCard<x.totalCards){const e=F.currentCard;F.currentCard+=1,y(F),te(e)?ae():ce(),W()}else L(x,F),W();return}}if(null!==K&&["a","b","c","d"].includes(r)){const e=le(K);if(e&&"mcq"===e.type){const o=r.toUpperCase(),n=o===e.answer;b(F,e.number,{answer:o,correct:n,submittedAt:(new Date).toISOString()}),h(F,e.number),y(F),_(e,o,n,F);const l=d();return Y.push(i(j,l.ctfdUrl||"https://practice.icoa2026.au",{card_number:e.number,event_type:"mcq_answered",mcq_answer:o,mcq_correct:n}).catch(()=>{})),K=null,void(n?F.currentCard<x.totalCards?(F.currentCard+=1,y(F),ce()):(L(x,F),W()):W())}}if(null!==Q){if("done"===r){const e=le(Q);if(e&&"practical"===e.type)return k(F,e.number),h(F,e.number),y(F),D(e),Q=null,void W()}if("skip"===r)return h(F,Q),y(F),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Q=null,void W()}if("ok"===r||"next"===r||"continue"===r||"n"===r){if(null!==K)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void W();if(null!==Q)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void W();if(null!==Z)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void W();const e=F.currentCard;return F.currentCard+=1,y(F),F.currentCard>x.totalCards?L(x,F):te(e)?ae():ce(),void W()}if(null!==Z)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void W();if(null!==K)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void W();if(null!==Q)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void W();console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("quit")),W()}else if(Y.length>0&&await Promise.race([Promise.allSettled(Y),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${F.streakDays} day(s)`)),console.log(),z){J.removeAllListeners("line");for(const e of B)J.on("line",e);J.prompt(),re()}else J.removeAllListeners("line"),J.close();else if(Y.length>0&&await Promise.race([Promise.allSettled(Y),new Promise(e=>setTimeout(e,3e3))]),J.removeAllListeners("line"),z||!ne){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(z?J:void 0),re()}else J.close();else W()}),z||J.on("close",async()=>{Y.length>0&&await Promise.race([Promise.allSettled(Y),new Promise(e=>setTimeout(e,5e3))]),ne?re():process.exit(0)}),ce(),W(),await oe}),T.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(` Server: ${(()=>{try{return JSON.parse(require("node:fs").readFileSync(require("node:path").join(require("node:os").homedir(),".icoa","config.json"),"utf-8")).ctfdUrl||"https://practice.icoa2026.au"}catch{return"https://practice.icoa2026.au"}})()}`)),console.log();let r=0,n=0,l=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),t=await c(e),a=Date.now()-o;if(t){const e=t.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(t).length;l+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),r++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${r} cached`)+chalk.gray(` · ${n} failed · total ${(l/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerConnectCommand as t}from"./commands/connect.js";import{registerNoteCommand as i}from"./commands/note.js";import{registerLogCommand as l}from"./commands/log.js";import{registerLangCommand as a}from"./commands/lang.js";import{registerSetupCommand as m}from"./commands/setup.js";import{registerEnvCommand as c}from"./commands/env.js";import{registerAi4ctfCommand as g}from"./commands/ai4ctf.js";import{registerExamCommand as d}from"./commands/exam.js";import{registerCtf4aiDemoCommand as p}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as y}from"./commands/theme.js";import{registerLearnCommand as h}from"./commands/learn.js";import{registerCtf4VlaCommand as f}from"./commands/ctf4vla.js";import{registerDemo2Command as u}from"./commands/demo2.js";import{registerSimCommand as w}from"./commands/sim.js";import{getConfig as T,saveConfig as b}from"./lib/config.js";import{startRepl as v}from"./repl.js";import{RELAUNCH_CODE as
|
|
2
|
+
import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerConnectCommand as t}from"./commands/connect.js";import{registerNoteCommand as i}from"./commands/note.js";import{registerLogCommand as l}from"./commands/log.js";import{registerLangCommand as a}from"./commands/lang.js";import{registerSetupCommand as m}from"./commands/setup.js";import{registerEnvCommand as c}from"./commands/env.js";import{registerAi4ctfCommand as g}from"./commands/ai4ctf.js";import{registerExamCommand as d}from"./commands/exam.js";import{registerCtf4aiDemoCommand as p}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as y}from"./commands/theme.js";import{registerLearnCommand as h}from"./commands/learn.js";import{registerCtf4VlaCommand as f}from"./commands/ctf4vla.js";import{registerDemo2Command as u}from"./commands/demo2.js";import{registerSimCommand as w}from"./commands/sim.js";import{getConfig as T,saveConfig as b}from"./lib/config.js";import{startRepl as v}from"./repl.js";import{RELAUNCH_CODE as I}from"./lib/menu-nav.js";import{setTerminalTheme as $}from"./lib/theme.js";import{checkForUpdates as A}from"./lib/update-check.js";import{detectIcoaInstalls as C}from"./lib/platform.js";import{ICOA_BIG as E}from"./lib/banner.js";import{readFileSync as _}from"node:fs";import{fileURLToPath as j}from"node:url";import{dirname as S,join as x}from"node:path";const L=S(j(import.meta.url)),N=JSON.parse(_(x(L,"..","package.json"),"utf-8")).version,O=chalk.cyan(" ─────────────────────────────────────────────────────"),k=`\n${O}\n\n${E.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${N}`)}\n\n${O}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=o(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(s.signal){e=0;break}e=s.status,n=!0}while(e===I);process.exit(e??0)}}const F=new o;if(F.name("icoa").version(N).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").action(async o=>{const e=T();$("high-contrast"===e.themeVariant?"high-contrast":"dark"),A(),function(){const o=C();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();if(console.log(k),process.argv.length<=2||o.resume)return o.resume||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void v(F,!!o.resume)}),e(F),n(F),s(F),r(F),t(F),i(F),l(F),a(F),m(F),c(F),g(F),d(F),p(F),y(F),h(F),f(F),u(F),w(F),F.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=T().geminiModel||"gemini-2.5-flash-lite";o?(b({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}F.parse();
|
package/dist/lib/hint-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(a,b){const v=a0b,c=a();while(!![]){try{const d
|
|
1
|
+
(function(a,b){const v=a0b,c=a();while(!![]){try{const d=-parseInt(v(0x138))/(-0x80a+-0x1*0xc07+-0x1412*-0x1)+parseInt(v(0x11f))/(-0xe4b*0x2+0xaca*-0x3+-0x1cb*-0x22)*(-parseInt(v(0x13d))/(-0x1587+-0x1*-0xc3d+0x94d))+-parseInt(v(0x128))/(0x304*-0x3+0x1*0xbc9+-0x2b9)+parseInt(v(0x120))/(0x14a2+-0x1821+0x384)*(parseInt(v(0x137))/(0xe79+-0xb1f+-0x354))+-parseInt(v(0x136))/(0x513*0x7+0x113c+-0x31a*0x11)+parseInt(v(0x125))/(0x1*0x2273+-0x5*0x24+-0x3*0xb3d)*(parseInt(v(0x124))/(-0xaf*0x31+0x2*-0x117e+0x4484))+parseInt(v(0x12e))/(-0x23d5*-0x1+-0x2072+0x1*-0x359);if(d===b)break;else c['push'](c['shift']());}catch(e){c['push'](c['shift']());}}}(a0a,-0xe2307+-0x5fefc+0x21dacb*0x1));function a0a(){const x=['oeLqrxrHsa','DgLTzw91Da','Ahr0Chm6lY9WCMfJDgLJzs5Py29HmJaYnI5HDq','ndu3mJiZmLnHrhHHzG','BgfUzW','CxvLC3rPB24','DgLTzw91De1Z','AwnVys1JBgK','l2fWAs9Py29Hl2v4yw1ZlW','ndG0odeWntbJwfLnruS','y2f0y2G','y3rMzfvYBa','BgfUz3vHz2u','AgLUDcbYzxf1zxn0igzHAwXLzcaO','Dg9Rzw4','zgf0yq','zxHHBuLK','nZyZmtqYofrMreHQta','mZbnt0Dcs0e','odKYotuZDLnhwMDA','Bgv2zwW','ue9tva','C3rYAw5NAwz5','ANnVBG','nLHTy1HpDW','C3vJy2vZCW','B2jQzwn0','mtm4ndyYnLjAtLL1BG','mJG1mteWwhv3tKzl','BwvZC2fNzq','oJKWotaVyxbPl2LJB2eVzxHHBxmV','C3rHDhvZ','mJq5mJa4mKvurgH5vq'];a0a=function(){return x;};return a0a();}function a0b(a,b){a=a-(0xd*0xb1+-0x9d*0x1d+0x9eb*0x1);const c=a0a();let d=c[a];if(a0b['KXlquZ']===undefined){var e=function(i){const j='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';let l='',m='';for(let n=-0x2041+-0x1890+0x38d1,o,p,q=0x17c4+-0x429+0x139b*-0x1;p=i['charAt'](q++);~p&&(o=n%(-0x168d+-0x144c*0x1+0x2add)?o*(-0x252a+-0x1*0x1b83+0x40ed)+p:p,n++%(0x1e52+-0x1365+-0x85*0x15))?l+=String['fromCharCode'](0x9a*0xa+-0x2688+0x2183*0x1&o>>(-(-0x23*0x10d+0x1a6d+0xd*0xcc)*n&0x14e*0x1d+0x1df5*-0x1+-0x1*0x7db)):-0x1225+0x234f+0xa9*-0x1a){p=j['indexOf'](p);}for(let r=-0x56b+-0x1*-0x1c51+-0x16e6,s=l['length'];r<s;r++){m+='%'+('00'+l['charCodeAt'](r)['toString'](-0x1f5a+0x22c3+0x1*-0x359))['slice'](-(0x3*0x513+0x3d*0x4f+0x1105*-0x2));}return decodeURIComponent(m);};a0b['JYNXHe']=e,a0b['cKZXDg']={},a0b['KXlquZ']=!![];}const f=c[-0x376*0x9+0x7*0xd9+0x1*0x1937],g=a+f,h=a0b['cKZXDg'][g];return!h?(d=a0b['JYNXHe'](d),a0b['cKZXDg'][g]=d):d=h,d;}import{getConfig as a0c}from'./config.js';export async function requestHint(d){const w=a0b,f=a0c(),g=f[w(0x130)]||w(0x127),h=d[w(0x129)]||f[w(0x131)]||'en',j=d[w(0x12b)]??-0x339b+-0x274d+0x7a28,k=[g+w(0x12d)+d['examId']+'/hint',g+w(0x122)+d[w(0x135)]+'/hint'];let l=null;for(const p of k)try{const q=await fetch(p,{'method':w(0x13a),'headers':{'Content-Type':'application/json','User-Agent':w(0x12c)},'body':JSON[w(0x13b)]({'token':d[w(0x133)],'question':d[w(0x12a)],'level':d[w(0x139)],'lang':h}),'signal':AbortSignal[w(0x126)](j)}),r=await q[w(0x13c)]()[w(0x12f)](()=>({}));if(!q['ok']||!(0x17c4+-0x429+0x139a*-0x1)===r[w(0x13e)]){if(l={'status':q[w(0x123)],'message':r?.[w(0x121)]||w(0x132)+q[w(0x123)]+')'},q[w(0x123)]>=-0x168d+-0x144c*0x1+0x2c69&&q['status']<-0x252a+-0x1*0x1b83+0x42a1)throw l;continue;}return r[w(0x134)];}catch(u){if(u&&w(0x13f)==typeof u&&w(0x123)in u)throw u;l={'status':0x0,'message':u?.[w(0x121)]||'network\x20error'};}const m={};m[w(0x123)]=0x0,m[w(0x121)]='hint\x20API\x20unreachable';throw l||m;}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export function localized(t,e){if(!e.startsWith("zh")||!t._zh)return t;const r=t._zh,n={...t};for(const t of Object.keys(r))void 0!==r[t]&&(n[t]=r[t]);return n}import{readFileSync as t,writeFileSync as e,mkdirSync as r,existsSync as n,statSync as c,utimesSync as a}from"node:fs";import{join as o}from"node:path";import{homedir as i}from"node:os";const s=o(i(),".icoa","learn-cache");function u(t){const e=t.replace(/[^A-Za-z0-9_-]/g,"_");return o(s,`${e}.json`)}function l(t){const e=t.replace(/[^A-Za-z0-9_-]/g,"_");return o(s,`${e}.etag`)}export async function loadCurriculumById(d){"ctf4eai-12"===d&&(d="LEARNDEMO01");const f=function(e){const r=u(e);if(!n(r))return null;try{const e=c(r),n=Date.now()-e.mtimeMs;return{curriculum:JSON.parse(t(r,"utf-8")),ageMs:n}}catch{return null}}(d);if(f&&f.ageMs<6048e5)return f.curriculum;const m=await async function(e){const r=function(){try{const e=JSON.parse(t(o(i(),".icoa","config.json"),"utf-8"));if("string"==typeof e.ctfdUrl&&e.ctfdUrl)return e.ctfdUrl}catch{}return"https://practice.icoa2026.au"}().replace(/\/$/,"")+"/api/icoa/learn/curriculum/"+encodeURIComponent(e),c={},a=function(e){const r=l(e);if(!n(r))return null;try{return t(r,"utf-8").trim()||null}catch{return null}}(e);a&&(c["If-None-Match"]=a);try{const t=await fetch(r,{headers:c,signal:AbortSignal.timeout(
|
|
1
|
+
export function localized(t,e){if(!e.startsWith("zh")||!t._zh)return t;const r=t._zh,n={...t};for(const t of Object.keys(r))void 0!==r[t]&&(n[t]=r[t]);return n}import{readFileSync as t,writeFileSync as e,mkdirSync as r,existsSync as n,statSync as c,utimesSync as a}from"node:fs";import{join as o}from"node:path";import{homedir as i}from"node:os";const s=o(i(),".icoa","learn-cache");function u(t){const e=t.replace(/[^A-Za-z0-9_-]/g,"_");return o(s,`${e}.json`)}function l(t){const e=t.replace(/[^A-Za-z0-9_-]/g,"_");return o(s,`${e}.etag`)}export async function loadCurriculumById(d){"ctf4eai-12"===d&&(d="LEARNDEMO01");const f=function(e){const r=u(e);if(!n(r))return null;try{const e=c(r),n=Date.now()-e.mtimeMs;return{curriculum:JSON.parse(t(r,"utf-8")),ageMs:n}}catch{return null}}(d);if(f&&f.ageMs<6048e5)return f.curriculum;const m=await async function(e){const r=function(){try{const e=JSON.parse(t(o(i(),".icoa","config.json"),"utf-8"));if("string"==typeof e.ctfdUrl&&e.ctfdUrl)return e.ctfdUrl}catch{}return"https://practice.icoa2026.au"}().replace(/\/$/,"")+"/api/icoa/learn/curriculum/"+encodeURIComponent(e),c={},a=function(e){const r=l(e);if(!n(r))return null;try{return t(r,"utf-8").trim()||null}catch{return null}}(e);a&&(c["If-None-Match"]=a);try{const t=await fetch(r,{headers:c,signal:AbortSignal.timeout(6e4)});if(304===t.status)return{kind:"unchanged"};if(!t.ok)return{kind:"error"};const e=await t.json();if(!e.success||!e.data)return{kind:"error"};const n=t.headers.get("etag")||t.headers.get("ETag")||void 0;return{kind:"fresh",curriculum:e.data,etag:n||void 0}}catch{return{kind:"error"}}}(d);return"fresh"===m.kind?(function(t,n,c){try{r(s,{recursive:!0}),e(u(t),JSON.stringify(n)),c&&e(l(t),c)}catch{}}(d,m.curriculum,m.etag),m.curriculum):"unchanged"===m.kind&&f?(function(t){try{const e=u(t);if(n(e)){const t=Date.now()/1e3;a(e,t,t)}}catch{}}(d),f.curriculum):f?f.curriculum:null}export function loadCurriculum(t){return null}export async function validateEAToken(t,e){const r=e.replace(/\/$/,"")+"/api/icoa/learn/validate";try{const e=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t.toUpperCase()}),signal:AbortSignal.timeout(8e3)});if(!e.ok)return{ok:!1,message:(await e.json().catch(()=>({}))).message||`HTTP ${e.status}`};const n=await e.json();return n.success&&n.data?{ok:!0,curriculumId:n.data.curriculum_id,status:n.data.status,validUntil:n.data.valid_until}:{ok:!1,message:n.message||"Validation failed"}}catch(t){return{ok:!1,message:`Network error: ${t instanceof Error?t.message:String(t)}`}}}export async function syncProgress(t,e,r){if("LEARNDEMO01"===t.toUpperCase())return;const n=e.replace(/\/$/,"")+"/api/icoa/learn/progress/"+t.toUpperCase();try{await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({card_number:r.card_number,event_type:r.event_type,mcq_answer:r.mcq_answer,mcq_correct:r.mcq_correct?1:0,check_answer:r.check_answer,check_correct:r.check_correct?1:0,time_on_card_ms:r.time_on_card_ms}),signal:AbortSignal.timeout(5e3)})}catch{}}export async function syncCardFeedback(t,e,r){const n=e.replace(/\/$/,"")+"/api/icoa/learn/feedback/"+t.toUpperCase();try{await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({curriculum_id:r.curriculum_id,card_number:r.card_number,feedback_text:r.feedback_text,time_on_card_ms:r.time_on_card_ms}),signal:AbortSignal.timeout(5e3)})}catch{}}
|
package/dist/repl.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInterface as o}from"node:readline";import{spawn as e,execSync as l}from"node:child_process";import chalk from"chalk";import{isConnected as n,getConfig as t,saveConfig as a}from"./lib/config.js";import{isActivated as s,activateToken as r,isFreeCommand as i,isDeviceMatch as c,recordExit as g,recordResume as y,isFirstRunOrUpgrade as m,markVersionSeen as d}from"./lib/access.js";import{setReplMode as p}from"./lib/ui.js";import{returnToMainMenu as u,printMenuHint as h,menuHintInline as w}from"./lib/menu-nav.js";import{setMainRl as f}from"./lib/main-rl.js";import{isChatActive as b,handleChatMessage as x}from"./commands/ai4ctf.js";import{isCtf4aiActive as v,handleCtf4aiMessage as C}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as A,handleCtf4VlaMessage as I}from"./commands/ctf4vla.js";import{isDemo2Active as k}from"./commands/demo2.js";import{loadDemo2Progress as T}from"./lib/demo2-progress.js";import{hasAnySimHistory as E,lastArmAt as S,lastBundledAt as O,lastSimAt as $}from"./lib/sim-cooldown.js";import{getExamState as D,getRealExamState as L,getDemoState as R}from"./lib/exam-state.js";import{resetTerminalTheme as j}from"./lib/theme.js";import{ensureSandbox as N,runInSandbox as P,isDockerAvailable as q}from"./lib/sandbox.js";import{checkShellRisk as F,logShellAudit as M,getActiveCwd as B}from"./lib/exam-sandbox.js";import{logCommand as _}from"./lib/logger.js";import{startLogSync as U,stopLogSync as Q}from"./lib/log-sync.js";import{existsSync as W,mkdirSync as X,writeFileSync as Y}from"node:fs";import{join as z}from"node:path";import{homedir as V}from"node:os";const G=Date.now();function J(){return L()?chalk.cyan("icoa exam> "):function(){const o=R();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=G}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const H=z(V(),"icoa-workspace"),K=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),Z="__REPL_NO_EXIT__",oo="2.5.1";function eo(){console.log(),console.log(` ${chalk.cyan.bold("🎯 ICOA 2026 · National Selection")}`),console.log(),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("ACxxxxxxxx")+chalk.gray(" → ai4ctf-12 (AI as your CTF teammate)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("CAxxxxxxxx")+chalk.gray(" → ctf4ai-12 (red-team software AI)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("EAxxxxxxxx")+chalk.gray(" → ctf4eai-12 (red-team embodied AI)")),console.log(" "+chalk.bold.cyan("exam ")+chalk.white("<CC>xxxxxxxx")+chalk.gray(" → Paper A/B/C/D/E (country exam token)")),console.log(" "+chalk.bold.cyan("demo")+chalk.gray(" → free practice")),console.log(" "+chalk.bold.cyan("lang")+chalk.white(" es")+chalk.gray(" → switch language")),console.log(" "+chalk.gray("help · menu · quit")),console.log()}export async function startRepl(e,R){process.env.ICOA_INSIDE_REPL="1";const G=t(),to=n(),ao=process.exit.bind(process),so=s();if(G.demoCleanedForVersion!==oo){try{const{existsSync:o,unlinkSync:e}=await import("node:fs"),{join:l}=await import("node:path"),{getIcoaDir:n}=await import("./lib/config.js"),t=l(n(),"demo-state.json");o(t)&&e(t)}catch{}a({demoCleanedForVersion:oo})}const{select:ro,confirm:io}=await import("@inquirer/prompts"),co=G.mode||"",go=""===co?"instant":["instant","learn","selection","olympiad"].includes(co)?co:"selection",yo=[{name:` ${chalk.bold("⚡ Try ICOA in 30 seconds")} ${chalk.gray("—")} ${chalk.gray("watch · no token needed")}`,value:"instant"},{name:` ${chalk.bold("🧠 Learn")} ${chalk.gray("—")} ${chalk.gray("AC / CA / EA token · skill up")}`,value:"learn"},{name:` ${chalk.bold("🎯 National Selection")} ${chalk.gray("—")} ${chalk.gray("country exam token · aim for finals")}`,value:"selection"},{name:` ${chalk.bold("🏆 International Olympiad")} ${chalk.gray("—")} ${chalk.gray("finals stage · Sydney 2026 · full sandbox")}`,value:"olympiad"},{name:` ${chalk.gray("ℹ️ About ICOA")} ${chalk.gray("·")} ${chalk.gray("what this is · how to join")}`,value:"about"}];console.log(chalk.gray(" Type ")+chalk.bold.cyan("menu")+chalk.gray(" from anywhere to return here.")),console.log();let mo="";for(;!mo;){let o;try{o=await ro({message:"Mode",choices:yo,default:go||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}"about"!==o?mo=o:(console.clear(),console.log(),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(chalk.bold.yellow(" ICOA")+chalk.white(" — AI-Native CLI OS for Cyber & AI Security")),console.log(chalk.gray(" Olympiad & Competition · K-12 to University")),console.log(chalk.cyan(" ───────────────────────────────────────────────────")),console.log(),console.log(chalk.bold.white(" What Makes ICOA Different")),console.log(chalk.gray(" · AI-native AI teammate, AI adversary, AI translation")),console.log(chalk.gray(" · CLI OS Complete competition environment in terminal")),console.log(chalk.gray(" · 110 tools pwntools, z3, gdb, nmap, sleuthkit... pre-configured")),console.log(chalk.gray(" · Global scale 15,000+ concurrent exams · 15 languages")),console.log(),console.log(chalk.bold.white(" Competition Format (2-day standard + 1-day Pioneer)")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" [Day 1] AI as teammate — speed track, dynamic decay + top-3 bonus")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" [Day 2] AI as target — knowledge track, static value per challenge")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" [Pioneer / Practical Round] Embodied AI — VLA + world models + sim-to-real")}`),console.log(),console.log(chalk.bold.white(" Scoring (in brief)")),console.log(chalk.gray(" · Standard medals: AI4CTF + CTF4AI combined · 1/12 Gold · 2/12 Silver · 3/12 Bronze")),console.log(chalk.gray(" · HMA: top 50% on either day, total below bronze cutoff")),console.log(chalk.gray(" · CTF4EAI: separate 15-finalist pool, G/S/B + 12 Finalist Awards")),console.log(),console.log(chalk.white(" Sydney, Australia")+chalk.gray(" · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.bold.white(" Organized by")+chalk.gray(" ASRA (Australia) · ICO Foundation Inc")),console.log(chalk.bold.white(" Contact ")+chalk.cyan(" australia@icoa2026.au · accreditation@icoa2026.au")),console.log(chalk.bold.white(" Website ")+chalk.cyan.underline(" https://icoa2026.au")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(),console.log(chalk.gray(" Press ")+chalk.yellow("Enter")+chalk.gray(" to return...")),await new Promise(o=>{const e=l=>{process.stdin.removeListener("data",e),process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!1),process.stdin.pause(),o()};process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.once("data",e)}),console.clear())}if("olympiad"===mo&&"olympiad"!==go){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await io({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(mo="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(mo!==go&&a({mode:mo}),console.log(),"olympiad"===mo&&m(oo)){d(oo),console.log(chalk.gray(" Checking competition environment..."));const{execSync:o}=await import("node:child_process"),e=[{name:"pwntools",cmd:'python3 -c "import pwn"'},{name:"z3-solver",cmd:'python3 -c "import z3"'},{name:"numpy",cmd:'python3 -c "import numpy"'},{name:"requests",cmd:'python3 -c "import requests"'}];let l=0;for(const n of e)try{o(n.cmd,{stdio:"ignore"})}catch{l++}if(l>0){console.log(chalk.yellow(` ${l} core libraries missing.`));try{const{confirm:o}=await import("@inquirer/prompts");if(await o({message:" Install competition Python libraries now?",default:!0,theme:{prefix:"",style:{message:o=>chalk.green(o),defaultAnswer:o=>chalk.green(o)}}})){console.log();const{execSync:o}=await import("node:child_process");o("icoa env setup",{stdio:"inherit"})}}catch{console.log(chalk.gray(" Run ")+chalk.white("env setup")+chalk.gray(" later to install."))}console.log()}else console.log(chalk.green(" All core libraries ready.")),console.log()}if(R){const o=y();if(o){const e=Math.floor(o.awaySeconds/60),l=o.awaySeconds%60;console.log(chalk.yellow(` Session resumed. Away: ${e}m ${l}s | Total exits: ${o.exitCount}`)),console.log()}}if("selection"===mo)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),eo();else if("embodied"===mo)!function(){console.log(chalk.cyan.bold(" [🤖 ctf4eai — Embodied AI Security]")),console.log(),console.log(chalk.bold.cyan(" CTF4VLA")+chalk.gray(" — ICOA 2026's ")+chalk.bold.white("Pioneer Round")),console.log(chalk.gray(" an independent parallel track alongside the scored main events: ")+chalk.green("AI4CTF")+chalk.gray(" (Day 1) and ")+chalk.red("CTF4AI")+chalk.gray(" (Day 2)")),console.log(),console.log(chalk.white(" Embodied AI is at its ImageNet moment.")),console.log(chalk.gray(" VLA models, MuJoCo physics, real robot arms.")),console.log(chalk.gray(" Real models, real physics, real attack surfaces.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const o=O()>0||$()>0,e=S()>0,l=E(),n=T(),t=null!==n&&"number"==typeof n.completedAt&&n.nextCardIndex>=n.totalCards,a=null!==n&&!t;if(t)console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (demo2 ✓ · sim")+(e?chalk.gray(" ✓ · sim arm ✓)"):chalk.gray(")")));else if(a){const o=`${n.nextCardIndex} / ${n.totalCards}`;console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" (last left at card ")+chalk.bold.yellow(o)+chalk.gray(")"))}else o&&e?console.log(chalk.bold.yellow(" Next up: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (sim ✓ · sim arm ✓)")):l?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(" — 8-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 (CTF4VLA) — 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(),h(),console.log()}();else if("instant"===mo)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Two free tastes — just type the word and press Enter:")),console.log(),console.log(chalk.bold.green(" demo ")+chalk.gray(" Paper A/B/C taste — 10 MCQs, no timer ")+chalk.bold.cyan("🎯 selection-style")),console.log(chalk.bold.green(" demo2")+chalk.gray(" Embodied-AI mini-demo — robots & MuJoCo ")+chalk.bold.yellow("🤖 hands-on")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(" or ")+chalk.bold.cyan("demo2")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),a({mode:"selection"}),mo="selection";else{if("learn"===mo){console.log(chalk.cyan.bold(" [🧠 Learn]")),console.log(),console.log(chalk.gray(" Three tracks · same difficulty curve.")),console.log(),console.log(chalk.white(" Free 12-card demos — paste the full command:")),console.log(),console.log(chalk.gray(" 🤝 ai4ctf AI as your teammate ")+chalk.bold.yellow("learn AI4CTFDEMO01")),console.log(chalk.gray(" 🔓 ctf4ai AI as your target ")+chalk.bold.yellow("learn CTF4AIDEMO01")),console.log(chalk.gray(" 🤖 ctf4eai Embodied AI Security ")+chalk.bold.yellow("learn LEARNDEMO01")),console.log(),console.log(chalk.gray(" Got a cohort token? Type ")+chalk.bold.yellow("learn <TOKEN>")+chalk.gray(" (e.g. ")+chalk.bold.yellow("learn EAABCD1234")+chalk.gray(").")),console.log();try{const{input:o}=await import("@inquirer/prompts"),{resolveLearnInput:l}=await import("./lib/learn-input.js");console.log(chalk.gray(" Enter a token (or just press Enter to go back).")),console.log();const n=l(await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}));if("token"===n.kind){console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${n.token}`)),console.log(),a({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";try{await e.parseAsync(["node","icoa","learn",n.token])}finally{delete process.env.ICOA_LEARN_EMBEDDED}}else"ambiguous"!==n.kind&&"unknown"!==n.kind||(console.log(),console.log(chalk.yellow(" "+n.hint)),console.log(chalk.gray(" Returning to main menu — pick 🧠 Learn again to retry.")),console.log())}catch{}return a({mode:"selection"}),void u()}"organizer"===mo?(console.log(chalk.yellow.bold(" [National/Regional Partner]")),console.log(),console.log(chalk.bold.white(" ██╗ ██████╗ ██████╗ █████╗")),console.log(chalk.bold.white(" ██║██╔════╝██╔═══██╗██╔══██╗")),console.log(chalk.bold.white(" ██║██║ ██║ ██║███████║")),console.log(chalk.bold.white(" ██║██║ ██║ ██║██╔══██║")),console.log(chalk.bold.white(" ██║╚██████╗╚██████╔╝██║ ██║")),console.log(chalk.bold.white(" ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝")),console.log(),console.log(chalk.yellow(" International Cyber Olympiad in AI 2026")),console.log(chalk.bold.magenta(" The World's First AI-Native CLI Operating System")),console.log(chalk.bold.magenta(" for Cybersecurity & AI Security Competition")),console.log(chalk.bold.magenta(" and Olympiad for K-12")),console.log(chalk.gray(" Sydney, Australia · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.white(" Vision")),console.log(chalk.gray(" Building a global pipeline for youth cyber & AI")),console.log(chalk.gray(" security talent through education and competition.")),console.log(),console.log(chalk.white(" Capacity")),console.log(chalk.gray(" 15,000+ concurrent online examinations")),console.log(chalk.gray(" National selection, training, and education support")),console.log(),console.log(chalk.white(" Olympic Spirit")),console.log(chalk.gray(" Excellence · Friendship · Respect")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" New country accreditation & support:")),console.log(chalk.cyan(" australia@icoa2026.au")),console.log(chalk.cyan(" accreditation@icoa2026.au")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),to?(console.log(chalk.green(` Logged in as ${G.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(),h(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),so&&!c()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):to?(console.log(chalk.green.bold(` Welcome back, ${G.userName}!`)),console.log(chalk.gray(` Connected to ${G.ctfdUrl}`)),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 & hint budget")),console.log(chalk.white(" scoreboard")+chalk.gray(" Live rankings")),console.log(chalk.white(" help")+chalk.gray(" Full command list")),console.log(),console.log(chalk.gray(" Tool environment:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("help")+chalk.gray(" · ")+w()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):so?(W(H)||X(H,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${H}`)),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Get started:")),console.log(),console.log(chalk.white(" Step 1 ")+chalk.bold.cyan("join <url>")+chalk.gray(" Connect to competition server")),console.log(chalk.white(" Step 2 ")+chalk.bold.cyan("challenges")+chalk.gray(" Browse & solve challenges")),console.log(chalk.white(" Step 3 ")+chalk.bold.cyan("ai4ctf")+chalk.gray(" Ask AI when stuck")),console.log(),console.log(chalk.gray(" Before Step 1 — make sure your tools are ready:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(),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 · ")+w()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()):(console.log(chalk.bold.yellow(" 🏆 You reached the finals tier.")),console.log(chalk.gray(" Full sandbox · 110 CTF tools · Sydney 2026 · this is where finalists compete.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" To begin, activate your competition token:")),console.log(),console.log(chalk.bold.cyan(" activate <token>")),console.log(),console.log(chalk.gray(" While waiting, explore:")),console.log(chalk.white(" ref linux")+chalk.gray(" Quick reference for Linux")),console.log(chalk.white(" ref web")+chalk.gray(" Quick reference for Web")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.white(" help")+chalk.gray(" All available commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+w()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}e.exitOverride(),e.configureOutput({writeErr:()=>{},writeOut:o=>{console.log(o)}});const po=o({input:process.stdin,output:process.stdout,prompt:J(),terminal:!0});f(po);let uo=!1;p(!0),U();const ho=po.prompt.bind(po);po.prompt=o=>{b()||v()||A()||k()||po.setPrompt(J()),ho(o)},po.prompt(),po.on("line",async o=>{if(uo)return;const n=o.trim();if(!n)return po.setPrompt(b()?chalk.magenta("icoa ai4ctf> "):J()),void po.prompt();if("menu"===n||"menu confirm"===n)return L()&&"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 po.prompt()):void u(po);if(b()){uo=!0;const o=await x(n);return uo=!1,"exit"===o&&po.setPrompt(J()),void po.prompt()}if(v()){uo=!0;const o=await C(n);return uo=!1,"exit"!==o&&"solved"!==o||po.setPrompt(J()),void po.prompt()}if(A()){uo=!0;const o=await I(n);return uo=!1,"exit"===o&&po.setPrompt(J()),po.setPrompt(A()?chalk.bold.cyan("icoa ctf4vla> "):J()),void po.prompt()}if(_(n),"exit"===n)return D()?(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 po.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"===mo&&eo(),void po.prompt());if("quit"===n||"q"===n||"quit confirm"===n){const o=D();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 po.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)."))),Q(),g(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),j(),void ao(0))}if("back"===n){const o=D(),e=o&&"demo-free"!==o.session.examId,l=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(l){const e=Object.keys(o.answers).length,l=o.session.questionCount;console.log(),console.log(chalk.gray(` Demo paused (${e}/${l} answered). Resume with: `)+chalk.white("exam q 1")),console.log(chalk.gray(" Or type ")+chalk.white("demo")+chalk.gray(" to restart.")),console.log()}else{if(o&&"demo-free"===o.session.examId){const{clearExamState:o}=await import("./lib/exam-state.js");o("demo-free")}const e=t();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"===mo?eo():console.log(chalk.gray(" Already at main menu."))}return void po.prompt()}if("help"===n||"?"===n){if(D()){uo=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return uo=!1,void po.prompt()}return no(s(),mo),void po.prompt()}if("man"===n||"manual"===n)return no(s(),mo),void po.prompt();if("more help"===n.toLowerCase()&&D()){uo=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return uo=!1,void po.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 competition, you get AI help at 3 levels:")),console.log(chalk.yellow(" hint a")+chalk.gray(" General guidance (50 uses)")),console.log(chalk.yellow(" hint b")+chalk.gray(" Deep analysis (10 uses)")),console.log(chalk.yellow(" hint c")+chalk.gray(" Critical assist (2 uses)")),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 po.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(n.trim())){uo=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim()])}catch{}return uo=!1,void po.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(n.trim())){uo=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim().toUpperCase()])}catch{}return uo=!1,void po.prompt()}const a=n.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(a){uo=!0;try{await e.parseAsync(["node","icoa","exam","token",a[1].toUpperCase()])}catch{}return uo=!1,void po.prompt()}const y=n.match(/^exam\s+([A-Z]{2,3})$/i);if(y){uo=!0;try{await e.parseAsync(["node","icoa","exam","list",y[1]])}catch{}return uo=!1,void po.prompt()}if("clear"===n||"cls"===n)return console.clear(),void po.prompt();if(n.startsWith("activate ")){const o=n.slice(9).trim(),e=r(o);return"ok"===e?console.log(chalk.green(" Access granted! Token bound to this device.")):"already_bound"===e?(console.log(),console.log(chalk.red(" Token already activated on a different device.")),console.log(chalk.gray(" Each token binds to the first device that uses it. If you lost the device,")),console.log(chalk.gray(" contact your proctor to have the token re-issued for a new device."))):(console.log(),console.log(chalk.red(" Token not recognized.")),console.log(chalk.gray(" Possible reasons:")),console.log(chalk.white(" • ")+chalk.gray("Typo — access tokens are case-insensitive and look like ")+chalk.cyan("ICOA-XXXX-XXXX-XXXX")+chalk.gray(" (4-char hex groups, e.g. ICOA-385E-27F2-B21B)")),console.log(chalk.white(" • ")+chalk.gray("Expired — ask your proctor or organizer for a fresh token")),console.log(chalk.white(" • ")+chalk.gray("Network — verify connection to ")+chalk.cyan("practice.icoa2026.au")),console.log(chalk.gray(" Still stuck? type ")+chalk.cyan("help")+chalk.gray(" or try ")+chalk.cyan("exam demo")+chalk.gray(" for a free practice round."))),console.log(),void po.prompt()}if("activate"===n)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void po.prompt();const m=D();if(m){const o=n.toUpperCase().trim(),l=o=>{const e=m.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},t=o=>{const e="demo-free"!==m.session.examId,l=e&&o>=39?"ctf4ai":e&&o>=31?"ai4ctf":null;console.log(),console.log(chalk.yellow(` Q${o} is a practical question — letters (A/B/C/D) don't apply here.`)),l?(console.log(chalk.white(" Enter the AI chat for this question: ")+chalk.bold.cyan(l)),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(/^[ABCD]$/.test(o)){const n=m._lastQ||1;if(l(n))return t(n),void po.prompt();uo=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(n),o])}catch{}return uo=!1,void po.prompt()}const a=o.match(/^(\d+)\s+([ABCD])$/);if(a){const o=parseInt(a[1],10);if(l(o))return t(o),void po.prompt();uo=!0;try{await e.parseAsync(["node","icoa","exam","answer",a[1],a[2]])}catch{}return uo=!1,void po.prompt()}}const d=n.split(/\s+/)[0].toLowerCase(),p=/^python3?(\.\d+)?$/.test(d),h="ls"===d||"pwd"===d,w=n.startsWith("!")||d.startsWith("!")||p||h,f=new Set(["nano","vi","vim","emacs","pico","ed","code","cat","less","more","head","tail","ls","pwd","cd","base64","xxd","hexdump","od","openssl","md5sum","sha256sum","grep","find","awk","sed","strings","file","curl","wget","nc","ping","nmap","echo","bash","sh","zsh","pip","pip3","node","npm"]),k=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${n}`)),console.log()};if("embodied"===mo&&!w&&!["demo2","learn","exam","ctf4vla","lang","ref","setup","env","sim"].includes(d))return f.has(d)?(k(),void po.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 po.prompt());if("selection"===mo&&!w&&!["exam","demo","demo2","retry","nations","next","prev","continue","setup","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","sim"].includes(d)){if(f.has(d))return k(),void po.prompt();if(console.log(chalk.gray(" Not available in Selection mode.")),m){const o=m._lastQ||1;console.log(chalk.white(` Resume exam: exam q ${o}`)+chalk.gray(" · ")+chalk.white("A/B/C/D")+chalk.gray(" to answer"))}else console.log(chalk.gray(" Try: demo · setup to switch mode"));return console.log(),void po.prompt()}if("organizer"===mo&&!["join","exam","demo","retry","next","prev","logout","setup","lang","ref","ctf","mark","unmark","review","submit"].includes(d))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void po.prompt();if(!("olympiad"!==mo||s()&&c()||i(d)))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 po.prompt();if(!["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","connect","note","notes","logbook","log","man","manual","lang","setup","env","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","submit","learn","demo2","ctf4vla","theme","sim"].includes(d)){if(K.has(d))return console.log(chalk.yellow(` "${d}" 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 po.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: ${H}`)),console.log(),void po.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 l("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 l("which python3.12",{stdio:"ignore"}),"python3.12"}catch{return"python3"}})();o=o.replace(/^python\s/,`${e} `).replace(/^python$/,e)}const e=B(),t=F(n);M({cwd:e,input:n,riskFlags:t}),t.length>0&&L()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=z(V(),".icoa");W(o)||X(o,{recursive:!0});const e=z(o,"python-startup.py");return W(e)||Y(e,"# 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\n"),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, 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()),uo=!0;try{q()&&await N()?await P(o,po):await lo(o,po,e)}catch{console.log(chalk.yellow(` Command failed: ${d}`))}return uo=!1,console.log(),void po.prompt()}uo=!0;const T=n.trim(),E=T.toLowerCase();let S,O=null,$="";if(m)if("submit"===E)O="final";else if(E.startsWith("submit ")){let o=T.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)&&(O="flag",$=o)}else/^ICOA\{[^}]+\}$/i.test(T)&&(O="flag",$=T);S="final"===O?["exam","submit"]:"flag"===O?["exam","answer",String(m?._lastQ||1),$]:function(o){const e=o.split(/\s+/),l=e[0].toLowerCase(),n=e.slice(1),t={demo:["exam","demo"],retry:["exam","demo-retry"],nations:["exam","nations"],next:["exam","next"],prev:["exam","prev"],mark:["exam","mark",...n],unmark:["exam","unmark",...n],review:["exam","review"],logout:["ctf","logout"],join:["ctf","join",...n],activate:["ctf","activate",...n],challenges:["ctf","challenges"],ch:["ctf","challenges"],open:["ctf","open",...n],submit:["ctf","submit",...n],flag:["ctf","submit",...n],scoreboard:["ctf","scoreboard",...n],sb:["ctf","scoreboard",...n],status:["ctf","status"],time:["ctf","time"]};return t[l]?t[l]:["ref","shell","files","connect","note","notes","logbook","log","man","manual","lang","setup","env","ai4ctf","model","ctf","exam","ctf4ai"].includes(l)?[l,...n]:e}(n);const R="ctf"===S[0]&&"join"===S[1];R&&po.pause(),process.exit=()=>{throw new Error(Z)};try{await e.parseAsync(["node","icoa",...S])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===Z);else if(e.includes("commander.unknownCommand")){const{distance:o}=await import("fastest-levenshtein"),e=["ctf","ref","shell","files","connect","note","notes","logbook","log","manual","lang","setup","env","ai4ctf","exam","ctf4ai","theme","clear","cls","quit","exit","back","menu","help","continue","activate","demo","challenges","status","scoreboard","join","logout"],l=d.split(/\s+/)[0]||d;let n={word:"",dist:1/0};for(const t of e){const e=o(l.toLowerCase(),t);e<n.dist&&(n={word:t,dist:e})}console.log(chalk.yellow(` Unknown command: ${d}.`)),n.dist>0&&n.dist<=2&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(n.word)+chalk.gray("?")),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for the full command list."))}else e.includes("commander.")||(e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ETIMEDOUT"))&&console.log(chalk.yellow(" Network error. Check your connection."))}finally{process.exit=ao,uo=!1,R&&po.resume()}b()?po.setPrompt(chalk.magenta("icoa ai4ctf> ")):v()?po.setPrompt(chalk.red("icoa ctf4ai> ")):A()&&po.setPrompt(chalk.bold.cyan("icoa ctf4vla> ")),console.log(),po.prompt()}),po.on("SIGINT",()=>{if(console.log(),b()||v())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(D()){const o="demo-free"!==D().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(),po.prompt()}),po.on("close",()=>{Q(),g(),j(),ao(0)})}function lo(o,l,n){return new Promise(t=>{const a=process.stdin,s=!!a.isTTY&&!!a.isRaw;if(l.pause(),a.isTTY&&"function"==typeof a.setRawMode)try{a.setRawMode(!1)}catch{}const r=e(o,{shell:!0,stdio:"inherit",cwd:n||process.cwd()}),i=()=>{if(a.isTTY&&"function"==typeof a.setRawMode&&s)try{a.setRawMode(!0)}catch{}l.resume(),t()};r.on("close",i),r.on("error",i)})}function no(o,e="olympiad"){return console.log(),"selection"===e||"organizer"===e?(console.log(chalk.bold.white(" Exam")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to exam server")),console.log(chalk.white(" exam list ")+chalk.gray("Available exams")),console.log(chalk.white(" exam start <id> ")+chalk.gray("Begin an exam")),console.log(chalk.white(" exam q [n] ")+chalk.gray("View questions")),console.log(chalk.white(" exam answer <n> <X> ")+chalk.gray("Answer question")),console.log(chalk.white(" exam review ")+chalk.gray("Review all answers")),console.log(chalk.white(" exam submit ")+chalk.gray("Submit for grading")),console.log(chalk.white(" exam result ")+chalk.gray("View your score")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" setup ")+chalk.gray("Settings / switch mode")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log()):o?(console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(chalk.bold.white(" How it works")),console.log(),console.log(chalk.gray(" 1. Browse ")+chalk.white("challenges")+chalk.gray(" and pick one")),console.log(chalk.gray(" 2. ")+chalk.white("open <id>")+chalk.gray(" to read the challenge")),console.log(chalk.gray(" 3. Use ")+chalk.white("ai4ctf")+chalk.gray(" to chat with AI when stuck")),console.log(chalk.gray(" 4. ")+chalk.white("submit <id> icoa{flag}")+chalk.gray(" to score points")),console.log(chalk.gray(" 5. Check ")+chalk.white("scoreboard")+chalk.gray(" to track your rank")),console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(),console.log(chalk.bold.white(" Competition")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to CTFd")),console.log(chalk.white(" challenges (ch) ")+chalk.gray("List challenges by category")),console.log(chalk.white(" open <id> ")+chalk.gray("Read challenge + get next steps")),console.log(chalk.white(" submit <id> <flag> ")+chalk.gray("Submit a flag")),console.log(chalk.white(" scoreboard (sb) ")+chalk.gray("Live rankings")),console.log(chalk.white(" status ")+chalk.gray("Your score, budget & timer")),console.log(chalk.white(" time ")+chalk.gray("Countdown timer")),console.log(),console.log(chalk.bold.white(" AI Teammate")+chalk.gray(" — 3 levels, use wisely")),console.log(chalk.white(' hint "question" ')+chalk.gray("Level A — General guidance (50 uses)")),console.log(chalk.white(' hint-b "question" ')+chalk.gray("Level B — Deep analysis (10 uses)")),console.log(chalk.white(' hint-c "question" ')+chalk.gray("Level C — Critical assist (2 uses)")),console.log(chalk.white(" hint budget ")+chalk.gray("Check remaining uses")),console.log(chalk.white(" ai4ctf ")+chalk.gray("Free-chat with AI (no limit)")),console.log(),console.log(chalk.bold.white(" Tools")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference (linux, web, crypto...)")),console.log(chalk.white(" shell ")+chalk.gray("Docker sandbox")),console.log(chalk.white(" files <id> ")+chalk.gray("Download challenge files")),console.log(chalk.white(" connect <id> ")+chalk.gray("Connect to remote target")),console.log(chalk.white(" note [text] ")+chalk.gray("Add a logbook entry (in-exam: tags current Q)")),console.log(chalk.white(" logbook [n] ")+chalk.gray("View your logbook (in-exam: filter by Q)")),console.log(chalk.white(" log ")+chalk.gray("Session history")),console.log(chalk.white(" man / manual ")+chalk.gray("Show this command list (works in exam too, does not burn elimination)")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" setup ")+chalk.gray("Configure settings")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language (15 supported)")),console.log(chalk.white(" logout ")+chalk.gray("Disconnect")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit (session saved)")),void console.log()):(console.log(chalk.bold.yellow(" Restricted Mode — activate with a token to unlock all commands")),console.log(),console.log(chalk.white(" activate <token> ")+chalk.gray("Unlock full access")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log())}
|
|
1
|
+
import{createInterface as o}from"node:readline";import{spawn as e,execSync as l}from"node:child_process";import chalk from"chalk";import{isConnected as n,getConfig as t,saveConfig as a}from"./lib/config.js";import{isActivated as s,activateToken as r,isFreeCommand as i,isDeviceMatch as c,recordExit as g,recordResume as y,isFirstRunOrUpgrade as m,markVersionSeen as d}from"./lib/access.js";import{setReplMode as p}from"./lib/ui.js";import{returnToMainMenu as u,printMenuHint as h,menuHintInline as w}from"./lib/menu-nav.js";import{setMainRl as f}from"./lib/main-rl.js";import{isChatActive as b,handleChatMessage as x}from"./commands/ai4ctf.js";import{isCtf4aiActive as v,handleCtf4aiMessage as C}from"./commands/ctf4ai-demo.js";import{isCtf4VlaActive as A,handleCtf4VlaMessage as I}from"./commands/ctf4vla.js";import{isDemo2Active as k}from"./commands/demo2.js";import{loadDemo2Progress as T}from"./lib/demo2-progress.js";import{hasAnySimHistory as E,lastArmAt as S,lastBundledAt as O,lastSimAt as $}from"./lib/sim-cooldown.js";import{getExamState as D,getRealExamState as L,getDemoState as R}from"./lib/exam-state.js";import{resetTerminalTheme as j}from"./lib/theme.js";import{ensureSandbox as N,runInSandbox as P,isDockerAvailable as q}from"./lib/sandbox.js";import{checkShellRisk as F,logShellAudit as M,getActiveCwd as B}from"./lib/exam-sandbox.js";import{logCommand as _}from"./lib/logger.js";import{startLogSync as U,stopLogSync as Q}from"./lib/log-sync.js";import{existsSync as W,mkdirSync as X,writeFileSync as Y}from"node:fs";import{join as z}from"node:path";import{homedir as G}from"node:os";const V=Date.now();function J(){return L()?chalk.cyan("icoa exam> "):function(){const o=R();return!(!o||"demo-free"!==o.session?.examId)&&new Date(o.session.startedAt||0).getTime()>=V}()?chalk.yellow("icoa demo> "):chalk.green("icoa> ")}const H=z(G(),"icoa-workspace"),K=new Set(["sudo","su","doas","pkexec","brew","apt","apt-get","yum","choco","npm","npx","pip","pip3","shutdown","reboot","halt","mkfs","fdisk","dd","iptables","ufw"]),Z="__REPL_NO_EXIT__",oo="2.5.1";function eo(){console.log(),console.log(` ${chalk.cyan.bold("🎯 ICOA 2026 · National Selection")}`),console.log(),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("ACxxxxxxxx")+chalk.gray(" → ai4ctf-12 (AI as your CTF teammate)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("CAxxxxxxxx")+chalk.gray(" → ctf4ai-12 (red-team software AI)")),console.log(" "+chalk.bold.cyan("learn ")+chalk.white("EAxxxxxxxx")+chalk.gray(" → ctf4eai-12 (red-team embodied AI)")),console.log(" "+chalk.bold.cyan("exam ")+chalk.white("<CC>xxxxxxxx")+chalk.gray(" → Paper A/B/C/D/E (country exam token)")),console.log(" "+chalk.bold.cyan("demo")+chalk.gray(" → free practice")),console.log(" "+chalk.bold.cyan("lang")+chalk.white(" es")+chalk.gray(" → switch language")),console.log(" "+chalk.gray("help · menu · quit")),console.log()}export async function startRepl(e,R){process.env.ICOA_INSIDE_REPL="1";const V=t(),to=n(),ao=process.exit.bind(process),so=s();if(V.demoCleanedForVersion!==oo){try{const{existsSync:o,unlinkSync:e}=await import("node:fs"),{join:l}=await import("node:path"),{getIcoaDir:n}=await import("./lib/config.js"),t=l(n(),"demo-state.json");o(t)&&e(t)}catch{}a({demoCleanedForVersion:oo})}const{select:ro,confirm:io}=await import("@inquirer/prompts"),co=V.mode||"",go=""===co?"instant":["instant","learn","selection","olympiad"].includes(co)?co:"selection",yo=[{name:` ${chalk.bold("⚡ Try ICOA in 30 seconds")} ${chalk.gray("—")} ${chalk.gray("watch · no token needed")}`,value:"instant"},{name:` ${chalk.bold("🧠 Learn")} ${chalk.gray("—")} ${chalk.gray("AC / CA / EA token · skill up")}`,value:"learn"},{name:` ${chalk.bold("🎯 National Selection")} ${chalk.gray("—")} ${chalk.gray("country exam token · aim for finals")}`,value:"selection"},{name:` ${chalk.bold("🏆 International Olympiad")} ${chalk.gray("—")} ${chalk.gray("finals stage · Sydney 2026 · full sandbox")}`,value:"olympiad"},{name:` ${chalk.gray("ℹ️ About ICOA")} ${chalk.gray("·")} ${chalk.gray("what this is · how to join")}`,value:"about"}];console.log(chalk.gray(" Type ")+chalk.bold.cyan("menu")+chalk.gray(" from anywhere to return here.")),console.log();let mo="";for(;!mo;){let o;try{o=await ro({message:"Mode",choices:yo,default:go||"instant"})}catch(o){throw o instanceof Error&&"ExitPromptError"===o.name&&(console.log(),console.log(chalk.gray(" Goodbye.")),process.exit(0)),o}"about"!==o?mo=o:(console.clear(),console.log(),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(chalk.bold.yellow(" ICOA")+chalk.white(" — AI-Native CLI OS for Cyber & AI Security")),console.log(chalk.gray(" Olympiad & Competition · K-12 to University")),console.log(chalk.cyan(" ───────────────────────────────────────────────────")),console.log(),console.log(chalk.bold.white(" What Makes ICOA Different")),console.log(chalk.gray(" · AI-native AI teammate, AI adversary, AI translation")),console.log(chalk.gray(" · CLI OS Complete competition environment in terminal")),console.log(chalk.gray(" · 110 tools pwntools, z3, gdb, nmap, sleuthkit... pre-configured")),console.log(chalk.gray(" · Global scale 15,000+ concurrent exams · 15 languages")),console.log(),console.log(chalk.bold.white(" Competition Format (2-day standard + 1-day Pioneer)")),console.log(` ${chalk.green.bold("AI4CTF")}${chalk.gray(" [Day 1] AI as teammate — speed track, dynamic decay + top-3 bonus")}`),console.log(` ${chalk.red.bold("CTF4AI")}${chalk.gray(" [Day 2] AI as target — knowledge track, static value per challenge")}`),console.log(` ${chalk.cyan.bold("CTF4EAI")}${chalk.gray(" [Pioneer / Practical Round] Embodied AI — VLA + world models + sim-to-real")}`),console.log(),console.log(chalk.bold.white(" Scoring (in brief)")),console.log(chalk.gray(" · Standard medals: AI4CTF + CTF4AI combined · 1/12 Gold · 2/12 Silver · 3/12 Bronze")),console.log(chalk.gray(" · HMA: top 50% on either day, total below bronze cutoff")),console.log(chalk.gray(" · CTF4EAI: separate 15-finalist pool, G/S/B + 12 Finalist Awards")),console.log(),console.log(chalk.white(" Sydney, Australia")+chalk.gray(" · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.bold.white(" Organized by")+chalk.gray(" ASRA (Australia) · ICO Foundation Inc")),console.log(chalk.bold.white(" Contact ")+chalk.cyan(" australia@icoa2026.au · accreditation@icoa2026.au")),console.log(chalk.bold.white(" Website ")+chalk.cyan.underline(" https://icoa2026.au")),console.log(chalk.cyan(" ═══════════════════════════════════════════════════")),console.log(),console.log(chalk.gray(" Press ")+chalk.yellow("Enter")+chalk.gray(" to return...")),await new Promise(o=>{const e=l=>{process.stdin.removeListener("data",e),process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!1),process.stdin.pause(),o()};process.stdin.isTTY&&process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.once("data",e)}),console.clear())}if("olympiad"===mo&&"olympiad"!==go){console.log(),console.log(chalk.yellow(" This mode will download ~500MB of CTF tools and AI models."));let o=!0;try{o=await io({message:"Continue?",default:!0})}catch(e){if(!(e instanceof Error&&"ExitPromptError"===e.name))throw e;o=!1}o||(mo="selection",console.log(chalk.gray(" Switched to National Selection mode.")))}if(mo!==go&&a({mode:mo}),console.log(),"olympiad"===mo&&m(oo)){d(oo),console.log(chalk.gray(" Checking competition environment..."));const{execSync:o}=await import("node:child_process"),e=[{name:"pwntools",cmd:'python3 -c "import pwn"'},{name:"z3-solver",cmd:'python3 -c "import z3"'},{name:"numpy",cmd:'python3 -c "import numpy"'},{name:"requests",cmd:'python3 -c "import requests"'}];let l=0;for(const n of e)try{o(n.cmd,{stdio:"ignore"})}catch{l++}if(l>0){console.log(chalk.yellow(` ${l} core libraries missing.`));try{const{confirm:o}=await import("@inquirer/prompts");if(await o({message:" Install competition Python libraries now?",default:!0,theme:{prefix:"",style:{message:o=>chalk.green(o),defaultAnswer:o=>chalk.green(o)}}})){console.log();const{execSync:o}=await import("node:child_process");o("icoa env setup",{stdio:"inherit"})}}catch{console.log(chalk.gray(" Run ")+chalk.white("env setup")+chalk.gray(" later to install."))}console.log()}else console.log(chalk.green(" All core libraries ready.")),console.log()}if(R){const o=y();if(o){const e=Math.floor(o.awaySeconds/60),l=o.awaySeconds%60;console.log(chalk.yellow(` Session resumed. Away: ${e}m ${l}s | Total exits: ${o.exitCount}`)),console.log()}}if("selection"===mo)console.log(chalk.gray(" ─── exam hall · 90 min per paper once started · no pause ───")),console.log(),eo();else if("embodied"===mo)!function(){console.log(chalk.cyan.bold(" [🤖 ctf4eai — Embodied AI Security]")),console.log(),console.log(chalk.bold.cyan(" CTF4EAI")+chalk.gray(" — ICOA 2026's ")+chalk.bold.white("Pioneer Round")),console.log(chalk.gray(" an independent parallel track alongside the scored main events: ")+chalk.green("AI4CTF")+chalk.gray(" (Day 1) and ")+chalk.red("CTF4AI")+chalk.gray(" (Day 2)")),console.log(),console.log(chalk.white(" Embodied AI is at its ImageNet moment.")),console.log(chalk.gray(" VLA models, MuJoCo physics, real robot arms.")),console.log(chalk.gray(" Real models, real physics, real attack surfaces.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const o=O()>0||$()>0,e=S()>0,l=E(),n=T(),t=null!==n&&"number"==typeof n.completedAt&&n.nextCardIndex>=n.totalCards,a=null!==n&&!t;if(t)console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (demo2 ✓ · sim")+(e?chalk.gray(" ✓ · sim arm ✓)"):chalk.gray(")")));else if(a){const o=`${n.nextCardIndex} / ${n.totalCards}`;console.log(chalk.bold.yellow(" Continue: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" (last left at card ")+chalk.bold.yellow(o)+chalk.gray(")"))}else o&&e?console.log(chalk.bold.yellow(" Next up: ")+chalk.bold.cyan("③ demo2")+chalk.gray(" → ")+chalk.bold.cyan("④ learn LEARNDEMO01")+chalk.gray(" (sim ✓ · sim arm ✓)")):l?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(" — 8-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(),h(),console.log()}();else if("instant"===mo)console.log(chalk.cyan.bold(" [⚡ Try ICOA in 30 seconds — no token needed]")),console.log(),console.log(chalk.gray(" Two free tastes — just type the word and press Enter:")),console.log(),console.log(chalk.bold.green(" demo ")+chalk.gray(" Paper A/B/C taste — 10 MCQs, no timer ")+chalk.bold.cyan("🎯 selection-style")),console.log(chalk.bold.green(" demo2")+chalk.gray(" Embodied-AI mini-demo — robots & MuJoCo ")+chalk.bold.yellow("🤖 hands-on")),console.log(),console.log(chalk.gray(" Type ")+chalk.bold.cyan("demo")+chalk.gray(" or ")+chalk.bold.cyan("demo2")+chalk.gray(" to start · ")+chalk.bold.cyan("menu")+chalk.gray(" to go back · ")+chalk.bold.cyan("quit")+chalk.gray(" to exit")),console.log(),a({mode:"selection"}),mo="selection";else{if("learn"===mo){console.log(chalk.cyan.bold(" [🧠 Learn]")),console.log(),console.log(chalk.gray(" Three tracks · same difficulty curve.")),console.log(),console.log(chalk.white(" Free 12-card demos — paste the full command:")),console.log(),console.log(chalk.gray(" 🤝 ai4ctf AI as your teammate ")+chalk.bold.yellow("learn AI4CTFDEMO01")),console.log(chalk.gray(" 🔓 ctf4ai AI as your target ")+chalk.bold.yellow("learn CTF4AIDEMO01")),console.log(chalk.gray(" 🤖 ctf4eai Embodied AI Security ")+chalk.bold.yellow("learn LEARNDEMO01")),console.log(),console.log(chalk.gray(" Got a cohort token? Type ")+chalk.bold.yellow("learn <TOKEN>")+chalk.gray(" (e.g. ")+chalk.bold.yellow("learn EAABCD1234")+chalk.gray(").")),console.log();try{const{input:o}=await import("@inquirer/prompts"),{resolveLearnInput:l}=await import("./lib/learn-input.js");console.log(chalk.gray(" Enter a token (or just press Enter to go back).")),console.log();const n=l(await o({message:chalk.bold.cyan("icoa learn>"),theme:{prefix:"",style:{message:o=>o}}}));if("token"===n.kind){console.log(),console.log(chalk.gray(" Opening ")+chalk.bold.cyan("learn")+chalk.gray(`: ${n.token}`)),console.log(),a({mode:"selection"}),process.env.ICOA_LEARN_EMBEDDED="1";try{await e.parseAsync(["node","icoa","learn",n.token])}finally{delete process.env.ICOA_LEARN_EMBEDDED}}else"ambiguous"!==n.kind&&"unknown"!==n.kind||(console.log(),console.log(chalk.yellow(" "+n.hint)),console.log(chalk.gray(" Returning to main menu — pick 🧠 Learn again to retry.")),console.log())}catch{}return a({mode:"selection"}),void u()}"organizer"===mo?(console.log(chalk.yellow.bold(" [National/Regional Partner]")),console.log(),console.log(chalk.bold.white(" ██╗ ██████╗ ██████╗ █████╗")),console.log(chalk.bold.white(" ██║██╔════╝██╔═══██╗██╔══██╗")),console.log(chalk.bold.white(" ██║██║ ██║ ██║███████║")),console.log(chalk.bold.white(" ██║██║ ██║ ██║██╔══██║")),console.log(chalk.bold.white(" ██║╚██████╗╚██████╔╝██║ ██║")),console.log(chalk.bold.white(" ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝")),console.log(),console.log(chalk.yellow(" International Cyber Olympiad in AI 2026")),console.log(chalk.bold.magenta(" The World's First AI-Native CLI Operating System")),console.log(chalk.bold.magenta(" for Cybersecurity & AI Security Competition")),console.log(chalk.bold.magenta(" and Olympiad for K-12")),console.log(chalk.gray(" Sydney, Australia · Jun 27 - Jul 2, 2026")),console.log(),console.log(chalk.white(" Vision")),console.log(chalk.gray(" Building a global pipeline for youth cyber & AI")),console.log(chalk.gray(" security talent through education and competition.")),console.log(),console.log(chalk.white(" Capacity")),console.log(chalk.gray(" 15,000+ concurrent online examinations")),console.log(chalk.gray(" National selection, training, and education support")),console.log(),console.log(chalk.white(" Olympic Spirit")),console.log(chalk.gray(" Excellence · Friendship · Respect")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" New country accreditation & support:")),console.log(chalk.cyan(" australia@icoa2026.au")),console.log(chalk.cyan(" accreditation@icoa2026.au")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(),to?(console.log(chalk.green(` Logged in as ${V.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(),h(),console.log()):(console.log(` ${chalk.cyan.bold("🏆 ICOA 2026 · International Olympiad")}`),console.log(),so&&!c()?(console.log(chalk.red(" Token was activated on a different device.")),console.log(chalk.gray(" Contact organizer for assistance.")),console.log()):to?(console.log(chalk.green.bold(` Welcome back, ${V.userName}!`)),console.log(chalk.gray(` Connected to ${V.ctfdUrl}`)),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 & hint budget")),console.log(chalk.white(" scoreboard")+chalk.gray(" Live rankings")),console.log(chalk.white(" help")+chalk.gray(" Full command list")),console.log(),console.log(chalk.gray(" Tool environment:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("help")+chalk.gray(" · ")+w()+chalk.gray(" · ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+chalk.cyan("quit")+chalk.gray(" closes")),console.log()):so?(W(H)||X(H,{recursive:!0}),console.log(chalk.green.bold(" Welcome, competitor!")),console.log(chalk.gray(` Workspace: ${H}`)),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" Get started:")),console.log(),console.log(chalk.white(" Step 1 ")+chalk.bold.cyan("join <url>")+chalk.gray(" Connect to competition server")),console.log(chalk.white(" Step 2 ")+chalk.bold.cyan("challenges")+chalk.gray(" Browse & solve challenges")),console.log(chalk.white(" Step 3 ")+chalk.bold.cyan("ai4ctf")+chalk.gray(" Ask AI when stuck")),console.log(),console.log(chalk.gray(" Before Step 1 — make sure your tools are ready:")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(),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 · ")+w()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()):(console.log(chalk.bold.yellow(" 🏆 You reached the finals tier.")),console.log(chalk.gray(" Full sandbox · 110 CTF tools · Sydney 2026 · this is where finalists compete.")),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.white(" To begin, activate your competition token:")),console.log(),console.log(chalk.bold.cyan(" activate <token>")),console.log(),console.log(chalk.gray(" While waiting, explore:")),console.log(chalk.white(" ref linux")+chalk.gray(" Quick reference for Linux")),console.log(chalk.white(" ref web")+chalk.gray(" Quick reference for Web")),console.log(chalk.white(" env")+chalk.gray(" See which of the 110 CTF tools are installed")),console.log(chalk.white(" env setup")+chalk.gray(" Install anything missing (~5 min, one-time)")),console.log(chalk.white(" help")+chalk.gray(" All available commands")),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log(chalk.gray(" Tip: ")+chalk.cyan("Ctrl+C")+chalk.gray(" pauses · ")+w()+chalk.gray(" · ")+chalk.cyan("quit")+chalk.gray(" closes CLI")),console.log()))}e.exitOverride(),e.configureOutput({writeErr:()=>{},writeOut:o=>{console.log(o)}});const po=o({input:process.stdin,output:process.stdout,prompt:J(),terminal:!0});f(po);let uo=!1;p(!0),U();const ho=po.prompt.bind(po);po.prompt=o=>{b()||v()||A()||k()||po.setPrompt(J()),ho(o)},po.prompt(),po.on("line",async o=>{if(uo)return;const n=o.trim();if(!n)return po.setPrompt(b()?chalk.magenta("icoa ai4ctf> "):J()),void po.prompt();if("menu"===n||"menu confirm"===n)return L()&&"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 po.prompt()):void u(po);if(b()){uo=!0;const o=await x(n);return uo=!1,"exit"===o&&po.setPrompt(J()),void po.prompt()}if(v()){uo=!0;const o=await C(n);return uo=!1,"exit"!==o&&"solved"!==o||po.setPrompt(J()),void po.prompt()}if(A()){uo=!0;const o=await I(n);return uo=!1,"exit"===o&&po.setPrompt(J()),po.setPrompt(A()?chalk.bold.cyan("icoa ctf4eai> "):J()),void po.prompt()}if(_(n),"exit"===n)return D()?(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 po.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"===mo&&eo(),void po.prompt());if("quit"===n||"q"===n||"quit confirm"===n){const o=D();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 po.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)."))),Q(),g(),console.log(chalk.gray(" Session saved. Use ")+chalk.white("icoa --resume")+chalk.gray(" to continue.")),j(),void ao(0))}if("back"===n){const o=D(),e=o&&"demo-free"!==o.session.examId,l=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(l){const e=Object.keys(o.answers).length,l=o.session.questionCount;console.log(),console.log(chalk.gray(` Demo paused (${e}/${l} answered). Resume with: `)+chalk.white("exam q 1")),console.log(chalk.gray(" Or type ")+chalk.white("demo")+chalk.gray(" to restart.")),console.log()}else{if(o&&"demo-free"===o.session.examId){const{clearExamState:o}=await import("./lib/exam-state.js");o("demo-free")}const e=t();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"===mo?eo():console.log(chalk.gray(" Already at main menu."))}return void po.prompt()}if("help"===n||"?"===n){if(D()){uo=!0;try{await e.parseAsync(["node","icoa","exam","help"])}catch{}return uo=!1,void po.prompt()}return no(s(),mo),void po.prompt()}if("man"===n||"manual"===n)return no(s(),mo),void po.prompt();if("more help"===n.toLowerCase()&&D()){uo=!0;try{await e.parseAsync(["node","icoa","exam","more-help"])}catch{}return uo=!1,void po.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 competition, you get AI help at 3 levels:")),console.log(chalk.yellow(" hint a")+chalk.gray(" General guidance (50 uses)")),console.log(chalk.yellow(" hint b")+chalk.gray(" Deep analysis (10 uses)")),console.log(chalk.yellow(" hint c")+chalk.gray(" Critical assist (2 uses)")),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 po.prompt();if(/^ICOA-[A-Z]{2,3}-\d{1,6}$/i.test(n.trim())){uo=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim()])}catch{}return uo=!1,void po.prompt()}if(/^[A-Z]{2}[0-9A-HJKMNP-TV-Z]{8}$/i.test(n.trim())){uo=!0;try{await e.parseAsync(["node","icoa","exam","token",n.trim().toUpperCase()])}catch{}return uo=!1,void po.prompt()}const a=n.match(/^exam\s+([A-Z]{2}[0-9A-HJKMNP-TV-Z]{8})$/i);if(a){uo=!0;try{await e.parseAsync(["node","icoa","exam","token",a[1].toUpperCase()])}catch{}return uo=!1,void po.prompt()}const y=n.match(/^exam\s+([A-Z]{2,3})$/i);if(y){uo=!0;try{await e.parseAsync(["node","icoa","exam","list",y[1]])}catch{}return uo=!1,void po.prompt()}if("clear"===n||"cls"===n)return console.clear(),void po.prompt();if(n.startsWith("activate ")){const o=n.slice(9).trim(),e=r(o);return"ok"===e?console.log(chalk.green(" Access granted! Token bound to this device.")):"already_bound"===e?(console.log(),console.log(chalk.red(" Token already activated on a different device.")),console.log(chalk.gray(" Each token binds to the first device that uses it. If you lost the device,")),console.log(chalk.gray(" contact your proctor to have the token re-issued for a new device."))):(console.log(),console.log(chalk.red(" Token not recognized.")),console.log(chalk.gray(" Possible reasons:")),console.log(chalk.white(" • ")+chalk.gray("Typo — access tokens are case-insensitive and look like ")+chalk.cyan("ICOA-XXXX-XXXX-XXXX")+chalk.gray(" (4-char hex groups, e.g. ICOA-385E-27F2-B21B)")),console.log(chalk.white(" • ")+chalk.gray("Expired — ask your proctor or organizer for a fresh token")),console.log(chalk.white(" • ")+chalk.gray("Network — verify connection to ")+chalk.cyan("practice.icoa2026.au")),console.log(chalk.gray(" Still stuck? type ")+chalk.cyan("help")+chalk.gray(" or try ")+chalk.cyan("exam demo")+chalk.gray(" for a free practice round."))),console.log(),void po.prompt()}if("activate"===n)return console.log(chalk.gray(" Usage: ")+chalk.white("activate <token>")),console.log(),void po.prompt();const m=D();if(m){const o=n.toUpperCase().trim(),l=o=>{const e=m.questions.find(e=>e.number===o);return!!e&&("ai4ctf"===e.type||"ctf4ai"===e.type||e.options&&!e.options.A&&!e.options.B)},t=o=>{const e="demo-free"!==m.session.examId,l=e&&o>=39?"ctf4ai":e&&o>=31?"ai4ctf":null;console.log(),console.log(chalk.yellow(` Q${o} is a practical question — letters (A/B/C/D) don't apply here.`)),l?(console.log(chalk.white(" Enter the AI chat for this question: ")+chalk.bold.cyan(l)),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(/^[ABCD]$/.test(o)){const n=m._lastQ||1;if(l(n))return t(n),void po.prompt();uo=!0;try{await e.parseAsync(["node","icoa","exam","answer",String(n),o])}catch{}return uo=!1,void po.prompt()}const a=o.match(/^(\d+)\s+([ABCD])$/);if(a){const o=parseInt(a[1],10);if(l(o))return t(o),void po.prompt();uo=!0;try{await e.parseAsync(["node","icoa","exam","answer",a[1],a[2]])}catch{}return uo=!1,void po.prompt()}}const d=n.split(/\s+/)[0].toLowerCase(),p=/^python3?(\.\d+)?$/.test(d),h="ls"===d||"pwd"===d,w=n.startsWith("!")||d.startsWith("!")||p||h,f=new Set(["nano","vi","vim","emacs","pico","ed","code","cat","less","more","head","tail","ls","pwd","cd","base64","xxd","hexdump","od","openssl","md5sum","sha256sum","grep","find","awk","sed","strings","file","curl","wget","nc","ping","nmap","echo","bash","sh","zsh","pip","pip3","node","npm"]),k=()=>{console.log(chalk.gray(" Shell commands need ")+chalk.bold.cyan("!")+chalk.gray(" prefix. Try: ")+chalk.bold.cyan(`!${n}`)),console.log()};if("embodied"===mo&&!w&&!["demo2","learn","exam","ctf4eai","ctf4vla","lang","ref","setup","env","sim"].includes(d))return f.has(d)?(k(),void po.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 po.prompt());if("selection"===mo&&!w&&!["exam","demo","demo2","retry","nations","next","prev","continue","setup","lang","ref","ai4ctf","ctf4ai","mark","unmark","review","submit","env","sim"].includes(d)){if(f.has(d))return k(),void po.prompt();if(console.log(chalk.gray(" Not available in Selection mode.")),m){const o=m._lastQ||1;console.log(chalk.white(` Resume exam: exam q ${o}`)+chalk.gray(" · ")+chalk.white("A/B/C/D")+chalk.gray(" to answer"))}else console.log(chalk.gray(" Try: demo · setup to switch mode"));return console.log(),void po.prompt()}if("organizer"===mo&&!["join","exam","demo","retry","next","prev","logout","setup","lang","ref","ctf","mark","unmark","review","submit"].includes(d))return console.log(chalk.gray(" Not available in Organizer mode. Switch via: setup")),console.log(),void po.prompt();if(!("olympiad"!==mo||s()&&c()||i(d)))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 po.prompt();if(!["join","activate","challenges","ch","open","submit","flag","scoreboard","sb","status","time","ref","shell","files","connect","note","notes","logbook","log","man","manual","lang","setup","env","ai4ctf","model","ctf","exam","demo","retry","nations","next","prev","continue","logout","ctf4ai","mark","unmark","review","submit","learn","demo2","ctf4eai","ctf4vla","theme","sim"].includes(d)){if(K.has(d))return console.log(chalk.yellow(` "${d}" 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 po.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: ${H}`)),console.log(),void po.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 l("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 l("which python3.12",{stdio:"ignore"}),"python3.12"}catch{return"python3"}})();o=o.replace(/^python\s/,`${e} `).replace(/^python$/,e)}const e=B(),t=F(n);M({cwd:e,input:n,riskFlags:t}),t.length>0&&L()&&(console.log(chalk.yellow(` ⚠ Action flagged: ${t.join(", ")} — logged.`)),console.log()),/^(\S*python3?(\.\d+)?)\s*$/.test(o)&&(o=`PYTHONSTARTUP="${function(){const o=z(G(),".icoa");W(o)||X(o,{recursive:!0});const e=z(o,"python-startup.py");return W(e)||Y(e,"# 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\n"),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, 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()),uo=!0;try{q()&&await N()?await P(o,po):await lo(o,po,e)}catch{console.log(chalk.yellow(` Command failed: ${d}`))}return uo=!1,console.log(),void po.prompt()}uo=!0;const T=n.trim(),E=T.toLowerCase();let S,O=null,$="";if(m)if("submit"===E)O="final";else if(E.startsWith("submit ")){let o=T.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)&&(O="flag",$=o)}else/^ICOA\{[^}]+\}$/i.test(T)&&(O="flag",$=T);S="final"===O?["exam","submit"]:"flag"===O?["exam","answer",String(m?._lastQ||1),$]:function(o){const e=o.split(/\s+/),l=e[0].toLowerCase(),n=e.slice(1),t={demo:["exam","demo"],retry:["exam","demo-retry"],nations:["exam","nations"],next:["exam","next"],prev:["exam","prev"],mark:["exam","mark",...n],unmark:["exam","unmark",...n],review:["exam","review"],logout:["ctf","logout"],join:["ctf","join",...n],activate:["ctf","activate",...n],challenges:["ctf","challenges"],ch:["ctf","challenges"],open:["ctf","open",...n],submit:["ctf","submit",...n],flag:["ctf","submit",...n],scoreboard:["ctf","scoreboard",...n],sb:["ctf","scoreboard",...n],status:["ctf","status"],time:["ctf","time"]};return t[l]?t[l]:["ref","shell","files","connect","note","notes","logbook","log","man","manual","lang","setup","env","ai4ctf","model","ctf","exam","ctf4ai"].includes(l)?[l,...n]:e}(n);const R="ctf"===S[0]&&"join"===S[1];R&&po.pause(),process.exit=()=>{throw new Error(Z)};try{await e.parseAsync(["node","icoa",...S])}catch(o){const e=o instanceof Error?o.message:String(o);if(e===Z);else if(e.includes("commander.unknownCommand")){const{distance:o}=await import("fastest-levenshtein"),e=["ctf","ref","shell","files","connect","note","notes","logbook","log","manual","lang","setup","env","ai4ctf","exam","ctf4ai","theme","clear","cls","quit","exit","back","menu","help","continue","activate","demo","challenges","status","scoreboard","join","logout"],l=d.split(/\s+/)[0]||d;let n={word:"",dist:1/0};for(const t of e){const e=o(l.toLowerCase(),t);e<n.dist&&(n={word:t,dist:e})}console.log(chalk.yellow(` Unknown command: ${d}.`)),n.dist>0&&n.dist<=2&&console.log(chalk.gray(" Did you mean: ")+chalk.bold.cyan(n.word)+chalk.gray("?")),console.log(chalk.gray(" Type ")+chalk.cyan("help")+chalk.gray(" for the full command list."))}else e.includes("commander.")||(e.includes("fetch failed")||e.includes("ECONNREFUSED")||e.includes("ETIMEDOUT"))&&console.log(chalk.yellow(" Network error. Check your connection."))}finally{process.exit=ao,uo=!1,R&&po.resume()}b()?po.setPrompt(chalk.magenta("icoa ai4ctf> ")):v()?po.setPrompt(chalk.red("icoa ctf4ai> ")):A()&&po.setPrompt(chalk.bold.cyan("icoa ctf4eai> ")),console.log(),po.prompt()}),po.on("SIGINT",()=>{if(console.log(),b()||v())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(D()){const o="demo-free"!==D().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(),po.prompt()}),po.on("close",()=>{Q(),g(),j(),ao(0)})}function lo(o,l,n){return new Promise(t=>{const a=process.stdin,s=!!a.isTTY&&!!a.isRaw;if(l.pause(),a.isTTY&&"function"==typeof a.setRawMode)try{a.setRawMode(!1)}catch{}const r=e(o,{shell:!0,stdio:"inherit",cwd:n||process.cwd()}),i=()=>{if(a.isTTY&&"function"==typeof a.setRawMode&&s)try{a.setRawMode(!0)}catch{}l.resume(),t()};r.on("close",i),r.on("error",i)})}function no(o,e="olympiad"){return console.log(),"selection"===e||"organizer"===e?(console.log(chalk.bold.white(" Exam")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to exam server")),console.log(chalk.white(" exam list ")+chalk.gray("Available exams")),console.log(chalk.white(" exam start <id> ")+chalk.gray("Begin an exam")),console.log(chalk.white(" exam q [n] ")+chalk.gray("View questions")),console.log(chalk.white(" exam answer <n> <X> ")+chalk.gray("Answer question")),console.log(chalk.white(" exam review ")+chalk.gray("Review all answers")),console.log(chalk.white(" exam submit ")+chalk.gray("Submit for grading")),console.log(chalk.white(" exam result ")+chalk.gray("View your score")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" setup ")+chalk.gray("Settings / switch mode")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log()):o?(console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(chalk.bold.white(" How it works")),console.log(),console.log(chalk.gray(" 1. Browse ")+chalk.white("challenges")+chalk.gray(" and pick one")),console.log(chalk.gray(" 2. ")+chalk.white("open <id>")+chalk.gray(" to read the challenge")),console.log(chalk.gray(" 3. Use ")+chalk.white("ai4ctf")+chalk.gray(" to chat with AI when stuck")),console.log(chalk.gray(" 4. ")+chalk.white("submit <id> icoa{flag}")+chalk.gray(" to score points")),console.log(chalk.gray(" 5. Check ")+chalk.white("scoreboard")+chalk.gray(" to track your rank")),console.log(chalk.cyan(" ═══════════════════════════════════════════════")),console.log(),console.log(chalk.bold.white(" Competition")),console.log(chalk.white(" join <url> ")+chalk.gray("Connect to CTFd")),console.log(chalk.white(" challenges (ch) ")+chalk.gray("List challenges by category")),console.log(chalk.white(" open <id> ")+chalk.gray("Read challenge + get next steps")),console.log(chalk.white(" submit <id> <flag> ")+chalk.gray("Submit a flag")),console.log(chalk.white(" scoreboard (sb) ")+chalk.gray("Live rankings")),console.log(chalk.white(" status ")+chalk.gray("Your score, budget & timer")),console.log(chalk.white(" time ")+chalk.gray("Countdown timer")),console.log(),console.log(chalk.bold.white(" AI Teammate")+chalk.gray(" — 3 levels, use wisely")),console.log(chalk.white(' hint "question" ')+chalk.gray("Level A — General guidance (50 uses)")),console.log(chalk.white(' hint-b "question" ')+chalk.gray("Level B — Deep analysis (10 uses)")),console.log(chalk.white(' hint-c "question" ')+chalk.gray("Level C — Critical assist (2 uses)")),console.log(chalk.white(" hint budget ")+chalk.gray("Check remaining uses")),console.log(chalk.white(" ai4ctf ")+chalk.gray("Free-chat with AI (no limit)")),console.log(),console.log(chalk.bold.white(" Tools")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference (linux, web, crypto...)")),console.log(chalk.white(" shell ")+chalk.gray("Docker sandbox")),console.log(chalk.white(" files <id> ")+chalk.gray("Download challenge files")),console.log(chalk.white(" connect <id> ")+chalk.gray("Connect to remote target")),console.log(chalk.white(" note [text] ")+chalk.gray("Add a logbook entry (in-exam: tags current Q)")),console.log(chalk.white(" logbook [n] ")+chalk.gray("View your logbook (in-exam: filter by Q)")),console.log(chalk.white(" log ")+chalk.gray("Session history")),console.log(chalk.white(" man / manual ")+chalk.gray("Show this command list (works in exam too, does not burn elimination)")),console.log(),console.log(chalk.bold.white(" System")),console.log(chalk.white(" setup ")+chalk.gray("Configure settings")),console.log(chalk.white(" lang [code] ")+chalk.gray("Switch language (15 supported)")),console.log(chalk.white(" logout ")+chalk.gray("Disconnect")),console.log(chalk.white(" clear ")+chalk.gray("Clear screen")),console.log(chalk.white(" exit ")+chalk.gray("Quit (session saved)")),void console.log()):(console.log(chalk.bold.yellow(" Restricted Mode — activate with a token to unlock all commands")),console.log(),console.log(chalk.white(" activate <token> ")+chalk.gray("Unlock full access")),console.log(chalk.white(" ref [topic] ")+chalk.gray("Quick reference")),console.log(chalk.white(" exit ")+chalk.gray("Quit")),void console.log())}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icoa-cli",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.252",
|
|
4
4
|
"description": "ICOA CLI — The world's first CLI-native cyber & AI security olympiad terminal: AI4CTF (Day 1), CTF4AI (Day 2), VLA4CTF (Pioneer Round — embodied AI)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|