icoa-cli 2.19.435 → 2.19.437

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 l}from"../lib/logger.js";import{getMainRl as s}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 y,renameSync as m,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 T,setNickname as _,streamLearnTutor as I,submitPqs as x,viewPqsTop as E,viewHonors as S}from"../lib/learn-ai.js";import{contestReset as P,contestStart as q,contestSubmit as M,linkToken as L,fetchGate as W,timeLeft as R}from"../lib/learn-contest.js";import{getConfig as O,saveConfig as N}from"../lib/config.js";import{isNativeWindows as j,isWindowsBuildInWslShell as D,whichBinary as Y}from"../lib/platform.js";import{loadLearnState as U,saveLearnState as F,newLearnState as z,updateStreak as H,markCardComplete as B,recordMCQ as Z,recordCheck as J,markPracticalComplete as K,addAchievement as Q}from"../lib/learn-state.js";import{renderWelcome as V,renderKnowledgeCard as X,renderMCQCard as G,renderMCQFeedback as ee,renderPracticalCard as oe,renderPracticalSuccess as te,renderSimDemoCard as ne,renderMilestone as re,renderArenaTaskCard as le,renderComingSoonCard as se,renderStatus as ae,renderPhaseComplete as ie,renderCurriculumComplete as ce,setLearnAiEnabled as de,setLearnHonorRanks as ge,setLearnPqsViewCards as ue,setLearnWide as ye,learnW as me,renderHonorWall as he,wrapMixed as pe}from"../lib/learn-render.js";import{printError as fe}from"../lib/ui.js";export function registerLearnCommand(be){be.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async be=>{be?.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(),be="LEARNDEMO01");let we=be.trim().toUpperCase(),$e=null;const ke=/^[A-Z0-9]+DEMO01$/i.test(we),ve=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(we);let Ce=!1,Ae=!1;if(ke)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),$e=await w(we,we);else if(ve){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(we);if(!e.ok){const o=C(we);if(o!==we){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${we} → ${o}`)),e=t,we=o)}}if(!e.ok)return fe(`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 Panda Tutor 🐼"):"")),Ce=!0===e.aiEnabled,Ae=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),$e=await w(e.curriculumId||"LEARNDEMO01",we),!$e)return fe(`Could not open a learn curriculum for token '${we}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${we}`)+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 ${we}`)+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(!$e){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(fe(`Could not reach the learn server to open ${we}.`),console.log(),console.log(chalk.gray(" Your token may be perfectly fine — we could not ask.")),console.log(chalk.gray(" Check your connection, then run ")+chalk.bold.yellow(`learn ${we}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(fe(`Unknown learn token: ${we}`),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(" Most tracks have a free demo. From the ")+chalk.bold.green("learn")+chalk.gray(" menu you can type the track name itself")),console.log(chalk.gray(" (e.g. ")+chalk.bold.green("biology")+chalk.gray(", ")+chalk.bold.green("ioipy")+chalk.gray(") and it opens that track's demo if one is published.")),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 Te=U(),_e=!1;try{Te&&Te.token===we?H(Te):(Te=z(we,$e.id,$e.totalCards),_e=!0),F(Te),V($e,Te,_e)}catch{return fe("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 ${we}`)+chalk.gray(".")),void console.log()}const Ie=s(),xe=null!==Ie,Ee=xe?Ie.listeners("line").slice():[];xe&&Ie.removeAllListeners("line");const Se=xe?Ie:o({input:process.stdin,output:process.stdout,terminal:!0}),Pe=xe?Se.prompt:null;xe&&(Se.prompt=e.prototype.prompt);const qe=()=>{xe&&Pe&&(Se.prompt=Pe)},Me=()=>{Se.setPrompt(Ke?chalk.bold.green(`icoa ${a()}> `):ze?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Ue?"icoa learn ai> ":"icoa learn> ")),Se.prompt()};let Le=null,We=null,Re=null,Oe=null,Ne=[],je=!1,De=null;const Ye=()=>{De&&clearTimeout(De),De=null,Ne=[],je=!1,Oe=null};let Ue=!1,Fe=!1,ze=!1,He=null,Be=!1,Ze=0,Je=!1,Ke=!1;const Qe=new Map,Ve=()=>{let e=Qe.get(Te.currentCard);return e||(e=[],Qe.set(Te.currentCard,e)),e};let Xe=!1;const Ge=new Set;let eo=!1,oo=0;const to=()=>(O().language||"en").toLowerCase().startsWith("zh");de(Ce),ye(!!O().learnWide),ue(Ge);const no=new Map;ge(no);const ro=[];let lo=null;const so=new Promise(e=>{lo=e}),ao=()=>{const e=lo;lo=null,e?.()},io="1"===process.env.ICOA_LEARN_EMBEDDED,co=e=>$e.cards.find(o=>o.number===e);let go=null,uo=null;const yo=!we.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(we),mo=async()=>{if(!yo)return;const e=await W(we);e.ok&&e.data&&(go=e.data)},ho=e=>{const o=$e.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},po=e=>{if(!Ae||!go)return null;const o=ho(e);if(o<=go.unlocked_through_phase)return null;const t=go.phases.find(e=>e.phase===go.unlocked_through_phase),n=[chalk.yellow(to()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${go.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${go.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(to()?` ⚔ 练习赛 ${go.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${go.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(to()?` ⚖ 判分赛: 最好 ${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(to()?` ⭐ 提问研究: ${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")},fo=async e=>Ae?null===po(e)?null:(await mo(),po(e)):null;yo&&await mo();const bo=async e=>{const o=$e.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=$e.modules.find(e=>e.number===o.number+1);let n;if(Ce){const e=await A({token:we,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}yo&&await mo();const r=go?.phases.find(e=>e.phase===o.number);return ie($e,Te,o,t,n,r),!0},wo=()=>{eo=!0,console.log(chalk.gray(to()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},$o=()=>{He=null;const e=co(Te.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":X(e,$e),e.check?(Re=e.number,oo=Date.now()):(B(Te,e.number),F(Te));break;case"mcq":G(e,$e),Le=e.number;break;case"practical":oe(e,$e),We=e.number;break;case"sim_demo":ne(e,$e),B(Te,e.number),F(Te);break;case"milestone":re(e,$e),Q(Te,e.badge),B(Te,e.number),F(Te);break;case"arena_task":le(e,$e),B(Te,e.number),F(Te);break;case"coming_soon":se(e,$e),B(Te,e.number),F(Te)}ko(e.number)},ko=e=>{if(!yo||!go)return;const o=$e.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=go.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===n);if(!l)return;const s=(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),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const t=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${t(o.getMonth()+1)}-${t(o.getDate())} ${t(o.getHours())}:${t(o.getMinutes())}`})(n);return`🏆 ${e} ${o}/${l.n}`+(r?to()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(me());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${to()?`练习赛 ${o.number}-${n}`:l.title||`PY Arena ${o.number}-${n}`}`)+(l.passed?chalk.bold.green(to()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(to()?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(to()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(to()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))),a.length>0)for(const e of a)console.log(c+chalk.bold.yellow(s(to()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(to()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(l.passed?chalk.gray(to()?" 再战刷成绩 · ":" race it again · "):chalk.gray(to()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(to()?" 继续学习":" keep going"):chalk.gray(to()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(to()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},vo=()=>{we.endsWith("DEMO01")?console.log(chalk.yellow(to()?" 🐼 AI 熊猫导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" 🐼 The AI Panda Tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(to()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(to()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Co=async(e,o)=>{if(Ce){Fe=!0;try{console.log(),console.log(chalk.gray("deep"===o?to()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":to()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await I({token:we,cardNumber:Te.currentCard,question:e,mode:o,history:Ve().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(to()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Ve().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(` (${to()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(to()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Re&&console.log(chalk.gray(to()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Fe=!1}}else vo()},Ao=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],To=async()=>{ze&&uo?Mo?Lo(Mo):So():He?await _o():$o()},_o=async()=>{Fe=!0;try{console.log();const e=await S({token:we,curriculumId:$e.id,cardNumber:Te.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(to()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(to()?` 🏆 本卡实时 Top-3 — 第 ${Te.currentCard} 张`:` 🏆 Live top-3 — card ${Te.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(to()?" (你)":" (you)"):""))}else console.log(chalk.gray(to()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(no.set(Te.currentCard,e.mine.rank),console.log(chalk.white(to()?" 你: ":" You: ")+chalk.bold.yellow(to()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(to()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Ce&&console.log(chalk.gray(to()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),he({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(to()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(to()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(to()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),He="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(to()?" 返回卡片":" returns to the card")),console.log()}finally{Fe=!1}},Io=e=>to()&&e.title_zh||e.title,xo=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of pe(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Eo=e=>uo.data.solved.includes(e.id)?"✅":uo.data.carried?.includes(e.id)?"✅↗":uo.tried.has(e.id)?"❌":"⬜",So=()=>{const e=uo.data,o=R(e.deadline),t=(e.carried??[]).filter(o=>!e.solved.includes(o)),n=e.solved.length+t.length,r=Math.min(20,Math.round(n/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(to()?` · 第 ${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(to()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${n}/${e.need} AC`)+chalk.gray(to()?`(共 ${e.n} 题)`:` (of ${e.n})`)),t.length>0&&console.log(chalk.cyan(` ✅↗ ${t.length}`)+chalk.gray(to()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo"));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(to()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(to()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(to()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(to()?` 满血重开本组(${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)} `)+Eo(e)+chalk.white(` ${Io(e)}`))}),console.log(),Po()},Po=()=>{console.log(chalk.gray(to()?" /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(to()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(to()?" 返回课程":" returns to the lesson")),console.log()},qo=e=>{const o=parseInt(e,10),t=uo.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(to()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}};let Mo=null;const Lo=e=>{const o=qo(e);if(!o)return;const{p:t,n:n}=o;Mo=String(n),console.log(),console.log(chalk.bold.white(` ${Eo(t)} ${Io(t)}`)),console.log();for(const e of(e=>to()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of pe(e,me()+2))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(to()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(to()?" 应输出:":" 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(to()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(to()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(to()?"写码(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(to()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(to()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(to()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((to()," ↩ "))+chalk.bold.green("back")+chalk.gray(to()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(to()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((to()," / "))+chalk.bold.green("wide")+chalk.gray(to()?" 换语言/宽度":" language / width")),console.log()},Wo=async(e,o)=>await new Promise(t=>{const n=process.stdin,l=!!n.isTTY&&!!n.isRaw;if(Se.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:uo.dir}),a=e=>{if(n.isTTY&&"function"==typeof n.setRawMode&&l)try{n.setRawMode(!0)}catch{}Se.resume(),t(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Ro=()=>{console.log(chalk.yellow(to()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(to()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(to()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(to()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Oo=new Map,No=async e=>{const o=e.trim().toLowerCase(),s=ze&&o.startsWith("/")?o.slice(1):o;if(Fe)return;if(null!==Oe){if(Ne.push(e.replace(/\s+$/,"")),De&&clearTimeout(De),De=null,je){const e=Ne[Ne.length-1]??"";return"/cancel"===e.trim()?(Ye(),console.log(chalk.gray(to()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Me()):""!==e.trim()?void Me():(Ne.pop(),void await a())}return void(De=setTimeout(()=>{if(De=null,Ne.length>1){je=!0;const e=Ne.length;return console.log(chalk.cyan(to()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(to()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Me()}a()},140))}async function a(){const e=Ne.join("\n").replace(/^\s+|\s+$/g,""),o=Oe??Te.currentCard,t=Ne.length;if(Ye(),""===e)console.log(chalk.gray(to()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(to()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(to()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(to()?" 即可执行。":" again to run it."));else{const n=oo>0?Date.now()-oo:void 0;if(await v(we,{curriculum_id:$e.id,card_number:o,feedback_text:e,time_on_card_ms:n})){const e=t>1?to()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(to()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(to()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Me()}if(Be){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Be=!1,console.log(),console.log(chalk.yellow(to()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(to()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(to()?" 即可执行该命令。":" again to run it.")),console.log(),void Me();if(!o)return Be=!1,console.log(chalk.gray(to()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Me();const t=await _({token:we,nickname:o});if(t.ok)Be=!1,console.log(chalk.bold.green(to()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(to()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Ze+=1;const e="taken"===t.code?to()?"已被占用":"already taken":"bad_charset"===t.code?to()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?to()?"未通过审核":"did not pass review":t.message||"error";if(!(Ze>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(to()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Me();Be=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(to()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Me()}if(Xe){Xe=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Fe=!0;try{console.log(),console.log(chalk.gray(to()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await x({token:we,cardNumber:Te.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(to()?"评审暂不可用。":"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(to()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(to()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(to()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(to()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(to()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(to()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=to()?` 本卡排名 #${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(to()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(to()?` 第 ${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 Ao(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(to()?" 改进提问: ":" 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(` (${to()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Ge.add(Te.currentCard):Ge.delete(Te.currentCard),"number"==typeof e.rank&&no.set(Te.currentCard,e.rank);const o=await S({token:we,curriculumId:$e.id,cardNumber:Te.currentCard});o.ok&&o.totals&&o.chapters&&(he({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!ke&&(Be=!0,Ze=0,console.log(chalk.bold.yellow(to()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(to()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(to()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Fe=!1}})():(console.log(chalk.gray(to()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Re&&(console.log(chalk.gray(to()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Me()}if(eo)return eo=!1,$o(),void Me();if(!o)return void Me();if(Ke)return"exit"===await i(e.trim())&&(Ke=!1),void Me();if(Ue){if(["q","quit","exit","back","b","menu"].includes(o))return Ue=!1,console.log(chalk.gray(to()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Me();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await Co(n,t?"fast":"deep"),console.log(chalk.gray(to()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Me()}if(ze&&uo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${uo.phase}s${uo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return ze=!1,console.log(chalk.gray(to()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),$o(),void Me();if(/^\d+$/.test(o))return Lo(o),void Me();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,n]=e;return"list"===o?So():n?"read"===o||"open"===o?Lo(n):"edit"===o?await(async e=>{const o=qo(e);if(!o)return;const t=f(uo.dir,`sol-${o.n}.py`);return j()?D()?(console.log(chalk.yellow(to()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(to()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(to()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(to()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(to()?" ← 不能是 /mnt/c":" not /mnt/c")),console.log(chalk.bold.cyan(" sudo npm install -g icoa-cli")),console.log(chalk.bold.cyan(" hash -r")+chalk.gray(to()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(to()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(to()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(to()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(to()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(to()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(to()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(to()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log()):Y("vi")?(console.log(chalk.gray(to()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await Wo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(to()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(to()?" 自测样例。":" to self-check the sample.")),void console.log()):(console.log(chalk.yellow(to()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(to()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim")))})(n):"run"===o?(e=>{const o=qo(e);if(!o)return;const{p:n,n:r}=o,l=f(uo.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(to()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const s=(n.samples??[])[0];if(!s)return void console.log(chalk.gray(to()?` 本题无样例(设计如此)— 用 /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",[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if("ENOENT"===o.code)Ro();else if(o.killed)console.log(chalk.yellow(to()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(to()?" ✗ 程序报错:":" ✗ 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=s.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(to()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(to()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(to()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(to()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(to()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(to()?" 改完再 /run。":" then /run again.")),console.log()})(n):"debug"===o?await(async e=>{const o=qo(e);if(!o)return;const t=f(uo.dir,`sol-${o.n}.py`);if(!d(t))return void console.log(chalk.yellow(to()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(to()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const n=await Wo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==n?.code?(console.log(chalk.gray(to()?" 回到竞技场。":" Back in the arena.")),console.log()):Ro()})(n):"recall"===o&&await(async e=>{const o=qo(e);if(!o)return;if(!Ce)return void vo();const{p:t,n:n}=o,r=f(process.cwd(),"icoa-contest"),l=`${$e.id}-phase${uo.phase}-g${uo.data.slot}-archived-`;let s=null;try{for(const e of u(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?f(r,s,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(to()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${uo.phase}-${uo.data.slot}-${n}`,g=Math.min(3,(Oo.get(c)??0)+1);console.log(chalk.gray(to()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await T({token:we,phase:uo.phase,slot:uo.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:to()?"zh":"en"});if(m.ok){Oo.set(c,g),console.log();for(const e of pe(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(to()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(to()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(to()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(n):console.log(chalk.yellow(to()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(to()?" (花名册: /list)":" (roster: /list)")),void Me()}if("contest"===o||"/contest"===o)return So(),void Me();const n="lang"===o||/^lang\s+\S+$/.test(o),r=/^(wide|wide on|wide off|normal|narrow)$/.test(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||n||r||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(to()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Me()}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(to()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Me()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(Se.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Se.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Me()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Ke=!0),void Me();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Ce)return vo(),void Me();Je||(Je=!0,console.log(),console.log(chalk.bold.cyan(to()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(to()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(to()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),to()||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){Ue=!0;const e=co(Te.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(to()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(to()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(to()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Me()}return await Co(n,t?"fast":"deep"),void Me()}if(!ze&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Ce)return vo(),void Me();const e=co(Te.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(to()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(to()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(to()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(to()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(to()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(to()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(to()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Xe=!0,void Me()}const w=!ze&&"honors"===He&&/^[1-3]$/.test(o);if(!ze&&He&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(to()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(to()?" ↩ back 回上一层":" ↩ back goes up one level")),void Me();if(!ze&&(w||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Ce)return vo(),void Me();const e=/^\/?view ([1-3])$/.exec(o),t=w?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Fe=!0;try{console.log();const o=await E({token:we,cardNumber:Te.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(to()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Ge.delete(Te.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Ge.add(Te.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(to()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${Te.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${Te.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(to()?` (第 ${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(to()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Ao(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(to()?" (无可显示的提问)":" (no questions to show)"))}console.log(),He="view",console.log(chalk.gray((to()," "))+chalk.bold.cyan("↩ back")+chalk.gray(to()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Fe=!1}})(t),void Me()}if("/honors"===o||"honors"===o)return ke?(console.log(),console.log(chalk.gray(to()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Me()):(await _o(),void Me());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return ae($e,Te),void Me();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(O().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Me();const t=$e.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,l=r?n:"en";return N({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Re=null,Le=null,We=null,Ye(),eo=!1,Xe=!1,await To(),void Me()}if(["wide","wide on","normal","narrow","wide off"].includes(o)){const e="wide"===o||"wide on"===o;return e===!!O().learnWide?(console.log(chalk.gray(e?to()?me()<=64?` 宽屏已开,但终端只有 ${process.stdout.columns||64} 列 — 画面已是最大可用宽度。输 normal 关闭。`:` 已是宽屏(${me()} 列)。输 normal 恢复 64 列。`:me()<=64?` Wide is on, but your terminal is only ${process.stdout.columns||64} cols — already at max usable width. Type normal to switch it off.`:` Already wide (${me()} cols). Type normal to restore 64.`:to()?" 已是标准 64 列。输 wide 拉伸到终端宽度。":" Already at the standard 64 cols. Type wide to stretch.")),void Me()):(N({learnWide:e}),ye(e),e&&me()<=64?(console.log(chalk.yellow(to()?` 终端只有 ${process.stdout.columns||64} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${process.stdout.columns||64} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray(to()?" 拉宽窗口后会自动生效;输 normal 关闭宽屏。":" Widen the window and it takes effect automatically; type normal to switch it off.")),void Me()):(console.log(chalk.green(" ✓ ")+chalk.gray(e?to()?`宽屏开 — 卡片拉伸到终端宽度(现在 ${me()} 列,上限 96)。输 normal 恢复。`:`Wide mode ON — cards stretch to your terminal (now ${me()} cols, max 96). Type normal to restore.`:to()?"已恢复 64 列标准宽。输 wide 再拉伸。":"Back to the 64-col standard width. Type wide to stretch again.")),Re=null,Le=null,We=null,Ye(),eo=!1,Xe=!1,await To(),void Me()))}if("sim"===o){const e=co(Te.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 Me()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Me())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=Te.currentCard,t=Te.bookmarks.includes(e),n="bookmark"!==o;return n?Te.bookmarks=Te.bookmarks.filter(o=>o!==e):t||Te.bookmarks.push(e),F(Te),n?console.log(t?chalk.gray(to()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(to()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(to()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(to()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Me()}if("e"===o)return Oe=Te.currentCard,console.log(chalk.gray(to()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void Me();if("back"===o||"b"===o)return"view"===He?(await _o(),void Me()):"honors"===He?(He=null,$o(),void Me()):(Te.currentCard>1&&(Te.currentCard-=1),Le=null,We=null,Re=null,F(Te),$o(),void Me());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!yo)return console.log(chalk.yellow(to()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Me();if(!e)return console.log(),console.log(chalk.bold.white(to()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(to()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(chalk.gray(to()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(to()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9")),console.log(chalk.gray(to()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Me();const t=await L(we,e);if(!t.ok||!t.data)return console.log(chalk.red(` ✗ ${t.message||(to()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(to()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Me();console.log(),console.log(chalk.bold.green(to()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 Linked — credit now carries both ways"));for(const e of t.data.members)console.log(chalk.gray(" · ")+chalk.white(e.curriculum_id)+chalk.gray(` ${e.token}`));return console.log(chalk.gray(to()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log(),await mo(),void Me()}if("contest"===o||"/contest"===o||"arena"===o||"contest start"===o||"/contest start"===o||"contest status"===o||"contest reset"===o||/^\/?contest [1-9]$/.test(o)){if(!yo)return console.log(chalk.yellow(to()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Me();const e=ho(Te.currentCard);if("contest reset"===o){const o=await P(we,e);if(o.ok){console.log(chalk.yellow(to()?` 已放弃当前计时(阶段 ${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",`${$e.id}-phase${e}-g${t}`);if(d(n))try{m(n,`${n}-archived-${o}`),console.log(chalk.gray(to()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(to()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(to()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),uo=null,ze=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Me()}const t=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(to()?" 连接判分赛…":" Contacting contest server…"));const n=await q(we,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(to()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void Me();const r=n.data,l=f(process.cwd(),"icoa-contest",`${$e.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=uo&&uo.phase===e&&uo.data.slot===r.slot?uo.tried:new Set;uo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,l=(t.samples??[])[0];l&&h(f(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=f(o,`sol-${r}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...xo(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.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(s,a.join("\n"))})})(r,l),ze=!0,So(),console.log(chalk.gray(to()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(to()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(to()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Me()}if("submit"===s)return console.log(chalk.yellow(to()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(to()?" 例如 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)")),uo||console.log(chalk.gray(to()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Me();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!uo)return console.log(chalk.yellow(to()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Me();const n=uo.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(to()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Me();const l=n.findIndex(e=>e.id===o)+1,a=t||f(uo.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(to()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Me()}console.log(chalk.gray(to()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await M(we,uo.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(to()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((to()," "))+chalk.bold.green("contest")+chalk.gray(to()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(to()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void Me();const d=c.data;if(d.already_ac)console.log(chalk.green(to()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(to()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(to()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),uo.data.solved.includes(o)||uo.data.solved.push(o),uo.tried.delete(o);else{uo.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?to()?` · 挂在第 ${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(to()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=R(d.deadline||"");if(console.log(chalk.white(to()?` 本组进度: 已过 ${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(to()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await mo();else if(!d.late){const e=n.findIndex(e=>!uo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(to()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Io(n[e])}`))}return void Me()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>$e.totalCards)return console.log(chalk.yellow(` Card number must be 1..${$e.totalCards}. Try: `)+chalk.bold.green("card 1")),void Me();const n=await fo(t);return n?(console.log(n),void Me()):(Te.currentCard=t,Le=null,We=null,Re=null,F(Te),$o(),void Me())}if(null!==Re&&["y","yes","n","no"].includes(o)){const e=co(Re);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-oo;B(Te,e.number),J(Te,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),F(Te);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),ro.push(k(we,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Re=null,e.solution&&e.solution.length>0)return void Me();if(Te.currentCard<$e.totalCards){const e=Te.currentCard,o=await fo(e+1);if(o)return await bo(e),console.log(o),void Me();Te.currentCard+=1,F(Te),await bo(e)?wo():$o(),Me()}else ce($e,Te),Me();return}}if(null!==Le&&["a","b","c","d"].includes(o)){const e=co(Le);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(Z(Te,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),B(Te,e.number),F(Te),ee(e,t,n,Te),ro.push(k(we,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Le=null,n)if(Te.currentCard<$e.totalCards){const e=await fo(Te.currentCard+1);if(e)return console.log(e),void Me();Te.currentCard+=1,F(Te),$o()}else ce($e,Te),Me();else Me();return}}if(null!==We){if("done"===o){const e=co(We);if(e&&"practical"===e.type)return K(Te,e.number),B(Te,e.number),F(Te),te(e),We=null,void Me()}if("skip"===o)return B(Te,We),F(Te),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),We=null,void Me()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==Le)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Me();if(null!==We)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Me();if(null!==Re)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Me();const e=Te.currentCard,o=e<$e.totalCards?await fo(e+1):null;return o?(await bo(e),console.log(o),void Me()):(Te.currentCard+=1,F(Te),Te.currentCard>$e.totalCards?ce($e,Te):await bo(e)?wo():$o(),void Me())}if(null!==Re)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Me();if(null!==Le)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Me();if(null!==We)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Me();"view"===He?console.log(chalk.gray(to()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(to()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(to()?" 回卡片":" to the card")):"honors"===He?console.log(chalk.gray(to()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(to()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(to()?" 回卡片":" to the card")):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")),Me()}else{if("view"===He)return await _o(),void Me();if("honors"===He)return He=null,$o(),void Me();if(ro.length>0&&await Promise.race([Promise.allSettled(ro),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Te.streakDays} day(s)`)),console.log(),xe){Se.removeAllListeners("line"),qe();for(const e of Ee)Se.on("line",e);Se.prompt(),ao()}else Se.removeAllListeners("line"),Se.close()}else if(ro.length>0&&await Promise.race([Promise.allSettled(ro),new Promise(e=>setTimeout(e,3e3))]),Se.removeAllListeners("line"),qe(),xe||!io){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(xe?Se:void 0),ao()}else Se.close()};Se.on("line",e=>{No(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.")),Me()})}),xe||Se.on("close",async()=>{ro.length>0&&await Promise.race([Promise.allSettled(ro),new Promise(e=>setTimeout(e,5e3))]),io?ao():process.exit(0)});try{$o(),Me();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(fe("Could not render this card — the curriculum may be malformed."),xe){Se.removeAllListeners("line"),qe();for(const e of Ee)Se.on("line",e);Se.prompt()}else Se.close();ao()}await so}),be.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(),l=await w(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.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 l}from"../lib/logger.js";import{getMainRl as s}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 y,renameSync as m,statSync as h,writeFileSync as p}from"node:fs";import{emptyDynamics as f,foldEditSession as b,isEmpty as w,noteRun as $}from"../lib/arena-edit-dynamics.js";import{dirname as k,join as v}from"node:path";import{fileURLToPath as C}from"node:url";import{loadCurriculumById as A,validateEAToken as T,syncProgress as _,syncCardFeedback as I}from"../lib/learn-curricula.js";import{normalizeTokenBody as x}from"../lib/token-format.js";import{fetchMyScores as E,recallCoach as S,setNickname as P,streamLearnTutor as M,submitPqs as q,viewPqsTop as L,viewHonors as W}from"../lib/learn-ai.js";import{contestReset as R,contestStart as N,contestSubmit as O,linkToken as j,fetchGate as D,timeLeft as Y}from"../lib/learn-contest.js";import{getConfig as U,saveConfig as F}from"../lib/config.js";import{isNativeWindows as z,isWindowsBuildInWslShell as H,whichBinary as B}from"../lib/platform.js";import{loadLearnState as Z,saveLearnState as J,newLearnState as K,updateStreak as Q,markCardComplete as V,recordMCQ as X,recordCheck as G,markPracticalComplete as ee,addAchievement as oe}from"../lib/learn-state.js";import{renderWelcome as te,renderKnowledgeCard as ne,renderMCQCard as re,renderMCQFeedback as le,renderPracticalCard as se,renderPracticalSuccess as ae,renderSimDemoCard as ie,renderMilestone as ce,renderArenaTaskCard as de,renderComingSoonCard as ge,renderStatus as ue,renderPhaseComplete as ye,renderCurriculumComplete as me,setLearnAiEnabled as he,setLearnHonorRanks as pe,setLearnPqsViewCards as fe,setLearnWide as be,learnW as we,renderHonorWall as $e,wrapMixed as ke}from"../lib/learn-render.js";import{printError as ve}from"../lib/ui.js";export function registerLearnCommand(Ce){Ce.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async Ce=>{Ce?.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(),Ce="LEARNDEMO01");let Ae=Ce.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ae)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Te=null;const _e=/^[A-Z0-9]+DEMO01$/i.test(Ae),Ie=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ae);let xe=!1,Ee=!1;if(_e)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Te=await A(Ae,Ae);else if(Ie){console.log(),console.log(chalk.gray(" Validating token..."));let e=await T(Ae);if(!e.ok){const o=x(Ae);if(o!==Ae){const t=await T(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ae} → ${o}`)),e=t,Ae=o)}}if(!e.ok)return ve(`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 Panda Tutor 🐼"):"")),xe=!0===e.aiEnabled,Ee=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Te=await A(e.curriculumId||"LEARNDEMO01",Ae),!Te)return ve(`Could not open a learn curriculum for token '${Ae}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ae}`)+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 ${Ae}`)+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(!Te){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(ve(`Could not reach the learn server to open ${Ae}.`),console.log(),console.log(chalk.gray(" Your token may be perfectly fine — we could not ask.")),console.log(chalk.gray(" Check your connection, then run ")+chalk.bold.yellow(`learn ${Ae}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(ve(`Unknown learn token: ${Ae}`),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(" Most tracks have a free demo. From the ")+chalk.bold.green("learn")+chalk.gray(" menu you can type the track name itself")),console.log(chalk.gray(" (e.g. ")+chalk.bold.green("biology")+chalk.gray(", ")+chalk.bold.green("ioipy")+chalk.gray(") and it opens that track's demo if one is published.")),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 Se=Z(),Pe=!1;try{Se&&Se.token===Ae?Q(Se):(Se=K(Ae,Te.id,Te.totalCards),Pe=!0),J(Se),te(Te,Se,Pe)}catch{return ve("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 ${Ae}`)+chalk.gray(".")),void console.log()}const Me=s(),qe=null!==Me,Le=qe?Me.listeners("line").slice():[];qe&&Me.removeAllListeners("line");const We=qe?Me:o({input:process.stdin,output:process.stdout,terminal:!0}),Re=qe?We.prompt:null;qe&&(We.prompt=e.prototype.prompt);const Ne=()=>{qe&&Re&&(We.prompt=Re)},Oe=()=>{We.setPrompt(eo?chalk.bold.green(`icoa ${a()}> `):Ke?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Ze?"icoa learn ai> ":"icoa learn> ")),We.prompt()};let je=null,De=null,Ye=null,Ue=null,Fe=[],ze=!1,He=null;const Be=()=>{He&&clearTimeout(He),He=null,Fe=[],ze=!1,Ue=null};let Ze=!1,Je=!1,Ke=!1,Qe=null,Ve=!1,Xe=0,Ge=!1,eo=!1;const oo=new Map,to=()=>{let e=oo.get(Se.currentCard);return e||(e=[],oo.set(Se.currentCard,e)),e};let no=!1;const ro=new Set;let lo=!1,so=0;const ao=()=>(U().language||"en").toLowerCase().startsWith("zh");he(xe),be(!!U().learnWide),fe(ro);const io=new Map;pe(io);const co=[];let go=null;const uo=new Promise(e=>{go=e}),yo=()=>{const e=go;go=null,e?.()},mo="1"===process.env.ICOA_LEARN_EMBEDDED,ho=e=>Te.cards.find(o=>o.number===e);let po=null,fo=null;const bo=new Map,wo=!Ae.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ae),$o=async()=>{if(!wo)return;const e=await D(Ae);e.ok&&e.data&&(po=e.data)},ko=e=>{const o=Te.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},vo=e=>{if(!Ee||!po)return null;const o=ko(e);if(o<=po.unlocked_through_phase)return null;const t=po.phases.find(e=>e.phase===po.unlocked_through_phase),n=[chalk.yellow(ao()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${po.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${po.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(ao()?` ⚔ 练习赛 ${po.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${po.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(ao()?` ⚖ 判分赛: 最好 ${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"))}if(t?.checks?.enabled&&!t.checks.passed){const e=t.checks.missing??[],o=e.slice(0,8).join(ao()?"、":", "),r=e.length>8?ao()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:ao()?" 张":"";n.push(chalk.gray(ao()?` ✓ 逐卡自测: ${t.checks.good}/${t.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${t.checks.good}/${t.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return t?.research&&!t.research.passed&&n.push(chalk.gray(ao()?` ⭐ 提问研究: ${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")},Co=async e=>Ee?null===vo(e)?null:(await $o(),vo(e)):null;wo&&await $o();const Ao=async e=>{const o=Te.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=Te.modules.find(e=>e.number===o.number+1);let n;if(xe){const e=await E({token:Ae,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}wo&&await $o();const r=po?.phases.find(e=>e.phase===o.number);return ye(Te,Se,o,t,n,r),!0},To=()=>{lo=!0,console.log(chalk.gray(ao()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},_o=()=>{Qe=null;const e=ho(Se.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":ne(e,Te),e.check?(Ye=e.number,so=Date.now()):(V(Se,e.number),J(Se));break;case"mcq":re(e,Te),je=e.number;break;case"practical":se(e,Te),De=e.number;break;case"sim_demo":ie(e,Te),V(Se,e.number),J(Se);break;case"milestone":ce(e,Te),oe(Se,e.badge),V(Se,e.number),J(Se);break;case"arena_task":de(e,Te),V(Se,e.number),J(Se);break;case"coming_soon":ge(e,Te),V(Se,e.number),J(Se)}Io(e.number)},Io=e=>{if(!wo||!po)return;const o=Te.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=po.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===n);if(!l)return;const s=(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),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const t=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${t(o.getMonth()+1)}-${t(o.getDate())} ${t(o.getHours())}:${t(o.getMinutes())}`})(n);return`🏆 ${e} ${o}/${l.n}`+(r?ao()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(we());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${ao()?`练习赛 ${o.number}-${n}`:l.title||`PY Arena ${o.number}-${n}`}`)+(l.passed?chalk.bold.green(ao()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(ao()?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(ao()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(ao()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))),a.length>0)for(const e of a)console.log(c+chalk.bold.yellow(s(ao()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(ao()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(l.passed?chalk.gray(ao()?" 再战刷成绩 · ":" race it again · "):chalk.gray(ao()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(ao()?" 继续学习":" keep going"):chalk.gray(ao()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(ao()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},xo=()=>{Ae.endsWith("DEMO01")?console.log(chalk.yellow(ao()?" 🐼 AI 熊猫导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" 🐼 The AI Panda Tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(ao()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(ao()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Eo=async(e,o)=>{if(xe){Je=!0;try{console.log(),console.log(chalk.gray("deep"===o?ao()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":ao()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await M({token:Ae,cardNumber:Se.currentCard,question:e,mode:o,history:to().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(ao()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(to().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(` (${ao()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(ao()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Ye&&console.log(chalk.gray(ao()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Je=!1}}else xo()},So=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Po=async()=>{Ke&&fo?jo?Do(jo):Ro():Qe?await Mo():_o()},Mo=async()=>{Je=!0;try{console.log();const e=await W({token:Ae,curriculumId:Te.id,cardNumber:Se.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(ao()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(ao()?` 🏆 本卡实时 Top-3 — 第 ${Se.currentCard} 张`:` 🏆 Live top-3 — card ${Se.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(ao()?" (你)":" (you)"):""))}else console.log(chalk.gray(ao()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(io.set(Se.currentCard,e.mine.rank),console.log(chalk.white(ao()?" 你: ":" You: ")+chalk.bold.yellow(ao()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(ao()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):xe&&console.log(chalk.gray(ao()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),$e({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(ao()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(ao()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(ao()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Qe="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(ao()?" 返回卡片":" returns to the card")),console.log()}finally{Je=!1}},qo=e=>ao()&&e.title_zh||e.title,Lo=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of ke(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Wo=e=>fo.data.solved.includes(e.id)?"✅":fo.data.carried?.includes(e.id)?"✅↗":fo.tried.has(e.id)?"❌":"⬜",Ro=()=>{const e=fo.data,o=Y(e.deadline),t=(e.carried??[]).filter(o=>!e.solved.includes(o)),n=e.solved.length+t.length,r=Math.min(20,Math.round(n/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(ao()?` · 第 ${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(ao()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${n}/${e.need} AC`)+chalk.gray(ao()?`(共 ${e.n} 题)`:` (of ${e.n})`)),t.length>0&&console.log(chalk.cyan(` ✅↗ ${t.length}`)+chalk.gray(ao()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo"));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(ao()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(ao()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(ao()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(ao()?` 满血重开本组(${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)} `)+Wo(e)+chalk.white(` ${qo(e)}`))}),console.log(),No()},No=()=>{console.log(chalk.gray(ao()?" /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(ao()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(ao()?" 返回课程":" returns to the lesson")),console.log()},Oo=e=>{const o=parseInt(e,10),t=fo.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(ao()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}};let jo=null;const Do=e=>{const o=Oo(e);if(!o)return;const{p:t,n:n}=o;jo=String(n),console.log(),console.log(chalk.bold.white(` ${Wo(t)} ${qo(t)}`)),console.log();for(const e of(e=>ao()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of ke(e,we()+2))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(ao()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(ao()?" 应输出:":" 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(ao()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(ao()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(ao()?"写码(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(ao()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(ao()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(ao()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((ao()," ↩ "))+chalk.bold.green("back")+chalk.gray(ao()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(ao()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((ao()," / "))+chalk.bold.green("wide")+chalk.gray(ao()?" 换语言/宽度":" language / width")),console.log()},Yo=async(e,o)=>await new Promise(t=>{const n=process.stdin,l=!!n.isTTY&&!!n.isRaw;if(We.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:fo.dir}),a=e=>{if(n.isTTY&&"function"==typeof n.setRawMode&&l)try{n.setRawMode(!0)}catch{}We.resume(),t(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Uo=()=>{console.log(chalk.yellow(ao()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(ao()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(ao()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(ao()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Fo=new Map,zo=async e=>{const o=e.trim().toLowerCase(),s=Ke&&o.startsWith("/")?o.slice(1):o;if(Je)return;if(null!==Ue){if(Fe.push(e.replace(/\s+$/,"")),He&&clearTimeout(He),He=null,ze){const e=Fe[Fe.length-1]??"";return"/cancel"===e.trim()?(Be(),console.log(chalk.gray(ao()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Oe()):""!==e.trim()?void Oe():(Fe.pop(),void await a())}return void(He=setTimeout(()=>{if(He=null,Fe.length>1){ze=!0;const e=Fe.length;return console.log(chalk.cyan(ao()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(ao()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Oe()}a()},140))}async function a(){const e=Fe.join("\n").replace(/^\s+|\s+$/g,""),o=Ue??Se.currentCard,t=Fe.length;if(Be(),""===e)console.log(chalk.gray(ao()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(ao()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(ao()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(ao()?" 即可执行。":" again to run it."));else{const n=so>0?Date.now()-so:void 0;if(await I(Ae,{curriculum_id:Te.id,card_number:o,feedback_text:e,time_on_card_ms:n})){const e=t>1?ao()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(ao()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(ao()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Oe()}if(Ve){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Ve=!1,console.log(),console.log(chalk.yellow(ao()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(ao()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(ao()?" 即可执行该命令。":" again to run it.")),console.log(),void Oe();if(!o)return Ve=!1,console.log(chalk.gray(ao()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Oe();const t=await P({token:Ae,nickname:o});if(t.ok)Ve=!1,console.log(chalk.bold.green(ao()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(ao()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Xe+=1;const e="taken"===t.code?ao()?"已被占用":"already taken":"bad_charset"===t.code?ao()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?ao()?"未通过审核":"did not pass review":t.message||"error";if(!(Xe>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(ao()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Oe();Ve=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(ao()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Oe()}if(no){no=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Je=!0;try{console.log(),console.log(chalk.gray(ao()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await q({token:Ae,cardNumber:Se.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(ao()?"评审暂不可用。":"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(ao()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(ao()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(ao()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(ao()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(ao()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(ao()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=ao()?` 本卡排名 #${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(ao()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(ao()?` 第 ${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 So(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(ao()?" 改进提问: ":" 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(` (${ao()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?ro.add(Se.currentCard):ro.delete(Se.currentCard),"number"==typeof e.rank&&io.set(Se.currentCard,e.rank);const o=await W({token:Ae,curriculumId:Te.id,cardNumber:Se.currentCard});o.ok&&o.totals&&o.chapters&&($e({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!_e&&(Ve=!0,Xe=0,console.log(chalk.bold.yellow(ao()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(ao()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(ao()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Je=!1}})():(console.log(chalk.gray(ao()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Ye&&(console.log(chalk.gray(ao()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Oe()}if(lo)return lo=!1,_o(),void Oe();if(!o)return void Oe();if(eo)return"exit"===await i(e.trim())&&(eo=!1),void Oe();if(Ze){if(["q","quit","exit","back","b","menu"].includes(o))return Ze=!1,console.log(chalk.gray(ao()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Oe();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await Eo(n,t?"fast":"deep"),console.log(chalk.gray(ao()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Oe()}if(Ke&&fo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${fo.phase}s${fo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Ke=!1,console.log(chalk.gray(ao()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),_o(),void Oe();if(/^\d+$/.test(o))return Do(o),void Oe();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,n]=e;return"list"===o?Ro():n?"read"===o||"open"===o?Do(n):"edit"===o?await(async e=>{const o=Oo(e);if(!o)return;const t=v(fo.dir,`sol-${o.n}.py`);if(z())return H()?(console.log(chalk.yellow(ao()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(ao()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(ao()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(ao()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(ao()?" ← 不能是 /mnt/c":" not /mnt/c")),console.log(chalk.bold.cyan(" sudo npm install -g icoa-cli")),console.log(chalk.bold.cyan(" hash -r")+chalk.gray(ao()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(ao()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(ao()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(ao()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(ao()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(ao()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(ao()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(ao()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!B("vi"))return console.log(chalk.yellow(ao()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(ao()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(ao()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const n=e=>{try{return h(e).size}catch{return 0}},r=n(t),l=Date.now();await Yo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),bo.set(o.n,b(bo.get(o.n)??f(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:n(t)})),console.log(chalk.gray(ao()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(ao()?" 自测样例。":" to self-check the sample.")),console.log()})(n):"run"===o?(e=>{const o=Oo(e);if(!o)return;const{p:n,n:r}=o,l=v(fo.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(ao()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));bo.set(r,$(bo.get(r)??f()));const s=(n.samples??[])[0];if(!s)return void console.log(chalk.gray(ao()?` 本题无样例(设计如此)— 用 /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",[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if("ENOENT"===o.code)Uo();else if(o.killed)console.log(chalk.yellow(ao()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(ao()?" ✗ 程序报错:":" ✗ 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=s.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(ao()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(ao()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(ao()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(ao()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(ao()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(ao()?" 改完再 /run。":" then /run again.")),console.log()})(n):"debug"===o?await(async e=>{const o=Oo(e);if(!o)return;const t=v(fo.dir,`sol-${o.n}.py`);if(!d(t))return void console.log(chalk.yellow(ao()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(ao()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const n=await Yo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==n?.code?(console.log(chalk.gray(ao()?" 回到竞技场。":" Back in the arena.")),console.log()):Uo()})(n):"recall"===o&&await(async e=>{const o=Oo(e);if(!o)return;if(!xe)return void xo();const{p:t,n:n}=o,r=v(process.cwd(),"icoa-contest"),l=`${Te.id}-phase${fo.phase}-g${fo.data.slot}-archived-`;let s=null;try{for(const e of u(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?v(r,s,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(ao()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${fo.phase}-${fo.data.slot}-${n}`,g=Math.min(3,(Fo.get(c)??0)+1);console.log(chalk.gray(ao()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await S({token:Ae,phase:fo.phase,slot:fo.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:ao()?"zh":"en"});if(m.ok){Fo.set(c,g),console.log();for(const e of ke(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(ao()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(ao()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(ao()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(n):console.log(chalk.yellow(ao()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(ao()?" (花名册: /list)":" (roster: /list)")),void Oe()}if("contest"===o||"/contest"===o)return Ro(),void Oe();const n="lang"===o||/^lang\s+\S+$/.test(o),r=/^(wide|wide on|wide off|normal|narrow)$/.test(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||n||r||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(ao()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Oe()}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(ao()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Oe()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(We.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}We.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Oe()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(eo=!0),void Oe();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!xe)return xo(),void Oe();Ge||(Ge=!0,console.log(),console.log(chalk.bold.cyan(ao()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(ao()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(ao()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),ao()||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){Ze=!0;const e=ho(Se.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(ao()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(ao()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(ao()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Oe()}return await Eo(n,t?"fast":"deep"),void Oe()}if(!Ke&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!xe)return xo(),void Oe();const e=ho(Se.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(ao()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(ao()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(ao()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(ao()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(ao()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(ao()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(ao()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),no=!0,void Oe()}const A=!Ke&&"honors"===Qe&&/^[1-3]$/.test(o);if(!Ke&&Qe&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(ao()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(ao()?" ↩ back 回上一层":" ↩ back goes up one level")),void Oe();if(!Ke&&(A||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!xe)return xo(),void Oe();const e=/^\/?view ([1-3])$/.exec(o),t=A?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Je=!0;try{console.log();const o=await L({token:Ae,cardNumber:Se.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(ao()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&ro.delete(Se.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&ro.add(Se.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(ao()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${Se.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${Se.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(ao()?` (第 ${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(ao()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=So(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(ao()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Qe="view",console.log(chalk.gray((ao()," "))+chalk.bold.cyan("↩ back")+chalk.gray(ao()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Je=!1}})(t),void Oe()}if("/honors"===o||"honors"===o)return _e?(console.log(),console.log(chalk.gray(ao()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Oe()):(await Mo(),void Oe());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return ue(Te,Se),void Oe();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(U().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Oe();const t=Te.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,l=r?n:"en";return F({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Ye=null,je=null,De=null,Be(),lo=!1,no=!1,await Po(),void Oe()}if(["wide","wide on","normal","narrow","wide off"].includes(o)){const e="wide"===o||"wide on"===o;return e===!!U().learnWide?(console.log(chalk.gray(e?ao()?we()<=64?` 宽屏已开,但终端只有 ${process.stdout.columns||64} 列 — 画面已是最大可用宽度。输 normal 关闭。`:` 已是宽屏(${we()} 列)。输 normal 恢复 64 列。`:we()<=64?` Wide is on, but your terminal is only ${process.stdout.columns||64} cols — already at max usable width. Type normal to switch it off.`:` Already wide (${we()} cols). Type normal to restore 64.`:ao()?" 已是标准 64 列。输 wide 拉伸到终端宽度。":" Already at the standard 64 cols. Type wide to stretch.")),void Oe()):(F({learnWide:e}),be(e),e&&we()<=64?(console.log(chalk.yellow(ao()?` 终端只有 ${process.stdout.columns||64} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${process.stdout.columns||64} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray(ao()?" 拉宽窗口后会自动生效;输 normal 关闭宽屏。":" Widen the window and it takes effect automatically; type normal to switch it off.")),void Oe()):(console.log(chalk.green(" ✓ ")+chalk.gray(e?ao()?`宽屏开 — 卡片拉伸到终端宽度(现在 ${we()} 列,上限 96)。输 normal 恢复。`:`Wide mode ON — cards stretch to your terminal (now ${we()} cols, max 96). Type normal to restore.`:ao()?"已恢复 64 列标准宽。输 wide 再拉伸。":"Back to the 64-col standard width. Type wide to stretch again.")),Ye=null,je=null,De=null,Be(),lo=!1,no=!1,await Po(),void Oe()))}if("sim"===o){const e=ho(Se.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=k(C(import.meta.url)),o=[v(e,"..","..","panda","mujoco-launcher.py"),v(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 Oe()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Oe())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=Se.currentCard,t=Se.bookmarks.includes(e),n="bookmark"!==o;return n?Se.bookmarks=Se.bookmarks.filter(o=>o!==e):t||Se.bookmarks.push(e),J(Se),n?console.log(t?chalk.gray(ao()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(ao()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(ao()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(ao()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Oe()}if("e"===o)return Ue=Se.currentCard,console.log(chalk.gray(ao()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void Oe();if("back"===o||"b"===o)return"view"===Qe?(await Mo(),void Oe()):"honors"===Qe?(Qe=null,_o(),void Oe()):(Se.currentCard>1&&(Se.currentCard-=1),je=null,De=null,Ye=null,J(Se),_o(),void Oe());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!wo)return console.log(chalk.yellow(ao()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Oe();if(!e)return console.log(),console.log(chalk.bold.white(ao()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(ao()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(chalk.gray(ao()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(ao()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9")),console.log(chalk.gray(ao()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Oe();const t=await j(Ae,e);if(!t.ok||!t.data)return console.log(chalk.red(` ✗ ${t.message||(ao()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(ao()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Oe();console.log(),console.log(chalk.bold.green(ao()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 Linked — credit now carries both ways"));for(const e of t.data.members)console.log(chalk.gray(" · ")+chalk.white(e.curriculum_id)+chalk.gray(` ${e.token}`));return console.log(chalk.gray(ao()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log(),await $o(),void Oe()}if("contest"===o||"/contest"===o||"arena"===o||"contest start"===o||"/contest start"===o||"contest status"===o||"contest reset"===o||/^\/?contest [1-9]$/.test(o)){if(!wo)return console.log(chalk.yellow(ao()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Oe();const e=ko(Se.currentCard);if("contest reset"===o){const o=await R(Ae,e);if(o.ok){console.log(chalk.yellow(ao()?` 已放弃当前计时(阶段 ${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=v(process.cwd(),"icoa-contest",`${Te.id}-phase${e}-g${t}`);if(d(n))try{m(n,`${n}-archived-${o}`),console.log(chalk.gray(ao()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(ao()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(ao()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),fo=null,Ke=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Oe()}const t=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(ao()?" 连接判分赛…":" Contacting contest server…"));const n=await N(Ae,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(ao()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void Oe();const r=n.data,l=v(process.cwd(),"icoa-contest",`${Te.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=fo&&fo.phase===e&&fo.data.slot===r.slot?fo.tried:new Set;fo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,l=(t.samples??[])[0];l&&p(v(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=v(o,`sol-${r}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Lo(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.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`,"",""),p(s,a.join("\n"))})})(r,l),Ke=!0,Ro(),console.log(chalk.gray(ao()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(ao()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(ao()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Oe()}if("submit"===s)return console.log(chalk.yellow(ao()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(ao()?" 例如 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)")),fo||console.log(chalk.gray(ao()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Oe();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!fo)return console.log(chalk.yellow(ao()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Oe();const n=fo.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(ao()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Oe();const l=n.findIndex(e=>e.id===o)+1,a=t||v(fo.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(ao()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Oe()}console.log(chalk.gray(ao()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=bo.get(l),d=await O(Ae,fo.phase,o,i,void 0,c&&!w(c)?c:void 0);if(!d.ok||!d.data)return"no_active_session"===d.code?console.log(chalk.yellow(ao()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((ao()," "))+chalk.bold.green("contest")+chalk.gray(ao()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(ao()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void Oe();const g=d.data;if(g.already_ac)console.log(chalk.green(ao()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(ao()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(ao()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),fo.data.solved.includes(o)||fo.data.solved.push(o),fo.tried.delete(o);else{fo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?ao()?` · 挂在第 ${g.test} 个用例(过 ${g.passed_tests}/${g.total_tests})`:` · failed test ${g.test} (passed ${g.passed_tests}/${g.total_tests})`:""))}g.late&&console.log(chalk.yellow(ao()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=Y(g.deadline||"");if(console.log(chalk.white(ao()?` 本组进度: 已过 ${g.ac_count} 题 · 过 ${g.need} 题过关(共 ${g.n} 题)`:` Group progress: ${g.ac_count} solved · ${g.need} needed to pass (${g.n} problems)`)+(u?chalk.gray(` · ⏱ ${u}`):"")),g.passed&&!g.late)console.log(chalk.bold.green(ao()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await $o();else if(!g.late){const e=n.findIndex(e=>!fo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(ao()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${qo(n[e])}`))}return void Oe()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>Te.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Te.totalCards}. Try: `)+chalk.bold.green("card 1")),void Oe();const n=await Co(t);return n?(console.log(n),void Oe()):(Se.currentCard=t,je=null,De=null,Ye=null,J(Se),_o(),void Oe())}if(null!==Ye&&["y","yes","n","no"].includes(o)){const e=ho(Ye);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-so;V(Se,e.number),G(Se,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),J(Se);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),co.push(_(Ae,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Ye=null,e.solution&&e.solution.length>0)return void Oe();if(Se.currentCard<Te.totalCards){const e=Se.currentCard,o=await Co(e+1);if(o)return await Ao(e),console.log(o),void Oe();Se.currentCard+=1,J(Se),await Ao(e)?To():_o(),Oe()}else me(Te,Se),Oe();return}}if(null!==je&&["a","b","c","d"].includes(o)){const e=ho(je);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(X(Se,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),V(Se,e.number),J(Se),le(e,t,n,Se),co.push(_(Ae,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),je=null,n)if(Se.currentCard<Te.totalCards){const e=await Co(Se.currentCard+1);if(e)return console.log(e),void Oe();Se.currentCard+=1,J(Se),_o()}else me(Te,Se),Oe();else Oe();return}}if(null!==De){if("done"===o){const e=ho(De);if(e&&"practical"===e.type)return ee(Se,e.number),V(Se,e.number),J(Se),ae(e),De=null,void Oe()}if("skip"===o)return V(Se,De),J(Se),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),De=null,void Oe()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==je)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Oe();if(null!==De)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Oe();if(null!==Ye)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Oe();const e=Se.currentCard,o=e<Te.totalCards?await Co(e+1):null;return o?(await Ao(e),console.log(o),void Oe()):(Se.currentCard+=1,J(Se),Se.currentCard>Te.totalCards?me(Te,Se):await Ao(e)?To():_o(),void Oe())}if(null!==Ye)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Oe();if(null!==je)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Oe();if(null!==De)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Oe();"view"===Qe?console.log(chalk.gray(ao()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(ao()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(ao()?" 回卡片":" to the card")):"honors"===Qe?console.log(chalk.gray(ao()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(ao()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(ao()?" 回卡片":" to the card")):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")),Oe()}else{if("view"===Qe)return await Mo(),void Oe();if("honors"===Qe)return Qe=null,_o(),void Oe();if(co.length>0&&await Promise.race([Promise.allSettled(co),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Se.streakDays} day(s)`)),console.log(),qe){We.removeAllListeners("line"),Ne();for(const e of Le)We.on("line",e);We.prompt(),yo()}else We.removeAllListeners("line"),We.close()}else if(co.length>0&&await Promise.race([Promise.allSettled(co),new Promise(e=>setTimeout(e,3e3))]),We.removeAllListeners("line"),Ne(),qe||!mo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(qe?We:void 0),yo()}else We.close()};We.on("line",e=>{zo(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.")),Oe()})}),qe||We.on("close",async()=>{co.length>0&&await Promise.race([Promise.allSettled(co),new Promise(e=>setTimeout(e,5e3))]),mo?yo():process.exit(0)});try{_o(),Oe();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(ve("Could not render this card — the curriculum may be malformed."),qe){We.removeAllListeners("line"),Ne();for(const e of Le)We.on("line",e);We.prompt()}else We.close();yo()}await uo}),Ce.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(),l=await A(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.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()})}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * How a contest solution came to exist — typed, or pasted in.
3
+ *
4
+ * The existing input-dynamics observer watches the readline prompt, which is
5
+ * the WRONG surface here: contest code is written inside vi, so at `/submit 3`
6
+ * it would only report how the five characters "submit 3" were typed. The
7
+ * signal that actually answers the question lives in the editor session —
8
+ * how long the editor was open against how much the file grew.
9
+ *
10
+ * A person types on the order of 5–10 bytes/second sustained. A paste lands
11
+ * thousands of bytes in the time it takes to release the key. That ratio is
12
+ * the whole measurement, and it needs no keystroke content at all: this module
13
+ * records byte counts and durations, never a single character of what was
14
+ * written. Same discipline as input-dynamics.ts — aggregate counters only.
15
+ *
16
+ * Detective, never preventive: a high ratio is a reason for a human to look,
17
+ * not a verdict, and nothing here gates a submission.
18
+ */
19
+ export type EditDynamics = {
20
+ /** How many times the editor was opened for this problem. */
21
+ editSessions: number;
22
+ /** Total milliseconds the editor was open. */
23
+ editMs: number;
24
+ /** Size of the solution file when last seen, in bytes. */
25
+ bytesFinal: number;
26
+ /** Net growth across all sessions (can be negative if they deleted). */
27
+ bytesAdded: number;
28
+ /**
29
+ * Fastest sustained growth seen in any single session, bytes/second.
30
+ * The paste fingerprint: sustained human typing sits in single digits.
31
+ */
32
+ maxBytesPerSec: number;
33
+ /** Self-checks (`/run`) before submitting — pasted answers often get none. */
34
+ runs: number;
35
+ };
36
+ export declare function emptyDynamics(): EditDynamics;
37
+ /**
38
+ * Fold one finished editor session into the accumulator.
39
+ *
40
+ * `ms` under a second is treated as one second for the rate, so opening and
41
+ * closing the editor instantly cannot manufacture an infinite rate — and a
42
+ * session that added nothing never moves the maximum.
43
+ */
44
+ export declare function foldEditSession(prev: EditDynamics, session: {
45
+ ms: number;
46
+ bytesBefore: number;
47
+ bytesAfter: number;
48
+ }): EditDynamics;
49
+ export declare function noteRun(prev: EditDynamics): EditDynamics;
50
+ /**
51
+ * Nothing observed at all — a solution that appeared without the editor ever
52
+ * being opened (written by an external editor, or dropped in as a file). Worth
53
+ * distinguishing from "typed fast", so the server stores the difference.
54
+ */
55
+ export declare function isEmpty(d: EditDynamics): boolean;
@@ -0,0 +1 @@
1
+ export function emptyDynamics(){return{editSessions:0,editMs:0,bytesFinal:0,bytesAdded:0,maxBytesPerSec:0,runs:0}}export function foldEditSession(e,t){const s=t.bytesAfter-t.bytesBefore,n=Math.max(1,t.ms/1e3),r=s>0?s/n:0;return{editSessions:e.editSessions+1,editMs:e.editMs+Math.max(0,t.ms),bytesFinal:t.bytesAfter,bytesAdded:e.bytesAdded+s,maxBytesPerSec:Math.max(e.maxBytesPerSec,Math.round(10*r)/10),runs:e.runs}}export function noteRun(e){return{...e,runs:e.runs+1}}export function isEmpty(e){return 0===e.editSessions&&0===e.runs}
@@ -88,6 +88,13 @@ export type GatePhase = {
88
88
  min_score: number;
89
89
  passed: boolean;
90
90
  };
91
+ checks?: {
92
+ enabled: boolean;
93
+ need: number;
94
+ good: number;
95
+ missing: number[];
96
+ passed: boolean;
97
+ };
91
98
  };
92
99
  export type GateData = {
93
100
  gated: number;
@@ -101,7 +108,7 @@ type ApiResult<T> = {
101
108
  message?: string;
102
109
  };
103
110
  export declare function contestStart(token: string, phase: number, slot?: number): Promise<ApiResult<ContestStartData>>;
104
- export declare function contestSubmit(token: string, phase: number, problemId: string, code: string, slot?: number): Promise<ApiResult<ContestSubmitData>>;
111
+ export declare function contestSubmit(token: string, phase: number, problemId: string, code: string, slot?: number, dyn?: Record<string, number>): Promise<ApiResult<ContestSubmitData>>;
105
112
  export declare function contestReset(token: string, phase: number, slot?: number): Promise<ApiResult<{
106
113
  reset_sessions: number;
107
114
  }>>;
@@ -1 +1 @@
1
- import{getDeviceFingerprint as e}from"./access.js";import{LEARN_SERVER as t}from"./learn-curricula.js";async function o(o,n,r){const a=t.replace(/\/$/,"")+o;try{const t=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,device_fingerprint:e()}),signal:AbortSignal.timeout(r)}),o=await t.json().catch(()=>({}));return t.ok&&o.success&&void 0!==o.data?{ok:!0,data:o.data}:{ok:!1,message:o.message||`HTTP ${t.status}`,code:o.code}}catch(e){return{ok:!1,message:`Network error: ${e instanceof Error?e.message:String(e)}`}}}export function contestStart(e,t,n){return o("/api/icoa/learn/contest/start",{token:e.toUpperCase(),phase:t,...null!=n?{slot:n}:{}},15e3)}export function contestSubmit(e,t,n,r,a){return o("/api/icoa/learn/contest/submit",{token:e.toUpperCase(),phase:t,problem_id:n,code:r,...null!=a?{slot:a}:{}},12e4)}export function contestReset(e,t,n){return o("/api/icoa/learn/contest/reset",{token:e.toUpperCase(),phase:t,...null!=n?{slot:n}:{}},15e3)}export function fetchGate(e){return o("/api/icoa/learn/gate",{token:e.toUpperCase()},15e3)}export function linkToken(e,t){return o("/api/icoa/learn/link",{token:e.toUpperCase(),other_token:t.toUpperCase()},2e4)}export function timeLeft(e){const t=Date.parse(e);if(Number.isNaN(t))return null;const o=t-Date.now();if(o<=0)return null;const n=Math.floor(o/6e4),r=Math.floor(o%6e4/1e3);return`${n}:${String(r).padStart(2,"0")}`}
1
+ import{getDeviceFingerprint as e}from"./access.js";import{LEARN_SERVER as t}from"./learn-curricula.js";async function o(o,n,r){const a=t.replace(/\/$/,"")+o;try{const t=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,device_fingerprint:e()}),signal:AbortSignal.timeout(r)}),o=await t.json().catch(()=>({}));return t.ok&&o.success&&void 0!==o.data?{ok:!0,data:o.data}:{ok:!1,message:o.message||`HTTP ${t.status}`,code:o.code}}catch(e){return{ok:!1,message:`Network error: ${e instanceof Error?e.message:String(e)}`}}}export function contestStart(e,t,n){return o("/api/icoa/learn/contest/start",{token:e.toUpperCase(),phase:t,...null!=n?{slot:n}:{}},15e3)}export function contestSubmit(e,t,n,r,a,s){return o("/api/icoa/learn/contest/submit",{token:e.toUpperCase(),phase:t,problem_id:n,code:r,...null!=a?{slot:a}:{},...s?{dyn:s}:{}},12e4)}export function contestReset(e,t,n){return o("/api/icoa/learn/contest/reset",{token:e.toUpperCase(),phase:t,...null!=n?{slot:n}:{}},15e3)}export function fetchGate(e){return o("/api/icoa/learn/gate",{token:e.toUpperCase()},15e3)}export function linkToken(e,t){return o("/api/icoa/learn/link",{token:e.toUpperCase(),other_token:t.toUpperCase()},2e4)}export function timeLeft(e){const t=Date.parse(e);if(Number.isNaN(t))return null;const o=t-Date.now();if(o<=0)return null;const n=Math.floor(o/6e4),r=Math.floor(o%6e4/1e3);return`${n}:${String(r).padStart(2,"0")}`}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.435",
3
+ "version": "2.19.437",
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": {