icoa-cli 2.19.412 → 2.19.413

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{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{logCommand as s}from"../lib/logger.js";import{getMainRl as l}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as a,handleAi4ioaiMessage as i,startAi4ioaiChat as c}from"./ai4ioai.js";import{existsSync as d,mkdirSync as g,readdirSync as u,readFileSync as m,renameSync as y,writeFileSync as h}from"node:fs";import{dirname as p,join as f}from"node:path";import{fileURLToPath as b}from"node:url";import{loadCurriculumById as w,validateEAToken as $,syncProgress as k,syncCardFeedback as v}from"../lib/learn-curricula.js";import{normalizeTokenBody as C}from"../lib/token-format.js";import{fetchMyScores as A,recallCoach as _,setNickname as I,streamLearnTutor as x,submitPqs as T,viewPqsTop as E,viewHonors as M}from"../lib/learn-ai.js";import{contestReset as S,contestStart as R,contestSubmit as P,fetchGate as q,timeLeft as D}from"../lib/learn-contest.js";import{getConfig as L,saveConfig as j}from"../lib/config.js";import{loadLearnState as O,saveLearnState as N,newLearnState as W,updateStreak as Y,markCardComplete as z,recordMCQ as B,recordCheck as F,markPracticalComplete as U,addAchievement as H}from"../lib/learn-state.js";import{renderWelcome as J,renderKnowledgeCard as Z,renderMCQCard as K,renderMCQFeedback as Q,renderPracticalCard as V,renderPracticalSuccess as G,renderSimDemoCard as X,renderMilestone as ee,renderArenaTaskCard as oe,renderComingSoonCard as te,renderStatus as ne,renderPhaseComplete as re,renderCurriculumComplete as se,setLearnAiEnabled as le,setLearnHonorRanks as ae,setLearnPqsViewCards as ie,renderHonorWall as ce,wrapMixed as de}from"../lib/learn-render.js";import{printError as ge}from"../lib/ui.js";export function registerLearnCommand(ue){ue.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ue=>{ue?.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 <your token>")+chalk.gray(" (2 letters + 8 chars) — from your country team leader.")),console.log(),ue="LEARNDEMO01");let me=ue.trim().toUpperCase(),ye=null;const he=/^[A-Z0-9]+DEMO01$/i.test(me),pe=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(me);let fe=!1,be=!1;if(he)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),ye=await w(me,me);else if(pe){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(me);if(!e.ok){const o=C(me);if(o!==me){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${me} → ${o}`)),e=t,me=o)}}if(!e.ok)return ge(`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"):"")),fe=!0===e.aiEnabled,be=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),ye=await w(e.curriculumId||"LEARNDEMO01",me),!ye)return ge(`Could not open a learn curriculum for token '${me}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${me}`)+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 ${me}`)+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(!ye)return ge(`Unknown learn token: ${me}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Every track has a free demo — ask for its name if you were not given one.")),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 we=O(),$e=!1;try{we&&we.token===me?Y(we):(we=W(me,ye.id,ye.totalCards),$e=!0),N(we),J(ye,we,$e)}catch{return ge("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 ${me}`)+chalk.gray(".")),void console.log()}const ke=l(),ve=null!==ke,Ce=ve?ke.listeners("line").slice():[];ve&&ke.removeAllListeners("line");const Ae=ve?ke:o({input:process.stdin,output:process.stdout,terminal:!0}),_e=ve?Ae.prompt:null;ve&&(Ae.prompt=e.prototype.prompt);const Ie=()=>{ve&&_e&&(Ae.prompt=_e)},xe=()=>{Ae.setPrompt(Ne?chalk.bold.green(`icoa ${a()}> `):qe?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Re?"icoa learn ai> ":"icoa learn> ")),Ae.prompt()};let Te=null,Ee=null,Me=null,Se=null,Re=!1,Pe=!1,qe=!1,De=null,Le=!1,je=0,Oe=!1,Ne=!1;const We=new Map,Ye=()=>{let e=We.get(we.currentCard);return e||(e=[],We.set(we.currentCard,e)),e};let ze=!1;const Be=new Set;let Fe=!1,Ue=0;const He=()=>(L().language||"en").toLowerCase().startsWith("zh");le(fe),ie(Be);const Je=new Map;ae(Je);const Ze=[];let Ke=null;const Qe=new Promise(e=>{Ke=e}),Ve=()=>{const e=Ke;Ke=null,e?.()},Ge="1"===process.env.ICOA_LEARN_EMBEDDED,Xe=e=>ye.cards.find(o=>o.number===e);let eo=null,oo=null;const to=!me.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(me),no=async()=>{if(!to)return;const e=await q(me);e.ok&&e.data&&(eo=e.data)},ro=e=>{const o=ye.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},so=e=>{if(!be||!eo)return null;const o=ro(e);if(o<=eo.unlocked_through_phase)return null;const t=eo.phases.find(e=>e.phase===eo.unlocked_through_phase),n=[chalk.yellow(He()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${eo.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${eo.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(He()?` ⚔ 练习赛 ${eo.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${eo.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(He()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(He()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},lo=async e=>be?null===so(e)?null:(await no(),so(e)):null;be&&await no();const ao=async e=>{const o=ye.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=ye.modules.find(e=>e.number===o.number+1);let n;if(fe){const e=await A({token:me,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}to&&await no();const r=eo?.phases.find(e=>e.phase===o.number);return re(ye,we,o,t,n,r),!0},io=()=>{Fe=!0,console.log(chalk.gray(He()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},co=()=>{De=null;const e=Xe(we.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":Z(e,ye),e.check?(Me=e.number,Ue=Date.now()):(z(we,e.number),N(we));break;case"mcq":K(e,ye),Te=e.number;break;case"practical":V(e,ye),Ee=e.number;break;case"sim_demo":X(e,ye),z(we,e.number),N(we);break;case"milestone":ee(e,ye),H(we,e.badge),z(we,e.number),N(we);break;case"arena_task":oe(e,ye),z(we,e.number),N(we);break;case"coming_soon":te(e,ye),z(we,e.number),N(we)}go(e.number)},go=e=>{if(!be||!to||!eo)return;const o=ye.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1;if(t%4!=0)return;const n=t/4,r=eo.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n);if(!s)return;const l=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),l=(n||"").slice(0,10);return`🏆 ${e} ${o}/${s.n}`+(r?He()?` · 用时 ${r}`:` · ${r}`:"")+(l?` · ${l}`:"")},a=s.perfect_runs??[],i=!!s.best&&(s.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(64);if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${He()?"练习赛":"PY Arena"} ${o.number}-${n}`)+(s.passed?chalk.bold.green(He()?" ✅ 已通过":" ✅ passed"):"")),s.passed||(He()?console.log(c+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(c+chalk.white("You learned the cards — now prove it.")),console.log(c+chalk.white("The clock starts the moment you type the command."))),console.log(c+chalk.gray(He()?`${s.n} 题 · AC ${s.need} 过关 · 限时 ${s.duration_minutes} 分钟 · 无限重开`:`${s.n} problems · AC ${s.need} to pass · ${s.duration_minutes} min · unlimited retries`))),a.length>0)for(const e of a)console.log(c+chalk.bold.yellow(l(He()?"满分":"Perfect",s.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(l(He()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(s.passed?chalk.gray(He()?" 再战刷成绩 · ":" race it again · "):chalk.gray(He()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(He()?" 继续学习":" keep going"):chalk.gray(He()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},uo=()=>{me.endsWith("DEMO01")?console.log(chalk.yellow(He()?" 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(He()?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(He()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},mo=async(e,o)=>{if(fe){Pe=!0;try{console.log(),console.log(chalk.gray("deep"===o?He()?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":He()?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await x({token:me,cardNumber:we.currentCard,question:e,mode:o,history:Ye().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(He()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Ye().push({role:"user",content:e},{role:"assistant",content:r.answer}),null!=r.spent&&null!=r.cap&&r.spent/r.cap>.8&&console.log(chalk.gray(` (${He()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(He()?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==Me&&console.log(chalk.gray(He()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Pe=!1}}else uo()},yo=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],ho=async()=>{Pe=!0;try{console.log();const e=await M({token:me,curriculumId:ye.id,cardNumber:we.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(He()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(He()?` 🏆 本卡实时 Top-3 — 第 ${we.currentCard} 张`:` 🏆 Live top-3 — card ${we.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.name||`Rank ${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(He()?" (你)":" (you)"):""))}else console.log(chalk.gray(He()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Je.set(we.currentCard,e.mine.rank),console.log(chalk.white(He()?" 你: ":" You: ")+chalk.bold.yellow(He()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(He()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):fe&&console.log(chalk.gray(He()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),ce({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(He()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(He()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(He()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),De="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(He()?" 返回卡片":" returns to the card")),console.log()}finally{Pe=!1}},po=e=>He()&&e.title_zh||e.title,fo=e=>He()&&e.statement_zh||e.statement,bo=e=>oo.data.solved.includes(e.id)?"✅":oo.tried.has(e.id)?"❌":"⬜",wo=()=>{const e=oo.data,o=D(e.deadline),t=e.solved.length,n=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(He()?` · 第 ${e.slot}/${e.group_count} 组 · 第 ${e.attempt} 次尝试${e.resumed?"(续)":""}`:` · group ${e.slot}/${e.group_count} · attempt ${e.attempt}${e.resumed?" (resumed)":""}`)),console.log((o?chalk.bold.yellow(` ⏱ ${o}`):chalk.red(He()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(He()?`(共 ${e.n} 题)`:` (of ${e.n})`));const r=Date.parse(e.deadline)-Date.now();o?e.resumed&&r<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(He()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(He()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(He()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(He()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+bo(e)+chalk.white(` ${po(e)}`))}),console.log(),$o()},$o=()=>{console.log(chalk.gray(He()?" /read <n> 读题 · /edit <n> 写码(vi) · /run <n> 样例自测 · /debug <n> 自由调试 · /submit <n> 判分":" /read <n> statement · /edit <n> code (vi) · /run <n> sample check · /debug <n> free run · /submit <n> judge")),console.log(chalk.gray(He()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(He()?" 返回课程":" returns to the lesson")),console.log()},ko=e=>{const o=parseInt(e,10),t=oo.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(He()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}},vo=e=>{const o=ko(e);if(!o)return;const{p:t,n:n}=o;console.log(),console.log(chalk.bold.white(` ${bo(t)} ${po(t)}`)),console.log();for(const e of de(fo(t),66))console.log(chalk.white(` ${e}`));let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(He()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(He()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(He()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(He()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(He()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(He()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(He()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(He()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log()},Co=async(e,o)=>{await new Promise(t=>{const n=process.stdin,s=!!n.isTTY&&!!n.isRaw;if(Ae.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e,o,{stdio:"inherit",cwd:oo.dir}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&s)try{n.setRawMode(!0)}catch{}Ae.resume(),t()};l.on("close",a),l.on("error",a)})},Ao=new Map,_o=async e=>{const o=e.trim().toLowerCase(),l=qe&&o.startsWith("/")?o.slice(1):o;if(!Pe){if(null!==Se){const o=e.trim(),t=Se;if(Se=null,""===o)console.log(chalk.gray(He()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=Ue>0?Date.now()-Ue:void 0;await v(me,{curriculum_id:ye.id,card_number:t,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(He()?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(He()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void xe()}if(Le){const o=e.trim();if(!o)return Le=!1,console.log(chalk.gray(He()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void xe();const t=await I({token:me,nickname:o});if(t.ok)Le=!1,console.log(chalk.bold.green(He()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(He()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{je+=1;const e="taken"===t.code?He()?"已被占用":"already taken":"bad_charset"===t.code?He()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?He()?"未通过审核":"did not pass review":t.message||"error";if(!(je>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(He()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void xe();Le=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(He()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void xe()}if(ze){ze=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Pe=!0;try{console.log(),console.log(chalk.gray(He()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await T({token:me,cardNumber:we.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(He()?"评审暂不可用。":"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(He()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(He()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(He()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(He()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(He()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(He()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=He()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(He()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(He()?` 第 ${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 yo(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(He()?" 改进提问: ":" 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(` (${He()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Be.add(we.currentCard):Be.delete(we.currentCard),"number"==typeof e.rank&&Je.set(we.currentCard,e.rank);const o=await M({token:me,curriculumId:ye.id,cardNumber:we.currentCard});o.ok&&o.totals&&o.chapters&&(ce({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!he&&(Le=!0,je=0,console.log(chalk.bold.yellow(He()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(He()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(He()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Pe=!1}})():(console.log(chalk.gray(He()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Me&&(console.log(chalk.gray(He()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void xe()}if(Fe)return Fe=!1,co(),void xe();if(o){if(Ne)return"exit"===await i(e.trim())&&(Ne=!1),void xe();if(Re){if(["q","quit","exit","back","b","menu"].includes(o))return Re=!1,console.log(chalk.gray(He()?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void xe();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await mo(n,t?"fast":"deep"),console.log(chalk.gray(He()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void xe()}if(qe&&oo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${oo.phase}s${oo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o)return qe=!1,console.log(chalk.gray(He()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),co(),void xe();if(/^\d+$/.test(o))return vo(o),void xe();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,r]=e;return"list"===o?wo():r?"read"===o||"open"===o?vo(r):"edit"===o?await(async e=>{const o=ko(e);if(o){try{n("command -v vi",{stdio:"ignore"})}catch{return console.log(chalk.yellow(He()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),void console.log(chalk.bold.white(` ${f(oo.dir,`sol-${o.n}.py`)}`))}console.log(chalk.gray(He()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await Co("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(He()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(He()?" 自测样例。":" to self-check the sample.")),console.log()}})(r):"run"===o?(e=>{const o=ko(e);if(!o)return;const{p:n,n:r}=o,s=f(oo.dir,`sol-${r}.py`);if(!d(s))return void console.log(chalk.yellow(He()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const l=(n.samples??[])[0];if(!l)return void console.log(chalk.gray(He()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=t("python3",[s],{input:l.in.endsWith("\n")?l.in:`${l.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if(o.killed)console.log(chalk.yellow(He()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(He()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const i=a.replace(/\r\n/g,"\n").trimEnd(),c=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(He()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(He()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(He()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(He()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(He()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(He()?" 改完再 /run。":" then /run again.")),console.log()})(r):"debug"===o?await(async e=>{const o=ko(e);if(!o)return;const t=f(oo.dir,`sol-${o.n}.py`);d(t)?(console.log(chalk.gray(He()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log(),await Co("python3",[`sol-${o.n}.py`]),console.log(),console.log(chalk.gray(He()?" 回到竞技场。":" Back in the arena.")),console.log()):console.log(chalk.yellow(He()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`))})(r):"recall"===o&&await(async e=>{const o=ko(e);if(!o)return;if(!fe)return void uo();const{p:t,n:n}=o,r=f(process.cwd(),"icoa-contest"),s=`${ye.id}-phase${oo.phase}-g${oo.data.slot}-archived-`;let l=null;try{for(const e of u(r))e.startsWith(s)&&(!l||e>l)&&(l=e)}catch{}const a=l?f(r,l,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(He()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${oo.phase}-${oo.data.slot}-${n}`,g=Math.min(3,(Ao.get(c)??0)+1);console.log(chalk.gray(He()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const y=await _({token:me,phase:oo.phase,slot:oo.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:He()?"zh":"en"});if(y.ok){Ao.set(c,g),console.log();for(const e of de(y.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(He()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(He()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===y.code?console.log(chalk.yellow(He()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${y.message}`)):console.log(chalk.yellow(` ${y.message||"Coach unavailable."}`))})(r):console.log(chalk.yellow(He()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(He()?" (花名册: /list)":" (roster: /list)")),void xe()}if("contest"===o||"/contest"===o)return wo(),void xe();if("submit"!==l&&!l.startsWith("submit ")&&!o.startsWith("contest ")&&"contest reset"!==o&&"quit"!==o&&"q"!==o&&"exit"!==o&&"menu"!==o&&"menu confirm"!==o)return console.log(chalk.gray(He()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void xe()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(He()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void xe()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(Ae.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Ae.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void xe()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Ne=!0),void xe();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!fe)return uo(),void xe();Oe||(Oe=!0,console.log(),console.log(chalk.bold.cyan(He()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(He()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(He()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),He()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Re=!0;const e=Xe(we.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(He()?"AI 导师":"AI tutor")+(o?chalk.gray(He()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(He()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void xe()}return await mo(n,t?"fast":"deep"),void xe()}if(!qe&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!fe)return uo(),void xe();const e=Xe(we.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(He()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(He()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(He()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(He()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(He()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(He()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(He()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),ze=!0,void xe()}if(!qe&&("/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!fe)return uo(),void xe();const e=/^\/?view ([1-3])$/.exec(o);return await(async e=>{Pe=!0;try{console.log();const o=await E({token:me,cardNumber:we.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(He()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Be.delete(we.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Be.add(we.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(He()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${we.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${we.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(He()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(He()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=yo(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(He()?" (无可显示的提问)":" (no questions to show)"))}console.log(),De="view",console.log(chalk.gray((He()," "))+chalk.bold.cyan("↩ back")+chalk.gray(He()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Pe=!1}})(e?parseInt(e[1],10):void 0),void xe()}if("/honors"===o||"honors"===o)return he?(console.log(),console.log(chalk.gray(He()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void xe()):(await ho(),void xe());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return ne(ye,we),void xe();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(L().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void xe();const t=ye.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,s=r?n:"en";return j({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Me=null,Te=null,Ee=null,Se=null,Fe=!1,ze=!1,co(),void xe()}if("sim"===o){const e=Xe(we.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=p(b(import.meta.url)),o=[f(e,"..","..","panda","mujoco-launcher.py"),f(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(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 t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,t,"--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 xe()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void xe())}if("bookmark"===o){const e=we.currentCard;return we.bookmarks.includes(e)||we.bookmarks.push(e),N(we),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void xe()}if("e"===o)return Se=we.currentCard,console.log(chalk.gray(He()?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void xe();if("back"===o||"b"===o)return"view"===De?(await ho(),void xe()):"honors"===De?(De=null,co(),void xe()):(we.currentCard>1&&(we.currentCard-=1),Te=null,Ee=null,Me=null,N(we),co(),void xe());if("contest"===o||"contest start"===o||"contest status"===o||"contest reset"===o||/^contest [1-9]$/.test(o)){if(!to)return console.log(chalk.yellow(He()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void xe();const e=ro(we.currentCard);if("contest reset"===o){const o=await S(me,e);if(o.ok){console.log(chalk.yellow(He()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let t=1;t<=3;t++){const n=f(process.cwd(),"icoa-contest",`${ye.id}-phase${e}-g${t}`);if(d(n))try{y(n,`${n}-archived-${o}`),console.log(chalk.gray(He()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(He()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(He()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),oo=null,qe=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void xe()}const t=/^contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(He()?" 连接判分赛…":" Contacting contest server…"));const n=await R(me,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(He()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void xe();const r=n.data,s=f(process.cwd(),"icoa-contest",`${ye.id}-phase${e}-g${r.slot}`);g(s,{recursive:!0});const l=oo&&oo.phase===e&&oo.data.slot===r.slot?oo.tried:new Set;oo={phase:e,dir:s,data:r,tried:l},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,s=(t.samples??[])[0];s&&h(f(o,`sample-${r}.txt`),s.in.endsWith("\n")?s.in:`${s.in}\n`);const l=f(o,`sol-${r}.py`);if(d(l))return;const a=He()&&t.statement_zh?`# English statement: type "lang en" in icoa, then /read ${r}`:t.statement_zh?`# 中文题面: 在 icoa 中输入 lang zh,然后 /read ${r}`:null,i=[`# ══ ${e.title||"PY Arena"} · ${po(t)} ══`,"#",...de(fo(t),72).map(e=>e?`# ${e}`:"#")];if(a&&i.push("#",a),s){i.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of s.in.split("\n"))i.push(`# ${e}`);i.push("# Expected output:");for(const e of s.out.split("\n"))i.push(`# ${e}`)}i.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),h(l,i.join("\n"))})})(r,s),qe=!0,wo(),console.log(chalk.gray(He()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(s));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(He()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(He()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void xe()}if("submit"===l)return console.log(chalk.yellow(He()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(He()?" 例如 submit 1 判第 1 题(默认判 sol-…q1.py;submit 1 <路径> 判指定文件)":" e.g. submit 1 grades problem 1 (defaults to sol-…q1.py; submit 1 <path> for a custom file)")),oo||console.log(chalk.gray(He()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void xe();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const t=e[2];if(!oo)return console.log(chalk.yellow(He()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void xe();const n=oo.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=n.length&&!n.some(e=>e.id===o)&&(o=n[r-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(He()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void xe();const s=n.findIndex(e=>e.id===o)+1,a=t||f(oo.dir,`sol-${s}.py`);let i;try{i=m(a,"utf-8")}catch{return console.log(chalk.red(He()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void xe()}console.log(chalk.gray(He()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await P(me,oo.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(He()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((He()," "))+chalk.bold.green("contest")+chalk.gray(He()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(He()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void xe();const d=c.data;if(d.already_ac)console.log(chalk.green(He()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(He()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(He()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),oo.data.solved.includes(o)||oo.data.solved.push(o),oo.tried.delete(o);else{oo.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?He()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(He()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=D(d.deadline||"");if(console.log(chalk.white(He()?` 本组进度: 已过 ${d.ac_count} 题 · 过 ${d.need} 题过关(共 ${d.n} 题)`:` Group progress: ${d.ac_count} solved · ${d.need} needed to pass (${d.n} problems)`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(He()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await no();else if(!d.late){const e=n.findIndex(e=>!oo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(He()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${po(n[e])}`))}return void xe()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>ye.totalCards)return console.log(chalk.yellow(` Card number must be 1..${ye.totalCards}. Try: `)+chalk.bold.green("card 1")),void xe();const n=await lo(t);return n?(console.log(n),void xe()):(we.currentCard=t,Te=null,Ee=null,Me=null,N(we),co(),void xe())}if(null!==Me&&["y","yes","n","no"].includes(o)){const e=Xe(Me);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Ue;z(we,e.number),F(we,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),N(we);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),Ze.push(k(me,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Me=null,e.solution&&e.solution.length>0)return void xe();if(we.currentCard<ye.totalCards){const e=we.currentCard,o=await lo(e+1);if(o)return await ao(e),console.log(o),void xe();we.currentCard+=1,N(we),await ao(e)?io():co(),xe()}else se(ye,we),xe();return}}if(null!==Te&&["a","b","c","d"].includes(o)){const e=Xe(Te);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(B(we,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),z(we,e.number),N(we),Q(e,t,n,we),Ze.push(k(me,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Te=null,n)if(we.currentCard<ye.totalCards){const e=await lo(we.currentCard+1);if(e)return console.log(e),void xe();we.currentCard+=1,N(we),co()}else se(ye,we),xe();else xe();return}}if(null!==Ee){if("done"===o){const e=Xe(Ee);if(e&&"practical"===e.type)return U(we,e.number),z(we,e.number),N(we),G(e),Ee=null,void xe()}if("skip"===o)return z(we,Ee),N(we),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Ee=null,void xe()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==Te)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void xe();if(null!==Ee)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void xe();if(null!==Me)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void xe();const e=we.currentCard,o=e<ye.totalCards?await lo(e+1):null;return o?(await ao(e),console.log(o),void xe()):(we.currentCard+=1,N(we),we.currentCard>ye.totalCards?se(ye,we):await ao(e)?io():co(),void xe())}if(null!==Me)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void xe();if(null!==Te)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void xe();if(null!==Ee)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void xe();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")),xe()}else if(Ze.length>0&&await Promise.race([Promise.allSettled(Ze),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${we.streakDays} day(s)`)),console.log(),ve){Ae.removeAllListeners("line"),Ie();for(const e of Ce)Ae.on("line",e);Ae.prompt(),Ve()}else Ae.removeAllListeners("line"),Ae.close();else if(Ze.length>0&&await Promise.race([Promise.allSettled(Ze),new Promise(e=>setTimeout(e,3e3))]),Ae.removeAllListeners("line"),Ie(),ve||!Ge){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ve?Ae:void 0),Ve()}else Ae.close()}else xe()}};Ae.on("line",e=>{_o(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.")),xe()})}),ve||Ae.on("close",async()=>{Ze.length>0&&await Promise.race([Promise.allSettled(Ze),new Promise(e=>setTimeout(e,5e3))]),Ge?Ve():process.exit(0)});try{co(),xe();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(ge("Could not render this card — the curriculum may be malformed."),ve){Ae.removeAllListeners("line"),Ie();for(const e of Ce)Ae.on("line",e);Ae.prompt()}else Ae.close();Ve()}await Qe}),ue.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 t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),s=await w(e),l=Date.now()-o;if(s){const e=s.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(s).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${l.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{logCommand as s}from"../lib/logger.js";import{getMainRl as l}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as a,handleAi4ioaiMessage as i,startAi4ioaiChat as c}from"./ai4ioai.js";import{existsSync as d,mkdirSync as g,readdirSync as u,readFileSync as m,renameSync as y,writeFileSync as h}from"node:fs";import{dirname as p,join as f}from"node:path";import{fileURLToPath as b}from"node:url";import{loadCurriculumById as w,validateEAToken as $,syncProgress as k,syncCardFeedback as v}from"../lib/learn-curricula.js";import{normalizeTokenBody as C}from"../lib/token-format.js";import{fetchMyScores as A,recallCoach as _,setNickname as I,streamLearnTutor as T,submitPqs as x,viewPqsTop as E,viewHonors as M}from"../lib/learn-ai.js";import{contestReset as q,contestStart as S,contestSubmit as R,fetchGate as P,timeLeft as O}from"../lib/learn-contest.js";import{getConfig as D,saveConfig as L}from"../lib/config.js";import{loadLearnState as j,saveLearnState as N,newLearnState as W,updateStreak as Y,markCardComplete as z,recordMCQ as B,recordCheck as U,markPracticalComplete as F,addAchievement as Z}from"../lib/learn-state.js";import{renderWelcome as H,renderKnowledgeCard as J,renderMCQCard as K,renderMCQFeedback as Q,renderPracticalCard as V,renderPracticalSuccess as G,renderSimDemoCard as X,renderMilestone as ee,renderArenaTaskCard as oe,renderComingSoonCard as te,renderStatus as ne,renderPhaseComplete as re,renderCurriculumComplete as se,setLearnAiEnabled as le,setLearnHonorRanks as ae,setLearnPqsViewCards as ie,renderHonorWall as ce,wrapMixed as de}from"../lib/learn-render.js";import{printError as ge}from"../lib/ui.js";export function registerLearnCommand(ue){ue.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ue=>{ue?.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 <your token>")+chalk.gray(" (2 letters + 8 chars) — from your country team leader.")),console.log(),ue="LEARNDEMO01");let me=ue.trim().toUpperCase(),ye=null;const he=/^[A-Z0-9]+DEMO01$/i.test(me),pe=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(me);let fe=!1,be=!1;if(he)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),ye=await w(me,me);else if(pe){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(me);if(!e.ok){const o=C(me);if(o!==me){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${me} → ${o}`)),e=t,me=o)}}if(!e.ok)return ge(`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"):"")),fe=!0===e.aiEnabled,be=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),ye=await w(e.curriculumId||"LEARNDEMO01",me),!ye)return ge(`Could not open a learn curriculum for token '${me}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${me}`)+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 ${me}`)+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(!ye)return ge(`Unknown learn token: ${me}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Every track has a free demo — ask for its name if you were not given one.")),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 we=j(),$e=!1;try{we&&we.token===me?Y(we):(we=W(me,ye.id,ye.totalCards),$e=!0),N(we),H(ye,we,$e)}catch{return ge("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 ${me}`)+chalk.gray(".")),void console.log()}const ke=l(),ve=null!==ke,Ce=ve?ke.listeners("line").slice():[];ve&&ke.removeAllListeners("line");const Ae=ve?ke:o({input:process.stdin,output:process.stdout,terminal:!0}),_e=ve?Ae.prompt:null;ve&&(Ae.prompt=e.prototype.prompt);const Ie=()=>{ve&&_e&&(Ae.prompt=_e)},Te=()=>{Ae.setPrompt(Ne?chalk.bold.green(`icoa ${a()}> `):Pe?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Se?"icoa learn ai> ":"icoa learn> ")),Ae.prompt()};let xe=null,Ee=null,Me=null,qe=null,Se=!1,Re=!1,Pe=!1,Oe=null,De=!1,Le=0,je=!1,Ne=!1;const We=new Map,Ye=()=>{let e=We.get(we.currentCard);return e||(e=[],We.set(we.currentCard,e)),e};let ze=!1;const Be=new Set;let Ue=!1,Fe=0;const Ze=()=>(D().language||"en").toLowerCase().startsWith("zh");le(fe),ie(Be);const He=new Map;ae(He);const Je=[];let Ke=null;const Qe=new Promise(e=>{Ke=e}),Ve=()=>{const e=Ke;Ke=null,e?.()},Ge="1"===process.env.ICOA_LEARN_EMBEDDED,Xe=e=>ye.cards.find(o=>o.number===e);let eo=null,oo=null;const to=!me.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(me),no=async()=>{if(!to)return;const e=await P(me);e.ok&&e.data&&(eo=e.data)},ro=e=>{const o=ye.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},so=e=>{if(!be||!eo)return null;const o=ro(e);if(o<=eo.unlocked_through_phase)return null;const t=eo.phases.find(e=>e.phase===eo.unlocked_through_phase),n=[chalk.yellow(Ze()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${eo.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${eo.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(Ze()?` ⚔ 练习赛 ${eo.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${eo.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(Ze()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(Ze()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},lo=async e=>be?null===so(e)?null:(await no(),so(e)):null;be&&await no();const ao=async e=>{const o=ye.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=ye.modules.find(e=>e.number===o.number+1);let n;if(fe){const e=await A({token:me,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}to&&await no();const r=eo?.phases.find(e=>e.phase===o.number);return re(ye,we,o,t,n,r),!0},io=()=>{Ue=!0,console.log(chalk.gray(Ze()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},co=()=>{Oe=null;const e=Xe(we.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":J(e,ye),e.check?(Me=e.number,Fe=Date.now()):(z(we,e.number),N(we));break;case"mcq":K(e,ye),xe=e.number;break;case"practical":V(e,ye),Ee=e.number;break;case"sim_demo":X(e,ye),z(we,e.number),N(we);break;case"milestone":ee(e,ye),Z(we,e.badge),z(we,e.number),N(we);break;case"arena_task":oe(e,ye),z(we,e.number),N(we);break;case"coming_soon":te(e,ye),z(we,e.number),N(we)}go(e.number)},go=e=>{if(!be||!to||!eo)return;const o=ye.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1;if(t%4!=0)return;const n=t/4,r=eo.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n);if(!s)return;const l=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),l=(n||"").slice(0,10);return`🏆 ${e} ${o}/${s.n}`+(r?Ze()?` · 用时 ${r}`:` · ${r}`:"")+(l?` · ${l}`:"")},a=s.perfect_runs??[],i=!!s.best&&(s.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(64);if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${Ze()?"练习赛":"PY Arena"} ${o.number}-${n}`)+(s.passed?chalk.bold.green(Ze()?" ✅ 已通过":" ✅ passed"):"")),s.passed||(Ze()?console.log(c+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(c+chalk.white("You learned the cards — now prove it.")),console.log(c+chalk.white("The clock starts the moment you type the command."))),console.log(c+chalk.gray(Ze()?`${s.n} 题 · AC ${s.need} 过关 · 限时 ${s.duration_minutes} 分钟 · 无限重开`:`${s.n} problems · AC ${s.need} to pass · ${s.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(Ze()?"✍ 第一次用 vi?/edit 打开后:i 开始输入 · Esc 退出输入 · :wq 保存退出":"✍ New to vi? After /edit: i = type · Esc = stop typing · :wq = save & quit"))),a.length>0)for(const e of a)console.log(c+chalk.bold.yellow(l(Ze()?"满分":"Perfect",s.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(l(Ze()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(s.passed?chalk.gray(Ze()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Ze()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(Ze()?" 继续学习":" keep going"):chalk.gray(Ze()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},uo=()=>{me.endsWith("DEMO01")?console.log(chalk.yellow(Ze()?" 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(Ze()?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Ze()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},mo=async(e,o)=>{if(fe){Re=!0;try{console.log(),console.log(chalk.gray("deep"===o?Ze()?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Ze()?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await T({token:me,cardNumber:we.currentCard,question:e,mode:o,history:Ye().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(Ze()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Ye().push({role:"user",content:e},{role:"assistant",content:r.answer}),null!=r.spent&&null!=r.cap&&r.spent/r.cap>.8&&console.log(chalk.gray(` (${Ze()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Ze()?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==Me&&console.log(chalk.gray(Ze()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Re=!1}}else uo()},yo=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],ho=async()=>{Re=!0;try{console.log();const e=await M({token:me,curriculumId:ye.id,cardNumber:we.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Ze()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Ze()?` 🏆 本卡实时 Top-3 — 第 ${we.currentCard} 张`:` 🏆 Live top-3 — card ${we.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.name||`Rank ${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(Ze()?" (你)":" (you)"):""))}else console.log(chalk.gray(Ze()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(He.set(we.currentCard,e.mine.rank),console.log(chalk.white(Ze()?" 你: ":" You: ")+chalk.bold.yellow(Ze()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Ze()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):fe&&console.log(chalk.gray(Ze()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),ce({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Ze()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Ze()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Ze()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Oe="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Ze()?" 返回卡片":" returns to the card")),console.log()}finally{Re=!1}},po=e=>Ze()&&e.title_zh||e.title,fo=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of de(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},bo=e=>oo.data.solved.includes(e.id)?"✅":oo.tried.has(e.id)?"❌":"⬜",wo=()=>{const e=oo.data,o=O(e.deadline),t=e.solved.length,n=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(Ze()?` · 第 ${e.slot}/${e.group_count} 组 · 第 ${e.attempt} 次尝试${e.resumed?"(续)":""}`:` · group ${e.slot}/${e.group_count} · attempt ${e.attempt}${e.resumed?" (resumed)":""}`)),console.log((o?chalk.bold.yellow(` ⏱ ${o}`):chalk.red(Ze()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(Ze()?`(共 ${e.n} 题)`:` (of ${e.n})`));const r=Date.parse(e.deadline)-Date.now();o?e.resumed&&r<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(Ze()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Ze()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(Ze()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(Ze()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+bo(e)+chalk.white(` ${po(e)}`))}),console.log(),$o()},$o=()=>{console.log(chalk.gray(Ze()?" /read <n> 读题 · /edit <n> 写码(vi) · /run <n> 样例自测 · /debug <n> 自由调试 · /submit <n> 判分":" /read <n> statement · /edit <n> code (vi) · /run <n> sample check · /debug <n> free run · /submit <n> judge")),console.log(chalk.gray(Ze()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Ze()?" 返回课程":" returns to the lesson")),console.log()},ko=e=>{const o=parseInt(e,10),t=oo.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(Ze()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}},vo=e=>{const o=ko(e);if(!o)return;const{p:t,n:n}=o;console.log(),console.log(chalk.bold.white(` ${bo(t)} ${po(t)}`)),console.log();for(const e of(e=>Ze()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of de(e,66))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(Ze()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Ze()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(Ze()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(Ze()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Ze()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(Ze()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(Ze()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Ze()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log()},Co=async(e,o)=>{await new Promise(t=>{const n=process.stdin,s=!!n.isTTY&&!!n.isRaw;if(Ae.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e,o,{stdio:"inherit",cwd:oo.dir}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&s)try{n.setRawMode(!0)}catch{}Ae.resume(),t()};l.on("close",a),l.on("error",a)})},Ao=new Map,_o=async e=>{const o=e.trim().toLowerCase(),l=Pe&&o.startsWith("/")?o.slice(1):o;if(!Re){if(null!==qe){const o=e.trim(),t=qe;if(qe=null,""===o)console.log(chalk.gray(Ze()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=Fe>0?Date.now()-Fe:void 0;await v(me,{curriculum_id:ye.id,card_number:t,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(Ze()?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Ze()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void Te()}if(De){const o=e.trim();if(!o)return De=!1,console.log(chalk.gray(Ze()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Te();const t=await I({token:me,nickname:o});if(t.ok)De=!1,console.log(chalk.bold.green(Ze()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Ze()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Le+=1;const e="taken"===t.code?Ze()?"已被占用":"already taken":"bad_charset"===t.code?Ze()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?Ze()?"未通过审核":"did not pass review":t.message||"error";if(!(Le>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ze()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Te();De=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ze()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Te()}if(ze){ze=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Re=!0;try{console.log(),console.log(chalk.gray(Ze()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await x({token:me,cardNumber:we.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Ze()?"评审暂不可用。":"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(Ze()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Ze()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Ze()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Ze()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Ze()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Ze()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=Ze()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(Ze()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Ze()?` 第 ${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 yo(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Ze()?" 改进提问: ":" 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(` (${Ze()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Be.add(we.currentCard):Be.delete(we.currentCard),"number"==typeof e.rank&&He.set(we.currentCard,e.rank);const o=await M({token:me,curriculumId:ye.id,cardNumber:we.currentCard});o.ok&&o.totals&&o.chapters&&(ce({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!he&&(De=!0,Le=0,console.log(chalk.bold.yellow(Ze()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Ze()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Ze()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Re=!1}})():(console.log(chalk.gray(Ze()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Me&&(console.log(chalk.gray(Ze()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Te()}if(Ue)return Ue=!1,co(),void Te();if(o){if(Ne)return"exit"===await i(e.trim())&&(Ne=!1),void Te();if(Se){if(["q","quit","exit","back","b","menu"].includes(o))return Se=!1,console.log(chalk.gray(Ze()?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void Te();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await mo(n,t?"fast":"deep"),console.log(chalk.gray(Ze()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Te()}if(Pe&&oo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${oo.phase}s${oo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o)return Pe=!1,console.log(chalk.gray(Ze()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),co(),void Te();if(/^\d+$/.test(o))return vo(o),void Te();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,r]=e;return"list"===o?wo():r?"read"===o||"open"===o?vo(r):"edit"===o?await(async e=>{const o=ko(e);if(o){try{n("command -v vi",{stdio:"ignore"})}catch{return console.log(chalk.yellow(Ze()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),void console.log(chalk.bold.white(` ${f(oo.dir,`sol-${o.n}.py`)}`))}console.log(chalk.gray(Ze()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await Co("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(Ze()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Ze()?" 自测样例。":" to self-check the sample.")),console.log()}})(r):"run"===o?(e=>{const o=ko(e);if(!o)return;const{p:n,n:r}=o,s=f(oo.dir,`sol-${r}.py`);if(!d(s))return void console.log(chalk.yellow(Ze()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const l=(n.samples??[])[0];if(!l)return void console.log(chalk.gray(Ze()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=t("python3",[s],{input:l.in.endsWith("\n")?l.in:`${l.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if(o.killed)console.log(chalk.yellow(Ze()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Ze()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const i=a.replace(/\r\n/g,"\n").trimEnd(),c=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(Ze()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Ze()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(Ze()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Ze()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Ze()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Ze()?" 改完再 /run。":" then /run again.")),console.log()})(r):"debug"===o?await(async e=>{const o=ko(e);if(!o)return;const t=f(oo.dir,`sol-${o.n}.py`);d(t)?(console.log(chalk.gray(Ze()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log(),await Co("python3",[`sol-${o.n}.py`]),console.log(),console.log(chalk.gray(Ze()?" 回到竞技场。":" Back in the arena.")),console.log()):console.log(chalk.yellow(Ze()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`))})(r):"recall"===o&&await(async e=>{const o=ko(e);if(!o)return;if(!fe)return void uo();const{p:t,n:n}=o,r=f(process.cwd(),"icoa-contest"),s=`${ye.id}-phase${oo.phase}-g${oo.data.slot}-archived-`;let l=null;try{for(const e of u(r))e.startsWith(s)&&(!l||e>l)&&(l=e)}catch{}const a=l?f(r,l,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(Ze()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${oo.phase}-${oo.data.slot}-${n}`,g=Math.min(3,(Ao.get(c)??0)+1);console.log(chalk.gray(Ze()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const y=await _({token:me,phase:oo.phase,slot:oo.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:Ze()?"zh":"en"});if(y.ok){Ao.set(c,g),console.log();for(const e of de(y.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(Ze()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(Ze()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===y.code?console.log(chalk.yellow(Ze()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${y.message}`)):console.log(chalk.yellow(` ${y.message||"Coach unavailable."}`))})(r):console.log(chalk.yellow(Ze()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(Ze()?" (花名册: /list)":" (roster: /list)")),void Te()}if("contest"===o||"/contest"===o)return wo(),void Te();if("submit"!==l&&!l.startsWith("submit ")&&!o.startsWith("contest ")&&"contest reset"!==o&&"quit"!==o&&"q"!==o&&"exit"!==o&&"menu"!==o&&"menu confirm"!==o)return console.log(chalk.gray(Ze()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Te()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(Ze()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Te()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(Ae.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Ae.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void Te()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Ne=!0),void Te();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!fe)return uo(),void Te();je||(je=!0,console.log(),console.log(chalk.bold.cyan(Ze()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Ze()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Ze()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Ze()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Se=!0;const e=Xe(we.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Ze()?"AI 导师":"AI tutor")+(o?chalk.gray(Ze()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ze()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Te()}return await mo(n,t?"fast":"deep"),void Te()}if(!Pe&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!fe)return uo(),void Te();const e=Xe(we.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Ze()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Ze()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ze()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Ze()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Ze()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Ze()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Ze()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),ze=!0,void Te()}if(!Pe&&("/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!fe)return uo(),void Te();const e=/^\/?view ([1-3])$/.exec(o);return await(async e=>{Re=!0;try{console.log();const o=await E({token:me,cardNumber:we.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Ze()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Be.delete(we.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Be.add(we.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Ze()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${we.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${we.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Ze()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(Ze()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=yo(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(Ze()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Oe="view",console.log(chalk.gray((Ze()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Ze()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Re=!1}})(e?parseInt(e[1],10):void 0),void Te()}if("/honors"===o||"honors"===o)return he?(console.log(),console.log(chalk.gray(Ze()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Te()):(await ho(),void Te());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return ne(ye,we),void Te();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(D().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Te();const t=ye.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,s=r?n:"en";return L({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Me=null,xe=null,Ee=null,qe=null,Ue=!1,ze=!1,co(),void Te()}if("sim"===o){const e=Xe(we.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=p(b(import.meta.url)),o=[f(e,"..","..","panda","mujoco-launcher.py"),f(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(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 t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,t,"--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 Te()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Te())}if("bookmark"===o){const e=we.currentCard;return we.bookmarks.includes(e)||we.bookmarks.push(e),N(we),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void Te()}if("e"===o)return qe=we.currentCard,console.log(chalk.gray(Ze()?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void Te();if("back"===o||"b"===o)return"view"===Oe?(await ho(),void Te()):"honors"===Oe?(Oe=null,co(),void Te()):(we.currentCard>1&&(we.currentCard-=1),xe=null,Ee=null,Me=null,N(we),co(),void Te());if("contest"===o||"contest start"===o||"contest status"===o||"contest reset"===o||/^contest [1-9]$/.test(o)){if(!to)return console.log(chalk.yellow(Ze()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Te();const e=ro(we.currentCard);if("contest reset"===o){const o=await q(me,e);if(o.ok){console.log(chalk.yellow(Ze()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let t=1;t<=3;t++){const n=f(process.cwd(),"icoa-contest",`${ye.id}-phase${e}-g${t}`);if(d(n))try{y(n,`${n}-archived-${o}`),console.log(chalk.gray(Ze()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(Ze()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(Ze()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),oo=null,Pe=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Te()}const t=/^contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Ze()?" 连接判分赛…":" Contacting contest server…"));const n=await S(me,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(Ze()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void Te();const r=n.data,s=f(process.cwd(),"icoa-contest",`${ye.id}-phase${e}-g${r.slot}`);g(s,{recursive:!0});const l=oo&&oo.phase===e&&oo.data.slot===r.slot?oo.tried:new Set;oo={phase:e,dir:s,data:r,tried:l},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,s=(t.samples??[])[0];s&&h(f(o,`sample-${r}.txt`),s.in.endsWith("\n")?s.in:`${s.in}\n`);const l=f(o,`sol-${r}.py`);if(d(l))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...fo(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),s){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of s.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of s.out.split("\n"))a.push(`# ${e}`)}a.push("#","# ── vi quick guide ── (/edit opens this file in vi)","# i = insert mode — start typing","# Esc = back to command mode","# :wq or ZZ = save & quit · :q! = quit WITHOUT saving","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),h(l,a.join("\n"))})})(r,s),Pe=!0,wo(),console.log(chalk.gray(Ze()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(s));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(Ze()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(Ze()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Te()}if("submit"===l)return console.log(chalk.yellow(Ze()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(Ze()?" 例如 submit 1 判第 1 题(默认判 sol-…q1.py;submit 1 <路径> 判指定文件)":" e.g. submit 1 grades problem 1 (defaults to sol-…q1.py; submit 1 <path> for a custom file)")),oo||console.log(chalk.gray(Ze()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Te();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const t=e[2];if(!oo)return console.log(chalk.yellow(Ze()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Te();const n=oo.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=n.length&&!n.some(e=>e.id===o)&&(o=n[r-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(Ze()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Te();const s=n.findIndex(e=>e.id===o)+1,a=t||f(oo.dir,`sol-${s}.py`);let i;try{i=m(a,"utf-8")}catch{return console.log(chalk.red(Ze()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Te()}console.log(chalk.gray(Ze()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await R(me,oo.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(Ze()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((Ze()," "))+chalk.bold.green("contest")+chalk.gray(Ze()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(Ze()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void Te();const d=c.data;if(d.already_ac)console.log(chalk.green(Ze()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(Ze()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(Ze()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),oo.data.solved.includes(o)||oo.data.solved.push(o),oo.tried.delete(o);else{oo.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?Ze()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(Ze()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=O(d.deadline||"");if(console.log(chalk.white(Ze()?` 本组进度: 已过 ${d.ac_count} 题 · 过 ${d.need} 题过关(共 ${d.n} 题)`:` Group progress: ${d.ac_count} solved · ${d.need} needed to pass (${d.n} problems)`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(Ze()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await no();else if(!d.late){const e=n.findIndex(e=>!oo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Ze()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${po(n[e])}`))}return void Te()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>ye.totalCards)return console.log(chalk.yellow(` Card number must be 1..${ye.totalCards}. Try: `)+chalk.bold.green("card 1")),void Te();const n=await lo(t);return n?(console.log(n),void Te()):(we.currentCard=t,xe=null,Ee=null,Me=null,N(we),co(),void Te())}if(null!==Me&&["y","yes","n","no"].includes(o)){const e=Xe(Me);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Fe;z(we,e.number),U(we,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),N(we);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),Je.push(k(me,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Me=null,e.solution&&e.solution.length>0)return void Te();if(we.currentCard<ye.totalCards){const e=we.currentCard,o=await lo(e+1);if(o)return await ao(e),console.log(o),void Te();we.currentCard+=1,N(we),await ao(e)?io():co(),Te()}else se(ye,we),Te();return}}if(null!==xe&&["a","b","c","d"].includes(o)){const e=Xe(xe);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(B(we,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),z(we,e.number),N(we),Q(e,t,n,we),Je.push(k(me,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),xe=null,n)if(we.currentCard<ye.totalCards){const e=await lo(we.currentCard+1);if(e)return console.log(e),void Te();we.currentCard+=1,N(we),co()}else se(ye,we),Te();else Te();return}}if(null!==Ee){if("done"===o){const e=Xe(Ee);if(e&&"practical"===e.type)return F(we,e.number),z(we,e.number),N(we),G(e),Ee=null,void Te()}if("skip"===o)return z(we,Ee),N(we),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Ee=null,void Te()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==xe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Te();if(null!==Ee)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Te();if(null!==Me)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Te();const e=we.currentCard,o=e<ye.totalCards?await lo(e+1):null;return o?(await ao(e),console.log(o),void Te()):(we.currentCard+=1,N(we),we.currentCard>ye.totalCards?se(ye,we):await ao(e)?io():co(),void Te())}if(null!==Me)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Te();if(null!==xe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Te();if(null!==Ee)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Te();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")),Te()}else if(Je.length>0&&await Promise.race([Promise.allSettled(Je),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${we.streakDays} day(s)`)),console.log(),ve){Ae.removeAllListeners("line"),Ie();for(const e of Ce)Ae.on("line",e);Ae.prompt(),Ve()}else Ae.removeAllListeners("line"),Ae.close();else if(Je.length>0&&await Promise.race([Promise.allSettled(Je),new Promise(e=>setTimeout(e,3e3))]),Ae.removeAllListeners("line"),Ie(),ve||!Ge){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ve?Ae:void 0),Ve()}else Ae.close()}else Te()}};Ae.on("line",e=>{_o(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.")),Te()})}),ve||Ae.on("close",async()=>{Je.length>0&&await Promise.race([Promise.allSettled(Je),new Promise(e=>setTimeout(e,5e3))]),Ge?Ve():process.exit(0)});try{co(),Te();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(ge("Could not render this card — the curriculum may be malformed."),ve){Ae.removeAllListeners("line"),Ie();for(const e of Ce)Ae.on("line",e);Ae.prompt()}else Ae.close();Ve()}await Qe}),ue.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 t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),s=await w(e),l=Date.now()-o;if(s){const e=s.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(s).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${l.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.412",
3
+ "version": "2.19.413",
4
4
  "description": "ICOA CLI — The world's first CLI-native cyber & AI security olympiad terminal: AI4CTF (Day 1), CTF4AI (Day 2), VLA4CTF (Pioneer Round — embodied AI)",
5
5
  "type": "module",
6
6
  "bin": {