icoa-cli 2.19.614 → 2.19.617

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 l}from"../lib/input-dynamics.js";import{FOCUS_MAX as s,FOCUS_MIN as a,FOCUS_STEP as i,getStudyTimer as c,parseFocusMinutes as d}from"../lib/learn-study-timer.js";import{FOCUS_LOG_RE as g,fetchFocusLog as u,renderFocusLog as h}from"../lib/learn-focus-log.js";import{setLearnFooterExtra as p}from"../lib/learn-render.js";import{CHECK_RE as y,runLearnCheck as m}from"../lib/learn-check.js";import{CLASS_RE as f,runLearnClass as $}from"../lib/learn-class.js";import{TEAM_RE as b,askOnReadline as w,runTeamMeeting as k}from"../lib/learn-team.js";import{fetchLearnProfile as v,postCreditsRolled as _,renderLearnProfile as C}from"../lib/learn-profile.js";import{buildCreditLines as A,creditsProgress as x,creditsRoadLines as T,rollCredits as S,storyListLines as j}from"../lib/learn-credits.js";import{logCommand as P}from"../lib/logger.js";import{startEditSampler as I}from"../lib/edit-sampler.js";import{probeVimInsertExpand as E}from"../lib/editor-spawn.js";import{getMainRl as N,setMainRl as M}from"../lib/main-rl.js";import{assetDir as L,lazyJson as q}from"../lib/lazy-assets.js";import{isMicroduckWord as O,runMicroduck as R}from"./microduck.js";import{JudgeWaitLine as W}from"../lib/judge-wait.js";import{ai4ioaiPromptLabel as D,handleAi4ioaiMessage as U,startAi4ioaiChat as z}from"./ai4ioai.js";import{existsSync as Y,mkdirSync as B,readdirSync as F,readFileSync as G,renameSync as Z,statSync as H,writeFileSync as K}from"node:fs";import{emptyDynamics as J,foldEditSession as Q,isEmpty as X,noteRun as V}from"../lib/arena-edit-dynamics.js";import{dirname as ee,join as oe}from"node:path";import{fileURLToPath as te}from"node:url";import{loadCurriculumById as ne,validateEAToken as re,syncProgress as le,postFlowEvent as se,fetchServerProgress as ae,syncCardFeedback as ie,fetchCardFaqs as ce}from"../lib/learn-curricula.js";import{FlowRunner as de}from"../lib/learn-flow.js";import{hometaskDetailLines as ge,hometaskLines as ue,isTaskCommand as he}from"../lib/learn-hometask.js";import{detectCaps as pe}from"../lib/render-card.js";import{parseReplyCommand as ye,renderReplyLines as me,repliesForCard as fe,replyPushLine as $e,replySignature as be,shortDay as we,unreadReplies as ke,wrapPlain as ve}from"../lib/learn-replies.js";import{ensureFullTable as _e,lookupPydoc as Ce,lookupRanked as Ae,refetchTableOnMiss as xe,nearKeys as Te,renderIndex as Se,renderPydoc as je,renderSyntax as Pe,tableSize as Ie}from"../lib/py-syntax.js";import{normalizeTokenBody as Ee}from"../lib/token-format.js";import{fetchMyScores as Ne,recallCoach as Me,setNickname as Le,streamLearnTutor as qe,submitPqs as Oe,viewPqsTop as Re,viewHonors as We}from"../lib/learn-ai.js";import{contestReset as De,contestStart as Ue,contestSubmit as ze,linkByIndex as Ye,linkSuggest as Be,linkToken as Fe,fetchGate as Ge,timeLeft as Ze,arenaCadence as He,arenaSlotAtPos as Ke,posForArenaSlot as Je}from"../lib/learn-contest.js";import{WARMUP as Qe,WARMUP_ID as Xe,WARMUP_N as Ve,WARMUP_TESTS as eo,gradeWarmup as oo,warmupEnabled as to}from"../lib/warmup.js";import{PY_MAX_CODE_BYTES as no,PY_MAX_FILES as ro,PY_TEMPLATE_EN as lo,PY_SPOOL_BATCH as so,PY_TEMPLATE_ZH as ao,listScratchFiles as io,localTimeNote as co,nextScratchN as go,readPyScratchSpool as uo,scratchCodeSha as ho,scratchDir as po,scratchFilePath as yo,scratchTitleOf as mo,shrinkPyScratchSpool as fo,spoolPyScratchEvent as $o,startRunTimer as bo,syncPyScratch as wo}from"../lib/py-scratch.js";import{SH_TIMEOUT_MS as ko,destructiveHint as vo,ensureLabDir as _o,interactiveHint as Co,labCardDir as Ao,labRoot as xo,resolveCd as To,runShell as So,shortCwd as jo,tildePath as Po}from"../lib/sh-lab.js";import{verdictLine as Io}from"../lib/verdict.js";import{printNoPython312 as Eo,probePython as No}from"../lib/python-setup.js";function Mo(){const e=No();return e.ok&&e.cmd?{cmd:e.cmd}:null}const Lo=()=>Mo()?.cmd??null;import{homedir as qo}from"node:os";import{getConfig as Oo,saveConfig as Ro}from"../lib/config.js";import{runType as Wo}from"./type.js";import{mobReportLine as Do,playSavedReplay as Uo,runBattle as zo,runMobLocal as Yo,saveJudgeReplay as Bo}from"./battle.js";import{runDuck as Fo}from"./duck.js";import{ARENA_VI_FLAGS as Go}from"../lib/vi-flags.js";import{isNativeWindows as Zo,isWindowsBuildInWslShell as Ho,whichBinary as Ko}from"../lib/platform.js";import{loadLearnState as Jo,saveLearnState as Qo,newLearnState as Xo,stateFromServerEvents as Vo,mergeServerProgress as et,activateSession as ot,updateStreak as tt,markCardComplete as nt,recordMCQ as rt,recordCheck as lt,markPracticalComplete as st,addAchievement as at}from"../lib/learn-state.js";import{renderWelcome as it,renderKnowledgeCard as ct,renderMCQCard as dt,renderMCQFeedback as gt,renderPracticalCard as ut,renderPracticalSuccess as ht,renderSimDemoCard as pt,renderMilestone as yt,renderArenaTaskCard as mt,renderArenaIntro as ft,learnCheckpointVerb as $t,renderComingSoonCard as bt,renderStatus as wt,renderPhaseComplete as kt,renderCurriculumComplete as vt,setLearnAiEnabled as _t,setLearnFaqs as Ct,setLearnArenaLane as At,setLearnArenaCards as xt,setLearnDuckLane as Tt,setLearnFooterProfile as St,setLearnShellLane as jt,setLearnHometask as Pt,setLearnPracticeChips as It,setLearnPracticeCount as Et,setLearnHonorRanks as Nt,setLearnPqsViewCards as Mt,setLearnReplies as Lt,setLearnWidth as qt,resolveLearnWidth as Ot,learnWidthCap as Rt,learnW as Wt,renderHonorWall as Dt,wrapMixed as Ut}from"../lib/learn-render.js";import{printError as zt}from"../lib/ui.js";const Yt=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","widest"],["wide max","widest"]]);function Bt(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 Ft=No.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ft)){const{runSprint:e}=await import("./sprint.js");return void await e()}if(O(No))return void await R();let Gt=null;const Zt=/^[A-Z0-9]+DEMO01$/i.test(Ft),Ht=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ft);let Kt=!1,Jt=3,Qt=!1,Xt=[],Vt=null,en=-1,on=Promise.resolve([]);if(Zt)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),on=ce(Ft),Gt=await ne(Ft,Ft,!0);else if(Ht){console.log(),console.log(chalk.gray(" Validating token..."));let e=await re(Ft);if(!e.ok){const o=Ee(Ft);if(o!==Ft){const t=await re(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ft} → ${o}`)),e=t,Ft=o)}}if(!e.ok){if(zt(`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."));else if("network"===e.code&&(e.advice?.length??0)>0){console.log(chalk.yellow(" Your token is fine — this computer could not reach the ICOA server.")),console.log();for(const o of e.advice??[])console.log(chalk.gray(` ${o}`));console.log(),console.log(chalk.gray(" Full check of this network: ")+chalk.cyan("doctor"))}else 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)"));return 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 🐼"):Zt?"":chalk.magenta(" · 🐼 AI tutor"))),Kt=!0===e.aiEnabled,Jt=e.aiBasicPerCard??3,Qt=!0===e.gated,Xt=e.replies??[],Vt=e.hometask??null,on=ce(Ft),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Gt=await ne(e.curriculumId||"LEARNDEMO01",Ft,!0),!Gt)return zt(`Could not open a learn curriculum for token '${Ft}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ft}`)+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 ${Ft}`)+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(!Gt){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(zt(`Could not reach the learn server to open ${Ft}.`),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 ${Ft}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(zt(`Unknown learn token: ${Ft}`),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 tn=Jo(),nn=!1,rn=!1;try{if(tn&&tn.token===Ft)tt(tn),rn=!0;else{const e=ot(Ft);if(e)tn=e,tn.totalCards=Gt.totalCards,tt(tn),rn=!0;else{const e=await ae(Ft),o=e?Vo(Ft,Gt.id,Gt.totalCards,e):null;o?(tn=o,console.log(chalk.green(" ↩ ")+chalk.white((Oo().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()):(tn=Xo(Ft,Gt.id,Gt.totalCards),nn=!0)}}if(rn){const e=await ae(Ft);if(e){const o=tn.currentCard;et(tn,Gt.totalCards,e),tn.currentCard>o&&(console.log(chalk.green(" ↩ ")+chalk.white((Oo().language||"en").toLowerCase().startsWith("zh")?`已同步手机进度:${tn.cardsCompleted.length} 张卡完成,从第 ${tn.currentCard} 张继续`:`Synced your phone progress: ${tn.cardsCompleted.length} cards done, resuming at card ${tn.currentCard}`)),console.log())}}Qo(tn),it(Gt,tn,nn),function(e){if(!e)return;const o=(Oo().language||"en").toLowerCase().startsWith("zh"),t="T0"===pe().tier;Bt(ue(e,o,Wt(),t),!!e.completedAt)}(Vt)}catch{return zt("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 ${Ft}`)+chalk.gray(".")),void console.log()}const ln=N(),sn=null!==ln,an=sn?ln.listeners("line").slice():[];sn&&ln.removeAllListeners("line");const cn=sn?ln:o({input:process.stdin,output:process.stdout,terminal:!0}),dn=sn?cn.prompt:null;sn&&(cn.prompt=e.prototype.prompt);const gn=()=>{sn&&dn&&(cn.prompt=dn)};let un=null,hn=!1,pn=!1,yn=null,mn=!1;const fn=()=>{cn.closed||(cn.setPrompt(Gn?chalk.bold.green(`icoa ${D()}> `):On?chalk.bold.magenta(Rl()):qn?chalk.bold.magenta("icoa py> "):Ln?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Nn?"icoa learn ai> ":"icoa learn> ")),cn.prompt(),un?.onPromptIdle())};let $n=null,bn=null,wn=null,kn=null;const vn=new Set,_n=(e,o)=>{const t=e.flow??[];0!==t.length&&(o&&(console.log(chalk.yellow(" 🧭 ")+chalk.white(Vn()?"这张卡是互动流程 —— 现在开始。选错不扣分,墙上写着为什么;":"This card is an interactive walk — starting now. Wrong turns cost nothing; the wall says why;")),console.log(chalk.gray(Vn()?" 每一步在 icoa learn> 后面敲答案。back 退回卡片 · flow 再走一遍。":" type each answer after icoa learn>. back returns to the card · flow walks it again.")),console.log()),kn=new de({steps:t,zh:Vn(),cardNumber:e.number,print:e=>console.log(e)}),"done"===kn.start()&&Cn("done"))},Cn=e=>{if(!kn)return;const o=kn.records(),t=kn.cardNumber;kn=null;for(const e of o)sr.push(se(Ft,Gt.id,t,e).catch(()=>{}));if("done"!==e)return console.log(chalk.gray(Vn()?" ↩ 已退出流程,回到卡片。":" ↩ Left the walk — back on the card.")),void console.log();const n=null!==wn?gr(wn):null;if(n&&"knowledge"===n.type&&n.check){const e=n._zh?.checkStatement??n._zh?.check?.statement,o=Vn()?e??n.check.statement:n.check.statement;console.log(chalk.gray(Vn()?" ✅ 流程走完。":" ✅ Walk complete.")+chalk.cyan(Vn()?" 🤔 现在回答卡片的检查题(输 y 或 n):":" 🤔 Now the card check (type y or n):")),console.log(chalk.white(` ${o}`)),console.log(chalk.gray(Vn()?" (flow 再走一遍)":" (flow walks it again)"))}else console.log(chalk.gray(Vn()?" ✅ 流程走完 — 敲 ok 下一张,或 flow 再走一遍。":" ✅ Walk complete — type ok for the next card, or flow to walk it again."));console.log()};let An=null,xn=[],Tn=!1,Sn=null;const jn=/^(quit|exit|q|back|b|menu|home|contest(\s+(\d+|reset))?)$/i;let Pn=null,In=!1;const En=()=>{Sn&&clearTimeout(Sn),Sn=null,xn=[],Tn=!1,An=null,Pn=null};let Nn=!1,Mn=!1,Ln=!1,qn=!1,On=!1,Rn=null,Wn="card",Dn=null,Un=null,zn=null,Yn=!1,Bn=0,Fn=!1,Gn=!1;const Zn=new Map,Hn=()=>{let e=Zn.get(tn.currentCard);return e||(e=[],Zn.set(tn.currentCard,e)),e};let Kn=!1;const Jn=new Set;let Qn=!1,Xn=0;const Vn=()=>(Oo().language||"en").toLowerCase().startsWith("zh");_t(Kt||!Zt,Kt),qt(Ot(Oo())),Mt(Jn);const er=new Map;Nt(er),Lt(Xt),Pt(Vt);const or="fill"===Gt.practiceMode,tr=Boolean(Gt.shellLane);jt(tr);const nr=Gt.mobCheckpoints;At("battleai"===Gt.practiceMode||Array.isArray(nr)),xt("battleai"===Gt.practiceMode?[]:(nr??[]).map(e=>Number(e.card)).filter(e=>e>0).map(e=>{const o=Gt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return{card:e,slot:o?Ke(e-o.cardRange[0]+1):0}}).filter(e=>e.slot>0)),Tt(Array.isArray(Gt.duckCheckpoints)),St("minimal"===Gt.footerProfile?"minimal":"full"),It(e=>{const o=gr(e),t=o?tl(o):null;if(!t)return null;const n=Cr.get(Xr+e);return t.map((e,o)=>`[${o+1}]${n?.has(ol(e.py_id))||n?.has(e.py_id)?"✅":"⬜"}`).join(" ")});const rr=e=>{const o=gr(e),t=o?tl(o):null;if(!t)return null;const n=Cr.get(Xr+e);return{solved:t.filter(e=>n?.has(ol(e.py_id))||n?.has(e.py_id)).length,total:t.length}};Et(rr);const lr=await on;Ct(lr);const sr=[];let ar=null;const ir=new Promise(e=>{ar=e}),cr=()=>{const e=ar;ar=null,e?.()},dr="1"===process.env.ICOA_LEARN_EMBEDDED,gr=e=>Gt.cards.find(o=>o.number===e);un=c();const ur={isZh:Vn,canInterrupt:()=>!(mn||Mn||Nn||Ln||qn||Gn||null!==Dn||null!==An||null!==zn),lineEmpty:()=>!cn.line,clearLine:()=>{try{process.stdout.write("\r")}catch{}},prompt:fn,currentCard:()=>tn.currentCard};p(()=>{const e=[],o=un?.footerLine();o&&e.push(o);const t=pr();return null!==t&&t>0&&t<=2&&e.push(Vn()?`🎁 还差 ${t} 项 · credits 看路线`:`🎁 ${t} to go · credits shows the road`),e.length?e.join("\n "):null});const hr=async(e,o)=>{const t=Vn();if(Zt)return void console.log(chalk.gray(t?"故事属于正式 learn token。":" Stories belong to full learn tokens."));const n=await v(Ft,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 j(r,t))console.log(e);return void console.log()}let l=null===e?r.tokens.find(e=>e.curriculum_id===Gt.id):void 0;if(null!==e){const o=Number(e);l=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(!l){console.log(),console.log(chalk.yellow(t?` 没有「${e}」这门课的故事。`:` No story for "${e}".`));for(const e of j(r,t))console.log(e);return void console.log()}if(!o&&!l.credits?.completed){const e=l.credits,o=[];e&&e.checks_total>0&&o.push(t?`自测 ${e.checks_answered}/${e.checks_total}`:`checks ${e.checks_answered}/${e.checks_total}`),l.practice.total>0&&o.push(t?`练习 ${l.practice.ac}/${l.practice.total} AC`:`practice ${l.practice.ac}/${l.practice.total} AC`),l.contests.total>0&&o.push(t?`检查点 ${l.contests.passed}/${l.contests.total} 过线`:`checkpoints ${l.contests.passed}/${l.contests.total} passed`),console.log(chalk.bold.white(t?" 🏁 离谢幕还差:":" 🏁 To the credits: ")+chalk.gray(o.join(" · ")));for(const e of T(Gt,tn,mr,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 s=A(l,r,l.curriculum_id===Gt.id?Gt.name:l.curriculum_id,l.curriculum_id===Gt.id?{longestStreak:tn.longestStreak,bookmarks:tn.bookmarks?.length??0}:{},t,Wt(),"T0"===pe().tier);console.log(),console.log(chalk.gray(t?" (回车跳到结尾)":" (Enter skips to the end)")),hn=!0,pn=!1;try{await S(s,()=>pn)}finally{hn=!1}if(l.curriculum_id===Gt.id&&!l.credits?.completed){for(const e of T(Gt,tn,mr,t))console.log(e);console.log()}l.credits?.completed&&!l.credits.credits_rolled_at&&_(l.token,l.curriculum_id),console.log(chalk.gray(t?" ↩ 回车继续 · story 选另一门 · me 看档案":" ↩ Enter to continue · story to pick another · me for your profile")),console.log()},pr=()=>{if(!tn||tn.creditsShownAt||Zt||!mr)return null;const e=x(Gt,tn,mr);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])},yr=async(e=!1)=>{if(!tn||tn.creditsShownAt||Zt)return;const o=x(Gt,tn,mr);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(mr&&t>0&&t<=2&&(e||tn.creditsTeasedLeft!==t)){tn.creditsTeasedLeft=t,Qo(tn);const e=Vn(),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 T(Gt,tn,mr,e))console.log(o);console.log()}return}tn.creditsShownAt=(new Date).toISOString(),Qo(tn),await hr(null,!1),fn()};let mr=null,fr=null;const $r=new Map,br=new Map;let wr=null;const kr=(e,o)=>wr?.[`${Gt.id}:${e}:${o}`]??null;q("contest-cells.json").then(e=>{wr=e?.map??null;for(const[e,o]of Object.entries(wr??{}))e.startsWith(`${Gt.id}:`)&&q(o)});const vr=(e,o,t)=>{const n=kr(e,o);if(!n)return null;const r=oe(t,"explore.ipynb");if(!Y(r)){const e=oe(L(),n);if(!Y(e))return null;try{K(r,G(e))}catch{return null}}return r},_r=!Ft.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ft),Cr=new Map,Ar=new Map,xr=new Set,Tr=async()=>{if(!_r)return;const e=await Ge(Ft);if(e.ok&&e.data){mr=e.data;for(const o of e.data.practice??[]){let e=Cr.get(o.slot);e||(e=new Set,Cr.set(o.slot,e));for(const t of o.solved)e.add(t)}yr()}},Sr=e=>{const o=Gt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},jr=e=>{if(!Qt||!mr)return null;const o=Sr(e);if(o<=mr.unlocked_through_phase)return null;const t=mr.phases.find(e=>e.phase===mr.unlocked_through_phase),n=[chalk.yellow(Vn()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${mr.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${mr.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(Vn()?` ⚔ 练习赛 ${mr.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${mr.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(Vn()?` ⚖ 判分赛: 最好 ${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(Vn()?"、":", "),r=e.length>8?Vn()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:Vn()?" 张":"";n.push(chalk.gray(Vn()?` ✓ 逐卡自测: ${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(Vn()?` ⭐ 提问研究: ${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")},Pr=async e=>Qt?null===jr(e)?null:(await Tr(),jr(e)):null;_r&&await Tr();const Ir=async e=>{const o=Gt.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=Gt.modules.find(e=>e.number===o.number+1);let n;if(Kt){const e=await Ne({token:Ft,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}_r&&await Tr();const r=mr?.phases.find(e=>e.phase===o.number);return kt(Gt,tn,o,t,n,r),!0},Er=()=>{Qn=!0,console.log(chalk.gray(Vn()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Nr=()=>{zn=null;const e=gr(tn.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();un?.noteCardShown(e.number,tn.cardsCompleted.includes(e.number));const o=ke(fe(Xt,e.number));if(o.length>0){const t=Math.max(40,Math.min(process.stdout.columns||80,96)),n="─".repeat(Math.max(24,t-4));console.log(),console.log(chalk.bold.cyan(` 💬 ──${n}`)),console.log(chalk.bold.cyan(" 💬 ")+chalk.bold.white(Vn()?`你有 ${o.length} 条回复(第 ${e.number} 张卡)`:`You have ${o.length} ${o.length>1?"replies":"reply"} (Card ${e.number})`)),console.log(chalk.bold.cyan(` 💬 ──${n}`));for(const e of o){console.log(chalk.gray(` ${Vn()?"你写的":"You wrote"}: ${(e.myText??"").slice(0,70)}${(e.myText?.length??0)>70?"…":""}`)),console.log(chalk.yellow(` 🐼 ${Vn()?"回复":"Reply"}(${we(e.repliedAt??"")}):`));for(const o of ve(e.replyText??"",t-4," "))console.log(chalk.bold.white(o));const o=be(e.repliedAt,e.repliedBy);o&&console.log(chalk.gray(` ${o}`)),console.log()}console.log(chalk.cyan(` 💬 ${"─".repeat(Math.max(24,t-6))}`)),console.log(chalk.gray(" "+(Vn()?"看完继续:next 去下一张卡;e 可再报告一条。":"Continue: type next, or press e to report again."))),console.log(),Xt=Xt.map(e=>o.some(o=>o.id===e.id)?{...e,seen:!0}:e)}switch(e.type){case"knowledge":{const o=or&&Boolean(tn.checkResults?.[String(e.number)])&&e.check?{...e,check:void 0}:e;ct(o,Gt),o.check?(wn=e.number,Xn=Date.now()):(nt(tn,e.number),Qo(tn));break}case"mcq":dt(e,Gt),$n=e.number;break;case"practical":ut(e,Gt),bn=e.number;break;case"sim_demo":pt(e,Gt),nt(tn,e.number),Qo(tn);break;case"milestone":yt(e,Gt),at(tn,e.badge),nt(tn,e.number),Qo(tn);break;case"arena_task":mt(e,Gt),nt(tn,e.number),Qo(tn);break;case"coming_soon":bt(e,Gt),nt(tn,e.number),Qo(tn)}Mr(e.number),ll(e),"knowledge"===e.type&&e.flow&&e.flow.length>0&&(vn.has(e.number)?(console.log(chalk.yellow(" 🧭 ")+chalk.gray(Vn()?"敲 flow 再走一遍这张卡的互动流程。":"type flow to walk this card again.")),console.log()):(vn.add(e.number),console.log(),_n(e,!0)))},Mr=e=>{if(!_r)return;const o=Gt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1,n=Ke(t);if(0===n)return;const r=He(o.cardRange[1]-o.cardRange[0]+1),l=mr?.phases.find(e=>e.phase===o.number),s=l?.contest?.slots?.find(e=>e.slot===n),a=()=>{tn.arenaIntroShownAt||(ft(o.cardRange[1]-o.cardRange[0]+1),tn.arenaIntroShownAt=(new Date).toISOString(),Qo(tn))};if(!mr){const e="═".repeat(Wt()),t=chalk.bold.yellow(" ║ "),r=$t();return a(),console.log(chalk.bold.yellow(` ╔${e}`)),console.log(t+chalk.bold.white("⚔ "+(Vn()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(Vn()?" 成绩暂时取不到":" scoreline unavailable")),console.log(t+chalk.white(Vn()?"这张卡下面有一场判分赛 — 服务器这会儿没答上来,所以显示不了你的成绩。":"A judged arena lives under this card — the server didn't answer in time, so your scoreline is missing.")),console.log(t+chalk.gray("▸ ")+chalk.bold.green(r??`contest ${n}`)+chalk.gray(Vn()?" 照常可以开赛(开赛是另一次请求) · ":" still opens it (starting is a separate call) · ")+chalk.gray("▸ ")+chalk.bold.green("ok")+chalk.gray(Vn()?" 继续学习":" keep going")),console.log(chalk.bold.yellow(` ╚${e}`)),void console.log()}if(!s){const e=o.cardRange;if(e[1]-e[0]+1>12)return;a();const t="═".repeat(Wt()),l=chalk.bold.yellow(" ║ ");return console.log(chalk.bold.yellow(` ╔${t}`)),console.log(l+chalk.bold.white("⚔ "+(Vn()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(Vn()?" 制作中":" in production")),console.log(l+chalk.white(Vn()?"这里以后有一场判分赛 — 很快更新。":"A judged arena lands here — coming soon.")),console.log(l+chalk.gray(Vn()?r.n>1?`每 4 张卡一场:卡 ${r.cards},本阶段共 ${r.n} 场,全过解锁下一阶段。${or?"(本轨无 research)":""}`:`本阶段一场:卡 ${r.cards},过了解锁下一阶段。${or?"(本轨无 research)":""}`:r.n>1?`One every 4 cards — ${r.cards}, ${["","one","two","three"][r.n]??r.n} this phase; all ${["","one","two","three"][r.n]??r.n} unlock the next.${or?" (no research on this track)":""}`:`One this phase — card ${r.cards}; passing it unlocks the next.${or?" (no research on this track)":""}`)),console.log(l+chalk.gray(Vn()?"▸ 现在什么都不用做 — 敲 ":"▸ Nothing to do yet — type ")+chalk.bold.green("next")+chalk.gray(Vn()?" 继续读卡。":" and keep reading.")),console.log(chalk.bold.yellow(` ╚${t}`)),void console.log()}a();const i=(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?Vn()?` · 用时 ${r}`:` · in ${r}`:"")+(l?` · ${l}`:"")},c=s.perfect_runs??[],d=!!s.best&&(s.best.ac??0)>0,g=chalk.bold.yellow(" ║ "),u="═".repeat(Wt());if(console.log(chalk.bold.yellow(` ╔${u}`)),console.log(g+chalk.bold.white(`⚔ ${Vn()?(()=>{const t=(nr??[]).find(o=>Number(o.card)===e)?.title;return t?`检查点 · 卡 ${e} · ${t}`:`练习赛 ${o.number}-${n}`})():s.title||`PY Arena ${o.number}-${n}`}`)+(s.passed?chalk.bold.green(Vn()?" ✅ 已通过":" ✅ passed"):"")),!s.passed){if(Vn()?console.log(g+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(g+chalk.white("You learned the cards — now prove it.")),console.log(g+chalk.white("The clock starts the moment you type the command."))),console.log(g+chalk.gray(Vn()?`${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?Vn()?`(${e})`:` (${e})`:"";console.log(g+chalk.cyan(Vn()?`🔗 你另一个 token${o}已做过这组的 ${s.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens${o} solved ${s.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Vn()?" 带过来(现在不做也行)":" to carry them over (or skip)"))}1!==o.number||or||console.log(g+chalk.gray(Vn()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))}if(c.length>0)for(const e of c)console.log(g+chalk.bold.yellow(i(Vn()?"满分":"Perfect",s.n,e.ms,e.ts)));else d&&console.log(g+chalk.yellow(i(Vn()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));3===n&&l?.leader&&console.log(g+chalk.white(Vn()?`🏅 本 phase 研究总分榜首 ${l.leader.name||"Rank 1"} ${l.leader.total}/${l.leader.max_total}`:`🏅 Phase research leader: ${l.leader.name||"Rank 1"} at ${l.leader.total}/${l.leader.max_total}`)+chalk.gray((Vn()," — "))+chalk.bold.green("/honors")+chalk.gray(Vn()?" 看你的位置":" shows where you stand"));const h=$t();console.log(g+chalk.gray("▸ ")+chalk.bold.green(h??`contest ${n}`)+(h?chalk.gray(Vn()?` 进竞技场(${"battle"===h?"play":"run"} 试跑 → submit 判分) · `:` enter the arena (${"battle"===h?"play":"run"} → submit) · `):s.passed?chalk.gray(Vn()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Vn()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(Vn()?" 继续学习":" keep going"):chalk.gray(Vn()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),!h&&(c.length>0||d)&&console.log(g+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(Vn()?" 日后回来整阶段重做 · 全新计时+模板(旧文件自动归档)":" come back later and redo the whole phase · fresh clock + templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${u}`)),console.log()},Lr=()=>{Ft.endsWith("DEMO01")?console.log(chalk.yellow(Vn()?" 🐼 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(Vn()?" /submit 评分、荣誉榜与 /recall 是 🐼 AI 高级 token 的功能。":" Prompt grading (/submit), the honors board and /recall are premium 🐼 AI-token features.")),console.log(chalk.gray(Vn()?` 你的 token 可以用 /ai 向熊猫导师提问(每卡每天 ${Jt} 问);要开通高级功能找领队 / 协调人。`:` Your token can still ask the tutor with /ai (${Jt} questions per card per day); ask your leader / coordinator for a premium token.`))),console.log()},qr=async(e,o)=>{if(Zt)return void Lr();un?.noteAi(Kt&&"deep"===o),Mn=!0;const t=Vn()?"🐼 熊猫导师思考中…":"🐼 Panda tutor is thinking…",n=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];let r=null;const l=()=>{r&&(clearInterval(r),r=null,process.stdout.write("\r"))},s=()=>Vn()?` (本卡今天的 ${Jt} 个问题已用完 — 24 小时后再问,或先去下一张卡)`:` (this card's ${Jt} questions for today are used up — ask again in 24 h, or move on to another card)`;try{console.log(),(()=>{if(!process.stdout.isTTY)return void console.log(chalk.gray(` ${t}`));let e=0;const o=()=>{process.stdout.write(`\r ${chalk.magenta(n[e++%n.length])} ${chalk.gray(t)}`)};o(),r=setInterval(o,80)})();let a=!1;const i=await qe({token:Ft,cardNumber:tn.currentCard,question:e,mode:o,history:Hn().slice(-8),lang:Vn()?"zh":"en"},e=>{"content"===e.kind&&(a||(l(),process.stdout.write(" "),a=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});l(),a&&console.log(),i.ok?i.offtopic?(console.log(),console.log(chalk.yellow(Kt?Vn()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)":Vn()?" (被判定与本卡主题无关 — 不会回答,也不计入本卡的次数)":" (judged unrelated to this card — not answered, and it does not count toward this card's questions)"))):(Hn().push({role:"user",content:e},{role:"assistant",content:i.answer}),null!=i.spent&&null!=i.cap&&i.spent/i.cap>.8&&console.log(chalk.gray(` (${Vn()?"AI 额度":"AI budget"}: ${Math.round(i.spent/1e3)}k / ${Math.round(i.cap/1e3)}k tokens)`)),"basic"===i.tier&&"number"==typeof i.cardLeft&&(1===i.cardLeft?console.log(chalk.yellow(Vn()?" (本卡今天还可以问最后 1 个问题)":" (this card: 1 question left today)")):0===i.cardLeft&&console.log(chalk.yellow(s())))):(console.log(),"card_daily_limit"===i.code?console.log(chalk.yellow(s())):console.log(chalk.yellow(` ${i.message||(Vn()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==wn&&console.log(chalk.gray(Vn()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{l(),Mn=!1}},Or=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Rr=async()=>{Ln&&fr?yl?fl(yl):ul():zn?await Wr():Nr()},Wr=async()=>{Mn=!0;try{console.log();const e=await We({token:Ft,curriculumId:Gt.id,cardNumber:tn.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Vn()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(_r&&(await Tr(),(e=>{const o=Gt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const[t,n]=o.cardRange,r=tn.checkResults||{};let l=0,s=0,a=0;for(let e=t;e<=n;e++){const o=gr(e);null!=o?.check&&a++;const t=r[String(e)];t&&(l++,t.correct&&s++)}console.log(chalk.bold.white(Vn()?` 🧭 Phase ${o.number} 进度 — ${o.name}(卡 ${t}-${n})`:` 🧭 Phase ${o.number} progress — ${o.name} (cards ${t}-${n})`)),console.log(chalk.gray(Vn()?" 理解检查: ":" comprehension: ")+chalk.white(`${s}/${l}`)+chalk.gray(Vn()?` 答对 · ${a-l} 张未作答`:` correct · ${a-l} unanswered`));const i=mr?.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(Vn()?`未开始 · ${e.n} 题 · 过 ${e.need} 题`:`not started · ${e.n} problems · AC ${e.need}`):chalk.yellow(Vn()?`最好 ${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(` ⚔ ${Vn()?"练习赛":"arena"} ${o.number}-${e.slot}: `)+t)}const c=[];let d=0,g=0,u=0,h=0;for(let e=t;e<=n;e++){const o=rr(e);o&&(g++,u+=o.solved,h+=o.total,o.solved>=o.total&&d++,c.push((o.solved>=o.total?chalk.green:o.solved>0?chalk.yellow:chalk.gray)(`${e}:${o.solved}/${o.total}`)))}if(g>0){console.log(chalk.gray(Vn()?" 卡片练习: ":" practice: ")+chalk.white(`${d}/${g}`)+chalk.gray(Vn()?` 卡全完成 · ${u}/${h} 题 AC`:` cards complete · ${u}/${h} problems AC`));const e=Math.max(40,(process.stdout.columns||80)-8);let o="",t=0;for(const n of c){const r=n.replace(/\x1b\[[0-9;]*m/g,"");t+r.length+2>e&&o&&(console.log(" "+o),o="",t=0),o+=(o?chalk.gray(" · "):"")+n,t+=r.length+3}o&&console.log(" "+o),console.log(chalk.gray(Vn()?" 卡号:已过/共 — 绿 全完成 · 黄 做了一部分 · 灰 未碰":" card:solved/total — green done · yellow partial · gray untouched"))}console.log()})(tn.currentCard)),console.log(chalk.bold.white(Vn()?` 🏆 本卡实时 Top-3 — 第 ${tn.currentCard} 张`:` 🏆 Live top-3 — card ${tn.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(Vn()?" (你)":" (you)"):""))}else console.log(chalk.gray(Vn()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));if(e.mine?(er.set(tn.currentCard,e.mine.rank),console.log(chalk.white(Vn()?" 你: ":" You: ")+chalk.bold.yellow(Vn()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Vn()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Kt&&console.log(chalk.gray(Vn()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Dt({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),e.phaseBoard){const o=e.phaseBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(Vn()?` 🏅 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(Vn()?" (还没有人有研究总分 — 第一个 /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(Vn()?`(${e.cards}/${o.cards_in_phase} 卡)`:` (${e.cards}/${o.cards_in_phase} cards)`)+(e.me?chalk.bold.magenta(Vn()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(Vn()?` 总分 ${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(Vn()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.total}`)+chalk.gray(Vn()?`(${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&&Kt&&console.log(chalk.gray(Vn()?" 你: 还未计入 — /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(Vn()?` ⚔ 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(Vn()?" (还没有人 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(Vn()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(Vn()?` 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(Vn()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.ac} AC`)+chalk.gray(Vn()?` · 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` · rank ${o.mine.rank} of ${o.mine.entrants}`)):o.mine||console.log(chalk.gray(Vn()?" 你: 还未计入 — 在有 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(Vn()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Vn()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Vn()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),zn="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Vn()?" 返回卡片":" returns to the card")),console.log()}finally{Mn=!1}},Dr=e=>Vn()&&e.title_zh||e.title,Ur=e=>"mob-match"===e?.kind,zr=()=>!!fr&&fr.data.problems.some(e=>Ur(e)),Yr=to(Gt.id);let Br=!1;const Fr=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of Ut(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Gr={cpp:"cpp",java:"java",go:"go"},Zr=e=>e?.lang&&Gr[e.lang]?e.lang:"python",Hr=(e,o)=>{const t=Zr(o);return`sol-${e}.${"python"===t?"py":Gr[t]}`},Kr=(e,o)=>{const t=[...Yr?[{p:Qe,n:Ve}]:[],...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:l})=>{const s=Yr&&l===Ve,a=s?`══ ${t.title} ══`:`══ ${e.title||"PY Arena"} · ${t.title} ══`;for(const e of["py",...Object.values(Gr)]){const s=oe(o,`sol-${l}.${e}`);if(!Y(s))continue;const i=G(s,"utf-8").split("\n",1)[0]??"",c=/^(?:#|\/\/) (══ .+ ══)\s*$/.exec(i);if(c&&c[1]!==a)try{Z(s,`${s}.archived-${n}`),r++;const e=oe(o,`sample-${l}.txt`);Y(e)&&!(t.samples??[])[0]&&Z(e,`${e}.archived-${n}`)}catch{}}const i=(t.samples??[])[0];null!=i?.in&&K(oe(o,`sample-${l}.txt`),i.in.endsWith("\n")?i.in:`${i.in}\n`);const c=oe(o,Hr(l,t));if(Y(c))return;const d=[s?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Fr(t.statement??"",72)];if(t.statement_zh&&d.push("#",`# Other language: type "lang zh" in icoa, then /read ${l} for the Chinese statement.`),null!=i?.in&&null!=i.out){d.push("#",`# Sample input (also in sample-${l}.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","#"),s||Ur(t)||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 Ut(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 ${l} = free run · /submit ${l} = judge`,"",'data = """',...g[1].trim().split("\n"),'""".strip()',"",""):s?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(???)",""):Ur(t)?d.push(`# In icoa: /run ${l} = play one match here (the replay opens) · /submit ${l} = judge`,""):t.starter?d.push("#",`# In icoa: /run ${l} = run it (shows your ms) · /submit ${l} = judge`,""):d.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${l} = sample self-check · /debug ${l} = free-input run · /submit ${l} = judge`,"","");const u="python"===Zr(t)?d:d.map(e=>e.startsWith("#")?`//${e.slice(1)}`:e),h=Ur(t)&&Vn()&&t.starter_zh?t.starter_zh:t.starter;h&&!s&&u.push(...h.replace(/\s+$/,"").split("\n"),""),K(c,u.join("\n"))}),r>0&&console.log(chalk.gray(Vn()?` 📦 本组题目已更换 — ${r} 个旧题答题文件已归档为 *.archived-${n},新题文件已就位`:` 📦 This group's problems changed — ${r} old solution file(s) archived as *.archived-${n}, fresh files written`))},Jr=e=>{console.log(),console.log(chalk.bold.green(Vn()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(Vn()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Qr=e=>e.id===Xe?Br?"✅":"⬜":fr.data.solved.includes(e.id)?"✅":fr.data.carried?.includes(e.id)?"✅↗":fr.tried.has(e.id)?"❌":"⬜",Xr=100,Vr=()=>!!fr&&fr.data.slot>=Xr,el=(e,o)=>{const t=oe(process.cwd(),"icoa-contest",`${Gt.id}-phase${e}-g${o}`);if(!Y(t))return;const n=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{Z(t,`${t}-archived-${n}`),console.log(chalk.gray(Vn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${n}`))}catch{console.log(chalk.yellow(Vn()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (restart still fine): ${t}`))}},ol=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,tl=e=>{const o=e?.practice;if(!o||!Array.isArray(o.problems)||0===o.problems.length)return null;const t=o.problems.filter(e=>nl(e));return[...o.problems.filter(e=>e.is_signature&&!nl(e)),...o.problems.filter(e=>!e.is_signature&&!nl(e)).sort((e,o)=>(e.difficulty??0)-(o.difficulty??0)||(e.order??0)-(o.order??0)),...t]},nl=e=>"mob-match"===e.kind,rl=()=>{if(!or)return!1;const e=gr(tn.currentCard),o=e?tl(e):null;if(!e||!o||xr.has(e.number))return!1;const t=Xr+e.number,n=Cr.get(t),r=Ar.get(t),l=o.map((e,o)=>{return t=e.py_id,Boolean(n?.has(ol(t))||n?.has(t)||r?.has(ol(t))||r?.has(t))?0:o+1;var t}).filter(e=>e>0);return 0!==l.length&&(console.log(chalk.yellow(Vn()?` ⚔ 这张卡还有 ${l.length} 道练习没做 —— 敲 `:` ⚔ ${l.length} practice problem${l.length>1?"s":""} on this card not tried yet — type `)+chalk.bold.green(`practice ${l[0]}`)+chalk.yellow(Vn()?" 开始,或 ":" to start, or ")+chalk.bold.yellow("skip")+chalk.yellow(Vn()?" 跳过本卡练习。":" to skip this card's practice.")),!0)},ll=e=>{const o=tl(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=Cr.get(Xr+e.number);console.log(chalk.bold.yellow(Vn()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(Vn()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(ol(e.py_id))||n?.has(e.py_id)?"✅":"⬜",r=e.is_signature?"🎯":e.is_hardest?"🔥":" ",l="·".repeat(Math.min(5,Math.max(1,Math.round(e.difficulty??1))));nl(e)?console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ⚔ ${chalk.bold.white(Vn()?"对局":"battle")}`+chalk.gray(Vn()?` — 改一行 · 打一局 · 看回放 · 判分 (敲 ${o+1})`:` — change one line · play · replay · judge (type ${o+1})`)):console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ${r} ${chalk.white(l.padEnd(5))}`)}),console.log(chalk.gray(" ▸ ")+chalk.bold.green("practice 1")+chalk.gray(Vn()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},sl=e=>e.split("\n").filter(e=>!e.trim().startsWith("#")).join("\n").split("____").length-1,al=e=>{console.log(chalk.yellow(Vn()?` ⏱ 每次练习 ${e} 分钟,这次的时间到了。`:` ⏱ Each practice window is ${e} minutes — this one has run out.`)),console.log(chalk.gray(Vn()?" 敲 ":" Type ")+chalk.bold.green("back")+chalk.gray(Vn()?" 回卡片,再敲 ":" for the card, then ")+chalk.bold.green("practice 1")+chalk.gray(Vn()?" 重新开始(重新计时)。":" to restart with a fresh clock."))},il=()=>Dn?Dn.data.problems[Dn.idx]??null:null,cl=()=>{const e=il();if(!Dn||!e)return;const o=sl(e.starter??""),t=Dn.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(Vn()?` 空${t}/${o}`:` blank ${t}/${o}`)+chalk.gray(" · ")+chalk.white(n)),console.log(chalk.gray(Vn()?" ▸ 敲答案后回车(back 回卡片)":" ▸ type the answer, press Enter (back = card)"))},dl=()=>{const e=il();if(!Dn||!e)return;const o=Vn()&&e.title_zh?e.title_zh:e.title;console.log(),console.log(chalk.bold.yellow(` ⚡ ${Vn()?"练习":"Practice"} ${Dn.idx+1}/${Dn.data.problems.length} · ${o}`));const t=((Vn()&&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(),cl()},gl=()=>{if(Dn){if(Dn.idx+1<Dn.data.problems.length)return Dn.idx+=1,Dn.answers=[],Dn.tries=0,void dl();console.log(chalk.bold.green(Vn()?" 🎉 本卡练习全部完成!":" 🎉 Card practice complete!")+chalk.gray(Vn()?" ok 进下一张卡。":" ok moves on to the next card.")),Dn=null,Un=null,Nr()}},ul=()=>{const e=fr.data,o=Ze(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 l=e.slot>=Xr?e.slot-Xr:null,s=e.problems.find(e=>Ur(e)),a=Vn()&&s?.title_zh?`检查点 · 卡 ${s.card} · ${s.title_zh}`:e.title||"PY Arena";if(console.log(chalk.bold.yellow(` ⚔ ${a}`)+chalk.gray(null!=l?Vn()?` · 第 ${l} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${l} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:Vn()?` · 第 ${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(Vn()?" ⏱ 已超时 — 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(Vn()?`(共 ${e.n} 题)`:` (of ${e.n})`)),null==l&&n>=e.need){const o=Math.max(0,e.n-n);console.log(0===o?chalk.bold.green(Vn()?` 🎉 满分 ${e.n}/${e.n} — 本组全部拿下!`:` 🎉 Perfect ${e.n}/${e.n} — every problem cleared!`)+chalk.gray(Vn()?" ↩ back 回卡片":" ↩ back returns to the card"):chalk.green(Vn()?" 🏁 已过关":" 🏁 passed")+chalk.yellow(Vn()?` · 还剩 ${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(Vn()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" 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?Vn()?`(${o})`:` (${o})`:"";console.log(chalk.cyan(Vn()?` 🔗 你另一个 token${t}已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens${t} solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Vn()?" 带过来,不必重做":" to carry them over instead of redoing them"))}const i=Date.parse(e.deadline)-Date.now();if(o?e.resumed&&i<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(Vn()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Vn()?"不够就 ":"Short on time? ")+chalk.bold.green("contest restart")+chalk.gray(Vn()?" 满血重开本组。":" restarts this group fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(Vn()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),Yr&&(console.log(chalk.gray(" 0 ")+Qr(Qe)+chalk.gray(` ${Dr(Qe)}`)+chalk.gray(Vn()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+Qr(e)+(e.gpu?chalk.magenta(" ⚡"):"")+chalk.white(` ${Dr(e)}`))}),e.problems.some(e=>e.gpu)){const o=e.gpu_state?.state??(e.gpu_window?"on":"off");console.log(),"on"===o?console.log(chalk.bold.green(Vn()?" ⚡ GPU 开 ✅":" ⚡ GPU on ✅")+chalk.gray(Vn()?" — /submit 一道 ⚡ 题,就在真 GPU 上跑":" — /submit a ⚡ rung and it runs on a real GPU right now")):"booting"===o?console.log(chalk.bold.yellow(Vn()?" ⚡ GPU 开机中…":" ⚡ GPU booting…")+chalk.gray(Vn()?" — 约 3–5 分钟,稍后重新 /submit":" — takes ~3–5 min; retry /submit shortly")):console.log(chalk.bold.gray(Vn()?" ⚡ GPU 关":" ⚡ GPU off")+chalk.gray(Vn()?" — 直接 /submit 一道 ⚡ 题会自动开机(约 3–5 分钟),之后重新 /submit":" — /submit a ⚡ rung to auto-boot the GPU (~3–5 min), then /submit again"))}kr(fr.phase,e.slot)&&(console.log(),console.log(chalk.gray(" ✍ ")+chalk.bold.green("cells")+chalk.gray(Vn()?" 在 notebook 里探索本场数据(引导走查 · 真图) — 不判分,判分仍走 /submit":" explore this lab in a notebook (guided walkthrough · real figures) — ungraded; judging stays /submit"))),console.log(),hl()},hl=()=>{console.log(chalk.gray(zr()?Vn()?" /read <n> 读目标 · /edit <n> 改 bot(vi) · /run <n> 本机打一局 · /submit <n> 判分(10 局)":" /read <n> goal · /edit <n> bot (vi) · /run <n> play a match here · /submit <n> judge (10 games)":Vn()?" /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(Vn()?"/syntax <词>":"/syntax <word>")+chalk.gray(Vn()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(Vn()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Vn()?" 返回课程":" returns to the lesson")),console.log(chalk.gray(Vn()?" memo 报告题面/判分问题 — 不打断比赛计时":" memo reports a statement/judging problem — the clock is unaffected")),console.log(chalk.gray(" ")+chalk.bold.green("contest restart")+chalk.gray(Vn()?" 超时/坏场时重开本组(全新计时+模板) · ":" time up or broken attempt → this group again (fresh clock + templates) · ")+chalk.bold.green("contest reset")+chalk.gray(Vn()?" 日后回来整阶段重做":" come back later and redo the whole phase")),console.log()},pl=e=>{const o=parseInt(e,10),t=fr.data.problems;if(o===Ve&&Yr)return{p:Qe,n:Ve};const n=Yr?Ve:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(Vn()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),Yr&&console.log(chalk.gray(Vn()?" 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 yl=null,ml=!1;const fl=e=>{const o=pl(e);if(!o)return;const{p:t,n:n}=o;yl=String(n),console.log(),console.log(chalk.bold.white(` ${Qr(t)} ${Dr(t)}`)),console.log();for(const e of(e=>Vn()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of Ut(e,Wt()+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(Vn()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Vn()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(Ur(t)){const e=Array.isArray(t.crit)?t.crit:[],o=Number(e[2]??10),r="mined"===e[0]?Vn()?`采矿 ≥ ${e[1]}`:`mine ≥ ${e[1]} opal`:"winrate"===e[0]?Vn()?`${o} 局赢 ≥ ${Math.round(100*Number(e[1]))}%`:`win ≥ ${Math.round(100*Number(e[1]))}% of ${o} games`:"";console.log(),console.log(chalk.gray(Vn()?" 对手 ":" vs ")+chalk.white(String(t.opp??"?"))+chalk.gray(Vn()?" · 地图 ":" · map ")+chalk.white(String(t.map??"?"))+chalk.gray(Vn()?" · 回合 ":" · turns ")+chalk.white(String(t.turns??"?"))+(r?chalk.gray(Vn()?" · 过线 ":" · pass: ")+chalk.bold.white(r):""));const l=Vn()&&t.hint_zh||t.hint;if(l){console.log();let e=!0;for(const o of l.split("\n"))for(const t of Ut(o,Wt()-2))console.log(e?chalk.yellow(" 🧭 ")+chalk.white(t):chalk.white(` ${t}`)),e=!1}console.log();let s=!1;try{s=_l(G(oe(fr.dir,Hr(n,t)),"utf8")).length>0}catch{s=!1}console.log(chalk.gray(" ▸ ")+chalk.bold.green(s?"set <KNOB> <value>":`/edit ${n}`)+chalk.gray(Vn()?" 改一行":" change one line")+chalk.gray(" → ")+chalk.bold.green(`/run ${n}`)+chalk.gray(Vn()?" 本机打一局(开回放)":" play one match here (replay opens)")+chalk.gray(" → ")+chalk.bold.green(`/submit ${n}`)+chalk.gray(Vn()?" 判分":" judge")),s&&console.log(chalk.gray(Vn()?" 旋钮列表敲 ":" bare ")+chalk.bold.green("set")+chalk.gray(Vn()?" · 想直接看文件用 ":" lists the knobs · the file itself is ")+chalk.bold.green(`/edit ${n}`))}else 0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(Vn()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)")));if(t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(Vn()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=Vn()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of Ut(o,Wt()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(Vn()?"数据就在上方 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(),Yr&&n===Ve)return console.log(chalk.white(Vn()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(Vn()?"第 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(Vn()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(Vn()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((Vn()," ↩ "))+chalk.bold.green("back")+chalk.gray(Vn()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(Vn()?" 直接看正式题目":" skips straight to the real problems")),void console.log();Ur(t)||(t.quiz?console.log(chalk.gray(" ▸ ")+chalk.bold.green(Vn()?"输入字母 A–E 回车":"type a letter A–E, press Enter")+chalk.gray(Vn()?" 即提交这一题 · 也可以 ":" to submit this one · or ")+chalk.bold.green(`/edit ${n}`)+chalk.gray(Vn()?" 在 vi 里填":" to fill it in vi")):t.gpu?(console.log(chalk.white(Vn()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Vn()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Vn()?"真 GPU 上跑并带回你的 ms(⚡ 每周一窗口 19:00–21:45 悉尼)":"runs on a real GPU and returns your ms (⚡ Monday window 19:00–21:45 Sydney)"))):t.starter&&!Ur(t)?(console.log(chalk.white(Vn()?" 三步:":" Three steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Vn()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(Vn()?"本机直跑,出你自己的 ms":"run it locally — see your own ms")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Vn()?"参考机判分(成绩 = 那里的 ms)":"judge on the reference machine (the scored ms)"))):(console.log(chalk.white(Vn()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Vn()?"写码(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(Vn()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(Vn()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Vn()?"正式判分(隐藏用例)":"official judging (hidden tests)")))),console.log(),Ur(t)||(console.log(chalk.gray(Vn()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(Vn()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log()),console.log(chalk.gray((Vn()," ↩ "))+chalk.bold.green("back")+chalk.gray(Vr()?Vn()?" 回花名册 · ":" to the roster · ":Vn()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(Vn()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((Vn()," / "))+chalk.bold.green("wide")+chalk.gray(Vn()?" 换语言/宽度":" language / width")),console.log()},$l=async(e,o,t)=>await new Promise(n=>{const s=process.stdin,a=!!s.isTTY&&!!s.isRaw;if(cn.pause(),s.isTTY&&"function"==typeof s.setRawMode)try{s.setRawMode(!1)}catch{}mn=!0;const i=r(e,o,{stdio:"inherit",cwd:t??fr.dir}),c=e=>{if(s.isTTY&&"function"==typeof s.setRawMode&&a)try{s.setRawMode(!0)}catch{}l(),mn=!1,cn.resume(),n(e)};i.on("close",()=>c(null)),i.on("error",e=>c(e))}),bl=Go,wl=()=>{const e=E("vi");console.log(chalk.gray(Vn()?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"))},kl=()=>Eo(Vn(),{judgeIsServerSide:!0}),vl=()=>{const e=Lo();return e||kl(),e},_l=e=>[...new Set([...e.matchAll(/^([A-Z][A-Z0-9_]*)\s*=\s*[^#\n]+/gm)].map(e=>e[1]))],Cl=(e,o)=>{const t=new RegExp(`^${o}\\s*=\\s*([^#\n]*?)\\s*(?:#.*)?$`,"m").exec(e);return t?t[1]:null},Al=new Map,xl=()=>po(process.cwd(),Gt.id),Tl=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())}`},Sl=async(e,o,t=!1)=>{if(!_r)return;let n;try{n=G(yo(xl(),e),"utf-8")}catch{return}if(Buffer.byteLength(n,"utf-8")>no)return;const r=ho(n),l=(new Date).toISOString(),s=uo(qo(),Ft).slice(0,so),a=await wo(Ft,{n:e,title:mo(n.split("\n",1)[0]),code:n,code_sha:r,card_number:tn.currentCard,run_meta:o,client_ts:l,events:s.length>0?s:void 0});a?s.length>0&&fo(qo(),Ft,s.length):$o(qo(),Ft,{n:e,code_sha:r,card_number:tn.currentCard,run_meta:o,client_ts:l}),a||t||console.log(chalk.gray(Vn()?" (未能同步到服务器 — 草稿只保存在本机)":" (could not reach the server — this scratch is saved locally only)"))},jl=()=>{console.log(chalk.gray(Vn()?" 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()},Pl=e=>{const o=io(xl()),t=parseInt(e,10);return Number.isInteger(t)&&o.some(e=>e.n===t)?t:(0===o.length?console.log(chalk.yellow(Vn()?" 还没有任何草稿 — ":" No scratch files yet — ")+chalk.bold.green("/py")+chalk.gray(Vn()?" 新建第一个。":" creates the first one.")):console.log(chalk.yellow(Vn()?` 没有 py-${e} — 现有编号: `:` No py-${e} — you have: `)+chalk.white(o.map(e=>e.n).join(", "))+chalk.gray(Vn()?" · pylist 看列表":" · pylist shows them")),null)},Il=e=>{const o=io(xl()),t=e?.trim().toLowerCase(),n=t?o.filter(e=>(e.title??"").toLowerCase().includes(t)):o;if(console.log(),console.log(chalk.bold.magenta(Vn()?" ✍ 我的 Python 草稿":" ✍ My Python scratch files")+(t?chalk.gray(` · "${e?.trim()}"`):"")+chalk.gray(` (${n.length})`)),0===o.length)return console.log(chalk.gray(Vn()?" 还没有草稿 — ":" Nothing here yet — ")+chalk.bold.green("/py")+chalk.gray(Vn()?" 新建一个(第一行写标题)。":" creates one (line 1 becomes its title).")),void console.log();if(0===n.length)return console.log(chalk.gray(Vn()?` 没有匹配 "${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(Ut(e.title,40)[0]??e.title):chalk.gray(Vn()?"(未命名 — 第一行写标题)":"(untitled — line 1 becomes the title)");console.log(chalk.gray(` py-${String(e.n).padEnd(3)} `)+o+chalk.gray(` · ${Tl(e.mtimeMs)}`))}console.log(chalk.gray(" ▸ ")+chalk.bold.green(Vn()?"/py <编号>":"/py <n>")+chalk.gray(Vn()?" 打开 · ":" opens one · ")+chalk.bold.green("/py")+chalk.gray(Vn()?" 新建":" new file")),console.log()},El=async e=>{const o=yo(xl(),e);if(Zo())return console.log(chalk.yellow(Vn()?" icoa 正跑在 Windows 上 — 草稿本的编辑器在 Ubuntu(WSL)那一侧。":" icoa is running on Windows — the scratchpad editor lives on the Linux (WSL) side.")),console.log(chalk.gray(Vn()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${o}`)),void console.log();if(!Ko("vi"))return console.log(chalk.yellow(Vn()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${o}`)),void console.log(chalk.gray(Vn()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));wl();const t=e=>{try{return H(e).size}catch{return 0}},n=t(o),r=Date.now(),l=I(o);await $l("vi",[...bl,`py-${e}.py`],xl());const s=l.stop();P(`learn-py edit-done py-${e}.py`,{ms:Date.now()-r,bytesBefore:n,bytesAfter:t(o),...s.ticks>0?{samples:s}:{}}),await Sl(e),console.log(chalk.gray(Vn()?" 已回到草稿本 — ":" Back in the scratchpad — ")+chalk.bold.green(`run ${e}`)+chalk.gray(Vn()?" 本机运行 · ":" runs it locally · ")+chalk.bold.green(`edit ${e}`)+chalk.gray(Vn()?" 再改。":" reopens vi.")),console.log()},Nl=async e=>{let o;if(B(xl(),{recursive:!0}),e){const t=Pl(e);if(null===t)return;o=t}else{const e=io(xl());o=go(e),o>ro&&console.log(chalk.gray(Vn()?` (已超过 ${ro} 个 — 服务器不再备份新文件,本机照常保存)`:` (past ${ro} files — the server stops backing new ones up; local saves still work)`)),K(yo(xl(),o),`${Vn()?ao:lo}\n\n`)}const t=!qn;qn=!0,P(`learn-py: open ${o}${e?"":" (new)"}`),t&&(console.log(),console.log(chalk.bold.magenta(Vn()?" ✍ Python 草稿本":" ✍ Python scratchpad")+chalk.gray(Vn()?" — 你的个人练习文件 · 只在本机运行 · 不判分":" — your personal practice files · runs locally · never judged")),console.log(chalk.gray(Vn()?" 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(Vn()?" 回卡片(退一层)":" returns to the card (one level)"))),await El(o),jl()},Ml=()=>xo(process.cwd(),Gt.id),Ll=()=>Rn??_o(Ao(process.cwd(),Gt.id,tn.currentCard)),ql=()=>{console.log(),console.log(chalk.bold.magenta(Vn()?" ⌨ shell 实验台":" ⌨ shell lab")+chalk.gray(Vn()?" — 在这里动手把答案弄出来 · 不判分 · 不解锁任何东西":" — work the answer out here · never judged · unlocks nothing")),console.log(chalk.gray(Vn()?` 真的 shell:管道 | 、重定向 > 、通配符 * 都能用 · 每条命令最多 ${ko/1e3} 秒`:` A real shell: pipes |, redirection >, globs * all work · ${ko/1e3}s per command`)),console.log(chalk.gray(Vn()?` 你在 ${Po(Ml())} 里面 —— 只能在这个文件夹内走动(自己的终端不受限)`:` You are inside ${Po(Ml())} — you can only move within it (your own terminal is unrestricted)`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(Vn()?" 回卡片(退一层)":" returns to the card (one level)")),console.log()},Ol=()=>{console.log(chalk.gray(Vn()?" 敲任何 shell 命令 · cd 换目录 · reset 还原文件 · clear 清屏 · ↩ back "+("fill"===Wn?"回到这道题":"arena"===Wn?"回赛场":"回卡片"):" type any shell command · cd to move · reset restores files · clear · ↩ back "+("fill"===Wn?"returns to the problem":"arena"===Wn?"returns to the arena":"returns to the card")))},Rl=()=>`icoa sh ${jo(Ml(),Ll())}> `,Wl=(e=!1)=>{const o=gr(tn.currentCard)?.files;if(!o)return[];const t=_o(Ao(process.cwd(),Gt.id,tn.currentCard)),n=[];for(const[r,l]of Object.entries(o)){if(!/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/.test(r))continue;if(r.split("/").some(e=>"."===e||".."===e))continue;const o=oe(t,r);if(o===t||o.startsWith(t+"/")){try{B(ee(o),{recursive:!0})}catch{}if(e||!Y(o))try{K(o,l),n.push(r)}catch{}}}return n},Dl=(e="card")=>{Wn=e;const o=!On;On=!0,Rn=Ll();const t=Wl();P(`learn-sh: enter card${tn.currentCard}`),o&&ql(),t.length>0&&(console.log(chalk.bold.green(Vn()?" 📦 本卡的文件已放好:":" 📦 This card ships files:")+chalk.white(` ${t.join(" ")}`)),console.log(chalk.gray(Vn()?" 先敲 ls 看看。":" Start with `ls`.")),console.log()),Ol()},Ul=async e=>{const o=e.trim().toLowerCase(),l=Ln&&o.startsWith("/")?o.slice(1):o;if(hn)return void(pn=!0);if(yn){const{sameName:o,issueCertificate:t,announceCertificate:n}=await import("../lib/learn-certificate.js"),r=e.trim(),l=Vn();if(!r||jn.test(r))return yn=null,console.log(chalk.gray(l?" 已取消,未签发。":" Cancelled — nothing issued.")),void fn();if(null===yn.first)return yn.first=r,console.log(chalk.gray(l?" 再输一次:":" Type it once more:")),void fn();const s={cid:yn.cid,tok:yn.tok,first:yn.first};return yn=null,o(s.first,r)?(console.log(chalk.gray(l?" 签发中…(名字只发送一次,不会保存)":" Issuing… (the name is sent once, never stored)")),n(await t(s.tok,s.cid,s.first),l),void fn()):(console.log(chalk.yellow(l?" 两次输入不一致 — 未签发。再敲 certificate 重来。":" The two names differ — nothing issued. Type certificate to try again.")),void fn())}if(Mn)return;if(un?.noteInput(),!Dn&&un?.consumeRating(o))return void fn();if(Dn)return await(async e=>{if(!Dn)return;const o=e.trim(),t=o.toLowerCase();if(tr&&("sh"===t||"/sh"===t))return Un=Dn,Dn=null,Dl("fill"),void console.log(chalk.gray(Vn()?" ▸ 看完敲 back 回到这道题。":" ▸ When you have looked: back returns to this problem."));if("back"===t||"quit"===t||"menu"===t)return Dn=null,Un=null,console.log(chalk.gray(Vn()?" ↩ 回到卡片。":" ↩ Back on the card.")),void Nr();if("skip"===t)return void gl();if(""===o)return void dl();const n=il();if(!n)return Dn=null,void Nr();const r=sl(n.starter??"");if(Dn.answers.push(o),Dn.answers.length<r)return void cl();const l=[...Dn.answers],s=((e,o)=>{let t=0;return e.split("\n").map(e=>{if(e.trim().startsWith("#"))return e;for(;e.includes("____")&&t<o.length;)e=e.replace("____",o[t]),t+=1;return e}).join("\n")})(n.starter??"",l);Dn.answers=[];let a=Ar.get(Dn.slot);a||(a=new Set,Ar.set(Dn.slot,a)),a.add(n.id);const i=Boolean(n.quiz),c=i?null:new W(Ft);c?.start();const d=await ze(Ft,Dn.phase,n.id,s,Dn.slot,void 0);if(c?.stop(),!Dn)return;if(!d.ok||!d.data)return"no_active_session"===d.code?void al(Dn.data.duration_minutes):(console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),console.log(chalk.gray(Vn()?" 再敲一遍空1重试,或 back 回卡片。":" Type blank 1 again to retry, or back for the card.")),void cl());const g=d.data;if("AC"!==g.verdict||g.already_ac||un?.notePracticeAc(),g.already_ac||"AC"===g.verdict){i?console.log(chalk.bold.green(Vn()?" ✅ 答对了!":" ✅ Correct!")):console.log(Io("AC",{isZh:Vn(),gentle:!0,passed:g.passed_tests??g.total_tests??null,total:g.total_tests??null,ms:g.time_ms??null}));let e=Cr.get(Dn.slot);return e||(e=new Set,Cr.set(Dn.slot,e)),e.add(n.id),Dn.data.solved.includes(n.id)||Dn.data.solved.push(n.id),void gl()}Dn.tries+=1,i?console.log(chalk.red(Vn()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(Vn()?" — 再选一次。":" — pick again.")):console.log(Io(g.verdict??"WA",{isZh:Vn(),gentle:!0,passed:g.passed_tests??null,total:g.total_tests??null,failedTest:g.test??null,ms:g.time_ms??null}));const u=n.samples?.[0];if(u?.out){console.log(chalk.gray(Vn()?" 期望输出:":" Expected output:"));for(const e of u.out.trimEnd().split("\n"))console.log(chalk.white(" "+e))}if(2===Dn.tries||Dn.tries>2&&Dn.tries%3==2){const e=i?[]:((e,o)=>{const t=[];let n=0;for(const r of e.split("\n")){if(r.trim().startsWith("#"))continue;const e=r.split("____");for(let r=0;r<e.length-1;r++,n++){const l=(o[n]??"").trim(),s=e[r+1].trimStart(),a=e[r].trimEnd(),i=n+1;s.startsWith("(")&&/\(\s*\)?$/.test(l)?t.push(Vn()?` ⚠ 空${i}:模板里 ____ 后面已经有 ( ) — 只填名字,别再带括号。`:` ⚠ blank ${i}: the ( ) after ____ is already in the template — type just the name, no brackets.`):(/["']$/.test(a)||/^["']/.test(s))&&/^["']|["']$/.test(l)?t.push(Vn()?` ⚠ 空${i}:引号模板里已经有了 — 只填引号中间的内容。`:` ⚠ blank ${i}: the quotes are already in the template — type only what goes between them.`):/^[A-Za-z_][\w.]*\(.*\)$/.test(l)&&!s.startsWith("(")&&/\)\s*[:)]/.test(s)&&t.push(Vn()?` ⚠ 空${i}:____ 后面已有右括号,你的答案可能多带了一个 )。`:` ⚠ blank ${i}: a closing ) already follows ____ — your answer may carry one too many.`)}}return t})(n.starter??"",l);for(const o of e)console.log(chalk.yellow(o));console.log(chalk.gray(Vn()?" 💡 两次没过,多半是细节不是思路 — 再敲之前过一遍:":" 💡 Two misses are usually a detail, not the idea — run this check before retrying:")),i||(console.log(chalk.gray(Vn()?" · 拼写和大小写(Python 区分大小写:Print ≠ print)":" · spelling and case (Python is case-sensitive: Print ≠ print)")),console.log(chalk.gray(Vn()?" · 只填缺的那一块 — ____ 周围已有的括号、引号、冒号不要重复":" · fill only what is missing — brackets, quotes, colons already around ____ stay"))),console.log(chalk.gray(Vn()?" · 没思路?往上翻,或 ":" · no idea? scroll up, or ")+chalk.bold.green("back")+chalk.gray(Vn()?" 回卡片再读一遍 — 答案就在正文里。打错字人人都有,继续。":" re-reads the card — the answer is in its body. Typos happen to everyone; keep going."))}console.log(chalk.gray(Vn()?" 从空1再来:":" From blank 1 again:")),cl()})(e),void fn();if(null!==An){if(xn.push(e.replace(/\s+$/,"")),Sn&&clearTimeout(Sn),Sn=null,Tn){const e=xn[xn.length-1]??"";return"/cancel"===e.trim()?(En(),console.log(chalk.gray(Vn()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void fn()):""!==e.trim()?void fn():(xn.pop(),void await c())}return void(Sn=setTimeout(()=>{if(Sn=null,xn.length>1){Tn=!0;const e=xn.length;return console.log(chalk.cyan(Vn()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(Vn()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void fn()}c()},140))}async function c(){const e=xn.join("\n").replace(/^\s+|\s+$/g,""),o=An??tn.currentCard,t=xn.length,n=Pn;if(En(),""===e)console.log(chalk.gray(Vn()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&jn.test(e))console.log(chalk.yellow(Vn()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(Vn()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(Vn()?" 即可执行。":" again to run it."));else{const r=!n&&Xn>0?Date.now()-Xn:void 0;if(await ie(Ft,{curriculum_id:Gt.id,card_number:o,feedback_text:n?`${n} ${e}`:e,time_on_card_ms:r})){const n=t>1?Vn()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(Vn()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(Vn()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),Xt=[...Xt,{id:en--,curriculumId:Gt.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Lt(Xt)}else console.log(chalk.yellow(Vn()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),fn()}if(Yn){const o=e.trim();if(jn.test(o))return Yn=!1,console.log(),console.log(chalk.yellow(Vn()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(Vn()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(Vn()?" 即可执行该命令。":" again to run it.")),console.log(),void fn();if(!o)return Yn=!1,console.log(chalk.gray(Vn()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void fn();const t=await Le({token:Ft,nickname:o});if(t.ok)Yn=!1,console.log(chalk.bold.green(Vn()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Vn()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Bn+=1;const e="taken"===t.code?Vn()?"已被占用":"already taken":"bad_charset"===t.code?Vn()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"real_name"===t.code?Vn()?"看起来像真名 — 系统不收集个人信息,换个游戏风格的昵称":"looks like a real name — we collect no personal info; pick a gamer-style handle":"rejected"===t.code?Vn()?"未通过审核":"did not pass review":t.message||"error";if(!(Bn>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Vn()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void fn();Yn=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Vn()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void fn()}if(Kn){Kn=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Mn=!0;try{console.log(),console.log(chalk.gray(Vn()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await Oe({token:Ft,cardNumber:tn.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Vn()?"评审暂不可用。":"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(Vn()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Vn()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Vn()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Vn()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Vn()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Vn()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=Vn()?` 本卡排名 #${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(Vn()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Vn()?` 第 ${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 Or(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Vn()?" 改进提问: ":" 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(` (${Vn()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Jn.add(tn.currentCard):Jn.delete(tn.currentCard),"number"==typeof e.rank&&er.set(tn.currentCard,e.rank);const o=await We({token:Ft,curriculumId:Gt.id,cardNumber:tn.currentCard});if(o.ok&&o.totals&&o.chapters&&(Dt({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),o.ok&&o.phaseBoard?.mine){const e=o.phaseBoard,t=o.phaseBoard.mine,n=e.top[0],r=n&&!n.me?chalk.gray(Vn()?` · 榜首 ${n.name||"Rank 1"} ${n.total}`:` · leader ${n.name||"Rank 1"} at ${n.total}`):chalk.bold.yellow(Vn()?" · 全场第一!":" · phase leader!");console.log(chalk.white(Vn()?` 🏅 Phase ${e.phase} 研究总分: `:` 🏅 Phase ${e.phase} research total: `)+chalk.bold.yellow(`${t.total}`)+chalk.gray(Vn()?`(${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&&!Zt&&(Yn=!0,Bn=0,console.log(chalk.bold.yellow(Vn()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Vn()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Vn()?" 英文开头,英文+数字,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{Mn=!1}})():(console.log(chalk.gray(Vn()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==wn&&(console.log(chalk.gray(Vn()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void fn()}if(Qn)return Qn=!1,Nr(),void fn();if(!o)return void fn();if(Gn)return"exit"===await U(e.trim())&&(Gn=!1),void fn();if(Nn){if(["q","quit","exit","back","b","menu"].includes(o))return Nn=!1,console.log(chalk.gray(Vn()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void fn();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),l=n.length>0&&!/[\p{L}\p{N}]/u.test(n);return r||l?(console.log(),console.log(chalk.yellow(Vn()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?Vn()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":Vn()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(Vn()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(Vn()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void fn()):(n&&(await qr(n,t?"fast":"deep"),console.log(chalk.gray(Kt?Vn()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)":Vn()?" (↩ q = 返回卡片)":" (↩ q = back to card)"))),void fn())}if(On){const t=e.trim();if(["back","b","quit","exit","q"].includes(o))return On=!1,Rn=null,P("learn-sh: leave"),"arena"===Wn?console.log(chalk.gray(Vn()?" ↩ 已离开实验台,回到赛场。":" ↩ Left the lab — back in the arena.")):"fill"===Wn&&Un?(Dn=Un,Un=null,dl()):(console.log(chalk.gray(Vn()?" ↩ 已离开 shell 实验台,回到卡片。":" ↩ Left the shell lab — back to the card.")),Nr()),void fn();if("menu"!==o&&!/^memo\b/.test(o)){if("reset"===o){const e=Wl(!0);return console.log(e.length>0?chalk.green((Vn()?" ↺ 已还原本卡的文件: ":" ↺ Restored this card's files: ")+e.join(" ")):chalk.gray(Vn()?" 本卡没有附带文件。":" This card ships no files.")),void fn()}return"clear"===o||"cls"===o?(console.clear(),Ol(),void fn()):"help"===o||"e"===o||"?"===o?(ql(),void fn()):""===t?void fn():/^\/?py(\s|$)/.test(o)?(On=!1,Rn=null,await Nl(/^\/?py\s+(\S+)/.exec(o)?.[1]),void fn()):(await(async e=>{P(`learn-sh: $ ${e}`);const o=/^cd(?:\s+(.*))?$/.exec(e.trim());if(o){const e=To(Ml(),Ll(),o[1]?.trim());return void(null===e?console.log(chalk.yellow(Vn()?" 去不了那儿 —— 目录不存在,或在实验台外面。":" Cannot go there — no such directory, or it is outside the lab.")+chalk.gray(Vn()?" cd 单独敲回到顶层。":" Bare `cd` returns to the top.")):Rn=e)}const t=vo(e);if(t)return void console.log(chalk.red((Vn(),` ⚠ \`${t.word}\` `))+chalk.yellow(t.why)+chalk.gray(Vn()?" —— 实验台不执行它。在自己的终端里敲之前,先 ls 看清楚它会碰到什么。":" — the lab never runs it. In your own terminal, `ls` what it will touch before you press Enter."));const n=Co(e);if(n)return void console.log(chalk.yellow(Vn()?` \`${e.trim().split(/\s+/)[0]}\` 会占住终端,这里跑不了 — `:` \`${e.trim().split(/\s+/)[0]}\` takes over the terminal and cannot run here — `)+chalk.bold.green(n));const r=/(^|[;&|]\s*)cd(\s|$)/.test(e)&&!/^cd(\s|$)/.test(e.trim()),l=await So(e,Ll());"no-shell"!==l.kind?"timeout"!==l.kind?"refused"!==l.kind&&(l.stdout&&console.log(chalk.white(l.stdout.replace(/\n$/,""))),l.stderr&&console.log(chalk.red(l.stderr.replace(/\n$/,""))),l.truncated&&console.log(chalk.gray(Vn()?" … 输出过长,已截断。":" … output truncated.")),r&&console.log(chalk.yellow(Vn()?" 注意:这一行里的 cd 只在子进程里生效,你还在原来的目录。":" Note: the cd in that line ran in a child process — you have not moved.")+chalk.gray(Vn()?" 单独敲一行 cd <目录>。":" Type `cd <dir>` on its own line.")),l.stdout||l.stderr?0!==l.code&&console.log(chalk.gray(Vn()?` (退出码 ${l.code})`:` (exit ${l.code})`)):console.log(chalk.gray(Vn()?` (没有输出 · 退出码 ${l.code})`:` (no output · exit ${l.code})`))):console.log(chalk.yellow(Vn()?` 超过 ${ko/1e3} 秒,已停止。`:` Stopped after ${ko/1e3}s.`)+chalk.gray(Vn()?" 换个更小的目标再试。":" Try a smaller target.")):console.log(chalk.red(Vn()?" 这台机器上找不到 /bin/sh。":" No /bin/sh on this machine.")+chalk.gray(Vn()?" Windows 请在 WSL2 里跑 icoa。":" On Windows, run icoa inside WSL2."))})(t),void fn())}}if(qn){if(/^\/?(py|pylist|edit|run|list|new)\b|^(b|q|quit|exit|back)$|^\d+$/.test(o)&&P(`learn-py: ${o}`),["back","b","quit","exit","q"].includes(o))return qn=!1,console.log(chalk.gray(Vn()?" ↩ 已离开草稿本,回到卡片。":" ↩ Left the scratchpad — back to the card.")),Nr(),void fn();const t=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(t||"list"===o||"/list"===o)return Il(t?.[1]),jl(),void fn();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=Pl(o);null!==t&&("edit"===e?(await El(t),jl()):await(async e=>{if(!Y(yo(xl(),e)))return void Pl(String(e));const o=Mo()?.cmd??null;if(!o)return void Eo(Vn());const[t,...n]=o.split(" ");console.log();const l=bo();let s="",a=!1;const i=await new Promise(o=>{const l=r(t,[...n,`py-${e}.py`],{cwd:xl(),stdio:["ignore","pipe","pipe"]}),i=setTimeout(()=>{a=!0;try{l.kill("SIGKILL")}catch{}},3e4);l.stdout?.on("data",e=>process.stdout.write(e)),l.stderr?.on("data",e=>{s.length<400&&(s+=e.toString("utf-8")),process.stderr.write(e)}),l.on("error",()=>{clearTimeout(i),o(127)}),l.on("close",(e,t)=>{clearTimeout(i),o(t?124:e??0)})}),c=l();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(Vn()?" ⏱ 超过 30 秒,已停止 — 检查死循环。":" ⏱ Over 30s — stopped. Check for an infinite loop."))),console.log(chalk.gray((Vn()," ▸ edit "))+chalk.gray(`${e} · pylist · `)+chalk.bold.green("back")),console.log(),sr.push(Sl(e,{run_ms:c,exit_code:i,stderr_head:s.trim().slice(0,300)||void 0},!0).catch(()=>{}))})(t))}else console.log(chalk.yellow(Vn()?` 用法: ${e} <编号>`:` Usage: ${e} <n>`)+chalk.gray(Vn()?" (pylist 看编号)":" (pylist shows the numbers)"));return void fn()}const l=/^\/?py(?:\s+(\S+))?$/.exec(o);if(l||"new"===o)return await Nl(l?.[1]),void fn();const s=/^\/?(python(?:3)?|m[ou]joco)(?:\s+(setup|install|status))?$/i.test(o.trim());if("menu"!==o&&"menu confirm"!==o&&!s)return console.log(chalk.gray(Vn()?" 草稿本命令: edit <n> · run <n> · pylist · /py 新建 · back 回卡片":" Scratchpad verbs: edit <n> · run <n> · pylist · /py (new) · back to the card")),void fn()}if(Ln&&fr){/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn|memo|cells|explore)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&P(`learn-arena p${fr.phase}s${fr.data.slot}: ${o}`);const n=/^([A-Ea-e])$/.exec(o.trim());if(n){const e=pl(yl??"1");if(e?.p.quiz)return P(`learn-arena p${fr.phase}s${fr.data.slot}: answer ${n[1].toUpperCase()}`),((e,o)=>{const t=oe(fr.dir,Hr(e.n,e.p));let n;try{n=G(t,"utf8")}catch{return console.log(chalk.yellow(Vn()?" 先 /read 一道题。":" Open a problem with /read first.")),!1}const r=/^(\s*Answer:\s*)(?:____|[A-Za-z0-9]+)\s*$/m,l=r.test(n)?n.replace(r,`$1${o}`):`${n.replace(/\s*$/,"")}\nAnswer: ${o}\n`;return K(t,l),console.log(chalk.gray(" Answer: ")+chalk.bold.green(o)),!0})(e,n[1].toUpperCase())?void await Ul(`/submit ${e.n}`):void fn()}if(tr&&("sh"===o||"/sh"===o))return Dl("arena"),console.log(chalk.gray(Vn()?" ▸ back 回赛场 · 计时照走":" ▸ back returns to the arena · the clock keeps running")),void fn();if("memo"===o||"/memo"===o||"e"===o)return An=tn.currentCard,Pn=`[arena p${fr.phase}-g${fr.data.slot}${yl?` #${yl}`:""}]`,console.log(chalk.gray(Vn()?` 报告归到: 竞技场 p${fr.phase}-g${fr.data.slot}${yl?` 题${yl}`:""} — 题面 / 判分 / 环境,一句话即可:`:` Files under: arena p${fr.phase}-g${fr.data.slot}${yl?` problem ${yl}`:""} — statement / judging / environment, one line is enough:`)),console.log(chalk.gray(Vn()?" (回车提交 · 空行取消 · 不打断比赛计时)":" (Enter to submit · blank to cancel · the contest clock is unaffected)")),void fn();if("back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Vr()&&null!==yl?(yl=null,ul(),void fn()):(Ln=!1,yl=null,console.log(chalk.gray(Vn()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Nr(),void fn());if(/^\d+$/.test(o))return fl(o),void fn();const r=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(r)return Vr()?r[1]?fl(r[1]):ul():console.log(chalk.gray(Vn()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void fn();if("cells"===o||"/cells"===o||"explore"===o||"/explore"===o){const e=vr(fr.phase,fr.data.slot,fr.dir);if(!e)return console.log(chalk.gray(kr(fr.phase,fr.data.slot)?Vn()?" 引导 notebook 还没下载到位(需要联网一次)— 稍后再敲 cells。":" The guided notebook has not downloaded yet (needs one online moment) — try cells again shortly.":Vn()?" 本场没有引导 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 fn();const o=null!==N();o||M(cn);try{const{runIpynb:o}=await import("./ipynb.js");await o(e)}catch(e){console.log(chalk.yellow(Vn()?" notebook 没打开: ":" The notebook failed to open: ")+chalk.gray(String(e)))}finally{o||M(null)}return ul(),void fn()}const s=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(s)return await(async e=>{const o=e.trim();if(await _e()||ml||(ml=!0,console.log(chalk.gray(Vn()?` (离线:只有 ${Ie()} 条核心速查可用;联网后自动补全)`:` (offline: ${Ie()} core entries available; the rest arrive when you have a connection)`))),!o)return void Se(Vn());const t=Ae(o);if(t.length){Pe(t[0],Vn());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(Vn()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await Ce("python3",o);if(n)je(n,Vn());else{if(await xe()){const e=Ae(o);if(e.length)return void Pe(e[0],Vn())}console.log(),console.log(chalk.yellow(Vn()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(Vn()?" 试试: ":" Try: ")+chalk.cyan(Te(o).join(" · "))),console.log(chalk.gray(Vn()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(s[1]??""),void fn();const a=/^\/?set\b\s*(.*)$/i.exec(e.trim());if(a)return await(async e=>{const o=pl(yl??"1");if(!o)return;const t=oe(fr.dir,Hr(o.n,o.p));let n;try{n=G(t,"utf8")}catch{return void console.log(chalk.yellow(Vn()?" 先 /read 一道题。":" Open a problem with /read first."))}const r=_l(n);if(0===r.length)return void console.log(chalk.yellow(Vn()?" 这道题的文件没有旋钮(顶部那种 NAME = value 行)。":" This problem's file has no knobs (the NAME = value lines at the top).")+chalk.gray(Vn()?" 用 ":" Use ")+chalk.bold.green(`/edit ${o.n}`));const l=/^([A-Za-z][A-Za-z0-9_]*)\s*(?:=|\s)\s*(.+)$/.exec(e.trim());if(!l){console.log(chalk.yellow(Vn()?" 用法: ":" Usage: ")+chalk.bold.green(Vn()?"set <旋钮> <值>":"set <KNOB> <value>")+chalk.gray(Vn()?" 例如 set WOMBATS 6":" e.g. set WOMBATS 6")),console.log(chalk.gray(Vn()?" 这个 bot 的旋钮:":" This bot's knobs:"));for(const e of r)console.log(chalk.gray(" ")+chalk.bold.white(e.padEnd(10))+chalk.gray(Cl(n,e)??""));return}const s=l[1].toUpperCase(),a=l[2].trim(),i=r.find(e=>e===s);if(!i)return console.log(chalk.yellow(Vn()?` 这个 bot 没有 ${s} 这个旋钮。`:` This bot has no knob called ${s}.`)),void console.log(chalk.gray(" ")+r.map(e=>chalk.bold.white(e)).join(chalk.gray(" · ")));const c=Cl(n,i)??"";if(c.trim()===a)return void console.log(chalk.gray((Vn()," "))+chalk.bold.white(i)+chalk.gray(Vn()?` 已经是 ${a} 了。`:` is already ${a}.`)+chalk.gray(Vn()?" 下一步: ":" Next: ")+chalk.bold.green(`/run ${o.n}`));const d=new RegExp(`^(${i}\\s*=\\s*)([^#\n]*?)(\\s*)(#.*)?$`,"m"),g=n.replace(d,(e,o,t,n,r)=>`${o}${a}${r?(n||" ")+r:""}`);K(t,g),console.log(chalk.gray(" ")+chalk.bold.white(i)+chalk.gray(" ")+chalk.gray(c.trim())+chalk.gray(" → ")+chalk.bold.green(a)),console.log(chalk.gray((Vn()," ▸ "))+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Vn()?" 打一局看看 · ":" play a match and watch · ")+chalk.bold.green(`set ${i} ${c.trim()}`)+chalk.gray(Vn()?" 改回去":" puts it back"))})(a[1]??""),void fn();const i=/^\/?(read|open|edit|run|debug|list|recall|replay)(?:\s+(\S+))?$/.exec(o);if(i){const[,e,o]=i;return"list"===e?ul():"replay"===e?await Uo()||console.log(chalk.gray(Vn()?" 还没有回放。先 submit 一次 —— 判分机会把你输的那一局送回来。":" No replay yet. Submit once — the judge sends back the game you lost.")):o?"read"===e||"open"===e?fl(o):"edit"===e?await(async e=>{const o=pl(e);if(!o)return;const t=oe(fr.dir,Hr(o.n,o.p));if(Zo())return Ho()?(console.log(chalk.yellow(Vn()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(Vn()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(Vn()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(Vn()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(Vn()?" ← 不能是 /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(Vn()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(Vn()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(Vn()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(Vn()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(Vn()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(Vn()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(Vn()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(Vn()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!Ko("vi"))return console.log(chalk.yellow(Vn()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(Vn()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));wl();const n=e=>{try{return H(e).size}catch{return 0}},r=n(t),l=Date.now(),s=I(t);await $l("vi",[...bl,Hr(o.n,o.p)]);const a=s.stop(),i={ms:Date.now()-l,bytesBefore:r,bytesAfter:n(t)};if($r.set(o.n,Q($r.get(o.n)??J(),i)),a.ticks>0){const e=br.get(o.n)??{list:[],dropped:0};e.list.push(a),e.list.length>16&&(e.list.shift(),e.dropped++),br.set(o.n,e)}P(`learn-arena edit-done ${Hr(o.n,o.p)}`,{...i,...a.ticks>0?{samples:a}:{}}),console.log(chalk.gray(Vn()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Ur(o.p)?Vn()?" 本机打一局。":" to play one match here.":Vn()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?await(async e=>{const o=pl(e);if(!o)return;const{p:n,n:r}=o;if(Ur(n)){const e=oe(fr.dir,Hr(r,n));if(!Y(e))return void console.log(chalk.yellow(Vn()?` 还没有 ${Hr(r,n)} — 先 /edit ${r}。`:` No ${Hr(r,n)} yet — /edit ${r} first.`));$r.set(r,V($r.get(r)??J()));const o=await Yo(e,n.card??0,0,n.crit,(e,o)=>$l(e,o));return void(o.ran&&(console.log(o.ok?chalk.gray(" ▸ ")+chalk.bold.green(`/submit ${r}`)+chalk.gray(Vn()?" 过线了 — 交给判分机(多局固定种子)":" over the bar — send it to the judge (seeded games)"):chalk.gray(" ▸ ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Vn()?" 改一改,再 ":" adjust, then ")+chalk.bold.green(`/run ${r}`)),console.log()))}if(Yr&&r===Ve)return void(()=>{const e=oe(fr.dir,`sol-${Ve}.py`);if(!Y(e))return void console.log(chalk.yellow(Vn()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=vl();if(!o)return;const n=[];for(const r of eo)try{n.push(t(o,[e],{input:`${r.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}))}catch(e){const o=e;if("ENOENT"===o.code)return void kl();if(console.log(),o.killed)return void console.log(chalk.yellow(Vn()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(Vn()?` ✗ 输入 ${r.in} 时程序报错:`:` ✗ Your program crashed on input ${r.in}:`));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));return console.log(),console.log(chalk.gray(Vn()?" 改完再来: ":" Fix it and rerun: ")+chalk.bold.green("/edit 0")+chalk.gray(" → ")+chalk.bold.green("/run 0")),void console.log()}const{cases:r,passed:l}=oo(n);console.log();for(const e of r)console.log((e.ok?chalk.green(" ✓ "):chalk.red(" ✗ "))+chalk.gray(`n = ${e.in.padEnd(6)} → `)+(e.ok?chalk.cyan(e.got||"(empty)"):chalk.red(e.got||"(empty)"))+(e.ok?"":chalk.gray(Vn()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),l===r.length){const e=Br?null:1;Br=!0,console.log(chalk.bold.green(Vn()?` 🎉 ${l}/${r.length} 全过 — `:` 🎉 ${l}/${r.length} — `)+chalk.white(Vn()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(Vn()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(Vn()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(Vn()?` ${l}/${r.length} 通过 — 还差一点。`:` ${l}/${r.length} passed — not there yet.`)+chalk.gray(Vn()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(Vn()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const l=oe(fr.dir,Hr(r,n));if(!Y(l))return void console.log(chalk.yellow(Vn()?` 还没有 ${Hr(r,n)} — 先 /edit ${r}。`:` No ${Hr(r,n)} yet — /edit ${r} first.`));$r.set(r,V($r.get(r)??J()));const s=(n.samples??[])[0];if(n.gpu)return console.log(chalk.gray(Vn()?" ⚡ 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(Vn()?"(窗口时间执行并返回你的 ms;窗口外会告诉你开放时间)":" (executes in the GPU window and returns your ms; outside the window it tells you the hours)")),void console.log();{const e=Zr(n),o={cpp:"c++",java:"java",go:"go"};if("python"===e?!Lo():!Ko(o[e]??e)){const t="python"===e?"Python":o[e]??e;return console.log(chalk.yellow(Vn()?` ⓘ 本机没有 ${t} 环境 — 这一题直接交给判分机跑。`:` ⓘ No local ${t} environment — running this one on the server judge instead.`)),console.log(chalk.gray(Vn()?" 判分机的计时本来就是准数;本地跑只是预览。":" The judge's timing is the real number anyway - local runs were only a preview.")),void await Ul(`/submit ${r}`)}}if(!s&&n.starter){const e=Zr(n);try{let o;if("cpp"===e){const e=oe(fr.dir,`.speed-${r}.bin`);t("c++",["-O2","-o",e,l],{timeout:3e4,stdio:["pipe","pipe","pipe"]}),o=t(e,[],{input:"",timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}else if("java"===e)o=t("java",[l],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});else if("go"===e)o=t("go",["run",l],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});else{const e=vl();if(!e)return;o=t(e,[l],{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(Vn()?` ${co(!0)} — 满意就 `:` ${co(!1)} — happy? `)+chalk.bold.green(`/submit ${r}`))}catch(e){const o=e;if("ENOENT"===o.code)kl();else if(o.killed)console.log(chalk.yellow(Vn()?" ⏱ 超过 30 秒 — 检查死循环。":" ⏱ Over 30s — check for an infinite loop."));else{console.log(chalk.yellow(Vn()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr??"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));console.log(chalk.gray(Vn()?` (空还没填对?/read ${r} 看题面的 hint,/edit ${r} 再改)`:` (blank not filled yet? /read ${r} for the hint, /edit ${r} to fix)`))}}return void console.log()}if(!s)return void console.log(chalk.gray(Vn()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";const i=vl();if(!i)return;const c=bo();try{a=t(i,[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(e){const o=e;if("ENOENT"===o.code)kl();else if(o.killed)console.log(chalk.yellow(Vn()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Vn()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const d=c(),g=a.replace(/\r\n/g,"\n").trimEnd(),u=s.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(Vn()?" 你的输出:":" Your output:"));for(const e of(g||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Vn()?" 样例应输出:":" Sample expects:"));for(const e of u.split("\n"))console.log(chalk.green(` ${e}`));console.log(chalk.gray(` ⏱ ${d}ms — ${co(Vn())}`)),g===u?console.log(chalk.bold.green(Vn()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Vn()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Vn()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Vn()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=pl(e);if(!o)return;if(Ur(o.p))return console.log(chalk.gray(Vn()?` bot 不读输入 — /run ${o.n} 本机打一局就是自由试跑,/submit ${o.n} 判分。`:` A bot reads no input — /run ${o.n} plays a match here (that is the free run); /submit ${o.n} judges.`)),void console.log();if("python"!==Zr(o.p)||o.p.gpu)return console.log(chalk.gray(Vn()?` 这一层不读输入 — 用 /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=oe(fr.dir,`sol-${o.n}.py`);if(!Y(t))return void console.log(chalk.yellow(Vn()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));const n=vl();if(!n)return;console.log(chalk.gray(Vn()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const r=await $l(n,[`sol-${o.n}.py`]);console.log(),"ENOENT"!==r?.code?(console.log(chalk.gray(Vn()?" 回到竞技场。":" Back in the arena.")),console.log()):kl()})(o):"recall"===e&&await(async e=>{const o=pl(e);if(!o)return;if(!Kt)return void Lr();const{p:t,n:n}=o,r=oe(process.cwd(),"icoa-contest"),l=`${Gt.id}-phase${fr.phase}-g${fr.data.slot}-archived-`;let s=null;try{for(const e of F(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?oe(r,s,`sol-${n}.py`):null;if(!a||!Y(a))return void console.log(chalk.gray(Vn()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=G(a,"utf-8"),c=`${fr.phase}-${fr.data.slot}-${n}`,d=Math.min(3,(Al.get(c)??0)+1);console.log(chalk.gray(Vn()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await Me({token:Ft,phase:fr.phase,slot:fr.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:Vn()?"zh":"en"});if(g.ok){Al.set(c,d),console.log();for(const e of Ut(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(Vn()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(Vn()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(Vn()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(Vn()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(Vn()?" (花名册: /list)":" (roster: /list)")),void fn()}if("contest"===o||"/contest"===o)return ul(),void fn();const c="lang"===o||/^lang\s+\S+$/.test(o),d=Yt.has(o);if(!(/^\/?(python(?:3)?|m[ou]joco)(?:\s+(setup|install|status))?$/i.test(o.trim())||"submit"===l||l.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||"restart"===o||c||d||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(Vn()?" 竞技场命令: /read set /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read set /edit /run /debug /submit /list /syntax · back returns to the lesson")),void fn()}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(Vn()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void fn()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(cn.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}mn=!0;const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}mn=!1,cn.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void fn()}if("ai4ioai"===o||"/ai4ioai"===o)return await z()&&(Gn=!0),void fn();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(Zt)return Lr(),void fn();Fn||(Fn=!0,console.log(),Kt?(console.log(chalk.bold.cyan(Vn()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Vn()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Vn()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Vn()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")),console.log(chalk.gray(Vn()?" 💡 一次好的研究通常会向 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(Vn()?" 新建草稿贴进去跑(":" a fresh scratch file and run them (")+chalk.bold.green("/pylist")+chalk.gray(Vn()?" 看草稿)。":" lists them)."))):(console.log(chalk.bold.cyan(Vn()?" 🐼 AI 熊猫导师":" 🐼 AI Panda Tutor")),console.log(chalk.gray(Vn()?` 围绕本卡内容提问 — 导师已经读过这张卡。每张卡每天最多 ${Jt} 个问题;`:` Ask about THIS card — the tutor has read it. Up to ${Jt} questions per card per day;`)),console.log(chalk.gray(Vn()?" 跑题的问题不会被回答,也不计次数。这里只是问答,没有评分和榜单。":" off-topic questions are not answered and do not count. Q&A only — no grading, no board."))),console.log(chalk.yellow(Vn()?" ↩ 重要:退出 AI 模式只需输入 ":" ↩ Important: to leave AI mode just type ")+chalk.bold.white("back")+chalk.yellow(Vn()?" 或 ":" or ")+chalk.bold.white("quit")+chalk.yellow(Vn()?",就回到卡片。":" — you are back on the card.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Nn=!0;const e=gr(tn.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Vn()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(Vn()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Kt?Vn()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · back / quit = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · back / quit = back to card":Vn()?" 直接输入问题 · back / quit = 返回卡片":" Type a question · back / quit = back to card")),Kt&&console.log(chalk.gray(Vn()?" 💡 通常要向 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 fn()}return await qr(n,t?"fast":"deep"),void fn()}if(!Ln&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Kt)return Lr(),void fn();const e=gr(tn.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Vn()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Vn()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Vn()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Vn()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Vn()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Vn()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Vn()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Kn=!0,void fn()}const p=!Ln&&"honors"===zn&&/^[1-3]$/.test(o);if(!Ln&&zn&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(Vn()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(Vn()?" ↩ back 回上一层":" ↩ back goes up one level")),void fn();if(!Ln&&(p||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Kt)return Lr(),void fn();const e=/^\/?view ([1-3])$/.exec(o),t=p?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Mn=!0;try{console.log();const o=await Re({token:Ft,cardNumber:tn.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Vn()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Jn.delete(tn.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Jn.add(tn.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Vn()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${tn.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${tn.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Vn()?` (第 ${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(Vn()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Or(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(Vn()?" (无可显示的提问)":" (no questions to show)"))}console.log(),zn="view",console.log(chalk.gray((Vn()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Vn()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Mn=!1}})(t),void fn()}const _=o.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(_&&!Ln&&!qn){const{certificateLines:e}=await import("../lib/learn-door.js"),{certifiable:o,certificateIntroLines:t}=await import("../lib/learn-certificate.js"),n=Vn(),r=Zt?null:await v(Ft,"me"),l=r&&"ok"===r.kind?r.profile:null,s=o(l),a=(_[2]??"").toLowerCase();console.log();const i=a?s.find(e=>e.curriculum_id.toLowerCase()===a||e.curriculum_id.toLowerCase().startsWith(a)):s.find(e=>e.curriculum_id===Gt.id)??(1===s.length?s[0]:void 0);if(!i){for(const o of e(l,n))console.log(o);return s.length>1&&console.log(chalk.gray(" ")+chalk.bold.green("certificate <track>")+chalk.gray(n?" 签发其中一门。":" to issue one.")),console.log(),void fn()}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:")),yn={cid:i.curriculum_id,tok:i.token,first:null},void fn()}const A=o.match(/^\/?(story|credits|fin)(?:\s+(\S+))?$/);if(A&&!Ln&&!qn){const e=(A[2]??"").trim();return await hr("story"===A[1]?e||"list":e||null,!0),void fn()}if(/^\/?(?:type|typing)(?:\s|$)/i.test(o))return await Wo(o.trim().split(/\s+/).slice(1)),void fn();if(/^\/?battle(?:\s|$)/i.test(o)&&!Ln&&!qn){const e=null!==N();return e||M(cn),await zo([...o.trim().split(/\s+/).slice(1),`from-card:${tn.currentCard}`]),e||M(null),void fn()}if(/^\/?duck(?:\s|$)/i.test(o)&&!Ln&&!qn){const e=null!==N();return e||M(cn),await Fo([...o.trim().split(/\s+/).slice(1),`from-card:${tn.currentCard}`]),e||M(null),void fn()}if(O(o))return await R(),void fn();if("me"===o||"/me"===o||"profile"===o||"/profile"===o||"my profile"===o){const e=Vn();if(Zt)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 fn();console.log(chalk.gray(e?" 正在取档案…":" Loading your profile…"));const o=await v(Ft);return"ok"===o.kind?C(o.profile,e,Wt()):"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 fn()}if("/honors"===o||"honors"===o)return Zt?(console.log(),console.log(chalk.gray(Vn()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void fn()):(await Wr(),void fn());const x=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(x)return P("learn-py: pylist"+(x[1]?` ${x[1]}`:"")),Il(x[1]),void fn();const T=/^\/?py(?:\s+(\S+))?$/.exec(o);if(T)return await Nl(T[1]),void fn();if(/^\/?sh$/.test(o))return Dl(),void fn();const S=/^\/?(python(?:3)?|m[ou]joco)(?:\s+(setup|install|status))?$/i.exec(o.trim());if(S){const e=/^m[ou]joco$/i.test(S[1]);P(`learn-${e?"mujoco":"python"}: ${S[2]??"status"}`);const o=(S[2]??"").toLowerCase();if(e){const{runMujocoSetup:e,printMujocoStatus:t}=await import("./mujoco.js");"setup"===o||"install"===o?await e():t()}else{const{runSetup:e,printStatus:t}=await import("./python.js");"setup"===o||"install"===o?await e():t()}return console.log(chalk.gray(Vn()?" ↩ back 回卡片 · ":" ↩ back to the card · ")+chalk.bold.green("/py")+chalk.gray(Vn()?" 打开草稿本":" opens the scratchpad")),console.log(),void fn()}if(kn&&"menu"!==o&&"menu confirm"!==o){const e=kn.handle(o);return"input"===e||Cn(e),void fn()}if(kn&&(kn=null),"menu"===o||"menu confirm"===o){if(un?.detach(),sr.length>0&&await Promise.race([Promise.allSettled(sr),new Promise(e=>setTimeout(e,3e3))]),cn.removeAllListeners("line"),gn(),sn||!dr){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(sn?cn:void 0),cr()}else cn.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===zn)return await Wr(),void fn();if("honors"===zn)return zn=null,Nr(),void fn();if(un?.detach(),sr.length>0&&await Promise.race([Promise.allSettled(sr),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${tn.streakDays} day(s)`)),console.log(),sn){cn.removeAllListeners("line"),gn();for(const e of an)cn.on("line",e);cn.prompt(),cr()}else cn.removeAllListeners("line"),cn.close();return}if(he(o))return Vt?Bt(ge(Vt,Vn(),Wt(),"T0"===pe().tier),!!Vt.completedAt):(console.log(chalk.gray(Vn()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void fn();{const e=o.match(y);if(e)return _r?(await m(Ft,e[1]??"",{curriculum:Gt}),P("learn: check"),void fn()):(console.log(chalk.yellow(Vn()?" check 需要正式课程 token(demo 不支持)。":" check needs a full curriculum token (not demos).")),void fn())}{const e=o.match(f);if(e)return _r?(await $(Ft,e[1]??"",Gt.totalCards),P("learn: class"),void fn()):(console.log(chalk.yellow(Vn()?" class 需要正式课程 token(demo 不支持)。":" class needs a full curriculum token (not demos).")),void fn())}if(b.test(o)&&!Ln&&!qn&&!On){if(!_r)return console.log(chalk.yellow(Vn()?" 队伍会议室凭 FTC 课程 token 进入(demo 不支持)。":" Team meeting needs an FTC course token (not demos).")),void fn();P("learn: teammeeting");const e=cn.listeners("line");cn.removeAllListeners("line");let o="back";try{o=await k(Ft,w(cn))}finally{for(const o of e)cn.on("line",o)}return"menu"===o?void cn.emit("line","menu"):(console.log(chalk.gray(Vn()?" ↩ 回到课程。":" ↩ Back to the course.")),void fn())}if("status"===o||/^status\s+/.test(o)){const e=o.slice(6).trim().toLowerCase(),t="all"===e?"all":/^\d+$/.test(e)?Number(e):"current";if(_r){const[,e]=await Promise.all([Tr(),ne(Gt.id,Ft,!0)]);e&&Object.assign(Gt,e)}return wt(Gt,tn,{gate:mr,gated:Qt,focus:t,posForSlot:Je}),void fn()}if("sync"===o){P("learn: sync");const e=await ae(Ft);if(!e)return console.log(chalk.yellow(" ⚠ ")+chalk.white(Vn()?"连不上服务器,进度保持本地。":"Server unreachable — keeping local progress.")),void fn();const o=tn.currentCard;return et(tn,Gt.totalCards,e),Qo(tn),tn.currentCard>o?console.log(chalk.green(" ↩ ")+chalk.white(Vn()?`已同步:${tn.cardsCompleted.length} 张卡完成,从第 ${tn.currentCard} 张继续`:`Synced: ${tn.cardsCompleted.length} cards done, resuming at card ${tn.currentCard}`)):console.log(chalk.green(" ✓ ")+chalk.white(Vn()?"已与服务器同步,无新进度。":"Synced with the server — no new progress.")),void fn()}if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await ne(Gt.id,Ft,!0);return void(e?(Object.assign(Gt,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Nr()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),fn()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(Oo().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void fn();const t=Gt.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,l=r?n:"en";return Ro({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),wn=null,$n=null,bn=null,En(),Qn=!1,Kn=!1,await Rr(),void fn()}const j=o.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(j&&!Ln&&!qn&&null===Dn&&g.test(o)){const e=Vn(),o=await u(Ft);if("ok"===o.kind)for(const t of h(o.log,e,"T0"===pe().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 fn()}if(j&&!Ln&&!qn&&null===Dn){const e=(j[2]??"").trim(),o=Vn(),t=`${a}–${s}`+(o?`,${i} 的倍数`:`, steps of ${i}`);if("off"===e||"stop"===e||"end"===e||"cancel"===e||"关"===e)return void(un?.stop()||(console.log(chalk.gray(o?" 没有进行中的专注。开始一场:":" No focus session running. Start one: ")+chalk.bold.green("focus 30")),fn()));if(un?.active)return console.log(chalk.yellow(" ⏱ ")+chalk.white(o?`专注进行中 · 还剩 ${un.remainingMin()} 分钟`:`focus running · ${un.remainingMin()} min left`)+chalk.gray(o?" · 提前结束:":" · end early: ")+chalk.bold.green("focus off")),void fn();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 fn();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 fn();if("ok"!==n.note){const t="min"===n.note?o?`最少 ${a}`:`min is ${a}`:"max"===n.note?o?`最多 ${s}`:`max is ${s}`:o?`取最近的 ${i} 的倍数`:`rounded to the nearest ${i}`;console.log(chalk.gray(o?` 你输入 ${e} → ${t},用 ${n.min}`:` you typed ${e} → ${t}, using ${n.min}`))}return un?.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 fn()}if(Yt.has(o)){const e=Yt.get(o),t=Ot(Oo()),n=e=>{const o=["normal","wide","wider","widest"].filter(o=>o!==e);return Vn()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((Vn()?"normal"===e?" 已是标准 64 列。":Wt()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Wt()} 列,上限 ${Rt(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Wt()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Wt()} cols, cap ${Rt(e)}). `)+n(e))),void fn()):(Ro({learnWidth:e,learnWide:"normal"!==e}),qt(e),"normal"!==e&&Wt()<=64?(console.log(chalk.yellow(Vn()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((Vn()?` 设置已记住(${e},上限 ${Rt(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Rt(e)} cols) and applies once you widen the window. `)+n(e))),void fn()):(console.log(chalk.green(" ✓ ")+chalk.gray((Vn()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Wt()} 列,上限 ${Rt(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Wt()} cols, cap ${Rt(e)}). `)+n(e))),wn=null,$n=null,bn=null,En(),Qn=!1,Kn=!1,await Rr(),void fn()))}if("sim"===o){const e=gr(tn.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=ee(te(import.meta.url)),o=[oe(e,"..","..","panda","mujoco-launcher.py"),oe(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(Y(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 fn()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void fn())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=tn.currentCard,t=tn.bookmarks.includes(e),n="bookmark"!==o;return n?tn.bookmarks=tn.bookmarks.filter(o=>o!==e):t||tn.bookmarks.push(e),Qo(tn),n?console.log(t?chalk.gray(Vn()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(Vn()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(Vn()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(Vn()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void fn()}const E=ye(o);if(E){const e="current"===E.target?tn.currentCard:E.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>Gt.cards.length))return console.log(chalk.yellow(Vn()?` 本课共 ${Gt.cards.length} 张,请输 r 1–${Gt.cards.length} 或 r all。`:` This course has ${Gt.cards.length} cards. Try r 1–${Gt.cards.length} or r all.`)),console.log(),void fn();for(const o of me(Xt,lr,e,Vn(),Wt()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?Xt:Xt.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(Xt=Xt.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Lt(Xt),sr.push(le(Ft,{card_number:tn.currentCard,event_type:"viewed"},o).catch(()=>{}))),void fn()}if("e"===o||"memo"===o)return An=tn.currentCard,console.log(chalk.gray(Vn()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(Vn()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void fn();if("back"===o||"b"===o&&null===$n)return"view"===zn?(await Wr(),void fn()):"honors"===zn?(zn=null,Nr(),void fn()):(tn.currentCard>1&&(tn.currentCard-=1),$n=null,bn=null,wn=null,Qo(tn),Nr(),void fn());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!_r)return console.log(chalk.yellow(Vn()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void fn();if(!e){const e=await Be(Ft),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(Vn()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(Vn()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(Vn()?` 这台电脑上有 ${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(Vn()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(Vn()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(Vn()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(Vn()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(Vn()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(Vn()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(Vn()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void fn()}if(/^\d{1,2}$/.test(e)){const o=await Ye(Ft,Number(e));return o.ok&&o.data?(Jr(o.data),await Tr(),void fn()):(console.log(chalk.red(` ✗ ${o.message||(Vn()?"关联失败":"Link failed")}`)),void fn())}const t=await Fe(Ft,e);return t.ok&&t.data?(Jr(t.data),await Tr(),void fn()):(console.log(chalk.red(` ✗ ${t.message||(Vn()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(Vn()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void fn())}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(!_r)return console.log(chalk.yellow(Vn()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void fn();if("duck"===$t()&&!Ln&&!qn){console.log(chalk.gray(Vn()?" 这条轨的检查点在 duck 子 REPL 里打:进入 duck → run 试跑 → submit 判分。":" This track's checkpoints are played in duck: duck → run → submit."));const e=null!==N();return e||M(cn),await Fo([`from-card:${tn.currentCard}`]),e||M(null),void fn()}let e=Sr(tn.currentCard),t=null;const n="contest restart"===o||"restart"===o;if(n&&(!Ln||!fr||Vr()))return console.log(chalk.gray(Vn()?" 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 fn();if(n&&fr){const o=fr.phase,n=fr.data.slot,r=await De(Ft,o,n);if(!r.ok&&"no_active_session"!==r.code)return console.log(chalk.red(` ✗ ${r.message||"reset failed"}`)),void fn();el(o,n),console.log(chalk.yellow(Vn()?` 🔄 第 ${n} 组重开 — 全新计时、全新模板。`:` 🔄 Group ${n} restarted — fresh clock, fresh templates.`)+chalk.gray(Vn()?" 只有计时内写的才算数:从头再写一遍,这正是练习。":" Only work written on the clock counts — write it again from scratch; that is the practice.")),fr=null,Ln=!1,yl=null,e=o,t=n}if("contest reset"===o&&Ln&&Vr()){const e=fr.phase,o=fr.data.slot,t=await De(Ft,e,o);if(t.ok){console.log(chalk.yellow(Vn()?" 已放弃本卡练习计时。回卡片后输入 practice <题号> 重新开始。":" Practice attempt abandoned. From the card, practice <n> starts a fresh one."));const t=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),n=oe(process.cwd(),"icoa-contest",`${Gt.id}-phase${e}-g${o}`);if(Y(n))try{Z(n,`${n}-archived-${t}`),console.log(chalk.gray(Vn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(Vn()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}fr=null,Ln=!1,yl=null,Nr()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void fn()}if("contest reset"===o){const o=await De(Ft,e);if(o.ok){console.log(chalk.yellow(Vn()?` 已放弃本阶段(${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=oe(process.cwd(),"icoa-contest"),n=new RegExp(`^${Gt.id}-phase${e}-g(\\d+)$`),r=(Y(t)?F(t):[]).map(e=>({name:e,m:n.exec(e)})).filter(({m:e})=>e&&Number(e[1])<Xr).map(({name:e})=>e).sort();for(const e of r){const n=oe(t,e);try{Z(n,`${n}-archived-${o}`),console.log(chalk.gray(Vn()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(Vn()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(Vn()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),fr=null,Ln=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void fn()}const r=null!=t?String(t):/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Vn()?" 连接判分赛…":" Contacting contest server…"));const l=await Ue(Ft,e,r?parseInt(r,10):void 0);if(!l.ok||!l.data){if("no_contest"===l.code){const o=Gt.modules.find(o=>o.number===e)?.cardRange,t=!!o&&o[1]-o[0]+1>12,n=He(o?o[1]-o[0]+1:12);console.log(chalk.gray(t?Vn()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(360 层第二阶段标准设计中)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (360-tier second-stage standard in design).`:or?Vn()?n.n>1?` 本阶段(${e})的 ${n.n} 场判分赛制作中 — 很快更新;赛场挂在卡 ${n.cards},${n.n} 场全过解锁下一阶段(本轨无 research)。`:` 本阶段(${e})的判分赛制作中 — 很快更新;赛场挂在卡 ${n.cards},通过即解锁下一阶段(本轨无 research)。`:n.n>1?` Phase ${e}'s ${n.n} judged arenas are in production — coming soon; they hang on cards ${n.cards} and all ${n.n} unlock the next phase (no research on this track).`:` Phase ${e}'s judged arena is in production — coming soon; it hangs on card ${n.cards} and passing it unlocks the next phase (no research on this track).`:Vn()?` 本阶段(${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(` ✗ ${l.message||"contest unavailable"}`));return void fn()}const s=l.data,a=oe(process.cwd(),"icoa-contest",`${Gt.id}-phase${e}-g${s.slot}`);if(!s.resumed&&Y(a)&&F(a).some(e=>/^sol-\d+\.[a-z]+$/.test(e))){const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{Z(a,`${a}-archived-${e}`),console.log(chalk.gray(Vn()?" 📦 上一场的答题文件已归档: ":" 📦 Previous window archived: ")+chalk.gray(`${a}-archived-${e}`)),console.log(chalk.gray(Vn()?" 新场次全新模板 — 计时窗口内写的才算数。":" Fresh window, fresh templates — only work done on the clock counts."))}catch{console.log(chalk.yellow(Vn()?` ⚠ 归档失败(比赛照常): ${a}`:` ⚠ Could not archive (contest still fine): ${a}`))}}B(a,{recursive:!0});const i=fr&&fr.phase===e&&fr.data.slot===s.slot?fr.tried:new Set;fr&&fr.phase===e&&fr.data.slot===s.slot&&fr.data.attempt===s.attempt||($r.clear(),br.clear()),fr={phase:e,dir:a,data:s,tried:i},Kr(s,a),vr(e,s.slot,a),Ln=!0,ul(),console.log(chalk.gray(Vn()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(a));const c=s.problems.findIndex(e=>!s.solved.includes(e.id))+1||1,d=Yr&&!Br?Ve:c;return console.log(chalk.white(Vn()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${d}`)+chalk.gray(d===Ve?Vn()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":Vn()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void fn()}if(/^\/?(?:flow|walk)$/.test(o)){const e=gr(tn.currentCard),o=e&&"knowledge"===e.type?e.flow:void 0;return o&&0!==o.length?(_n(e,!1),void fn()):(console.log(chalk.gray(Vn()?" 这张卡没有互动流程 — 有流程的卡片脚注会印 [flow]。":" No interactive walk on this card — cards that have one show [flow] in the footer.")),void fn())}const L=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(or&&/^[1-9]$/.test(o)?`practice ${o}`:o);if(L){const e=gr(tn.currentCard),o=tl(e);if(!o)return console.log(chalk.gray(Vn()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void fn();if(!_r)return console.log(chalk.yellow(Vn()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void fn();if(!L[1])return console.log(),ll(e),console.log(chalk.gray(Vn()?" 用法: ":" Usage: ")+chalk.bold.green(Vn()?"practice <题号>":"practice <n>")+chalk.gray(Vn()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void fn();const t=parseInt(L[1],10);if(!Number.isInteger(t)||t<1||t>o.length)return console.log(chalk.yellow(Vn()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void fn();const n=o[t-1],r=nl(n),l=o.filter(e=>nl(e)===r),s=l.indexOf(n)+1;return await(r||!or?(async(e,o,t)=>{const n=Sr(e.number),r=Xr+e.number;console.log(chalk.gray(Vn()?" 连接判分赛…":" Contacting contest server…"));const l=await Ue(Ft,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(Vn()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${l.message||"practice unavailable"}`)));const s=l.data;if(0===s.problems.length)return void console.log(chalk.gray(Vn()?" 本卡练习题库是空的。":" This card practice set is empty."));const a=new Map(s.problems.map(e=>[e.id,e])),i=[];for(const e of o){const o=a.has(ol(e.py_id))?ol(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 s.problems)a.has(e.id)&&0===i.length&&i.push(e);s.problems=i;let c=Cr.get(r);c||(c=new Set,Cr.set(r,c));for(const e of s.solved)c.add(e);const d=oe(process.cwd(),"icoa-contest",`${Gt.id}-phase${n}-g${r}`);B(d,{recursive:!0});const g=fr&&fr.phase===n&&fr.data.slot===r?fr.tried:new Set;fr&&fr.phase===n&&fr.data.slot===r&&fr.data.attempt===s.attempt||($r.clear(),br.clear()),fr={phase:n,dir:d,data:s,tried:g},Kr(s,d),Ln=!0,yl=null,P(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(Vn()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(Vn()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(Vn()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(d)),console.log(chalk.gray((Vn()," ↩ "))+chalk.bold.green("back")+chalk.gray(Vn()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),fl(String(Math.min(t,s.problems.length)))})(e,l,s):(async(e,o,t)=>{const n=Sr(e.number),r=Xr+e.number;Un=null,console.log(chalk.gray(Vn()?" 连接判分赛…":" Contacting contest server…"));const l=await Ue(Ft,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(Vn()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${l.message||"practice unavailable"}`)));const s=l.data;if(0===s.problems.length)return void console.log(chalk.gray(Vn()?" 本卡练习题库是空的。":" This card practice set is empty."));const a=new Map(s.problems.map(e=>[e.id,e])),i=[];for(const e of o){const o=a.has(ol(e.py_id))?ol(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 s.problems)a.has(e.id)&&0===i.length&&!Ur(e)&&i.push(e);s.problems=i;let c=Cr.get(r);c||(c=new Set,Cr.set(r,c));for(const e of s.solved)c.add(e);Dn={card:e,phase:n,slot:r,data:s,idx:Math.min(Math.max(t,1),s.problems.length)-1,answers:[],tries:0},P(`learn-fillpractice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(Vn()?` ⚡ 快速填空 — 第 ${e.number} 张卡`:` ⚡ Quick fill — card ${e.number}`)+chalk.gray(Vn()?"(敲答案 → 自动判分 · 不计分)":" (type the blank → auto-judged · unscored)")),console.log(chalk.gray(Vn()?` ⏱ 每次练习 ${s.duration_minutes} 分钟 · 剩 ${Ze(s.deadline)??"0:00"} · 到时敲 back 再 practice 重开`:` ⏱ ${s.duration_minutes}-minute practice window · ${Ze(s.deadline)??"0:00"} left · when it ends: back, then practice again`)),dl()})(e,l,s)),void fn()}if("submit"===l)return console.log(chalk.yellow(Vn()?" 用法: ":" Usage: ")+chalk.bold.green(Vn()?"submit <题号>":"submit <n>")+chalk.gray(Vn()?" 例如 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)")),fr||console.log(chalk.gray(Vn()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void fn();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const t=e[2];if(!fr)return console.log(chalk.yellow(Vn()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void fn();const n=fr.data.problems,r=parseInt(o,10);if(Yr&&r===Ve)return console.log(chalk.gray(Vn()?" 热身题不判分 — /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(Vn()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(Vn()?" 开始。":".")),void fn();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(Vn()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void fn();const s=n.findIndex(e=>e.id===o)+1,a=t||oe(fr.dir,Hr(s,n[s-1]));let i;try{i=G(a,"utf-8")}catch{return console.log(chalk.red(Vn()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void fn()}const c=Boolean(n[s-1]?.quiz),d=c?null:new W(Ft);d?.start();const g=$r.get(s),u=br.get(s),h=g&&!X(g)?{...g,...u?{samples:u.list}:{},...u&&u.dropped>0?{samplesDropped:u.dropped}:{}}:void 0,p=await ze(Ft,fr.phase,o,i,fr.data.slot>=Xr?fr.data.slot:void 0,h);if(d?.stop(),!p.ok||!p.data)return"no_active_session"===p.code&&fr.data.slot>=Xr?al(fr.data.duration_minutes):"no_active_session"===p.code?(el(fr.phase,fr.data.slot),console.log(chalk.yellow(Vn()?" ⏱ 时间到 — 这一场结束了,判分机已停表。":" ⏱ Time is up — this attempt is over; the judge stopped the clock.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(Vn()?" 重开这一组:全新计时 + 全新模板(旧文件已归档)。只有计时内写的才算数 — 从头再写一遍,这正是练习。":" 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(Vn()?" ↩ back 回卡片":" ↩ back returns to the card"))):(console.log(chalk.red(` ✗ ${p.message||"judging failed"}`)),console.log(chalk.gray(Vn()?" 判分服务异常?敲 memo 一句话告诉我们 — 不打断比赛计时。":" Judge acting up? Type memo — one line reaches us, the clock is unaffected."))),void fn();const y=p.data;let m=!1;if(zr()){const e=y;for(const o of(e.report??[]).slice(0,3))console.log(chalk.gray(` ${Vn()?o:Do(o)}`));e.note&&console.log(chalk.gray(` ${e.note}`)),"string"==typeof y.replay&&y.replay&&(m=Bo(y.replay))}if(m&&"AC"!==y.verdict&&!y.already_ac&&console.log(chalk.gray(" ▸ ")+chalk.bold.green("replay")+chalk.gray(Vn()?" 看你输掉的那一局 —— 判分机把它送回来了(q 退出回放)":" watch the game you lost — the judge sent it back (q quits the player)")),y.already_ac)console.log(chalk.green(Vn()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===y.verdict){if(c?console.log(chalk.bold.green(Vn()?" ✅ 答对了!":" ✅ Correct!")):console.log(Io("AC",{isZh:Vn(),passed:y.passed_tests??y.total_tests??null,total:y.total_tests??null,ms:y.time_ms??null})),fr.data.solved.includes(o)||fr.data.solved.push(o),fr.tried.delete(o),Vr()){let e=Cr.get(fr.data.slot);e||(e=new Set,Cr.set(fr.data.slot,e)),e.add(o);const t=await We({token:Ft,curriculumId:Gt.id,cardNumber:tn.currentCard}),n=t.ok?t.practiceBoard:null;if(n?.mine){const e=n.top[0],o=e&&!e.me?chalk.gray(Vn()?` · 榜首 ${e.name||"Rank 1"} ${e.ac} AC`:` · leader ${e.name||"Rank 1"} at ${e.ac} AC`):chalk.bold.yellow(Vn()?" · 全场第一!":" · phase leader!");console.log(chalk.white(Vn()?` ⚔ Phase ${n.phase} Practice AC: `:` ⚔ Phase ${n.phase} practice AC: `)+chalk.bold.yellow(`${n.mine.ac}`)+chalk.gray(`/${n.problems_total}`)+chalk.gray(Vn()?` · 第 ${n.mine.rank} 名`:` · rank ${n.mine.rank}`)+o)}}}else fr.tried.add(o),c?console.log(chalk.red(Vn()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(Vn()?" — 再选一次。":" — pick again.")):console.log(Io(y.verdict,{isZh:Vn(),passed:y.passed_tests??null,total:y.total_tests??null,failedTest:y.test??null,ms:y.time_ms??null})),In||(In=!0,console.log(chalk.gray(Vn()?" 觉得题面有误或判分不对?敲 memo 一句话 — 不打断比赛计时。":" Statement wrong or judging looks off? Type memo — one line, the clock is unaffected.")));y.late&&console.log(chalk.yellow(Vn()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const f=Ze(y.deadline||""),$=Vr();if(console.log(chalk.white($?Vn()?` 本卡练习: 已过 ${y.ac_count}/${y.n} 题(不计分)`:` Card practice: ${y.ac_count}/${y.n} solved (unscored)`:Vn()?` 本组进度: 已过 ${y.ac_count} 题 · 过 ${y.need} 题过关(共 ${y.n} 题)`:` Group progress: ${y.ac_count} solved · ${y.need} needed to pass (${y.n} problems)`)+(f?chalk.gray(` · ⏱ ${f}`):"")),$&&!y.late&&y.ac_count>=y.n)console.log(chalk.bold.green(Vn()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(Vn()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!y.passed||y.late||$){if(!y.late){const e=n.findIndex(e=>!fr.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Vn()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Dr(n[e])}`))}}else{const e=Math.max(0,y.n-y.ac_count);if(0===e)console.log(chalk.bold.green(Vn()?` 🎉 满分!${y.n}/${y.n} 全部 AC — 这组题你已经彻底拿下。`:` 🎉 Perfect! ${y.n}/${y.n} AC — you have completely cleared this group.`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(Vn()?" 回到上一层(卡片),继续往下学;":" returns to the previous layer (the card) — keep going from there; ")+chalk.bold.green("contest")+chalk.gray(Vn()?" 看本阶段其他赛场。":" lists the other arenas of this phase."));else{console.log(chalk.bold.green(Vn()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")+chalk.yellow(Vn()?` 还剩 ${e} 题 — 全部做完就是满分 ${y.n}/${y.n},别停在这里。`:` ${e} more to go — solve them all for a perfect ${y.n}/${y.n}, don't stop here.`));const o=n.findIndex(e=>!fr.data.solved.includes(e.id));o>=0&&console.log(chalk.gray(Vn()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${o+1}`)+chalk.gray(` ${Dr(n[o])}`)+chalk.gray(Vn()?" · ↩ back 回卡片":" · ↩ back returns to the card"))}await Tr()}return void fn()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>Gt.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Gt.totalCards}. Try: `)+chalk.bold.green("card 1")),void fn();const n=await Pr(t);return n?(console.log(n),void fn()):(tn.currentCard=t,$n=null,bn=null,wn=null,Qo(tn),Nr(),void fn())}if(null!==wn&&["y","yes","n","no"].includes(o)){const e=gr(wn);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Xn;un?.noteCheck(n,r),nt(tn,e.number),lt(tn,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),Qo(tn);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),sr.push(le(Ft,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),wn=null,yr(),e.solution&&e.solution.length>0)return void fn();if(rl())return void fn();if(tn.currentCard<Gt.totalCards){const e=tn.currentCard,o=await Pr(e+1);if(o)return await Ir(e),console.log(o),void fn();tn.currentCard+=1,Qo(tn),await Ir(e)?Er():Nr(),fn()}else vt(Gt,tn),hr(null,!1).then(()=>fn()),fn();return}}if(null!==$n&&["a","b","c","d"].includes(o)){const e=gr($n);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(rt(tn,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),nt(tn,e.number),Qo(tn),gt(e,t,n,tn),sr.push(le(Ft,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),$n=null,n)if(tn.currentCard<Gt.totalCards){const e=await Pr(tn.currentCard+1);if(e)return console.log(e),void fn();tn.currentCard+=1,Qo(tn),Nr()}else vt(Gt,tn),hr(null,!1).then(()=>fn()),fn();else fn();return}}if(null!==bn){if("done"===o){const e=gr(bn);if(e&&"practical"===e.type)return st(tn,e.number),nt(tn,e.number),Qo(tn),ht(e),bn=null,void fn()}if("skip"===o)return nt(tn,bn),Qo(tn),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),bn=null,void fn()}const q=or&&"skip"===o&&null===$n&&null===bn&&null===wn&&null!==tl(gr(tn.currentCard));if("ok"===o||"next"===o||"continue"===o||"n"===o||q){if(q){const e=tn.currentCard;xr.add(e),un?.notePracticeSkipped(),console.log(chalk.gray(Vn()?" ⚔ 本卡练习已跳过(有记录)。":" ⚔ Practice skipped for this card (recorded).")),le(Ft,{card_number:e,event_type:"practice_skipped"}).catch(()=>{})}else if(null===wn&&null===$n&&null===bn&&rl())return void fn();if(null!==$n)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void fn();if(null!==bn)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void fn();if(null!==wn)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void fn();const e=tn.currentCard,o=e<Gt.totalCards?await Pr(e+1):null;return o?(await Ir(e),console.log(o),void fn()):(tn.currentCard+=1,Qo(tn),tn.currentCard>Gt.totalCards?(vt(Gt,tn),hr(null,!1).then(()=>fn())):await Ir(e)?Er():Nr(),void fn())}return null!==wn?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void fn()):null!==$n?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void fn()):null!==bn?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void fn()):("view"===zn?console.log(chalk.gray(Vn()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(Vn()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(Vn()?" 回卡片":" to the card")):"honors"===zn?console.log(chalk.gray(Vn()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(Vn()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(Vn()?" 回卡片":" 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 fn())};cn.on("line",e=>{Ul(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.")),fn()})}),sn||cn.on("close",async()=>{un?.detach(),sr.length>0&&await Promise.race([Promise.allSettled(sr),new Promise(e=>setTimeout(e,5e3))]),dr?cr():process.exit(0)});const zl=$e(Xt,Vn());if(zl){const e=Math.max(40,Math.min(process.stdout.columns||80,96));console.log(),console.log(chalk.bold.cyan(` ╭${"─".repeat(Math.max(26,e-5))}╮`)),console.log(chalk.bold.cyan(" │ 💬 ")+chalk.bold.white(zl)+chalk.bold.cyan(" │")),console.log(chalk.bold.cyan(` ╰${"─".repeat(Math.max(26,e-5))}╯`)),console.log()}try{Nr();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0),(async()=>{for(let e=0;e<20&&!mr;e++)await new Promise(e=>setTimeout(e,250));const e=pr();null!==e&&e>0&&e<=2&&(await yr(!0),fn())})();const o=un?.attach(Ft,Gt.id,ur);"resumed"===o&&(console.log(chalk.yellow(" ⏱ ")+chalk.white(Vn()?`专注进行中 · 还剩 ${un.remainingMin()} 分钟 · 这条轨也算在内 · focus off 提前结束`:`focus running · ${un.remainingMin()} min left · this course counts too · focus off to end early`)),console.log()),fn()}catch(e){if(process.env.ICOA_DEBUG&&console.error(e),zt("Could not render this card — the curriculum may be malformed."),sn){cn.removeAllListeners("line"),gn();for(const e of an)cn.on("line",e);cn.prompt()}else cn.close();cr()}await ir}),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(),l=await ne(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{rearmFocusMode as l}from"../lib/input-dynamics.js";import{FOCUS_MAX as s,FOCUS_MIN as a,FOCUS_STEP as i,getStudyTimer as c,parseFocusMinutes as d}from"../lib/learn-study-timer.js";import{FOCUS_LOG_RE as g,fetchFocusLog as u,renderFocusLog as h}from"../lib/learn-focus-log.js";import{setLearnFooterExtra as p}from"../lib/learn-render.js";import{CHECK_RE as y,runLearnCheck as m}from"../lib/learn-check.js";import{CLASS_RE as f,runLearnClass as $}from"../lib/learn-class.js";import{TEAM_RE as b,askOnReadline as w,runTeamMeeting as k}from"../lib/learn-team.js";import{fetchLearnProfile as v,postCreditsRolled as _,renderLearnProfile as C}from"../lib/learn-profile.js";import{buildCreditLines as A,creditsProgress as x,creditsRoadLines as T,rollCredits as S,storyListLines as j}from"../lib/learn-credits.js";import{logCommand as P}from"../lib/logger.js";import{startEditSampler as I}from"../lib/edit-sampler.js";import{probeVimInsertExpand as E}from"../lib/editor-spawn.js";import{getMainRl as N,setMainRl as M}from"../lib/main-rl.js";import{assetDir as L,lazyJson as q}from"../lib/lazy-assets.js";import{isMicroduckWord as O,runMicroduck as R}from"./microduck.js";import{JudgeWaitLine as W}from"../lib/judge-wait.js";import{ai4ioaiPromptLabel as D,handleAi4ioaiMessage as U,startAi4ioaiChat as Y}from"./ai4ioai.js";import{existsSync as B,mkdirSync as F,readdirSync as z,readFileSync as G,renameSync as Z,statSync as H,writeFileSync as K}from"node:fs";import{emptyDynamics as J,foldEditSession as Q,isEmpty as X,noteRun as V}from"../lib/arena-edit-dynamics.js";import{dirname as ee,join as oe}from"node:path";import{fileURLToPath as te}from"node:url";import{loadCurriculumById as ne,validateEAToken as re,syncProgress as le,postFlowEvent as se,fetchServerProgress as ae,syncCardFeedback as ie,fetchCardFaqs as ce,overlayLanguages as de}from"../lib/learn-curricula.js";import{FlowRunner as ge}from"../lib/learn-flow.js";import{hometaskDetailLines as ue,hometaskLines as he,isTaskCommand as pe}from"../lib/learn-hometask.js";import{detectCaps as ye}from"../lib/render-card.js";import{parseReplyCommand as me,renderReplyLines as fe,repliesForCard as $e,replyPushLine as be,replySignature as we,shortDay as ke,unreadReplies as ve,wrapPlain as _e}from"../lib/learn-replies.js";import{ensureFullTable as Ce,lookupPydoc as Ae,lookupRanked as xe,refetchTableOnMiss as Te,nearKeys as Se,renderIndex as je,renderPydoc as Pe,renderSyntax as Ie,tableSize as Ee}from"../lib/py-syntax.js";import{normalizeTokenBody as Ne}from"../lib/token-format.js";import{fetchMyScores as Me,recallCoach as Le,setNickname as qe,streamLearnTutor as Oe,submitPqs as Re,viewPqsTop as We,viewHonors as De}from"../lib/learn-ai.js";import{contestReset as Ue,contestStart as Ye,contestSubmit as Be,linkByIndex as Fe,linkSuggest as ze,linkToken as Ge,fetchGate as Ze,timeLeft as He,arenaCadence as Ke,arenaSlotAtPos as Je,posForArenaSlot as Qe,quizShape as Xe,fillQuizAnswer as Ve}from"../lib/learn-contest.js";import{WARMUP as eo,WARMUP_ID as oo,WARMUP_N as to,WARMUP_TESTS as no,gradeWarmup as ro,warmupEnabled as lo}from"../lib/warmup.js";import{PY_MAX_CODE_BYTES as so,PY_MAX_FILES as ao,PY_TEMPLATE_EN as io,PY_SPOOL_BATCH as co,PY_TEMPLATE_ZH as go,listScratchFiles as uo,localTimeNote as ho,nextScratchN as po,readPyScratchSpool as yo,scratchCodeSha as mo,scratchDir as fo,scratchFilePath as $o,scratchTitleOf as bo,shrinkPyScratchSpool as wo,spoolPyScratchEvent as ko,startRunTimer as vo,syncPyScratch as _o}from"../lib/py-scratch.js";import{SH_TIMEOUT_MS as Co,destructiveHint as Ao,ensureLabDir as xo,interactiveHint as To,labCardDir as So,labRoot as jo,resolveCd as Po,runShell as Io,shortCwd as Eo,tildePath as No}from"../lib/sh-lab.js";import{verdictLine as Mo}from"../lib/verdict.js";import{printNoPython312 as Lo,probePython as qo}from"../lib/python-setup.js";function Oo(){const e=qo();return e.ok&&e.cmd?{cmd:e.cmd}:null}const Ro=()=>Oo()?.cmd??null;import{homedir as Wo}from"node:os";import{getConfig as Do,saveConfig as Uo}from"../lib/config.js";import{runType as Yo}from"./type.js";import{mobReportLine as Bo,playSavedReplay as Fo,runBattle as zo,runMobLocal as Go,saveJudgeReplay as Zo}from"./battle.js";import{runDuck as Ho}from"./duck.js";import{ARENA_VI_FLAGS as Ko}from"../lib/vi-flags.js";import{isNativeWindows as Jo,isWindowsBuildInWslShell as Qo,whichBinary as Xo}from"../lib/platform.js";import{loadLearnState as Vo,saveLearnState as et,newLearnState as ot,stateFromServerEvents as tt,mergeServerProgress as nt,activateSession as rt,updateStreak as lt,markCardComplete as st,recordMCQ as at,recordCheck as it,markPracticalComplete as ct,addAchievement as dt}from"../lib/learn-state.js";import{renderWelcome as gt,renderKnowledgeCard as ut,renderMCQCard as ht,renderMCQFeedback as pt,renderPracticalCard as yt,renderPracticalSuccess as mt,renderSimDemoCard as ft,renderMilestone as $t,renderArenaTaskCard as bt,renderArenaIntro as wt,learnCheckpointVerb as kt,renderComingSoonCard as vt,renderStatus as _t,renderPhaseComplete as Ct,renderCurriculumComplete as At,setLearnAiEnabled as xt,setLearnFaqs as Tt,setLearnArenaLane as St,setLearnArenaCards as jt,setLearnDuckLane as Pt,setLearnFooterProfile as It,setLearnShellLane as Et,setLearnHometask as Nt,setLearnPracticeChips as Mt,setLearnPracticeCount as Lt,setLearnHonorRanks as qt,setLearnPqsViewCards as Ot,setLearnReplies as Rt,setLearnWidth as Wt,resolveLearnWidth as Dt,learnWidthCap as Ut,learnW as Yt,renderHonorWall as Bt,wrapMixed as Ft}from"../lib/learn-render.js";import{printError as zt}from"../lib/ui.js";const Gt=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","widest"],["wide max","widest"]]);function Zt(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(qo){qo.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async qo=>{qo?.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(),qo="LEARNDEMO01");let Ht=qo.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ht)){const{runSprint:e}=await import("./sprint.js");return void await e()}if(O(qo))return void await R();let Kt=null;const Jt=/^[A-Z0-9]+DEMO01$/i.test(Ht),Qt=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ht);let Xt=!1,Vt=3,en=!1,on=[],tn=null,nn=-1,rn=Promise.resolve([]);if(Jt)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),rn=ce(Ht),Kt=await ne(Ht,Ht,!0);else if(Qt){console.log(),console.log(chalk.gray(" Validating token..."));let e=await re(Ht);if(!e.ok){const o=Ne(Ht);if(o!==Ht){const t=await re(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ht} → ${o}`)),e=t,Ht=o)}}if(!e.ok){if(zt(`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."));else if("network"===e.code&&(e.advice?.length??0)>0){console.log(chalk.yellow(" Your token is fine — this computer could not reach the ICOA server.")),console.log();for(const o of e.advice??[])console.log(chalk.gray(` ${o}`));console.log(),console.log(chalk.gray(" Full check of this network: ")+chalk.cyan("doctor"))}else 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)"));return 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 🐼"):Jt?"":chalk.magenta(" · 🐼 AI tutor"))),Xt=!0===e.aiEnabled,Vt=e.aiBasicPerCard??3,en=!0===e.gated,on=e.replies??[],tn=e.hometask??null,rn=ce(Ht),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Kt=await ne(e.curriculumId||"LEARNDEMO01",Ht,!0),!Kt)return zt(`Could not open a learn curriculum for token '${Ht}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ht}`)+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 ${Ht}`)+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(!Kt){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(zt(`Could not reach the learn server to open ${Ht}.`),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 ${Ht}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(zt(`Unknown learn token: ${Ht}`),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 ln=Vo(),sn=!1,an=!1;try{if(ln&&ln.token===Ht)lt(ln),an=!0;else{const e=rt(Ht);if(e)ln=e,ln.totalCards=Kt.totalCards,lt(ln),an=!0;else{const e=await ae(Ht),o=e?tt(Ht,Kt.id,Kt.totalCards,e):null;o?(ln=o,console.log(chalk.green(" ↩ ")+chalk.white((Do().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()):(ln=ot(Ht,Kt.id,Kt.totalCards),sn=!0)}}if(an){const e=await ae(Ht);if(e){const o=ln.currentCard;nt(ln,Kt.totalCards,e),ln.currentCard>o&&(console.log(chalk.green(" ↩ ")+chalk.white((Do().language||"en").toLowerCase().startsWith("zh")?`已同步手机进度:${ln.cardsCompleted.length} 张卡完成,从第 ${ln.currentCard} 张继续`:`Synced your phone progress: ${ln.cardsCompleted.length} cards done, resuming at card ${ln.currentCard}`)),console.log())}}et(ln),gt(Kt,ln,sn),function(e){if(!e)return;const o=(Do().language||"en").toLowerCase().startsWith("zh"),t="T0"===ye().tier;Zt(he(e,o,Yt(),t),!!e.completedAt)}(tn)}catch{return zt("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 ${Ht}`)+chalk.gray(".")),void console.log()}const cn=N(),dn=null!==cn,gn=dn?cn.listeners("line").slice():[];dn&&cn.removeAllListeners("line");const un=dn?cn:o({input:process.stdin,output:process.stdout,terminal:!0}),hn=dn?un.prompt:null;dn&&(un.prompt=e.prototype.prompt);const pn=()=>{dn&&hn&&(un.prompt=hn)};let yn=null,mn=!1,fn=!1,$n=null,bn=!1;const wn=()=>{un.closed||(un.setPrompt(Kn?chalk.bold.green(`icoa ${D()}> `):Dn?chalk.bold.magenta(Fl()):Wn?chalk.bold.magenta("icoa py> "):Rn?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(qn?"icoa learn ai> ":"icoa learn> ")),un.prompt(),yn?.onPromptIdle())};let kn=null,vn=null,_n=null,Cn=null;const An=new Set,xn=(e,o)=>{const t=e.flow??[];0!==t.length&&(o&&(console.log(chalk.yellow(" 🧭 ")+chalk.white(tr()?"这张卡是互动流程 —— 现在开始。选错不扣分,墙上写着为什么;":"This card is an interactive walk — starting now. Wrong turns cost nothing; the wall says why;")),console.log(chalk.gray(tr()?" 每一步在 icoa learn> 后面敲答案。back 退回卡片 · flow 再走一遍。":" type each answer after icoa learn>. back returns to the card · flow walks it again.")),console.log()),Cn=new ge({steps:t,zh:tr(),cardNumber:e.number,print:e=>console.log(e)}),"done"===Cn.start()&&Tn("done"))},Tn=e=>{if(!Cn)return;const o=Cn.records(),t=Cn.cardNumber;Cn=null;for(const e of o)cr.push(se(Ht,Kt.id,t,e).catch(()=>{}));if("done"!==e)return console.log(chalk.gray(tr()?" ↩ 已退出流程,回到卡片。":" ↩ Left the walk — back on the card.")),void console.log();const n=null!==_n?pr(_n):null;if(n&&"knowledge"===n.type&&n.check){const e=(Do().language||"en").slice(0,2).toLowerCase(),o=n[`_${e}`],t="en"!==e?o?.checkStatement??o?.check?.statement??n.check.statement:n.check.statement;console.log(chalk.gray(tr()?" ✅ 流程走完。":" ✅ Walk complete.")+chalk.cyan(tr()?" 🤔 现在回答卡片的检查题(输 y 或 n):":" 🤔 Now the card check (type y or n):")),console.log(chalk.white(` ${t}`)),console.log(chalk.gray(tr()?" (flow 再走一遍)":" (flow walks it again)"))}else console.log(chalk.gray(tr()?" ✅ 流程走完 — 敲 ok 下一张,或 flow 再走一遍。":" ✅ Walk complete — type ok for the next card, or flow to walk it again."));console.log()};let Sn=null,jn=[],Pn=!1,In=null;const En=/^(quit|exit|q|back|b|menu|home|contest(\s+(\d+|reset))?)$/i;let Nn=null,Mn=!1;const Ln=()=>{In&&clearTimeout(In),In=null,jn=[],Pn=!1,Sn=null,Nn=null};let qn=!1,On=!1,Rn=!1,Wn=!1,Dn=!1,Un=null,Yn="card",Bn=null,Fn=null,zn=null,Gn=!1,Zn=0,Hn=!1,Kn=!1;const Jn=new Map,Qn=()=>{let e=Jn.get(ln.currentCard);return e||(e=[],Jn.set(ln.currentCard,e)),e};let Xn=!1;const Vn=new Set;let er=!1,or=0;const tr=()=>(Do().language||"en").toLowerCase().startsWith("zh");xt(Xt||!Jt,Xt),Wt(Dt(Do())),Ot(Vn);const nr=new Map;qt(nr),Rt(on),Nt(tn);const rr="fill"===Kt.practiceMode,lr=Boolean(Kt.shellLane);Et(lr);const sr=Kt.mobCheckpoints;St("battleai"===Kt.practiceMode||Array.isArray(sr)),jt("battleai"===Kt.practiceMode?[]:(sr??[]).map(e=>Number(e.card)).filter(e=>e>0).map(e=>{const o=Kt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return{card:e,slot:o?Je(e-o.cardRange[0]+1):0}}).filter(e=>e.slot>0)),Pt(Array.isArray(Kt.duckCheckpoints)),It("minimal"===Kt.footerProfile?"minimal":"full"),Mt(e=>{const o=pr(e),t=o?al(o):null;if(!t)return null;const n=Tr.get(nl+e);return t.map((e,o)=>`[${o+1}]${n?.has(sl(e.py_id))||n?.has(e.py_id)?"✅":"⬜"}`).join(" ")});const ar=e=>{const o=pr(e),t=o?al(o):null;if(!t)return null;const n=Tr.get(nl+e);return{solved:t.filter(e=>n?.has(sl(e.py_id))||n?.has(e.py_id)).length,total:t.length}};Lt(ar);const ir=await rn;Tt(ir);const cr=[];let dr=null;const gr=new Promise(e=>{dr=e}),ur=()=>{const e=dr;dr=null,e?.()},hr="1"===process.env.ICOA_LEARN_EMBEDDED,pr=e=>Kt.cards.find(o=>o.number===e);yn=c();const yr={isZh:tr,canInterrupt:()=>!(bn||On||qn||Rn||Wn||Kn||null!==Bn||null!==Sn||null!==zn),lineEmpty:()=>!un.line,clearLine:()=>{try{process.stdout.write("\r")}catch{}},prompt:wn,currentCard:()=>ln.currentCard};p(()=>{const e=[],o=yn?.footerLine();o&&e.push(o);const t=fr();return null!==t&&t>0&&t<=2&&e.push(tr()?`🎁 还差 ${t} 项 · credits 看路线`:`🎁 ${t} to go · credits shows the road`),e.length?e.join("\n "):null});const mr=async(e,o)=>{const t=tr();if(Jt)return void console.log(chalk.gray(t?"故事属于正式 learn token。":" Stories belong to full learn tokens."));const n=await v(Ht,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 j(r,t))console.log(e);return void console.log()}let l=null===e?r.tokens.find(e=>e.curriculum_id===Kt.id):void 0;if(null!==e){const o=Number(e);l=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(!l){console.log(),console.log(chalk.yellow(t?` 没有「${e}」这门课的故事。`:` No story for "${e}".`));for(const e of j(r,t))console.log(e);return void console.log()}if(!o&&!l.credits?.completed){const e=l.credits,o=[];e&&e.checks_total>0&&o.push(t?`自测 ${e.checks_answered}/${e.checks_total}`:`checks ${e.checks_answered}/${e.checks_total}`),l.practice.total>0&&o.push(t?`练习 ${l.practice.ac}/${l.practice.total} AC`:`practice ${l.practice.ac}/${l.practice.total} AC`),l.contests.total>0&&o.push(t?`检查点 ${l.contests.passed}/${l.contests.total} 过线`:`checkpoints ${l.contests.passed}/${l.contests.total} passed`),console.log(chalk.bold.white(t?" 🏁 离谢幕还差:":" 🏁 To the credits: ")+chalk.gray(o.join(" · ")));for(const e of T(Kt,ln,br,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 s=A(l,r,l.curriculum_id===Kt.id?Kt.name:l.curriculum_id,l.curriculum_id===Kt.id?{longestStreak:ln.longestStreak,bookmarks:ln.bookmarks?.length??0}:{},t,Yt(),"T0"===ye().tier);console.log(),console.log(chalk.gray(t?" (回车跳到结尾)":" (Enter skips to the end)")),mn=!0,fn=!1;try{await S(s,()=>fn)}finally{mn=!1}if(l.curriculum_id===Kt.id&&!l.credits?.completed){for(const e of T(Kt,ln,br,t))console.log(e);console.log()}l.credits?.completed&&!l.credits.credits_rolled_at&&_(l.token,l.curriculum_id),console.log(chalk.gray(t?" ↩ 回车继续 · story 选另一门 · me 看档案":" ↩ Enter to continue · story to pick another · me for your profile")),console.log()},fr=()=>{if(!ln||ln.creditsShownAt||Jt||!br)return null;const e=x(Kt,ln,br);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])},$r=async(e=!1)=>{if(!ln||ln.creditsShownAt||Jt)return;const o=x(Kt,ln,br);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(br&&t>0&&t<=2&&(e||ln.creditsTeasedLeft!==t)){ln.creditsTeasedLeft=t,et(ln);const e=tr(),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 T(Kt,ln,br,e))console.log(o);console.log()}return}ln.creditsShownAt=(new Date).toISOString(),et(ln),await mr(null,!1),wn()};let br=null,wr=null;const kr=new Map,vr=new Map;let _r=null;const Cr=(e,o)=>_r?.[`${Kt.id}:${e}:${o}`]??null;q("contest-cells.json").then(e=>{_r=e?.map??null;for(const[e,o]of Object.entries(_r??{}))e.startsWith(`${Kt.id}:`)&&q(o)});const Ar=(e,o,t)=>{const n=Cr(e,o);if(!n)return null;const r=oe(t,"explore.ipynb");if(!B(r)){const e=oe(L(),n);if(!B(e))return null;try{K(r,G(e))}catch{return null}}return r},xr=!Ht.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ht),Tr=new Map,Sr=new Map,jr=new Set,Pr=async()=>{if(!xr)return;const e=await Ze(Ht);if(e.ok&&e.data){br=e.data;for(const o of e.data.practice??[]){let e=Tr.get(o.slot);e||(e=new Set,Tr.set(o.slot,e));for(const t of o.solved)e.add(t)}$r()}},Ir=e=>{const o=Kt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Er=e=>{if(!en||!br)return null;const o=Ir(e);if(o<=br.unlocked_through_phase)return null;const t=br.phases.find(e=>e.phase===br.unlocked_through_phase),n=[chalk.yellow(tr()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${br.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${br.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(tr()?` ⚔ 练习赛 ${br.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${br.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(tr()?` ⚖ 判分赛: 最好 ${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(tr()?"、":", "),r=e.length>8?tr()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:tr()?" 张":"";n.push(chalk.gray(tr()?` ✓ 逐卡自测: ${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(tr()?` ⭐ 提问研究: ${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")},Nr=async e=>en?null===Er(e)?null:(await Pr(),Er(e)):null;xr&&await Pr();const Mr=async e=>{const o=Kt.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=Kt.modules.find(e=>e.number===o.number+1);let n;if(Xt){const e=await Me({token:Ht,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}xr&&await Pr();const r=br?.phases.find(e=>e.phase===o.number);return Ct(Kt,ln,o,t,n,r),!0},Lr=()=>{er=!0,console.log(chalk.gray(tr()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},qr=()=>{zn=null;const e=pr(ln.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();yn?.noteCardShown(e.number,ln.cardsCompleted.includes(e.number));const o=ve($e(on,e.number));if(o.length>0){const t=Math.max(40,Math.min(process.stdout.columns||80,96)),n="─".repeat(Math.max(24,t-4));console.log(),console.log(chalk.bold.cyan(` 💬 ──${n}`)),console.log(chalk.bold.cyan(" 💬 ")+chalk.bold.white(tr()?`你有 ${o.length} 条回复(第 ${e.number} 张卡)`:`You have ${o.length} ${o.length>1?"replies":"reply"} (Card ${e.number})`)),console.log(chalk.bold.cyan(` 💬 ──${n}`));for(const e of o){console.log(chalk.gray(` ${tr()?"你写的":"You wrote"}: ${(e.myText??"").slice(0,70)}${(e.myText?.length??0)>70?"…":""}`)),console.log(chalk.yellow(` 🐼 ${tr()?"回复":"Reply"}(${ke(e.repliedAt??"")}):`));for(const o of _e(e.replyText??"",t-4," "))console.log(chalk.bold.white(o));const o=we(e.repliedAt,e.repliedBy);o&&console.log(chalk.gray(` ${o}`)),console.log()}console.log(chalk.cyan(` 💬 ${"─".repeat(Math.max(24,t-6))}`)),console.log(chalk.gray(" "+(tr()?"看完继续:next 去下一张卡;e 可再报告一条。":"Continue: type next, or press e to report again."))),console.log(),on=on.map(e=>o.some(o=>o.id===e.id)?{...e,seen:!0}:e)}switch(e.type){case"knowledge":{const o=rr&&Boolean(ln.checkResults?.[String(e.number)])&&e.check?{...e,check:void 0}:e;ut(o,Kt),o.check?(_n=e.number,or=Date.now()):(st(ln,e.number),et(ln));break}case"mcq":ht(e,Kt),kn=e.number;break;case"practical":yt(e,Kt),vn=e.number;break;case"sim_demo":ft(e,Kt),st(ln,e.number),et(ln);break;case"milestone":$t(e,Kt),dt(ln,e.badge),st(ln,e.number),et(ln);break;case"arena_task":bt(e,Kt),st(ln,e.number),et(ln);break;case"coming_soon":vt(e,Kt),st(ln,e.number),et(ln)}Or(e.number),dl(e),"knowledge"===e.type&&e.flow&&e.flow.length>0&&(An.has(e.number)?(console.log(chalk.yellow(" 🧭 ")+chalk.gray(tr()?"敲 flow 再走一遍这张卡的互动流程。":"type flow to walk this card again.")),console.log()):(An.add(e.number),console.log(),xn(e,!0)))},Or=e=>{if(!xr)return;const o=Kt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1,n=Je(t);if(0===n)return;const r=Ke(o.cardRange[1]-o.cardRange[0]+1),l=br?.phases.find(e=>e.phase===o.number),s=l?.contest?.slots?.find(e=>e.slot===n),a=()=>{ln.arenaIntroShownAt||(wt(o.cardRange[1]-o.cardRange[0]+1),ln.arenaIntroShownAt=(new Date).toISOString(),et(ln))};if(!br){const e="═".repeat(Yt()),t=chalk.bold.yellow(" ║ "),r=kt();return a(),console.log(chalk.bold.yellow(` ╔${e}`)),console.log(t+chalk.bold.white("⚔ "+(tr()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(tr()?" 成绩暂时取不到":" scoreline unavailable")),console.log(t+chalk.white(tr()?"这张卡下面有一场判分赛 — 服务器这会儿没答上来,所以显示不了你的成绩。":"A judged arena lives under this card — the server didn't answer in time, so your scoreline is missing.")),console.log(t+chalk.gray("▸ ")+chalk.bold.green(r??`contest ${n}`)+chalk.gray(tr()?" 照常可以开赛(开赛是另一次请求) · ":" still opens it (starting is a separate call) · ")+chalk.gray("▸ ")+chalk.bold.green("ok")+chalk.gray(tr()?" 继续学习":" keep going")),console.log(chalk.bold.yellow(` ╚${e}`)),void console.log()}if(!s){const e=o.cardRange;if(e[1]-e[0]+1>12)return;a();const t="═".repeat(Yt()),l=chalk.bold.yellow(" ║ ");return console.log(chalk.bold.yellow(` ╔${t}`)),console.log(l+chalk.bold.white("⚔ "+(tr()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(tr()?" 制作中":" in production")),console.log(l+chalk.white(tr()?"这里以后有一场判分赛 — 很快更新。":"A judged arena lands here — coming soon.")),console.log(l+chalk.gray(tr()?r.n>1?`每 4 张卡一场:卡 ${r.cards},本阶段共 ${r.n} 场,全过解锁下一阶段。${rr?"(本轨无 research)":""}`:`本阶段一场:卡 ${r.cards},过了解锁下一阶段。${rr?"(本轨无 research)":""}`:r.n>1?`One every 4 cards — ${r.cards}, ${["","one","two","three"][r.n]??r.n} this phase; all ${["","one","two","three"][r.n]??r.n} unlock the next.${rr?" (no research on this track)":""}`:`One this phase — card ${r.cards}; passing it unlocks the next.${rr?" (no research on this track)":""}`)),console.log(l+chalk.gray(tr()?"▸ 现在什么都不用做 — 敲 ":"▸ Nothing to do yet — type ")+chalk.bold.green("next")+chalk.gray(tr()?" 继续读卡。":" and keep reading.")),console.log(chalk.bold.yellow(` ╚${t}`)),void console.log()}a();const i=(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?tr()?` · 用时 ${r}`:` · in ${r}`:"")+(l?` · ${l}`:"")},c=s.perfect_runs??[],d=!!s.best&&(s.best.ac??0)>0,g=chalk.bold.yellow(" ║ "),u="═".repeat(Yt());if(console.log(chalk.bold.yellow(` ╔${u}`)),console.log(g+chalk.bold.white(`⚔ ${tr()?(()=>{const t=(sr??[]).find(o=>Number(o.card)===e)?.title;return t?`检查点 · 卡 ${e} · ${t}`:`练习赛 ${o.number}-${n}`})():s.title||`PY Arena ${o.number}-${n}`}`)+(s.passed?chalk.bold.green(tr()?" ✅ 已通过":" ✅ passed"):"")),!s.passed){if(tr()?console.log(g+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(g+chalk.white("You learned the cards — now prove it.")),console.log(g+chalk.white("The clock starts the moment you type the command."))),console.log(g+chalk.gray(tr()?`${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?tr()?`(${e})`:` (${e})`:"";console.log(g+chalk.cyan(tr()?`🔗 你另一个 token${o}已做过这组的 ${s.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens${o} solved ${s.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(tr()?" 带过来(现在不做也行)":" to carry them over (or skip)"))}1!==o.number||rr||console.log(g+chalk.gray(tr()?"✍ 第一次用 vi?/edit 后:i 输入 · Esc 退出 · :wq 存盘退出":"✍ New to vi? After /edit: i = type · Esc · :wq = save & quit"))}if(c.length>0)for(const e of c)console.log(g+chalk.bold.yellow(i(tr()?"满分":"Perfect",s.n,e.ms,e.ts)));else d&&console.log(g+chalk.yellow(i(tr()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));3===n&&l?.leader&&console.log(g+chalk.white(tr()?`🏅 本 phase 研究总分榜首 ${l.leader.name||"Rank 1"} ${l.leader.total}/${l.leader.max_total}`:`🏅 Phase research leader: ${l.leader.name||"Rank 1"} at ${l.leader.total}/${l.leader.max_total}`)+chalk.gray((tr()," — "))+chalk.bold.green("/honors")+chalk.gray(tr()?" 看你的位置":" shows where you stand"));const h=kt();console.log(g+chalk.gray("▸ ")+chalk.bold.green(h??`contest ${n}`)+(h?chalk.gray(tr()?` 进竞技场(${"battle"===h?"play":"run"} 试跑 → submit 判分) · `:` enter the arena (${"battle"===h?"play":"run"} → submit) · `):s.passed?chalk.gray(tr()?" 再战刷成绩 · ":" race it again · "):chalk.gray(tr()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(tr()?" 继续学习":" keep going"):chalk.gray(tr()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),!h&&(c.length>0||d)&&console.log(g+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(tr()?" 日后回来整阶段重做 · 全新计时+模板(旧文件自动归档)":" come back later and redo the whole phase · fresh clock + templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${u}`)),console.log()},Rr=()=>{Ht.endsWith("DEMO01")?console.log(chalk.yellow(tr()?" 🐼 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(tr()?" /submit 评分、荣誉榜与 /recall 是 🐼 AI 高级 token 的功能。":" Prompt grading (/submit), the honors board and /recall are premium 🐼 AI-token features.")),console.log(chalk.gray(tr()?` 你的 token 可以用 /ai 向熊猫导师提问(每卡每天 ${Vt} 问);要开通高级功能找领队 / 协调人。`:` Your token can still ask the tutor with /ai (${Vt} questions per card per day); ask your leader / coordinator for a premium token.`))),console.log()},Wr=async(e,o)=>{if(Jt)return void Rr();yn?.noteAi(Xt&&"deep"===o),On=!0;const t=tr()?"🐼 熊猫导师思考中…":"🐼 Panda tutor is thinking…",n=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];let r=null;const l=()=>{r&&(clearInterval(r),r=null,process.stdout.write("\r"))},s=()=>tr()?` (本卡今天的 ${Vt} 个问题已用完 — 24 小时后再问,或先去下一张卡)`:` (this card's ${Vt} questions for today are used up — ask again in 24 h, or move on to another card)`;try{console.log(),(()=>{if(!process.stdout.isTTY)return void console.log(chalk.gray(` ${t}`));let e=0;const o=()=>{process.stdout.write(`\r ${chalk.magenta(n[e++%n.length])} ${chalk.gray(t)}`)};o(),r=setInterval(o,80)})();let a=!1;const i=await Oe({token:Ht,cardNumber:ln.currentCard,question:e,mode:o,history:Qn().slice(-8),lang:tr()?"zh":"en"},e=>{"content"===e.kind&&(a||(l(),process.stdout.write(" "),a=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});l(),a&&console.log(),i.ok?i.offtopic?(console.log(),console.log(chalk.yellow(Xt?tr()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)":tr()?" (被判定与本卡主题无关 — 不会回答,也不计入本卡的次数)":" (judged unrelated to this card — not answered, and it does not count toward this card's questions)"))):(Qn().push({role:"user",content:e},{role:"assistant",content:i.answer}),null!=i.spent&&null!=i.cap&&i.spent/i.cap>.8&&console.log(chalk.gray(` (${tr()?"AI 额度":"AI budget"}: ${Math.round(i.spent/1e3)}k / ${Math.round(i.cap/1e3)}k tokens)`)),"basic"===i.tier&&"number"==typeof i.cardLeft&&(1===i.cardLeft?console.log(chalk.yellow(tr()?" (本卡今天还可以问最后 1 个问题)":" (this card: 1 question left today)")):0===i.cardLeft&&console.log(chalk.yellow(s())))):(console.log(),"card_daily_limit"===i.code?console.log(chalk.yellow(s())):console.log(chalk.yellow(` ${i.message||(tr()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==_n&&console.log(chalk.gray(tr()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{l(),On=!1}},Dr=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ur=async()=>{Rn&&wr?wl?vl(wl):fl():zn?await Yr():qr()},Yr=async()=>{On=!0;try{console.log();const e=await De({token:Ht,curriculumId:Kt.id,cardNumber:ln.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(tr()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(xr&&(await Pr(),(e=>{const o=Kt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const[t,n]=o.cardRange,r=ln.checkResults||{};let l=0,s=0,a=0;for(let e=t;e<=n;e++){const o=pr(e);null!=o?.check&&a++;const t=r[String(e)];t&&(l++,t.correct&&s++)}console.log(chalk.bold.white(tr()?` 🧭 Phase ${o.number} 进度 — ${o.name}(卡 ${t}-${n})`:` 🧭 Phase ${o.number} progress — ${o.name} (cards ${t}-${n})`)),console.log(chalk.gray(tr()?" 理解检查: ":" comprehension: ")+chalk.white(`${s}/${l}`)+chalk.gray(tr()?` 答对 · ${a-l} 张未作答`:` correct · ${a-l} unanswered`));const i=br?.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(tr()?`未开始 · ${e.n} 题 · 过 ${e.need} 题`:`not started · ${e.n} problems · AC ${e.need}`):chalk.yellow(tr()?`最好 ${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(` ⚔ ${tr()?"练习赛":"arena"} ${o.number}-${e.slot}: `)+t)}const c=[];let d=0,g=0,u=0,h=0;for(let e=t;e<=n;e++){const o=ar(e);o&&(g++,u+=o.solved,h+=o.total,o.solved>=o.total&&d++,c.push((o.solved>=o.total?chalk.green:o.solved>0?chalk.yellow:chalk.gray)(`${e}:${o.solved}/${o.total}`)))}if(g>0){console.log(chalk.gray(tr()?" 卡片练习: ":" practice: ")+chalk.white(`${d}/${g}`)+chalk.gray(tr()?` 卡全完成 · ${u}/${h} 题 AC`:` cards complete · ${u}/${h} problems AC`));const e=Math.max(40,(process.stdout.columns||80)-8);let o="",t=0;for(const n of c){const r=n.replace(/\x1b\[[0-9;]*m/g,"");t+r.length+2>e&&o&&(console.log(" "+o),o="",t=0),o+=(o?chalk.gray(" · "):"")+n,t+=r.length+3}o&&console.log(" "+o),console.log(chalk.gray(tr()?" 卡号:已过/共 — 绿 全完成 · 黄 做了一部分 · 灰 未碰":" card:solved/total — green done · yellow partial · gray untouched"))}console.log()})(ln.currentCard)),console.log(chalk.bold.white(tr()?` 🏆 本卡实时 Top-3 — 第 ${ln.currentCard} 张`:` 🏆 Live top-3 — card ${ln.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(tr()?" (你)":" (you)"):""))}else console.log(chalk.gray(tr()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));if(e.mine?(nr.set(ln.currentCard,e.mine.rank),console.log(chalk.white(tr()?" 你: ":" You: ")+chalk.bold.yellow(tr()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(tr()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Xt&&console.log(chalk.gray(tr()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Bt({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),e.phaseBoard){const o=e.phaseBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(tr()?` 🏅 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(tr()?" (还没有人有研究总分 — 第一个 /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(tr()?`(${e.cards}/${o.cards_in_phase} 卡)`:` (${e.cards}/${o.cards_in_phase} cards)`)+(e.me?chalk.bold.magenta(tr()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(tr()?` 总分 ${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(tr()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.total}`)+chalk.gray(tr()?`(${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&&Xt&&console.log(chalk.gray(tr()?" 你: 还未计入 — /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(tr()?` ⚔ 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(tr()?" (还没有人 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(tr()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(tr()?` 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(tr()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.ac} AC`)+chalk.gray(tr()?` · 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` · rank ${o.mine.rank} of ${o.mine.entrants}`)):o.mine||console.log(chalk.gray(tr()?" 你: 还未计入 — 在有 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(tr()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(tr()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(tr()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),zn="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(tr()?" 返回卡片":" returns to the card")),console.log()}finally{On=!1}},Br=()=>(Do().language||"en").slice(0,2).toLowerCase(),Fr=e=>{const o=e[`title_${Br()}`];return"string"==typeof o&&o||e.title},zr=e=>{const o=e[`statement_${Br()}`];return"string"==typeof o&&o||e.statement},Gr=e=>"mob-match"===e?.kind,Zr=()=>!!wr&&wr.data.problems.some(e=>Gr(e)),Hr=lo(Kt.id);let Kr=!1;const Jr=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of Ft(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Qr={cpp:"cpp",java:"java",go:"go"},Xr=e=>e?.lang&&Qr[e.lang]?e.lang:"python",Vr=(e,o)=>{const t=Xr(o);return`sol-${e}.${"python"===t?"py":Qr[t]}`},el=(e,o)=>{const t=[...Hr?[{p:eo,n:to}]:[],...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:l})=>{const s=Hr&&l===to,a=s?`══ ${t.title} ══`:`══ ${e.title||"PY Arena"} · ${t.title} ══`;for(const e of["py",...Object.values(Qr)]){const s=oe(o,`sol-${l}.${e}`);if(!B(s))continue;const i=G(s,"utf-8").split("\n",1)[0]??"",c=/^(?:#|\/\/) (══ .+ ══)\s*$/.exec(i);if(c&&c[1]!==a)try{Z(s,`${s}.archived-${n}`),r++;const e=oe(o,`sample-${l}.txt`);B(e)&&!(t.samples??[])[0]&&Z(e,`${e}.archived-${n}`)}catch{}}const i=(t.samples??[])[0];null!=i?.in&&K(oe(o,`sample-${l}.txt`),i.in.endsWith("\n")?i.in:`${i.in}\n`);const c=oe(o,Vr(l,t));if(B(c))return;const d=[s?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Jr(t.statement??"",72)];if(t.statement_zh&&d.push("#",`# Other language: type "lang zh" in icoa, then /read ${l} for the Chinese statement.`),t.statement_th&&d.push("#",`# Other language: type "lang th" in icoa, then /read ${l} for the Thai statement.`),null!=i?.in&&null!=i.out){d.push("#",`# Sample input (also in sample-${l}.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","#"),s||Gr(t)||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 Ft(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 ${l} = free run · /submit ${l} = judge`,"",'data = """',...g[1].trim().split("\n"),'""".strip()',"",""):s?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(???)",""):Gr(t)?d.push(`# In icoa: /run ${l} = play one match here (the replay opens) · /submit ${l} = judge`,""):t.starter?d.push("#",`# In icoa: /run ${l} = run it (shows your ms) · /submit ${l} = judge`,""):d.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${l} = sample self-check · /debug ${l} = free-input run · /submit ${l} = judge`,"","");const u="python"===Xr(t)?d:d.map(e=>e.startsWith("#")?`//${e.slice(1)}`:e),h=Gr(t)&&tr()&&t.starter_zh?t.starter_zh:t.starter;h&&!s&&u.push(...h.replace(/\s+$/,"").split("\n"),""),K(c,u.join("\n"))}),r>0&&console.log(chalk.gray(tr()?` 📦 本组题目已更换 — ${r} 个旧题答题文件已归档为 *.archived-${n},新题文件已就位`:` 📦 This group's problems changed — ${r} old solution file(s) archived as *.archived-${n}, fresh files written`))},ol=e=>{console.log(),console.log(chalk.bold.green(tr()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(tr()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},tl=e=>e.id===oo?Kr?"✅":"⬜":wr.data.solved.includes(e.id)?"✅":wr.data.carried?.includes(e.id)?"✅↗":wr.tried.has(e.id)?"❌":"⬜",nl=100,rl=()=>!!wr&&wr.data.slot>=nl,ll=(e,o)=>{const t=oe(process.cwd(),"icoa-contest",`${Kt.id}-phase${e}-g${o}`);if(!B(t))return;const n=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{Z(t,`${t}-archived-${n}`),console.log(chalk.gray(tr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${n}`))}catch{console.log(chalk.yellow(tr()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (restart still fine): ${t}`))}},sl=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,al=e=>{const o=e?.practice;if(!o||!Array.isArray(o.problems)||0===o.problems.length)return null;const t=o.problems.filter(e=>il(e));return[...o.problems.filter(e=>e.is_signature&&!il(e)),...o.problems.filter(e=>!e.is_signature&&!il(e)).sort((e,o)=>(e.difficulty??0)-(o.difficulty??0)||(e.order??0)-(o.order??0)),...t]},il=e=>"mob-match"===e.kind,cl=()=>{if(!rr)return!1;const e=pr(ln.currentCard),o=e?al(e):null;if(!e||!o||jr.has(e.number))return!1;const t=nl+e.number,n=Tr.get(t),r=Sr.get(t),l=o.map((e,o)=>{return t=e.py_id,Boolean(n?.has(sl(t))||n?.has(t)||r?.has(sl(t))||r?.has(t))?0:o+1;var t}).filter(e=>e>0);return 0!==l.length&&(console.log(chalk.yellow(tr()?` ⚔ 这张卡还有 ${l.length} 道练习没做 —— 敲 `:` ⚔ ${l.length} practice problem${l.length>1?"s":""} on this card not tried yet — type `)+chalk.bold.green(`practice ${l[0]}`)+chalk.yellow(tr()?" 开始,或 ":" to start, or ")+chalk.bold.yellow("skip")+chalk.yellow(tr()?" 跳过本卡练习。":" to skip this card's practice.")),!0)},dl=e=>{const o=al(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=Tr.get(nl+e.number);console.log(chalk.bold.yellow(tr()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(tr()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(sl(e.py_id))||n?.has(e.py_id)?"✅":"⬜",r=e.is_signature?"🎯":e.is_hardest?"🔥":" ",l="·".repeat(Math.min(5,Math.max(1,Math.round(e.difficulty??1))));il(e)?console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ⚔ ${chalk.bold.white(tr()?"对局":"battle")}`+chalk.gray(tr()?` — 改一行 · 打一局 · 看回放 · 判分 (敲 ${o+1})`:` — change one line · play · replay · judge (type ${o+1})`)):console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ${r} ${chalk.white(l.padEnd(5))}`)}),console.log(chalk.gray(" ▸ ")+chalk.bold.green("practice 1")+chalk.gray(tr()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},gl=e=>e.split("\n").filter(e=>!e.trim().startsWith("#")).join("\n").split("____").length-1,ul=e=>{console.log(chalk.yellow(tr()?` ⏱ 每次练习 ${e} 分钟,这次的时间到了。`:` ⏱ Each practice window is ${e} minutes — this one has run out.`)),console.log(chalk.gray(tr()?" 敲 ":" Type ")+chalk.bold.green("back")+chalk.gray(tr()?" 回卡片,再敲 ":" for the card, then ")+chalk.bold.green("practice 1")+chalk.gray(tr()?" 重新开始(重新计时)。":" to restart with a fresh clock."))},hl=()=>Bn?Bn.data.problems[Bn.idx]??null:null,pl=()=>{const e=hl();if(!Bn||!e)return;const o=gl(e.starter??""),t=Bn.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(tr()?` 空${t}/${o}`:` blank ${t}/${o}`)+chalk.gray(" · ")+chalk.white(n)),console.log(chalk.gray(tr()?" ▸ 敲答案后回车(back 回卡片)":" ▸ type the answer, press Enter (back = card)"))},yl=()=>{const e=hl();if(!Bn||!e)return;const o=Fr(e);console.log(),console.log(chalk.bold.yellow(` ⚡ ${tr()?"练习":"Practice"} ${Bn.idx+1}/${Bn.data.problems.length} · ${o}`));const t=(zr(e)??"").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(),pl()},ml=()=>{if(Bn){if(Bn.idx+1<Bn.data.problems.length)return Bn.idx+=1,Bn.answers=[],Bn.tries=0,void yl();console.log(chalk.bold.green(tr()?" 🎉 本卡练习全部完成!":" 🎉 Card practice complete!")+chalk.gray(tr()?" ok 进下一张卡。":" ok moves on to the next card.")),Bn=null,Fn=null,qr()}},fl=()=>{const e=wr.data,o=He(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 l=e.slot>=nl?e.slot-nl:null,s=e.problems.find(e=>Gr(e)),a=tr()&&s?.title_zh?`检查点 · 卡 ${s.card} · ${s.title_zh}`:e.title||"PY Arena";if(console.log(chalk.bold.yellow(` ⚔ ${a}`)+chalk.gray(null!=l?tr()?` · 第 ${l} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${l} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:tr()?` · 第 ${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(tr()?" ⏱ 已超时 — 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(tr()?`(共 ${e.n} 题)`:` (of ${e.n})`)),null==l&&n>=e.need){const o=Math.max(0,e.n-n);console.log(0===o?chalk.bold.green(tr()?` 🎉 满分 ${e.n}/${e.n} — 本组全部拿下!`:` 🎉 Perfect ${e.n}/${e.n} — every problem cleared!`)+chalk.gray(tr()?" ↩ back 回卡片":" ↩ back returns to the card"):chalk.green(tr()?" 🏁 已过关":" 🏁 passed")+chalk.yellow(tr()?` · 还剩 ${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(tr()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" 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?tr()?`(${o})`:` (${o})`:"";console.log(chalk.cyan(tr()?` 🔗 你另一个 token${t}已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens${t} solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(tr()?" 带过来,不必重做":" to carry them over instead of redoing them"))}const i=Date.parse(e.deadline)-Date.now();if(o?e.resumed&&i<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(tr()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(tr()?"不够就 ":"Short on time? ")+chalk.bold.green("contest restart")+chalk.gray(tr()?" 满血重开本组。":" restarts this group fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(tr()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),Hr&&(console.log(chalk.gray(" 0 ")+tl(eo)+chalk.gray(` ${Fr(eo)}`)+chalk.gray(tr()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+tl(e)+(e.gpu?chalk.magenta(" ⚡"):"")+chalk.white(` ${Fr(e)}`))}),e.problems.some(e=>e.gpu)){const o=e.gpu_state?.state??(e.gpu_window?"on":"off");console.log(),"on"===o?console.log(chalk.bold.green(tr()?" ⚡ GPU 开 ✅":" ⚡ GPU on ✅")+chalk.gray(tr()?" — /submit 一道 ⚡ 题,就在真 GPU 上跑":" — /submit a ⚡ rung and it runs on a real GPU right now")):"booting"===o?console.log(chalk.bold.yellow(tr()?" ⚡ GPU 开机中…":" ⚡ GPU booting…")+chalk.gray(tr()?" — 约 3–5 分钟,稍后重新 /submit":" — takes ~3–5 min; retry /submit shortly")):console.log(chalk.bold.gray(tr()?" ⚡ GPU 关":" ⚡ GPU off")+chalk.gray(tr()?" — 直接 /submit 一道 ⚡ 题会自动开机(约 3–5 分钟),之后重新 /submit":" — /submit a ⚡ rung to auto-boot the GPU (~3–5 min), then /submit again"))}Cr(wr.phase,e.slot)&&(console.log(),console.log(chalk.gray(" ✍ ")+chalk.bold.green("cells")+chalk.gray(tr()?" 在 notebook 里探索本场数据(引导走查 · 真图) — 不判分,判分仍走 /submit":" explore this lab in a notebook (guided walkthrough · real figures) — ungraded; judging stays /submit"))),console.log(),$l()},$l=()=>{console.log(chalk.gray(Zr()?tr()?" /read <n> 读目标 · /edit <n> 改 bot(vi) · /run <n> 本机打一局 · /submit <n> 判分(10 局)":" /read <n> goal · /edit <n> bot (vi) · /run <n> play a match here · /submit <n> judge (10 games)":tr()?" /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(tr()?"/syntax <词>":"/syntax <word>")+chalk.gray(tr()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(tr()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(tr()?" 返回课程":" returns to the lesson")),console.log(chalk.gray(tr()?" memo 报告题面/判分问题 — 不打断比赛计时":" memo reports a statement/judging problem — the clock is unaffected")),console.log(chalk.gray(" ")+chalk.bold.green("contest restart")+chalk.gray(tr()?" 超时/坏场时重开本组(全新计时+模板) · ":" time up or broken attempt → this group again (fresh clock + templates) · ")+chalk.bold.green("contest reset")+chalk.gray(tr()?" 日后回来整阶段重做":" come back later and redo the whole phase")),console.log()},bl=e=>{const o=parseInt(e,10),t=wr.data.problems;if(o===to&&Hr)return{p:eo,n:to};const n=Hr?to:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(tr()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),Hr&&console.log(chalk.gray(tr()?" 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 wl=null,kl=!1;const vl=e=>{const o=bl(e);if(!o)return;const{p:t,n:n}=o;wl=String(n),console.log(),console.log(chalk.bold.white(` ${tl(t)} ${Fr(t)}`)),console.log();for(const e of zr(t).split("\n"))if(e.trim())for(const o of Ft(e,Yt()+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(tr()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(tr()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(Gr(t)){const e=Array.isArray(t.crit)?t.crit:[],o=Number(e[2]??10),r="mined"===e[0]?tr()?`采矿 ≥ ${e[1]}`:`mine ≥ ${e[1]} opal`:"winrate"===e[0]?tr()?`${o} 局赢 ≥ ${Math.round(100*Number(e[1]))}%`:`win ≥ ${Math.round(100*Number(e[1]))}% of ${o} games`:"";console.log(),console.log(chalk.gray(tr()?" 对手 ":" vs ")+chalk.white(String(t.opp??"?"))+chalk.gray(tr()?" · 地图 ":" · map ")+chalk.white(String(t.map??"?"))+chalk.gray(tr()?" · 回合 ":" · turns ")+chalk.white(String(t.turns??"?"))+(r?chalk.gray(tr()?" · 过线 ":" · pass: ")+chalk.bold.white(r):""));const l=tr()&&t.hint_zh||t.hint;if(l){console.log();let e=!0;for(const o of l.split("\n"))for(const t of Ft(o,Yt()-2))console.log(e?chalk.yellow(" 🧭 ")+chalk.white(t):chalk.white(` ${t}`)),e=!1}console.log();let s=!1;try{s=Sl(G(oe(wr.dir,Vr(n,t)),"utf8")).length>0}catch{s=!1}console.log(chalk.gray(" ▸ ")+chalk.bold.green(s?"set <KNOB> <value>":`/edit ${n}`)+chalk.gray(tr()?" 改一行":" change one line")+chalk.gray(" → ")+chalk.bold.green(`/run ${n}`)+chalk.gray(tr()?" 本机打一局(开回放)":" play one match here (replay opens)")+chalk.gray(" → ")+chalk.bold.green(`/submit ${n}`)+chalk.gray(tr()?" 判分":" judge")),s&&console.log(chalk.gray(tr()?" 旋钮列表敲 ":" bare ")+chalk.bold.green("set")+chalk.gray(tr()?" · 想直接看文件用 ":" lists the knobs · the file itself is ")+chalk.bold.green(`/edit ${n}`))}else 0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(tr()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)")));if(t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(tr()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=tr()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of Ft(o,Yt()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(tr()?"数据就在上方 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(),Hr&&n===to)return console.log(chalk.white(tr()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(tr()?"第 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(tr()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(tr()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((tr()," ↩ "))+chalk.bold.green("back")+chalk.gray(tr()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(tr()?" 直接看正式题目":" skips straight to the real problems")),void console.log();if(Gr(t));else if(t.quiz){const e=Xe(t);let o;if("letter"===e.kind)o=tr()?"输入字母 A–E 回车":"type a letter A–E, press Enter";else if("choose"===e.kind){const t=e.options.join(" / ");o=tr()?`输入其中一个词回车:${t}`:`type one of ${t}, press Enter`}else o=tr()?"输入 answer 你的答案 回车":"type answer <your answer>, press Enter";console.log(chalk.gray(" ▸ ")+chalk.bold.green(o)+chalk.gray(tr()?" 即提交这一题 · 也可以 ":" to submit this one · or ")+chalk.bold.green(`/edit ${n}`)+chalk.gray(tr()?" 在 vi 里填":" to fill it in vi")),"value"===e.kind&&console.log(chalk.gray(tr()?" 例如 ":" e.g. ")+chalk.white("answer 1200")+chalk.gray(tr()?" · 只填空里的那个值,不用写整句":" · just the value that fills the blank, not the whole sentence"))}else t.gpu?(console.log(chalk.white(tr()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(tr()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(tr()?"真 GPU 上跑并带回你的 ms(⚡ 每周一窗口 19:00–21:45 悉尼)":"runs on a real GPU and returns your ms (⚡ Monday window 19:00–21:45 Sydney)"))):t.starter&&!Gr(t)?(console.log(chalk.white(tr()?" 三步:":" Three steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(tr()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(tr()?"本机直跑,出你自己的 ms":"run it locally — see your own ms")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(tr()?"参考机判分(成绩 = 那里的 ms)":"judge on the reference machine (the scored ms)"))):(console.log(chalk.white(tr()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(tr()?"写码(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(tr()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(tr()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(tr()?"正式判分(隐藏用例)":"official judging (hidden tests)")));console.log(),Gr(t)||t.quiz||(console.log(chalk.gray(tr()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(tr()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log()),console.log(chalk.gray((tr()," ↩ "))+chalk.bold.green("back")+chalk.gray(rl()?tr()?" 回花名册 · ":" to the roster · ":tr()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(tr()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang")+chalk.gray((tr()," / "))+chalk.bold.green("wide")+chalk.gray(tr()?" 换语言/宽度":" language / width")),console.log()},_l=async(e,o,t)=>await new Promise(n=>{const s=process.stdin,a=!!s.isTTY&&!!s.isRaw;if(un.pause(),s.isTTY&&"function"==typeof s.setRawMode)try{s.setRawMode(!1)}catch{}bn=!0;const i=r(e,o,{stdio:"inherit",cwd:t??wr.dir}),c=e=>{if(s.isTTY&&"function"==typeof s.setRawMode&&a)try{s.setRawMode(!0)}catch{}l(),bn=!1,un.resume(),n(e)};i.on("close",()=>c(null)),i.on("error",e=>c(e))}),Cl=Ko,Al=()=>{const e=E("vi");console.log(chalk.gray(tr()?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"))},xl=()=>Lo(tr(),{judgeIsServerSide:!0}),Tl=()=>{const e=Ro();return e||xl(),e},Sl=e=>[...new Set([...e.matchAll(/^([A-Z][A-Z0-9_]*)\s*=\s*[^#\n]+/gm)].map(e=>e[1]))],jl=(e,o)=>{const t=new RegExp(`^${o}\\s*=\\s*([^#\n]*?)\\s*(?:#.*)?$`,"m").exec(e);return t?t[1]:null},Pl=async(e,o)=>{P(`learn-arena p${wr.phase}s${wr.data.slot}: answer ${o.trim().slice(0,40)}`),((e,o)=>{const t=oe(wr.dir,Vr(e.n,e.p));let n;try{n=G(t,"utf8")}catch{return console.log(chalk.yellow(tr()?" 先 /read 一道题。":" Open a problem with /read first.")),!1}return K(t,Ve(e.p.starter,n,o)),console.log(chalk.gray(" Answer: ")+chalk.bold.green(o.trim())),!0})(e,o)?await Zl(`/submit ${e.n}`):wn()},Il=new Map,El=()=>fo(process.cwd(),Kt.id),Nl=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())}`},Ml=async(e,o,t=!1)=>{if(!xr)return;let n;try{n=G($o(El(),e),"utf-8")}catch{return}if(Buffer.byteLength(n,"utf-8")>so)return;const r=mo(n),l=(new Date).toISOString(),s=yo(Wo(),Ht).slice(0,co),a=await _o(Ht,{n:e,title:bo(n.split("\n",1)[0]),code:n,code_sha:r,card_number:ln.currentCard,run_meta:o,client_ts:l,events:s.length>0?s:void 0});a?s.length>0&&wo(Wo(),Ht,s.length):ko(Wo(),Ht,{n:e,code_sha:r,card_number:ln.currentCard,run_meta:o,client_ts:l}),a||t||console.log(chalk.gray(tr()?" (未能同步到服务器 — 草稿只保存在本机)":" (could not reach the server — this scratch is saved locally only)"))},Ll=()=>{console.log(chalk.gray(tr()?" 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()},ql=e=>{const o=uo(El()),t=parseInt(e,10);return Number.isInteger(t)&&o.some(e=>e.n===t)?t:(0===o.length?console.log(chalk.yellow(tr()?" 还没有任何草稿 — ":" No scratch files yet — ")+chalk.bold.green("/py")+chalk.gray(tr()?" 新建第一个。":" creates the first one.")):console.log(chalk.yellow(tr()?` 没有 py-${e} — 现有编号: `:` No py-${e} — you have: `)+chalk.white(o.map(e=>e.n).join(", "))+chalk.gray(tr()?" · pylist 看列表":" · pylist shows them")),null)},Ol=e=>{const o=uo(El()),t=e?.trim().toLowerCase(),n=t?o.filter(e=>(e.title??"").toLowerCase().includes(t)):o;if(console.log(),console.log(chalk.bold.magenta(tr()?" ✍ 我的 Python 草稿":" ✍ My Python scratch files")+(t?chalk.gray(` · "${e?.trim()}"`):"")+chalk.gray(` (${n.length})`)),0===o.length)return console.log(chalk.gray(tr()?" 还没有草稿 — ":" Nothing here yet — ")+chalk.bold.green("/py")+chalk.gray(tr()?" 新建一个(第一行写标题)。":" creates one (line 1 becomes its title).")),void console.log();if(0===n.length)return console.log(chalk.gray(tr()?` 没有匹配 "${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(Ft(e.title,40)[0]??e.title):chalk.gray(tr()?"(未命名 — 第一行写标题)":"(untitled — line 1 becomes the title)");console.log(chalk.gray(` py-${String(e.n).padEnd(3)} `)+o+chalk.gray(` · ${Nl(e.mtimeMs)}`))}console.log(chalk.gray(" ▸ ")+chalk.bold.green(tr()?"/py <编号>":"/py <n>")+chalk.gray(tr()?" 打开 · ":" opens one · ")+chalk.bold.green("/py")+chalk.gray(tr()?" 新建":" new file")),console.log()},Rl=async e=>{const o=$o(El(),e);if(Jo())return console.log(chalk.yellow(tr()?" icoa 正跑在 Windows 上 — 草稿本的编辑器在 Ubuntu(WSL)那一侧。":" icoa is running on Windows — the scratchpad editor lives on the Linux (WSL) side.")),console.log(chalk.gray(tr()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${o}`)),void console.log();if(!Xo("vi"))return console.log(chalk.yellow(tr()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${o}`)),void console.log(chalk.gray(tr()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));Al();const t=e=>{try{return H(e).size}catch{return 0}},n=t(o),r=Date.now(),l=I(o);await _l("vi",[...Cl,`py-${e}.py`],El());const s=l.stop();P(`learn-py edit-done py-${e}.py`,{ms:Date.now()-r,bytesBefore:n,bytesAfter:t(o),...s.ticks>0?{samples:s}:{}}),await Ml(e),console.log(chalk.gray(tr()?" 已回到草稿本 — ":" Back in the scratchpad — ")+chalk.bold.green(`run ${e}`)+chalk.gray(tr()?" 本机运行 · ":" runs it locally · ")+chalk.bold.green(`edit ${e}`)+chalk.gray(tr()?" 再改。":" reopens vi.")),console.log()},Wl=async e=>{let o;if(F(El(),{recursive:!0}),e){const t=ql(e);if(null===t)return;o=t}else{const e=uo(El());o=po(e),o>ao&&console.log(chalk.gray(tr()?` (已超过 ${ao} 个 — 服务器不再备份新文件,本机照常保存)`:` (past ${ao} files — the server stops backing new ones up; local saves still work)`)),K($o(El(),o),`${tr()?go:io}\n\n`)}const t=!Wn;Wn=!0,P(`learn-py: open ${o}${e?"":" (new)"}`),t&&(console.log(),console.log(chalk.bold.magenta(tr()?" ✍ Python 草稿本":" ✍ Python scratchpad")+chalk.gray(tr()?" — 你的个人练习文件 · 只在本机运行 · 不判分":" — your personal practice files · runs locally · never judged")),console.log(chalk.gray(tr()?" 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(tr()?" 回卡片(退一层)":" returns to the card (one level)"))),await Rl(o),Ll()},Dl=()=>jo(process.cwd(),Kt.id),Ul=()=>Un??xo(So(process.cwd(),Kt.id,ln.currentCard)),Yl=()=>{console.log(),console.log(chalk.bold.magenta(tr()?" ⌨ shell 实验台":" ⌨ shell lab")+chalk.gray(tr()?" — 在这里动手把答案弄出来 · 不判分 · 不解锁任何东西":" — work the answer out here · never judged · unlocks nothing")),console.log(chalk.gray(tr()?` 真的 shell:管道 | 、重定向 > 、通配符 * 都能用 · 每条命令最多 ${Co/1e3} 秒`:` A real shell: pipes |, redirection >, globs * all work · ${Co/1e3}s per command`)),console.log(chalk.gray(tr()?` 你在 ${No(Dl())} 里面 —— 只能在这个文件夹内走动(自己的终端不受限)`:` You are inside ${No(Dl())} — you can only move within it (your own terminal is unrestricted)`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(tr()?" 回卡片(退一层)":" returns to the card (one level)")),console.log()},Bl=()=>{console.log(chalk.gray(tr()?" 敲任何 shell 命令 · cd 换目录 · reset 还原文件 · clear 清屏 · ↩ back "+("fill"===Yn?"回到这道题":"arena"===Yn?"回赛场":"回卡片"):" type any shell command · cd to move · reset restores files · clear · ↩ back "+("fill"===Yn?"returns to the problem":"arena"===Yn?"returns to the arena":"returns to the card")))},Fl=()=>`icoa sh ${Eo(Dl(),Ul())}> `,zl=(e=!1)=>{const o=pr(ln.currentCard)?.files;if(!o)return[];const t=xo(So(process.cwd(),Kt.id,ln.currentCard)),n=[];for(const[r,l]of Object.entries(o)){if(!/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/.test(r))continue;if(r.split("/").some(e=>"."===e||".."===e))continue;const o=oe(t,r);if(o===t||o.startsWith(t+"/")){try{F(ee(o),{recursive:!0})}catch{}if(e||!B(o))try{K(o,l),n.push(r)}catch{}}}return n},Gl=(e="card")=>{Yn=e;const o=!Dn;Dn=!0,Un=Ul();const t=zl();P(`learn-sh: enter card${ln.currentCard}`),o&&Yl(),t.length>0&&(console.log(chalk.bold.green(tr()?" 📦 本卡的文件已放好:":" 📦 This card ships files:")+chalk.white(` ${t.join(" ")}`)),console.log(chalk.gray(tr()?" 先敲 ls 看看。":" Start with `ls`.")),console.log()),Bl()},Zl=async e=>{const o=e.trim().toLowerCase(),l=Rn&&o.startsWith("/")?o.slice(1):o;if(mn)return void(fn=!0);if($n){const{sameName:o,issueCertificate:t,announceCertificate:n}=await import("../lib/learn-certificate.js"),r=e.trim(),l=tr();if(!r||En.test(r))return $n=null,console.log(chalk.gray(l?" 已取消,未签发。":" Cancelled — nothing issued.")),void wn();if(null===$n.first)return $n.first=r,console.log(chalk.gray(l?" 再输一次:":" Type it once more:")),void wn();const s={cid:$n.cid,tok:$n.tok,first:$n.first};return $n=null,o(s.first,r)?(console.log(chalk.gray(l?" 签发中…(名字只发送一次,不会保存)":" Issuing… (the name is sent once, never stored)")),n(await t(s.tok,s.cid,s.first),l),void wn()):(console.log(chalk.yellow(l?" 两次输入不一致 — 未签发。再敲 certificate 重来。":" The two names differ — nothing issued. Type certificate to try again.")),void wn())}if(On)return;if(yn?.noteInput(),!Bn&&yn?.consumeRating(o))return void wn();if(Bn)return await(async e=>{if(!Bn)return;const o=e.trim(),t=o.toLowerCase();if(lr&&("sh"===t||"/sh"===t))return Fn=Bn,Bn=null,Gl("fill"),void console.log(chalk.gray(tr()?" ▸ 看完敲 back 回到这道题。":" ▸ When you have looked: back returns to this problem."));if("back"===t||"quit"===t||"menu"===t)return Bn=null,Fn=null,console.log(chalk.gray(tr()?" ↩ 回到卡片。":" ↩ Back on the card.")),void qr();if("skip"===t)return void ml();if(""===o)return void yl();const n=hl();if(!n)return Bn=null,void qr();const r=gl(n.starter??"");if(Bn.answers.push(o),Bn.answers.length<r)return void pl();const l=[...Bn.answers],s=((e,o)=>{let t=0;return e.split("\n").map(e=>{if(e.trim().startsWith("#"))return e;for(;e.includes("____")&&t<o.length;)e=e.replace("____",o[t]),t+=1;return e}).join("\n")})(n.starter??"",l);Bn.answers=[];let a=Sr.get(Bn.slot);a||(a=new Set,Sr.set(Bn.slot,a)),a.add(n.id);const i=Boolean(n.quiz),c=i?null:new W(Ht);c?.start();const d=await Be(Ht,Bn.phase,n.id,s,Bn.slot,void 0);if(c?.stop(),!Bn)return;if(!d.ok||!d.data)return"no_active_session"===d.code?void ul(Bn.data.duration_minutes):(console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),console.log(chalk.gray(tr()?" 再敲一遍空1重试,或 back 回卡片。":" Type blank 1 again to retry, or back for the card.")),void pl());const g=d.data;if("AC"!==g.verdict||g.already_ac||yn?.notePracticeAc(),g.already_ac||"AC"===g.verdict){i?console.log(chalk.bold.green(tr()?" ✅ 答对了!":" ✅ Correct!")):console.log(Mo("AC",{isZh:tr(),gentle:!0,passed:g.passed_tests??g.total_tests??null,total:g.total_tests??null,ms:g.time_ms??null}));let e=Tr.get(Bn.slot);return e||(e=new Set,Tr.set(Bn.slot,e)),e.add(n.id),Bn.data.solved.includes(n.id)||Bn.data.solved.push(n.id),void ml()}Bn.tries+=1,i?console.log(chalk.red(tr()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(tr()?" — 再选一次。":" — pick again.")):console.log(Mo(g.verdict??"WA",{isZh:tr(),gentle:!0,passed:g.passed_tests??null,total:g.total_tests??null,failedTest:g.test??null,ms:g.time_ms??null}));const u=n.samples?.[0];if(u?.out){console.log(chalk.gray(tr()?" 期望输出:":" Expected output:"));for(const e of u.out.trimEnd().split("\n"))console.log(chalk.white(" "+e))}if(2===Bn.tries||Bn.tries>2&&Bn.tries%3==2){const e=i?[]:((e,o)=>{const t=[];let n=0;for(const r of e.split("\n")){if(r.trim().startsWith("#"))continue;const e=r.split("____");for(let r=0;r<e.length-1;r++,n++){const l=(o[n]??"").trim(),s=e[r+1].trimStart(),a=e[r].trimEnd(),i=n+1;s.startsWith("(")&&/\(\s*\)?$/.test(l)?t.push(tr()?` ⚠ 空${i}:模板里 ____ 后面已经有 ( ) — 只填名字,别再带括号。`:` ⚠ blank ${i}: the ( ) after ____ is already in the template — type just the name, no brackets.`):(/["']$/.test(a)||/^["']/.test(s))&&/^["']|["']$/.test(l)?t.push(tr()?` ⚠ 空${i}:引号模板里已经有了 — 只填引号中间的内容。`:` ⚠ blank ${i}: the quotes are already in the template — type only what goes between them.`):/^[A-Za-z_][\w.]*\(.*\)$/.test(l)&&!s.startsWith("(")&&/\)\s*[:)]/.test(s)&&t.push(tr()?` ⚠ 空${i}:____ 后面已有右括号,你的答案可能多带了一个 )。`:` ⚠ blank ${i}: a closing ) already follows ____ — your answer may carry one too many.`)}}return t})(n.starter??"",l);for(const o of e)console.log(chalk.yellow(o));console.log(chalk.gray(tr()?" 💡 两次没过,多半是细节不是思路 — 再敲之前过一遍:":" 💡 Two misses are usually a detail, not the idea — run this check before retrying:")),i||(console.log(chalk.gray(tr()?" · 拼写和大小写(Python 区分大小写:Print ≠ print)":" · spelling and case (Python is case-sensitive: Print ≠ print)")),console.log(chalk.gray(tr()?" · 只填缺的那一块 — ____ 周围已有的括号、引号、冒号不要重复":" · fill only what is missing — brackets, quotes, colons already around ____ stay"))),console.log(chalk.gray(tr()?" · 没思路?往上翻,或 ":" · no idea? scroll up, or ")+chalk.bold.green("back")+chalk.gray(tr()?" 回卡片再读一遍 — 答案就在正文里。打错字人人都有,继续。":" re-reads the card — the answer is in its body. Typos happen to everyone; keep going."))}console.log(chalk.gray(tr()?" 从空1再来:":" From blank 1 again:")),pl()})(e),void wn();if(null!==Sn){if(jn.push(e.replace(/\s+$/,"")),In&&clearTimeout(In),In=null,Pn){const e=jn[jn.length-1]??"";return"/cancel"===e.trim()?(Ln(),console.log(chalk.gray(tr()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void wn()):""!==e.trim()?void wn():(jn.pop(),void await c())}return void(In=setTimeout(()=>{if(In=null,jn.length>1){Pn=!0;const e=jn.length;return console.log(chalk.cyan(tr()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(tr()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void wn()}c()},140))}async function c(){const e=jn.join("\n").replace(/^\s+|\s+$/g,""),o=Sn??ln.currentCard,t=jn.length,n=Nn;if(Ln(),""===e)console.log(chalk.gray(tr()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&En.test(e))console.log(chalk.yellow(tr()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(tr()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(tr()?" 即可执行。":" again to run it."));else{const r=!n&&or>0?Date.now()-or:void 0;if(await ie(Ht,{curriculum_id:Kt.id,card_number:o,feedback_text:n?`${n} ${e}`:e,time_on_card_ms:r})){const n=t>1?tr()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(tr()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(tr()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),on=[...on,{id:nn--,curriculumId:Kt.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Rt(on)}else console.log(chalk.yellow(tr()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),wn()}if(Gn){const o=e.trim();if(En.test(o))return Gn=!1,console.log(),console.log(chalk.yellow(tr()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(tr()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(tr()?" 即可执行该命令。":" again to run it.")),console.log(),void wn();if(!o)return Gn=!1,console.log(chalk.gray(tr()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void wn();const t=await qe({token:Ht,nickname:o});if(t.ok)Gn=!1,console.log(chalk.bold.green(tr()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(tr()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Zn+=1;const e="taken"===t.code?tr()?"已被占用":"already taken":"bad_charset"===t.code?tr()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"real_name"===t.code?tr()?"看起来像真名 — 系统不收集个人信息,换个游戏风格的昵称":"looks like a real name — we collect no personal info; pick a gamer-style handle":"rejected"===t.code?tr()?"未通过审核":"did not pass review":t.message||"error";if(!(Zn>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(tr()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void wn();Gn=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(tr()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void wn()}if(Xn){Xn=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{On=!0;try{console.log(),console.log(chalk.gray(tr()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await Re({token:Ht,cardNumber:ln.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(tr()?"评审暂不可用。":"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(tr()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(tr()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(tr()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(tr()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(tr()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(tr()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=tr()?` 本卡排名 #${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(tr()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(tr()?` 第 ${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 Dr(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(tr()?" 改进提问: ":" 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(` (${tr()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Vn.add(ln.currentCard):Vn.delete(ln.currentCard),"number"==typeof e.rank&&nr.set(ln.currentCard,e.rank);const o=await De({token:Ht,curriculumId:Kt.id,cardNumber:ln.currentCard});if(o.ok&&o.totals&&o.chapters&&(Bt({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(tr()?` · 榜首 ${n.name||"Rank 1"} ${n.total}`:` · leader ${n.name||"Rank 1"} at ${n.total}`):chalk.bold.yellow(tr()?" · 全场第一!":" · phase leader!");console.log(chalk.white(tr()?` 🏅 Phase ${e.phase} 研究总分: `:` 🏅 Phase ${e.phase} research total: `)+chalk.bold.yellow(`${t.total}`)+chalk.gray(tr()?`(${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&&!Jt&&(Gn=!0,Zn=0,console.log(chalk.bold.yellow(tr()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(tr()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(tr()?" 英文开头,英文+数字,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{On=!1}})():(console.log(chalk.gray(tr()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==_n&&(console.log(chalk.gray(tr()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void wn()}if(er)return er=!1,qr(),void wn();if(!o)return void wn();if(Kn)return"exit"===await U(e.trim())&&(Kn=!1),void wn();if(qn){if(["q","quit","exit","back","b","menu"].includes(o))return qn=!1,console.log(chalk.gray(tr()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void wn();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),l=n.length>0&&!/[\p{L}\p{N}]/u.test(n);return r||l?(console.log(),console.log(chalk.yellow(tr()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?tr()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":tr()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(tr()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(tr()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void wn()):(n&&(await Wr(n,t?"fast":"deep"),console.log(chalk.gray(Xt?tr()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)":tr()?" (↩ q = 返回卡片)":" (↩ q = back to card)"))),void wn())}if(Dn){const t=e.trim();if(["back","b","quit","exit","q"].includes(o))return Dn=!1,Un=null,P("learn-sh: leave"),"arena"===Yn?console.log(chalk.gray(tr()?" ↩ 已离开实验台,回到赛场。":" ↩ Left the lab — back in the arena.")):"fill"===Yn&&Fn?(Bn=Fn,Fn=null,yl()):(console.log(chalk.gray(tr()?" ↩ 已离开 shell 实验台,回到卡片。":" ↩ Left the shell lab — back to the card.")),qr()),void wn();if("menu"!==o&&!/^memo\b/.test(o)){if("reset"===o){const e=zl(!0);return console.log(e.length>0?chalk.green((tr()?" ↺ 已还原本卡的文件: ":" ↺ Restored this card's files: ")+e.join(" ")):chalk.gray(tr()?" 本卡没有附带文件。":" This card ships no files.")),void wn()}return"clear"===o||"cls"===o?(console.clear(),Bl(),void wn()):"help"===o||"e"===o||"?"===o?(Yl(),void wn()):""===t?void wn():/^\/?py(\s|$)/.test(o)?(Dn=!1,Un=null,await Wl(/^\/?py\s+(\S+)/.exec(o)?.[1]),void wn()):(await(async e=>{P(`learn-sh: $ ${e}`);const o=/^cd(?:\s+(.*))?$/.exec(e.trim());if(o){const e=Po(Dl(),Ul(),o[1]?.trim());return void(null===e?console.log(chalk.yellow(tr()?" 去不了那儿 —— 目录不存在,或在实验台外面。":" Cannot go there — no such directory, or it is outside the lab.")+chalk.gray(tr()?" cd 单独敲回到顶层。":" Bare `cd` returns to the top.")):Un=e)}const t=Ao(e);if(t)return void console.log(chalk.red((tr(),` ⚠ \`${t.word}\` `))+chalk.yellow(t.why)+chalk.gray(tr()?" —— 实验台不执行它。在自己的终端里敲之前,先 ls 看清楚它会碰到什么。":" — the lab never runs it. In your own terminal, `ls` what it will touch before you press Enter."));const n=To(e);if(n)return void console.log(chalk.yellow(tr()?` \`${e.trim().split(/\s+/)[0]}\` 会占住终端,这里跑不了 — `:` \`${e.trim().split(/\s+/)[0]}\` takes over the terminal and cannot run here — `)+chalk.bold.green(n));const r=/(^|[;&|]\s*)cd(\s|$)/.test(e)&&!/^cd(\s|$)/.test(e.trim()),l=await Io(e,Ul());"no-shell"!==l.kind?"timeout"!==l.kind?"refused"!==l.kind&&(l.stdout&&console.log(chalk.white(l.stdout.replace(/\n$/,""))),l.stderr&&console.log(chalk.red(l.stderr.replace(/\n$/,""))),l.truncated&&console.log(chalk.gray(tr()?" … 输出过长,已截断。":" … output truncated.")),r&&console.log(chalk.yellow(tr()?" 注意:这一行里的 cd 只在子进程里生效,你还在原来的目录。":" Note: the cd in that line ran in a child process — you have not moved.")+chalk.gray(tr()?" 单独敲一行 cd <目录>。":" Type `cd <dir>` on its own line.")),l.stdout||l.stderr?0!==l.code&&console.log(chalk.gray(tr()?` (退出码 ${l.code})`:` (exit ${l.code})`)):console.log(chalk.gray(tr()?` (没有输出 · 退出码 ${l.code})`:` (no output · exit ${l.code})`))):console.log(chalk.yellow(tr()?` 超过 ${Co/1e3} 秒,已停止。`:` Stopped after ${Co/1e3}s.`)+chalk.gray(tr()?" 换个更小的目标再试。":" Try a smaller target.")):console.log(chalk.red(tr()?" 这台机器上找不到 /bin/sh。":" No /bin/sh on this machine.")+chalk.gray(tr()?" Windows 请在 WSL2 里跑 icoa。":" On Windows, run icoa inside WSL2."))})(t),void wn())}}if(Wn){if(/^\/?(py|pylist|edit|run|list|new)\b|^(b|q|quit|exit|back)$|^\d+$/.test(o)&&P(`learn-py: ${o}`),["back","b","quit","exit","q"].includes(o))return Wn=!1,console.log(chalk.gray(tr()?" ↩ 已离开草稿本,回到卡片。":" ↩ Left the scratchpad — back to the card.")),qr(),void wn();const t=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(t||"list"===o||"/list"===o)return Ol(t?.[1]),Ll(),void wn();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=ql(o);null!==t&&("edit"===e?(await Rl(t),Ll()):await(async e=>{if(!B($o(El(),e)))return void ql(String(e));const o=Oo()?.cmd??null;if(!o)return void Lo(tr());const[t,...n]=o.split(" ");console.log();const l=vo();let s="",a=!1;const i=await new Promise(o=>{const l=r(t,[...n,`py-${e}.py`],{cwd:El(),stdio:["ignore","pipe","pipe"]}),i=setTimeout(()=>{a=!0;try{l.kill("SIGKILL")}catch{}},3e4);l.stdout?.on("data",e=>process.stdout.write(e)),l.stderr?.on("data",e=>{s.length<400&&(s+=e.toString("utf-8")),process.stderr.write(e)}),l.on("error",()=>{clearTimeout(i),o(127)}),l.on("close",(e,t)=>{clearTimeout(i),o(t?124:e??0)})}),c=l();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(tr()?" ⏱ 超过 30 秒,已停止 — 检查死循环。":" ⏱ Over 30s — stopped. Check for an infinite loop."))),console.log(chalk.gray((tr()," ▸ edit "))+chalk.gray(`${e} · pylist · `)+chalk.bold.green("back")),console.log(),cr.push(Ml(e,{run_ms:c,exit_code:i,stderr_head:s.trim().slice(0,300)||void 0},!0).catch(()=>{}))})(t))}else console.log(chalk.yellow(tr()?` 用法: ${e} <编号>`:` Usage: ${e} <n>`)+chalk.gray(tr()?" (pylist 看编号)":" (pylist shows the numbers)"));return void wn()}const l=/^\/?py(?:\s+(\S+))?$/.exec(o);if(l||"new"===o)return await Wl(l?.[1]),void wn();const s=/^\/?(python(?:3)?|m[ou]joco)(?:\s+(setup|install|status))?$/i.test(o.trim());if("menu"!==o&&"menu confirm"!==o&&!s)return console.log(chalk.gray(tr()?" 草稿本命令: edit <n> · run <n> · pylist · /py 新建 · back 回卡片":" Scratchpad verbs: edit <n> · run <n> · pylist · /py (new) · back to the card")),void wn()}if(Rn&&wr){/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn|memo|cells|explore|answer|ans)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&P(`learn-arena p${wr.phase}s${wr.data.slot}: ${o}`);const n=parseInt(wl??"1",10),r=wr.data.problems[n-1],s=r?.quiz?{p:r,n:n}:null,a=s?Xe(s.p):null,i=/^\/?(?:answer|ans)\s+(.+)$/i.exec(o.trim());if(i)return s?void await Pl(s,i[1]):(console.log(chalk.yellow(tr()?" 这一题不是答题式的 — 用 /edit 写代码,/submit 提交。":" This problem is not a typed-answer item — /edit the code and /submit it.")),void wn());const c=/^([A-Ea-e])$/.exec(o.trim());if(c&&s&&a){if("letter"===a.kind)return void await Pl(s,c[1].toUpperCase());let e;return e="choose"===a.kind?(tr()?" 输入其中一个词:":" Type one of: ")+a.options.join(" / "):tr()?" 输入 answer 你的答案(例如 answer 1200)。":" Type answer <your answer> (e.g. answer 1200).",console.log(chalk.yellow(tr()?" 这一题不是选字母的。":" This one is not a letter question.")+chalk.gray(e)),void wn()}if(s&&"choose"===a?.kind){const e=o.trim().toLowerCase(),t=a.options.find(o=>o.toLowerCase()===e);if(t)return void await Pl(s,t)}if(lr&&("sh"===o||"/sh"===o))return Gl("arena"),console.log(chalk.gray(tr()?" ▸ back 回赛场 · 计时照走":" ▸ back returns to the arena · the clock keeps running")),void wn();if("memo"===o||"/memo"===o||"e"===o)return Sn=ln.currentCard,Nn=`[arena p${wr.phase}-g${wr.data.slot}${wl?` #${wl}`:""}]`,console.log(chalk.gray(tr()?` 报告归到: 竞技场 p${wr.phase}-g${wr.data.slot}${wl?` 题${wl}`:""} — 题面 / 判分 / 环境,一句话即可:`:` Files under: arena p${wr.phase}-g${wr.data.slot}${wl?` problem ${wl}`:""} — statement / judging / environment, one line is enough:`)),console.log(chalk.gray(tr()?" (回车提交 · 空行取消 · 不打断比赛计时)":" (Enter to submit · blank to cancel · the contest clock is unaffected)")),void wn();if("back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return rl()&&null!==wl?(wl=null,fl(),void wn()):(Rn=!1,wl=null,console.log(chalk.gray(tr()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),qr(),void wn());if(/^\d+$/.test(o))return vl(o),void wn();const d=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(d)return rl()?d[1]?vl(d[1]):fl():console.log(chalk.gray(tr()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void wn();if("cells"===o||"/cells"===o||"explore"===o||"/explore"===o){const e=Ar(wr.phase,wr.data.slot,wr.dir);if(!e)return console.log(chalk.gray(Cr(wr.phase,wr.data.slot)?tr()?" 引导 notebook 还没下载到位(需要联网一次)— 稍后再敲 cells。":" The guided notebook has not downloaded yet (needs one online moment) — try cells again shortly.":tr()?" 本场没有引导 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 wn();const o=null!==N();o||M(un);try{const{runIpynb:o}=await import("./ipynb.js");await o(e)}catch(e){console.log(chalk.yellow(tr()?" notebook 没打开: ":" The notebook failed to open: ")+chalk.gray(String(e)))}finally{o||M(null)}return fl(),void wn()}const g=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(g)return await(async e=>{const o=e.trim();if(await Ce()||kl||(kl=!0,console.log(chalk.gray(tr()?` (离线:只有 ${Ee()} 条核心速查可用;联网后自动补全)`:` (offline: ${Ee()} core entries available; the rest arrive when you have a connection)`))),!o)return void je(tr());const t=xe(o);if(t.length){Ie(t[0],tr());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(tr()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await Ae("python3",o);if(n)Pe(n,tr());else{if(await Te()){const e=xe(o);if(e.length)return void Ie(e[0],tr())}console.log(),console.log(chalk.yellow(tr()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(tr()?" 试试: ":" Try: ")+chalk.cyan(Se(o).join(" · "))),console.log(chalk.gray(tr()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(g[1]??""),void wn();const u=/^\/?set\b\s*(.*)$/i.exec(e.trim());if(u)return await(async e=>{const o=bl(wl??"1");if(!o)return;const t=oe(wr.dir,Vr(o.n,o.p));let n;try{n=G(t,"utf8")}catch{return void console.log(chalk.yellow(tr()?" 先 /read 一道题。":" Open a problem with /read first."))}const r=Sl(n);if(0===r.length)return void console.log(chalk.yellow(tr()?" 这道题的文件没有旋钮(顶部那种 NAME = value 行)。":" This problem's file has no knobs (the NAME = value lines at the top).")+chalk.gray(tr()?" 用 ":" Use ")+chalk.bold.green(`/edit ${o.n}`));const l=/^([A-Za-z][A-Za-z0-9_]*)\s*(?:=|\s)\s*(.+)$/.exec(e.trim());if(!l){console.log(chalk.yellow(tr()?" 用法: ":" Usage: ")+chalk.bold.green(tr()?"set <旋钮> <值>":"set <KNOB> <value>")+chalk.gray(tr()?" 例如 set WOMBATS 6":" e.g. set WOMBATS 6")),console.log(chalk.gray(tr()?" 这个 bot 的旋钮:":" This bot's knobs:"));for(const e of r)console.log(chalk.gray(" ")+chalk.bold.white(e.padEnd(10))+chalk.gray(jl(n,e)??""));return}const s=l[1].toUpperCase(),a=l[2].trim(),i=r.find(e=>e===s);if(!i)return console.log(chalk.yellow(tr()?` 这个 bot 没有 ${s} 这个旋钮。`:` This bot has no knob called ${s}.`)),void console.log(chalk.gray(" ")+r.map(e=>chalk.bold.white(e)).join(chalk.gray(" · ")));const c=jl(n,i)??"";if(c.trim()===a)return void console.log(chalk.gray((tr()," "))+chalk.bold.white(i)+chalk.gray(tr()?` 已经是 ${a} 了。`:` is already ${a}.`)+chalk.gray(tr()?" 下一步: ":" Next: ")+chalk.bold.green(`/run ${o.n}`));const d=new RegExp(`^(${i}\\s*=\\s*)([^#\n]*?)(\\s*)(#.*)?$`,"m"),g=n.replace(d,(e,o,t,n,r)=>`${o}${a}${r?(n||" ")+r:""}`);K(t,g),console.log(chalk.gray(" ")+chalk.bold.white(i)+chalk.gray(" ")+chalk.gray(c.trim())+chalk.gray(" → ")+chalk.bold.green(a)),console.log(chalk.gray((tr()," ▸ "))+chalk.bold.green(`/run ${o.n}`)+chalk.gray(tr()?" 打一局看看 · ":" play a match and watch · ")+chalk.bold.green(`set ${i} ${c.trim()}`)+chalk.gray(tr()?" 改回去":" puts it back"))})(u[1]??""),void wn();const h=/^\/?(read|open|edit|run|debug|list|recall|replay)(?:\s+(\S+))?$/.exec(o);if(h){const[,e,o]=h;return"list"===e?fl():"replay"===e?await Fo()||console.log(chalk.gray(tr()?" 还没有回放。先 submit 一次 —— 判分机会把你输的那一局送回来。":" No replay yet. Submit once — the judge sends back the game you lost.")):o?"read"===e||"open"===e?vl(o):"edit"===e?await(async e=>{const o=bl(e);if(!o)return;const t=oe(wr.dir,Vr(o.n,o.p));if(Jo())return Qo()?(console.log(chalk.yellow(tr()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(tr()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(tr()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(tr()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(tr()?" ← 不能是 /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(tr()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(tr()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(tr()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(tr()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(tr()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(tr()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(tr()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(tr()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!Xo("vi"))return console.log(chalk.yellow(tr()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(tr()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));Al();const n=e=>{try{return H(e).size}catch{return 0}},r=n(t),l=Date.now(),s=I(t);await _l("vi",[...Cl,Vr(o.n,o.p)]);const a=s.stop(),i={ms:Date.now()-l,bytesBefore:r,bytesAfter:n(t)};if(kr.set(o.n,Q(kr.get(o.n)??J(),i)),a.ticks>0){const e=vr.get(o.n)??{list:[],dropped:0};e.list.push(a),e.list.length>16&&(e.list.shift(),e.dropped++),vr.set(o.n,e)}P(`learn-arena edit-done ${Vr(o.n,o.p)}`,{...i,...a.ticks>0?{samples:a}:{}}),console.log(chalk.gray(tr()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Gr(o.p)?tr()?" 本机打一局。":" to play one match here.":tr()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?await(async e=>{const o=bl(e);if(!o)return;const{p:n,n:r}=o;if(Gr(n)){const e=oe(wr.dir,Vr(r,n));if(!B(e))return void console.log(chalk.yellow(tr()?` 还没有 ${Vr(r,n)} — 先 /edit ${r}。`:` No ${Vr(r,n)} yet — /edit ${r} first.`));kr.set(r,V(kr.get(r)??J()));const o=await Go(e,n.card??0,0,n.crit,(e,o)=>_l(e,o));return void(o.ran&&(console.log(o.ok?chalk.gray(" ▸ ")+chalk.bold.green(`/submit ${r}`)+chalk.gray(tr()?" 过线了 — 交给判分机(多局固定种子)":" over the bar — send it to the judge (seeded games)"):chalk.gray(" ▸ ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(tr()?" 改一改,再 ":" adjust, then ")+chalk.bold.green(`/run ${r}`)),console.log()))}if(Hr&&r===to)return void(()=>{const e=oe(wr.dir,`sol-${to}.py`);if(!B(e))return void console.log(chalk.yellow(tr()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=Tl();if(!o)return;const n=[];for(const r of no)try{n.push(t(o,[e],{input:`${r.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}))}catch(e){const o=e;if("ENOENT"===o.code)return void xl();if(console.log(),o.killed)return void console.log(chalk.yellow(tr()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(tr()?` ✗ 输入 ${r.in} 时程序报错:`:` ✗ Your program crashed on input ${r.in}:`));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));return console.log(),console.log(chalk.gray(tr()?" 改完再来: ":" Fix it and rerun: ")+chalk.bold.green("/edit 0")+chalk.gray(" → ")+chalk.bold.green("/run 0")),void console.log()}const{cases:r,passed:l}=ro(n);console.log();for(const e of r)console.log((e.ok?chalk.green(" ✓ "):chalk.red(" ✗ "))+chalk.gray(`n = ${e.in.padEnd(6)} → `)+(e.ok?chalk.cyan(e.got||"(empty)"):chalk.red(e.got||"(empty)"))+(e.ok?"":chalk.gray(tr()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),l===r.length){const e=Kr?null:1;Kr=!0,console.log(chalk.bold.green(tr()?` 🎉 ${l}/${r.length} 全过 — `:` 🎉 ${l}/${r.length} — `)+chalk.white(tr()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(tr()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(tr()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(tr()?` ${l}/${r.length} 通过 — 还差一点。`:` ${l}/${r.length} passed — not there yet.`)+chalk.gray(tr()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(tr()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const l=oe(wr.dir,Vr(r,n));if(!B(l))return void console.log(chalk.yellow(tr()?` 还没有 ${Vr(r,n)} — 先 /edit ${r}。`:` No ${Vr(r,n)} yet — /edit ${r} first.`));kr.set(r,V(kr.get(r)??J()));const s=(n.samples??[])[0];if(n.gpu)return console.log(chalk.gray(tr()?" ⚡ 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(tr()?"(窗口时间执行并返回你的 ms;窗口外会告诉你开放时间)":" (executes in the GPU window and returns your ms; outside the window it tells you the hours)")),void console.log();{const e=Xr(n),o={cpp:"c++",java:"java",go:"go"};if("python"===e?!Ro():!Xo(o[e]??e)){const t="python"===e?"Python":o[e]??e;return console.log(chalk.yellow(tr()?` ⓘ 本机没有 ${t} 环境 — 这一题直接交给判分机跑。`:` ⓘ No local ${t} environment — running this one on the server judge instead.`)),console.log(chalk.gray(tr()?" 判分机的计时本来就是准数;本地跑只是预览。":" The judge's timing is the real number anyway - local runs were only a preview.")),void await Zl(`/submit ${r}`)}}if(!s&&n.starter){const e=Xr(n);try{let o;if("cpp"===e){const e=oe(wr.dir,`.speed-${r}.bin`);t("c++",["-O2","-o",e,l],{timeout:3e4,stdio:["pipe","pipe","pipe"]}),o=t(e,[],{input:"",timeout:3e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}else if("java"===e)o=t("java",[l],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});else if("go"===e)o=t("go",["run",l],{input:"",timeout:6e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]});else{const e=Tl();if(!e)return;o=t(e,[l],{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(tr()?` ${ho(!0)} — 满意就 `:` ${ho(!1)} — happy? `)+chalk.bold.green(`/submit ${r}`))}catch(e){const o=e;if("ENOENT"===o.code)xl();else if(o.killed)console.log(chalk.yellow(tr()?" ⏱ 超过 30 秒 — 检查死循环。":" ⏱ Over 30s — check for an infinite loop."));else{console.log(chalk.yellow(tr()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr??"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));console.log(chalk.gray(tr()?` (空还没填对?/read ${r} 看题面的 hint,/edit ${r} 再改)`:` (blank not filled yet? /read ${r} for the hint, /edit ${r} to fix)`))}}return void console.log()}if(!s)return void console.log(chalk.gray(tr()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";const i=Tl();if(!i)return;const c=vo();try{a=t(i,[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(e){const o=e;if("ENOENT"===o.code)xl();else if(o.killed)console.log(chalk.yellow(tr()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(tr()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const d=c(),g=a.replace(/\r\n/g,"\n").trimEnd(),u=s.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(tr()?" 你的输出:":" Your output:"));for(const e of(g||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(tr()?" 样例应输出:":" Sample expects:"));for(const e of u.split("\n"))console.log(chalk.green(` ${e}`));console.log(chalk.gray(` ⏱ ${d}ms — ${ho(tr())}`)),g===u?console.log(chalk.bold.green(tr()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(tr()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(tr()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(tr()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=bl(e);if(!o)return;if(Gr(o.p))return console.log(chalk.gray(tr()?` bot 不读输入 — /run ${o.n} 本机打一局就是自由试跑,/submit ${o.n} 判分。`:` A bot reads no input — /run ${o.n} plays a match here (that is the free run); /submit ${o.n} judges.`)),void console.log();if("python"!==Xr(o.p)||o.p.gpu)return console.log(chalk.gray(tr()?` 这一层不读输入 — 用 /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=oe(wr.dir,`sol-${o.n}.py`);if(!B(t))return void console.log(chalk.yellow(tr()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));const n=Tl();if(!n)return;console.log(chalk.gray(tr()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const r=await _l(n,[`sol-${o.n}.py`]);console.log(),"ENOENT"!==r?.code?(console.log(chalk.gray(tr()?" 回到竞技场。":" Back in the arena.")),console.log()):xl()})(o):"recall"===e&&await(async e=>{const o=bl(e);if(!o)return;if(!Xt)return void Rr();const{p:t,n:n}=o,r=oe(process.cwd(),"icoa-contest"),l=`${Kt.id}-phase${wr.phase}-g${wr.data.slot}-archived-`;let s=null;try{for(const e of z(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?oe(r,s,`sol-${n}.py`):null;if(!a||!B(a))return void console.log(chalk.gray(tr()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=G(a,"utf-8"),c=`${wr.phase}-${wr.data.slot}-${n}`,d=Math.min(3,(Il.get(c)??0)+1);console.log(chalk.gray(tr()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await Le({token:Ht,phase:wr.phase,slot:wr.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:tr()?"zh":"en"});if(g.ok){Il.set(c,d),console.log();for(const e of Ft(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(tr()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(tr()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(tr()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(tr()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(tr()?" (花名册: /list)":" (roster: /list)")),void wn()}if("contest"===o||"/contest"===o)return fl(),void wn();const p="lang"===o||/^lang\s+\S+$/.test(o),y=Gt.has(o);if(!(/^\/?(python(?:3)?|m[ou]joco)(?:\s+(setup|install|status))?$/i.test(o.trim())||"submit"===l||l.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||"restart"===o||p||y||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(tr()?" 竞技场命令: /read set /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read set /edit /run /debug /submit /list /syntax · back returns to the lesson")),void wn()}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(tr()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void wn()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(un.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}bn=!0;const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}bn=!1,un.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void wn()}if("ai4ioai"===o||"/ai4ioai"===o)return await Y()&&(Kn=!0),void wn();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(Jt)return Rr(),void wn();Hn||(Hn=!0,console.log(),Xt?(console.log(chalk.bold.cyan(tr()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(tr()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(tr()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),tr()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")),console.log(chalk.gray(tr()?" 💡 一次好的研究通常会向 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(tr()?" 新建草稿贴进去跑(":" a fresh scratch file and run them (")+chalk.bold.green("/pylist")+chalk.gray(tr()?" 看草稿)。":" lists them)."))):(console.log(chalk.bold.cyan(tr()?" 🐼 AI 熊猫导师":" 🐼 AI Panda Tutor")),console.log(chalk.gray(tr()?` 围绕本卡内容提问 — 导师已经读过这张卡。每张卡每天最多 ${Vt} 个问题;`:` Ask about THIS card — the tutor has read it. Up to ${Vt} questions per card per day;`)),console.log(chalk.gray(tr()?" 跑题的问题不会被回答,也不计次数。这里只是问答,没有评分和榜单。":" off-topic questions are not answered and do not count. Q&A only — no grading, no board."))),console.log(chalk.yellow(tr()?" ↩ 重要:退出 AI 模式只需输入 ":" ↩ Important: to leave AI mode just type ")+chalk.bold.white("back")+chalk.yellow(tr()?" 或 ":" or ")+chalk.bold.white("quit")+chalk.yellow(tr()?",就回到卡片。":" — you are back on the card.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){qn=!0;const e=pr(ln.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(tr()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(tr()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Xt?tr()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · back / quit = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · back / quit = back to card":tr()?" 直接输入问题 · back / quit = 返回卡片":" Type a question · back / quit = back to card")),Xt&&console.log(chalk.gray(tr()?" 💡 通常要向 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 wn()}return await Wr(n,t?"fast":"deep"),void wn()}if(!Rn&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Xt)return Rr(),void wn();const e=pr(ln.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(tr()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(tr()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(tr()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(tr()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(tr()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(tr()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(tr()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Xn=!0,void wn()}const p=!Rn&&"honors"===zn&&/^[1-3]$/.test(o);if(!Rn&&zn&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(tr()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(tr()?" ↩ back 回上一层":" ↩ back goes up one level")),void wn();if(!Rn&&(p||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Xt)return Rr(),void wn();const e=/^\/?view ([1-3])$/.exec(o),t=p?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{On=!0;try{console.log();const o=await We({token:Ht,cardNumber:ln.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(tr()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Vn.delete(ln.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Vn.add(ln.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(tr()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${ln.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${ln.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(tr()?` (第 ${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(tr()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Dr(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(tr()?" (无可显示的提问)":" (no questions to show)"))}console.log(),zn="view",console.log(chalk.gray((tr()," "))+chalk.bold.cyan("↩ back")+chalk.gray(tr()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{On=!1}})(t),void wn()}const _=o.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(_&&!Rn&&!Wn){const{certificateLines:e}=await import("../lib/learn-door.js"),{certifiable:o,certificateIntroLines:t}=await import("../lib/learn-certificate.js"),n=tr(),r=Jt?null:await v(Ht,"me"),l=r&&"ok"===r.kind?r.profile:null,s=o(l),a=(_[2]??"").toLowerCase();console.log();const i=a?s.find(e=>e.curriculum_id.toLowerCase()===a||e.curriculum_id.toLowerCase().startsWith(a)):s.find(e=>e.curriculum_id===Kt.id)??(1===s.length?s[0]:void 0);if(!i){for(const o of e(l,n))console.log(o);return s.length>1&&console.log(chalk.gray(" ")+chalk.bold.green("certificate <track>")+chalk.gray(n?" 签发其中一门。":" to issue one.")),console.log(),void wn()}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:")),$n={cid:i.curriculum_id,tok:i.token,first:null},void wn()}const A=o.match(/^\/?(story|credits|fin)(?:\s+(\S+))?$/);if(A&&!Rn&&!Wn){const e=(A[2]??"").trim();return await mr("story"===A[1]?e||"list":e||null,!0),void wn()}if(/^\/?(?:type|typing)(?:\s|$)/i.test(o))return await Yo(o.trim().split(/\s+/).slice(1)),void wn();if(/^\/?battle(?:\s|$)/i.test(o)&&!Rn&&!Wn){const e=null!==N();return e||M(un),await zo([...o.trim().split(/\s+/).slice(1),`from-card:${ln.currentCard}`]),e||M(null),void wn()}if(/^\/?duck(?:\s|$)/i.test(o)&&!Rn&&!Wn){const e=null!==N();return e||M(un),await Ho([...o.trim().split(/\s+/).slice(1),`from-card:${ln.currentCard}`]),e||M(null),void wn()}if(O(o))return await R(),void wn();if("me"===o||"/me"===o||"profile"===o||"/profile"===o||"my profile"===o){const e=tr();if(Jt)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 wn();console.log(chalk.gray(e?" 正在取档案…":" Loading your profile…"));const o=await v(Ht);return"ok"===o.kind?C(o.profile,e,Yt()):"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 wn()}if("/honors"===o||"honors"===o)return Jt?(console.log(),console.log(chalk.gray(tr()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void wn()):(await Yr(),void wn());const x=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(x)return P("learn-py: pylist"+(x[1]?` ${x[1]}`:"")),Ol(x[1]),void wn();const T=/^\/?py(?:\s+(\S+))?$/.exec(o);if(T)return await Wl(T[1]),void wn();if(/^\/?sh$/.test(o))return Gl(),void wn();const S=/^\/?(python(?:3)?|m[ou]joco)(?:\s+(setup|install|status))?$/i.exec(o.trim());if(S){const e=/^m[ou]joco$/i.test(S[1]);P(`learn-${e?"mujoco":"python"}: ${S[2]??"status"}`);const o=(S[2]??"").toLowerCase();if(e){const{runMujocoSetup:e,printMujocoStatus:t}=await import("./mujoco.js");"setup"===o||"install"===o?await e():t()}else{const{runSetup:e,printStatus:t}=await import("./python.js");"setup"===o||"install"===o?await e():t()}return console.log(chalk.gray(tr()?" ↩ back 回卡片 · ":" ↩ back to the card · ")+chalk.bold.green("/py")+chalk.gray(tr()?" 打开草稿本":" opens the scratchpad")),console.log(),void wn()}if(Cn&&"menu"!==o&&"menu confirm"!==o){const e=Cn.handle(o);return"input"===e||Tn(e),void wn()}if(Cn&&(Cn=null),"menu"===o||"menu confirm"===o){if(yn?.detach(),cr.length>0&&await Promise.race([Promise.allSettled(cr),new Promise(e=>setTimeout(e,3e3))]),un.removeAllListeners("line"),pn(),dn||!hr){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(dn?un:void 0),ur()}else un.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===zn)return await Yr(),void wn();if("honors"===zn)return zn=null,qr(),void wn();if(yn?.detach(),cr.length>0&&await Promise.race([Promise.allSettled(cr),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ln.streakDays} day(s)`)),console.log(),dn){un.removeAllListeners("line"),pn();for(const e of gn)un.on("line",e);un.prompt(),ur()}else un.removeAllListeners("line"),un.close();return}if(pe(o))return tn?Zt(ue(tn,tr(),Yt(),"T0"===ye().tier),!!tn.completedAt):(console.log(chalk.gray(tr()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void wn();{const e=o.match(y);if(e)return xr?(await m(Ht,e[1]??"",{curriculum:Kt}),P("learn: check"),void wn()):(console.log(chalk.yellow(tr()?" check 需要正式课程 token(demo 不支持)。":" check needs a full curriculum token (not demos).")),void wn())}{const e=o.match(f);if(e)return xr?(await $(Ht,e[1]??"",Kt.totalCards),P("learn: class"),void wn()):(console.log(chalk.yellow(tr()?" class 需要正式课程 token(demo 不支持)。":" class needs a full curriculum token (not demos).")),void wn())}if(b.test(o)&&!Rn&&!Wn&&!Dn){if(!xr)return console.log(chalk.yellow(tr()?" 队伍会议室凭 FTC 课程 token 进入(demo 不支持)。":" Team meeting needs an FTC course token (not demos).")),void wn();P("learn: teammeeting");const e=un.listeners("line");un.removeAllListeners("line");let o="back";try{o=await k(Ht,w(un))}finally{for(const o of e)un.on("line",o)}return"menu"===o?void un.emit("line","menu"):(console.log(chalk.gray(tr()?" ↩ 回到课程。":" ↩ Back to the course.")),void wn())}if("status"===o||/^status\s+/.test(o)){const e=o.slice(6).trim().toLowerCase(),t="all"===e?"all":/^\d+$/.test(e)?Number(e):"current";if(xr){const[,e]=await Promise.all([Pr(),ne(Kt.id,Ht,!0)]);e&&Object.assign(Kt,e)}return _t(Kt,ln,{gate:br,gated:en,focus:t,posForSlot:Qe}),void wn()}if("sync"===o){P("learn: sync");const e=await ae(Ht);if(!e)return console.log(chalk.yellow(" ⚠ ")+chalk.white(tr()?"连不上服务器,进度保持本地。":"Server unreachable — keeping local progress.")),void wn();const o=ln.currentCard;return nt(ln,Kt.totalCards,e),et(ln),ln.currentCard>o?console.log(chalk.green(" ↩ ")+chalk.white(tr()?`已同步:${ln.cardsCompleted.length} 张卡完成,从第 ${ln.currentCard} 张继续`:`Synced: ${ln.cardsCompleted.length} cards done, resuming at card ${ln.currentCard}`)):console.log(chalk.green(" ✓ ")+chalk.white(tr()?"已与服务器同步,无新进度。":"Synced with the server — no new progress.")),void wn()}if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await ne(Kt.id,Ht,!0);return void(e?(Object.assign(Kt,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),qr()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),wn()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim(),t=de(Kt.cards);if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(Do().language||"en")+chalk.gray(" · ")+[...t,"en"].map(e=>chalk.bold.green(`lang ${e}`)).join(chalk.gray(" / "))),void wn();const n=e.toLowerCase().slice(0,2),r="en"===n||2===n.length&&t.includes(n),l=r?n:"en";return Uo({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),_n=null,kn=null,vn=null,Ln(),er=!1,Xn=!1,await Ur(),void wn()}const j=o.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(j&&!Rn&&!Wn&&null===Bn&&g.test(o)){const e=tr(),o=await u(Ht);if("ok"===o.kind)for(const t of h(o.log,e,"T0"===ye().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 wn()}if(j&&!Rn&&!Wn&&null===Bn){const e=(j[2]??"").trim(),o=tr(),t=`${a}–${s}`+(o?`,${i} 的倍数`:`, steps of ${i}`);if("off"===e||"stop"===e||"end"===e||"cancel"===e||"关"===e)return void(yn?.stop()||(console.log(chalk.gray(o?" 没有进行中的专注。开始一场:":" No focus session running. Start one: ")+chalk.bold.green("focus 30")),wn()));if(yn?.active)return console.log(chalk.yellow(" ⏱ ")+chalk.white(o?`专注进行中 · 还剩 ${yn.remainingMin()} 分钟`:`focus running · ${yn.remainingMin()} min left`)+chalk.gray(o?" · 提前结束:":" · end early: ")+chalk.bold.green("focus off")),void wn();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 wn();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 wn();if("ok"!==n.note){const t="min"===n.note?o?`最少 ${a}`:`min is ${a}`:"max"===n.note?o?`最多 ${s}`:`max is ${s}`:o?`取最近的 ${i} 的倍数`:`rounded to the nearest ${i}`;console.log(chalk.gray(o?` 你输入 ${e} → ${t},用 ${n.min}`:` you typed ${e} → ${t}, using ${n.min}`))}return yn?.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 wn()}if(Gt.has(o)){const e=Gt.get(o),t=Dt(Do()),n=e=>{const o=["normal","wide","wider","widest"].filter(o=>o!==e);return tr()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((tr()?"normal"===e?" 已是标准 64 列。":Yt()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Yt()} 列,上限 ${Ut(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Yt()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Yt()} cols, cap ${Ut(e)}). `)+n(e))),void wn()):(Uo({learnWidth:e,learnWide:"normal"!==e}),Wt(e),"normal"!==e&&Yt()<=64?(console.log(chalk.yellow(tr()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((tr()?` 设置已记住(${e},上限 ${Ut(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Ut(e)} cols) and applies once you widen the window. `)+n(e))),void wn()):(console.log(chalk.green(" ✓ ")+chalk.gray((tr()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Yt()} 列,上限 ${Ut(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Yt()} cols, cap ${Ut(e)}). `)+n(e))),_n=null,kn=null,vn=null,Ln(),er=!1,Xn=!1,await Ur(),void wn()))}if("sim"===o){const e=pr(ln.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=ee(te(import.meta.url)),o=[oe(e,"..","..","panda","mujoco-launcher.py"),oe(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(B(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 wn()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void wn())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=ln.currentCard,t=ln.bookmarks.includes(e),n="bookmark"!==o;return n?ln.bookmarks=ln.bookmarks.filter(o=>o!==e):t||ln.bookmarks.push(e),et(ln),n?console.log(t?chalk.gray(tr()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(tr()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(tr()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(tr()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void wn()}const E=me(o);if(E){const e="current"===E.target?ln.currentCard:E.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>Kt.cards.length))return console.log(chalk.yellow(tr()?` 本课共 ${Kt.cards.length} 张,请输 r 1–${Kt.cards.length} 或 r all。`:` This course has ${Kt.cards.length} cards. Try r 1–${Kt.cards.length} or r all.`)),console.log(),void wn();for(const o of fe(on,ir,e,tr(),Yt()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?on:on.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(on=on.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Rt(on),cr.push(le(Ht,{card_number:ln.currentCard,event_type:"viewed"},o).catch(()=>{}))),void wn()}if("e"===o||"memo"===o)return Sn=ln.currentCard,console.log(chalk.gray(tr()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(tr()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void wn();if("back"===o||"b"===o&&null===kn)return"view"===zn?(await Yr(),void wn()):"honors"===zn?(zn=null,qr(),void wn()):(ln.currentCard>1&&(ln.currentCard-=1),kn=null,vn=null,_n=null,et(ln),qr(),void wn());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!xr)return console.log(chalk.yellow(tr()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void wn();if(!e){const e=await ze(Ht),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(tr()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(tr()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(tr()?` 这台电脑上有 ${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(tr()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(tr()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(tr()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(tr()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(tr()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(tr()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(tr()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void wn()}if(/^\d{1,2}$/.test(e)){const o=await Fe(Ht,Number(e));return o.ok&&o.data?(ol(o.data),await Pr(),void wn()):(console.log(chalk.red(` ✗ ${o.message||(tr()?"关联失败":"Link failed")}`)),void wn())}const t=await Ge(Ht,e);return t.ok&&t.data?(ol(t.data),await Pr(),void wn()):(console.log(chalk.red(` ✗ ${t.message||(tr()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(tr()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void wn())}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(!xr)return console.log(chalk.yellow(tr()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void wn();if("duck"===kt()&&!Rn&&!Wn){console.log(chalk.gray(tr()?" 这条轨的检查点在 duck 子 REPL 里打:进入 duck → run 试跑 → submit 判分。":" This track's checkpoints are played in duck: duck → run → submit."));const e=null!==N();return e||M(un),await Ho([`from-card:${ln.currentCard}`]),e||M(null),void wn()}let e=Ir(ln.currentCard),t=null;const n="contest restart"===o||"restart"===o;if(n&&(!Rn||!wr||rl()))return console.log(chalk.gray(tr()?" 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 wn();if(n&&wr){const o=wr.phase,n=wr.data.slot,r=await Ue(Ht,o,n);if(!r.ok&&"no_active_session"!==r.code)return console.log(chalk.red(` ✗ ${r.message||"reset failed"}`)),void wn();ll(o,n),console.log(chalk.yellow(tr()?` 🔄 第 ${n} 组重开 — 全新计时、全新模板。`:` 🔄 Group ${n} restarted — fresh clock, fresh templates.`)+chalk.gray(tr()?" 只有计时内写的才算数:从头再写一遍,这正是练习。":" Only work written on the clock counts — write it again from scratch; that is the practice.")),wr=null,Rn=!1,wl=null,e=o,t=n}if("contest reset"===o&&Rn&&rl()){const e=wr.phase,o=wr.data.slot,t=await Ue(Ht,e,o);if(t.ok){console.log(chalk.yellow(tr()?" 已放弃本卡练习计时。回卡片后输入 practice <题号> 重新开始。":" Practice attempt abandoned. From the card, practice <n> starts a fresh one."));const t=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),n=oe(process.cwd(),"icoa-contest",`${Kt.id}-phase${e}-g${o}`);if(B(n))try{Z(n,`${n}-archived-${t}`),console.log(chalk.gray(tr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(tr()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}wr=null,Rn=!1,wl=null,qr()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void wn()}if("contest reset"===o){const o=await Ue(Ht,e);if(o.ok){console.log(chalk.yellow(tr()?` 已放弃本阶段(${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=oe(process.cwd(),"icoa-contest"),n=new RegExp(`^${Kt.id}-phase${e}-g(\\d+)$`),r=(B(t)?z(t):[]).map(e=>({name:e,m:n.exec(e)})).filter(({m:e})=>e&&Number(e[1])<nl).map(({name:e})=>e).sort();for(const e of r){const n=oe(t,e);try{Z(n,`${n}-archived-${o}`),console.log(chalk.gray(tr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(tr()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(tr()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),wr=null,Rn=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void wn()}const r=null!=t?String(t):/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(tr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Ht,e,r?parseInt(r,10):void 0);if(!l.ok||!l.data){if("no_contest"===l.code){const o=Kt.modules.find(o=>o.number===e)?.cardRange,t=!!o&&o[1]-o[0]+1>12,n=Ke(o?o[1]-o[0]+1:12);console.log(chalk.gray(t?tr()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(360 层第二阶段标准设计中)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (360-tier second-stage standard in design).`:rr?tr()?n.n>1?` 本阶段(${e})的 ${n.n} 场判分赛制作中 — 很快更新;赛场挂在卡 ${n.cards},${n.n} 场全过解锁下一阶段(本轨无 research)。`:` 本阶段(${e})的判分赛制作中 — 很快更新;赛场挂在卡 ${n.cards},通过即解锁下一阶段(本轨无 research)。`:n.n>1?` Phase ${e}'s ${n.n} judged arenas are in production — coming soon; they hang on cards ${n.cards} and all ${n.n} unlock the next phase (no research on this track).`:` Phase ${e}'s judged arena is in production — coming soon; it hangs on card ${n.cards} and passing it unlocks the next phase (no research on this track).`:tr()?` 本阶段(${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(` ✗ ${l.message||"contest unavailable"}`));return void wn()}const s=l.data,a=oe(process.cwd(),"icoa-contest",`${Kt.id}-phase${e}-g${s.slot}`);if(!s.resumed&&B(a)&&z(a).some(e=>/^sol-\d+\.[a-z]+$/.test(e))){const e=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);try{Z(a,`${a}-archived-${e}`),console.log(chalk.gray(tr()?" 📦 上一场的答题文件已归档: ":" 📦 Previous window archived: ")+chalk.gray(`${a}-archived-${e}`)),console.log(chalk.gray(tr()?" 新场次全新模板 — 计时窗口内写的才算数。":" Fresh window, fresh templates — only work done on the clock counts."))}catch{console.log(chalk.yellow(tr()?` ⚠ 归档失败(比赛照常): ${a}`:` ⚠ Could not archive (contest still fine): ${a}`))}}F(a,{recursive:!0});const i=wr&&wr.phase===e&&wr.data.slot===s.slot?wr.tried:new Set;wr&&wr.phase===e&&wr.data.slot===s.slot&&wr.data.attempt===s.attempt||(kr.clear(),vr.clear()),wr={phase:e,dir:a,data:s,tried:i},el(s,a),Ar(e,s.slot,a),Rn=!0,fl(),console.log(chalk.gray(tr()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(a));const c=s.problems.findIndex(e=>!s.solved.includes(e.id))+1||1,d=Hr&&!Kr?to:c;return console.log(chalk.white(tr()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${d}`)+chalk.gray(d===to?tr()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":tr()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void wn()}if(/^\/?(?:flow|walk)$/.test(o)){const e=pr(ln.currentCard),o=e&&"knowledge"===e.type?e.flow:void 0;return o&&0!==o.length?(xn(e,!1),void wn()):(console.log(chalk.gray(tr()?" 这张卡没有互动流程 — 有流程的卡片脚注会印 [flow]。":" No interactive walk on this card — cards that have one show [flow] in the footer.")),void wn())}const L=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(rr&&/^[1-9]$/.test(o)?`practice ${o}`:o);if(L){const e=pr(ln.currentCard),o=al(e);if(!o)return console.log(chalk.gray(tr()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void wn();if(!xr)return console.log(chalk.yellow(tr()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void wn();if(!L[1])return console.log(),dl(e),console.log(chalk.gray(tr()?" 用法: ":" Usage: ")+chalk.bold.green(tr()?"practice <题号>":"practice <n>")+chalk.gray(tr()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void wn();const t=parseInt(L[1],10);if(!Number.isInteger(t)||t<1||t>o.length)return console.log(chalk.yellow(tr()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void wn();const n=o[t-1],r=il(n),l=o.filter(e=>il(e)===r),s=l.indexOf(n)+1;return await(r||!rr?(async(e,o,t)=>{const n=Ir(e.number),r=nl+e.number;console.log(chalk.gray(tr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Ht,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(tr()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${l.message||"practice unavailable"}`)));const s=l.data;if(0===s.problems.length)return void console.log(chalk.gray(tr()?" 本卡练习题库是空的。":" This card practice set is empty."));const a=new Map(s.problems.map(e=>[e.id,e])),i=[];for(const e of o){const o=a.has(sl(e.py_id))?sl(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 s.problems)a.has(e.id)&&0===i.length&&i.push(e);s.problems=i;let c=Tr.get(r);c||(c=new Set,Tr.set(r,c));for(const e of s.solved)c.add(e);const d=oe(process.cwd(),"icoa-contest",`${Kt.id}-phase${n}-g${r}`);F(d,{recursive:!0});const g=wr&&wr.phase===n&&wr.data.slot===r?wr.tried:new Set;wr&&wr.phase===n&&wr.data.slot===r&&wr.data.attempt===s.attempt||(kr.clear(),vr.clear()),wr={phase:n,dir:d,data:s,tried:g},el(s,d),Rn=!0,wl=null,P(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(tr()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(tr()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(tr()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(d)),console.log(chalk.gray((tr()," ↩ "))+chalk.bold.green("back")+chalk.gray(tr()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),vl(String(Math.min(t,s.problems.length)))})(e,l,s):(async(e,o,t)=>{const n=Ir(e.number),r=nl+e.number;Fn=null,console.log(chalk.gray(tr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Ht,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(tr()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${l.message||"practice unavailable"}`)));const s=l.data;if(0===s.problems.length)return void console.log(chalk.gray(tr()?" 本卡练习题库是空的。":" This card practice set is empty."));const a=new Map(s.problems.map(e=>[e.id,e])),i=[];for(const e of o){const o=a.has(sl(e.py_id))?sl(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 s.problems)a.has(e.id)&&0===i.length&&!Gr(e)&&i.push(e);s.problems=i;let c=Tr.get(r);c||(c=new Set,Tr.set(r,c));for(const e of s.solved)c.add(e);Bn={card:e,phase:n,slot:r,data:s,idx:Math.min(Math.max(t,1),s.problems.length)-1,answers:[],tries:0},P(`learn-fillpractice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(tr()?` ⚡ 快速填空 — 第 ${e.number} 张卡`:` ⚡ Quick fill — card ${e.number}`)+chalk.gray(tr()?"(敲答案 → 自动判分 · 不计分)":" (type the blank → auto-judged · unscored)")),console.log(chalk.gray(tr()?` ⏱ 每次练习 ${s.duration_minutes} 分钟 · 剩 ${He(s.deadline)??"0:00"} · 到时敲 back 再 practice 重开`:` ⏱ ${s.duration_minutes}-minute practice window · ${He(s.deadline)??"0:00"} left · when it ends: back, then practice again`)),yl()})(e,l,s)),void wn()}if("submit"===l)return console.log(chalk.yellow(tr()?" 用法: ":" Usage: ")+chalk.bold.green(tr()?"submit <题号>":"submit <n>")+chalk.gray(tr()?" 例如 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)")),wr||console.log(chalk.gray(tr()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void wn();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const t=e[2];if(!wr)return console.log(chalk.yellow(tr()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void wn();const n=wr.data.problems,r=parseInt(o,10);if(Hr&&r===to)return console.log(chalk.gray(tr()?" 热身题不判分 — /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(tr()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(tr()?" 开始。":".")),void wn();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(tr()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void wn();const s=n.findIndex(e=>e.id===o)+1,a=t||oe(wr.dir,Vr(s,n[s-1]));let i;try{i=G(a,"utf-8")}catch{return console.log(chalk.red(tr()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void wn()}const c=Boolean(n[s-1]?.quiz),d=c?null:new W(Ht);d?.start();const g=kr.get(s),u=vr.get(s),h=g&&!X(g)?{...g,...u?{samples:u.list}:{},...u&&u.dropped>0?{samplesDropped:u.dropped}:{}}:void 0,p=await Be(Ht,wr.phase,o,i,wr.data.slot>=nl?wr.data.slot:void 0,h);if(d?.stop(),!p.ok||!p.data)return"no_active_session"===p.code&&wr.data.slot>=nl?ul(wr.data.duration_minutes):"no_active_session"===p.code?(ll(wr.phase,wr.data.slot),console.log(chalk.yellow(tr()?" ⏱ 时间到 — 这一场结束了,判分机已停表。":" ⏱ Time is up — this attempt is over; the judge stopped the clock.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(tr()?" 重开这一组:全新计时 + 全新模板(旧文件已归档)。只有计时内写的才算数 — 从头再写一遍,这正是练习。":" 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(tr()?" ↩ back 回卡片":" ↩ back returns to the card"))):(console.log(chalk.red(` ✗ ${p.message||"judging failed"}`)),console.log(chalk.gray(tr()?" 判分服务异常?敲 memo 一句话告诉我们 — 不打断比赛计时。":" Judge acting up? Type memo — one line reaches us, the clock is unaffected."))),void wn();const y=p.data;let m=!1;if(Zr()){const e=y;for(const o of(e.report??[]).slice(0,3))console.log(chalk.gray(` ${tr()?o:Bo(o)}`));e.note&&console.log(chalk.gray(` ${e.note}`)),"string"==typeof y.replay&&y.replay&&(m=Zo(y.replay))}if(m&&"AC"!==y.verdict&&!y.already_ac&&console.log(chalk.gray(" ▸ ")+chalk.bold.green("replay")+chalk.gray(tr()?" 看你输掉的那一局 —— 判分机把它送回来了(q 退出回放)":" watch the game you lost — the judge sent it back (q quits the player)")),y.already_ac)console.log(chalk.green(tr()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===y.verdict){if(c?console.log(chalk.bold.green(tr()?" ✅ 答对了!":" ✅ Correct!")):console.log(Mo("AC",{isZh:tr(),passed:y.passed_tests??y.total_tests??null,total:y.total_tests??null,ms:y.time_ms??null})),wr.data.solved.includes(o)||wr.data.solved.push(o),wr.tried.delete(o),rl()){let e=Tr.get(wr.data.slot);e||(e=new Set,Tr.set(wr.data.slot,e)),e.add(o);const t=await De({token:Ht,curriculumId:Kt.id,cardNumber:ln.currentCard}),n=t.ok?t.practiceBoard:null;if(n?.mine){const e=n.top[0],o=e&&!e.me?chalk.gray(tr()?` · 榜首 ${e.name||"Rank 1"} ${e.ac} AC`:` · leader ${e.name||"Rank 1"} at ${e.ac} AC`):chalk.bold.yellow(tr()?" · 全场第一!":" · phase leader!");console.log(chalk.white(tr()?` ⚔ Phase ${n.phase} Practice AC: `:` ⚔ Phase ${n.phase} practice AC: `)+chalk.bold.yellow(`${n.mine.ac}`)+chalk.gray(`/${n.problems_total}`)+chalk.gray(tr()?` · 第 ${n.mine.rank} 名`:` · rank ${n.mine.rank}`)+o)}}}else wr.tried.add(o),c?console.log(chalk.red(tr()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(tr()?" — 再选一次。":" — pick again.")):console.log(Mo(y.verdict,{isZh:tr(),passed:y.passed_tests??null,total:y.total_tests??null,failedTest:y.test??null,ms:y.time_ms??null})),Mn||(Mn=!0,console.log(chalk.gray(tr()?" 觉得题面有误或判分不对?敲 memo 一句话 — 不打断比赛计时。":" Statement wrong or judging looks off? Type memo — one line, the clock is unaffected.")));y.late&&console.log(chalk.yellow(tr()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const f=He(y.deadline||""),$=rl();if(console.log(chalk.white($?tr()?` 本卡练习: 已过 ${y.ac_count}/${y.n} 题(不计分)`:` Card practice: ${y.ac_count}/${y.n} solved (unscored)`:tr()?` 本组进度: 已过 ${y.ac_count} 题 · 过 ${y.need} 题过关(共 ${y.n} 题)`:` Group progress: ${y.ac_count} solved · ${y.need} needed to pass (${y.n} problems)`)+(f?chalk.gray(` · ⏱ ${f}`):"")),$&&!y.late&&y.ac_count>=y.n)console.log(chalk.bold.green(tr()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(tr()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!y.passed||y.late||$){if(!y.late){const e=n.findIndex(e=>!wr.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(tr()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Fr(n[e])}`))}}else{const e=Math.max(0,y.n-y.ac_count);if(0===e)console.log(chalk.bold.green(tr()?` 🎉 满分!${y.n}/${y.n} 全部 AC — 这组题你已经彻底拿下。`:` 🎉 Perfect! ${y.n}/${y.n} AC — you have completely cleared this group.`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(tr()?" 回到上一层(卡片),继续往下学;":" returns to the previous layer (the card) — keep going from there; ")+chalk.bold.green("contest")+chalk.gray(tr()?" 看本阶段其他赛场。":" lists the other arenas of this phase."));else{console.log(chalk.bold.green(tr()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")+chalk.yellow(tr()?` 还剩 ${e} 题 — 全部做完就是满分 ${y.n}/${y.n},别停在这里。`:` ${e} more to go — solve them all for a perfect ${y.n}/${y.n}, don't stop here.`));const o=n.findIndex(e=>!wr.data.solved.includes(e.id));o>=0&&console.log(chalk.gray(tr()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${o+1}`)+chalk.gray(` ${Fr(n[o])}`)+chalk.gray(tr()?" · ↩ back 回卡片":" · ↩ back returns to the card"))}await Pr()}return void wn()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>Kt.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Kt.totalCards}. Try: `)+chalk.bold.green("card 1")),void wn();const n=await Nr(t);return n?(console.log(n),void wn()):(ln.currentCard=t,kn=null,vn=null,_n=null,et(ln),qr(),void wn())}if(null!==_n&&["y","yes","n","no"].includes(o)){const e=pr(_n);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-or;yn?.noteCheck(n,r),st(ln,e.number),it(ln,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),et(ln);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),cr.push(le(Ht,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),_n=null,$r(),e.solution&&e.solution.length>0)return void wn();if(cl())return void wn();if(ln.currentCard<Kt.totalCards){const e=ln.currentCard,o=await Nr(e+1);if(o)return await Mr(e),console.log(o),void wn();ln.currentCard+=1,et(ln),await Mr(e)?Lr():qr(),wn()}else At(Kt,ln),mr(null,!1).then(()=>wn()),wn();return}}if(null!==kn&&["a","b","c","d"].includes(o)){const e=pr(kn);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(at(ln,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),st(ln,e.number),et(ln),pt(e,t,n,ln),cr.push(le(Ht,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),kn=null,n)if(ln.currentCard<Kt.totalCards){const e=await Nr(ln.currentCard+1);if(e)return console.log(e),void wn();ln.currentCard+=1,et(ln),qr()}else At(Kt,ln),mr(null,!1).then(()=>wn()),wn();else wn();return}}if(null!==vn){if("done"===o){const e=pr(vn);if(e&&"practical"===e.type)return ct(ln,e.number),st(ln,e.number),et(ln),mt(e),vn=null,void wn()}if("skip"===o)return st(ln,vn),et(ln),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),vn=null,void wn()}const q=rr&&"skip"===o&&null===kn&&null===vn&&null===_n&&null!==al(pr(ln.currentCard));if("ok"===o||"next"===o||"continue"===o||"n"===o||q){if(q){const e=ln.currentCard;jr.add(e),yn?.notePracticeSkipped(),console.log(chalk.gray(tr()?" ⚔ 本卡练习已跳过(有记录)。":" ⚔ Practice skipped for this card (recorded).")),le(Ht,{card_number:e,event_type:"practice_skipped"}).catch(()=>{})}else if(null===_n&&null===kn&&null===vn&&cl())return void wn();if(null!==kn)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void wn();if(null!==vn)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void wn();if(null!==_n)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void wn();const e=ln.currentCard,o=e<Kt.totalCards?await Nr(e+1):null;return o?(await Mr(e),console.log(o),void wn()):(ln.currentCard+=1,et(ln),ln.currentCard>Kt.totalCards?(At(Kt,ln),mr(null,!1).then(()=>wn())):await Mr(e)?Lr():qr(),void wn())}return null!==_n?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void wn()):null!==kn?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void wn()):null!==vn?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void wn()):("view"===zn?console.log(chalk.gray(tr()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(tr()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(tr()?" 回卡片":" to the card")):"honors"===zn?console.log(chalk.gray(tr()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(tr()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(tr()?" 回卡片":" 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 wn())};un.on("line",e=>{Zl(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.")),wn()})}),dn||un.on("close",async()=>{yn?.detach(),cr.length>0&&await Promise.race([Promise.allSettled(cr),new Promise(e=>setTimeout(e,5e3))]),hr?ur():process.exit(0)});const Hl=be(on,tr());if(Hl){const e=Math.max(40,Math.min(process.stdout.columns||80,96));console.log(),console.log(chalk.bold.cyan(` ╭${"─".repeat(Math.max(26,e-5))}╮`)),console.log(chalk.bold.cyan(" │ 💬 ")+chalk.bold.white(Hl)+chalk.bold.cyan(" │")),console.log(chalk.bold.cyan(` ╰${"─".repeat(Math.max(26,e-5))}╯`)),console.log()}try{qr();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0),(async()=>{for(let e=0;e<20&&!br;e++)await new Promise(e=>setTimeout(e,250));const e=fr();null!==e&&e>0&&e<=2&&(await $r(!0),wn())})();const o=yn?.attach(Ht,Kt.id,yr);"resumed"===o&&(console.log(chalk.yellow(" ⏱ ")+chalk.white(tr()?`专注进行中 · 还剩 ${yn.remainingMin()} 分钟 · 这条轨也算在内 · focus off 提前结束`:`focus running · ${yn.remainingMin()} min left · this course counts too · focus off to end early`)),console.log()),wn()}catch(e){if(process.env.ICOA_DEBUG&&console.error(e),zt("Could not render this card — the curriculum may be malformed."),dn){un.removeAllListeners("line"),pn();for(const e of gn)un.on("line",e);un.prompt()}else un.close();ur()}await gr}),qo.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await ne(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}