icoa-cli 2.19.441 → 2.19.442

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 n,execSync as t,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 A}from"node:url";import{loadCurriculumById as C,validateEAToken as _,syncProgress as T,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 L,viewPqsTop as q,viewHonors as W}from"../lib/learn-ai.js";import{contestReset as R,contestStart as N,contestSubmit as O,linkByIndex as j,linkSuggest as D,linkToken as Y,fetchGate as U,timeLeft as F}from"../lib/learn-contest.js";import{getConfig as z,saveConfig as H}from"../lib/config.js";import{isNativeWindows as B,isWindowsBuildInWslShell as Z,whichBinary as J}from"../lib/platform.js";import{loadLearnState as K,saveLearnState as Q,newLearnState as V,updateStreak as X,markCardComplete as G,recordMCQ as ee,recordCheck as oe,markPracticalComplete as ne,addAchievement as te}from"../lib/learn-state.js";import{renderWelcome as re,renderKnowledgeCard as le,renderMCQCard as se,renderMCQFeedback as ae,renderPracticalCard as ie,renderPracticalSuccess as ce,renderSimDemoCard as de,renderMilestone as ge,renderArenaTaskCard as ue,renderComingSoonCard as ye,renderStatus as me,renderPhaseComplete as he,renderCurriculumComplete as pe,setLearnAiEnabled as fe,setLearnHonorRanks as be,setLearnPqsViewCards as we,setLearnWidth as $e,resolveLearnWidth as ke,learnWidthCap as ve,learnW as Ae,renderHonorWall as Ce,wrapMixed as _e}from"../lib/learn-render.js";import{printError as Te}from"../lib/ui.js";const Ie=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(xe){xe.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async xe=>{xe?.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(),xe="LEARNDEMO01");let Ee=xe.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ee)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Se=null;const Pe=/^[A-Z0-9]+DEMO01$/i.test(Ee),Me=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ee);let Le=!1,qe=!1;if(Pe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Se=await C(Ee,Ee);else if(Me){console.log(),console.log(chalk.gray(" Validating token..."));let e=await _(Ee);if(!e.ok){const o=x(Ee);if(o!==Ee){const n=await _(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ee} → ${o}`)),e=n,Ee=o)}}if(!e.ok)return Te(`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 🐼"):"")),Le=!0===e.aiEnabled,qe=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Se=await C(e.curriculumId||"LEARNDEMO01",Ee),!Se)return Te(`Could not open a learn curriculum for token '${Ee}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ee}`)+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 ${Ee}`)+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(!Se){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Te(`Could not reach the learn server to open ${Ee}.`),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 ${Ee}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Te(`Unknown learn token: ${Ee}`),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 We=K(),Re=!1;try{We&&We.token===Ee?X(We):(We=V(Ee,Se.id,Se.totalCards),Re=!0),Q(We),re(Se,We,Re)}catch{return Te("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 ${Ee}`)+chalk.gray(".")),void console.log()}const Ne=s(),Oe=null!==Ne,je=Oe?Ne.listeners("line").slice():[];Oe&&Ne.removeAllListeners("line");const De=Oe?Ne:o({input:process.stdin,output:process.stdout,terminal:!0}),Ye=Oe?De.prompt:null;Oe&&(De.prompt=e.prototype.prompt);const Ue=()=>{Oe&&Ye&&(De.prompt=Ye)},Fe=()=>{De.setPrompt(lo?chalk.bold.green(`icoa ${a()}> `):eo?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Xe?"icoa learn ai> ":"icoa learn> ")),De.prompt()};let ze=null,He=null,Be=null,Ze=null,Je=[],Ke=!1,Qe=null;const Ve=()=>{Qe&&clearTimeout(Qe),Qe=null,Je=[],Ke=!1,Ze=null};let Xe=!1,Ge=!1,eo=!1,oo=null,no=!1,to=0,ro=!1,lo=!1;const so=new Map,ao=()=>{let e=so.get(We.currentCard);return e||(e=[],so.set(We.currentCard,e)),e};let io=!1;const co=new Set;let go=!1,uo=0;const yo=()=>(z().language||"en").toLowerCase().startsWith("zh");fe(Le),$e(ke(z())),we(co);const mo=new Map;be(mo);const ho=[];let po=null;const fo=new Promise(e=>{po=e}),bo=()=>{const e=po;po=null,e?.()},wo="1"===process.env.ICOA_LEARN_EMBEDDED,$o=e=>Se.cards.find(o=>o.number===e);let ko=null,vo=null;const Ao=new Map,Co=!Ee.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ee),_o=async()=>{if(!Co)return;const e=await U(Ee);e.ok&&e.data&&(ko=e.data)},To=e=>{const o=Se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Io=e=>{if(!qe||!ko)return null;const o=To(e);if(o<=ko.unlocked_through_phase)return null;const n=ko.phases.find(e=>e.phase===ko.unlocked_through_phase),t=[chalk.yellow(yo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${ko.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${ko.unlocked_through_phase}'s core tasks first:`)];if(n?.contest&&!n.contest.passed){const e=n.contest.slots??[];if(e.length>0)for(const o of e)o.passed||t.push(chalk.gray(yo()?` ⚔ 练习赛 ${ko.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${ko.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else t.push(chalk.gray(yo()?` ⚖ 判分赛: 最好 ${n.contest.best_ac}/${n.contest.n} AC,需 ${n.contest.need} — 输入 `:` ⚖ contest: best ${n.contest.best_ac}/${n.contest.n} AC, need ${n.contest.need} — type `)+chalk.bold.green("contest"))}if(n?.checks?.enabled&&!n.checks.passed){const e=n.checks.missing??[],o=e.slice(0,8).join(yo()?"、":", "),r=e.length>8?yo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:yo()?" 张":"";t.push(chalk.gray(yo()?` ✓ 逐卡自测: ${n.checks.good}/${n.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${n.checks.good}/${n.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return n?.research&&!n.research.passed&&t.push(chalk.gray(yo()?` ⭐ 提问研究: ${n.research.good_cards}/${n.research.need_cards} 卡达到 ${n.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${n.research.good_cards}/${n.research.need_cards} cards at ${n.research.min_score}+ — research with /ai, then /submit`)),t.join("\n")},xo=async e=>qe?null===Io(e)?null:(await _o(),Io(e)):null;Co&&await _o();const Eo=async e=>{const o=Se.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Se.modules.find(e=>e.number===o.number+1);let t;if(Le){const e=await E({token:Ee,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}Co&&await _o();const r=ko?.phases.find(e=>e.phase===o.number);return he(Se,We,o,n,t,r),!0},So=()=>{go=!0,console.log(chalk.gray(yo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Po=()=>{oo=null;const e=$o(We.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":le(e,Se),e.check?(Be=e.number,uo=Date.now()):(G(We,e.number),Q(We));break;case"mcq":se(e,Se),ze=e.number;break;case"practical":ie(e,Se),He=e.number;break;case"sim_demo":de(e,Se),G(We,e.number),Q(We);break;case"milestone":ge(e,Se),te(We,e.badge),G(We,e.number),Q(We);break;case"arena_task":ue(e,Se),G(We,e.number),Q(We);break;case"coming_soon":ye(e,Se),G(We,e.number),Q(We)}Mo(e.number)},Mo=e=>{if(!Co||!ko)return;const o=Se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const n=e-o.cardRange[0]+1;if(n%4!=0)return;const t=n/4,r=ko.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===t);if(!l)return;const s=(e,o,n,t)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${o}:${String(n).padStart(2,"0")}`})(n),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${n(o.getMonth()+1)}-${n(o.getDate())} ${n(o.getHours())}:${n(o.getMinutes())}`})(t);return`🏆 ${e} ${o}/${l.n}`+(r?yo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Ae());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${yo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(yo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(yo()?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(yo()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),(l.carryable_ac??0)>0&&console.log(c+chalk.cyan(yo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(yo()?"✍ 第一次用 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(yo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(yo()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${t}`)+(l.passed?chalk.gray(yo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(yo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(yo()?" 继续学习":" keep going"):chalk.gray(yo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Lo=()=>{Ee.endsWith("DEMO01")?console.log(chalk.yellow(yo()?" 🐼 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(yo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(yo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},qo=async(e,o)=>{if(Le){Ge=!0;try{console.log(),console.log(chalk.gray("deep"===o?yo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":yo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await M({token:Ee,cardNumber:We.currentCard,question:e,mode:o,history:ao().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(t||(process.stdout.write(n?"\n\n ":" "),t=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||t)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(yo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(ao().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(` (${yo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(yo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Be&&console.log(chalk.gray(yo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ge=!1}}else Lo()},Wo=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ro=async()=>{eo&&vo?Ho?Bo(Ho):Uo():oo?await No():Po()},No=async()=>{Ge=!0;try{console.log();const e=await W({token:Ee,curriculumId:Se.id,cardNumber:We.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(yo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(yo()?` 🏆 本卡实时 Top-3 — 第 ${We.currentCard} 张`:` 🏆 Live top-3 — card ${We.currentCard}`)),e.board&&0!==e.board.length)for(const o of e.board){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(chalk.white(` ${o.icon} `)+chalk.bold.cyan(o.name||`Rank ${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(yo()?" (你)":" (you)"):""))}else console.log(chalk.gray(yo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(mo.set(We.currentCard,e.mine.rank),console.log(chalk.white(yo()?" 你: ":" You: ")+chalk.bold.yellow(yo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(yo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Le&&console.log(chalk.gray(yo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ce({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(yo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(yo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(yo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),oo="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 返回卡片":" returns to the card")),console.log()}finally{Ge=!1}},Oo=e=>yo()&&e.title_zh||e.title,jo=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of _e(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},Do=e=>{console.log(),console.log(chalk.bold.green(yo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 Linked — credit now carries both ways"));for(const o of e.members)console.log(chalk.gray(" · ")+chalk.white(o.curriculum_id)+chalk.gray(` ${o.token}`));console.log(chalk.gray(yo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Yo=e=>vo.data.solved.includes(e.id)?"✅":vo.data.carried?.includes(e.id)?"✅↗":vo.tried.has(e.id)?"❌":"⬜",Uo=()=>{const e=vo.data,o=F(e.deadline),n=(e.carried??[]).filter(o=>!e.solved.includes(o)),t=e.solved.length+n.length,r=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(yo()?` · 第 ${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(yo()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(yo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(yo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(yo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yo()?" 带过来,不必重做":" to carry them over instead of redoing them"));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(yo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(yo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(yo()?` 满血重开本组(${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)} `)+Yo(e)+chalk.white(` ${Oo(e)}`))}),console.log(),Fo()},Fo=()=>{console.log(chalk.gray(yo()?" /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(yo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 返回课程":" returns to the lesson")),console.log()},zo=e=>{const o=parseInt(e,10),n=vo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(yo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let Ho=null;const Bo=e=>{const o=zo(e);if(!o)return;const{p:n,n:t}=o;Ho=String(t),console.log(),console.log(chalk.bold.white(` ${Yo(n)} ${Oo(n)}`)),console.log();for(const e of(e=>yo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of _e(e,Ae()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of n.samples??[]){r+=1,console.log(),console.log(chalk.gray(yo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(yo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(n.samples??[]).length&&(console.log(),console.log(chalk.gray(yo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(yo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(yo()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${t}`.padEnd(11))+chalk.gray(yo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(yo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(yo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((yo()," ↩ "))+chalk.bold.green("back")+chalk.gray(yo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(yo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((yo()," / "))+chalk.bold.green("wide")+chalk.gray(yo()?" 换语言/宽度":" language / width")),console.log()},Zo=async(e,o)=>await new Promise(n=>{const t=process.stdin,l=!!t.isTTY&&!!t.isRaw;if(De.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:vo.dir}),a=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&l)try{t.setRawMode(!0)}catch{}De.resume(),n(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Jo=()=>{console.log(chalk.yellow(yo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(yo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(yo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(yo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Ko=new Map,Qo=async e=>{const o=e.trim().toLowerCase(),s=eo&&o.startsWith("/")?o.slice(1):o;if(Ge)return;if(null!==Ze){if(Je.push(e.replace(/\s+$/,"")),Qe&&clearTimeout(Qe),Qe=null,Ke){const e=Je[Je.length-1]??"";return"/cancel"===e.trim()?(Ve(),console.log(chalk.gray(yo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Fe()):""!==e.trim()?void Fe():(Je.pop(),void await a())}return void(Qe=setTimeout(()=>{if(Qe=null,Je.length>1){Ke=!0;const e=Je.length;return console.log(chalk.cyan(yo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(yo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Fe()}a()},140))}async function a(){const e=Je.join("\n").replace(/^\s+|\s+$/g,""),o=Ze??We.currentCard,n=Je.length;if(Ve(),""===e)console.log(chalk.gray(yo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(yo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(yo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(yo()?" 即可执行。":" again to run it."));else{const t=uo>0?Date.now()-uo:void 0;if(await I(Ee,{curriculum_id:Se.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const e=n>1?yo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(yo()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(yo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Fe()}if(no){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return no=!1,console.log(),console.log(chalk.yellow(yo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(yo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(yo()?" 即可执行该命令。":" again to run it.")),console.log(),void Fe();if(!o)return no=!1,console.log(chalk.gray(yo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Fe();const n=await P({token:Ee,nickname:o});if(n.ok)no=!1,console.log(chalk.bold.green(yo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(yo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{to+=1;const e="taken"===n.code?yo()?"已被占用":"already taken":"bad_charset"===n.code?yo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?yo()?"未通过审核":"did not pass review":n.message||"error";if(!(to>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Fe();no=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Fe()}if(io){io=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ge=!0;try{console.log(),console.log(chalk.gray(yo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await L({token:Ee,cardNumber:We.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(yo()?"评审暂不可用。":"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(yo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(yo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(yo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(yo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(yo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(yo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=yo()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(yo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(yo()?` 第 ${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 Wo(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(yo()?" 改进提问: ":" 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(` (${yo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?co.add(We.currentCard):co.delete(We.currentCard),"number"==typeof e.rank&&mo.set(We.currentCard,e.rank);const o=await W({token:Ee,curriculumId:Se.id,cardNumber:We.currentCard});o.ok&&o.totals&&o.chapters&&(Ce({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Pe&&(no=!0,to=0,console.log(chalk.bold.yellow(yo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(yo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(yo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Ge=!1}})():(console.log(chalk.gray(yo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Be&&(console.log(chalk.gray(yo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Fe()}if(go)return go=!1,Po(),void Fe();if(!o)return void Fe();if(lo)return"exit"===await i(e.trim())&&(lo=!1),void Fe();if(Xe){if(["q","quit","exit","back","b","menu"].includes(o))return Xe=!1,console.log(chalk.gray(yo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Fe();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim();return t&&(await qo(t,n?"fast":"deep"),console.log(chalk.gray(yo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Fe()}if(eo&&vo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${vo.phase}s${vo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return eo=!1,console.log(chalk.gray(yo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Po(),void Fe();if(/^\d+$/.test(o))return Bo(o),void Fe();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,t]=e;return"list"===o?Uo():t?"read"===o||"open"===o?Bo(t):"edit"===o?await(async e=>{const o=zo(e);if(!o)return;const n=v(vo.dir,`sol-${o.n}.py`);if(B())return Z()?(console.log(chalk.yellow(yo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(yo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(yo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(yo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(yo()?" ← 不能是 /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(yo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(yo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(yo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(yo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(yo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(yo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(yo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(yo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!J("vi"))return console.log(chalk.yellow(yo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(yo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(yo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return h(e).size}catch{return 0}},r=t(n),l=Date.now();await Zo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),Ao.set(o.n,b(Ao.get(o.n)??f(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(yo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(yo()?" 自测样例。":" to self-check the sample.")),console.log()})(t):"run"===o?(e=>{const o=zo(e);if(!o)return;const{p:t,n:r}=o,l=v(vo.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(yo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Ao.set(r,$(Ao.get(r)??f()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(yo()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=n("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)Jo();else if(o.killed)console.log(chalk.yellow(yo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(yo()?" ✗ 程序报错:":" ✗ 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(yo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(yo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(yo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(yo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(yo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(yo()?" 改完再 /run。":" then /run again.")),console.log()})(t):"debug"===o?await(async e=>{const o=zo(e);if(!o)return;const n=v(vo.dir,`sol-${o.n}.py`);if(!d(n))return void console.log(chalk.yellow(yo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(yo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const t=await Zo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(yo()?" 回到竞技场。":" Back in the arena.")),console.log()):Jo()})(t):"recall"===o&&await(async e=>{const o=zo(e);if(!o)return;if(!Le)return void Lo();const{p:n,n:t}=o,r=v(process.cwd(),"icoa-contest"),l=`${Se.id}-phase${vo.phase}-g${vo.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-${t}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(yo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${vo.phase}-${vo.data.slot}-${t}`,g=Math.min(3,(Ko.get(c)??0)+1);console.log(chalk.gray(yo()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await S({token:Ee,phase:vo.phase,slot:vo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:g,lang:yo()?"zh":"en"});if(m.ok){Ko.set(c,g),console.log();for(const e of _e(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(yo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(yo()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(yo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(t):console.log(chalk.yellow(yo()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(yo()?" (花名册: /list)":" (roster: /list)")),void Fe()}if("contest"===o||"/contest"===o)return Uo(),void Fe();const t="lang"===o||/^lang\s+\S+$/.test(o),r=Ie.has(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||t||r||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(yo()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Fe()}if("tmux"===o||o.startsWith("tmux ")){try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(yo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Fe()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(De.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&t)try{n.setRawMode(!0)}catch{}De.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Fe()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(lo=!0),void Fe();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Le)return Lo(),void Fe();ro||(ro=!0,console.log(),console.log(chalk.bold.cyan(yo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(yo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(yo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),yo()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const n=o.startsWith("/ai!"),t=e.trim().slice(n?4:3).trim();if(!t){Xe=!0;const e=$o(We.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(yo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(yo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Fe()}return await qo(t,n?"fast":"deep"),void Fe()}if(!eo&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Le)return Lo(),void Fe();const e=$o(We.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(yo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(yo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(yo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(yo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(yo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(yo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),io=!0,void Fe()}const C=!eo&&"honors"===oo&&/^[1-3]$/.test(o);if(!eo&&oo&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(yo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(yo()?" ↩ back 回上一层":" ↩ back goes up one level")),void Fe();if(!eo&&(C||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Le)return Lo(),void Fe();const e=/^\/?view ([1-3])$/.exec(o),n=C?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Ge=!0;try{console.log();const o=await q({token:Ee,cardNumber:We.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(yo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&co.delete(We.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&co.add(We.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(yo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${We.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${We.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(yo()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of n){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(yo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=Wo(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(yo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),oo="view",console.log(chalk.gray((yo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Ge=!1}})(n),void Fe()}if("/honors"===o||"honors"===o)return Pe?(console.log(),console.log(chalk.gray(yo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Fe()):(await No(),void Fe());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return me(Se,We),void Fe();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(z().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Fe();const n=Se.cards.some(e=>null!=e._zh),t=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===t||"zh"===t&&n,l=r?t:"en";return H({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Be=null,ze=null,He=null,Ve(),go=!1,io=!1,await Ro(),void Fe()}if(Ie.has(o)){const e=Ie.get(o),n=ke(z()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return yo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((yo()?"normal"===e?" 已是标准 64 列。":Ae()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Ae()} 列,上限 ${ve(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Ae()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Ae()} cols, cap ${ve(e)}). `)+t(e))),void Fe()):(H({learnWidth:e,learnWide:"normal"!==e}),$e(e),"normal"!==e&&Ae()<=64?(console.log(chalk.yellow(yo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((yo()?` 设置已记住(${e},上限 ${ve(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${ve(e)} cols) and applies once you widen the window. `)+t(e))),void Fe()):(console.log(chalk.green(" ✓ ")+chalk.gray((yo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Ae()} 列,上限 ${ve(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Ae()} cols, cap ${ve(e)}). `)+t(e))),Be=null,ze=null,He=null,Ve(),go=!1,io=!1,await Ro(),void Fe()))}if("sim"===o){const e=$o(We.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=k(A(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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--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 Fe()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Fe())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=We.currentCard,n=We.bookmarks.includes(e),t="bookmark"!==o;return t?We.bookmarks=We.bookmarks.filter(o=>o!==e):n||We.bookmarks.push(e),Q(We),t?console.log(n?chalk.gray(yo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(yo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(yo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(yo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Fe()}if("e"===o)return Ze=We.currentCard,console.log(chalk.gray(yo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void Fe();if("back"===o||"b"===o)return"view"===oo?(await No(),void Fe()):"honors"===oo?(oo=null,Po(),void Fe()):(We.currentCard>1&&(We.currentCard-=1),ze=null,He=null,Be=null,Q(We),Po(),void Fe());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Co)return console.log(chalk.yellow(yo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Fe();if(!e){const e=await D(Ee),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(yo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(yo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(yo()?` 这台电脑上有 ${o.length} 个你的 token 还没关联:`:` ${o.length} token${1===o.length?"":"s"} of yours on this computer `+(1===o.length?"is":"are")+" not linked yet:"));for(const e of o)console.log(chalk.bold.green(` ${e.index}. `)+chalk.white(e.curriculum_id.padEnd(12))+chalk.gray(e.token)+(e.carry_problems>0?chalk.cyan(yo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(yo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(yo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(yo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(yo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(yo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(yo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Fe()}if(/^\d{1,2}$/.test(e)){const o=await j(Ee,Number(e));return o.ok&&o.data?(Do(o.data),await _o(),void Fe()):(console.log(chalk.red(` ✗ ${o.message||(yo()?"关联失败":"Link failed")}`)),void Fe())}const n=await Y(Ee,e);return n.ok&&n.data?(Do(n.data),await _o(),void Fe()):(console.log(chalk.red(` ✗ ${n.message||(yo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(yo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Fe())}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(!Co)return console.log(chalk.yellow(yo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Fe();const e=To(We.currentCard);if("contest reset"===o){const o=await R(Ee,e);if(o.ok){console.log(chalk.yellow(yo()?` 已放弃当前计时(阶段 ${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 n=1;n<=3;n++){const t=v(process.cwd(),"icoa-contest",`${Se.id}-phase${e}-g${n}`);if(d(t))try{m(t,`${t}-archived-${o}`),console.log(chalk.gray(yo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(yo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(yo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),vo=null,eo=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Fe()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(yo()?" 连接判分赛…":" Contacting contest server…"));const t=await N(Ee,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(yo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void Fe();const r=t.data,l=v(process.cwd(),"icoa-contest",`${Se.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=vo&&vo.phase===e&&vo.data.slot===r.slot?vo.tried:new Set;vo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.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"} · ${n.title} ══`,"#",...jo(n.statement,72)];if(n.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),eo=!0,Uo(),console.log(chalk.gray(yo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(yo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(yo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Fe()}if("submit"===s)return console.log(chalk.yellow(yo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(yo()?" 例如 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)")),vo||console.log(chalk.gray(yo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Fe();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const n=e[2];if(!vo)return console.log(chalk.yellow(yo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Fe();const t=vo.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=t.length&&!t.some(e=>e.id===o)&&(o=t[r-1].id),!t.some(e=>e.id===o))return console.log(chalk.yellow(yo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Fe();const l=t.findIndex(e=>e.id===o)+1,a=n||v(vo.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(yo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Fe()}console.log(chalk.gray(yo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Ao.get(l),d=await O(Ee,vo.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(yo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((yo()," "))+chalk.bold.green("contest")+chalk.gray(yo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void Fe();const g=d.data;if(g.already_ac)console.log(chalk.green(yo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(yo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(yo()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),vo.data.solved.includes(o)||vo.data.solved.push(o),vo.tried.delete(o);else{vo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?yo()?` · 挂在第 ${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(yo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=F(g.deadline||"");if(console.log(chalk.white(yo()?` 本组进度: 已过 ${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(yo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await _o();else if(!g.late){const e=t.findIndex(e=>!vo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(yo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Oo(t[e])}`))}return void Fe()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Se.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Se.totalCards}. Try: `)+chalk.bold.green("card 1")),void Fe();const t=await xo(n);return t?(console.log(t),void Fe()):(We.currentCard=n,ze=null,He=null,Be=null,Q(We),Po(),void Fe())}if(null!==Be&&["y","yes","n","no"].includes(o)){const e=$o(Be);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-uo;G(We,e.number),oe(We,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),Q(We);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),ho.push(T(Ee,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),Be=null,e.solution&&e.solution.length>0)return void Fe();if(We.currentCard<Se.totalCards){const e=We.currentCard,o=await xo(e+1);if(o)return await Eo(e),console.log(o),void Fe();We.currentCard+=1,Q(We),await Eo(e)?So():Po(),Fe()}else pe(Se,We),Fe();return}}if(null!==ze&&["a","b","c","d"].includes(o)){const e=$o(ze);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(ee(We,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),G(We,e.number),Q(We),ae(e,n,t,We),ho.push(T(Ee,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),ze=null,t)if(We.currentCard<Se.totalCards){const e=await xo(We.currentCard+1);if(e)return console.log(e),void Fe();We.currentCard+=1,Q(We),Po()}else pe(Se,We),Fe();else Fe();return}}if(null!==He){if("done"===o){const e=$o(He);if(e&&"practical"===e.type)return ne(We,e.number),G(We,e.number),Q(We),ce(e),He=null,void Fe()}if("skip"===o)return G(We,He),Q(We),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),He=null,void Fe()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ze)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Fe();if(null!==He)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Fe();if(null!==Be)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Fe();const e=We.currentCard,o=e<Se.totalCards?await xo(e+1):null;return o?(await Eo(e),console.log(o),void Fe()):(We.currentCard+=1,Q(We),We.currentCard>Se.totalCards?pe(Se,We):await Eo(e)?So():Po(),void Fe())}if(null!==Be)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Fe();if(null!==ze)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Fe();if(null!==He)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Fe();"view"===oo?console.log(chalk.gray(yo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(yo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(yo()?" 回卡片":" to the card")):"honors"===oo?console.log(chalk.gray(yo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(yo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(yo()?" 回卡片":" 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")),Fe()}else{if("view"===oo)return await No(),void Fe();if("honors"===oo)return oo=null,Po(),void Fe();if(ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${We.streakDays} day(s)`)),console.log(),Oe){De.removeAllListeners("line"),Ue();for(const e of je)De.on("line",e);De.prompt(),bo()}else De.removeAllListeners("line"),De.close()}else if(ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,3e3))]),De.removeAllListeners("line"),Ue(),Oe||!wo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Oe?De:void 0),bo()}else De.close()};De.on("line",e=>{Qo(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.")),Fe()})}),Oe||De.on("close",async()=>{ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,5e3))]),wo?bo():process.exit(0)});try{Po(),Fe();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Te("Could not render this card — the curriculum may be malformed."),Oe){De.removeAllListeners("line"),Ue();for(const e of je)De.on("line",e);De.prompt()}else De.close();bo()}await fo}),xe.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await C(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} 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 n,execSync as t,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 A}from"node:url";import{loadCurriculumById as C,validateEAToken as _,syncProgress as T,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 L,viewPqsTop as q,viewHonors as W}from"../lib/learn-ai.js";import{contestReset as R,contestStart as N,contestSubmit as O,linkByIndex as j,linkSuggest as D,linkToken as Y,fetchGate as U,timeLeft as F}from"../lib/learn-contest.js";import{getConfig as z,saveConfig as H}from"../lib/config.js";import{isNativeWindows as B,isWindowsBuildInWslShell as Z,whichBinary as J}from"../lib/platform.js";import{loadLearnState as K,saveLearnState as Q,newLearnState as V,updateStreak as X,markCardComplete as G,recordMCQ as ee,recordCheck as oe,markPracticalComplete as ne,addAchievement as te}from"../lib/learn-state.js";import{renderWelcome as re,renderKnowledgeCard as le,renderMCQCard as se,renderMCQFeedback as ae,renderPracticalCard as ie,renderPracticalSuccess as ce,renderSimDemoCard as de,renderMilestone as ge,renderArenaTaskCard as ue,renderComingSoonCard as ye,renderStatus as me,renderPhaseComplete as he,renderCurriculumComplete as pe,setLearnAiEnabled as fe,setLearnHonorRanks as be,setLearnPqsViewCards as we,setLearnWidth as $e,resolveLearnWidth as ke,learnWidthCap as ve,learnW as Ae,renderHonorWall as Ce,wrapMixed as _e}from"../lib/learn-render.js";import{printError as Te}from"../lib/ui.js";const Ie=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(xe){xe.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async xe=>{xe?.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(),xe="LEARNDEMO01");let Ee=xe.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ee)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Se=null;const Pe=/^[A-Z0-9]+DEMO01$/i.test(Ee),Me=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ee);let Le=!1,qe=!1;if(Pe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Se=await C(Ee,Ee);else if(Me){console.log(),console.log(chalk.gray(" Validating token..."));let e=await _(Ee);if(!e.ok){const o=x(Ee);if(o!==Ee){const n=await _(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ee} → ${o}`)),e=n,Ee=o)}}if(!e.ok)return Te(`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 🐼"):"")),Le=!0===e.aiEnabled,qe=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Se=await C(e.curriculumId||"LEARNDEMO01",Ee),!Se)return Te(`Could not open a learn curriculum for token '${Ee}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ee}`)+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 ${Ee}`)+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(!Se){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Te(`Could not reach the learn server to open ${Ee}.`),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 ${Ee}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Te(`Unknown learn token: ${Ee}`),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 We=K(),Re=!1;try{We&&We.token===Ee?X(We):(We=V(Ee,Se.id,Se.totalCards),Re=!0),Q(We),re(Se,We,Re)}catch{return Te("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 ${Ee}`)+chalk.gray(".")),void console.log()}const Ne=s(),Oe=null!==Ne,je=Oe?Ne.listeners("line").slice():[];Oe&&Ne.removeAllListeners("line");const De=Oe?Ne:o({input:process.stdin,output:process.stdout,terminal:!0}),Ye=Oe?De.prompt:null;Oe&&(De.prompt=e.prototype.prompt);const Ue=()=>{Oe&&Ye&&(De.prompt=Ye)},Fe=()=>{De.setPrompt(lo?chalk.bold.green(`icoa ${a()}> `):eo?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Xe?"icoa learn ai> ":"icoa learn> ")),De.prompt()};let ze=null,He=null,Be=null,Ze=null,Je=[],Ke=!1,Qe=null;const Ve=()=>{Qe&&clearTimeout(Qe),Qe=null,Je=[],Ke=!1,Ze=null};let Xe=!1,Ge=!1,eo=!1,oo=null,no=!1,to=0,ro=!1,lo=!1;const so=new Map,ao=()=>{let e=so.get(We.currentCard);return e||(e=[],so.set(We.currentCard,e)),e};let io=!1;const co=new Set;let go=!1,uo=0;const yo=()=>(z().language||"en").toLowerCase().startsWith("zh");fe(Le),$e(ke(z())),we(co);const mo=new Map;be(mo);const ho=[];let po=null;const fo=new Promise(e=>{po=e}),bo=()=>{const e=po;po=null,e?.()},wo="1"===process.env.ICOA_LEARN_EMBEDDED,$o=e=>Se.cards.find(o=>o.number===e);let ko=null,vo=null;const Ao=new Map,Co=!Ee.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ee),_o=async()=>{if(!Co)return;const e=await U(Ee);e.ok&&e.data&&(ko=e.data)},To=e=>{const o=Se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Io=e=>{if(!qe||!ko)return null;const o=To(e);if(o<=ko.unlocked_through_phase)return null;const n=ko.phases.find(e=>e.phase===ko.unlocked_through_phase),t=[chalk.yellow(yo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${ko.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${ko.unlocked_through_phase}'s core tasks first:`)];if(n?.contest&&!n.contest.passed){const e=n.contest.slots??[];if(e.length>0)for(const o of e)o.passed||t.push(chalk.gray(yo()?` ⚔ 练习赛 ${ko.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${ko.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else t.push(chalk.gray(yo()?` ⚖ 判分赛: 最好 ${n.contest.best_ac}/${n.contest.n} AC,需 ${n.contest.need} — 输入 `:` ⚖ contest: best ${n.contest.best_ac}/${n.contest.n} AC, need ${n.contest.need} — type `)+chalk.bold.green("contest"))}if(n?.checks?.enabled&&!n.checks.passed){const e=n.checks.missing??[],o=e.slice(0,8).join(yo()?"、":", "),r=e.length>8?yo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:yo()?" 张":"";t.push(chalk.gray(yo()?` ✓ 逐卡自测: ${n.checks.good}/${n.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${n.checks.good}/${n.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return n?.research&&!n.research.passed&&t.push(chalk.gray(yo()?` ⭐ 提问研究: ${n.research.good_cards}/${n.research.need_cards} 卡达到 ${n.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${n.research.good_cards}/${n.research.need_cards} cards at ${n.research.min_score}+ — research with /ai, then /submit`)),t.join("\n")},xo=async e=>qe?null===Io(e)?null:(await _o(),Io(e)):null;Co&&await _o();const Eo=async e=>{const o=Se.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Se.modules.find(e=>e.number===o.number+1);let t;if(Le){const e=await E({token:Ee,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}Co&&await _o();const r=ko?.phases.find(e=>e.phase===o.number);return he(Se,We,o,n,t,r),!0},So=()=>{go=!0,console.log(chalk.gray(yo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Po=()=>{oo=null;const e=$o(We.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":le(e,Se),e.check?(Be=e.number,uo=Date.now()):(G(We,e.number),Q(We));break;case"mcq":se(e,Se),ze=e.number;break;case"practical":ie(e,Se),He=e.number;break;case"sim_demo":de(e,Se),G(We,e.number),Q(We);break;case"milestone":ge(e,Se),te(We,e.badge),G(We,e.number),Q(We);break;case"arena_task":ue(e,Se),G(We,e.number),Q(We);break;case"coming_soon":ye(e,Se),G(We,e.number),Q(We)}Mo(e.number)},Mo=e=>{if(!Co||!ko)return;const o=Se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const n=e-o.cardRange[0]+1;if(n%4!=0)return;const t=n/4,r=ko.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===t);if(!l)return;const s=(e,o,n,t)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${o}:${String(n).padStart(2,"0")}`})(n),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${n(o.getMonth()+1)}-${n(o.getDate())} ${n(o.getHours())}:${n(o.getMinutes())}`})(t);return`🏆 ${e} ${o}/${l.n}`+(r?yo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Ae());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${yo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(yo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(yo()?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(yo()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),(l.carryable_ac??0)>0&&console.log(c+chalk.cyan(yo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(yo()?"✍ 第一次用 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(yo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(yo()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${t}`)+(l.passed?chalk.gray(yo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(yo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(yo()?" 继续学习":" keep going"):chalk.gray(yo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Lo=()=>{Ee.endsWith("DEMO01")?console.log(chalk.yellow(yo()?" 🐼 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(yo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(yo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},qo=async(e,o)=>{if(Le){Ge=!0;try{console.log(),console.log(chalk.gray("deep"===o?yo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":yo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await M({token:Ee,cardNumber:We.currentCard,question:e,mode:o,history:ao().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(t||(process.stdout.write(n?"\n\n ":" "),t=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||t)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(yo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(ao().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(` (${yo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(yo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Be&&console.log(chalk.gray(yo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ge=!1}}else Lo()},Wo=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ro=async()=>{eo&&vo?Ho?Bo(Ho):Uo():oo?await No():Po()},No=async()=>{Ge=!0;try{console.log();const e=await W({token:Ee,curriculumId:Se.id,cardNumber:We.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(yo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(yo()?` 🏆 本卡实时 Top-3 — 第 ${We.currentCard} 张`:` 🏆 Live top-3 — card ${We.currentCard}`)),e.board&&0!==e.board.length)for(const o of e.board){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(chalk.white(` ${o.icon} `)+chalk.bold.cyan(o.name||`Rank ${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(yo()?" (你)":" (you)"):""))}else console.log(chalk.gray(yo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(mo.set(We.currentCard,e.mine.rank),console.log(chalk.white(yo()?" 你: ":" You: ")+chalk.bold.yellow(yo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(yo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Le&&console.log(chalk.gray(yo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ce({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(yo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(yo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(yo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),oo="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 返回卡片":" returns to the card")),console.log()}finally{Ge=!1}},Oo=e=>yo()&&e.title_zh||e.title,jo=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of _e(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},Do=e=>{console.log(),console.log(chalk.bold.green(yo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 Linked — credit now carries both ways"));for(const o of e.members)console.log(chalk.gray(" · ")+chalk.white(o.curriculum_id)+chalk.gray(` ${o.token}`));console.log(chalk.gray(yo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Yo=e=>vo.data.solved.includes(e.id)?"✅":vo.data.carried?.includes(e.id)?"✅↗":vo.tried.has(e.id)?"❌":"⬜",Uo=()=>{const e=vo.data,o=F(e.deadline),n=(e.carried??[]).filter(o=>!e.solved.includes(o)),t=e.solved.length+n.length,r=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(yo()?` · 第 ${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(yo()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(yo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(yo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(yo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yo()?" 带过来,不必重做":" to carry them over instead of redoing them"));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(yo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(yo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(yo()?` 满血重开本组(${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)} `)+Yo(e)+chalk.white(` ${Oo(e)}`))}),console.log(),Fo()},Fo=()=>{console.log(chalk.gray(yo()?" /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(yo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 返回课程":" returns to the lesson")),console.log()},zo=e=>{const o=parseInt(e,10),n=vo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(yo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let Ho=null;const Bo=e=>{const o=zo(e);if(!o)return;const{p:n,n:t}=o;Ho=String(t),console.log(),console.log(chalk.bold.white(` ${Yo(n)} ${Oo(n)}`)),console.log();for(const e of(e=>yo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of _e(e,Ae()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of n.samples??[]){r+=1,console.log(),console.log(chalk.gray(yo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(yo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(n.samples??[]).length&&(console.log(),console.log(chalk.gray(yo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(yo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(yo()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${t}`.padEnd(11))+chalk.gray(yo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(yo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(yo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((yo()," ↩ "))+chalk.bold.green("back")+chalk.gray(yo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(yo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((yo()," / "))+chalk.bold.green("wide")+chalk.gray(yo()?" 换语言/宽度":" language / width")),console.log()},Zo=async(e,o)=>await new Promise(n=>{const t=process.stdin,l=!!t.isTTY&&!!t.isRaw;if(De.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:vo.dir}),a=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&l)try{t.setRawMode(!0)}catch{}De.resume(),n(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Jo=()=>{console.log(chalk.yellow(yo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(yo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(yo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(yo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Ko=new Map,Qo=async e=>{const o=e.trim().toLowerCase(),s=eo&&o.startsWith("/")?o.slice(1):o;if(Ge)return;if(null!==Ze){if(Je.push(e.replace(/\s+$/,"")),Qe&&clearTimeout(Qe),Qe=null,Ke){const e=Je[Je.length-1]??"";return"/cancel"===e.trim()?(Ve(),console.log(chalk.gray(yo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Fe()):""!==e.trim()?void Fe():(Je.pop(),void await a())}return void(Qe=setTimeout(()=>{if(Qe=null,Je.length>1){Ke=!0;const e=Je.length;return console.log(chalk.cyan(yo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(yo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Fe()}a()},140))}async function a(){const e=Je.join("\n").replace(/^\s+|\s+$/g,""),o=Ze??We.currentCard,n=Je.length;if(Ve(),""===e)console.log(chalk.gray(yo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(yo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(yo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(yo()?" 即可执行。":" again to run it."));else{const t=uo>0?Date.now()-uo:void 0;if(await I(Ee,{curriculum_id:Se.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const e=n>1?yo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(yo()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(yo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Fe()}if(no){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return no=!1,console.log(),console.log(chalk.yellow(yo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(yo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(yo()?" 即可执行该命令。":" again to run it.")),console.log(),void Fe();if(!o)return no=!1,console.log(chalk.gray(yo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Fe();const n=await P({token:Ee,nickname:o});if(n.ok)no=!1,console.log(chalk.bold.green(yo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(yo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{to+=1;const e="taken"===n.code?yo()?"已被占用":"already taken":"bad_charset"===n.code?yo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?yo()?"未通过审核":"did not pass review":n.message||"error";if(!(to>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Fe();no=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Fe()}if(io){io=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ge=!0;try{console.log(),console.log(chalk.gray(yo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await L({token:Ee,cardNumber:We.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(yo()?"评审暂不可用。":"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(yo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(yo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(yo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(yo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(yo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(yo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=yo()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(yo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(yo()?` 第 ${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 Wo(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(yo()?" 改进提问: ":" 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(` (${yo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?co.add(We.currentCard):co.delete(We.currentCard),"number"==typeof e.rank&&mo.set(We.currentCard,e.rank);const o=await W({token:Ee,curriculumId:Se.id,cardNumber:We.currentCard});o.ok&&o.totals&&o.chapters&&(Ce({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Pe&&(no=!0,to=0,console.log(chalk.bold.yellow(yo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(yo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(yo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Ge=!1}})():(console.log(chalk.gray(yo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Be&&(console.log(chalk.gray(yo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Fe()}if(go)return go=!1,Po(),void Fe();if(!o)return void Fe();if(lo)return"exit"===await i(e.trim())&&(lo=!1),void Fe();if(Xe){if(["q","quit","exit","back","b","menu"].includes(o))return Xe=!1,console.log(chalk.gray(yo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Fe();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim();return t&&(await qo(t,n?"fast":"deep"),console.log(chalk.gray(yo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Fe()}if(eo&&vo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${vo.phase}s${vo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return eo=!1,console.log(chalk.gray(yo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Po(),void Fe();if(/^\d+$/.test(o))return Bo(o),void Fe();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,t]=e;return"list"===o?Uo():t?"read"===o||"open"===o?Bo(t):"edit"===o?await(async e=>{const o=zo(e);if(!o)return;const n=v(vo.dir,`sol-${o.n}.py`);if(B())return Z()?(console.log(chalk.yellow(yo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(yo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(yo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(yo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(yo()?" ← 不能是 /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(yo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(yo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(yo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(yo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(yo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(yo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(yo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(yo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!J("vi"))return console.log(chalk.yellow(yo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(yo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(yo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return h(e).size}catch{return 0}},r=t(n),l=Date.now();await Zo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),Ao.set(o.n,b(Ao.get(o.n)??f(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(yo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(yo()?" 自测样例。":" to self-check the sample.")),console.log()})(t):"run"===o?(e=>{const o=zo(e);if(!o)return;const{p:t,n:r}=o,l=v(vo.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(yo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Ao.set(r,$(Ao.get(r)??f()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(yo()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=n("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)Jo();else if(o.killed)console.log(chalk.yellow(yo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(yo()?" ✗ 程序报错:":" ✗ 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(yo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(yo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(yo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(yo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(yo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(yo()?" 改完再 /run。":" then /run again.")),console.log()})(t):"debug"===o?await(async e=>{const o=zo(e);if(!o)return;const n=v(vo.dir,`sol-${o.n}.py`);if(!d(n))return void console.log(chalk.yellow(yo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(yo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const t=await Zo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(yo()?" 回到竞技场。":" Back in the arena.")),console.log()):Jo()})(t):"recall"===o&&await(async e=>{const o=zo(e);if(!o)return;if(!Le)return void Lo();const{p:n,n:t}=o,r=v(process.cwd(),"icoa-contest"),l=`${Se.id}-phase${vo.phase}-g${vo.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-${t}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(yo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${vo.phase}-${vo.data.slot}-${t}`,g=Math.min(3,(Ko.get(c)??0)+1);console.log(chalk.gray(yo()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await S({token:Ee,phase:vo.phase,slot:vo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:g,lang:yo()?"zh":"en"});if(m.ok){Ko.set(c,g),console.log();for(const e of _e(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(yo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(yo()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(yo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(t):console.log(chalk.yellow(yo()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(yo()?" (花名册: /list)":" (roster: /list)")),void Fe()}if("contest"===o||"/contest"===o)return Uo(),void Fe();const t="lang"===o||/^lang\s+\S+$/.test(o),r=Ie.has(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||t||r||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(yo()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Fe()}if("tmux"===o||o.startsWith("tmux ")){try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(yo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Fe()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(De.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&t)try{n.setRawMode(!0)}catch{}De.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Fe()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(lo=!0),void Fe();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Le)return Lo(),void Fe();ro||(ro=!0,console.log(),console.log(chalk.bold.cyan(yo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(yo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(yo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),yo()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const n=o.startsWith("/ai!"),t=e.trim().slice(n?4:3).trim();if(!t){Xe=!0;const e=$o(We.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(yo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(yo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Fe()}return await qo(t,n?"fast":"deep"),void Fe()}if(!eo&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Le)return Lo(),void Fe();const e=$o(We.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(yo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(yo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(yo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(yo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(yo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(yo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),io=!0,void Fe()}const _=!eo&&"honors"===oo&&/^[1-3]$/.test(o);if(!eo&&oo&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(yo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(yo()?" ↩ back 回上一层":" ↩ back goes up one level")),void Fe();if(!eo&&(_||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Le)return Lo(),void Fe();const e=/^\/?view ([1-3])$/.exec(o),n=_?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Ge=!0;try{console.log();const o=await q({token:Ee,cardNumber:We.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(yo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&co.delete(We.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&co.add(We.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(yo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${We.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${We.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(yo()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of n){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(yo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=Wo(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(yo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),oo="view",console.log(chalk.gray((yo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Ge=!1}})(n),void Fe()}if("/honors"===o||"honors"===o)return Pe?(console.log(),console.log(chalk.gray(yo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Fe()):(await No(),void Fe());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return me(Se,We),void Fe();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await C(Se.id,Ee,!0);return void(e?(Object.assign(Se,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Po()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本")),Fe()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(z().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Fe();const n=Se.cards.some(e=>null!=e._zh),t=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===t||"zh"===t&&n,l=r?t:"en";return H({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Be=null,ze=null,He=null,Ve(),go=!1,io=!1,await Ro(),void Fe()}if(Ie.has(o)){const e=Ie.get(o),n=ke(z()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return yo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((yo()?"normal"===e?" 已是标准 64 列。":Ae()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Ae()} 列,上限 ${ve(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Ae()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Ae()} cols, cap ${ve(e)}). `)+t(e))),void Fe()):(H({learnWidth:e,learnWide:"normal"!==e}),$e(e),"normal"!==e&&Ae()<=64?(console.log(chalk.yellow(yo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((yo()?` 设置已记住(${e},上限 ${ve(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${ve(e)} cols) and applies once you widen the window. `)+t(e))),void Fe()):(console.log(chalk.green(" ✓ ")+chalk.gray((yo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Ae()} 列,上限 ${ve(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Ae()} cols, cap ${ve(e)}). `)+t(e))),Be=null,ze=null,He=null,Ve(),go=!1,io=!1,await Ro(),void Fe()))}if("sim"===o){const e=$o(We.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=k(A(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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--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 Fe()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Fe())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=We.currentCard,n=We.bookmarks.includes(e),t="bookmark"!==o;return t?We.bookmarks=We.bookmarks.filter(o=>o!==e):n||We.bookmarks.push(e),Q(We),t?console.log(n?chalk.gray(yo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(yo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(yo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(yo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Fe()}if("e"===o)return Ze=We.currentCard,console.log(chalk.gray(yo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void Fe();if("back"===o||"b"===o)return"view"===oo?(await No(),void Fe()):"honors"===oo?(oo=null,Po(),void Fe()):(We.currentCard>1&&(We.currentCard-=1),ze=null,He=null,Be=null,Q(We),Po(),void Fe());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Co)return console.log(chalk.yellow(yo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Fe();if(!e){const e=await D(Ee),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(yo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(yo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(yo()?` 这台电脑上有 ${o.length} 个你的 token 还没关联:`:` ${o.length} token${1===o.length?"":"s"} of yours on this computer `+(1===o.length?"is":"are")+" not linked yet:"));for(const e of o)console.log(chalk.bold.green(` ${e.index}. `)+chalk.white(e.curriculum_id.padEnd(12))+chalk.gray(e.token)+(e.carry_problems>0?chalk.cyan(yo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(yo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(yo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(yo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(yo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(yo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(yo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Fe()}if(/^\d{1,2}$/.test(e)){const o=await j(Ee,Number(e));return o.ok&&o.data?(Do(o.data),await _o(),void Fe()):(console.log(chalk.red(` ✗ ${o.message||(yo()?"关联失败":"Link failed")}`)),void Fe())}const n=await Y(Ee,e);return n.ok&&n.data?(Do(n.data),await _o(),void Fe()):(console.log(chalk.red(` ✗ ${n.message||(yo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(yo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Fe())}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(!Co)return console.log(chalk.yellow(yo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Fe();const e=To(We.currentCard);if("contest reset"===o){const o=await R(Ee,e);if(o.ok){console.log(chalk.yellow(yo()?` 已放弃当前计时(阶段 ${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 n=1;n<=3;n++){const t=v(process.cwd(),"icoa-contest",`${Se.id}-phase${e}-g${n}`);if(d(t))try{m(t,`${t}-archived-${o}`),console.log(chalk.gray(yo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(yo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(yo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),vo=null,eo=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Fe()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(yo()?" 连接判分赛…":" Contacting contest server…"));const t=await N(Ee,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(yo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void Fe();const r=t.data,l=v(process.cwd(),"icoa-contest",`${Se.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=vo&&vo.phase===e&&vo.data.slot===r.slot?vo.tried:new Set;vo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.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"} · ${n.title} ══`,"#",...jo(n.statement,72)];if(n.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),eo=!0,Uo(),console.log(chalk.gray(yo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(yo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(yo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Fe()}if("submit"===s)return console.log(chalk.yellow(yo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(yo()?" 例如 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)")),vo||console.log(chalk.gray(yo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Fe();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const n=e[2];if(!vo)return console.log(chalk.yellow(yo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Fe();const t=vo.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=t.length&&!t.some(e=>e.id===o)&&(o=t[r-1].id),!t.some(e=>e.id===o))return console.log(chalk.yellow(yo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Fe();const l=t.findIndex(e=>e.id===o)+1,a=n||v(vo.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(yo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Fe()}console.log(chalk.gray(yo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Ao.get(l),d=await O(Ee,vo.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(yo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((yo()," "))+chalk.bold.green("contest")+chalk.gray(yo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void Fe();const g=d.data;if(g.already_ac)console.log(chalk.green(yo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(yo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(yo()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),vo.data.solved.includes(o)||vo.data.solved.push(o),vo.tried.delete(o);else{vo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?yo()?` · 挂在第 ${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(yo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=F(g.deadline||"");if(console.log(chalk.white(yo()?` 本组进度: 已过 ${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(yo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await _o();else if(!g.late){const e=t.findIndex(e=>!vo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(yo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Oo(t[e])}`))}return void Fe()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Se.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Se.totalCards}. Try: `)+chalk.bold.green("card 1")),void Fe();const t=await xo(n);return t?(console.log(t),void Fe()):(We.currentCard=n,ze=null,He=null,Be=null,Q(We),Po(),void Fe())}if(null!==Be&&["y","yes","n","no"].includes(o)){const e=$o(Be);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-uo;G(We,e.number),oe(We,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),Q(We);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),ho.push(T(Ee,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),Be=null,e.solution&&e.solution.length>0)return void Fe();if(We.currentCard<Se.totalCards){const e=We.currentCard,o=await xo(e+1);if(o)return await Eo(e),console.log(o),void Fe();We.currentCard+=1,Q(We),await Eo(e)?So():Po(),Fe()}else pe(Se,We),Fe();return}}if(null!==ze&&["a","b","c","d"].includes(o)){const e=$o(ze);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(ee(We,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),G(We,e.number),Q(We),ae(e,n,t,We),ho.push(T(Ee,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),ze=null,t)if(We.currentCard<Se.totalCards){const e=await xo(We.currentCard+1);if(e)return console.log(e),void Fe();We.currentCard+=1,Q(We),Po()}else pe(Se,We),Fe();else Fe();return}}if(null!==He){if("done"===o){const e=$o(He);if(e&&"practical"===e.type)return ne(We,e.number),G(We,e.number),Q(We),ce(e),He=null,void Fe()}if("skip"===o)return G(We,He),Q(We),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),He=null,void Fe()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ze)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Fe();if(null!==He)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Fe();if(null!==Be)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Fe();const e=We.currentCard,o=e<Se.totalCards?await xo(e+1):null;return o?(await Eo(e),console.log(o),void Fe()):(We.currentCard+=1,Q(We),We.currentCard>Se.totalCards?pe(Se,We):await Eo(e)?So():Po(),void Fe())}if(null!==Be)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Fe();if(null!==ze)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Fe();if(null!==He)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Fe();"view"===oo?console.log(chalk.gray(yo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(yo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(yo()?" 回卡片":" to the card")):"honors"===oo?console.log(chalk.gray(yo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(yo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(yo()?" 回卡片":" 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")),Fe()}else{if("view"===oo)return await No(),void Fe();if("honors"===oo)return oo=null,Po(),void Fe();if(ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${We.streakDays} day(s)`)),console.log(),Oe){De.removeAllListeners("line"),Ue();for(const e of je)De.on("line",e);De.prompt(),bo()}else De.removeAllListeners("line"),De.close()}else if(ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,3e3))]),De.removeAllListeners("line"),Ue(),Oe||!wo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Oe?De:void 0),bo()}else De.close()};De.on("line",e=>{Qo(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.")),Fe()})}),Oe||De.on("close",async()=>{ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,5e3))]),wo?bo():process.exit(0)});try{Po(),Fe();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Te("Could not render this card — the curriculum may be malformed."),Oe){De.removeAllListeners("line"),Ue();for(const e of je)De.on("line",e);De.prompt()}else De.close();bo()}await fo}),xe.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await C(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
@@ -213,7 +213,7 @@ export declare function getLastCurriculumFailure(): 'notfound' | 'offline' | nul
213
213
  * 3. Stale cache as fallback → if server unreachable but cache exists
214
214
  * 4. null → no cache, no server
215
215
  */
216
- export declare function loadCurriculumById(id: string, token?: string): Promise<Curriculum | null>;
216
+ export declare function loadCurriculumById(id: string, token?: string, force?: boolean): Promise<Curriculum | null>;
217
217
  /**
218
218
  * Server-side validation for EAxxxxxxxx tokens.
219
219
  * Returns curriculum identifier + status; the actual cards are still
@@ -1 +1 @@
1
- export function localized(r,t){if(!t.startsWith("zh")||!r._zh)return r;const e=r._zh,n={...r};for(const r of Object.keys(e))void 0!==e[r]&&(n[r]=e[r]);return n}export function isValidCurriculum(r){if(!r||"object"!=typeof r)return!1;const t=r;return"string"==typeof t.id&&"number"==typeof t.totalCards&&Array.isArray(t.cards)&&Array.isArray(t.modules)}import{readFileSync as r,writeFileSync as t,mkdirSync as e,existsSync as n,statSync as a,utimesSync as c}from"node:fs";import{join as i}from"node:path";import{homedir as o}from"node:os";import{getDeviceFingerprint as u}from"./access.js";import{getCliVersion as s}from"./version.js";import{httpFetch as d}from"./http.js";const l=i(o(),".icoa","learn-cache");export const LEARN_SERVER="https://practice.icoa2026.au";function m(r){const t=r.replace(/[^A-Za-z0-9_-]/g,"_");return i(l,`${t}.json`)}function f(r){const t=r.replace(/[^A-Za-z0-9_-]/g,"_");return i(l,`${t}.etag`)}let p=null;export function getLastCurriculumFailure(){return p}export async function loadCurriculumById(i,o){"ctf4eai-12"===i&&(i="LEARNDEMO01");const u=function(t){const e=m(t);if(!n(e))return null;try{const t=a(e),n=Date.now()-t.mtimeMs;return{curriculum:JSON.parse(r(e,"utf-8")),ageMs:n}}catch{return null}}(i);if(u&&u.ageMs<6048e5&&isValidCurriculum(u.curriculum))return u.curriculum;p=null;const d=await async function(t,e){const a=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/curriculum/"+encodeURIComponent(t),c={},i=function(t){const e=f(t);if(!n(e))return null;try{return r(e,"utf-8").trim()||null}catch{return null}}(t);i&&(c["If-None-Match"]=i),e&&(c["X-Learn-Token"]=e.toUpperCase()),c["X-ICOA-Client"]=s();try{const r=await fetch(a,{headers:c,signal:AbortSignal.timeout(6e4)});if(304===r.status)return{kind:"unchanged"};if(404===r.status)return{kind:"notfound"};if(!r.ok)return{kind:"error"};const t=await r.json();if(!t.success||!t.data)return{kind:"error"};if(!isValidCurriculum(t.data))return{kind:"error"};const e=r.headers.get("etag")||r.headers.get("ETag")||void 0;return{kind:"fresh",curriculum:t.data,etag:e||void 0}}catch{return{kind:"error"}}}(i,o);return"fresh"===d.kind?(function(r,n,a){try{e(l,{recursive:!0}),t(m(r),JSON.stringify(n)),a&&t(f(r),a)}catch{}}(i,d.curriculum,d.etag),d.curriculum):"unchanged"===d.kind&&u&&isValidCurriculum(u.curriculum)?(function(r){try{const t=m(r);if(n(t)){const r=Date.now()/1e3;c(t,r,r)}}catch{}}(i),u.curriculum):u&&isValidCurriculum(u.curriculum)?u.curriculum:(p="notfound"===d.kind?"notfound":"offline",null)}export async function validateEAToken(r){const t=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/validate";try{const e=await d(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r.toUpperCase(),device_fingerprint:u()}),signal:AbortSignal.timeout(8e3)});if(!e.ok){const r=await e.json().catch(()=>({}));return{ok:!1,message:r.message||`HTTP ${e.status}`,code:r.code}}const n=await e.json();return n.success&&n.data?{ok:!0,curriculumId:n.data.curriculum_id,status:n.data.status,validUntil:n.data.valid_until,aiEnabled:1===n.data.ai_enabled||!0===n.data.ai_enabled,gated:1===n.data.gated||!0===n.data.gated}:{ok:!1,message:n.message||"Validation failed"}}catch(r){return{ok:!1,message:`Network error: ${r instanceof Error?r.message:String(r)}`}}}export async function syncProgress(r,t){if("LEARNDEMO01"===r.toUpperCase())return;const e=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/progress/"+r.toUpperCase();try{await d(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({card_number:t.card_number,event_type:t.event_type,mcq_answer:t.mcq_answer,mcq_correct:t.mcq_correct?1:0,check_answer:t.check_answer,check_correct:t.check_correct?1:0,time_on_card_ms:t.time_on_card_ms,device_fingerprint:u()}),signal:AbortSignal.timeout(5e3)})}catch{}}export async function syncCardFeedback(r,t){const e=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/feedback/"+r.toUpperCase();try{return(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({curriculum_id:t.curriculum_id,card_number:t.card_number,feedback_text:t.feedback_text,time_on_card_ms:t.time_on_card_ms}),signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}
1
+ export function localized(r,t){if(!t.startsWith("zh")||!r._zh)return r;const e=r._zh,n={...r};for(const r of Object.keys(e))void 0!==e[r]&&(n[r]=e[r]);return n}export function isValidCurriculum(r){if(!r||"object"!=typeof r)return!1;const t=r;return"string"==typeof t.id&&"number"==typeof t.totalCards&&Array.isArray(t.cards)&&Array.isArray(t.modules)}import{readFileSync as r,writeFileSync as t,mkdirSync as e,existsSync as n,statSync as a,utimesSync as c}from"node:fs";import{join as i}from"node:path";import{homedir as o}from"node:os";import{getDeviceFingerprint as u}from"./access.js";import{getCliVersion as s}from"./version.js";import{httpFetch as d}from"./http.js";const l=i(o(),".icoa","learn-cache");export const LEARN_SERVER="https://practice.icoa2026.au";function m(r){const t=r.replace(/[^A-Za-z0-9_-]/g,"_");return i(l,`${t}.json`)}function f(r){const t=r.replace(/[^A-Za-z0-9_-]/g,"_");return i(l,`${t}.etag`)}let p=null;export function getLastCurriculumFailure(){return p}export async function loadCurriculumById(i,o,u=!1){"ctf4eai-12"===i&&(i="LEARNDEMO01");const d=function(t){const e=m(t);if(!n(e))return null;try{const t=a(e),n=Date.now()-t.mtimeMs;return{curriculum:JSON.parse(r(e,"utf-8")),ageMs:n}}catch{return null}}(i);if(!u&&d&&d.ageMs<6048e5&&isValidCurriculum(d.curriculum))return d.curriculum;p=null;const _=await async function(t,e){const a=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/curriculum/"+encodeURIComponent(t),c={},i=function(t){const e=f(t);if(!n(e))return null;try{return r(e,"utf-8").trim()||null}catch{return null}}(t);i&&(c["If-None-Match"]=i),e&&(c["X-Learn-Token"]=e.toUpperCase()),c["X-ICOA-Client"]=s();try{const r=await fetch(a,{headers:c,signal:AbortSignal.timeout(6e4)});if(304===r.status)return{kind:"unchanged"};if(404===r.status)return{kind:"notfound"};if(!r.ok)return{kind:"error"};const t=await r.json();if(!t.success||!t.data)return{kind:"error"};if(!isValidCurriculum(t.data))return{kind:"error"};const e=r.headers.get("etag")||r.headers.get("ETag")||void 0;return{kind:"fresh",curriculum:t.data,etag:e||void 0}}catch{return{kind:"error"}}}(i,o);return"fresh"===_.kind?(function(r,n,a){try{e(l,{recursive:!0}),t(m(r),JSON.stringify(n)),a&&t(f(r),a)}catch{}}(i,_.curriculum,_.etag),_.curriculum):"unchanged"===_.kind&&d&&isValidCurriculum(d.curriculum)?(function(r){try{const t=m(r);if(n(t)){const r=Date.now()/1e3;c(t,r,r)}}catch{}}(i),d.curriculum):d&&isValidCurriculum(d.curriculum)?d.curriculum:(p="notfound"===_.kind?"notfound":"offline",null)}export async function validateEAToken(r){const t=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/validate";try{const e=await d(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r.toUpperCase(),device_fingerprint:u()}),signal:AbortSignal.timeout(8e3)});if(!e.ok){const r=await e.json().catch(()=>({}));return{ok:!1,message:r.message||`HTTP ${e.status}`,code:r.code}}const n=await e.json();return n.success&&n.data?{ok:!0,curriculumId:n.data.curriculum_id,status:n.data.status,validUntil:n.data.valid_until,aiEnabled:1===n.data.ai_enabled||!0===n.data.ai_enabled,gated:1===n.data.gated||!0===n.data.gated}:{ok:!1,message:n.message||"Validation failed"}}catch(r){return{ok:!1,message:`Network error: ${r instanceof Error?r.message:String(r)}`}}}export async function syncProgress(r,t){if("LEARNDEMO01"===r.toUpperCase())return;const e=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/progress/"+r.toUpperCase();try{await d(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({card_number:t.card_number,event_type:t.event_type,mcq_answer:t.mcq_answer,mcq_correct:t.mcq_correct?1:0,check_answer:t.check_answer,check_correct:t.check_correct?1:0,time_on_card_ms:t.time_on_card_ms,device_fingerprint:u()}),signal:AbortSignal.timeout(5e3)})}catch{}}export async function syncCardFeedback(r,t){const e=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/feedback/"+r.toUpperCase();try{return(await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({curriculum_id:t.curriculum_id,card_number:t.card_number,feedback_text:t.feedback_text,time_on_card_ms:t.time_on_card_ms}),signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}
@@ -1 +1 @@
1
- import chalk from"chalk";import o from"string-width";import{localized as e}from"./learn-curricula.js";import{t as n}from"./learn-i18n.js";import{getConfig as t}from"./config.js";import{icoaBannerLines as l}from"./banner.js";import{renderCharts as r,detectCaps as a}from"./render-card.js";function s(){return(t().language||"en").toLowerCase()}let c="normal";export function resolveLearnWidth(o){return"normal"===o.learnWidth||"wide"===o.learnWidth||"wider"===o.learnWidth?o.learnWidth:o.learnWide?"wide":"normal"}export function setLearnWidth(o){c=o}export function learnWidthCap(o=c){return"wider"===o?120:"wide"===o?96:64}export function learnW(){if("normal"===c)return 64;const o=process.stdout.columns||64;return Math.max(64,Math.min(o-6,learnWidthCap()))}const g=learnW;function i(o="─"){return o.repeat(g()+2)}function d(o,e,n=20){const t=e>0?o/e:0,l=Math.floor(t*n),r=n-l;return`${chalk.green("█".repeat(l))+chalk.gray("░".repeat(r))} ${(100*t).toFixed(1)}%`}function y(o){return o>=30?chalk.red("🔥🔥🔥 "+o+" days"):o>=7?chalk.yellow("🔥 "+o+" days"):o>=1?chalk.gray("· "+o+" day"+(o>1?"s":"")):chalk.gray("—")}export function renderWelcome(o,e,t){const l=s(),r=e.cardsCompleted.length,a=o.totalCards,c=a-r,g=o.modules.find(o=>e.currentCard>=o.cardRange[0]&&e.currentCard<=o.cardRange[1]),u=/demo/i.test(o.id);if(console.log(),console.log(chalk.cyan(" ╭"+i("═"))),console.log(chalk.cyan(" ║")),console.log(chalk.cyan(" ║ ")+chalk.bold.white(" "+(o.name?.trim()||n("academy_title",l)))),console.log(chalk.cyan(" ║")),t)console.log(chalk.cyan(" ║ ")+chalk.white(" "+n(u?"welcome_new_demo":"welcome_new",l)));else{const o=new Date(e.lastSeenAt),t=Math.floor((Date.now()-o.getTime())/36e5),r=t<1?n("just_now",l):t<24?`${t}${n("ago_hours",l)}`:`${Math.floor(t/24)}${n("ago_days",l)}`;console.log(chalk.cyan(" ║ ")+chalk.white(` ${n("welcome_back",l)} ${r}`))}console.log(chalk.cyan(" ║"));const h=g?`${g.number}. ${g.name}`:"—";console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("module",l).padEnd(11))+chalk.white(h)),console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("progress",l).padEnd(11))+d(r,a)+chalk.gray(` (${r}/${a})`)),console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("streak",l).padEnd(11))+y(e.streakDays)),c>0&&e.currentCard<=a&&console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("next_card",l).padEnd(11))+chalk.white(`#${e.currentCard} ${n("of",l)} ${a}`)),console.log(chalk.cyan(" ║")),console.log(chalk.cyan(" ╰"+i("═"))),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const m=0===r?n("continue_start",l):`${n("continue_resume",l)} ${e.currentCard}`;console.log(chalk.bold.green(" continue")+chalk.gray(" "+m)),console.log(chalk.yellow(" status")+chalk.gray(" "+n("status_full",l))),e.bookmarks.length>0&&console.log(chalk.yellow(" bookmarks")+chalk.gray(` ${e.bookmarks.length} ${n("bookmarks_desc",l)}`)),console.log(chalk.gray(" quit")+chalk.gray(" "+n("quit_desc",l))),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log()}function u(o,e){const t=s(),l=o.module,r=e.modules.find(o=>o.number===l),a=r?r.name:n("unknown_module",t),c=n("module",t).replace(":","").trim(),i=`${n("card",t)} ${o.number} / ${e.totalCards} · ${c} ${l} · ${a}`;console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(i)+" "+chalk.cyan("─".repeat(Math.max(0,g()-i.length-4))))}function h(){console.log(chalk.cyan(" ╰"+i())),console.log()}function m(o){console.log(chalk.cyan(" │ ")+chalk.white(o))}function b(){console.log(chalk.cyan(" │"))}const p=/[┌┐└┘├┤┬┴┼─│╔╗╚╝═║╠╣╦╩╬▓▒░█]/;function f(o){return/^(?: {4}|\t)/.test(o)||p.test(o)||/ {3,}/.test(o)}export function wrapMixed(e,n){const t=[];let l="",r=0,a=!1;for(const s of function(e){const n=[],t=e=>{let t="";const l=()=>{t&&(n.push({t:"atom",s:t}),t="")};for(const r of e)" "===r?(l(),n.push({t:"space"})):2===o(r)?(l(),n.push({t:"wide",s:r})):t+=r;l()},l=/`[^`]*`/g;let r,a=0;for(;null!==(r=l.exec(e));)t(e.slice(a,r.index)),n.push({t:"code",s:r[0]}),a=r.index+r[0].length;return t(e.slice(a)),n}(e)){if("space"===s.t){""!==l&&(a=!0);continue}const e=s.s,c=o("code"===s.t?e.replace(/`/g,""):e),g=a?1:0,i="atom"===s.t&&e.length<=2&&/^[.,;:!?)\]}…'"]+$/.test(e);""!==l&&!i&&r+g+c>n?(t.push(l),l=e,r=c,a=!1):(a&&(l+=" ",r+=1,a=!1),l+=e,r+=c)}return l&&t.push(l),t}const $=/\b(?:Common bug|Common mistake|Common error|Pitfall|Gotcha|Footgun)\b[::]?|\b(?:Warning|Caution)\b[::]|(?:常见错误|常见陷阱|常见误区|陷阱|注意|警告|误区)[::]/gi;function w(o,e){const n=e?chalk.bold.white:chalk.white;let t,l="",r=0;for($.lastIndex=0;null!==(t=$.exec(o));)t.index>r&&(l+=n(o.slice(r,t.index))),l+=chalk.bold.yellow(t[0]),r=t.index+t[0].length;return r<o.length&&(l+=n(o.slice(r))),l}function _(o,e=!1){let n="",t=0;const l=/`([^`]*)`/g;let r;for(;null!==(r=l.exec(o));)r.index>t&&(n+=w(o.slice(t,r.index),e)),n+=chalk.cyan(r[1]),t=r.index+r[0].length;return t<o.length&&(n+=w(o.slice(t),e)),n}function k(o,e=!1){let n=!1;for(const t of o.split("\n"))if(/^\s*```/.test(t))n=!n;else if(n)console.log(chalk.cyan(" │ ")+chalk.cyan(` ${t}`));else if(""!==t)if(f(t))console.log(chalk.cyan(" │ ")+chalk.white(t));else for(const o of wrapMixed(t,g()-4))console.log(chalk.cyan(" │ ")+` ${_(o,e)}`);else b()}function x(o,e){const n=[];for(const t of o.split("\n")){if(""===t){n.push("");continue}if(f(t)){n.push(t);continue}let o="";for(const l of t.split(" "))(o+" "+l).trim().length>e?(n.push(o.trim()),o=l):o=(o+" "+l).trim();o&&n.push(o)}return n}let C=!1;export function setLearnAiEnabled(o){C=o}let M=new Set;export function setLearnPqsViewCards(o){M=o}let v=new Map;export function setLearnHonorRanks(o){v=o}const W=["①","②","③","④","⑤","⑥","⑦","⑧","⑨","⑩"];export function renderHonorWall(o){const e=s().startsWith("zh"),{totals:n,chapters:t}=o,l=n.gold+n.silver+n.bronze,r=(o,e)=>e>0?chalk.bold.white(`${o}×${e}`):chalk.gray(`${o}×0`);if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.bold.white(e?" 🏅 奖牌墙 ":" 🏅 Medal wall ")+r("🥇",n.gold)+chalk.gray(" · ")+r("🥈",n.silver)+chalk.gray(" · ")+r("🥉",n.bronze)+chalk.gray(e?" (永久 — 挂上墙就不会摘下)":" (permanent — once earned, never removed)")),0===l){const n=null!=o.floor?`${o.floor}+`:e?"高分":"a high score";return console.log(chalk.gray(e?` 还没有奖牌 — 单卡提问评分 ${n} 并进入该卡前三,即可永久挂墙 🥇🥈🥉`:` No medals yet — score ${n} on a card and hold its top-3 to hang one 🥇🥈🥉`)),void console.log(chalk.gray(" ─────────────────────────────────────────"))}const a=t.map(o=>{const e=`Ch${o.chapter}`,n=(o.gold>0?`🥇${o.gold}`:"")+(o.silver>0?`🥈${o.silver}`:"")+(o.bronze>0?`🥉${o.bronze}`:"");return n?chalk.white(`${e} ${n}`):chalk.gray(`${e} —`)}).join(chalk.gray(" "));console.log(" "+a);const c=t.flatMap(o=>o.cards.map(e=>({...e,chapter:o.chapter})));c.sort((o,e)=>o.rank-e.rank||o.chapter-e.chapter||o.card-e.card);for(const o of c.slice(0,24)){const n=(o.since||"").slice(0,10);console.log(chalk.white(` ${o.icon} `)+chalk.gray(`Ch${o.chapter} · `)+chalk.white(e?`第 ${o.card} 张`:`card ${o.card}`)+chalk.gray(` · ${o.score}`)+(n?chalk.gray(e?` · 始于 ${n}`:` · since ${n}`):""))}c.length>24&&console.log(chalk.gray(e?` …还有 ${c.length-24} 枚`:` …and ${c.length-24} more`)),console.log(chalk.gray(" ─────────────────────────────────────────"))}export function renderKnowledgeCard(t,l){const i=s(),d=e(t,i);u(d,l),b();const y=wrapMixed(d.title,g()-4);for(const o of y)m(chalk.bold.yellow(o));m(chalk.gray("─".repeat(Math.min(Math.max(...y.map(e=>o(e))),g()))));const p=!!(t.chart_ids&&t.chart_ids.length>0);if(p&&r(t.chart_ids.slice(0,1),l.charts,a()),d.key_point&&""!==d.key_point.trim()?(p||b(),function(o,e,n){const t=s().startsWith("zh"),l=a().cols,r="-".repeat(Math.min(g(),Math.max(24,l-6))),c=t?"要点":"KEY POINT",i=t?`第 ${e} / ${n} 张`:`Card ${e} / ${n}`;console.log(chalk.cyan(" │ ")+chalk.green(r)),console.log(chalk.cyan(" │ ")+chalk.green(`${c} · ${i}`));for(const e of wrapMixed(o,g()-4))console.log(chalk.cyan(" │ ")+chalk.bold.green(" "+e));console.log(chalk.cyan(" │ ")+chalk.green(r)),b()}(d.key_point,d.number,l.totalCards)):p||b(),d.body.filter(o=>null!=o&&""!==o.trim()).forEach((o,e)=>{const n=0===e?o.match(/^([\s\S]*?(?:[.!?](?=\s|$)|[。!?]))(\s[\s\S]*)?$/):null;if(n&&n[1].trim().length<=180){k(n[1],!0);const o=n[2]?.trimStart();o&&k(o,!1)}else k(o,!1);b()}),d.icoaConnection){m(chalk.magenta(" "+n("icoa_connection",i))),m(chalk.gray(" "+"─".repeat(20)));for(const o of wrapMixed(d.icoaConnection,g()-4))m(" "+chalk.magenta(o));b()}if(t.check){const o=i.startsWith("zh"),e=t._zh?.checkStatement??t._zh?.check?.statement,n=o?e??t.check.statement:t.check.statement;m(chalk.cyan(" 🤔 "+(o?"请回答 (输 y 或 n):":"Quick comprehension check (type y or n):"))),m(chalk.gray(" "+"─".repeat(20)));for(const o of wrapMixed(n,g()-4))m(" "+chalk.white(o));b()}h(),function(e,n){const t=s().startsWith("zh"),l=a().cols,r="-".repeat(Math.min(g(),Math.max(24,l-6))),i=chalk.gray(" "),d=[];e.check?(d.push(chalk.bold.green("[y]")+chalk.gray(t?" 是":" yes")),d.push(chalk.bold.green("[n]")+chalk.gray(t?" 否":" no"))):d.push(chalk.bold.green("[ok]")+chalk.gray(t?" 继续":" next")),C&&(d.push(chalk.bold.magenta("[/ai]")+chalk.gray(t?" 🐼 熊猫导师":" 🐼 Panda tutor")),d.push(chalk.bold.magenta("[/submit]")+chalk.gray(t?" 提问评分":" prompt score")));const y=v.get(e.number);var u;d.push(chalk.bold.magenta(y?`[/honors ${u=y,W[u-1]??`#${u}`}]`:"[/honors]")+chalk.gray(t?" 排行":" board")),"normal"===c?d.push(chalk.bold.cyan("[wide]")+chalk.gray(t?" 宽屏":" widen")):(d.push("wide"===c?chalk.bold.cyan("[wider]")+chalk.gray(t?" 更宽":" wider"):chalk.bold.cyan("[wide]")+chalk.gray(t?" 窄一点":" narrower")),d.push(chalk.bold.cyan("[normal]")+chalk.gray(t?" 64列":" 64-col"))),d.push(chalk.bold.yellow("[e]")+chalk.gray(t?" 报告问题":" report")),d.push(chalk.bold.cyan("[b]")+chalk.gray(t?" 上一张":" back")),d.push(chalk.bold.cyan("[card N]")+chalk.gray(t?" 跳转":" jump")),d.push(chalk.gray("[quit]")+(t?chalk.gray(" 退出"):""));const h=o(r);console.log(chalk.gray(" "+r)),console.log(chalk.gray(" "+(t?`第 ${e.number} / ${n.totalCards} 张`:`Card ${e.number} / ${n.totalCards}`)));let m="",b=0;for(const e of d){const n=o(e);m&&b+2+n>h?(console.log(" "+m),m=e,b=n):(m=m?m+i+e:e,b=m===e?n:b+2+n)}m&&console.log(" "+m),console.log(chalk.gray(" "+r));const p=[t?"e = 报告本卡错误,不算作答;提交后回到本题继续":"e = report a card problem, not an answer — you come back here",t?"更多: bookmark / unbookmark · status · lang zh/en · link":"more: bookmark / unbookmark · status · lang zh/en · link"];for(const o of p)for(const e of wrapMixed(o,h))console.log(chalk.gray(" "+e));console.log()}(t,l)}export function renderCheckFeedback(o,e,n,t=!1){const l=s().startsWith("zh");if(console.log(),n)console.log(chalk.green(" ✓ ")+chalk.white(l?"答对了。":"Correct."));else if(console.log(chalk.yellow(" ✗ ")+chalk.white(l?"记下了,继续。":"Noted — moving on.")),t){const e="y"===o.check?.answer?l?"是":"Yes":l?"否":"No";console.log(chalk.gray(" "+(l?"正确答案: ":"Answer: ")+e+". "+(l?"回看上面那段。":"Re-read the paragraph above.")))}const r=l?o._zh?.solution??o.solution:o.solution;if(r&&r.length>0){console.log(),console.log(chalk.cyan(" 📝 "+(l?"解答:":"Worked solution:")));for(const o of r){for(const e of wrapMixed(o,g()-4))console.log(chalk.white(" "+e));console.log()}}console.log()}function z(o){return[chalk.white(" "+(o?"编著:Charlie Zhu":"Created & edited by Charlie Zhu")),chalk.gray(" "+(o?"ICOA 2026 创始人 · 课程总架构师":"Founder & Chief Curriculum Architect · ICOA 2026"))]}export function renderPhaseComplete(o,e,n,t,r,a){const c=s().startsWith("zh"),[i,d]=n.cardRange,y=e.checkResults||{};let u=0,h=0;for(let o=i;o<=d;o++){const e=y[String(o)];e&&(u++,e.correct&&h++)}const m="-".repeat(48);console.log();for(const o of l(" "))console.log(o);console.log(),console.log(chalk.bold.yellow(" "+m)),console.log(chalk.bold.yellow(" "+(c?`阶段 ${n.number} 完成`:`Phase ${n.number} complete`))+chalk.gray(" · ")+chalk.white(n.name));const b=u>0&&h===u?chalk.bold.green:chalk.bold.white;console.log(chalk.gray(" "+(c?"理解检查得分: ":"comprehension score: "))+b(`${h}/${u}`)+chalk.gray(0===u?c?" (本阶段未作答 y/n)":" (no y/n answered)":""));const p=String(d).length;for(let e=i;e<=d;e++){const n=o.cards.find(o=>o.number===e);if(!n)continue;const t=n,l=t.title??t.badge??"",r=(c?t._zh?.title??t._zh?.badge??l:l)||"",a=null!=n.check,s=y[String(e)];let i;i=s?s.correct?chalk.green("✓"):chalk.red("✗"):a?chalk.gray("○"):chalk.gray("·");const d=wrapMixed(r,g()-10-p),u=d[0]+(d.length>1?"…":"");console.log(chalk.gray(` ${String(e).padStart(p)} `)+i+chalk.white(" "+u))}if(console.log(chalk.gray(c?" ✓ 答对 · ✗ 答错 · ○ 未作答 · 无 y/n 的卡不计分":" ✓ correct · ✗ wrong · ○ unanswered · cards without a y/n are unscored")),r){const o=o=>"green"===o?chalk.bold.green:"blue"===o?chalk.bold.cyan:"yellow"===o?chalk.bold.yellow:chalk.bold.red;console.log(chalk.bold.magenta(" ⭐ "+(c?"提问得分 (best): ":"Prompt scores (best): "))+(0===r.length?chalk.gray(c?"本阶段尚未提问 — 用 /ai 研究,再 /submit 评分":"none this phase — research with /ai, then /submit"):r.map(e=>chalk.gray((c?"卡":"#")+e.card+" ")+o(e.tier)(String(e.score))).join(chalk.gray(" · "))))}if(a?.configured&&a.contest){const o=a.contest;if(o.slots&&o.slots.length>0)for(const e of o.slots){const o=chalk.bold.cyan(` ⚔ ${c?"练习赛":"arena"} ${n.number}-${e.slot}: `);e.passed?console.log(o+chalk.bold.green(`${e.best_ac}/${e.n} AC ✅`)):0===e.attempts?console.log(o+chalk.white(c?`${e.n} 题 · 过 ${e.need} 题 — `:`${e.n} problems · AC ${e.need} — `)+chalk.bold.green(`contest ${e.slot}`)):console.log(o+chalk.yellow(c?`最好 ${e.best_ac}/${e.n}(需 ${e.need})· 已试 ${e.attempts} 次 — `:`best ${e.best_ac}/${e.n} (need ${e.need}) · ${e.attempts} attempt(s) — `)+chalk.bold.green(`contest ${e.slot}`))}else{const e=chalk.bold.cyan(" ⚖ "+(c?"判分赛: ":"Contest: "));o.passed?console.log(e+chalk.bold.green(`${o.best_ac}/${o.n} AC ✅ `+(c?"已过关":"passed"))):0===o.attempts?console.log(e+chalk.white(c?`${o.n} 题 · 过 ${o.need} 题解锁 — 输入 `:`${o.n} problems · AC ${o.need} to pass — type `)+chalk.bold.green("contest")+chalk.white(c?" 开始":" to start")):console.log(e+chalk.yellow(c?`最好 ${o.best_ac}/${o.n} AC(需 ${o.need})· 已试 ${o.attempts} 次 — 输入 `:`best ${o.best_ac}/${o.n} AC (need ${o.need}) · ${o.attempts} attempt(s) — type `)+chalk.bold.green("contest")+chalk.yellow(c?" 再战":" to retry"))}}t&&console.log(chalk.gray(" "+(c?"下一阶段: ":"next: "))+chalk.bold.cyan(c?`阶段 ${t.number}`:`Phase ${t.number}`)+chalk.gray(" · ")+chalk.white(t.name)),console.log(chalk.bold.yellow(" "+m));for(const o of z(c))console.log(o)}export function renderCurriculumComplete(o,e){const n=s().startsWith("zh"),t=e.checkResults||{},r="-".repeat(48);let a=0,c=0;console.log();for(const o of l(" "))console.log(o);console.log(),console.log(chalk.bold.green(" "+r)),console.log(chalk.bold.green(" 🏆 "+(n?`${o.name} — 全部完成!`:`${o.name} — complete!`))),console.log(chalk.bold.green(" "+r));for(const e of o.modules){const[o,l]=e.cardRange;let r=0,s=0;for(let e=o;e<=l;e++){const o=t[String(e)];o&&(r++,o.correct&&s++)}a+=r,c+=s;const g=r>0&&s===r?chalk.green:chalk.white;console.log(chalk.gray(" "+(n?`阶段 ${e.number}`:`Phase ${e.number}`).padEnd(8))+g(`${s}/${r}`.padEnd(7))+chalk.gray(e.name))}console.log(chalk.bold.green(" "+r)),console.log(chalk.bold.green(" "+(n?"总分 / overall: ":"Overall: "))+chalk.bold.white(`${c}/${a}`)),console.log(chalk.bold.green(" "+r));for(const o of z(n))console.log(o);console.log()}export function renderMCQCard(o,t){const l=s(),r=e(o,l);u(r,t),b(),m(chalk.bold.yellow("🎯 "+r.title)),m(chalk.gray("─".repeat(Math.min(r.title.length+4,g())))),b();for(const o of x(r.question,g()-4))m(" "+o);b();for(const o of["A","B","C","D"])m(chalk.cyan(` ${o}.`)+" "+chalk.white(r.options[o]));b(),h(),console.log(chalk.gray(" "+(l.startsWith("zh")?"输入 ":"Type "))+chalk.bold.green("A")+chalk.gray(" / ")+chalk.bold.green("B")+chalk.gray(" / ")+chalk.bold.green("C")+chalk.gray(" / ")+chalk.bold.green("D")+chalk.gray(" "+n("type_to_answer",l))),console.log(chalk.gray(" ")+chalk.bold.cyan("back")+chalk.gray(l.startsWith("zh")?" 上一张 · ":" previous card · ")+chalk.bold.cyan("card N")+chalk.gray(l.startsWith("zh")?" 跳转":" jump")),console.log()}export function renderMCQFeedback(o,t,l,r){const a=s(),c=e(o,a);console.log(),l?console.log(" "+chalk.bold.green(n("correct",a)+" ")+chalk.gray(`${n("one_point",a)} · ${t} = ${c.options[t]}`)):console.log(" "+chalk.bold.red(n("not_quite",a)+" ")+chalk.gray(`${n("you_chose",a)} ${t}; ${n("answer_is",a)} ${c.answer}.`)),console.log(),console.log(chalk.gray(" "+n("explanation",a)));for(const o of x(c.explanation,g()-4))console.log(chalk.gray(" "+o));const i=Object.values(r.mcqResults),d=i.filter(o=>o.correct).length;console.log(),console.log(chalk.gray(" "+n("mcq_accuracy_so_far",a)+" ")+chalk.white(`${d}/${i.length}`)),console.log(),l||(console.log(chalk.gray(" "+n("press_ok_continue",a)+" ")+chalk.bold.green("ok")+chalk.gray(" "+n("to_continue",a))),console.log())}export function renderPracticalCard(o,t){const l=s(),r=e(o,l);u(r,t),b(),m(chalk.bold.yellow("🛠 "+r.title)),m(chalk.gray("─".repeat(Math.min(r.title.length+4,g())))),b();for(const o of x(r.task,g()-4))m(" "+o);if(r.starterCode){b(),m(chalk.gray(" "+n("starter_code",l))),b();for(const o of r.starterCode.split("\n"))m(" "+chalk.cyan(o))}b(),h(),console.log(chalk.gray(" "+n("try_in_sandbox",l)+" ")+chalk.bold.cyan("!python3")+chalk.gray(" "+n("drops_into_python",l))),console.log(chalk.gray(" "+n("when_done",l))),console.log(chalk.gray(" ")+chalk.bold.green("done")+chalk.gray(" "+n("done_desc",l))),console.log(chalk.gray(" ")+chalk.bold.yellow("skip")+chalk.gray(" "+n("skip_desc",l))),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log()}export function renderPracticalSuccess(o){const t=s(),l=e(o,t);console.log(),console.log(" "+chalk.bold.green(n("practical_recorded",t))),console.log(),console.log(chalk.gray(" "+n("reference_answer",t)));for(const o of x(l.successHint,g()-4))console.log(chalk.gray(" "+o));console.log(),console.log(chalk.gray(" "+n("press_ok_continue",t)+" ")+chalk.bold.green("ok")+chalk.gray(" "+n("to_continue",t))),console.log()}export function renderSimDemoCard(o,t){const l=s(),r=e(o,l);u(r,t),b(),m(chalk.bold.yellow("🎬 "+r.title)),b();for(const o of x(r.description,g()-4))m(" "+o);b(),m(chalk.gray(" "+n("sim_requires",l))),b(),h(),console.log(chalk.gray(" ")+chalk.bold.cyan("sim")+chalk.gray(" "+n("sim_launch_desc",l))),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(" "+n("continue_to_next",l))),console.log(chalk.gray(" bookmark "+n("bookmark_desc",l))),console.log(chalk.gray(" back "+n("back_desc",l))),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+n("quit_desc",l))),console.log()}export function renderArenaTaskCard(o,n){const t=s(),l=t.startsWith("zh"),r=e(o,t);u(r,n),b(),m(chalk.bold.cyan("🏟 "+r.title)),m(chalk.gray(" "+r.origin+" · "+r.domain+" · "+r.metric)),b();for(const o of r.statement){for(const e of x(o,g()-4))m(" "+e);b()}m(chalk.bold.green(l?" 核心要点 — baseline → 解法的关键变化":" CORE DELTA — baseline → solution"));for(const o of r.core_delta)for(const e of x("• "+o,g()-6))m(" "+chalk.white(e));b(),m(chalk.gray((l?" 提交格式: ":" Submission: ")+r.submission_format)),r.hints&&m(chalk.gray(l?" 本题有 5 级提示 (a–e),进入 arena 后逐级解锁。":" 5 progressive hints (a–e) unlock inside the arena.")),b(),h(),console.log(chalk.gray(" ")+chalk.bold.cyan("arena "+r.task_id)+chalk.gray(l?" 动手做这道题(下载 / 提示 / 提交 / 榜单)":" open the arena (download / hints / submit / board)")),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(l?" 继续下一张":" continue to next")),console.log(chalk.gray(" back "+(l?"上一张":"previous"))),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+(l?"退出":"exit"))),console.log()}export function renderComingSoonCard(o,n){const t=s(),l=t.startsWith("zh"),r=e(o,t);u(r,n),b(),m(chalk.bold.yellow("🔜 "+r.title)),b();const a=r.note||(l?"这道竞技场题目正在编写中,敬请期待。":"This arena task is coming soon.");for(const o of x(a,g()-4))m(" "+chalk.gray(o));b(),h(),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(l?" 继续":" continue")),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+(l?"退出":"exit"))),console.log()}export function renderMilestone(o,t){const l=s(),r=e(o,l),a=o.number===t.totalCards;console.log(),console.log(chalk.bold.yellow(" ╭"+i("═"))),console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+chalk.white(" "+n("milestone_header",l))),console.log(chalk.bold.yellow(" ║"));const c=` ${r.badge} ${r.emoji}`;console.log(chalk.bold.yellow(" ║ ")+chalk.bold.green(c)),console.log(chalk.bold.yellow(" ║ ")+chalk.gray(" ─".repeat(Math.max(1,Math.floor(r.badge.length/2+2))))),console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+" "+chalk.gray(n("in_wild_corresponds",l)));for(const o of x(r.realWorldLevel,g()-4))console.log(chalk.bold.yellow(" ║ ")+" "+chalk.white(o));console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+" "+chalk.gray(n("whats_next",l)));for(const o of x(r.unlockedNext,g()-4))console.log(chalk.bold.yellow(" ║ ")+" "+chalk.white(o));console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ╰"+i("═"))),console.log(),a?(console.log(chalk.gray(" "+n("demo_complete",l))),console.log(),console.log(chalk.gray(" "+n("unlock_full",l)+" ")+chalk.white(n("curriculum_name",l))+chalk.gray(",")),console.log(chalk.gray(" "+n("contact_team_leader",l)+" ")+chalk.bold.yellow("EA")+chalk.gray(" "+n("learn_token",l))),console.log(chalk.gray(" "+n("or_email",l)+" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" "+n("for_partnership",l))),console.log(),console.log(chalk.gray(" "+n("type_quit",l)+" ")+chalk.bold.green("quit")+chalk.gray(" "+n("to_exit",l)+" ")+chalk.bold.green("status")+chalk.gray(" "+n("for_dashboard",l)))):(console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(" "+n("continue_to_next",l))),console.log(chalk.gray(" status "+n("status_full",l))),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+n("quit_desc",l)))),console.log()}export function renderStatus(o,e){const t=s(),l=e.cardsCompleted.length,r=o.totalCards,a=Object.values(e.mcqResults),c=a.filter(o=>o.correct).length;console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(n("status_title",t))+" "+chalk.cyan("─".repeat(25))),b(),m(" "+chalk.gray(n("total_progress",t)+" ")+d(l,r)+chalk.gray(` (${l}/${r})`)),m(" "+chalk.gray(n("streak",t)+" ")+y(e.streakDays)+chalk.gray(` (${n("longest",t)} ${e.longestStreak})`)),m(" "+chalk.gray(n("mcq_accuracy",t)+" ")+chalk.white(`${c}/${a.length}`)),m(" "+chalk.gray(n("practicals_done",t)+" ")+chalk.white(`${e.practicalsCompleted.length}`)),m(" "+chalk.gray(n("bookmarked",t)+" ")+chalk.white(`${e.bookmarks.length}`)),b();const g=n("module",t).replace(":","").trim();for(const n of o.modules){const[o,t]=n.cardRange,l=e.cardsCompleted.filter(e=>e>=o&&e<=t).length,r=t-o+1;m(" "+(l===r?chalk.green("✓"):l>0?chalk.yellow("▶"):chalk.gray("□"))+" "+chalk.gray(`${g} ${n.number}: `)+chalk.white(`${l}/${r}`)+chalk.gray(" "+n.name))}if(b(),e.achievements.length>0){m(" "+chalk.gray(n("achievements",t)));for(const o of e.achievements)m(" "+chalk.bold.yellow("★ ")+chalk.white(o))}else m(" "+chalk.gray(n("achievements_none",t)));b(),h()}
1
+ import chalk from"chalk";import o from"string-width";import{localized as e}from"./learn-curricula.js";import{t as n}from"./learn-i18n.js";import{getConfig as t}from"./config.js";import{icoaBannerLines as l}from"./banner.js";import{renderCharts as r,detectCaps as a}from"./render-card.js";function s(){return(t().language||"en").toLowerCase()}let c="normal";export function resolveLearnWidth(o){return"normal"===o.learnWidth||"wide"===o.learnWidth||"wider"===o.learnWidth?o.learnWidth:o.learnWide?"wide":"normal"}export function setLearnWidth(o){c=o}export function learnWidthCap(o=c){return"wider"===o?120:"wide"===o?96:64}export function learnW(){if("normal"===c)return 64;const o=process.stdout.columns||64;return Math.max(64,Math.min(o-6,learnWidthCap()))}const g=learnW;function i(o="─"){return o.repeat(g()+2)}function d(o,e,n=20){const t=e>0?o/e:0,l=Math.floor(t*n),r=n-l;return`${chalk.green("█".repeat(l))+chalk.gray("░".repeat(r))} ${(100*t).toFixed(1)}%`}function y(o){return o>=30?chalk.red("🔥🔥🔥 "+o+" days"):o>=7?chalk.yellow("🔥 "+o+" days"):o>=1?chalk.gray("· "+o+" day"+(o>1?"s":"")):chalk.gray("—")}export function renderWelcome(o,e,t){const l=s(),r=e.cardsCompleted.length,a=o.totalCards,c=a-r,g=o.modules.find(o=>e.currentCard>=o.cardRange[0]&&e.currentCard<=o.cardRange[1]),u=/demo/i.test(o.id);if(console.log(),console.log(chalk.cyan(" ╭"+i("═"))),console.log(chalk.cyan(" ║")),console.log(chalk.cyan(" ║ ")+chalk.bold.white(" "+(o.name?.trim()||n("academy_title",l)))),console.log(chalk.cyan(" ║")),t)console.log(chalk.cyan(" ║ ")+chalk.white(" "+n(u?"welcome_new_demo":"welcome_new",l)));else{const o=new Date(e.lastSeenAt),t=Math.floor((Date.now()-o.getTime())/36e5),r=t<1?n("just_now",l):t<24?`${t}${n("ago_hours",l)}`:`${Math.floor(t/24)}${n("ago_days",l)}`;console.log(chalk.cyan(" ║ ")+chalk.white(` ${n("welcome_back",l)} ${r}`))}console.log(chalk.cyan(" ║"));const h=g?`${g.number}. ${g.name}`:"—";console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("module",l).padEnd(11))+chalk.white(h)),console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("progress",l).padEnd(11))+d(r,a)+chalk.gray(` (${r}/${a})`)),console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("streak",l).padEnd(11))+y(e.streakDays)),c>0&&e.currentCard<=a&&console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("next_card",l).padEnd(11))+chalk.white(`#${e.currentCard} ${n("of",l)} ${a}`)),console.log(chalk.cyan(" ║")),console.log(chalk.cyan(" ╰"+i("═"))),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const m=0===r?n("continue_start",l):`${n("continue_resume",l)} ${e.currentCard}`;console.log(chalk.bold.green(" continue")+chalk.gray(" "+m)),console.log(chalk.yellow(" status")+chalk.gray(" "+n("status_full",l))),e.bookmarks.length>0&&console.log(chalk.yellow(" bookmarks")+chalk.gray(` ${e.bookmarks.length} ${n("bookmarks_desc",l)}`)),console.log(chalk.gray(" quit")+chalk.gray(" "+n("quit_desc",l))),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log()}function u(o,e){const t=s(),l=o.module,r=e.modules.find(o=>o.number===l),a=r?r.name:n("unknown_module",t),c=n("module",t).replace(":","").trim(),i=`${n("card",t)} ${o.number} / ${e.totalCards} · ${c} ${l} · ${a}`;console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(i)+" "+chalk.cyan("─".repeat(Math.max(0,g()-i.length-4))))}function h(){console.log(chalk.cyan(" ╰"+i())),console.log()}function m(o){console.log(chalk.cyan(" │ ")+chalk.white(o))}function b(){console.log(chalk.cyan(" │"))}const p=/[┌┐└┘├┤┬┴┼─│╔╗╚╝═║╠╣╦╩╬▓▒░█]/;function f(o){return/^(?: {4}|\t)/.test(o)||p.test(o)||/ {3,}/.test(o)}export function wrapMixed(e,n){const t=[];let l="",r=0,a=!1;for(const s of function(e){const n=[],t=e=>{let t="";const l=()=>{t&&(n.push({t:"atom",s:t}),t="")};for(const r of e)" "===r?(l(),n.push({t:"space"})):2===o(r)?(l(),n.push({t:"wide",s:r})):t+=r;l()},l=/`[^`]*`/g;let r,a=0;for(;null!==(r=l.exec(e));)t(e.slice(a,r.index)),n.push({t:"code",s:r[0]}),a=r.index+r[0].length;return t(e.slice(a)),n}(e)){if("space"===s.t){""!==l&&(a=!0);continue}const e=s.s,c=o("code"===s.t?e.replace(/`/g,""):e),g=a?1:0,i="atom"===s.t&&e.length<=2&&/^[.,;:!?)\]}…'"]+$/.test(e);""!==l&&!i&&r+g+c>n?(t.push(l),l=e,r=c,a=!1):(a&&(l+=" ",r+=1,a=!1),l+=e,r+=c)}return l&&t.push(l),t}const $=/\b(?:Common bug|Common mistake|Common error|Pitfall|Gotcha|Footgun)\b[::]?|\b(?:Warning|Caution)\b[::]|(?:常见错误|常见陷阱|常见误区|陷阱|注意|警告|误区)[::]/gi;function w(o,e){const n=e?chalk.bold.white:chalk.white;let t,l="",r=0;for($.lastIndex=0;null!==(t=$.exec(o));)t.index>r&&(l+=n(o.slice(r,t.index))),l+=chalk.bold.yellow(t[0]),r=t.index+t[0].length;return r<o.length&&(l+=n(o.slice(r))),l}function _(o,e=!1){let n="",t=0;const l=/`([^`]*)`/g;let r;for(;null!==(r=l.exec(o));)r.index>t&&(n+=w(o.slice(t,r.index),e)),n+=chalk.cyan(r[1]),t=r.index+r[0].length;return t<o.length&&(n+=w(o.slice(t),e)),n}function k(o,e=!1){let n=!1;for(const t of o.split("\n"))if(/^\s*```/.test(t))n=!n;else if(n)console.log(chalk.cyan(" │ ")+chalk.cyan(` ${t}`));else if(""!==t)if(f(t))console.log(chalk.cyan(" │ ")+chalk.white(t));else for(const o of wrapMixed(t,g()-4))console.log(chalk.cyan(" │ ")+` ${_(o,e)}`);else b()}function x(o,e){const n=[];for(const t of o.split("\n")){if(""===t){n.push("");continue}if(f(t)){n.push(t);continue}let o="";for(const l of t.split(" "))(o+" "+l).trim().length>e?(n.push(o.trim()),o=l):o=(o+" "+l).trim();o&&n.push(o)}return n}let C=!1;export function setLearnAiEnabled(o){C=o}let M=new Set;export function setLearnPqsViewCards(o){M=o}let v=new Map;export function setLearnHonorRanks(o){v=o}const W=["①","②","③","④","⑤","⑥","⑦","⑧","⑨","⑩"];export function renderHonorWall(o){const e=s().startsWith("zh"),{totals:n,chapters:t}=o,l=n.gold+n.silver+n.bronze,r=(o,e)=>e>0?chalk.bold.white(`${o}×${e}`):chalk.gray(`${o}×0`);if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.bold.white(e?" 🏅 奖牌墙 ":" 🏅 Medal wall ")+r("🥇",n.gold)+chalk.gray(" · ")+r("🥈",n.silver)+chalk.gray(" · ")+r("🥉",n.bronze)+chalk.gray(e?" (永久 — 挂上墙就不会摘下)":" (permanent — once earned, never removed)")),0===l){const n=null!=o.floor?`${o.floor}+`:e?"高分":"a high score";return console.log(chalk.gray(e?` 还没有奖牌 — 单卡提问评分 ${n} 并进入该卡前三,即可永久挂墙 🥇🥈🥉`:` No medals yet — score ${n} on a card and hold its top-3 to hang one 🥇🥈🥉`)),void console.log(chalk.gray(" ─────────────────────────────────────────"))}const a=t.map(o=>{const e=`Ch${o.chapter}`,n=(o.gold>0?`🥇${o.gold}`:"")+(o.silver>0?`🥈${o.silver}`:"")+(o.bronze>0?`🥉${o.bronze}`:"");return n?chalk.white(`${e} ${n}`):chalk.gray(`${e} —`)}).join(chalk.gray(" "));console.log(" "+a);const c=t.flatMap(o=>o.cards.map(e=>({...e,chapter:o.chapter})));c.sort((o,e)=>o.rank-e.rank||o.chapter-e.chapter||o.card-e.card);for(const o of c.slice(0,24)){const n=(o.since||"").slice(0,10);console.log(chalk.white(` ${o.icon} `)+chalk.gray(`Ch${o.chapter} · `)+chalk.white(e?`第 ${o.card} 张`:`card ${o.card}`)+chalk.gray(` · ${o.score}`)+(n?chalk.gray(e?` · 始于 ${n}`:` · since ${n}`):""))}c.length>24&&console.log(chalk.gray(e?` …还有 ${c.length-24} 枚`:` …and ${c.length-24} more`)),console.log(chalk.gray(" ─────────────────────────────────────────"))}export function renderKnowledgeCard(t,l){const i=s(),d=e(t,i);u(d,l),b();const y=wrapMixed(d.title,g()-4);for(const o of y)m(chalk.bold.yellow(o));m(chalk.gray("─".repeat(Math.min(Math.max(...y.map(e=>o(e))),g()))));const p=!!(t.chart_ids&&t.chart_ids.length>0);if(p&&r(t.chart_ids.slice(0,1),l.charts,a()),d.key_point&&""!==d.key_point.trim()?(p||b(),function(o,e,n){const t=s().startsWith("zh"),l=a().cols,r="-".repeat(Math.min(g(),Math.max(24,l-6))),c=t?"要点":"KEY POINT",i=t?`第 ${e} / ${n} 张`:`Card ${e} / ${n}`;console.log(chalk.cyan(" │ ")+chalk.green(r)),console.log(chalk.cyan(" │ ")+chalk.green(`${c} · ${i}`));for(const e of wrapMixed(o,g()-4))console.log(chalk.cyan(" │ ")+chalk.bold.green(" "+e));console.log(chalk.cyan(" │ ")+chalk.green(r)),b()}(d.key_point,d.number,l.totalCards)):p||b(),d.body.filter(o=>null!=o&&""!==o.trim()).forEach((o,e)=>{const n=0===e?o.match(/^([\s\S]*?(?:[.!?](?=\s|$)|[。!?]))(\s[\s\S]*)?$/):null;if(n&&n[1].trim().length<=180){k(n[1],!0);const o=n[2]?.trimStart();o&&k(o,!1)}else k(o,!1);b()}),d.icoaConnection){m(chalk.magenta(" "+n("icoa_connection",i))),m(chalk.gray(" "+"─".repeat(20)));for(const o of wrapMixed(d.icoaConnection,g()-4))m(" "+chalk.magenta(o));b()}if(t.check){const o=i.startsWith("zh"),e=t._zh?.checkStatement??t._zh?.check?.statement,n=o?e??t.check.statement:t.check.statement;m(chalk.cyan(" 🤔 "+(o?"请回答 (输 y 或 n):":"Quick comprehension check (type y or n):"))),m(chalk.gray(" "+"─".repeat(20)));for(const o of wrapMixed(n,g()-4))m(" "+chalk.white(o));b()}h(),function(e,n){const t=s().startsWith("zh"),l=a().cols,r="-".repeat(Math.min(g(),Math.max(24,l-6))),i=chalk.gray(" "),d=[];e.check?(d.push(chalk.bold.green("[y]")+chalk.gray(t?" 是":" yes")),d.push(chalk.bold.green("[n]")+chalk.gray(t?" 否":" no"))):d.push(chalk.bold.green("[ok]")+chalk.gray(t?" 继续":" next")),C&&(d.push(chalk.bold.magenta("[/ai]")+chalk.gray(t?" 🐼 熊猫导师":" 🐼 Panda tutor")),d.push(chalk.bold.magenta("[/submit]")+chalk.gray(t?" 提问评分":" prompt score")));const y=v.get(e.number);var u;d.push(chalk.bold.magenta(y?`[/honors ${u=y,W[u-1]??`#${u}`}]`:"[/honors]")+chalk.gray(t?" 排行":" board")),"normal"===c?d.push(chalk.bold.cyan("[wide]")+chalk.gray(t?" 宽屏":" widen")):(d.push("wide"===c?chalk.bold.cyan("[wider]")+chalk.gray(t?" 更宽":" wider"):chalk.bold.cyan("[wide]")+chalk.gray(t?" 窄一点":" narrower")),d.push(chalk.bold.cyan("[normal]")+chalk.gray(t?" 64列":" 64-col"))),d.push(chalk.bold.yellow("[e]")+chalk.gray(t?" 报告问题":" report")),d.push(chalk.bold.cyan("[b]")+chalk.gray(t?" 上一张":" back")),d.push(chalk.bold.cyan("[card N]")+chalk.gray(t?" 跳转":" jump")),d.push(chalk.gray("[reload]")+(t?chalk.gray(" 刷新"):"")),d.push(chalk.gray("[quit]")+(t?chalk.gray(" 退出"):""));const h=o(r);console.log(chalk.gray(" "+r)),console.log(chalk.gray(" "+(t?`第 ${e.number} / ${n.totalCards} 张`:`Card ${e.number} / ${n.totalCards}`)));let m="",b=0;for(const e of d){const n=o(e);m&&b+2+n>h?(console.log(" "+m),m=e,b=n):(m=m?m+i+e:e,b=m===e?n:b+2+n)}m&&console.log(" "+m),console.log(chalk.gray(" "+r));const p=[t?"e = 报告本卡错误,不算作答;提交后回到本题继续":"e = report a card problem, not an answer — you come back here",t?"更多: bookmark / unbookmark · status · lang zh/en · link":"more: bookmark / unbookmark · status · lang zh/en · link"];for(const o of p)for(const e of wrapMixed(o,h))console.log(chalk.gray(" "+e));console.log()}(t,l)}export function renderCheckFeedback(o,e,n,t=!1){const l=s().startsWith("zh");if(console.log(),n)console.log(chalk.green(" ✓ ")+chalk.white(l?"答对了。":"Correct."));else if(console.log(chalk.yellow(" ✗ ")+chalk.white(l?"记下了,继续。":"Noted — moving on.")),t){const e="y"===o.check?.answer?l?"是":"Yes":l?"否":"No";console.log(chalk.gray(" "+(l?"正确答案: ":"Answer: ")+e+". "+(l?"回看上面那段。":"Re-read the paragraph above.")))}const r=l?o._zh?.solution??o.solution:o.solution;if(r&&r.length>0){console.log(),console.log(chalk.cyan(" 📝 "+(l?"解答:":"Worked solution:")));for(const o of r){for(const e of wrapMixed(o,g()-4))console.log(chalk.white(" "+e));console.log()}}console.log()}function z(o){return[chalk.white(" "+(o?"编著:Charlie Zhu":"Created & edited by Charlie Zhu")),chalk.gray(" "+(o?"ICOA 2026 创始人 · 课程总架构师":"Founder & Chief Curriculum Architect · ICOA 2026"))]}export function renderPhaseComplete(o,e,n,t,r,a){const c=s().startsWith("zh"),[i,d]=n.cardRange,y=e.checkResults||{};let u=0,h=0;for(let o=i;o<=d;o++){const e=y[String(o)];e&&(u++,e.correct&&h++)}const m="-".repeat(48);console.log();for(const o of l(" "))console.log(o);console.log(),console.log(chalk.bold.yellow(" "+m)),console.log(chalk.bold.yellow(" "+(c?`阶段 ${n.number} 完成`:`Phase ${n.number} complete`))+chalk.gray(" · ")+chalk.white(n.name));const b=u>0&&h===u?chalk.bold.green:chalk.bold.white;console.log(chalk.gray(" "+(c?"理解检查得分: ":"comprehension score: "))+b(`${h}/${u}`)+chalk.gray(0===u?c?" (本阶段未作答 y/n)":" (no y/n answered)":""));const p=String(d).length;for(let e=i;e<=d;e++){const n=o.cards.find(o=>o.number===e);if(!n)continue;const t=n,l=t.title??t.badge??"",r=(c?t._zh?.title??t._zh?.badge??l:l)||"",a=null!=n.check,s=y[String(e)];let i;i=s?s.correct?chalk.green("✓"):chalk.red("✗"):a?chalk.gray("○"):chalk.gray("·");const d=wrapMixed(r,g()-10-p),u=d[0]+(d.length>1?"…":"");console.log(chalk.gray(` ${String(e).padStart(p)} `)+i+chalk.white(" "+u))}if(console.log(chalk.gray(c?" ✓ 答对 · ✗ 答错 · ○ 未作答 · 无 y/n 的卡不计分":" ✓ correct · ✗ wrong · ○ unanswered · cards without a y/n are unscored")),r){const o=o=>"green"===o?chalk.bold.green:"blue"===o?chalk.bold.cyan:"yellow"===o?chalk.bold.yellow:chalk.bold.red;console.log(chalk.bold.magenta(" ⭐ "+(c?"提问得分 (best): ":"Prompt scores (best): "))+(0===r.length?chalk.gray(c?"本阶段尚未提问 — 用 /ai 研究,再 /submit 评分":"none this phase — research with /ai, then /submit"):r.map(e=>chalk.gray((c?"卡":"#")+e.card+" ")+o(e.tier)(String(e.score))).join(chalk.gray(" · "))))}if(a?.configured&&a.contest){const o=a.contest;if(o.slots&&o.slots.length>0)for(const e of o.slots){const o=chalk.bold.cyan(` ⚔ ${c?"练习赛":"arena"} ${n.number}-${e.slot}: `);e.passed?console.log(o+chalk.bold.green(`${e.best_ac}/${e.n} AC ✅`)):0===e.attempts?console.log(o+chalk.white(c?`${e.n} 题 · 过 ${e.need} 题 — `:`${e.n} problems · AC ${e.need} — `)+chalk.bold.green(`contest ${e.slot}`)):console.log(o+chalk.yellow(c?`最好 ${e.best_ac}/${e.n}(需 ${e.need})· 已试 ${e.attempts} 次 — `:`best ${e.best_ac}/${e.n} (need ${e.need}) · ${e.attempts} attempt(s) — `)+chalk.bold.green(`contest ${e.slot}`))}else{const e=chalk.bold.cyan(" ⚖ "+(c?"判分赛: ":"Contest: "));o.passed?console.log(e+chalk.bold.green(`${o.best_ac}/${o.n} AC ✅ `+(c?"已过关":"passed"))):0===o.attempts?console.log(e+chalk.white(c?`${o.n} 题 · 过 ${o.need} 题解锁 — 输入 `:`${o.n} problems · AC ${o.need} to pass — type `)+chalk.bold.green("contest")+chalk.white(c?" 开始":" to start")):console.log(e+chalk.yellow(c?`最好 ${o.best_ac}/${o.n} AC(需 ${o.need})· 已试 ${o.attempts} 次 — 输入 `:`best ${o.best_ac}/${o.n} AC (need ${o.need}) · ${o.attempts} attempt(s) — type `)+chalk.bold.green("contest")+chalk.yellow(c?" 再战":" to retry"))}}t&&console.log(chalk.gray(" "+(c?"下一阶段: ":"next: "))+chalk.bold.cyan(c?`阶段 ${t.number}`:`Phase ${t.number}`)+chalk.gray(" · ")+chalk.white(t.name)),console.log(chalk.bold.yellow(" "+m));for(const o of z(c))console.log(o)}export function renderCurriculumComplete(o,e){const n=s().startsWith("zh"),t=e.checkResults||{},r="-".repeat(48);let a=0,c=0;console.log();for(const o of l(" "))console.log(o);console.log(),console.log(chalk.bold.green(" "+r)),console.log(chalk.bold.green(" 🏆 "+(n?`${o.name} — 全部完成!`:`${o.name} — complete!`))),console.log(chalk.bold.green(" "+r));for(const e of o.modules){const[o,l]=e.cardRange;let r=0,s=0;for(let e=o;e<=l;e++){const o=t[String(e)];o&&(r++,o.correct&&s++)}a+=r,c+=s;const g=r>0&&s===r?chalk.green:chalk.white;console.log(chalk.gray(" "+(n?`阶段 ${e.number}`:`Phase ${e.number}`).padEnd(8))+g(`${s}/${r}`.padEnd(7))+chalk.gray(e.name))}console.log(chalk.bold.green(" "+r)),console.log(chalk.bold.green(" "+(n?"总分 / overall: ":"Overall: "))+chalk.bold.white(`${c}/${a}`)),console.log(chalk.bold.green(" "+r));for(const o of z(n))console.log(o);console.log()}export function renderMCQCard(o,t){const l=s(),r=e(o,l);u(r,t),b(),m(chalk.bold.yellow("🎯 "+r.title)),m(chalk.gray("─".repeat(Math.min(r.title.length+4,g())))),b();for(const o of x(r.question,g()-4))m(" "+o);b();for(const o of["A","B","C","D"])m(chalk.cyan(` ${o}.`)+" "+chalk.white(r.options[o]));b(),h(),console.log(chalk.gray(" "+(l.startsWith("zh")?"输入 ":"Type "))+chalk.bold.green("A")+chalk.gray(" / ")+chalk.bold.green("B")+chalk.gray(" / ")+chalk.bold.green("C")+chalk.gray(" / ")+chalk.bold.green("D")+chalk.gray(" "+n("type_to_answer",l))),console.log(chalk.gray(" ")+chalk.bold.cyan("back")+chalk.gray(l.startsWith("zh")?" 上一张 · ":" previous card · ")+chalk.bold.cyan("card N")+chalk.gray(l.startsWith("zh")?" 跳转":" jump")),console.log()}export function renderMCQFeedback(o,t,l,r){const a=s(),c=e(o,a);console.log(),l?console.log(" "+chalk.bold.green(n("correct",a)+" ")+chalk.gray(`${n("one_point",a)} · ${t} = ${c.options[t]}`)):console.log(" "+chalk.bold.red(n("not_quite",a)+" ")+chalk.gray(`${n("you_chose",a)} ${t}; ${n("answer_is",a)} ${c.answer}.`)),console.log(),console.log(chalk.gray(" "+n("explanation",a)));for(const o of x(c.explanation,g()-4))console.log(chalk.gray(" "+o));const i=Object.values(r.mcqResults),d=i.filter(o=>o.correct).length;console.log(),console.log(chalk.gray(" "+n("mcq_accuracy_so_far",a)+" ")+chalk.white(`${d}/${i.length}`)),console.log(),l||(console.log(chalk.gray(" "+n("press_ok_continue",a)+" ")+chalk.bold.green("ok")+chalk.gray(" "+n("to_continue",a))),console.log())}export function renderPracticalCard(o,t){const l=s(),r=e(o,l);u(r,t),b(),m(chalk.bold.yellow("🛠 "+r.title)),m(chalk.gray("─".repeat(Math.min(r.title.length+4,g())))),b();for(const o of x(r.task,g()-4))m(" "+o);if(r.starterCode){b(),m(chalk.gray(" "+n("starter_code",l))),b();for(const o of r.starterCode.split("\n"))m(" "+chalk.cyan(o))}b(),h(),console.log(chalk.gray(" "+n("try_in_sandbox",l)+" ")+chalk.bold.cyan("!python3")+chalk.gray(" "+n("drops_into_python",l))),console.log(chalk.gray(" "+n("when_done",l))),console.log(chalk.gray(" ")+chalk.bold.green("done")+chalk.gray(" "+n("done_desc",l))),console.log(chalk.gray(" ")+chalk.bold.yellow("skip")+chalk.gray(" "+n("skip_desc",l))),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log()}export function renderPracticalSuccess(o){const t=s(),l=e(o,t);console.log(),console.log(" "+chalk.bold.green(n("practical_recorded",t))),console.log(),console.log(chalk.gray(" "+n("reference_answer",t)));for(const o of x(l.successHint,g()-4))console.log(chalk.gray(" "+o));console.log(),console.log(chalk.gray(" "+n("press_ok_continue",t)+" ")+chalk.bold.green("ok")+chalk.gray(" "+n("to_continue",t))),console.log()}export function renderSimDemoCard(o,t){const l=s(),r=e(o,l);u(r,t),b(),m(chalk.bold.yellow("🎬 "+r.title)),b();for(const o of x(r.description,g()-4))m(" "+o);b(),m(chalk.gray(" "+n("sim_requires",l))),b(),h(),console.log(chalk.gray(" ")+chalk.bold.cyan("sim")+chalk.gray(" "+n("sim_launch_desc",l))),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(" "+n("continue_to_next",l))),console.log(chalk.gray(" bookmark "+n("bookmark_desc",l))),console.log(chalk.gray(" back "+n("back_desc",l))),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+n("quit_desc",l))),console.log()}export function renderArenaTaskCard(o,n){const t=s(),l=t.startsWith("zh"),r=e(o,t);u(r,n),b(),m(chalk.bold.cyan("🏟 "+r.title)),m(chalk.gray(" "+r.origin+" · "+r.domain+" · "+r.metric)),b();for(const o of r.statement){for(const e of x(o,g()-4))m(" "+e);b()}m(chalk.bold.green(l?" 核心要点 — baseline → 解法的关键变化":" CORE DELTA — baseline → solution"));for(const o of r.core_delta)for(const e of x("• "+o,g()-6))m(" "+chalk.white(e));b(),m(chalk.gray((l?" 提交格式: ":" Submission: ")+r.submission_format)),r.hints&&m(chalk.gray(l?" 本题有 5 级提示 (a–e),进入 arena 后逐级解锁。":" 5 progressive hints (a–e) unlock inside the arena.")),b(),h(),console.log(chalk.gray(" ")+chalk.bold.cyan("arena "+r.task_id)+chalk.gray(l?" 动手做这道题(下载 / 提示 / 提交 / 榜单)":" open the arena (download / hints / submit / board)")),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(l?" 继续下一张":" continue to next")),console.log(chalk.gray(" back "+(l?"上一张":"previous"))),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+(l?"退出":"exit"))),console.log()}export function renderComingSoonCard(o,n){const t=s(),l=t.startsWith("zh"),r=e(o,t);u(r,n),b(),m(chalk.bold.yellow("🔜 "+r.title)),b();const a=r.note||(l?"这道竞技场题目正在编写中,敬请期待。":"This arena task is coming soon.");for(const o of x(a,g()-4))m(" "+chalk.gray(o));b(),h(),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(l?" 继续":" continue")),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+(l?"退出":"exit"))),console.log()}export function renderMilestone(o,t){const l=s(),r=e(o,l),a=o.number===t.totalCards;console.log(),console.log(chalk.bold.yellow(" ╭"+i("═"))),console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+chalk.white(" "+n("milestone_header",l))),console.log(chalk.bold.yellow(" ║"));const c=` ${r.badge} ${r.emoji}`;console.log(chalk.bold.yellow(" ║ ")+chalk.bold.green(c)),console.log(chalk.bold.yellow(" ║ ")+chalk.gray(" ─".repeat(Math.max(1,Math.floor(r.badge.length/2+2))))),console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+" "+chalk.gray(n("in_wild_corresponds",l)));for(const o of x(r.realWorldLevel,g()-4))console.log(chalk.bold.yellow(" ║ ")+" "+chalk.white(o));console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+" "+chalk.gray(n("whats_next",l)));for(const o of x(r.unlockedNext,g()-4))console.log(chalk.bold.yellow(" ║ ")+" "+chalk.white(o));console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ╰"+i("═"))),console.log(),a?(console.log(chalk.gray(" "+n("demo_complete",l))),console.log(),console.log(chalk.gray(" "+n("unlock_full",l)+" ")+chalk.white(n("curriculum_name",l))+chalk.gray(",")),console.log(chalk.gray(" "+n("contact_team_leader",l)+" ")+chalk.bold.yellow("EA")+chalk.gray(" "+n("learn_token",l))),console.log(chalk.gray(" "+n("or_email",l)+" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" "+n("for_partnership",l))),console.log(),console.log(chalk.gray(" "+n("type_quit",l)+" ")+chalk.bold.green("quit")+chalk.gray(" "+n("to_exit",l)+" ")+chalk.bold.green("status")+chalk.gray(" "+n("for_dashboard",l)))):(console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(" "+n("continue_to_next",l))),console.log(chalk.gray(" status "+n("status_full",l))),console.log(chalk.gray(" back previous card")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+n("quit_desc",l)))),console.log()}export function renderStatus(o,e){const t=s(),l=e.cardsCompleted.length,r=o.totalCards,a=Object.values(e.mcqResults),c=a.filter(o=>o.correct).length;console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(n("status_title",t))+" "+chalk.cyan("─".repeat(25))),b(),m(" "+chalk.gray(n("total_progress",t)+" ")+d(l,r)+chalk.gray(` (${l}/${r})`)),m(" "+chalk.gray(n("streak",t)+" ")+y(e.streakDays)+chalk.gray(` (${n("longest",t)} ${e.longestStreak})`)),m(" "+chalk.gray(n("mcq_accuracy",t)+" ")+chalk.white(`${c}/${a.length}`)),m(" "+chalk.gray(n("practicals_done",t)+" ")+chalk.white(`${e.practicalsCompleted.length}`)),m(" "+chalk.gray(n("bookmarked",t)+" ")+chalk.white(`${e.bookmarks.length}`)),b();const g=n("module",t).replace(":","").trim();for(const n of o.modules){const[o,t]=n.cardRange,l=e.cardsCompleted.filter(e=>e>=o&&e<=t).length,r=t-o+1;m(" "+(l===r?chalk.green("✓"):l>0?chalk.yellow("▶"):chalk.gray("□"))+" "+chalk.gray(`${g} ${n.number}: `)+chalk.white(`${l}/${r}`)+chalk.gray(" "+n.name))}if(b(),e.achievements.length>0){m(" "+chalk.gray(n("achievements",t)));for(const o of e.achievements)m(" "+chalk.bold.yellow("★ ")+chalk.white(o))}else m(" "+chalk.gray(n("achievements_none",t)));b(),h()}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.441",
3
+ "version": "2.19.442",
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": {