icoa-cli 2.19.626 → 2.19.627

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 R,runMicroduck as O}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 Re,submitPqs as Oe,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 Ro(){const e=qo();return e.ok&&e.cmd?{cmd:e.cmd}:null}const Oo=()=>Ro()?.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,forgetAdoptedSession as lt,updateStreak as st,markCardComplete as at,recordMCQ as it,recordCheck as ct,markPracticalComplete as dt,addAchievement as gt}from"../lib/learn-state.js";import{renderWelcome as ut,renderKnowledgeCard as ht,renderMCQCard as pt,renderMCQFeedback as yt,renderPracticalCard as mt,renderPracticalSuccess as ft,renderSimDemoCard as $t,renderMilestone as bt,renderArenaTaskCard as wt,renderArenaIntro as kt,learnCheckpointVerb as vt,renderComingSoonCard as _t,renderStatus as Ct,renderPhaseComplete as At,renderCurriculumComplete as xt,setLearnAiEnabled as Tt,setLearnFaqs as St,setLearnArenaLane as jt,setLearnArenaCards as Pt,setLearnDuckLane as It,setLearnFooterProfile as Et,setLearnShellLane as Nt,setLearnHometask as Mt,setLearnPracticeChips as Lt,setLearnPracticeCount as qt,setLearnHonorRanks as Rt,setLearnPqsViewCards as Ot,setLearnReplies as Wt,setLearnWidth as Dt,resolveLearnWidth as Ut,learnWidthCap as Yt,learnW as Bt,renderHonorWall as Ft,wrapMixed as zt}from"../lib/learn-render.js";import{printError as Gt}from"../lib/ui.js";const Zt=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","widest"],["wide max","widest"]]);function Ht(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 Kt=qo.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Kt)){const{runSprint:e}=await import("./sprint.js");return void await e()}if(R(qo))return void await O();let Jt=null;const Qt=/^[A-Z0-9]+DEMO01$/i.test(Kt),Xt=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Kt);let Vt=!1,en=3,on=!1,tn=[],nn=null,rn=-1,ln=Promise.resolve([]);if(Qt)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),ln=ce(Kt),Jt=await ne(Kt,Kt,!0);else if(Xt){console.log(),console.log(chalk.gray(" Validating token..."));let e=await re(Kt);if(!e.ok){const o=Ne(Kt);if(o!==Kt){const t=await re(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Kt} → ${o}`)),e=t,Kt=o)}}if(!e.ok){if(Gt(`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.")),lt(Kt)&&(console.log(),console.log(chalk.gray(" It belongs to your other computer, so it is no longer listed on this one.")));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 🐼"):Qt?"":chalk.magenta(" · 🐼 AI tutor"))),Vt=!0===e.aiEnabled,en=e.aiBasicPerCard??3,on=!0===e.gated,tn=e.replies??[],nn=e.hometask??null,ln=ce(Kt),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Jt=await ne(e.curriculumId||"LEARNDEMO01",Kt,!0),!Jt)return Gt(`Could not open a learn curriculum for token '${Kt}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Kt}`)+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 ${Kt}`)+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(!Jt){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Gt(`Could not reach the learn server to open ${Kt}.`),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 ${Kt}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Gt(`Unknown learn token: ${Kt}`),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 sn=Vo(),an=!1,cn=!1;try{if(sn&&sn.token===Kt)st(sn),cn=!0;else{const e=rt(Kt),o=e?.adoptedFromServer?null:e;if(o)sn=o,sn.totalCards=Jt.totalCards,st(sn),cn=!0;else{const e=await ae(Kt),o=e?tt(Kt,Jt.id,Jt.totalCards,e):null;o?(sn=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()):(sn=ot(Kt,Jt.id,Jt.totalCards),an=!0)}}if(cn){const e=await ae(Kt);if(e){const o=sn.currentCard;nt(sn,Jt.totalCards,e),sn.currentCard>o&&(console.log(chalk.green(" ↩ ")+chalk.white((Do().language||"en").toLowerCase().startsWith("zh")?`已同步手机进度:${sn.cardsCompleted.length} 张卡完成,从第 ${sn.currentCard} 张继续`:`Synced your phone progress: ${sn.cardsCompleted.length} cards done, resuming at card ${sn.currentCard}`)),console.log())}}et(sn),ut(Jt,sn,an),function(e){if(!e)return;const o=(Do().language||"en").toLowerCase().startsWith("zh"),t="T0"===ye().tier;Ht(he(e,o,Bt(),t),!!e.completedAt)}(nn)}catch{return Gt("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 ${Kt}`)+chalk.gray(".")),void console.log()}const dn=N(),gn=null!==dn,un=gn?dn.listeners("line").slice():[];gn&&dn.removeAllListeners("line");const hn=gn?dn:o({input:process.stdin,output:process.stdout,terminal:!0}),pn=gn?hn.prompt:null;gn&&(hn.prompt=e.prototype.prompt);const yn=()=>{gn&&pn&&(hn.prompt=pn)};let mn=null,fn=!1,$n=!1,bn=null,wn=!1;const kn=()=>{hn.closed||(hn.setPrompt(Jn?chalk.bold.green(`icoa ${D()}> `):Un?chalk.bold.magenta(zl()):Dn?chalk.bold.magenta("icoa py> "):Wn?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Rn?"icoa learn ai> ":"icoa learn> ")),hn.prompt(),mn?.onPromptIdle())};let vn=null,_n=null,Cn=null,An=null;const xn=new Set,Tn=(e,o)=>{const t=e.flow??[];0!==t.length&&(o&&(console.log(chalk.yellow(" 🧭 ")+chalk.white(nr()?"这张卡是互动流程 —— 现在开始。选错不扣分,墙上写着为什么;":"This card is an interactive walk — starting now. Wrong turns cost nothing; the wall says why;")),console.log(chalk.gray(nr()?" 每一步在 icoa learn> 后面敲答案。back 退回卡片 · flow 再走一遍。":" type each answer after icoa learn>. back returns to the card · flow walks it again.")),console.log()),An=new ge({steps:t,zh:nr(),cardNumber:e.number,print:e=>console.log(e)}),"done"===An.start()&&Sn("done"))},Sn=e=>{if(!An)return;const o=An.records(),t=An.cardNumber;An=null;for(const e of o)dr.push(se(Kt,Jt.id,t,e).catch(()=>{}));if("done"!==e)return console.log(chalk.gray(nr()?" ↩ 已退出流程,回到卡片。":" ↩ Left the walk — back on the card.")),void console.log();const n=null!==Cn?yr(Cn):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(nr()?" ✅ 流程走完。":" ✅ Walk complete.")+chalk.cyan(nr()?" 🤔 现在回答卡片的检查题(输 y 或 n):":" 🤔 Now the card check (type y or n):")),console.log(chalk.white(` ${t}`)),console.log(chalk.gray(nr()?" (flow 再走一遍)":" (flow walks it again)"))}else console.log(chalk.gray(nr()?" ✅ 流程走完 — 敲 ok 下一张,或 flow 再走一遍。":" ✅ Walk complete — type ok for the next card, or flow to walk it again."));console.log()};let jn=null,Pn=[],In=!1,En=null;const Nn=/^(quit|exit|q|back|b|menu|home|contest(\s+(\d+|reset))?)$/i;let Mn=null,Ln=!1;const qn=()=>{En&&clearTimeout(En),En=null,Pn=[],In=!1,jn=null,Mn=null};let Rn=!1,On=!1,Wn=!1,Dn=!1,Un=!1,Yn=null,Bn="card",Fn=null,zn=null,Gn=null,Zn=!1,Hn=0,Kn=!1,Jn=!1;const Qn=new Map,Xn=()=>{let e=Qn.get(sn.currentCard);return e||(e=[],Qn.set(sn.currentCard,e)),e};let Vn=!1;const er=new Set;let or=!1,tr=0;const nr=()=>(Do().language||"en").toLowerCase().startsWith("zh");Tt(Vt||!Qt,Vt),Dt(Ut(Do())),Ot(er);const rr=new Map;Rt(rr),Wt(tn),Mt(nn);const lr="fill"===Jt.practiceMode,sr=Boolean(Jt.shellLane);Nt(sr);const ar=Jt.mobCheckpoints;jt("battleai"===Jt.practiceMode||Array.isArray(ar)),Pt("battleai"===Jt.practiceMode?[]:(ar??[]).map(e=>Number(e.card)).filter(e=>e>0).map(e=>{const o=Jt.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)),It(Array.isArray(Jt.duckCheckpoints)),Et("minimal"===Jt.footerProfile?"minimal":"full"),Lt(e=>{const o=yr(e),t=o?il(o):null;if(!t)return null;const n=Sr.get(rl+e);return t.map((e,o)=>`[${o+1}]${n?.has(al(e.py_id))||n?.has(e.py_id)?"✅":"⬜"}`).join(" ")});const ir=e=>{const o=yr(e),t=o?il(o):null;if(!t)return null;const n=Sr.get(rl+e);return{solved:t.filter(e=>n?.has(al(e.py_id))||n?.has(e.py_id)).length,total:t.length}};qt(ir);const cr=await ln;St(cr);const dr=[];let gr=null;const ur=new Promise(e=>{gr=e}),hr=()=>{const e=gr;gr=null,e?.()},pr="1"===process.env.ICOA_LEARN_EMBEDDED,yr=e=>Jt.cards.find(o=>o.number===e);mn=c();const mr={isZh:nr,canInterrupt:()=>!(wn||On||Rn||Wn||Dn||Jn||null!==Fn||null!==jn||null!==Gn),lineEmpty:()=>!hn.line,clearLine:()=>{try{process.stdout.write("\r")}catch{}},prompt:kn,currentCard:()=>sn.currentCard};p(()=>{const e=[],o=mn?.footerLine();o&&e.push(o);const t=$r();return null!==t&&t>0&&t<=2&&e.push(nr()?`🎁 还差 ${t} 项 · credits 看路线`:`🎁 ${t} to go · credits shows the road`),e.length?e.join("\n "):null});const fr=async(e,o)=>{const t=nr();if(Qt)return void console.log(chalk.gray(t?"故事属于正式 learn token。":" Stories belong to full learn tokens."));const n=await v(Kt,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===Jt.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(Jt,sn,wr,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===Jt.id?Jt.name:l.curriculum_id,l.curriculum_id===Jt.id?{longestStreak:sn.longestStreak,bookmarks:sn.bookmarks?.length??0}:{},t,Bt(),"T0"===ye().tier);console.log(),console.log(chalk.gray(t?" (回车跳到结尾)":" (Enter skips to the end)")),fn=!0,$n=!1;try{await S(s,()=>$n)}finally{fn=!1}if(l.curriculum_id===Jt.id&&!l.credits?.completed){for(const e of T(Jt,sn,wr,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()},$r=()=>{if(!sn||sn.creditsShownAt||Qt||!wr)return null;const e=x(Jt,sn,wr);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])},br=async(e=!1)=>{if(!sn||sn.creditsShownAt||Qt)return;const o=x(Jt,sn,wr);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(wr&&t>0&&t<=2&&(e||sn.creditsTeasedLeft!==t)){sn.creditsTeasedLeft=t,et(sn);const e=nr(),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(Jt,sn,wr,e))console.log(o);console.log()}return}sn.creditsShownAt=(new Date).toISOString(),et(sn),await fr(null,!1),kn()};let wr=null,kr=null;const vr=new Map,_r=new Map;let Cr=null;const Ar=(e,o)=>Cr?.[`${Jt.id}:${e}:${o}`]??null;q("contest-cells.json").then(e=>{Cr=e?.map??null;for(const[e,o]of Object.entries(Cr??{}))e.startsWith(`${Jt.id}:`)&&q(o)});const xr=(e,o,t)=>{const n=Ar(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},Tr=!Kt.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Kt),Sr=new Map,jr=new Map,Pr=new Set,Ir=async()=>{if(!Tr)return;const e=await Ze(Kt);if(e.ok&&e.data){wr=e.data;for(const o of e.data.practice??[]){let e=Sr.get(o.slot);e||(e=new Set,Sr.set(o.slot,e));for(const t of o.solved)e.add(t)}br()}},Er=e=>{const o=Jt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Nr=e=>{if(!on||!wr)return null;const o=Er(e);if(o<=wr.unlocked_through_phase)return null;const t=wr.phases.find(e=>e.phase===wr.unlocked_through_phase),n=[chalk.yellow(nr()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${wr.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${wr.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(nr()?` ⚔ 练习赛 ${wr.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${wr.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(nr()?` ⚖ 判分赛: 最好 ${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(nr()?"、":", "),r=e.length>8?nr()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:nr()?" 张":"";n.push(chalk.gray(nr()?` ✓ 逐卡自测: ${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(nr()?` ⭐ 提问研究: ${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")},Mr=async e=>on?null===Nr(e)?null:(await Ir(),Nr(e)):null;Tr&&await Ir();const Lr=async e=>{const o=Jt.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=Jt.modules.find(e=>e.number===o.number+1);let n;if(Vt){const e=await Me({token:Kt,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}Tr&&await Ir();const r=wr?.phases.find(e=>e.phase===o.number);return At(Jt,sn,o,t,n,r),!0},qr=()=>{or=!0,console.log(chalk.gray(nr()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Rr=()=>{Gn=null;const e=yr(sn.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();mn?.noteCardShown(e.number,sn.cardsCompleted.includes(e.number));const o=ve($e(tn,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(nr()?`你有 ${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(` ${nr()?"你写的":"You wrote"}: ${(e.myText??"").slice(0,70)}${(e.myText?.length??0)>70?"…":""}`)),console.log(chalk.yellow(` 🐼 ${nr()?"回复":"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(" "+(nr()?"看完继续:next 去下一张卡;e 可再报告一条。":"Continue: type next, or press e to report again."))),console.log(),tn=tn.map(e=>o.some(o=>o.id===e.id)?{...e,seen:!0}:e)}switch(e.type){case"knowledge":{const o=lr&&Boolean(sn.checkResults?.[String(e.number)])&&e.check?{...e,check:void 0}:e;ht(o,Jt),o.check?(Cn=e.number,tr=Date.now()):(at(sn,e.number),et(sn));break}case"mcq":pt(e,Jt),vn=e.number;break;case"practical":mt(e,Jt),_n=e.number;break;case"sim_demo":$t(e,Jt),at(sn,e.number),et(sn);break;case"milestone":bt(e,Jt),gt(sn,e.badge),at(sn,e.number),et(sn);break;case"arena_task":wt(e,Jt),at(sn,e.number),et(sn);break;case"coming_soon":_t(e,Jt),at(sn,e.number),et(sn)}Or(e.number),gl(e),"knowledge"===e.type&&e.flow&&e.flow.length>0&&(xn.has(e.number)?(console.log(chalk.yellow(" 🧭 ")+chalk.gray(nr()?"敲 flow 再走一遍这张卡的互动流程。":"type flow to walk this card again.")),console.log()):(xn.add(e.number),console.log(),Tn(e,!0)))},Or=e=>{if(!Tr)return;const o=Jt.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=wr?.phases.find(e=>e.phase===o.number),s=l?.contest?.slots?.find(e=>e.slot===n),a=()=>{sn.arenaIntroShownAt||(kt(o.cardRange[1]-o.cardRange[0]+1),sn.arenaIntroShownAt=(new Date).toISOString(),et(sn))};if(!wr){const e="═".repeat(Bt()),t=chalk.bold.yellow(" ║ "),r=vt();return a(),console.log(chalk.bold.yellow(` ╔${e}`)),console.log(t+chalk.bold.white("⚔ "+(nr()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(nr()?" 成绩暂时取不到":" scoreline unavailable")),console.log(t+chalk.white(nr()?"这张卡下面有一场判分赛 — 服务器这会儿没答上来,所以显示不了你的成绩。":"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(nr()?" 照常可以开赛(开赛是另一次请求) · ":" still opens it (starting is a separate call) · ")+chalk.gray("▸ ")+chalk.bold.green("ok")+chalk.gray(nr()?" 继续学习":" 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(Bt()),l=chalk.bold.yellow(" ║ ");return console.log(chalk.bold.yellow(` ╔${t}`)),console.log(l+chalk.bold.white("⚔ "+(nr()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(nr()?" 制作中":" in production")),console.log(l+chalk.white(nr()?"这里以后有一场判分赛 — 很快更新。":"A judged arena lands here — coming soon.")),console.log(l+chalk.gray(nr()?r.n>1?`每 4 张卡一场:卡 ${r.cards},本阶段共 ${r.n} 场,全过解锁下一阶段。${lr?"(本轨无 research)":""}`:`本阶段一场:卡 ${r.cards},过了解锁下一阶段。${lr?"(本轨无 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.${lr?" (no research on this track)":""}`:`One this phase — card ${r.cards}; passing it unlocks the next.${lr?" (no research on this track)":""}`)),console.log(l+chalk.gray(nr()?"▸ 现在什么都不用做 — 敲 ":"▸ Nothing to do yet — type ")+chalk.bold.green("next")+chalk.gray(nr()?" 继续读卡。":" 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?nr()?` · 用时 ${r}`:` · in ${r}`:"")+(l?` · ${l}`:"")},c=s.perfect_runs??[],d=!!s.best&&(s.best.ac??0)>0,g=chalk.bold.yellow(" ║ "),u="═".repeat(Bt());if(console.log(chalk.bold.yellow(` ╔${u}`)),console.log(g+chalk.bold.white(`⚔ ${nr()?(()=>{const t=(ar??[]).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(nr()?" ✅ 已通过":" ✅ passed"):"")),!s.passed){if(nr()?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(nr()?`${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?nr()?`(${e})`:` (${e})`:"";console.log(g+chalk.cyan(nr()?`🔗 你另一个 token${o}已做过这组的 ${s.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens${o} solved ${s.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(nr()?" 带过来(现在不做也行)":" to carry them over (or skip)"))}1!==o.number||lr||console.log(g+chalk.gray(nr()?"✍ 第一次用 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(nr()?"满分":"Perfect",s.n,e.ms,e.ts)));else d&&console.log(g+chalk.yellow(i(nr()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));3===n&&l?.leader&&console.log(g+chalk.white(nr()?`🏅 本 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((nr()," — "))+chalk.bold.green("/honors")+chalk.gray(nr()?" 看你的位置":" shows where you stand"));const h=vt();console.log(g+chalk.gray("▸ ")+chalk.bold.green(h??`contest ${n}`)+(h?chalk.gray(nr()?` 进竞技场(${"battle"===h?"play":"run"} 试跑 → submit 判分) · `:` enter the arena (${"battle"===h?"play":"run"} → submit) · `):s.passed?chalk.gray(nr()?" 再战刷成绩 · ":" race it again · "):chalk.gray(nr()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(nr()?" 继续学习":" keep going"):chalk.gray(nr()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),!h&&(c.length>0||d)&&console.log(g+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(nr()?" 日后回来整阶段重做 · 全新计时+模板(旧文件自动归档)":" come back later and redo the whole phase · fresh clock + templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${u}`)),console.log()},Wr=()=>{Kt.endsWith("DEMO01")?console.log(chalk.yellow(nr()?" 🐼 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(nr()?" /submit 评分、荣誉榜与 /recall 是 🐼 AI 高级 token 的功能。":" Prompt grading (/submit), the honors board and /recall are premium 🐼 AI-token features.")),console.log(chalk.gray(nr()?` 你的 token 可以用 /ai 向熊猫导师提问(每卡每天 ${en} 问);要开通高级功能找领队 / 协调人。`:` Your token can still ask the tutor with /ai (${en} questions per card per day); ask your leader / coordinator for a premium token.`))),console.log()},Dr=async(e,o)=>{if(Qt)return void Wr();mn?.noteAi(Vt&&"deep"===o),On=!0;const t=nr()?"🐼 熊猫导师思考中…":"🐼 Panda tutor is thinking…",n=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];let r=null;const l=()=>{r&&(clearInterval(r),r=null,process.stdout.write("\r"))},s=()=>nr()?` (本卡今天的 ${en} 个问题已用完 — 24 小时后再问,或先去下一张卡)`:` (this card's ${en} 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 Re({token:Kt,cardNumber:sn.currentCard,question:e,mode:o,history:Xn().slice(-8),lang:nr()?"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(Vt?nr()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)":nr()?" (被判定与本卡主题无关 — 不会回答,也不计入本卡的次数)":" (judged unrelated to this card — not answered, and it does not count toward this card's questions)"))):(Xn().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(` (${nr()?"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(nr()?" (本卡今天还可以问最后 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||(nr()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Cn&&console.log(chalk.gray(nr()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{l(),On=!1}},Ur=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Yr=async()=>{Wn&&kr?kl?_l(kl):$l():Gn?await Br():Rr()},Br=async()=>{On=!0;try{console.log();const e=await De({token:Kt,curriculumId:Jt.id,cardNumber:sn.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(nr()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(Tr&&(await Ir(),(e=>{const o=Jt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const[t,n]=o.cardRange,r=sn.checkResults||{};let l=0,s=0,a=0;for(let e=t;e<=n;e++){const o=yr(e);null!=o?.check&&a++;const t=r[String(e)];t&&(l++,t.correct&&s++)}console.log(chalk.bold.white(nr()?` 🧭 Phase ${o.number} 进度 — ${o.name}(卡 ${t}-${n})`:` 🧭 Phase ${o.number} progress — ${o.name} (cards ${t}-${n})`)),console.log(chalk.gray(nr()?" 理解检查: ":" comprehension: ")+chalk.white(`${s}/${l}`)+chalk.gray(nr()?` 答对 · ${a-l} 张未作答`:` correct · ${a-l} unanswered`));const i=wr?.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(nr()?`未开始 · ${e.n} 题 · 过 ${e.need} 题`:`not started · ${e.n} problems · AC ${e.need}`):chalk.yellow(nr()?`最好 ${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(` ⚔ ${nr()?"练习赛":"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=ir(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(nr()?" 卡片练习: ":" practice: ")+chalk.white(`${d}/${g}`)+chalk.gray(nr()?` 卡全完成 · ${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(nr()?" 卡号:已过/共 — 绿 全完成 · 黄 做了一部分 · 灰 未碰":" card:solved/total — green done · yellow partial · gray untouched"))}console.log()})(sn.currentCard)),console.log(chalk.bold.white(nr()?` 🏆 本卡实时 Top-3 — 第 ${sn.currentCard} 张`:` 🏆 Live top-3 — card ${sn.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(nr()?" (你)":" (you)"):""))}else console.log(chalk.gray(nr()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));if(e.mine?(rr.set(sn.currentCard,e.mine.rank),console.log(chalk.white(nr()?" 你: ":" You: ")+chalk.bold.yellow(nr()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(nr()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Vt&&console.log(chalk.gray(nr()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ft({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),e.phaseBoard){const o=e.phaseBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(nr()?` 🏅 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(nr()?" (还没有人有研究总分 — 第一个 /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(nr()?`(${e.cards}/${o.cards_in_phase} 卡)`:` (${e.cards}/${o.cards_in_phase} cards)`)+(e.me?chalk.bold.magenta(nr()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(nr()?` 总分 ${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(nr()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.total}`)+chalk.gray(nr()?`(${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&&Vt&&console.log(chalk.gray(nr()?" 你: 还未计入 — /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(nr()?` ⚔ 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(nr()?" (还没有人 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(nr()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(nr()?` 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(nr()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.ac} AC`)+chalk.gray(nr()?` · 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` · rank ${o.mine.rank} of ${o.mine.entrants}`)):o.mine||console.log(chalk.gray(nr()?" 你: 还未计入 — 在有 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(nr()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(nr()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(nr()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Gn="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(nr()?" 返回卡片":" returns to the card")),console.log()}finally{On=!1}},Fr=()=>(Do().language||"en").slice(0,2).toLowerCase(),zr=e=>{const o=e[`title_${Fr()}`];return"string"==typeof o&&o||e.title},Gr=e=>{const o=e[`statement_${Fr()}`];return"string"==typeof o&&o||e.statement},Zr=e=>"mob-match"===e?.kind,Hr=()=>!!kr&&kr.data.problems.some(e=>Zr(e)),Kr=lo(Jt.id);let Jr=!1;const Qr=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of zt(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Xr={cpp:"cpp",java:"java",go:"go"},Vr=e=>e?.lang&&Xr[e.lang]?e.lang:"python",el=(e,o)=>{const t=Vr(o);return`sol-${e}.${"python"===t?"py":Xr[t]}`},ol=(e,o)=>{const t=[...Kr?[{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=Kr&&l===to,a=s?`══ ${t.title} ══`:`══ ${e.title||"PY Arena"} · ${t.title} ══`;for(const e of["py",...Object.values(Xr)]){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,el(l,t));if(B(c))return;const d=[s?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Qr(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||Zr(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 zt(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(???)",""):Zr(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"===Vr(t)?d:d.map(e=>e.startsWith("#")?`//${e.slice(1)}`:e),h=Zr(t)&&nr()&&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(nr()?` 📦 本组题目已更换 — ${r} 个旧题答题文件已归档为 *.archived-${n},新题文件已就位`:` 📦 This group's problems changed — ${r} old solution file(s) archived as *.archived-${n}, fresh files written`))},tl=e=>{console.log(),console.log(chalk.bold.green(nr()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(nr()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},nl=e=>e.id===oo?Jr?"✅":"⬜":kr.data.solved.includes(e.id)?"✅":kr.data.carried?.includes(e.id)?"✅↗":kr.tried.has(e.id)?"❌":"⬜",rl=100,ll=()=>!!kr&&kr.data.slot>=rl,sl=(e,o)=>{const t=oe(process.cwd(),"icoa-contest",`${Jt.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(nr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${n}`))}catch{console.log(chalk.yellow(nr()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (restart still fine): ${t}`))}},al=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,il=e=>{const o=e?.practice;if(!o||!Array.isArray(o.problems)||0===o.problems.length)return null;const t=o.problems.filter(e=>cl(e));return[...o.problems.filter(e=>e.is_signature&&!cl(e)),...o.problems.filter(e=>!e.is_signature&&!cl(e)).sort((e,o)=>(e.difficulty??0)-(o.difficulty??0)||(e.order??0)-(o.order??0)),...t]},cl=e=>"mob-match"===e.kind,dl=()=>{if(!lr)return!1;const e=yr(sn.currentCard),o=e?il(e):null;if(!e||!o||Pr.has(e.number))return!1;const t=rl+e.number,n=Sr.get(t),r=jr.get(t),l=o.map((e,o)=>{return t=e.py_id,Boolean(n?.has(al(t))||n?.has(t)||r?.has(al(t))||r?.has(t))?0:o+1;var t}).filter(e=>e>0);return 0!==l.length&&(console.log(chalk.yellow(nr()?` ⚔ 这张卡还有 ${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(nr()?" 开始,或 ":" to start, or ")+chalk.bold.yellow("skip")+chalk.yellow(nr()?" 跳过本卡练习。":" to skip this card's practice.")),!0)},gl=e=>{const o=il(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=Sr.get(rl+e.number);console.log(chalk.bold.yellow(nr()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(nr()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(al(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))));cl(e)?console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ⚔ ${chalk.bold.white(nr()?"对局":"battle")}`+chalk.gray(nr()?` — 改一行 · 打一局 · 看回放 · 判分 (敲 ${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(nr()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},ul=e=>e.split("\n").filter(e=>!e.trim().startsWith("#")).join("\n").split("____").length-1,hl=e=>{console.log(chalk.yellow(nr()?` ⏱ 每次练习 ${e} 分钟,这次的时间到了。`:` ⏱ Each practice window is ${e} minutes — this one has run out.`)),console.log(chalk.gray(nr()?" 敲 ":" Type ")+chalk.bold.green("back")+chalk.gray(nr()?" 回卡片,再敲 ":" for the card, then ")+chalk.bold.green("practice 1")+chalk.gray(nr()?" 重新开始(重新计时)。":" to restart with a fresh clock."))},pl=()=>Fn?Fn.data.problems[Fn.idx]??null:null,yl=()=>{const e=pl();if(!Fn||!e)return;const o=ul(e.starter??""),t=Fn.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(nr()?` 空${t}/${o}`:` blank ${t}/${o}`)+chalk.gray(" · ")+chalk.white(n)),console.log(chalk.gray(nr()?" ▸ 敲答案后回车(back 回卡片)":" ▸ type the answer, press Enter (back = card)"))},ml=()=>{const e=pl();if(!Fn||!e)return;const o=zr(e);console.log(),console.log(chalk.bold.yellow(` ⚡ ${nr()?"练习":"Practice"} ${Fn.idx+1}/${Fn.data.problems.length} · ${o}`));const t=(Gr(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(),yl()},fl=()=>{if(Fn){if(Fn.idx+1<Fn.data.problems.length)return Fn.idx+=1,Fn.answers=[],Fn.tries=0,void ml();console.log(chalk.bold.green(nr()?" 🎉 本卡练习全部完成!":" 🎉 Card practice complete!")+chalk.gray(nr()?" ok 进下一张卡。":" ok moves on to the next card.")),Fn=null,zn=null,Rr()}},$l=()=>{const e=kr.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>=rl?e.slot-rl:null,s=e.problems.find(e=>Zr(e)),a=nr()&&s?.title_zh?`检查点 · 卡 ${s.card} · ${s.title_zh}`:e.title||"PY Arena";if(console.log(chalk.bold.yellow(` ⚔ ${a}`)+chalk.gray(null!=l?nr()?` · 第 ${l} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${l} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:nr()?` · 第 ${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(nr()?" ⏱ 已超时 — 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(nr()?`(共 ${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(nr()?` 🎉 满分 ${e.n}/${e.n} — 本组全部拿下!`:` 🎉 Perfect ${e.n}/${e.n} — every problem cleared!`)+chalk.gray(nr()?" ↩ back 回卡片":" ↩ back returns to the card"):chalk.green(nr()?" 🏁 已过关":" 🏁 passed")+chalk.yellow(nr()?` · 还剩 ${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(nr()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" 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?nr()?`(${o})`:` (${o})`:"";console.log(chalk.cyan(nr()?` 🔗 你另一个 token${t}已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens${t} solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(nr()?" 带过来,不必重做":" 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(nr()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(nr()?"不够就 ":"Short on time? ")+chalk.bold.green("contest restart")+chalk.gray(nr()?" 满血重开本组。":" restarts this group fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(nr()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),Kr&&(console.log(chalk.gray(" 0 ")+nl(eo)+chalk.gray(` ${zr(eo)}`)+chalk.gray(nr()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+nl(e)+(e.gpu?chalk.magenta(" ⚡"):"")+chalk.white(` ${zr(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(nr()?" ⚡ GPU 开 ✅":" ⚡ GPU on ✅")+chalk.gray(nr()?" — /submit 一道 ⚡ 题,就在真 GPU 上跑":" — /submit a ⚡ rung and it runs on a real GPU right now")):"booting"===o?console.log(chalk.bold.yellow(nr()?" ⚡ GPU 开机中…":" ⚡ GPU booting…")+chalk.gray(nr()?" — 约 3–5 分钟,稍后重新 /submit":" — takes ~3–5 min; retry /submit shortly")):console.log(chalk.bold.gray(nr()?" ⚡ GPU 关":" ⚡ GPU off")+chalk.gray(nr()?" — 直接 /submit 一道 ⚡ 题会自动开机(约 3–5 分钟),之后重新 /submit":" — /submit a ⚡ rung to auto-boot the GPU (~3–5 min), then /submit again"))}Ar(kr.phase,e.slot)&&(console.log(),console.log(chalk.gray(" ✍ ")+chalk.bold.green("cells")+chalk.gray(nr()?" 在 notebook 里探索本场数据(引导走查 · 真图) — 不判分,判分仍走 /submit":" explore this lab in a notebook (guided walkthrough · real figures) — ungraded; judging stays /submit"))),console.log(),bl()},bl=()=>{console.log(chalk.gray(Hr()?nr()?" /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)":nr()?" /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(nr()?"/syntax <词>":"/syntax <word>")+chalk.gray(nr()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(nr()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(nr()?" 返回课程":" returns to the lesson")),console.log(chalk.gray(nr()?" memo 报告题面/判分问题 — 不打断比赛计时":" memo reports a statement/judging problem — the clock is unaffected")),console.log(chalk.gray(" ")+chalk.bold.green("contest restart")+chalk.gray(nr()?" 超时/坏场时重开本组(全新计时+模板) · ":" time up or broken attempt → this group again (fresh clock + templates) · ")+chalk.bold.green("contest reset")+chalk.gray(nr()?" 日后回来整阶段重做":" come back later and redo the whole phase")),console.log()},wl=e=>{const o=parseInt(e,10),t=kr.data.problems;if(o===to&&Kr)return{p:eo,n:to};const n=Kr?to:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(nr()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),Kr&&console.log(chalk.gray(nr()?" 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 kl=null,vl=!1;const _l=e=>{const o=wl(e);if(!o)return;const{p:t,n:n}=o;kl=String(n),console.log(),console.log(chalk.bold.white(` ${nl(t)} ${zr(t)}`)),console.log();for(const e of Gr(t).split("\n"))if(e.trim())for(const o of zt(e,Bt()+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(nr()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(nr()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(Zr(t)){const e=Array.isArray(t.crit)?t.crit:[],o=Number(e[2]??10),r="mined"===e[0]?nr()?`采矿 ≥ ${e[1]}`:`mine ≥ ${e[1]} opal`:"winrate"===e[0]?nr()?`${o} 局赢 ≥ ${Math.round(100*Number(e[1]))}%`:`win ≥ ${Math.round(100*Number(e[1]))}% of ${o} games`:"";console.log(),console.log(chalk.gray(nr()?" 对手 ":" vs ")+chalk.white(String(t.opp??"?"))+chalk.gray(nr()?" · 地图 ":" · map ")+chalk.white(String(t.map??"?"))+chalk.gray(nr()?" · 回合 ":" · turns ")+chalk.white(String(t.turns??"?"))+(r?chalk.gray(nr()?" · 过线 ":" · pass: ")+chalk.bold.white(r):""));const l=nr()&&t.hint_zh||t.hint;if(l){console.log();let e=!0;for(const o of l.split("\n"))for(const t of zt(o,Bt()-2))console.log(e?chalk.yellow(" 🧭 ")+chalk.white(t):chalk.white(` ${t}`)),e=!1}console.log();let s=!1;try{s=jl(G(oe(kr.dir,el(n,t)),"utf8")).length>0}catch{s=!1}console.log(chalk.gray(" ▸ ")+chalk.bold.green(s?"set <KNOB> <value>":`/edit ${n}`)+chalk.gray(nr()?" 改一行":" change one line")+chalk.gray(" → ")+chalk.bold.green(`/run ${n}`)+chalk.gray(nr()?" 本机打一局(开回放)":" play one match here (replay opens)")+chalk.gray(" → ")+chalk.bold.green(`/submit ${n}`)+chalk.gray(nr()?" 判分":" judge")),s&&console.log(chalk.gray(nr()?" 旋钮列表敲 ":" bare ")+chalk.bold.green("set")+chalk.gray(nr()?" · 想直接看文件用 ":" lists the knobs · the file itself is ")+chalk.bold.green(`/edit ${n}`))}else 0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(nr()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)")));if(t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(nr()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=nr()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of zt(o,Bt()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(nr()?"数据就在上方 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(),Kr&&n===to)return console.log(chalk.white(nr()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(nr()?"第 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(nr()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(nr()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((nr()," ↩ "))+chalk.bold.green("back")+chalk.gray(nr()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(nr()?" 直接看正式题目":" skips straight to the real problems")),void console.log();if(Zr(t));else if(t.quiz){const e=Xe(t);let o;if("letter"===e.kind)o=nr()?"输入字母 A–E 回车":"type a letter A–E, press Enter";else if("choose"===e.kind){const t=e.options.join(" / ");o=nr()?`输入其中一个词回车:${t}`:`type one of ${t}, press Enter`}else o=nr()?"输入 answer 你的答案 回车":"type answer <your answer>, press Enter";console.log(chalk.gray(" ▸ ")+chalk.bold.green(o)+chalk.gray(nr()?" 即提交这一题 · 也可以 ":" to submit this one · or ")+chalk.bold.green(`/edit ${n}`)+chalk.gray(nr()?" 在 vi 里填":" to fill it in vi")),"value"===e.kind&&console.log(chalk.gray(nr()?" 例如 ":" e.g. ")+chalk.white("answer 1200")+chalk.gray(nr()?" · 只填空里的那个值,不用写整句":" · just the value that fills the blank, not the whole sentence"))}else t.gpu?(console.log(chalk.white(nr()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(nr()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(nr()?"真 GPU 上跑并带回你的 ms(⚡ 每周一窗口 19:00–21:45 悉尼)":"runs on a real GPU and returns your ms (⚡ Monday window 19:00–21:45 Sydney)"))):t.starter&&!Zr(t)?(console.log(chalk.white(nr()?" 三步:":" Three steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(nr()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(nr()?"本机直跑,出你自己的 ms":"run it locally — see your own ms")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(nr()?"参考机判分(成绩 = 那里的 ms)":"judge on the reference machine (the scored ms)"))):(console.log(chalk.white(nr()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(nr()?"写码(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(nr()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(nr()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(nr()?"正式判分(隐藏用例)":"official judging (hidden tests)")));console.log(),Zr(t)||t.quiz||(console.log(chalk.gray(nr()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(nr()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log()),console.log(chalk.gray((nr()," ↩ "))+chalk.bold.green("back")+chalk.gray(ll()?nr()?" 回花名册 · ":" to the roster · ":nr()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(nr()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang")+chalk.gray((nr()," / "))+chalk.bold.green("wide")+chalk.gray(nr()?" 换语言/宽度":" language / width")),console.log()},Cl=async(e,o,t)=>await new Promise(n=>{const s=process.stdin,a=!!s.isTTY&&!!s.isRaw;if(hn.pause(),s.isTTY&&"function"==typeof s.setRawMode)try{s.setRawMode(!1)}catch{}wn=!0;const i=r(e,o,{stdio:"inherit",cwd:t??kr.dir}),c=e=>{if(s.isTTY&&"function"==typeof s.setRawMode&&a)try{s.setRawMode(!0)}catch{}l(),wn=!1,hn.resume(),n(e)};i.on("close",()=>c(null)),i.on("error",e=>c(e))}),Al=Ko,xl=()=>{const e=E("vi");console.log(chalk.gray(nr()?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"))},Tl=()=>Lo(nr(),{judgeIsServerSide:!0}),Sl=()=>{const e=Oo();return e||Tl(),e},jl=e=>[...new Set([...e.matchAll(/^([A-Z][A-Z0-9_]*)\s*=\s*[^#\n]+/gm)].map(e=>e[1]))],Pl=(e,o)=>{const t=new RegExp(`^${o}\\s*=\\s*([^#\n]*?)\\s*(?:#.*)?$`,"m").exec(e);return t?t[1]:null},Il=async(e,o)=>{P(`learn-arena p${kr.phase}s${kr.data.slot}: answer ${o.trim().slice(0,40)}`),((e,o)=>{const t=oe(kr.dir,el(e.n,e.p));let n;try{n=G(t,"utf8")}catch{return console.log(chalk.yellow(nr()?" 先 /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 Hl(`/submit ${e.n}`):kn()},El=new Map,Nl=()=>fo(process.cwd(),Jt.id),Ml=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())}`},Ll=async(e,o,t=!1)=>{if(!Tr)return;let n;try{n=G($o(Nl(),e),"utf-8")}catch{return}if(Buffer.byteLength(n,"utf-8")>so)return;const r=mo(n),l=(new Date).toISOString(),s=yo(Wo(),Kt).slice(0,co),a=await _o(Kt,{n:e,title:bo(n.split("\n",1)[0]),code:n,code_sha:r,card_number:sn.currentCard,run_meta:o,client_ts:l,events:s.length>0?s:void 0});a?s.length>0&&wo(Wo(),Kt,s.length):ko(Wo(),Kt,{n:e,code_sha:r,card_number:sn.currentCard,run_meta:o,client_ts:l}),a||t||console.log(chalk.gray(nr()?" (未能同步到服务器 — 草稿只保存在本机)":" (could not reach the server — this scratch is saved locally only)"))},ql=()=>{console.log(chalk.gray(nr()?" 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()},Rl=e=>{const o=uo(Nl()),t=parseInt(e,10);return Number.isInteger(t)&&o.some(e=>e.n===t)?t:(0===o.length?console.log(chalk.yellow(nr()?" 还没有任何草稿 — ":" No scratch files yet — ")+chalk.bold.green("/py")+chalk.gray(nr()?" 新建第一个。":" creates the first one.")):console.log(chalk.yellow(nr()?` 没有 py-${e} — 现有编号: `:` No py-${e} — you have: `)+chalk.white(o.map(e=>e.n).join(", "))+chalk.gray(nr()?" · pylist 看列表":" · pylist shows them")),null)},Ol=e=>{const o=uo(Nl()),t=e?.trim().toLowerCase(),n=t?o.filter(e=>(e.title??"").toLowerCase().includes(t)):o;if(console.log(),console.log(chalk.bold.magenta(nr()?" ✍ 我的 Python 草稿":" ✍ My Python scratch files")+(t?chalk.gray(` · "${e?.trim()}"`):"")+chalk.gray(` (${n.length})`)),0===o.length)return console.log(chalk.gray(nr()?" 还没有草稿 — ":" Nothing here yet — ")+chalk.bold.green("/py")+chalk.gray(nr()?" 新建一个(第一行写标题)。":" creates one (line 1 becomes its title).")),void console.log();if(0===n.length)return console.log(chalk.gray(nr()?` 没有匹配 "${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(zt(e.title,40)[0]??e.title):chalk.gray(nr()?"(未命名 — 第一行写标题)":"(untitled — line 1 becomes the title)");console.log(chalk.gray(` py-${String(e.n).padEnd(3)} `)+o+chalk.gray(` · ${Ml(e.mtimeMs)}`))}console.log(chalk.gray(" ▸ ")+chalk.bold.green(nr()?"/py <编号>":"/py <n>")+chalk.gray(nr()?" 打开 · ":" opens one · ")+chalk.bold.green("/py")+chalk.gray(nr()?" 新建":" new file")),console.log()},Wl=async e=>{const o=$o(Nl(),e);if(Jo())return console.log(chalk.yellow(nr()?" icoa 正跑在 Windows 上 — 草稿本的编辑器在 Ubuntu(WSL)那一侧。":" icoa is running on Windows — the scratchpad editor lives on the Linux (WSL) side.")),console.log(chalk.gray(nr()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${o}`)),void console.log();if(!Xo("vi"))return console.log(chalk.yellow(nr()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${o}`)),void console.log(chalk.gray(nr()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));xl();const t=e=>{try{return H(e).size}catch{return 0}},n=t(o),r=Date.now(),l=I(o);await Cl("vi",[...Al,`py-${e}.py`],Nl());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 Ll(e),console.log(chalk.gray(nr()?" 已回到草稿本 — ":" Back in the scratchpad — ")+chalk.bold.green(`run ${e}`)+chalk.gray(nr()?" 本机运行 · ":" runs it locally · ")+chalk.bold.green(`edit ${e}`)+chalk.gray(nr()?" 再改。":" reopens vi.")),console.log()},Dl=async e=>{let o;if(F(Nl(),{recursive:!0}),e){const t=Rl(e);if(null===t)return;o=t}else{const e=uo(Nl());o=po(e),o>ao&&console.log(chalk.gray(nr()?` (已超过 ${ao} 个 — 服务器不再备份新文件,本机照常保存)`:` (past ${ao} files — the server stops backing new ones up; local saves still work)`)),K($o(Nl(),o),`${nr()?go:io}\n\n`)}const t=!Dn;Dn=!0,P(`learn-py: open ${o}${e?"":" (new)"}`),t&&(console.log(),console.log(chalk.bold.magenta(nr()?" ✍ Python 草稿本":" ✍ Python scratchpad")+chalk.gray(nr()?" — 你的个人练习文件 · 只在本机运行 · 不判分":" — your personal practice files · runs locally · never judged")),console.log(chalk.gray(nr()?" 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(nr()?" 回卡片(退一层)":" returns to the card (one level)"))),await Wl(o),ql()},Ul=()=>jo(process.cwd(),Jt.id),Yl=()=>Yn??xo(So(process.cwd(),Jt.id,sn.currentCard)),Bl=()=>{console.log(),console.log(chalk.bold.magenta(nr()?" ⌨ shell 实验台":" ⌨ shell lab")+chalk.gray(nr()?" — 在这里动手把答案弄出来 · 不判分 · 不解锁任何东西":" — work the answer out here · never judged · unlocks nothing")),console.log(chalk.gray(nr()?` 真的 shell:管道 | 、重定向 > 、通配符 * 都能用 · 每条命令最多 ${Co/1e3} 秒`:` A real shell: pipes |, redirection >, globs * all work · ${Co/1e3}s per command`)),console.log(chalk.gray(nr()?` 你在 ${No(Ul())} 里面 —— 只能在这个文件夹内走动(自己的终端不受限)`:` You are inside ${No(Ul())} — you can only move within it (your own terminal is unrestricted)`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(nr()?" 回卡片(退一层)":" returns to the card (one level)")),console.log()},Fl=()=>{console.log(chalk.gray(nr()?" 敲任何 shell 命令 · cd 换目录 · reset 还原文件 · clear 清屏 · ↩ back "+("fill"===Bn?"回到这道题":"arena"===Bn?"回赛场":"回卡片"):" type any shell command · cd to move · reset restores files · clear · ↩ back "+("fill"===Bn?"returns to the problem":"arena"===Bn?"returns to the arena":"returns to the card")))},zl=()=>`icoa sh ${Eo(Ul(),Yl())}> `,Gl=(e=!1)=>{const o=yr(sn.currentCard)?.files;if(!o)return[];const t=xo(So(process.cwd(),Jt.id,sn.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},Zl=(e="card")=>{Bn=e;const o=!Un;Un=!0,Yn=Yl();const t=Gl();P(`learn-sh: enter card${sn.currentCard}`),o&&Bl(),t.length>0&&(console.log(chalk.bold.green(nr()?" 📦 本卡的文件已放好:":" 📦 This card ships files:")+chalk.white(` ${t.join(" ")}`)),console.log(chalk.gray(nr()?" 先敲 ls 看看。":" Start with `ls`.")),console.log()),Fl()},Hl=async e=>{const o=e.trim().toLowerCase(),l=Wn&&o.startsWith("/")?o.slice(1):o;if(fn)return void($n=!0);if(bn){const{sameName:o,issueCertificate:t,announceCertificate:n}=await import("../lib/learn-certificate.js"),r=e.trim(),l=nr();if(!r||Nn.test(r))return bn=null,console.log(chalk.gray(l?" 已取消,未签发。":" Cancelled — nothing issued.")),void kn();if(null===bn.first)return bn.first=r,console.log(chalk.gray(l?" 再输一次:":" Type it once more:")),void kn();const s={cid:bn.cid,tok:bn.tok,first:bn.first};return bn=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 kn()):(console.log(chalk.yellow(l?" 两次输入不一致 — 未签发。再敲 certificate 重来。":" The two names differ — nothing issued. Type certificate to try again.")),void kn())}if(On)return;if(mn?.noteInput(),!Fn&&mn?.consumeRating(o))return void kn();if(Fn)return await(async e=>{if(!Fn)return;const o=e.trim(),t=o.toLowerCase();if(sr&&("sh"===t||"/sh"===t))return zn=Fn,Fn=null,Zl("fill"),void console.log(chalk.gray(nr()?" ▸ 看完敲 back 回到这道题。":" ▸ When you have looked: back returns to this problem."));if("back"===t||"quit"===t||"menu"===t)return Fn=null,zn=null,console.log(chalk.gray(nr()?" ↩ 回到卡片。":" ↩ Back on the card.")),void Rr();if("skip"===t)return void fl();if(""===o)return void ml();const n=pl();if(!n)return Fn=null,void Rr();const r=ul(n.starter??"");if(Fn.answers.push(o),Fn.answers.length<r)return void yl();const l=[...Fn.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);Fn.answers=[];let a=jr.get(Fn.slot);a||(a=new Set,jr.set(Fn.slot,a)),a.add(n.id);const i=Boolean(n.quiz),c=i?null:new W(Kt);c?.start();const d=await Be(Kt,Fn.phase,n.id,s,Fn.slot,void 0);if(c?.stop(),!Fn)return;if(!d.ok||!d.data)return"no_active_session"===d.code?void hl(Fn.data.duration_minutes):(console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),console.log(chalk.gray(nr()?" 再敲一遍空1重试,或 back 回卡片。":" Type blank 1 again to retry, or back for the card.")),void yl());const g=d.data;if("AC"!==g.verdict||g.already_ac||mn?.notePracticeAc(),g.already_ac||"AC"===g.verdict){i?console.log(chalk.bold.green(nr()?" ✅ 答对了!":" ✅ Correct!")):console.log(Mo("AC",{isZh:nr(),gentle:!0,passed:g.passed_tests??g.total_tests??null,total:g.total_tests??null,ms:g.time_ms??null}));let e=Sr.get(Fn.slot);return e||(e=new Set,Sr.set(Fn.slot,e)),e.add(n.id),Fn.data.solved.includes(n.id)||Fn.data.solved.push(n.id),void fl()}Fn.tries+=1,i?console.log(chalk.red(nr()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(nr()?" — 再选一次。":" — pick again.")):console.log(Mo(g.verdict??"WA",{isZh:nr(),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(nr()?" 期望输出:":" Expected output:"));for(const e of u.out.trimEnd().split("\n"))console.log(chalk.white(" "+e))}if(2===Fn.tries||Fn.tries>2&&Fn.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(nr()?` ⚠ 空${i}:模板里 ____ 后面已经有 ( ) — 只填名字,别再带括号。`:` ⚠ blank ${i}: the ( ) after ____ is already in the template — type just the name, no brackets.`):(/["']$/.test(a)||/^["']/.test(s))&&/^["']|["']$/.test(l)?t.push(nr()?` ⚠ 空${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(nr()?` ⚠ 空${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(nr()?" 💡 两次没过,多半是细节不是思路 — 再敲之前过一遍:":" 💡 Two misses are usually a detail, not the idea — run this check before retrying:")),i||(console.log(chalk.gray(nr()?" · 拼写和大小写(Python 区分大小写:Print ≠ print)":" · spelling and case (Python is case-sensitive: Print ≠ print)")),console.log(chalk.gray(nr()?" · 只填缺的那一块 — ____ 周围已有的括号、引号、冒号不要重复":" · fill only what is missing — brackets, quotes, colons already around ____ stay"))),console.log(chalk.gray(nr()?" · 没思路?往上翻,或 ":" · no idea? scroll up, or ")+chalk.bold.green("back")+chalk.gray(nr()?" 回卡片再读一遍 — 答案就在正文里。打错字人人都有,继续。":" re-reads the card — the answer is in its body. Typos happen to everyone; keep going."))}console.log(chalk.gray(nr()?" 从空1再来:":" From blank 1 again:")),yl()})(e),void kn();if(null!==jn){if(Pn.push(e.replace(/\s+$/,"")),En&&clearTimeout(En),En=null,In){const e=Pn[Pn.length-1]??"";return"/cancel"===e.trim()?(qn(),console.log(chalk.gray(nr()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void kn()):""!==e.trim()?void kn():(Pn.pop(),void await c())}return void(En=setTimeout(()=>{if(En=null,Pn.length>1){In=!0;const e=Pn.length;return console.log(chalk.cyan(nr()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(nr()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void kn()}c()},140))}async function c(){const e=Pn.join("\n").replace(/^\s+|\s+$/g,""),o=jn??sn.currentCard,t=Pn.length,n=Mn;if(qn(),""===e)console.log(chalk.gray(nr()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&Nn.test(e))console.log(chalk.yellow(nr()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(nr()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(nr()?" 即可执行。":" again to run it."));else{const r=!n&&tr>0?Date.now()-tr:void 0;if(await ie(Kt,{curriculum_id:Jt.id,card_number:o,feedback_text:n?`${n} ${e}`:e,time_on_card_ms:r})){const n=t>1?nr()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(nr()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(nr()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),tn=[...tn,{id:rn--,curriculumId:Jt.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Wt(tn)}else console.log(chalk.yellow(nr()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),kn()}if(Zn){const o=e.trim();if(Nn.test(o))return Zn=!1,console.log(),console.log(chalk.yellow(nr()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(nr()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(nr()?" 即可执行该命令。":" again to run it.")),console.log(),void kn();if(!o)return Zn=!1,console.log(chalk.gray(nr()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void kn();const t=await qe({token:Kt,nickname:o});if(t.ok)Zn=!1,console.log(chalk.bold.green(nr()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(nr()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Hn+=1;const e="taken"===t.code?nr()?"已被占用":"already taken":"bad_charset"===t.code?nr()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"real_name"===t.code?nr()?"看起来像真名 — 系统不收集个人信息,换个游戏风格的昵称":"looks like a real name — we collect no personal info; pick a gamer-style handle":"rejected"===t.code?nr()?"未通过审核":"did not pass review":t.message||"error";if(!(Hn>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(nr()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void kn();Zn=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(nr()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void kn()}if(Vn){Vn=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{On=!0;try{console.log(),console.log(chalk.gray(nr()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await Oe({token:Kt,cardNumber:sn.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(nr()?"评审暂不可用。":"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(nr()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(nr()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(nr()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(nr()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(nr()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(nr()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=nr()?` 本卡排名 #${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(nr()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(nr()?` 第 ${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 Ur(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(nr()?" 改进提问: ":" 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(` (${nr()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?er.add(sn.currentCard):er.delete(sn.currentCard),"number"==typeof e.rank&&rr.set(sn.currentCard,e.rank);const o=await De({token:Kt,curriculumId:Jt.id,cardNumber:sn.currentCard});if(o.ok&&o.totals&&o.chapters&&(Ft({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(nr()?` · 榜首 ${n.name||"Rank 1"} ${n.total}`:` · leader ${n.name||"Rank 1"} at ${n.total}`):chalk.bold.yellow(nr()?" · 全场第一!":" · phase leader!");console.log(chalk.white(nr()?` 🏅 Phase ${e.phase} 研究总分: `:` 🏅 Phase ${e.phase} research total: `)+chalk.bold.yellow(`${t.total}`)+chalk.gray(nr()?`(${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&&!Qt&&(Zn=!0,Hn=0,console.log(chalk.bold.yellow(nr()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(nr()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(nr()?" 英文开头,英文+数字,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(nr()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Cn&&(console.log(chalk.gray(nr()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void kn()}if(or)return or=!1,Rr(),void kn();if(!o)return void kn();if(Jn)return"exit"===await U(e.trim())&&(Jn=!1),void kn();if(Rn){if(["q","quit","exit","back","b","menu"].includes(o))return Rn=!1,console.log(chalk.gray(nr()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void kn();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(nr()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?nr()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":nr()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(nr()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(nr()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void kn()):(n&&(await Dr(n,t?"fast":"deep"),console.log(chalk.gray(Vt?nr()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)":nr()?" (↩ q = 返回卡片)":" (↩ q = back to card)"))),void kn())}if(Un){const t=e.trim();if(["back","b","quit","exit","q"].includes(o))return Un=!1,Yn=null,P("learn-sh: leave"),"arena"===Bn?console.log(chalk.gray(nr()?" ↩ 已离开实验台,回到赛场。":" ↩ Left the lab — back in the arena.")):"fill"===Bn&&zn?(Fn=zn,zn=null,ml()):(console.log(chalk.gray(nr()?" ↩ 已离开 shell 实验台,回到卡片。":" ↩ Left the shell lab — back to the card.")),Rr()),void kn();if("menu"!==o&&!/^memo\b/.test(o)){if("reset"===o){const e=Gl(!0);return console.log(e.length>0?chalk.green((nr()?" ↺ 已还原本卡的文件: ":" ↺ Restored this card's files: ")+e.join(" ")):chalk.gray(nr()?" 本卡没有附带文件。":" This card ships no files.")),void kn()}return"clear"===o||"cls"===o?(console.clear(),Fl(),void kn()):"help"===o||"e"===o||"?"===o?(Bl(),void kn()):""===t?void kn():/^\/?py(\s|$)/.test(o)?(Un=!1,Yn=null,await Dl(/^\/?py\s+(\S+)/.exec(o)?.[1]),void kn()):(await(async e=>{P(`learn-sh: $ ${e}`);const o=/^cd(?:\s+(.*))?$/.exec(e.trim());if(o){const e=Po(Ul(),Yl(),o[1]?.trim());return void(null===e?console.log(chalk.yellow(nr()?" 去不了那儿 —— 目录不存在,或在实验台外面。":" Cannot go there — no such directory, or it is outside the lab.")+chalk.gray(nr()?" cd 单独敲回到顶层。":" Bare `cd` returns to the top.")):Yn=e)}const t=Ao(e);if(t)return void console.log(chalk.red((nr(),` ⚠ \`${t.word}\` `))+chalk.yellow(t.why)+chalk.gray(nr()?" —— 实验台不执行它。在自己的终端里敲之前,先 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(nr()?` \`${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,Yl());"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(nr()?" … 输出过长,已截断。":" … output truncated.")),r&&console.log(chalk.yellow(nr()?" 注意:这一行里的 cd 只在子进程里生效,你还在原来的目录。":" Note: the cd in that line ran in a child process — you have not moved.")+chalk.gray(nr()?" 单独敲一行 cd <目录>。":" Type `cd <dir>` on its own line.")),l.stdout||l.stderr?0!==l.code&&console.log(chalk.gray(nr()?` (退出码 ${l.code})`:` (exit ${l.code})`)):console.log(chalk.gray(nr()?` (没有输出 · 退出码 ${l.code})`:` (no output · exit ${l.code})`))):console.log(chalk.yellow(nr()?` 超过 ${Co/1e3} 秒,已停止。`:` Stopped after ${Co/1e3}s.`)+chalk.gray(nr()?" 换个更小的目标再试。":" Try a smaller target.")):console.log(chalk.red(nr()?" 这台机器上找不到 /bin/sh。":" No /bin/sh on this machine.")+chalk.gray(nr()?" Windows 请在 WSL2 里跑 icoa。":" On Windows, run icoa inside WSL2."))})(t),void kn())}}if(Dn){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 Dn=!1,console.log(chalk.gray(nr()?" ↩ 已离开草稿本,回到卡片。":" ↩ Left the scratchpad — back to the card.")),Rr(),void kn();const t=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(t||"list"===o||"/list"===o)return Ol(t?.[1]),ql(),void kn();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=Rl(o);null!==t&&("edit"===e?(await Wl(t),ql()):await(async e=>{if(!B($o(Nl(),e)))return void Rl(String(e));const o=Ro()?.cmd??null;if(!o)return void Lo(nr());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:Nl(),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(nr()?" ⏱ 超过 30 秒,已停止 — 检查死循环。":" ⏱ Over 30s — stopped. Check for an infinite loop."))),console.log(chalk.gray((nr()," ▸ edit "))+chalk.gray(`${e} · pylist · `)+chalk.bold.green("back")),console.log(),dr.push(Ll(e,{run_ms:c,exit_code:i,stderr_head:s.trim().slice(0,300)||void 0},!0).catch(()=>{}))})(t))}else console.log(chalk.yellow(nr()?` 用法: ${e} <编号>`:` Usage: ${e} <n>`)+chalk.gray(nr()?" (pylist 看编号)":" (pylist shows the numbers)"));return void kn()}const l=/^\/?py(?:\s+(\S+))?$/.exec(o);if(l||"new"===o)return await Dl(l?.[1]),void kn();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(nr()?" 草稿本命令: edit <n> · run <n> · pylist · /py 新建 · back 回卡片":" Scratchpad verbs: edit <n> · run <n> · pylist · /py (new) · back to the card")),void kn()}if(Wn&&kr){/^(\/?(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${kr.phase}s${kr.data.slot}: ${o}`);const n=parseInt(kl??"1",10),r=kr.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 Il(s,i[1]):(console.log(chalk.yellow(nr()?" 这一题不是答题式的 — 用 /edit 写代码,/submit 提交。":" This problem is not a typed-answer item — /edit the code and /submit it.")),void kn());const c=/^([A-Ea-e])$/.exec(o.trim());if(c&&s&&a){if("letter"===a.kind)return void await Il(s,c[1].toUpperCase());let e;return e="choose"===a.kind?(nr()?" 输入其中一个词:":" Type one of: ")+a.options.join(" / "):nr()?" 输入 answer 你的答案(例如 answer 1200)。":" Type answer <your answer> (e.g. answer 1200).",console.log(chalk.yellow(nr()?" 这一题不是选字母的。":" This one is not a letter question.")+chalk.gray(e)),void kn()}if(s&&"choose"===a?.kind){const e=o.trim().toLowerCase(),t=a.options.find(o=>o.toLowerCase()===e);if(t)return void await Il(s,t)}if(sr&&("sh"===o||"/sh"===o))return Zl("arena"),console.log(chalk.gray(nr()?" ▸ back 回赛场 · 计时照走":" ▸ back returns to the arena · the clock keeps running")),void kn();if("memo"===o||"/memo"===o||"e"===o)return jn=sn.currentCard,Mn=`[arena p${kr.phase}-g${kr.data.slot}${kl?` #${kl}`:""}]`,console.log(chalk.gray(nr()?` 报告归到: 竞技场 p${kr.phase}-g${kr.data.slot}${kl?` 题${kl}`:""} — 题面 / 判分 / 环境,一句话即可:`:` Files under: arena p${kr.phase}-g${kr.data.slot}${kl?` problem ${kl}`:""} — statement / judging / environment, one line is enough:`)),console.log(chalk.gray(nr()?" (回车提交 · 空行取消 · 不打断比赛计时)":" (Enter to submit · blank to cancel · the contest clock is unaffected)")),void kn();if("back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return ll()&&null!==kl?(kl=null,$l(),void kn()):(Wn=!1,kl=null,console.log(chalk.gray(nr()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Rr(),void kn());if(/^\d+$/.test(o))return _l(o),void kn();const d=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(d)return ll()?d[1]?_l(d[1]):$l():console.log(chalk.gray(nr()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void kn();if("cells"===o||"/cells"===o||"explore"===o||"/explore"===o){const e=xr(kr.phase,kr.data.slot,kr.dir);if(!e)return console.log(chalk.gray(Ar(kr.phase,kr.data.slot)?nr()?" 引导 notebook 还没下载到位(需要联网一次)— 稍后再敲 cells。":" The guided notebook has not downloaded yet (needs one online moment) — try cells again shortly.":nr()?" 本场没有引导 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 kn();const o=null!==N();o||M(hn);try{const{runIpynb:o}=await import("./ipynb.js");await o(e)}catch(e){console.log(chalk.yellow(nr()?" notebook 没打开: ":" The notebook failed to open: ")+chalk.gray(String(e)))}finally{o||M(null)}return $l(),void kn()}const g=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(g)return await(async e=>{const o=e.trim();if(await Ce()||vl||(vl=!0,console.log(chalk.gray(nr()?` (离线:只有 ${Ee()} 条核心速查可用;联网后自动补全)`:` (offline: ${Ee()} core entries available; the rest arrive when you have a connection)`))),!o)return void je(nr());const t=xe(o);if(t.length){Ie(t[0],nr());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(nr()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await Ae("python3",o);if(n)Pe(n,nr());else{if(await Te()){const e=xe(o);if(e.length)return void Ie(e[0],nr())}console.log(),console.log(chalk.yellow(nr()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(nr()?" 试试: ":" Try: ")+chalk.cyan(Se(o).join(" · "))),console.log(chalk.gray(nr()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(g[1]??""),void kn();const u=/^\/?set\b\s*(.*)$/i.exec(e.trim());if(u)return await(async e=>{const o=wl(kl??"1");if(!o)return;const t=oe(kr.dir,el(o.n,o.p));let n;try{n=G(t,"utf8")}catch{return void console.log(chalk.yellow(nr()?" 先 /read 一道题。":" Open a problem with /read first."))}const r=jl(n);if(0===r.length)return void console.log(chalk.yellow(nr()?" 这道题的文件没有旋钮(顶部那种 NAME = value 行)。":" This problem's file has no knobs (the NAME = value lines at the top).")+chalk.gray(nr()?" 用 ":" 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(nr()?" 用法: ":" Usage: ")+chalk.bold.green(nr()?"set <旋钮> <值>":"set <KNOB> <value>")+chalk.gray(nr()?" 例如 set WOMBATS 6":" e.g. set WOMBATS 6")),console.log(chalk.gray(nr()?" 这个 bot 的旋钮:":" This bot's knobs:"));for(const e of r)console.log(chalk.gray(" ")+chalk.bold.white(e.padEnd(10))+chalk.gray(Pl(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(nr()?` 这个 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=Pl(n,i)??"";if(c.trim()===a)return void console.log(chalk.gray((nr()," "))+chalk.bold.white(i)+chalk.gray(nr()?` 已经是 ${a} 了。`:` is already ${a}.`)+chalk.gray(nr()?" 下一步: ":" 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((nr()," ▸ "))+chalk.bold.green(`/run ${o.n}`)+chalk.gray(nr()?" 打一局看看 · ":" play a match and watch · ")+chalk.bold.green(`set ${i} ${c.trim()}`)+chalk.gray(nr()?" 改回去":" puts it back"))})(u[1]??""),void kn();const h=/^\/?(read|open|edit|run|debug|list|recall|replay)(?:\s+(\S+))?$/.exec(o);if(h){const[,e,o]=h;return"list"===e?$l():"replay"===e?await Fo()||console.log(chalk.gray(nr()?" 还没有回放。先 submit 一次 —— 判分机会把你输的那一局送回来。":" No replay yet. Submit once — the judge sends back the game you lost.")):o?"read"===e||"open"===e?_l(o):"edit"===e?await(async e=>{const o=wl(e);if(!o)return;const t=oe(kr.dir,el(o.n,o.p));if(Jo())return Qo()?(console.log(chalk.yellow(nr()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(nr()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(nr()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(nr()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(nr()?" ← 不能是 /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(nr()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(nr()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(nr()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(nr()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(nr()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(nr()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(nr()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(nr()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!Xo("vi"))return console.log(chalk.yellow(nr()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(nr()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));xl();const n=e=>{try{return H(e).size}catch{return 0}},r=n(t),l=Date.now(),s=I(t);await Cl("vi",[...Al,el(o.n,o.p)]);const a=s.stop(),i={ms:Date.now()-l,bytesBefore:r,bytesAfter:n(t)};if(vr.set(o.n,Q(vr.get(o.n)??J(),i)),a.ticks>0){const e=_r.get(o.n)??{list:[],dropped:0};e.list.push(a),e.list.length>16&&(e.list.shift(),e.dropped++),_r.set(o.n,e)}P(`learn-arena edit-done ${el(o.n,o.p)}`,{...i,...a.ticks>0?{samples:a}:{}}),console.log(chalk.gray(nr()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Zr(o.p)?nr()?" 本机打一局。":" to play one match here.":nr()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?await(async e=>{const o=wl(e);if(!o)return;const{p:n,n:r}=o;if(Zr(n)){const e=oe(kr.dir,el(r,n));if(!B(e))return void console.log(chalk.yellow(nr()?` 还没有 ${el(r,n)} — 先 /edit ${r}。`:` No ${el(r,n)} yet — /edit ${r} first.`));vr.set(r,V(vr.get(r)??J()));const o=await Go(e,n.card??0,0,n.crit,(e,o)=>Cl(e,o));return void(o.ran&&(console.log(o.ok?chalk.gray(" ▸ ")+chalk.bold.green(`/submit ${r}`)+chalk.gray(nr()?" 过线了 — 交给判分机(多局固定种子)":" over the bar — send it to the judge (seeded games)"):chalk.gray(" ▸ ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(nr()?" 改一改,再 ":" adjust, then ")+chalk.bold.green(`/run ${r}`)),console.log()))}if(Kr&&r===to)return void(()=>{const e=oe(kr.dir,`sol-${to}.py`);if(!B(e))return void console.log(chalk.yellow(nr()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=Sl();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 Tl();if(console.log(),o.killed)return void console.log(chalk.yellow(nr()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(nr()?` ✗ 输入 ${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(nr()?" 改完再来: ":" 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(nr()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),l===r.length){const e=Jr?null:1;Jr=!0,console.log(chalk.bold.green(nr()?` 🎉 ${l}/${r.length} 全过 — `:` 🎉 ${l}/${r.length} — `)+chalk.white(nr()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(nr()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(nr()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(nr()?` ${l}/${r.length} 通过 — 还差一点。`:` ${l}/${r.length} passed — not there yet.`)+chalk.gray(nr()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(nr()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const l=oe(kr.dir,el(r,n));if(!B(l))return void console.log(chalk.yellow(nr()?` 还没有 ${el(r,n)} — 先 /edit ${r}。`:` No ${el(r,n)} yet — /edit ${r} first.`));vr.set(r,V(vr.get(r)??J()));const s=(n.samples??[])[0];if(n.gpu)return console.log(chalk.gray(nr()?" ⚡ 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(nr()?"(窗口时间执行并返回你的 ms;窗口外会告诉你开放时间)":" (executes in the GPU window and returns your ms; outside the window it tells you the hours)")),void console.log();{const e=Vr(n),o={cpp:"c++",java:"java",go:"go"};if("python"===e?!Oo():!Xo(o[e]??e)){const t="python"===e?"Python":o[e]??e;return console.log(chalk.yellow(nr()?` ⓘ 本机没有 ${t} 环境 — 这一题直接交给判分机跑。`:` ⓘ No local ${t} environment — running this one on the server judge instead.`)),console.log(chalk.gray(nr()?" 判分机的计时本来就是准数;本地跑只是预览。":" The judge's timing is the real number anyway - local runs were only a preview.")),void await Hl(`/submit ${r}`)}}if(!s&&n.starter){const e=Vr(n);try{let o;if("cpp"===e){const e=oe(kr.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=Sl();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(nr()?` ${ho(!0)} — 满意就 `:` ${ho(!1)} — happy? `)+chalk.bold.green(`/submit ${r}`))}catch(e){const o=e;if("ENOENT"===o.code)Tl();else if(o.killed)console.log(chalk.yellow(nr()?" ⏱ 超过 30 秒 — 检查死循环。":" ⏱ Over 30s — check for an infinite loop."));else{console.log(chalk.yellow(nr()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr??"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));console.log(chalk.gray(nr()?` (空还没填对?/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(nr()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";const i=Sl();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)Tl();else if(o.killed)console.log(chalk.yellow(nr()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(nr()?" ✗ 程序报错:":" ✗ 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(nr()?" 你的输出:":" Your output:"));for(const e of(g||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(nr()?" 样例应输出:":" Sample expects:"));for(const e of u.split("\n"))console.log(chalk.green(` ${e}`));console.log(chalk.gray(` ⏱ ${d}ms — ${ho(nr())}`)),g===u?console.log(chalk.bold.green(nr()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(nr()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(nr()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(nr()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=wl(e);if(!o)return;if(Zr(o.p))return console.log(chalk.gray(nr()?` 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"!==Vr(o.p)||o.p.gpu)return console.log(chalk.gray(nr()?` 这一层不读输入 — 用 /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(kr.dir,`sol-${o.n}.py`);if(!B(t))return void console.log(chalk.yellow(nr()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));const n=Sl();if(!n)return;console.log(chalk.gray(nr()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 Cl(n,[`sol-${o.n}.py`]);console.log(),"ENOENT"!==r?.code?(console.log(chalk.gray(nr()?" 回到竞技场。":" Back in the arena.")),console.log()):Tl()})(o):"recall"===e&&await(async e=>{const o=wl(e);if(!o)return;if(!Vt)return void Wr();const{p:t,n:n}=o,r=oe(process.cwd(),"icoa-contest"),l=`${Jt.id}-phase${kr.phase}-g${kr.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(nr()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=G(a,"utf-8"),c=`${kr.phase}-${kr.data.slot}-${n}`,d=Math.min(3,(El.get(c)??0)+1);console.log(chalk.gray(nr()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await Le({token:Kt,phase:kr.phase,slot:kr.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:nr()?"zh":"en"});if(g.ok){El.set(c,d),console.log();for(const e of zt(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(nr()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(nr()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(nr()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(nr()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(nr()?" (花名册: /list)":" (roster: /list)")),void kn()}if("contest"===o||"/contest"===o)return $l(),void kn();const p="lang"===o||/^lang\s+\S+$/.test(o),y=Zt.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(nr()?" 竞技场命令: /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 kn()}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(nr()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void kn()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(hn.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}wn=!0;const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}wn=!1,hn.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void kn()}if("ai4ioai"===o||"/ai4ioai"===o)return await Y()&&(Jn=!0),void kn();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(Qt)return Wr(),void kn();Kn||(Kn=!0,console.log(),Vt?(console.log(chalk.bold.cyan(nr()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(nr()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(nr()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),nr()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")),console.log(chalk.gray(nr()?" 💡 一次好的研究通常会向 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(nr()?" 新建草稿贴进去跑(":" a fresh scratch file and run them (")+chalk.bold.green("/pylist")+chalk.gray(nr()?" 看草稿)。":" lists them)."))):(console.log(chalk.bold.cyan(nr()?" 🐼 AI 熊猫导师":" 🐼 AI Panda Tutor")),console.log(chalk.gray(nr()?` 围绕本卡内容提问 — 导师已经读过这张卡。每张卡每天最多 ${en} 个问题;`:` Ask about THIS card — the tutor has read it. Up to ${en} questions per card per day;`)),console.log(chalk.gray(nr()?" 跑题的问题不会被回答,也不计次数。这里只是问答,没有评分和榜单。":" off-topic questions are not answered and do not count. Q&A only — no grading, no board."))),console.log(chalk.yellow(nr()?" ↩ 重要:退出 AI 模式只需输入 ":" ↩ Important: to leave AI mode just type ")+chalk.bold.white("back")+chalk.yellow(nr()?" 或 ":" or ")+chalk.bold.white("quit")+chalk.yellow(nr()?",就回到卡片。":" — you are back on the card.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Rn=!0;const e=yr(sn.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(nr()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(nr()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Vt?nr()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · back / quit = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · back / quit = back to card":nr()?" 直接输入问题 · back / quit = 返回卡片":" Type a question · back / quit = back to card")),Vt&&console.log(chalk.gray(nr()?" 💡 通常要向 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 kn()}return await Dr(n,t?"fast":"deep"),void kn()}if(!Wn&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Vt)return Wr(),void kn();const e=yr(sn.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(nr()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(nr()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(nr()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(nr()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(nr()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(nr()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(nr()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Vn=!0,void kn()}const p=!Wn&&"honors"===Gn&&/^[1-3]$/.test(o);if(!Wn&&Gn&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(nr()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(nr()?" ↩ back 回上一层":" ↩ back goes up one level")),void kn();if(!Wn&&(p||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Vt)return Wr(),void kn();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:Kt,cardNumber:sn.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(nr()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&er.delete(sn.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&er.add(sn.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(nr()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${sn.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${sn.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(nr()?` (第 ${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(nr()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Ur(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(nr()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Gn="view",console.log(chalk.gray((nr()," "))+chalk.bold.cyan("↩ back")+chalk.gray(nr()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{On=!1}})(t),void kn()}const _=o.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(_&&!Wn&&!Dn){const{certificateLines:e}=await import("../lib/learn-door.js"),{certifiable:o,certificateIntroLines:t}=await import("../lib/learn-certificate.js"),n=nr(),r=Qt?null:await v(Kt,"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===Jt.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 kn()}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:")),bn={cid:i.curriculum_id,tok:i.token,first:null},void kn()}const A=o.match(/^\/?(story|credits|fin)(?:\s+(\S+))?$/);if(A&&!Wn&&!Dn){const e=(A[2]??"").trim();return await fr("story"===A[1]?e||"list":e||null,!0),void kn()}if(/^\/?(?:type|typing)(?:\s|$)/i.test(o))return await Yo(o.trim().split(/\s+/).slice(1)),void kn();if(/^\/?battle(?:\s|$)/i.test(o)&&!Wn&&!Dn){const e=null!==N();return e||M(hn),await zo([...o.trim().split(/\s+/).slice(1),`from-card:${sn.currentCard}`]),e||M(null),void kn()}if(/^\/?duck(?:\s|$)/i.test(o)&&!Wn&&!Dn){const e=null!==N();return e||M(hn),await Ho([...o.trim().split(/\s+/).slice(1),`from-card:${sn.currentCard}`]),e||M(null),void kn()}if(R(o))return await O(),void kn();if("me"===o||"/me"===o||"profile"===o||"/profile"===o||"my profile"===o){const e=nr();if(Qt)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 kn();console.log(chalk.gray(e?" 正在取档案…":" Loading your profile…"));const o=await v(Kt);return"ok"===o.kind?C(o.profile,e,Bt()):"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 kn()}if("/honors"===o||"honors"===o)return Qt?(console.log(),console.log(chalk.gray(nr()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void kn()):(await Br(),void kn());const x=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(x)return P("learn-py: pylist"+(x[1]?` ${x[1]}`:"")),Ol(x[1]),void kn();const T=/^\/?py(?:\s+(\S+))?$/.exec(o);if(T)return await Dl(T[1]),void kn();if(/^\/?sh$/.test(o))return Zl(),void kn();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(nr()?" ↩ back 回卡片 · ":" ↩ back to the card · ")+chalk.bold.green("/py")+chalk.gray(nr()?" 打开草稿本":" opens the scratchpad")),console.log(),void kn()}if(/^\/?(upgrade|update)$/i.test(o.trim())){P("learn-upgrade");const{runUpgrade:e}=await import("../lib/update-check.js");return"upgraded"===await e({ask:!1})&&console.log(chalk.gray(nr()?" 输入 ":" type ")+chalk.bold.green("menu")+chalk.gray(nr()?" 进入新版本(进度已保存)":" to start the new version (your progress is saved)")),console.log(),void kn()}if(An&&"menu"!==o&&"menu confirm"!==o){const e=An.handle(o);return"input"===e||Sn(e),void kn()}if(An&&(An=null),"menu"===o||"menu confirm"===o){if(mn?.detach(),dr.length>0&&await Promise.race([Promise.allSettled(dr),new Promise(e=>setTimeout(e,3e3))]),hn.removeAllListeners("line"),yn(),gn||!pr){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(gn?hn:void 0),hr()}else hn.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===Gn)return await Br(),void kn();if("honors"===Gn)return Gn=null,Rr(),void kn();if(mn?.detach(),dr.length>0&&await Promise.race([Promise.allSettled(dr),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${sn.streakDays} day(s)`)),console.log(),gn){hn.removeAllListeners("line"),yn();for(const e of un)hn.on("line",e);hn.prompt(),hr()}else hn.removeAllListeners("line"),hn.close();return}if(pe(o))return nn?Ht(ue(nn,nr(),Bt(),"T0"===ye().tier),!!nn.completedAt):(console.log(chalk.gray(nr()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void kn();{const e=o.match(y);if(e)return Tr?(await m(Kt,e[1]??"",{curriculum:Jt}),P("learn: check"),void kn()):(console.log(chalk.yellow(nr()?" check 需要正式课程 token(demo 不支持)。":" check needs a full curriculum token (not demos).")),void kn())}{const e=o.match(f);if(e)return Tr?(await $(Kt,e[1]??"",Jt.totalCards),P("learn: class"),void kn()):(console.log(chalk.yellow(nr()?" class 需要正式课程 token(demo 不支持)。":" class needs a full curriculum token (not demos).")),void kn())}if(b.test(o)&&!Wn&&!Dn&&!Un){if(!Tr)return console.log(chalk.yellow(nr()?" 队伍会议室凭 FTC 课程 token 进入(demo 不支持)。":" Team meeting needs an FTC course token (not demos).")),void kn();P("learn: teammeeting");const e=hn.listeners("line");hn.removeAllListeners("line");let o="back";try{o=await k(Kt,w(hn))}finally{for(const o of e)hn.on("line",o)}return"menu"===o?void hn.emit("line","menu"):(console.log(chalk.gray(nr()?" ↩ 回到课程。":" ↩ Back to the course.")),void kn())}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(Tr){const[,e]=await Promise.all([Ir(),ne(Jt.id,Kt,!0)]);e&&Object.assign(Jt,e)}return Ct(Jt,sn,{gate:wr,gated:on,focus:t,posForSlot:Qe}),void kn()}if("sync"===o){P("learn: sync");const e=await ae(Kt);if(!e)return console.log(chalk.yellow(" ⚠ ")+chalk.white(nr()?"连不上服务器,进度保持本地。":"Server unreachable — keeping local progress.")),void kn();const o=sn.currentCard;return nt(sn,Jt.totalCards,e),et(sn),sn.currentCard>o?console.log(chalk.green(" ↩ ")+chalk.white(nr()?`已同步:${sn.cardsCompleted.length} 张卡完成,从第 ${sn.currentCard} 张继续`:`Synced: ${sn.cardsCompleted.length} cards done, resuming at card ${sn.currentCard}`)):console.log(chalk.green(" ✓ ")+chalk.white(nr()?"已与服务器同步,无新进度。":"Synced with the server — no new progress.")),void kn()}if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await ne(Jt.id,Kt,!0);return void(e?(Object.assign(Jt,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Rr()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),kn()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim(),t=de(Jt.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 kn();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`)),Cn=null,vn=null,_n=null,qn(),or=!1,Vn=!1,await Yr(),void kn()}const j=o.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(j&&!Wn&&!Dn&&null===Fn&&g.test(o)){const e=nr(),o=await u(Kt);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 kn()}if(j&&!Wn&&!Dn&&null===Fn){const e=(j[2]??"").trim(),o=nr(),t=`${a}–${s}`+(o?`,${i} 的倍数`:`, steps of ${i}`);if("off"===e||"stop"===e||"end"===e||"cancel"===e||"关"===e)return void(mn?.stop()||(console.log(chalk.gray(o?" 没有进行中的专注。开始一场:":" No focus session running. Start one: ")+chalk.bold.green("focus 30")),kn()));if(mn?.active)return console.log(chalk.yellow(" ⏱ ")+chalk.white(o?`专注进行中 · 还剩 ${mn.remainingMin()} 分钟`:`focus running · ${mn.remainingMin()} min left`)+chalk.gray(o?" · 提前结束:":" · end early: ")+chalk.bold.green("focus off")),void kn();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 kn();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 kn();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 mn?.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 kn()}if(Zt.has(o)){const e=Zt.get(o),t=Ut(Do()),n=e=>{const o=["normal","wide","wider","widest"].filter(o=>o!==e);return nr()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((nr()?"normal"===e?" 已是标准 64 列。":Bt()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Bt()} 列,上限 ${Yt(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Bt()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Bt()} cols, cap ${Yt(e)}). `)+n(e))),void kn()):(Uo({learnWidth:e,learnWide:"normal"!==e}),Dt(e),"normal"!==e&&Bt()<=64?(console.log(chalk.yellow(nr()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((nr()?` 设置已记住(${e},上限 ${Yt(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Yt(e)} cols) and applies once you widen the window. `)+n(e))),void kn()):(console.log(chalk.green(" ✓ ")+chalk.gray((nr()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Bt()} 列,上限 ${Yt(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Bt()} cols, cap ${Yt(e)}). `)+n(e))),Cn=null,vn=null,_n=null,qn(),or=!1,Vn=!1,await Yr(),void kn()))}if("sim"===o){const e=yr(sn.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 kn()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void kn())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=sn.currentCard,t=sn.bookmarks.includes(e),n="bookmark"!==o;return n?sn.bookmarks=sn.bookmarks.filter(o=>o!==e):t||sn.bookmarks.push(e),et(sn),n?console.log(t?chalk.gray(nr()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(nr()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(nr()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(nr()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void kn()}const E=me(o);if(E){const e="current"===E.target?sn.currentCard:E.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>Jt.cards.length))return console.log(chalk.yellow(nr()?` 本课共 ${Jt.cards.length} 张,请输 r 1–${Jt.cards.length} 或 r all。`:` This course has ${Jt.cards.length} cards. Try r 1–${Jt.cards.length} or r all.`)),console.log(),void kn();for(const o of fe(tn,cr,e,nr(),Bt()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?tn:tn.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(tn=tn.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Wt(tn),dr.push(le(Kt,{card_number:sn.currentCard,event_type:"viewed"},o).catch(()=>{}))),void kn()}if("e"===o||"memo"===o)return jn=sn.currentCard,console.log(chalk.gray(nr()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(nr()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void kn();if("back"===o||"b"===o&&null===vn)return"view"===Gn?(await Br(),void kn()):"honors"===Gn?(Gn=null,Rr(),void kn()):(sn.currentCard>1&&(sn.currentCard-=1),vn=null,_n=null,Cn=null,et(sn),Rr(),void kn());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Tr)return console.log(chalk.yellow(nr()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void kn();if(!e){const e=await ze(Kt),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(nr()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(nr()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(nr()?` 这台电脑上有 ${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(nr()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(nr()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(nr()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(nr()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(nr()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(nr()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(nr()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void kn()}if(/^\d{1,2}$/.test(e)){const o=await Fe(Kt,Number(e));return o.ok&&o.data?(tl(o.data),await Ir(),void kn()):(console.log(chalk.red(` ✗ ${o.message||(nr()?"关联失败":"Link failed")}`)),void kn())}const t=await Ge(Kt,e);return t.ok&&t.data?(tl(t.data),await Ir(),void kn()):(console.log(chalk.red(` ✗ ${t.message||(nr()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(nr()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void kn())}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(!Tr)return console.log(chalk.yellow(nr()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void kn();if("duck"===vt()&&!Wn&&!Dn){console.log(chalk.gray(nr()?" 这条轨的检查点在 duck 子 REPL 里打:进入 duck → run 试跑 → submit 判分。":" This track's checkpoints are played in duck: duck → run → submit."));const e=null!==N();return e||M(hn),await Ho([`from-card:${sn.currentCard}`]),e||M(null),void kn()}let e=Er(sn.currentCard),t=null;const n="contest restart"===o||"restart"===o;if(n&&(!Wn||!kr||ll()))return console.log(chalk.gray(nr()?" 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 kn();if(n&&kr){const o=kr.phase,n=kr.data.slot,r=await Ue(Kt,o,n);if(!r.ok&&"no_active_session"!==r.code)return console.log(chalk.red(` ✗ ${r.message||"reset failed"}`)),void kn();sl(o,n),console.log(chalk.yellow(nr()?` 🔄 第 ${n} 组重开 — 全新计时、全新模板。`:` 🔄 Group ${n} restarted — fresh clock, fresh templates.`)+chalk.gray(nr()?" 只有计时内写的才算数:从头再写一遍,这正是练习。":" Only work written on the clock counts — write it again from scratch; that is the practice.")),kr=null,Wn=!1,kl=null,e=o,t=n}if("contest reset"===o&&Wn&&ll()){const e=kr.phase,o=kr.data.slot,t=await Ue(Kt,e,o);if(t.ok){console.log(chalk.yellow(nr()?" 已放弃本卡练习计时。回卡片后输入 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",`${Jt.id}-phase${e}-g${o}`);if(B(n))try{Z(n,`${n}-archived-${t}`),console.log(chalk.gray(nr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(nr()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}kr=null,Wn=!1,kl=null,Rr()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void kn()}if("contest reset"===o){const o=await Ue(Kt,e);if(o.ok){console.log(chalk.yellow(nr()?` 已放弃本阶段(${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(`^${Jt.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])<rl).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(nr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(nr()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(nr()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),kr=null,Wn=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void kn()}const r=null!=t?String(t):/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(nr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Kt,e,r?parseInt(r,10):void 0);if(!l.ok||!l.data){if("no_contest"===l.code){const o=Jt.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?nr()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(360 层第二阶段标准设计中)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (360-tier second-stage standard in design).`:lr?nr()?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).`:nr()?` 本阶段(${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 kn()}const s=l.data,a=oe(process.cwd(),"icoa-contest",`${Jt.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(nr()?" 📦 上一场的答题文件已归档: ":" 📦 Previous window archived: ")+chalk.gray(`${a}-archived-${e}`)),console.log(chalk.gray(nr()?" 新场次全新模板 — 计时窗口内写的才算数。":" Fresh window, fresh templates — only work done on the clock counts."))}catch{console.log(chalk.yellow(nr()?` ⚠ 归档失败(比赛照常): ${a}`:` ⚠ Could not archive (contest still fine): ${a}`))}}F(a,{recursive:!0});const i=kr&&kr.phase===e&&kr.data.slot===s.slot?kr.tried:new Set;kr&&kr.phase===e&&kr.data.slot===s.slot&&kr.data.attempt===s.attempt||(vr.clear(),_r.clear()),kr={phase:e,dir:a,data:s,tried:i},ol(s,a),xr(e,s.slot,a),Wn=!0,$l(),console.log(chalk.gray(nr()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(a));const c=s.problems.findIndex(e=>!s.solved.includes(e.id))+1||1,d=Kr&&!Jr?to:c;return console.log(chalk.white(nr()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${d}`)+chalk.gray(d===to?nr()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":nr()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void kn()}if(/^\/?(?:flow|walk)$/.test(o)){const e=yr(sn.currentCard),o=e&&"knowledge"===e.type?e.flow:void 0;return o&&0!==o.length?(Tn(e,!1),void kn()):(console.log(chalk.gray(nr()?" 这张卡没有互动流程 — 有流程的卡片脚注会印 [flow]。":" No interactive walk on this card — cards that have one show [flow] in the footer.")),void kn())}const L=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(lr&&/^[1-9]$/.test(o)?`practice ${o}`:o);if(L){const e=yr(sn.currentCard),o=il(e);if(!o)return console.log(chalk.gray(nr()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void kn();if(!Tr)return console.log(chalk.yellow(nr()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void kn();if(!L[1])return console.log(),gl(e),console.log(chalk.gray(nr()?" 用法: ":" Usage: ")+chalk.bold.green(nr()?"practice <题号>":"practice <n>")+chalk.gray(nr()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void kn();const t=parseInt(L[1],10);if(!Number.isInteger(t)||t<1||t>o.length)return console.log(chalk.yellow(nr()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void kn();const n=o[t-1],r=cl(n),l=o.filter(e=>cl(e)===r),s=l.indexOf(n)+1;return await(r||!lr?(async(e,o,t)=>{const n=Er(e.number),r=rl+e.number;console.log(chalk.gray(nr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Kt,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(nr()?" 本卡暂无练习题库。":" 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(nr()?" 本卡练习题库是空的。":" 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(al(e.py_id))?al(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=Sr.get(r);c||(c=new Set,Sr.set(r,c));for(const e of s.solved)c.add(e);const d=oe(process.cwd(),"icoa-contest",`${Jt.id}-phase${n}-g${r}`);F(d,{recursive:!0});const g=kr&&kr.phase===n&&kr.data.slot===r?kr.tried:new Set;kr&&kr.phase===n&&kr.data.slot===r&&kr.data.attempt===s.attempt||(vr.clear(),_r.clear()),kr={phase:n,dir:d,data:s,tried:g},ol(s,d),Wn=!0,kl=null,P(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(nr()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(nr()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(nr()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(d)),console.log(chalk.gray((nr()," ↩ "))+chalk.bold.green("back")+chalk.gray(nr()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),_l(String(Math.min(t,s.problems.length)))})(e,l,s):(async(e,o,t)=>{const n=Er(e.number),r=rl+e.number;zn=null,console.log(chalk.gray(nr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Kt,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(nr()?" 本卡暂无练习题库。":" 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(nr()?" 本卡练习题库是空的。":" 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(al(e.py_id))?al(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&&!Zr(e)&&i.push(e);s.problems=i;let c=Sr.get(r);c||(c=new Set,Sr.set(r,c));for(const e of s.solved)c.add(e);Fn={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(nr()?` ⚡ 快速填空 — 第 ${e.number} 张卡`:` ⚡ Quick fill — card ${e.number}`)+chalk.gray(nr()?"(敲答案 → 自动判分 · 不计分)":" (type the blank → auto-judged · unscored)")),console.log(chalk.gray(nr()?` ⏱ 每次练习 ${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`)),ml()})(e,l,s)),void kn()}if("submit"===l)return console.log(chalk.yellow(nr()?" 用法: ":" Usage: ")+chalk.bold.green(nr()?"submit <题号>":"submit <n>")+chalk.gray(nr()?" 例如 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)")),kr||console.log(chalk.gray(nr()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void kn();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const t=e[2];if(!kr)return console.log(chalk.yellow(nr()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void kn();const n=kr.data.problems,r=parseInt(o,10);if(Kr&&r===to)return console.log(chalk.gray(nr()?" 热身题不判分 — /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(nr()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(nr()?" 开始。":".")),void kn();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(nr()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void kn();const s=n.findIndex(e=>e.id===o)+1,a=t||oe(kr.dir,el(s,n[s-1]));let i;try{i=G(a,"utf-8")}catch{return console.log(chalk.red(nr()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void kn()}const c=Boolean(n[s-1]?.quiz),d=c?null:new W(Kt);d?.start();const g=vr.get(s),u=_r.get(s),h=g&&!X(g)?{...g,...u?{samples:u.list}:{},...u&&u.dropped>0?{samplesDropped:u.dropped}:{}}:void 0,p=await Be(Kt,kr.phase,o,i,kr.data.slot>=rl?kr.data.slot:void 0,h);if(d?.stop(),!p.ok||!p.data)return"no_active_session"===p.code&&kr.data.slot>=rl?hl(kr.data.duration_minutes):"no_active_session"===p.code?(sl(kr.phase,kr.data.slot),console.log(chalk.yellow(nr()?" ⏱ 时间到 — 这一场结束了,判分机已停表。":" ⏱ Time is up — this attempt is over; the judge stopped the clock.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(nr()?" 重开这一组:全新计时 + 全新模板(旧文件已归档)。只有计时内写的才算数 — 从头再写一遍,这正是练习。":" 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(nr()?" ↩ back 回卡片":" ↩ back returns to the card"))):(console.log(chalk.red(` ✗ ${p.message||"judging failed"}`)),console.log(chalk.gray(nr()?" 判分服务异常?敲 memo 一句话告诉我们 — 不打断比赛计时。":" Judge acting up? Type memo — one line reaches us, the clock is unaffected."))),void kn();const y=p.data;let m=!1;if(Hr()){const e=y;for(const o of(e.report??[]).slice(0,3))console.log(chalk.gray(` ${nr()?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(nr()?" 看你输掉的那一局 —— 判分机把它送回来了(q 退出回放)":" watch the game you lost — the judge sent it back (q quits the player)")),y.already_ac)console.log(chalk.green(nr()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===y.verdict){if(c?console.log(chalk.bold.green(nr()?" ✅ 答对了!":" ✅ Correct!")):console.log(Mo("AC",{isZh:nr(),passed:y.passed_tests??y.total_tests??null,total:y.total_tests??null,ms:y.time_ms??null})),kr.data.solved.includes(o)||kr.data.solved.push(o),kr.tried.delete(o),ll()){let e=Sr.get(kr.data.slot);e||(e=new Set,Sr.set(kr.data.slot,e)),e.add(o);const t=await De({token:Kt,curriculumId:Jt.id,cardNumber:sn.currentCard}),n=t.ok?t.practiceBoard:null;if(n?.mine){const e=n.top[0],o=e&&!e.me?chalk.gray(nr()?` · 榜首 ${e.name||"Rank 1"} ${e.ac} AC`:` · leader ${e.name||"Rank 1"} at ${e.ac} AC`):chalk.bold.yellow(nr()?" · 全场第一!":" · phase leader!");console.log(chalk.white(nr()?` ⚔ Phase ${n.phase} Practice AC: `:` ⚔ Phase ${n.phase} practice AC: `)+chalk.bold.yellow(`${n.mine.ac}`)+chalk.gray(`/${n.problems_total}`)+chalk.gray(nr()?` · 第 ${n.mine.rank} 名`:` · rank ${n.mine.rank}`)+o)}}}else kr.tried.add(o),c?console.log(chalk.red(nr()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(nr()?" — 再选一次。":" — pick again.")):console.log(Mo(y.verdict,{isZh:nr(),passed:y.passed_tests??null,total:y.total_tests??null,failedTest:y.test??null,ms:y.time_ms??null})),Ln||(Ln=!0,console.log(chalk.gray(nr()?" 觉得题面有误或判分不对?敲 memo 一句话 — 不打断比赛计时。":" Statement wrong or judging looks off? Type memo — one line, the clock is unaffected.")));y.late&&console.log(chalk.yellow(nr()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const f=He(y.deadline||""),$=ll();if(console.log(chalk.white($?nr()?` 本卡练习: 已过 ${y.ac_count}/${y.n} 题(不计分)`:` Card practice: ${y.ac_count}/${y.n} solved (unscored)`:nr()?` 本组进度: 已过 ${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(nr()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(nr()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!y.passed||y.late||$){if(!y.late){const e=n.findIndex(e=>!kr.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(nr()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${zr(n[e])}`))}}else{const e=Math.max(0,y.n-y.ac_count);if(0===e)console.log(chalk.bold.green(nr()?` 🎉 满分!${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(nr()?" 回到上一层(卡片),继续往下学;":" returns to the previous layer (the card) — keep going from there; ")+chalk.bold.green("contest")+chalk.gray(nr()?" 看本阶段其他赛场。":" lists the other arenas of this phase."));else{console.log(chalk.bold.green(nr()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")+chalk.yellow(nr()?` 还剩 ${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=>!kr.data.solved.includes(e.id));o>=0&&console.log(chalk.gray(nr()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${o+1}`)+chalk.gray(` ${zr(n[o])}`)+chalk.gray(nr()?" · ↩ back 回卡片":" · ↩ back returns to the card"))}{const e=Jt.modules.find(e=>e.number===kr.phase);if(e&&e.cardRange[1]-e.cardRange[0]+1>12&&1===kr.data.slot){const e=Jt.modules.find(e=>e.number===kr.phase+1);console.log(e?chalk.bold.cyan(nr()?" 🎁 定位检查过关 — 这个模块你已经会了。":" 🎁 Placement check passed — you already own this module.")+chalk.gray(nr()?" 想跳过剩下的卡:":" To skip the rest of it: ")+chalk.bold.green(`card ${e.cardRange[0]}`)+chalk.gray(nr()?"(下一模块开头)· 想留下练也可以,":" (next module) · or stay and drill, ")+chalk.bold.green("contest 2")+chalk.gray(nr()?" 是本模块的模拟卷。":" is this module's mock paper."):chalk.bold.cyan(nr()?" 🎁 定位检查过关 — 这是最后一个模块,":" 🎁 Placement check passed — last module; ")+chalk.bold.green("contest 2")+chalk.gray(nr()?" 做最后一套模拟卷。":" is the final mock paper."))}}await Ir()}return void kn()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>Jt.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Jt.totalCards}. Try: `)+chalk.bold.green("card 1")),void kn();const n=await Mr(t);return n?(console.log(n),void kn()):(sn.currentCard=t,vn=null,_n=null,Cn=null,et(sn),Rr(),void kn())}if(null!==Cn&&["y","yes","n","no"].includes(o)){const e=yr(Cn);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-tr;mn?.noteCheck(n,r),at(sn,e.number),ct(sn,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),et(sn);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),dr.push(le(Kt,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Cn=null,br(),e.solution&&e.solution.length>0)return void kn();if(dl())return void kn();if(sn.currentCard<Jt.totalCards){const e=sn.currentCard,o=await Mr(e+1);if(o)return await Lr(e),console.log(o),void kn();sn.currentCard+=1,et(sn),await Lr(e)?qr():Rr(),kn()}else xt(Jt,sn),fr(null,!1).then(()=>kn()),kn();return}}if(null!==vn&&["a","b","c","d"].includes(o)){const e=yr(vn);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(it(sn,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),at(sn,e.number),et(sn),yt(e,t,n,sn),dr.push(le(Kt,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),vn=null,n)if(sn.currentCard<Jt.totalCards){const e=await Mr(sn.currentCard+1);if(e)return console.log(e),void kn();sn.currentCard+=1,et(sn),Rr()}else xt(Jt,sn),fr(null,!1).then(()=>kn()),kn();else kn();return}}if(null!==_n){if("done"===o){const e=yr(_n);if(e&&"practical"===e.type)return dt(sn,e.number),at(sn,e.number),et(sn),ft(e),_n=null,void kn()}if("skip"===o)return at(sn,_n),et(sn),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),_n=null,void kn()}const q=lr&&"skip"===o&&null===vn&&null===_n&&null===Cn&&null!==il(yr(sn.currentCard));if("ok"===o||"next"===o||"continue"===o||"n"===o||q){if(q){const e=sn.currentCard;Pr.add(e),mn?.notePracticeSkipped(),console.log(chalk.gray(nr()?" ⚔ 本卡练习已跳过(有记录)。":" ⚔ Practice skipped for this card (recorded).")),le(Kt,{card_number:e,event_type:"practice_skipped"}).catch(()=>{})}else if(null===Cn&&null===vn&&null===_n&&dl())return void kn();if(null!==vn)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void kn();if(null!==_n)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void kn();if(null!==Cn)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void kn();const e=sn.currentCard,o=e<Jt.totalCards?await Mr(e+1):null;return o?(await Lr(e),console.log(o),void kn()):(sn.currentCard+=1,et(sn),sn.currentCard>Jt.totalCards?(xt(Jt,sn),fr(null,!1).then(()=>kn())):await Lr(e)?qr():Rr(),void kn())}return null!==Cn?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void kn()):null!==vn?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void kn()):null!==_n?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void kn()):("view"===Gn?console.log(chalk.gray(nr()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(nr()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(nr()?" 回卡片":" to the card")):"honors"===Gn?console.log(chalk.gray(nr()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(nr()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(nr()?" 回卡片":" 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 kn())};hn.on("line",e=>{Hl(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.")),kn()})}),gn||hn.on("close",async()=>{mn?.detach(),dr.length>0&&await Promise.race([Promise.allSettled(dr),new Promise(e=>setTimeout(e,5e3))]),pr?hr():process.exit(0)});const Kl=be(tn,nr());if(Kl){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(Kl)+chalk.bold.cyan(" │")),console.log(chalk.bold.cyan(` ╰${"─".repeat(Math.max(26,e-5))}╯`)),console.log()}try{Rr();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0),(async()=>{for(let e=0;e<20&&!wr;e++)await new Promise(e=>setTimeout(e,250));const e=$r();null!==e&&e>0&&e<=2&&(await br(!0),kn())})();const o=mn?.attach(Kt,Jt.id,mr);"resumed"===o&&(console.log(chalk.yellow(" ⏱ ")+chalk.white(nr()?`专注进行中 · 还剩 ${mn.remainingMin()} 分钟 · 这条轨也算在内 · focus off 提前结束`:`focus running · ${mn.remainingMin()} min left · this course counts too · focus off to end early`)),console.log()),kn()}catch(e){if(process.env.ICOA_DEBUG&&console.error(e),Gt("Could not render this card — the curriculum may be malformed."),gn){hn.removeAllListeners("line"),yn();for(const e of un)hn.on("line",e);hn.prompt()}else hn.close();hr()}await ur}),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()})}
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 L}from"../lib/main-rl.js";import{assetDir as M,lazyJson as q}from"../lib/lazy-assets.js";import{isMicroduckWord as R,runMicroduck as O}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 Le,recallCoach as Me,setNickname as qe,streamLearnTutor as Re,submitPqs as Oe,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 Lo}from"../lib/verdict.js";import{printNoPython312 as Mo,probePython as qo}from"../lib/python-setup.js";function Ro(){const e=qo();return e.ok&&e.cmd?{cmd:e.cmd}:null}const Oo=()=>Ro()?.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,forgetAdoptedSession as lt,updateStreak as st,markCardComplete as at,recordMCQ as it,recordCheck as ct,markPracticalComplete as dt,addAchievement as gt}from"../lib/learn-state.js";import{renderWelcome as ut,renderKnowledgeCard as ht,renderMCQCard as pt,renderMCQFeedback as yt,renderPracticalCard as mt,renderPracticalSuccess as ft,renderSimDemoCard as $t,renderMilestone as bt,renderArenaTaskCard as wt,renderArenaIntro as kt,learnCheckpointVerb as vt,renderComingSoonCard as _t,renderStatus as Ct,renderPhaseComplete as At,renderCurriculumComplete as xt,setLearnAiEnabled as Tt,setLearnFaqs as St,setLearnArenaLane as jt,setLearnArenaCards as Pt,setLearnDuckLane as It,setLearnFooterProfile as Et,setLearnShellLane as Nt,setLearnHometask as Lt,setLearnPracticeChips as Mt,setLearnPracticeCount as qt,setLearnHonorRanks as Rt,setLearnPqsViewCards as Ot,setLearnReplies as Wt,setLearnWidth as Dt,resolveLearnWidth as Ut,learnWidthCap as Yt,learnW as Bt,renderHonorWall as Ft,wrapMixed as zt}from"../lib/learn-render.js";import{printError as Gt}from"../lib/ui.js";const Zt=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","widest"],["wide max","widest"]]);function Ht(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 Kt=qo.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Kt)){const{runSprint:e}=await import("./sprint.js");return void await e()}if(R(qo))return void await O();let Jt=null;const Qt=/^[A-Z0-9]+DEMO01$/i.test(Kt),Xt=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Kt);let Vt=!1,en=3,on=!1,tn=[],nn=null,rn=-1,ln=Promise.resolve([]);if(Qt)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),ln=ce(Kt),Jt=await ne(Kt,Kt,!0);else if(Xt){console.log(),console.log(chalk.gray(" Validating token..."));let e=await re(Kt);if(!e.ok){const o=Ne(Kt);if(o!==Kt){const t=await re(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Kt} → ${o}`)),e=t,Kt=o)}}if(!e.ok){if(Gt(`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(" New or reinstalled computer? Type ")+chalk.bold.green("menu")+chalk.gray(", pick 🧠 Learn with ↑↓ + Enter, enter this token, then type ")+chalk.bold.green("move")+chalk.gray(" (all your courses come here, progress kept).")),lt(Kt)&&(console.log(),console.log(chalk.gray(" It belongs to your other computer, so it is no longer listed on this one.")));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 🐼"):Qt?"":chalk.magenta(" · 🐼 AI tutor"))),Vt=!0===e.aiEnabled,en=e.aiBasicPerCard??3,on=!0===e.gated,tn=e.replies??[],nn=e.hometask??null,ln=ce(Kt),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Jt=await ne(e.curriculumId||"LEARNDEMO01",Kt,!0),!Jt)return Gt(`Could not open a learn curriculum for token '${Kt}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Kt}`)+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 ${Kt}`)+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(!Jt){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Gt(`Could not reach the learn server to open ${Kt}.`),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 ${Kt}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Gt(`Unknown learn token: ${Kt}`),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 sn=Vo(),an=!1,cn=!1;try{if(sn&&sn.token===Kt)st(sn),cn=!0;else{const e=rt(Kt),o=e?.adoptedFromServer?null:e;if(o)sn=o,sn.totalCards=Jt.totalCards,st(sn),cn=!0;else{const e=await ae(Kt),o=e?tt(Kt,Jt.id,Jt.totalCards,e):null;o?(sn=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()):(sn=ot(Kt,Jt.id,Jt.totalCards),an=!0)}}if(cn){const e=await ae(Kt);if(e){const o=sn.currentCard;nt(sn,Jt.totalCards,e),sn.currentCard>o&&(console.log(chalk.green(" ↩ ")+chalk.white((Do().language||"en").toLowerCase().startsWith("zh")?`已同步手机进度:${sn.cardsCompleted.length} 张卡完成,从第 ${sn.currentCard} 张继续`:`Synced your phone progress: ${sn.cardsCompleted.length} cards done, resuming at card ${sn.currentCard}`)),console.log())}}et(sn),ut(Jt,sn,an),function(e){if(!e)return;const o=(Do().language||"en").toLowerCase().startsWith("zh"),t="T0"===ye().tier;Ht(he(e,o,Bt(),t),!!e.completedAt)}(nn)}catch{return Gt("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 ${Kt}`)+chalk.gray(".")),void console.log()}const dn=N(),gn=null!==dn,un=gn?dn.listeners("line").slice():[];gn&&dn.removeAllListeners("line");const hn=gn?dn:o({input:process.stdin,output:process.stdout,terminal:!0}),pn=gn?hn.prompt:null;gn&&(hn.prompt=e.prototype.prompt);const yn=()=>{gn&&pn&&(hn.prompt=pn)};let mn=null,fn=!1,$n=!1,bn=null,wn=!1;const kn=()=>{hn.closed||(hn.setPrompt(Jn?chalk.bold.green(`icoa ${D()}> `):Un?chalk.bold.magenta(zl()):Dn?chalk.bold.magenta("icoa py> "):Wn?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Rn?"icoa learn ai> ":"icoa learn> ")),hn.prompt(),mn?.onPromptIdle())};let vn=null,_n=null,Cn=null,An=null;const xn=new Set,Tn=(e,o)=>{const t=e.flow??[];0!==t.length&&(o&&(console.log(chalk.yellow(" 🧭 ")+chalk.white(nr()?"这张卡是互动流程 —— 现在开始。选错不扣分,墙上写着为什么;":"This card is an interactive walk — starting now. Wrong turns cost nothing; the wall says why;")),console.log(chalk.gray(nr()?" 每一步在 icoa learn> 后面敲答案。back 退回卡片 · flow 再走一遍。":" type each answer after icoa learn>. back returns to the card · flow walks it again.")),console.log()),An=new ge({steps:t,zh:nr(),cardNumber:e.number,print:e=>console.log(e)}),"done"===An.start()&&Sn("done"))},Sn=e=>{if(!An)return;const o=An.records(),t=An.cardNumber;An=null;for(const e of o)dr.push(se(Kt,Jt.id,t,e).catch(()=>{}));if("done"!==e)return console.log(chalk.gray(nr()?" ↩ 已退出流程,回到卡片。":" ↩ Left the walk — back on the card.")),void console.log();const n=null!==Cn?yr(Cn):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(nr()?" ✅ 流程走完。":" ✅ Walk complete.")+chalk.cyan(nr()?" 🤔 现在回答卡片的检查题(输 y 或 n):":" 🤔 Now the card check (type y or n):")),console.log(chalk.white(` ${t}`)),console.log(chalk.gray(nr()?" (flow 再走一遍)":" (flow walks it again)"))}else console.log(chalk.gray(nr()?" ✅ 流程走完 — 敲 ok 下一张,或 flow 再走一遍。":" ✅ Walk complete — type ok for the next card, or flow to walk it again."));console.log()};let jn=null,Pn=[],In=!1,En=null;const Nn=/^(quit|exit|q|back|b|menu|home|contest(\s+(\d+|reset))?)$/i;let Ln=null,Mn=!1;const qn=()=>{En&&clearTimeout(En),En=null,Pn=[],In=!1,jn=null,Ln=null};let Rn=!1,On=!1,Wn=!1,Dn=!1,Un=!1,Yn=null,Bn="card",Fn=null,zn=null,Gn=null,Zn=!1,Hn=0,Kn=!1,Jn=!1;const Qn=new Map,Xn=()=>{let e=Qn.get(sn.currentCard);return e||(e=[],Qn.set(sn.currentCard,e)),e};let Vn=!1;const er=new Set;let or=!1,tr=0;const nr=()=>(Do().language||"en").toLowerCase().startsWith("zh");Tt(Vt||!Qt,Vt),Dt(Ut(Do())),Ot(er);const rr=new Map;Rt(rr),Wt(tn),Lt(nn);const lr="fill"===Jt.practiceMode,sr=Boolean(Jt.shellLane);Nt(sr);const ar=Jt.mobCheckpoints;jt("battleai"===Jt.practiceMode||Array.isArray(ar)),Pt("battleai"===Jt.practiceMode?[]:(ar??[]).map(e=>Number(e.card)).filter(e=>e>0).map(e=>{const o=Jt.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)),It(Array.isArray(Jt.duckCheckpoints)),Et("minimal"===Jt.footerProfile?"minimal":"full"),Mt(e=>{const o=yr(e),t=o?il(o):null;if(!t)return null;const n=Sr.get(rl+e);return t.map((e,o)=>`[${o+1}]${n?.has(al(e.py_id))||n?.has(e.py_id)?"✅":"⬜"}`).join(" ")});const ir=e=>{const o=yr(e),t=o?il(o):null;if(!t)return null;const n=Sr.get(rl+e);return{solved:t.filter(e=>n?.has(al(e.py_id))||n?.has(e.py_id)).length,total:t.length}};qt(ir);const cr=await ln;St(cr);const dr=[];let gr=null;const ur=new Promise(e=>{gr=e}),hr=()=>{const e=gr;gr=null,e?.()},pr="1"===process.env.ICOA_LEARN_EMBEDDED,yr=e=>Jt.cards.find(o=>o.number===e);mn=c();const mr={isZh:nr,canInterrupt:()=>!(wn||On||Rn||Wn||Dn||Jn||null!==Fn||null!==jn||null!==Gn),lineEmpty:()=>!hn.line,clearLine:()=>{try{process.stdout.write("\r")}catch{}},prompt:kn,currentCard:()=>sn.currentCard};p(()=>{const e=[],o=mn?.footerLine();o&&e.push(o);const t=$r();return null!==t&&t>0&&t<=2&&e.push(nr()?`🎁 还差 ${t} 项 · credits 看路线`:`🎁 ${t} to go · credits shows the road`),e.length?e.join("\n "):null});const fr=async(e,o)=>{const t=nr();if(Qt)return void console.log(chalk.gray(t?"故事属于正式 learn token。":" Stories belong to full learn tokens."));const n=await v(Kt,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===Jt.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(Jt,sn,wr,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===Jt.id?Jt.name:l.curriculum_id,l.curriculum_id===Jt.id?{longestStreak:sn.longestStreak,bookmarks:sn.bookmarks?.length??0}:{},t,Bt(),"T0"===ye().tier);console.log(),console.log(chalk.gray(t?" (回车跳到结尾)":" (Enter skips to the end)")),fn=!0,$n=!1;try{await S(s,()=>$n)}finally{fn=!1}if(l.curriculum_id===Jt.id&&!l.credits?.completed){for(const e of T(Jt,sn,wr,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()},$r=()=>{if(!sn||sn.creditsShownAt||Qt||!wr)return null;const e=x(Jt,sn,wr);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])},br=async(e=!1)=>{if(!sn||sn.creditsShownAt||Qt)return;const o=x(Jt,sn,wr);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(wr&&t>0&&t<=2&&(e||sn.creditsTeasedLeft!==t)){sn.creditsTeasedLeft=t,et(sn);const e=nr(),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(Jt,sn,wr,e))console.log(o);console.log()}return}sn.creditsShownAt=(new Date).toISOString(),et(sn),await fr(null,!1),kn()};let wr=null,kr=null;const vr=new Map,_r=new Map;let Cr=null;const Ar=(e,o)=>Cr?.[`${Jt.id}:${e}:${o}`]??null;q("contest-cells.json").then(e=>{Cr=e?.map??null;for(const[e,o]of Object.entries(Cr??{}))e.startsWith(`${Jt.id}:`)&&q(o)});const xr=(e,o,t)=>{const n=Ar(e,o);if(!n)return null;const r=oe(t,"explore.ipynb");if(!B(r)){const e=oe(M(),n);if(!B(e))return null;try{K(r,G(e))}catch{return null}}return r},Tr=!Kt.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Kt),Sr=new Map,jr=new Map,Pr=new Set,Ir=async()=>{if(!Tr)return;const e=await Ze(Kt);if(e.ok&&e.data){wr=e.data;for(const o of e.data.practice??[]){let e=Sr.get(o.slot);e||(e=new Set,Sr.set(o.slot,e));for(const t of o.solved)e.add(t)}br()}},Er=e=>{const o=Jt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Nr=e=>{if(!on||!wr)return null;const o=Er(e);if(o<=wr.unlocked_through_phase)return null;const t=wr.phases.find(e=>e.phase===wr.unlocked_through_phase),n=[chalk.yellow(nr()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${wr.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${wr.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(nr()?` ⚔ 练习赛 ${wr.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${wr.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(nr()?` ⚖ 判分赛: 最好 ${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(nr()?"、":", "),r=e.length>8?nr()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:nr()?" 张":"";n.push(chalk.gray(nr()?` ✓ 逐卡自测: ${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(nr()?` ⭐ 提问研究: ${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")},Lr=async e=>on?null===Nr(e)?null:(await Ir(),Nr(e)):null;Tr&&await Ir();const Mr=async e=>{const o=Jt.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=Jt.modules.find(e=>e.number===o.number+1);let n;if(Vt){const e=await Le({token:Kt,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}Tr&&await Ir();const r=wr?.phases.find(e=>e.phase===o.number);return At(Jt,sn,o,t,n,r),!0},qr=()=>{or=!0,console.log(chalk.gray(nr()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Rr=()=>{Gn=null;const e=yr(sn.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();mn?.noteCardShown(e.number,sn.cardsCompleted.includes(e.number));const o=ve($e(tn,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(nr()?`你有 ${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(` ${nr()?"你写的":"You wrote"}: ${(e.myText??"").slice(0,70)}${(e.myText?.length??0)>70?"…":""}`)),console.log(chalk.yellow(` 🐼 ${nr()?"回复":"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(" "+(nr()?"看完继续:next 去下一张卡;e 可再报告一条。":"Continue: type next, or press e to report again."))),console.log(),tn=tn.map(e=>o.some(o=>o.id===e.id)?{...e,seen:!0}:e)}switch(e.type){case"knowledge":{const o=lr&&Boolean(sn.checkResults?.[String(e.number)])&&e.check?{...e,check:void 0}:e;ht(o,Jt),o.check?(Cn=e.number,tr=Date.now()):(at(sn,e.number),et(sn));break}case"mcq":pt(e,Jt),vn=e.number;break;case"practical":mt(e,Jt),_n=e.number;break;case"sim_demo":$t(e,Jt),at(sn,e.number),et(sn);break;case"milestone":bt(e,Jt),gt(sn,e.badge),at(sn,e.number),et(sn);break;case"arena_task":wt(e,Jt),at(sn,e.number),et(sn);break;case"coming_soon":_t(e,Jt),at(sn,e.number),et(sn)}Or(e.number),gl(e),"knowledge"===e.type&&e.flow&&e.flow.length>0&&(xn.has(e.number)?(console.log(chalk.yellow(" 🧭 ")+chalk.gray(nr()?"敲 flow 再走一遍这张卡的互动流程。":"type flow to walk this card again.")),console.log()):(xn.add(e.number),console.log(),Tn(e,!0)))},Or=e=>{if(!Tr)return;const o=Jt.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=wr?.phases.find(e=>e.phase===o.number),s=l?.contest?.slots?.find(e=>e.slot===n),a=()=>{sn.arenaIntroShownAt||(kt(o.cardRange[1]-o.cardRange[0]+1),sn.arenaIntroShownAt=(new Date).toISOString(),et(sn))};if(!wr){const e="═".repeat(Bt()),t=chalk.bold.yellow(" ║ "),r=vt();return a(),console.log(chalk.bold.yellow(` ╔${e}`)),console.log(t+chalk.bold.white("⚔ "+(nr()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(nr()?" 成绩暂时取不到":" scoreline unavailable")),console.log(t+chalk.white(nr()?"这张卡下面有一场判分赛 — 服务器这会儿没答上来,所以显示不了你的成绩。":"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(nr()?" 照常可以开赛(开赛是另一次请求) · ":" still opens it (starting is a separate call) · ")+chalk.gray("▸ ")+chalk.bold.green("ok")+chalk.gray(nr()?" 继续学习":" 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(Bt()),l=chalk.bold.yellow(" ║ ");return console.log(chalk.bold.yellow(` ╔${t}`)),console.log(l+chalk.bold.white("⚔ "+(nr()?`练习赛 ${o.number}-${n}`:`Arena ${o.number}-${n}`))+chalk.gray(nr()?" 制作中":" in production")),console.log(l+chalk.white(nr()?"这里以后有一场判分赛 — 很快更新。":"A judged arena lands here — coming soon.")),console.log(l+chalk.gray(nr()?r.n>1?`每 4 张卡一场:卡 ${r.cards},本阶段共 ${r.n} 场,全过解锁下一阶段。${lr?"(本轨无 research)":""}`:`本阶段一场:卡 ${r.cards},过了解锁下一阶段。${lr?"(本轨无 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.${lr?" (no research on this track)":""}`:`One this phase — card ${r.cards}; passing it unlocks the next.${lr?" (no research on this track)":""}`)),console.log(l+chalk.gray(nr()?"▸ 现在什么都不用做 — 敲 ":"▸ Nothing to do yet — type ")+chalk.bold.green("next")+chalk.gray(nr()?" 继续读卡。":" 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?nr()?` · 用时 ${r}`:` · in ${r}`:"")+(l?` · ${l}`:"")},c=s.perfect_runs??[],d=!!s.best&&(s.best.ac??0)>0,g=chalk.bold.yellow(" ║ "),u="═".repeat(Bt());if(console.log(chalk.bold.yellow(` ╔${u}`)),console.log(g+chalk.bold.white(`⚔ ${nr()?(()=>{const t=(ar??[]).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(nr()?" ✅ 已通过":" ✅ passed"):"")),!s.passed){if(nr()?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(nr()?`${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?nr()?`(${e})`:` (${e})`:"";console.log(g+chalk.cyan(nr()?`🔗 你另一个 token${o}已做过这组的 ${s.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens${o} solved ${s.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(nr()?" 带过来(现在不做也行)":" to carry them over (or skip)"))}1!==o.number||lr||console.log(g+chalk.gray(nr()?"✍ 第一次用 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(nr()?"满分":"Perfect",s.n,e.ms,e.ts)));else d&&console.log(g+chalk.yellow(i(nr()?"最好":"Best",s.best.ac??0,s.best.ms,s.best.ts)));3===n&&l?.leader&&console.log(g+chalk.white(nr()?`🏅 本 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((nr()," — "))+chalk.bold.green("/honors")+chalk.gray(nr()?" 看你的位置":" shows where you stand"));const h=vt();console.log(g+chalk.gray("▸ ")+chalk.bold.green(h??`contest ${n}`)+(h?chalk.gray(nr()?` 进竞技场(${"battle"===h?"play":"run"} 试跑 → submit 判分) · `:` enter the arena (${"battle"===h?"play":"run"} → submit) · `):s.passed?chalk.gray(nr()?" 再战刷成绩 · ":" race it again · "):chalk.gray(nr()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(s.passed?chalk.gray(nr()?" 继续学习":" keep going"):chalk.gray(nr()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),!h&&(c.length>0||d)&&console.log(g+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(nr()?" 日后回来整阶段重做 · 全新计时+模板(旧文件自动归档)":" come back later and redo the whole phase · fresh clock + templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${u}`)),console.log()},Wr=()=>{Kt.endsWith("DEMO01")?console.log(chalk.yellow(nr()?" 🐼 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(nr()?" /submit 评分、荣誉榜与 /recall 是 🐼 AI 高级 token 的功能。":" Prompt grading (/submit), the honors board and /recall are premium 🐼 AI-token features.")),console.log(chalk.gray(nr()?` 你的 token 可以用 /ai 向熊猫导师提问(每卡每天 ${en} 问);要开通高级功能找领队 / 协调人。`:` Your token can still ask the tutor with /ai (${en} questions per card per day); ask your leader / coordinator for a premium token.`))),console.log()},Dr=async(e,o)=>{if(Qt)return void Wr();mn?.noteAi(Vt&&"deep"===o),On=!0;const t=nr()?"🐼 熊猫导师思考中…":"🐼 Panda tutor is thinking…",n=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"];let r=null;const l=()=>{r&&(clearInterval(r),r=null,process.stdout.write("\r"))},s=()=>nr()?` (本卡今天的 ${en} 个问题已用完 — 24 小时后再问,或先去下一张卡)`:` (this card's ${en} 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 Re({token:Kt,cardNumber:sn.currentCard,question:e,mode:o,history:Xn().slice(-8),lang:nr()?"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(Vt?nr()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)":nr()?" (被判定与本卡主题无关 — 不会回答,也不计入本卡的次数)":" (judged unrelated to this card — not answered, and it does not count toward this card's questions)"))):(Xn().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(` (${nr()?"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(nr()?" (本卡今天还可以问最后 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||(nr()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Cn&&console.log(chalk.gray(nr()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{l(),On=!1}},Ur=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Yr=async()=>{Wn&&kr?kl?_l(kl):$l():Gn?await Br():Rr()},Br=async()=>{On=!0;try{console.log();const e=await De({token:Kt,curriculumId:Jt.id,cardNumber:sn.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(nr()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(Tr&&(await Ir(),(e=>{const o=Jt.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const[t,n]=o.cardRange,r=sn.checkResults||{};let l=0,s=0,a=0;for(let e=t;e<=n;e++){const o=yr(e);null!=o?.check&&a++;const t=r[String(e)];t&&(l++,t.correct&&s++)}console.log(chalk.bold.white(nr()?` 🧭 Phase ${o.number} 进度 — ${o.name}(卡 ${t}-${n})`:` 🧭 Phase ${o.number} progress — ${o.name} (cards ${t}-${n})`)),console.log(chalk.gray(nr()?" 理解检查: ":" comprehension: ")+chalk.white(`${s}/${l}`)+chalk.gray(nr()?` 答对 · ${a-l} 张未作答`:` correct · ${a-l} unanswered`));const i=wr?.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(nr()?`未开始 · ${e.n} 题 · 过 ${e.need} 题`:`not started · ${e.n} problems · AC ${e.need}`):chalk.yellow(nr()?`最好 ${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(` ⚔ ${nr()?"练习赛":"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=ir(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(nr()?" 卡片练习: ":" practice: ")+chalk.white(`${d}/${g}`)+chalk.gray(nr()?` 卡全完成 · ${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(nr()?" 卡号:已过/共 — 绿 全完成 · 黄 做了一部分 · 灰 未碰":" card:solved/total — green done · yellow partial · gray untouched"))}console.log()})(sn.currentCard)),console.log(chalk.bold.white(nr()?` 🏆 本卡实时 Top-3 — 第 ${sn.currentCard} 张`:` 🏆 Live top-3 — card ${sn.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(nr()?" (你)":" (you)"):""))}else console.log(chalk.gray(nr()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));if(e.mine?(rr.set(sn.currentCard,e.mine.rank),console.log(chalk.white(nr()?" 你: ":" You: ")+chalk.bold.yellow(nr()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(nr()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Vt&&console.log(chalk.gray(nr()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ft({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),e.phaseBoard){const o=e.phaseBoard,t=["🥇","🥈","🥉"];console.log(chalk.bold.white(nr()?` 🏅 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(nr()?" (还没有人有研究总分 — 第一个 /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(nr()?`(${e.cards}/${o.cards_in_phase} 卡)`:` (${e.cards}/${o.cards_in_phase} cards)`)+(e.me?chalk.bold.magenta(nr()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(nr()?` 总分 ${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(nr()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.total}`)+chalk.gray(nr()?`(${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&&Vt&&console.log(chalk.gray(nr()?" 你: 还未计入 — /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(nr()?` ⚔ 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(nr()?" (还没有人 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(nr()?" (你)":" (you)"):""));o.unveiled||console.log(chalk.gray(nr()?` 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(nr()?" 你: ":" You: ")+chalk.bold.yellow(`${o.mine.ac} AC`)+chalk.gray(nr()?` · 第 ${o.mine.rank} 名 / 共 ${o.mine.entrants} 人`:` · rank ${o.mine.rank} of ${o.mine.entrants}`)):o.mine||console.log(chalk.gray(nr()?" 你: 还未计入 — 在有 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(nr()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(nr()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(nr()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Gn="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(nr()?" 返回卡片":" returns to the card")),console.log()}finally{On=!1}},Fr=()=>(Do().language||"en").slice(0,2).toLowerCase(),zr=e=>{const o=e[`title_${Fr()}`];return"string"==typeof o&&o||e.title},Gr=e=>{const o=e[`statement_${Fr()}`];return"string"==typeof o&&o||e.statement},Zr=e=>"mob-match"===e?.kind,Hr=()=>!!kr&&kr.data.problems.some(e=>Zr(e)),Kr=lo(Jt.id);let Jr=!1;const Qr=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of zt(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Xr={cpp:"cpp",java:"java",go:"go"},Vr=e=>e?.lang&&Xr[e.lang]?e.lang:"python",el=(e,o)=>{const t=Vr(o);return`sol-${e}.${"python"===t?"py":Xr[t]}`},ol=(e,o)=>{const t=[...Kr?[{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=Kr&&l===to,a=s?`══ ${t.title} ══`:`══ ${e.title||"PY Arena"} · ${t.title} ══`;for(const e of["py",...Object.values(Xr)]){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,el(l,t));if(B(c))return;const d=[s?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Qr(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||Zr(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 zt(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(???)",""):Zr(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"===Vr(t)?d:d.map(e=>e.startsWith("#")?`//${e.slice(1)}`:e),h=Zr(t)&&nr()&&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(nr()?` 📦 本组题目已更换 — ${r} 个旧题答题文件已归档为 *.archived-${n},新题文件已就位`:` 📦 This group's problems changed — ${r} old solution file(s) archived as *.archived-${n}, fresh files written`))},tl=e=>{console.log(),console.log(chalk.bold.green(nr()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(nr()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},nl=e=>e.id===oo?Jr?"✅":"⬜":kr.data.solved.includes(e.id)?"✅":kr.data.carried?.includes(e.id)?"✅↗":kr.tried.has(e.id)?"❌":"⬜",rl=100,ll=()=>!!kr&&kr.data.slot>=rl,sl=(e,o)=>{const t=oe(process.cwd(),"icoa-contest",`${Jt.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(nr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${n}`))}catch{console.log(chalk.yellow(nr()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (restart still fine): ${t}`))}},al=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,il=e=>{const o=e?.practice;if(!o||!Array.isArray(o.problems)||0===o.problems.length)return null;const t=o.problems.filter(e=>cl(e));return[...o.problems.filter(e=>e.is_signature&&!cl(e)),...o.problems.filter(e=>!e.is_signature&&!cl(e)).sort((e,o)=>(e.difficulty??0)-(o.difficulty??0)||(e.order??0)-(o.order??0)),...t]},cl=e=>"mob-match"===e.kind,dl=()=>{if(!lr)return!1;const e=yr(sn.currentCard),o=e?il(e):null;if(!e||!o||Pr.has(e.number))return!1;const t=rl+e.number,n=Sr.get(t),r=jr.get(t),l=o.map((e,o)=>{return t=e.py_id,Boolean(n?.has(al(t))||n?.has(t)||r?.has(al(t))||r?.has(t))?0:o+1;var t}).filter(e=>e>0);return 0!==l.length&&(console.log(chalk.yellow(nr()?` ⚔ 这张卡还有 ${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(nr()?" 开始,或 ":" to start, or ")+chalk.bold.yellow("skip")+chalk.yellow(nr()?" 跳过本卡练习。":" to skip this card's practice.")),!0)},gl=e=>{const o=il(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=Sr.get(rl+e.number);console.log(chalk.bold.yellow(nr()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(nr()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(al(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))));cl(e)?console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ⚔ ${chalk.bold.white(nr()?"对局":"battle")}`+chalk.gray(nr()?` — 改一行 · 打一局 · 看回放 · 判分 (敲 ${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(nr()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},ul=e=>e.split("\n").filter(e=>!e.trim().startsWith("#")).join("\n").split("____").length-1,hl=e=>{console.log(chalk.yellow(nr()?` ⏱ 每次练习 ${e} 分钟,这次的时间到了。`:` ⏱ Each practice window is ${e} minutes — this one has run out.`)),console.log(chalk.gray(nr()?" 敲 ":" Type ")+chalk.bold.green("back")+chalk.gray(nr()?" 回卡片,再敲 ":" for the card, then ")+chalk.bold.green("practice 1")+chalk.gray(nr()?" 重新开始(重新计时)。":" to restart with a fresh clock."))},pl=()=>Fn?Fn.data.problems[Fn.idx]??null:null,yl=()=>{const e=pl();if(!Fn||!e)return;const o=ul(e.starter??""),t=Fn.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(nr()?` 空${t}/${o}`:` blank ${t}/${o}`)+chalk.gray(" · ")+chalk.white(n)),console.log(chalk.gray(nr()?" ▸ 敲答案后回车(back 回卡片)":" ▸ type the answer, press Enter (back = card)"))},ml=()=>{const e=pl();if(!Fn||!e)return;const o=zr(e);console.log(),console.log(chalk.bold.yellow(` ⚡ ${nr()?"练习":"Practice"} ${Fn.idx+1}/${Fn.data.problems.length} · ${o}`));const t=(Gr(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(),yl()},fl=()=>{if(Fn){if(Fn.idx+1<Fn.data.problems.length)return Fn.idx+=1,Fn.answers=[],Fn.tries=0,void ml();console.log(chalk.bold.green(nr()?" 🎉 本卡练习全部完成!":" 🎉 Card practice complete!")+chalk.gray(nr()?" ok 进下一张卡。":" ok moves on to the next card.")),Fn=null,zn=null,Rr()}},$l=()=>{const e=kr.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>=rl?e.slot-rl:null,s=e.problems.find(e=>Zr(e)),a=nr()&&s?.title_zh?`检查点 · 卡 ${s.card} · ${s.title_zh}`:e.title||"PY Arena";if(console.log(chalk.bold.yellow(` ⚔ ${a}`)+chalk.gray(null!=l?nr()?` · 第 ${l} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${l} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:nr()?` · 第 ${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(nr()?" ⏱ 已超时 — 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(nr()?`(共 ${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(nr()?` 🎉 满分 ${e.n}/${e.n} — 本组全部拿下!`:` 🎉 Perfect ${e.n}/${e.n} — every problem cleared!`)+chalk.gray(nr()?" ↩ back 回卡片":" ↩ back returns to the card"):chalk.green(nr()?" 🏁 已过关":" 🏁 passed")+chalk.yellow(nr()?` · 还剩 ${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(nr()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" 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?nr()?`(${o})`:` (${o})`:"";console.log(chalk.cyan(nr()?` 🔗 你另一个 token${t}已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens${t} solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(nr()?" 带过来,不必重做":" 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(nr()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(nr()?"不够就 ":"Short on time? ")+chalk.bold.green("contest restart")+chalk.gray(nr()?" 满血重开本组。":" restarts this group fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(nr()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),Kr&&(console.log(chalk.gray(" 0 ")+nl(eo)+chalk.gray(` ${zr(eo)}`)+chalk.gray(nr()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+nl(e)+(e.gpu?chalk.magenta(" ⚡"):"")+chalk.white(` ${zr(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(nr()?" ⚡ GPU 开 ✅":" ⚡ GPU on ✅")+chalk.gray(nr()?" — /submit 一道 ⚡ 题,就在真 GPU 上跑":" — /submit a ⚡ rung and it runs on a real GPU right now")):"booting"===o?console.log(chalk.bold.yellow(nr()?" ⚡ GPU 开机中…":" ⚡ GPU booting…")+chalk.gray(nr()?" — 约 3–5 分钟,稍后重新 /submit":" — takes ~3–5 min; retry /submit shortly")):console.log(chalk.bold.gray(nr()?" ⚡ GPU 关":" ⚡ GPU off")+chalk.gray(nr()?" — 直接 /submit 一道 ⚡ 题会自动开机(约 3–5 分钟),之后重新 /submit":" — /submit a ⚡ rung to auto-boot the GPU (~3–5 min), then /submit again"))}Ar(kr.phase,e.slot)&&(console.log(),console.log(chalk.gray(" ✍ ")+chalk.bold.green("cells")+chalk.gray(nr()?" 在 notebook 里探索本场数据(引导走查 · 真图) — 不判分,判分仍走 /submit":" explore this lab in a notebook (guided walkthrough · real figures) — ungraded; judging stays /submit"))),console.log(),bl()},bl=()=>{console.log(chalk.gray(Hr()?nr()?" /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)":nr()?" /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(nr()?"/syntax <词>":"/syntax <word>")+chalk.gray(nr()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(nr()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(nr()?" 返回课程":" returns to the lesson")),console.log(chalk.gray(nr()?" memo 报告题面/判分问题 — 不打断比赛计时":" memo reports a statement/judging problem — the clock is unaffected")),console.log(chalk.gray(" ")+chalk.bold.green("contest restart")+chalk.gray(nr()?" 超时/坏场时重开本组(全新计时+模板) · ":" time up or broken attempt → this group again (fresh clock + templates) · ")+chalk.bold.green("contest reset")+chalk.gray(nr()?" 日后回来整阶段重做":" come back later and redo the whole phase")),console.log()},wl=e=>{const o=parseInt(e,10),t=kr.data.problems;if(o===to&&Kr)return{p:eo,n:to};const n=Kr?to:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(nr()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),Kr&&console.log(chalk.gray(nr()?" 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 kl=null,vl=!1;const _l=e=>{const o=wl(e);if(!o)return;const{p:t,n:n}=o;kl=String(n),console.log(),console.log(chalk.bold.white(` ${nl(t)} ${zr(t)}`)),console.log();for(const e of Gr(t).split("\n"))if(e.trim())for(const o of zt(e,Bt()+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(nr()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(nr()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(Zr(t)){const e=Array.isArray(t.crit)?t.crit:[],o=Number(e[2]??10),r="mined"===e[0]?nr()?`采矿 ≥ ${e[1]}`:`mine ≥ ${e[1]} opal`:"winrate"===e[0]?nr()?`${o} 局赢 ≥ ${Math.round(100*Number(e[1]))}%`:`win ≥ ${Math.round(100*Number(e[1]))}% of ${o} games`:"";console.log(),console.log(chalk.gray(nr()?" 对手 ":" vs ")+chalk.white(String(t.opp??"?"))+chalk.gray(nr()?" · 地图 ":" · map ")+chalk.white(String(t.map??"?"))+chalk.gray(nr()?" · 回合 ":" · turns ")+chalk.white(String(t.turns??"?"))+(r?chalk.gray(nr()?" · 过线 ":" · pass: ")+chalk.bold.white(r):""));const l=nr()&&t.hint_zh||t.hint;if(l){console.log();let e=!0;for(const o of l.split("\n"))for(const t of zt(o,Bt()-2))console.log(e?chalk.yellow(" 🧭 ")+chalk.white(t):chalk.white(` ${t}`)),e=!1}console.log();let s=!1;try{s=jl(G(oe(kr.dir,el(n,t)),"utf8")).length>0}catch{s=!1}console.log(chalk.gray(" ▸ ")+chalk.bold.green(s?"set <KNOB> <value>":`/edit ${n}`)+chalk.gray(nr()?" 改一行":" change one line")+chalk.gray(" → ")+chalk.bold.green(`/run ${n}`)+chalk.gray(nr()?" 本机打一局(开回放)":" play one match here (replay opens)")+chalk.gray(" → ")+chalk.bold.green(`/submit ${n}`)+chalk.gray(nr()?" 判分":" judge")),s&&console.log(chalk.gray(nr()?" 旋钮列表敲 ":" bare ")+chalk.bold.green("set")+chalk.gray(nr()?" · 想直接看文件用 ":" lists the knobs · the file itself is ")+chalk.bold.green(`/edit ${n}`))}else 0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(nr()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)")));if(t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(nr()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=nr()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of zt(o,Bt()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(nr()?"数据就在上方 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(),Kr&&n===to)return console.log(chalk.white(nr()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(nr()?"第 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(nr()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(nr()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((nr()," ↩ "))+chalk.bold.green("back")+chalk.gray(nr()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(nr()?" 直接看正式题目":" skips straight to the real problems")),void console.log();if(Zr(t));else if(t.quiz){const e=Xe(t);let o;if("letter"===e.kind)o=nr()?"输入字母 A–E 回车":"type a letter A–E, press Enter";else if("choose"===e.kind){const t=e.options.join(" / ");o=nr()?`输入其中一个词回车:${t}`:`type one of ${t}, press Enter`}else o=nr()?"输入 answer 你的答案 回车":"type answer <your answer>, press Enter";console.log(chalk.gray(" ▸ ")+chalk.bold.green(o)+chalk.gray(nr()?" 即提交这一题 · 也可以 ":" to submit this one · or ")+chalk.bold.green(`/edit ${n}`)+chalk.gray(nr()?" 在 vi 里填":" to fill it in vi")),"value"===e.kind&&console.log(chalk.gray(nr()?" 例如 ":" e.g. ")+chalk.white("answer 1200")+chalk.gray(nr()?" · 只填空里的那个值,不用写整句":" · just the value that fills the blank, not the whole sentence"))}else t.gpu?(console.log(chalk.white(nr()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(nr()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(nr()?"真 GPU 上跑并带回你的 ms(⚡ 每周一窗口 19:00–21:45 悉尼)":"runs on a real GPU and returns your ms (⚡ Monday window 19:00–21:45 Sydney)"))):t.starter&&!Zr(t)?(console.log(chalk.white(nr()?" 三步:":" Three steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(nr()?"填空(vi:i 编辑 · Esc · :wq 存盘退出)":"fill the blank (vi: i · Esc · :wq)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(nr()?"本机直跑,出你自己的 ms":"run it locally — see your own ms")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(nr()?"参考机判分(成绩 = 那里的 ms)":"judge on the reference machine (the scored ms)"))):(console.log(chalk.white(nr()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(nr()?"写码(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(nr()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(nr()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(nr()?"正式判分(隐藏用例)":"official judging (hidden tests)")));console.log(),Zr(t)||t.quiz||(console.log(chalk.gray(nr()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(nr()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log()),console.log(chalk.gray((nr()," ↩ "))+chalk.bold.green("back")+chalk.gray(ll()?nr()?" 回花名册 · ":" to the roster · ":nr()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(nr()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang")+chalk.gray((nr()," / "))+chalk.bold.green("wide")+chalk.gray(nr()?" 换语言/宽度":" language / width")),console.log()},Cl=async(e,o,t)=>await new Promise(n=>{const s=process.stdin,a=!!s.isTTY&&!!s.isRaw;if(hn.pause(),s.isTTY&&"function"==typeof s.setRawMode)try{s.setRawMode(!1)}catch{}wn=!0;const i=r(e,o,{stdio:"inherit",cwd:t??kr.dir}),c=e=>{if(s.isTTY&&"function"==typeof s.setRawMode&&a)try{s.setRawMode(!0)}catch{}l(),wn=!1,hn.resume(),n(e)};i.on("close",()=>c(null)),i.on("error",e=>c(e))}),Al=Ko,xl=()=>{const e=E("vi");console.log(chalk.gray(nr()?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"))},Tl=()=>Mo(nr(),{judgeIsServerSide:!0}),Sl=()=>{const e=Oo();return e||Tl(),e},jl=e=>[...new Set([...e.matchAll(/^([A-Z][A-Z0-9_]*)\s*=\s*[^#\n]+/gm)].map(e=>e[1]))],Pl=(e,o)=>{const t=new RegExp(`^${o}\\s*=\\s*([^#\n]*?)\\s*(?:#.*)?$`,"m").exec(e);return t?t[1]:null},Il=async(e,o)=>{P(`learn-arena p${kr.phase}s${kr.data.slot}: answer ${o.trim().slice(0,40)}`),((e,o)=>{const t=oe(kr.dir,el(e.n,e.p));let n;try{n=G(t,"utf8")}catch{return console.log(chalk.yellow(nr()?" 先 /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 Hl(`/submit ${e.n}`):kn()},El=new Map,Nl=()=>fo(process.cwd(),Jt.id),Ll=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(!Tr)return;let n;try{n=G($o(Nl(),e),"utf-8")}catch{return}if(Buffer.byteLength(n,"utf-8")>so)return;const r=mo(n),l=(new Date).toISOString(),s=yo(Wo(),Kt).slice(0,co),a=await _o(Kt,{n:e,title:bo(n.split("\n",1)[0]),code:n,code_sha:r,card_number:sn.currentCard,run_meta:o,client_ts:l,events:s.length>0?s:void 0});a?s.length>0&&wo(Wo(),Kt,s.length):ko(Wo(),Kt,{n:e,code_sha:r,card_number:sn.currentCard,run_meta:o,client_ts:l}),a||t||console.log(chalk.gray(nr()?" (未能同步到服务器 — 草稿只保存在本机)":" (could not reach the server — this scratch is saved locally only)"))},ql=()=>{console.log(chalk.gray(nr()?" 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()},Rl=e=>{const o=uo(Nl()),t=parseInt(e,10);return Number.isInteger(t)&&o.some(e=>e.n===t)?t:(0===o.length?console.log(chalk.yellow(nr()?" 还没有任何草稿 — ":" No scratch files yet — ")+chalk.bold.green("/py")+chalk.gray(nr()?" 新建第一个。":" creates the first one.")):console.log(chalk.yellow(nr()?` 没有 py-${e} — 现有编号: `:` No py-${e} — you have: `)+chalk.white(o.map(e=>e.n).join(", "))+chalk.gray(nr()?" · pylist 看列表":" · pylist shows them")),null)},Ol=e=>{const o=uo(Nl()),t=e?.trim().toLowerCase(),n=t?o.filter(e=>(e.title??"").toLowerCase().includes(t)):o;if(console.log(),console.log(chalk.bold.magenta(nr()?" ✍ 我的 Python 草稿":" ✍ My Python scratch files")+(t?chalk.gray(` · "${e?.trim()}"`):"")+chalk.gray(` (${n.length})`)),0===o.length)return console.log(chalk.gray(nr()?" 还没有草稿 — ":" Nothing here yet — ")+chalk.bold.green("/py")+chalk.gray(nr()?" 新建一个(第一行写标题)。":" creates one (line 1 becomes its title).")),void console.log();if(0===n.length)return console.log(chalk.gray(nr()?` 没有匹配 "${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(zt(e.title,40)[0]??e.title):chalk.gray(nr()?"(未命名 — 第一行写标题)":"(untitled — line 1 becomes the title)");console.log(chalk.gray(` py-${String(e.n).padEnd(3)} `)+o+chalk.gray(` · ${Ll(e.mtimeMs)}`))}console.log(chalk.gray(" ▸ ")+chalk.bold.green(nr()?"/py <编号>":"/py <n>")+chalk.gray(nr()?" 打开 · ":" opens one · ")+chalk.bold.green("/py")+chalk.gray(nr()?" 新建":" new file")),console.log()},Wl=async e=>{const o=$o(Nl(),e);if(Jo())return console.log(chalk.yellow(nr()?" icoa 正跑在 Windows 上 — 草稿本的编辑器在 Ubuntu(WSL)那一侧。":" icoa is running on Windows — the scratchpad editor lives on the Linux (WSL) side.")),console.log(chalk.gray(nr()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${o}`)),void console.log();if(!Xo("vi"))return console.log(chalk.yellow(nr()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${o}`)),void console.log(chalk.gray(nr()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));xl();const t=e=>{try{return H(e).size}catch{return 0}},n=t(o),r=Date.now(),l=I(o);await Cl("vi",[...Al,`py-${e}.py`],Nl());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(nr()?" 已回到草稿本 — ":" Back in the scratchpad — ")+chalk.bold.green(`run ${e}`)+chalk.gray(nr()?" 本机运行 · ":" runs it locally · ")+chalk.bold.green(`edit ${e}`)+chalk.gray(nr()?" 再改。":" reopens vi.")),console.log()},Dl=async e=>{let o;if(F(Nl(),{recursive:!0}),e){const t=Rl(e);if(null===t)return;o=t}else{const e=uo(Nl());o=po(e),o>ao&&console.log(chalk.gray(nr()?` (已超过 ${ao} 个 — 服务器不再备份新文件,本机照常保存)`:` (past ${ao} files — the server stops backing new ones up; local saves still work)`)),K($o(Nl(),o),`${nr()?go:io}\n\n`)}const t=!Dn;Dn=!0,P(`learn-py: open ${o}${e?"":" (new)"}`),t&&(console.log(),console.log(chalk.bold.magenta(nr()?" ✍ Python 草稿本":" ✍ Python scratchpad")+chalk.gray(nr()?" — 你的个人练习文件 · 只在本机运行 · 不判分":" — your personal practice files · runs locally · never judged")),console.log(chalk.gray(nr()?" 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(nr()?" 回卡片(退一层)":" returns to the card (one level)"))),await Wl(o),ql()},Ul=()=>jo(process.cwd(),Jt.id),Yl=()=>Yn??xo(So(process.cwd(),Jt.id,sn.currentCard)),Bl=()=>{console.log(),console.log(chalk.bold.magenta(nr()?" ⌨ shell 实验台":" ⌨ shell lab")+chalk.gray(nr()?" — 在这里动手把答案弄出来 · 不判分 · 不解锁任何东西":" — work the answer out here · never judged · unlocks nothing")),console.log(chalk.gray(nr()?` 真的 shell:管道 | 、重定向 > 、通配符 * 都能用 · 每条命令最多 ${Co/1e3} 秒`:` A real shell: pipes |, redirection >, globs * all work · ${Co/1e3}s per command`)),console.log(chalk.gray(nr()?` 你在 ${No(Ul())} 里面 —— 只能在这个文件夹内走动(自己的终端不受限)`:` You are inside ${No(Ul())} — you can only move within it (your own terminal is unrestricted)`)),console.log(chalk.gray(" ↩ ")+chalk.bold.green("back")+chalk.gray(nr()?" 回卡片(退一层)":" returns to the card (one level)")),console.log()},Fl=()=>{console.log(chalk.gray(nr()?" 敲任何 shell 命令 · cd 换目录 · reset 还原文件 · clear 清屏 · ↩ back "+("fill"===Bn?"回到这道题":"arena"===Bn?"回赛场":"回卡片"):" type any shell command · cd to move · reset restores files · clear · ↩ back "+("fill"===Bn?"returns to the problem":"arena"===Bn?"returns to the arena":"returns to the card")))},zl=()=>`icoa sh ${Eo(Ul(),Yl())}> `,Gl=(e=!1)=>{const o=yr(sn.currentCard)?.files;if(!o)return[];const t=xo(So(process.cwd(),Jt.id,sn.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},Zl=(e="card")=>{Bn=e;const o=!Un;Un=!0,Yn=Yl();const t=Gl();P(`learn-sh: enter card${sn.currentCard}`),o&&Bl(),t.length>0&&(console.log(chalk.bold.green(nr()?" 📦 本卡的文件已放好:":" 📦 This card ships files:")+chalk.white(` ${t.join(" ")}`)),console.log(chalk.gray(nr()?" 先敲 ls 看看。":" Start with `ls`.")),console.log()),Fl()},Hl=async e=>{const o=e.trim().toLowerCase(),l=Wn&&o.startsWith("/")?o.slice(1):o;if(fn)return void($n=!0);if(bn){const{sameName:o,issueCertificate:t,announceCertificate:n}=await import("../lib/learn-certificate.js"),r=e.trim(),l=nr();if(!r||Nn.test(r))return bn=null,console.log(chalk.gray(l?" 已取消,未签发。":" Cancelled — nothing issued.")),void kn();if(null===bn.first)return bn.first=r,console.log(chalk.gray(l?" 再输一次:":" Type it once more:")),void kn();const s={cid:bn.cid,tok:bn.tok,first:bn.first};return bn=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 kn()):(console.log(chalk.yellow(l?" 两次输入不一致 — 未签发。再敲 certificate 重来。":" The two names differ — nothing issued. Type certificate to try again.")),void kn())}if(On)return;if(mn?.noteInput(),!Fn&&mn?.consumeRating(o))return void kn();if(Fn)return await(async e=>{if(!Fn)return;const o=e.trim(),t=o.toLowerCase();if(sr&&("sh"===t||"/sh"===t))return zn=Fn,Fn=null,Zl("fill"),void console.log(chalk.gray(nr()?" ▸ 看完敲 back 回到这道题。":" ▸ When you have looked: back returns to this problem."));if("back"===t||"quit"===t||"menu"===t)return Fn=null,zn=null,console.log(chalk.gray(nr()?" ↩ 回到卡片。":" ↩ Back on the card.")),void Rr();if("skip"===t)return void fl();if(""===o)return void ml();const n=pl();if(!n)return Fn=null,void Rr();const r=ul(n.starter??"");if(Fn.answers.push(o),Fn.answers.length<r)return void yl();const l=[...Fn.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);Fn.answers=[];let a=jr.get(Fn.slot);a||(a=new Set,jr.set(Fn.slot,a)),a.add(n.id);const i=Boolean(n.quiz),c=i?null:new W(Kt);c?.start();const d=await Be(Kt,Fn.phase,n.id,s,Fn.slot,void 0);if(c?.stop(),!Fn)return;if(!d.ok||!d.data)return"no_active_session"===d.code?void hl(Fn.data.duration_minutes):(console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),console.log(chalk.gray(nr()?" 再敲一遍空1重试,或 back 回卡片。":" Type blank 1 again to retry, or back for the card.")),void yl());const g=d.data;if("AC"!==g.verdict||g.already_ac||mn?.notePracticeAc(),g.already_ac||"AC"===g.verdict){i?console.log(chalk.bold.green(nr()?" ✅ 答对了!":" ✅ Correct!")):console.log(Lo("AC",{isZh:nr(),gentle:!0,passed:g.passed_tests??g.total_tests??null,total:g.total_tests??null,ms:g.time_ms??null}));let e=Sr.get(Fn.slot);return e||(e=new Set,Sr.set(Fn.slot,e)),e.add(n.id),Fn.data.solved.includes(n.id)||Fn.data.solved.push(n.id),void fl()}Fn.tries+=1,i?console.log(chalk.red(nr()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(nr()?" — 再选一次。":" — pick again.")):console.log(Lo(g.verdict??"WA",{isZh:nr(),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(nr()?" 期望输出:":" Expected output:"));for(const e of u.out.trimEnd().split("\n"))console.log(chalk.white(" "+e))}if(2===Fn.tries||Fn.tries>2&&Fn.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(nr()?` ⚠ 空${i}:模板里 ____ 后面已经有 ( ) — 只填名字,别再带括号。`:` ⚠ blank ${i}: the ( ) after ____ is already in the template — type just the name, no brackets.`):(/["']$/.test(a)||/^["']/.test(s))&&/^["']|["']$/.test(l)?t.push(nr()?` ⚠ 空${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(nr()?` ⚠ 空${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(nr()?" 💡 两次没过,多半是细节不是思路 — 再敲之前过一遍:":" 💡 Two misses are usually a detail, not the idea — run this check before retrying:")),i||(console.log(chalk.gray(nr()?" · 拼写和大小写(Python 区分大小写:Print ≠ print)":" · spelling and case (Python is case-sensitive: Print ≠ print)")),console.log(chalk.gray(nr()?" · 只填缺的那一块 — ____ 周围已有的括号、引号、冒号不要重复":" · fill only what is missing — brackets, quotes, colons already around ____ stay"))),console.log(chalk.gray(nr()?" · 没思路?往上翻,或 ":" · no idea? scroll up, or ")+chalk.bold.green("back")+chalk.gray(nr()?" 回卡片再读一遍 — 答案就在正文里。打错字人人都有,继续。":" re-reads the card — the answer is in its body. Typos happen to everyone; keep going."))}console.log(chalk.gray(nr()?" 从空1再来:":" From blank 1 again:")),yl()})(e),void kn();if(null!==jn){if(Pn.push(e.replace(/\s+$/,"")),En&&clearTimeout(En),En=null,In){const e=Pn[Pn.length-1]??"";return"/cancel"===e.trim()?(qn(),console.log(chalk.gray(nr()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void kn()):""!==e.trim()?void kn():(Pn.pop(),void await c())}return void(En=setTimeout(()=>{if(En=null,Pn.length>1){In=!0;const e=Pn.length;return console.log(chalk.cyan(nr()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(nr()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void kn()}c()},140))}async function c(){const e=Pn.join("\n").replace(/^\s+|\s+$/g,""),o=jn??sn.currentCard,t=Pn.length,n=Ln;if(qn(),""===e)console.log(chalk.gray(nr()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&Nn.test(e))console.log(chalk.yellow(nr()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(nr()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(nr()?" 即可执行。":" again to run it."));else{const r=!n&&tr>0?Date.now()-tr:void 0;if(await ie(Kt,{curriculum_id:Jt.id,card_number:o,feedback_text:n?`${n} ${e}`:e,time_on_card_ms:r})){const n=t>1?nr()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(nr()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(nr()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),tn=[...tn,{id:rn--,curriculumId:Jt.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Wt(tn)}else console.log(chalk.yellow(nr()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),kn()}if(Zn){const o=e.trim();if(Nn.test(o))return Zn=!1,console.log(),console.log(chalk.yellow(nr()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(nr()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(nr()?" 即可执行该命令。":" again to run it.")),console.log(),void kn();if(!o)return Zn=!1,console.log(chalk.gray(nr()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void kn();const t=await qe({token:Kt,nickname:o});if(t.ok)Zn=!1,console.log(chalk.bold.green(nr()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(nr()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Hn+=1;const e="taken"===t.code?nr()?"已被占用":"already taken":"bad_charset"===t.code?nr()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"real_name"===t.code?nr()?"看起来像真名 — 系统不收集个人信息,换个游戏风格的昵称":"looks like a real name — we collect no personal info; pick a gamer-style handle":"rejected"===t.code?nr()?"未通过审核":"did not pass review":t.message||"error";if(!(Hn>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(nr()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void kn();Zn=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(nr()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void kn()}if(Vn){Vn=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{On=!0;try{console.log(),console.log(chalk.gray(nr()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await Oe({token:Kt,cardNumber:sn.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(nr()?"评审暂不可用。":"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(nr()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(nr()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(nr()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(nr()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(nr()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(nr()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=nr()?` 本卡排名 #${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(nr()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(nr()?` 第 ${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 Ur(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(nr()?" 改进提问: ":" 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(` (${nr()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?er.add(sn.currentCard):er.delete(sn.currentCard),"number"==typeof e.rank&&rr.set(sn.currentCard,e.rank);const o=await De({token:Kt,curriculumId:Jt.id,cardNumber:sn.currentCard});if(o.ok&&o.totals&&o.chapters&&(Ft({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(nr()?` · 榜首 ${n.name||"Rank 1"} ${n.total}`:` · leader ${n.name||"Rank 1"} at ${n.total}`):chalk.bold.yellow(nr()?" · 全场第一!":" · phase leader!");console.log(chalk.white(nr()?` 🏅 Phase ${e.phase} 研究总分: `:` 🏅 Phase ${e.phase} research total: `)+chalk.bold.yellow(`${t.total}`)+chalk.gray(nr()?`(${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&&!Qt&&(Zn=!0,Hn=0,console.log(chalk.bold.yellow(nr()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(nr()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(nr()?" 英文开头,英文+数字,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(nr()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Cn&&(console.log(chalk.gray(nr()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void kn()}if(or)return or=!1,Rr(),void kn();if(!o)return void kn();if(Jn)return"exit"===await U(e.trim())&&(Jn=!1),void kn();if(Rn){if(["q","quit","exit","back","b","menu"].includes(o))return Rn=!1,console.log(chalk.gray(nr()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void kn();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(nr()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?nr()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":nr()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(nr()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(nr()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void kn()):(n&&(await Dr(n,t?"fast":"deep"),console.log(chalk.gray(Vt?nr()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)":nr()?" (↩ q = 返回卡片)":" (↩ q = back to card)"))),void kn())}if(Un){const t=e.trim();if(["back","b","quit","exit","q"].includes(o))return Un=!1,Yn=null,P("learn-sh: leave"),"arena"===Bn?console.log(chalk.gray(nr()?" ↩ 已离开实验台,回到赛场。":" ↩ Left the lab — back in the arena.")):"fill"===Bn&&zn?(Fn=zn,zn=null,ml()):(console.log(chalk.gray(nr()?" ↩ 已离开 shell 实验台,回到卡片。":" ↩ Left the shell lab — back to the card.")),Rr()),void kn();if("menu"!==o&&!/^memo\b/.test(o)){if("reset"===o){const e=Gl(!0);return console.log(e.length>0?chalk.green((nr()?" ↺ 已还原本卡的文件: ":" ↺ Restored this card's files: ")+e.join(" ")):chalk.gray(nr()?" 本卡没有附带文件。":" This card ships no files.")),void kn()}return"clear"===o||"cls"===o?(console.clear(),Fl(),void kn()):"help"===o||"e"===o||"?"===o?(Bl(),void kn()):""===t?void kn():/^\/?py(\s|$)/.test(o)?(Un=!1,Yn=null,await Dl(/^\/?py\s+(\S+)/.exec(o)?.[1]),void kn()):(await(async e=>{P(`learn-sh: $ ${e}`);const o=/^cd(?:\s+(.*))?$/.exec(e.trim());if(o){const e=Po(Ul(),Yl(),o[1]?.trim());return void(null===e?console.log(chalk.yellow(nr()?" 去不了那儿 —— 目录不存在,或在实验台外面。":" Cannot go there — no such directory, or it is outside the lab.")+chalk.gray(nr()?" cd 单独敲回到顶层。":" Bare `cd` returns to the top.")):Yn=e)}const t=Ao(e);if(t)return void console.log(chalk.red((nr(),` ⚠ \`${t.word}\` `))+chalk.yellow(t.why)+chalk.gray(nr()?" —— 实验台不执行它。在自己的终端里敲之前,先 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(nr()?` \`${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,Yl());"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(nr()?" … 输出过长,已截断。":" … output truncated.")),r&&console.log(chalk.yellow(nr()?" 注意:这一行里的 cd 只在子进程里生效,你还在原来的目录。":" Note: the cd in that line ran in a child process — you have not moved.")+chalk.gray(nr()?" 单独敲一行 cd <目录>。":" Type `cd <dir>` on its own line.")),l.stdout||l.stderr?0!==l.code&&console.log(chalk.gray(nr()?` (退出码 ${l.code})`:` (exit ${l.code})`)):console.log(chalk.gray(nr()?` (没有输出 · 退出码 ${l.code})`:` (no output · exit ${l.code})`))):console.log(chalk.yellow(nr()?` 超过 ${Co/1e3} 秒,已停止。`:` Stopped after ${Co/1e3}s.`)+chalk.gray(nr()?" 换个更小的目标再试。":" Try a smaller target.")):console.log(chalk.red(nr()?" 这台机器上找不到 /bin/sh。":" No /bin/sh on this machine.")+chalk.gray(nr()?" Windows 请在 WSL2 里跑 icoa。":" On Windows, run icoa inside WSL2."))})(t),void kn())}}if(Dn){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 Dn=!1,console.log(chalk.gray(nr()?" ↩ 已离开草稿本,回到卡片。":" ↩ Left the scratchpad — back to the card.")),Rr(),void kn();const t=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(t||"list"===o||"/list"===o)return Ol(t?.[1]),ql(),void kn();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=Rl(o);null!==t&&("edit"===e?(await Wl(t),ql()):await(async e=>{if(!B($o(Nl(),e)))return void Rl(String(e));const o=Ro()?.cmd??null;if(!o)return void Mo(nr());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:Nl(),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(nr()?" ⏱ 超过 30 秒,已停止 — 检查死循环。":" ⏱ Over 30s — stopped. Check for an infinite loop."))),console.log(chalk.gray((nr()," ▸ edit "))+chalk.gray(`${e} · pylist · `)+chalk.bold.green("back")),console.log(),dr.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(nr()?` 用法: ${e} <编号>`:` Usage: ${e} <n>`)+chalk.gray(nr()?" (pylist 看编号)":" (pylist shows the numbers)"));return void kn()}const l=/^\/?py(?:\s+(\S+))?$/.exec(o);if(l||"new"===o)return await Dl(l?.[1]),void kn();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(nr()?" 草稿本命令: edit <n> · run <n> · pylist · /py 新建 · back 回卡片":" Scratchpad verbs: edit <n> · run <n> · pylist · /py (new) · back to the card")),void kn()}if(Wn&&kr){/^(\/?(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${kr.phase}s${kr.data.slot}: ${o}`);const n=parseInt(kl??"1",10),r=kr.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 Il(s,i[1]):(console.log(chalk.yellow(nr()?" 这一题不是答题式的 — 用 /edit 写代码,/submit 提交。":" This problem is not a typed-answer item — /edit the code and /submit it.")),void kn());const c=/^([A-Ea-e])$/.exec(o.trim());if(c&&s&&a){if("letter"===a.kind)return void await Il(s,c[1].toUpperCase());let e;return e="choose"===a.kind?(nr()?" 输入其中一个词:":" Type one of: ")+a.options.join(" / "):nr()?" 输入 answer 你的答案(例如 answer 1200)。":" Type answer <your answer> (e.g. answer 1200).",console.log(chalk.yellow(nr()?" 这一题不是选字母的。":" This one is not a letter question.")+chalk.gray(e)),void kn()}if(s&&"choose"===a?.kind){const e=o.trim().toLowerCase(),t=a.options.find(o=>o.toLowerCase()===e);if(t)return void await Il(s,t)}if(sr&&("sh"===o||"/sh"===o))return Zl("arena"),console.log(chalk.gray(nr()?" ▸ back 回赛场 · 计时照走":" ▸ back returns to the arena · the clock keeps running")),void kn();if("memo"===o||"/memo"===o||"e"===o)return jn=sn.currentCard,Ln=`[arena p${kr.phase}-g${kr.data.slot}${kl?` #${kl}`:""}]`,console.log(chalk.gray(nr()?` 报告归到: 竞技场 p${kr.phase}-g${kr.data.slot}${kl?` 题${kl}`:""} — 题面 / 判分 / 环境,一句话即可:`:` Files under: arena p${kr.phase}-g${kr.data.slot}${kl?` problem ${kl}`:""} — statement / judging / environment, one line is enough:`)),console.log(chalk.gray(nr()?" (回车提交 · 空行取消 · 不打断比赛计时)":" (Enter to submit · blank to cancel · the contest clock is unaffected)")),void kn();if("back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return ll()&&null!==kl?(kl=null,$l(),void kn()):(Wn=!1,kl=null,console.log(chalk.gray(nr()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Rr(),void kn());if(/^\d+$/.test(o))return _l(o),void kn();const d=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(d)return ll()?d[1]?_l(d[1]):$l():console.log(chalk.gray(nr()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void kn();if("cells"===o||"/cells"===o||"explore"===o||"/explore"===o){const e=xr(kr.phase,kr.data.slot,kr.dir);if(!e)return console.log(chalk.gray(Ar(kr.phase,kr.data.slot)?nr()?" 引导 notebook 还没下载到位(需要联网一次)— 稍后再敲 cells。":" The guided notebook has not downloaded yet (needs one online moment) — try cells again shortly.":nr()?" 本场没有引导 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 kn();const o=null!==N();o||L(hn);try{const{runIpynb:o}=await import("./ipynb.js");await o(e)}catch(e){console.log(chalk.yellow(nr()?" notebook 没打开: ":" The notebook failed to open: ")+chalk.gray(String(e)))}finally{o||L(null)}return $l(),void kn()}const g=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(g)return await(async e=>{const o=e.trim();if(await Ce()||vl||(vl=!0,console.log(chalk.gray(nr()?` (离线:只有 ${Ee()} 条核心速查可用;联网后自动补全)`:` (offline: ${Ee()} core entries available; the rest arrive when you have a connection)`))),!o)return void je(nr());const t=xe(o);if(t.length){Ie(t[0],nr());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(nr()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await Ae("python3",o);if(n)Pe(n,nr());else{if(await Te()){const e=xe(o);if(e.length)return void Ie(e[0],nr())}console.log(),console.log(chalk.yellow(nr()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(nr()?" 试试: ":" Try: ")+chalk.cyan(Se(o).join(" · "))),console.log(chalk.gray(nr()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(g[1]??""),void kn();const u=/^\/?set\b\s*(.*)$/i.exec(e.trim());if(u)return await(async e=>{const o=wl(kl??"1");if(!o)return;const t=oe(kr.dir,el(o.n,o.p));let n;try{n=G(t,"utf8")}catch{return void console.log(chalk.yellow(nr()?" 先 /read 一道题。":" Open a problem with /read first."))}const r=jl(n);if(0===r.length)return void console.log(chalk.yellow(nr()?" 这道题的文件没有旋钮(顶部那种 NAME = value 行)。":" This problem's file has no knobs (the NAME = value lines at the top).")+chalk.gray(nr()?" 用 ":" 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(nr()?" 用法: ":" Usage: ")+chalk.bold.green(nr()?"set <旋钮> <值>":"set <KNOB> <value>")+chalk.gray(nr()?" 例如 set WOMBATS 6":" e.g. set WOMBATS 6")),console.log(chalk.gray(nr()?" 这个 bot 的旋钮:":" This bot's knobs:"));for(const e of r)console.log(chalk.gray(" ")+chalk.bold.white(e.padEnd(10))+chalk.gray(Pl(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(nr()?` 这个 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=Pl(n,i)??"";if(c.trim()===a)return void console.log(chalk.gray((nr()," "))+chalk.bold.white(i)+chalk.gray(nr()?` 已经是 ${a} 了。`:` is already ${a}.`)+chalk.gray(nr()?" 下一步: ":" 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((nr()," ▸ "))+chalk.bold.green(`/run ${o.n}`)+chalk.gray(nr()?" 打一局看看 · ":" play a match and watch · ")+chalk.bold.green(`set ${i} ${c.trim()}`)+chalk.gray(nr()?" 改回去":" puts it back"))})(u[1]??""),void kn();const h=/^\/?(read|open|edit|run|debug|list|recall|replay)(?:\s+(\S+))?$/.exec(o);if(h){const[,e,o]=h;return"list"===e?$l():"replay"===e?await Fo()||console.log(chalk.gray(nr()?" 还没有回放。先 submit 一次 —— 判分机会把你输的那一局送回来。":" No replay yet. Submit once — the judge sends back the game you lost.")):o?"read"===e||"open"===e?_l(o):"edit"===e?await(async e=>{const o=wl(e);if(!o)return;const t=oe(kr.dir,el(o.n,o.p));if(Jo())return Qo()?(console.log(chalk.yellow(nr()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(nr()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(nr()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(nr()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(nr()?" ← 不能是 /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(nr()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(nr()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(nr()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(nr()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(nr()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(nr()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(nr()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(nr()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!Xo("vi"))return console.log(chalk.yellow(nr()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(nr()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));xl();const n=e=>{try{return H(e).size}catch{return 0}},r=n(t),l=Date.now(),s=I(t);await Cl("vi",[...Al,el(o.n,o.p)]);const a=s.stop(),i={ms:Date.now()-l,bytesBefore:r,bytesAfter:n(t)};if(vr.set(o.n,Q(vr.get(o.n)??J(),i)),a.ticks>0){const e=_r.get(o.n)??{list:[],dropped:0};e.list.push(a),e.list.length>16&&(e.list.shift(),e.dropped++),_r.set(o.n,e)}P(`learn-arena edit-done ${el(o.n,o.p)}`,{...i,...a.ticks>0?{samples:a}:{}}),console.log(chalk.gray(nr()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Zr(o.p)?nr()?" 本机打一局。":" to play one match here.":nr()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?await(async e=>{const o=wl(e);if(!o)return;const{p:n,n:r}=o;if(Zr(n)){const e=oe(kr.dir,el(r,n));if(!B(e))return void console.log(chalk.yellow(nr()?` 还没有 ${el(r,n)} — 先 /edit ${r}。`:` No ${el(r,n)} yet — /edit ${r} first.`));vr.set(r,V(vr.get(r)??J()));const o=await Go(e,n.card??0,0,n.crit,(e,o)=>Cl(e,o));return void(o.ran&&(console.log(o.ok?chalk.gray(" ▸ ")+chalk.bold.green(`/submit ${r}`)+chalk.gray(nr()?" 过线了 — 交给判分机(多局固定种子)":" over the bar — send it to the judge (seeded games)"):chalk.gray(" ▸ ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(nr()?" 改一改,再 ":" adjust, then ")+chalk.bold.green(`/run ${r}`)),console.log()))}if(Kr&&r===to)return void(()=>{const e=oe(kr.dir,`sol-${to}.py`);if(!B(e))return void console.log(chalk.yellow(nr()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=Sl();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 Tl();if(console.log(),o.killed)return void console.log(chalk.yellow(nr()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(nr()?` ✗ 输入 ${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(nr()?" 改完再来: ":" 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(nr()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),l===r.length){const e=Jr?null:1;Jr=!0,console.log(chalk.bold.green(nr()?` 🎉 ${l}/${r.length} 全过 — `:` 🎉 ${l}/${r.length} — `)+chalk.white(nr()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(nr()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(nr()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(nr()?` ${l}/${r.length} 通过 — 还差一点。`:` ${l}/${r.length} passed — not there yet.`)+chalk.gray(nr()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(nr()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const l=oe(kr.dir,el(r,n));if(!B(l))return void console.log(chalk.yellow(nr()?` 还没有 ${el(r,n)} — 先 /edit ${r}。`:` No ${el(r,n)} yet — /edit ${r} first.`));vr.set(r,V(vr.get(r)??J()));const s=(n.samples??[])[0];if(n.gpu)return console.log(chalk.gray(nr()?" ⚡ 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(nr()?"(窗口时间执行并返回你的 ms;窗口外会告诉你开放时间)":" (executes in the GPU window and returns your ms; outside the window it tells you the hours)")),void console.log();{const e=Vr(n),o={cpp:"c++",java:"java",go:"go"};if("python"===e?!Oo():!Xo(o[e]??e)){const t="python"===e?"Python":o[e]??e;return console.log(chalk.yellow(nr()?` ⓘ 本机没有 ${t} 环境 — 这一题直接交给判分机跑。`:` ⓘ No local ${t} environment — running this one on the server judge instead.`)),console.log(chalk.gray(nr()?" 判分机的计时本来就是准数;本地跑只是预览。":" The judge's timing is the real number anyway - local runs were only a preview.")),void await Hl(`/submit ${r}`)}}if(!s&&n.starter){const e=Vr(n);try{let o;if("cpp"===e){const e=oe(kr.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=Sl();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(nr()?` ${ho(!0)} — 满意就 `:` ${ho(!1)} — happy? `)+chalk.bold.green(`/submit ${r}`))}catch(e){const o=e;if("ENOENT"===o.code)Tl();else if(o.killed)console.log(chalk.yellow(nr()?" ⏱ 超过 30 秒 — 检查死循环。":" ⏱ Over 30s — check for an infinite loop."));else{console.log(chalk.yellow(nr()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr??"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));console.log(chalk.gray(nr()?` (空还没填对?/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(nr()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";const i=Sl();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)Tl();else if(o.killed)console.log(chalk.yellow(nr()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(nr()?" ✗ 程序报错:":" ✗ 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(nr()?" 你的输出:":" Your output:"));for(const e of(g||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(nr()?" 样例应输出:":" Sample expects:"));for(const e of u.split("\n"))console.log(chalk.green(` ${e}`));console.log(chalk.gray(` ⏱ ${d}ms — ${ho(nr())}`)),g===u?console.log(chalk.bold.green(nr()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(nr()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(nr()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(nr()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=wl(e);if(!o)return;if(Zr(o.p))return console.log(chalk.gray(nr()?` 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"!==Vr(o.p)||o.p.gpu)return console.log(chalk.gray(nr()?` 这一层不读输入 — 用 /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(kr.dir,`sol-${o.n}.py`);if(!B(t))return void console.log(chalk.yellow(nr()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));const n=Sl();if(!n)return;console.log(chalk.gray(nr()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 Cl(n,[`sol-${o.n}.py`]);console.log(),"ENOENT"!==r?.code?(console.log(chalk.gray(nr()?" 回到竞技场。":" Back in the arena.")),console.log()):Tl()})(o):"recall"===e&&await(async e=>{const o=wl(e);if(!o)return;if(!Vt)return void Wr();const{p:t,n:n}=o,r=oe(process.cwd(),"icoa-contest"),l=`${Jt.id}-phase${kr.phase}-g${kr.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(nr()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=G(a,"utf-8"),c=`${kr.phase}-${kr.data.slot}-${n}`,d=Math.min(3,(El.get(c)??0)+1);console.log(chalk.gray(nr()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await Me({token:Kt,phase:kr.phase,slot:kr.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:nr()?"zh":"en"});if(g.ok){El.set(c,d),console.log();for(const e of zt(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(nr()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(nr()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(nr()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(nr()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(nr()?" (花名册: /list)":" (roster: /list)")),void kn()}if("contest"===o||"/contest"===o)return $l(),void kn();const p="lang"===o||/^lang\s+\S+$/.test(o),y=Zt.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(nr()?" 竞技场命令: /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 kn()}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(nr()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void kn()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(hn.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}wn=!0;const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}wn=!1,hn.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void kn()}if("ai4ioai"===o||"/ai4ioai"===o)return await Y()&&(Jn=!0),void kn();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(Qt)return Wr(),void kn();Kn||(Kn=!0,console.log(),Vt?(console.log(chalk.bold.cyan(nr()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(nr()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(nr()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),nr()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")),console.log(chalk.gray(nr()?" 💡 一次好的研究通常会向 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(nr()?" 新建草稿贴进去跑(":" a fresh scratch file and run them (")+chalk.bold.green("/pylist")+chalk.gray(nr()?" 看草稿)。":" lists them)."))):(console.log(chalk.bold.cyan(nr()?" 🐼 AI 熊猫导师":" 🐼 AI Panda Tutor")),console.log(chalk.gray(nr()?` 围绕本卡内容提问 — 导师已经读过这张卡。每张卡每天最多 ${en} 个问题;`:` Ask about THIS card — the tutor has read it. Up to ${en} questions per card per day;`)),console.log(chalk.gray(nr()?" 跑题的问题不会被回答,也不计次数。这里只是问答,没有评分和榜单。":" off-topic questions are not answered and do not count. Q&A only — no grading, no board."))),console.log(chalk.yellow(nr()?" ↩ 重要:退出 AI 模式只需输入 ":" ↩ Important: to leave AI mode just type ")+chalk.bold.white("back")+chalk.yellow(nr()?" 或 ":" or ")+chalk.bold.white("quit")+chalk.yellow(nr()?",就回到卡片。":" — you are back on the card.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Rn=!0;const e=yr(sn.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(nr()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(nr()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Vt?nr()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · back / quit = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · back / quit = back to card":nr()?" 直接输入问题 · back / quit = 返回卡片":" Type a question · back / quit = back to card")),Vt&&console.log(chalk.gray(nr()?" 💡 通常要向 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 kn()}return await Dr(n,t?"fast":"deep"),void kn()}if(!Wn&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Vt)return Wr(),void kn();const e=yr(sn.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(nr()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(nr()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(nr()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(nr()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(nr()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(nr()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(nr()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Vn=!0,void kn()}const p=!Wn&&"honors"===Gn&&/^[1-3]$/.test(o);if(!Wn&&Gn&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(nr()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(nr()?" ↩ back 回上一层":" ↩ back goes up one level")),void kn();if(!Wn&&(p||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Vt)return Wr(),void kn();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:Kt,cardNumber:sn.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(nr()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&er.delete(sn.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&er.add(sn.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(nr()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${sn.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${sn.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(nr()?` (第 ${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(nr()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Ur(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(nr()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Gn="view",console.log(chalk.gray((nr()," "))+chalk.bold.cyan("↩ back")+chalk.gray(nr()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{On=!1}})(t),void kn()}const _=o.match(/^\/?(certificate|certificates|cert)(?:\s+(\S+))?$/);if(_&&!Wn&&!Dn){const{certificateLines:e}=await import("../lib/learn-door.js"),{certifiable:o,certificateIntroLines:t}=await import("../lib/learn-certificate.js"),n=nr(),r=Qt?null:await v(Kt,"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===Jt.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 kn()}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:")),bn={cid:i.curriculum_id,tok:i.token,first:null},void kn()}const A=o.match(/^\/?(story|credits|fin)(?:\s+(\S+))?$/);if(A&&!Wn&&!Dn){const e=(A[2]??"").trim();return await fr("story"===A[1]?e||"list":e||null,!0),void kn()}if(/^\/?(?:type|typing)(?:\s|$)/i.test(o))return await Yo(o.trim().split(/\s+/).slice(1)),void kn();if(/^\/?battle(?:\s|$)/i.test(o)&&!Wn&&!Dn){const e=null!==N();return e||L(hn),await zo([...o.trim().split(/\s+/).slice(1),`from-card:${sn.currentCard}`]),e||L(null),void kn()}if(/^\/?duck(?:\s|$)/i.test(o)&&!Wn&&!Dn){const e=null!==N();return e||L(hn),await Ho([...o.trim().split(/\s+/).slice(1),`from-card:${sn.currentCard}`]),e||L(null),void kn()}if(R(o))return await O(),void kn();if("me"===o||"/me"===o||"profile"===o||"/profile"===o||"my profile"===o){const e=nr();if(Qt)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 kn();console.log(chalk.gray(e?" 正在取档案…":" Loading your profile…"));const o=await v(Kt);return"ok"===o.kind?C(o.profile,e,Bt()):"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 kn()}if("/honors"===o||"honors"===o)return Qt?(console.log(),console.log(chalk.gray(nr()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void kn()):(await Br(),void kn());const x=/^\/?pylist(?:\s+(.+))?$/i.exec(e.trim());if(x)return P("learn-py: pylist"+(x[1]?` ${x[1]}`:"")),Ol(x[1]),void kn();const T=/^\/?py(?:\s+(\S+))?$/.exec(o);if(T)return await Dl(T[1]),void kn();if(/^\/?sh$/.test(o))return Zl(),void kn();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(nr()?" ↩ back 回卡片 · ":" ↩ back to the card · ")+chalk.bold.green("/py")+chalk.gray(nr()?" 打开草稿本":" opens the scratchpad")),console.log(),void kn()}if(/^\/?(upgrade|update)$/i.test(o.trim())){P("learn-upgrade");const{runUpgrade:e}=await import("../lib/update-check.js");return"upgraded"===await e({ask:!1})&&console.log(chalk.gray(nr()?" 输入 ":" type ")+chalk.bold.green("menu")+chalk.gray(nr()?" 进入新版本(进度已保存)":" to start the new version (your progress is saved)")),console.log(),void kn()}if(An&&"menu"!==o&&"menu confirm"!==o){const e=An.handle(o);return"input"===e||Sn(e),void kn()}if(An&&(An=null),"menu"===o||"menu confirm"===o){if(mn?.detach(),dr.length>0&&await Promise.race([Promise.allSettled(dr),new Promise(e=>setTimeout(e,3e3))]),hn.removeAllListeners("line"),yn(),gn||!pr){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(gn?hn:void 0),hr()}else hn.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===Gn)return await Br(),void kn();if("honors"===Gn)return Gn=null,Rr(),void kn();if(mn?.detach(),dr.length>0&&await Promise.race([Promise.allSettled(dr),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${sn.streakDays} day(s)`)),console.log(),gn){hn.removeAllListeners("line"),yn();for(const e of un)hn.on("line",e);hn.prompt(),hr()}else hn.removeAllListeners("line"),hn.close();return}if(pe(o))return nn?Ht(ue(nn,nr(),Bt(),"T0"===ye().tier),!!nn.completedAt):(console.log(chalk.gray(nr()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void kn();{const e=o.match(y);if(e)return Tr?(await m(Kt,e[1]??"",{curriculum:Jt}),P("learn: check"),void kn()):(console.log(chalk.yellow(nr()?" check 需要正式课程 token(demo 不支持)。":" check needs a full curriculum token (not demos).")),void kn())}{const e=o.match(f);if(e)return Tr?(await $(Kt,e[1]??"",Jt.totalCards),P("learn: class"),void kn()):(console.log(chalk.yellow(nr()?" class 需要正式课程 token(demo 不支持)。":" class needs a full curriculum token (not demos).")),void kn())}if(b.test(o)&&!Wn&&!Dn&&!Un){if(!Tr)return console.log(chalk.yellow(nr()?" 队伍会议室凭 FTC 课程 token 进入(demo 不支持)。":" Team meeting needs an FTC course token (not demos).")),void kn();P("learn: teammeeting");const e=hn.listeners("line");hn.removeAllListeners("line");let o="back";try{o=await k(Kt,w(hn))}finally{for(const o of e)hn.on("line",o)}return"menu"===o?void hn.emit("line","menu"):(console.log(chalk.gray(nr()?" ↩ 回到课程。":" ↩ Back to the course.")),void kn())}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(Tr){const[,e]=await Promise.all([Ir(),ne(Jt.id,Kt,!0)]);e&&Object.assign(Jt,e)}return Ct(Jt,sn,{gate:wr,gated:on,focus:t,posForSlot:Qe}),void kn()}if("sync"===o){P("learn: sync");const e=await ae(Kt);if(!e)return console.log(chalk.yellow(" ⚠ ")+chalk.white(nr()?"连不上服务器,进度保持本地。":"Server unreachable — keeping local progress.")),void kn();const o=sn.currentCard;return nt(sn,Jt.totalCards,e),et(sn),sn.currentCard>o?console.log(chalk.green(" ↩ ")+chalk.white(nr()?`已同步:${sn.cardsCompleted.length} 张卡完成,从第 ${sn.currentCard} 张继续`:`Synced: ${sn.cardsCompleted.length} cards done, resuming at card ${sn.currentCard}`)):console.log(chalk.green(" ✓ ")+chalk.white(nr()?"已与服务器同步,无新进度。":"Synced with the server — no new progress.")),void kn()}if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await ne(Jt.id,Kt,!0);return void(e?(Object.assign(Jt,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Rr()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),kn()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim(),t=de(Jt.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 kn();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`)),Cn=null,vn=null,_n=null,qn(),or=!1,Vn=!1,await Yr(),void kn()}const j=o.match(/^\/?(focus|timer)(?:\s+(.*))?$/);if(j&&!Wn&&!Dn&&null===Fn&&g.test(o)){const e=nr(),o=await u(Kt);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 kn()}if(j&&!Wn&&!Dn&&null===Fn){const e=(j[2]??"").trim(),o=nr(),t=`${a}–${s}`+(o?`,${i} 的倍数`:`, steps of ${i}`);if("off"===e||"stop"===e||"end"===e||"cancel"===e||"关"===e)return void(mn?.stop()||(console.log(chalk.gray(o?" 没有进行中的专注。开始一场:":" No focus session running. Start one: ")+chalk.bold.green("focus 30")),kn()));if(mn?.active)return console.log(chalk.yellow(" ⏱ ")+chalk.white(o?`专注进行中 · 还剩 ${mn.remainingMin()} 分钟`:`focus running · ${mn.remainingMin()} min left`)+chalk.gray(o?" · 提前结束:":" · end early: ")+chalk.bold.green("focus off")),void kn();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 kn();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 kn();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 mn?.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 kn()}if(Zt.has(o)){const e=Zt.get(o),t=Ut(Do()),n=e=>{const o=["normal","wide","wider","widest"].filter(o=>o!==e);return nr()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((nr()?"normal"===e?" 已是标准 64 列。":Bt()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Bt()} 列,上限 ${Yt(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Bt()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Bt()} cols, cap ${Yt(e)}). `)+n(e))),void kn()):(Uo({learnWidth:e,learnWide:"normal"!==e}),Dt(e),"normal"!==e&&Bt()<=64?(console.log(chalk.yellow(nr()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((nr()?` 设置已记住(${e},上限 ${Yt(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Yt(e)} cols) and applies once you widen the window. `)+n(e))),void kn()):(console.log(chalk.green(" ✓ ")+chalk.gray((nr()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Bt()} 列,上限 ${Yt(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Bt()} cols, cap ${Yt(e)}). `)+n(e))),Cn=null,vn=null,_n=null,qn(),or=!1,Vn=!1,await Yr(),void kn()))}if("sim"===o){const e=yr(sn.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 kn()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void kn())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=sn.currentCard,t=sn.bookmarks.includes(e),n="bookmark"!==o;return n?sn.bookmarks=sn.bookmarks.filter(o=>o!==e):t||sn.bookmarks.push(e),et(sn),n?console.log(t?chalk.gray(nr()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(nr()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(nr()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(nr()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void kn()}const E=me(o);if(E){const e="current"===E.target?sn.currentCard:E.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>Jt.cards.length))return console.log(chalk.yellow(nr()?` 本课共 ${Jt.cards.length} 张,请输 r 1–${Jt.cards.length} 或 r all。`:` This course has ${Jt.cards.length} cards. Try r 1–${Jt.cards.length} or r all.`)),console.log(),void kn();for(const o of fe(tn,cr,e,nr(),Bt()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?tn:tn.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(tn=tn.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Wt(tn),dr.push(le(Kt,{card_number:sn.currentCard,event_type:"viewed"},o).catch(()=>{}))),void kn()}if("e"===o||"memo"===o)return jn=sn.currentCard,console.log(chalk.gray(nr()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(nr()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void kn();if("back"===o||"b"===o&&null===vn)return"view"===Gn?(await Br(),void kn()):"honors"===Gn?(Gn=null,Rr(),void kn()):(sn.currentCard>1&&(sn.currentCard-=1),vn=null,_n=null,Cn=null,et(sn),Rr(),void kn());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Tr)return console.log(chalk.yellow(nr()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void kn();if(!e){const e=await ze(Kt),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(nr()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(nr()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(nr()?` 这台电脑上有 ${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(nr()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(nr()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(nr()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(nr()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(nr()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(nr()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(nr()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void kn()}if(/^\d{1,2}$/.test(e)){const o=await Fe(Kt,Number(e));return o.ok&&o.data?(tl(o.data),await Ir(),void kn()):(console.log(chalk.red(` ✗ ${o.message||(nr()?"关联失败":"Link failed")}`)),void kn())}const t=await Ge(Kt,e);return t.ok&&t.data?(tl(t.data),await Ir(),void kn()):(console.log(chalk.red(` ✗ ${t.message||(nr()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(nr()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void kn())}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(!Tr)return console.log(chalk.yellow(nr()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void kn();if("duck"===vt()&&!Wn&&!Dn){console.log(chalk.gray(nr()?" 这条轨的检查点在 duck 子 REPL 里打:进入 duck → run 试跑 → submit 判分。":" This track's checkpoints are played in duck: duck → run → submit."));const e=null!==N();return e||L(hn),await Ho([`from-card:${sn.currentCard}`]),e||L(null),void kn()}let e=Er(sn.currentCard),t=null;const n="contest restart"===o||"restart"===o;if(n&&(!Wn||!kr||ll()))return console.log(chalk.gray(nr()?" 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 kn();if(n&&kr){const o=kr.phase,n=kr.data.slot,r=await Ue(Kt,o,n);if(!r.ok&&"no_active_session"!==r.code)return console.log(chalk.red(` ✗ ${r.message||"reset failed"}`)),void kn();sl(o,n),console.log(chalk.yellow(nr()?` 🔄 第 ${n} 组重开 — 全新计时、全新模板。`:` 🔄 Group ${n} restarted — fresh clock, fresh templates.`)+chalk.gray(nr()?" 只有计时内写的才算数:从头再写一遍,这正是练习。":" Only work written on the clock counts — write it again from scratch; that is the practice.")),kr=null,Wn=!1,kl=null,e=o,t=n}if("contest reset"===o&&Wn&&ll()){const e=kr.phase,o=kr.data.slot,t=await Ue(Kt,e,o);if(t.ok){console.log(chalk.yellow(nr()?" 已放弃本卡练习计时。回卡片后输入 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",`${Jt.id}-phase${e}-g${o}`);if(B(n))try{Z(n,`${n}-archived-${t}`),console.log(chalk.gray(nr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(nr()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}kr=null,Wn=!1,kl=null,Rr()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void kn()}if("contest reset"===o){const o=await Ue(Kt,e);if(o.ok){console.log(chalk.yellow(nr()?` 已放弃本阶段(${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(`^${Jt.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])<rl).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(nr()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(nr()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(nr()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),kr=null,Wn=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void kn()}const r=null!=t?String(t):/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(nr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Kt,e,r?parseInt(r,10):void 0);if(!l.ok||!l.data){if("no_contest"===l.code){const o=Jt.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?nr()?` 本阶段(${e})判分赛制作中 — 通关标准很快更新(360 层第二阶段标准设计中)。`:` Phase ${e}'s contest is in production — pass criteria coming soon (360-tier second-stage standard in design).`:lr?nr()?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).`:nr()?` 本阶段(${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 kn()}const s=l.data,a=oe(process.cwd(),"icoa-contest",`${Jt.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(nr()?" 📦 上一场的答题文件已归档: ":" 📦 Previous window archived: ")+chalk.gray(`${a}-archived-${e}`)),console.log(chalk.gray(nr()?" 新场次全新模板 — 计时窗口内写的才算数。":" Fresh window, fresh templates — only work done on the clock counts."))}catch{console.log(chalk.yellow(nr()?` ⚠ 归档失败(比赛照常): ${a}`:` ⚠ Could not archive (contest still fine): ${a}`))}}F(a,{recursive:!0});const i=kr&&kr.phase===e&&kr.data.slot===s.slot?kr.tried:new Set;kr&&kr.phase===e&&kr.data.slot===s.slot&&kr.data.attempt===s.attempt||(vr.clear(),_r.clear()),kr={phase:e,dir:a,data:s,tried:i},ol(s,a),xr(e,s.slot,a),Wn=!0,$l(),console.log(chalk.gray(nr()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(a));const c=s.problems.findIndex(e=>!s.solved.includes(e.id))+1||1,d=Kr&&!Jr?to:c;return console.log(chalk.white(nr()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${d}`)+chalk.gray(d===to?nr()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":nr()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void kn()}if(/^\/?(?:flow|walk)$/.test(o)){const e=yr(sn.currentCard),o=e&&"knowledge"===e.type?e.flow:void 0;return o&&0!==o.length?(Tn(e,!1),void kn()):(console.log(chalk.gray(nr()?" 这张卡没有互动流程 — 有流程的卡片脚注会印 [flow]。":" No interactive walk on this card — cards that have one show [flow] in the footer.")),void kn())}const M=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(lr&&/^[1-9]$/.test(o)?`practice ${o}`:o);if(M){const e=yr(sn.currentCard),o=il(e);if(!o)return console.log(chalk.gray(nr()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void kn();if(!Tr)return console.log(chalk.yellow(nr()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void kn();if(!M[1])return console.log(),gl(e),console.log(chalk.gray(nr()?" 用法: ":" Usage: ")+chalk.bold.green(nr()?"practice <题号>":"practice <n>")+chalk.gray(nr()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void kn();const t=parseInt(M[1],10);if(!Number.isInteger(t)||t<1||t>o.length)return console.log(chalk.yellow(nr()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void kn();const n=o[t-1],r=cl(n),l=o.filter(e=>cl(e)===r),s=l.indexOf(n)+1;return await(r||!lr?(async(e,o,t)=>{const n=Er(e.number),r=rl+e.number;console.log(chalk.gray(nr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Kt,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(nr()?" 本卡暂无练习题库。":" 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(nr()?" 本卡练习题库是空的。":" 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(al(e.py_id))?al(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=Sr.get(r);c||(c=new Set,Sr.set(r,c));for(const e of s.solved)c.add(e);const d=oe(process.cwd(),"icoa-contest",`${Jt.id}-phase${n}-g${r}`);F(d,{recursive:!0});const g=kr&&kr.phase===n&&kr.data.slot===r?kr.tried:new Set;kr&&kr.phase===n&&kr.data.slot===r&&kr.data.attempt===s.attempt||(vr.clear(),_r.clear()),kr={phase:n,dir:d,data:s,tried:g},ol(s,d),Wn=!0,kl=null,P(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(nr()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(nr()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(nr()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(d)),console.log(chalk.gray((nr()," ↩ "))+chalk.bold.green("back")+chalk.gray(nr()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),_l(String(Math.min(t,s.problems.length)))})(e,l,s):(async(e,o,t)=>{const n=Er(e.number),r=rl+e.number;zn=null,console.log(chalk.gray(nr()?" 连接判分赛…":" Contacting contest server…"));const l=await Ye(Kt,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(nr()?" 本卡暂无练习题库。":" 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(nr()?" 本卡练习题库是空的。":" 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(al(e.py_id))?al(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&&!Zr(e)&&i.push(e);s.problems=i;let c=Sr.get(r);c||(c=new Set,Sr.set(r,c));for(const e of s.solved)c.add(e);Fn={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(nr()?` ⚡ 快速填空 — 第 ${e.number} 张卡`:` ⚡ Quick fill — card ${e.number}`)+chalk.gray(nr()?"(敲答案 → 自动判分 · 不计分)":" (type the blank → auto-judged · unscored)")),console.log(chalk.gray(nr()?` ⏱ 每次练习 ${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`)),ml()})(e,l,s)),void kn()}if("submit"===l)return console.log(chalk.yellow(nr()?" 用法: ":" Usage: ")+chalk.bold.green(nr()?"submit <题号>":"submit <n>")+chalk.gray(nr()?" 例如 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)")),kr||console.log(chalk.gray(nr()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void kn();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const t=e[2];if(!kr)return console.log(chalk.yellow(nr()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void kn();const n=kr.data.problems,r=parseInt(o,10);if(Kr&&r===to)return console.log(chalk.gray(nr()?" 热身题不判分 — /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(nr()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(nr()?" 开始。":".")),void kn();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(nr()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void kn();const s=n.findIndex(e=>e.id===o)+1,a=t||oe(kr.dir,el(s,n[s-1]));let i;try{i=G(a,"utf-8")}catch{return console.log(chalk.red(nr()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void kn()}const c=Boolean(n[s-1]?.quiz),d=c?null:new W(Kt);d?.start();const g=vr.get(s),u=_r.get(s),h=g&&!X(g)?{...g,...u?{samples:u.list}:{},...u&&u.dropped>0?{samplesDropped:u.dropped}:{}}:void 0,p=await Be(Kt,kr.phase,o,i,kr.data.slot>=rl?kr.data.slot:void 0,h);if(d?.stop(),!p.ok||!p.data)return"no_active_session"===p.code&&kr.data.slot>=rl?hl(kr.data.duration_minutes):"no_active_session"===p.code?(sl(kr.phase,kr.data.slot),console.log(chalk.yellow(nr()?" ⏱ 时间到 — 这一场结束了,判分机已停表。":" ⏱ Time is up — this attempt is over; the judge stopped the clock.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest restart")+chalk.gray(nr()?" 重开这一组:全新计时 + 全新模板(旧文件已归档)。只有计时内写的才算数 — 从头再写一遍,这正是练习。":" 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(nr()?" ↩ back 回卡片":" ↩ back returns to the card"))):(console.log(chalk.red(` ✗ ${p.message||"judging failed"}`)),console.log(chalk.gray(nr()?" 判分服务异常?敲 memo 一句话告诉我们 — 不打断比赛计时。":" Judge acting up? Type memo — one line reaches us, the clock is unaffected."))),void kn();const y=p.data;let m=!1;if(Hr()){const e=y;for(const o of(e.report??[]).slice(0,3))console.log(chalk.gray(` ${nr()?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(nr()?" 看你输掉的那一局 —— 判分机把它送回来了(q 退出回放)":" watch the game you lost — the judge sent it back (q quits the player)")),y.already_ac)console.log(chalk.green(nr()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===y.verdict){if(c?console.log(chalk.bold.green(nr()?" ✅ 答对了!":" ✅ Correct!")):console.log(Lo("AC",{isZh:nr(),passed:y.passed_tests??y.total_tests??null,total:y.total_tests??null,ms:y.time_ms??null})),kr.data.solved.includes(o)||kr.data.solved.push(o),kr.tried.delete(o),ll()){let e=Sr.get(kr.data.slot);e||(e=new Set,Sr.set(kr.data.slot,e)),e.add(o);const t=await De({token:Kt,curriculumId:Jt.id,cardNumber:sn.currentCard}),n=t.ok?t.practiceBoard:null;if(n?.mine){const e=n.top[0],o=e&&!e.me?chalk.gray(nr()?` · 榜首 ${e.name||"Rank 1"} ${e.ac} AC`:` · leader ${e.name||"Rank 1"} at ${e.ac} AC`):chalk.bold.yellow(nr()?" · 全场第一!":" · phase leader!");console.log(chalk.white(nr()?` ⚔ Phase ${n.phase} Practice AC: `:` ⚔ Phase ${n.phase} practice AC: `)+chalk.bold.yellow(`${n.mine.ac}`)+chalk.gray(`/${n.problems_total}`)+chalk.gray(nr()?` · 第 ${n.mine.rank} 名`:` · rank ${n.mine.rank}`)+o)}}}else kr.tried.add(o),c?console.log(chalk.red(nr()?" ✗ 还没对":" ✗ Not yet")+chalk.gray(nr()?" — 再选一次。":" — pick again.")):console.log(Lo(y.verdict,{isZh:nr(),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(nr()?" 觉得题面有误或判分不对?敲 memo 一句话 — 不打断比赛计时。":" Statement wrong or judging looks off? Type memo — one line, the clock is unaffected.")));y.late&&console.log(chalk.yellow(nr()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const f=He(y.deadline||""),$=ll();if(console.log(chalk.white($?nr()?` 本卡练习: 已过 ${y.ac_count}/${y.n} 题(不计分)`:` Card practice: ${y.ac_count}/${y.n} solved (unscored)`:nr()?` 本组进度: 已过 ${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(nr()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(nr()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!y.passed||y.late||$){if(!y.late){const e=n.findIndex(e=>!kr.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(nr()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${zr(n[e])}`))}}else{const e=Math.max(0,y.n-y.ac_count);if(0===e)console.log(chalk.bold.green(nr()?` 🎉 满分!${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(nr()?" 回到上一层(卡片),继续往下学;":" returns to the previous layer (the card) — keep going from there; ")+chalk.bold.green("contest")+chalk.gray(nr()?" 看本阶段其他赛场。":" lists the other arenas of this phase."));else{console.log(chalk.bold.green(nr()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")+chalk.yellow(nr()?` 还剩 ${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=>!kr.data.solved.includes(e.id));o>=0&&console.log(chalk.gray(nr()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${o+1}`)+chalk.gray(` ${zr(n[o])}`)+chalk.gray(nr()?" · ↩ back 回卡片":" · ↩ back returns to the card"))}{const e=Jt.modules.find(e=>e.number===kr.phase);if(e&&e.cardRange[1]-e.cardRange[0]+1>12&&1===kr.data.slot){const e=Jt.modules.find(e=>e.number===kr.phase+1);console.log(e?chalk.bold.cyan(nr()?" 🎁 定位检查过关 — 这个模块你已经会了。":" 🎁 Placement check passed — you already own this module.")+chalk.gray(nr()?" 想跳过剩下的卡:":" To skip the rest of it: ")+chalk.bold.green(`card ${e.cardRange[0]}`)+chalk.gray(nr()?"(下一模块开头)· 想留下练也可以,":" (next module) · or stay and drill, ")+chalk.bold.green("contest 2")+chalk.gray(nr()?" 是本模块的模拟卷。":" is this module's mock paper."):chalk.bold.cyan(nr()?" 🎁 定位检查过关 — 这是最后一个模块,":" 🎁 Placement check passed — last module; ")+chalk.bold.green("contest 2")+chalk.gray(nr()?" 做最后一套模拟卷。":" is the final mock paper."))}}await Ir()}return void kn()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>Jt.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Jt.totalCards}. Try: `)+chalk.bold.green("card 1")),void kn();const n=await Lr(t);return n?(console.log(n),void kn()):(sn.currentCard=t,vn=null,_n=null,Cn=null,et(sn),Rr(),void kn())}if(null!==Cn&&["y","yes","n","no"].includes(o)){const e=yr(Cn);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-tr;mn?.noteCheck(n,r),at(sn,e.number),ct(sn,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),et(sn);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),dr.push(le(Kt,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Cn=null,br(),e.solution&&e.solution.length>0)return void kn();if(dl())return void kn();if(sn.currentCard<Jt.totalCards){const e=sn.currentCard,o=await Lr(e+1);if(o)return await Mr(e),console.log(o),void kn();sn.currentCard+=1,et(sn),await Mr(e)?qr():Rr(),kn()}else xt(Jt,sn),fr(null,!1).then(()=>kn()),kn();return}}if(null!==vn&&["a","b","c","d"].includes(o)){const e=yr(vn);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(it(sn,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),at(sn,e.number),et(sn),yt(e,t,n,sn),dr.push(le(Kt,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),vn=null,n)if(sn.currentCard<Jt.totalCards){const e=await Lr(sn.currentCard+1);if(e)return console.log(e),void kn();sn.currentCard+=1,et(sn),Rr()}else xt(Jt,sn),fr(null,!1).then(()=>kn()),kn();else kn();return}}if(null!==_n){if("done"===o){const e=yr(_n);if(e&&"practical"===e.type)return dt(sn,e.number),at(sn,e.number),et(sn),ft(e),_n=null,void kn()}if("skip"===o)return at(sn,_n),et(sn),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),_n=null,void kn()}const q=lr&&"skip"===o&&null===vn&&null===_n&&null===Cn&&null!==il(yr(sn.currentCard));if("ok"===o||"next"===o||"continue"===o||"n"===o||q){if(q){const e=sn.currentCard;Pr.add(e),mn?.notePracticeSkipped(),console.log(chalk.gray(nr()?" ⚔ 本卡练习已跳过(有记录)。":" ⚔ Practice skipped for this card (recorded).")),le(Kt,{card_number:e,event_type:"practice_skipped"}).catch(()=>{})}else if(null===Cn&&null===vn&&null===_n&&dl())return void kn();if(null!==vn)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void kn();if(null!==_n)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void kn();if(null!==Cn)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void kn();const e=sn.currentCard,o=e<Jt.totalCards?await Lr(e+1):null;return o?(await Mr(e),console.log(o),void kn()):(sn.currentCard+=1,et(sn),sn.currentCard>Jt.totalCards?(xt(Jt,sn),fr(null,!1).then(()=>kn())):await Mr(e)?qr():Rr(),void kn())}return null!==Cn?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void kn()):null!==vn?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void kn()):null!==_n?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void kn()):("view"===Gn?console.log(chalk.gray(nr()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(nr()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(nr()?" 回卡片":" to the card")):"honors"===Gn?console.log(chalk.gray(nr()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(nr()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(nr()?" 回卡片":" 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 kn())};hn.on("line",e=>{Hl(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.")),kn()})}),gn||hn.on("close",async()=>{mn?.detach(),dr.length>0&&await Promise.race([Promise.allSettled(dr),new Promise(e=>setTimeout(e,5e3))]),pr?hr():process.exit(0)});const Kl=be(tn,nr());if(Kl){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(Kl)+chalk.bold.cyan(" │")),console.log(chalk.bold.cyan(` ╰${"─".repeat(Math.max(26,e-5))}╯`)),console.log()}try{Rr();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0),(async()=>{for(let e=0;e<20&&!wr;e++)await new Promise(e=>setTimeout(e,250));const e=$r();null!==e&&e>0&&e<=2&&(await br(!0),kn())})();const o=mn?.attach(Kt,Jt.id,mr);"resumed"===o&&(console.log(chalk.yellow(" ⏱ ")+chalk.white(nr()?`专注进行中 · 还剩 ${mn.remainingMin()} 分钟 · 这条轨也算在内 · focus off 提前结束`:`focus running · ${mn.remainingMin()} min left · this course counts too · focus off to end early`)),console.log()),kn()}catch(e){if(process.env.ICOA_DEBUG&&console.error(e),Gt("Could not render this card — the curriculum may be malformed."),gn){hn.removeAllListeners("line"),yn();for(const e of un)hn.on("line",e);hn.prompt()}else hn.close();hr()}await ur}),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()})}