icoa-cli 2.19.536 → 2.19.538

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 p}from"../lib/learn-focus-log.js";import{setLearnFooterExtra as h}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 P,lazyJson as S}from"../lib/lazy-assets.js";import{JudgeWaitLine as I}from"../lib/judge-wait.js";import{ai4ioaiPromptLabel as j,handleAi4ioaiMessage as E,startAi4ioaiChat as M}from"./ai4ioai.js";import{existsSync as L,mkdirSync as N,readdirSync as q,readFileSync as O,renameSync as R,statSync as W,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 H}from"node:path";import{fileURLToPath as G}from"node:url";import{loadCurriculumById as Z,validateEAToken as K,syncProgress as J,fetchServerProgress as X,syncCardFeedback as Q,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 pe,renderSyntax as he,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 Pe,linkToken as Se,fetchGate as Ie,timeLeft as je,arenaSlotAtPos as Ee}from"../lib/learn-contest.js";import{WARMUP as Me,WARMUP_ID as Le,WARMUP_N as Ne,WARMUP_TESTS as qe,gradeWarmup as Oe,warmupEnabled as Re}from"../lib/warmup.js";import{PY_MAX_CODE_BYTES as We,PY_MAX_FILES as De,PY_TEMPLATE_EN as Ue,PY_SPOOL_BATCH as Ye,PY_TEMPLATE_ZH as Be,listScratchFiles as ze,localTimeNote as Fe,nextScratchN as He,readPyScratchSpool as Ge,scratchCodeSha as Ze,scratchDir as Ke,scratchFilePath as Je,scratchTitleOf as Xe,shrinkPyScratchSpool as Qe,spoolPyScratchEvent as Ve,startRunTimer as eo,syncPyScratch as oo}from"../lib/py-scratch.js";import{REQUIRED_PY as to,resolveRunPython as no}from"../lib/aienv.js";let ro;function so(){return void 0!==ro||(ro=no(e=>{try{return n(`${e} --version 2>&1`,{encoding:"utf-8",timeout:4e3,stdio:["ignore","pipe","pipe"]})}catch{return null}},process.platform,ao())),ro}const lo=()=>so()?.cmd??"python3";import{homedir as ao}from"node:os";import{getConfig as io,saveConfig as co}from"../lib/config.js";import{isNativeWindows as go,isWindowsBuildInWslShell as uo,whichBinary as po}from"../lib/platform.js";import{loadLearnState as ho,saveLearnState as yo,newLearnState as mo,stateFromServerEvents as fo,activateSession as $o,updateStreak as bo,markCardComplete as wo,recordMCQ as ko,recordCheck as vo,markPracticalComplete as _o,addAchievement as Co}from"../lib/learn-state.js";import{renderWelcome as Ao,renderKnowledgeCard as xo,renderMCQCard as To,renderMCQFeedback as Po,renderPracticalCard as So,renderPracticalSuccess as Io,renderSimDemoCard as jo,renderMilestone as Eo,renderArenaTaskCard as Mo,renderComingSoonCard as Lo,renderStatus as No,renderPhaseComplete as qo,renderCurriculumComplete as Oo,setLearnAiEnabled as Ro,setLearnFaqs as Wo,setLearnFooterProfile as Do,setLearnHometask as Uo,setLearnPracticeChips as Yo,setLearnPracticeCount as Bo,setLearnHonorRanks as zo,setLearnPqsViewCards as Fo,setLearnReplies as Ho,setLearnWidth as Go,resolveLearnWidth as Zo,learnWidthCap as Ko,learnW as Jo,renderHonorWall as Xo,wrapMixed as Qo}from"../lib/learn-render.js";import{printError as Vo}from"../lib/ui.js";const et=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","widest"],["wide max","widest"]]);function ot(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(no){no.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async no=>{no?.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(),no="LEARNDEMO01");let ro=no.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(ro)){const{runSprint:e}=await import("./sprint.js");return void await e()}let tt=null;const nt=/^[A-Z0-9]+DEMO01$/i.test(ro),rt=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(ro);let st=!1,lt=!1,at=[],it=null,ct=-1,dt=Promise.resolve([]);if(nt)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),dt=V(ro),tt=await Z(ro,ro,!0);else if(rt){console.log(),console.log(chalk.gray(" Validating token..."));let e=await K(ro);if(!e.ok){const o=me(ro);if(o!==ro){const t=await K(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${ro} → ${o}`)),e=t,ro=o)}}if(!e.ok)return Vo(`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 🐼"):"")),st=!0===e.aiEnabled,lt=!0===e.gated,at=e.replies??[],it=e.hometask??null,dt=V(ro),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),tt=await Z(e.curriculumId||"LEARNDEMO01",ro,!0),!tt)return Vo(`Could not open a learn curriculum for token '${ro}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${ro}`)+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 ${ro}`)+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(!tt){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Vo(`Could not reach the learn server to open ${ro}.`),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 ${ro}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Vo(`Unknown learn token: ${ro}`),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 gt=ho(),ut=!1;try{if(gt&&gt.token===ro)bo(gt);else{const e=$o(ro);if(e)gt=e,gt.totalCards=tt.totalCards,bo(gt);else{const e=await X(ro),o=e?fo(ro,tt.id,tt.totalCards,e):null;o?(gt=o,console.log(chalk.green(" ↩ ")+chalk.white((io().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()):(gt=mo(ro,tt.id,tt.totalCards),ut=!0)}}yo(gt),Ao(tt,gt,ut),function(e){if(!e)return;const o=(io().language||"en").toLowerCase().startsWith("zh"),t="T0"===ne().tier;ot(oe(e,o,Jo(),t),!!e.completedAt)}(it)}catch{return Vo("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 ${ro}`)+chalk.gray(".")),void console.log()}const pt=x(),ht=null!==pt,yt=ht?pt.listeners("line").slice():[];ht&&pt.removeAllListeners("line");const mt=ht?pt:o({input:process.stdin,output:process.stdout,terminal:!0}),ft=ht?mt.prompt:null;ht&&(mt.prompt=e.prototype.prompt);const $t=()=>{ht&&ft&&(mt.prompt=ft)};let bt=null,wt=!1,kt=!1,vt=null,_t=!1;const Ct=()=>{mt.setPrompt(Ft?chalk.bold.green(`icoa ${j()}> `):Wt?chalk.bold.magenta("icoa py> "):Rt?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(qt?"icoa learn ai> ":"icoa learn> ")),mt.prompt(),bt?.onPromptIdle()};let At=null,xt=null,Tt=null,Pt=null,St=[],It=!1,jt=null;const Et=/^(quit|exit|q|back|b|menu|home|contest(\s+(\d+|reset))?)$/i;let Mt=null,Lt=!1;const Nt=()=>{jt&&clearTimeout(jt),jt=null,St=[],It=!1,Pt=null,Mt=null};let qt=!1,Ot=!1,Rt=!1,Wt=!1,Dt=null,Ut=null,Yt=!1,Bt=0,zt=!1,Ft=!1;const Ht=new Map,Gt=()=>{let e=Ht.get(gt.currentCard);return e||(e=[],Ht.set(gt.currentCard,e)),e};let Zt=!1;const Kt=new Set;let Jt=!1,Xt=0;const Qt=()=>(io().language||"en").toLowerCase().startsWith("zh");Ro(st),Go(Zo(io())),Fo(Kt);const Vt=new Map;zo(Vt),Ho(at),Uo(it);const en="fill"===tt.practiceMode;Do("minimal"===tt.footerProfile?"minimal":"full"),Yo(e=>{const o=cn(e),t=o?Qn(o):null;if(!t)return null;const n=vn.get(Zn+e);return t.map((e,o)=>`[${o+1}]${n?.has(Xn(e.py_id))||n?.has(e.py_id)?"✅":"⬜"}`).join(" ")});const on=e=>{const o=cn(e),t=o?Qn(o):null;if(!t)return null;const n=vn.get(Zn+e);return{solved:t.filter(e=>n?.has(Xn(e.py_id))||n?.has(e.py_id)).length,total:t.length}};Bo(on);const tn=await dt;Wo(tn);const nn=[];let rn=null;const sn=new Promise(e=>{rn=e}),ln=()=>{const e=rn;rn=null,e?.()},an="1"===process.env.ICOA_LEARN_EMBEDDED,cn=e=>tt.cards.find(o=>o.number===e);bt=c();const dn={isZh:Qt,canInterrupt:()=>!(_t||Ot||qt||Rt||Wt||Ft||null!==Dt||null!==Pt||null!==Ut),lineEmpty:()=>!mt.line,clearLine:()=>{try{process.stdout.write("\r")}catch{}},prompt:Ct,currentCard:()=>gt.currentCard};h(()=>{const e=[],o=bt?.footerLine();o&&e.push(o);const t=un();return null!==t&&t>0&&t<=2&&e.push(Qt()?`🎁 还差 ${t} 项 · credits 看路线`:`🎁 ${t} to go · credits shows the road`),e.length?e.join("\n "):null});const gn=async(e,o)=>{const t=Qt();if(nt)return void console.log(chalk.gray(t?"故事属于正式 learn token。":" Stories belong to full learn tokens."));const n=await y(ro,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===tt.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(tt,gt,hn,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===tt.id?tt.name:s.curriculum_id,s.curriculum_id===tt.id?{longestStreak:gt.longestStreak,bookmarks:gt.bookmarks?.length??0}:{},t,Jo(),"T0"===ne().tier);console.log(),console.log(chalk.gray(t?" (回车跳到结尾)":" (Enter skips to the end)")),wt=!0,kt=!1;try{await k(l,()=>kt)}finally{wt=!1}if(s.curriculum_id===tt.id&&!s.credits?.completed){for(const e of w(tt,gt,hn,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()},un=()=>{if(!gt||gt.creditsShownAt||nt||!hn)return null;const e=b(tt,gt,hn);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(!gt||gt.creditsShownAt||nt)return;const o=b(tt,gt,hn);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(hn&&t>0&&t<=2&&(e||gt.creditsTeasedLeft!==t)){gt.creditsTeasedLeft=t,yo(gt);const e=Qt(),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(tt,gt,hn,e))console.log(o);console.log()}return}gt.creditsShownAt=(new Date).toISOString(),yo(gt),await gn(null,!1),Ct()};let hn=null,yn=null;const mn=new Map,fn=new Map;let $n=null;const bn=(e,o)=>$n?.[`${tt.id}:${e}:${o}`]??null;S("contest-cells.json").then(e=>{$n=e?.map??null;for(const[e,o]of Object.entries($n??{}))e.startsWith(`${tt.id}:`)&&S(o)});const wn=(e,o,t)=>{const n=bn(e,o);if(!n)return null;const r=H(t,"explore.ipynb");if(!L(r)){const e=H(P(),n);if(!L(e))return null;try{D(r,O(e))}catch{return null}}return r},kn=!ro.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(ro),vn=new Map,_n=new Map,Cn=new Set,An=async()=>{if(!kn)return;const e=await Ie(ro);if(e.ok&&e.data){hn=e.data;for(const o of e.data.practice??[]){let e=vn.get(o.slot);e||(e=new Set,vn.set(o.slot,e));for(const t of o.solved)e.add(t)}pn()}},xn=e=>{const o=tt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Tn=e=>{if(!lt||!hn)return null;const o=xn(e);if(o<=hn.unlocked_through_phase)return null;const t=hn.phases.find(e=>e.phase===hn.unlocked_through_phase),n=[chalk.yellow(Qt()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${hn.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${hn.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(Qt()?` ⚔ 练习赛 ${hn.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${hn.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(Qt()?` ⚖ 判分赛: 最好 ${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(Qt()?"、":", "),r=e.length>8?Qt()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:Qt()?" 张":"";n.push(chalk.gray(Qt()?` ✓ 逐卡自测: ${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(Qt()?` ⭐ 提问研究: ${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")},Pn=async e=>lt?null===Tn(e)?null:(await An(),Tn(e)):null;kn&&await An();const Sn=async e=>{const o=tt.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=tt.modules.find(e=>e.number===o.number+1);let n;if(st){const e=await fe({token:ro,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}kn&&await An();const r=hn?.phases.find(e=>e.phase===o.number);return qo(tt,gt,o,t,n,r),!0},In=()=>{Jt=!0,console.log(chalk.gray(Qt()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},jn=()=>{Ut=null;const e=cn(gt.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(bt?.noteCardShown(e.number,gt.cardsCompleted.includes(e.number)),e.type){case"knowledge":{const o=en&&Boolean(gt.checkResults?.[String(e.number)])&&e.check?{...e,check:void 0}:e;xo(o,tt),o.check?(Tt=e.number,Xt=Date.now()):(wo(gt,e.number),yo(gt));break}case"mcq":To(e,tt),At=e.number;break;case"practical":So(e,tt),xt=e.number;break;case"sim_demo":jo(e,tt),wo(gt,e.number),yo(gt);break;case"milestone":Eo(e,tt),Co(gt,e.badge),wo(gt,e.number),yo(gt);break;case"arena_task":Mo(e,tt),wo(gt,e.number),yo(gt);break;case"coming_soon":Lo(e,tt),wo(gt,e.number),yo(gt)}En(e.number),er(e)},En=e=>{if(!kn||!hn)return;const o=tt.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=hn.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n);if(!s)return;const l=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),l=(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?Qt()?` · 用时 ${r}`:` · in ${r}`:"")+(l?` · ${l}`:"")},a=s.perfect_runs??[],i=!!s.best&&(s.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Jo());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${Qt()?`练习赛 ${o.number}-${n}`:s.title||`PY Arena ${o.number}-${n}`}`)+(s.passed?chalk.bold.green(Qt()?" ✅ 已通过":" ✅ passed"):"")),!s.passed){if(Qt()?console.log(c+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(c+chalk.white("You learned the cards — now prove it.")),console.log(c+chalk.white("The clock starts the moment you type the command."))),console.log(c+chalk.gray(Qt()?`${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?Qt()?`(${e})`:` (${e})`:"";console.log(c+chalk.cyan(Qt()?`🔗 你另一个 token${o}已做过这组的 ${s.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens${o} solved ${s.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Qt()?" 带过来(现在不做也行)":" to carry them over (or skip)"))}1!==o.number||en||console.log(c+chalk.gray(Qt()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))}if(a.length>0)for(const e of a)console.log(c+chalk.bold.yellow(l(Qt()?"满分":"Perfect",s.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(l(Qt()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));3===n&&r?.leader&&console.log(c+chalk.white(Qt()?`🏅 本 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((Qt()," — "))+chalk.bold.green("/honors")+chalk.gray(Qt()?" 看你的位置":" shows where you stand")),console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(s.passed?chalk.gray(Qt()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Qt()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(Qt()?" 继续学习":" keep going"):chalk.gray(Qt()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(Qt()?" 日后回来整阶段重做 · 全新计时+模板(旧文件自动归档)":" come back later and redo the whole phase · fresh clock + templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Mn=()=>{ro.endsWith("DEMO01")?console.log(chalk.yellow(Qt()?" 🐼 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(Qt()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(Qt()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Ln=async(e,o)=>{if(st){bt?.noteAi("deep"===o),Ot=!0;try{console.log(),console.log(chalk.gray("deep"===o?Qt()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":Qt()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await we({token:ro,cardNumber:gt.currentCard,question:e,mode:o,history:Gt().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(Qt()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Gt().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(` (${Qt()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Qt()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Tt&&console.log(chalk.gray(Qt()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ot=!1}}else Mn()},Nn=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],qn=async()=>{Rt&&yn?dr?ur(dr):ar():Ut?await On():jn()},On=async()=>{Ot=!0;try{console.log();const e=await _e({token:ro,curriculumId:tt.id,cardNumber:gt.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Qt()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(kn&&(await An(),(e=>{const o=tt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const[t,n]=o.cardRange,r=gt.checkResults||{};let s=0,l=0,a=0;for(let e=t;e<=n;e++){const o=cn(e);null!=o?.check&&a++;const t=r[String(e)];t&&(s++,t.correct&&l++)}console.log(chalk.bold.white(Qt()?` 🧭 Phase ${o.number} 进度 — ${o.name}(卡 ${t}-${n})`:` 🧭 Phase ${o.number} progress — ${o.name} (cards ${t}-${n})`)),console.log(chalk.gray(Qt()?" 理解检查: ":" comprehension: ")+chalk.white(`${l}/${s}`)+chalk.gray(Qt()?` 答对 · ${a-s} 张未作答`:` correct · ${a-s} unanswered`));const i=hn?.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(Qt()?`未开始 · ${e.n} 题 · 过 ${e.need} 题`:`not started · ${e.n} problems · AC ${e.need}`):chalk.yellow(Qt()?`最好 ${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(` ⚔ ${Qt()?"练习赛":"arena"} ${o.number}-${e.slot}: `)+t)}const c=[];let d=0,g=0,u=0,p=0;for(let e=t;e<=n;e++){const o=on(e);o&&(g++,u+=o.solved,p+=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(Qt()?" 卡片练习: ":" practice: ")+chalk.white(`${d}/${g}`)+chalk.gray(Qt()?` 卡全完成 · ${u}/${p} 题 AC`:` cards complete · ${u}/${p} 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(Qt()?" 卡号:已过/共 — 绿 全完成 · 黄 做了一部分 · 灰 未碰":" card:solved/total — green done · yellow partial · gray untouched"))}console.log()})(gt.currentCard)),console.log(chalk.bold.white(Qt()?` 🏆 本卡实时 Top-3 — 第 ${gt.currentCard} 张`:` 🏆 Live top-3 — card ${gt.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(Qt()?" (你)":" (you)"):""))}else console.log(chalk.gray(Qt()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));if(e.mine?(Vt.set(gt.currentCard,e.mine.rank),console.log(chalk.white(Qt()?" 你: ":" You: ")+chalk.bold.yellow(Qt()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Qt()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):st&&console.log(chalk.gray(Qt()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Xo({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),e.phaseBoard){const o=e.phaseBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(Qt()?` 🏅 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(Qt()?" (还没有人有研究总分 — 第一个 /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(Qt()?`(${e.cards}/${o.cards_in_phase} 卡)`:` (${e.cards}/${o.cards_in_phase} cards)`)+(e.me?chalk.bold.magenta(Qt()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(Qt()?` 总分 ${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(Qt()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.total}`)+chalk.gray(Qt()?`(${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&&st&&console.log(chalk.gray(Qt()?" 你: 还未计入 — /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(Qt()?` ⚔ 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(Qt()?" (还没有人 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(Qt()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(Qt()?` 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(Qt()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.ac} AC`)+chalk.gray(Qt()?` · 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` · rank ${o.mine.rank} of ${o.mine.entrants}`)):o.mine||console.log(chalk.gray(Qt()?" 你: 还未计入 — 在有 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(Qt()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Qt()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Qt()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Ut="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Qt()?" 返回卡片":" returns to the card")),console.log()}finally{Ot=!1}},Rn=e=>Qt()&&e.title_zh||e.title,Wn=Re(tt.id);let Dn=!1;const Un=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of Qo(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Yn={cpp:"cpp",java:"java",go:"go"},Bn=e=>e?.lang&&Yn[e.lang]?e.lang:"python",zn=(e,o)=>{const t=Bn(o);return`sol-${e}.${"python"===t?"py":Yn[t]}`},Fn=(e,o)=>{const t=[...Wn?[{p:Me,n:Ne}]:[],...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=Wn&&s===Ne,a=l?`══ ${t.title} ══`:`══ ${e.title||"PY Arena"} · ${t.title} ══`;for(const e of["py",...Object.values(Yn)]){const l=H(o,`sol-${s}.${e}`);if(!L(l))continue;const i=O(l,"utf-8").split("\n",1)[0]??"",c=/^(?:#|\/\/) (══ .+ ══)\s*$/.exec(i);if(c&&c[1]!==a)try{R(l,`${l}.archived-${n}`),r++;const e=H(o,`sample-${s}.txt`);L(e)&&!(t.samples??[])[0]&&R(e,`${e}.archived-${n}`)}catch{}}const i=(t.samples??[])[0];i&&D(H(o,`sample-${s}.txt`),i.in.endsWith("\n")?i.in:`${i.in}\n`);const c=H(o,zn(s,t));if(L(c))return;const d=[l?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Un(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 Qo(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"===Bn(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(Qt()?` 📦 本组题目已更换 — ${r} 个旧题答题文件已归档为 *.archived-${n},新题文件已就位`:` 📦 This group's problems changed — ${r} old solution file(s) archived as *.archived-${n}, fresh files written`))},Hn=e=>{console.log(),console.log(chalk.bold.green(Qt()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(Qt()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Gn=e=>e.id===Le?Dn?"✅":"⬜":yn.data.solved.includes(e.id)?"✅":yn.data.carried?.includes(e.id)?"✅↗":yn.tried.has(e.id)?"❌":"⬜",Zn=100,Kn=()=>!!yn&&yn.data.slot>=Zn,Jn=(e,o)=>{const t=H(process.cwd(),"icoa-contest",`${tt.id}-phase${e}-g${o}`);if(!L(t))return;const n=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{R(t,`${t}-archived-${n}`),console.log(chalk.gray(Qt()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${n}`))}catch{console.log(chalk.yellow(Qt()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (restart still fine): ${t}`))}},Xn=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,Qn=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},Vn=()=>{if(!en)return!1;const e=cn(gt.currentCard),o=e?Qn(e):null;if(!e||!o||Cn.has(e.number))return!1;const t=Zn+e.number,n=vn.get(t),r=_n.get(t),s=o.map((e,o)=>{return t=e.py_id,Boolean(n?.has(Xn(t))||n?.has(t)||r?.has(Xn(t))||r?.has(t))?0:o+1;var t}).filter(e=>e>0);return 0!==s.length&&(console.log(chalk.yellow(Qt()?` ⚔ 这张卡还有 ${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(Qt()?" 开始,或 ":" to start, or ")+chalk.bold.yellow("skip")+chalk.yellow(Qt()?" 跳过本卡练习。":" to skip this card's practice.")),!0)},er=e=>{const o=Qn(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=vn.get(Zn+e.number);console.log(chalk.bold.yellow(Qt()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(Qt()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(Xn(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(Qt()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},or=e=>e.split("\n").filter(e=>!e.trim().startsWith("#")).join("\n").split("____").length-1,tr=e=>{console.log(chalk.yellow(Qt()?` ⏱ 每次练习 ${e} 分钟,这次的时间到了。`:` ⏱ Each practice window is ${e} minutes — this one has run out.`)),console.log(chalk.gray(Qt()?" 敲 ":" Type ")+chalk.bold.green("back")+chalk.gray(Qt()?" 回卡片,再敲 ":" for the card, then ")+chalk.bold.green("practice 1")+chalk.gray(Qt()?" 重新开始(重新计时)。":" to restart with a fresh clock."))},nr=()=>Dt?Dt.data.problems[Dt.idx]??null:null,rr=()=>{const e=nr();if(!Dt||!e)return;const o=or(e.starter??""),t=Dt.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(Qt()?` 空${t}/${o}`:` blank ${t}/${o}`)+chalk.gray(" · ")+chalk.white(n)),console.log(chalk.gray(Qt()?" ▸ 敲答案后回车(back 回卡片)":" ▸ type the answer, press Enter (back = card)"))},sr=()=>{const e=nr();if(!Dt||!e)return;const o=Qt()&&e.title_zh?e.title_zh:e.title;console.log(),console.log(chalk.bold.yellow(` ⚡ ${Qt()?"练习":"Practice"} ${Dt.idx+1}/${Dt.data.problems.length} · ${o}`));const t=((Qt()&&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(),rr()},lr=()=>{if(Dt){if(Dt.idx+1<Dt.data.problems.length)return Dt.idx+=1,Dt.answers=[],Dt.tries=0,void sr();console.log(chalk.bold.green(Qt()?" 🎉 本卡练习全部完成!":" 🎉 Card practice complete!")+chalk.gray(Qt()?" ok 进下一张卡。":" ok moves on to the next card.")),Dt=null,jn()}},ar=()=>{const e=yn.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>=Zn?e.slot-Zn:null;if(console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(null!=s?Qt()?` · 第 ${s} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${s} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:Qt()?` · 第 ${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(Qt()?" ⏱ 已超时 — 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(Qt()?`(共 ${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(Qt()?` 🎉 满分 ${e.n}/${e.n} — 本组全部拿下!`:` 🎉 Perfect ${e.n}/${e.n} — every problem cleared!`)+chalk.gray(Qt()?" ↩ back 回卡片":" ↩ back returns to the card"):chalk.green(Qt()?" 🏁 已过关":" 🏁 passed")+chalk.yellow(Qt()?` · 还剩 ${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(Qt()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" 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?Qt()?`(${o})`:` (${o})`:"";console.log(chalk.cyan(Qt()?` 🔗 你另一个 token${t}已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens${t} solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Qt()?" 带过来,不必重做":" 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(Qt()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Qt()?"不够就 ":"Short on time? ")+chalk.bold.green("contest restart")+chalk.gray(Qt()?" 满血重开本组。":" restarts this group fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(Qt()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),Wn&&(console.log(chalk.gray(" 0 ")+Gn(Me)+chalk.gray(` ${Rn(Me)}`)+chalk.gray(Qt()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+Gn(e)+(e.gpu?chalk.magenta(" ⚡"):"")+chalk.white(` ${Rn(e)}`))}),e.problems.some(e=>e.gpu)&&(console.log(),console.log(e.gpu_window?chalk.bold.green(Qt()?" ⚡ GPU 窗口:开 ✅":" ⚡ GPU window: OPEN ✅")+chalk.gray(Qt()?" — 带 ⚡ 的层现在 /submit 就在真 GPU 上跑":" — /submit a ⚡ rung and it runs on a real GPU right now"):chalk.gray(Qt()?" ⚡ GPU 窗口:关(每周一 19:00–21:45 悉尼开放)— 带 ⚡ 的层等窗口内 /submit":" ⚡ GPU window: closed (Mondays 19:00–21:45 Sydney) — /submit ⚡ rungs inside the window"))),bn(yn.phase,e.slot)&&(console.log(),console.log(chalk.gray(" ✍ ")+chalk.bold.green("cells")+chalk.gray(Qt()?" 在 notebook 里探索本场数据(引导走查 · 真图) — 不判分,判分仍走 /submit":" explore this lab in a notebook (guided walkthrough · real figures) — ungraded; judging stays /submit"))),console.log(),ir()},ir=()=>{console.log(chalk.gray(Qt()?" /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(Qt()?"/syntax <词>":"/syntax <word>")+chalk.gray(Qt()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(Qt()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Qt()?" 返回课程":" returns to the lesson")),console.log(chalk.gray(Qt()?" memo 报告题面/判分问题 — 不打断比赛计时":" memo reports a statement/judging problem — the clock is unaffected")),console.log(chalk.gray(" ")+chalk.bold.green("contest restart")+chalk.gray(Qt()?" 超时/坏场时重开本组(全新计时+模板) · ":" time up or broken attempt → this group again (fresh clock + templates) · ")+chalk.bold.green("contest reset")+chalk.gray(Qt()?" 日后回来整阶段重做":" come back later and redo the whole phase")),console.log()},cr=e=>{const o=parseInt(e,10),t=yn.data.problems;if(o===Ne&&Wn)return{p:Me,n:Ne};const n=Wn?Ne:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(Qt()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),Wn&&console.log(chalk.gray(Qt()?" 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 dr=null,gr=!1;const ur=e=>{const o=cr(e);if(!o)return;const{p:t,n:n}=o;dr=String(n),console.log(),console.log(chalk.bold.white(` ${Gn(t)} ${Rn(t)}`)),console.log();for(const e of(e=>Qt()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of Qo(e,Jo()+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(Qt()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Qt()?" 应输出:":" 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(Qt()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(Qt()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=Qt()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of Qo(o,Jo()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(Qt()?"数据就在上方 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(),Wn&&n===Ne)return console.log(chalk.white(Qt()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(Qt()?"第 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(Qt()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(Qt()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((Qt()," ↩ "))+chalk.bold.green("back")+chalk.gray(Qt()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(Qt()?" 直接看正式题目":" skips straight to the real problems")),void console.log();t.gpu?(console.log(chalk.white(Qt()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Qt()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Qt()?"真 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(Qt()?" 三步:":" Three steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Qt()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(Qt()?"本机直跑,出你自己的 ms":"run it locally — see your own ms")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Qt()?"参考机判分(成绩 = 那里的 ms)":"judge on the reference machine (the scored ms)"))):(console.log(chalk.white(Qt()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Qt()?"写码(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(Qt()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(Qt()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Qt()?"正式判分(隐藏用例)":"official judging (hidden tests)"))),console.log(),console.log(chalk.gray(Qt()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(Qt()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((Qt()," ↩ "))+chalk.bold.green("back")+chalk.gray(Kn()?Qt()?" 回花名册 · ":" to the roster · ":Qt()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(Qt()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((Qt()," / "))+chalk.bold.green("wide")+chalk.gray(Qt()?" 换语言/宽度":" language / width")),console.log()},pr=async(e,o,t)=>await new Promise(n=>{const l=process.stdin,a=!!l.isTTY&&!!l.isRaw;if(mt.pause(),l.isTTY&&"function"==typeof l.setRawMode)try{l.setRawMode(!1)}catch{}_t=!0;const i=r(e,o,{stdio:"inherit",cwd:t??yn.dir}),c=e=>{if(l.isTTY&&"function"==typeof l.setRawMode&&a)try{l.setRawMode(!0)}catch{}s(),_t=!1,mt.resume(),n(e)};i.on("close",()=>c(null)),i.on("error",e=>c(e))}),hr=["-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"],yr=()=>{const e=A("vi");console.log(chalk.gray(Qt()?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=()=>{console.log(chalk.yellow(Qt()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(Qt()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(Qt()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(Qt()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},fr=new Map,$r=()=>Ke(process.cwd(),tt.id),br=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())}`},wr=async(e,o,t=!1)=>{if(!kn)return;let n;try{n=O(Je($r(),e),"utf-8")}catch{return}if(Buffer.byteLength(n,"utf-8")>We)return;const r=Ze(n),s=(new Date).toISOString(),l=Ge(ao(),ro).slice(0,Ye),a=await oo(ro,{n:e,title:Xe(n.split("\n",1)[0]),code:n,code_sha:r,card_number:gt.currentCard,run_meta:o,client_ts:s,events:l.length>0?l:void 0});a?l.length>0&&Qe(ao(),ro,l.length):Ve(ao(),ro,{n:e,code_sha:r,card_number:gt.currentCard,run_meta:o,client_ts:s}),a||t||console.log(chalk.gray(Qt()?" (未能同步到服务器 — 草稿只保存在本机)":" (could not reach the server — this scratch is saved locally only)"))},kr=()=>{console.log(chalk.gray(Qt()?" 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()},vr=e=>{const o=ze($r()),t=parseInt(e,10);return Number.isInteger(t)&&o.some(e=>e.n===t)?t:(0===o.length?console.log(chalk.yellow(Qt()?" 还没有任何草稿 — ":" No scratch files yet — ")+chalk.bold.green("/py")+chalk.gray(Qt()?" 新建第一个。":" creates the first one.")):console.log(chalk.yellow(Qt()?` 没有 py-${e} — 现有编号: `:` No py-${e} — you have: `)+chalk.white(o.map(e=>e.n).join(", "))+chalk.gray(Qt()?" · pylist 看列表":" · pylist shows them")),null)},_r=e=>{const o=ze($r()),t=e?.trim().toLowerCase(),n=t?o.filter(e=>(e.title??"").toLowerCase().includes(t)):o;if(console.log(),console.log(chalk.bold.magenta(Qt()?" ✍ 我的 Python 草稿":" ✍ My Python scratch files")+(t?chalk.gray(` · "${e?.trim()}"`):"")+chalk.gray(` (${n.length})`)),0===o.length)return console.log(chalk.gray(Qt()?" 还没有草稿 — ":" Nothing here yet — ")+chalk.bold.green("/py")+chalk.gray(Qt()?" 新建一个(第一行写标题)。":" creates one (line 1 becomes its title).")),void console.log();if(0===n.length)return console.log(chalk.gray(Qt()?` 没有匹配 "${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(Qo(e.title,40)[0]??e.title):chalk.gray(Qt()?"(未命名 — 第一行写标题)":"(untitled — line 1 becomes the title)");console.log(chalk.gray(` py-${String(e.n).padEnd(3)} `)+o+chalk.gray(` · ${br(e.mtimeMs)}`))}console.log(chalk.gray(" ▸ ")+chalk.bold.green(Qt()?"/py <编号>":"/py <n>")+chalk.gray(Qt()?" 打开 · ":" opens one · ")+chalk.bold.green("/py")+chalk.gray(Qt()?" 新建":" new file")),console.log()},Cr=async e=>{const o=Je($r(),e);if(go())return console.log(chalk.yellow(Qt()?" icoa 正跑在 Windows 上 — 草稿本的编辑器在 Ubuntu(WSL)那一侧。":" icoa is running on Windows — the scratchpad editor lives on the Linux (WSL) side.")),console.log(chalk.gray(Qt()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${o}`)),void console.log();if(!po("vi"))return console.log(chalk.yellow(Qt()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${o}`)),void console.log(chalk.gray(Qt()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));yr();const t=e=>{try{return W(e).size}catch{return 0}},n=t(o),r=Date.now(),s=C(o);await pr("vi",[...hr,`py-${e}.py`],$r());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 wr(e),console.log(chalk.gray(Qt()?" 已回到草稿本 — ":" Back in the scratchpad — ")+chalk.bold.green(`run ${e}`)+chalk.gray(Qt()?" 本机运行 · ":" runs it locally · ")+chalk.bold.green(`edit ${e}`)+chalk.gray(Qt()?" 再改。":" reopens vi.")),console.log()},Ar=async e=>{let o;if(N($r(),{recursive:!0}),e){const t=vr(e);if(null===t)return;o=t}else{const e=ze($r());o=He(e),o>De&&console.log(chalk.gray(Qt()?` (已超过 ${De} 个 — 服务器不再备份新文件,本机照常保存)`:` (past ${De} files — the server stops backing new ones up; local saves still work)`)),D(Je($r(),o),`${Qt()?Be:Ue}\n\n`)}const t=!Wt;Wt=!0,_(`learn-py: open ${o}${e?"":" (new)"}`),t&&(console.log(),console.log(chalk.bold.magenta(Qt()?" ✍ Python 草稿本":" ✍ Python scratchpad")+chalk.gray(Qt()?" — 你的个人练习文件 · 只在本机运行 · 不判分":" — your personal practice files · runs locally · never judged")),console.log(chalk.gray(Qt()?" 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(Qt()?" 回卡片(退一层)":" returns to the card (one level)"))),await Cr(o),kr()},xr=async e=>{const o=e.trim().toLowerCase(),s=Rt&&o.startsWith("/")?o.slice(1):o;if(wt)return void(kt=!0);if(vt){const{sameName:o,issueCertificate:t,announceCertificate:n}=await import("../lib/learn-certificate.js"),r=e.trim(),s=Qt();if(!r||Et.test(r))return vt=null,console.log(chalk.gray(s?" 已取消,未签发。":" Cancelled — nothing issued.")),void Ct();if(null===vt.first)return vt.first=r,console.log(chalk.gray(s?" 再输一次:":" Type it once more:")),void Ct();const l={cid:vt.cid,tok:vt.tok,first:vt.first};return vt=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 Ct()):(console.log(chalk.yellow(s?" 两次输入不一致 — 未签发。再敲 certificate 重来。":" The two names differ — nothing issued. Type certificate to try again.")),void Ct())}if(Ot)return;if(bt?.noteInput(),bt?.consumeRating(o))return void Ct();if(Dt)return await(async e=>{if(!Dt)return;const o=e.trim(),t=o.toLowerCase(),n=Boolean(nr()?.quiz);if("back"===t||"b"===t&&!n||"quit"===t||"menu"===t)return Dt=null,console.log(chalk.gray(Qt()?" ↩ 回到卡片。":" ↩ Back on the card.")),void jn();if("skip"===t)return void lr();if(""===o)return void sr();const r=nr();if(!r)return Dt=null,void jn();const s=or(r.starter??"");if(Dt.answers.push(o),Dt.answers.length<s)return void rr();const l=[...Dt.answers],a=((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")})(r.starter??"",l);Dt.answers=[];let i=_n.get(Dt.slot);i||(i=new Set,_n.set(Dt.slot,i)),i.add(r.id);const c=Boolean(r.quiz),d=c?null:new I(ro);d?.start();const g=await xe(ro,Dt.phase,r.id,a,Dt.slot,void 0);if(d?.stop(),!Dt)return;if(!g.ok||!g.data)return"no_active_session"===g.code?void tr(Dt.data.duration_minutes):(console.log(chalk.red(` ✗ ${g.message||"judging failed"}`)),console.log(chalk.gray(Qt()?" 再敲一遍空1重试,或 back 回卡片。":" Type blank 1 again to retry, or back for the card.")),void rr());const u=g.data;if("AC"!==u.verdict||u.already_ac||bt?.notePracticeAc(),u.already_ac||"AC"===u.verdict){c?console.log(chalk.bold.green(Qt()?" ✅ 答对了!":" ✅ Correct!")):console.log(chalk.bold.green(" ✅ AC!")+chalk.gray(` · ${u.passed_tests??u.total_tests??"?"}/${u.total_tests??"?"} `+(Qt()?"用例全过":"tests passed")));let e=vn.get(Dt.slot);return e||(e=new Set,vn.set(Dt.slot,e)),e.add(r.id),Dt.data.solved.includes(r.id)||Dt.data.solved.push(r.id),void lr()}Dt.tries+=1,c?console.log(chalk.red(Qt()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(Qt()?" — 再选一次。":" — pick again.")):console.log(chalk.red(` ✗ ${u.verdict??"WA"}`)+chalk.gray(Qt()?" — 还没对,再来。":" — not yet."));const p=r.samples?.[0];if(p?.out){console.log(chalk.gray(Qt()?" 期望输出:":" Expected output:"));for(const e of p.out.trimEnd().split("\n"))console.log(chalk.white(" "+e))}if(2===Dt.tries||Dt.tries>2&&Dt.tries%3==2){const e=c?[]:((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(Qt()?` ⚠ 空${i}:模板里 ____ 后面已经有 ( ) — 只填名字,别再带括号。`:` ⚠ blank ${i}: the ( ) after ____ is already in the template — type just the name, no brackets.`):(/["']$/.test(a)||/^["']/.test(l))&&/^["']|["']$/.test(s)?t.push(Qt()?` ⚠ 空${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(Qt()?` ⚠ 空${i}:____ 后面已有右括号,你的答案可能多带了一个 )。`:` ⚠ blank ${i}: a closing ) already follows ____ — your answer may carry one too many.`)}}return t})(r.starter??"",l);for(const o of e)console.log(chalk.yellow(o));console.log(chalk.gray(Qt()?" 💡 两次没过,多半是细节不是思路 — 再敲之前过一遍:":" 💡 Two misses are usually a detail, not the idea — run this check before retrying:")),c||(console.log(chalk.gray(Qt()?" · 拼写和大小写(Python 区分大小写:Print ≠ print)":" · spelling and case (Python is case-sensitive: Print ≠ print)")),console.log(chalk.gray(Qt()?" · 只填缺的那一块 — ____ 周围已有的括号、引号、冒号不要重复":" · fill only what is missing — brackets, quotes, colons already around ____ stay"))),console.log(chalk.gray(Qt()?" · 没思路?往上翻,或 ":" · no idea? scroll up, or ")+chalk.bold.green("back")+chalk.gray(Qt()?" 回卡片再读一遍 — 答案就在正文里。打错字人人都有,继续。":" re-reads the card — the answer is in its body. Typos happen to everyone; keep going."))}console.log(chalk.gray(Qt()?" 从空1再来:":" From blank 1 again:")),rr()})(e),void Ct();if(null!==Pt){if(St.push(e.replace(/\s+$/,"")),jt&&clearTimeout(jt),jt=null,It){const e=St[St.length-1]??"";return"/cancel"===e.trim()?(Nt(),console.log(chalk.gray(Qt()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Ct()):""!==e.trim()?void Ct():(St.pop(),void await c())}return void(jt=setTimeout(()=>{if(jt=null,St.length>1){It=!0;const e=St.length;return console.log(chalk.cyan(Qt()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(Qt()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Ct()}c()},140))}async function c(){const e=St.join("\n").replace(/^\s+|\s+$/g,""),o=Pt??gt.currentCard,t=St.length,n=Mt;if(Nt(),""===e)console.log(chalk.gray(Qt()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&Et.test(e))console.log(chalk.yellow(Qt()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(Qt()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(Qt()?" 即可执行。":" again to run it."));else{const r=!n&&Xt>0?Date.now()-Xt:void 0;if(await Q(ro,{curriculum_id:tt.id,card_number:o,feedback_text:n?`${n} ${e}`:e,time_on_card_ms:r})){const n=t>1?Qt()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(Qt()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(Qt()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),at=[...at,{id:ct--,curriculumId:tt.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Ho(at)}else console.log(chalk.yellow(Qt()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Ct()}if(Yt){const o=e.trim();if(Et.test(o))return Yt=!1,console.log(),console.log(chalk.yellow(Qt()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(Qt()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(Qt()?" 即可执行该命令。":" again to run it.")),console.log(),void Ct();if(!o)return Yt=!1,console.log(chalk.gray(Qt()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Ct();const t=await be({token:ro,nickname:o});if(t.ok)Yt=!1,console.log(chalk.bold.green(Qt()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Qt()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Bt+=1;const e="taken"===t.code?Qt()?"已被占用":"already taken":"bad_charset"===t.code?Qt()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"real_name"===t.code?Qt()?"看起来像真名 — 系统不收集个人信息,换个游戏风格的昵称":"looks like a real name — we collect no personal info; pick a gamer-style handle":"rejected"===t.code?Qt()?"未通过审核":"did not pass review":t.message||"error";if(!(Bt>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Qt()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Ct();Yt=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Qt()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Ct()}if(Zt){Zt=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ot=!0;try{console.log(),console.log(chalk.gray(Qt()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await ke({token:ro,cardNumber:gt.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Qt()?"评审暂不可用。":"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(Qt()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Qt()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Qt()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Qt()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Qt()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Qt()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=Qt()?` 本卡排名 #${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(Qt()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Qt()?` 第 ${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 Nn(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Qt()?" 改进提问: ":" 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(` (${Qt()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Kt.add(gt.currentCard):Kt.delete(gt.currentCard),"number"==typeof e.rank&&Vt.set(gt.currentCard,e.rank);const o=await _e({token:ro,curriculumId:tt.id,cardNumber:gt.currentCard});if(o.ok&&o.totals&&o.chapters&&(Xo({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(Qt()?` · 榜首 ${n.name||"Rank 1"} ${n.total}`:` · leader ${n.name||"Rank 1"} at ${n.total}`):chalk.bold.yellow(Qt()?" · 全场第一!":" · phase leader!");console.log(chalk.white(Qt()?` 🏅 Phase ${e.phase} 研究总分: `:` 🏅 Phase ${e.phase} research total: `)+chalk.bold.yellow(`${t.total}`)+chalk.gray(Qt()?`(${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&&!nt&&(Yt=!0,Bt=0,console.log(chalk.bold.yellow(Qt()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Qt()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Qt()?" 英文开头,英文+数字,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{Ot=!1}})():(console.log(chalk.gray(Qt()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Tt&&(console.log(chalk.gray(Qt()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Ct()}if(Jt)return Jt=!1,jn(),void Ct();if(!o)return void Ct();if(Ft)return"exit"===await E(e.trim())&&(Ft=!1),void Ct();if(qt){if(["q","quit","exit","back","b","menu"].includes(o))return qt=!1,console.log(chalk.gray(Qt()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Ct();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(Qt()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(s?Qt()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":Qt()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(Qt()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(Qt()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void Ct()):(n&&(await Ln(n,t?"fast":"deep"),console.log(chalk.gray(Qt()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Ct())}if(Wt){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 Wt=!1,console.log(chalk.gray(Qt()?" ↩ 已离开草稿本,回到卡片。":" ↩ Left the scratchpad — back to the card.")),jn(),void Ct();const t=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(t||"list"===o||"/list"===o)return _r(t?.[1]),kr(),void Ct();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=vr(o);null!==t&&("edit"===e?(await Cr(t),kr()):await(async e=>{if(!L(Je($r(),e)))return void vr(String(e));const o=so()?.cmd??null;if(!o)return console.log(chalk.yellow(Qt()?` 找不到 Python ${to.major}.${to.minor} — 草稿本和判分机固定在同一条 3.12 版本线上。`:` Python ${to.major}.${to.minor} not found — the scratchpad runs on the same 3.12 line as the judge.`)),console.log(chalk.gray(Qt()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3.12")+chalk.gray(Qt()?" — 或 quit 回 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")),void console.log();const[t,...n]=o.split(" ");console.log();const s=eo();let l="",a=!1;const i=await new Promise(o=>{const s=r(t,[...n,`py-${e}.py`],{cwd:$r(),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(Qt()?" ⏱ 超过 30 秒,已停止 — 检查死循环。":" ⏱ Over 30s — stopped. Check for an infinite loop."))),console.log(chalk.gray((Qt()," ▸ edit "))+chalk.gray(`${e} · pylist · `)+chalk.bold.green("back")),console.log(),nn.push(wr(e,{run_ms:c,exit_code:i,stderr_head:l.trim().slice(0,300)||void 0},!0).catch(()=>{}))})(t))}else console.log(chalk.yellow(Qt()?` 用法: ${e} <编号>`:` Usage: ${e} <n>`)+chalk.gray(Qt()?" (pylist 看编号)":" (pylist shows the numbers)"));return void Ct()}const s=/^\/?py(?:\s+(\S+))?$/.exec(o);if(s||"new"===o)return await Ar(s?.[1]),void Ct();if("menu"!==o&&"menu confirm"!==o)return console.log(chalk.gray(Qt()?" 草稿本命令: edit <n> · run <n> · pylist · /py 新建 · back 回卡片":" Scratchpad verbs: edit <n> · run <n> · pylist · /py (new) · back to the card")),void Ct()}if(Rt&&yn){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${yn.phase}s${yn.data.slot}: ${o}`),"memo"===o||"/memo"===o||"e"===o)return Pt=gt.currentCard,Mt=`[arena p${yn.phase}-g${yn.data.slot}${dr?` #${dr}`:""}]`,console.log(chalk.gray(Qt()?` 报告归到: 竞技场 p${yn.phase}-g${yn.data.slot}${dr?` 题${dr}`:""} — 题面 / 判分 / 环境,一句话即可:`:` Files under: arena p${yn.phase}-g${yn.data.slot}${dr?` problem ${dr}`:""} — statement / judging / environment, one line is enough:`)),console.log(chalk.gray(Qt()?" (回车提交 · 空行取消 · 不打断比赛计时)":" (Enter to submit · blank to cancel · the contest clock is unaffected)")),void Ct();if("back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Kn()&&null!==dr?(dr=null,ar(),void Ct()):(Rt=!1,dr=null,console.log(chalk.gray(Qt()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),jn(),void Ct());if(/^\d+$/.test(o))return ur(o),void Ct();const n=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(n)return Kn()?n[1]?ur(n[1]):ar():console.log(chalk.gray(Qt()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void Ct();if("cells"===o||"/cells"===o||"explore"===o||"/explore"===o){const e=wn(yn.phase,yn.data.slot,yn.dir);if(!e)return console.log(chalk.gray(bn(yn.phase,yn.data.slot)?Qt()?" 引导 notebook 还没下载到位(需要联网一次)— 稍后再敲 cells。":" The guided notebook has not downloaded yet (needs one online moment) — try cells again shortly.":Qt()?" 本场没有引导 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 Ct();const o=null!==x();o||T(mt);try{const{runIpynb:o}=await import("./ipynb.js");await o(e)}catch(e){console.log(chalk.yellow(Qt()?" notebook 没打开: ":" The notebook failed to open: ")+chalk.gray(String(e)))}finally{o||T(null)}return ar(),void Ct()}const r=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(r)return await(async e=>{const o=e.trim();if(await ae()||gr||(gr=!0,console.log(chalk.gray(Qt()?` (离线:只有 ${ye()} 条核心速查可用;联网后自动补全)`:` (offline: ${ye()} core entries available; the rest arrive when you have a connection)`))),!o)return void ue(Qt());const t=ce(o);if(t.length){he(t[0],Qt());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(Qt()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await ie("python3",o);if(n)pe(n,Qt());else{if(await de()){const e=ce(o);if(e.length)return void he(e[0],Qt())}console.log(),console.log(chalk.yellow(Qt()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(Qt()?" 试试: ":" Try: ")+chalk.cyan(ge(o).join(" · "))),console.log(chalk.gray(Qt()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(r[1]??""),void Ct();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?ur(o):"edit"===e?await(async e=>{const o=cr(e);if(!o)return;const t=H(yn.dir,zn(o.n,o.p));if(go())return uo()?(console.log(chalk.yellow(Qt()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(Qt()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(Qt()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(Qt()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(Qt()?" ← 不能是 /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(Qt()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(Qt()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(Qt()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(Qt()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(Qt()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(Qt()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(Qt()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(Qt()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!po("vi"))return console.log(chalk.yellow(Qt()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(Qt()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));yr();const n=e=>{try{return W(e).size}catch{return 0}},r=n(t),s=Date.now(),l=C(t);await pr("vi",[...hr,zn(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=fn.get(o.n)??{list:[],dropped:0};e.list.push(a),e.list.length>16&&(e.list.shift(),e.dropped++),fn.set(o.n,e)}_(`learn-arena edit-done ${zn(o.n,o.p)}`,{...i,...a.ticks>0?{samples:a}:{}}),console.log(chalk.gray(Qt()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Qt()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=cr(e);if(!o)return;const{p:n,n:r}=o;if(Wn&&r===Ne)return void(()=>{const e=H(yn.dir,`sol-${Ne}.py`);if(!L(e))return void console.log(chalk.yellow(Qt()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=[];for(const n of qe)try{o.push(t(lo(),[e],{input:`${n.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(Qt()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(Qt()?` ✗ 输入 ${n.in} 时程序报错:`:` ✗ Your program crashed on input ${n.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(Qt()?" 改完再来: ":" Fix it and rerun: ")+chalk.bold.green("/edit 0")+chalk.gray(" → ")+chalk.bold.green("/run 0")),void console.log()}const{cases:n,passed:r}=Oe(o);console.log();for(const e of n)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(Qt()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),r===n.length){const e=Dn?null:1;Dn=!0,console.log(chalk.bold.green(Qt()?` 🎉 ${r}/${n.length} 全过 — `:` 🎉 ${r}/${n.length} — `)+chalk.white(Qt()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(Qt()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(Qt()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(Qt()?` ${r}/${n.length} 通过 — 还差一点。`:` ${r}/${n.length} passed — not there yet.`)+chalk.gray(Qt()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(Qt()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const s=H(yn.dir,zn(r,n));if(!L(s))return void console.log(chalk.yellow(Qt()?` 还没有 ${zn(r,n)} — 先 /edit ${r}。`:` No ${zn(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(Qt()?" ⚡ 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(Qt()?"(窗口时间执行并返回你的 ms;窗口外会告诉你开放时间)":" (executes in the GPU window and returns your ms; outside the window it tells you the hours)")),void console.log();if(!l&&n.starter){const e=Bn(n),o={cpp:"c++",java:"java",go:"go"};if("python"!==e&&!po(o[e]))return console.log(chalk.gray(Qt()?` 本机没有 ${o[e]} — 这一层的计时以判分机为准,直接 `:` No local ${o[e]} — the judge compiles and times this level; go straight to `)+chalk.bold.green(`/submit ${r}`)),void console.log();try{let o;if("cpp"===e){const e=H(yn.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 o="java"===e?t("java",[s],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):"go"===e?t("go",["run",s],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):t(lo(),[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(Qt()?` ${Fe(!0)} — 满意就 `:` ${Fe(!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(Qt()?" ⏱ 超过 30 秒 — 检查死循环。":" ⏱ Over 30s — check for an infinite loop."));else{console.log(chalk.yellow(Qt()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of(o.stderr??"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));console.log(chalk.gray(Qt()?` (空还没填对?/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(Qt()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";const i=eo();try{a=t(lo(),[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(Qt()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Qt()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const c=i(),d=a.replace(/\r\n/g,"\n").trimEnd(),g=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(Qt()?" 你的输出:":" Your output:"));for(const e of(d||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Qt()?" 样例应输出:":" Sample expects:"));for(const e of g.split("\n"))console.log(chalk.green(` ${e}`));console.log(chalk.gray(` ⏱ ${c}ms — ${Fe(Qt())}`)),d===g?console.log(chalk.bold.green(Qt()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Qt()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Qt()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Qt()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=cr(e);if(!o)return;if("python"!==Bn(o.p)||o.p.gpu)return console.log(chalk.gray(Qt()?` 这一层不读输入 — 用 /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=H(yn.dir,`sol-${o.n}.py`);if(!L(t))return void console.log(chalk.yellow(Qt()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(Qt()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const n=await pr(lo(),[`sol-${o.n}.py`]);console.log(),"ENOENT"!==n?.code?(console.log(chalk.gray(Qt()?" 回到竞技场。":" Back in the arena.")),console.log()):mr()})(o):"recall"===e&&await(async e=>{const o=cr(e);if(!o)return;if(!st)return void Mn();const{p:t,n:n}=o,r=H(process.cwd(),"icoa-contest"),s=`${tt.id}-phase${yn.phase}-g${yn.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?H(r,l,`sol-${n}.py`):null;if(!a||!L(a))return void console.log(chalk.gray(Qt()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=O(a,"utf-8"),c=`${yn.phase}-${yn.data.slot}-${n}`,d=Math.min(3,(fr.get(c)??0)+1);console.log(chalk.gray(Qt()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await $e({token:ro,phase:yn.phase,slot:yn.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:Qt()?"zh":"en"});if(g.ok){fr.set(c,d),console.log();for(const e of Qo(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(Qt()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(Qt()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(Qt()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(Qt()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(Qt()?" (花名册: /list)":" (roster: /list)")),void Ct()}if("contest"===o||"/contest"===o)return ar(),void Ct();const a="lang"===o||/^lang\s+\S+$/.test(o),i=et.has(o);if(!("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(Qt()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void Ct()}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(Qt()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Ct()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(mt.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}_t=!0;const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}_t=!1,mt.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void Ct()}if("ai4ioai"===o||"/ai4ioai"===o)return await M()&&(Ft=!0),void Ct();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!st)return Mn(),void Ct();zt||(zt=!0,console.log(),console.log(chalk.bold.cyan(Qt()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Qt()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Qt()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Qt()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")),console.log(chalk.gray(Qt()?" 💡 一次好的研究通常会向 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(Qt()?" 新建草稿贴进去跑(":" a fresh scratch file and run them (")+chalk.bold.green("/pylist")+chalk.gray(Qt()?" 看草稿)。":" lists them).")),console.log(chalk.yellow(Qt()?" ↩ 重要:退出 AI 模式只需输入 ":" ↩ Important: to leave AI mode just type ")+chalk.bold.white("back")+chalk.yellow(Qt()?" 或 ":" or ")+chalk.bold.white("quit")+chalk.yellow(Qt()?",就回到卡片。":" — you are back on the card.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){qt=!0;const e=cn(gt.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Qt()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(Qt()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Qt()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · back / quit = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · back / quit = back to card")),console.log(chalk.gray(Qt()?" 💡 通常要向 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 Ct()}return await Ln(n,t?"fast":"deep"),void Ct()}if(!Rt&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!st)return Mn(),void Ct();const e=cn(gt.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Qt()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Qt()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Qt()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Qt()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Qt()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Qt()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Qt()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Zt=!0,void Ct()}const h=!Rt&&"honors"===Ut&&/^[1-3]$/.test(o);if(!Rt&&Ut&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(Qt()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(Qt()?" ↩ back 回上一层":" ↩ back goes up one level")),void Ct();if(!Rt&&(h||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!st)return Mn(),void Ct();const e=/^\/?view ([1-3])$/.exec(o),t=h?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Ot=!0;try{console.log();const o=await ve({token:ro,cardNumber:gt.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Qt()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Kt.delete(gt.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Kt.add(gt.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Qt()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${gt.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${gt.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Qt()?` (第 ${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(Qt()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Nn(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(Qt()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Ut="view",console.log(chalk.gray((Qt()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Qt()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Ot=!1}})(t),void Ct()}const m=o.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(m&&!Rt&&!Wt){const{certificateLines:e}=await import("../lib/learn-door.js"),{certifiable:o,certificateIntroLines:t}=await import("../lib/learn-certificate.js"),n=Qt(),r=nt?null:await y(ro,"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===tt.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 Ct()}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:")),vt={cid:i.curriculum_id,tok:i.token,first:null},void Ct()}const $=o.match(/^\/?(story|credits|fin)(?:\s+(\S+))?$/);if($&&!Rt&&!Wt){const e=($[2]??"").trim();return await gn("story"===$[1]?e||"list":e||null,!0),void Ct()}if("me"===o||"/me"===o||"profile"===o||"/profile"===o||"my profile"===o){const e=Qt();if(nt)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 Ct();console.log(chalk.gray(e?" 正在取档案…":" Loading your profile…"));const o=await y(ro);return"ok"===o.kind?f(o.profile,e,Jo()):"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 Ct()}if("/honors"===o||"honors"===o)return nt?(console.log(),console.log(chalk.gray(Qt()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Ct()):(await On(),void Ct());const b=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(b)return _("learn-py: pylist"+(b[1]?` ${b[1]}`:"")),_r(b[1]),void Ct();const w=/^\/?py(?:\s+(\S+))?$/.exec(o);if(w)return await Ar(w[1]),void Ct();if("menu"===o||"menu confirm"===o){if(bt?.detach(),nn.length>0&&await Promise.race([Promise.allSettled(nn),new Promise(e=>setTimeout(e,3e3))]),mt.removeAllListeners("line"),$t(),ht||!an){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ht?mt:void 0),ln()}else mt.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===Ut)return await On(),void Ct();if("honors"===Ut)return Ut=null,jn(),void Ct();if(bt?.detach(),nn.length>0&&await Promise.race([Promise.allSettled(nn),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${gt.streakDays} day(s)`)),console.log(),ht){mt.removeAllListeners("line"),$t();for(const e of yt)mt.on("line",e);mt.prompt(),ln()}else mt.removeAllListeners("line"),mt.close();return}if(te(o))return it?ot(ee(it,Qt(),Jo(),"T0"===ne().tier),!!it.completedAt):(console.log(chalk.gray(Qt()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void Ct();if("status"===o)return No(tt,gt),void Ct();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await Z(tt.id,ro,!0);return void(e?(Object.assign(tt,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),jn()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),Ct()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(io().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Ct();const t=tt.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 co({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Tt=null,At=null,xt=null,Nt(),Jt=!1,Zt=!1,await qn(),void Ct()}const k=o.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(k&&!Rt&&!Wt&&null===Dt&&g.test(o)){const e=Qt(),o=await u(ro);if("ok"===o.kind)for(const t of p(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 Ct()}if(k&&!Rt&&!Wt&&null===Dt){const e=(k[2]??"").trim(),o=Qt(),t=`${a}–${l}`+(o?`,${i} 的倍数`:`, steps of ${i}`);if("off"===e||"stop"===e||"end"===e||"cancel"===e||"关"===e)return void(bt?.stop()||(console.log(chalk.gray(o?" 没有进行中的专注。开始一场:":" No focus session running. Start one: ")+chalk.bold.green("focus 30")),Ct()));if(bt?.active)return console.log(chalk.yellow(" ⏱ ")+chalk.white(o?`专注进行中 · 还剩 ${bt.remainingMin()} 分钟`:`focus running · ${bt.remainingMin()} min left`)+chalk.gray(o?" · 提前结束:":" · end early: ")+chalk.bold.green("focus off")),void Ct();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 Ct();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 Ct();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 bt?.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 Ct()}if(et.has(o)){const e=et.get(o),t=Zo(io()),n=e=>{const o=["normal","wide","wider","widest"].filter(o=>o!==e);return Qt()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((Qt()?"normal"===e?" 已是标准 64 列。":Jo()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Jo()} 列,上限 ${Ko(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Jo()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Jo()} cols, cap ${Ko(e)}). `)+n(e))),void Ct()):(co({learnWidth:e,learnWide:"normal"!==e}),Go(e),"normal"!==e&&Jo()<=64?(console.log(chalk.yellow(Qt()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((Qt()?` 设置已记住(${e},上限 ${Ko(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Ko(e)} cols) and applies once you widen the window. `)+n(e))),void Ct()):(console.log(chalk.green(" ✓ ")+chalk.gray((Qt()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Jo()} 列,上限 ${Ko(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Jo()} cols, cap ${Ko(e)}). `)+n(e))),Tt=null,At=null,xt=null,Nt(),Jt=!1,Zt=!1,await qn(),void Ct()))}if("sim"===o){const e=cn(gt.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=F(G(import.meta.url)),o=[H(e,"..","..","panda","mujoco-launcher.py"),H(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(L(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 Ct()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Ct())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=gt.currentCard,t=gt.bookmarks.includes(e),n="bookmark"!==o;return n?gt.bookmarks=gt.bookmarks.filter(o=>o!==e):t||gt.bookmarks.push(e),yo(gt),n?console.log(t?chalk.gray(Qt()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(Qt()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(Qt()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(Qt()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Ct()}const v=re(o);if(v){const e="current"===v.target?gt.currentCard:v.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>tt.cards.length))return console.log(chalk.yellow(Qt()?` 本课共 ${tt.cards.length} 张,请输 r 1–${tt.cards.length} 或 r all。`:` This course has ${tt.cards.length} cards. Try r 1–${tt.cards.length} or r all.`)),console.log(),void Ct();for(const o of se(at,tn,e,Qt(),Jo()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?at:at.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(at=at.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Ho(at),nn.push(J(ro,{card_number:gt.currentCard,event_type:"viewed"},o).catch(()=>{}))),void Ct()}if("e"===o||"memo"===o)return Pt=gt.currentCard,console.log(chalk.gray(Qt()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(Qt()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void Ct();if("back"===o||"b"===o)return"view"===Ut?(await On(),void Ct()):"honors"===Ut?(Ut=null,jn(),void Ct()):(gt.currentCard>1&&(gt.currentCard-=1),At=null,xt=null,Tt=null,yo(gt),jn(),void Ct());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!kn)return console.log(chalk.yellow(Qt()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Ct();if(!e){const e=await Pe(ro),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(Qt()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(Qt()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(Qt()?` 这台电脑上有 ${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(Qt()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(Qt()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(Qt()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(Qt()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(Qt()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(Qt()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(Qt()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Ct()}if(/^\d{1,2}$/.test(e)){const o=await Te(ro,Number(e));return o.ok&&o.data?(Hn(o.data),await An(),void Ct()):(console.log(chalk.red(` ✗ ${o.message||(Qt()?"关联失败":"Link failed")}`)),void Ct())}const t=await Se(ro,e);return t.ok&&t.data?(Hn(t.data),await An(),void Ct()):(console.log(chalk.red(` ✗ ${t.message||(Qt()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(Qt()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Ct())}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(!kn)return console.log(chalk.yellow(Qt()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Ct();let e=xn(gt.currentCard),t=null;const n="contest restart"===o||"restart"===o;if(n&&(!Rt||!yn||Kn()))return console.log(chalk.gray(Qt()?" 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 Ct();if(n&&yn){const o=yn.phase,n=yn.data.slot,r=await Ce(ro,o,n);if(!r.ok&&"no_active_session"!==r.code)return console.log(chalk.red(` ✗ ${r.message||"reset failed"}`)),void Ct();Jn(o,n),console.log(chalk.yellow(Qt()?` 🔄 第 ${n} 组重开 — 全新计时、全新模板。`:` 🔄 Group ${n} restarted — fresh clock, fresh templates.`)+chalk.gray(Qt()?" 只有计时内写的才算数:从头再写一遍,这正是练习。":" Only work written on the clock counts — write it again from scratch; that is the practice.")),yn=null,Rt=!1,dr=null,e=o,t=n}if("contest reset"===o&&Rt&&Kn()){const e=yn.phase,o=yn.data.slot,t=await Ce(ro,e,o);if(t.ok){console.log(chalk.yellow(Qt()?" 已放弃本卡练习计时。回卡片后输入 practice <题号> 重新开始。":" Practice attempt abandoned. From the card, practice <n> starts a fresh one."));const t=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),n=H(process.cwd(),"icoa-contest",`${tt.id}-phase${e}-g${o}`);if(L(n))try{R(n,`${n}-archived-${t}`),console.log(chalk.gray(Qt()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(Qt()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}yn=null,Rt=!1,dr=null,jn()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void Ct()}if("contest reset"===o){const o=await Ce(ro,e);if(o.ok){console.log(chalk.yellow(Qt()?` 已放弃本阶段(${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=H(process.cwd(),"icoa-contest"),n=new RegExp(`^${tt.id}-phase${e}-g(\\d+)$`),r=(L(t)?q(t):[]).map(e=>({name:e,m:n.exec(e)})).filter(({m:e})=>e&&Number(e[1])<Zn).map(({name:e})=>e).sort();for(const e of r){const n=H(t,e);try{R(n,`${n}-archived-${o}`),console.log(chalk.gray(Qt()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(Qt()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(Qt()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),yn=null,Rt=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Ct()}const r=null!=t?String(t):/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Qt()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(ro,e,r?parseInt(r,10):void 0);if(!s.ok||!s.data){if("no_contest"===s.code){const o=tt.modules.find(o=>o.number===e)?.cardRange,t=!!o&&o[1]-o[0]+1>12;console.log(chalk.gray(t?Qt()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(360 层第二阶段标准设计中)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (360-tier second-stage standard in design).`:Qt()?` 本阶段(${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 Ct()}const l=s.data,a=H(process.cwd(),"icoa-contest",`${tt.id}-phase${e}-g${l.slot}`);if(!l.resumed&&L(a)&&q(a).some(e=>/^sol-\d+\.[a-z]+$/.test(e))){const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{R(a,`${a}-archived-${e}`),console.log(chalk.gray(Qt()?" 📦 上一场的答题文件已归档: ":" 📦 Previous window archived: ")+chalk.gray(`${a}-archived-${e}`)),console.log(chalk.gray(Qt()?" 新场次全新模板 — 计时窗口内写的才算数。":" Fresh window, fresh templates — only work done on the clock counts."))}catch{console.log(chalk.yellow(Qt()?` ⚠ 归档失败(比赛照常): ${a}`:` ⚠ Could not archive (contest still fine): ${a}`))}}N(a,{recursive:!0});const i=yn&&yn.phase===e&&yn.data.slot===l.slot?yn.tried:new Set;yn&&yn.phase===e&&yn.data.slot===l.slot&&yn.data.attempt===l.attempt||(mn.clear(),fn.clear()),yn={phase:e,dir:a,data:l,tried:i},Fn(l,a),wn(e,l.slot,a),Rt=!0,ar(),console.log(chalk.gray(Qt()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(a));const c=l.problems.findIndex(e=>!l.solved.includes(e.id))+1||1,d=Wn&&!Dn?Ne:c;return console.log(chalk.white(Qt()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${d}`)+chalk.gray(d===Ne?Qt()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":Qt()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Ct()}const A=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(en&&/^[1-9]$/.test(o)?`practice ${o}`:o);if(A){const e=cn(gt.currentCard),o=Qn(e);if(!o)return console.log(chalk.gray(Qt()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void Ct();if(!kn)return console.log(chalk.yellow(Qt()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void Ct();if(!A[1])return console.log(),er(e),console.log(chalk.gray(Qt()?" 用法: ":" Usage: ")+chalk.bold.green(Qt()?"practice <题号>":"practice <n>")+chalk.gray(Qt()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void Ct();const t=parseInt(A[1],10);return!Number.isInteger(t)||t<1||t>o.length?(console.log(chalk.yellow(Qt()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void Ct()):(await(en?(async(e,o,t)=>{const n=xn(e.number),r=Zn+e.number;console.log(chalk.gray(Qt()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(ro,n,r,!0);if(!s.ok||!s.data)return void("no_contest"===s.code?console.log(chalk.gray(Qt()?" 本卡暂无练习题库。":" 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(Qt()?" 本卡练习题库是空的。":" 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(Xn(e.py_id))?Xn(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=vn.get(r);c||(c=new Set,vn.set(r,c));for(const e of l.solved)c.add(e);Dt={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(Qt()?` ⚡ 快速填空 — 第 ${e.number} 张卡`:` ⚡ Quick fill — card ${e.number}`)+chalk.gray(Qt()?"(敲答案 → 自动判分 · 不计分)":" (type the blank → auto-judged · unscored)")),console.log(chalk.gray(Qt()?` ⏱ 每次练习 ${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`)),sr()})(e,o,t):(async(e,o,t)=>{const n=xn(e.number),r=Zn+e.number;console.log(chalk.gray(Qt()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(ro,n,r,!0);if(!s.ok||!s.data)return void("no_contest"===s.code?console.log(chalk.gray(Qt()?" 本卡暂无练习题库。":" 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(Qt()?" 本卡练习题库是空的。":" 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(Xn(e.py_id))?Xn(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=vn.get(r);c||(c=new Set,vn.set(r,c));for(const e of l.solved)c.add(e);const d=H(process.cwd(),"icoa-contest",`${tt.id}-phase${n}-g${r}`);N(d,{recursive:!0});const g=yn&&yn.phase===n&&yn.data.slot===r?yn.tried:new Set;yn&&yn.phase===n&&yn.data.slot===r&&yn.data.attempt===l.attempt||(mn.clear(),fn.clear()),yn={phase:n,dir:d,data:l,tried:g},Fn(l,d),Rt=!0,dr=null,_(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(Qt()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(Qt()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(Qt()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(d)),console.log(chalk.gray((Qt()," ↩ "))+chalk.bold.green("back")+chalk.gray(Qt()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),ur(String(Math.min(t,l.problems.length)))})(e,o,t)),void Ct())}if("submit"===s)return console.log(chalk.yellow(Qt()?" 用法: ":" Usage: ")+chalk.bold.green(Qt()?"submit <题号>":"submit <n>")+chalk.gray(Qt()?" 例如 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)")),yn||console.log(chalk.gray(Qt()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Ct();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!yn)return console.log(chalk.yellow(Qt()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Ct();const n=yn.data.problems,r=parseInt(o,10);if(Wn&&r===Ne)return console.log(chalk.gray(Qt()?" 热身题不判分 — /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(Qt()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(Qt()?" 开始。":".")),void Ct();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(Qt()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Ct();const l=n.findIndex(e=>e.id===o)+1,a=t||H(yn.dir,zn(l,n[l-1]));let i;try{i=O(a,"utf-8")}catch{return console.log(chalk.red(Qt()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Ct()}const c=new I(ro);c.start();const d=mn.get(l),g=fn.get(l),u=d&&!B(d)?{...d,...g?{samples:g.list}:{},...g&&g.dropped>0?{samplesDropped:g.dropped}:{}}:void 0,p=await xe(ro,yn.phase,o,i,yn.data.slot>=Zn?yn.data.slot:void 0,u);if(c.stop(),!p.ok||!p.data)return"no_active_session"===p.code&&yn.data.slot>=Zn?tr(yn.data.duration_minutes):"no_active_session"===p.code?(Jn(yn.phase,yn.data.slot),console.log(chalk.yellow(Qt()?" ⏱ 时间到 — 这一场结束了,判分机已停表。":" ⏱ Time is up — this attempt is over; the judge stopped the clock.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(Qt()?" 重开这一组:全新计时 + 全新模板(旧文件已归档)。只有计时内写的才算数 — 从头再写一遍,这正是练习。":" 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(Qt()?" ↩ back 回卡片":" ↩ back returns to the card"))):(console.log(chalk.red(` ✗ ${p.message||"judging failed"}`)),console.log(chalk.gray(Qt()?" 判分服务异常?敲 memo 一句话告诉我们 — 不打断比赛计时。":" Judge acting up? Type memo — one line reaches us, the clock is unaffected."))),void Ct();const h=p.data;if(h.already_ac)console.log(chalk.green(Qt()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===h.verdict){if(console.log(chalk.bold.green(Qt()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${h.passed_tests??h.total_tests??"?"}/${h.total_tests??"?"} `+(Qt()?"隐藏用例全过":"hidden tests passed")+` · ${h.time_ms??"?"}ms`)),yn.data.solved.includes(o)||yn.data.solved.push(o),yn.tried.delete(o),Kn()){let e=vn.get(yn.data.slot);e||(e=new Set,vn.set(yn.data.slot,e)),e.add(o);const t=await _e({token:ro,curriculumId:tt.id,cardNumber:gt.currentCard}),n=t.ok?t.practiceBoard:null;if(n?.mine){const e=n.top[0],o=e&&!e.me?chalk.gray(Qt()?` · 榜首 ${e.name||"Rank 1"} ${e.ac} AC`:` · leader ${e.name||"Rank 1"} at ${e.ac} AC`):chalk.bold.yellow(Qt()?" · 全场第一!":" · phase leader!");console.log(chalk.white(Qt()?` ⚔ Phase ${n.phase} Practice AC: `:` ⚔ Phase ${n.phase} practice AC: `)+chalk.bold.yellow(`${n.mine.ac}`)+chalk.gray(`/${n.problems_total}`)+chalk.gray(Qt()?` · 第 ${n.mine.rank} 名`:` · rank ${n.mine.rank}`)+o)}}}else{yn.tried.add(o);const e="TLE"===h.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${h.verdict}`)+chalk.gray(h.test?Qt()?` · 挂在第 ${h.test} 个用例(过 ${h.passed_tests}/${h.total_tests})`:` · failed test ${h.test} (passed ${h.passed_tests}/${h.total_tests})`:"")),Lt||(Lt=!0,console.log(chalk.gray(Qt()?" 觉得题面有误或判分不对?敲 memo 一句话 — 不打断比赛计时。":" Statement wrong or judging looks off? Type memo — one line, the clock is unaffected.")))}h.late&&console.log(chalk.yellow(Qt()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const y=je(h.deadline||""),m=Kn();if(console.log(chalk.white(m?Qt()?` 本卡练习: 已过 ${h.ac_count}/${h.n} 题(不计分)`:` Card practice: ${h.ac_count}/${h.n} solved (unscored)`:Qt()?` 本组进度: 已过 ${h.ac_count} 题 · 过 ${h.need} 题过关(共 ${h.n} 题)`:` Group progress: ${h.ac_count} solved · ${h.need} needed to pass (${h.n} problems)`)+(y?chalk.gray(` · ⏱ ${y}`):"")),m&&!h.late&&h.ac_count>=h.n)console.log(chalk.bold.green(Qt()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(Qt()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!h.passed||h.late||m){if(!h.late){const e=n.findIndex(e=>!yn.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Qt()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Rn(n[e])}`))}}else{const e=Math.max(0,h.n-h.ac_count);if(0===e)console.log(chalk.bold.green(Qt()?` 🎉 满分!${h.n}/${h.n} 全部 AC — 这组题你已经彻底拿下。`:` 🎉 Perfect! ${h.n}/${h.n} AC — you have completely cleared this group.`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(Qt()?" 回到上一层(卡片),继续往下学;":" returns to the previous layer (the card) — keep going from there; ")+chalk.bold.green("contest")+chalk.gray(Qt()?" 看本阶段其他赛场。":" lists the other arenas of this phase."));else{console.log(chalk.bold.green(Qt()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")+chalk.yellow(Qt()?` 还剩 ${e} 题 — 全部做完就是满分 ${h.n}/${h.n},别停在这里。`:` ${e} more to go — solve them all for a perfect ${h.n}/${h.n}, don't stop here.`));const o=n.findIndex(e=>!yn.data.solved.includes(e.id));o>=0&&console.log(chalk.gray(Qt()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${o+1}`)+chalk.gray(` ${Rn(n[o])}`)+chalk.gray(Qt()?" · ↩ back 回卡片":" · ↩ back returns to the card"))}await An()}return void Ct()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>tt.totalCards)return console.log(chalk.yellow(` Card number must be 1..${tt.totalCards}. Try: `)+chalk.bold.green("card 1")),void Ct();const n=await Pn(t);return n?(console.log(n),void Ct()):(gt.currentCard=t,At=null,xt=null,Tt=null,yo(gt),jn(),void Ct())}if(null!==Tt&&["y","yes","n","no"].includes(o)){const e=cn(Tt);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Xt;bt?.noteCheck(n,r),wo(gt,e.number),vo(gt,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),yo(gt);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),nn.push(J(ro,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Tt=null,pn(),e.solution&&e.solution.length>0)return void Ct();if(Vn())return void Ct();if(gt.currentCard<tt.totalCards){const e=gt.currentCard,o=await Pn(e+1);if(o)return await Sn(e),console.log(o),void Ct();gt.currentCard+=1,yo(gt),await Sn(e)?In():jn(),Ct()}else Oo(tt,gt),gn(null,!1).then(()=>Ct()),Ct();return}}if(null!==At&&["a","b","c","d"].includes(o)){const e=cn(At);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(ko(gt,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),wo(gt,e.number),yo(gt),Po(e,t,n,gt),nn.push(J(ro,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),At=null,n)if(gt.currentCard<tt.totalCards){const e=await Pn(gt.currentCard+1);if(e)return console.log(e),void Ct();gt.currentCard+=1,yo(gt),jn()}else Oo(tt,gt),gn(null,!1).then(()=>Ct()),Ct();else Ct();return}}if(null!==xt){if("done"===o){const e=cn(xt);if(e&&"practical"===e.type)return _o(gt,e.number),wo(gt,e.number),yo(gt),Io(e),xt=null,void Ct()}if("skip"===o)return wo(gt,xt),yo(gt),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),xt=null,void Ct()}const P=en&&"skip"===o&&null===At&&null===xt&&null===Tt&&null!==Qn(cn(gt.currentCard));if("ok"===o||"next"===o||"continue"===o||"n"===o||P){if(P){const e=gt.currentCard;Cn.add(e),bt?.notePracticeSkipped(),console.log(chalk.gray(Qt()?" ⚔ 本卡练习已跳过(有记录)。":" ⚔ Practice skipped for this card (recorded).")),J(ro,{card_number:e,event_type:"practice_skipped"}).catch(()=>{})}else if(null===Tt&&null===At&&null===xt&&Vn())return void Ct();if(null!==At)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Ct();if(null!==xt)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Ct();if(null!==Tt)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Ct();const e=gt.currentCard,o=e<tt.totalCards?await Pn(e+1):null;return o?(await Sn(e),console.log(o),void Ct()):(gt.currentCard+=1,yo(gt),gt.currentCard>tt.totalCards?(Oo(tt,gt),gn(null,!1).then(()=>Ct())):await Sn(e)?In():jn(),void Ct())}return null!==Tt?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Ct()):null!==At?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Ct()):null!==xt?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Ct()):("view"===Ut?console.log(chalk.gray(Qt()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(Qt()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(Qt()?" 回卡片":" to the card")):"honors"===Ut?console.log(chalk.gray(Qt()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(Qt()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(Qt()?" 回卡片":" 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 Ct())};mt.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.")),Ct()})}),ht||mt.on("close",async()=>{bt?.detach(),nn.length>0&&await Promise.race([Promise.allSettled(nn),new Promise(e=>setTimeout(e,5e3))]),an?ln():process.exit(0)});const Tr=le(at,Qt());Tr&&(console.log(chalk.bold.cyan(` ${Tr}`)),console.log());try{jn();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0),(async()=>{for(let e=0;e<20&&!hn;e++)await new Promise(e=>setTimeout(e,250));const e=un();null!==e&&e>0&&e<=2&&(await pn(!0),Ct())})();const o=bt?.attach(ro,tt.id,dn);"resumed"===o&&(console.log(chalk.yellow(" ⏱ ")+chalk.white(Qt()?`专注进行中 · 还剩 ${bt.remainingMin()} 分钟 · 这条轨也算在内 · focus off 提前结束`:`focus running · ${bt.remainingMin()} min left · this course counts too · focus off to end early`)),console.log()),Ct()}catch{if(Vo("Could not render this card — the curriculum may be malformed."),ht){mt.removeAllListeners("line"),$t();for(const e of yt)mt.on("line",e);mt.prompt()}else mt.close();ln()}await sn}),no.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 p}from"../lib/learn-focus-log.js";import{setLearnFooterExtra as h}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 R,statSync as W,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 H}from"node:path";import{fileURLToPath as G}from"node:url";import{loadCurriculumById as Z,validateEAToken as K,syncProgress as J,fetchServerProgress as X,syncCardFeedback as Q,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 pe,renderSyntax as he,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 Re,warmupEnabled as We}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 He,nextScratchN as Ge,readPyScratchSpool as Ze,scratchCodeSha as Ke,scratchDir as Je,scratchFilePath as Xe,scratchTitleOf as Qe,shrinkPyScratchSpool as Ve,spoolPyScratchEvent as eo,startRunTimer as oo,syncPyScratch as to}from"../lib/py-scratch.js";import{REQUIRED_PY as no,resolveRunPython as ro}from"../lib/aienv.js";let so;function lo(){return void 0!==so||(so=ro(e=>{try{return n(`${e} --version 2>&1`,{encoding:"utf-8",timeout:4e3,stdio:["ignore","pipe","pipe"]})}catch{return null}},process.platform,io())),so}const ao=()=>lo()?.cmd??"python3";import{homedir as io}from"node:os";import{getConfig as co,saveConfig as go}from"../lib/config.js";import{runType as uo}from"./type.js";import{isNativeWindows as po,isWindowsBuildInWslShell as ho,whichBinary as yo}from"../lib/platform.js";import{loadLearnState as mo,saveLearnState as fo,newLearnState as $o,stateFromServerEvents as bo,activateSession as wo,updateStreak as ko,markCardComplete as vo,recordMCQ as _o,recordCheck as Co,markPracticalComplete as Ao,addAchievement as xo}from"../lib/learn-state.js";import{renderWelcome as To,renderKnowledgeCard as So,renderMCQCard as Po,renderMCQFeedback as Io,renderPracticalCard as jo,renderPracticalSuccess as Eo,renderSimDemoCard as Lo,renderMilestone as Mo,renderArenaTaskCard as No,renderComingSoonCard as qo,renderStatus as Oo,renderPhaseComplete as Ro,renderCurriculumComplete as Wo,setLearnAiEnabled as Do,setLearnFaqs as Uo,setLearnFooterProfile as Yo,setLearnHometask as Bo,setLearnPracticeChips as Fo,setLearnPracticeCount as zo,setLearnHonorRanks as Ho,setLearnPqsViewCards as Go,setLearnReplies as Zo,setLearnWidth as Ko,resolveLearnWidth as Jo,learnWidthCap as Xo,learnW as Qo,renderHonorWall as Vo,wrapMixed as et}from"../lib/learn-render.js";import{printError as ot}from"../lib/ui.js";const tt=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","widest"],["wide max","widest"]]);function nt(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(ro){ro.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ro=>{ro?.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(),ro="LEARNDEMO01");let so=ro.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(so)){const{runSprint:e}=await import("./sprint.js");return void await e()}let rt=null;const st=/^[A-Z0-9]+DEMO01$/i.test(so),lt=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(so);let at=!1,it=!1,ct=[],dt=null,gt=-1,ut=Promise.resolve([]);if(st)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),ut=V(so),rt=await Z(so,so,!0);else if(lt){console.log(),console.log(chalk.gray(" Validating token..."));let e=await K(so);if(!e.ok){const o=me(so);if(o!==so){const t=await K(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${so} → ${o}`)),e=t,so=o)}}if(!e.ok)return ot(`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 🐼"):"")),at=!0===e.aiEnabled,it=!0===e.gated,ct=e.replies??[],dt=e.hometask??null,ut=V(so),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),rt=await Z(e.curriculumId||"LEARNDEMO01",so,!0),!rt)return ot(`Could not open a learn curriculum for token '${so}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${so}`)+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 ${so}`)+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(!rt){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(ot(`Could not reach the learn server to open ${so}.`),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 ${so}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(ot(`Unknown learn token: ${so}`),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 pt=mo(),ht=!1;try{if(pt&&pt.token===so)ko(pt);else{const e=wo(so);if(e)pt=e,pt.totalCards=rt.totalCards,ko(pt);else{const e=await X(so),o=e?bo(so,rt.id,rt.totalCards,e):null;o?(pt=o,console.log(chalk.green(" ↩ ")+chalk.white((co().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()):(pt=$o(so,rt.id,rt.totalCards),ht=!0)}}fo(pt),To(rt,pt,ht),function(e){if(!e)return;const o=(co().language||"en").toLowerCase().startsWith("zh"),t="T0"===ne().tier;nt(oe(e,o,Qo(),t),!!e.completedAt)}(dt)}catch{return ot("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 ${so}`)+chalk.gray(".")),void console.log()}const yt=x(),mt=null!==yt,ft=mt?yt.listeners("line").slice():[];mt&&yt.removeAllListeners("line");const $t=mt?yt:o({input:process.stdin,output:process.stdout,terminal:!0}),bt=mt?$t.prompt:null;mt&&($t.prompt=e.prototype.prompt);const wt=()=>{mt&&bt&&($t.prompt=bt)};let kt=null,vt=!1,_t=!1,Ct=null,At=!1;const xt=()=>{$t.setPrompt(Gt?chalk.bold.green(`icoa ${j()}> `):Ut?chalk.bold.magenta("icoa py> "):Dt?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Rt?"icoa learn ai> ":"icoa learn> ")),$t.prompt(),kt?.onPromptIdle()};let Tt=null,St=null,Pt=null,It=null,jt=[],Et=!1,Lt=null;const Mt=/^(quit|exit|q|back|b|menu|home|contest(\s+(\d+|reset))?)$/i;let Nt=null,qt=!1;const Ot=()=>{Lt&&clearTimeout(Lt),Lt=null,jt=[],Et=!1,It=null,Nt=null};let Rt=!1,Wt=!1,Dt=!1,Ut=!1,Yt=null,Bt=null,Ft=!1,zt=0,Ht=!1,Gt=!1;const Zt=new Map,Kt=()=>{let e=Zt.get(pt.currentCard);return e||(e=[],Zt.set(pt.currentCard,e)),e};let Jt=!1;const Xt=new Set;let Qt=!1,Vt=0;const en=()=>(co().language||"en").toLowerCase().startsWith("zh");Do(at),Ko(Jo(co())),Go(Xt);const on=new Map;Ho(on),Zo(ct),Bo(dt);const tn="fill"===rt.practiceMode;Yo("minimal"===rt.footerProfile?"minimal":"full"),Fo(e=>{const o=gn(e),t=o?er(o):null;if(!t)return null;const n=Cn.get(Jn+e);return t.map((e,o)=>`[${o+1}]${n?.has(Vn(e.py_id))||n?.has(e.py_id)?"✅":"⬜"}`).join(" ")});const nn=e=>{const o=gn(e),t=o?er(o):null;if(!t)return null;const n=Cn.get(Jn+e);return{solved:t.filter(e=>n?.has(Vn(e.py_id))||n?.has(e.py_id)).length,total:t.length}};zo(nn);const rn=await ut;Uo(rn);const sn=[];let ln=null;const an=new Promise(e=>{ln=e}),cn=()=>{const e=ln;ln=null,e?.()},dn="1"===process.env.ICOA_LEARN_EMBEDDED,gn=e=>rt.cards.find(o=>o.number===e);kt=c();const un={isZh:en,canInterrupt:()=>!(At||Wt||Rt||Dt||Ut||Gt||null!==Yt||null!==It||null!==Bt),lineEmpty:()=>!$t.line,clearLine:()=>{try{process.stdout.write("\r")}catch{}},prompt:xt,currentCard:()=>pt.currentCard};h(()=>{const e=[],o=kt?.footerLine();o&&e.push(o);const t=hn();return null!==t&&t>0&&t<=2&&e.push(en()?`🎁 还差 ${t} 项 · credits 看路线`:`🎁 ${t} to go · credits shows the road`),e.length?e.join("\n "):null});const pn=async(e,o)=>{const t=en();if(st)return void console.log(chalk.gray(t?"故事属于正式 learn token。":" Stories belong to full learn tokens."));const n=await y(so,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===rt.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(rt,pt,mn,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===rt.id?rt.name:s.curriculum_id,s.curriculum_id===rt.id?{longestStreak:pt.longestStreak,bookmarks:pt.bookmarks?.length??0}:{},t,Qo(),"T0"===ne().tier);console.log(),console.log(chalk.gray(t?" (回车跳到结尾)":" (Enter skips to the end)")),vt=!0,_t=!1;try{await k(l,()=>_t)}finally{vt=!1}if(s.curriculum_id===rt.id&&!s.credits?.completed){for(const e of w(rt,pt,mn,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()},hn=()=>{if(!pt||pt.creditsShownAt||st||!mn)return null;const e=b(rt,pt,mn);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])},yn=async(e=!1)=>{if(!pt||pt.creditsShownAt||st)return;const o=b(rt,pt,mn);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(mn&&t>0&&t<=2&&(e||pt.creditsTeasedLeft!==t)){pt.creditsTeasedLeft=t,fo(pt);const e=en(),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(rt,pt,mn,e))console.log(o);console.log()}return}pt.creditsShownAt=(new Date).toISOString(),fo(pt),await pn(null,!1),xt()};let mn=null,fn=null;const $n=new Map,bn=new Map;let wn=null;const kn=(e,o)=>wn?.[`${rt.id}:${e}:${o}`]??null;P("contest-cells.json").then(e=>{wn=e?.map??null;for(const[e,o]of Object.entries(wn??{}))e.startsWith(`${rt.id}:`)&&P(o)});const vn=(e,o,t)=>{const n=kn(e,o);if(!n)return null;const r=H(t,"explore.ipynb");if(!M(r)){const e=H(S(),n);if(!M(e))return null;try{D(r,O(e))}catch{return null}}return r},_n=!so.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(so),Cn=new Map,An=new Map,xn=new Set,Tn=async()=>{if(!_n)return;const e=await Ie(so);if(e.ok&&e.data){mn=e.data;for(const o of e.data.practice??[]){let e=Cn.get(o.slot);e||(e=new Set,Cn.set(o.slot,e));for(const t of o.solved)e.add(t)}yn()}},Sn=e=>{const o=rt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Pn=e=>{if(!it||!mn)return null;const o=Sn(e);if(o<=mn.unlocked_through_phase)return null;const t=mn.phases.find(e=>e.phase===mn.unlocked_through_phase),n=[chalk.yellow(en()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${mn.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${mn.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(en()?` ⚔ 练习赛 ${mn.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${mn.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(en()?` ⚖ 判分赛: 最好 ${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(en()?"、":", "),r=e.length>8?en()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:en()?" 张":"";n.push(chalk.gray(en()?` ✓ 逐卡自测: ${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(en()?` ⭐ 提问研究: ${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")},In=async e=>it?null===Pn(e)?null:(await Tn(),Pn(e)):null;_n&&await Tn();const jn=async e=>{const o=rt.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=rt.modules.find(e=>e.number===o.number+1);let n;if(at){const e=await fe({token:so,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}_n&&await Tn();const r=mn?.phases.find(e=>e.phase===o.number);return Ro(rt,pt,o,t,n,r),!0},En=()=>{Qt=!0,console.log(chalk.gray(en()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Ln=()=>{Bt=null;const e=gn(pt.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(kt?.noteCardShown(e.number,pt.cardsCompleted.includes(e.number)),e.type){case"knowledge":{const o=tn&&Boolean(pt.checkResults?.[String(e.number)])&&e.check?{...e,check:void 0}:e;So(o,rt),o.check?(Pt=e.number,Vt=Date.now()):(vo(pt,e.number),fo(pt));break}case"mcq":Po(e,rt),Tt=e.number;break;case"practical":jo(e,rt),St=e.number;break;case"sim_demo":Lo(e,rt),vo(pt,e.number),fo(pt);break;case"milestone":Mo(e,rt),xo(pt,e.badge),vo(pt,e.number),fo(pt);break;case"arena_task":No(e,rt),vo(pt,e.number),fo(pt);break;case"coming_soon":qo(e,rt),vo(pt,e.number),fo(pt)}Mn(e.number),tr(e)},Mn=e=>{if(!_n||!mn)return;const o=rt.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=mn.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n);if(!s)return;const l=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),l=(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?en()?` · 用时 ${r}`:` · in ${r}`:"")+(l?` · ${l}`:"")},a=s.perfect_runs??[],i=!!s.best&&(s.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Qo());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${en()?`练习赛 ${o.number}-${n}`:s.title||`PY Arena ${o.number}-${n}`}`)+(s.passed?chalk.bold.green(en()?" ✅ 已通过":" ✅ passed"):"")),!s.passed){if(en()?console.log(c+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(c+chalk.white("You learned the cards — now prove it.")),console.log(c+chalk.white("The clock starts the moment you type the command."))),console.log(c+chalk.gray(en()?`${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?en()?`(${e})`:` (${e})`:"";console.log(c+chalk.cyan(en()?`🔗 你另一个 token${o}已做过这组的 ${s.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens${o} solved ${s.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(en()?" 带过来(现在不做也行)":" to carry them over (or skip)"))}1!==o.number||tn||console.log(c+chalk.gray(en()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))}if(a.length>0)for(const e of a)console.log(c+chalk.bold.yellow(l(en()?"满分":"Perfect",s.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(l(en()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));3===n&&r?.leader&&console.log(c+chalk.white(en()?`🏅 本 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((en()," — "))+chalk.bold.green("/honors")+chalk.gray(en()?" 看你的位置":" shows where you stand")),console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(s.passed?chalk.gray(en()?" 再战刷成绩 · ":" race it again · "):chalk.gray(en()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(en()?" 继续学习":" keep going"):chalk.gray(en()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(en()?" 日后回来整阶段重做 · 全新计时+模板(旧文件自动归档)":" come back later and redo the whole phase · fresh clock + templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Nn=()=>{so.endsWith("DEMO01")?console.log(chalk.yellow(en()?" 🐼 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(en()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(en()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},qn=async(e,o)=>{if(at){kt?.noteAi("deep"===o),Wt=!0;try{console.log(),console.log(chalk.gray("deep"===o?en()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":en()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await we({token:so,cardNumber:pt.currentCard,question:e,mode:o,history:Kt().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(en()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Kt().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(` (${en()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(en()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Pt&&console.log(chalk.gray(en()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Wt=!1}}else Nn()},On=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Rn=async()=>{Dt&&fn?ur?hr(ur):cr():Bt?await Wn():Ln()},Wn=async()=>{Wt=!0;try{console.log();const e=await _e({token:so,curriculumId:rt.id,cardNumber:pt.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(en()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(_n&&(await Tn(),(e=>{const o=rt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const[t,n]=o.cardRange,r=pt.checkResults||{};let s=0,l=0,a=0;for(let e=t;e<=n;e++){const o=gn(e);null!=o?.check&&a++;const t=r[String(e)];t&&(s++,t.correct&&l++)}console.log(chalk.bold.white(en()?` 🧭 Phase ${o.number} 进度 — ${o.name}(卡 ${t}-${n})`:` 🧭 Phase ${o.number} progress — ${o.name} (cards ${t}-${n})`)),console.log(chalk.gray(en()?" 理解检查: ":" comprehension: ")+chalk.white(`${l}/${s}`)+chalk.gray(en()?` 答对 · ${a-s} 张未作答`:` correct · ${a-s} unanswered`));const i=mn?.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(en()?`未开始 · ${e.n} 题 · 过 ${e.need} 题`:`not started · ${e.n} problems · AC ${e.need}`):chalk.yellow(en()?`最好 ${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(` ⚔ ${en()?"练习赛":"arena"} ${o.number}-${e.slot}: `)+t)}const c=[];let d=0,g=0,u=0,p=0;for(let e=t;e<=n;e++){const o=nn(e);o&&(g++,u+=o.solved,p+=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(en()?" 卡片练习: ":" practice: ")+chalk.white(`${d}/${g}`)+chalk.gray(en()?` 卡全完成 · ${u}/${p} 题 AC`:` cards complete · ${u}/${p} 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(en()?" 卡号:已过/共 — 绿 全完成 · 黄 做了一部分 · 灰 未碰":" card:solved/total — green done · yellow partial · gray untouched"))}console.log()})(pt.currentCard)),console.log(chalk.bold.white(en()?` 🏆 本卡实时 Top-3 — 第 ${pt.currentCard} 张`:` 🏆 Live top-3 — card ${pt.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(en()?" (你)":" (you)"):""))}else console.log(chalk.gray(en()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));if(e.mine?(on.set(pt.currentCard,e.mine.rank),console.log(chalk.white(en()?" 你: ":" You: ")+chalk.bold.yellow(en()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(en()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):at&&console.log(chalk.gray(en()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Vo({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),e.phaseBoard){const o=e.phaseBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(en()?` 🏅 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(en()?" (还没有人有研究总分 — 第一个 /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(en()?`(${e.cards}/${o.cards_in_phase} 卡)`:` (${e.cards}/${o.cards_in_phase} cards)`)+(e.me?chalk.bold.magenta(en()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(en()?` 总分 ${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(en()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.total}`)+chalk.gray(en()?`(${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&&at&&console.log(chalk.gray(en()?" 你: 还未计入 — /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(en()?` ⚔ 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(en()?" (还没有人 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(en()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(en()?` 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(en()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.ac} AC`)+chalk.gray(en()?` · 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` · rank ${o.mine.rank} of ${o.mine.entrants}`)):o.mine||console.log(chalk.gray(en()?" 你: 还未计入 — 在有 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(en()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(en()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(en()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Bt="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(en()?" 返回卡片":" returns to the card")),console.log()}finally{Wt=!1}},Dn=e=>en()&&e.title_zh||e.title,Un=We(rt.id);let Yn=!1;const Bn=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of et(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Fn={cpp:"cpp",java:"java",go:"go"},zn=e=>e?.lang&&Fn[e.lang]?e.lang:"python",Hn=(e,o)=>{const t=zn(o);return`sol-${e}.${"python"===t?"py":Fn[t]}`},Gn=(e,o)=>{const t=[...Un?[{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=Un&&s===qe,a=l?`══ ${t.title} ══`:`══ ${e.title||"PY Arena"} · ${t.title} ══`;for(const e of["py",...Object.values(Fn)]){const l=H(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{R(l,`${l}.archived-${n}`),r++;const e=H(o,`sample-${s}.txt`);M(e)&&!(t.samples??[])[0]&&R(e,`${e}.archived-${n}`)}catch{}}const i=(t.samples??[])[0];i&&D(H(o,`sample-${s}.txt`),i.in.endsWith("\n")?i.in:`${i.in}\n`);const c=H(o,Hn(s,t));if(M(c))return;const d=[l?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Bn(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 et(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"===zn(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(en()?` 📦 本组题目已更换 — ${r} 个旧题答题文件已归档为 *.archived-${n},新题文件已就位`:` 📦 This group's problems changed — ${r} old solution file(s) archived as *.archived-${n}, fresh files written`))},Zn=e=>{console.log(),console.log(chalk.bold.green(en()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(en()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Kn=e=>e.id===Ne?Yn?"✅":"⬜":fn.data.solved.includes(e.id)?"✅":fn.data.carried?.includes(e.id)?"✅↗":fn.tried.has(e.id)?"❌":"⬜",Jn=100,Xn=()=>!!fn&&fn.data.slot>=Jn,Qn=(e,o)=>{const t=H(process.cwd(),"icoa-contest",`${rt.id}-phase${e}-g${o}`);if(!M(t))return;const n=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{R(t,`${t}-archived-${n}`),console.log(chalk.gray(en()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${n}`))}catch{console.log(chalk.yellow(en()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (restart still fine): ${t}`))}},Vn=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,er=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},or=()=>{if(!tn)return!1;const e=gn(pt.currentCard),o=e?er(e):null;if(!e||!o||xn.has(e.number))return!1;const t=Jn+e.number,n=Cn.get(t),r=An.get(t),s=o.map((e,o)=>{return t=e.py_id,Boolean(n?.has(Vn(t))||n?.has(t)||r?.has(Vn(t))||r?.has(t))?0:o+1;var t}).filter(e=>e>0);return 0!==s.length&&(console.log(chalk.yellow(en()?` ⚔ 这张卡还有 ${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(en()?" 开始,或 ":" to start, or ")+chalk.bold.yellow("skip")+chalk.yellow(en()?" 跳过本卡练习。":" to skip this card's practice.")),!0)},tr=e=>{const o=er(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=Cn.get(Jn+e.number);console.log(chalk.bold.yellow(en()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(en()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(Vn(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(en()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},nr=e=>e.split("\n").filter(e=>!e.trim().startsWith("#")).join("\n").split("____").length-1,rr=e=>{console.log(chalk.yellow(en()?` ⏱ 每次练习 ${e} 分钟,这次的时间到了。`:` ⏱ Each practice window is ${e} minutes — this one has run out.`)),console.log(chalk.gray(en()?" 敲 ":" Type ")+chalk.bold.green("back")+chalk.gray(en()?" 回卡片,再敲 ":" for the card, then ")+chalk.bold.green("practice 1")+chalk.gray(en()?" 重新开始(重新计时)。":" to restart with a fresh clock."))},sr=()=>Yt?Yt.data.problems[Yt.idx]??null:null,lr=()=>{const e=sr();if(!Yt||!e)return;const o=nr(e.starter??""),t=Yt.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(en()?` 空${t}/${o}`:` blank ${t}/${o}`)+chalk.gray(" · ")+chalk.white(n)),console.log(chalk.gray(en()?" ▸ 敲答案后回车(back 回卡片)":" ▸ type the answer, press Enter (back = card)"))},ar=()=>{const e=sr();if(!Yt||!e)return;const o=en()&&e.title_zh?e.title_zh:e.title;console.log(),console.log(chalk.bold.yellow(` ⚡ ${en()?"练习":"Practice"} ${Yt.idx+1}/${Yt.data.problems.length} · ${o}`));const t=((en()&&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(),lr()},ir=()=>{if(Yt){if(Yt.idx+1<Yt.data.problems.length)return Yt.idx+=1,Yt.answers=[],Yt.tries=0,void ar();console.log(chalk.bold.green(en()?" 🎉 本卡练习全部完成!":" 🎉 Card practice complete!")+chalk.gray(en()?" ok 进下一张卡。":" ok moves on to the next card.")),Yt=null,Ln()}},cr=()=>{const e=fn.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>=Jn?e.slot-Jn:null;if(console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(null!=s?en()?` · 第 ${s} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${s} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:en()?` · 第 ${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(en()?" ⏱ 已超时 — 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(en()?`(共 ${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(en()?` 🎉 满分 ${e.n}/${e.n} — 本组全部拿下!`:` 🎉 Perfect ${e.n}/${e.n} — every problem cleared!`)+chalk.gray(en()?" ↩ back 回卡片":" ↩ back returns to the card"):chalk.green(en()?" 🏁 已过关":" 🏁 passed")+chalk.yellow(en()?` · 还剩 ${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(en()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" 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?en()?`(${o})`:` (${o})`:"";console.log(chalk.cyan(en()?` 🔗 你另一个 token${t}已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens${t} solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(en()?" 带过来,不必重做":" 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(en()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(en()?"不够就 ":"Short on time? ")+chalk.bold.green("contest restart")+chalk.gray(en()?" 满血重开本组。":" restarts this group fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(en()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),Un&&(console.log(chalk.gray(" 0 ")+Kn(Me)+chalk.gray(` ${Dn(Me)}`)+chalk.gray(en()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+Kn(e)+(e.gpu?chalk.magenta(" ⚡"):"")+chalk.white(` ${Dn(e)}`))}),e.problems.some(e=>e.gpu)&&(console.log(),console.log(e.gpu_window?chalk.bold.green(en()?" ⚡ GPU 窗口:开 ✅":" ⚡ GPU window: OPEN ✅")+chalk.gray(en()?" — 带 ⚡ 的层现在 /submit 就在真 GPU 上跑":" — /submit a ⚡ rung and it runs on a real GPU right now"):chalk.gray(en()?" ⚡ GPU 窗口:关(每周一 19:00–21:45 悉尼开放)— 带 ⚡ 的层等窗口内 /submit":" ⚡ GPU window: closed (Mondays 19:00–21:45 Sydney) — /submit ⚡ rungs inside the window"))),kn(fn.phase,e.slot)&&(console.log(),console.log(chalk.gray(" ✍ ")+chalk.bold.green("cells")+chalk.gray(en()?" 在 notebook 里探索本场数据(引导走查 · 真图) — 不判分,判分仍走 /submit":" explore this lab in a notebook (guided walkthrough · real figures) — ungraded; judging stays /submit"))),console.log(),dr()},dr=()=>{console.log(chalk.gray(en()?" /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(en()?"/syntax <词>":"/syntax <word>")+chalk.gray(en()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(en()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(en()?" 返回课程":" returns to the lesson")),console.log(chalk.gray(en()?" memo 报告题面/判分问题 — 不打断比赛计时":" memo reports a statement/judging problem — the clock is unaffected")),console.log(chalk.gray(" ")+chalk.bold.green("contest restart")+chalk.gray(en()?" 超时/坏场时重开本组(全新计时+模板) · ":" time up or broken attempt → this group again (fresh clock + templates) · ")+chalk.bold.green("contest reset")+chalk.gray(en()?" 日后回来整阶段重做":" come back later and redo the whole phase")),console.log()},gr=e=>{const o=parseInt(e,10),t=fn.data.problems;if(o===qe&&Un)return{p:Me,n:qe};const n=Un?qe:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(en()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),Un&&console.log(chalk.gray(en()?" 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 ur=null,pr=!1;const hr=e=>{const o=gr(e);if(!o)return;const{p:t,n:n}=o;ur=String(n),console.log(),console.log(chalk.bold.white(` ${Kn(t)} ${Dn(t)}`)),console.log();for(const e of(e=>en()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of et(e,Qo()+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(en()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(en()?" 应输出:":" 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(en()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(en()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=en()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of et(o,Qo()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(en()?"数据就在上方 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(),Un&&n===qe)return console.log(chalk.white(en()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(en()?"第 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(en()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(en()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((en()," ↩ "))+chalk.bold.green("back")+chalk.gray(en()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(en()?" 直接看正式题目":" skips straight to the real problems")),void console.log();t.gpu?(console.log(chalk.white(en()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(en()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(en()?"真 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(en()?" 三步:":" Three steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(en()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(en()?"本机直跑,出你自己的 ms":"run it locally — see your own ms")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(en()?"参考机判分(成绩 = 那里的 ms)":"judge on the reference machine (the scored ms)"))):(console.log(chalk.white(en()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(en()?"写码(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(en()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(en()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(en()?"正式判分(隐藏用例)":"official judging (hidden tests)"))),console.log(),console.log(chalk.gray(en()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(en()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((en()," ↩ "))+chalk.bold.green("back")+chalk.gray(Xn()?en()?" 回花名册 · ":" to the roster · ":en()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(en()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((en()," / "))+chalk.bold.green("wide")+chalk.gray(en()?" 换语言/宽度":" language / width")),console.log()},yr=async(e,o,t)=>await new Promise(n=>{const l=process.stdin,a=!!l.isTTY&&!!l.isRaw;if($t.pause(),l.isTTY&&"function"==typeof l.setRawMode)try{l.setRawMode(!1)}catch{}At=!0;const i=r(e,o,{stdio:"inherit",cwd:t??fn.dir}),c=e=>{if(l.isTTY&&"function"==typeof l.setRawMode&&a)try{l.setRawMode(!0)}catch{}s(),At=!1,$t.resume(),n(e)};i.on("close",()=>c(null)),i.on("error",e=>c(e))}),mr=["-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"],fr=()=>{const e=A("vi");console.log(chalk.gray(en()?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"))},$r=()=>{console.log(chalk.yellow(en()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(en()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(en()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(en()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},br=new Map,wr=()=>Je(process.cwd(),rt.id),kr=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())}`},vr=async(e,o,t=!1)=>{if(!_n)return;let n;try{n=O(Xe(wr(),e),"utf-8")}catch{return}if(Buffer.byteLength(n,"utf-8")>De)return;const r=Ke(n),s=(new Date).toISOString(),l=Ze(io(),so).slice(0,Be),a=await to(so,{n:e,title:Qe(n.split("\n",1)[0]),code:n,code_sha:r,card_number:pt.currentCard,run_meta:o,client_ts:s,events:l.length>0?l:void 0});a?l.length>0&&Ve(io(),so,l.length):eo(io(),so,{n:e,code_sha:r,card_number:pt.currentCard,run_meta:o,client_ts:s}),a||t||console.log(chalk.gray(en()?" (未能同步到服务器 — 草稿只保存在本机)":" (could not reach the server — this scratch is saved locally only)"))},_r=()=>{console.log(chalk.gray(en()?" 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()},Cr=e=>{const o=ze(wr()),t=parseInt(e,10);return Number.isInteger(t)&&o.some(e=>e.n===t)?t:(0===o.length?console.log(chalk.yellow(en()?" 还没有任何草稿 — ":" No scratch files yet — ")+chalk.bold.green("/py")+chalk.gray(en()?" 新建第一个。":" creates the first one.")):console.log(chalk.yellow(en()?` 没有 py-${e} — 现有编号: `:` No py-${e} — you have: `)+chalk.white(o.map(e=>e.n).join(", "))+chalk.gray(en()?" · pylist 看列表":" · pylist shows them")),null)},Ar=e=>{const o=ze(wr()),t=e?.trim().toLowerCase(),n=t?o.filter(e=>(e.title??"").toLowerCase().includes(t)):o;if(console.log(),console.log(chalk.bold.magenta(en()?" ✍ 我的 Python 草稿":" ✍ My Python scratch files")+(t?chalk.gray(` · "${e?.trim()}"`):"")+chalk.gray(` (${n.length})`)),0===o.length)return console.log(chalk.gray(en()?" 还没有草稿 — ":" Nothing here yet — ")+chalk.bold.green("/py")+chalk.gray(en()?" 新建一个(第一行写标题)。":" creates one (line 1 becomes its title).")),void console.log();if(0===n.length)return console.log(chalk.gray(en()?` 没有匹配 "${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(et(e.title,40)[0]??e.title):chalk.gray(en()?"(未命名 — 第一行写标题)":"(untitled — line 1 becomes the title)");console.log(chalk.gray(` py-${String(e.n).padEnd(3)} `)+o+chalk.gray(` · ${kr(e.mtimeMs)}`))}console.log(chalk.gray(" ▸ ")+chalk.bold.green(en()?"/py <编号>":"/py <n>")+chalk.gray(en()?" 打开 · ":" opens one · ")+chalk.bold.green("/py")+chalk.gray(en()?" 新建":" new file")),console.log()},xr=async e=>{const o=Xe(wr(),e);if(po())return console.log(chalk.yellow(en()?" icoa 正跑在 Windows 上 — 草稿本的编辑器在 Ubuntu(WSL)那一侧。":" icoa is running on Windows — the scratchpad editor lives on the Linux (WSL) side.")),console.log(chalk.gray(en()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${o}`)),void console.log();if(!yo("vi"))return console.log(chalk.yellow(en()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${o}`)),void console.log(chalk.gray(en()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));fr();const t=e=>{try{return W(e).size}catch{return 0}},n=t(o),r=Date.now(),s=C(o);await yr("vi",[...mr,`py-${e}.py`],wr());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 vr(e),console.log(chalk.gray(en()?" 已回到草稿本 — ":" Back in the scratchpad — ")+chalk.bold.green(`run ${e}`)+chalk.gray(en()?" 本机运行 · ":" runs it locally · ")+chalk.bold.green(`edit ${e}`)+chalk.gray(en()?" 再改。":" reopens vi.")),console.log()},Tr=async e=>{let o;if(N(wr(),{recursive:!0}),e){const t=Cr(e);if(null===t)return;o=t}else{const e=ze(wr());o=Ge(e),o>Ue&&console.log(chalk.gray(en()?` (已超过 ${Ue} 个 — 服务器不再备份新文件,本机照常保存)`:` (past ${Ue} files — the server stops backing new ones up; local saves still work)`)),D(Xe(wr(),o),`${en()?Fe:Ye}\n\n`)}const t=!Ut;Ut=!0,_(`learn-py: open ${o}${e?"":" (new)"}`),t&&(console.log(),console.log(chalk.bold.magenta(en()?" ✍ Python 草稿本":" ✍ Python scratchpad")+chalk.gray(en()?" — 你的个人练习文件 · 只在本机运行 · 不判分":" — your personal practice files · runs locally · never judged")),console.log(chalk.gray(en()?" 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(en()?" 回卡片(退一层)":" returns to the card (one level)"))),await xr(o),_r()},Sr=async e=>{const o=e.trim().toLowerCase(),s=Dt&&o.startsWith("/")?o.slice(1):o;if(vt)return void(_t=!0);if(Ct){const{sameName:o,issueCertificate:t,announceCertificate:n}=await import("../lib/learn-certificate.js"),r=e.trim(),s=en();if(!r||Mt.test(r))return Ct=null,console.log(chalk.gray(s?" 已取消,未签发。":" Cancelled — nothing issued.")),void xt();if(null===Ct.first)return Ct.first=r,console.log(chalk.gray(s?" 再输一次:":" Type it once more:")),void xt();const l={cid:Ct.cid,tok:Ct.tok,first:Ct.first};return Ct=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 xt()):(console.log(chalk.yellow(s?" 两次输入不一致 — 未签发。再敲 certificate 重来。":" The two names differ — nothing issued. Type certificate to try again.")),void xt())}if(Wt)return;if(kt?.noteInput(),kt?.consumeRating(o))return void xt();if(Yt)return await(async e=>{if(!Yt)return;const o=e.trim(),t=o.toLowerCase(),n=Boolean(sr()?.quiz);if("back"===t||"b"===t&&!n||"quit"===t||"menu"===t)return Yt=null,console.log(chalk.gray(en()?" ↩ 回到卡片。":" ↩ Back on the card.")),void Ln();if("skip"===t)return void ir();if(""===o)return void ar();const r=sr();if(!r)return Yt=null,void Ln();const s=nr(r.starter??"");if(Yt.answers.push(o),Yt.answers.length<s)return void lr();const l=[...Yt.answers],a=((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")})(r.starter??"",l);Yt.answers=[];let i=An.get(Yt.slot);i||(i=new Set,An.set(Yt.slot,i)),i.add(r.id);const c=Boolean(r.quiz),d=c?null:new I(so);d?.start();const g=await xe(so,Yt.phase,r.id,a,Yt.slot,void 0);if(d?.stop(),!Yt)return;if(!g.ok||!g.data)return"no_active_session"===g.code?void rr(Yt.data.duration_minutes):(console.log(chalk.red(` ✗ ${g.message||"judging failed"}`)),console.log(chalk.gray(en()?" 再敲一遍空1重试,或 back 回卡片。":" Type blank 1 again to retry, or back for the card.")),void lr());const u=g.data;if("AC"!==u.verdict||u.already_ac||kt?.notePracticeAc(),u.already_ac||"AC"===u.verdict){c?console.log(chalk.bold.green(en()?" ✅ 答对了!":" ✅ Correct!")):console.log(chalk.bold.green(" ✅ AC!")+chalk.gray(` · ${u.passed_tests??u.total_tests??"?"}/${u.total_tests??"?"} `+(en()?"用例全过":"tests passed")));let e=Cn.get(Yt.slot);return e||(e=new Set,Cn.set(Yt.slot,e)),e.add(r.id),Yt.data.solved.includes(r.id)||Yt.data.solved.push(r.id),void ir()}Yt.tries+=1,c?console.log(chalk.red(en()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(en()?" — 再选一次。":" — pick again.")):console.log(chalk.red(` ✗ ${u.verdict??"WA"}`)+chalk.gray(en()?" — 还没对,再来。":" — not yet."));const p=r.samples?.[0];if(p?.out){console.log(chalk.gray(en()?" 期望输出:":" Expected output:"));for(const e of p.out.trimEnd().split("\n"))console.log(chalk.white(" "+e))}if(2===Yt.tries||Yt.tries>2&&Yt.tries%3==2){const e=c?[]:((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(en()?` ⚠ 空${i}:模板里 ____ 后面已经有 ( ) — 只填名字,别再带括号。`:` ⚠ blank ${i}: the ( ) after ____ is already in the template — type just the name, no brackets.`):(/["']$/.test(a)||/^["']/.test(l))&&/^["']|["']$/.test(s)?t.push(en()?` ⚠ 空${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(en()?` ⚠ 空${i}:____ 后面已有右括号,你的答案可能多带了一个 )。`:` ⚠ blank ${i}: a closing ) already follows ____ — your answer may carry one too many.`)}}return t})(r.starter??"",l);for(const o of e)console.log(chalk.yellow(o));console.log(chalk.gray(en()?" 💡 两次没过,多半是细节不是思路 — 再敲之前过一遍:":" 💡 Two misses are usually a detail, not the idea — run this check before retrying:")),c||(console.log(chalk.gray(en()?" · 拼写和大小写(Python 区分大小写:Print ≠ print)":" · spelling and case (Python is case-sensitive: Print ≠ print)")),console.log(chalk.gray(en()?" · 只填缺的那一块 — ____ 周围已有的括号、引号、冒号不要重复":" · fill only what is missing — brackets, quotes, colons already around ____ stay"))),console.log(chalk.gray(en()?" · 没思路?往上翻,或 ":" · no idea? scroll up, or ")+chalk.bold.green("back")+chalk.gray(en()?" 回卡片再读一遍 — 答案就在正文里。打错字人人都有,继续。":" re-reads the card — the answer is in its body. Typos happen to everyone; keep going."))}console.log(chalk.gray(en()?" 从空1再来:":" From blank 1 again:")),lr()})(e),void xt();if(null!==It){if(jt.push(e.replace(/\s+$/,"")),Lt&&clearTimeout(Lt),Lt=null,Et){const e=jt[jt.length-1]??"";return"/cancel"===e.trim()?(Ot(),console.log(chalk.gray(en()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void xt()):""!==e.trim()?void xt():(jt.pop(),void await c())}return void(Lt=setTimeout(()=>{if(Lt=null,jt.length>1){Et=!0;const e=jt.length;return console.log(chalk.cyan(en()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(en()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void xt()}c()},140))}async function c(){const e=jt.join("\n").replace(/^\s+|\s+$/g,""),o=It??pt.currentCard,t=jt.length,n=Nt;if(Ot(),""===e)console.log(chalk.gray(en()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&Mt.test(e))console.log(chalk.yellow(en()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(en()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(en()?" 即可执行。":" again to run it."));else{const r=!n&&Vt>0?Date.now()-Vt:void 0;if(await Q(so,{curriculum_id:rt.id,card_number:o,feedback_text:n?`${n} ${e}`:e,time_on_card_ms:r})){const n=t>1?en()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(en()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(en()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),ct=[...ct,{id:gt--,curriculumId:rt.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Zo(ct)}else console.log(chalk.yellow(en()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),xt()}if(Ft){const o=e.trim();if(Mt.test(o))return Ft=!1,console.log(),console.log(chalk.yellow(en()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(en()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(en()?" 即可执行该命令。":" again to run it.")),console.log(),void xt();if(!o)return Ft=!1,console.log(chalk.gray(en()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void xt();const t=await be({token:so,nickname:o});if(t.ok)Ft=!1,console.log(chalk.bold.green(en()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(en()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{zt+=1;const e="taken"===t.code?en()?"已被占用":"already taken":"bad_charset"===t.code?en()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"real_name"===t.code?en()?"看起来像真名 — 系统不收集个人信息,换个游戏风格的昵称":"looks like a real name — we collect no personal info; pick a gamer-style handle":"rejected"===t.code?en()?"未通过审核":"did not pass review":t.message||"error";if(!(zt>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(en()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void xt();Ft=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(en()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void xt()}if(Jt){Jt=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Wt=!0;try{console.log(),console.log(chalk.gray(en()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await ke({token:so,cardNumber:pt.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(en()?"评审暂不可用。":"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(en()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(en()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(en()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(en()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(en()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(en()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=en()?` 本卡排名 #${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(en()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(en()?` 第 ${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 On(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(en()?" 改进提问: ":" 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(` (${en()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Xt.add(pt.currentCard):Xt.delete(pt.currentCard),"number"==typeof e.rank&&on.set(pt.currentCard,e.rank);const o=await _e({token:so,curriculumId:rt.id,cardNumber:pt.currentCard});if(o.ok&&o.totals&&o.chapters&&(Vo({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(en()?` · 榜首 ${n.name||"Rank 1"} ${n.total}`:` · leader ${n.name||"Rank 1"} at ${n.total}`):chalk.bold.yellow(en()?" · 全场第一!":" · phase leader!");console.log(chalk.white(en()?` 🏅 Phase ${e.phase} 研究总分: `:` 🏅 Phase ${e.phase} research total: `)+chalk.bold.yellow(`${t.total}`)+chalk.gray(en()?`(${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&&!st&&(Ft=!0,zt=0,console.log(chalk.bold.yellow(en()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(en()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(en()?" 英文开头,英文+数字,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{Wt=!1}})():(console.log(chalk.gray(en()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Pt&&(console.log(chalk.gray(en()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void xt()}if(Qt)return Qt=!1,Ln(),void xt();if(!o)return void xt();if(Gt)return"exit"===await E(e.trim())&&(Gt=!1),void xt();if(Rt){if(["q","quit","exit","back","b","menu"].includes(o))return Rt=!1,console.log(chalk.gray(en()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void xt();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(en()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(s?en()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":en()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(en()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(en()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void xt()):(n&&(await qn(n,t?"fast":"deep"),console.log(chalk.gray(en()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void xt())}if(Ut){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 Ut=!1,console.log(chalk.gray(en()?" ↩ 已离开草稿本,回到卡片。":" ↩ Left the scratchpad — back to the card.")),Ln(),void xt();const t=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(t||"list"===o||"/list"===o)return Ar(t?.[1]),_r(),void xt();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=Cr(o);null!==t&&("edit"===e?(await xr(t),_r()):await(async e=>{if(!M(Xe(wr(),e)))return void Cr(String(e));const o=lo()?.cmd??null;if(!o)return console.log(chalk.yellow(en()?` 找不到 Python ${no.major}.${no.minor} — 草稿本和判分机固定在同一条 3.12 版本线上。`:` Python ${no.major}.${no.minor} not found — the scratchpad runs on the same 3.12 line as the judge.`)),console.log(chalk.gray(en()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3.12")+chalk.gray(en()?" — 或 quit 回 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")),void console.log();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:wr(),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(en()?" ⏱ 超过 30 秒,已停止 — 检查死循环。":" ⏱ Over 30s — stopped. Check for an infinite loop."))),console.log(chalk.gray((en()," ▸ edit "))+chalk.gray(`${e} · pylist · `)+chalk.bold.green("back")),console.log(),sn.push(vr(e,{run_ms:c,exit_code:i,stderr_head:l.trim().slice(0,300)||void 0},!0).catch(()=>{}))})(t))}else console.log(chalk.yellow(en()?` 用法: ${e} <编号>`:` Usage: ${e} <n>`)+chalk.gray(en()?" (pylist 看编号)":" (pylist shows the numbers)"));return void xt()}const s=/^\/?py(?:\s+(\S+))?$/.exec(o);if(s||"new"===o)return await Tr(s?.[1]),void xt();if("menu"!==o&&"menu confirm"!==o)return console.log(chalk.gray(en()?" 草稿本命令: edit <n> · run <n> · pylist · /py 新建 · back 回卡片":" Scratchpad verbs: edit <n> · run <n> · pylist · /py (new) · back to the card")),void xt()}if(Dt&&fn){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${fn.phase}s${fn.data.slot}: ${o}`),"memo"===o||"/memo"===o||"e"===o)return It=pt.currentCard,Nt=`[arena p${fn.phase}-g${fn.data.slot}${ur?` #${ur}`:""}]`,console.log(chalk.gray(en()?` 报告归到: 竞技场 p${fn.phase}-g${fn.data.slot}${ur?` 题${ur}`:""} — 题面 / 判分 / 环境,一句话即可:`:` Files under: arena p${fn.phase}-g${fn.data.slot}${ur?` problem ${ur}`:""} — statement / judging / environment, one line is enough:`)),console.log(chalk.gray(en()?" (回车提交 · 空行取消 · 不打断比赛计时)":" (Enter to submit · blank to cancel · the contest clock is unaffected)")),void xt();if("back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Xn()&&null!==ur?(ur=null,cr(),void xt()):(Dt=!1,ur=null,console.log(chalk.gray(en()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Ln(),void xt());if(/^\d+$/.test(o))return hr(o),void xt();const n=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(n)return Xn()?n[1]?hr(n[1]):cr():console.log(chalk.gray(en()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void xt();if("cells"===o||"/cells"===o||"explore"===o||"/explore"===o){const e=vn(fn.phase,fn.data.slot,fn.dir);if(!e)return console.log(chalk.gray(kn(fn.phase,fn.data.slot)?en()?" 引导 notebook 还没下载到位(需要联网一次)— 稍后再敲 cells。":" The guided notebook has not downloaded yet (needs one online moment) — try cells again shortly.":en()?" 本场没有引导 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 xt();const o=null!==x();o||T($t);try{const{runIpynb:o}=await import("./ipynb.js");await o(e)}catch(e){console.log(chalk.yellow(en()?" notebook 没打开: ":" The notebook failed to open: ")+chalk.gray(String(e)))}finally{o||T(null)}return cr(),void xt()}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(en()?` (离线:只有 ${ye()} 条核心速查可用;联网后自动补全)`:` (offline: ${ye()} core entries available; the rest arrive when you have a connection)`))),!o)return void ue(en());const t=ce(o);if(t.length){he(t[0],en());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(en()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await ie("python3",o);if(n)pe(n,en());else{if(await de()){const e=ce(o);if(e.length)return void he(e[0],en())}console.log(),console.log(chalk.yellow(en()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(en()?" 试试: ":" Try: ")+chalk.cyan(ge(o).join(" · "))),console.log(chalk.gray(en()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(r[1]??""),void xt();const l=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(l){const[,e,o]=l;return"list"===e?cr():o?"read"===e||"open"===e?hr(o):"edit"===e?await(async e=>{const o=gr(e);if(!o)return;const t=H(fn.dir,Hn(o.n,o.p));if(po())return ho()?(console.log(chalk.yellow(en()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(en()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(en()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(en()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(en()?" ← 不能是 /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(en()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(en()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(en()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(en()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(en()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(en()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(en()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(en()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!yo("vi"))return console.log(chalk.yellow(en()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(en()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));fr();const n=e=>{try{return W(e).size}catch{return 0}},r=n(t),s=Date.now(),l=C(t);await yr("vi",[...mr,Hn(o.n,o.p)]);const a=l.stop(),i={ms:Date.now()-s,bytesBefore:r,bytesAfter:n(t)};if($n.set(o.n,Y($n.get(o.n)??U(),i)),a.ticks>0){const e=bn.get(o.n)??{list:[],dropped:0};e.list.push(a),e.list.length>16&&(e.list.shift(),e.dropped++),bn.set(o.n,e)}_(`learn-arena edit-done ${Hn(o.n,o.p)}`,{...i,...a.ticks>0?{samples:a}:{}}),console.log(chalk.gray(en()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(en()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=gr(e);if(!o)return;const{p:n,n:r}=o;if(Un&&r===qe)return void(()=>{const e=H(fn.dir,`sol-${qe}.py`);if(!M(e))return void console.log(chalk.yellow(en()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=[];for(const n of Oe)try{o.push(t(ao(),[e],{input:`${n.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}))}catch(e){const o=e;if("ENOENT"===o.code)return void $r();if(console.log(),o.killed)return void console.log(chalk.yellow(en()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(en()?` ✗ 输入 ${n.in} 时程序报错:`:` ✗ Your program crashed on input ${n.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(en()?" 改完再来: ":" Fix it and rerun: ")+chalk.bold.green("/edit 0")+chalk.gray(" → ")+chalk.bold.green("/run 0")),void console.log()}const{cases:n,passed:r}=Re(o);console.log();for(const e of n)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(en()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),r===n.length){const e=Yn?null:1;Yn=!0,console.log(chalk.bold.green(en()?` 🎉 ${r}/${n.length} 全过 — `:` 🎉 ${r}/${n.length} — `)+chalk.white(en()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(en()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(en()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(en()?` ${r}/${n.length} 通过 — 还差一点。`:` ${r}/${n.length} passed — not there yet.`)+chalk.gray(en()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(en()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const s=H(fn.dir,Hn(r,n));if(!M(s))return void console.log(chalk.yellow(en()?` 还没有 ${Hn(r,n)} — 先 /edit ${r}。`:` No ${Hn(r,n)} yet — /edit ${r} first.`));$n.set(r,F($n.get(r)??U()));const l=(n.samples??[])[0];if(n.gpu)return console.log(chalk.gray(en()?" ⚡ 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(en()?"(窗口时间执行并返回你的 ms;窗口外会告诉你开放时间)":" (executes in the GPU window and returns your ms; outside the window it tells you the hours)")),void console.log();if(!l&&n.starter){const e=zn(n),o={cpp:"c++",java:"java",go:"go"};if("python"!==e&&!yo(o[e]))return console.log(chalk.gray(en()?` 本机没有 ${o[e]} — 这一层的计时以判分机为准,直接 `:` No local ${o[e]} — the judge compiles and times this level; go straight to `)+chalk.bold.green(`/submit ${r}`)),void console.log();try{let o;if("cpp"===e){const e=H(fn.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 o="java"===e?t("java",[s],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):"go"===e?t("go",["run",s],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}):t(ao(),[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(en()?` ${He(!0)} — 满意就 `:` ${He(!1)} — happy? `)+chalk.bold.green(`/submit ${r}`))}catch(e){const o=e;if("ENOENT"===o.code)$r();else if(o.killed)console.log(chalk.yellow(en()?" ⏱ 超过 30 秒 — 检查死循环。":" ⏱ Over 30s — check for an infinite loop."));else{console.log(chalk.yellow(en()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of(o.stderr??"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));console.log(chalk.gray(en()?` (空还没填对?/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(en()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";const i=oo();try{a=t(ao(),[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)$r();else if(o.killed)console.log(chalk.yellow(en()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(en()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const c=i(),d=a.replace(/\r\n/g,"\n").trimEnd(),g=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(en()?" 你的输出:":" Your output:"));for(const e of(d||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(en()?" 样例应输出:":" Sample expects:"));for(const e of g.split("\n"))console.log(chalk.green(` ${e}`));console.log(chalk.gray(` ⏱ ${c}ms — ${He(en())}`)),d===g?console.log(chalk.bold.green(en()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(en()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(en()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(en()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=gr(e);if(!o)return;if("python"!==zn(o.p)||o.p.gpu)return console.log(chalk.gray(en()?` 这一层不读输入 — 用 /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=H(fn.dir,`sol-${o.n}.py`);if(!M(t))return void console.log(chalk.yellow(en()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(en()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const n=await yr(ao(),[`sol-${o.n}.py`]);console.log(),"ENOENT"!==n?.code?(console.log(chalk.gray(en()?" 回到竞技场。":" Back in the arena.")),console.log()):$r()})(o):"recall"===e&&await(async e=>{const o=gr(e);if(!o)return;if(!at)return void Nn();const{p:t,n:n}=o,r=H(process.cwd(),"icoa-contest"),s=`${rt.id}-phase${fn.phase}-g${fn.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?H(r,l,`sol-${n}.py`):null;if(!a||!M(a))return void console.log(chalk.gray(en()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=O(a,"utf-8"),c=`${fn.phase}-${fn.data.slot}-${n}`,d=Math.min(3,(br.get(c)??0)+1);console.log(chalk.gray(en()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await $e({token:so,phase:fn.phase,slot:fn.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:en()?"zh":"en"});if(g.ok){br.set(c,d),console.log();for(const e of et(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(en()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(en()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(en()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(en()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(en()?" (花名册: /list)":" (roster: /list)")),void xt()}if("contest"===o||"/contest"===o)return cr(),void xt();const a="lang"===o||/^lang\s+\S+$/.test(o),i=tt.has(o);if(!("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(en()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void xt()}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(en()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void xt()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if($t.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}At=!0;const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}At=!1,$t.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void xt()}if("ai4ioai"===o||"/ai4ioai"===o)return await L()&&(Gt=!0),void xt();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!at)return Nn(),void xt();Ht||(Ht=!0,console.log(),console.log(chalk.bold.cyan(en()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(en()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(en()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),en()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")),console.log(chalk.gray(en()?" 💡 一次好的研究通常会向 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(en()?" 新建草稿贴进去跑(":" a fresh scratch file and run them (")+chalk.bold.green("/pylist")+chalk.gray(en()?" 看草稿)。":" lists them).")),console.log(chalk.yellow(en()?" ↩ 重要:退出 AI 模式只需输入 ":" ↩ Important: to leave AI mode just type ")+chalk.bold.white("back")+chalk.yellow(en()?" 或 ":" or ")+chalk.bold.white("quit")+chalk.yellow(en()?",就回到卡片。":" — you are back on the card.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Rt=!0;const e=gn(pt.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(en()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(en()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(en()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · back / quit = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · back / quit = back to card")),console.log(chalk.gray(en()?" 💡 通常要向 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 xt()}return await qn(n,t?"fast":"deep"),void xt()}if(!Dt&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!at)return Nn(),void xt();const e=gn(pt.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(en()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(en()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(en()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(en()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(en()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(en()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(en()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Jt=!0,void xt()}const h=!Dt&&"honors"===Bt&&/^[1-3]$/.test(o);if(!Dt&&Bt&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(en()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(en()?" ↩ back 回上一层":" ↩ back goes up one level")),void xt();if(!Dt&&(h||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!at)return Nn(),void xt();const e=/^\/?view ([1-3])$/.exec(o),t=h?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Wt=!0;try{console.log();const o=await ve({token:so,cardNumber:pt.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(en()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Xt.delete(pt.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Xt.add(pt.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(en()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${pt.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${pt.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(en()?` (第 ${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(en()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=On(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(en()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Bt="view",console.log(chalk.gray((en()," "))+chalk.bold.cyan("↩ back")+chalk.gray(en()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Wt=!1}})(t),void xt()}const m=o.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(m&&!Dt&&!Ut){const{certificateLines:e}=await import("../lib/learn-door.js"),{certifiable:o,certificateIntroLines:t}=await import("../lib/learn-certificate.js"),n=en(),r=st?null:await y(so,"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===rt.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 xt()}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:")),Ct={cid:i.curriculum_id,tok:i.token,first:null},void xt()}const $=o.match(/^\/?(story|credits|fin)(?:\s+(\S+))?$/);if($&&!Dt&&!Ut){const e=($[2]??"").trim();return await pn("story"===$[1]?e||"list":e||null,!0),void xt()}if(/^\/?(?:type|typing)(?:\s|$)/i.test(o))return await uo(o.trim().split(/\s+/).slice(1)),void xt();if("me"===o||"/me"===o||"profile"===o||"/profile"===o||"my profile"===o){const e=en();if(st)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 xt();console.log(chalk.gray(e?" 正在取档案…":" Loading your profile…"));const o=await y(so);return"ok"===o.kind?f(o.profile,e,Qo()):"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 xt()}if("/honors"===o||"honors"===o)return st?(console.log(),console.log(chalk.gray(en()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void xt()):(await Wn(),void xt());const b=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(b)return _("learn-py: pylist"+(b[1]?` ${b[1]}`:"")),Ar(b[1]),void xt();const w=/^\/?py(?:\s+(\S+))?$/.exec(o);if(w)return await Tr(w[1]),void xt();if("menu"===o||"menu confirm"===o){if(kt?.detach(),sn.length>0&&await Promise.race([Promise.allSettled(sn),new Promise(e=>setTimeout(e,3e3))]),$t.removeAllListeners("line"),wt(),mt||!dn){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(mt?$t:void 0),cn()}else $t.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===Bt)return await Wn(),void xt();if("honors"===Bt)return Bt=null,Ln(),void xt();if(kt?.detach(),sn.length>0&&await Promise.race([Promise.allSettled(sn),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${pt.streakDays} day(s)`)),console.log(),mt){$t.removeAllListeners("line"),wt();for(const e of ft)$t.on("line",e);$t.prompt(),cn()}else $t.removeAllListeners("line"),$t.close();return}if(te(o))return dt?nt(ee(dt,en(),Qo(),"T0"===ne().tier),!!dt.completedAt):(console.log(chalk.gray(en()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void xt();if("status"===o||/^status\s+/.test(o)){const e=o.slice(6).trim().toLowerCase(),t="all"===e?"all":/^\d+$/.test(e)?Number(e):"current";return _n&&await Tn(),Oo(rt,pt,{gate:mn,gated:it,focus:t,posForSlot:Le}),void xt()}if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await Z(rt.id,so,!0);return void(e?(Object.assign(rt,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Ln()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),xt()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(co().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void xt();const t=rt.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 go({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Pt=null,Tt=null,St=null,Ot(),Qt=!1,Jt=!1,await Rn(),void xt()}const k=o.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(k&&!Dt&&!Ut&&null===Yt&&g.test(o)){const e=en(),o=await u(so);if("ok"===o.kind)for(const t of p(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 xt()}if(k&&!Dt&&!Ut&&null===Yt){const e=(k[2]??"").trim(),o=en(),t=`${a}–${l}`+(o?`,${i} 的倍数`:`, steps of ${i}`);if("off"===e||"stop"===e||"end"===e||"cancel"===e||"关"===e)return void(kt?.stop()||(console.log(chalk.gray(o?" 没有进行中的专注。开始一场:":" No focus session running. Start one: ")+chalk.bold.green("focus 30")),xt()));if(kt?.active)return console.log(chalk.yellow(" ⏱ ")+chalk.white(o?`专注进行中 · 还剩 ${kt.remainingMin()} 分钟`:`focus running · ${kt.remainingMin()} min left`)+chalk.gray(o?" · 提前结束:":" · end early: ")+chalk.bold.green("focus off")),void xt();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 xt();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 xt();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 kt?.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 xt()}if(tt.has(o)){const e=tt.get(o),t=Jo(co()),n=e=>{const o=["normal","wide","wider","widest"].filter(o=>o!==e);return en()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((en()?"normal"===e?" 已是标准 64 列。":Qo()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Qo()} 列,上限 ${Xo(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Qo()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Qo()} cols, cap ${Xo(e)}). `)+n(e))),void xt()):(go({learnWidth:e,learnWide:"normal"!==e}),Ko(e),"normal"!==e&&Qo()<=64?(console.log(chalk.yellow(en()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((en()?` 设置已记住(${e},上限 ${Xo(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Xo(e)} cols) and applies once you widen the window. `)+n(e))),void xt()):(console.log(chalk.green(" ✓ ")+chalk.gray((en()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Qo()} 列,上限 ${Xo(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Qo()} cols, cap ${Xo(e)}). `)+n(e))),Pt=null,Tt=null,St=null,Ot(),Qt=!1,Jt=!1,await Rn(),void xt()))}if("sim"===o){const e=gn(pt.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=z(G(import.meta.url)),o=[H(e,"..","..","panda","mujoco-launcher.py"),H(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 xt()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void xt())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=pt.currentCard,t=pt.bookmarks.includes(e),n="bookmark"!==o;return n?pt.bookmarks=pt.bookmarks.filter(o=>o!==e):t||pt.bookmarks.push(e),fo(pt),n?console.log(t?chalk.gray(en()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(en()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(en()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(en()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void xt()}const v=re(o);if(v){const e="current"===v.target?pt.currentCard:v.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>rt.cards.length))return console.log(chalk.yellow(en()?` 本课共 ${rt.cards.length} 张,请输 r 1–${rt.cards.length} 或 r all。`:` This course has ${rt.cards.length} cards. Try r 1–${rt.cards.length} or r all.`)),console.log(),void xt();for(const o of se(ct,rn,e,en(),Qo()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?ct:ct.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(ct=ct.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Zo(ct),sn.push(J(so,{card_number:pt.currentCard,event_type:"viewed"},o).catch(()=>{}))),void xt()}if("e"===o||"memo"===o)return It=pt.currentCard,console.log(chalk.gray(en()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(en()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void xt();if("back"===o||"b"===o)return"view"===Bt?(await Wn(),void xt()):"honors"===Bt?(Bt=null,Ln(),void xt()):(pt.currentCard>1&&(pt.currentCard-=1),Tt=null,St=null,Pt=null,fo(pt),Ln(),void xt());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!_n)return console.log(chalk.yellow(en()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void xt();if(!e){const e=await Se(so),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(en()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(en()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(en()?` 这台电脑上有 ${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(en()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(en()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(en()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(en()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(en()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(en()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(en()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void xt()}if(/^\d{1,2}$/.test(e)){const o=await Te(so,Number(e));return o.ok&&o.data?(Zn(o.data),await Tn(),void xt()):(console.log(chalk.red(` ✗ ${o.message||(en()?"关联失败":"Link failed")}`)),void xt())}const t=await Pe(so,e);return t.ok&&t.data?(Zn(t.data),await Tn(),void xt()):(console.log(chalk.red(` ✗ ${t.message||(en()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(en()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void xt())}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(!_n)return console.log(chalk.yellow(en()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void xt();let e=Sn(pt.currentCard),t=null;const n="contest restart"===o||"restart"===o;if(n&&(!Dt||!fn||Xn()))return console.log(chalk.gray(en()?" 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 xt();if(n&&fn){const o=fn.phase,n=fn.data.slot,r=await Ce(so,o,n);if(!r.ok&&"no_active_session"!==r.code)return console.log(chalk.red(` ✗ ${r.message||"reset failed"}`)),void xt();Qn(o,n),console.log(chalk.yellow(en()?` 🔄 第 ${n} 组重开 — 全新计时、全新模板。`:` 🔄 Group ${n} restarted — fresh clock, fresh templates.`)+chalk.gray(en()?" 只有计时内写的才算数:从头再写一遍,这正是练习。":" Only work written on the clock counts — write it again from scratch; that is the practice.")),fn=null,Dt=!1,ur=null,e=o,t=n}if("contest reset"===o&&Dt&&Xn()){const e=fn.phase,o=fn.data.slot,t=await Ce(so,e,o);if(t.ok){console.log(chalk.yellow(en()?" 已放弃本卡练习计时。回卡片后输入 practice <题号> 重新开始。":" Practice attempt abandoned. From the card, practice <n> starts a fresh one."));const t=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),n=H(process.cwd(),"icoa-contest",`${rt.id}-phase${e}-g${o}`);if(M(n))try{R(n,`${n}-archived-${t}`),console.log(chalk.gray(en()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(en()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}fn=null,Dt=!1,ur=null,Ln()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void xt()}if("contest reset"===o){const o=await Ce(so,e);if(o.ok){console.log(chalk.yellow(en()?` 已放弃本阶段(${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=H(process.cwd(),"icoa-contest"),n=new RegExp(`^${rt.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])<Jn).map(({name:e})=>e).sort();for(const e of r){const n=H(t,e);try{R(n,`${n}-archived-${o}`),console.log(chalk.gray(en()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(en()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(en()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),fn=null,Dt=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void xt()}const r=null!=t?String(t):/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(en()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(so,e,r?parseInt(r,10):void 0);if(!s.ok||!s.data){if("no_contest"===s.code){const o=rt.modules.find(o=>o.number===e)?.cardRange,t=!!o&&o[1]-o[0]+1>12;console.log(chalk.gray(t?en()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(360 层第二阶段标准设计中)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (360-tier second-stage standard in design).`:en()?` 本阶段(${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 xt()}const l=s.data,a=H(process.cwd(),"icoa-contest",`${rt.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{R(a,`${a}-archived-${e}`),console.log(chalk.gray(en()?" 📦 上一场的答题文件已归档: ":" 📦 Previous window archived: ")+chalk.gray(`${a}-archived-${e}`)),console.log(chalk.gray(en()?" 新场次全新模板 — 计时窗口内写的才算数。":" Fresh window, fresh templates — only work done on the clock counts."))}catch{console.log(chalk.yellow(en()?` ⚠ 归档失败(比赛照常): ${a}`:` ⚠ Could not archive (contest still fine): ${a}`))}}N(a,{recursive:!0});const i=fn&&fn.phase===e&&fn.data.slot===l.slot?fn.tried:new Set;fn&&fn.phase===e&&fn.data.slot===l.slot&&fn.data.attempt===l.attempt||($n.clear(),bn.clear()),fn={phase:e,dir:a,data:l,tried:i},Gn(l,a),vn(e,l.slot,a),Dt=!0,cr(),console.log(chalk.gray(en()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(a));const c=l.problems.findIndex(e=>!l.solved.includes(e.id))+1||1,d=Un&&!Yn?qe:c;return console.log(chalk.white(en()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${d}`)+chalk.gray(d===qe?en()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":en()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void xt()}const A=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(tn&&/^[1-9]$/.test(o)?`practice ${o}`:o);if(A){const e=gn(pt.currentCard),o=er(e);if(!o)return console.log(chalk.gray(en()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void xt();if(!_n)return console.log(chalk.yellow(en()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void xt();if(!A[1])return console.log(),tr(e),console.log(chalk.gray(en()?" 用法: ":" Usage: ")+chalk.bold.green(en()?"practice <题号>":"practice <n>")+chalk.gray(en()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void xt();const t=parseInt(A[1],10);return!Number.isInteger(t)||t<1||t>o.length?(console.log(chalk.yellow(en()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void xt()):(await(tn?(async(e,o,t)=>{const n=Sn(e.number),r=Jn+e.number;console.log(chalk.gray(en()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(so,n,r,!0);if(!s.ok||!s.data)return void("no_contest"===s.code?console.log(chalk.gray(en()?" 本卡暂无练习题库。":" 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(en()?" 本卡练习题库是空的。":" 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(Vn(e.py_id))?Vn(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=Cn.get(r);c||(c=new Set,Cn.set(r,c));for(const e of l.solved)c.add(e);Yt={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(en()?` ⚡ 快速填空 — 第 ${e.number} 张卡`:` ⚡ Quick fill — card ${e.number}`)+chalk.gray(en()?"(敲答案 → 自动判分 · 不计分)":" (type the blank → auto-judged · unscored)")),console.log(chalk.gray(en()?` ⏱ 每次练习 ${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`)),ar()})(e,o,t):(async(e,o,t)=>{const n=Sn(e.number),r=Jn+e.number;console.log(chalk.gray(en()?" 连接判分赛…":" Contacting contest server…"));const s=await Ae(so,n,r,!0);if(!s.ok||!s.data)return void("no_contest"===s.code?console.log(chalk.gray(en()?" 本卡暂无练习题库。":" 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(en()?" 本卡练习题库是空的。":" 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(Vn(e.py_id))?Vn(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=Cn.get(r);c||(c=new Set,Cn.set(r,c));for(const e of l.solved)c.add(e);const d=H(process.cwd(),"icoa-contest",`${rt.id}-phase${n}-g${r}`);N(d,{recursive:!0});const g=fn&&fn.phase===n&&fn.data.slot===r?fn.tried:new Set;fn&&fn.phase===n&&fn.data.slot===r&&fn.data.attempt===l.attempt||($n.clear(),bn.clear()),fn={phase:n,dir:d,data:l,tried:g},Gn(l,d),Dt=!0,ur=null,_(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(en()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(en()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(en()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(d)),console.log(chalk.gray((en()," ↩ "))+chalk.bold.green("back")+chalk.gray(en()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),hr(String(Math.min(t,l.problems.length)))})(e,o,t)),void xt())}if("submit"===s)return console.log(chalk.yellow(en()?" 用法: ":" Usage: ")+chalk.bold.green(en()?"submit <题号>":"submit <n>")+chalk.gray(en()?" 例如 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)")),fn||console.log(chalk.gray(en()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void xt();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!fn)return console.log(chalk.yellow(en()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void xt();const n=fn.data.problems,r=parseInt(o,10);if(Un&&r===qe)return console.log(chalk.gray(en()?" 热身题不判分 — /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(en()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(en()?" 开始。":".")),void xt();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(en()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void xt();const l=n.findIndex(e=>e.id===o)+1,a=t||H(fn.dir,Hn(l,n[l-1]));let i;try{i=O(a,"utf-8")}catch{return console.log(chalk.red(en()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void xt()}const c=new I(so);c.start();const d=$n.get(l),g=bn.get(l),u=d&&!B(d)?{...d,...g?{samples:g.list}:{},...g&&g.dropped>0?{samplesDropped:g.dropped}:{}}:void 0,p=await xe(so,fn.phase,o,i,fn.data.slot>=Jn?fn.data.slot:void 0,u);if(c.stop(),!p.ok||!p.data)return"no_active_session"===p.code&&fn.data.slot>=Jn?rr(fn.data.duration_minutes):"no_active_session"===p.code?(Qn(fn.phase,fn.data.slot),console.log(chalk.yellow(en()?" ⏱ 时间到 — 这一场结束了,判分机已停表。":" ⏱ Time is up — this attempt is over; the judge stopped the clock.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(en()?" 重开这一组:全新计时 + 全新模板(旧文件已归档)。只有计时内写的才算数 — 从头再写一遍,这正是练习。":" 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(en()?" ↩ back 回卡片":" ↩ back returns to the card"))):(console.log(chalk.red(` ✗ ${p.message||"judging failed"}`)),console.log(chalk.gray(en()?" 判分服务异常?敲 memo 一句话告诉我们 — 不打断比赛计时。":" Judge acting up? Type memo — one line reaches us, the clock is unaffected."))),void xt();const h=p.data;if(h.already_ac)console.log(chalk.green(en()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===h.verdict){if(console.log(chalk.bold.green(en()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${h.passed_tests??h.total_tests??"?"}/${h.total_tests??"?"} `+(en()?"隐藏用例全过":"hidden tests passed")+` · ${h.time_ms??"?"}ms`)),fn.data.solved.includes(o)||fn.data.solved.push(o),fn.tried.delete(o),Xn()){let e=Cn.get(fn.data.slot);e||(e=new Set,Cn.set(fn.data.slot,e)),e.add(o);const t=await _e({token:so,curriculumId:rt.id,cardNumber:pt.currentCard}),n=t.ok?t.practiceBoard:null;if(n?.mine){const e=n.top[0],o=e&&!e.me?chalk.gray(en()?` · 榜首 ${e.name||"Rank 1"} ${e.ac} AC`:` · leader ${e.name||"Rank 1"} at ${e.ac} AC`):chalk.bold.yellow(en()?" · 全场第一!":" · phase leader!");console.log(chalk.white(en()?` ⚔ Phase ${n.phase} Practice AC: `:` ⚔ Phase ${n.phase} practice AC: `)+chalk.bold.yellow(`${n.mine.ac}`)+chalk.gray(`/${n.problems_total}`)+chalk.gray(en()?` · 第 ${n.mine.rank} 名`:` · rank ${n.mine.rank}`)+o)}}}else{fn.tried.add(o);const e="TLE"===h.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${h.verdict}`)+chalk.gray(h.test?en()?` · 挂在第 ${h.test} 个用例(过 ${h.passed_tests}/${h.total_tests})`:` · failed test ${h.test} (passed ${h.passed_tests}/${h.total_tests})`:"")),qt||(qt=!0,console.log(chalk.gray(en()?" 觉得题面有误或判分不对?敲 memo 一句话 — 不打断比赛计时。":" Statement wrong or judging looks off? Type memo — one line, the clock is unaffected.")))}h.late&&console.log(chalk.yellow(en()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const y=je(h.deadline||""),m=Xn();if(console.log(chalk.white(m?en()?` 本卡练习: 已过 ${h.ac_count}/${h.n} 题(不计分)`:` Card practice: ${h.ac_count}/${h.n} solved (unscored)`:en()?` 本组进度: 已过 ${h.ac_count} 题 · 过 ${h.need} 题过关(共 ${h.n} 题)`:` Group progress: ${h.ac_count} solved · ${h.need} needed to pass (${h.n} problems)`)+(y?chalk.gray(` · ⏱ ${y}`):"")),m&&!h.late&&h.ac_count>=h.n)console.log(chalk.bold.green(en()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(en()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!h.passed||h.late||m){if(!h.late){const e=n.findIndex(e=>!fn.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(en()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Dn(n[e])}`))}}else{const e=Math.max(0,h.n-h.ac_count);if(0===e)console.log(chalk.bold.green(en()?` 🎉 满分!${h.n}/${h.n} 全部 AC — 这组题你已经彻底拿下。`:` 🎉 Perfect! ${h.n}/${h.n} AC — you have completely cleared this group.`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(en()?" 回到上一层(卡片),继续往下学;":" returns to the previous layer (the card) — keep going from there; ")+chalk.bold.green("contest")+chalk.gray(en()?" 看本阶段其他赛场。":" lists the other arenas of this phase."));else{console.log(chalk.bold.green(en()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")+chalk.yellow(en()?` 还剩 ${e} 题 — 全部做完就是满分 ${h.n}/${h.n},别停在这里。`:` ${e} more to go — solve them all for a perfect ${h.n}/${h.n}, don't stop here.`));const o=n.findIndex(e=>!fn.data.solved.includes(e.id));o>=0&&console.log(chalk.gray(en()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${o+1}`)+chalk.gray(` ${Dn(n[o])}`)+chalk.gray(en()?" · ↩ back 回卡片":" · ↩ back returns to the card"))}await Tn()}return void xt()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>rt.totalCards)return console.log(chalk.yellow(` Card number must be 1..${rt.totalCards}. Try: `)+chalk.bold.green("card 1")),void xt();const n=await In(t);return n?(console.log(n),void xt()):(pt.currentCard=t,Tt=null,St=null,Pt=null,fo(pt),Ln(),void xt())}if(null!==Pt&&["y","yes","n","no"].includes(o)){const e=gn(Pt);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Vt;kt?.noteCheck(n,r),vo(pt,e.number),Co(pt,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),fo(pt);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),sn.push(J(so,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Pt=null,yn(),e.solution&&e.solution.length>0)return void xt();if(or())return void xt();if(pt.currentCard<rt.totalCards){const e=pt.currentCard,o=await In(e+1);if(o)return await jn(e),console.log(o),void xt();pt.currentCard+=1,fo(pt),await jn(e)?En():Ln(),xt()}else Wo(rt,pt),pn(null,!1).then(()=>xt()),xt();return}}if(null!==Tt&&["a","b","c","d"].includes(o)){const e=gn(Tt);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(_o(pt,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),vo(pt,e.number),fo(pt),Io(e,t,n,pt),sn.push(J(so,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Tt=null,n)if(pt.currentCard<rt.totalCards){const e=await In(pt.currentCard+1);if(e)return console.log(e),void xt();pt.currentCard+=1,fo(pt),Ln()}else Wo(rt,pt),pn(null,!1).then(()=>xt()),xt();else xt();return}}if(null!==St){if("done"===o){const e=gn(St);if(e&&"practical"===e.type)return Ao(pt,e.number),vo(pt,e.number),fo(pt),Eo(e),St=null,void xt()}if("skip"===o)return vo(pt,St),fo(pt),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),St=null,void xt()}const S=tn&&"skip"===o&&null===Tt&&null===St&&null===Pt&&null!==er(gn(pt.currentCard));if("ok"===o||"next"===o||"continue"===o||"n"===o||S){if(S){const e=pt.currentCard;xn.add(e),kt?.notePracticeSkipped(),console.log(chalk.gray(en()?" ⚔ 本卡练习已跳过(有记录)。":" ⚔ Practice skipped for this card (recorded).")),J(so,{card_number:e,event_type:"practice_skipped"}).catch(()=>{})}else if(null===Pt&&null===Tt&&null===St&&or())return void xt();if(null!==Tt)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void xt();if(null!==St)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void xt();if(null!==Pt)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void xt();const e=pt.currentCard,o=e<rt.totalCards?await In(e+1):null;return o?(await jn(e),console.log(o),void xt()):(pt.currentCard+=1,fo(pt),pt.currentCard>rt.totalCards?(Wo(rt,pt),pn(null,!1).then(()=>xt())):await jn(e)?En():Ln(),void xt())}return null!==Pt?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void xt()):null!==Tt?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void xt()):null!==St?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void xt()):("view"===Bt?console.log(chalk.gray(en()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(en()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(en()?" 回卡片":" to the card")):"honors"===Bt?console.log(chalk.gray(en()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(en()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(en()?" 回卡片":" 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 xt())};$t.on("line",e=>{Sr(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.")),xt()})}),mt||$t.on("close",async()=>{kt?.detach(),sn.length>0&&await Promise.race([Promise.allSettled(sn),new Promise(e=>setTimeout(e,5e3))]),dn?cn():process.exit(0)});const Pr=le(ct,en());Pr&&(console.log(chalk.bold.cyan(` ${Pr}`)),console.log());try{Ln();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0),(async()=>{for(let e=0;e<20&&!mn;e++)await new Promise(e=>setTimeout(e,250));const e=hn();null!==e&&e>0&&e<=2&&(await yn(!0),xt())})();const o=kt?.attach(so,rt.id,un);"resumed"===o&&(console.log(chalk.yellow(" ⏱ ")+chalk.white(en()?`专注进行中 · 还剩 ${kt.remainingMin()} 分钟 · 这条轨也算在内 · focus off 提前结束`:`focus running · ${kt.remainingMin()} min left · this course counts too · focus off to end early`)),console.log()),xt()}catch{if(ot("Could not render this card — the curriculum may be malformed."),mt){$t.removeAllListeners("line"),wt();for(const e of ft)$t.on("line",e);$t.prompt()}else $t.close();cn()}await an}),ro.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()})}