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