icoa-cli 2.19.373 → 2.19.375

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{spawn as n}from"node:child_process";import{getMainRl as r}from"../lib/main-rl.js";import{existsSync as t}from"node:fs";import{dirname as l,join as a}from"node:path";import{fileURLToPath as s}from"node:url";import{loadCurriculumById as c,validateEAToken as i,syncProgress as u,syncCardFeedback as d}from"../lib/learn-curricula.js";import{normalizeTokenBody as g}from"../lib/token-format.js";import{streamLearnTutor as m,submitPqs as y,viewPqsTop as h,viewHonors as f}from"../lib/learn-ai.js";import{getConfig as p,saveConfig as b}from"../lib/config.js";import{loadLearnState as w,saveLearnState as k,newLearnState as v,updateStreak as A,markCardComplete as C,recordMCQ as I,recordCheck as $,markPracticalComplete as E,addAchievement as _}from"../lib/learn-state.js";import{renderWelcome as T,renderKnowledgeCard as M,renderMCQCard as P,renderMCQFeedback as L,renderPracticalCard as O,renderPracticalSuccess as x,renderSimDemoCard as D,renderMilestone as S,renderArenaTaskCard as q,renderComingSoonCard as j,renderStatus as N,renderPhaseComplete as R,renderCurriculumComplete as W,setLearnAiEnabled as F,setLearnPqsViewCards as B,renderHonorWall as z}from"../lib/learn-render.js";import{printError as U}from"../lib/ui.js";export function registerLearnCommand(J){J.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async J=>{J&&J.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(),J="LEARNDEMO01");let Q=J.trim().toUpperCase(),V=null;const H=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(Q),K=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Q);let X=!1;if(H)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),V=await c(Q,Q);else if(K){console.log(),console.log(chalk.gray(" Validating token..."));let e=await i(Q);if(!e.ok){const o=g(Q);if(o!==Q){const n=await i(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Q} → ${o}`)),e=n,Q=o)}}if(!e.ok)return U(`Token validation failed: ${e.message}`),console.log(),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(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 (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${e.curriculumId} · status: ${e.status}`)+(!0===e.aiEnabled?chalk.bold.magenta(" · ⭐ AI tutor"):"")),X=!0===e.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),V=await c(e.curriculumId||"LEARNDEMO01",Q),!V)return U(`Could not open a learn curriculum for token '${Q}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Q}`)+chalk.gray(" instead.")),console.log(chalk.gray(" Otherwise: the full curriculum is ~3 MB; on a slow link the download")),console.log(chalk.gray(" can take a while — stay on a stable connection and run ")+chalk.bold.yellow(`learn ${Q}`)+chalk.gray(" again")),console.log(chalk.gray(" (it caches after the first load). If it keeps failing, check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()}if(!V)return U(`Unknown learn token: ${Q}`),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 Z=w(),G=!1;try{Z&&Z.token===Q?A(Z):(Z=v(Q,V.id,V.totalCards),G=!0),k(Z),T(V,Z,G)}catch{return U("Could not open this curriculum — it may be malformed or not a learn curriculum."),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Q}`)+chalk.gray(".")),void console.log()}const Y=r(),ee=null!==Y,oe=ee?Y.listeners("line").slice():[];ee&&Y.removeAllListeners("line");const ne=ee?Y:o({input:process.stdin,output:process.stdout,terminal:!0}),re=ee?ne.prompt:null;ee&&(ne.prompt=e.prototype.prompt);const te=()=>{ee&&re&&(ne.prompt=re)},le=()=>{ne.setPrompt(chalk.bold.cyan(ue?"icoa learn ai> ":"icoa learn> ")),ne.prompt()};let ae=null,se=null,ce=null,ie=null,ue=!1,de=!1;const ge=new Map,me=()=>{let e=ge.get(Z.currentCard);return e||(e=[],ge.set(Z.currentCard,e)),e};let ye=!1;const he=new Set;let fe=!1,pe=0;const be=(p().language||"en").toLowerCase().startsWith("zh");F(X),B(he);const we=[];let ke=null;const ve=new Promise(e=>{ke=e}),Ae=()=>{const e=ke;ke=null,e?.()},Ce="1"===process.env.ICOA_LEARN_EMBEDDED,Ie=e=>V.cards.find(o=>o.number===e),$e=e=>{const o=V.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=V.modules.find(e=>e.number===o.number+1);return R(V,Z,o,n),!0},Ee=()=>{fe=!0,console.log(chalk.gray(be?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},_e=()=>{const e=Ie(Z.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":M(e,V),e.check?(ce=e.number,pe=Date.now()):(C(Z,e.number),k(Z));break;case"mcq":P(e,V),ae=e.number;break;case"practical":O(e,V),se=e.number;break;case"sim_demo":D(e,V),C(Z,e.number),k(Z);break;case"milestone":S(e,V),_(Z,e.badge),C(Z,e.number),k(Z);break;case"arena_task":q(e,V),C(Z,e.number),k(Z);break;case"coming_soon":j(e,V),C(Z,e.number),k(Z)}},Te=()=>{Q.endsWith("DEMO01")?console.log(chalk.yellow(be?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(be?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(be?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Me=async(e,o)=>{if(X){de=!0;try{console.log(),console.log(chalk.gray("deep"===o?be?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":be?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let n=!1,r=!1;const t=await m({token:Q,cardNumber:Z.currentCard,question:e,mode:o,history:me().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(r||(process.stdout.write(n?"\n\n ":" "),r=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||r)&&console.log(),t.ok?t.offtopic?(console.log(),console.log(chalk.yellow(be?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(me().push({role:"user",content:e},{role:"assistant",content:t.answer}),null!=t.spent&&null!=t.cap&&t.spent/t.cap>.8&&console.log(chalk.gray(` (${be?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(be?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==ce&&console.log(chalk.gray(be?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{de=!1}}else Te()},Pe=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Le=async e=>{const o=e.trim().toLowerCase();if(!de){if(null!==ie){const o=e.trim(),n=ie;if(ie=null,""===o)console.log(chalk.gray(be?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=pe>0?Date.now()-pe:void 0;we.push(d(Q,{curriculum_id:V.id,card_number:n,feedback_text:o,time_on_card_ms:e}).catch(()=>{})),console.log(chalk.green(be?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void le()}if(ye){ye=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{de=!0;try{console.log(),console.log(chalk.gray(be?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await y({token:Q,cardNumber:Z.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(be?"评审暂不可用。":"Review unavailable.")}`)),void console.log();(e=>{const o="green"===e.tier?chalk.bold.green:"blue"===e.tier?chalk.bold.cyan:"yellow"===e.tier?chalk.bold.yellow:chalk.bold.red;if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.white(be?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(be?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(be?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(be?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(be?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(be?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=be?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(be?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(be?` 第 ${e.submissionIndex??"?"} / 2 次提交 · 剩余 ${e.submissionsLeft??0} 次(可先追加 /ai 对话再交)`:` Attempt ${e.submissionIndex??"?"} of 2 · ${e.submissionsLeft??0} left (extend the /ai conversation before your next one)`)),e.feedback){console.log();for(const o of Pe(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(be?" 改进提问: ":" Ask better: ")+chalk.gray(e.improve))),console.log(chalk.gray(" ─────────────────────────────────────────")),null!=e.spent&&null!=e.cap&&e.spent/e.cap>.8&&console.log(chalk.gray(` (${be?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?he.add(Z.currentCard):he.delete(Z.currentCard);const o=await f({token:Q,curriculumId:V.id,cardNumber:Z.currentCard});o.ok&&o.totals&&o.chapters&&(z({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log())}finally{de=!1}})():(console.log(chalk.gray(be?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==ce&&(console.log(chalk.gray(be?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void le()}if(fe)return fe=!1,_e(),void le();if(o){if(ue){if(["q","quit","exit","back","b","menu"].includes(o))return ue=!1,console.log(chalk.gray(be?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void le();const n=e.trim().startsWith("!"),r=n?e.trim().slice(1).trim():e.trim();return r&&await Me(r,n?"fast":"deep"),void le()}if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!X)return Te(),void le();const n=o.startsWith("/ai!"),r=e.trim().slice(n?4:3).trim();if(!r){ue=!0;const e=Ie(Z.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(be?"AI 导师":"AI tutor")+(o?chalk.gray(be?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(be?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void le()}return await Me(r,n?"fast":"deep"),void le()}if("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research ")){if(!X)return Te(),void le();const e=Ie(Z.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(be?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(be?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(be?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(be?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(be?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(be?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(be?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),ye=!0,void le()}if("/view"===o)return X?(await(async()=>{de=!0;try{console.log();const e=await h({token:Q,cardNumber:Z.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(be?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&he.delete(Z.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&he.add(Z.currentCard),console.log(chalk.bold.white(be?` 🏆 本卡 Top-3 提问 — 第 ${Z.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${Z.currentCard} · ${e.entrants??0} entrant(s)`));for(const o of e.top3??[]){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── Rank ${o.rank}`)+(o.me?chalk.bold.magenta(" (me)"):"")+chalk.white(` · ${o.score}`)+` ${e}`),o.questions.forEach((e,o)=>{const n=Pe(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(" "+e))}),0===o.questions.length&&console.log(chalk.gray(be?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{de=!1}})(),void le()):(Te(),void le());if("/honors"===o||"honors"===o)return H?(console.log(),console.log(chalk.gray(be?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void le()):(await(async()=>{de=!0;try{console.log();const e=await f({token:Q,curriculumId:V.id,cardNumber:Z.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(be?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(be?` 🏆 本卡实时 Top-3 — 第 ${Z.currentCard} 张`:` 🏆 Live top-3 — card ${Z.currentCard}`)),e.board&&0!==e.board.length)for(const o of e.board){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(chalk.white(` ${o.icon} `)+chalk.bold.cyan(`#${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(" (me)"):""))}else console.log(chalk.gray(be?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),z({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log()}finally{de=!1}})(),void le());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return N(V,Z),void le();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(p().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void le();const n=V.cards.some(e=>null!=e._zh),r=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),t="en"===r||"zh"===r&&n,l=t?r:"en";return b({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),ce=null,ae=null,se=null,ie=null,fe=!1,ye=!1,_e(),void le()}if("sim"===o){const e=Ie(Z.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=l(s(import.meta.url)),o=[a(e,"..","..","panda","mujoco-launcher.py"),a(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(t(e))return e;return null}();if(!o)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 r={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${r})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),n("python3",[o,r,"--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 le()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void le())}if("bookmark"===o){const e=Z.currentCard;return Z.bookmarks.includes(e)||Z.bookmarks.push(e),k(Z),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void le()}if("e"===o)return ie=Z.currentCard,console.log(chalk.gray(be?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void le();if("back"===o||"b"===o)return Z.currentCard>1&&(Z.currentCard-=1),ae=null,se=null,ce=null,k(Z),_e(),void le();if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);return!Number.isInteger(n)||n<1||n>V.totalCards?(console.log(chalk.yellow(` Card number must be 1..${V.totalCards}. Try: `)+chalk.bold.green("card 1")),void le()):(Z.currentCard=n,ae=null,se=null,ce=null,k(Z),_e(),void le())}if(null!==ce&&["y","yes","n","no"].includes(o)){const e=Ie(ce);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",r=n===e.check.answer,t=Date.now()-pe;C(Z,e.number),$(Z,e.number,{answer:n,correct:r,submittedAt:(new Date).toISOString()}),k(Z);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,r,!1),we.push(u(Q,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:r,time_on_card_ms:t}).catch(()=>{})),ce=null,e.solution&&e.solution.length>0)return void le();if(Z.currentCard<V.totalCards){const e=Z.currentCard;Z.currentCard+=1,k(Z),$e(e)?Ee():_e(),le()}else W(V,Z),le();return}}if(null!==ae&&["a","b","c","d"].includes(o)){const e=Ie(ae);if(e&&"mcq"===e.type){const n=o.toUpperCase(),r=n===e.answer;return I(Z,e.number,{answer:n,correct:r,submittedAt:(new Date).toISOString()}),C(Z,e.number),k(Z),L(e,n,r,Z),we.push(u(Q,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:r}).catch(()=>{})),ae=null,void(r?Z.currentCard<V.totalCards?(Z.currentCard+=1,k(Z),_e()):(W(V,Z),le()):le())}}if(null!==se){if("done"===o){const e=Ie(se);if(e&&"practical"===e.type)return E(Z,e.number),C(Z,e.number),k(Z),x(e),se=null,void le()}if("skip"===o)return C(Z,se),k(Z),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),se=null,void le()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ae)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void le();if(null!==se)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void le();if(null!==ce)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void le();const e=Z.currentCard;return Z.currentCard+=1,k(Z),Z.currentCard>V.totalCards?W(V,Z):$e(e)?Ee():_e(),void le()}if(null!==ce)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void le();if(null!==ae)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void le();if(null!==se)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void le();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("/ai")+chalk.gray(" / ")+chalk.white("quit")),le()}else if(we.length>0&&await Promise.race([Promise.allSettled(we),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Z.streakDays} day(s)`)),console.log(),ee){ne.removeAllListeners("line"),te();for(const e of oe)ne.on("line",e);ne.prompt(),Ae()}else ne.removeAllListeners("line"),ne.close();else if(we.length>0&&await Promise.race([Promise.allSettled(we),new Promise(e=>setTimeout(e,3e3))]),ne.removeAllListeners("line"),te(),ee||!Ce){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ee?ne:void 0),Ae()}else ne.close()}else le()}};ne.on("line",e=>{Le(e).catch(e=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),le()})}),ee||ne.on("close",async()=>{we.length>0&&await Promise.race([Promise.allSettled(we),new Promise(e=>setTimeout(e,5e3))]),Ce?Ae():process.exit(0)});try{_e(),le()}catch{if(U("Could not render this card — the curriculum may be malformed."),ee){ne.removeAllListeners("line"),te();for(const e of oe)ne.on("line",e);ne.prompt()}else ne.close();Ae()}await ve}),J.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: https://practice.icoa2026.au")),console.log();let n=0,r=0,t=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await c(e),a=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,r=JSON.stringify(l).length;t+=r,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(r/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),r++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${r} failed · total ${(t/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as o,createInterface as e}from"node:readline";import{spawn as r}from"node:child_process";import{getMainRl as n}from"../lib/main-rl.js";import{handleAi4ioaiMessage as t,startAi4ioaiChat as l}from"./ai4ioai.js";import{existsSync as a}from"node:fs";import{dirname as s,join as i}from"node:path";import{fileURLToPath as c}from"node:url";import{loadCurriculumById as u,validateEAToken as d,syncProgress as g,syncCardFeedback as m}from"../lib/learn-curricula.js";import{normalizeTokenBody as y}from"../lib/token-format.js";import{streamLearnTutor as h,submitPqs as f,viewPqsTop as p,viewHonors as w}from"../lib/learn-ai.js";import{getConfig as b,saveConfig as k}from"../lib/config.js";import{loadLearnState as v,saveLearnState as A,newLearnState as C,updateStreak as I,markCardComplete as $,recordMCQ as E,recordCheck as _,markPracticalComplete as T,addAchievement as M}from"../lib/learn-state.js";import{renderWelcome as P,renderKnowledgeCard as x,renderMCQCard as L,renderMCQFeedback as O,renderPracticalCard as D,renderPracticalSuccess as S,renderSimDemoCard as q,renderMilestone as j,renderArenaTaskCard as N,renderComingSoonCard as R,renderStatus as W,renderPhaseComplete as F,renderCurriculumComplete as B,setLearnAiEnabled as z,setLearnPqsViewCards as U,renderHonorWall as J}from"../lib/learn-render.js";import{printError as Q}from"../lib/ui.js";export function registerLearnCommand(V){V.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async V=>{V&&V.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(),V="LEARNDEMO01");let H=V.trim().toUpperCase(),K=null;const X=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(H),Z=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(H);let G=!1;if(X)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),K=await u(H,H);else if(Z){console.log(),console.log(chalk.gray(" Validating token..."));let o=await d(H);if(!o.ok){const e=y(H);if(e!==H){const r=await d(e);r.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${H} → ${e}`)),o=r,H=e)}}if(!o.ok)return Q(`Token validation failed: ${o.message}`),console.log(),"device_bound"===o.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(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 (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${o.curriculumId} · status: ${o.status}`)+(!0===o.aiEnabled?chalk.bold.magenta(" · ⭐ AI tutor"):"")),G=!0===o.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),K=await u(o.curriculumId||"LEARNDEMO01",H),!K)return Q(`Could not open a learn curriculum for token '${H}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${H}`)+chalk.gray(" instead.")),console.log(chalk.gray(" Otherwise: the full curriculum is ~3 MB; on a slow link the download")),console.log(chalk.gray(" can take a while — stay on a stable connection and run ")+chalk.bold.yellow(`learn ${H}`)+chalk.gray(" again")),console.log(chalk.gray(" (it caches after the first load). If it keeps failing, check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()}if(!K)return Q(`Unknown learn token: ${H}`),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 Y=v(),oo=!1;try{Y&&Y.token===H?I(Y):(Y=C(H,K.id,K.totalCards),oo=!0),A(Y),P(K,Y,oo)}catch{return Q("Could not open this curriculum — it may be malformed or not a learn curriculum."),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${H}`)+chalk.gray(".")),void console.log()}const eo=n(),ro=null!==eo,no=ro?eo.listeners("line").slice():[];ro&&eo.removeAllListeners("line");const to=ro?eo:e({input:process.stdin,output:process.stdout,terminal:!0}),lo=ro?to.prompt:null;ro&&(to.prompt=o.prototype.prompt);const ao=()=>{ro&&lo&&(to.prompt=lo)},so=()=>{to.setPrompt(ho?chalk.bold.green("icoa ai4ioai> "):chalk.bold.cyan(mo?"icoa learn ai> ":"icoa learn> ")),to.prompt()};let io=null,co=null,uo=null,go=null,mo=!1,yo=!1,ho=!1;const fo=new Map,po=()=>{let o=fo.get(Y.currentCard);return o||(o=[],fo.set(Y.currentCard,o)),o};let wo=!1;const bo=new Set;let ko=!1,vo=0;const Ao=(b().language||"en").toLowerCase().startsWith("zh");z(G),U(bo);const Co=[];let Io=null;const $o=new Promise(o=>{Io=o}),Eo=()=>{const o=Io;Io=null,o?.()},_o="1"===process.env.ICOA_LEARN_EMBEDDED,To=o=>K.cards.find(e=>e.number===o),Mo=o=>{const e=K.modules.find(e=>e.cardRange[1]===o);if(!e)return!1;const r=K.modules.find(o=>o.number===e.number+1);return F(K,Y,e,r),!0},Po=()=>{ko=!0,console.log(chalk.gray(Ao?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},xo=()=>{const o=To(Y.currentCard);if(!o)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(o.type){case"knowledge":x(o,K),o.check?(uo=o.number,vo=Date.now()):($(Y,o.number),A(Y));break;case"mcq":L(o,K),io=o.number;break;case"practical":D(o,K),co=o.number;break;case"sim_demo":q(o,K),$(Y,o.number),A(Y);break;case"milestone":j(o,K),M(Y,o.badge),$(Y,o.number),A(Y);break;case"arena_task":N(o,K),$(Y,o.number),A(Y);break;case"coming_soon":R(o,K),$(Y,o.number),A(Y)}},Lo=()=>{H.endsWith("DEMO01")?console.log(chalk.yellow(Ao?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Ao?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Ao?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Oo=async(o,e)=>{if(G){yo=!0;try{console.log(),console.log(chalk.gray("deep"===e?Ao?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Ao?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let r=!1,n=!1;const t=await h({token:H,cardNumber:Y.currentCard,question:o,mode:e,history:po().slice(-8)},o=>{"reasoning"===o.kind?(r||(process.stdout.write(" "),r=!0),process.stdout.write(chalk.dim(o.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(r?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(o.text.replace(/\n/g,"\n "))))});(r||n)&&console.log(),t.ok?t.offtopic?(console.log(),console.log(chalk.yellow(Ao?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(po().push({role:"user",content:o},{role:"assistant",content:t.answer}),null!=t.spent&&null!=t.cap&&t.spent/t.cap>.8&&console.log(chalk.gray(` (${Ao?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(Ao?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==uo&&console.log(chalk.gray(Ao?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{yo=!1}}else Lo()},Do=o=>o.match(/.{1,64}(\s|$)/g)?.map(o=>o.trim())??[o],So=async o=>{const e=o.trim().toLowerCase();if(!yo){if(null!==go){const e=o.trim(),r=go;if(go=null,""===e)console.log(chalk.gray(Ao?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const o=vo>0?Date.now()-vo:void 0;Co.push(m(H,{curriculum_id:K.id,card_number:r,feedback_text:e,time_on_card_ms:o}).catch(()=>{})),console.log(chalk.green(Ao?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void so()}if(wo){wo=!1;const e=o.trim().toLowerCase();return"y"===e||"yes"===e?await(async()=>{yo=!0;try{console.log(),console.log(chalk.gray(Ao?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const o=await f({token:H,cardNumber:Y.currentCard});if(console.log(),!o.ok)return console.log(chalk.yellow(` ${o.message||(Ao?"评审暂不可用。":"Review unavailable.")}`)),void console.log();(o=>{const e="green"===o.tier?chalk.bold.green:"blue"===o.tier?chalk.bold.cyan:"yellow"===o.tier?chalk.bold.yellow:chalk.bold.red;if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.white(Ao?" 提问评分 ":" Prompt score ")+e(`${o.score??0} / 100`)+chalk.gray(" "+(o=>{switch(o){case"green":return"🟢 "+(Ao?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Ao?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Ao?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Ao?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(o.tier))),o.manipulation&&console.log(chalk.red(Ao?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=o.rank&&null!=o.entrants){const e=!0===o.inTop3,r=Ao?` 本卡排名 #${o.rank} / ${o.entrants}`:` Rank on this card: #${o.rank} of ${o.entrants}`;console.log((e?chalk.bold.green(r):chalk.white(r))+(e?chalk.bold.magenta(Ao?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Ao?` 第 ${o.submissionIndex??"?"} / 2 次提交 · 剩余 ${o.submissionsLeft??0} 次(可先追加 /ai 对话再交)`:` Attempt ${o.submissionIndex??"?"} of 2 · ${o.submissionsLeft??0} left (extend the /ai conversation before your next one)`)),o.feedback){console.log();for(const e of Do(o.feedback))console.log(chalk.white(" "+e))}o.improve&&(console.log(),console.log(chalk.cyan(Ao?" 改进提问: ":" Ask better: ")+chalk.gray(o.improve))),console.log(chalk.gray(" ─────────────────────────────────────────")),null!=o.spent&&null!=o.cap&&o.spent/o.cap>.8&&console.log(chalk.gray(` (${Ao?"AI 额度":"AI budget"}: ${Math.round(o.spent/1e3)}k / ${Math.round(o.cap/1e3)}k tokens)`)),console.log()})(o),!0===o.inTop3?bo.add(Y.currentCard):bo.delete(Y.currentCard);const e=await w({token:H,curriculumId:K.id,cardNumber:Y.currentCard});e.ok&&e.totals&&e.chapters&&(J({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log())}finally{yo=!1}})():(console.log(chalk.gray(Ao?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==uo&&(console.log(chalk.gray(Ao?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void so()}if(ko)return ko=!1,xo(),void so();if(e){if(ho)return"exit"===await t(o.trim())&&(ho=!1),void so();if(mo){if(["q","quit","exit","back","b","menu"].includes(e))return mo=!1,console.log(chalk.gray(Ao?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void so();const r=o.trim().startsWith("!"),n=r?o.trim().slice(1).trim():o.trim();return n&&await Oo(n,r?"fast":"deep"),void so()}if("ai4ioai"===e||"/ai4ioai"===e)return await l()&&(ho=!0),void so();if("/ai"===e||"/ai!"===e||e.startsWith("/ai ")||e.startsWith("/ai! ")){if(!G)return Lo(),void so();const r=e.startsWith("/ai!"),n=o.trim().slice(r?4:3).trim();if(!n){mo=!0;const o=To(Y.currentCard),e=o?o.title??o.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Ao?"AI 导师":"AI tutor")+(e?chalk.gray(Ao?` — 主题「${e}」`:` — topic “${e}”`):"")),console.log(chalk.gray(Ao?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void so()}return await Oo(n,r?"fast":"deep"),void so()}if("/submit"===e||e.startsWith("/submit ")||"/research"===e||e.startsWith("/research ")){if(!G)return Lo(),void so();const o=To(Y.currentCard),e=o?o.title??o.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Ao?"Panda 提问评审":"Panda's prompt review")+(e?chalk.gray(Ao?` — 主题「${e}」`:` — topic “${e}”`):"")),console.log(chalk.gray(Ao?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Ao?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Ao?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Ao?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Ao?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),wo=!0,void so()}if("/view"===e)return G?(await(async()=>{yo=!0;try{console.log();const o=await p({token:H,cardNumber:Y.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Ao?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&bo.delete(Y.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&bo.add(Y.currentCard),console.log(chalk.bold.white(Ao?` 🏆 本卡 Top-3 提问 — 第 ${Y.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${Y.currentCard} · ${o.entrants??0} entrant(s)`));for(const e of o.top3??[]){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── Rank ${e.rank}`)+(e.me?chalk.bold.magenta(" (me)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((o,e)=>{const r=Do(o);console.log(chalk.gray(` Q${e+1} `)+chalk.white(r[0]??""));for(const o of r.slice(1))console.log(chalk.white(" "+o))}),0===e.questions.length&&console.log(chalk.gray(Ao?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{yo=!1}})(),void so()):(Lo(),void so());if("/honors"===e||"honors"===e)return X?(console.log(),console.log(chalk.gray(Ao?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void so()):(await(async()=>{yo=!0;try{console.log();const o=await w({token:H,curriculumId:K.id,cardNumber:Y.currentCard});if(!o.ok||!o.totals||!o.chapters)return console.log(chalk.yellow(` ${o.message||(Ao?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Ao?` 🏆 本卡实时 Top-3 — 第 ${Y.currentCard} 张`:` 🏆 Live top-3 — card ${Y.currentCard}`)),o.board&&0!==o.board.length)for(const e of o.board){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(chalk.white(` ${e.icon} `)+chalk.bold.cyan(`#${e.rank}`)+chalk.white(` · ${e.score} `)+o+(e.me?chalk.bold.magenta(" (me)"):""))}else console.log(chalk.gray(Ao?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),J({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()}finally{yo=!1}})(),void so());if("menu"!==e&&"menu confirm"!==e)if("quit"!==e&&"exit"!==e&&"q"!==e){if("status"===e)return W(K,Y),void so();if("lang"===e||e.startsWith("lang ")){const o=e.slice(4).trim();if(!o)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(b().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void so();const r=K.cards.some(o=>null!=o._zh),n=o.toLowerCase().startsWith("zh")?"zh":o.toLowerCase(),t="en"===n||"zh"===n&&r,l=t?n:"en";return k({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${o} 本课暂无翻译,已用英文 / not available — using English`)),uo=null,io=null,co=null,go=null,ko=!1,wo=!1,xo(),void so()}if("sim"===e){const o=To(Y.currentCard);return o&&"sim_demo"===o.type?(function(o){const e=function(){const o=s(c(import.meta.url)),e=[i(o,"..","..","panda","mujoco-launcher.py"),i(o,"..","..","..","panda","mujoco-launcher.py")];for(const o of e)if(a(o))return o;return null}();if(!e)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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[o]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[e,n,"--seconds","5"],{stdio:"inherit"}).on("exit",o=>{0!==o?console.log(chalk.yellow(` MuJoCo exited with code ${o} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(o.simAction),void so()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void so())}if("bookmark"===e){const o=Y.currentCard;return Y.bookmarks.includes(o)||Y.bookmarks.push(o),A(Y),console.log(chalk.gray(` ✓ Card ${o} bookmarked.`)),void so()}if("e"===e)return go=Y.currentCard,console.log(chalk.gray(Ao?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void so();if("back"===e||"b"===e)return Y.currentCard>1&&(Y.currentCard-=1),io=null,co=null,uo=null,A(Y),xo(),void so();if(e.startsWith("card ")){const o=e.slice(5).trim(),r=parseInt(o,10);return!Number.isInteger(r)||r<1||r>K.totalCards?(console.log(chalk.yellow(` Card number must be 1..${K.totalCards}. Try: `)+chalk.bold.green("card 1")),void so()):(Y.currentCard=r,io=null,co=null,uo=null,A(Y),xo(),void so())}if(null!==uo&&["y","yes","n","no"].includes(e)){const o=To(uo);if(o&&"knowledge"===o.type&&o.check){const r=e.startsWith("y")?"y":"n",n=r===o.check.answer,t=Date.now()-vo;$(Y,o.number),_(Y,o.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),A(Y);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(o,r,n,!1),Co.push(g(H,{card_number:o.number,event_type:"check_answered",check_answer:r,check_correct:n,time_on_card_ms:t}).catch(()=>{})),uo=null,o.solution&&o.solution.length>0)return void so();if(Y.currentCard<K.totalCards){const o=Y.currentCard;Y.currentCard+=1,A(Y),Mo(o)?Po():xo(),so()}else B(K,Y),so();return}}if(null!==io&&["a","b","c","d"].includes(e)){const o=To(io);if(o&&"mcq"===o.type){const r=e.toUpperCase(),n=r===o.answer;return E(Y,o.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),$(Y,o.number),A(Y),O(o,r,n,Y),Co.push(g(H,{card_number:o.number,event_type:"mcq_answered",mcq_answer:r,mcq_correct:n}).catch(()=>{})),io=null,void(n?Y.currentCard<K.totalCards?(Y.currentCard+=1,A(Y),xo()):(B(K,Y),so()):so())}}if(null!==co){if("done"===e){const o=To(co);if(o&&"practical"===o.type)return T(Y,o.number),$(Y,o.number),A(Y),S(o),co=null,void so()}if("skip"===e)return $(Y,co),A(Y),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),co=null,void so()}if("ok"===e||"next"===e||"continue"===e||"n"===e){if(null!==io)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void so();if(null!==co)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void so();if(null!==uo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void so();const o=Y.currentCard;return Y.currentCard+=1,A(Y),Y.currentCard>K.totalCards?B(K,Y):Mo(o)?Po():xo(),void so()}if(null!==uo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void so();if(null!==io)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void so();if(null!==co)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void so();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("/ai")+chalk.gray(" / ")+chalk.white("quit")),so()}else if(Co.length>0&&await Promise.race([Promise.allSettled(Co),new Promise(o=>setTimeout(o,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Y.streakDays} day(s)`)),console.log(),ro){to.removeAllListeners("line"),ao();for(const o of no)to.on("line",o);to.prompt(),Eo()}else to.removeAllListeners("line"),to.close();else if(Co.length>0&&await Promise.race([Promise.allSettled(Co),new Promise(o=>setTimeout(o,3e3))]),to.removeAllListeners("line"),ao(),ro||!_o){const{returnToMainMenu:o}=await import("../lib/menu-nav.js");o(ro?to:void 0),Eo()}else to.close()}else so()}};to.on("line",o=>{So(o).catch(o=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),so()})}),ro||to.on("close",async()=>{Co.length>0&&await Promise.race([Promise.allSettled(Co),new Promise(o=>setTimeout(o,5e3))]),_o?Eo():process.exit(0)});try{xo(),so()}catch{if(Q("Could not render this card — the curriculum may be malformed."),ro){to.removeAllListeners("line"),ao();for(const o of no)to.on("line",o);to.prompt()}else to.close();Eo()}await $o}),V.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async o=>{const e=o?[o.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: https://practice.icoa2026.au")),console.log();let r=0,n=0,t=0;for(const o of e){process.stdout.write(` ${o.padEnd(22)} `);const e=Date.now(),l=await u(o),a=Date.now()-e;if(l){const o=l.cards,e=Array.isArray(o)?o.length:0,n=JSON.stringify(l).length;t+=n,console.log(chalk.green("✓ ")+chalk.gray(`${e.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 ${(t/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{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as a}from"./commands/challenge.js";import{registerDoctorCommand as l}from"./commands/doctor.js";import{registerNoteCommand as m}from"./commands/note.js";import{registerLogCommand as c}from"./commands/log.js";import{registerLangCommand as g}from"./commands/lang.js";import{registerSetupCommand as d}from"./commands/setup.js";import{registerEnvCommand as p}from"./commands/env.js";import{registerAienvCommand as y}from"./commands/aienv.js";import{registerIpynbCommand as f}from"./commands/ipynb.js";import{registerAi4ctfCommand as h}from"./commands/ai4ctf.js";import{registerExamCommand as u}from"./commands/exam.js";import{registerCtf4aiDemoCommand as w}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as T}from"./commands/theme.js";import{registerLearnCommand as v}from"./commands/learn.js";import{registerCtf4VlaCommand as b}from"./commands/ctf4vla.js";import{registerDemo2Command as j}from"./commands/demo2.js";import{registerSimCommand as A}from"./commands/sim.js";import{registerArenaCommand as I}from"./commands/arena.js";import{getConfig as $,saveConfig as C}from"./lib/config.js";import{startRepl as E}from"./repl.js";import{RELAUNCH_CODE as _}from"./lib/menu-nav.js";import{setTerminalTheme as S}from"./lib/theme.js";import{checkForUpdates as x}from"./lib/update-check.js";import{detectIcoaInstalls as O}from"./lib/platform.js";import{ICOA_BIG as L}from"./lib/banner.js";import{readFileSync as N}from"node:fs";import{fileURLToPath as R}from"node:url";import{dirname as k,join as F}from"node:path";const U=k(R(import.meta.url)),P=JSON.parse(N(F(U,"..","package.json"),"utf-8")).version,M=chalk.cyan(" ─────────────────────────────────────────────────────"),G=`\n${M}\n\n${L.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${P}`)}\n\n${M}\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===_);process.exit(e??0)}}const D=new o;if(D.name("icoa").version(P).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=$();S("high-contrast"===e.themeVariant?"high-contrast":"dark"),x(),function(){const o=O();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();console.log(G);const s=!!o.resume||!!o.continue;if(process.argv.length<=2||s)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),s||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void E(D,s)}),e(D),n(D),s(D),r(D),t(D),i(D),a(D),l(D),m(D),c(D),g(D),d(D),p(D),y(D),f(D),h(D),u(D),w(D),T(D),v(D),b(D),j(D),A(D),I(D),D.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=$().geminiModel||"gemini-2.5-flash-lite";o?(C({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)))}D.parse();
2
+ import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as i}from"./commands/connect.js";import{registerChallengeCommand as a}from"./commands/challenge.js";import{registerDoctorCommand as l}from"./commands/doctor.js";import{registerNoteCommand as m}from"./commands/note.js";import{registerLogCommand as c}from"./commands/log.js";import{registerLangCommand as d}from"./commands/lang.js";import{registerSetupCommand as g}from"./commands/setup.js";import{registerEnvCommand as p}from"./commands/env.js";import{registerAienvCommand as y}from"./commands/aienv.js";import{registerIpynbCommand as f}from"./commands/ipynb.js";import{registerAi4ctfCommand as h}from"./commands/ai4ctf.js";import{registerExamCommand as u}from"./commands/exam.js";import{registerCtf4aiDemoCommand as w}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as T}from"./commands/theme.js";import{registerLearnCommand as b}from"./commands/learn.js";import{registerCtf4VlaCommand as v}from"./commands/ctf4vla.js";import{registerDemo2Command as j}from"./commands/demo2.js";import{registerSimCommand as A}from"./commands/sim.js";import{registerArenaCommand as I}from"./commands/arena.js";import{registerBoardCommand as $}from"./commands/board.js";import{getConfig as C,saveConfig as E}from"./lib/config.js";import{startRepl as _}from"./repl.js";import{RELAUNCH_CODE as S}from"./lib/menu-nav.js";import{setTerminalTheme as x}from"./lib/theme.js";import{checkForUpdates as O}from"./lib/update-check.js";import{detectIcoaInstalls as L}from"./lib/platform.js";import{ICOA_BIG as N}from"./lib/banner.js";import{readFileSync as R}from"node:fs";import{fileURLToPath as k}from"node:url";import{dirname as F,join as U}from"node:path";const P=F(k(import.meta.url)),M=JSON.parse(R(U(P,"..","package.json"),"utf-8")).version,G=chalk.cyan(" ─────────────────────────────────────────────────────"),D=`\n${G}\n\n${N.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${M}`)}\n\n${G}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=o(process.execPath,process.argv.slice(1),{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(s.signal){e=0;break}e=s.status,n=!0}while(e===S);process.exit(e??0)}}const H=new o;if(H.name("icoa").version(M).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=C();x("high-contrast"===e.themeVariant?"high-contrast":"dark"),O(),function(){const o=L();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();console.log(D);const s=!!o.resume||!!o.continue;if(process.argv.length<=2||s)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),s||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void _(H,s)}),e(H),n(H),s(H),r(H),t(H),i(H),a(H),l(H),m(H),c(H),d(H),g(H),p(H),y(H),f(H),h(H),u(H),w(H),T(H),b(H),v(H),j(H),A(H),I(H),$(H),H.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=C().geminiModel||"gemini-2.5-flash-lite";o?(E({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}H.parse();
@@ -1 +1 @@
1
- import{createHash as t,randomUUID as e}from"node:crypto";import{execSync as n}from"node:child_process";import{platform as r}from"node:os";import{getConfig as i,saveConfig as o,getIcoaDir as c}from"./config.js";import{readFileSync as s,writeFileSync as a,existsSync as u}from"node:fs";import{join as f}from"node:path";const p=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return i().lastVersion!==t}export function markVersionSeen(t){o({lastVersion:t})}const l=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb"]);export function isActivated(){return!!i().accessToken}export function getDeviceFingerprint(){const c=i();if(c.deviceFingerprint)return c.deviceFingerprint;let a=c.installSalt;a||(a=e(),o({installSalt:a}));const f=function(){try{if("darwin"===r()){const t=n("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===r()){if(u("/etc/machine-id"))return s("/etc/machine-id","utf-8").trim()}else if("win32"===r())return n('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${f}|${a}`).digest("hex")}export function activateToken(e){if(!function(t){return p.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=f(c(),"token-bindings.json");let i={};if(u(r))try{i=JSON.parse(s(r,"utf-8"))}catch{}const l=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),d=i[l];return d&&d!==n?"already_bound":(i[l]=n,a(r,JSON.stringify(i,null,2)),o({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=i();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return l.has(t.toLowerCase())}const d=()=>f(c(),"session-state.json");function m(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function g(){const t=d();if(!u(t))return m();try{return{...m(),...JSON.parse(s(t,"utf-8"))}}catch{return m()}}function x(t){const e={...g(),...t};a(d(),JSON.stringify(e,null,2))}export function recordExit(){const t=g();t.lastExitAt=(new Date).toISOString(),t.exitCount++,x(t)}export function recordResume(){const t=g();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,x(t),{awaySeconds:r,exitCount:t.exitCount}}
1
+ import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * board-render — pure formatting for the ICOA Board CLI (no chalk, no I/O;
3
+ * caller applies colors). Mirrors the arena-submit.ts pure-module pattern.
4
+ */
5
+ export interface BoardRow {
6
+ rank: number;
7
+ label: string;
8
+ value?: number | null;
9
+ display_score?: number | null;
10
+ total_display?: number | null;
11
+ tasks_counted?: number;
12
+ }
13
+ export declare function deltaLine(prevRank: number | null | undefined, rank: number | null | undefined, fieldSize: number | null | undefined): string;
14
+ export declare function renderBoardLines(rows: BoardRow[], width: number): string[];
@@ -0,0 +1 @@
1
+ export function deltaLine(e,l,n){return null==l||null==n?"":null==e?`entered the board at #${l} of ${n}`:l<e?`▲ up ${e-l} — now #${l} of ${n}`:l>e?`best unchanged — slipped to #${l} of ${n}`:`best unchanged — still #${l} of ${n}`}export function renderBoardLines(e,l){return e.map(e=>{const n=null!=e.total_display?`${e.total_display.toFixed(1)}${null!=e.tasks_counted?` (${e.tasks_counted} tasks)`:""}`:null!=e.value?`${e.value}${null!=e.display_score?` ${e.display_score.toFixed(1)}/100`:""}`:"",t=`#${e.rank} ${e.label} ${n}`.trimEnd(),o=Array.from(t);return o.length>l?`${o.slice(0,l-1).join("")}…`:t})}
@@ -4,4 +4,5 @@ export declare function saveConfig(config: Partial<IcoaConfig>): void;
4
4
  export declare function getBudget(): HintBudget;
5
5
  export declare function saveBudget(budget: HintBudget): void;
6
6
  export declare function getIcoaDir(): string;
7
+ export declare function getInstallSalt(): string;
7
8
  export declare function isConnected(): boolean;
@@ -1 +1 @@
1
- import{mkdirSync as t,readFileSync as n,writeFileSync as o,existsSync as r,chmodSync as e,statSync as i}from"node:fs";import{join as c}from"node:path";import{homedir as f}from"node:os";import{randomUUID as s}from"node:crypto";import{DEFAULT_CONFIG as u,DEFAULT_BUDGET as g}from"../types/index.js";const p=c(f(),".icoa"),d=c(p,"config.json"),m=c(p,"budget.json");function a(t,n){o(t,n);try{e(t,384)}catch{}}function y(t){try{63&i(t).mode&&e(t,384)}catch{}}function l(){r(p)||t(p,{recursive:!0,mode:448})}export function getConfig(){if(l(),!r(d)){const t={...u,sessionId:s()};return a(d,JSON.stringify(t,null,2)),t}y(d);try{const t=n(d,"utf-8");return{...u,...JSON.parse(t)}}catch{return{...u,sessionId:s()}}}export function saveConfig(t){l();const n={...getConfig(),...t};a(d,JSON.stringify(n,null,2))}export function getBudget(){if(l(),!r(m))return a(m,JSON.stringify(g,null,2)),{...g};y(m);try{const t=n(m,"utf-8");return{...g,...JSON.parse(t)}}catch{return{...g}}}export function saveBudget(t){l(),a(m,JSON.stringify(t,null,2))}export function getIcoaDir(){return l(),p}export function isConnected(){const t=getConfig();return!(!t.ctfdUrl||!t.token)}
1
+ import{mkdirSync as t,readFileSync as n,writeFileSync as o,existsSync as e,chmodSync as r,statSync as i}from"node:fs";import{join as l}from"node:path";import{homedir as s}from"node:os";import{randomUUID as a}from"node:crypto";import{DEFAULT_CONFIG as c,DEFAULT_BUDGET as f}from"../types/index.js";import{deriveFileKey as u,writeSignedFile as g,readSignedFile as d,verifyObject as p,recordVerdict as S}from"./secure-store.js";const m=l(s(),".icoa"),y=l(m,"config.json"),x=l(m,"budget.json"),C="config",h="budget";function v(){e(m)||t(m,{recursive:!0,mode:448})}export function getConfig(){if(v(),!e(y)){const t={...c,sessionId:a(),installSalt:a()};try{g(y,t,u(t.installSalt,C))}catch{}return t}let t;!function(t){try{63&i(t).mode&&r(t,384)}catch{}}(y);try{t=JSON.parse(n(y,"utf-8"))}catch{return S(C,"corrupt"),{...c,sessionId:a()}}let l="string"==typeof t.installSalt?t.installSalt:void 0;if(!l){l=a(),t={...t,installSalt:l};try{!function(t,n){o(t,n);try{r(t,384)}catch{}}(y,JSON.stringify(t,null,2))}catch{}}const s=u(l,C),f=p(t,s);S(C,f);const d={...c,...t};return delete d._sig,d}export function saveConfig(t){v();const n={...getConfig(),...t};n.installSalt||(n.installSalt=a()),g(y,n,u(n.installSalt,C))}export function getBudget(){v();const t=u(getInstallSalt(),h),{data:n,verdict:o}=d(x,t);return S(h,o),n?{...f,...n}:(g(x,{...f},t),{...f})}export function saveBudget(t){v(),g(x,t,u(getInstallSalt(),h))}export function getIcoaDir(){return v(),m}export function getInstallSalt(){const t=getConfig();if(t.installSalt)return t.installSalt;const n=a();return saveConfig({installSalt:n}),n}export function isConnected(){const t=getConfig();return!(!t.ctfdUrl||!t.token)}
@@ -1 +1 @@
1
- import{mkdirSync as t,readFileSync as e,unlinkSync as r,writeFileSync as o}from"node:fs";import{join as n}from"node:path";import{homedir as a}from"node:os";const s=n(a(),".icoa","demo2-progress.json");export function loadDemo2Progress(){let t,r;try{t=e(s,"utf-8")}catch{return null}try{r=JSON.parse(t)}catch{return clearDemo2Progress(),null}if("number"!=typeof r.nextCardIndex||"number"!=typeof r.totalCards||"string"!=typeof r.lang||"number"!=typeof r.startedAt)return clearDemo2Progress(),null;const o=r.completedAt??r.startedAt;return"number"==typeof o&&Date.now()-o>6048e5?(clearDemo2Progress(),null):{nextCardIndex:r.nextCardIndex,totalCards:r.totalCards,lang:r.lang,startedAt:r.startedAt,completedAt:"number"==typeof r.completedAt?r.completedAt:void 0}}export function saveDemo2Progress(e){!function(){try{t(n(a(),".icoa"),{recursive:!0})}catch{}}();try{o(s,JSON.stringify(e))}catch{}}export function clearDemo2Progress(){try{r(s)}catch{}}export function markCardDone(t,e,r,o){saveDemo2Progress({nextCardIndex:t+1,totalCards:e,lang:r,startedAt:o})}export function markDemo2Complete(t,e,r){saveDemo2Progress({nextCardIndex:t,totalCards:t,lang:e,startedAt:r,completedAt:Date.now()})}
1
+ import{unlinkSync as e}from"node:fs";import{join as t}from"node:path";import{getIcoaDir as r,getInstallSalt as o}from"./config.js";import{deriveFileKey as n,readSignedFile as s,writeSignedFile as a,recordVerdict as d}from"./secure-store.js";const m="demo2-progress";function l(){return t(r(),"demo2-progress.json")}function c(){return n(o(),m)}export function loadDemo2Progress(){const{data:e,verdict:t}=s(l(),c());if(d(m,t),"corrupt"===t)return clearDemo2Progress(),null;if(!e)return null;const r=e;if("number"!=typeof r.nextCardIndex||"number"!=typeof r.totalCards||"string"!=typeof r.lang||"number"!=typeof r.startedAt)return clearDemo2Progress(),null;const o=r.completedAt??r.startedAt;return"number"==typeof o&&Date.now()-o>6048e5?(clearDemo2Progress(),null):{nextCardIndex:r.nextCardIndex,totalCards:r.totalCards,lang:r.lang,startedAt:r.startedAt,completedAt:"number"==typeof r.completedAt?r.completedAt:void 0}}export function saveDemo2Progress(e){try{a(l(),e,c())}catch{}}export function clearDemo2Progress(){try{e(l())}catch{}}export function markCardDone(e,t,r,o){saveDemo2Progress({nextCardIndex:e+1,totalCards:t,lang:r,startedAt:o})}export function markDemo2Complete(e,t,r){saveDemo2Progress({nextCardIndex:e,totalCards:e,lang:t,startedAt:r,completedAt:Date.now()})}
@@ -1 +1 @@
1
- import{readFileSync as t,writeFileSync as e,existsSync as n,unlinkSync as a,mkdirSync as r,chmodSync as o}from"node:fs";import{execFileSync as i}from"node:child_process";import{join as s}from"node:path";import{homedir as c}from"node:os";import{getIcoaDir as u}from"./config.js";export function practicalChatCommand(t,e){return e?"ctf4ai"===t?"ctf4ai":"ai4ctf"===t?"ai4ctf":"vla"===t?"ctf4eai":null:null}export function materializeAttachedData(t,a){if(!a)return null;let o;try{const i=getRealExamState(),u=i?.session?.workspaceDir,f=u&&n(u)?u:s(c(),"icoa-workspace");r(f,{recursive:!0}),o=s(f,`q${t}.txt`),e(o,a,"utf-8")}catch{return null}try{return i("docker",["cp",o,`icoa-sandbox:/home/competitor/challenges/q${t}.txt`],{stdio:"ignore",timeout:3e3}),`challenges/q${t}.txt`}catch{return o}}function f(){return s(u(),"exam-state.json")}function l(){return s(u(),"demo-state.json")}function m(t){return"demo-free"===t?l():f()}export function getRealExamState(){const e=f();if(!n(e))return null;try{const n=JSON.parse(t(e,"utf-8"));if("demo-free"===n?.session?.examId){try{a(e)}catch{}return null}return n}catch{return null}}export function getDemoState(){const e=l();if(!n(e))return null;try{return JSON.parse(t(e,"utf-8"))}catch{return null}}export function getExamState(){return getRealExamState()||getDemoState()}export function saveExamState(t){const n=m(t.session.examId);e(n,JSON.stringify(t,null,2));try{o(n,384)}catch{}}export function clearExamState(t){if(t){const e=m(t);n(e)&&a(e)}else{const t=getExamState();if(t){const e=m(t.session.examId);n(e)&&a(e)}}}function d(t){if(!t.session.durationMinutes)return null;const{deadlineServerMs:e,clockOffsetMs:n}=t.session;if("number"==typeof e&&"number"==typeof n)return new Date(e-n);const a=t.session.confirmedAt||t.session.startedAt,r=new Date(a).getTime();return new Date(r+60*t.session.durationMinutes*1e3)}export function getExamDeadline(){const t=getExamState();return t?d(t):null}export function getRealExamDeadline(){const t=getRealExamState();return t?d(t):null}let p=!1;export async function refetchQuestionDataIfStale(){const t=getRealExamState();if(!t)return null;if(p)return t;const e=t.session.token;if(!e)return t;if(!t.questions.some(t=>{if("ai4ctf"!==t.type&&"ctf4ai"!==t.type)return!1;const e=String(t.description||"");return(e.includes("attachedData")||/base64 blob/i.test(e))&&!t.attachedData}))return t;p=!0;try{const{getConfig:n}=await import("./config.js"),a=n(),r=a.ctfdUrl||"https://practice.icoa2026.au",o=a.language||"en",i=await fetch(`${r}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,deviceHash:"",lang:o}),signal:AbortSignal.timeout(8e3)});if(!i.ok)return t;const s=await i.json(),c=s?.data?.questions||[];if(0===c.length)return t;const u=new Map;for(const t of c)u.set(t.number,t);let f=0;for(const e of t.questions){const t=u.get(e.number);t&&(t.attachedData&&!e.attachedData&&(e.attachedData=t.attachedData,f++),t.description&&(!e.description||t.description.length>e.description.length)&&(e.description=t.description))}return f>0&&saveExamState(t),t}catch{return t}}
1
+ import{writeFileSync as t,existsSync as e,unlinkSync as n,mkdirSync as a}from"node:fs";import{execFileSync as o}from"node:child_process";import{join as r}from"node:path";import{homedir as i}from"node:os";import{getIcoaDir as s,getInstallSalt as c}from"./config.js";import{deriveFileKey as u,readSignedFile as f,writeSignedFile as m,recordVerdict as l}from"./secure-store.js";export function practicalChatCommand(t,e){return e?"ctf4ai"===t?"ctf4ai":"ai4ctf"===t?"ai4ctf":"vla"===t?"ctf4eai":null:null}export function materializeAttachedData(n,s){if(!s)return null;let c;try{const o=getRealExamState(),u=o?.session?.workspaceDir,f=u&&e(u)?u:r(i(),"icoa-workspace");a(f,{recursive:!0}),c=r(f,`q${n}.txt`),t(c,s,"utf-8")}catch{return null}try{return o("docker",["cp",c,`icoa-sandbox:/home/competitor/challenges/q${n}.txt`],{stdio:"ignore",timeout:3e3}),`challenges/q${n}.txt`}catch{return c}}function d(){return r(s(),"exam-state.json")}function p(){return r(s(),"demo-state.json")}function x(t){return"demo-free"===t?p():d()}export function getRealExamState(){const t=d(),{data:e,verdict:a}=f(t,u(c(),"exam-state"));if(l("exam-state",a),!e)return null;if("demo-free"===e?.session?.examId){try{n(t)}catch{}return null}return e}export function getDemoState(){const t=p(),{data:e,verdict:n}=f(t,u(c(),"demo-state"));return l("demo-state",n),e}export function getExamState(){return getRealExamState()||getDemoState()}export function saveExamState(t){const e=t.session.examId,n=x(e);m(n,t,u(c(),function(t){return"demo-free"===t?"demo-state":"exam-state"}(e)))}export function clearExamState(t){if(t){const a=x(t);e(a)&&n(a)}else{const t=getExamState();if(t){const a=x(t.session.examId);e(a)&&n(a)}}}function g(t){if(!t.session.durationMinutes)return null;const{deadlineServerMs:e,clockOffsetMs:n}=t.session;if("number"==typeof e&&"number"==typeof n)return new Date(e-n);const a=t.session.confirmedAt||t.session.startedAt,o=new Date(a).getTime();return new Date(o+60*t.session.durationMinutes*1e3)}export function getExamDeadline(){const t=getExamState();return t?g(t):null}export function getRealExamDeadline(){const t=getRealExamState();return t?g(t):null}let h=!1;export async function refetchQuestionDataIfStale(){const t=getRealExamState();if(!t)return null;if(h)return t;const e=t.session.token;if(!e)return t;if(!t.questions.some(t=>{if("ai4ctf"!==t.type&&"ctf4ai"!==t.type)return!1;const e=String(t.description||"");return(e.includes("attachedData")||/base64 blob/i.test(e))&&!t.attachedData}))return t;h=!0;try{const{getConfig:n}=await import("./config.js"),a=n(),o=a.ctfdUrl||"https://practice.icoa2026.au",r=a.language||"en",i=await fetch(`${o}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,deviceHash:"",lang:r}),signal:AbortSignal.timeout(8e3)});if(!i.ok)return t;const s=await i.json(),c=s?.data?.questions||[];if(0===c.length)return t;const u=new Map;for(const t of c)u.set(t.number,t);let f=0;for(const e of t.questions){const t=u.get(e.number);t&&(t.attachedData&&!e.attachedData&&(e.attachedData=t.attachedData,f++),t.description&&(!e.description||t.description.length>e.description.length)&&(e.description=t.description))}return f>0&&saveExamState(t),t}catch{return t}}
@@ -0,0 +1,9 @@
1
+ import type { InputDynamics } from '../types/index.js';
2
+ export declare function classifyBurst(interKeyMs: number[]): {
3
+ maxBurst: number;
4
+ suspectPaste: boolean;
5
+ };
6
+ export declare function stripPasteMarkers(line: string): string;
7
+ export declare function installInputDynamics(enableBracketed?: boolean): void;
8
+ export declare function uninstallInputDynamics(): void;
9
+ export declare function consumeLineDynamics(): InputDynamics | undefined;
@@ -0,0 +1 @@
1
+ let s=!1,t=0,e=null,n=[];function a(){return{start:Date.now(),keys:0,backspaces:0,pastes:0,pasteChars:0}}export function classifyBurst(s){let t=1,e=1;for(let n=1;n<s.length;n++)s[n]<5?(t++,t>e&&(e=t)):t=1;return{maxBurst:e,suspectPaste:e>=8}}export function stripPasteMarkers(s){return s.replace(/\x1b?\[20[01]~/g,"")}function r(s,r){e||(e=a());const c=Date.now();t&&n.push(c-t),t=c,e.keys++,"backspace"===r?.name&&e.backspaces++}function c(s){const t=s.toString("latin1");let n=t.indexOf("[200~");for(;-1!==n;){e||(e=a()),e.pastes++;const s=t.indexOf("[201~",n);-1!==s&&(e.pasteChars+=s-(n+6)),n=t.indexOf("[200~",n+6)}}export function installInputDynamics(a=!0){if(!s&&(s=!0,e=null,n=[],t=0,process.stdin.on("keypress",r),process.stdin.on("data",c),a&&process.stdout.isTTY))try{process.stdout.write("[?2004h")}catch{}}export function uninstallInputDynamics(){if(s&&(s=!1,process.stdin.removeListener("keypress",r),process.stdin.removeListener("data",c),process.stdout.isTTY))try{process.stdout.write("[?2004l")}catch{}}export function consumeLineDynamics(){if(!e)return;const{maxBurst:s,suspectPaste:a}=classifyBurst(n),r={ms:Date.now()-e.start,keys:e.keys,backspaces:e.backspaces,pastes:e.pastes,pasteChars:e.pasteChars,maxBurst:s,suspectPaste:a||e.pastes>0};return e=null,n=[],t=0,r}
@@ -1,3 +1,19 @@
1
+ /**
2
+ * Pure payload builder — no I/O, no network. Extracted from
3
+ * `postIntegritySnapshot` so the SCRUBBED shape (and the secret-exclusion
4
+ * invariant: config.accessToken / config.token never enter this object) is
5
+ * unit-testable without a live server or filesystem.
6
+ */
7
+ export declare function buildSnapshotPayload(cfg: {
8
+ deviceFingerprint?: string;
9
+ installSalt?: string;
10
+ }, budget: {
11
+ tokensUsed: number;
12
+ tokenCap: number;
13
+ }, extras?: {
14
+ simCooldown?: unknown;
15
+ tokenBindings?: unknown;
16
+ }): Record<string, unknown>;
1
17
  /**
2
18
  * Fire a scrubbed integrity snapshot to the server. Best-effort, non-blocking,
3
19
  * and self-swallowing — callers may `await` it inside an existing try/catch
@@ -1 +1 @@
1
- import{readFileSync as t}from"node:fs";import{join as n}from"node:path";import{homedir as o}from"node:os";import{getConfig as e,getBudget as i}from"./config.js";import{getCliVersion as r}from"./version.js";function s(n){try{return JSON.parse(t(n,"utf-8"))}catch{return null}}export async function postIntegritySnapshot(){try{const t=e();if("live"!==t.competitionState)return;const a=t.ctfdUrl;if(!a)return;const c=n(o(),".icoa"),p=i(),d={deviceFingerprint:t.deviceFingerprint||"",installSalt:t.installSalt||"",budget:{tokensUsed:p.tokensUsed,tokenCap:p.tokenCap},simCooldown:s(n(c,"sim-cooldown.json")),tokenBindings:s(n(c,"token-bindings.json"))},m={"Content-Type":"application/json","User-Agent":`icoa-cli/${r()}`,"X-Device-Fingerprint":t.deviceFingerprint||""};t.token&&t.userName&&(d.account=t.userName,m.Authorization=`Token ${t.token}`),await fetch(`${a}/api/icoa/snapshot`,{method:"POST",headers:m,body:JSON.stringify(d),signal:AbortSignal.timeout(8e3)})}catch{}}
1
+ import{readFileSync as n}from"node:fs";import{join as o}from"node:path";import{homedir as t}from"node:os";import{getConfig as i,getBudget as e}from"./config.js";import{getCliVersion as r}from"./version.js";import{collectVerdicts as s}from"./secure-store.js";function a(o){try{return JSON.parse(n(o,"utf-8"))}catch{return null}}export function buildSnapshotPayload(n,o,t){return{deviceFingerprint:n.deviceFingerprint||"",installSalt:n.installSalt||"",budget:{tokensUsed:o.tokensUsed,tokenCap:o.tokenCap},simCooldown:t?.simCooldown??null,tokenBindings:t?.tokenBindings??null,integrity:s()}}export async function postIntegritySnapshot(){try{const n=i();if("live"!==n.competitionState)return;const s=n.ctfdUrl;if(!s)return;const c=o(t(),".icoa"),l=buildSnapshotPayload(n,e(),{simCooldown:a(o(c,"sim-cooldown.json")),tokenBindings:a(o(c,"token-bindings.json"))}),p={"Content-Type":"application/json","User-Agent":`icoa-cli/${r()}`,"X-Device-Fingerprint":n.deviceFingerprint||""};n.token&&n.userName&&(l.account=n.userName,p.Authorization=`Token ${n.token}`),await fetch(`${s}/api/icoa/snapshot`,{method:"POST",headers:p,body:JSON.stringify(l),signal:AbortSignal.timeout(8e3)})}catch{}}
@@ -1 +1 @@
1
- import{existsSync as e,mkdirSync as t,readFileSync as r,writeFileSync as a}from"node:fs";import{homedir as n}from"node:os";import{join as o}from"node:path";const s=o(n(),".icoa"),c=o(s,"learn-state.json");export function loadLearnState(){if(!e(c))return null;try{return JSON.parse(r(c,"utf-8"))}catch{return null}}export function saveLearnState(r){e(s)||t(s,{recursive:!0}),r.lastSeenAt=(new Date).toISOString(),a(c,JSON.stringify(r,null,2))}export function newLearnState(e,t,r){const a=(new Date).toISOString();return{token:e,curriculumId:t,currentCard:1,totalCards:r,startedAt:a,lastSeenAt:a,streakDays:1,longestStreak:1,cardsCompleted:[],mcqResults:{},checkResults:{},practicalsCompleted:[],bookmarks:[],achievements:[],totalSecondsActive:0}}export function updateStreak(e){const t=new Date(e.lastSeenAt),r=new Date,a=Math.floor(t.getTime()/864e5),n=Math.floor(r.getTime()/864e5)-a;0!==n&&(1===n?(e.streakDays+=1,e.streakDays>e.longestStreak&&(e.longestStreak=e.streakDays)):e.streakDays=1)}export function markCardComplete(e,t){e.cardsCompleted.includes(t)||e.cardsCompleted.push(t)}export function recordMCQ(e,t,r){e.mcqResults[String(t)]=r}export function recordCheck(e,t,r){e.checkResults||(e.checkResults={}),e.checkResults[String(t)]=r}export function markPracticalComplete(e,t){e.practicalsCompleted.includes(t)||e.practicalsCompleted.push(t)}export function addAchievement(e,t){e.achievements.includes(t)||e.achievements.push(t)}
1
+ import{join as e}from"node:path";import{getIcoaDir as t,getInstallSalt as r}from"./config.js";import{deriveFileKey as a,readSignedFile as n,writeSignedFile as o,recordVerdict as s}from"./secure-store.js";const c="learn-state";function i(){return e(t(),"learn-state.json")}function l(){return a(r(),c)}export function loadLearnState(){const{data:e,verdict:t}=n(i(),l());return s(c,t),e}export function saveLearnState(e){e.lastSeenAt=(new Date).toISOString(),o(i(),e,l())}export function newLearnState(e,t,r){const a=(new Date).toISOString();return{token:e,curriculumId:t,currentCard:1,totalCards:r,startedAt:a,lastSeenAt:a,streakDays:1,longestStreak:1,cardsCompleted:[],mcqResults:{},checkResults:{},practicalsCompleted:[],bookmarks:[],achievements:[],totalSecondsActive:0}}export function updateStreak(e){const t=new Date(e.lastSeenAt),r=new Date,a=Math.floor(t.getTime()/864e5),n=Math.floor(r.getTime()/864e5)-a;0!==n&&(1===n?(e.streakDays+=1,e.streakDays>e.longestStreak&&(e.longestStreak=e.streakDays)):e.streakDays=1)}export function markCardComplete(e,t){e.cardsCompleted.includes(t)||e.cardsCompleted.push(t)}export function recordMCQ(e,t,r){e.mcqResults[String(t)]=r}export function recordCheck(e,t,r){e.checkResults||(e.checkResults={}),e.checkResults[String(t)]=r}export function markPracticalComplete(e,t){e.practicalsCompleted.includes(t)||e.practicalsCompleted.push(t)}export function addAchievement(e,t){e.achievements.includes(t)||e.achievements.push(t)}
@@ -1 +1 @@
1
- import{readFileSync as t,existsSync as n,writeFileSync as e,chmodSync as s}from"node:fs";import{join as i}from"node:path";import{getIcoaDir as o,getConfig as c}from"./config.js";import{getDeviceFingerprint as r}from"./access.js";import{getCliVersion as a}from"./version.js";const l=()=>i(o(),"sync-state.json");let u=null;function f(t){const n=l();e(n,JSON.stringify(t,null,2));try{s(n,384)}catch{}}async function y(){const e=c(),s=e.ctfdUrl||"https://practice.icoa2026.au",u=i(o(),"session.log");if(!n(u))return;const y=function(){const e=l();if(!n(e))return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0};try{const n=JSON.parse(t(e,"utf-8"));return{lastSyncedLine:n.lastSyncedLine??0,lastSyncAt:n.lastSyncAt??null,syncCount:n.syncCount??0,failCount:n.failCount??0,seq:n.seq??0}}catch{return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0}}}(),d=t(u,"utf-8").trim().split("\n").filter(Boolean);d.length<y.lastSyncedLine&&(y.lastSyncedLine=0);const p=d.slice(y.lastSyncedLine);if(0===p.length)return;const S={"Content-Type":"application/json"};let m;if(e.token)S.Authorization=`Token ${e.token}`,m=`user:${e.userId??"unknown"}`;else{const t=e.deviceFingerprint||r();S["X-Device-Fingerprint"]=t,m=`demo:${t.slice(0,12)}`}const g=y.seq??0,h=p.map((t,n)=>{let e;try{e=JSON.parse(t)}catch{e={raw:t}}return{...e,_seq:g+n+1}}),C=a(),I=h.map(t=>({...t,_cli:C})),L={identity:m,userId:e.userId,userName:e.userName,teamId:e.teamId,sessionId:e.sessionId,deviceFingerprint:e.deviceFingerprint||r(),lang:e.language||"en",clientVersion:C,timestamp:(new Date).toISOString(),seqRange:{from:g+1,to:g+h.length},entries:I};try{const t=new URL("/api/icoa/audit",s).href;(await fetch(t,{method:"POST",headers:S,body:JSON.stringify(L),signal:AbortSignal.timeout(1e4)})).ok?(y.lastSyncedLine=d.length,y.lastSyncAt=(new Date).toISOString(),y.syncCount++,y.seq=g+h.length,f(y)):(y.failCount++,f(y))}catch{y.failCount++,f(y)}}export function startLogSync(){setTimeout(()=>y(),5e3),u=setInterval(()=>y(),3e4)}export function stopLogSync(){u&&(clearInterval(u),u=null),y()}
1
+ import{readFileSync as t,existsSync as n,writeFileSync as e,chmodSync as s}from"node:fs";import{join as i}from"node:path";import{getIcoaDir as o,getConfig as a,getInstallSalt as c}from"./config.js";import{getDeviceFingerprint as r}from"./access.js";import{getCliVersion as l}from"./version.js";const u=()=>i(o(),"sync-state.json");let f=null;function y(t){const n=u();e(n,JSON.stringify(t,null,2));try{s(n,384)}catch{}}async function d(){const e=a(),s=e.ctfdUrl||"https://practice.icoa2026.au",f=i(o(),"session.log");if(!n(f))return;const d=function(){const e=u();if(!n(e))return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0};try{const n=JSON.parse(t(e,"utf-8"));return{lastSyncedLine:n.lastSyncedLine??0,lastSyncAt:n.lastSyncAt??null,syncCount:n.syncCount??0,failCount:n.failCount??0,seq:n.seq??0}}catch{return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0}}}(),S=t(f,"utf-8").trim().split("\n").filter(Boolean);S.length<d.lastSyncedLine&&(d.lastSyncedLine=0);const p=S.slice(d.lastSyncedLine);if(0===p.length)return;const m={"Content-Type":"application/json"};let g;if(e.token)m.Authorization=`Token ${e.token}`,g=`user:${e.userId??"unknown"}`;else{const t=e.deviceFingerprint||r();m["X-Device-Fingerprint"]=t,g=`demo:${t.slice(0,12)}`}const h=d.seq??0,C=p.map((t,n)=>{let e;try{e=JSON.parse(t)}catch{e={raw:t}}return{...e,_seq:h+n+1}}),I=l(),L=C.map(t=>({...t,_cli:I})),q={identity:g,userId:e.userId,userName:e.userName,teamId:e.teamId,sessionId:e.sessionId,deviceFingerprint:e.deviceFingerprint||r(),installSalt:e.installSalt||c(),lang:e.language||"en",clientVersion:I,timestamp:(new Date).toISOString(),seqRange:{from:h+1,to:h+C.length},entries:L};try{const t=new URL("/api/icoa/audit",s).href;(await fetch(t,{method:"POST",headers:m,body:JSON.stringify(q),signal:AbortSignal.timeout(1e4)})).ok?(d.lastSyncedLine=S.length,d.lastSyncAt=(new Date).toISOString(),d.syncCount++,d.seq=h+C.length,y(d)):(d.failCount++,y(d))}catch{d.failCount++,y(d)}}export function startLogSync(){setTimeout(()=>d(),5e3),f=setInterval(()=>d(),3e4)}export function stopLogSync(){f&&(clearInterval(f),f=null),d()}
@@ -1,4 +1,12 @@
1
1
  import type { LogEntry } from '../types/index.js';
2
+ /** Test-only: force the next currentLastMac() call to re-seed from the log
3
+ * tail, simulating a fresh process picking up an existing session.log. */
4
+ export declare function __resetChainHeadForTest(): void;
5
+ export declare function chainMac(prevMac: string, entry: object, key: Buffer): string;
6
+ export declare function verifyChain(entries: Array<Record<string, unknown>>, startMac: string, key: Buffer): {
7
+ ok: boolean;
8
+ brokenAt: number;
9
+ };
2
10
  export declare function logCommand(command: string): void;
3
11
  export declare function logSubmission(challengeId: number, flag: string): void;
4
12
  export declare function getSessionLog(): LogEntry[];
@@ -1 +1 @@
1
- import{appendFileSync as t,readFileSync as n,existsSync as o}from"node:fs";import{join as e}from"node:path";import{getConfig as i,getIcoaDir as s}from"./config.js";function r(){return e(s(),"session.log")}function m(n){try{t(r(),`${JSON.stringify(n)}\n`)}catch{}}export function logCommand(t){const n=i();m({timestamp:(new Date).toISOString(),level:"command",input:t,sessionId:n.sessionId})}export function logSubmission(t,n){const o=i();m({timestamp:(new Date).toISOString(),level:"submit",input:n,challengeId:t,sessionId:o.sessionId})}export function getSessionLog(){const t=r();if(!o(t))return[];try{return n(t,"utf-8").trim().split("\n").filter(Boolean).map(t=>JSON.parse(t))}catch{return[]}}
1
+ import{appendFileSync as t,readFileSync as n,existsSync as e}from"node:fs";import{join as o}from"node:path";import{createHmac as r}from"node:crypto";import{getConfig as i,getIcoaDir as s,getInstallSalt as c}from"./config.js";import{deriveFileKey as a,canonicalize as u}from"./secure-store.js";import{consumeLineDynamics as l}from"./input-dynamics.js";function m(){return o(s(),"session.log")}let f=null;export function __resetChainHeadForTest(){f=null}export function chainMac(t,n,e){const o={...n};return delete o._mac,r("sha256",e).update(t).update("\n").update(u(o)).digest("hex")}export function verifyChain(t,n,e){let o=n;for(let n=0;n<t.length;n++){const r=chainMac(o,t[n],e);if(t[n]._mac!==r)return{ok:!1,brokenAt:n};o=r}return{ok:!0,brokenAt:-1}}function p(e){try{const o=a(c(),"session-log"),r=chainMac(function(){if(null!==f)return f;try{const t=n(m(),"utf-8").split("\n").filter(t=>t.trim().length>0),e=t[t.length-1],o=JSON.parse(e);f=o._mac??""}catch{f=""}return f}(),e,o),i={...e,_mac:r};t(m(),`${JSON.stringify(i)}\n`),f=r}catch{try{t(m(),`${JSON.stringify(e)}\n`)}catch{}f=null}}export function logCommand(t){const n=i();p({timestamp:(new Date).toISOString(),level:"command",input:t,sessionId:n.sessionId,dyn:l()})}export function logSubmission(t,n){const e=i();p({timestamp:(new Date).toISOString(),level:"submit",input:n,challengeId:t,sessionId:e.sessionId,dyn:l()})}export function getSessionLog(){const t=m();if(!e(t))return[];try{return n(t,"utf-8").trim().split("\n").filter(Boolean).map(t=>JSON.parse(t))}catch{return[]}}
@@ -0,0 +1,18 @@
1
+ export type IntegrityVerdict = 'ok' | 'tampered' | 'unsigned' | 'absent' | 'corrupt';
2
+ export interface SigBlock {
3
+ v: 1;
4
+ alg: 'HS256';
5
+ mac: string;
6
+ ts: string;
7
+ }
8
+ export declare function deriveFileKey(installSalt: string, fileId: string): Buffer;
9
+ export declare function canonicalize(obj: unknown): string;
10
+ export declare function signObject(payload: object, key: Buffer): SigBlock;
11
+ export declare function verifyObject(payloadWithSig: object, key: Buffer): IntegrityVerdict;
12
+ export declare function writeSignedFile(path: string, payload: object, key: Buffer): void;
13
+ export declare function readSignedFile<T>(path: string, key: Buffer): {
14
+ data: T | null;
15
+ verdict: IntegrityVerdict;
16
+ };
17
+ export declare function recordVerdict(fileId: string, verdict: IntegrityVerdict): void;
18
+ export declare function collectVerdicts(): Record<string, IntegrityVerdict>;
@@ -0,0 +1 @@
1
+ import{writeFileSync as e,readFileSync as t,existsSync as r,chmodSync as n}from"node:fs";import{hkdfSync as o,createHmac as i,timingSafeEqual as c}from"node:crypto";export function deriveFileKey(e,t){const r=o("sha256",Buffer.from(e,"utf-8"),Buffer.from("icoa-secure-store-v1"),Buffer.from(t),32);return Buffer.from(r)}export function canonicalize(e){const t=new Set,r=e=>{if(null===e||"object"!=typeof e)return e;if(t.has(e))return null;let n;if(t.add(e),Array.isArray(e))n=e.map(r);else{const t=e,o={};for(const e of Object.keys(t).sort())"_sig"!==e&&(o[e]=r(t[e]));n=o}return t.delete(e),n};return JSON.stringify(r(e))}function f(e,t){return i("sha256",t).update(canonicalize(e)).digest("hex")}export function signObject(e,t){return{v:1,alg:"HS256",mac:f(e,t),ts:(new Date).toISOString()}}export function verifyObject(e,t){const r=e._sig;if(!r||"string"!=typeof r.mac)return"unsigned";const n=f(e,t),o=Buffer.from(r.mac,"hex"),i=Buffer.from(n,"hex");return o.length!==i.length?"tampered":c(o,i)?"ok":"tampered"}export function writeSignedFile(t,r,o){const i={...r};delete i._sig;const c=signObject(i,o);e(t,JSON.stringify({...i,_sig:c},null,2));try{n(t,384)}catch{}}export function readSignedFile(e,n){if(!r(e))return{data:null,verdict:"absent"};let o;try{o=JSON.parse(t(e,"utf-8"))}catch{return{data:null,verdict:"corrupt"}}const i=verifyObject(o,n),c={...o};return delete c._sig,{data:c,verdict:i}}const u=new Map,s={ok:0,absent:0,unsigned:1,corrupt:2,tampered:3};export function recordVerdict(e,t){if(0===s[t])return;const r=u.get(e);(!r||s[t]>s[r])&&u.set(e,t)}export function collectVerdicts(){return Object.fromEntries(u)}
@@ -1 +1 @@
1
- import{mkdirSync as t,readFileSync as n,writeFileSync as o}from"node:fs";import{join as r}from"node:path";import{homedir as e}from"node:os";export const COOLDOWN_SECONDS=60;const l=r(e(),".icoa","sim-cooldown.json");function a(){try{const t=n(l,"utf-8"),o=JSON.parse(t);return"object"==typeof o&&null!==o?o:{}}catch{return{}}}function s(n){try{t(r(e(),".icoa"),{recursive:!0});const s={...a(),...n};o(l,JSON.stringify(s))}catch{}}export function lastSimAt(){const t=a();return"number"==typeof t.lastCallAt?t.lastCallAt:0}export function markSimAt(t){s({lastCallAt:t})}export function cooldownRemaining(){const t=(Date.now()-lastSimAt())/1e3;return Math.max(0,Math.ceil(60-t))}export function lastBundledAt(){const t=a();return"number"==typeof t.lastBundledAt?t.lastBundledAt:0}export function markBundledAt(t){s({lastBundledAt:t})}export function lastArmAt(){const t=a();return"number"==typeof t.lastArmAt?t.lastArmAt:0}export function markArmAt(t){s({lastArmAt:t})}export function hasAnySimHistory(){const t=a();return"number"==typeof t.lastBundledAt&&t.lastBundledAt>0||"number"==typeof t.lastCallAt&&t.lastCallAt>0||"number"==typeof t.lastArmAt&&t.lastArmAt>0}
1
+ import{join as t}from"node:path";import{getIcoaDir as n,getInstallSalt as o}from"./config.js";import{deriveFileKey as r,readSignedFile as e,writeSignedFile as l,recordVerdict as a}from"./secure-store.js";export const COOLDOWN_SECONDS=60;const s="sim-cooldown";function u(){return t(n(),"sim-cooldown.json")}function c(){return r(o(),s)}function m(){try{const{data:t,verdict:n}=e(u(),c());return a(s,n),t||{}}catch{return{}}}function A(t){try{const n={...m(),...t};l(u(),n,c())}catch{}}export function lastSimAt(){const t=m();return"number"==typeof t.lastCallAt?t.lastCallAt:0}export function markSimAt(t){A({lastCallAt:t})}export function cooldownRemaining(){const t=(Date.now()-lastSimAt())/1e3;return Math.max(0,Math.ceil(60-t))}export function lastBundledAt(){const t=m();return"number"==typeof t.lastBundledAt?t.lastBundledAt:0}export function markBundledAt(t){A({lastBundledAt:t})}export function lastArmAt(){const t=m();return"number"==typeof t.lastArmAt?t.lastArmAt:0}export function markArmAt(t){A({lastArmAt:t})}export function hasAnySimHistory(){const t=m();return"number"==typeof t.lastBundledAt&&t.lastBundledAt>0||"number"==typeof t.lastCallAt&&t.lastCallAt>0||"number"==typeof t.lastArmAt&&t.lastArmAt>0}