icoa-cli 2.19.453 → 2.19.454

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,!0);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,!0),!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 nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`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()})}
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 C}from"node:url";import{loadCurriculumById as A,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,activateSession as X,updateStreak as G,markCardComplete as ee,recordMCQ as oe,recordCheck as ne,markPracticalComplete as te,addAchievement as re}from"../lib/learn-state.js";import{renderWelcome as le,renderKnowledgeCard as se,renderMCQCard as ae,renderMCQFeedback as ie,renderPracticalCard as ce,renderPracticalSuccess as de,renderSimDemoCard as ge,renderMilestone as ue,renderArenaTaskCard as ye,renderComingSoonCard as me,renderStatus as he,renderPhaseComplete as pe,renderCurriculumComplete as fe,setLearnAiEnabled as be,setLearnHonorRanks as we,setLearnPqsViewCards as $e,setLearnWidth as ke,resolveLearnWidth as ve,learnWidthCap as Ce,learnW as Ae,renderHonorWall as _e,wrapMixed as Te}from"../lib/learn-render.js";import{printError as Ie}from"../lib/ui.js";const xe=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(Ee){Ee.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async Ee=>{Ee?.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(),Ee="LEARNDEMO01");let Se=Ee.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Se)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Pe=null;const Me=/^[A-Z0-9]+DEMO01$/i.test(Se),Le=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Se);let qe=!1,We=!1;if(Me)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Pe=await A(Se,Se,!0);else if(Le){console.log(),console.log(chalk.gray(" Validating token..."));let e=await _(Se);if(!e.ok){const o=x(Se);if(o!==Se){const n=await _(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Se} → ${o}`)),e=n,Se=o)}}if(!e.ok)return Ie(`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 🐼"):"")),qe=!0===e.aiEnabled,We=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Pe=await A(e.curriculumId||"LEARNDEMO01",Se,!0),!Pe)return Ie(`Could not open a learn curriculum for token '${Se}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Se}`)+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 ${Se}`)+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(!Pe){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Ie(`Could not reach the learn server to open ${Se}.`),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 ${Se}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Ie(`Unknown learn token: ${Se}`),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 Re=K(),Ne=!1;try{if(Re&&Re.token===Se)G(Re);else{const e=X(Se);e?(Re=e,Re.totalCards=Pe.totalCards,G(Re)):(Re=V(Se,Pe.id,Pe.totalCards),Ne=!0)}Q(Re),le(Pe,Re,Ne)}catch{return Ie("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 ${Se}`)+chalk.gray(".")),void console.log()}const Oe=s(),je=null!==Oe,De=je?Oe.listeners("line").slice():[];je&&Oe.removeAllListeners("line");const Ye=je?Oe:o({input:process.stdin,output:process.stdout,terminal:!0}),Ue=je?Ye.prompt:null;je&&(Ye.prompt=e.prototype.prompt);const Fe=()=>{je&&Ue&&(Ye.prompt=Ue)},ze=()=>{Ye.setPrompt(so?chalk.bold.green(`icoa ${a()}> `):oo?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Ge?"icoa learn ai> ":"icoa learn> ")),Ye.prompt()};let He=null,Be=null,Ze=null,Je=null,Ke=[],Qe=!1,Ve=null;const Xe=()=>{Ve&&clearTimeout(Ve),Ve=null,Ke=[],Qe=!1,Je=null};let Ge=!1,eo=!1,oo=!1,no=null,to=!1,ro=0,lo=!1,so=!1;const ao=new Map,io=()=>{let e=ao.get(Re.currentCard);return e||(e=[],ao.set(Re.currentCard,e)),e};let co=!1;const go=new Set;let uo=!1,yo=0;const mo=()=>(z().language||"en").toLowerCase().startsWith("zh");be(qe),ke(ve(z())),$e(go);const ho=new Map;we(ho);const po=[];let fo=null;const bo=new Promise(e=>{fo=e}),wo=()=>{const e=fo;fo=null,e?.()},$o="1"===process.env.ICOA_LEARN_EMBEDDED,ko=e=>Pe.cards.find(o=>o.number===e);let vo=null,Co=null;const Ao=new Map,_o=!Se.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Se),To=async()=>{if(!_o)return;const e=await U(Se);e.ok&&e.data&&(vo=e.data)},Io=e=>{const o=Pe.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},xo=e=>{if(!We||!vo)return null;const o=Io(e);if(o<=vo.unlocked_through_phase)return null;const n=vo.phases.find(e=>e.phase===vo.unlocked_through_phase),t=[chalk.yellow(mo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${vo.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${vo.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(mo()?` ⚔ 练习赛 ${vo.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${vo.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(mo()?` ⚖ 判分赛: 最好 ${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(mo()?"、":", "),r=e.length>8?mo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:mo()?" 张":"";t.push(chalk.gray(mo()?` ✓ 逐卡自测: ${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(mo()?` ⭐ 提问研究: ${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")},Eo=async e=>We?null===xo(e)?null:(await To(),xo(e)):null;_o&&await To();const So=async e=>{const o=Pe.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Pe.modules.find(e=>e.number===o.number+1);let t;if(qe){const e=await E({token:Se,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}_o&&await To();const r=vo?.phases.find(e=>e.phase===o.number);return pe(Pe,Re,o,n,t,r),!0},Po=()=>{uo=!0,console.log(chalk.gray(mo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Mo=()=>{no=null;const e=ko(Re.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":se(e,Pe),e.check?(Ze=e.number,yo=Date.now()):(ee(Re,e.number),Q(Re));break;case"mcq":ae(e,Pe),He=e.number;break;case"practical":ce(e,Pe),Be=e.number;break;case"sim_demo":ge(e,Pe),ee(Re,e.number),Q(Re);break;case"milestone":ue(e,Pe),re(Re,e.badge),ee(Re,e.number),Q(Re);break;case"arena_task":ye(e,Pe),ee(Re,e.number),Q(Re);break;case"coming_soon":me(e,Pe),ee(Re,e.number),Q(Re)}Lo(e.number)},Lo=e=>{if(!_o||!vo)return;const o=Pe.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=vo.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?mo()?` · 用时 ${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(`⚔ ${mo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(mo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(mo()?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(mo()?`${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(mo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(mo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(mo()?"✍ 第一次用 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(mo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(mo()?"最好":"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(mo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(mo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(mo()?" 继续学习":" keep going"):chalk.gray(mo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(mo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},qo=()=>{Se.endsWith("DEMO01")?console.log(chalk.yellow(mo()?" 🐼 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(mo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(mo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Wo=async(e,o)=>{if(qe){eo=!0;try{console.log(),console.log(chalk.gray("deep"===o?mo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":mo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await M({token:Se,cardNumber:Re.currentCard,question:e,mode:o,history:io().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(mo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(io().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(` (${mo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(mo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Ze&&console.log(chalk.gray(mo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{eo=!1}}else qo()},Ro=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],No=async()=>{oo&&Co?Bo?Zo(Bo):Fo():no?await Oo():Mo()},Oo=async()=>{eo=!0;try{console.log();const e=await W({token:Se,curriculumId:Pe.id,cardNumber:Re.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(mo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(mo()?` 🏆 本卡实时 Top-3 — 第 ${Re.currentCard} 张`:` 🏆 Live top-3 — card ${Re.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(mo()?" (你)":" (you)"):""))}else console.log(chalk.gray(mo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(ho.set(Re.currentCard,e.mine.rank),console.log(chalk.white(mo()?" 你: ":" You: ")+chalk.bold.yellow(mo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(mo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):qe&&console.log(chalk.gray(mo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),_e({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(mo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(mo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(mo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),no="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(mo()?" 返回卡片":" returns to the card")),console.log()}finally{eo=!1}},jo=e=>mo()&&e.title_zh||e.title,Do=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of Te(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},Yo=e=>{console.log(),console.log(chalk.bold.green(mo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(mo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Uo=e=>Co.data.solved.includes(e.id)?"✅":Co.data.carried?.includes(e.id)?"✅↗":Co.tried.has(e.id)?"❌":"⬜",Fo=()=>{const e=Co.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(mo()?` · 第 ${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(mo()?" ⏱ 已超时 — 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(mo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(mo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(mo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(mo()?" 带过来,不必重做":" 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(mo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(mo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(mo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(mo()?` 满血重开本组(${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)} `)+Uo(e)+chalk.white(` ${jo(e)}`))}),console.log(),zo()},zo=()=>{console.log(chalk.gray(mo()?" /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(mo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(mo()?" 返回课程":" returns to the lesson")),console.log()},Ho=e=>{const o=parseInt(e,10),n=Co.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(mo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let Bo=null;const Zo=e=>{const o=Ho(e);if(!o)return;const{p:n,n:t}=o;Bo=String(t),console.log(),console.log(chalk.bold.white(` ${Uo(n)} ${jo(n)}`)),console.log();for(const e of(e=>mo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of Te(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(mo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(mo()?" 应输出:":" 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(mo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(mo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(mo()?"写码(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(mo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(mo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(mo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((mo()," ↩ "))+chalk.bold.green("back")+chalk.gray(mo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(mo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((mo()," / "))+chalk.bold.green("wide")+chalk.gray(mo()?" 换语言/宽度":" language / width")),console.log()},Jo=async(e,o)=>await new Promise(n=>{const t=process.stdin,l=!!t.isTTY&&!!t.isRaw;if(Ye.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:Co.dir}),a=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&l)try{t.setRawMode(!0)}catch{}Ye.resume(),n(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Ko=()=>{console.log(chalk.yellow(mo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(mo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(mo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(mo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Qo=new Map,Vo=async e=>{const o=e.trim().toLowerCase(),s=oo&&o.startsWith("/")?o.slice(1):o;if(eo)return;if(null!==Je){if(Ke.push(e.replace(/\s+$/,"")),Ve&&clearTimeout(Ve),Ve=null,Qe){const e=Ke[Ke.length-1]??"";return"/cancel"===e.trim()?(Xe(),console.log(chalk.gray(mo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void ze()):""!==e.trim()?void ze():(Ke.pop(),void await a())}return void(Ve=setTimeout(()=>{if(Ve=null,Ke.length>1){Qe=!0;const e=Ke.length;return console.log(chalk.cyan(mo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(mo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void ze()}a()},140))}async function a(){const e=Ke.join("\n").replace(/^\s+|\s+$/g,""),o=Je??Re.currentCard,n=Ke.length;if(Xe(),""===e)console.log(chalk.gray(mo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(mo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(mo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(mo()?" 即可执行。":" again to run it."));else{const t=yo>0?Date.now()-yo:void 0;if(await I(Se,{curriculum_id:Pe.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const e=n>1?mo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(mo()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(mo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),ze()}if(to){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return to=!1,console.log(),console.log(chalk.yellow(mo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(mo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(mo()?" 即可执行该命令。":" again to run it.")),console.log(),void ze();if(!o)return to=!1,console.log(chalk.gray(mo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void ze();const n=await P({token:Se,nickname:o});if(n.ok)to=!1,console.log(chalk.bold.green(mo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(mo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{ro+=1;const e="taken"===n.code?mo()?"已被占用":"already taken":"bad_charset"===n.code?mo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?mo()?"未通过审核":"did not pass review":n.message||"error";if(!(ro>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(mo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void ze();to=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(mo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void ze()}if(co){co=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{eo=!0;try{console.log(),console.log(chalk.gray(mo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await L({token:Se,cardNumber:Re.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(mo()?"评审暂不可用。":"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(mo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(mo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(mo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(mo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(mo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(mo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=mo()?` 本卡排名 #${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(mo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(mo()?` 第 ${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 Ro(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(mo()?" 改进提问: ":" 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(` (${mo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?go.add(Re.currentCard):go.delete(Re.currentCard),"number"==typeof e.rank&&ho.set(Re.currentCard,e.rank);const o=await W({token:Se,curriculumId:Pe.id,cardNumber:Re.currentCard});o.ok&&o.totals&&o.chapters&&(_e({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Me&&(to=!0,ro=0,console.log(chalk.bold.yellow(mo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(mo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(mo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{eo=!1}})():(console.log(chalk.gray(mo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Ze&&(console.log(chalk.gray(mo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ze()}if(uo)return uo=!1,Mo(),void ze();if(!o)return void ze();if(so)return"exit"===await i(e.trim())&&(so=!1),void ze();if(Ge){if(["q","quit","exit","back","b","menu"].includes(o))return Ge=!1,console.log(chalk.gray(mo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void ze();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim();return t&&(await Wo(t,n?"fast":"deep"),console.log(chalk.gray(mo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void ze()}if(oo&&Co){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${Co.phase}s${Co.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return oo=!1,console.log(chalk.gray(mo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Mo(),void ze();if(/^\d+$/.test(o))return Zo(o),void ze();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,t]=e;return"list"===o?Fo():t?"read"===o||"open"===o?Zo(t):"edit"===o?await(async e=>{const o=Ho(e);if(!o)return;const n=v(Co.dir,`sol-${o.n}.py`);if(B())return Z()?(console.log(chalk.yellow(mo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(mo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(mo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(mo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(mo()?" ← 不能是 /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(mo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(mo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(mo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(mo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(mo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(mo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(mo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(mo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!J("vi"))return console.log(chalk.yellow(mo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(mo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(mo()?" 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 Jo("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`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(mo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(mo()?" 自测样例。":" to self-check the sample.")),console.log()})(t):"run"===o?(e=>{const o=Ho(e);if(!o)return;const{p:t,n:r}=o,l=v(Co.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(mo()?` 还没有 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(mo()?` 本题无样例(设计如此)— 用 /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)Ko();else if(o.killed)console.log(chalk.yellow(mo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(mo()?" ✗ 程序报错:":" ✗ 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(mo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(mo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(mo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(mo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(mo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(mo()?" 改完再 /run。":" then /run again.")),console.log()})(t):"debug"===o?await(async e=>{const o=Ho(e);if(!o)return;const n=v(Co.dir,`sol-${o.n}.py`);if(!d(n))return void console.log(chalk.yellow(mo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(mo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 Jo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(mo()?" 回到竞技场。":" Back in the arena.")),console.log()):Ko()})(t):"recall"===o&&await(async e=>{const o=Ho(e);if(!o)return;if(!qe)return void qo();const{p:n,n:t}=o,r=v(process.cwd(),"icoa-contest"),l=`${Pe.id}-phase${Co.phase}-g${Co.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(mo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${Co.phase}-${Co.data.slot}-${t}`,g=Math.min(3,(Qo.get(c)??0)+1);console.log(chalk.gray(mo()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await S({token:Se,phase:Co.phase,slot:Co.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:g,lang:mo()?"zh":"en"});if(m.ok){Qo.set(c,g),console.log();for(const e of Te(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(mo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(mo()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(mo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(t):console.log(chalk.yellow(mo()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(mo()?" (花名册: /list)":" (roster: /list)")),void ze()}if("contest"===o||"/contest"===o)return Fo(),void ze();const t="lang"===o||/^lang\s+\S+$/.test(o),r=xe.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(mo()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void ze()}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(mo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void ze()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(Ye.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{}Ye.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void ze()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(so=!0),void ze();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!qe)return qo(),void ze();lo||(lo=!0,console.log(),console.log(chalk.bold.cyan(mo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(mo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(mo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),mo()||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){Ge=!0;const e=ko(Re.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(mo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(mo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(mo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void ze()}return await Wo(t,n?"fast":"deep"),void ze()}if(!oo&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!qe)return qo(),void ze();const e=ko(Re.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(mo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(mo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(mo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(mo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(mo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(mo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(mo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),co=!0,void ze()}const _=!oo&&"honors"===no&&/^[1-3]$/.test(o);if(!oo&&no&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(mo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(mo()?" ↩ back 回上一层":" ↩ back goes up one level")),void ze();if(!oo&&(_||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!qe)return qo(),void ze();const e=/^\/?view ([1-3])$/.exec(o),n=_?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{eo=!0;try{console.log();const o=await q({token:Se,cardNumber:Re.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(mo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&go.delete(Re.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&go.add(Re.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(mo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${Re.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${Re.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(mo()?` (第 ${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(mo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=Ro(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(mo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),no="view",console.log(chalk.gray((mo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(mo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{eo=!1}})(n),void ze()}if("/honors"===o||"honors"===o)return Me?(console.log(),console.log(chalk.gray(mo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void ze()):(await Oo(),void ze());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return he(Pe,Re),void ze();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await A(Pe.id,Se,!0);return void(e?(Object.assign(Pe,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Mo()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本")),ze()))}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 ze();const n=Pe.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`)),Ze=null,He=null,Be=null,Xe(),uo=!1,co=!1,await No(),void ze()}if(xe.has(o)){const e=xe.get(o),n=ve(z()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return mo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((mo()?"normal"===e?" 已是标准 64 列。":Ae()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Ae()} 列,上限 ${Ce(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 ${Ce(e)}). `)+t(e))),void ze()):(H({learnWidth:e,learnWide:"normal"!==e}),ke(e),"normal"!==e&&Ae()<=64?(console.log(chalk.yellow(mo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((mo()?` 设置已记住(${e},上限 ${Ce(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Ce(e)} cols) and applies once you widen the window. `)+t(e))),void ze()):(console.log(chalk.green(" ✓ ")+chalk.gray((mo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Ae()} 列,上限 ${Ce(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Ae()} cols, cap ${Ce(e)}). `)+t(e))),Ze=null,He=null,Be=null,Xe(),uo=!1,co=!1,await No(),void ze()))}if("sim"===o){const e=ko(Re.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=k(C(import.meta.url)),o=[v(e,"..","..","panda","mujoco-launcher.py"),v(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const 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 ze()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ze())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=Re.currentCard,n=Re.bookmarks.includes(e),t="bookmark"!==o;return t?Re.bookmarks=Re.bookmarks.filter(o=>o!==e):n||Re.bookmarks.push(e),Q(Re),t?console.log(n?chalk.gray(mo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(mo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(mo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(mo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void ze()}if("e"===o)return Je=Re.currentCard,console.log(chalk.gray(mo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void ze();if("back"===o||"b"===o)return"view"===no?(await Oo(),void ze()):"honors"===no?(no=null,Mo(),void ze()):(Re.currentCard>1&&(Re.currentCard-=1),He=null,Be=null,Ze=null,Q(Re),Mo(),void ze());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!_o)return console.log(chalk.yellow(mo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void ze();if(!e){const e=await D(Se),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(mo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(mo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(mo()?` 这台电脑上有 ${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(mo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(mo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(mo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(mo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(mo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(mo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(mo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void ze()}if(/^\d{1,2}$/.test(e)){const o=await j(Se,Number(e));return o.ok&&o.data?(Yo(o.data),await To(),void ze()):(console.log(chalk.red(` ✗ ${o.message||(mo()?"关联失败":"Link failed")}`)),void ze())}const n=await Y(Se,e);return n.ok&&n.data?(Yo(n.data),await To(),void ze()):(console.log(chalk.red(` ✗ ${n.message||(mo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(mo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void ze())}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(!_o)return console.log(chalk.yellow(mo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void ze();const e=Io(Re.currentCard);if("contest reset"===o){const o=await R(Se,e);if(o.ok){console.log(chalk.yellow(mo()?` 已放弃当前计时(阶段 ${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",`${Pe.id}-phase${e}-g${n}`);if(d(t))try{m(t,`${t}-archived-${o}`),console.log(chalk.gray(mo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(mo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(mo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),Co=null,oo=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void ze()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(mo()?" 连接判分赛…":" Contacting contest server…"));const t=await N(Se,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(mo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void ze();const r=t.data,l=v(process.cwd(),"icoa-contest",`${Pe.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=Co&&Co.phase===e&&Co.data.slot===r.slot?Co.tried:new Set;Co={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} ══`,"#",...Do(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),oo=!0,Fo(),console.log(chalk.gray(mo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(mo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(mo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void ze()}if("submit"===s)return console.log(chalk.yellow(mo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(mo()?" 例如 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)")),Co||console.log(chalk.gray(mo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void ze();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const n=e[2];if(!Co)return console.log(chalk.yellow(mo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void ze();const t=Co.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(mo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void ze();const l=t.findIndex(e=>e.id===o)+1,a=n||v(Co.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(mo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void ze()}console.log(chalk.gray(mo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Ao.get(l),d=await O(Se,Co.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(mo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((mo()," "))+chalk.bold.green("contest")+chalk.gray(mo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(mo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void ze();const g=d.data;if(g.already_ac)console.log(chalk.green(mo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(mo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(mo()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),Co.data.solved.includes(o)||Co.data.solved.push(o),Co.tried.delete(o);else{Co.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?mo()?` · 挂在第 ${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(mo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=F(g.deadline||"");if(console.log(chalk.white(mo()?` 本组进度: 已过 ${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(mo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await To();else if(!g.late){const e=t.findIndex(e=>!Co.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(mo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${jo(t[e])}`))}return void ze()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Pe.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Pe.totalCards}. Try: `)+chalk.bold.green("card 1")),void ze();const t=await Eo(n);return t?(console.log(t),void ze()):(Re.currentCard=n,He=null,Be=null,Ze=null,Q(Re),Mo(),void ze())}if(null!==Ze&&["y","yes","n","no"].includes(o)){const e=ko(Ze);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-yo;ee(Re,e.number),ne(Re,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),Q(Re);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),po.push(T(Se,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),Ze=null,e.solution&&e.solution.length>0)return void ze();if(Re.currentCard<Pe.totalCards){const e=Re.currentCard,o=await Eo(e+1);if(o)return await So(e),console.log(o),void ze();Re.currentCard+=1,Q(Re),await So(e)?Po():Mo(),ze()}else fe(Pe,Re),ze();return}}if(null!==He&&["a","b","c","d"].includes(o)){const e=ko(He);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(oe(Re,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),ee(Re,e.number),Q(Re),ie(e,n,t,Re),po.push(T(Se,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),He=null,t)if(Re.currentCard<Pe.totalCards){const e=await Eo(Re.currentCard+1);if(e)return console.log(e),void ze();Re.currentCard+=1,Q(Re),Mo()}else fe(Pe,Re),ze();else ze();return}}if(null!==Be){if("done"===o){const e=ko(Be);if(e&&"practical"===e.type)return te(Re,e.number),ee(Re,e.number),Q(Re),de(e),Be=null,void ze()}if("skip"===o)return ee(Re,Be),Q(Re),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Be=null,void ze()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==He)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ze();if(null!==Be)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ze();if(null!==Ze)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ze();const e=Re.currentCard,o=e<Pe.totalCards?await Eo(e+1):null;return o?(await So(e),console.log(o),void ze()):(Re.currentCard+=1,Q(Re),Re.currentCard>Pe.totalCards?fe(Pe,Re):await So(e)?Po():Mo(),void ze())}if(null!==Ze)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ze();if(null!==He)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ze();if(null!==Be)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ze();"view"===no?console.log(chalk.gray(mo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(mo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(mo()?" 回卡片":" to the card")):"honors"===no?console.log(chalk.gray(mo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(mo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(mo()?" 回卡片":" 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")),ze()}else{if("view"===no)return await Oo(),void ze();if("honors"===no)return no=null,Mo(),void ze();if(po.length>0&&await Promise.race([Promise.allSettled(po),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Re.streakDays} day(s)`)),console.log(),je){Ye.removeAllListeners("line"),Fe();for(const e of De)Ye.on("line",e);Ye.prompt(),wo()}else Ye.removeAllListeners("line"),Ye.close()}else if(po.length>0&&await Promise.race([Promise.allSettled(po),new Promise(e=>setTimeout(e,3e3))]),Ye.removeAllListeners("line"),Fe(),je||!$o){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(je?Ye:void 0),wo()}else Ye.close()};Ye.on("line",e=>{Vo(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.")),ze()})}),je||Ye.on("close",async()=>{po.length>0&&await Promise.race([Promise.allSettled(po),new Promise(e=>setTimeout(e,5e3))]),$o?wo():process.exit(0)});try{Mo(),ze();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Ie("Could not render this card — the curriculum may be malformed."),je){Ye.removeAllListeners("line"),Fe();for(const e of De)Ye.on("line",e);Ye.prompt()}else Ye.close();wo()}await bo}),Ee.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 A(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()})}
@@ -3,6 +3,15 @@ export declare function classifyBurst(interKeyMs: number[]): {
3
3
  maxBurst: number;
4
4
  suspectPaste: boolean;
5
5
  };
6
+ export declare function countFocusMarkers(s: string): {
7
+ focusIn: number;
8
+ focusOut: number;
9
+ };
10
+ export declare function getFocusState(): 'in' | 'out' | 'unknown';
11
+ export declare function consumeFocusEvents(): Array<{
12
+ kind: 'focus_in' | 'focus_out';
13
+ ts: number;
14
+ }>;
6
15
  export declare function stripTerminalMarkers(line: string): string;
7
16
  export declare function installInputDynamics(enableBracketed?: boolean): void;
8
17
  export declare function uninstallInputDynamics(): void;
@@ -1 +1 @@
1
- import{armTerminalCleanup as s}from"./terminal-cleanup.js";let t=!1,e=0,n=null,r=[];function a(){return{start:Date.now(),keys:0,backspaces:0,pastes:0,pasteChars:0}}export function classifyBurst(s){let t=1,e=1;for(let n=1;n<s.length;n++)s[n]<5?(t++,t>e&&(e=t)):t=1;return{maxBurst:e,suspectPaste:e>=8}}export function stripTerminalMarkers(s){return s.replace(/\x1b?\[20[01]~/g,"").replace(/\x1b\[[IO]/g,"")}function c(s,t){n||(n=a());const c=Date.now();e&&r.push(c-e),e=c,n.keys++,"backspace"===t?.name&&n.backspaces++}function o(s){const t=s.toString("latin1");let e=t.indexOf("[200~");for(;-1!==e;){n||(n=a()),n.pastes++;const s=t.indexOf("[201~",e);-1!==s&&(n.pasteChars+=s-(e+6)),e=t.indexOf("[200~",e+6)}}export function installInputDynamics(a=!0){if(!t&&(t=!0,n=null,r=[],e=0,process.stdin.on("keypress",c),process.stdin.on("data",o),a&&process.stdout.isTTY))try{process.stdout.write("[?2004h"),s()}catch{}}export function uninstallInputDynamics(){if(t&&(t=!1,process.stdin.removeListener("keypress",c),process.stdin.removeListener("data",o),process.stdout.isTTY))try{process.stdout.write("[?2004l")}catch{}}export function consumeLineDynamics(){if(!n)return;const{maxBurst:s,suspectPaste:t}=classifyBurst(r),a={ms:Date.now()-n.start,keys:n.keys,backspaces:n.backspaces,pastes:n.pastes,pasteChars:n.pasteChars,maxBurst:s,suspectPaste:t||n.pastes>0};return n=null,r=[],e=0,a}
1
+ import{armTerminalCleanup as s}from"./terminal-cleanup.js";let t=!1,e=0,n=null,r=[];function o(){return{start:Date.now(),keys:0,backspaces:0,pastes:0,pasteChars:0}}export function classifyBurst(s){let t=1,e=1;for(let n=1;n<s.length;n++)s[n]<5?(t++,t>e&&(e=t)):t=1;return{maxBurst:e,suspectPaste:e>=8}}export function countFocusMarkers(s){let t=0,e=0;for(let n=0;n+2<s.length;n++)""===s[n]&&"["===s[n+1]&&("I"===s[n+2]?t++:"O"===s[n+2]&&e++);return{focusIn:t,focusOut:e}}let c=!1,u=!0,a=[],i="";export function getFocusState(){return c?u?"in":"out":"unknown"}export function consumeFocusEvents(){const s=a;return a=[],s}export function stripTerminalMarkers(s){return s.replace(/\x1b?\[20[01]~/g,"").replace(/\x1b\[[IO]/g,"")}function p(s,t){n||(n=o());const c=Date.now();e&&r.push(c-e),e=c,n.keys++,"backspace"===t?.name&&n.backspaces++}function l(s){const t=s.toString("latin1");let e=t.indexOf("[200~");for(;-1!==e;){n||(n=o()),n.pastes++;const s=t.indexOf("[201~",e);-1!==s&&(n.pasteChars+=s-(e+6)),e=t.indexOf("[200~",e+6)}const r=i+t;i=r.slice(-2);const{focusIn:p,focusOut:l}=countFocusMarkers(r),f=Date.now();for(let s=0;s<l;s++)c=!0,u=!1,a.push({kind:"focus_out",ts:f});for(let s=0;s<p;s++)c=!0,u=!0,a.push({kind:"focus_in",ts:f})}export function installInputDynamics(o=!0){if(!t&&(t=!0,n=null,r=[],e=0,c=!1,u=!0,a=[],i="",process.stdin.on("keypress",p),process.stdin.on("data",l),o&&process.stdout.isTTY))try{process.stdout.write("[?2004h"),process.stdout.write("[?1004h"),s()}catch{}}export function uninstallInputDynamics(){if(t&&(t=!1,process.stdin.removeListener("keypress",p),process.stdin.removeListener("data",l),process.stdout.isTTY))try{process.stdout.write("[?2004l"),process.stdout.write("[?1004l")}catch{}}export function consumeLineDynamics(){if(!n)return;const{maxBurst:s,suspectPaste:t}=classifyBurst(r),o={ms:Date.now()-n.start,keys:n.keys,backspaces:n.backspaces,pastes:n.pastes,pasteChars:n.pasteChars,maxBurst:s,suspectPaste:t||n.pastes>0};return n=null,r=[],e=0,o}
@@ -29,6 +29,7 @@ export type LearnInputResolution = {
29
29
  from?: string;
30
30
  } | {
31
31
  kind: 'continue';
32
+ which?: number | string;
32
33
  } | {
33
34
  kind: 'ambiguous';
34
35
  hint: string;
@@ -1 +1 @@
1
- const e={ai4ctf:"AI4CTFDEMO01",ctf4ai:"CTF4AIDEMO01",ctf4eai:"LEARNDEMO01","ai4ctf-12":"AI4CTFDEMO01","ctf4ai-12":"CTF4AIDEMO01","ctf4eai-12":"LEARNDEMO01","ioai-jr":"IOAIJRDEMO01","ioai-jr-48":"IOAIJRDEMO01",ioaijr:"IOAIJRDEMO01",junior:"IOAIJRDEMO01",jr:"IOAIJRDEMO01",ioaijrdemo:"IOAIJRDEMO01",ctf4vla:"LEARNDEMO01",vla:"LEARNDEMO01",embodied:"LEARNDEMO01",ai4ctfdemo:"AI4CTFDEMO01",ctf4aidemo:"CTF4AIDEMO01",learndemo:"LEARNDEMO01"},t={1:"AI4CTFDEMO01",2:"CTF4AIDEMO01",3:"LEARNDEMO01"},o=/^[A-Z0-9]{2,}DEMO\d+$/,i={biology:"BIODEMO01",bio:"BIODEMO01",coretools:"COREDEMO01","core-tools":"COREDEMO01",core:"COREDEMO01",worldmodel:"WMDEMO01","world-model":"WMDEMO01",wm:"WMDEMO01",arsenal:"ARSDEMO01",cybersec:"CYBERDEMO01",sc:"CYBERDEMO01",neuroscience:"NEURODEMO01",informatics:"IOIPYDEMO01",physics:"PHYSICSDEMO01",chemistry:"CHEMDEMO01",economics:"ECONDEMO01"};export function resolveLearnInput(n){const r=n.trim();if(!r)return{kind:"back"};if(/^(back|b|quit|q|exit|menu|home)$/i.test(r))return{kind:"back"};const a=r.replace(/^\s*(?:[/>])?\s*(?:icoa\s+)?learn\s+/i,"").trim();if(!a)return{kind:"ambiguous",hint:"Type just the token (e.g. LEARNDEMO01) or one of: ai4ctf / ctf4ai / ctf4eai"};if(/^(c|continue|cont|resume|last|继续|上次)$/i.test(a))return{kind:"continue"};if(t[a])return{kind:"token",token:t[a]};const c=a.toLowerCase();if(e[c])return{kind:"token",token:e[c]};if(i[c])return{kind:"token",token:i[c]};if("demo"===c||"demos"===c)return{kind:"ambiguous",hint:"Which demo? Type: 1 (ai4ctf) / 2 (ctf4ai) / 3 (ctf4eai)"};if(/\s/.test(a))return{kind:"unknown",hint:`Don't recognize "${r}". Try a track name (ai4ctf / ctf4ai / ctf4eai / junior), 1/2/3, a demo id like LEARNDEMO01, or paste your token (2 letters + 8 chars). Blank to go back.`};const E=a.toUpperCase();return o.test(E)||/^[A-Z]{2}[A-Z0-9]{8}$/.test(E)?{kind:"token",token:E}:/^[a-z][a-z0-9-]{2,15}$/.test(c)&&!c.includes("demo")?{kind:"token",token:`${c.replace(/-/g,"").toUpperCase()}DEMO01`,from:c}:/^[A-Z0-9]{8,}$/.test(E)&&/\d/.test(E)?{kind:"token",token:E}:{kind:"unknown",hint:`Don't recognize "${r}". Try a track name (e.g. ai4ctf, biology, ioipy), a demo id like LEARNDEMO01, or paste your cohort token (2 letters + 8 characters). Blank to go back.`}}
1
+ const e={ai4ctf:"AI4CTFDEMO01",ctf4ai:"CTF4AIDEMO01",ctf4eai:"LEARNDEMO01","ai4ctf-12":"AI4CTFDEMO01","ctf4ai-12":"CTF4AIDEMO01","ctf4eai-12":"LEARNDEMO01","ioai-jr":"IOAIJRDEMO01","ioai-jr-48":"IOAIJRDEMO01",ioaijr:"IOAIJRDEMO01",junior:"IOAIJRDEMO01",jr:"IOAIJRDEMO01",ioaijrdemo:"IOAIJRDEMO01",ctf4vla:"LEARNDEMO01",vla:"LEARNDEMO01",embodied:"LEARNDEMO01",ai4ctfdemo:"AI4CTFDEMO01",ctf4aidemo:"CTF4AIDEMO01",learndemo:"LEARNDEMO01"},t={1:"AI4CTFDEMO01",2:"CTF4AIDEMO01",3:"LEARNDEMO01"},o=/^[A-Z0-9]{2,}DEMO\d+$/,i={biology:"BIODEMO01",bio:"BIODEMO01",coretools:"COREDEMO01","core-tools":"COREDEMO01",core:"COREDEMO01",worldmodel:"WMDEMO01","world-model":"WMDEMO01",wm:"WMDEMO01",arsenal:"ARSDEMO01",cybersec:"CYBERDEMO01",sc:"CYBERDEMO01",neuroscience:"NEURODEMO01",informatics:"IOIPYDEMO01",physics:"PHYSICSDEMO01",chemistry:"CHEMDEMO01",economics:"ECONDEMO01"},n="c|continue|cont|resume|last|继续|上次",r=new RegExp(`^(?:${n})$`,"i"),c=new RegExp(`^(?:${n})\\s+(\\S+)$`,"i"),a=new RegExp(`^(?:${n})(\\d+)$`,"i");export function resolveLearnInput(n){const E=n.trim();if(!E)return{kind:"back"};if(/^(back|b|quit|q|exit|menu|home)$/i.test(E))return{kind:"back"};const O=E.replace(/^\s*(?:[/>])?\s*(?:icoa\s+)?learn\s+/i,"").trim();if(!O)return{kind:"ambiguous",hint:"Type just the token (e.g. LEARNDEMO01) or one of: ai4ctf / ctf4ai / ctf4eai"};if(r.test(O))return{kind:"continue"};const s=O.match(c)??O.match(a);if(s){const e=s[1];return{kind:"continue",which:/^\d+$/.test(e)?Number(e):e.toLowerCase()}}if(t[O])return{kind:"token",token:t[O]};const M=O.toLowerCase();if(e[M])return{kind:"token",token:e[M]};if(i[M])return{kind:"token",token:i[M]};if("demo"===M||"demos"===M)return{kind:"ambiguous",hint:"Which demo? Type: 1 (ai4ctf) / 2 (ctf4ai) / 3 (ctf4eai)"};if(/\s/.test(O))return{kind:"unknown",hint:`Don't recognize "${E}". Try a track name (ai4ctf / ctf4ai / ctf4eai / junior), 1/2/3, a demo id like LEARNDEMO01, or paste your token (2 letters + 8 chars). Blank to go back.`};const D=O.toUpperCase();return o.test(D)||/^[A-Z]{2}[A-Z0-9]{8}$/.test(D)?{kind:"token",token:D}:/^[a-z][a-z0-9-]{2,15}$/.test(M)&&!M.includes("demo")?{kind:"token",token:`${M.replace(/-/g,"").toUpperCase()}DEMO01`,from:M}:/^[A-Z0-9]{8,}$/.test(D)&&/\d/.test(D)?{kind:"token",token:D}:{kind:"unknown",hint:`Don't recognize "${E}". Try a track name (e.g. ai4ctf, biology, ioipy), a demo id like LEARNDEMO01, or paste your cohort token (2 letters + 8 characters). Blank to go back.`}}
@@ -25,6 +25,30 @@ export type LearnState = {
25
25
  achievements: string[];
26
26
  totalSecondsActive: number;
27
27
  };
28
+ /** Courses listed on the Learn picker. The rest need `c <track>` or `c all`. */
29
+ export declare const CONTINUE_LIST_MAX = 5;
30
+ /**
31
+ * Every remembered course, most-recently-seen first.
32
+ *
33
+ * The active session comes from learn-state.json; a same-token copy left in the
34
+ * archive is ignored (see `activateSession` — promotion deliberately does not
35
+ * delete, so the active file always wins).
36
+ */
37
+ export declare function listLearnSessions(): LearnState[];
38
+ /**
39
+ * Switch the active course to `token`.
40
+ *
41
+ * Archives whichever course is active now, then returns this token's stored
42
+ * progress if we have ever seen it (the caller writes it back via
43
+ * `saveLearnState`, keeping a single writer for learn-state.json). Returns null
44
+ * for a course this machine has never opened — the caller makes a fresh state.
45
+ *
46
+ * Promotion does NOT delete the archived copy. Deleting would open a window
47
+ * where a crash between this call and the caller's `saveLearnState` loses the
48
+ * course from both files; leaving a stale copy is harmless because the lookup
49
+ * rule always prefers the active file for the active token.
50
+ */
51
+ export declare function activateSession(token: string): LearnState | null;
28
52
  export declare function loadLearnState(): LearnState | null;
29
53
  export declare function saveLearnState(state: LearnState): void;
30
54
  export declare function newLearnState(token: string, curriculumId: string, totalCards: number): LearnState;
@@ -1 +1 @@
1
- import{join as e}from"node:path";import{getIcoaDir as t,getInstallSalt as r}from"./config.js";import{deriveFileKey as a,readSignedFile as n,writeSignedFile as o,recordVerdict as s}from"./secure-store.js";const c="learn-state";function i(){return e(t(),"learn-state.json")}function l(){return a(r(),c)}export function loadLearnState(){const{data:e,verdict:t}=n(i(),l());return s(c,t),e}export function saveLearnState(e){e.lastSeenAt=(new Date).toISOString(),o(i(),e,l())}export function newLearnState(e,t,r){const a=(new Date).toISOString();return{token:e,curriculumId:t,currentCard:1,totalCards:r,startedAt:a,lastSeenAt:a,streakDays:1,longestStreak:1,cardsCompleted:[],mcqResults:{},checkResults:{},practicalsCompleted:[],bookmarks:[],achievements:[],totalSecondsActive:0}}export function updateStreak(e){const t=new Date(e.lastSeenAt),r=new Date,a=Math.floor(t.getTime()/864e5),n=Math.floor(r.getTime()/864e5)-a;0!==n&&(1===n?(e.streakDays+=1,e.streakDays>e.longestStreak&&(e.longestStreak=e.streakDays)):e.streakDays=1)}export function markCardComplete(e,t){e.cardsCompleted.includes(t)||e.cardsCompleted.push(t)}export function recordMCQ(e,t,r){e.mcqResults[String(t)]=r}export function recordCheck(e,t,r){e.checkResults||(e.checkResults={}),e.checkResults[String(t)]=r}export function markPracticalComplete(e,t){e.practicalsCompleted.includes(t)||e.practicalsCompleted.push(t)}export function addAchievement(e,t){e.achievements.includes(t)||e.achievements.push(t)}
1
+ import{join as t}from"node:path";import{getIcoaDir as e,getInstallSalt as n}from"./config.js";import{deriveFileKey as o,readSignedFile as r,writeSignedFile as s,recordVerdict as c}from"./secure-store.js";const a="learn-state";function i(){return t(e(),"learn-state.json")}function l(){return o(n(),a)}const u="learn-sessions";export const CONTINUE_LIST_MAX=5;function p(){return t(e(),"learn-sessions.json")}function d(){return o(n(),u)}function f(){const{data:t,verdict:e}=r(p(),d());if(c(u,e),!t||"object"!=typeof t)return{};const n={};for(const[e,o]of Object.entries(t))o&&"object"==typeof o&&"string"==typeof o.token&&"string"==typeof o.curriculumId&&(n[e]=o);return n}export function listLearnSessions(){const t=loadLearnState(),e=[];t?.token&&t.curriculumId&&e.push(t);for(const[n,o]of Object.entries(f()))n!==t?.token&&e.push(o);return e.sort((t,e)=>(e.lastSeenAt??"").localeCompare(t.lastSeenAt??""))}export function activateSession(t){const e=loadLearnState(),n=f();e?.token&&e.curriculumId&&e.token!==t&&(n[e.token]=e);const o=n[t]??null;return function(t){const e=Object.keys(t);if(e.length>20){const n=e.sort((e,n)=>(t[e].lastSeenAt??"").localeCompare(t[n].lastSeenAt??"")).slice(0,e.length-20);for(const e of n)delete t[e]}s(p(),t,d())}(n),o}export function loadLearnState(){const{data:t,verdict:e}=r(i(),l());return c(a,e),t}export function saveLearnState(t){t.lastSeenAt=(new Date).toISOString(),s(i(),t,l())}export function newLearnState(t,e,n){const o=(new Date).toISOString();return{token:t,curriculumId:e,currentCard:1,totalCards:n,startedAt:o,lastSeenAt:o,streakDays:1,longestStreak:1,cardsCompleted:[],mcqResults:{},checkResults:{},practicalsCompleted:[],bookmarks:[],achievements:[],totalSecondsActive:0}}export function updateStreak(t){const e=new Date(t.lastSeenAt),n=new Date,o=Math.floor(e.getTime()/864e5),r=Math.floor(n.getTime()/864e5)-o;0!==r&&(1===r?(t.streakDays+=1,t.streakDays>t.longestStreak&&(t.longestStreak=t.streakDays)):t.streakDays=1)}export function markCardComplete(t,e){t.cardsCompleted.includes(e)||t.cardsCompleted.push(e)}export function recordMCQ(t,e,n){t.mcqResults[String(e)]=n}export function recordCheck(t,e,n){t.checkResults||(t.checkResults={}),t.checkResults[String(e)]=n}export function markPracticalComplete(t,e){t.practicalsCompleted.includes(e)||t.practicalsCompleted.push(e)}export function addAchievement(t,e){t.achievements.includes(e)||t.achievements.push(e)}
@@ -1 +1 @@
1
- import{writeSync as e}from"node:fs";export function isIcoaTerminal(){return"1"===process.env.ICOA_TERMINAL}export function supportsAnsi(){if(!process.stdout.isTTY)return!1;const e=process.stdout.getColorDepth?.();return"number"!=typeof e||e>=8}export function buildCleanupSequence(e){return"[?2004l[?25h"+(e.ansi&&!e.icoaTerminal?"]110]111]112":"")}export function cleanupTerminal(){if(!process.stdout.isTTY)return;const n=buildCleanupSequence({ansi:supportsAnsi(),icoaTerminal:isIcoaTerminal()});try{e(process.stdout.fd,n)}catch{try{process.stdout.write(n)}catch{}}}let n=!1;export function armTerminalCleanup(){if(n)return;n=!0,process.on("exit",cleanupTerminal);const e={SIGINT:130,SIGTERM:143,SIGHUP:129};for(const[n,r]of Object.entries(e))process.on(n,()=>{cleanupTerminal(),process.exit(r)})}
1
+ import{writeSync as e}from"node:fs";export function isIcoaTerminal(){return"1"===process.env.ICOA_TERMINAL}export function supportsAnsi(){if(!process.stdout.isTTY)return!1;const e=process.stdout.getColorDepth?.();return"number"!=typeof e||e>=8}export function buildCleanupSequence(e){return"[?2004l[?1004l[?25h"+(e.ansi&&!e.icoaTerminal?"]110]111]112":"")}export function cleanupTerminal(){if(!process.stdout.isTTY)return;const n=buildCleanupSequence({ansi:supportsAnsi(),icoaTerminal:isIcoaTerminal()});try{e(process.stdout.fd,n)}catch{try{process.stdout.write(n)}catch{}}}let n=!1;export function armTerminalCleanup(){if(n)return;n=!0,process.on("exit",cleanupTerminal);const e={SIGINT:130,SIGTERM:143,SIGHUP:129};for(const[n,r]of Object.entries(e))process.on(n,()=>{cleanupTerminal(),process.exit(r)})}