icoa-cli 2.19.555 → 2.19.557

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{rearmFocusMode as s}from"../lib/input-dynamics.js";import{FOCUS_MAX as l,FOCUS_MIN as a,FOCUS_STEP as i,getStudyTimer as c,parseFocusMinutes as d}from"../lib/learn-study-timer.js";import{FOCUS_LOG_RE as g,fetchFocusLog as u,renderFocusLog as h}from"../lib/learn-focus-log.js";import{setLearnFooterExtra as p}from"../lib/learn-render.js";import{fetchLearnProfile as y,postCreditsRolled as m,renderLearnProfile as f}from"../lib/learn-profile.js";import{buildCreditLines as $,creditsProgress as b,creditsRoadLines as w,rollCredits as k,storyListLines as v}from"../lib/learn-credits.js";import{logCommand as _}from"../lib/logger.js";import{startEditSampler as C}from"../lib/edit-sampler.js";import{probeVimInsertExpand as A}from"../lib/editor-spawn.js";import{getMainRl as x,setMainRl as T}from"../lib/main-rl.js";import{assetDir as S,lazyJson as P}from"../lib/lazy-assets.js";import{JudgeWaitLine as I}from"../lib/judge-wait.js";import{ai4ioaiPromptLabel as j,handleAi4ioaiMessage as E,startAi4ioaiChat as L}from"./ai4ioai.js";import{existsSync as M,mkdirSync as N,readdirSync as q,readFileSync as O,renameSync as W,statSync as R,writeFileSync as D}from"node:fs";import{emptyDynamics as U,foldEditSession as Y,isEmpty as B,noteRun as F}from"../lib/arena-edit-dynamics.js";import{dirname as z,join as G}from"node:path";import{fileURLToPath as H}from"node:url";import{loadCurriculumById as Z,validateEAToken as K,syncProgress as J,fetchServerProgress as Q,syncCardFeedback as X,fetchCardFaqs as V}from"../lib/learn-curricula.js";import{hometaskDetailLines as ee,hometaskLines as oe,isTaskCommand as te}from"../lib/learn-hometask.js";import{detectCaps as ne}from"../lib/render-card.js";import{parseReplyCommand as re,renderReplyLines as se,replyPushLine as le}from"../lib/learn-replies.js";import{ensureFullTable as ae,lookupPydoc as ie,lookupRanked as ce,refetchTableOnMiss as de,nearKeys as ge,renderIndex as ue,renderPydoc as he,renderSyntax as pe,tableSize as ye}from"../lib/py-syntax.js";import{normalizeTokenBody as me}from"../lib/token-format.js";import{fetchMyScores as fe,recallCoach as $e,setNickname as be,streamLearnTutor as we,submitPqs as ke,viewPqsTop as ve,viewHonors as _e}from"../lib/learn-ai.js";import{contestReset as Ce,contestStart as Ae,contestSubmit as xe,linkByIndex as Te,linkSuggest as Se,linkToken as Pe,fetchGate as Ie,timeLeft as je,arenaSlotAtPos as Ee,posForArenaSlot as Le}from"../lib/learn-contest.js";import{WARMUP as Me,WARMUP_ID as Ne,WARMUP_N as qe,WARMUP_TESTS as Oe,gradeWarmup as We,warmupEnabled as Re}from"../lib/warmup.js";import{PY_MAX_CODE_BYTES as De,PY_MAX_FILES as Ue,PY_TEMPLATE_EN as Ye,PY_SPOOL_BATCH as Be,PY_TEMPLATE_ZH as Fe,listScratchFiles as ze,localTimeNote as Ge,nextScratchN as He,readPyScratchSpool as Ze,scratchCodeSha as Ke,scratchDir as Je,scratchFilePath as Qe,scratchTitleOf as Xe,shrinkPyScratchSpool as Ve,spoolPyScratchEvent as eo,startRunTimer as oo,syncPyScratch as to}from"../lib/py-scratch.js";import{SH_TIMEOUT_MS as no,ensureLabDir as ro,interactiveHint as so,labCardDir as lo,labRoot as ao,resolveCd as io,runShell as co,shortCwd as go,tildePath as uo}from"../lib/sh-lab.js";import{verdictLine as ho}from"../lib/verdict.js";import{printNoPython312 as po,probePython as yo}from"../lib/python-setup.js";function mo(){const e=yo();return e.ok&&e.cmd?{cmd:e.cmd}:null}const fo=()=>mo()?.cmd??null;import{homedir as $o}from"node:os";import{getConfig as bo,saveConfig as wo}from"../lib/config.js";import{runType as ko}from"./type.js";import{isNativeWindows as vo,isWindowsBuildInWslShell as _o,whichBinary as Co}from"../lib/platform.js";import{loadLearnState as Ao,saveLearnState as xo,newLearnState as To,stateFromServerEvents as So,activateSession as Po,updateStreak as Io,markCardComplete as jo,recordMCQ as Eo,recordCheck as Lo,markPracticalComplete as Mo,addAchievement as No}from"../lib/learn-state.js";import{renderWelcome as qo,renderKnowledgeCard as Oo,renderMCQCard as Wo,renderMCQFeedback as Ro,renderPracticalCard as Do,renderPracticalSuccess as Uo,renderSimDemoCard as Yo,renderMilestone as Bo,renderArenaTaskCard as Fo,renderArenaIntro as zo,renderComingSoonCard as Go,renderStatus as Ho,renderPhaseComplete as Zo,renderCurriculumComplete as Ko,setLearnAiEnabled as Jo,setLearnFaqs as Qo,setLearnFooterProfile as Xo,setLearnShellLane as Vo,setLearnHometask as et,setLearnPracticeChips as ot,setLearnPracticeCount as tt,setLearnHonorRanks as nt,setLearnPqsViewCards as rt,setLearnReplies as st,setLearnWidth as lt,resolveLearnWidth as at,learnWidthCap as it,learnW as ct,renderHonorWall as dt,wrapMixed as gt}from"../lib/learn-render.js";import{printError as ut}from"../lib/ui.js";const ht=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","widest"],["wide max","widest"]]);function pt(e,o){e.forEach((t,n)=>{const r=n===e.length-1;0===n?console.log(chalk.bold.cyan(` ${t}`)):/^[─-]+$/.test(t.trim())&&t.trim().length>3?console.log(chalk.gray(` ${t}`)):r?console.log((o?chalk.bold.green:chalk.yellow)(` ${t}`)):console.log(chalk.white(` ${t}`))}),console.log()}export function registerLearnCommand(yo){yo.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async yo=>{yo?.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(),yo="LEARNDEMO01");let yt=yo.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(yt)){const{runSprint:e}=await import("./sprint.js");return void await e()}let mt=null;const ft=/^[A-Z0-9]+DEMO01$/i.test(yt),$t=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(yt);let bt=!1,wt=!1,kt=[],vt=null,_t=-1,Ct=Promise.resolve([]);if(ft)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Ct=V(yt),mt=await Z(yt,yt,!0);else if($t){console.log(),console.log(chalk.gray(" Validating token..."));let e=await K(yt);if(!e.ok){const o=me(yt);if(o!==yt){const t=await K(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${yt} → ${o}`)),e=t,yt=o)}}if(!e.ok)return ut(`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 🐼"):"")),bt=!0===e.aiEnabled,wt=!0===e.gated,kt=e.replies??[],vt=e.hometask??null,Ct=V(yt),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),mt=await Z(e.curriculumId||"LEARNDEMO01",yt,!0),!mt)return ut(`Could not open a learn curriculum for token '${yt}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${yt}`)+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 ${yt}`)+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(!mt){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(ut(`Could not reach the learn server to open ${yt}.`),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 ${yt}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(ut(`Unknown learn token: ${yt}`),console.log(),console.log(chalk.gray(" A learn token is ")+chalk.bold.yellow("2 letters + 8 characters")+chalk.gray(", issued by your team leader.")),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 At=Ao(),xt=!1;try{if(At&&At.token===yt)Io(At);else{const e=Po(yt);if(e)At=e,At.totalCards=mt.totalCards,Io(At);else{const e=await Q(yt),o=e?So(yt,mt.id,mt.totalCards,e):null;o?(At=o,console.log(chalk.green(" ↩ ")+chalk.white((bo().language||"en").toLowerCase().startsWith("zh")?`已从服务器取回你的进度:${o.cardsCompleted.length} 张卡已完成,从第 ${o.currentCard} 张继续`:`Restored your progress from the server: ${o.cardsCompleted.length} cards done, resuming at card ${o.currentCard}`)),console.log()):(At=To(yt,mt.id,mt.totalCards),xt=!0)}}xo(At),qo(mt,At,xt),function(e){if(!e)return;const o=(bo().language||"en").toLowerCase().startsWith("zh"),t="T0"===ne().tier;pt(oe(e,o,ct(),t),!!e.completedAt)}(vt)}catch{return ut("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 ${yt}`)+chalk.gray(".")),void console.log()}const Tt=x(),St=null!==Tt,Pt=St?Tt.listeners("line").slice():[];St&&Tt.removeAllListeners("line");const It=St?Tt:o({input:process.stdin,output:process.stdout,terminal:!0}),jt=St?It.prompt:null;St&&(It.prompt=e.prototype.prompt);const Et=()=>{St&&jt&&(It.prompt=jt)};let Lt=null,Mt=!1,Nt=!1,qt=null,Ot=!1;const Wt=()=>{It.setPrompt(an?chalk.bold.green(`icoa ${j()}> `):en?chalk.bold.magenta(Hr()):Vt?chalk.bold.magenta("icoa py> "):Xt?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Jt?"icoa learn ai> ":"icoa learn> ")),It.prompt(),Lt?.onPromptIdle()};let Rt=null,Dt=null,Ut=null,Yt=null,Bt=[],Ft=!1,zt=null;const Gt=/^(quit|exit|q|back|b|menu|home|contest(\s+(\d+|reset))?)$/i;let Ht=null,Zt=!1;const Kt=()=>{zt&&clearTimeout(zt),zt=null,Bt=[],Ft=!1,Yt=null,Ht=null};let Jt=!1,Qt=!1,Xt=!1,Vt=!1,en=!1,on=null,tn=null,nn=null,rn=!1,sn=0,ln=!1,an=!1;const cn=new Map,dn=()=>{let e=cn.get(At.currentCard);return e||(e=[],cn.set(At.currentCard,e)),e};let gn=!1;const un=new Set;let hn=!1,pn=0;const yn=()=>(bo().language||"en").toLowerCase().startsWith("zh");Jo(bt),lt(at(bo())),rt(un);const mn=new Map;nt(mn),st(kt),et(vt);const fn="fill"===mt.practiceMode;Vo(Boolean(mt.shellLane)),Xo("minimal"===mt.footerProfile?"minimal":"full"),ot(e=>{const o=An(e),t=o?pr(o):null;if(!t)return null;const n=Wn.get(dr+e);return t.map((e,o)=>`[${o+1}]${n?.has(hr(e.py_id))||n?.has(e.py_id)?"✅":"⬜"}`).join(" ")});const $n=e=>{const o=An(e),t=o?pr(o):null;if(!t)return null;const n=Wn.get(dr+e);return{solved:t.filter(e=>n?.has(hr(e.py_id))||n?.has(e.py_id)).length,total:t.length}};tt($n);const bn=await Ct;Qo(bn);const wn=[];let kn=null;const vn=new Promise(e=>{kn=e}),_n=()=>{const e=kn;kn=null,e?.()},Cn="1"===process.env.ICOA_LEARN_EMBEDDED,An=e=>mt.cards.find(o=>o.number===e);Lt=c();const xn={isZh:yn,canInterrupt:()=>!(Ot||Qt||Jt||Xt||Vt||an||null!==tn||null!==Yt||null!==nn),lineEmpty:()=>!It.line,clearLine:()=>{try{process.stdout.write("\r")}catch{}},prompt:Wt,currentCard:()=>At.currentCard};p(()=>{const e=[],o=Lt?.footerLine();o&&e.push(o);const t=Sn();return null!==t&&t>0&&t<=2&&e.push(yn()?`🎁 还差 ${t} 项 · credits 看路线`:`🎁 ${t} to go · credits shows the road`),e.length?e.join("\n "):null});const Tn=async(e,o)=>{const t=yn();if(ft)return void console.log(chalk.gray(t?"故事属于正式 learn token。":" Stories belong to full learn tokens."));const n=await y(yt,o?null===e?"credits":"story":"auto");if("ok"!==n.kind){if(!o)return;return void console.log(chalk.yellow(t?" 连不上 learn 服务器 — 故事的数据住在服务端,联网后再敲 story。":" Cannot reach the learn server — your story lives there; type story again online."))}const r=n.profile;if("list"===e){console.log();for(const e of v(r,t))console.log(e);return void console.log()}let s=null===e?r.tokens.find(e=>e.curriculum_id===mt.id):void 0;if(null!==e){const o=Number(e);s=Number.isInteger(o)&&o>=1&&o<=r.tokens.length?r.tokens[o-1]:r.tokens.find(o=>o.curriculum_id.toLowerCase()===e||o.curriculum_id.toLowerCase().startsWith(e))}if(!s){console.log(),console.log(chalk.yellow(t?` 没有「${e}」这门课的故事。`:` No story for "${e}".`));for(const e of v(r,t))console.log(e);return void console.log()}if(!o&&!s.credits?.completed){const e=s.credits,o=[];e&&e.checks_total>0&&o.push(t?`自测 ${e.checks_answered}/${e.checks_total}`:`checks ${e.checks_answered}/${e.checks_total}`),s.practice.total>0&&o.push(t?`练习 ${s.practice.ac}/${s.practice.total} AC`:`practice ${s.practice.ac}/${s.practice.total} AC`),s.contests.total>0&&o.push(t?`检查点 ${s.contests.passed}/${s.contests.total} 过线`:`checkpoints ${s.contests.passed}/${s.contests.total} passed`),console.log(chalk.bold.white(t?" 🏁 离谢幕还差:":" 🏁 To the credits: ")+chalk.gray(o.join(" · ")));for(const e of w(mt,At,In,t))console.log(e);return console.log(chalk.gray(t?" 三项全满,谢幕自动上演 · contest 看未过的场次 · story 看这门课的故事":" all three full → the credits roll · contest lists what is left · story for this course so far")),void console.log()}const l=$(s,r,s.curriculum_id===mt.id?mt.name:s.curriculum_id,s.curriculum_id===mt.id?{longestStreak:At.longestStreak,bookmarks:At.bookmarks?.length??0}:{},t,ct(),"T0"===ne().tier);console.log(),console.log(chalk.gray(t?" (回车跳到结尾)":" (Enter skips to the end)")),Mt=!0,Nt=!1;try{await k(l,()=>Nt)}finally{Mt=!1}if(s.curriculum_id===mt.id&&!s.credits?.completed){for(const e of w(mt,At,In,t))console.log(e);console.log()}s.credits?.completed&&!s.credits.credits_rolled_at&&m(s.token,s.curriculum_id),console.log(chalk.gray(t?" ↩ 回车继续 · story 选另一门 · me 看档案":" ↩ Enter to continue · story to pick another · me for your profile")),console.log()},Sn=()=>{if(!At||At.creditsShownAt||ft||!In)return null;const e=b(mt,At,In);return e.complete?0:Math.max(0,e.checks[1]-e.checks[0])+Math.max(0,e.practice[1]-e.practice[0])+Math.max(0,e.contests[1]-e.contests[0])},Pn=async(e=!1)=>{if(!At||At.creditsShownAt||ft)return;const o=b(mt,At,In);if(!o.complete){const t=Math.max(0,o.checks[1]-o.checks[0])+Math.max(0,o.practice[1]-o.practice[0])+Math.max(0,o.contests[1]-o.contests[0]);if(In&&t>0&&t<=2&&(e||At.creditsTeasedLeft!==t)){At.creditsTeasedLeft=t,xo(At);const e=yn(),n=[];o.checks[1]>o.checks[0]&&n.push(e?o.checks[1]-o.checks[0]+" 个自测":`${o.checks[1]-o.checks[0]} check${o.checks[1]-o.checks[0]===1?"":"s"}`),o.practice[1]>o.practice[0]&&n.push(e?o.practice[1]-o.practice[0]+" 道练习":`${o.practice[1]-o.practice[0]} practice problem${o.practice[1]-o.practice[0]===1?"":"s"}`),o.contests[1]>o.contests[0]&&n.push(e?o.contests[1]-o.contests[0]+" 场检查点":`${o.contests[1]-o.contests[0]} checkpoint${o.contests[1]-o.contests[0]===1?"":"s"}`),console.log(),console.log(chalk.yellow(" 🎁 ")+chalk.bold.white(e?`还差 ${t} 项`:`${t} to go`)+chalk.gray(e?` — ${n.join("、")}。全部完成,会有一点小东西。`:` — ${n.join(" and ")}. Finish them all and something happens.`));for(const o of w(mt,At,In,e))console.log(o);console.log()}return}At.creditsShownAt=(new Date).toISOString(),xo(At),await Tn(null,!1),Wt()};let In=null,jn=null;const En=new Map,Ln=new Map;let Mn=null;const Nn=(e,o)=>Mn?.[`${mt.id}:${e}:${o}`]??null;P("contest-cells.json").then(e=>{Mn=e?.map??null;for(const[e,o]of Object.entries(Mn??{}))e.startsWith(`${mt.id}:`)&&P(o)});const qn=(e,o,t)=>{const n=Nn(e,o);if(!n)return null;const r=G(t,"explore.ipynb");if(!M(r)){const e=G(S(),n);if(!M(e))return null;try{D(r,O(e))}catch{return null}}return r},On=!yt.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(yt),Wn=new Map,Rn=new Map,Dn=new Set,Un=async()=>{if(!On)return;const e=await Ie(yt);if(e.ok&&e.data){In=e.data;for(const o of e.data.practice??[]){let e=Wn.get(o.slot);e||(e=new Set,Wn.set(o.slot,e));for(const t of o.solved)e.add(t)}Pn()}},Yn=e=>{const o=mt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Bn=e=>{if(!wt||!In)return null;const o=Yn(e);if(o<=In.unlocked_through_phase)return null;const t=In.phases.find(e=>e.phase===In.unlocked_through_phase),n=[chalk.yellow(yn()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${In.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${In.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(yn()?` ⚔ 练习赛 ${In.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${In.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(yn()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}if(t?.checks?.enabled&&!t.checks.passed){const e=t.checks.missing??[],o=e.slice(0,8).join(yn()?"、":", "),r=e.length>8?yn()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:yn()?" 张":"";n.push(chalk.gray(yn()?` ✓ 逐卡自测: ${t.checks.good}/${t.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${t.checks.good}/${t.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return t?.research&&!t.research.passed&&n.push(chalk.gray(yn()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},Fn=async e=>wt?null===Bn(e)?null:(await Un(),Bn(e)):null;On&&await Un();const zn=async e=>{const o=mt.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=mt.modules.find(e=>e.number===o.number+1);let n;if(bt){const e=await fe({token:yt,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}On&&await Un();const r=In?.phases.find(e=>e.phase===o.number);return Zo(mt,At,o,t,n,r),!0},Gn=()=>{hn=!0,console.log(chalk.gray(yn()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Hn=()=>{nn=null;const e=An(At.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(Lt?.noteCardShown(e.number,At.cardsCompleted.includes(e.number)),e.type){case"knowledge":{const o=fn&&Boolean(At.checkResults?.[String(e.number)])&&e.check?{...e,check:void 0}:e;Oo(o,mt),o.check?(Ut=e.number,pn=Date.now()):(jo(At,e.number),xo(At));break}case"mcq":Wo(e,mt),Rt=e.number;break;case"practical":Do(e,mt),Dt=e.number;break;case"sim_demo":Yo(e,mt),jo(At,e.number),xo(At);break;case"milestone":Bo(e,mt),No(At,e.badge),jo(At,e.number),xo(At);break;case"arena_task":Fo(e,mt),jo(At,e.number),xo(At);break;case"coming_soon":Go(e,mt),jo(At,e.number),xo(At)}Zn(e.number),mr(e)},Zn=e=>{if(!On||!In)return;const o=mt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1,n=Ee(t);if(0===n)return;const r=In.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n),l=()=>{At.arenaIntroShownAt||(zo(),At.arenaIntroShownAt=(new Date).toISOString(),xo(At))};if(!s){const e=o.cardRange;if(e[1]-e[0]+1>12)return;l();const t="═".repeat(ct()),r=chalk.bold.yellow(" ║ ");return console.log(chalk.bold.yellow(` ╔${t}`)),console.log(r+chalk.bold.white("⚔ "+(yn()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(yn()?" 制作中":" in production")),console.log(r+chalk.white(yn()?"这里以后有一场判分赛 — 很快更新。":"A judged arena lands here — coming soon.")),console.log(r+chalk.gray(yn()?"每 4 张卡一场:卡 4 / 8 / 12,本阶段共 3 场,全过解锁下一阶段。"+(fn?"(本轨无 research)":""):"One every 4 cards — 4 / 8 / 12, three this phase; all three unlock the next."+(fn?" (no research on this track)":""))),console.log(r+chalk.gray(yn()?"▸ 现在什么都不用做 — 敲 ":"▸ Nothing to do yet — type ")+chalk.bold.green("next")+chalk.gray(yn()?" 继续读卡。":" and keep reading.")),console.log(chalk.bold.yellow(` ╚${t}`)),void console.log()}l();const a=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),l=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const t=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${t(o.getMonth()+1)}-${t(o.getDate())} ${t(o.getHours())}:${t(o.getMinutes())}`})(n);return`🏆 ${e} ${o}/${s.n}`+(r?yn()?` · 用时 ${r}`:` · in ${r}`:"")+(l?` · ${l}`:"")},i=s.perfect_runs??[],c=!!s.best&&(s.best.ac??0)>0,d=chalk.bold.yellow(" ║ "),g="═".repeat(ct());if(console.log(chalk.bold.yellow(` ╔${g}`)),console.log(d+chalk.bold.white(`⚔ ${yn()?`练习赛 ${o.number}-${n}`:s.title||`PY Arena ${o.number}-${n}`}`)+(s.passed?chalk.bold.green(yn()?" ✅ 已通过":" ✅ passed"):"")),!s.passed){if(yn()?console.log(d+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(d+chalk.white("You learned the cards — now prove it.")),console.log(d+chalk.white("The clock starts the moment you type the command."))),console.log(d+chalk.gray(yn()?`${s.n} 题 · AC ${s.need} 过关 · 限时 ${s.duration_minutes} 分钟 · 无限重开`:`${s.n} problems · AC ${s.need} to pass · ${s.duration_minutes} min · unlimited retries`)),(s.carryable_ac??0)>0){const e=(s.carry_from??[]).join(", "),o=e?yn()?`(${e})`:` (${e})`:"";console.log(d+chalk.cyan(yn()?`🔗 你另一个 token${o}已做过这组的 ${s.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens${o} solved ${s.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yn()?" 带过来(现在不做也行)":" to carry them over (or skip)"))}1!==o.number||fn||console.log(d+chalk.gray(yn()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))}if(i.length>0)for(const e of i)console.log(d+chalk.bold.yellow(a(yn()?"满分":"Perfect",s.n,e.ms,e.ts)));else c&&console.log(d+chalk.yellow(a(yn()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));3===n&&r?.leader&&console.log(d+chalk.white(yn()?`🏅 本 phase 研究总分榜首 ${r.leader.name||"Rank 1"} ${r.leader.total}/${r.leader.max_total}`:`🏅 Phase research leader: ${r.leader.name||"Rank 1"} at ${r.leader.total}/${r.leader.max_total}`)+chalk.gray((yn()," — "))+chalk.bold.green("/honors")+chalk.gray(yn()?" 看你的位置":" shows where you stand")),console.log(d+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(s.passed?chalk.gray(yn()?" 再战刷成绩 · ":" race it again · "):chalk.gray(yn()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(yn()?" 继续学习":" keep going"):chalk.gray(yn()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(i.length>0||c)&&console.log(d+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(yn()?" 日后回来整阶段重做 · 全新计时+模板(旧文件自动归档)":" come back later and redo the whole phase · fresh clock + templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${g}`)),console.log()},Kn=()=>{yt.endsWith("DEMO01")?console.log(chalk.yellow(yn()?" 🐼 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(yn()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(yn()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Jn=async(e,o)=>{if(bt){Lt?.noteAi("deep"===o),Qt=!0;try{console.log(),console.log(chalk.gray("deep"===o?yn()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":yn()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await we({token:yt,cardNumber:At.currentCard,question:e,mode:o,history:dn().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(yn()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(dn().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(` (${yn()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(yn()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Ut&&console.log(chalk.gray(yn()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Qt=!1}}else Kn()},Qn=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Xn=async()=>{Xt&&jn?xr?Sr(xr):_r():nn?await Vn():Hn()},Vn=async()=>{Qt=!0;try{console.log();const e=await _e({token:yt,curriculumId:mt.id,cardNumber:At.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(yn()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(On&&(await Un(),(e=>{const o=mt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const[t,n]=o.cardRange,r=At.checkResults||{};let s=0,l=0,a=0;for(let e=t;e<=n;e++){const o=An(e);null!=o?.check&&a++;const t=r[String(e)];t&&(s++,t.correct&&l++)}console.log(chalk.bold.white(yn()?` 🧭 Phase ${o.number} 进度 — ${o.name}(卡 ${t}-${n})`:` 🧭 Phase ${o.number} progress — ${o.name} (cards ${t}-${n})`)),console.log(chalk.gray(yn()?" 理解检查: ":" comprehension: ")+chalk.white(`${l}/${s}`)+chalk.gray(yn()?` 答对 · ${a-s} 张未作答`:` correct · ${a-s} unanswered`));const i=In?.phases.find(e=>e.phase===o.number);if(i?.configured&&i.contest?.slots?.length)for(const e of i.contest.slots){const t=e.passed?chalk.bold.green(`${e.best_ac}/${e.n} AC ✅`):0===e.attempts?chalk.gray(yn()?`未开始 · ${e.n} 题 · 过 ${e.need} 题`:`not started · ${e.n} problems · AC ${e.need}`):chalk.yellow(yn()?`最好 ${e.best_ac}/${e.n}(需 ${e.need})· 已试 ${e.attempts} 次`:`best ${e.best_ac}/${e.n} (need ${e.need}) · ${e.attempts} attempt(s)`);console.log(chalk.gray(` ⚔ ${yn()?"练习赛":"arena"} ${o.number}-${e.slot}: `)+t)}const c=[];let d=0,g=0,u=0,h=0;for(let e=t;e<=n;e++){const o=$n(e);o&&(g++,u+=o.solved,h+=o.total,o.solved>=o.total&&d++,c.push((o.solved>=o.total?chalk.green:o.solved>0?chalk.yellow:chalk.gray)(`${e}:${o.solved}/${o.total}`)))}if(g>0){console.log(chalk.gray(yn()?" 卡片练习: ":" practice: ")+chalk.white(`${d}/${g}`)+chalk.gray(yn()?` 卡全完成 · ${u}/${h} 题 AC`:` cards complete · ${u}/${h} problems AC`));const e=Math.max(40,(process.stdout.columns||80)-8);let o="",t=0;for(const n of c){const r=n.replace(/\x1b\[[0-9;]*m/g,"");t+r.length+2>e&&o&&(console.log(" "+o),o="",t=0),o+=(o?chalk.gray(" · "):"")+n,t+=r.length+3}o&&console.log(" "+o),console.log(chalk.gray(yn()?" 卡号:已过/共 — 绿 全完成 · 黄 做了一部分 · 灰 未碰":" card:solved/total — green done · yellow partial · gray untouched"))}console.log()})(At.currentCard)),console.log(chalk.bold.white(yn()?` 🏆 本卡实时 Top-3 — 第 ${At.currentCard} 张`:` 🏆 Live top-3 — card ${At.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(yn()?" (你)":" (you)"):""))}else console.log(chalk.gray(yn()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));if(e.mine?(mn.set(At.currentCard,e.mine.rank),console.log(chalk.white(yn()?" 你: ":" You: ")+chalk.bold.yellow(yn()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(yn()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):bt&&console.log(chalk.gray(yn()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),dt({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),e.phaseBoard){const o=e.phaseBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(yn()?` 🏅 Phase ${o.phase} 研究总分 — ${o.cards_in_phase} 卡 · 满分 ${o.max_total}`:` 🏅 Phase ${o.phase} research total — ${o.cards_in_phase} cards · max ${o.max_total}`)),0===o.top.length&&console.log(chalk.gray(yn()?" (还没有人有研究总分 — 第一个 /ai 研究 + /submit 的人直接登顶)":" (no research totals yet — the first to research with /ai + /submit takes #1)"));for(const e of o.top)console.log(chalk.white(` ${t[e.rank-1]??" "} `)+chalk.bold.cyan(e.name||`Rank ${e.rank}`)+chalk.white(` · ${e.total}`)+chalk.gray(yn()?`(${e.cards}/${o.cards_in_phase} 卡)`:` (${e.cards}/${o.cards_in_phase} cards)`)+(e.me?chalk.bold.magenta(yn()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(yn()?` 总分 ${o.gate_total}+(${o.cards_in_phase} 卡全部 60 分以上)揭榜 top-3 — 目前虚位以待`:` Top-3 unveils at ${o.gate_total}+ (all ${o.cards_in_phase} cards at 60+) — seats open`)),o.mine&&!o.top.some(e=>e.me)?console.log(chalk.white(yn()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.total}`)+chalk.gray(yn()?`(${o.mine.cards}/${o.cards_in_phase} 卡)· 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` (${o.mine.cards}/${o.cards_in_phase} cards) · rank ${o.mine.rank} of ${o.mine.entrants}`)):!o.mine&&bt&&console.log(chalk.gray(yn()?" 你: 还未计入 — /ai 研究任意卡并 /submit 评分,每卡最高分计入总分":" You: not counted yet — research any card with /ai, then /submit; each card’s best score counts")),console.log()}if(e.practiceBoard){const o=e.practiceBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(yn()?` ⚔ Phase ${o.phase} Practice AC — 已投放 ${o.problems_total} 题`:` ⚔ Phase ${o.phase} practice AC — ${o.problems_total} problems live`)),0===o.top.length&&console.log(chalk.gray(yn()?" (还没有人 AC — 第一个做出 practice 题的人直接登顶)":" (no ACs yet — the first solved practice problem takes #1)"));for(const e of o.top)console.log(chalk.white(` ${t[e.rank-1]??" "} `)+chalk.bold.cyan(e.name||`Rank ${e.rank}`)+chalk.white(` · ${e.ac} AC`)+chalk.gray(`/${o.problems_total}`)+(e.me?chalk.bold.magenta(yn()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(yn()?` AC 满 ${o.gate_ac} 题(已投放的 60%)揭榜 top-3 — 目前虚位以待`:` Top-3 unveils at ${o.gate_ac} ACs (60% of the pool) — seats open`)),o.mine&&!o.top.some(e=>e.me)?console.log(chalk.white(yn()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.ac} AC`)+chalk.gray(yn()?` · 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` · rank ${o.mine.rank} of ${o.mine.entrants}`)):o.mine||console.log(chalk.gray(yn()?" 你: 还未计入 — 在有 practice 的卡上输 practice 1 做题,AC 即计入":" You: not counted yet — type practice 1 on a card that has problems; each AC counts")),console.log()}!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(yn()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(yn()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(yn()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),nn="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(yn()?" 返回卡片":" returns to the card")),console.log()}finally{Qt=!1}},er=e=>yn()&&e.title_zh||e.title,or=Re(mt.id);let tr=!1;const nr=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of gt(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},rr={cpp:"cpp",java:"java",go:"go"},sr=e=>e?.lang&&rr[e.lang]?e.lang:"python",lr=(e,o)=>{const t=sr(o);return`sol-${e}.${"python"===t?"py":rr[t]}`},ar=(e,o)=>{const t=[...or?[{p:Me,n:qe}]:[],...e.problems.map((e,o)=>({p:e,n:o+1}))],n=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);let r=0;t.forEach(({p:t,n:s})=>{const l=or&&s===qe,a=l?`══ ${t.title} ══`:`══ ${e.title||"PY Arena"} · ${t.title} ══`;for(const e of["py",...Object.values(rr)]){const l=G(o,`sol-${s}.${e}`);if(!M(l))continue;const i=O(l,"utf-8").split("\n",1)[0]??"",c=/^(?:#|\/\/) (══ .+ ══)\s*$/.exec(i);if(c&&c[1]!==a)try{W(l,`${l}.archived-${n}`),r++;const e=G(o,`sample-${s}.txt`);M(e)&&!(t.samples??[])[0]&&W(e,`${e}.archived-${n}`)}catch{}}const i=(t.samples??[])[0];i&&D(G(o,`sample-${s}.txt`),i.in.endsWith("\n")?i.in:`${i.in}\n`);const c=G(o,lr(s,t));if(M(c))return;const d=[l?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...nr(t.statement,72)];if(t.statement_zh&&d.push("#",`# Other language: type "lang zh" in icoa, then /read ${s} for the Chinese statement.`),i){d.push("#",`# Sample input (also in sample-${s}.txt):`);for(const e of i.in.split("\n"))d.push(`# ${e}`);d.push("# Expected output:");for(const e of i.out.split("\n"))d.push(`# ${e}`)}if(d.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","#"),l||d.push("# ── toolkit ──",...e.toolkit_available?.length?[`# Available on the judge: ${e.toolkit_available.join(", ")}`]:["# The judge runs the Python standard library only."],...e.toolkit_available?.includes("chepy")?["# from chepy import Chepy — chain ops on the DATA block;","# /syntax chepy = op index · plain stdlib always works too."]:["# 'array', 'bisect', 'heapq' and sys.stdin.buffer.read() are the","# standard speed-ups; none is ever required to solve a problem."]),t.toolkit?.length&&(d.push(`# Recommended for THIS problem: ${t.toolkit.join(", ")}`),t.toolkit_note))for(const e of t.toolkit_note.split("\n"))for(const o of gt(e,68))d.push(`# ${o}`);const g=/\nDATA\n----\n([\s\S]+)$/.exec(t.statement??"");g?d.push("#","# No input() on this one — the DATA block is already assigned below.","# Compute, then print() ONLY the flag{...} token — nothing around it.",`# In icoa: /debug ${s} = free run · /submit ${s} = judge`,"",'data = """',...g[1].trim().split("\n"),'""".strip()',"",""):l?d.push("# Your first program. Line 1 is written for you: it reads the number.","# Replace the ??? on line 2 with the arithmetic, then :wq and /run 0.","","n = int(input())","print(???)",""):t.starter?d.push("#",`# In icoa: /run ${s} = run it (shows your ms) · /submit ${s} = judge`,""):d.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${s} = sample self-check · /debug ${s} = free-input run · /submit ${s} = judge`,"","");const u="python"===sr(t)?d:d.map(e=>e.startsWith("#")?`//${e.slice(1)}`:e);t.starter&&!l&&u.push(...t.starter.replace(/\s+$/,"").split("\n"),""),D(c,u.join("\n"))}),r>0&&console.log(chalk.gray(yn()?` 📦 本组题目已更换 — ${r} 个旧题答题文件已归档为 *.archived-${n},新题文件已就位`:` 📦 This group's problems changed — ${r} old solution file(s) archived as *.archived-${n}, fresh files written`))},ir=e=>{console.log(),console.log(chalk.bold.green(yn()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(yn()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},cr=e=>e.id===Ne?tr?"✅":"⬜":jn.data.solved.includes(e.id)?"✅":jn.data.carried?.includes(e.id)?"✅↗":jn.tried.has(e.id)?"❌":"⬜",dr=100,gr=()=>!!jn&&jn.data.slot>=dr,ur=(e,o)=>{const t=G(process.cwd(),"icoa-contest",`${mt.id}-phase${e}-g${o}`);if(!M(t))return;const n=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{W(t,`${t}-archived-${n}`),console.log(chalk.gray(yn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${n}`))}catch{console.log(chalk.yellow(yn()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (restart still fine): ${t}`))}},hr=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,pr=e=>{const o=e?.practice;return o&&Array.isArray(o.problems)&&0!==o.problems.length?[...o.problems.filter(e=>e.is_signature),...o.problems.filter(e=>!e.is_signature).sort((e,o)=>(e.difficulty??0)-(o.difficulty??0)||(e.order??0)-(o.order??0))]:null},yr=()=>{if(!fn)return!1;const e=An(At.currentCard),o=e?pr(e):null;if(!e||!o||Dn.has(e.number))return!1;const t=dr+e.number,n=Wn.get(t),r=Rn.get(t),s=o.map((e,o)=>{return t=e.py_id,Boolean(n?.has(hr(t))||n?.has(t)||r?.has(hr(t))||r?.has(t))?0:o+1;var t}).filter(e=>e>0);return 0!==s.length&&(console.log(chalk.yellow(yn()?` ⚔ 这张卡还有 ${s.length} 道练习没做 —— 敲 `:` ⚔ ${s.length} practice problem${s.length>1?"s":""} on this card not tried yet — type `)+chalk.bold.green(`practice ${s[0]}`)+chalk.yellow(yn()?" 开始,或 ":" to start, or ")+chalk.bold.yellow("skip")+chalk.yellow(yn()?" 跳过本卡练习。":" to skip this card's practice.")),!0)},mr=e=>{const o=pr(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=Wn.get(dr+e.number);console.log(chalk.bold.yellow(yn()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(yn()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(hr(e.py_id))||n?.has(e.py_id)?"✅":"⬜",r=e.is_signature?"🎯":e.is_hardest?"🔥":" ",s="·".repeat(Math.min(5,Math.max(1,Math.round(e.difficulty??1))));console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ${r} ${chalk.white(s.padEnd(5))}`)}),console.log(chalk.gray(" ▸ ")+chalk.bold.green("practice 1")+chalk.gray(yn()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},fr=e=>e.split("\n").filter(e=>!e.trim().startsWith("#")).join("\n").split("____").length-1,$r=e=>{console.log(chalk.yellow(yn()?` ⏱ 每次练习 ${e} 分钟,这次的时间到了。`:` ⏱ Each practice window is ${e} minutes — this one has run out.`)),console.log(chalk.gray(yn()?" 敲 ":" Type ")+chalk.bold.green("back")+chalk.gray(yn()?" 回卡片,再敲 ":" for the card, then ")+chalk.bold.green("practice 1")+chalk.gray(yn()?" 重新开始(重新计时)。":" to restart with a fresh clock."))},br=()=>tn?tn.data.problems[tn.idx]??null:null,wr=()=>{const e=br();if(!tn||!e)return;const o=fr(e.starter??""),t=tn.answers.length+1,n=(e=>{const o=[];for(const t of e.split("\n"))if(!t.trim().startsWith("#"))for(let e=t.split("____").length-1;e>0;e--)o.push(t.trim());return o})(e.starter??"")[t-1]??"";console.log(chalk.bold.yellow(yn()?` 空${t}/${o}`:` blank ${t}/${o}`)+chalk.gray(" · ")+chalk.white(n)),console.log(chalk.gray(yn()?" ▸ 敲答案后回车(back 回卡片)":" ▸ type the answer, press Enter (back = card)"))},kr=()=>{const e=br();if(!tn||!e)return;const o=yn()&&e.title_zh?e.title_zh:e.title;console.log(),console.log(chalk.bold.yellow(` ⚡ ${yn()?"练习":"Practice"} ${tn.idx+1}/${tn.data.problems.length} · ${o}`));const t=((yn()&&e.statement_zh?e.statement_zh:e.statement)??"").split(/\n(?:Rules|规则)\n/)[0].trimEnd();for(const e of t.split("\n"))console.log(chalk.white(" "+e));console.log();let n=0;(e.starter??"").split("\n").forEach((e,o)=>{let t;if(e.trim().startsWith("#"))t=e;else{const o=e.split("____");t=o.map((e,t)=>t<o.length-1?e+chalk.bold.yellow("____"+ ++n):e).join("")}console.log(chalk.gray(` ${String(o+1).padStart(2)} │ `)+chalk.white(t))}),console.log(),wr()},vr=()=>{if(tn){if(tn.idx+1<tn.data.problems.length)return tn.idx+=1,tn.answers=[],tn.tries=0,void kr();console.log(chalk.bold.green(yn()?" 🎉 本卡练习全部完成!":" 🎉 Card practice complete!")+chalk.gray(yn()?" ok 进下一张卡。":" ok moves on to the next card.")),tn=null,Hn()}},_r=()=>{const e=jn.data,o=je(e.deadline),t=(e.carried??[]).filter(o=>!e.solved.includes(o)),n=e.solved.length+t.length,r=Math.min(20,Math.round(n/Math.max(1,e.need)*20));console.log();const s=e.slot>=dr?e.slot-dr:null;if(console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(null!=s?yn()?` · 第 ${s} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${s} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:yn()?` · 第 ${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(yn()?" ⏱ 已超时 — contest restart 重开本组":" ⏱ time up — contest restart to retry this group"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${n}/${e.need} AC`)+chalk.gray(yn()?`(共 ${e.n} 题)`:` (of ${e.n})`)),null==s&&n>=e.need){const o=Math.max(0,e.n-n);console.log(0===o?chalk.bold.green(yn()?` 🎉 满分 ${e.n}/${e.n} — 本组全部拿下!`:` 🎉 Perfect ${e.n}/${e.n} — every problem cleared!`)+chalk.gray(yn()?" ↩ back 回卡片":" ↩ back returns to the card"):chalk.green(yn()?" 🏁 已过关":" 🏁 passed")+chalk.yellow(yn()?` · 还剩 ${o} 题,全做完 = 满分 ${e.n}/${e.n}`:` · ${o} more for a perfect ${e.n}/${e.n}`))}if(t.length>0&&console.log(chalk.cyan(` ✅↗ ${t.length}`)+chalk.gray(yn()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0){const o=(e.carry_from??[]).join(", "),t=o?yn()?`(${o})`:` (${o})`:"";console.log(chalk.cyan(yn()?` 🔗 你另一个 token${t}已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens${t} solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yn()?" 带过来,不必重做":" 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(yn()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(yn()?"不够就 ":"Short on time? ")+chalk.bold.green("contest restart")+chalk.gray(yn()?" 满血重开本组。":" restarts this group fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(yn()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),or&&(console.log(chalk.gray(" 0 ")+cr(Me)+chalk.gray(` ${er(Me)}`)+chalk.gray(yn()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+cr(e)+(e.gpu?chalk.magenta(" ⚡"):"")+chalk.white(` ${er(e)}`))}),e.problems.some(e=>e.gpu)&&(console.log(),console.log(e.gpu_window?chalk.bold.green(yn()?" ⚡ GPU 窗口:开 ✅":" ⚡ GPU window: OPEN ✅")+chalk.gray(yn()?" — 带 ⚡ 的层现在 /submit 就在真 GPU 上跑":" — /submit a ⚡ rung and it runs on a real GPU right now"):chalk.gray(yn()?" ⚡ GPU 窗口:关(每周一 19:00–21:45 悉尼开放)— 带 ⚡ 的层等窗口内 /submit":" ⚡ GPU window: closed (Mondays 19:00–21:45 Sydney) — /submit ⚡ rungs inside the window"))),Nn(jn.phase,e.slot)&&(console.log(),console.log(chalk.gray(" ✍ ")+chalk.bold.green("cells")+chalk.gray(yn()?" 在 notebook 里探索本场数据(引导走查 · 真图) — 不判分,判分仍走 /submit":" explore this lab in a notebook (guided walkthrough · real figures) — ungraded; judging stays /submit"))),console.log(),Cr()},Cr=()=>{console.log(chalk.gray(yn()?" /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(" ")+chalk.bold.green(yn()?"/syntax <词>":"/syntax <word>")+chalk.gray(yn()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(yn()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(yn()?" 返回课程":" returns to the lesson")),console.log(chalk.gray(yn()?" memo 报告题面/判分问题 — 不打断比赛计时":" memo reports a statement/judging problem — the clock is unaffected")),console.log(chalk.gray(" ")+chalk.bold.green("contest restart")+chalk.gray(yn()?" 超时/坏场时重开本组(全新计时+模板) · ":" time up or broken attempt → this group again (fresh clock + templates) · ")+chalk.bold.green("contest reset")+chalk.gray(yn()?" 日后回来整阶段重做":" come back later and redo the whole phase")),console.log()},Ar=e=>{const o=parseInt(e,10),t=jn.data.problems;if(o===qe&&or)return{p:Me,n:qe};const n=or?qe:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(yn()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),or&&console.log(chalk.gray(yn()?" 0 = 热身题(不计分,证明环境通了)· 1 起是本组正式题目。":" 0 = the warm-up (unscored — proves your setup works) · 1 and up are the real problems.")),null):{p:t[o-1],n:o}};let xr=null,Tr=!1;const Sr=e=>{const o=Ar(e);if(!o)return;const{p:t,n:n}=o;xr=String(n),console.log(),console.log(chalk.bold.white(` ${cr(t)} ${er(t)}`)),console.log();for(const e of(e=>yn()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of gt(e,ct()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(yn()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(yn()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(yn()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(yn()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=yn()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of gt(o,ct()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(yn()?"数据就在上方 DATA 块(sol 文件里已赋给 data 变量)— 不用 input(),只 print flag{...} 本身":"The data is the DATA block above (already assigned to `data` in your sol file) — no input(); print ONLY the flag{...} token"))),console.log(),or&&n===qe)return console.log(chalk.white(yn()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(yn()?"第 1 行已经写好了,把第 2 行的 ??? 换掉(vi:i 编辑 · Esc · :wq 存盘退出)":"line 1 is written for you — replace the ??? on line 2 (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green("/run 0".padEnd(11))+chalk.gray(yn()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(yn()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((yn()," ↩ "))+chalk.bold.green("back")+chalk.gray(yn()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(yn()?" 直接看正式题目":" skips straight to the real problems")),void console.log();t.gpu?(console.log(chalk.white(yn()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(yn()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(yn()?"真 GPU 上跑并带回你的 ms(⚡ 每周一窗口 19:00–21:45 悉尼)":"runs on a real GPU and returns your ms (⚡ Monday window 19:00–21:45 Sydney)"))):t.starter?(console.log(chalk.white(yn()?" 三步:":" Three steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(yn()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(yn()?"本机直跑,出你自己的 ms":"run it locally — see your own ms")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(yn()?"参考机判分(成绩 = 那里的 ms)":"judge on the reference machine (the scored ms)"))):(console.log(chalk.white(yn()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(yn()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(yn()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(yn()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(yn()?"正式判分(隐藏用例)":"official judging (hidden tests)"))),console.log(),console.log(chalk.gray(yn()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(yn()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((yn()," ↩ "))+chalk.bold.green("back")+chalk.gray(gr()?yn()?" 回花名册 · ":" to the roster · ":yn()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(yn()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((yn()," / "))+chalk.bold.green("wide")+chalk.gray(yn()?" 换语言/宽度":" language / width")),console.log()},Pr=async(e,o,t)=>await new Promise(n=>{const l=process.stdin,a=!!l.isTTY&&!!l.isRaw;if(It.pause(),l.isTTY&&"function"==typeof l.setRawMode)try{l.setRawMode(!1)}catch{}Ot=!0;const i=r(e,o,{stdio:"inherit",cwd:t??jn.dir}),c=e=>{if(l.isTTY&&"function"==typeof l.setRawMode&&a)try{l.setRawMode(!0)}catch{}s(),Ot=!1,It.resume(),n(e)};i.on("close",()=>c(null)),i.on("error",e=>c(e))}),Ir=["-n","-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark number","-c","silent! set complete=. completeopt=menu,menuone","-c","silent! highlight Normal ctermfg=252 | silent! highlight ModeMsg ctermfg=231 cterm=bold | silent! highlight MoreMsg ctermfg=252 | silent! highlight Question ctermfg=252"],jr=()=>{const e=A("vi");console.log(chalk.gray(yn()?e?" vi 四键: i 进入编辑 · Esc 退出编辑 · Ctrl-N 补全 · :wq 存盘离开":" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":e?" vi survival: i = edit · Esc = stop editing · Ctrl-N = complete word · :wq = save and leave":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"))},Er=()=>po(yn(),{judgeIsServerSide:!0}),Lr=()=>{const e=fo();return e||Er(),e},Mr=new Map,Nr=()=>Je(process.cwd(),mt.id),qr=e=>{const o=new Date(e),t=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${t(o.getMonth()+1)}-${t(o.getDate())} ${t(o.getHours())}:${t(o.getMinutes())}`},Or=async(e,o,t=!1)=>{if(!On)return;let n;try{n=O(Qe(Nr(),e),"utf-8")}catch{return}if(Buffer.byteLength(n,"utf-8")>De)return;const r=Ke(n),s=(new Date).toISOString(),l=Ze($o(),yt).slice(0,Be),a=await to(yt,{n:e,title:Xe(n.split("\n",1)[0]),code:n,code_sha:r,card_number:At.currentCard,run_meta:o,client_ts:s,events:l.length>0?l:void 0});a?l.length>0&&Ve($o(),yt,l.length):eo($o(),yt,{n:e,code_sha:r,card_number:At.currentCard,run_meta:o,client_ts:s}),a||t||console.log(chalk.gray(yn()?" (未能同步到服务器 — 草稿只保存在本机)":" (could not reach the server — this scratch is saved locally only)"))},Wr=()=>{console.log(chalk.gray(yn()?" edit <n> 改码(vi) · run <n> 本机运行 · pylist 列表 · /py 新建 · ↩ back 回卡片":" edit <n> code (vi) · run <n> local run · pylist list · /py new file · ↩ back to the card")),console.log()},Rr=e=>{const o=ze(Nr()),t=parseInt(e,10);return Number.isInteger(t)&&o.some(e=>e.n===t)?t:(0===o.length?console.log(chalk.yellow(yn()?" 还没有任何草稿 — ":" No scratch files yet — ")+chalk.bold.green("/py")+chalk.gray(yn()?" 新建第一个。":" creates the first one.")):console.log(chalk.yellow(yn()?` 没有 py-${e} — 现有编号: `:` No py-${e} — you have: `)+chalk.white(o.map(e=>e.n).join(", "))+chalk.gray(yn()?" · pylist 看列表":" · pylist shows them")),null)},Dr=e=>{const o=ze(Nr()),t=e?.trim().toLowerCase(),n=t?o.filter(e=>(e.title??"").toLowerCase().includes(t)):o;if(console.log(),console.log(chalk.bold.magenta(yn()?" ✍ 我的 Python 草稿":" ✍ My Python scratch files")+(t?chalk.gray(` · "${e?.trim()}"`):"")+chalk.gray(` (${n.length})`)),0===o.length)return console.log(chalk.gray(yn()?" 还没有草稿 — ":" Nothing here yet — ")+chalk.bold.green("/py")+chalk.gray(yn()?" 新建一个(第一行写标题)。":" creates one (line 1 becomes its title).")),void console.log();if(0===n.length)return console.log(chalk.gray(yn()?` 没有匹配 "${e?.trim()}" 的草稿 — 直接 pylist 看全部。`:` No title matches "${e?.trim()}" — bare pylist lists everything.`)),void console.log();for(const e of n){const o=e.title?chalk.white(gt(e.title,40)[0]??e.title):chalk.gray(yn()?"(未命名 — 第一行写标题)":"(untitled — line 1 becomes the title)");console.log(chalk.gray(` py-${String(e.n).padEnd(3)} `)+o+chalk.gray(` · ${qr(e.mtimeMs)}`))}console.log(chalk.gray(" ▸ ")+chalk.bold.green(yn()?"/py <编号>":"/py <n>")+chalk.gray(yn()?" 打开 · ":" opens one · ")+chalk.bold.green("/py")+chalk.gray(yn()?" 新建":" new file")),console.log()},Ur=async e=>{const o=Qe(Nr(),e);if(vo())return console.log(chalk.yellow(yn()?" icoa 正跑在 Windows 上 — 草稿本的编辑器在 Ubuntu(WSL)那一侧。":" icoa is running on Windows — the scratchpad editor lives on the Linux (WSL) side.")),console.log(chalk.gray(yn()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${o}`)),void console.log();if(!Co("vi"))return console.log(chalk.yellow(yn()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${o}`)),void console.log(chalk.gray(yn()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));jr();const t=e=>{try{return R(e).size}catch{return 0}},n=t(o),r=Date.now(),s=C(o);await Pr("vi",[...Ir,`py-${e}.py`],Nr());const l=s.stop();_(`learn-py edit-done py-${e}.py`,{ms:Date.now()-r,bytesBefore:n,bytesAfter:t(o),...l.ticks>0?{samples:l}:{}}),await Or(e),console.log(chalk.gray(yn()?" 已回到草稿本 — ":" Back in the scratchpad — ")+chalk.bold.green(`run ${e}`)+chalk.gray(yn()?" 本机运行 · ":" runs it locally · ")+chalk.bold.green(`edit ${e}`)+chalk.gray(yn()?" 再改。":" reopens vi.")),console.log()},Yr=async e=>{let o;if(N(Nr(),{recursive:!0}),e){const t=Rr(e);if(null===t)return;o=t}else{const e=ze(Nr());o=He(e),o>Ue&&console.log(chalk.gray(yn()?` (已超过 ${Ue} 个 — 服务器不再备份新文件,本机照常保存)`:` (past ${Ue} files — the server stops backing new ones up; local saves still work)`)),D(Qe(Nr(),o),`${yn()?Fe:Ye}\n\n`)}const t=!Vt;Vt=!0,_(`learn-py: open ${o}${e?"":" (new)"}`),t&&(console.log(),console.log(chalk.bold.magenta(yn()?" ✍ Python 草稿本":" ✍ Python scratchpad")+chalk.gray(yn()?" — 你的个人练习文件 · 只在本机运行 · 不判分":" — your personal practice files · runs locally · never judged")),console.log(chalk.gray(yn()?" edit <n> 改码(vi) · run <n> 本机运行 · 整轨一份文件列表,跨卡共用":" edit <n> code (vi) · run <n> local run · one file list shared across the whole track")),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(yn()?" 回卡片(退一层)":" returns to the card (one level)"))),await Ur(o),Wr()},Br=()=>ao(process.cwd(),mt.id),Fr=()=>on??ro(lo(process.cwd(),mt.id,At.currentCard)),zr=()=>{console.log(),console.log(chalk.bold.magenta(yn()?" ⌨ shell 实验台":" ⌨ shell lab")+chalk.gray(yn()?" — 在这里动手把答案弄出来 · 不判分 · 不解锁任何东西":" — work the answer out here · never judged · unlocks nothing")),console.log(chalk.gray(yn()?` 真的 shell:管道 | 、重定向 > 、通配符 * 都能用 · 每条命令最多 ${no/1e3} 秒`:` A real shell: pipes |, redirection >, globs * all work · ${no/1e3}s per command`)),console.log(chalk.gray(yn()?` 你在 ${uo(Br())} 里面 —— 只能在这个文件夹内走动(自己的终端不受限)`:` You are inside ${uo(Br())} — you can only move within it (your own terminal is unrestricted)`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(yn()?" 回卡片(退一层)":" returns to the card (one level)")),console.log()},Gr=()=>{console.log(chalk.gray(yn()?" 敲任何 shell 命令 · cd 换目录 · reset 还原文件 · clear 清屏 · ↩ back 回卡片":" type any shell command · cd to move · reset restores files · clear · ↩ back"))},Hr=()=>`icoa sh ${go(Br(),Fr())}> `,Zr=(e=!1)=>{const o=An(At.currentCard)?.files;if(!o)return[];const t=ro(lo(process.cwd(),mt.id,At.currentCard)),n=[];for(const[r,s]of Object.entries(o)){if(!/^[A-Za-z0-9._-]+$/.test(r)||"."===r||".."===r)continue;const o=G(t,r);if(e||!M(o))try{D(o,s),n.push(r)}catch{}}return n},Kr=async e=>{const o=e.trim().toLowerCase(),s=Xt&&o.startsWith("/")?o.slice(1):o;if(Mt)return void(Nt=!0);if(qt){const{sameName:o,issueCertificate:t,announceCertificate:n}=await import("../lib/learn-certificate.js"),r=e.trim(),s=yn();if(!r||Gt.test(r))return qt=null,console.log(chalk.gray(s?" 已取消,未签发。":" Cancelled — nothing issued.")),void Wt();if(null===qt.first)return qt.first=r,console.log(chalk.gray(s?" 再输一次:":" Type it once more:")),void Wt();const l={cid:qt.cid,tok:qt.tok,first:qt.first};return qt=null,o(l.first,r)?(console.log(chalk.gray(s?" 签发中…(名字只发送一次,不会保存)":" Issuing… (the name is sent once, never stored)")),n(await t(l.tok,l.cid,l.first),s),void Wt()):(console.log(chalk.yellow(s?" 两次输入不一致 — 未签发。再敲 certificate 重来。":" The two names differ — nothing issued. Type certificate to try again.")),void Wt())}if(Qt)return;if(Lt?.noteInput(),!tn&&Lt?.consumeRating(o))return void Wt();if(tn)return await(async e=>{if(!tn)return;const o=e.trim(),t=o.toLowerCase();if("back"===t||"quit"===t||"menu"===t)return tn=null,console.log(chalk.gray(yn()?" ↩ 回到卡片。":" ↩ Back on the card.")),void Hn();if("skip"===t)return void vr();if(""===o)return void kr();const n=br();if(!n)return tn=null,void Hn();const r=fr(n.starter??"");if(tn.answers.push(o),tn.answers.length<r)return void wr();const s=[...tn.answers],l=((e,o)=>{let t=0;return e.split("\n").map(e=>{if(e.trim().startsWith("#"))return e;for(;e.includes("____")&&t<o.length;)e=e.replace("____",o[t]),t+=1;return e}).join("\n")})(n.starter??"",s);tn.answers=[];let a=Rn.get(tn.slot);a||(a=new Set,Rn.set(tn.slot,a)),a.add(n.id);const i=Boolean(n.quiz),c=i?null:new I(yt);c?.start();const d=await xe(yt,tn.phase,n.id,l,tn.slot,void 0);if(c?.stop(),!tn)return;if(!d.ok||!d.data)return"no_active_session"===d.code?void $r(tn.data.duration_minutes):(console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),console.log(chalk.gray(yn()?" 再敲一遍空1重试,或 back 回卡片。":" Type blank 1 again to retry, or back for the card.")),void wr());const g=d.data;if("AC"!==g.verdict||g.already_ac||Lt?.notePracticeAc(),g.already_ac||"AC"===g.verdict){i?console.log(chalk.bold.green(yn()?" ✅ 答对了!":" ✅ Correct!")):console.log(ho("AC",{isZh:yn(),gentle:!0,passed:g.passed_tests??g.total_tests??null,total:g.total_tests??null,ms:g.time_ms??null}));let e=Wn.get(tn.slot);return e||(e=new Set,Wn.set(tn.slot,e)),e.add(n.id),tn.data.solved.includes(n.id)||tn.data.solved.push(n.id),void vr()}tn.tries+=1,i?console.log(chalk.red(yn()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(yn()?" — 再选一次。":" — pick again.")):console.log(ho(g.verdict??"WA",{isZh:yn(),gentle:!0,passed:g.passed_tests??null,total:g.total_tests??null,failedTest:g.test??null,ms:g.time_ms??null}));const u=n.samples?.[0];if(u?.out){console.log(chalk.gray(yn()?" 期望输出:":" Expected output:"));for(const e of u.out.trimEnd().split("\n"))console.log(chalk.white(" "+e))}if(2===tn.tries||tn.tries>2&&tn.tries%3==2){const e=i?[]:((e,o)=>{const t=[];let n=0;for(const r of e.split("\n")){if(r.trim().startsWith("#"))continue;const e=r.split("____");for(let r=0;r<e.length-1;r++,n++){const s=(o[n]??"").trim(),l=e[r+1].trimStart(),a=e[r].trimEnd(),i=n+1;l.startsWith("(")&&/\(\s*\)?$/.test(s)?t.push(yn()?` ⚠ 空${i}:模板里 ____ 后面已经有 ( ) — 只填名字,别再带括号。`:` ⚠ blank ${i}: the ( ) after ____ is already in the template — type just the name, no brackets.`):(/["']$/.test(a)||/^["']/.test(l))&&/^["']|["']$/.test(s)?t.push(yn()?` ⚠ 空${i}:引号模板里已经有了 — 只填引号中间的内容。`:` ⚠ blank ${i}: the quotes are already in the template — type only what goes between them.`):/^[A-Za-z_][\w.]*\(.*\)$/.test(s)&&!l.startsWith("(")&&/\)\s*[:)]/.test(l)&&t.push(yn()?` ⚠ 空${i}:____ 后面已有右括号,你的答案可能多带了一个 )。`:` ⚠ blank ${i}: a closing ) already follows ____ — your answer may carry one too many.`)}}return t})(n.starter??"",s);for(const o of e)console.log(chalk.yellow(o));console.log(chalk.gray(yn()?" 💡 两次没过,多半是细节不是思路 — 再敲之前过一遍:":" 💡 Two misses are usually a detail, not the idea — run this check before retrying:")),i||(console.log(chalk.gray(yn()?" · 拼写和大小写(Python 区分大小写:Print ≠ print)":" · spelling and case (Python is case-sensitive: Print ≠ print)")),console.log(chalk.gray(yn()?" · 只填缺的那一块 — ____ 周围已有的括号、引号、冒号不要重复":" · fill only what is missing — brackets, quotes, colons already around ____ stay"))),console.log(chalk.gray(yn()?" · 没思路?往上翻,或 ":" · no idea? scroll up, or ")+chalk.bold.green("back")+chalk.gray(yn()?" 回卡片再读一遍 — 答案就在正文里。打错字人人都有,继续。":" re-reads the card — the answer is in its body. Typos happen to everyone; keep going."))}console.log(chalk.gray(yn()?" 从空1再来:":" From blank 1 again:")),wr()})(e),void Wt();if(null!==Yt){if(Bt.push(e.replace(/\s+$/,"")),zt&&clearTimeout(zt),zt=null,Ft){const e=Bt[Bt.length-1]??"";return"/cancel"===e.trim()?(Kt(),console.log(chalk.gray(yn()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Wt()):""!==e.trim()?void Wt():(Bt.pop(),void await c())}return void(zt=setTimeout(()=>{if(zt=null,Bt.length>1){Ft=!0;const e=Bt.length;return console.log(chalk.cyan(yn()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(yn()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Wt()}c()},140))}async function c(){const e=Bt.join("\n").replace(/^\s+|\s+$/g,""),o=Yt??At.currentCard,t=Bt.length,n=Ht;if(Kt(),""===e)console.log(chalk.gray(yn()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&Gt.test(e))console.log(chalk.yellow(yn()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(yn()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(yn()?" 即可执行。":" again to run it."));else{const r=!n&&pn>0?Date.now()-pn:void 0;if(await X(yt,{curriculum_id:mt.id,card_number:o,feedback_text:n?`${n} ${e}`:e,time_on_card_ms:r})){const n=t>1?yn()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(yn()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(yn()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),kt=[...kt,{id:_t--,curriculumId:mt.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],st(kt)}else console.log(chalk.yellow(yn()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Wt()}if(rn){const o=e.trim();if(Gt.test(o))return rn=!1,console.log(),console.log(chalk.yellow(yn()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(yn()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(yn()?" 即可执行该命令。":" again to run it.")),console.log(),void Wt();if(!o)return rn=!1,console.log(chalk.gray(yn()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Wt();const t=await be({token:yt,nickname:o});if(t.ok)rn=!1,console.log(chalk.bold.green(yn()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(yn()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{sn+=1;const e="taken"===t.code?yn()?"已被占用":"already taken":"bad_charset"===t.code?yn()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"real_name"===t.code?yn()?"看起来像真名 — 系统不收集个人信息,换个游戏风格的昵称":"looks like a real name — we collect no personal info; pick a gamer-style handle":"rejected"===t.code?yn()?"未通过审核":"did not pass review":t.message||"error";if(!(sn>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yn()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Wt();rn=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yn()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Wt()}if(gn){gn=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Qt=!0;try{console.log(),console.log(chalk.gray(yn()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await ke({token:yt,cardNumber:At.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(yn()?"评审暂不可用。":"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(yn()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(yn()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(yn()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(yn()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(yn()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(yn()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=yn()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(yn()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(yn()?` 第 ${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 Qn(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(yn()?" 改进提问: ":" 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(` (${yn()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?un.add(At.currentCard):un.delete(At.currentCard),"number"==typeof e.rank&&mn.set(At.currentCard,e.rank);const o=await _e({token:yt,curriculumId:mt.id,cardNumber:At.currentCard});if(o.ok&&o.totals&&o.chapters&&(dt({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),o.ok&&o.phaseBoard?.mine){const e=o.phaseBoard,t=o.phaseBoard.mine,n=e.top[0],r=n&&!n.me?chalk.gray(yn()?` · 榜首 ${n.name||"Rank 1"} ${n.total}`:` · leader ${n.name||"Rank 1"} at ${n.total}`):chalk.bold.yellow(yn()?" · 全场第一!":" · phase leader!");console.log(chalk.white(yn()?` 🏅 Phase ${e.phase} 研究总分: `:` 🏅 Phase ${e.phase} research total: `)+chalk.bold.yellow(`${t.total}`)+chalk.gray(yn()?`(${t.cards}/${e.cards_in_phase} 卡)· 第 ${t.rank} 名`:` (${t.cards}/${e.cards_in_phase} cards) · rank ${t.rank}`)+r),console.log()}!0===e.inTop3&&o.ok&&null==o.nickname&&!ft&&(rn=!0,sn=0,console.log(chalk.bold.yellow(yn()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(yn()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(yn()?" 英文开头,英文+数字,3-16 位 · 别用真名(系统不收集个人信息,会被拒)· 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · not your real name (we collect no personal info — it gets refused) · permanent · Enter skips")))}finally{Qt=!1}})():(console.log(chalk.gray(yn()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Ut&&(console.log(chalk.gray(yn()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Wt()}if(hn)return hn=!1,Hn(),void Wt();if(!o)return void Wt();if(an)return"exit"===await E(e.trim())&&(an=!1),void Wt();if(Jt){if(["q","quit","exit","back","b","menu"].includes(o))return Jt=!1,console.log(chalk.gray(yn()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Wt();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim(),r=/^(\/?(submit|read|edit|run|debug|list|honors|recall|view|ai|syntax|contest|practice|practise|py|memo)\b\s*\d*|\/?pylist\b\s*\S*|card\s+\d+|\d+|status|bookmark|unbookmark|reload|link|wide|wider|widest|normal|narrow|next|ok|y|n|yes|no|menu|lang(\s+\S+)?|e)$/i.exec(n),s=n.length>0&&!/[\p{L}\p{N}]/u.test(n);return r||s?(console.log(),console.log(chalk.yellow(yn()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(s?yn()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":yn()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(yn()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(yn()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void Wt()):(n&&(await Jn(n,t?"fast":"deep"),console.log(chalk.gray(yn()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Wt())}if(en){const t=e.trim();if(["back","b","quit","exit","q"].includes(o))return en=!1,on=null,_("learn-sh: leave"),console.log(chalk.gray(yn()?" ↩ 已离开 shell 实验台,回到卡片。":" ↩ Left the shell lab — back to the card.")),Hn(),void Wt();if("menu"!==o&&!/^memo\b/.test(o)){if("reset"===o){const e=Zr(!0);return console.log(e.length>0?chalk.green((yn()?" ↺ 已还原本卡的文件: ":" ↺ Restored this card's files: ")+e.join(" ")):chalk.gray(yn()?" 本卡没有附带文件。":" This card ships no files.")),void Wt()}return"clear"===o||"cls"===o?(console.clear(),Gr(),void Wt()):"help"===o||"e"===o||"?"===o?(zr(),void Wt()):""===t?void Wt():/^\/?py(\s|$)/.test(o)?(en=!1,on=null,await Yr(/^\/?py\s+(\S+)/.exec(o)?.[1]),void Wt()):(await(async e=>{_(`learn-sh: $ ${e}`);const o=/^cd(?:\s+(.*))?$/.exec(e.trim());if(o){const e=io(Br(),Fr(),o[1]?.trim());return void(null===e?console.log(chalk.yellow(yn()?" 去不了那儿 —— 目录不存在,或在实验台外面。":" Cannot go there — no such directory, or it is outside the lab.")+chalk.gray(yn()?" cd 单独敲回到顶层。":" Bare `cd` returns to the top.")):on=e)}const t=so(e);if(t)return void console.log(chalk.yellow(yn()?` \`${e.trim().split(/\s+/)[0]}\` 会占住终端,这里跑不了 — `:` \`${e.trim().split(/\s+/)[0]}\` takes over the terminal and cannot run here — `)+chalk.bold.green(t));const n=/(^|[;&|]\s*)cd(\s|$)/.test(e)&&!/^cd(\s|$)/.test(e.trim()),r=await co(e,Fr());"no-shell"!==r.kind?"timeout"!==r.kind?"refused"!==r.kind&&(r.stdout&&console.log(chalk.white(r.stdout.replace(/\n$/,""))),r.stderr&&console.log(chalk.red(r.stderr.replace(/\n$/,""))),r.truncated&&console.log(chalk.gray(yn()?" … 输出过长,已截断。":" … output truncated.")),n&&console.log(chalk.yellow(yn()?" 注意:这一行里的 cd 只在子进程里生效,你还在原来的目录。":" Note: the cd in that line ran in a child process — you have not moved.")+chalk.gray(yn()?" 单独敲一行 cd <目录>。":" Type `cd <dir>` on its own line.")),r.stdout||r.stderr?0!==r.code&&console.log(chalk.gray(yn()?` (退出码 ${r.code})`:` (exit ${r.code})`)):console.log(chalk.gray(yn()?` (没有输出 · 退出码 ${r.code})`:` (no output · exit ${r.code})`))):console.log(chalk.yellow(yn()?` 超过 ${no/1e3} 秒,已停止。`:` Stopped after ${no/1e3}s.`)+chalk.gray(yn()?" 换个更小的目标再试。":" Try a smaller target.")):console.log(chalk.red(yn()?" 这台机器上找不到 /bin/sh。":" No /bin/sh on this machine.")+chalk.gray(yn()?" Windows 请在 WSL2 里跑 icoa。":" On Windows, run icoa inside WSL2."))})(t),void Wt())}}if(Vt){if(/^\/?(py|pylist|edit|run|list|new)\b|^(b|q|quit|exit|back)$|^\d+$/.test(o)&&_(`learn-py: ${o}`),["back","b","quit","exit","q"].includes(o))return Vt=!1,console.log(chalk.gray(yn()?" ↩ 已离开草稿本,回到卡片。":" ↩ Left the scratchpad — back to the card.")),Hn(),void Wt();const t=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(t||"list"===o||"/list"===o)return Dr(t?.[1]),Wr(),void Wt();const n=/^\/?(edit|run)(?:\s+(\S+))?$/.exec(o)??(/^\d+$/.test(o)?["","edit",o]:null);if(n){const e=n[1],o=n[2];if(o){const t=Rr(o);null!==t&&("edit"===e?(await Ur(t),Wr()):await(async e=>{if(!M(Qe(Nr(),e)))return void Rr(String(e));const o=mo()?.cmd??null;if(!o)return void po(yn());const[t,...n]=o.split(" ");console.log();const s=oo();let l="",a=!1;const i=await new Promise(o=>{const s=r(t,[...n,`py-${e}.py`],{cwd:Nr(),stdio:["ignore","pipe","pipe"]}),i=setTimeout(()=>{a=!0;try{s.kill("SIGKILL")}catch{}},3e4);s.stdout?.on("data",e=>process.stdout.write(e)),s.stderr?.on("data",e=>{l.length<400&&(l+=e.toString("utf-8")),process.stderr.write(e)}),s.on("error",()=>{clearTimeout(i),o(127)}),s.on("close",(e,t)=>{clearTimeout(i),o(t?124:e??0)})}),c=s();console.log(),0===i?console.log(chalk.bold.green(` ✓ ran py-${e}`)+chalk.gray(` · ${c}ms · exit 0`)):(console.log(chalk.yellow(` ✗ ran py-${e} · ${c}ms · exit ${i}`)),a&&console.log(chalk.gray(yn()?" ⏱ 超过 30 秒,已停止 — 检查死循环。":" ⏱ Over 30s — stopped. Check for an infinite loop."))),console.log(chalk.gray((yn()," ▸ edit "))+chalk.gray(`${e} · pylist · `)+chalk.bold.green("back")),console.log(),wn.push(Or(e,{run_ms:c,exit_code:i,stderr_head:l.trim().slice(0,300)||void 0},!0).catch(()=>{}))})(t))}else console.log(chalk.yellow(yn()?` 用法: ${e} <编号>`:` Usage: ${e} <n>`)+chalk.gray(yn()?" (pylist 看编号)":" (pylist shows the numbers)"));return void Wt()}const s=/^\/?py(?:\s+(\S+))?$/.exec(o);if(s||"new"===o)return await Yr(s?.[1]),void Wt();const l=/^\/?python(?:3)?(?:\s+(setup|install|status))?$/i.test(o.trim());if("menu"!==o&&"menu confirm"!==o&&!l)return console.log(chalk.gray(yn()?" 草稿本命令: edit <n> · run <n> · pylist · /py 新建 · back 回卡片":" Scratchpad verbs: edit <n> · run <n> · pylist · /py (new) · back to the card")),void Wt()}if(Xt&&jn){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn|memo|cells|explore)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&_(`learn-arena p${jn.phase}s${jn.data.slot}: ${o}`),"memo"===o||"/memo"===o||"e"===o)return Yt=At.currentCard,Ht=`[arena p${jn.phase}-g${jn.data.slot}${xr?` #${xr}`:""}]`,console.log(chalk.gray(yn()?` 报告归到: 竞技场 p${jn.phase}-g${jn.data.slot}${xr?` 题${xr}`:""} — 题面 / 判分 / 环境,一句话即可:`:` Files under: arena p${jn.phase}-g${jn.data.slot}${xr?` problem ${xr}`:""} — statement / judging / environment, one line is enough:`)),console.log(chalk.gray(yn()?" (回车提交 · 空行取消 · 不打断比赛计时)":" (Enter to submit · blank to cancel · the contest clock is unaffected)")),void Wt();if("back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return gr()&&null!==xr?(xr=null,_r(),void Wt()):(Xt=!1,xr=null,console.log(chalk.gray(yn()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Hn(),void Wt());if(/^\d+$/.test(o))return Sr(o),void Wt();const n=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(n)return gr()?n[1]?Sr(n[1]):_r():console.log(chalk.gray(yn()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void Wt();if("cells"===o||"/cells"===o||"explore"===o||"/explore"===o){const e=qn(jn.phase,jn.data.slot,jn.dir);if(!e)return console.log(chalk.gray(Nn(jn.phase,jn.data.slot)?yn()?" 引导 notebook 还没下载到位(需要联网一次)— 稍后再敲 cells。":" The guided notebook has not downloaded yet (needs one online moment) — try cells again shortly.":yn()?" 本场没有引导 notebook — /read <n> 读题;EXPLORE 段在本机把 SHOW 改成 True 即可出图。":" No guided notebook for this group — /read <n> for statements; flip SHOW to True locally in the EXPLORE section for plots.")),void Wt();const o=null!==x();o||T(It);try{const{runIpynb:o}=await import("./ipynb.js");await o(e)}catch(e){console.log(chalk.yellow(yn()?" notebook 没打开: ":" The notebook failed to open: ")+chalk.gray(String(e)))}finally{o||T(null)}return _r(),void Wt()}const r=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(r)return await(async e=>{const o=e.trim();if(await ae()||Tr||(Tr=!0,console.log(chalk.gray(yn()?` (离线:只有 ${ye()} 条核心速查可用;联网后自动补全)`:` (offline: ${ye()} core entries available; the rest arrive when you have a connection)`))),!o)return void ue(yn());const t=ce(o);if(t.length){pe(t[0],yn());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(yn()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await ie("python3",o);if(n)he(n,yn());else{if(await de()){const e=ce(o);if(e.length)return void pe(e[0],yn())}console.log(),console.log(chalk.yellow(yn()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(yn()?" 试试: ":" Try: ")+chalk.cyan(ge(o).join(" · "))),console.log(chalk.gray(yn()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(r[1]??""),void Wt();const l=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(l){const[,e,o]=l;return"list"===e?_r():o?"read"===e||"open"===e?Sr(o):"edit"===e?await(async e=>{const o=Ar(e);if(!o)return;const t=G(jn.dir,lr(o.n,o.p));if(vo())return _o()?(console.log(chalk.yellow(yn()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(yn()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(yn()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(yn()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(yn()?" ← 不能是 /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(yn()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(yn()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(yn()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(yn()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(yn()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(yn()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(yn()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(yn()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!Co("vi"))return console.log(chalk.yellow(yn()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(yn()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));jr();const n=e=>{try{return R(e).size}catch{return 0}},r=n(t),s=Date.now(),l=C(t);await Pr("vi",[...Ir,lr(o.n,o.p)]);const a=l.stop(),i={ms:Date.now()-s,bytesBefore:r,bytesAfter:n(t)};if(En.set(o.n,Y(En.get(o.n)??U(),i)),a.ticks>0){const e=Ln.get(o.n)??{list:[],dropped:0};e.list.push(a),e.list.length>16&&(e.list.shift(),e.dropped++),Ln.set(o.n,e)}_(`learn-arena edit-done ${lr(o.n,o.p)}`,{...i,...a.ticks>0?{samples:a}:{}}),console.log(chalk.gray(yn()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(yn()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?await(async e=>{const o=Ar(e);if(!o)return;const{p:n,n:r}=o;if(or&&r===qe)return void(()=>{const e=G(jn.dir,`sol-${qe}.py`);if(!M(e))return void console.log(chalk.yellow(yn()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=Lr();if(!o)return;const n=[];for(const r of Oe)try{n.push(t(o,[e],{input:`${r.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}))}catch(e){const o=e;if("ENOENT"===o.code)return void Er();if(console.log(),o.killed)return void console.log(chalk.yellow(yn()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(yn()?` ✗ 输入 ${r.in} 时程序报错:`:` ✗ Your program crashed on input ${r.in}:`));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));return console.log(),console.log(chalk.gray(yn()?" 改完再来: ":" Fix it and rerun: ")+chalk.bold.green("/edit 0")+chalk.gray(" → ")+chalk.bold.green("/run 0")),void console.log()}const{cases:r,passed:s}=We(n);console.log();for(const e of r)console.log((e.ok?chalk.green(" ✓ "):chalk.red(" ✗ "))+chalk.gray(`n = ${e.in.padEnd(6)} → `)+(e.ok?chalk.cyan(e.got||"(empty)"):chalk.red(e.got||"(empty)"))+(e.ok?"":chalk.gray(yn()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),s===r.length){const e=tr?null:1;tr=!0,console.log(chalk.bold.green(yn()?` 🎉 ${s}/${r.length} 全过 — `:` 🎉 ${s}/${r.length} — `)+chalk.white(yn()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(yn()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(yn()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(yn()?` ${s}/${r.length} 通过 — 还差一点。`:` ${s}/${r.length} passed — not there yet.`)+chalk.gray(yn()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(yn()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const s=G(jn.dir,lr(r,n));if(!M(s))return void console.log(chalk.yellow(yn()?` 还没有 ${lr(r,n)} — 先 /edit ${r}。`:` No ${lr(r,n)} yet — /edit ${r} first.`));En.set(r,F(En.get(r)??U()));const l=(n.samples??[])[0];if(n.gpu)return console.log(chalk.gray(yn()?" ⚡ GPU 层 — 本机没有 CUDA,这一层在真 GPU 上跑:直接 ":" ⚡ GPU rung — no CUDA on your machine; this level runs on a real GPU: go ")+chalk.bold.green(`/submit ${r}`)+chalk.gray(yn()?"(窗口时间执行并返回你的 ms;窗口外会告诉你开放时间)":" (executes in the GPU window and returns your ms; outside the window it tells you the hours)")),void console.log();{const e=sr(n),o={cpp:"c++",java:"java",go:"go"};if("python"===e?!fo():!Co(o[e]??e)){const t="python"===e?"Python":o[e]??e;return console.log(chalk.yellow(yn()?` ⓘ 本机没有 ${t} 环境 — 这一题直接交给判分机跑。`:` ⓘ No local ${t} environment — running this one on the server judge instead.`)),console.log(chalk.gray(yn()?" 判分机的计时本来就是准数;本地跑只是预览。":" The judge's timing is the real number anyway - local runs were only a preview.")),void await Kr(`/submit ${r}`)}}if(!l&&n.starter){const e=sr(n);try{let o;if("cpp"===e){const e=G(jn.dir,`.speed-${r}.bin`);t("c++",["-O2","-o",e,s],{timeout:3e4,stdio:["pipe","pipe","pipe"]}),o=t(e,[],{input:"",timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}else if("java"===e)o=t("java",[s],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});else if("go"===e)o=t("go",["run",s],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});else{const e=Lr();if(!e)return;o=t(e,[s],{input:"",timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}console.log();for(const e of o.replace(/\n$/,"").split("\n"))console.log(` ${e}`);console.log(),console.log(chalk.gray(yn()?` ${Ge(!0)} — 满意就 `:` ${Ge(!1)} — happy? `)+chalk.bold.green(`/submit ${r}`))}catch(e){const o=e;if("ENOENT"===o.code)Er();else if(o.killed)console.log(chalk.yellow(yn()?" ⏱ 超过 30 秒 — 检查死循环。":" ⏱ Over 30s — check for an infinite loop."));else{console.log(chalk.yellow(yn()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of(o.stderr??"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));console.log(chalk.gray(yn()?` (空还没填对?/read ${r} 看题面的 hint,/edit ${r} 再改)`:` (blank not filled yet? /read ${r} for the hint, /edit ${r} to fix)`))}}return void console.log()}if(!l)return void console.log(chalk.gray(yn()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";const i=Lr();if(!i)return;const c=oo();try{a=t(i,[s],{input:l.in.endsWith("\n")?l.in:`${l.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(e){const o=e;if("ENOENT"===o.code)Er();else if(o.killed)console.log(chalk.yellow(yn()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(yn()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const d=c(),g=a.replace(/\r\n/g,"\n").trimEnd(),u=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(yn()?" 你的输出:":" Your output:"));for(const e of(g||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(yn()?" 样例应输出:":" Sample expects:"));for(const e of u.split("\n"))console.log(chalk.green(` ${e}`));console.log(chalk.gray(` ⏱ ${d}ms — ${Ge(yn())}`)),g===u?console.log(chalk.bold.green(yn()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(yn()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(yn()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(yn()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=Ar(e);if(!o)return;if("python"!==sr(o.p)||o.p.gpu)return console.log(chalk.gray(yn()?` 这一层不读输入 — 用 /run ${o.n} 本机跑,或直接 /submit ${o.n}(判分机编译计时)。`:` This level reads no input — use /run ${o.n} locally, or /submit ${o.n} (the judge compiles and times it).`)),void console.log();const t=G(jn.dir,`sol-${o.n}.py`);if(!M(t))return void console.log(chalk.yellow(yn()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));const n=Lr();if(!n)return;console.log(chalk.gray(yn()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const r=await Pr(n,[`sol-${o.n}.py`]);console.log(),"ENOENT"!==r?.code?(console.log(chalk.gray(yn()?" 回到竞技场。":" Back in the arena.")),console.log()):Er()})(o):"recall"===e&&await(async e=>{const o=Ar(e);if(!o)return;if(!bt)return void Kn();const{p:t,n:n}=o,r=G(process.cwd(),"icoa-contest"),s=`${mt.id}-phase${jn.phase}-g${jn.data.slot}-archived-`;let l=null;try{for(const e of q(r))e.startsWith(s)&&(!l||e>l)&&(l=e)}catch{}const a=l?G(r,l,`sol-${n}.py`):null;if(!a||!M(a))return void console.log(chalk.gray(yn()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=O(a,"utf-8"),c=`${jn.phase}-${jn.data.slot}-${n}`,d=Math.min(3,(Mr.get(c)??0)+1);console.log(chalk.gray(yn()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await $e({token:yt,phase:jn.phase,slot:jn.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:yn()?"zh":"en"});if(g.ok){Mr.set(c,d),console.log();for(const e of gt(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(yn()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(yn()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(yn()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(yn()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(yn()?" (花名册: /list)":" (roster: /list)")),void Wt()}if("contest"===o||"/contest"===o)return _r(),void Wt();const a="lang"===o||/^lang\s+\S+$/.test(o),i=ht.has(o);if(!(/^\/?python(?:3)?(?:\s+(setup|install|status))?$/i.test(o.trim())||"submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||"restart"===o||a||i||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(yn()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void Wt()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(yn()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Wt()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(It.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}Ot=!0;const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Ot=!1,It.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void Wt()}if("ai4ioai"===o||"/ai4ioai"===o)return await L()&&(an=!0),void Wt();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!bt)return Kn(),void Wt();ln||(ln=!0,console.log(),console.log(chalk.bold.cyan(yn()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(yn()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(yn()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),yn()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")),console.log(chalk.gray(yn()?" 💡 一次好的研究通常会向 AI 要到 3 段可运行的 Python 代码;建议每张卡都用 ":" 💡 A good research run usually asks the AI for 3 runnable Python snippets; for each card, ")+chalk.bold.green("/py")+chalk.gray(yn()?" 新建草稿贴进去跑(":" a fresh scratch file and run them (")+chalk.bold.green("/pylist")+chalk.gray(yn()?" 看草稿)。":" lists them).")),console.log(chalk.yellow(yn()?" ↩ 重要:退出 AI 模式只需输入 ":" ↩ Important: to leave AI mode just type ")+chalk.bold.white("back")+chalk.yellow(yn()?" 或 ":" or ")+chalk.bold.white("quit")+chalk.yellow(yn()?",就回到卡片。":" — you are back on the card.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Jt=!0;const e=An(At.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(yn()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(yn()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yn()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · back / quit = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · back / quit = back to card")),console.log(chalk.gray(yn()?" 💡 通常要向 AI 要到 3 段 Python 代码 · back 回卡片后 /py 新建草稿运行 · /pylist 看草稿":" 💡 Usually ask for 3 Python snippets · back to the card, then /py a new scratch to run · /pylist lists them")),console.log(),void Wt()}return await Jn(n,t?"fast":"deep"),void Wt()}if(!Xt&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!bt)return Kn(),void Wt();const e=An(At.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(yn()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(yn()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yn()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(yn()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(yn()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(yn()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(yn()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),gn=!0,void Wt()}const p=!Xt&&"honors"===nn&&/^[1-3]$/.test(o);if(!Xt&&nn&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(yn()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(yn()?" ↩ back 回上一层":" ↩ back goes up one level")),void Wt();if(!Xt&&(p||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!bt)return Kn(),void Wt();const e=/^\/?view ([1-3])$/.exec(o),t=p?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Qt=!0;try{console.log();const o=await ve({token:yt,cardNumber:At.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(yn()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&un.delete(At.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&un.add(At.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(yn()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${At.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${At.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(yn()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(yn()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Qn(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(yn()?" (无可显示的提问)":" (no questions to show)"))}console.log(),nn="view",console.log(chalk.gray((yn()," "))+chalk.bold.cyan("↩ back")+chalk.gray(yn()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Qt=!1}})(t),void Wt()}const m=o.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(m&&!Xt&&!Vt){const{certificateLines:e}=await import("../lib/learn-door.js"),{certifiable:o,certificateIntroLines:t}=await import("../lib/learn-certificate.js"),n=yn(),r=ft?null:await y(yt,"me"),s=r&&"ok"===r.kind?r.profile:null,l=o(s),a=(m[2]??"").toLowerCase();console.log();const i=a?l.find(e=>e.curriculum_id.toLowerCase()===a||e.curriculum_id.toLowerCase().startsWith(a)):l.find(e=>e.curriculum_id===mt.id)??(1===l.length?l[0]:void 0);if(!i){for(const o of e(s,n))console.log(o);return l.length>1&&console.log(chalk.gray(" ")+chalk.bold.green("certificate <track>")+chalk.gray(n?" 签发其中一门。":" to issue one.")),console.log(),void Wt()}for(const e of t(i,n))console.log(e);return console.log(chalk.gray(n?" (空行或 back 取消)":" (blank line or back cancels)")),console.log(),console.log(chalk.bold.cyan(n?" 证书上的名字:":" Name on the certificate:")),qt={cid:i.curriculum_id,tok:i.token,first:null},void Wt()}const $=o.match(/^\/?(story|credits|fin)(?:\s+(\S+))?$/);if($&&!Xt&&!Vt){const e=($[2]??"").trim();return await Tn("story"===$[1]?e||"list":e||null,!0),void Wt()}if(/^\/?(?:type|typing)(?:\s|$)/i.test(o))return await ko(o.trim().split(/\s+/).slice(1)),void Wt();if("me"===o||"/me"===o||"profile"===o||"/profile"===o||"my profile"===o){const e=yn();if(ft)return console.log(),console.log(chalk.gray(e?" 档案属于正式 learn token — demo 是大家共用的。":" Profiles belong to full learn tokens — the demo is shared by everyone.")),console.log(),void Wt();console.log(chalk.gray(e?" 正在取档案…":" Loading your profile…"));const o=await y(yt);return"ok"===o.kind?f(o.profile,e,ct()):"offline"===o.kind?(console.log(chalk.yellow(e?" 现在连不上 learn 服务器 — 档案住在服务端,联网后再试 me。":" Cannot reach the learn server right now — your profile lives there; try me again online.")),console.log()):(console.log(chalk.yellow(` ${"demo"===o.kind?e?"demo token 没有档案":"No profile for a demo token":o.message}`)),console.log()),void Wt()}if("/honors"===o||"honors"===o)return ft?(console.log(),console.log(chalk.gray(yn()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Wt()):(await Vn(),void Wt());const b=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(b)return _("learn-py: pylist"+(b[1]?` ${b[1]}`:"")),Dr(b[1]),void Wt();const w=/^\/?py(?:\s+(\S+))?$/.exec(o);if(w)return await Yr(w[1]),void Wt();if(/^\/?sh$/.test(o))return(()=>{const e=!en;en=!0,on=Fr();const o=Zr();_(`learn-sh: enter card${At.currentCard}`),e&&zr(),o.length>0&&(console.log(chalk.bold.green(yn()?" 📦 本卡的文件已放好:":" 📦 This card ships files:")+chalk.white(` ${o.join(" ")}`)),console.log(chalk.gray(yn()?" 先敲 ls 看看。":" Start with `ls`.")),console.log()),Gr()})(),void Wt();const k=/^\/?python(?:3)?(?:\s+(setup|install|status))?$/i.exec(o.trim());if(k){_(`learn-python: ${k[1]??"status"}`);const{runSetup:e,printStatus:o}=await import("./python.js"),t=(k[1]??"").toLowerCase();return"setup"===t||"install"===t?await e():o(),console.log(chalk.gray(yn()?" ↩ back 回卡片 · ":" ↩ back to the card · ")+chalk.bold.green("/py")+chalk.gray(yn()?" 打开草稿本":" opens the scratchpad")),console.log(),void Wt()}if("menu"===o||"menu confirm"===o){if(Lt?.detach(),wn.length>0&&await Promise.race([Promise.allSettled(wn),new Promise(e=>setTimeout(e,3e3))]),It.removeAllListeners("line"),Et(),St||!Cn){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(St?It:void 0),_n()}else It.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===nn)return await Vn(),void Wt();if("honors"===nn)return nn=null,Hn(),void Wt();if(Lt?.detach(),wn.length>0&&await Promise.race([Promise.allSettled(wn),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${At.streakDays} day(s)`)),console.log(),St){It.removeAllListeners("line"),Et();for(const e of Pt)It.on("line",e);It.prompt(),_n()}else It.removeAllListeners("line"),It.close();return}if(te(o))return vt?pt(ee(vt,yn(),ct(),"T0"===ne().tier),!!vt.completedAt):(console.log(chalk.gray(yn()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void Wt();if("status"===o||/^status\s+/.test(o)){const e=o.slice(6).trim().toLowerCase(),t="all"===e?"all":/^\d+$/.test(e)?Number(e):"current";if(On){const[,e]=await Promise.all([Un(),Z(mt.id,yt,!0)]);e&&Object.assign(mt,e)}return Ho(mt,At,{gate:In,gated:wt,focus:t,posForSlot:Le}),void Wt()}if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await Z(mt.id,yt,!0);return void(e?(Object.assign(mt,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Hn()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),Wt()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(bo().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Wt();const t=mt.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,s=r?n:"en";return wo({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Ut=null,Rt=null,Dt=null,Kt(),hn=!1,gn=!1,await Xn(),void Wt()}const v=o.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(v&&!Xt&&!Vt&&null===tn&&g.test(o)){const e=yn(),o=await u(yt);if("ok"===o.kind)for(const t of h(o.log,e,"T0"===ne().tier,e?"Enter 继续学习":"Enter to keep learning"))console.log(t);else console.log(chalk.yellow("offline"===o.kind?e?" 离线 — 专注记录在服务端,联网后再看。":" Offline — the focus log lives on the server; try again when connected.":"demo"===o.kind?e?" Demo token 是共享的,没有专注记录。":" Demo tokens are shared — no focus log.":e?` 专注记录加载失败:${o.message}`:` Could not load the focus log: ${o.message}`));return console.log(),void Wt()}if(v&&!Xt&&!Vt&&null===tn){const e=(v[2]??"").trim(),o=yn(),t=`${a}–${l}`+(o?`,${i} 的倍数`:`, steps of ${i}`);if("off"===e||"stop"===e||"end"===e||"cancel"===e||"关"===e)return void(Lt?.stop()||(console.log(chalk.gray(o?" 没有进行中的专注。开始一场:":" No focus session running. Start one: ")+chalk.bold.green("focus 30")),Wt()));if(Lt?.active)return console.log(chalk.yellow(" ⏱ ")+chalk.white(o?`专注进行中 · 还剩 ${Lt.remainingMin()} 分钟`:`focus running · ${Lt.remainingMin()} min left`)+chalk.gray(o?" · 提前结束:":" · end early: ")+chalk.bold.green("focus off")),void Wt();if(""===e||"?"===e||"help"===e)return console.log(),console.log(chalk.bold.white(o?" ⏱ 专注一场":" ⏱ Focus session")),console.log(chalk.gray(o?` 多少分钟?(${t}) 例如 `:` How long? (${t}) e.g. `)+chalk.bold.green("focus 30")),console.log(chalk.gray(o?" 每 10 分钟轻提醒一次,到点给你一份这段时间的学习报告。":" A soft reminder every 10 min, and a report on what you did when time is up.")),console.log(),void Wt();const n=d(e);if(!n)return console.log(chalk.yellow(o?` 看不懂「${e}」。`:` Didn't understand "${e}". `)+chalk.gray(o?`请输分钟数(${t}),例如 `:`Type minutes (${t}), e.g. `)+chalk.bold.green("focus 30")),void Wt();if("ok"!==n.note){const t="min"===n.note?o?`最少 ${a}`:`min is ${a}`:"max"===n.note?o?`最多 ${l}`:`max is ${l}`:o?`取最近的 ${i} 的倍数`:`rounded to the nearest ${i}`;console.log(chalk.gray(o?` 你输入 ${e} → ${t},用 ${n.min}`:` you typed ${e} → ${t}, using ${n.min}`))}return Lt?.start(n.min),console.log(),console.log(chalk.yellow(" ⏱ ")+chalk.bold.white(o?`专注 ${n.min} 分钟开始`:`Focus ${n.min} min — go`)+chalk.gray(o?" · 每 10 分钟一次轻提醒 · 提前结束:":" · soft reminder every 10 min · end early: ")+chalk.bold.green("focus off")),console.log(),void Wt()}if(ht.has(o)){const e=ht.get(o),t=at(bo()),n=e=>{const o=["normal","wide","wider","widest"].filter(o=>o!==e);return yn()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((yn()?"normal"===e?" 已是标准 64 列。":ct()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${ct()} 列,上限 ${it(e)})。`:"normal"===e?" Already at the standard 64 cols. ":ct()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${ct()} cols, cap ${it(e)}). `)+n(e))),void Wt()):(wo({learnWidth:e,learnWide:"normal"!==e}),lt(e),"normal"!==e&&ct()<=64?(console.log(chalk.yellow(yn()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((yn()?` 设置已记住(${e},上限 ${it(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${it(e)} cols) and applies once you widen the window. `)+n(e))),void Wt()):(console.log(chalk.green(" ✓ ")+chalk.gray((yn()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${ct()} 列,上限 ${it(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${ct()} cols, cap ${it(e)}). `)+n(e))),Ut=null,Rt=null,Dt=null,Kt(),hn=!1,gn=!1,await Xn(),void Wt()))}if("sim"===o){const e=An(At.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=z(H(import.meta.url)),o=[G(e,"..","..","panda","mujoco-launcher.py"),G(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(M(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void Wt()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Wt())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=At.currentCard,t=At.bookmarks.includes(e),n="bookmark"!==o;return n?At.bookmarks=At.bookmarks.filter(o=>o!==e):t||At.bookmarks.push(e),xo(At),n?console.log(t?chalk.gray(yn()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(yn()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(yn()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(yn()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Wt()}const A=re(o);if(A){const e="current"===A.target?At.currentCard:A.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>mt.cards.length))return console.log(chalk.yellow(yn()?` 本课共 ${mt.cards.length} 张,请输 r 1–${mt.cards.length} 或 r all。`:` This course has ${mt.cards.length} cards. Try r 1–${mt.cards.length} or r all.`)),console.log(),void Wt();for(const o of se(kt,bn,e,yn(),ct()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?kt:kt.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(kt=kt.map(e=>o.includes(e.id)?{...e,seen:!0}:e),st(kt),wn.push(J(yt,{card_number:At.currentCard,event_type:"viewed"},o).catch(()=>{}))),void Wt()}if("e"===o||"memo"===o)return Yt=At.currentCard,console.log(chalk.gray(yn()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(yn()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void Wt();if("back"===o||"b"===o&&null===Rt)return"view"===nn?(await Vn(),void Wt()):"honors"===nn?(nn=null,Hn(),void Wt()):(At.currentCard>1&&(At.currentCard-=1),Rt=null,Dt=null,Ut=null,xo(At),Hn(),void Wt());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!On)return console.log(chalk.yellow(yn()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Wt();if(!e){const e=await Se(yt),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(yn()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(yn()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(yn()?` 这台电脑上有 ${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(yn()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(yn()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(yn()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(yn()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(yn()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(yn()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(yn()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Wt()}if(/^\d{1,2}$/.test(e)){const o=await Te(yt,Number(e));return o.ok&&o.data?(ir(o.data),await Un(),void Wt()):(console.log(chalk.red(` ✗ ${o.message||(yn()?"关联失败":"Link failed")}`)),void Wt())}const t=await Pe(yt,e);return t.ok&&t.data?(ir(t.data),await Un(),void Wt()):(console.log(chalk.red(` ✗ ${t.message||(yn()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(yn()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Wt())}if("contest"===o||"/contest"===o||"arena"===o||"contest start"===o||"/contest start"===o||"contest status"===o||"contest reset"===o||"contest restart"===o||"restart"===o||/^\/?contest [1-9]$/.test(o)){if(!On)return console.log(chalk.yellow(yn()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Wt();let e=Yn(At.currentCard),t=null;const n="contest restart"===o||"restart"===o;if(n&&(!Xt||!jn||gr()))return console.log(chalk.gray(yn()?" restart 只在赛场里用(重开当前这一组)。在卡片上用 contest <组号> 开一组,contest reset 放弃整个阶段的计时。":" restart works inside an arena (it reopens the current group). From the card: contest <n> opens a group · contest reset abandons the whole phase.")),void Wt();if(n&&jn){const o=jn.phase,n=jn.data.slot,r=await Ce(yt,o,n);if(!r.ok&&"no_active_session"!==r.code)return console.log(chalk.red(` ✗ ${r.message||"reset failed"}`)),void Wt();ur(o,n),console.log(chalk.yellow(yn()?` 🔄 第 ${n} 组重开 — 全新计时、全新模板。`:` 🔄 Group ${n} restarted — fresh clock, fresh templates.`)+chalk.gray(yn()?" 只有计时内写的才算数:从头再写一遍,这正是练习。":" Only work written on the clock counts — write it again from scratch; that is the practice.")),jn=null,Xt=!1,xr=null,e=o,t=n}if("contest reset"===o&&Xt&&gr()){const e=jn.phase,o=jn.data.slot,t=await Ce(yt,e,o);if(t.ok){console.log(chalk.yellow(yn()?" 已放弃本卡练习计时。回卡片后输入 practice <题号> 重新开始。":" Practice attempt abandoned. From the card, practice <n> starts a fresh one."));const t=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),n=G(process.cwd(),"icoa-contest",`${mt.id}-phase${e}-g${o}`);if(M(n))try{W(n,`${n}-archived-${t}`),console.log(chalk.gray(yn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(yn()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}jn=null,Xt=!1,xr=null,Hn()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void Wt()}if("contest reset"===o){const o=await Ce(yt,e);if(o.ok){console.log(chalk.yellow(yn()?` 已放弃本阶段(${e})所有计时。输入 contest <组号> 重开某一组(裸 contest 会开第一个未过的组)。`:` All live attempts in phase ${e} abandoned. Type contest <n> to reopen a group (bare contest opens the first unpassed one).`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),t=G(process.cwd(),"icoa-contest"),n=new RegExp(`^${mt.id}-phase${e}-g(\\d+)$`),r=(M(t)?q(t):[]).map(e=>({name:e,m:n.exec(e)})).filter(({m:e})=>e&&Number(e[1])<dr).map(({name:e})=>e).sort();for(const e of r){const n=G(t,e);try{W(n,`${n}-archived-${o}`),console.log(chalk.gray(yn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(yn()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(yn()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),jn=null,Xt=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Wt()}const r=null!=t?String(t):/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(yn()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(yt,e,r?parseInt(r,10):void 0);if(!s.ok||!s.data){if("no_contest"===s.code){const o=mt.modules.find(o=>o.number===e)?.cardRange,t=!!o&&o[1]-o[0]+1>12;console.log(chalk.gray(t?yn()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(360 层第二阶段标准设计中)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (360-tier second-stage standard in design).`:fn?yn()?` 本阶段(${e})的 3 场判分赛制作中 — 很快更新;赛场挂在卡 4 / 8 / 12,3 场全过解锁下一阶段(本轨无 research)。`:` Phase ${e}'s 3 judged arenas are in production — coming soon; they hang on cards 4 / 8 / 12 and all 3 unlock the next phase (no research on this track).`:yn()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(标准范式:3 场练习赛 + 3 卡研究)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (standard: 3 arenas + 3 research cards).`))}else console.log(chalk.red(` ✗ ${s.message||"contest unavailable"}`));return void Wt()}const l=s.data,a=G(process.cwd(),"icoa-contest",`${mt.id}-phase${e}-g${l.slot}`);if(!l.resumed&&M(a)&&q(a).some(e=>/^sol-\d+\.[a-z]+$/.test(e))){const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{W(a,`${a}-archived-${e}`),console.log(chalk.gray(yn()?" 📦 上一场的答题文件已归档: ":" 📦 Previous window archived: ")+chalk.gray(`${a}-archived-${e}`)),console.log(chalk.gray(yn()?" 新场次全新模板 — 计时窗口内写的才算数。":" Fresh window, fresh templates — only work done on the clock counts."))}catch{console.log(chalk.yellow(yn()?` ⚠ 归档失败(比赛照常): ${a}`:` ⚠ Could not archive (contest still fine): ${a}`))}}N(a,{recursive:!0});const i=jn&&jn.phase===e&&jn.data.slot===l.slot?jn.tried:new Set;jn&&jn.phase===e&&jn.data.slot===l.slot&&jn.data.attempt===l.attempt||(En.clear(),Ln.clear()),jn={phase:e,dir:a,data:l,tried:i},ar(l,a),qn(e,l.slot,a),Xt=!0,_r(),console.log(chalk.gray(yn()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(a));const c=l.problems.findIndex(e=>!l.solved.includes(e.id))+1||1,d=or&&!tr?qe:c;return console.log(chalk.white(yn()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${d}`)+chalk.gray(d===qe?yn()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":yn()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Wt()}const S=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(fn&&/^[1-9]$/.test(o)?`practice ${o}`:o);if(S){const e=An(At.currentCard),o=pr(e);if(!o)return console.log(chalk.gray(yn()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void Wt();if(!On)return console.log(chalk.yellow(yn()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void Wt();if(!S[1])return console.log(),mr(e),console.log(chalk.gray(yn()?" 用法: ":" Usage: ")+chalk.bold.green(yn()?"practice <题号>":"practice <n>")+chalk.gray(yn()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void Wt();const t=parseInt(S[1],10);return!Number.isInteger(t)||t<1||t>o.length?(console.log(chalk.yellow(yn()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void Wt()):(await(fn?(async(e,o,t)=>{const n=Yn(e.number),r=dr+e.number;console.log(chalk.gray(yn()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(yt,n,r,!0);if(!s.ok||!s.data)return void("no_contest"===s.code?console.log(chalk.gray(yn()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${s.message||"practice unavailable"}`)));const l=s.data;if(0===l.problems.length)return void console.log(chalk.gray(yn()?" 本卡练习题库是空的。":" This card practice set is empty."));const a=new Map(l.problems.map(e=>[e.id,e])),i=[];for(const e of o){const o=a.has(hr(e.py_id))?hr(e.py_id):a.has(e.py_id)?e.py_id:null;o&&(i.push(a.get(o)),a.delete(o))}for(const e of l.problems)a.has(e.id)&&i.push(e);l.problems=i;let c=Wn.get(r);c||(c=new Set,Wn.set(r,c));for(const e of l.solved)c.add(e);tn={card:e,phase:n,slot:r,data:l,idx:Math.min(Math.max(t,1),l.problems.length)-1,answers:[],tries:0},_(`learn-fillpractice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(yn()?` ⚡ 快速填空 — 第 ${e.number} 张卡`:` ⚡ Quick fill — card ${e.number}`)+chalk.gray(yn()?"(敲答案 → 自动判分 · 不计分)":" (type the blank → auto-judged · unscored)")),console.log(chalk.gray(yn()?` ⏱ 每次练习 ${l.duration_minutes} 分钟 · 剩 ${je(l.deadline)??"0:00"} · 到时敲 back 再 practice 重开`:` ⏱ ${l.duration_minutes}-minute practice window · ${je(l.deadline)??"0:00"} left · when it ends: back, then practice again`)),kr()})(e,o,t):(async(e,o,t)=>{const n=Yn(e.number),r=dr+e.number;console.log(chalk.gray(yn()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(yt,n,r,!0);if(!s.ok||!s.data)return void("no_contest"===s.code?console.log(chalk.gray(yn()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${s.message||"practice unavailable"}`)));const l=s.data;if(0===l.problems.length)return void console.log(chalk.gray(yn()?" 本卡练习题库是空的。":" This card practice set is empty."));const a=new Map(l.problems.map(e=>[e.id,e])),i=[];for(const e of o){const o=a.has(hr(e.py_id))?hr(e.py_id):a.has(e.py_id)?e.py_id:null;o&&(i.push(a.get(o)),a.delete(o))}for(const e of l.problems)a.has(e.id)&&i.push(e);l.problems=i;let c=Wn.get(r);c||(c=new Set,Wn.set(r,c));for(const e of l.solved)c.add(e);const d=G(process.cwd(),"icoa-contest",`${mt.id}-phase${n}-g${r}`);N(d,{recursive:!0});const g=jn&&jn.phase===n&&jn.data.slot===r?jn.tried:new Set;jn&&jn.phase===n&&jn.data.slot===r&&jn.data.attempt===l.attempt||(En.clear(),Ln.clear()),jn={phase:n,dir:d,data:l,tried:g},ar(l,d),Xt=!0,xr=null,_(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(yn()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(yn()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(yn()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(d)),console.log(chalk.gray((yn()," ↩ "))+chalk.bold.green("back")+chalk.gray(yn()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),Sr(String(Math.min(t,l.problems.length)))})(e,o,t)),void Wt())}if("submit"===s)return console.log(chalk.yellow(yn()?" 用法: ":" Usage: ")+chalk.bold.green(yn()?"submit <题号>":"submit <n>")+chalk.gray(yn()?" 例如 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)")),jn||console.log(chalk.gray(yn()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Wt();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!jn)return console.log(chalk.yellow(yn()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Wt();const n=jn.data.problems,r=parseInt(o,10);if(or&&r===qe)return console.log(chalk.gray(yn()?" 热身题不判分 — /run 0 就是它的完整判定(10 个用例全在本机)。":" The warm-up is not judged — /run 0 IS its full check (all ten cases, on your machine).")),console.log(chalk.white(yn()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(yn()?" 开始。":".")),void Wt();if(Number.isInteger(r)&&r>=1&&r<=n.length&&!n.some(e=>e.id===o)&&(o=n[r-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(yn()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Wt();const l=n.findIndex(e=>e.id===o)+1,a=t||G(jn.dir,lr(l,n[l-1]));let i;try{i=O(a,"utf-8")}catch{return console.log(chalk.red(yn()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Wt()}const c=new I(yt);c.start();const d=En.get(l),g=Ln.get(l),u=d&&!B(d)?{...d,...g?{samples:g.list}:{},...g&&g.dropped>0?{samplesDropped:g.dropped}:{}}:void 0,h=await xe(yt,jn.phase,o,i,jn.data.slot>=dr?jn.data.slot:void 0,u);if(c.stop(),!h.ok||!h.data)return"no_active_session"===h.code&&jn.data.slot>=dr?$r(jn.data.duration_minutes):"no_active_session"===h.code?(ur(jn.phase,jn.data.slot),console.log(chalk.yellow(yn()?" ⏱ 时间到 — 这一场结束了,判分机已停表。":" ⏱ Time is up — this attempt is over; the judge stopped the clock.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(yn()?" 重开这一组:全新计时 + 全新模板(旧文件已归档)。只有计时内写的才算数 — 从头再写一遍,这正是练习。":" reopens this group: fresh clock + fresh templates (old files archived). Only work written on the clock counts — write it again from scratch; that is the practice.")),console.log(chalk.gray(yn()?" ↩ back 回卡片":" ↩ back returns to the card"))):(console.log(chalk.red(` ✗ ${h.message||"judging failed"}`)),console.log(chalk.gray(yn()?" 判分服务异常?敲 memo 一句话告诉我们 — 不打断比赛计时。":" Judge acting up? Type memo — one line reaches us, the clock is unaffected."))),void Wt();const p=h.data;if(p.already_ac)console.log(chalk.green(yn()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===p.verdict){if(console.log(ho("AC",{isZh:yn(),passed:p.passed_tests??p.total_tests??null,total:p.total_tests??null,ms:p.time_ms??null})),jn.data.solved.includes(o)||jn.data.solved.push(o),jn.tried.delete(o),gr()){let e=Wn.get(jn.data.slot);e||(e=new Set,Wn.set(jn.data.slot,e)),e.add(o);const t=await _e({token:yt,curriculumId:mt.id,cardNumber:At.currentCard}),n=t.ok?t.practiceBoard:null;if(n?.mine){const e=n.top[0],o=e&&!e.me?chalk.gray(yn()?` · 榜首 ${e.name||"Rank 1"} ${e.ac} AC`:` · leader ${e.name||"Rank 1"} at ${e.ac} AC`):chalk.bold.yellow(yn()?" · 全场第一!":" · phase leader!");console.log(chalk.white(yn()?` ⚔ Phase ${n.phase} Practice AC: `:` ⚔ Phase ${n.phase} practice AC: `)+chalk.bold.yellow(`${n.mine.ac}`)+chalk.gray(`/${n.problems_total}`)+chalk.gray(yn()?` · 第 ${n.mine.rank} 名`:` · rank ${n.mine.rank}`)+o)}}}else jn.tried.add(o),console.log(ho(p.verdict,{isZh:yn(),passed:p.passed_tests??null,total:p.total_tests??null,failedTest:p.test??null,ms:p.time_ms??null})),Zt||(Zt=!0,console.log(chalk.gray(yn()?" 觉得题面有误或判分不对?敲 memo 一句话 — 不打断比赛计时。":" Statement wrong or judging looks off? Type memo — one line, the clock is unaffected.")));p.late&&console.log(chalk.yellow(yn()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const y=je(p.deadline||""),m=gr();if(console.log(chalk.white(m?yn()?` 本卡练习: 已过 ${p.ac_count}/${p.n} 题(不计分)`:` Card practice: ${p.ac_count}/${p.n} solved (unscored)`:yn()?` 本组进度: 已过 ${p.ac_count} 题 · 过 ${p.need} 题过关(共 ${p.n} 题)`:` Group progress: ${p.ac_count} solved · ${p.need} needed to pass (${p.n} problems)`)+(y?chalk.gray(` · ⏱ ${y}`):"")),m&&!p.late&&p.ac_count>=p.n)console.log(chalk.bold.green(yn()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(yn()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!p.passed||p.late||m){if(!p.late){const e=n.findIndex(e=>!jn.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(yn()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${er(n[e])}`))}}else{const e=Math.max(0,p.n-p.ac_count);if(0===e)console.log(chalk.bold.green(yn()?` 🎉 满分!${p.n}/${p.n} 全部 AC — 这组题你已经彻底拿下。`:` 🎉 Perfect! ${p.n}/${p.n} AC — you have completely cleared this group.`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(yn()?" 回到上一层(卡片),继续往下学;":" returns to the previous layer (the card) — keep going from there; ")+chalk.bold.green("contest")+chalk.gray(yn()?" 看本阶段其他赛场。":" lists the other arenas of this phase."));else{console.log(chalk.bold.green(yn()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")+chalk.yellow(yn()?` 还剩 ${e} 题 — 全部做完就是满分 ${p.n}/${p.n},别停在这里。`:` ${e} more to go — solve them all for a perfect ${p.n}/${p.n}, don't stop here.`));const o=n.findIndex(e=>!jn.data.solved.includes(e.id));o>=0&&console.log(chalk.gray(yn()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${o+1}`)+chalk.gray(` ${er(n[o])}`)+chalk.gray(yn()?" · ↩ back 回卡片":" · ↩ back returns to the card"))}await Un()}return void Wt()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>mt.totalCards)return console.log(chalk.yellow(` Card number must be 1..${mt.totalCards}. Try: `)+chalk.bold.green("card 1")),void Wt();const n=await Fn(t);return n?(console.log(n),void Wt()):(At.currentCard=t,Rt=null,Dt=null,Ut=null,xo(At),Hn(),void Wt())}if(null!==Ut&&["y","yes","n","no"].includes(o)){const e=An(Ut);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-pn;Lt?.noteCheck(n,r),jo(At,e.number),Lo(At,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),xo(At);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),wn.push(J(yt,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Ut=null,Pn(),e.solution&&e.solution.length>0)return void Wt();if(yr())return void Wt();if(At.currentCard<mt.totalCards){const e=At.currentCard,o=await Fn(e+1);if(o)return await zn(e),console.log(o),void Wt();At.currentCard+=1,xo(At),await zn(e)?Gn():Hn(),Wt()}else Ko(mt,At),Tn(null,!1).then(()=>Wt()),Wt();return}}if(null!==Rt&&["a","b","c","d"].includes(o)){const e=An(Rt);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(Eo(At,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),jo(At,e.number),xo(At),Ro(e,t,n,At),wn.push(J(yt,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Rt=null,n)if(At.currentCard<mt.totalCards){const e=await Fn(At.currentCard+1);if(e)return console.log(e),void Wt();At.currentCard+=1,xo(At),Hn()}else Ko(mt,At),Tn(null,!1).then(()=>Wt()),Wt();else Wt();return}}if(null!==Dt){if("done"===o){const e=An(Dt);if(e&&"practical"===e.type)return Mo(At,e.number),jo(At,e.number),xo(At),Uo(e),Dt=null,void Wt()}if("skip"===o)return jo(At,Dt),xo(At),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Dt=null,void Wt()}const P=fn&&"skip"===o&&null===Rt&&null===Dt&&null===Ut&&null!==pr(An(At.currentCard));if("ok"===o||"next"===o||"continue"===o||"n"===o||P){if(P){const e=At.currentCard;Dn.add(e),Lt?.notePracticeSkipped(),console.log(chalk.gray(yn()?" ⚔ 本卡练习已跳过(有记录)。":" ⚔ Practice skipped for this card (recorded).")),J(yt,{card_number:e,event_type:"practice_skipped"}).catch(()=>{})}else if(null===Ut&&null===Rt&&null===Dt&&yr())return void Wt();if(null!==Rt)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Wt();if(null!==Dt)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Wt();if(null!==Ut)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Wt();const e=At.currentCard,o=e<mt.totalCards?await Fn(e+1):null;return o?(await zn(e),console.log(o),void Wt()):(At.currentCard+=1,xo(At),At.currentCard>mt.totalCards?(Ko(mt,At),Tn(null,!1).then(()=>Wt())):await zn(e)?Gn():Hn(),void Wt())}return null!==Ut?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Wt()):null!==Rt?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Wt()):null!==Dt?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Wt()):("view"===nn?console.log(chalk.gray(yn()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(yn()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(yn()?" 回卡片":" to the card")):"honors"===nn?console.log(chalk.gray(yn()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(yn()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(yn()?" 回卡片":" 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")),void Wt())};It.on("line",e=>{Kr(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.")),Wt()})}),St||It.on("close",async()=>{Lt?.detach(),wn.length>0&&await Promise.race([Promise.allSettled(wn),new Promise(e=>setTimeout(e,5e3))]),Cn?_n():process.exit(0)});const Jr=le(kt,yn());Jr&&(console.log(chalk.bold.cyan(` ${Jr}`)),console.log());try{Hn();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0),(async()=>{for(let e=0;e<20&&!In;e++)await new Promise(e=>setTimeout(e,250));const e=Sn();null!==e&&e>0&&e<=2&&(await Pn(!0),Wt())})();const o=Lt?.attach(yt,mt.id,xn);"resumed"===o&&(console.log(chalk.yellow(" ⏱ ")+chalk.white(yn()?`专注进行中 · 还剩 ${Lt.remainingMin()} 分钟 · 这条轨也算在内 · focus off 提前结束`:`focus running · ${Lt.remainingMin()} min left · this course counts too · focus off to end early`)),console.log()),Wt()}catch{if(ut("Could not render this card — the curriculum may be malformed."),St){It.removeAllListeners("line"),Et();for(const e of Pt)It.on("line",e);It.prompt()}else It.close();_n()}await vn}),yo.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),s=await Z(e),l=Date.now()-o;if(s){const e=s.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(s).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${l.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{rearmFocusMode as s}from"../lib/input-dynamics.js";import{FOCUS_MAX as l,FOCUS_MIN as a,FOCUS_STEP as i,getStudyTimer as c,parseFocusMinutes as d}from"../lib/learn-study-timer.js";import{FOCUS_LOG_RE as g,fetchFocusLog as u,renderFocusLog as h}from"../lib/learn-focus-log.js";import{setLearnFooterExtra as p}from"../lib/learn-render.js";import{fetchLearnProfile as y,postCreditsRolled as m,renderLearnProfile as f}from"../lib/learn-profile.js";import{buildCreditLines as $,creditsProgress as b,creditsRoadLines as w,rollCredits as k,storyListLines as v}from"../lib/learn-credits.js";import{logCommand as _}from"../lib/logger.js";import{startEditSampler as C}from"../lib/edit-sampler.js";import{probeVimInsertExpand as A}from"../lib/editor-spawn.js";import{getMainRl as x,setMainRl as T}from"../lib/main-rl.js";import{assetDir as S,lazyJson as P}from"../lib/lazy-assets.js";import{JudgeWaitLine as I}from"../lib/judge-wait.js";import{ai4ioaiPromptLabel as j,handleAi4ioaiMessage as E,startAi4ioaiChat as L}from"./ai4ioai.js";import{existsSync as M,mkdirSync as N,readdirSync as q,readFileSync as O,renameSync as W,statSync as R,writeFileSync as D}from"node:fs";import{emptyDynamics as U,foldEditSession as Y,isEmpty as B,noteRun as z}from"../lib/arena-edit-dynamics.js";import{dirname as F,join as G}from"node:path";import{fileURLToPath as H}from"node:url";import{loadCurriculumById as Z,validateEAToken as K,syncProgress as J,fetchServerProgress as Q,syncCardFeedback as X,fetchCardFaqs as V}from"../lib/learn-curricula.js";import{hometaskDetailLines as ee,hometaskLines as oe,isTaskCommand as te}from"../lib/learn-hometask.js";import{detectCaps as ne}from"../lib/render-card.js";import{parseReplyCommand as re,renderReplyLines as se,replyPushLine as le}from"../lib/learn-replies.js";import{ensureFullTable as ae,lookupPydoc as ie,lookupRanked as ce,refetchTableOnMiss as de,nearKeys as ge,renderIndex as ue,renderPydoc as he,renderSyntax as pe,tableSize as ye}from"../lib/py-syntax.js";import{normalizeTokenBody as me}from"../lib/token-format.js";import{fetchMyScores as fe,recallCoach as $e,setNickname as be,streamLearnTutor as we,submitPqs as ke,viewPqsTop as ve,viewHonors as _e}from"../lib/learn-ai.js";import{contestReset as Ce,contestStart as Ae,contestSubmit as xe,linkByIndex as Te,linkSuggest as Se,linkToken as Pe,fetchGate as Ie,timeLeft as je,arenaSlotAtPos as Ee,posForArenaSlot as Le}from"../lib/learn-contest.js";import{WARMUP as Me,WARMUP_ID as Ne,WARMUP_N as qe,WARMUP_TESTS as Oe,gradeWarmup as We,warmupEnabled as Re}from"../lib/warmup.js";import{PY_MAX_CODE_BYTES as De,PY_MAX_FILES as Ue,PY_TEMPLATE_EN as Ye,PY_SPOOL_BATCH as Be,PY_TEMPLATE_ZH as ze,listScratchFiles as Fe,localTimeNote as Ge,nextScratchN as He,readPyScratchSpool as Ze,scratchCodeSha as Ke,scratchDir as Je,scratchFilePath as Qe,scratchTitleOf as Xe,shrinkPyScratchSpool as Ve,spoolPyScratchEvent as eo,startRunTimer as oo,syncPyScratch as to}from"../lib/py-scratch.js";import{SH_TIMEOUT_MS as no,ensureLabDir as ro,interactiveHint as so,labCardDir as lo,labRoot as ao,resolveCd as io,runShell as co,shortCwd as go,tildePath as uo}from"../lib/sh-lab.js";import{verdictLine as ho}from"../lib/verdict.js";import{printNoPython312 as po,probePython as yo}from"../lib/python-setup.js";function mo(){const e=yo();return e.ok&&e.cmd?{cmd:e.cmd}:null}const fo=()=>mo()?.cmd??null;import{homedir as $o}from"node:os";import{getConfig as bo,saveConfig as wo}from"../lib/config.js";import{runType as ko}from"./type.js";import{isNativeWindows as vo,isWindowsBuildInWslShell as _o,whichBinary as Co}from"../lib/platform.js";import{loadLearnState as Ao,saveLearnState as xo,newLearnState as To,stateFromServerEvents as So,activateSession as Po,updateStreak as Io,markCardComplete as jo,recordMCQ as Eo,recordCheck as Lo,markPracticalComplete as Mo,addAchievement as No}from"../lib/learn-state.js";import{renderWelcome as qo,renderKnowledgeCard as Oo,renderMCQCard as Wo,renderMCQFeedback as Ro,renderPracticalCard as Do,renderPracticalSuccess as Uo,renderSimDemoCard as Yo,renderMilestone as Bo,renderArenaTaskCard as zo,renderArenaIntro as Fo,renderComingSoonCard as Go,renderStatus as Ho,renderPhaseComplete as Zo,renderCurriculumComplete as Ko,setLearnAiEnabled as Jo,setLearnFaqs as Qo,setLearnFooterProfile as Xo,setLearnShellLane as Vo,setLearnHometask as et,setLearnPracticeChips as ot,setLearnPracticeCount as tt,setLearnHonorRanks as nt,setLearnPqsViewCards as rt,setLearnReplies as st,setLearnWidth as lt,resolveLearnWidth as at,learnWidthCap as it,learnW as ct,renderHonorWall as dt,wrapMixed as gt}from"../lib/learn-render.js";import{printError as ut}from"../lib/ui.js";const ht=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","widest"],["wide max","widest"]]);function pt(e,o){e.forEach((t,n)=>{const r=n===e.length-1;0===n?console.log(chalk.bold.cyan(` ${t}`)):/^[─-]+$/.test(t.trim())&&t.trim().length>3?console.log(chalk.gray(` ${t}`)):r?console.log((o?chalk.bold.green:chalk.yellow)(` ${t}`)):console.log(chalk.white(` ${t}`))}),console.log()}export function registerLearnCommand(yo){yo.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async yo=>{yo?.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(),yo="LEARNDEMO01");let yt=yo.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(yt)){const{runSprint:e}=await import("./sprint.js");return void await e()}let mt=null;const ft=/^[A-Z0-9]+DEMO01$/i.test(yt),$t=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(yt);let bt=!1,wt=!1,kt=[],vt=null,_t=-1,Ct=Promise.resolve([]);if(ft)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Ct=V(yt),mt=await Z(yt,yt,!0);else if($t){console.log(),console.log(chalk.gray(" Validating token..."));let e=await K(yt);if(!e.ok){const o=me(yt);if(o!==yt){const t=await K(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${yt} → ${o}`)),e=t,yt=o)}}if(!e.ok)return ut(`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 🐼"):"")),bt=!0===e.aiEnabled,wt=!0===e.gated,kt=e.replies??[],vt=e.hometask??null,Ct=V(yt),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),mt=await Z(e.curriculumId||"LEARNDEMO01",yt,!0),!mt)return ut(`Could not open a learn curriculum for token '${yt}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${yt}`)+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 ${yt}`)+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(!mt){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(ut(`Could not reach the learn server to open ${yt}.`),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 ${yt}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(ut(`Unknown learn token: ${yt}`),console.log(),console.log(chalk.gray(" A learn token is ")+chalk.bold.yellow("2 letters + 8 characters")+chalk.gray(", issued by your team leader.")),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 At=Ao(),xt=!1;try{if(At&&At.token===yt)Io(At);else{const e=Po(yt);if(e)At=e,At.totalCards=mt.totalCards,Io(At);else{const e=await Q(yt),o=e?So(yt,mt.id,mt.totalCards,e):null;o?(At=o,console.log(chalk.green(" ↩ ")+chalk.white((bo().language||"en").toLowerCase().startsWith("zh")?`已从服务器取回你的进度:${o.cardsCompleted.length} 张卡已完成,从第 ${o.currentCard} 张继续`:`Restored your progress from the server: ${o.cardsCompleted.length} cards done, resuming at card ${o.currentCard}`)),console.log()):(At=To(yt,mt.id,mt.totalCards),xt=!0)}}xo(At),qo(mt,At,xt),function(e){if(!e)return;const o=(bo().language||"en").toLowerCase().startsWith("zh"),t="T0"===ne().tier;pt(oe(e,o,ct(),t),!!e.completedAt)}(vt)}catch{return ut("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 ${yt}`)+chalk.gray(".")),void console.log()}const Tt=x(),St=null!==Tt,Pt=St?Tt.listeners("line").slice():[];St&&Tt.removeAllListeners("line");const It=St?Tt:o({input:process.stdin,output:process.stdout,terminal:!0}),jt=St?It.prompt:null;St&&(It.prompt=e.prototype.prompt);const Et=()=>{St&&jt&&(It.prompt=jt)};let Lt=null,Mt=!1,Nt=!1,qt=null,Ot=!1;const Wt=()=>{It.setPrompt(cn?chalk.bold.green(`icoa ${j()}> `):en?chalk.bold.magenta(Kr()):Vt?chalk.bold.magenta("icoa py> "):Xt?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Jt?"icoa learn ai> ":"icoa learn> ")),It.prompt(),Lt?.onPromptIdle()};let Rt=null,Dt=null,Ut=null,Yt=null,Bt=[],zt=!1,Ft=null;const Gt=/^(quit|exit|q|back|b|menu|home|contest(\s+(\d+|reset))?)$/i;let Ht=null,Zt=!1;const Kt=()=>{Ft&&clearTimeout(Ft),Ft=null,Bt=[],zt=!1,Yt=null,Ht=null};let Jt=!1,Qt=!1,Xt=!1,Vt=!1,en=!1,on=null,tn="card",nn=null,rn=null,sn=!1,ln=0,an=!1,cn=!1;const dn=new Map,gn=()=>{let e=dn.get(At.currentCard);return e||(e=[],dn.set(At.currentCard,e)),e};let un=!1;const hn=new Set;let pn=!1,yn=0;const mn=()=>(bo().language||"en").toLowerCase().startsWith("zh");Jo(bt),lt(at(bo())),rt(hn);const fn=new Map;nt(fn),st(kt),et(vt);const $n="fill"===mt.practiceMode,bn=Boolean(mt.shellLane);Vo(bn),Xo("minimal"===mt.footerProfile?"minimal":"full"),ot(e=>{const o=Tn(e),t=o?mr(o):null;if(!t)return null;const n=Dn.get(ur+e);return t.map((e,o)=>`[${o+1}]${n?.has(yr(e.py_id))||n?.has(e.py_id)?"✅":"⬜"}`).join(" ")});const wn=e=>{const o=Tn(e),t=o?mr(o):null;if(!t)return null;const n=Dn.get(ur+e);return{solved:t.filter(e=>n?.has(yr(e.py_id))||n?.has(e.py_id)).length,total:t.length}};tt(wn);const kn=await Ct;Qo(kn);const vn=[];let _n=null;const Cn=new Promise(e=>{_n=e}),An=()=>{const e=_n;_n=null,e?.()},xn="1"===process.env.ICOA_LEARN_EMBEDDED,Tn=e=>mt.cards.find(o=>o.number===e);Lt=c();const Sn={isZh:mn,canInterrupt:()=>!(Ot||Qt||Jt||Xt||Vt||cn||null!==nn||null!==Yt||null!==rn),lineEmpty:()=>!It.line,clearLine:()=>{try{process.stdout.write("\r")}catch{}},prompt:Wt,currentCard:()=>At.currentCard};p(()=>{const e=[],o=Lt?.footerLine();o&&e.push(o);const t=In();return null!==t&&t>0&&t<=2&&e.push(mn()?`🎁 还差 ${t} 项 · credits 看路线`:`🎁 ${t} to go · credits shows the road`),e.length?e.join("\n "):null});const Pn=async(e,o)=>{const t=mn();if(ft)return void console.log(chalk.gray(t?"故事属于正式 learn token。":" Stories belong to full learn tokens."));const n=await y(yt,o?null===e?"credits":"story":"auto");if("ok"!==n.kind){if(!o)return;return void console.log(chalk.yellow(t?" 连不上 learn 服务器 — 故事的数据住在服务端,联网后再敲 story。":" Cannot reach the learn server — your story lives there; type story again online."))}const r=n.profile;if("list"===e){console.log();for(const e of v(r,t))console.log(e);return void console.log()}let s=null===e?r.tokens.find(e=>e.curriculum_id===mt.id):void 0;if(null!==e){const o=Number(e);s=Number.isInteger(o)&&o>=1&&o<=r.tokens.length?r.tokens[o-1]:r.tokens.find(o=>o.curriculum_id.toLowerCase()===e||o.curriculum_id.toLowerCase().startsWith(e))}if(!s){console.log(),console.log(chalk.yellow(t?` 没有「${e}」这门课的故事。`:` No story for "${e}".`));for(const e of v(r,t))console.log(e);return void console.log()}if(!o&&!s.credits?.completed){const e=s.credits,o=[];e&&e.checks_total>0&&o.push(t?`自测 ${e.checks_answered}/${e.checks_total}`:`checks ${e.checks_answered}/${e.checks_total}`),s.practice.total>0&&o.push(t?`练习 ${s.practice.ac}/${s.practice.total} AC`:`practice ${s.practice.ac}/${s.practice.total} AC`),s.contests.total>0&&o.push(t?`检查点 ${s.contests.passed}/${s.contests.total} 过线`:`checkpoints ${s.contests.passed}/${s.contests.total} passed`),console.log(chalk.bold.white(t?" 🏁 离谢幕还差:":" 🏁 To the credits: ")+chalk.gray(o.join(" · ")));for(const e of w(mt,At,En,t))console.log(e);return console.log(chalk.gray(t?" 三项全满,谢幕自动上演 · contest 看未过的场次 · story 看这门课的故事":" all three full → the credits roll · contest lists what is left · story for this course so far")),void console.log()}const l=$(s,r,s.curriculum_id===mt.id?mt.name:s.curriculum_id,s.curriculum_id===mt.id?{longestStreak:At.longestStreak,bookmarks:At.bookmarks?.length??0}:{},t,ct(),"T0"===ne().tier);console.log(),console.log(chalk.gray(t?" (回车跳到结尾)":" (Enter skips to the end)")),Mt=!0,Nt=!1;try{await k(l,()=>Nt)}finally{Mt=!1}if(s.curriculum_id===mt.id&&!s.credits?.completed){for(const e of w(mt,At,En,t))console.log(e);console.log()}s.credits?.completed&&!s.credits.credits_rolled_at&&m(s.token,s.curriculum_id),console.log(chalk.gray(t?" ↩ 回车继续 · story 选另一门 · me 看档案":" ↩ Enter to continue · story to pick another · me for your profile")),console.log()},In=()=>{if(!At||At.creditsShownAt||ft||!En)return null;const e=b(mt,At,En);return e.complete?0:Math.max(0,e.checks[1]-e.checks[0])+Math.max(0,e.practice[1]-e.practice[0])+Math.max(0,e.contests[1]-e.contests[0])},jn=async(e=!1)=>{if(!At||At.creditsShownAt||ft)return;const o=b(mt,At,En);if(!o.complete){const t=Math.max(0,o.checks[1]-o.checks[0])+Math.max(0,o.practice[1]-o.practice[0])+Math.max(0,o.contests[1]-o.contests[0]);if(En&&t>0&&t<=2&&(e||At.creditsTeasedLeft!==t)){At.creditsTeasedLeft=t,xo(At);const e=mn(),n=[];o.checks[1]>o.checks[0]&&n.push(e?o.checks[1]-o.checks[0]+" 个自测":`${o.checks[1]-o.checks[0]} check${o.checks[1]-o.checks[0]===1?"":"s"}`),o.practice[1]>o.practice[0]&&n.push(e?o.practice[1]-o.practice[0]+" 道练习":`${o.practice[1]-o.practice[0]} practice problem${o.practice[1]-o.practice[0]===1?"":"s"}`),o.contests[1]>o.contests[0]&&n.push(e?o.contests[1]-o.contests[0]+" 场检查点":`${o.contests[1]-o.contests[0]} checkpoint${o.contests[1]-o.contests[0]===1?"":"s"}`),console.log(),console.log(chalk.yellow(" 🎁 ")+chalk.bold.white(e?`还差 ${t} 项`:`${t} to go`)+chalk.gray(e?` — ${n.join("、")}。全部完成,会有一点小东西。`:` — ${n.join(" and ")}. Finish them all and something happens.`));for(const o of w(mt,At,En,e))console.log(o);console.log()}return}At.creditsShownAt=(new Date).toISOString(),xo(At),await Pn(null,!1),Wt()};let En=null,Ln=null;const Mn=new Map,Nn=new Map;let qn=null;const On=(e,o)=>qn?.[`${mt.id}:${e}:${o}`]??null;P("contest-cells.json").then(e=>{qn=e?.map??null;for(const[e,o]of Object.entries(qn??{}))e.startsWith(`${mt.id}:`)&&P(o)});const Wn=(e,o,t)=>{const n=On(e,o);if(!n)return null;const r=G(t,"explore.ipynb");if(!M(r)){const e=G(S(),n);if(!M(e))return null;try{D(r,O(e))}catch{return null}}return r},Rn=!yt.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(yt),Dn=new Map,Un=new Map,Yn=new Set,Bn=async()=>{if(!Rn)return;const e=await Ie(yt);if(e.ok&&e.data){En=e.data;for(const o of e.data.practice??[]){let e=Dn.get(o.slot);e||(e=new Set,Dn.set(o.slot,e));for(const t of o.solved)e.add(t)}jn()}},zn=e=>{const o=mt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Fn=e=>{if(!wt||!En)return null;const o=zn(e);if(o<=En.unlocked_through_phase)return null;const t=En.phases.find(e=>e.phase===En.unlocked_through_phase),n=[chalk.yellow(mn()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${En.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${En.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(mn()?` ⚔ 练习赛 ${En.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${En.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(mn()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}if(t?.checks?.enabled&&!t.checks.passed){const e=t.checks.missing??[],o=e.slice(0,8).join(mn()?"、":", "),r=e.length>8?mn()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:mn()?" 张":"";n.push(chalk.gray(mn()?` ✓ 逐卡自测: ${t.checks.good}/${t.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${t.checks.good}/${t.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return t?.research&&!t.research.passed&&n.push(chalk.gray(mn()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},Gn=async e=>wt?null===Fn(e)?null:(await Bn(),Fn(e)):null;Rn&&await Bn();const Hn=async e=>{const o=mt.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=mt.modules.find(e=>e.number===o.number+1);let n;if(bt){const e=await fe({token:yt,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}Rn&&await Bn();const r=En?.phases.find(e=>e.phase===o.number);return Zo(mt,At,o,t,n,r),!0},Zn=()=>{pn=!0,console.log(chalk.gray(mn()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Kn=()=>{rn=null;const e=Tn(At.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(Lt?.noteCardShown(e.number,At.cardsCompleted.includes(e.number)),e.type){case"knowledge":{const o=$n&&Boolean(At.checkResults?.[String(e.number)])&&e.check?{...e,check:void 0}:e;Oo(o,mt),o.check?(Ut=e.number,yn=Date.now()):(jo(At,e.number),xo(At));break}case"mcq":Wo(e,mt),Rt=e.number;break;case"practical":Do(e,mt),Dt=e.number;break;case"sim_demo":Yo(e,mt),jo(At,e.number),xo(At);break;case"milestone":Bo(e,mt),No(At,e.badge),jo(At,e.number),xo(At);break;case"arena_task":zo(e,mt),jo(At,e.number),xo(At);break;case"coming_soon":Go(e,mt),jo(At,e.number),xo(At)}Jn(e.number),$r(e)},Jn=e=>{if(!Rn||!En)return;const o=mt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1,n=Ee(t);if(0===n)return;const r=En.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n),l=()=>{At.arenaIntroShownAt||(Fo(),At.arenaIntroShownAt=(new Date).toISOString(),xo(At))};if(!s){const e=o.cardRange;if(e[1]-e[0]+1>12)return;l();const t="═".repeat(ct()),r=chalk.bold.yellow(" ║ ");return console.log(chalk.bold.yellow(` ╔${t}`)),console.log(r+chalk.bold.white("⚔ "+(mn()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(mn()?" 制作中":" in production")),console.log(r+chalk.white(mn()?"这里以后有一场判分赛 — 很快更新。":"A judged arena lands here — coming soon.")),console.log(r+chalk.gray(mn()?"每 4 张卡一场:卡 4 / 8 / 12,本阶段共 3 场,全过解锁下一阶段。"+($n?"(本轨无 research)":""):"One every 4 cards — 4 / 8 / 12, three this phase; all three unlock the next."+($n?" (no research on this track)":""))),console.log(r+chalk.gray(mn()?"▸ 现在什么都不用做 — 敲 ":"▸ Nothing to do yet — type ")+chalk.bold.green("next")+chalk.gray(mn()?" 继续读卡。":" and keep reading.")),console.log(chalk.bold.yellow(` ╚${t}`)),void console.log()}l();const a=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),l=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const t=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${t(o.getMonth()+1)}-${t(o.getDate())} ${t(o.getHours())}:${t(o.getMinutes())}`})(n);return`🏆 ${e} ${o}/${s.n}`+(r?mn()?` · 用时 ${r}`:` · in ${r}`:"")+(l?` · ${l}`:"")},i=s.perfect_runs??[],c=!!s.best&&(s.best.ac??0)>0,d=chalk.bold.yellow(" ║ "),g="═".repeat(ct());if(console.log(chalk.bold.yellow(` ╔${g}`)),console.log(d+chalk.bold.white(`⚔ ${mn()?`练习赛 ${o.number}-${n}`:s.title||`PY Arena ${o.number}-${n}`}`)+(s.passed?chalk.bold.green(mn()?" ✅ 已通过":" ✅ passed"):"")),!s.passed){if(mn()?console.log(d+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(d+chalk.white("You learned the cards — now prove it.")),console.log(d+chalk.white("The clock starts the moment you type the command."))),console.log(d+chalk.gray(mn()?`${s.n} 题 · AC ${s.need} 过关 · 限时 ${s.duration_minutes} 分钟 · 无限重开`:`${s.n} problems · AC ${s.need} to pass · ${s.duration_minutes} min · unlimited retries`)),(s.carryable_ac??0)>0){const e=(s.carry_from??[]).join(", "),o=e?mn()?`(${e})`:` (${e})`:"";console.log(d+chalk.cyan(mn()?`🔗 你另一个 token${o}已做过这组的 ${s.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens${o} solved ${s.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(mn()?" 带过来(现在不做也行)":" to carry them over (or skip)"))}1!==o.number||$n||console.log(d+chalk.gray(mn()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))}if(i.length>0)for(const e of i)console.log(d+chalk.bold.yellow(a(mn()?"满分":"Perfect",s.n,e.ms,e.ts)));else c&&console.log(d+chalk.yellow(a(mn()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));3===n&&r?.leader&&console.log(d+chalk.white(mn()?`🏅 本 phase 研究总分榜首 ${r.leader.name||"Rank 1"} ${r.leader.total}/${r.leader.max_total}`:`🏅 Phase research leader: ${r.leader.name||"Rank 1"} at ${r.leader.total}/${r.leader.max_total}`)+chalk.gray((mn()," — "))+chalk.bold.green("/honors")+chalk.gray(mn()?" 看你的位置":" shows where you stand")),console.log(d+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(s.passed?chalk.gray(mn()?" 再战刷成绩 · ":" race it again · "):chalk.gray(mn()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(mn()?" 继续学习":" keep going"):chalk.gray(mn()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(i.length>0||c)&&console.log(d+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(mn()?" 日后回来整阶段重做 · 全新计时+模板(旧文件自动归档)":" come back later and redo the whole phase · fresh clock + templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${g}`)),console.log()},Qn=()=>{yt.endsWith("DEMO01")?console.log(chalk.yellow(mn()?" 🐼 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(mn()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(mn()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Xn=async(e,o)=>{if(bt){Lt?.noteAi("deep"===o),Qt=!0;try{console.log(),console.log(chalk.gray("deep"===o?mn()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":mn()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await we({token:yt,cardNumber:At.currentCard,question:e,mode:o,history:gn().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(mn()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(gn().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(` (${mn()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(mn()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Ut&&console.log(chalk.gray(mn()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Qt=!1}}else Qn()},Vn=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],er=async()=>{Xt&&Ln?Sr?Ir(Sr):Ar():rn?await or():Kn()},or=async()=>{Qt=!0;try{console.log();const e=await _e({token:yt,curriculumId:mt.id,cardNumber:At.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(mn()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(Rn&&(await Bn(),(e=>{const o=mt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const[t,n]=o.cardRange,r=At.checkResults||{};let s=0,l=0,a=0;for(let e=t;e<=n;e++){const o=Tn(e);null!=o?.check&&a++;const t=r[String(e)];t&&(s++,t.correct&&l++)}console.log(chalk.bold.white(mn()?` 🧭 Phase ${o.number} 进度 — ${o.name}(卡 ${t}-${n})`:` 🧭 Phase ${o.number} progress — ${o.name} (cards ${t}-${n})`)),console.log(chalk.gray(mn()?" 理解检查: ":" comprehension: ")+chalk.white(`${l}/${s}`)+chalk.gray(mn()?` 答对 · ${a-s} 张未作答`:` correct · ${a-s} unanswered`));const i=En?.phases.find(e=>e.phase===o.number);if(i?.configured&&i.contest?.slots?.length)for(const e of i.contest.slots){const t=e.passed?chalk.bold.green(`${e.best_ac}/${e.n} AC ✅`):0===e.attempts?chalk.gray(mn()?`未开始 · ${e.n} 题 · 过 ${e.need} 题`:`not started · ${e.n} problems · AC ${e.need}`):chalk.yellow(mn()?`最好 ${e.best_ac}/${e.n}(需 ${e.need})· 已试 ${e.attempts} 次`:`best ${e.best_ac}/${e.n} (need ${e.need}) · ${e.attempts} attempt(s)`);console.log(chalk.gray(` ⚔ ${mn()?"练习赛":"arena"} ${o.number}-${e.slot}: `)+t)}const c=[];let d=0,g=0,u=0,h=0;for(let e=t;e<=n;e++){const o=wn(e);o&&(g++,u+=o.solved,h+=o.total,o.solved>=o.total&&d++,c.push((o.solved>=o.total?chalk.green:o.solved>0?chalk.yellow:chalk.gray)(`${e}:${o.solved}/${o.total}`)))}if(g>0){console.log(chalk.gray(mn()?" 卡片练习: ":" practice: ")+chalk.white(`${d}/${g}`)+chalk.gray(mn()?` 卡全完成 · ${u}/${h} 题 AC`:` cards complete · ${u}/${h} problems AC`));const e=Math.max(40,(process.stdout.columns||80)-8);let o="",t=0;for(const n of c){const r=n.replace(/\x1b\[[0-9;]*m/g,"");t+r.length+2>e&&o&&(console.log(" "+o),o="",t=0),o+=(o?chalk.gray(" · "):"")+n,t+=r.length+3}o&&console.log(" "+o),console.log(chalk.gray(mn()?" 卡号:已过/共 — 绿 全完成 · 黄 做了一部分 · 灰 未碰":" card:solved/total — green done · yellow partial · gray untouched"))}console.log()})(At.currentCard)),console.log(chalk.bold.white(mn()?` 🏆 本卡实时 Top-3 — 第 ${At.currentCard} 张`:` 🏆 Live top-3 — card ${At.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(mn()?" (你)":" (you)"):""))}else console.log(chalk.gray(mn()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));if(e.mine?(fn.set(At.currentCard,e.mine.rank),console.log(chalk.white(mn()?" 你: ":" You: ")+chalk.bold.yellow(mn()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(mn()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):bt&&console.log(chalk.gray(mn()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),dt({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),e.phaseBoard){const o=e.phaseBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(mn()?` 🏅 Phase ${o.phase} 研究总分 — ${o.cards_in_phase} 卡 · 满分 ${o.max_total}`:` 🏅 Phase ${o.phase} research total — ${o.cards_in_phase} cards · max ${o.max_total}`)),0===o.top.length&&console.log(chalk.gray(mn()?" (还没有人有研究总分 — 第一个 /ai 研究 + /submit 的人直接登顶)":" (no research totals yet — the first to research with /ai + /submit takes #1)"));for(const e of o.top)console.log(chalk.white(` ${t[e.rank-1]??" "} `)+chalk.bold.cyan(e.name||`Rank ${e.rank}`)+chalk.white(` · ${e.total}`)+chalk.gray(mn()?`(${e.cards}/${o.cards_in_phase} 卡)`:` (${e.cards}/${o.cards_in_phase} cards)`)+(e.me?chalk.bold.magenta(mn()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(mn()?` 总分 ${o.gate_total}+(${o.cards_in_phase} 卡全部 60 分以上)揭榜 top-3 — 目前虚位以待`:` Top-3 unveils at ${o.gate_total}+ (all ${o.cards_in_phase} cards at 60+) — seats open`)),o.mine&&!o.top.some(e=>e.me)?console.log(chalk.white(mn()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.total}`)+chalk.gray(mn()?`(${o.mine.cards}/${o.cards_in_phase} 卡)· 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` (${o.mine.cards}/${o.cards_in_phase} cards) · rank ${o.mine.rank} of ${o.mine.entrants}`)):!o.mine&&bt&&console.log(chalk.gray(mn()?" 你: 还未计入 — /ai 研究任意卡并 /submit 评分,每卡最高分计入总分":" You: not counted yet — research any card with /ai, then /submit; each card’s best score counts")),console.log()}if(e.practiceBoard){const o=e.practiceBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(mn()?` ⚔ Phase ${o.phase} Practice AC — 已投放 ${o.problems_total} 题`:` ⚔ Phase ${o.phase} practice AC — ${o.problems_total} problems live`)),0===o.top.length&&console.log(chalk.gray(mn()?" (还没有人 AC — 第一个做出 practice 题的人直接登顶)":" (no ACs yet — the first solved practice problem takes #1)"));for(const e of o.top)console.log(chalk.white(` ${t[e.rank-1]??" "} `)+chalk.bold.cyan(e.name||`Rank ${e.rank}`)+chalk.white(` · ${e.ac} AC`)+chalk.gray(`/${o.problems_total}`)+(e.me?chalk.bold.magenta(mn()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(mn()?` AC 满 ${o.gate_ac} 题(已投放的 60%)揭榜 top-3 — 目前虚位以待`:` Top-3 unveils at ${o.gate_ac} ACs (60% of the pool) — seats open`)),o.mine&&!o.top.some(e=>e.me)?console.log(chalk.white(mn()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.ac} AC`)+chalk.gray(mn()?` · 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` · rank ${o.mine.rank} of ${o.mine.entrants}`)):o.mine||console.log(chalk.gray(mn()?" 你: 还未计入 — 在有 practice 的卡上输 practice 1 做题,AC 即计入":" You: not counted yet — type practice 1 on a card that has problems; each AC counts")),console.log()}!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(mn()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(mn()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(mn()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),rn="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(mn()?" 返回卡片":" returns to the card")),console.log()}finally{Qt=!1}},tr=e=>mn()&&e.title_zh||e.title,nr=Re(mt.id);let rr=!1;const sr=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of gt(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},lr={cpp:"cpp",java:"java",go:"go"},ar=e=>e?.lang&&lr[e.lang]?e.lang:"python",ir=(e,o)=>{const t=ar(o);return`sol-${e}.${"python"===t?"py":lr[t]}`},cr=(e,o)=>{const t=[...nr?[{p:Me,n:qe}]:[],...e.problems.map((e,o)=>({p:e,n:o+1}))],n=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);let r=0;t.forEach(({p:t,n:s})=>{const l=nr&&s===qe,a=l?`══ ${t.title} ══`:`══ ${e.title||"PY Arena"} · ${t.title} ══`;for(const e of["py",...Object.values(lr)]){const l=G(o,`sol-${s}.${e}`);if(!M(l))continue;const i=O(l,"utf-8").split("\n",1)[0]??"",c=/^(?:#|\/\/) (══ .+ ══)\s*$/.exec(i);if(c&&c[1]!==a)try{W(l,`${l}.archived-${n}`),r++;const e=G(o,`sample-${s}.txt`);M(e)&&!(t.samples??[])[0]&&W(e,`${e}.archived-${n}`)}catch{}}const i=(t.samples??[])[0];i&&D(G(o,`sample-${s}.txt`),i.in.endsWith("\n")?i.in:`${i.in}\n`);const c=G(o,ir(s,t));if(M(c))return;const d=[l?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...sr(t.statement,72)];if(t.statement_zh&&d.push("#",`# Other language: type "lang zh" in icoa, then /read ${s} for the Chinese statement.`),i){d.push("#",`# Sample input (also in sample-${s}.txt):`);for(const e of i.in.split("\n"))d.push(`# ${e}`);d.push("# Expected output:");for(const e of i.out.split("\n"))d.push(`# ${e}`)}if(d.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","#"),l||d.push("# ── toolkit ──",...e.toolkit_available?.length?[`# Available on the judge: ${e.toolkit_available.join(", ")}`]:["# The judge runs the Python standard library only."],...e.toolkit_available?.includes("chepy")?["# from chepy import Chepy — chain ops on the DATA block;","# /syntax chepy = op index · plain stdlib always works too."]:["# 'array', 'bisect', 'heapq' and sys.stdin.buffer.read() are the","# standard speed-ups; none is ever required to solve a problem."]),t.toolkit?.length&&(d.push(`# Recommended for THIS problem: ${t.toolkit.join(", ")}`),t.toolkit_note))for(const e of t.toolkit_note.split("\n"))for(const o of gt(e,68))d.push(`# ${o}`);const g=/\nDATA\n----\n([\s\S]+)$/.exec(t.statement??"");g?d.push("#","# No input() on this one — the DATA block is already assigned below.","# Compute, then print() ONLY the flag{...} token — nothing around it.",`# In icoa: /debug ${s} = free run · /submit ${s} = judge`,"",'data = """',...g[1].trim().split("\n"),'""".strip()',"",""):l?d.push("# Your first program. Line 1 is written for you: it reads the number.","# Replace the ??? on line 2 with the arithmetic, then :wq and /run 0.","","n = int(input())","print(???)",""):t.starter?d.push("#",`# In icoa: /run ${s} = run it (shows your ms) · /submit ${s} = judge`,""):d.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${s} = sample self-check · /debug ${s} = free-input run · /submit ${s} = judge`,"","");const u="python"===ar(t)?d:d.map(e=>e.startsWith("#")?`//${e.slice(1)}`:e);t.starter&&!l&&u.push(...t.starter.replace(/\s+$/,"").split("\n"),""),D(c,u.join("\n"))}),r>0&&console.log(chalk.gray(mn()?` 📦 本组题目已更换 — ${r} 个旧题答题文件已归档为 *.archived-${n},新题文件已就位`:` 📦 This group's problems changed — ${r} old solution file(s) archived as *.archived-${n}, fresh files written`))},dr=e=>{console.log(),console.log(chalk.bold.green(mn()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(mn()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},gr=e=>e.id===Ne?rr?"✅":"⬜":Ln.data.solved.includes(e.id)?"✅":Ln.data.carried?.includes(e.id)?"✅↗":Ln.tried.has(e.id)?"❌":"⬜",ur=100,hr=()=>!!Ln&&Ln.data.slot>=ur,pr=(e,o)=>{const t=G(process.cwd(),"icoa-contest",`${mt.id}-phase${e}-g${o}`);if(!M(t))return;const n=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{W(t,`${t}-archived-${n}`),console.log(chalk.gray(mn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${n}`))}catch{console.log(chalk.yellow(mn()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (restart still fine): ${t}`))}},yr=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,mr=e=>{const o=e?.practice;return o&&Array.isArray(o.problems)&&0!==o.problems.length?[...o.problems.filter(e=>e.is_signature),...o.problems.filter(e=>!e.is_signature).sort((e,o)=>(e.difficulty??0)-(o.difficulty??0)||(e.order??0)-(o.order??0))]:null},fr=()=>{if(!$n)return!1;const e=Tn(At.currentCard),o=e?mr(e):null;if(!e||!o||Yn.has(e.number))return!1;const t=ur+e.number,n=Dn.get(t),r=Un.get(t),s=o.map((e,o)=>{return t=e.py_id,Boolean(n?.has(yr(t))||n?.has(t)||r?.has(yr(t))||r?.has(t))?0:o+1;var t}).filter(e=>e>0);return 0!==s.length&&(console.log(chalk.yellow(mn()?` ⚔ 这张卡还有 ${s.length} 道练习没做 —— 敲 `:` ⚔ ${s.length} practice problem${s.length>1?"s":""} on this card not tried yet — type `)+chalk.bold.green(`practice ${s[0]}`)+chalk.yellow(mn()?" 开始,或 ":" to start, or ")+chalk.bold.yellow("skip")+chalk.yellow(mn()?" 跳过本卡练习。":" to skip this card's practice.")),!0)},$r=e=>{const o=mr(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=Dn.get(ur+e.number);console.log(chalk.bold.yellow(mn()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(mn()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(yr(e.py_id))||n?.has(e.py_id)?"✅":"⬜",r=e.is_signature?"🎯":e.is_hardest?"🔥":" ",s="·".repeat(Math.min(5,Math.max(1,Math.round(e.difficulty??1))));console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ${r} ${chalk.white(s.padEnd(5))}`)}),console.log(chalk.gray(" ▸ ")+chalk.bold.green("practice 1")+chalk.gray(mn()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},br=e=>e.split("\n").filter(e=>!e.trim().startsWith("#")).join("\n").split("____").length-1,wr=e=>{console.log(chalk.yellow(mn()?` ⏱ 每次练习 ${e} 分钟,这次的时间到了。`:` ⏱ Each practice window is ${e} minutes — this one has run out.`)),console.log(chalk.gray(mn()?" 敲 ":" Type ")+chalk.bold.green("back")+chalk.gray(mn()?" 回卡片,再敲 ":" for the card, then ")+chalk.bold.green("practice 1")+chalk.gray(mn()?" 重新开始(重新计时)。":" to restart with a fresh clock."))},kr=()=>nn?nn.data.problems[nn.idx]??null:null,vr=()=>{const e=kr();if(!nn||!e)return;const o=br(e.starter??""),t=nn.answers.length+1,n=(e=>{const o=[];for(const t of e.split("\n"))if(!t.trim().startsWith("#"))for(let e=t.split("____").length-1;e>0;e--)o.push(t.trim());return o})(e.starter??"")[t-1]??"";console.log(chalk.bold.yellow(mn()?` 空${t}/${o}`:` blank ${t}/${o}`)+chalk.gray(" · ")+chalk.white(n)),console.log(chalk.gray(mn()?" ▸ 敲答案后回车(back 回卡片)":" ▸ type the answer, press Enter (back = card)"))},_r=()=>{const e=kr();if(!nn||!e)return;const o=mn()&&e.title_zh?e.title_zh:e.title;console.log(),console.log(chalk.bold.yellow(` ⚡ ${mn()?"练习":"Practice"} ${nn.idx+1}/${nn.data.problems.length} · ${o}`));const t=((mn()&&e.statement_zh?e.statement_zh:e.statement)??"").split(/\n(?:Rules|规则)\n/)[0].trimEnd();for(const e of t.split("\n"))console.log(chalk.white(" "+e));console.log();let n=0;(e.starter??"").split("\n").forEach((e,o)=>{let t;if(e.trim().startsWith("#"))t=e;else{const o=e.split("____");t=o.map((e,t)=>t<o.length-1?e+chalk.bold.yellow("____"+ ++n):e).join("")}console.log(chalk.gray(` ${String(o+1).padStart(2)} │ `)+chalk.white(t))}),console.log(),vr()},Cr=()=>{if(nn){if(nn.idx+1<nn.data.problems.length)return nn.idx+=1,nn.answers=[],nn.tries=0,void _r();console.log(chalk.bold.green(mn()?" 🎉 本卡练习全部完成!":" 🎉 Card practice complete!")+chalk.gray(mn()?" ok 进下一张卡。":" ok moves on to the next card.")),nn=null,Kn()}},Ar=()=>{const e=Ln.data,o=je(e.deadline),t=(e.carried??[]).filter(o=>!e.solved.includes(o)),n=e.solved.length+t.length,r=Math.min(20,Math.round(n/Math.max(1,e.need)*20));console.log();const s=e.slot>=ur?e.slot-ur:null;if(console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(null!=s?mn()?` · 第 ${s} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${s} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:mn()?` · 第 ${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(mn()?" ⏱ 已超时 — contest restart 重开本组":" ⏱ time up — contest restart to retry this group"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${n}/${e.need} AC`)+chalk.gray(mn()?`(共 ${e.n} 题)`:` (of ${e.n})`)),null==s&&n>=e.need){const o=Math.max(0,e.n-n);console.log(0===o?chalk.bold.green(mn()?` 🎉 满分 ${e.n}/${e.n} — 本组全部拿下!`:` 🎉 Perfect ${e.n}/${e.n} — every problem cleared!`)+chalk.gray(mn()?" ↩ back 回卡片":" ↩ back returns to the card"):chalk.green(mn()?" 🏁 已过关":" 🏁 passed")+chalk.yellow(mn()?` · 还剩 ${o} 题,全做完 = 满分 ${e.n}/${e.n}`:` · ${o} more for a perfect ${e.n}/${e.n}`))}if(t.length>0&&console.log(chalk.cyan(` ✅↗ ${t.length}`)+chalk.gray(mn()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0){const o=(e.carry_from??[]).join(", "),t=o?mn()?`(${o})`:` (${o})`:"";console.log(chalk.cyan(mn()?` 🔗 你另一个 token${t}已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens${t} solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(mn()?" 带过来,不必重做":" 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(mn()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(mn()?"不够就 ":"Short on time? ")+chalk.bold.green("contest restart")+chalk.gray(mn()?" 满血重开本组。":" restarts this group fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(mn()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),nr&&(console.log(chalk.gray(" 0 ")+gr(Me)+chalk.gray(` ${tr(Me)}`)+chalk.gray(mn()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+gr(e)+(e.gpu?chalk.magenta(" ⚡"):"")+chalk.white(` ${tr(e)}`))}),e.problems.some(e=>e.gpu)&&(console.log(),console.log(e.gpu_window?chalk.bold.green(mn()?" ⚡ GPU 窗口:开 ✅":" ⚡ GPU window: OPEN ✅")+chalk.gray(mn()?" — 带 ⚡ 的层现在 /submit 就在真 GPU 上跑":" — /submit a ⚡ rung and it runs on a real GPU right now"):chalk.gray(mn()?" ⚡ GPU 窗口:关(每周一 19:00–21:45 悉尼开放)— 带 ⚡ 的层等窗口内 /submit":" ⚡ GPU window: closed (Mondays 19:00–21:45 Sydney) — /submit ⚡ rungs inside the window"))),On(Ln.phase,e.slot)&&(console.log(),console.log(chalk.gray(" ✍ ")+chalk.bold.green("cells")+chalk.gray(mn()?" 在 notebook 里探索本场数据(引导走查 · 真图) — 不判分,判分仍走 /submit":" explore this lab in a notebook (guided walkthrough · real figures) — ungraded; judging stays /submit"))),console.log(),xr()},xr=()=>{console.log(chalk.gray(mn()?" /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(" ")+chalk.bold.green(mn()?"/syntax <词>":"/syntax <word>")+chalk.gray(mn()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(mn()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(mn()?" 返回课程":" returns to the lesson")),console.log(chalk.gray(mn()?" memo 报告题面/判分问题 — 不打断比赛计时":" memo reports a statement/judging problem — the clock is unaffected")),console.log(chalk.gray(" ")+chalk.bold.green("contest restart")+chalk.gray(mn()?" 超时/坏场时重开本组(全新计时+模板) · ":" time up or broken attempt → this group again (fresh clock + templates) · ")+chalk.bold.green("contest reset")+chalk.gray(mn()?" 日后回来整阶段重做":" come back later and redo the whole phase")),console.log()},Tr=e=>{const o=parseInt(e,10),t=Ln.data.problems;if(o===qe&&nr)return{p:Me,n:qe};const n=nr?qe:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(mn()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),nr&&console.log(chalk.gray(mn()?" 0 = 热身题(不计分,证明环境通了)· 1 起是本组正式题目。":" 0 = the warm-up (unscored — proves your setup works) · 1 and up are the real problems.")),null):{p:t[o-1],n:o}};let Sr=null,Pr=!1;const Ir=e=>{const o=Tr(e);if(!o)return;const{p:t,n:n}=o;Sr=String(n),console.log(),console.log(chalk.bold.white(` ${gr(t)} ${tr(t)}`)),console.log();for(const e of(e=>mn()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of gt(e,ct()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(mn()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(mn()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(mn()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(mn()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=mn()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of gt(o,ct()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(mn()?"数据就在上方 DATA 块(sol 文件里已赋给 data 变量)— 不用 input(),只 print flag{...} 本身":"The data is the DATA block above (already assigned to `data` in your sol file) — no input(); print ONLY the flag{...} token"))),console.log(),nr&&n===qe)return console.log(chalk.white(mn()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(mn()?"第 1 行已经写好了,把第 2 行的 ??? 换掉(vi:i 编辑 · Esc · :wq 存盘退出)":"line 1 is written for you — replace the ??? on line 2 (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green("/run 0".padEnd(11))+chalk.gray(mn()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(mn()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((mn()," ↩ "))+chalk.bold.green("back")+chalk.gray(mn()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(mn()?" 直接看正式题目":" skips straight to the real problems")),void console.log();t.gpu?(console.log(chalk.white(mn()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(mn()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(mn()?"真 GPU 上跑并带回你的 ms(⚡ 每周一窗口 19:00–21:45 悉尼)":"runs on a real GPU and returns your ms (⚡ Monday window 19:00–21:45 Sydney)"))):t.starter?(console.log(chalk.white(mn()?" 三步:":" Three steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(mn()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(mn()?"本机直跑,出你自己的 ms":"run it locally — see your own ms")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(mn()?"参考机判分(成绩 = 那里的 ms)":"judge on the reference machine (the scored ms)"))):(console.log(chalk.white(mn()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(mn()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(mn()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(mn()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(mn()?"正式判分(隐藏用例)":"official judging (hidden tests)"))),console.log(),console.log(chalk.gray(mn()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(mn()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((mn()," ↩ "))+chalk.bold.green("back")+chalk.gray(hr()?mn()?" 回花名册 · ":" to the roster · ":mn()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(mn()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((mn()," / "))+chalk.bold.green("wide")+chalk.gray(mn()?" 换语言/宽度":" language / width")),console.log()},jr=async(e,o,t)=>await new Promise(n=>{const l=process.stdin,a=!!l.isTTY&&!!l.isRaw;if(It.pause(),l.isTTY&&"function"==typeof l.setRawMode)try{l.setRawMode(!1)}catch{}Ot=!0;const i=r(e,o,{stdio:"inherit",cwd:t??Ln.dir}),c=e=>{if(l.isTTY&&"function"==typeof l.setRawMode&&a)try{l.setRawMode(!0)}catch{}s(),Ot=!1,It.resume(),n(e)};i.on("close",()=>c(null)),i.on("error",e=>c(e))}),Er=["-n","-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark number","-c","silent! set complete=. completeopt=menu,menuone","-c","silent! highlight Normal ctermfg=252 | silent! highlight ModeMsg ctermfg=231 cterm=bold | silent! highlight MoreMsg ctermfg=252 | silent! highlight Question ctermfg=252"],Lr=()=>{const e=A("vi");console.log(chalk.gray(mn()?e?" vi 四键: i 进入编辑 · Esc 退出编辑 · Ctrl-N 补全 · :wq 存盘离开":" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":e?" vi survival: i = edit · Esc = stop editing · Ctrl-N = complete word · :wq = save and leave":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"))},Mr=()=>po(mn(),{judgeIsServerSide:!0}),Nr=()=>{const e=fo();return e||Mr(),e},qr=new Map,Or=()=>Je(process.cwd(),mt.id),Wr=e=>{const o=new Date(e),t=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${t(o.getMonth()+1)}-${t(o.getDate())} ${t(o.getHours())}:${t(o.getMinutes())}`},Rr=async(e,o,t=!1)=>{if(!Rn)return;let n;try{n=O(Qe(Or(),e),"utf-8")}catch{return}if(Buffer.byteLength(n,"utf-8")>De)return;const r=Ke(n),s=(new Date).toISOString(),l=Ze($o(),yt).slice(0,Be),a=await to(yt,{n:e,title:Xe(n.split("\n",1)[0]),code:n,code_sha:r,card_number:At.currentCard,run_meta:o,client_ts:s,events:l.length>0?l:void 0});a?l.length>0&&Ve($o(),yt,l.length):eo($o(),yt,{n:e,code_sha:r,card_number:At.currentCard,run_meta:o,client_ts:s}),a||t||console.log(chalk.gray(mn()?" (未能同步到服务器 — 草稿只保存在本机)":" (could not reach the server — this scratch is saved locally only)"))},Dr=()=>{console.log(chalk.gray(mn()?" edit <n> 改码(vi) · run <n> 本机运行 · pylist 列表 · /py 新建 · ↩ back 回卡片":" edit <n> code (vi) · run <n> local run · pylist list · /py new file · ↩ back to the card")),console.log()},Ur=e=>{const o=Fe(Or()),t=parseInt(e,10);return Number.isInteger(t)&&o.some(e=>e.n===t)?t:(0===o.length?console.log(chalk.yellow(mn()?" 还没有任何草稿 — ":" No scratch files yet — ")+chalk.bold.green("/py")+chalk.gray(mn()?" 新建第一个。":" creates the first one.")):console.log(chalk.yellow(mn()?` 没有 py-${e} — 现有编号: `:` No py-${e} — you have: `)+chalk.white(o.map(e=>e.n).join(", "))+chalk.gray(mn()?" · pylist 看列表":" · pylist shows them")),null)},Yr=e=>{const o=Fe(Or()),t=e?.trim().toLowerCase(),n=t?o.filter(e=>(e.title??"").toLowerCase().includes(t)):o;if(console.log(),console.log(chalk.bold.magenta(mn()?" ✍ 我的 Python 草稿":" ✍ My Python scratch files")+(t?chalk.gray(` · "${e?.trim()}"`):"")+chalk.gray(` (${n.length})`)),0===o.length)return console.log(chalk.gray(mn()?" 还没有草稿 — ":" Nothing here yet — ")+chalk.bold.green("/py")+chalk.gray(mn()?" 新建一个(第一行写标题)。":" creates one (line 1 becomes its title).")),void console.log();if(0===n.length)return console.log(chalk.gray(mn()?` 没有匹配 "${e?.trim()}" 的草稿 — 直接 pylist 看全部。`:` No title matches "${e?.trim()}" — bare pylist lists everything.`)),void console.log();for(const e of n){const o=e.title?chalk.white(gt(e.title,40)[0]??e.title):chalk.gray(mn()?"(未命名 — 第一行写标题)":"(untitled — line 1 becomes the title)");console.log(chalk.gray(` py-${String(e.n).padEnd(3)} `)+o+chalk.gray(` · ${Wr(e.mtimeMs)}`))}console.log(chalk.gray(" ▸ ")+chalk.bold.green(mn()?"/py <编号>":"/py <n>")+chalk.gray(mn()?" 打开 · ":" opens one · ")+chalk.bold.green("/py")+chalk.gray(mn()?" 新建":" new file")),console.log()},Br=async e=>{const o=Qe(Or(),e);if(vo())return console.log(chalk.yellow(mn()?" icoa 正跑在 Windows 上 — 草稿本的编辑器在 Ubuntu(WSL)那一侧。":" icoa is running on Windows — the scratchpad editor lives on the Linux (WSL) side.")),console.log(chalk.gray(mn()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${o}`)),void console.log();if(!Co("vi"))return console.log(chalk.yellow(mn()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${o}`)),void console.log(chalk.gray(mn()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));Lr();const t=e=>{try{return R(e).size}catch{return 0}},n=t(o),r=Date.now(),s=C(o);await jr("vi",[...Er,`py-${e}.py`],Or());const l=s.stop();_(`learn-py edit-done py-${e}.py`,{ms:Date.now()-r,bytesBefore:n,bytesAfter:t(o),...l.ticks>0?{samples:l}:{}}),await Rr(e),console.log(chalk.gray(mn()?" 已回到草稿本 — ":" Back in the scratchpad — ")+chalk.bold.green(`run ${e}`)+chalk.gray(mn()?" 本机运行 · ":" runs it locally · ")+chalk.bold.green(`edit ${e}`)+chalk.gray(mn()?" 再改。":" reopens vi.")),console.log()},zr=async e=>{let o;if(N(Or(),{recursive:!0}),e){const t=Ur(e);if(null===t)return;o=t}else{const e=Fe(Or());o=He(e),o>Ue&&console.log(chalk.gray(mn()?` (已超过 ${Ue} 个 — 服务器不再备份新文件,本机照常保存)`:` (past ${Ue} files — the server stops backing new ones up; local saves still work)`)),D(Qe(Or(),o),`${mn()?ze:Ye}\n\n`)}const t=!Vt;Vt=!0,_(`learn-py: open ${o}${e?"":" (new)"}`),t&&(console.log(),console.log(chalk.bold.magenta(mn()?" ✍ Python 草稿本":" ✍ Python scratchpad")+chalk.gray(mn()?" — 你的个人练习文件 · 只在本机运行 · 不判分":" — your personal practice files · runs locally · never judged")),console.log(chalk.gray(mn()?" edit <n> 改码(vi) · run <n> 本机运行 · 整轨一份文件列表,跨卡共用":" edit <n> code (vi) · run <n> local run · one file list shared across the whole track")),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(mn()?" 回卡片(退一层)":" returns to the card (one level)"))),await Br(o),Dr()},Fr=()=>ao(process.cwd(),mt.id),Gr=()=>on??ro(lo(process.cwd(),mt.id,At.currentCard)),Hr=()=>{console.log(),console.log(chalk.bold.magenta(mn()?" ⌨ shell 实验台":" ⌨ shell lab")+chalk.gray(mn()?" — 在这里动手把答案弄出来 · 不判分 · 不解锁任何东西":" — work the answer out here · never judged · unlocks nothing")),console.log(chalk.gray(mn()?` 真的 shell:管道 | 、重定向 > 、通配符 * 都能用 · 每条命令最多 ${no/1e3} 秒`:` A real shell: pipes |, redirection >, globs * all work · ${no/1e3}s per command`)),console.log(chalk.gray(mn()?` 你在 ${uo(Fr())} 里面 —— 只能在这个文件夹内走动(自己的终端不受限)`:` You are inside ${uo(Fr())} — you can only move within it (your own terminal is unrestricted)`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(mn()?" 回卡片(退一层)":" returns to the card (one level)")),console.log()},Zr=()=>{console.log(chalk.gray(mn()?" 敲任何 shell 命令 · cd 换目录 · reset 还原文件 · clear 清屏 · ↩ back 回卡片":" type any shell command · cd to move · reset restores files · clear · ↩ back"))},Kr=()=>`icoa sh ${go(Fr(),Gr())}> `,Jr=(e=!1)=>{const o=Tn(At.currentCard)?.files;if(!o)return[];const t=ro(lo(process.cwd(),mt.id,At.currentCard)),n=[];for(const[r,s]of Object.entries(o)){if(!/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/.test(r))continue;if(r.split("/").some(e=>"."===e||".."===e))continue;const o=G(t,r);if(o===t||o.startsWith(t+"/")){try{N(F(o),{recursive:!0})}catch{}if(e||!M(o))try{D(o,s),n.push(r)}catch{}}}return n},Qr=(e="card")=>{tn=e;const o=!en;en=!0,on=Gr();const t=Jr();_(`learn-sh: enter card${At.currentCard}`),o&&Hr(),t.length>0&&(console.log(chalk.bold.green(mn()?" 📦 本卡的文件已放好:":" 📦 This card ships files:")+chalk.white(` ${t.join(" ")}`)),console.log(chalk.gray(mn()?" 先敲 ls 看看。":" Start with `ls`.")),console.log()),Zr()},Xr=async e=>{const o=e.trim().toLowerCase(),s=Xt&&o.startsWith("/")?o.slice(1):o;if(Mt)return void(Nt=!0);if(qt){const{sameName:o,issueCertificate:t,announceCertificate:n}=await import("../lib/learn-certificate.js"),r=e.trim(),s=mn();if(!r||Gt.test(r))return qt=null,console.log(chalk.gray(s?" 已取消,未签发。":" Cancelled — nothing issued.")),void Wt();if(null===qt.first)return qt.first=r,console.log(chalk.gray(s?" 再输一次:":" Type it once more:")),void Wt();const l={cid:qt.cid,tok:qt.tok,first:qt.first};return qt=null,o(l.first,r)?(console.log(chalk.gray(s?" 签发中…(名字只发送一次,不会保存)":" Issuing… (the name is sent once, never stored)")),n(await t(l.tok,l.cid,l.first),s),void Wt()):(console.log(chalk.yellow(s?" 两次输入不一致 — 未签发。再敲 certificate 重来。":" The two names differ — nothing issued. Type certificate to try again.")),void Wt())}if(Qt)return;if(Lt?.noteInput(),!nn&&Lt?.consumeRating(o))return void Wt();if(nn)return await(async e=>{if(!nn)return;const o=e.trim(),t=o.toLowerCase();if(bn&&("sh"===t||"/sh"===t))return nn=null,Qr(),void console.log(chalk.gray(mn()?" ▸ 看完敲 back 回卡片,再 practice <n> 回到这道题。":" ▸ When you have looked: back to the card, then practice <n> to return."));if("back"===t||"quit"===t||"menu"===t)return nn=null,console.log(chalk.gray(mn()?" ↩ 回到卡片。":" ↩ Back on the card.")),void Kn();if("skip"===t)return void Cr();if(""===o)return void _r();const n=kr();if(!n)return nn=null,void Kn();const r=br(n.starter??"");if(nn.answers.push(o),nn.answers.length<r)return void vr();const s=[...nn.answers],l=((e,o)=>{let t=0;return e.split("\n").map(e=>{if(e.trim().startsWith("#"))return e;for(;e.includes("____")&&t<o.length;)e=e.replace("____",o[t]),t+=1;return e}).join("\n")})(n.starter??"",s);nn.answers=[];let a=Un.get(nn.slot);a||(a=new Set,Un.set(nn.slot,a)),a.add(n.id);const i=Boolean(n.quiz),c=i?null:new I(yt);c?.start();const d=await xe(yt,nn.phase,n.id,l,nn.slot,void 0);if(c?.stop(),!nn)return;if(!d.ok||!d.data)return"no_active_session"===d.code?void wr(nn.data.duration_minutes):(console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),console.log(chalk.gray(mn()?" 再敲一遍空1重试,或 back 回卡片。":" Type blank 1 again to retry, or back for the card.")),void vr());const g=d.data;if("AC"!==g.verdict||g.already_ac||Lt?.notePracticeAc(),g.already_ac||"AC"===g.verdict){i?console.log(chalk.bold.green(mn()?" ✅ 答对了!":" ✅ Correct!")):console.log(ho("AC",{isZh:mn(),gentle:!0,passed:g.passed_tests??g.total_tests??null,total:g.total_tests??null,ms:g.time_ms??null}));let e=Dn.get(nn.slot);return e||(e=new Set,Dn.set(nn.slot,e)),e.add(n.id),nn.data.solved.includes(n.id)||nn.data.solved.push(n.id),void Cr()}nn.tries+=1,i?console.log(chalk.red(mn()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(mn()?" — 再选一次。":" — pick again.")):console.log(ho(g.verdict??"WA",{isZh:mn(),gentle:!0,passed:g.passed_tests??null,total:g.total_tests??null,failedTest:g.test??null,ms:g.time_ms??null}));const u=n.samples?.[0];if(u?.out){console.log(chalk.gray(mn()?" 期望输出:":" Expected output:"));for(const e of u.out.trimEnd().split("\n"))console.log(chalk.white(" "+e))}if(2===nn.tries||nn.tries>2&&nn.tries%3==2){const e=i?[]:((e,o)=>{const t=[];let n=0;for(const r of e.split("\n")){if(r.trim().startsWith("#"))continue;const e=r.split("____");for(let r=0;r<e.length-1;r++,n++){const s=(o[n]??"").trim(),l=e[r+1].trimStart(),a=e[r].trimEnd(),i=n+1;l.startsWith("(")&&/\(\s*\)?$/.test(s)?t.push(mn()?` ⚠ 空${i}:模板里 ____ 后面已经有 ( ) — 只填名字,别再带括号。`:` ⚠ blank ${i}: the ( ) after ____ is already in the template — type just the name, no brackets.`):(/["']$/.test(a)||/^["']/.test(l))&&/^["']|["']$/.test(s)?t.push(mn()?` ⚠ 空${i}:引号模板里已经有了 — 只填引号中间的内容。`:` ⚠ blank ${i}: the quotes are already in the template — type only what goes between them.`):/^[A-Za-z_][\w.]*\(.*\)$/.test(s)&&!l.startsWith("(")&&/\)\s*[:)]/.test(l)&&t.push(mn()?` ⚠ 空${i}:____ 后面已有右括号,你的答案可能多带了一个 )。`:` ⚠ blank ${i}: a closing ) already follows ____ — your answer may carry one too many.`)}}return t})(n.starter??"",s);for(const o of e)console.log(chalk.yellow(o));console.log(chalk.gray(mn()?" 💡 两次没过,多半是细节不是思路 — 再敲之前过一遍:":" 💡 Two misses are usually a detail, not the idea — run this check before retrying:")),i||(console.log(chalk.gray(mn()?" · 拼写和大小写(Python 区分大小写:Print ≠ print)":" · spelling and case (Python is case-sensitive: Print ≠ print)")),console.log(chalk.gray(mn()?" · 只填缺的那一块 — ____ 周围已有的括号、引号、冒号不要重复":" · fill only what is missing — brackets, quotes, colons already around ____ stay"))),console.log(chalk.gray(mn()?" · 没思路?往上翻,或 ":" · no idea? scroll up, or ")+chalk.bold.green("back")+chalk.gray(mn()?" 回卡片再读一遍 — 答案就在正文里。打错字人人都有,继续。":" re-reads the card — the answer is in its body. Typos happen to everyone; keep going."))}console.log(chalk.gray(mn()?" 从空1再来:":" From blank 1 again:")),vr()})(e),void Wt();if(null!==Yt){if(Bt.push(e.replace(/\s+$/,"")),Ft&&clearTimeout(Ft),Ft=null,zt){const e=Bt[Bt.length-1]??"";return"/cancel"===e.trim()?(Kt(),console.log(chalk.gray(mn()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Wt()):""!==e.trim()?void Wt():(Bt.pop(),void await c())}return void(Ft=setTimeout(()=>{if(Ft=null,Bt.length>1){zt=!0;const e=Bt.length;return console.log(chalk.cyan(mn()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(mn()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Wt()}c()},140))}async function c(){const e=Bt.join("\n").replace(/^\s+|\s+$/g,""),o=Yt??At.currentCard,t=Bt.length,n=Ht;if(Kt(),""===e)console.log(chalk.gray(mn()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&Gt.test(e))console.log(chalk.yellow(mn()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(mn()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(mn()?" 即可执行。":" again to run it."));else{const r=!n&&yn>0?Date.now()-yn:void 0;if(await X(yt,{curriculum_id:mt.id,card_number:o,feedback_text:n?`${n} ${e}`:e,time_on_card_ms:r})){const n=t>1?mn()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(mn()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(mn()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),kt=[...kt,{id:_t--,curriculumId:mt.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],st(kt)}else console.log(chalk.yellow(mn()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Wt()}if(sn){const o=e.trim();if(Gt.test(o))return sn=!1,console.log(),console.log(chalk.yellow(mn()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(mn()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(mn()?" 即可执行该命令。":" again to run it.")),console.log(),void Wt();if(!o)return sn=!1,console.log(chalk.gray(mn()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Wt();const t=await be({token:yt,nickname:o});if(t.ok)sn=!1,console.log(chalk.bold.green(mn()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(mn()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{ln+=1;const e="taken"===t.code?mn()?"已被占用":"already taken":"bad_charset"===t.code?mn()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"real_name"===t.code?mn()?"看起来像真名 — 系统不收集个人信息,换个游戏风格的昵称":"looks like a real name — we collect no personal info; pick a gamer-style handle":"rejected"===t.code?mn()?"未通过审核":"did not pass review":t.message||"error";if(!(ln>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(mn()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Wt();sn=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(mn()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Wt()}if(un){un=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Qt=!0;try{console.log(),console.log(chalk.gray(mn()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await ke({token:yt,cardNumber:At.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(mn()?"评审暂不可用。":"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(mn()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(mn()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(mn()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(mn()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(mn()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(mn()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=mn()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(mn()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(mn()?` 第 ${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 Vn(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(mn()?" 改进提问: ":" 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(` (${mn()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?hn.add(At.currentCard):hn.delete(At.currentCard),"number"==typeof e.rank&&fn.set(At.currentCard,e.rank);const o=await _e({token:yt,curriculumId:mt.id,cardNumber:At.currentCard});if(o.ok&&o.totals&&o.chapters&&(dt({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),o.ok&&o.phaseBoard?.mine){const e=o.phaseBoard,t=o.phaseBoard.mine,n=e.top[0],r=n&&!n.me?chalk.gray(mn()?` · 榜首 ${n.name||"Rank 1"} ${n.total}`:` · leader ${n.name||"Rank 1"} at ${n.total}`):chalk.bold.yellow(mn()?" · 全场第一!":" · phase leader!");console.log(chalk.white(mn()?` 🏅 Phase ${e.phase} 研究总分: `:` 🏅 Phase ${e.phase} research total: `)+chalk.bold.yellow(`${t.total}`)+chalk.gray(mn()?`(${t.cards}/${e.cards_in_phase} 卡)· 第 ${t.rank} 名`:` (${t.cards}/${e.cards_in_phase} cards) · rank ${t.rank}`)+r),console.log()}!0===e.inTop3&&o.ok&&null==o.nickname&&!ft&&(sn=!0,ln=0,console.log(chalk.bold.yellow(mn()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(mn()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(mn()?" 英文开头,英文+数字,3-16 位 · 别用真名(系统不收集个人信息,会被拒)· 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · not your real name (we collect no personal info — it gets refused) · permanent · Enter skips")))}finally{Qt=!1}})():(console.log(chalk.gray(mn()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Ut&&(console.log(chalk.gray(mn()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Wt()}if(pn)return pn=!1,Kn(),void Wt();if(!o)return void Wt();if(cn)return"exit"===await E(e.trim())&&(cn=!1),void Wt();if(Jt){if(["q","quit","exit","back","b","menu"].includes(o))return Jt=!1,console.log(chalk.gray(mn()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Wt();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim(),r=/^(\/?(submit|read|edit|run|debug|list|honors|recall|view|ai|syntax|contest|practice|practise|py|memo)\b\s*\d*|\/?pylist\b\s*\S*|card\s+\d+|\d+|status|bookmark|unbookmark|reload|link|wide|wider|widest|normal|narrow|next|ok|y|n|yes|no|menu|lang(\s+\S+)?|e)$/i.exec(n),s=n.length>0&&!/[\p{L}\p{N}]/u.test(n);return r||s?(console.log(),console.log(chalk.yellow(mn()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(s?mn()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":mn()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(mn()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(mn()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void Wt()):(n&&(await Xn(n,t?"fast":"deep"),console.log(chalk.gray(mn()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Wt())}if(en){const t=e.trim();if(["back","b","quit","exit","q"].includes(o))return en=!1,on=null,_("learn-sh: leave"),"arena"===tn?console.log(chalk.gray(mn()?" ↩ 已离开实验台,回到赛场。":" ↩ Left the lab — back in the arena.")):(console.log(chalk.gray(mn()?" ↩ 已离开 shell 实验台,回到卡片。":" ↩ Left the shell lab — back to the card.")),Kn()),void Wt();if("menu"!==o&&!/^memo\b/.test(o)){if("reset"===o){const e=Jr(!0);return console.log(e.length>0?chalk.green((mn()?" ↺ 已还原本卡的文件: ":" ↺ Restored this card's files: ")+e.join(" ")):chalk.gray(mn()?" 本卡没有附带文件。":" This card ships no files.")),void Wt()}return"clear"===o||"cls"===o?(console.clear(),Zr(),void Wt()):"help"===o||"e"===o||"?"===o?(Hr(),void Wt()):""===t?void Wt():/^\/?py(\s|$)/.test(o)?(en=!1,on=null,await zr(/^\/?py\s+(\S+)/.exec(o)?.[1]),void Wt()):(await(async e=>{_(`learn-sh: $ ${e}`);const o=/^cd(?:\s+(.*))?$/.exec(e.trim());if(o){const e=io(Fr(),Gr(),o[1]?.trim());return void(null===e?console.log(chalk.yellow(mn()?" 去不了那儿 —— 目录不存在,或在实验台外面。":" Cannot go there — no such directory, or it is outside the lab.")+chalk.gray(mn()?" cd 单独敲回到顶层。":" Bare `cd` returns to the top.")):on=e)}const t=so(e);if(t)return void console.log(chalk.yellow(mn()?` \`${e.trim().split(/\s+/)[0]}\` 会占住终端,这里跑不了 — `:` \`${e.trim().split(/\s+/)[0]}\` takes over the terminal and cannot run here — `)+chalk.bold.green(t));const n=/(^|[;&|]\s*)cd(\s|$)/.test(e)&&!/^cd(\s|$)/.test(e.trim()),r=await co(e,Gr());"no-shell"!==r.kind?"timeout"!==r.kind?"refused"!==r.kind&&(r.stdout&&console.log(chalk.white(r.stdout.replace(/\n$/,""))),r.stderr&&console.log(chalk.red(r.stderr.replace(/\n$/,""))),r.truncated&&console.log(chalk.gray(mn()?" … 输出过长,已截断。":" … output truncated.")),n&&console.log(chalk.yellow(mn()?" 注意:这一行里的 cd 只在子进程里生效,你还在原来的目录。":" Note: the cd in that line ran in a child process — you have not moved.")+chalk.gray(mn()?" 单独敲一行 cd <目录>。":" Type `cd <dir>` on its own line.")),r.stdout||r.stderr?0!==r.code&&console.log(chalk.gray(mn()?` (退出码 ${r.code})`:` (exit ${r.code})`)):console.log(chalk.gray(mn()?` (没有输出 · 退出码 ${r.code})`:` (no output · exit ${r.code})`))):console.log(chalk.yellow(mn()?` 超过 ${no/1e3} 秒,已停止。`:` Stopped after ${no/1e3}s.`)+chalk.gray(mn()?" 换个更小的目标再试。":" Try a smaller target.")):console.log(chalk.red(mn()?" 这台机器上找不到 /bin/sh。":" No /bin/sh on this machine.")+chalk.gray(mn()?" Windows 请在 WSL2 里跑 icoa。":" On Windows, run icoa inside WSL2."))})(t),void Wt())}}if(Vt){if(/^\/?(py|pylist|edit|run|list|new)\b|^(b|q|quit|exit|back)$|^\d+$/.test(o)&&_(`learn-py: ${o}`),["back","b","quit","exit","q"].includes(o))return Vt=!1,console.log(chalk.gray(mn()?" ↩ 已离开草稿本,回到卡片。":" ↩ Left the scratchpad — back to the card.")),Kn(),void Wt();const t=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(t||"list"===o||"/list"===o)return Yr(t?.[1]),Dr(),void Wt();const n=/^\/?(edit|run)(?:\s+(\S+))?$/.exec(o)??(/^\d+$/.test(o)?["","edit",o]:null);if(n){const e=n[1],o=n[2];if(o){const t=Ur(o);null!==t&&("edit"===e?(await Br(t),Dr()):await(async e=>{if(!M(Qe(Or(),e)))return void Ur(String(e));const o=mo()?.cmd??null;if(!o)return void po(mn());const[t,...n]=o.split(" ");console.log();const s=oo();let l="",a=!1;const i=await new Promise(o=>{const s=r(t,[...n,`py-${e}.py`],{cwd:Or(),stdio:["ignore","pipe","pipe"]}),i=setTimeout(()=>{a=!0;try{s.kill("SIGKILL")}catch{}},3e4);s.stdout?.on("data",e=>process.stdout.write(e)),s.stderr?.on("data",e=>{l.length<400&&(l+=e.toString("utf-8")),process.stderr.write(e)}),s.on("error",()=>{clearTimeout(i),o(127)}),s.on("close",(e,t)=>{clearTimeout(i),o(t?124:e??0)})}),c=s();console.log(),0===i?console.log(chalk.bold.green(` ✓ ran py-${e}`)+chalk.gray(` · ${c}ms · exit 0`)):(console.log(chalk.yellow(` ✗ ran py-${e} · ${c}ms · exit ${i}`)),a&&console.log(chalk.gray(mn()?" ⏱ 超过 30 秒,已停止 — 检查死循环。":" ⏱ Over 30s — stopped. Check for an infinite loop."))),console.log(chalk.gray((mn()," ▸ edit "))+chalk.gray(`${e} · pylist · `)+chalk.bold.green("back")),console.log(),vn.push(Rr(e,{run_ms:c,exit_code:i,stderr_head:l.trim().slice(0,300)||void 0},!0).catch(()=>{}))})(t))}else console.log(chalk.yellow(mn()?` 用法: ${e} <编号>`:` Usage: ${e} <n>`)+chalk.gray(mn()?" (pylist 看编号)":" (pylist shows the numbers)"));return void Wt()}const s=/^\/?py(?:\s+(\S+))?$/.exec(o);if(s||"new"===o)return await zr(s?.[1]),void Wt();const l=/^\/?python(?:3)?(?:\s+(setup|install|status))?$/i.test(o.trim());if("menu"!==o&&"menu confirm"!==o&&!l)return console.log(chalk.gray(mn()?" 草稿本命令: edit <n> · run <n> · pylist · /py 新建 · back 回卡片":" Scratchpad verbs: edit <n> · run <n> · pylist · /py (new) · back to the card")),void Wt()}if(Xt&&Ln){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn|memo|cells|explore)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&_(`learn-arena p${Ln.phase}s${Ln.data.slot}: ${o}`),bn&&("sh"===o||"/sh"===o))return Qr("arena"),console.log(chalk.gray(mn()?" ▸ back 回赛场 · 计时照走":" ▸ back returns to the arena · the clock keeps running")),void Wt();if("memo"===o||"/memo"===o||"e"===o)return Yt=At.currentCard,Ht=`[arena p${Ln.phase}-g${Ln.data.slot}${Sr?` #${Sr}`:""}]`,console.log(chalk.gray(mn()?` 报告归到: 竞技场 p${Ln.phase}-g${Ln.data.slot}${Sr?` 题${Sr}`:""} — 题面 / 判分 / 环境,一句话即可:`:` Files under: arena p${Ln.phase}-g${Ln.data.slot}${Sr?` problem ${Sr}`:""} — statement / judging / environment, one line is enough:`)),console.log(chalk.gray(mn()?" (回车提交 · 空行取消 · 不打断比赛计时)":" (Enter to submit · blank to cancel · the contest clock is unaffected)")),void Wt();if("back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return hr()&&null!==Sr?(Sr=null,Ar(),void Wt()):(Xt=!1,Sr=null,console.log(chalk.gray(mn()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Kn(),void Wt());if(/^\d+$/.test(o))return Ir(o),void Wt();const n=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(n)return hr()?n[1]?Ir(n[1]):Ar():console.log(chalk.gray(mn()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void Wt();if("cells"===o||"/cells"===o||"explore"===o||"/explore"===o){const e=Wn(Ln.phase,Ln.data.slot,Ln.dir);if(!e)return console.log(chalk.gray(On(Ln.phase,Ln.data.slot)?mn()?" 引导 notebook 还没下载到位(需要联网一次)— 稍后再敲 cells。":" The guided notebook has not downloaded yet (needs one online moment) — try cells again shortly.":mn()?" 本场没有引导 notebook — /read <n> 读题;EXPLORE 段在本机把 SHOW 改成 True 即可出图。":" No guided notebook for this group — /read <n> for statements; flip SHOW to True locally in the EXPLORE section for plots.")),void Wt();const o=null!==x();o||T(It);try{const{runIpynb:o}=await import("./ipynb.js");await o(e)}catch(e){console.log(chalk.yellow(mn()?" notebook 没打开: ":" The notebook failed to open: ")+chalk.gray(String(e)))}finally{o||T(null)}return Ar(),void Wt()}const r=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(r)return await(async e=>{const o=e.trim();if(await ae()||Pr||(Pr=!0,console.log(chalk.gray(mn()?` (离线:只有 ${ye()} 条核心速查可用;联网后自动补全)`:` (offline: ${ye()} core entries available; the rest arrive when you have a connection)`))),!o)return void ue(mn());const t=ce(o);if(t.length){pe(t[0],mn());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(mn()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await ie("python3",o);if(n)he(n,mn());else{if(await de()){const e=ce(o);if(e.length)return void pe(e[0],mn())}console.log(),console.log(chalk.yellow(mn()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(mn()?" 试试: ":" Try: ")+chalk.cyan(ge(o).join(" · "))),console.log(chalk.gray(mn()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(r[1]??""),void Wt();const l=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(l){const[,e,o]=l;return"list"===e?Ar():o?"read"===e||"open"===e?Ir(o):"edit"===e?await(async e=>{const o=Tr(e);if(!o)return;const t=G(Ln.dir,ir(o.n,o.p));if(vo())return _o()?(console.log(chalk.yellow(mn()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(mn()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(mn()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(mn()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(mn()?" ← 不能是 /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(mn()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(mn()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(mn()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(mn()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(mn()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(mn()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(mn()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(mn()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!Co("vi"))return console.log(chalk.yellow(mn()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(mn()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));Lr();const n=e=>{try{return R(e).size}catch{return 0}},r=n(t),s=Date.now(),l=C(t);await jr("vi",[...Er,ir(o.n,o.p)]);const a=l.stop(),i={ms:Date.now()-s,bytesBefore:r,bytesAfter:n(t)};if(Mn.set(o.n,Y(Mn.get(o.n)??U(),i)),a.ticks>0){const e=Nn.get(o.n)??{list:[],dropped:0};e.list.push(a),e.list.length>16&&(e.list.shift(),e.dropped++),Nn.set(o.n,e)}_(`learn-arena edit-done ${ir(o.n,o.p)}`,{...i,...a.ticks>0?{samples:a}:{}}),console.log(chalk.gray(mn()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(mn()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?await(async e=>{const o=Tr(e);if(!o)return;const{p:n,n:r}=o;if(nr&&r===qe)return void(()=>{const e=G(Ln.dir,`sol-${qe}.py`);if(!M(e))return void console.log(chalk.yellow(mn()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=Nr();if(!o)return;const n=[];for(const r of Oe)try{n.push(t(o,[e],{input:`${r.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}))}catch(e){const o=e;if("ENOENT"===o.code)return void Mr();if(console.log(),o.killed)return void console.log(chalk.yellow(mn()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(mn()?` ✗ 输入 ${r.in} 时程序报错:`:` ✗ Your program crashed on input ${r.in}:`));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));return console.log(),console.log(chalk.gray(mn()?" 改完再来: ":" Fix it and rerun: ")+chalk.bold.green("/edit 0")+chalk.gray(" → ")+chalk.bold.green("/run 0")),void console.log()}const{cases:r,passed:s}=We(n);console.log();for(const e of r)console.log((e.ok?chalk.green(" ✓ "):chalk.red(" ✗ "))+chalk.gray(`n = ${e.in.padEnd(6)} → `)+(e.ok?chalk.cyan(e.got||"(empty)"):chalk.red(e.got||"(empty)"))+(e.ok?"":chalk.gray(mn()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),s===r.length){const e=rr?null:1;rr=!0,console.log(chalk.bold.green(mn()?` 🎉 ${s}/${r.length} 全过 — `:` 🎉 ${s}/${r.length} — `)+chalk.white(mn()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(mn()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(mn()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(mn()?` ${s}/${r.length} 通过 — 还差一点。`:` ${s}/${r.length} passed — not there yet.`)+chalk.gray(mn()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(mn()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const s=G(Ln.dir,ir(r,n));if(!M(s))return void console.log(chalk.yellow(mn()?` 还没有 ${ir(r,n)} — 先 /edit ${r}。`:` No ${ir(r,n)} yet — /edit ${r} first.`));Mn.set(r,z(Mn.get(r)??U()));const l=(n.samples??[])[0];if(n.gpu)return console.log(chalk.gray(mn()?" ⚡ GPU 层 — 本机没有 CUDA,这一层在真 GPU 上跑:直接 ":" ⚡ GPU rung — no CUDA on your machine; this level runs on a real GPU: go ")+chalk.bold.green(`/submit ${r}`)+chalk.gray(mn()?"(窗口时间执行并返回你的 ms;窗口外会告诉你开放时间)":" (executes in the GPU window and returns your ms; outside the window it tells you the hours)")),void console.log();{const e=ar(n),o={cpp:"c++",java:"java",go:"go"};if("python"===e?!fo():!Co(o[e]??e)){const t="python"===e?"Python":o[e]??e;return console.log(chalk.yellow(mn()?` ⓘ 本机没有 ${t} 环境 — 这一题直接交给判分机跑。`:` ⓘ No local ${t} environment — running this one on the server judge instead.`)),console.log(chalk.gray(mn()?" 判分机的计时本来就是准数;本地跑只是预览。":" The judge's timing is the real number anyway - local runs were only a preview.")),void await Xr(`/submit ${r}`)}}if(!l&&n.starter){const e=ar(n);try{let o;if("cpp"===e){const e=G(Ln.dir,`.speed-${r}.bin`);t("c++",["-O2","-o",e,s],{timeout:3e4,stdio:["pipe","pipe","pipe"]}),o=t(e,[],{input:"",timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}else if("java"===e)o=t("java",[s],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});else if("go"===e)o=t("go",["run",s],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});else{const e=Nr();if(!e)return;o=t(e,[s],{input:"",timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}console.log();for(const e of o.replace(/\n$/,"").split("\n"))console.log(` ${e}`);console.log(),console.log(chalk.gray(mn()?` ${Ge(!0)} — 满意就 `:` ${Ge(!1)} — happy? `)+chalk.bold.green(`/submit ${r}`))}catch(e){const o=e;if("ENOENT"===o.code)Mr();else if(o.killed)console.log(chalk.yellow(mn()?" ⏱ 超过 30 秒 — 检查死循环。":" ⏱ Over 30s — check for an infinite loop."));else{console.log(chalk.yellow(mn()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of(o.stderr??"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));console.log(chalk.gray(mn()?` (空还没填对?/read ${r} 看题面的 hint,/edit ${r} 再改)`:` (blank not filled yet? /read ${r} for the hint, /edit ${r} to fix)`))}}return void console.log()}if(!l)return void console.log(chalk.gray(mn()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";const i=Nr();if(!i)return;const c=oo();try{a=t(i,[s],{input:l.in.endsWith("\n")?l.in:`${l.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(e){const o=e;if("ENOENT"===o.code)Mr();else if(o.killed)console.log(chalk.yellow(mn()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(mn()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const d=c(),g=a.replace(/\r\n/g,"\n").trimEnd(),u=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(mn()?" 你的输出:":" Your output:"));for(const e of(g||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(mn()?" 样例应输出:":" Sample expects:"));for(const e of u.split("\n"))console.log(chalk.green(` ${e}`));console.log(chalk.gray(` ⏱ ${d}ms — ${Ge(mn())}`)),g===u?console.log(chalk.bold.green(mn()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(mn()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(mn()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(mn()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=Tr(e);if(!o)return;if("python"!==ar(o.p)||o.p.gpu)return console.log(chalk.gray(mn()?` 这一层不读输入 — 用 /run ${o.n} 本机跑,或直接 /submit ${o.n}(判分机编译计时)。`:` This level reads no input — use /run ${o.n} locally, or /submit ${o.n} (the judge compiles and times it).`)),void console.log();const t=G(Ln.dir,`sol-${o.n}.py`);if(!M(t))return void console.log(chalk.yellow(mn()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));const n=Nr();if(!n)return;console.log(chalk.gray(mn()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const r=await jr(n,[`sol-${o.n}.py`]);console.log(),"ENOENT"!==r?.code?(console.log(chalk.gray(mn()?" 回到竞技场。":" Back in the arena.")),console.log()):Mr()})(o):"recall"===e&&await(async e=>{const o=Tr(e);if(!o)return;if(!bt)return void Qn();const{p:t,n:n}=o,r=G(process.cwd(),"icoa-contest"),s=`${mt.id}-phase${Ln.phase}-g${Ln.data.slot}-archived-`;let l=null;try{for(const e of q(r))e.startsWith(s)&&(!l||e>l)&&(l=e)}catch{}const a=l?G(r,l,`sol-${n}.py`):null;if(!a||!M(a))return void console.log(chalk.gray(mn()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=O(a,"utf-8"),c=`${Ln.phase}-${Ln.data.slot}-${n}`,d=Math.min(3,(qr.get(c)??0)+1);console.log(chalk.gray(mn()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await $e({token:yt,phase:Ln.phase,slot:Ln.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:mn()?"zh":"en"});if(g.ok){qr.set(c,d),console.log();for(const e of gt(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(mn()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(mn()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(mn()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(mn()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(mn()?" (花名册: /list)":" (roster: /list)")),void Wt()}if("contest"===o||"/contest"===o)return Ar(),void Wt();const a="lang"===o||/^lang\s+\S+$/.test(o),i=ht.has(o);if(!(/^\/?python(?:3)?(?:\s+(setup|install|status))?$/i.test(o.trim())||"submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||"restart"===o||a||i||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(mn()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void Wt()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(mn()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Wt()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(It.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}Ot=!0;const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Ot=!1,It.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void Wt()}if("ai4ioai"===o||"/ai4ioai"===o)return await L()&&(cn=!0),void Wt();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!bt)return Qn(),void Wt();an||(an=!0,console.log(),console.log(chalk.bold.cyan(mn()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(mn()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(mn()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),mn()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")),console.log(chalk.gray(mn()?" 💡 一次好的研究通常会向 AI 要到 3 段可运行的 Python 代码;建议每张卡都用 ":" 💡 A good research run usually asks the AI for 3 runnable Python snippets; for each card, ")+chalk.bold.green("/py")+chalk.gray(mn()?" 新建草稿贴进去跑(":" a fresh scratch file and run them (")+chalk.bold.green("/pylist")+chalk.gray(mn()?" 看草稿)。":" lists them).")),console.log(chalk.yellow(mn()?" ↩ 重要:退出 AI 模式只需输入 ":" ↩ Important: to leave AI mode just type ")+chalk.bold.white("back")+chalk.yellow(mn()?" 或 ":" or ")+chalk.bold.white("quit")+chalk.yellow(mn()?",就回到卡片。":" — you are back on the card.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Jt=!0;const e=Tn(At.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(mn()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(mn()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(mn()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · back / quit = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · back / quit = back to card")),console.log(chalk.gray(mn()?" 💡 通常要向 AI 要到 3 段 Python 代码 · back 回卡片后 /py 新建草稿运行 · /pylist 看草稿":" 💡 Usually ask for 3 Python snippets · back to the card, then /py a new scratch to run · /pylist lists them")),console.log(),void Wt()}return await Xn(n,t?"fast":"deep"),void Wt()}if(!Xt&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!bt)return Qn(),void Wt();const e=Tn(At.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(mn()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(mn()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(mn()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(mn()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(mn()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(mn()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(mn()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),un=!0,void Wt()}const p=!Xt&&"honors"===rn&&/^[1-3]$/.test(o);if(!Xt&&rn&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(mn()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(mn()?" ↩ back 回上一层":" ↩ back goes up one level")),void Wt();if(!Xt&&(p||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!bt)return Qn(),void Wt();const e=/^\/?view ([1-3])$/.exec(o),t=p?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Qt=!0;try{console.log();const o=await ve({token:yt,cardNumber:At.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(mn()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&hn.delete(At.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&hn.add(At.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(mn()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${At.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${At.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(mn()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(mn()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Vn(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(mn()?" (无可显示的提问)":" (no questions to show)"))}console.log(),rn="view",console.log(chalk.gray((mn()," "))+chalk.bold.cyan("↩ back")+chalk.gray(mn()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Qt=!1}})(t),void Wt()}const m=o.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(m&&!Xt&&!Vt){const{certificateLines:e}=await import("../lib/learn-door.js"),{certifiable:o,certificateIntroLines:t}=await import("../lib/learn-certificate.js"),n=mn(),r=ft?null:await y(yt,"me"),s=r&&"ok"===r.kind?r.profile:null,l=o(s),a=(m[2]??"").toLowerCase();console.log();const i=a?l.find(e=>e.curriculum_id.toLowerCase()===a||e.curriculum_id.toLowerCase().startsWith(a)):l.find(e=>e.curriculum_id===mt.id)??(1===l.length?l[0]:void 0);if(!i){for(const o of e(s,n))console.log(o);return l.length>1&&console.log(chalk.gray(" ")+chalk.bold.green("certificate <track>")+chalk.gray(n?" 签发其中一门。":" to issue one.")),console.log(),void Wt()}for(const e of t(i,n))console.log(e);return console.log(chalk.gray(n?" (空行或 back 取消)":" (blank line or back cancels)")),console.log(),console.log(chalk.bold.cyan(n?" 证书上的名字:":" Name on the certificate:")),qt={cid:i.curriculum_id,tok:i.token,first:null},void Wt()}const $=o.match(/^\/?(story|credits|fin)(?:\s+(\S+))?$/);if($&&!Xt&&!Vt){const e=($[2]??"").trim();return await Pn("story"===$[1]?e||"list":e||null,!0),void Wt()}if(/^\/?(?:type|typing)(?:\s|$)/i.test(o))return await ko(o.trim().split(/\s+/).slice(1)),void Wt();if("me"===o||"/me"===o||"profile"===o||"/profile"===o||"my profile"===o){const e=mn();if(ft)return console.log(),console.log(chalk.gray(e?" 档案属于正式 learn token — demo 是大家共用的。":" Profiles belong to full learn tokens — the demo is shared by everyone.")),console.log(),void Wt();console.log(chalk.gray(e?" 正在取档案…":" Loading your profile…"));const o=await y(yt);return"ok"===o.kind?f(o.profile,e,ct()):"offline"===o.kind?(console.log(chalk.yellow(e?" 现在连不上 learn 服务器 — 档案住在服务端,联网后再试 me。":" Cannot reach the learn server right now — your profile lives there; try me again online.")),console.log()):(console.log(chalk.yellow(` ${"demo"===o.kind?e?"demo token 没有档案":"No profile for a demo token":o.message}`)),console.log()),void Wt()}if("/honors"===o||"honors"===o)return ft?(console.log(),console.log(chalk.gray(mn()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Wt()):(await or(),void Wt());const b=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(b)return _("learn-py: pylist"+(b[1]?` ${b[1]}`:"")),Yr(b[1]),void Wt();const w=/^\/?py(?:\s+(\S+))?$/.exec(o);if(w)return await zr(w[1]),void Wt();if(/^\/?sh$/.test(o))return Qr(),void Wt();const k=/^\/?python(?:3)?(?:\s+(setup|install|status))?$/i.exec(o.trim());if(k){_(`learn-python: ${k[1]??"status"}`);const{runSetup:e,printStatus:o}=await import("./python.js"),t=(k[1]??"").toLowerCase();return"setup"===t||"install"===t?await e():o(),console.log(chalk.gray(mn()?" ↩ back 回卡片 · ":" ↩ back to the card · ")+chalk.bold.green("/py")+chalk.gray(mn()?" 打开草稿本":" opens the scratchpad")),console.log(),void Wt()}if("menu"===o||"menu confirm"===o){if(Lt?.detach(),vn.length>0&&await Promise.race([Promise.allSettled(vn),new Promise(e=>setTimeout(e,3e3))]),It.removeAllListeners("line"),Et(),St||!xn){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(St?It:void 0),An()}else It.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===rn)return await or(),void Wt();if("honors"===rn)return rn=null,Kn(),void Wt();if(Lt?.detach(),vn.length>0&&await Promise.race([Promise.allSettled(vn),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${At.streakDays} day(s)`)),console.log(),St){It.removeAllListeners("line"),Et();for(const e of Pt)It.on("line",e);It.prompt(),An()}else It.removeAllListeners("line"),It.close();return}if(te(o))return vt?pt(ee(vt,mn(),ct(),"T0"===ne().tier),!!vt.completedAt):(console.log(chalk.gray(mn()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void Wt();if("status"===o||/^status\s+/.test(o)){const e=o.slice(6).trim().toLowerCase(),t="all"===e?"all":/^\d+$/.test(e)?Number(e):"current";if(Rn){const[,e]=await Promise.all([Bn(),Z(mt.id,yt,!0)]);e&&Object.assign(mt,e)}return Ho(mt,At,{gate:En,gated:wt,focus:t,posForSlot:Le}),void Wt()}if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await Z(mt.id,yt,!0);return void(e?(Object.assign(mt,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Kn()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),Wt()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(bo().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Wt();const t=mt.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,s=r?n:"en";return wo({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Ut=null,Rt=null,Dt=null,Kt(),pn=!1,un=!1,await er(),void Wt()}const v=o.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(v&&!Xt&&!Vt&&null===nn&&g.test(o)){const e=mn(),o=await u(yt);if("ok"===o.kind)for(const t of h(o.log,e,"T0"===ne().tier,e?"Enter 继续学习":"Enter to keep learning"))console.log(t);else console.log(chalk.yellow("offline"===o.kind?e?" 离线 — 专注记录在服务端,联网后再看。":" Offline — the focus log lives on the server; try again when connected.":"demo"===o.kind?e?" Demo token 是共享的,没有专注记录。":" Demo tokens are shared — no focus log.":e?` 专注记录加载失败:${o.message}`:` Could not load the focus log: ${o.message}`));return console.log(),void Wt()}if(v&&!Xt&&!Vt&&null===nn){const e=(v[2]??"").trim(),o=mn(),t=`${a}–${l}`+(o?`,${i} 的倍数`:`, steps of ${i}`);if("off"===e||"stop"===e||"end"===e||"cancel"===e||"关"===e)return void(Lt?.stop()||(console.log(chalk.gray(o?" 没有进行中的专注。开始一场:":" No focus session running. Start one: ")+chalk.bold.green("focus 30")),Wt()));if(Lt?.active)return console.log(chalk.yellow(" ⏱ ")+chalk.white(o?`专注进行中 · 还剩 ${Lt.remainingMin()} 分钟`:`focus running · ${Lt.remainingMin()} min left`)+chalk.gray(o?" · 提前结束:":" · end early: ")+chalk.bold.green("focus off")),void Wt();if(""===e||"?"===e||"help"===e)return console.log(),console.log(chalk.bold.white(o?" ⏱ 专注一场":" ⏱ Focus session")),console.log(chalk.gray(o?` 多少分钟?(${t}) 例如 `:` How long? (${t}) e.g. `)+chalk.bold.green("focus 30")),console.log(chalk.gray(o?" 每 10 分钟轻提醒一次,到点给你一份这段时间的学习报告。":" A soft reminder every 10 min, and a report on what you did when time is up.")),console.log(),void Wt();const n=d(e);if(!n)return console.log(chalk.yellow(o?` 看不懂「${e}」。`:` Didn't understand "${e}". `)+chalk.gray(o?`请输分钟数(${t}),例如 `:`Type minutes (${t}), e.g. `)+chalk.bold.green("focus 30")),void Wt();if("ok"!==n.note){const t="min"===n.note?o?`最少 ${a}`:`min is ${a}`:"max"===n.note?o?`最多 ${l}`:`max is ${l}`:o?`取最近的 ${i} 的倍数`:`rounded to the nearest ${i}`;console.log(chalk.gray(o?` 你输入 ${e} → ${t},用 ${n.min}`:` you typed ${e} → ${t}, using ${n.min}`))}return Lt?.start(n.min),console.log(),console.log(chalk.yellow(" ⏱ ")+chalk.bold.white(o?`专注 ${n.min} 分钟开始`:`Focus ${n.min} min — go`)+chalk.gray(o?" · 每 10 分钟一次轻提醒 · 提前结束:":" · soft reminder every 10 min · end early: ")+chalk.bold.green("focus off")),console.log(),void Wt()}if(ht.has(o)){const e=ht.get(o),t=at(bo()),n=e=>{const o=["normal","wide","wider","widest"].filter(o=>o!==e);return mn()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((mn()?"normal"===e?" 已是标准 64 列。":ct()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${ct()} 列,上限 ${it(e)})。`:"normal"===e?" Already at the standard 64 cols. ":ct()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${ct()} cols, cap ${it(e)}). `)+n(e))),void Wt()):(wo({learnWidth:e,learnWide:"normal"!==e}),lt(e),"normal"!==e&&ct()<=64?(console.log(chalk.yellow(mn()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((mn()?` 设置已记住(${e},上限 ${it(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${it(e)} cols) and applies once you widen the window. `)+n(e))),void Wt()):(console.log(chalk.green(" ✓ ")+chalk.gray((mn()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${ct()} 列,上限 ${it(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${ct()} cols, cap ${it(e)}). `)+n(e))),Ut=null,Rt=null,Dt=null,Kt(),pn=!1,un=!1,await er(),void Wt()))}if("sim"===o){const e=Tn(At.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=F(H(import.meta.url)),o=[G(e,"..","..","panda","mujoco-launcher.py"),G(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(M(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void Wt()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Wt())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=At.currentCard,t=At.bookmarks.includes(e),n="bookmark"!==o;return n?At.bookmarks=At.bookmarks.filter(o=>o!==e):t||At.bookmarks.push(e),xo(At),n?console.log(t?chalk.gray(mn()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(mn()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(mn()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(mn()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Wt()}const A=re(o);if(A){const e="current"===A.target?At.currentCard:A.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>mt.cards.length))return console.log(chalk.yellow(mn()?` 本课共 ${mt.cards.length} 张,请输 r 1–${mt.cards.length} 或 r all。`:` This course has ${mt.cards.length} cards. Try r 1–${mt.cards.length} or r all.`)),console.log(),void Wt();for(const o of se(kt,kn,e,mn(),ct()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?kt:kt.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(kt=kt.map(e=>o.includes(e.id)?{...e,seen:!0}:e),st(kt),vn.push(J(yt,{card_number:At.currentCard,event_type:"viewed"},o).catch(()=>{}))),void Wt()}if("e"===o||"memo"===o)return Yt=At.currentCard,console.log(chalk.gray(mn()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(mn()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void Wt();if("back"===o||"b"===o&&null===Rt)return"view"===rn?(await or(),void Wt()):"honors"===rn?(rn=null,Kn(),void Wt()):(At.currentCard>1&&(At.currentCard-=1),Rt=null,Dt=null,Ut=null,xo(At),Kn(),void Wt());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Rn)return console.log(chalk.yellow(mn()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Wt();if(!e){const e=await Se(yt),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(mn()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(mn()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(mn()?` 这台电脑上有 ${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(mn()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(mn()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(mn()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(mn()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(mn()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(mn()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(mn()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Wt()}if(/^\d{1,2}$/.test(e)){const o=await Te(yt,Number(e));return o.ok&&o.data?(dr(o.data),await Bn(),void Wt()):(console.log(chalk.red(` ✗ ${o.message||(mn()?"关联失败":"Link failed")}`)),void Wt())}const t=await Pe(yt,e);return t.ok&&t.data?(dr(t.data),await Bn(),void Wt()):(console.log(chalk.red(` ✗ ${t.message||(mn()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(mn()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Wt())}if("contest"===o||"/contest"===o||"arena"===o||"contest start"===o||"/contest start"===o||"contest status"===o||"contest reset"===o||"contest restart"===o||"restart"===o||/^\/?contest [1-9]$/.test(o)){if(!Rn)return console.log(chalk.yellow(mn()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Wt();let e=zn(At.currentCard),t=null;const n="contest restart"===o||"restart"===o;if(n&&(!Xt||!Ln||hr()))return console.log(chalk.gray(mn()?" restart 只在赛场里用(重开当前这一组)。在卡片上用 contest <组号> 开一组,contest reset 放弃整个阶段的计时。":" restart works inside an arena (it reopens the current group). From the card: contest <n> opens a group · contest reset abandons the whole phase.")),void Wt();if(n&&Ln){const o=Ln.phase,n=Ln.data.slot,r=await Ce(yt,o,n);if(!r.ok&&"no_active_session"!==r.code)return console.log(chalk.red(` ✗ ${r.message||"reset failed"}`)),void Wt();pr(o,n),console.log(chalk.yellow(mn()?` 🔄 第 ${n} 组重开 — 全新计时、全新模板。`:` 🔄 Group ${n} restarted — fresh clock, fresh templates.`)+chalk.gray(mn()?" 只有计时内写的才算数:从头再写一遍,这正是练习。":" Only work written on the clock counts — write it again from scratch; that is the practice.")),Ln=null,Xt=!1,Sr=null,e=o,t=n}if("contest reset"===o&&Xt&&hr()){const e=Ln.phase,o=Ln.data.slot,t=await Ce(yt,e,o);if(t.ok){console.log(chalk.yellow(mn()?" 已放弃本卡练习计时。回卡片后输入 practice <题号> 重新开始。":" Practice attempt abandoned. From the card, practice <n> starts a fresh one."));const t=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),n=G(process.cwd(),"icoa-contest",`${mt.id}-phase${e}-g${o}`);if(M(n))try{W(n,`${n}-archived-${t}`),console.log(chalk.gray(mn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(mn()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}Ln=null,Xt=!1,Sr=null,Kn()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void Wt()}if("contest reset"===o){const o=await Ce(yt,e);if(o.ok){console.log(chalk.yellow(mn()?` 已放弃本阶段(${e})所有计时。输入 contest <组号> 重开某一组(裸 contest 会开第一个未过的组)。`:` All live attempts in phase ${e} abandoned. Type contest <n> to reopen a group (bare contest opens the first unpassed one).`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),t=G(process.cwd(),"icoa-contest"),n=new RegExp(`^${mt.id}-phase${e}-g(\\d+)$`),r=(M(t)?q(t):[]).map(e=>({name:e,m:n.exec(e)})).filter(({m:e})=>e&&Number(e[1])<ur).map(({name:e})=>e).sort();for(const e of r){const n=G(t,e);try{W(n,`${n}-archived-${o}`),console.log(chalk.gray(mn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(mn()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(mn()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),Ln=null,Xt=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Wt()}const r=null!=t?String(t):/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(mn()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(yt,e,r?parseInt(r,10):void 0);if(!s.ok||!s.data){if("no_contest"===s.code){const o=mt.modules.find(o=>o.number===e)?.cardRange,t=!!o&&o[1]-o[0]+1>12;console.log(chalk.gray(t?mn()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(360 层第二阶段标准设计中)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (360-tier second-stage standard in design).`:$n?mn()?` 本阶段(${e})的 3 场判分赛制作中 — 很快更新;赛场挂在卡 4 / 8 / 12,3 场全过解锁下一阶段(本轨无 research)。`:` Phase ${e}'s 3 judged arenas are in production — coming soon; they hang on cards 4 / 8 / 12 and all 3 unlock the next phase (no research on this track).`:mn()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(标准范式:3 场练习赛 + 3 卡研究)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (standard: 3 arenas + 3 research cards).`))}else console.log(chalk.red(` ✗ ${s.message||"contest unavailable"}`));return void Wt()}const l=s.data,a=G(process.cwd(),"icoa-contest",`${mt.id}-phase${e}-g${l.slot}`);if(!l.resumed&&M(a)&&q(a).some(e=>/^sol-\d+\.[a-z]+$/.test(e))){const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{W(a,`${a}-archived-${e}`),console.log(chalk.gray(mn()?" 📦 上一场的答题文件已归档: ":" 📦 Previous window archived: ")+chalk.gray(`${a}-archived-${e}`)),console.log(chalk.gray(mn()?" 新场次全新模板 — 计时窗口内写的才算数。":" Fresh window, fresh templates — only work done on the clock counts."))}catch{console.log(chalk.yellow(mn()?` ⚠ 归档失败(比赛照常): ${a}`:` ⚠ Could not archive (contest still fine): ${a}`))}}N(a,{recursive:!0});const i=Ln&&Ln.phase===e&&Ln.data.slot===l.slot?Ln.tried:new Set;Ln&&Ln.phase===e&&Ln.data.slot===l.slot&&Ln.data.attempt===l.attempt||(Mn.clear(),Nn.clear()),Ln={phase:e,dir:a,data:l,tried:i},cr(l,a),Wn(e,l.slot,a),Xt=!0,Ar(),console.log(chalk.gray(mn()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(a));const c=l.problems.findIndex(e=>!l.solved.includes(e.id))+1||1,d=nr&&!rr?qe:c;return console.log(chalk.white(mn()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${d}`)+chalk.gray(d===qe?mn()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":mn()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Wt()}const S=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec($n&&/^[1-9]$/.test(o)?`practice ${o}`:o);if(S){const e=Tn(At.currentCard),o=mr(e);if(!o)return console.log(chalk.gray(mn()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void Wt();if(!Rn)return console.log(chalk.yellow(mn()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void Wt();if(!S[1])return console.log(),$r(e),console.log(chalk.gray(mn()?" 用法: ":" Usage: ")+chalk.bold.green(mn()?"practice <题号>":"practice <n>")+chalk.gray(mn()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void Wt();const t=parseInt(S[1],10);return!Number.isInteger(t)||t<1||t>o.length?(console.log(chalk.yellow(mn()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void Wt()):(await($n?(async(e,o,t)=>{const n=zn(e.number),r=ur+e.number;console.log(chalk.gray(mn()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(yt,n,r,!0);if(!s.ok||!s.data)return void("no_contest"===s.code?console.log(chalk.gray(mn()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${s.message||"practice unavailable"}`)));const l=s.data;if(0===l.problems.length)return void console.log(chalk.gray(mn()?" 本卡练习题库是空的。":" This card practice set is empty."));const a=new Map(l.problems.map(e=>[e.id,e])),i=[];for(const e of o){const o=a.has(yr(e.py_id))?yr(e.py_id):a.has(e.py_id)?e.py_id:null;o&&(i.push(a.get(o)),a.delete(o))}for(const e of l.problems)a.has(e.id)&&i.push(e);l.problems=i;let c=Dn.get(r);c||(c=new Set,Dn.set(r,c));for(const e of l.solved)c.add(e);nn={card:e,phase:n,slot:r,data:l,idx:Math.min(Math.max(t,1),l.problems.length)-1,answers:[],tries:0},_(`learn-fillpractice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(mn()?` ⚡ 快速填空 — 第 ${e.number} 张卡`:` ⚡ Quick fill — card ${e.number}`)+chalk.gray(mn()?"(敲答案 → 自动判分 · 不计分)":" (type the blank → auto-judged · unscored)")),console.log(chalk.gray(mn()?` ⏱ 每次练习 ${l.duration_minutes} 分钟 · 剩 ${je(l.deadline)??"0:00"} · 到时敲 back 再 practice 重开`:` ⏱ ${l.duration_minutes}-minute practice window · ${je(l.deadline)??"0:00"} left · when it ends: back, then practice again`)),_r()})(e,o,t):(async(e,o,t)=>{const n=zn(e.number),r=ur+e.number;console.log(chalk.gray(mn()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(yt,n,r,!0);if(!s.ok||!s.data)return void("no_contest"===s.code?console.log(chalk.gray(mn()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${s.message||"practice unavailable"}`)));const l=s.data;if(0===l.problems.length)return void console.log(chalk.gray(mn()?" 本卡练习题库是空的。":" This card practice set is empty."));const a=new Map(l.problems.map(e=>[e.id,e])),i=[];for(const e of o){const o=a.has(yr(e.py_id))?yr(e.py_id):a.has(e.py_id)?e.py_id:null;o&&(i.push(a.get(o)),a.delete(o))}for(const e of l.problems)a.has(e.id)&&i.push(e);l.problems=i;let c=Dn.get(r);c||(c=new Set,Dn.set(r,c));for(const e of l.solved)c.add(e);const d=G(process.cwd(),"icoa-contest",`${mt.id}-phase${n}-g${r}`);N(d,{recursive:!0});const g=Ln&&Ln.phase===n&&Ln.data.slot===r?Ln.tried:new Set;Ln&&Ln.phase===n&&Ln.data.slot===r&&Ln.data.attempt===l.attempt||(Mn.clear(),Nn.clear()),Ln={phase:n,dir:d,data:l,tried:g},cr(l,d),Xt=!0,Sr=null,_(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(mn()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(mn()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(mn()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(d)),console.log(chalk.gray((mn()," ↩ "))+chalk.bold.green("back")+chalk.gray(mn()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),Ir(String(Math.min(t,l.problems.length)))})(e,o,t)),void Wt())}if("submit"===s)return console.log(chalk.yellow(mn()?" 用法: ":" Usage: ")+chalk.bold.green(mn()?"submit <题号>":"submit <n>")+chalk.gray(mn()?" 例如 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)")),Ln||console.log(chalk.gray(mn()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Wt();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!Ln)return console.log(chalk.yellow(mn()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Wt();const n=Ln.data.problems,r=parseInt(o,10);if(nr&&r===qe)return console.log(chalk.gray(mn()?" 热身题不判分 — /run 0 就是它的完整判定(10 个用例全在本机)。":" The warm-up is not judged — /run 0 IS its full check (all ten cases, on your machine).")),console.log(chalk.white(mn()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(mn()?" 开始。":".")),void Wt();if(Number.isInteger(r)&&r>=1&&r<=n.length&&!n.some(e=>e.id===o)&&(o=n[r-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(mn()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Wt();const l=n.findIndex(e=>e.id===o)+1,a=t||G(Ln.dir,ir(l,n[l-1]));let i;try{i=O(a,"utf-8")}catch{return console.log(chalk.red(mn()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Wt()}const c=new I(yt);c.start();const d=Mn.get(l),g=Nn.get(l),u=d&&!B(d)?{...d,...g?{samples:g.list}:{},...g&&g.dropped>0?{samplesDropped:g.dropped}:{}}:void 0,h=await xe(yt,Ln.phase,o,i,Ln.data.slot>=ur?Ln.data.slot:void 0,u);if(c.stop(),!h.ok||!h.data)return"no_active_session"===h.code&&Ln.data.slot>=ur?wr(Ln.data.duration_minutes):"no_active_session"===h.code?(pr(Ln.phase,Ln.data.slot),console.log(chalk.yellow(mn()?" ⏱ 时间到 — 这一场结束了,判分机已停表。":" ⏱ Time is up — this attempt is over; the judge stopped the clock.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(mn()?" 重开这一组:全新计时 + 全新模板(旧文件已归档)。只有计时内写的才算数 — 从头再写一遍,这正是练习。":" reopens this group: fresh clock + fresh templates (old files archived). Only work written on the clock counts — write it again from scratch; that is the practice.")),console.log(chalk.gray(mn()?" ↩ back 回卡片":" ↩ back returns to the card"))):(console.log(chalk.red(` ✗ ${h.message||"judging failed"}`)),console.log(chalk.gray(mn()?" 判分服务异常?敲 memo 一句话告诉我们 — 不打断比赛计时。":" Judge acting up? Type memo — one line reaches us, the clock is unaffected."))),void Wt();const p=h.data;if(p.already_ac)console.log(chalk.green(mn()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===p.verdict){if(console.log(ho("AC",{isZh:mn(),passed:p.passed_tests??p.total_tests??null,total:p.total_tests??null,ms:p.time_ms??null})),Ln.data.solved.includes(o)||Ln.data.solved.push(o),Ln.tried.delete(o),hr()){let e=Dn.get(Ln.data.slot);e||(e=new Set,Dn.set(Ln.data.slot,e)),e.add(o);const t=await _e({token:yt,curriculumId:mt.id,cardNumber:At.currentCard}),n=t.ok?t.practiceBoard:null;if(n?.mine){const e=n.top[0],o=e&&!e.me?chalk.gray(mn()?` · 榜首 ${e.name||"Rank 1"} ${e.ac} AC`:` · leader ${e.name||"Rank 1"} at ${e.ac} AC`):chalk.bold.yellow(mn()?" · 全场第一!":" · phase leader!");console.log(chalk.white(mn()?` ⚔ Phase ${n.phase} Practice AC: `:` ⚔ Phase ${n.phase} practice AC: `)+chalk.bold.yellow(`${n.mine.ac}`)+chalk.gray(`/${n.problems_total}`)+chalk.gray(mn()?` · 第 ${n.mine.rank} 名`:` · rank ${n.mine.rank}`)+o)}}}else Ln.tried.add(o),console.log(ho(p.verdict,{isZh:mn(),passed:p.passed_tests??null,total:p.total_tests??null,failedTest:p.test??null,ms:p.time_ms??null})),Zt||(Zt=!0,console.log(chalk.gray(mn()?" 觉得题面有误或判分不对?敲 memo 一句话 — 不打断比赛计时。":" Statement wrong or judging looks off? Type memo — one line, the clock is unaffected.")));p.late&&console.log(chalk.yellow(mn()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const y=je(p.deadline||""),m=hr();if(console.log(chalk.white(m?mn()?` 本卡练习: 已过 ${p.ac_count}/${p.n} 题(不计分)`:` Card practice: ${p.ac_count}/${p.n} solved (unscored)`:mn()?` 本组进度: 已过 ${p.ac_count} 题 · 过 ${p.need} 题过关(共 ${p.n} 题)`:` Group progress: ${p.ac_count} solved · ${p.need} needed to pass (${p.n} problems)`)+(y?chalk.gray(` · ⏱ ${y}`):"")),m&&!p.late&&p.ac_count>=p.n)console.log(chalk.bold.green(mn()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(mn()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!p.passed||p.late||m){if(!p.late){const e=n.findIndex(e=>!Ln.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(mn()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${tr(n[e])}`))}}else{const e=Math.max(0,p.n-p.ac_count);if(0===e)console.log(chalk.bold.green(mn()?` 🎉 满分!${p.n}/${p.n} 全部 AC — 这组题你已经彻底拿下。`:` 🎉 Perfect! ${p.n}/${p.n} AC — you have completely cleared this group.`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(mn()?" 回到上一层(卡片),继续往下学;":" returns to the previous layer (the card) — keep going from there; ")+chalk.bold.green("contest")+chalk.gray(mn()?" 看本阶段其他赛场。":" lists the other arenas of this phase."));else{console.log(chalk.bold.green(mn()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")+chalk.yellow(mn()?` 还剩 ${e} 题 — 全部做完就是满分 ${p.n}/${p.n},别停在这里。`:` ${e} more to go — solve them all for a perfect ${p.n}/${p.n}, don't stop here.`));const o=n.findIndex(e=>!Ln.data.solved.includes(e.id));o>=0&&console.log(chalk.gray(mn()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${o+1}`)+chalk.gray(` ${tr(n[o])}`)+chalk.gray(mn()?" · ↩ back 回卡片":" · ↩ back returns to the card"))}await Bn()}return void Wt()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>mt.totalCards)return console.log(chalk.yellow(` Card number must be 1..${mt.totalCards}. Try: `)+chalk.bold.green("card 1")),void Wt();const n=await Gn(t);return n?(console.log(n),void Wt()):(At.currentCard=t,Rt=null,Dt=null,Ut=null,xo(At),Kn(),void Wt())}if(null!==Ut&&["y","yes","n","no"].includes(o)){const e=Tn(Ut);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-yn;Lt?.noteCheck(n,r),jo(At,e.number),Lo(At,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),xo(At);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),vn.push(J(yt,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Ut=null,jn(),e.solution&&e.solution.length>0)return void Wt();if(fr())return void Wt();if(At.currentCard<mt.totalCards){const e=At.currentCard,o=await Gn(e+1);if(o)return await Hn(e),console.log(o),void Wt();At.currentCard+=1,xo(At),await Hn(e)?Zn():Kn(),Wt()}else Ko(mt,At),Pn(null,!1).then(()=>Wt()),Wt();return}}if(null!==Rt&&["a","b","c","d"].includes(o)){const e=Tn(Rt);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(Eo(At,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),jo(At,e.number),xo(At),Ro(e,t,n,At),vn.push(J(yt,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Rt=null,n)if(At.currentCard<mt.totalCards){const e=await Gn(At.currentCard+1);if(e)return console.log(e),void Wt();At.currentCard+=1,xo(At),Kn()}else Ko(mt,At),Pn(null,!1).then(()=>Wt()),Wt();else Wt();return}}if(null!==Dt){if("done"===o){const e=Tn(Dt);if(e&&"practical"===e.type)return Mo(At,e.number),jo(At,e.number),xo(At),Uo(e),Dt=null,void Wt()}if("skip"===o)return jo(At,Dt),xo(At),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Dt=null,void Wt()}const P=$n&&"skip"===o&&null===Rt&&null===Dt&&null===Ut&&null!==mr(Tn(At.currentCard));if("ok"===o||"next"===o||"continue"===o||"n"===o||P){if(P){const e=At.currentCard;Yn.add(e),Lt?.notePracticeSkipped(),console.log(chalk.gray(mn()?" ⚔ 本卡练习已跳过(有记录)。":" ⚔ Practice skipped for this card (recorded).")),J(yt,{card_number:e,event_type:"practice_skipped"}).catch(()=>{})}else if(null===Ut&&null===Rt&&null===Dt&&fr())return void Wt();if(null!==Rt)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Wt();if(null!==Dt)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Wt();if(null!==Ut)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Wt();const e=At.currentCard,o=e<mt.totalCards?await Gn(e+1):null;return o?(await Hn(e),console.log(o),void Wt()):(At.currentCard+=1,xo(At),At.currentCard>mt.totalCards?(Ko(mt,At),Pn(null,!1).then(()=>Wt())):await Hn(e)?Zn():Kn(),void Wt())}return null!==Ut?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Wt()):null!==Rt?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Wt()):null!==Dt?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Wt()):("view"===rn?console.log(chalk.gray(mn()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(mn()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(mn()?" 回卡片":" to the card")):"honors"===rn?console.log(chalk.gray(mn()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(mn()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(mn()?" 回卡片":" 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")),void Wt())};It.on("line",e=>{Xr(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.")),Wt()})}),St||It.on("close",async()=>{Lt?.detach(),vn.length>0&&await Promise.race([Promise.allSettled(vn),new Promise(e=>setTimeout(e,5e3))]),xn?An():process.exit(0)});const Vr=le(kt,mn());Vr&&(console.log(chalk.bold.cyan(` ${Vr}`)),console.log());try{Kn();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0),(async()=>{for(let e=0;e<20&&!En;e++)await new Promise(e=>setTimeout(e,250));const e=In();null!==e&&e>0&&e<=2&&(await jn(!0),Wt())})();const o=Lt?.attach(yt,mt.id,Sn);"resumed"===o&&(console.log(chalk.yellow(" ⏱ ")+chalk.white(mn()?`专注进行中 · 还剩 ${Lt.remainingMin()} 分钟 · 这条轨也算在内 · focus off 提前结束`:`focus running · ${Lt.remainingMin()} min left · this course counts too · focus off to end early`)),console.log()),Wt()}catch{if(ut("Could not render this card — the curriculum may be malformed."),St){It.removeAllListeners("line"),Et();for(const e of Pt)It.on("line",e);It.prompt()}else It.close();An()}await Cn}),yo.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),s=await Z(e),l=Date.now()-o;if(s){const e=s.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(s).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${l.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}