icoa-cli 2.19.457 → 2.19.459
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/ai4ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/lib/py-syntax.js +1 -1
- package/package.json +1 -1
- package/dist/commands/ai4ctf.d.ts +0 -4
- package/dist/commands/ai4ioai.d.ts +0 -29
- package/dist/commands/aienv.d.ts +0 -23
- package/dist/commands/arena-eai.d.ts +0 -37
- package/dist/commands/arena.d.ts +0 -8
- package/dist/commands/board.d.ts +0 -2
- package/dist/commands/challenge.d.ts +0 -9
- package/dist/commands/comms.d.ts +0 -2
- package/dist/commands/connect.d.ts +0 -15
- package/dist/commands/ctf.d.ts +0 -3
- package/dist/commands/ctf4ai-demo.d.ts +0 -4
- package/dist/commands/ctf4vla.d.ts +0 -34
- package/dist/commands/demo2.d.ts +0 -31
- package/dist/commands/demo4.d.ts +0 -3
- package/dist/commands/demo5.d.ts +0 -3
- package/dist/commands/doctor.d.ts +0 -2
- package/dist/commands/env.d.ts +0 -5
- package/dist/commands/exam.d.ts +0 -13
- package/dist/commands/files.d.ts +0 -2
- package/dist/commands/ioailab.d.ts +0 -1
- package/dist/commands/ipynb.d.ts +0 -20
- package/dist/commands/kaggle.d.ts +0 -12
- package/dist/commands/lang.d.ts +0 -2
- package/dist/commands/learn.d.ts +0 -16
- package/dist/commands/log.d.ts +0 -2
- package/dist/commands/note.d.ts +0 -25
- package/dist/commands/ref.d.ts +0 -2
- package/dist/commands/setup.d.ts +0 -2
- package/dist/commands/shell.d.ts +0 -35
- package/dist/commands/sim.d.ts +0 -32
- package/dist/commands/sprint.d.ts +0 -7
- package/dist/commands/teleload.d.ts +0 -8
- package/dist/commands/theme.d.ts +0 -13
- package/dist/commands/view.d.ts +0 -2
- package/dist/index.d.ts +0 -2
- package/dist/lib/access.d.ts +0 -14
- package/dist/lib/aienv.d.ts +0 -118
- package/dist/lib/arena-edit-dynamics.d.ts +0 -55
- package/dist/lib/arena-submit.d.ts +0 -23
- package/dist/lib/banner.d.ts +0 -9
- package/dist/lib/bgtasks.d.ts +0 -21
- package/dist/lib/board-render.d.ts +0 -14
- package/dist/lib/budget.d.ts +0 -1
- package/dist/lib/card-engine.d.ts +0 -45
- package/dist/lib/challenge-dir.d.ts +0 -1
- package/dist/lib/colors.d.ts +0 -11
- package/dist/lib/commands.d.ts +0 -53
- package/dist/lib/comms.d.ts +0 -40
- package/dist/lib/config.d.ts +0 -8
- package/dist/lib/countdown.d.ts +0 -4
- package/dist/lib/country-lang.d.ts +0 -1
- package/dist/lib/ctfd-client.d.ts +0 -33
- package/dist/lib/deck-cooldown.d.ts +0 -7
- package/dist/lib/demo-exam.d.ts +0 -28
- package/dist/lib/demo-flags.d.ts +0 -8
- package/dist/lib/demo-stats.d.ts +0 -17
- package/dist/lib/docker-probe.d.ts +0 -45
- package/dist/lib/drafts.d.ts +0 -11
- package/dist/lib/editor-spawn.d.ts +0 -28
- package/dist/lib/exam-client.d.ts +0 -15
- package/dist/lib/exam-sandbox.d.ts +0 -15
- package/dist/lib/exam-setup.d.ts +0 -19
- package/dist/lib/exam-state.d.ts +0 -42
- package/dist/lib/gemini.d.ts +0 -16
- package/dist/lib/gpu.d.ts +0 -51
- package/dist/lib/http.d.ts +0 -35
- package/dist/lib/i18n.d.ts +0 -215
- package/dist/lib/input-dynamics.d.ts +0 -38
- package/dist/lib/integrity-snapshot.d.ts +0 -22
- package/dist/lib/interactive-spawn.d.ts +0 -25
- package/dist/lib/ipynb-input.d.ts +0 -25
- package/dist/lib/kaggle.d.ts +0 -115
- package/dist/lib/kernel-protocol.d.ts +0 -92
- package/dist/lib/kernel.d.ts +0 -81
- package/dist/lib/learn-ai.d.ts +0 -159
- package/dist/lib/learn-contest.d.ts +0 -141
- package/dist/lib/learn-curricula.d.ts +0 -274
- package/dist/lib/learn-i18n.d.ts +0 -8
- package/dist/lib/learn-input.d.ts +0 -40
- package/dist/lib/learn-outcome.d.ts +0 -1
- package/dist/lib/learn-render.d.ts +0 -107
- package/dist/lib/learn-replies.d.ts +0 -42
- package/dist/lib/learn-state.d.ts +0 -66
- package/dist/lib/log-sync.d.ts +0 -2
- package/dist/lib/logger.d.ts +0 -12
- package/dist/lib/main-rl.d.ts +0 -20
- package/dist/lib/md-term.d.ts +0 -17
- package/dist/lib/menu-nav.d.ts +0 -25
- package/dist/lib/notebook-doc.d.ts +0 -38
- package/dist/lib/open-file.d.ts +0 -35
- package/dist/lib/paper-upgrade.d.ts +0 -27
- package/dist/lib/platform.d.ts +0 -110
- package/dist/lib/py-syntax.d.ts +0 -36
- package/dist/lib/render-card.d.ts +0 -17
- package/dist/lib/repl-asker.d.ts +0 -7
- package/dist/lib/resume.d.ts +0 -7
- package/dist/lib/sample-runner.d.ts +0 -14
- package/dist/lib/sandbox.d.ts +0 -30
- package/dist/lib/secure-store.d.ts +0 -18
- package/dist/lib/shell-split.d.ts +0 -17
- package/dist/lib/sim-cooldown.d.ts +0 -14
- package/dist/lib/sprint-meta.d.ts +0 -72
- package/dist/lib/statusline.d.ts +0 -1
- package/dist/lib/terminal-cleanup.d.ts +0 -35
- package/dist/lib/theme.d.ts +0 -4
- package/dist/lib/token-format.d.ts +0 -41
- package/dist/lib/tool-man.d.ts +0 -11
- package/dist/lib/toolset-hash.d.ts +0 -15
- package/dist/lib/translation.d.ts +0 -1
- package/dist/lib/translations-fetcher.d.ts +0 -6
- package/dist/lib/ui.d.ts +0 -12
- package/dist/lib/update-check.d.ts +0 -1
- package/dist/lib/version.d.ts +0 -8
- package/dist/repl.d.ts +0 -4
- package/dist/types/index.d.ts +0 -221
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 n,execSync as t,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{getMainRl as a}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as i,handleAi4ioaiMessage as c,startAi4ioaiChat as d}from"./ai4ioai.js";import{existsSync as g,mkdirSync as u,readdirSync as y,readFileSync as m,renameSync as h,statSync as p,writeFileSync as f}from"node:fs";import{emptyDynamics as b,foldEditSession as w,isEmpty as $,noteRun as k}from"../lib/arena-edit-dynamics.js";import{dirname as v,join as C}from"node:path";import{fileURLToPath as A}from"node:url";import{loadCurriculumById as _,validateEAToken as x,syncProgress as T,syncCardFeedback as I}from"../lib/learn-curricula.js";import{parseReplyCommand as E,renderReplyLines as P,replyPushLine as S}from"../lib/learn-replies.js";import{SYNTAX_INDEX as M,lookupLocal as q,lookupPydoc as L,nearKeys as N,renderPydoc as j,renderSyntax as W}from"../lib/py-syntax.js";import{normalizeTokenBody as R}from"../lib/token-format.js";import{fetchMyScores as O,recallCoach as D,setNickname as Y,streamLearnTutor as U,submitPqs as F,viewPqsTop as z,viewHonors as B}from"../lib/learn-ai.js";import{contestReset as H,contestStart as Z,contestSubmit as J,linkByIndex as K,linkSuggest as Q,linkToken as V,fetchGate as X,timeLeft as G}from"../lib/learn-contest.js";import{getConfig as ee,saveConfig as oe}from"../lib/config.js";import{isNativeWindows as ne,isWindowsBuildInWslShell as te,whichBinary as re}from"../lib/platform.js";import{loadLearnState as le,saveLearnState as se,newLearnState as ae,activateSession as ie,updateStreak as ce,markCardComplete as de,recordMCQ as ge,recordCheck as ue,markPracticalComplete as ye,addAchievement as me}from"../lib/learn-state.js";import{renderWelcome as he,renderKnowledgeCard as pe,renderMCQCard as fe,renderMCQFeedback as be,renderPracticalCard as we,renderPracticalSuccess as $e,renderSimDemoCard as ke,renderMilestone as ve,renderArenaTaskCard as Ce,renderComingSoonCard as Ae,renderStatus as _e,renderPhaseComplete as xe,renderCurriculumComplete as Te,setLearnAiEnabled as Ie,setLearnHonorRanks as Ee,setLearnPqsViewCards as Pe,setLearnReplies as Se,setLearnWidth as Me,resolveLearnWidth as qe,learnWidthCap as Le,learnW as Ne,renderHonorWall as je,wrapMixed as We}from"../lib/learn-render.js";import{printError as Re}from"../lib/ui.js";const Oe=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(De){De.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async De=>{De?.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(),De="LEARNDEMO01");let Ye=De.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ye)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Ue=null;const Fe=/^[A-Z0-9]+DEMO01$/i.test(Ye),ze=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ye);let Be=!1,He=!1,Ze=[],Je=-1;if(Fe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Ue=await _(Ye,Ye,!0);else if(ze){console.log(),console.log(chalk.gray(" Validating token..."));let e=await x(Ye);if(!e.ok){const o=R(Ye);if(o!==Ye){const n=await x(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ye} → ${o}`)),e=n,Ye=o)}}if(!e.ok)return Re(`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 🐼"):"")),Be=!0===e.aiEnabled,He=!0===e.gated,Ze=e.replies??[],console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Ue=await _(e.curriculumId||"LEARNDEMO01",Ye,!0),!Ue)return Re(`Could not open a learn curriculum for token '${Ye}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ye}`)+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 ${Ye}`)+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(!Ue){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Re(`Could not reach the learn server to open ${Ye}.`),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 ${Ye}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Re(`Unknown learn token: ${Ye}`),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 Ke=le(),Qe=!1;try{if(Ke&&Ke.token===Ye)ce(Ke);else{const e=ie(Ye);e?(Ke=e,Ke.totalCards=Ue.totalCards,ce(Ke)):(Ke=ae(Ye,Ue.id,Ue.totalCards),Qe=!0)}se(Ke),he(Ue,Ke,Qe)}catch{return Re("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 ${Ye}`)+chalk.gray(".")),void console.log()}const Ve=a(),Xe=null!==Ve,Ge=Xe?Ve.listeners("line").slice():[];Xe&&Ve.removeAllListeners("line");const eo=Xe?Ve:o({input:process.stdin,output:process.stdout,terminal:!0}),oo=Xe?eo.prompt:null;Xe&&(eo.prompt=e.prototype.prompt);const no=()=>{Xe&&oo&&(eo.prompt=oo)},to=()=>{eo.setPrompt($o?chalk.bold.green(`icoa ${i()}> `):ho?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(yo?"icoa learn ai> ":"icoa learn> ")),eo.prompt()};let ro=null,lo=null,so=null,ao=null,io=[],co=!1,go=null;const uo=()=>{go&&clearTimeout(go),go=null,io=[],co=!1,ao=null};let yo=!1,mo=!1,ho=!1,po=null,fo=!1,bo=0,wo=!1,$o=!1;const ko=new Map,vo=()=>{let e=ko.get(Ke.currentCard);return e||(e=[],ko.set(Ke.currentCard,e)),e};let Co=!1;const Ao=new Set;let _o=!1,xo=0;const To=()=>(ee().language||"en").toLowerCase().startsWith("zh");Ie(Be),Me(qe(ee())),Pe(Ao);const Io=new Map;Ee(Io),Se(Ze);const Eo=[];let Po=null;const So=new Promise(e=>{Po=e}),Mo=()=>{const e=Po;Po=null,e?.()},qo="1"===process.env.ICOA_LEARN_EMBEDDED,Lo=e=>Ue.cards.find(o=>o.number===e);let No=null,jo=null;const Wo=new Map,Ro=!Ye.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ye),Oo=async()=>{if(!Ro)return;const e=await X(Ye);e.ok&&e.data&&(No=e.data)},Do=e=>{const o=Ue.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Yo=e=>{if(!He||!No)return null;const o=Do(e);if(o<=No.unlocked_through_phase)return null;const n=No.phases.find(e=>e.phase===No.unlocked_through_phase),t=[chalk.yellow(To()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${No.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${No.unlocked_through_phase}'s core tasks first:`)];if(n?.contest&&!n.contest.passed){const e=n.contest.slots??[];if(e.length>0)for(const o of e)o.passed||t.push(chalk.gray(To()?` ⚔ 练习赛 ${No.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${No.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else t.push(chalk.gray(To()?` ⚖ 判分赛: 最好 ${n.contest.best_ac}/${n.contest.n} AC,需 ${n.contest.need} — 输入 `:` ⚖ contest: best ${n.contest.best_ac}/${n.contest.n} AC, need ${n.contest.need} — type `)+chalk.bold.green("contest"))}if(n?.checks?.enabled&&!n.checks.passed){const e=n.checks.missing??[],o=e.slice(0,8).join(To()?"、":", "),r=e.length>8?To()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:To()?" 张":"";t.push(chalk.gray(To()?` ✓ 逐卡自测: ${n.checks.good}/${n.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${n.checks.good}/${n.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return n?.research&&!n.research.passed&&t.push(chalk.gray(To()?` ⭐ 提问研究: ${n.research.good_cards}/${n.research.need_cards} 卡达到 ${n.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${n.research.good_cards}/${n.research.need_cards} cards at ${n.research.min_score}+ — research with /ai, then /submit`)),t.join("\n")},Uo=async e=>He?null===Yo(e)?null:(await Oo(),Yo(e)):null;Ro&&await Oo();const Fo=async e=>{const o=Ue.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Ue.modules.find(e=>e.number===o.number+1);let t;if(Be){const e=await O({token:Ye,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}Ro&&await Oo();const r=No?.phases.find(e=>e.phase===o.number);return xe(Ue,Ke,o,n,t,r),!0},zo=()=>{_o=!0,console.log(chalk.gray(To()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Bo=()=>{po=null;const e=Lo(Ke.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":pe(e,Ue),e.check?(so=e.number,xo=Date.now()):(de(Ke,e.number),se(Ke));break;case"mcq":fe(e,Ue),ro=e.number;break;case"practical":we(e,Ue),lo=e.number;break;case"sim_demo":ke(e,Ue),de(Ke,e.number),se(Ke);break;case"milestone":ve(e,Ue),me(Ke,e.badge),de(Ke,e.number),se(Ke);break;case"arena_task":Ce(e,Ue),de(Ke,e.number),se(Ke);break;case"coming_soon":Ae(e,Ue),de(Ke,e.number),se(Ke)}Ho(e.number)},Ho=e=>{if(!Ro||!No)return;const o=Ue.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const n=e-o.cardRange[0]+1;if(n%4!=0)return;const t=n/4,r=No.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===t);if(!l)return;const s=(e,o,n,t)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${o}:${String(n).padStart(2,"0")}`})(n),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${n(o.getMonth()+1)}-${n(o.getDate())} ${n(o.getHours())}:${n(o.getMinutes())}`})(t);return`🏆 ${e} ${o}/${l.n}`+(r?To()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Ne());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${To()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(To()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(To()?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(To()?`${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(To()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(To()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(To()?"✍ 第一次用 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(To()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(To()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${t}`)+(l.passed?chalk.gray(To()?" 再战刷成绩 · ":" race it again · "):chalk.gray(To()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(To()?" 继续学习":" keep going"):chalk.gray(To()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(To()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Zo=()=>{Ye.endsWith("DEMO01")?console.log(chalk.yellow(To()?" 🐼 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(To()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(To()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Jo=async(e,o)=>{if(Be){mo=!0;try{console.log(),console.log(chalk.gray("deep"===o?To()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":To()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await U({token:Ye,cardNumber:Ke.currentCard,question:e,mode:o,history:vo().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(t||(process.stdout.write(n?"\n\n ":" "),t=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||t)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(To()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(vo().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(` (${To()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(To()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==so&&console.log(chalk.gray(To()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{mo=!1}}else Zo()},Ko=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Qo=async()=>{ho&&jo?ln?sn(ln):nn():po?await Vo():Bo()},Vo=async()=>{mo=!0;try{console.log();const e=await B({token:Ye,curriculumId:Ue.id,cardNumber:Ke.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(To()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(To()?` 🏆 本卡实时 Top-3 — 第 ${Ke.currentCard} 张`:` 🏆 Live top-3 — card ${Ke.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(To()?" (你)":" (you)"):""))}else console.log(chalk.gray(To()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Io.set(Ke.currentCard,e.mine.rank),console.log(chalk.white(To()?" 你: ":" You: ")+chalk.bold.yellow(To()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(To()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Be&&console.log(chalk.gray(To()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),je({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(To()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(To()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(To()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),po="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(To()?" 返回卡片":" returns to the card")),console.log()}finally{mo=!1}},Xo=e=>To()&&e.title_zh||e.title,Go=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of We(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},en=e=>{console.log(),console.log(chalk.bold.green(To()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(To()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},on=e=>jo.data.solved.includes(e.id)?"✅":jo.data.carried?.includes(e.id)?"✅↗":jo.tried.has(e.id)?"❌":"⬜",nn=()=>{const e=jo.data,o=G(e.deadline),n=(e.carried??[]).filter(o=>!e.solved.includes(o)),t=e.solved.length+n.length,r=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(To()?` · 第 ${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(To()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(To()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(To()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(To()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(To()?" 带过来,不必重做":" to carry them over instead of redoing them"));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(To()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(To()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(To()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(To()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+on(e)+chalk.white(` ${Xo(e)}`))}),console.log(),tn()},tn=()=>{console.log(chalk.gray(To()?" /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((To()," "))+chalk.bold.green("/syntax <词>")+chalk.gray(To()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(To()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(To()?" 返回课程":" returns to the lesson")),console.log()},rn=e=>{const o=parseInt(e,10),n=jo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(To()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let ln=null;const sn=e=>{const o=rn(e);if(!o)return;const{p:n,n:t}=o;ln=String(t),console.log(),console.log(chalk.bold.white(` ${on(n)} ${Xo(n)}`)),console.log();for(const e of(e=>To()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of We(e,Ne()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of n.samples??[]){r+=1,console.log(),console.log(chalk.gray(To()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(To()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(n.samples??[]).length&&(console.log(),console.log(chalk.gray(To()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(To()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(To()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${t}`.padEnd(11))+chalk.gray(To()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(To()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(To()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray(To()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(To()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((To()," ↩ "))+chalk.bold.green("back")+chalk.gray(To()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(To()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((To()," / "))+chalk.bold.green("wide")+chalk.gray(To()?" 换语言/宽度":" language / width")),console.log()},an=async(e,o)=>await new Promise(n=>{const t=process.stdin,s=!!t.isTTY&&!!t.isRaw;if(eo.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const a=r(e,o,{stdio:"inherit",cwd:jo.dir}),i=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&s)try{t.setRawMode(!0)}catch{}l(),eo.resume(),n(e)};a.on("close",()=>i(null)),a.on("error",e=>i(e))}),cn=()=>{console.log(chalk.yellow(To()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(To()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(To()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(To()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},dn=new Map,gn=async e=>{const o=e.trim().toLowerCase(),l=ho&&o.startsWith("/")?o.slice(1):o;if(mo)return;if(null!==ao){if(io.push(e.replace(/\s+$/,"")),go&&clearTimeout(go),go=null,co){const e=io[io.length-1]??"";return"/cancel"===e.trim()?(uo(),console.log(chalk.gray(To()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void to()):""!==e.trim()?void to():(io.pop(),void await a())}return void(go=setTimeout(()=>{if(go=null,io.length>1){co=!0;const e=io.length;return console.log(chalk.cyan(To()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(To()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void to()}a()},140))}async function a(){const e=io.join("\n").replace(/^\s+|\s+$/g,""),o=ao??Ke.currentCard,n=io.length;if(uo(),""===e)console.log(chalk.gray(To()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(To()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(To()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(To()?" 即可执行。":" again to run it."));else{const t=xo>0?Date.now()-xo:void 0;if(await I(Ye,{curriculum_id:Ue.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const t=n>1?To()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(To()?` ✓ 已收到${t},谢谢帮助完善这张卡。`:` ✓ Thanks ${t}— your report was recorded.`)),console.log(chalk.gray(To()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),Ze=[...Ze,{id:Je--,curriculumId:Ue.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Se(Ze)}else console.log(chalk.yellow(To()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),to()}if(fo){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return fo=!1,console.log(),console.log(chalk.yellow(To()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(To()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(To()?" 即可执行该命令。":" again to run it.")),console.log(),void to();if(!o)return fo=!1,console.log(chalk.gray(To()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void to();const n=await Y({token:Ye,nickname:o});if(n.ok)fo=!1,console.log(chalk.bold.green(To()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(To()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{bo+=1;const e="taken"===n.code?To()?"已被占用":"already taken":"bad_charset"===n.code?To()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?To()?"未通过审核":"did not pass review":n.message||"error";if(!(bo>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(To()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void to();fo=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(To()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void to()}if(Co){Co=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{mo=!0;try{console.log(),console.log(chalk.gray(To()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await F({token:Ye,cardNumber:Ke.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(To()?"评审暂不可用。":"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(To()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(To()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(To()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(To()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(To()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(To()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=To()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(To()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(To()?` 第 ${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 Ko(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(To()?" 改进提问: ":" 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(` (${To()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Ao.add(Ke.currentCard):Ao.delete(Ke.currentCard),"number"==typeof e.rank&&Io.set(Ke.currentCard,e.rank);const o=await B({token:Ye,curriculumId:Ue.id,cardNumber:Ke.currentCard});o.ok&&o.totals&&o.chapters&&(je({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Fe&&(fo=!0,bo=0,console.log(chalk.bold.yellow(To()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(To()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(To()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{mo=!1}})():(console.log(chalk.gray(To()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==so&&(console.log(chalk.gray(To()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void to()}if(_o)return _o=!1,Bo(),void to();if(!o)return void to();if($o)return"exit"===await c(e.trim())&&($o=!1),void to();if(yo){if(["q","quit","exit","back","b","menu"].includes(o))return yo=!1,console.log(chalk.gray(To()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void to();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim();return t&&(await Jo(t,n?"fast":"deep"),console.log(chalk.gray(To()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void to()}if(ho&&jo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${jo.phase}s${jo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return ho=!1,console.log(chalk.gray(To()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Bo(),void to();if(/^\d+$/.test(o))return sn(o),void to();const t=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(t)return await(async e=>{const o=e.trim();if(!o){console.log(),console.log(chalk.white(To()?" /syntax <要查的东西>":" /syntax <what you need>")+chalk.gray(To()?" 查本机 Python 文档 — 不联网,也不会给解法":" your own Python's docs — offline, never a solution")),console.log(),console.log(chalk.gray(To()?" 常查:":" Common:"));for(let e=0;e<M.length;e+=3)console.log(chalk.cyan(" "+M.slice(e,e+3).map(e=>e.padEnd(16)).join("")));return console.log(),console.log(chalk.gray(To()?" 方法名也能直接查: ":" Any name works too: ")+chalk.bold.cyan("/syntax list.pop")+chalk.gray(" · ")+chalk.bold.cyan("/syntax IndexError")),void console.log()}const n=q(o);if(n)return void W(n,To());const t=await L("python3",o);t?j(t,To()):(console.log(),console.log(chalk.yellow(To()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(To()?" 试试: ":" Try: ")+chalk.cyan(N(o).join(" · "))),console.log(chalk.gray(To()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log())})(t[1]??""),void to();const r=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(r){const[,e,o]=r;return"list"===e?nn():o?"read"===e||"open"===e?sn(o):"edit"===e?await(async e=>{const o=rn(e);if(!o)return;const n=C(jo.dir,`sol-${o.n}.py`);if(ne())return te()?(console.log(chalk.yellow(To()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(To()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(To()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(To()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(To()?" ← 不能是 /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(To()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(To()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(To()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(To()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(To()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(To()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(To()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(To()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!re("vi"))return console.log(chalk.yellow(To()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(To()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(To()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return p(e).size}catch{return 0}},r=t(n),l=Date.now();await an("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),Wo.set(o.n,w(Wo.get(o.n)??b(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(To()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(To()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=rn(e);if(!o)return;const{p:t,n:r}=o,l=C(jo.dir,`sol-${r}.py`);if(!g(l))return void console.log(chalk.yellow(To()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Wo.set(r,k(Wo.get(r)??b()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(To()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=n("python3",[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if("ENOENT"===o.code)cn();else if(o.killed)console.log(chalk.yellow(To()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(To()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const i=a.replace(/\r\n/g,"\n").trimEnd(),c=s.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(To()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(To()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(To()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(To()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(To()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(To()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=rn(e);if(!o)return;const n=C(jo.dir,`sol-${o.n}.py`);if(!g(n))return void console.log(chalk.yellow(To()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(To()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const t=await an("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(To()?" 回到竞技场。":" Back in the arena.")),console.log()):cn()})(o):"recall"===e&&await(async e=>{const o=rn(e);if(!o)return;if(!Be)return void Zo();const{p:n,n:t}=o,r=C(process.cwd(),"icoa-contest"),l=`${Ue.id}-phase${jo.phase}-g${jo.data.slot}-archived-`;let s=null;try{for(const e of y(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?C(r,s,`sol-${t}.py`):null;if(!a||!g(a))return void console.log(chalk.gray(To()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${jo.phase}-${jo.data.slot}-${t}`,d=Math.min(3,(dn.get(c)??0)+1);console.log(chalk.gray(To()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const u=await D({token:Ye,phase:jo.phase,slot:jo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:d,lang:To()?"zh":"en"});if(u.ok){dn.set(c,d),console.log();for(const e of We(u.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(To()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(To()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===u.code?console.log(chalk.yellow(To()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${u.message}`)):console.log(chalk.yellow(` ${u.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(To()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(To()?" (花名册: /list)":" (roster: /list)")),void to()}if("contest"===o||"/contest"===o)return nn(),void to();const a="lang"===o||/^lang\s+\S+$/.test(o),i=Oe.has(o);if(!("submit"===l||l.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||a||i||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(To()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void to()}if("tmux"===o||o.startsWith("tmux ")){try{t("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(To()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void to()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(eo.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&t)try{n.setRawMode(!0)}catch{}eo.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void to()}if("ai4ioai"===o||"/ai4ioai"===o)return await d()&&($o=!0),void to();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Be)return Zo(),void to();wo||(wo=!0,console.log(),console.log(chalk.bold.cyan(To()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(To()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(To()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),To()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const n=o.startsWith("/ai!"),t=e.trim().slice(n?4:3).trim();if(!t){yo=!0;const e=Lo(Ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(To()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(To()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(To()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void to()}return await Jo(t,n?"fast":"deep"),void to()}if(!ho&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Be)return Zo(),void to();const e=Lo(Ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(To()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(To()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(To()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(To()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(To()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(To()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(To()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Co=!0,void to()}const i=!ho&&"honors"===po&&/^[1-3]$/.test(o);if(!ho&&po&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(To()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(To()?" ↩ back 回上一层":" ↩ back goes up one level")),void to();if(!ho&&(i||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Be)return Zo(),void to();const e=/^\/?view ([1-3])$/.exec(o),n=i?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{mo=!0;try{console.log();const o=await z({token:Ye,cardNumber:Ke.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(To()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Ao.delete(Ke.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Ao.add(Ke.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(To()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${Ke.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${Ke.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(To()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of n){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(To()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=Ko(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(To()?" (无可显示的提问)":" (no questions to show)"))}console.log(),po="view",console.log(chalk.gray((To()," "))+chalk.bold.cyan("↩ back")+chalk.gray(To()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{mo=!1}})(n),void to()}if("/honors"===o||"honors"===o)return Fe?(console.log(),console.log(chalk.gray(To()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void to()):(await Vo(),void to());if("menu"===o||"menu confirm"===o){if(Eo.length>0&&await Promise.race([Promise.allSettled(Eo),new Promise(e=>setTimeout(e,3e3))]),eo.removeAllListeners("line"),no(),Xe||!qo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Xe?eo:void 0),Mo()}else eo.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===po)return await Vo(),void to();if("honors"===po)return po=null,Bo(),void to();if(Eo.length>0&&await Promise.race([Promise.allSettled(Eo),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Ke.streakDays} day(s)`)),console.log(),Xe){eo.removeAllListeners("line"),no();for(const e of Ge)eo.on("line",e);eo.prompt(),Mo()}else eo.removeAllListeners("line"),eo.close();return}if("status"===o)return _e(Ue,Ke),void to();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await _(Ue.id,Ye,!0);return void(e?(Object.assign(Ue,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Bo()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本")),to()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(ee().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void to();const n=Ue.cards.some(e=>null!=e._zh),t=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===t||"zh"===t&&n,l=r?t:"en";return oe({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),so=null,ro=null,lo=null,uo(),_o=!1,Co=!1,await Qo(),void to()}if(Oe.has(o)){const e=Oe.get(o),n=qe(ee()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return To()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((To()?"normal"===e?" 已是标准 64 列。":Ne()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Ne()} 列,上限 ${Le(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Ne()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Ne()} cols, cap ${Le(e)}). `)+t(e))),void to()):(oe({learnWidth:e,learnWide:"normal"!==e}),Me(e),"normal"!==e&&Ne()<=64?(console.log(chalk.yellow(To()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((To()?` 设置已记住(${e},上限 ${Le(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Le(e)} cols) and applies once you widen the window. `)+t(e))),void to()):(console.log(chalk.green(" ✓ ")+chalk.gray((To()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Ne()} 列,上限 ${Le(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Ne()} cols, cap ${Le(e)}). `)+t(e))),so=null,ro=null,lo=null,uo(),_o=!1,Co=!1,await Qo(),void to()))}if("sim"===o){const e=Lo(Ke.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=v(A(import.meta.url)),o=[C(e,"..","..","panda","mujoco-launcher.py"),C(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(g(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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--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 to()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void to())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=Ke.currentCard,n=Ke.bookmarks.includes(e),t="bookmark"!==o;return t?Ke.bookmarks=Ke.bookmarks.filter(o=>o!==e):n||Ke.bookmarks.push(e),se(Ke),t?console.log(n?chalk.gray(To()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(To()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(To()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(To()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void to()}const x=E(o);if(x){const e="current"===x.target?Ke.currentCard:x.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>Ue.cards.length))return console.log(chalk.yellow(To()?` 本课共 ${Ue.cards.length} 张,请输 r 1–${Ue.cards.length} 或 r all。`:` This course has ${Ue.cards.length} cards. Try r 1–${Ue.cards.length} or r all.`)),console.log(),void to();for(const o of P(Ze,e,To(),Ne()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?Ze:Ze.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(Ze=Ze.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Se(Ze),Eo.push(T(Ye,{card_number:Ke.currentCard,event_type:"viewed"},o).catch(()=>{}))),void to()}if("e"===o)return ao=Ke.currentCard,console.log(chalk.gray(To()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void to();if("back"===o||"b"===o)return"view"===po?(await Vo(),void to()):"honors"===po?(po=null,Bo(),void to()):(Ke.currentCard>1&&(Ke.currentCard-=1),ro=null,lo=null,so=null,se(Ke),Bo(),void to());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Ro)return console.log(chalk.yellow(To()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void to();if(!e){const e=await Q(Ye),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(To()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(To()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(To()?` 这台电脑上有 ${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(To()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(To()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(To()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(To()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(To()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(To()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(To()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void to()}if(/^\d{1,2}$/.test(e)){const o=await K(Ye,Number(e));return o.ok&&o.data?(en(o.data),await Oo(),void to()):(console.log(chalk.red(` ✗ ${o.message||(To()?"关联失败":"Link failed")}`)),void to())}const n=await V(Ye,e);return n.ok&&n.data?(en(n.data),await Oo(),void to()):(console.log(chalk.red(` ✗ ${n.message||(To()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(To()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void to())}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(!Ro)return console.log(chalk.yellow(To()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void to();const e=Do(Ke.currentCard);if("contest reset"===o){const o=await H(Ye,e);if(o.ok){console.log(chalk.yellow(To()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let n=1;n<=3;n++){const t=C(process.cwd(),"icoa-contest",`${Ue.id}-phase${e}-g${n}`);if(g(t))try{h(t,`${t}-archived-${o}`),console.log(chalk.gray(To()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(To()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(To()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),jo=null,ho=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void to()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(To()?" 连接判分赛…":" Contacting contest server…"));const t=await Z(Ye,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(To()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void to();const r=t.data,l=C(process.cwd(),"icoa-contest",`${Ue.id}-phase${e}-g${r.slot}`);u(l,{recursive:!0});const s=jo&&jo.phase===e&&jo.data.slot===r.slot?jo.tried:new Set;jo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.samples??[])[0];l&&f(C(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=C(o,`sol-${r}.py`);if(g(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${n.title} ══`,"#",...Go(n.statement,72)];if(n.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.out.split("\n"))a.push(`# ${e}`)}a.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","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),f(s,a.join("\n"))})})(r,l),ho=!0,nn(),console.log(chalk.gray(To()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(To()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(To()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void to()}if("submit"===l)return console.log(chalk.yellow(To()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(To()?" 例如 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)")),jo||console.log(chalk.gray(To()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void to();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const n=e[2];if(!jo)return console.log(chalk.yellow(To()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void to();const t=jo.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=t.length&&!t.some(e=>e.id===o)&&(o=t[r-1].id),!t.some(e=>e.id===o))return console.log(chalk.yellow(To()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void to();const s=t.findIndex(e=>e.id===o)+1,a=n||C(jo.dir,`sol-${s}.py`);let i;try{i=m(a,"utf-8")}catch{return console.log(chalk.red(To()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void to()}console.log(chalk.gray(To()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Wo.get(s),d=await J(Ye,jo.phase,o,i,void 0,c&&!$(c)?c:void 0);if(!d.ok||!d.data)return"no_active_session"===d.code?console.log(chalk.yellow(To()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((To()," "))+chalk.bold.green("contest")+chalk.gray(To()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(To()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void to();const g=d.data;if(g.already_ac)console.log(chalk.green(To()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(To()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(To()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),jo.data.solved.includes(o)||jo.data.solved.push(o),jo.tried.delete(o);else{jo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?To()?` · 挂在第 ${g.test} 个用例(过 ${g.passed_tests}/${g.total_tests})`:` · failed test ${g.test} (passed ${g.passed_tests}/${g.total_tests})`:""))}g.late&&console.log(chalk.yellow(To()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=G(g.deadline||"");if(console.log(chalk.white(To()?` 本组进度: 已过 ${g.ac_count} 题 · 过 ${g.need} 题过关(共 ${g.n} 题)`:` Group progress: ${g.ac_count} solved · ${g.need} needed to pass (${g.n} problems)`)+(u?chalk.gray(` · ⏱ ${u}`):"")),g.passed&&!g.late)console.log(chalk.bold.green(To()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Oo();else if(!g.late){const e=t.findIndex(e=>!jo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(To()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Xo(t[e])}`))}return void to()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Ue.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Ue.totalCards}. Try: `)+chalk.bold.green("card 1")),void to();const t=await Uo(n);return t?(console.log(t),void to()):(Ke.currentCard=n,ro=null,lo=null,so=null,se(Ke),Bo(),void to())}if(null!==so&&["y","yes","n","no"].includes(o)){const e=Lo(so);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-xo;de(Ke,e.number),ue(Ke,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),se(Ke);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),Eo.push(T(Ye,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),so=null,e.solution&&e.solution.length>0)return void to();if(Ke.currentCard<Ue.totalCards){const e=Ke.currentCard,o=await Uo(e+1);if(o)return await Fo(e),console.log(o),void to();Ke.currentCard+=1,se(Ke),await Fo(e)?zo():Bo(),to()}else Te(Ue,Ke),to();return}}if(null!==ro&&["a","b","c","d"].includes(o)){const e=Lo(ro);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(ge(Ke,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),de(Ke,e.number),se(Ke),be(e,n,t,Ke),Eo.push(T(Ye,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),ro=null,t)if(Ke.currentCard<Ue.totalCards){const e=await Uo(Ke.currentCard+1);if(e)return console.log(e),void to();Ke.currentCard+=1,se(Ke),Bo()}else Te(Ue,Ke),to();else to();return}}if(null!==lo){if("done"===o){const e=Lo(lo);if(e&&"practical"===e.type)return ye(Ke,e.number),de(Ke,e.number),se(Ke),$e(e),lo=null,void to()}if("skip"===o)return de(Ke,lo),se(Ke),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),lo=null,void to()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ro)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void to();if(null!==lo)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void to();if(null!==so)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void to();const e=Ke.currentCard,o=e<Ue.totalCards?await Uo(e+1):null;return o?(await Fo(e),console.log(o),void to()):(Ke.currentCard+=1,se(Ke),Ke.currentCard>Ue.totalCards?Te(Ue,Ke):await Fo(e)?zo():Bo(),void to())}return null!==so?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void to()):null!==ro?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void to()):null!==lo?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void to()):("view"===po?console.log(chalk.gray(To()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(To()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(To()?" 回卡片":" to the card")):"honors"===po?console.log(chalk.gray(To()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(To()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(To()?" 回卡片":" 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 to())};eo.on("line",e=>{gn(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.")),to()})}),Xe||eo.on("close",async()=>{Eo.length>0&&await Promise.race([Promise.allSettled(Eo),new Promise(e=>setTimeout(e,5e3))]),qo?Mo():process.exit(0)});const un=S(Ze,To());un&&(console.log(chalk.bold.cyan(` ${un}`)),console.log());try{Bo(),to();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Re("Could not render this card — the curriculum may be malformed."),Xe){eo.removeAllListeners("line"),no();for(const e of Ge)eo.on("line",e);eo.prompt()}else eo.close();Mo()}await So}),De.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 n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await _(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} 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 n,execSync as t,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{getMainRl as a}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as i,handleAi4ioaiMessage as c,startAi4ioaiChat as d}from"./ai4ioai.js";import{existsSync as g,mkdirSync as u,readdirSync as y,readFileSync as m,renameSync as h,statSync as p,writeFileSync as f}from"node:fs";import{emptyDynamics as b,foldEditSession as w,isEmpty as $,noteRun as k}from"../lib/arena-edit-dynamics.js";import{dirname as v,join as A}from"node:path";import{fileURLToPath as C}from"node:url";import{loadCurriculumById as _,validateEAToken as T,syncProgress as x,syncCardFeedback as I}from"../lib/learn-curricula.js";import{parseReplyCommand as E,renderReplyLines as S,replyPushLine as P}from"../lib/learn-replies.js";import{lookupPydoc as q,lookupRanked as M,nearKeys as L,renderIndex as N,renderPydoc as j,renderSyntax as R}from"../lib/py-syntax.js";import{normalizeTokenBody as W}from"../lib/token-format.js";import{fetchMyScores as O,recallCoach as D,setNickname as Y,streamLearnTutor as U,submitPqs as F,viewPqsTop as z,viewHonors as B}from"../lib/learn-ai.js";import{contestReset as H,contestStart as Z,contestSubmit as J,linkByIndex as K,linkSuggest as Q,linkToken as V,fetchGate as X,timeLeft as G}from"../lib/learn-contest.js";import{getConfig as ee,saveConfig as oe}from"../lib/config.js";import{isNativeWindows as ne,isWindowsBuildInWslShell as te,whichBinary as re}from"../lib/platform.js";import{loadLearnState as le,saveLearnState as se,newLearnState as ae,activateSession as ie,updateStreak as ce,markCardComplete as de,recordMCQ as ge,recordCheck as ue,markPracticalComplete as ye,addAchievement as me}from"../lib/learn-state.js";import{renderWelcome as he,renderKnowledgeCard as pe,renderMCQCard as fe,renderMCQFeedback as be,renderPracticalCard as we,renderPracticalSuccess as $e,renderSimDemoCard as ke,renderMilestone as ve,renderArenaTaskCard as Ae,renderComingSoonCard as Ce,renderStatus as _e,renderPhaseComplete as Te,renderCurriculumComplete as xe,setLearnAiEnabled as Ie,setLearnHonorRanks as Ee,setLearnPqsViewCards as Se,setLearnReplies as Pe,setLearnWidth as qe,resolveLearnWidth as Me,learnWidthCap as Le,learnW as Ne,renderHonorWall as je,wrapMixed as Re}from"../lib/learn-render.js";import{printError as We}from"../lib/ui.js";const Oe=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(De){De.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async De=>{De?.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(),De="LEARNDEMO01");let Ye=De.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ye)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Ue=null;const Fe=/^[A-Z0-9]+DEMO01$/i.test(Ye),ze=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ye);let Be=!1,He=!1,Ze=[],Je=-1;if(Fe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Ue=await _(Ye,Ye,!0);else if(ze){console.log(),console.log(chalk.gray(" Validating token..."));let e=await T(Ye);if(!e.ok){const o=W(Ye);if(o!==Ye){const n=await T(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ye} → ${o}`)),e=n,Ye=o)}}if(!e.ok)return We(`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 🐼"):"")),Be=!0===e.aiEnabled,He=!0===e.gated,Ze=e.replies??[],console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Ue=await _(e.curriculumId||"LEARNDEMO01",Ye,!0),!Ue)return We(`Could not open a learn curriculum for token '${Ye}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ye}`)+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 ${Ye}`)+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(!Ue){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(We(`Could not reach the learn server to open ${Ye}.`),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 ${Ye}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(We(`Unknown learn token: ${Ye}`),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 Ke=le(),Qe=!1;try{if(Ke&&Ke.token===Ye)ce(Ke);else{const e=ie(Ye);e?(Ke=e,Ke.totalCards=Ue.totalCards,ce(Ke)):(Ke=ae(Ye,Ue.id,Ue.totalCards),Qe=!0)}se(Ke),he(Ue,Ke,Qe)}catch{return We("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 ${Ye}`)+chalk.gray(".")),void console.log()}const Ve=a(),Xe=null!==Ve,Ge=Xe?Ve.listeners("line").slice():[];Xe&&Ve.removeAllListeners("line");const eo=Xe?Ve:o({input:process.stdin,output:process.stdout,terminal:!0}),oo=Xe?eo.prompt:null;Xe&&(eo.prompt=e.prototype.prompt);const no=()=>{Xe&&oo&&(eo.prompt=oo)},to=()=>{eo.setPrompt($o?chalk.bold.green(`icoa ${i()}> `):ho?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(yo?"icoa learn ai> ":"icoa learn> ")),eo.prompt()};let ro=null,lo=null,so=null,ao=null,io=[],co=!1,go=null;const uo=()=>{go&&clearTimeout(go),go=null,io=[],co=!1,ao=null};let yo=!1,mo=!1,ho=!1,po=null,fo=!1,bo=0,wo=!1,$o=!1;const ko=new Map,vo=()=>{let e=ko.get(Ke.currentCard);return e||(e=[],ko.set(Ke.currentCard,e)),e};let Ao=!1;const Co=new Set;let _o=!1,To=0;const xo=()=>(ee().language||"en").toLowerCase().startsWith("zh");Ie(Be),qe(Me(ee())),Se(Co);const Io=new Map;Ee(Io),Pe(Ze);const Eo=[];let So=null;const Po=new Promise(e=>{So=e}),qo=()=>{const e=So;So=null,e?.()},Mo="1"===process.env.ICOA_LEARN_EMBEDDED,Lo=e=>Ue.cards.find(o=>o.number===e);let No=null,jo=null;const Ro=new Map,Wo=!Ye.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ye),Oo=async()=>{if(!Wo)return;const e=await X(Ye);e.ok&&e.data&&(No=e.data)},Do=e=>{const o=Ue.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Yo=e=>{if(!He||!No)return null;const o=Do(e);if(o<=No.unlocked_through_phase)return null;const n=No.phases.find(e=>e.phase===No.unlocked_through_phase),t=[chalk.yellow(xo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${No.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${No.unlocked_through_phase}'s core tasks first:`)];if(n?.contest&&!n.contest.passed){const e=n.contest.slots??[];if(e.length>0)for(const o of e)o.passed||t.push(chalk.gray(xo()?` ⚔ 练习赛 ${No.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${No.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else t.push(chalk.gray(xo()?` ⚖ 判分赛: 最好 ${n.contest.best_ac}/${n.contest.n} AC,需 ${n.contest.need} — 输入 `:` ⚖ contest: best ${n.contest.best_ac}/${n.contest.n} AC, need ${n.contest.need} — type `)+chalk.bold.green("contest"))}if(n?.checks?.enabled&&!n.checks.passed){const e=n.checks.missing??[],o=e.slice(0,8).join(xo()?"、":", "),r=e.length>8?xo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:xo()?" 张":"";t.push(chalk.gray(xo()?` ✓ 逐卡自测: ${n.checks.good}/${n.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${n.checks.good}/${n.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return n?.research&&!n.research.passed&&t.push(chalk.gray(xo()?` ⭐ 提问研究: ${n.research.good_cards}/${n.research.need_cards} 卡达到 ${n.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${n.research.good_cards}/${n.research.need_cards} cards at ${n.research.min_score}+ — research with /ai, then /submit`)),t.join("\n")},Uo=async e=>He?null===Yo(e)?null:(await Oo(),Yo(e)):null;Wo&&await Oo();const Fo=async e=>{const o=Ue.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Ue.modules.find(e=>e.number===o.number+1);let t;if(Be){const e=await O({token:Ye,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}Wo&&await Oo();const r=No?.phases.find(e=>e.phase===o.number);return Te(Ue,Ke,o,n,t,r),!0},zo=()=>{_o=!0,console.log(chalk.gray(xo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Bo=()=>{po=null;const e=Lo(Ke.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":pe(e,Ue),e.check?(so=e.number,To=Date.now()):(de(Ke,e.number),se(Ke));break;case"mcq":fe(e,Ue),ro=e.number;break;case"practical":we(e,Ue),lo=e.number;break;case"sim_demo":ke(e,Ue),de(Ke,e.number),se(Ke);break;case"milestone":ve(e,Ue),me(Ke,e.badge),de(Ke,e.number),se(Ke);break;case"arena_task":Ae(e,Ue),de(Ke,e.number),se(Ke);break;case"coming_soon":Ce(e,Ue),de(Ke,e.number),se(Ke)}Ho(e.number)},Ho=e=>{if(!Wo||!No)return;const o=Ue.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const n=e-o.cardRange[0]+1;if(n%4!=0)return;const t=n/4,r=No.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===t);if(!l)return;const s=(e,o,n,t)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${o}:${String(n).padStart(2,"0")}`})(n),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${n(o.getMonth()+1)}-${n(o.getDate())} ${n(o.getHours())}:${n(o.getMinutes())}`})(t);return`🏆 ${e} ${o}/${l.n}`+(r?xo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Ne());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${xo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(xo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(xo()?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(xo()?`${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(xo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(xo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(xo()?"✍ 第一次用 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(xo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(xo()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${t}`)+(l.passed?chalk.gray(xo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(xo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(xo()?" 继续学习":" keep going"):chalk.gray(xo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(xo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Zo=()=>{Ye.endsWith("DEMO01")?console.log(chalk.yellow(xo()?" 🐼 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(xo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(xo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Jo=async(e,o)=>{if(Be){mo=!0;try{console.log(),console.log(chalk.gray("deep"===o?xo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":xo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await U({token:Ye,cardNumber:Ke.currentCard,question:e,mode:o,history:vo().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(t||(process.stdout.write(n?"\n\n ":" "),t=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||t)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(xo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(vo().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(` (${xo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(xo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==so&&console.log(chalk.gray(xo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{mo=!1}}else Zo()},Ko=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Qo=async()=>{ho&&jo?ln?sn(ln):nn():po?await Vo():Bo()},Vo=async()=>{mo=!0;try{console.log();const e=await B({token:Ye,curriculumId:Ue.id,cardNumber:Ke.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(xo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(xo()?` 🏆 本卡实时 Top-3 — 第 ${Ke.currentCard} 张`:` 🏆 Live top-3 — card ${Ke.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(xo()?" (你)":" (you)"):""))}else console.log(chalk.gray(xo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Io.set(Ke.currentCard,e.mine.rank),console.log(chalk.white(xo()?" 你: ":" You: ")+chalk.bold.yellow(xo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(xo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Be&&console.log(chalk.gray(xo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),je({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(xo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(xo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(xo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),po="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(xo()?" 返回卡片":" returns to the card")),console.log()}finally{mo=!1}},Xo=e=>xo()&&e.title_zh||e.title,Go=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of Re(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},en=e=>{console.log(),console.log(chalk.bold.green(xo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(xo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},on=e=>jo.data.solved.includes(e.id)?"✅":jo.data.carried?.includes(e.id)?"✅↗":jo.tried.has(e.id)?"❌":"⬜",nn=()=>{const e=jo.data,o=G(e.deadline),n=(e.carried??[]).filter(o=>!e.solved.includes(o)),t=e.solved.length+n.length,r=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(xo()?` · 第 ${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(xo()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(xo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(xo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(xo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(xo()?" 带过来,不必重做":" to carry them over instead of redoing them"));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(xo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(xo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(xo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(xo()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+on(e)+chalk.white(` ${Xo(e)}`))}),console.log(),tn()},tn=()=>{console.log(chalk.gray(xo()?" /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((xo()," "))+chalk.bold.green("/syntax <词>")+chalk.gray(xo()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(xo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(xo()?" 返回课程":" returns to the lesson")),console.log()},rn=e=>{const o=parseInt(e,10),n=jo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(xo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let ln=null;const sn=e=>{const o=rn(e);if(!o)return;const{p:n,n:t}=o;ln=String(t),console.log(),console.log(chalk.bold.white(` ${on(n)} ${Xo(n)}`)),console.log();for(const e of(e=>xo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of Re(e,Ne()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of n.samples??[]){r+=1,console.log(),console.log(chalk.gray(xo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(xo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(n.samples??[]).length&&(console.log(),console.log(chalk.gray(xo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(xo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(xo()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${t}`.padEnd(11))+chalk.gray(xo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(xo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(xo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray(xo()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(xo()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((xo()," ↩ "))+chalk.bold.green("back")+chalk.gray(xo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(xo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((xo()," / "))+chalk.bold.green("wide")+chalk.gray(xo()?" 换语言/宽度":" language / width")),console.log()},an=async(e,o)=>await new Promise(n=>{const t=process.stdin,s=!!t.isTTY&&!!t.isRaw;if(eo.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const a=r(e,o,{stdio:"inherit",cwd:jo.dir}),i=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&s)try{t.setRawMode(!0)}catch{}l(),eo.resume(),n(e)};a.on("close",()=>i(null)),a.on("error",e=>i(e))}),cn=()=>{console.log(chalk.yellow(xo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(xo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(xo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(xo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},dn=new Map,gn=async e=>{const o=e.trim().toLowerCase(),l=ho&&o.startsWith("/")?o.slice(1):o;if(mo)return;if(null!==ao){if(io.push(e.replace(/\s+$/,"")),go&&clearTimeout(go),go=null,co){const e=io[io.length-1]??"";return"/cancel"===e.trim()?(uo(),console.log(chalk.gray(xo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void to()):""!==e.trim()?void to():(io.pop(),void await a())}return void(go=setTimeout(()=>{if(go=null,io.length>1){co=!0;const e=io.length;return console.log(chalk.cyan(xo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(xo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void to()}a()},140))}async function a(){const e=io.join("\n").replace(/^\s+|\s+$/g,""),o=ao??Ke.currentCard,n=io.length;if(uo(),""===e)console.log(chalk.gray(xo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(xo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(xo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(xo()?" 即可执行。":" again to run it."));else{const t=To>0?Date.now()-To:void 0;if(await I(Ye,{curriculum_id:Ue.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const t=n>1?xo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(xo()?` ✓ 已收到${t},谢谢帮助完善这张卡。`:` ✓ Thanks ${t}— your report was recorded.`)),console.log(chalk.gray(xo()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),Ze=[...Ze,{id:Je--,curriculumId:Ue.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Pe(Ze)}else console.log(chalk.yellow(xo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),to()}if(fo){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return fo=!1,console.log(),console.log(chalk.yellow(xo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(xo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(xo()?" 即可执行该命令。":" again to run it.")),console.log(),void to();if(!o)return fo=!1,console.log(chalk.gray(xo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void to();const n=await Y({token:Ye,nickname:o});if(n.ok)fo=!1,console.log(chalk.bold.green(xo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(xo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{bo+=1;const e="taken"===n.code?xo()?"已被占用":"already taken":"bad_charset"===n.code?xo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?xo()?"未通过审核":"did not pass review":n.message||"error";if(!(bo>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(xo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void to();fo=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(xo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void to()}if(Ao){Ao=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{mo=!0;try{console.log(),console.log(chalk.gray(xo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await F({token:Ye,cardNumber:Ke.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(xo()?"评审暂不可用。":"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(xo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(xo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(xo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(xo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(xo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(xo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=xo()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(xo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(xo()?` 第 ${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 Ko(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(xo()?" 改进提问: ":" 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(` (${xo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Co.add(Ke.currentCard):Co.delete(Ke.currentCard),"number"==typeof e.rank&&Io.set(Ke.currentCard,e.rank);const o=await B({token:Ye,curriculumId:Ue.id,cardNumber:Ke.currentCard});o.ok&&o.totals&&o.chapters&&(je({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Fe&&(fo=!0,bo=0,console.log(chalk.bold.yellow(xo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(xo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(xo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{mo=!1}})():(console.log(chalk.gray(xo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==so&&(console.log(chalk.gray(xo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void to()}if(_o)return _o=!1,Bo(),void to();if(!o)return void to();if($o)return"exit"===await c(e.trim())&&($o=!1),void to();if(yo){if(["q","quit","exit","back","b","menu"].includes(o))return yo=!1,console.log(chalk.gray(xo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void to();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim(),r=/^(\/?(submit|read|edit|run|debug|list|honors|recall|view|ai|syntax|contest)\b\s*\d*|card\s+\d+|\d+|status|bookmark|unbookmark|reload|link|wide|wider|normal|narrow|next|ok|y|n|yes|no|menu|lang(\s+\S+)?)$/i.exec(t),l=t.length>0&&!/[\p{L}\p{N}]/u.test(t);return r||l?(console.log(),console.log(chalk.yellow(xo()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?xo()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":xo()?`「${t}」是卡片命令,不是问题,没有送出去。`:`“${t}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(xo()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(xo()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void to()):(t&&(await Jo(t,n?"fast":"deep"),console.log(chalk.gray(xo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void to())}if(ho&&jo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${jo.phase}s${jo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return ho=!1,console.log(chalk.gray(xo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Bo(),void to();if(/^\d+$/.test(o))return sn(o),void to();const t=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(t)return await(async e=>{const o=e.trim();if(!o)return void N(xo());const n=M(o);if(n.length){R(n[0],xo());const e=n.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(xo()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const t=await q("python3",o);t?j(t,xo()):(console.log(),console.log(chalk.yellow(xo()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(xo()?" 试试: ":" Try: ")+chalk.cyan(L(o).join(" · "))),console.log(chalk.gray(xo()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log())})(t[1]??""),void to();const r=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(r){const[,e,o]=r;return"list"===e?nn():o?"read"===e||"open"===e?sn(o):"edit"===e?await(async e=>{const o=rn(e);if(!o)return;const n=A(jo.dir,`sol-${o.n}.py`);if(ne())return te()?(console.log(chalk.yellow(xo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(xo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(xo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(xo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(xo()?" ← 不能是 /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(xo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(xo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(xo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(xo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(xo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(xo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(xo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(xo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!re("vi"))return console.log(chalk.yellow(xo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(xo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(xo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return p(e).size}catch{return 0}},r=t(n),l=Date.now();await an("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),Ro.set(o.n,w(Ro.get(o.n)??b(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(xo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(xo()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=rn(e);if(!o)return;const{p:t,n:r}=o,l=A(jo.dir,`sol-${r}.py`);if(!g(l))return void console.log(chalk.yellow(xo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Ro.set(r,k(Ro.get(r)??b()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(xo()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=n("python3",[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if("ENOENT"===o.code)cn();else if(o.killed)console.log(chalk.yellow(xo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(xo()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const i=a.replace(/\r\n/g,"\n").trimEnd(),c=s.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(xo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(xo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(xo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(xo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(xo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(xo()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=rn(e);if(!o)return;const n=A(jo.dir,`sol-${o.n}.py`);if(!g(n))return void console.log(chalk.yellow(xo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(xo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const t=await an("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(xo()?" 回到竞技场。":" Back in the arena.")),console.log()):cn()})(o):"recall"===e&&await(async e=>{const o=rn(e);if(!o)return;if(!Be)return void Zo();const{p:n,n:t}=o,r=A(process.cwd(),"icoa-contest"),l=`${Ue.id}-phase${jo.phase}-g${jo.data.slot}-archived-`;let s=null;try{for(const e of y(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?A(r,s,`sol-${t}.py`):null;if(!a||!g(a))return void console.log(chalk.gray(xo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${jo.phase}-${jo.data.slot}-${t}`,d=Math.min(3,(dn.get(c)??0)+1);console.log(chalk.gray(xo()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const u=await D({token:Ye,phase:jo.phase,slot:jo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:d,lang:xo()?"zh":"en"});if(u.ok){dn.set(c,d),console.log();for(const e of Re(u.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(xo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(xo()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===u.code?console.log(chalk.yellow(xo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${u.message}`)):console.log(chalk.yellow(` ${u.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(xo()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(xo()?" (花名册: /list)":" (roster: /list)")),void to()}if("contest"===o||"/contest"===o)return nn(),void to();const a="lang"===o||/^lang\s+\S+$/.test(o),i=Oe.has(o);if(!("submit"===l||l.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||a||i||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(xo()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void to()}if("tmux"===o||o.startsWith("tmux ")){try{t("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(xo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void to()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(eo.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&t)try{n.setRawMode(!0)}catch{}eo.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void to()}if("ai4ioai"===o||"/ai4ioai"===o)return await d()&&($o=!0),void to();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Be)return Zo(),void to();wo||(wo=!0,console.log(),console.log(chalk.bold.cyan(xo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(xo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(xo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),xo()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const n=o.startsWith("/ai!"),t=e.trim().slice(n?4:3).trim();if(!t){yo=!0;const e=Lo(Ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(xo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(xo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(xo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void to()}return await Jo(t,n?"fast":"deep"),void to()}if(!ho&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Be)return Zo(),void to();const e=Lo(Ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(xo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(xo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(xo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(xo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(xo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(xo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(xo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Ao=!0,void to()}const i=!ho&&"honors"===po&&/^[1-3]$/.test(o);if(!ho&&po&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(xo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(xo()?" ↩ back 回上一层":" ↩ back goes up one level")),void to();if(!ho&&(i||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Be)return Zo(),void to();const e=/^\/?view ([1-3])$/.exec(o),n=i?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{mo=!0;try{console.log();const o=await z({token:Ye,cardNumber:Ke.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(xo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Co.delete(Ke.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Co.add(Ke.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(xo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${Ke.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${Ke.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(xo()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of n){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(xo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=Ko(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(xo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),po="view",console.log(chalk.gray((xo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(xo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{mo=!1}})(n),void to()}if("/honors"===o||"honors"===o)return Fe?(console.log(),console.log(chalk.gray(xo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void to()):(await Vo(),void to());if("menu"===o||"menu confirm"===o){if(Eo.length>0&&await Promise.race([Promise.allSettled(Eo),new Promise(e=>setTimeout(e,3e3))]),eo.removeAllListeners("line"),no(),Xe||!Mo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Xe?eo:void 0),qo()}else eo.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===po)return await Vo(),void to();if("honors"===po)return po=null,Bo(),void to();if(Eo.length>0&&await Promise.race([Promise.allSettled(Eo),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Ke.streakDays} day(s)`)),console.log(),Xe){eo.removeAllListeners("line"),no();for(const e of Ge)eo.on("line",e);eo.prompt(),qo()}else eo.removeAllListeners("line"),eo.close();return}if("status"===o)return _e(Ue,Ke),void to();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await _(Ue.id,Ye,!0);return void(e?(Object.assign(Ue,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Bo()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本")),to()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(ee().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void to();const n=Ue.cards.some(e=>null!=e._zh),t=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===t||"zh"===t&&n,l=r?t:"en";return oe({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),so=null,ro=null,lo=null,uo(),_o=!1,Ao=!1,await Qo(),void to()}if(Oe.has(o)){const e=Oe.get(o),n=Me(ee()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return xo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((xo()?"normal"===e?" 已是标准 64 列。":Ne()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Ne()} 列,上限 ${Le(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Ne()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Ne()} cols, cap ${Le(e)}). `)+t(e))),void to()):(oe({learnWidth:e,learnWide:"normal"!==e}),qe(e),"normal"!==e&&Ne()<=64?(console.log(chalk.yellow(xo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((xo()?` 设置已记住(${e},上限 ${Le(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Le(e)} cols) and applies once you widen the window. `)+t(e))),void to()):(console.log(chalk.green(" ✓ ")+chalk.gray((xo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Ne()} 列,上限 ${Le(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Ne()} cols, cap ${Le(e)}). `)+t(e))),so=null,ro=null,lo=null,uo(),_o=!1,Ao=!1,await Qo(),void to()))}if("sim"===o){const e=Lo(Ke.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=v(C(import.meta.url)),o=[A(e,"..","..","panda","mujoco-launcher.py"),A(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(g(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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--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 to()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void to())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=Ke.currentCard,n=Ke.bookmarks.includes(e),t="bookmark"!==o;return t?Ke.bookmarks=Ke.bookmarks.filter(o=>o!==e):n||Ke.bookmarks.push(e),se(Ke),t?console.log(n?chalk.gray(xo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(xo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(xo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(xo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void to()}const T=E(o);if(T){const e="current"===T.target?Ke.currentCard:T.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>Ue.cards.length))return console.log(chalk.yellow(xo()?` 本课共 ${Ue.cards.length} 张,请输 r 1–${Ue.cards.length} 或 r all。`:` This course has ${Ue.cards.length} cards. Try r 1–${Ue.cards.length} or r all.`)),console.log(),void to();for(const o of S(Ze,e,xo(),Ne()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?Ze:Ze.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(Ze=Ze.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Pe(Ze),Eo.push(x(Ye,{card_number:Ke.currentCard,event_type:"viewed"},o).catch(()=>{}))),void to()}if("e"===o)return ao=Ke.currentCard,console.log(chalk.gray(xo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void to();if("back"===o||"b"===o)return"view"===po?(await Vo(),void to()):"honors"===po?(po=null,Bo(),void to()):(Ke.currentCard>1&&(Ke.currentCard-=1),ro=null,lo=null,so=null,se(Ke),Bo(),void to());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Wo)return console.log(chalk.yellow(xo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void to();if(!e){const e=await Q(Ye),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(xo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(xo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(xo()?` 这台电脑上有 ${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(xo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(xo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(xo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(xo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(xo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(xo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(xo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void to()}if(/^\d{1,2}$/.test(e)){const o=await K(Ye,Number(e));return o.ok&&o.data?(en(o.data),await Oo(),void to()):(console.log(chalk.red(` ✗ ${o.message||(xo()?"关联失败":"Link failed")}`)),void to())}const n=await V(Ye,e);return n.ok&&n.data?(en(n.data),await Oo(),void to()):(console.log(chalk.red(` ✗ ${n.message||(xo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(xo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void to())}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(!Wo)return console.log(chalk.yellow(xo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void to();const e=Do(Ke.currentCard);if("contest reset"===o){const o=await H(Ye,e);if(o.ok){console.log(chalk.yellow(xo()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let n=1;n<=3;n++){const t=A(process.cwd(),"icoa-contest",`${Ue.id}-phase${e}-g${n}`);if(g(t))try{h(t,`${t}-archived-${o}`),console.log(chalk.gray(xo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(xo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(xo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),jo=null,ho=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void to()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(xo()?" 连接判分赛…":" Contacting contest server…"));const t=await Z(Ye,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(xo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void to();const r=t.data,l=A(process.cwd(),"icoa-contest",`${Ue.id}-phase${e}-g${r.slot}`);u(l,{recursive:!0});const s=jo&&jo.phase===e&&jo.data.slot===r.slot?jo.tried:new Set;jo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.samples??[])[0];l&&f(A(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=A(o,`sol-${r}.py`);if(g(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${n.title} ══`,"#",...Go(n.statement,72)];if(n.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.out.split("\n"))a.push(`# ${e}`)}a.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","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),f(s,a.join("\n"))})})(r,l),ho=!0,nn(),console.log(chalk.gray(xo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(xo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(xo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void to()}if("submit"===l)return console.log(chalk.yellow(xo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(xo()?" 例如 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)")),jo||console.log(chalk.gray(xo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void to();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const n=e[2];if(!jo)return console.log(chalk.yellow(xo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void to();const t=jo.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=t.length&&!t.some(e=>e.id===o)&&(o=t[r-1].id),!t.some(e=>e.id===o))return console.log(chalk.yellow(xo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void to();const s=t.findIndex(e=>e.id===o)+1,a=n||A(jo.dir,`sol-${s}.py`);let i;try{i=m(a,"utf-8")}catch{return console.log(chalk.red(xo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void to()}console.log(chalk.gray(xo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Ro.get(s),d=await J(Ye,jo.phase,o,i,void 0,c&&!$(c)?c:void 0);if(!d.ok||!d.data)return"no_active_session"===d.code?console.log(chalk.yellow(xo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((xo()," "))+chalk.bold.green("contest")+chalk.gray(xo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(xo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void to();const g=d.data;if(g.already_ac)console.log(chalk.green(xo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(xo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(xo()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),jo.data.solved.includes(o)||jo.data.solved.push(o),jo.tried.delete(o);else{jo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?xo()?` · 挂在第 ${g.test} 个用例(过 ${g.passed_tests}/${g.total_tests})`:` · failed test ${g.test} (passed ${g.passed_tests}/${g.total_tests})`:""))}g.late&&console.log(chalk.yellow(xo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=G(g.deadline||"");if(console.log(chalk.white(xo()?` 本组进度: 已过 ${g.ac_count} 题 · 过 ${g.need} 题过关(共 ${g.n} 题)`:` Group progress: ${g.ac_count} solved · ${g.need} needed to pass (${g.n} problems)`)+(u?chalk.gray(` · ⏱ ${u}`):"")),g.passed&&!g.late)console.log(chalk.bold.green(xo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Oo();else if(!g.late){const e=t.findIndex(e=>!jo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(xo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Xo(t[e])}`))}return void to()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Ue.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Ue.totalCards}. Try: `)+chalk.bold.green("card 1")),void to();const t=await Uo(n);return t?(console.log(t),void to()):(Ke.currentCard=n,ro=null,lo=null,so=null,se(Ke),Bo(),void to())}if(null!==so&&["y","yes","n","no"].includes(o)){const e=Lo(so);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-To;de(Ke,e.number),ue(Ke,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),se(Ke);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),Eo.push(x(Ye,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),so=null,e.solution&&e.solution.length>0)return void to();if(Ke.currentCard<Ue.totalCards){const e=Ke.currentCard,o=await Uo(e+1);if(o)return await Fo(e),console.log(o),void to();Ke.currentCard+=1,se(Ke),await Fo(e)?zo():Bo(),to()}else xe(Ue,Ke),to();return}}if(null!==ro&&["a","b","c","d"].includes(o)){const e=Lo(ro);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(ge(Ke,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),de(Ke,e.number),se(Ke),be(e,n,t,Ke),Eo.push(x(Ye,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),ro=null,t)if(Ke.currentCard<Ue.totalCards){const e=await Uo(Ke.currentCard+1);if(e)return console.log(e),void to();Ke.currentCard+=1,se(Ke),Bo()}else xe(Ue,Ke),to();else to();return}}if(null!==lo){if("done"===o){const e=Lo(lo);if(e&&"practical"===e.type)return ye(Ke,e.number),de(Ke,e.number),se(Ke),$e(e),lo=null,void to()}if("skip"===o)return de(Ke,lo),se(Ke),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),lo=null,void to()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ro)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void to();if(null!==lo)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void to();if(null!==so)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void to();const e=Ke.currentCard,o=e<Ue.totalCards?await Uo(e+1):null;return o?(await Fo(e),console.log(o),void to()):(Ke.currentCard+=1,se(Ke),Ke.currentCard>Ue.totalCards?xe(Ue,Ke):await Fo(e)?zo():Bo(),void to())}return null!==so?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void to()):null!==ro?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void to()):null!==lo?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void to()):("view"===po?console.log(chalk.gray(xo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(xo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(xo()?" 回卡片":" to the card")):"honors"===po?console.log(chalk.gray(xo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(xo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(xo()?" 回卡片":" 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 to())};eo.on("line",e=>{gn(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.")),to()})}),Xe||eo.on("close",async()=>{Eo.length>0&&await Promise.race([Promise.allSettled(Eo),new Promise(e=>setTimeout(e,5e3))]),Mo?qo():process.exit(0)});const un=P(Ze,xo());un&&(console.log(chalk.bold.cyan(` ${un}`)),console.log());try{Bo(),to();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(We("Could not render this card — the curriculum may be malformed."),Xe){eo.removeAllListeners("line"),no();for(const e of Ge)eo.on("line",e);eo.prompt()}else eo.close();qo()}await Po}),De.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 n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await _(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
package/dist/lib/py-syntax.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as e}from"node:child_process";import chalk from"chalk";export const SYNTAX_TABLE=[{keys:["del","delete","remove index"],en:"Statement, not a method: deletes without returning. Only `del` can delete a slice.",zh:"语句(不是方法):删掉但不返回。只有 del 能删切片。",demo:["l = [0, 1, 2, 3, 4, 5]","del l[1] # → [0, 2, 3, 4, 5]","del l[1:3] # → [0, 4, 5] slice: pop cannot","del l[:] # → [] same as l.clear()","del l[9] # IndexError; del l[9:99] is silently fine"]},{keys:["pop","list.pop"],en:"Method: removes AND returns. O(1) at the end, O(n) anywhere else.",zh:"方法:删掉并返回。尾部 O(1),其他位置 O(n)。",demo:["l = [10, 20, 30]","l.pop() # → 30 l is [10, 20]","l.pop(0) # → 10 O(n): shifts everything left","[].pop() # IndexError: pop from empty list","d.pop(k, None) # dict: default avoids KeyError"]},{keys:["slice","slicing","sublist"],en:"l[start:stop:step] — stop is EXCLUSIVE, out-of-range is silently clamped.",zh:"l[起:止:步] — 止是开区间,越界静默截断不报错。",demo:["l = [0, 1, 2, 3, 4]","l[1:3] # → [1, 2] stop excluded","l[:2] l[2:] # → [0,1] [2,3,4]","l[-2:] # → [3, 4] last two","l[::-1] # → [4,3,2,1,0] reversed copy","l[9:99] # → [] no IndexError"]},{keys:["fstring","f-string","format","interpolate"],en:'f"..." embeds expressions; :.2f rounds, := width pads, {x=} prints name+value.',zh:'f"..." 内嵌表达式;:.2f 保留小数,:>5 补宽,{x=} 连名字一起打。',demo:["n, x = 7, 3.14159",'f"{n} items" # → "7 items"','f"{x:.2f}" # → "3.14"','f"{n:>5}" # → " 7" right-pad to 5','f"{n=}" # → "n=7" debug form']},{keys:["comprehension","listcomp","dictcomp","setcomp"],en:"Build a list/dict/set in one expression; the `if` filters, and it is faster than append in a loop.",zh:"一行构造 list/dict/set;if 做过滤,比循环里 append 快。",demo:["[x * x for x in range(5)] # → [0,1,4,9,16]","[x for x in l if x % 2 == 0] # filter","{k: len(k) for k in words} # dict","{x % 3 for x in l} # set (dedups)","[(i, c) for i, c in enumerate(s)] # pairs"]},{keys:["sort","sorted","key","sort by"],en:"sorted() returns a new list; l.sort() edits in place and returns None. key= is the sort field.",zh:"sorted() 返回新表;l.sort() 原地改并返回 None。key= 指定按什么排。",demo:["sorted(l) # new list, ascending","sorted(l, reverse=True) # descending","sorted(ps, key=lambda p: p[1]) # by 2nd field","sorted(ps, key=lambda p: (-p[1], p[0])) # desc, then asc tiebreak","l.sort() # in place — returns None!"]},{keys:["stdin","input","read input","fast io"],en:"input() per line; for big input read all of stdin at once — it is far faster.",zh:"input() 一行一行;数据量大时一次读完整个 stdin,快得多。",demo:["n = int(input()) # one number","a = list(map(int, input().split())) # a line of numbers","import sys","data = sys.stdin.read().split() # everything, fastest","for line in sys.stdin: # stream line by line"]},{keys:["print","output","sep","end"],en:"print joins args with a space and adds a newline; sep=/end= change both.",zh:"print 用空格连接参数并换行;sep=/end= 可改。",demo:['print(a, b) # "1 2\\n"',"print(*l) # unpack: each item, space-separated",'print(" ".join(map(str, l))) # explicit, no trailing space','print(x, end="") # no newline','print(a, b, sep=",") # "1,2"']},{keys:["2d list","grid","matrix","2d array"],en:"TRAP: [[0]*m]*n shares ONE row — every row changes together. Build rows in a comprehension.",zh:"陷阱:[[0]*m]*n 是同一行的 n 个引用,改一行全变。用推导式逐行造。",demo:["g = [[0] * 3 for _ in range(2)] # CORRECT","g[0][0] = 9 # → [[9,0,0], [0,0,0]]","","bad = [[0] * 3] * 2 # WRONG — aliased","bad[0][0] = 9 # → [[9,0,0], [9,0,0]] both rows!"]},{keys:["copy","deepcopy","alias","reference"],en:"b = a does NOT copy a list — both names point at one object. Slice or list() for a shallow copy.",zh:"b = a 不是拷贝,两个名字指同一个对象。浅拷贝用切片或 list()。",demo:["b = a # same object — a changes too","b = a[:] # shallow copy (or list(a))","import copy","b = copy.deepcopy(a) # nested lists too"]},{keys:["recursionerror","recursion limit","setrecursionlimit"],en:"CPython caps nesting near 1000 calls. Raise the limit, or rewrite as a loop (usually the right answer).",zh:"CPython 嵌套上限约 1000 层。可以抬上限,但改成循环通常才是对的。",demo:["import sys","sys.setrecursionlimit(300000) # buys depth, not speed","# depth grows with n → prefer iteration:","total = 0","for i in range(1, n + 1): total += i"]},{keys:["dict get","keyerror","default","setdefault"],en:"d[k] raises KeyError; d.get(k, default) does not. Counting? use a Counter.",zh:"d[k] 缺键报 KeyError;d.get(k, 默认) 不报。计数用 Counter。",demo:["d.get(k) # → None if missing","d.get(k, 0) + 1 # count safely","d.setdefault(k, []).append(v) # group into lists","from collections import Counter, defaultdict","Counter(l).most_common(3) # top 3 by frequency"]},{keys:["divide","division","modulo","floor","divmod"],en:"/ is always float; // floors (toward -inf, watch negatives); % follows the divisor sign.",zh:"/ 一定是浮点;// 向下取整(负数会咬人);% 的符号跟除数。",demo:["7 / 2 # → 3.5 float, even for ints","7 // 2 # → 3 floor","-7 // 2 # → -4 NOT -3","-7 % 2 # → 1 sign follows divisor","divmod(7, 2) # → (3, 1)"]},{keys:["try","except","finally","raise"],en:"Catch the narrowest type you expect; finally always runs; bare except hides real bugs.",zh:"只抓你预期的最窄类型;finally 一定执行;裸 except 会藏真 bug。",demo:["try:"," x = int(s)","except ValueError:"," x = 0","finally:"," ... # always runs"]},{keys:["unpack","star","args","kwargs","swap"],en:"* spreads an iterable, ** spreads a dict; a, *rest = l splits head from tail.",zh:"* 展开可迭代,** 展开字典;a, *rest = l 拆头尾。",demo:["a, b = b, a # swap, no temp","a, *rest = [1, 2, 3] # a=1 rest=[2,3]","f(*l) # positional spread","f(**d) # keyword spread","x, y = map(int, input().split())"]},{keys:["enumerate","zip","index in loop"],en:"enumerate gives (index, item); zip walks lists in parallel and stops at the shortest.",zh:"enumerate 给 (下标, 元素);zip 并行遍历,以最短的为准。",demo:["for i, c in enumerate(s): ...","for i, c in enumerate(s, 1): ... # start at 1","for a, b in zip(xs, ys): ...","list(zip(*rows)) # transpose a grid"]},{keys:["string methods","split","join","strip","replace"],en:"Strings are immutable — every method returns a NEW string.",zh:"字符串不可变 —— 每个方法都返回新字符串。",demo:["s.split() # on any whitespace → list",'s.split(",") # on a comma','"-".join(parts) # list → string (parts must be str)',"s.strip() # trim both ends","s.replace(a, b) # returns new; s unchanged"]},{keys:["ternary","inline if","conditional expression"],en:"Value-position if: `a if cond else b` — one expression, always needs the else.",zh:"值位置的 if:a if 条件 else b —— 是表达式,else 不能省。",demo:["x = 1 if ok else -1",'print("yes" if n > 0 else "no")',"l = [f(x) if x else 0 for x in xs]"]},{keys:["set","dedup","union","intersection","in"],en:"set() dedups and makes `in` O(1) instead of O(n) — the single biggest easy speedup.",zh:"set() 去重,并让 in 从 O(n) 变 O(1) —— 最容易拿到的一次加速。",demo:["seen = set(); seen.add(x)","if x in seen: ... # O(1); on a list this is O(n)","a | b a & b a - b # union / intersect / difference","len(set(l)) # distinct count"]},{keys:["walrus",":=","assignment expression"],en:"Assign inside an expression — mostly for while-read loops.",zh:"在表达式里赋值 —— 主要用在 while 读输入。",demo:["while (line := sys.stdin.readline()):"," ...","if (m := len(l)) > 3: print(m)"]},{keys:["lambda","anonymous function"],en:"One-expression function, no return keyword. Mostly for key= / sort.",zh:"单表达式函数,不写 return。主要给 key= / 排序用。",demo:["key=lambda p: p[1]","key=lambda p: (-p[1], p[0]) # desc then asc","f = lambda x: x * 2"]},{keys:["range","loop n times","countdown"],en:"range(stop) / range(start, stop[, step]) — stop is EXCLUSIVE.",zh:"range(止) / range(起, 止[, 步]) —— 止是开区间。",demo:["range(5) # 0 1 2 3 4","range(1, 6) # 1..5","range(10, 0, -1) # 10 down to 1","range(0, 10, 2) # 0 2 4 6 8"]},{keys:["float","rounding","precision","isclose"],en:"Binary floats are inexact: 0.1+0.2 != 0.3. Compare with a tolerance, never ==.",zh:"二进制浮点不精确:0.1+0.2 != 0.3。比较要给容差,别用 ==。",demo:["0.1 + 0.2 == 0.3 # → False","abs(a - b) < 1e-9 # compare like this","round(2.675, 2) # → 2.67 (not 2.68)",'f"{x:.6f}" # print fixed decimals']},{keys:["truthy","falsy","empty check","none"],en:'Empty containers, 0 and "" are falsy. Test None with `is None`, not ==.',zh:'空容器、0、"" 都是假。判 None 用 is None,不用 ==。',demo:["if not l: ... # empty list/str/dict","if x is None: ... # None specifically","if l: ... # non-empty","# careful: 0 and [] are both falsy but not equal"]}];export const SYNTAX_INDEX=SYNTAX_TABLE.map(e=>e.keys[0]);function t(e){return n(e).toLowerCase()}function n(e){return e.trim().replace(/^\/+/,"").replace(/[?。?]+$/,"").replace(/\s+/g," ")}export function lookupLocal(e){const n=t(e);if(!n)return null;for(const e of SYNTAX_TABLE)if(e.keys.some(e=>e===n))return e;const s=n.split(" ").filter(Boolean);let o=null;for(const e of SYNTAX_TABLE){let t=0;for(const o of e.keys)o.includes(" ")?n.includes(o)&&(t+=2*o.length):s.includes(o)&&(t+=o.length);t>0&&(!o||t>o.score)&&(o={e:e,score:t})}return o?o.e:null}export function nearKeys(e,n=6){const s=t(e).split(" ").filter(e=>e.length>=3),o=SYNTAX_INDEX.filter(e=>s.some(t=>e.includes(t)||t.includes(e)));return(o.length?o:SYNTAX_INDEX).slice(0,n)}export function lookupPydoc(t,s,o=14){const i=n(s);return i.length>60||!/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,2}$/.test(i)?Promise.resolve(null):new Promise(n=>{let s="",r=!1;const l=e=>{r||(r=!0,n(e))};let a;try{a=e(t,["-c","\nimport io, sys, contextlib, pydoc\nq = sys.argv[1] if len(sys.argv) > 1 else ''\ncands = [q] + ([] if '.' in q else ['list.' + q, 'str.' + q, 'dict.' + q, 'set.' + q])\nfor c in cands:\n try:\n txt = pydoc.render_doc(c, renderer=pydoc.plaintext)\n except Exception:\n continue\n print('OBJ ' + c); print(txt); sys.exit(0)\nbuf = io.StringIO()\ntry:\n with contextlib.redirect_stdout(buf):\n pydoc.Helper(output=buf).help(q.upper())\n out = buf.getvalue()\nexcept Exception:\n out = ''\nif out.strip() and 'no python documentation' not in out.lower():\n print('TOPIC ' + q.upper()); print(out); sys.exit(0)\nsys.exit(1)\n",i],{stdio:["ignore","pipe","ignore"]})}catch{return void l(null)}const d=setTimeout(()=>{try{a.kill("SIGKILL")}catch{}l(null)},4e3);a.stdout?.on("data",e=>{s+=String(e)}),a.on("error",()=>{clearTimeout(d),l(null)}),a.on("close",e=>{if(clearTimeout(d),0!==e||!s.trim())return void l(null);const t=s.split("\n"),n=(t[0]??"").replace(/^(OBJ|TOPIC)\s+/,"").trim(),i=/^\s*\|?\s*(Method resolution order|Methods? (defined here|inherited)|Data (descriptors|and other attributes)|Static methods|Class methods|Readonly properties|-{3,}|_{2})/,r=[];for(const e of t.slice(1)){if(/^Python Library Documentation/.test(e))continue;if(i.test(e))break;const t=e.replace(/^\s*\|\s?/," ");(t.trim()||r.length&&r[r.length-1].trim())&&r.push(t)}for(;r.length&&!r[0].trim();)r.shift();for(;r.length&&!r[r.length-1].trim();)r.pop();l({title:n,lines:r.slice(0,o)})})})}export function renderSyntax(e,t){console.log(),console.log(chalk.bold.white(` ${e.keys[0]}`)+chalk.gray(t?" (语法速查)":" (syntax lookup)")),console.log(chalk.gray(` ${t?e.zh:e.en}`)),console.log();for(const t of e.demo)console.log(t.trim()?chalk.cyan(` ${t}`):"");console.log()}export function renderPydoc(e,t){console.log(),console.log(chalk.bold.white(` ${e.title}`)+chalk.gray(t?" (你本机 Python 的官方文档)":" (your own Python's official doc)")),console.log();for(const t of e.lines)console.log(t.trim()?chalk.white(` ${t}`):"");console.log()}
|
|
1
|
+
import{spawn as e}from"node:child_process";import chalk from"chalk";export const SYNTAX_TABLE=[{keys:["del","delete","remove index"],en:"Statement, not a method: deletes without returning. Only `del` can delete a slice.",zh:"语句(不是方法):删掉但不返回。只有 del 能删切片。",demo:["l = [0, 1, 2, 3, 4, 5]","del l[1] # → [0, 2, 3, 4, 5]","del l[1:3] # → [0, 4, 5] slice: pop cannot","del l[:] # → [] same as l.clear()","del l[9] # IndexError; del l[9:99] is silently fine"]},{keys:["list","array","lst"],en:"The workhorse sequence: ordered, mutable, mixed types. End operations are O(1), front operations O(n).",zh:"最常用的序列:有序、可变、可混类型。尾部操作 O(1),头部操作 O(n)。",demo:["l = [] l = [1, 2, 3]","l = [0] * n # n zeros","l.append(x) # add at end O(1)","l[0] l[-1] len(l) # first, last, size O(1)","for i, x in enumerate(l): ...","# O(n) traps: l.pop(0) · l.insert(0,x) · x in l"]},{keys:["append","extend","insert","add to list"],en:"append adds ONE item; extend adds each item of an iterable; insert shifts everything after it.",zh:"append 加一个;extend 把可迭代对象逐个加进来;insert 会把后面全部搬移。",demo:["l = [1, 2]","l.append([3, 4]) # → [1, 2, [3, 4]] ONE item (a list!)","l = [1, 2]","l.extend([3, 4]) # → [1, 2, 3, 4] each item","l.insert(0, 9) # → [9, 1, 2, 3, 4] O(n), shifts all"]},{keys:["remove","clear","count","index"],en:"remove deletes the FIRST match by value (ValueError if absent); index finds its position; count tallies.",zh:"remove 按值删第一个匹配(没有会 ValueError);index 找位置;count 数个数。",demo:["l = [5, 7, 5]","l.remove(5) # → [7, 5] first match only","l.index(5) # → 1 ValueError if absent","l.count(5) # → 1","l.clear() # → [] same as del l[:]","if x in l: l.remove(x) # guard against ValueError"]},{keys:["dict","hashmap","map","key value"],en:"Key→value with O(1) lookup. Iterating gives keys; use .items() for pairs.",zh:"键→值,查找 O(1)。直接迭代给的是键,要键值对用 .items()。",demo:['d = {} d = {"a": 1}','d["b"] = 2 # insert or overwrite',"for k in d: ... # keys","for k, v in d.items(): ...",'"a" in d # O(1) — checks KEYS, not values',"len(d) d.keys() d.values()"]},{keys:["tuple","immutable","pair"],en:"Like a list but frozen — so it can be a dict key or go in a set. Parentheses optional.",zh:"像 list 但不可改 —— 所以能当 dict 的键、能进 set。括号可省。",demo:["t = (1, 2) t = 1, 2 # same thing","t[0] # read ok","t[0] = 9 # TypeError — immutable","seen = {(r, c)} # a list here would fail","d[(x, y)] = v # coordinate as a key"]},{keys:["deque","queue","bfs","front queue"],en:"THE fix for l.pop(0): popping from either end is O(1). This is what BFS needs.",zh:"l.pop(0) 的正解:两端弹出都是 O(1)。BFS 要的就是它。",demo:["from collections import deque","q = deque([start])","q.append(x) # push right O(1)","q.popleft() # pop left O(1) ← list is O(n)","q.appendleft(x) q.pop()","while q: node = q.popleft()"]},{keys:["heapq","heap","priority queue","smallest"],en:"A min-heap on a plain list: push/pop are O(log n), smallest is always at [0]. Negate for a max-heap.",zh:"建在普通 list 上的小顶堆:push/pop 都是 O(log n),最小值永远在 [0]。取负数即大顶堆。",demo:["import heapq","h = []","heapq.heappush(h, (cost, node)) # tuples sort by first","cost, node = heapq.heappop(h) # smallest","h[0] # peek, no removal","heapq.heappush(h, -x) # max-heap: negate"]},{keys:["bisect","binary search","sorted insert"],en:"Binary search on an already-SORTED list — O(log n). bisect_left is the insertion point.",zh:"在**已排序**的 list 上二分 —— O(log n)。bisect_left 给的是插入位置。",demo:["import bisect","a = [1, 3, 5, 7]","bisect.bisect_left(a, 5) # → 2 first index >= 5","bisect.bisect_right(a, 5) # → 3 first index > 5","bisect.insort(a, 4) # → [1,3,4,5,7] keeps order"]},{keys:["cache","memo","lru_cache","memoize"],en:"One decorator turns exponential recursion into linear — the biggest single speedup in contest Python.",zh:"一个装饰器把指数级递归变线性 —— 竞赛 Python 里单点提速最大的一招。",demo:["from functools import cache","","@cache","def fib(n):"," return n if n < 2 else fib(n-1) + fib(n-2)","# fib(100) instant; without @cache it never finishes"]},{keys:["math","gcd","sqrt","inf","factorial"],en:"Integer-safe helpers. Use math.isqrt for exact integer square roots and math.inf as a starting bound.",zh:"整数安全的工具。整数开方用 math.isqrt,起始边界用 math.inf。",demo:["import math","math.gcd(12, 18) # → 6 lcm(a,b) = a*b//gcd","math.isqrt(17) # → 4 exact int, no float error","math.inf -math.inf # safe initial min / max","math.ceil(7/2) # → 4 (or -(-7//2))","math.factorial(5) # → 120"]},{keys:["itertools","permutations","combinations","product"],en:"Brute-force generators. Watch the count: permutations of 10 items is 3.6 million.",zh:"暴力枚举生成器。注意规模:10 个元素的全排列是 362 万。",demo:["from itertools import permutations, combinations, product","permutations([1,2,3]) # 6 orderings","combinations([1,2,3], 2) # (1,2) (1,3) (2,3)",'product("ab", repeat=2) # aa ab ba bb',"product(range(3), range(3)) # all grid cells"]},{keys:["any","all","exists"],en:"any = at least one true; all = every one true (and all([]) is True). Both short-circuit.",zh:"any = 至少一个真;all = 全部为真(空表 all([]) 是 True)。两者都短路。",demo:["any(x < 0 for x in l) # is there a negative?","all(x > 0 for x in l) # are they all positive?","all([]) # → True (careful!)","if any(c.isdigit() for c in s): ..."]},{keys:["min","max","sum","total"],en:"Aggregate a whole iterable in one call; key= picks the field, default= saves you from empty input.",zh:"一次聚合整个可迭代对象;key= 指定按什么比,default= 防空输入报错。",demo:["sum(l) min(l) max(l)","max(l, default=0) # empty-safe","min(ps, key=lambda p: p[1]) # by 2nd field","max(range(n), key=lambda i: a[i]) # argmax","sum(x*x for x in l) # no list built"]},{keys:["map","filter","convert list"],en:"map applies a function to every item, filter keeps the truthy ones. Both are lazy — wrap in list() to see them.",zh:"map 对每项应用函数,filter 留下为真的。两者惰性 —— 要看内容得 list() 包一层。",demo:["list(map(int, input().split())) # the standard input line","list(map(str, l)) # ints → strings","list(filter(None, l)) # drop falsy items","# a comprehension is usually clearer:","[int(x) for x in parts]"]},{keys:["join","build string","concatenate"],en:"TRAP: s += x in a loop is O(n squared). Collect in a list, join once.",zh:"陷阱:循环里 s += x 是 O(n²)。先收进 list,最后 join 一次。",demo:["parts = []","for x in l: parts.append(str(x))",'out = " ".join(parts) # ONE pass — correct',"","# slow: rebuilds the whole string every iteration","for x in l: out += str(x)"]},{keys:["reverse","reversed","backwards"],en:"l[::-1] gives a reversed COPY; l.reverse() flips in place and returns None; reversed() is a lazy view.",zh:"l[::-1] 是反转的**拷贝**;l.reverse() 原地反转并返回 None;reversed() 是惰性视图。",demo:["l[::-1] # new reversed list (works on str too)","l.reverse() # in place — returns None!","for x in reversed(l): ... # no copy made","s[::-1] == s # palindrome check"]},{keys:["grid","neighbors","4 directions","flood"],en:"The standard 4-neighbour walk with a bounds guard — the shape almost every grid problem needs.",zh:"标准四邻域遍历 + 越界判断 —— 几乎每道网格题都要这个形状。",demo:["R, C = len(g), len(g[0])","for dr, dc in ((1,0), (-1,0), (0,1), (0,-1)):"," nr, nc = r + dr, c + dc"," if 0 <= nr < R and 0 <= nc < C:"," ... # g[nr][nc]","# 8 dirs: add (1,1) (1,-1) (-1,1) (-1,-1)"]},{keys:["break","continue","while","loop control"],en:"break leaves the loop, continue skips to the next round; both act on the INNERMOST loop only.",zh:"break 跳出循环,continue 跳到下一轮;两者都只作用于**最内层**循环。",demo:["for x in l:"," if x < 0: continue # skip this one"," if x > 99: break # stop entirely","while True:"," if done: break # the usual exit","# leaving 2 loops: use a flag, or return from a function"]},{keys:["pop","list.pop"],en:"Method: removes AND returns. O(1) at the end, O(n) anywhere else.",zh:"方法:删掉并返回。尾部 O(1),其他位置 O(n)。",demo:["l = [10, 20, 30]","l.pop() # → 30 l is [10, 20]","l.pop(0) # → 10 O(n): shifts everything left","[].pop() # IndexError: pop from empty list","d.pop(k, None) # dict: default avoids KeyError"]},{keys:["slice","slicing","sublist"],en:"l[start:stop:step] — stop is EXCLUSIVE, out-of-range is silently clamped.",zh:"l[起:止:步] — 止是开区间,越界静默截断不报错。",demo:["l = [0, 1, 2, 3, 4]","l[1:3] # → [1, 2] stop excluded","l[:2] l[2:] # → [0,1] [2,3,4]","l[-2:] # → [3, 4] last two","l[::-1] # → [4,3,2,1,0] reversed copy","l[9:99] # → [] no IndexError"]},{keys:["fstring","f-string","format","interpolate"],en:'f"..." embeds expressions; :.2f rounds, := width pads, {x=} prints name+value.',zh:'f"..." 内嵌表达式;:.2f 保留小数,:>5 补宽,{x=} 连名字一起打。',demo:["n, x = 7, 3.14159",'f"{n} items" # → "7 items"','f"{x:.2f}" # → "3.14"','f"{n:>5}" # → " 7" right-pad to 5','f"{n=}" # → "n=7" debug form']},{keys:["comprehension","listcomp","dictcomp","setcomp"],en:"Build a list/dict/set in one expression; the `if` filters, and it is faster than append in a loop.",zh:"一行构造 list/dict/set;if 做过滤,比循环里 append 快。",demo:["[x * x for x in range(5)] # → [0,1,4,9,16]","[x for x in l if x % 2 == 0] # filter","{k: len(k) for k in words} # dict","{x % 3 for x in l} # set (dedups)","[(i, c) for i, c in enumerate(s)] # pairs"]},{keys:["sort","sorted","key","sort by"],en:"sorted() returns a new list; l.sort() edits in place and returns None. key= is the sort field.",zh:"sorted() 返回新表;l.sort() 原地改并返回 None。key= 指定按什么排。",demo:["sorted(l) # new list, ascending","sorted(l, reverse=True) # descending","sorted(ps, key=lambda p: p[1]) # by 2nd field","sorted(ps, key=lambda p: (-p[1], p[0])) # desc, then asc tiebreak","l.sort() # in place — returns None!"]},{keys:["stdin","input","read input","fast io"],en:"input() per line; for big input read all of stdin at once — it is far faster.",zh:"input() 一行一行;数据量大时一次读完整个 stdin,快得多。",demo:["n = int(input()) # one number","a = list(map(int, input().split())) # a line of numbers","import sys","data = sys.stdin.read().split() # everything, fastest","for line in sys.stdin: # stream line by line"]},{keys:["print","output","sep","end"],en:"print joins args with a space and adds a newline; sep=/end= change both.",zh:"print 用空格连接参数并换行;sep=/end= 可改。",demo:['print(a, b) # "1 2\\n"',"print(*l) # unpack: each item, space-separated",'print(" ".join(map(str, l))) # explicit, no trailing space','print(x, end="") # no newline','print(a, b, sep=",") # "1,2"']},{keys:["2d list","grid","matrix","2d array"],en:"TRAP: [[0]*m]*n shares ONE row — every row changes together. Build rows in a comprehension.",zh:"陷阱:[[0]*m]*n 是同一行的 n 个引用,改一行全变。用推导式逐行造。",demo:["g = [[0] * 3 for _ in range(2)] # CORRECT","g[0][0] = 9 # → [[9,0,0], [0,0,0]]","","bad = [[0] * 3] * 2 # WRONG — aliased","bad[0][0] = 9 # → [[9,0,0], [9,0,0]] both rows!"]},{keys:["copy","deepcopy","alias","reference"],en:"b = a does NOT copy a list — both names point at one object. Slice or list() for a shallow copy.",zh:"b = a 不是拷贝,两个名字指同一个对象。浅拷贝用切片或 list()。",demo:["b = a # same object — a changes too","b = a[:] # shallow copy (or list(a))","import copy","b = copy.deepcopy(a) # nested lists too"]},{keys:["recursionerror","recursion limit","setrecursionlimit"],en:"CPython caps nesting near 1000 calls. Raise the limit, or rewrite as a loop (usually the right answer).",zh:"CPython 嵌套上限约 1000 层。可以抬上限,但改成循环通常才是对的。",demo:["import sys","sys.setrecursionlimit(300000) # buys depth, not speed","# depth grows with n → prefer iteration:","total = 0","for i in range(1, n + 1): total += i"]},{keys:["dict get","keyerror","default","setdefault"],en:"d[k] raises KeyError; d.get(k, default) does not. Counting? use a Counter.",zh:"d[k] 缺键报 KeyError;d.get(k, 默认) 不报。计数用 Counter。",demo:["d.get(k) # → None if missing","d.get(k, 0) + 1 # count safely","d.setdefault(k, []).append(v) # group into lists","from collections import Counter, defaultdict","Counter(l).most_common(3) # top 3 by frequency"]},{keys:["divide","division","modulo","floor","divmod"],en:"/ is always float; // floors (toward -inf, watch negatives); % follows the divisor sign.",zh:"/ 一定是浮点;// 向下取整(负数会咬人);% 的符号跟除数。",demo:["7 / 2 # → 3.5 float, even for ints","7 // 2 # → 3 floor","-7 // 2 # → -4 NOT -3","-7 % 2 # → 1 sign follows divisor","divmod(7, 2) # → (3, 1)"]},{keys:["try","except","finally","raise"],en:"Catch the narrowest type you expect; finally always runs; bare except hides real bugs.",zh:"只抓你预期的最窄类型;finally 一定执行;裸 except 会藏真 bug。",demo:["try:"," x = int(s)","except ValueError:"," x = 0","finally:"," ... # always runs"]},{keys:["unpack","star","args","kwargs","swap"],en:"* spreads an iterable, ** spreads a dict; a, *rest = l splits head from tail.",zh:"* 展开可迭代,** 展开字典;a, *rest = l 拆头尾。",demo:["a, b = b, a # swap, no temp","a, *rest = [1, 2, 3] # a=1 rest=[2,3]","f(*l) # positional spread","f(**d) # keyword spread","x, y = map(int, input().split())"]},{keys:["enumerate","zip","index in loop"],en:"enumerate gives (index, item); zip walks lists in parallel and stops at the shortest.",zh:"enumerate 给 (下标, 元素);zip 并行遍历,以最短的为准。",demo:["for i, c in enumerate(s): ...","for i, c in enumerate(s, 1): ... # start at 1","for a, b in zip(xs, ys): ...","list(zip(*rows)) # transpose a grid"]},{keys:["string methods","split","join","strip","replace"],en:"Strings are immutable — every method returns a NEW string.",zh:"字符串不可变 —— 每个方法都返回新字符串。",demo:["s.split() # on any whitespace → list",'s.split(",") # on a comma','"-".join(parts) # list → string (parts must be str)',"s.strip() # trim both ends","s.replace(a, b) # returns new; s unchanged"]},{keys:["ternary","inline if","conditional expression"],en:"Value-position if: `a if cond else b` — one expression, always needs the else.",zh:"值位置的 if:a if 条件 else b —— 是表达式,else 不能省。",demo:["x = 1 if ok else -1",'print("yes" if n > 0 else "no")',"l = [f(x) if x else 0 for x in xs]"]},{keys:["set","dedup","union","intersection","in"],en:"set() dedups and makes `in` O(1) instead of O(n) — the single biggest easy speedup.",zh:"set() 去重,并让 in 从 O(n) 变 O(1) —— 最容易拿到的一次加速。",demo:["seen = set(); seen.add(x)","if x in seen: ... # O(1); on a list this is O(n)","a | b a & b a - b # union / intersect / difference","len(set(l)) # distinct count"]},{keys:["walrus",":=","assignment expression"],en:"Assign inside an expression — mostly for while-read loops.",zh:"在表达式里赋值 —— 主要用在 while 读输入。",demo:["while (line := sys.stdin.readline()):"," ...","if (m := len(l)) > 3: print(m)"]},{keys:["lambda","anonymous function"],en:"One-expression function, no return keyword. Mostly for key= / sort.",zh:"单表达式函数,不写 return。主要给 key= / 排序用。",demo:["key=lambda p: p[1]","key=lambda p: (-p[1], p[0]) # desc then asc","f = lambda x: x * 2"]},{keys:["range","loop n times","countdown"],en:"range(stop) / range(start, stop[, step]) — stop is EXCLUSIVE.",zh:"range(止) / range(起, 止[, 步]) —— 止是开区间。",demo:["range(5) # 0 1 2 3 4","range(1, 6) # 1..5","range(10, 0, -1) # 10 down to 1","range(0, 10, 2) # 0 2 4 6 8"]},{keys:["float","rounding","precision","isclose"],en:"Binary floats are inexact: 0.1+0.2 != 0.3. Compare with a tolerance, never ==.",zh:"二进制浮点不精确:0.1+0.2 != 0.3。比较要给容差,别用 ==。",demo:["0.1 + 0.2 == 0.3 # → False","abs(a - b) < 1e-9 # compare like this","round(2.675, 2) # → 2.67 (not 2.68)",'f"{x:.6f}" # print fixed decimals']},{keys:["counter","frequency","most common","tally"],en:'Counts everything in one call and ranks it — no loop, no dict setup. The fastest way to answer "which appears most".',zh:"一行统计全部并排序 —— 不用循环、不用先建 dict。回答「哪个出现最多」最快的办法。",demo:["from collections import Counter",'c = Counter("hello") # {"l":2,"h":1,"e":1,"o":1}',"c = Counter(l) # works on any iterable","c.most_common(3) # top 3 as (item, count) pairs","c.most_common(1)[0][0] # THE most common item",'c["z"] # → 0, never a KeyError']},{keys:["defaultdict","group by","adjacency","graph"],en:'A dict that creates the empty value for you — how you build a graph or group items without any "if key in" checks.',zh:"会自动建空值的 dict —— 建图或分组时不用再写「if key in」。",demo:["from collections import defaultdict","g = defaultdict(list)","g[a].append(b) # no setup needed","cnt = defaultdict(int)","cnt[k] += 1 # starts at 0","groups = defaultdict(list)","for w in words: groups[len(w)].append(w)"]},{keys:["stderr","debug print","debugging"],en:"Print debug lines to stderr — the judge only reads stdout, so your prints cannot cause a wrong answer.",zh:"调试信息打到 stderr —— 判题机只读 stdout,这样你的打印**不会**把答案judge成错。",demo:["import sys",'print("here:", x, file=sys.stderr) # safe to leave in',"print(answer) # stdout = the answer","# a stray print() to stdout is a classic WA cause"]},{keys:["assert","sanity check","test"],en:"Cheap self-test while writing: it raises the moment an assumption breaks, right where it broke.",zh:"写题时最便宜的自测:假设一破就在破的那一行抛出。",demo:["assert len(a) == n",'assert 1 <= x <= 1000, f"x out of range: {x}"',"# sample check:",'assert solve("5") == "24"',"# python -O disables asserts; judges do not use -O"]},{keys:["timing","perf_counter","how slow","tle"],en:"Measure before you optimise. If a local run of the max input is over ~1s, expect TLE.",zh:"先量再优化。最大输入本地跑超过约 1 秒,就要预期 TLE。",demo:["import time","t = time.perf_counter()","...","print(time.perf_counter() - t, file=sys.stderr)","# rule of thumb: CPython ≈ 10^7 simple ops per second"]},{keys:["test cases","t cases","multiple inputs"],en:"The standard shape when the first line is how many cases follow.",zh:"第一行给「有几组数据」时的标准写法。",demo:["import sys","data = sys.stdin.read().split()","i = 0","t = int(data[i]); i += 1","for _ in range(t):"," n = int(data[i]); i += 1"," ... # print one answer per case"]},{keys:["read grid","read matrix","2d input"],en:"Read R rows of a grid, as characters or as numbers.",zh:"读入 R 行网格 —— 字符版和数字版。",demo:["R, C = map(int, input().split())","g = [input() for _ in range(R)] # chars: g[r][c]","g = [list(input()) for _ in range(R)] # mutable chars","g = [list(map(int, input().split()))"," for _ in range(R)] # numbers"]},{keys:["ord","chr","char to int","letter index"],en:'Letters ↔ numbers. ord(c) - ord("a") turns a lowercase letter into 0..25.',zh:'字母↔数字。ord(c) - ord("a") 把小写字母变成 0..25。',demo:['ord("a") # → 97','chr(97) # → "a"','ord(c) - ord("a") # → 0..25 bucket index',"cnt = [0] * 26",'for c in s: cnt[ord(c) - ord("a")] += 1']},{keys:["isdigit","isalpha","char type","validate"],en:"Character/string classification — all return True/False and are true for the WHOLE string.",zh:"字符/字符串分类 —— 返回布尔,且要求**整串**都满足。",demo:['"42".isdigit() # → True','"4a".isdigit() # → False (whole string)',"c.isalpha() c.isalnum() c.isupper() c.islower()","s.lower() s.upper()",'if s.lstrip("-").isdigit(): n = int(s) # signed check']},{keys:["pow","modulo power","mod","big numbers"],en:"pow(a, b, m) is modular exponentiation — fast and never overflows. Python ints have no size limit anyway.",zh:"pow(a, b, m) 是模幂 —— 快且不溢出。Python 整数本身也没有位数上限。",demo:["pow(2, 100) # exact, arbitrary size","pow(2, 1000000, 10**9+7) # instant, modular","MOD = 10**9 + 7","ans = ans * x % MOD # keep it reduced every step","pow(a, MOD-2, MOD) # modular inverse (MOD prime)"]},{keys:["prefix sum","range sum","cumulative"],en:'Build once in O(n), then any range sum is O(1). The standard answer to "sum of a[i..j], many queries".',zh:"O(n) 建一次,之后任意区间和都是 O(1)。「多次查询 a[i..j] 的和」的标准解。",demo:["p = [0] * (n + 1)","for i in range(n): p[i+1] = p[i] + a[i]","p[j+1] - p[i] # sum of a[i..j] O(1)","","from itertools import accumulate","p = list(accumulate(a, initial=0)) # same thing"]},{keys:["dfs","stack","iterative dfs"],en:"DFS with an explicit stack — no recursion, so no RecursionError however deep the graph.",zh:"用显式栈做 DFS —— 不递归,所以图再深也不会 RecursionError。",demo:["seen = set([start])","st = [start]","while st:"," u = st.pop()"," for v in g[u]:"," if v not in seen:"," seen.add(v); st.append(v)"]},{keys:["union find","dsu","connected"],en:'Disjoint-set union: near-O(1) "are these connected?" and "join these two".',zh:"并查集:近 O(1) 回答「这两个连通吗」和「把这两个合并」。",demo:["p = list(range(n))","def find(x):"," while p[x] != x:"," p[x] = p[p[x]]; x = p[x] # path halving"," return x","def union(a, b): p[find(a)] = find(b)","find(a) == find(b) # same component?"]},{keys:["readline","strip","trailing newline"],en:"sys.stdin.readline is faster than input() but KEEPS the newline — strip it or int() will still work but string compares will not.",zh:"sys.stdin.readline 比 input() 快,但**保留换行** —— 要 strip,否则字符串比较会失败(int() 仍能用)。",demo:["import sys","input = sys.stdin.readline # rebind once, then use input()","s = input().strip() # strip for STRINGS",'n = int(input()) # int() tolerates "\\n"','# forgetting .strip() breaks s == "YES" silently']},{keys:["flush","output speed","interactive"],en:"Many prints are slow — build one string and print it once. Interactive problems need flush=True.",zh:"大量 print 很慢 —— 攒成一个字符串一次打。交互题必须 flush=True。",demo:["out = []","for x in answers: out.append(str(x))",'print("\\n".join(out)) # ONE write — much faster',"","print(guess, flush=True) # interactive problems only"]},{keys:["dedup","unique","keep order"],en:"set() dedups but loses order; dict.fromkeys dedups and KEEPS first-seen order.",zh:"set() 去重但丢顺序;dict.fromkeys 去重并**保留首次出现的顺序**。",demo:["list(set(l)) # unique, order LOST","list(dict.fromkeys(l)) # unique, order KEPT","sorted(set(l)) # unique + sorted","len(l) != len(set(l)) # are there duplicates?"]},{keys:["transpose","rotate","matrix ops"],en:"Transpose and 90-degree rotation in one line each — zip(*g) is the trick.",zh:"转置与 90 度旋转各一行 —— 关键是 zip(*g)。",demo:["list(zip(*g)) # transpose (rows of tuples)","[list(r) for r in zip(*g)] # transpose, mutable","[list(r) for r in zip(*g[::-1])] # rotate 90° clockwise","[list(r)[::-1] for r in zip(*g)] # rotate 90° anticlockwise"]},{keys:["scope","global","nonlocal","unboundlocal"],en:"Assigning to a name inside a function makes it LOCAL for the whole function — that is the UnboundLocalError.",zh:"在函数里给某个名字赋值,它在整个函数内就是**局部**的 —— 这就是 UnboundLocalError 的来源。",demo:["total = 0","def f():"," total += 1 # UnboundLocalError!","def g():"," global total"," total += 1 # ok","# reading without assigning never needs global"]},{keys:["truthy","falsy","empty check","none"],en:'Empty containers, 0 and "" are falsy. Test None with `is None`, not ==.',zh:'空容器、0、"" 都是假。判 None 用 is None,不用 ==。',demo:["if not l: ... # empty list/str/dict","if x is None: ... # None specifically","if l: ... # non-empty","# careful: 0 and [] are both falsy but not equal"]}];export const SYNTAX_INDEX=SYNTAX_TABLE.map(e=>e.keys[0]);const t={list:["Types","类型"],dict:["Types","类型"],tuple:["Types","类型"],set:["Types","类型"],"string methods":["Types","类型"],append:["Add / remove","增删改"],remove:["Add / remove","增删改"],pop:["Add / remove","增删改"],del:["Add / remove","增删改"],slice:["Add / remove","增删改"],copy:["Add / remove","增删改"],dedup:["Add / remove","增删改"],counter:["Data structures","数据结构"],defaultdict:["Data structures","数据结构"],deque:["Data structures","数据结构"],heapq:["Data structures","数据结构"],"union find":["Data structures","数据结构"],dfs:["Data structures","数据结构"],comprehension:["Loops","循环与推导"],enumerate:["Loops","循环与推导"],range:["Loops","循环与推导"],break:["Loops","循环与推导"],any:["Loops","循环与推导"],map:["Loops","循环与推导"],ternary:["Loops","循环与推导"],lambda:["Loops","循环与推导"],walrus:["Loops","循环与推导"],sort:["Order / search","排序与查找"],min:["Order / search","排序与查找"],bisect:["Order / search","排序与查找"],reverse:["Order / search","排序与查找"],stdin:["Input / output","输入输出"],print:["Input / output","输入输出"],readline:["Input / output","输入输出"],flush:["Input / output","输入输出"],"read grid":["Input / output","输入输出"],"test cases":["Input / output","输入输出"],fstring:["Input / output","输入输出"],join:["Input / output","输入输出"],divide:["Numbers / math","数学"],float:["Numbers / math","数学"],math:["Numbers / math","数学"],pow:["Numbers / math","数学"],"prefix sum":["Numbers / math","数学"],ord:["Characters","字符"],isdigit:["Characters","字符"],grid:["Grid / matrix","网格与矩阵"],"2d list":["Grid / matrix","网格与矩阵"],transpose:["Grid / matrix","网格与矩阵"],itertools:["Brute force","暴力枚举"],cache:["Speed / traps","性能与陷阱"],recursionerror:["Speed / traps","性能与陷阱"],timing:["Speed / traps","性能与陷阱"],scope:["Speed / traps","性能与陷阱"],truthy:["Speed / traps","性能与陷阱"],"dict get":["Speed / traps","性能与陷阱"],stderr:["Debug / test","调试与自测"],assert:["Debug / test","调试与自测"],try:["Debug / test","调试与自测"],unpack:["Misc","其他"]},s=["Types","Add / remove","Data structures","Loops","Order / search","Input / output","Numbers / math","Characters","Grid / matrix","Brute force","Speed / traps","Debug / test","Misc"];export function renderIndex(e){const n=new Map;for(const o of SYNTAX_TABLE){const[r,i]=t[o.keys[0]]??["Misc","其他"],a=e?i:r,l=`${s.indexOf(r)}\0${a}`;n.has(l)||n.set(l,[]),n.get(l)?.push(o)}const o=[...n.keys()].sort((e,t)=>{const s=Number.parseInt(e.split("\0")[0],10),n=Number.parseInt(t.split("\0")[0],10);return(s<0?99:s)-(n<0?99:n)});console.log(),console.log(chalk.bold.white(e?` /syntax 全部关键词 — ${SYNTAX_TABLE.length} 条`:` /syntax keyword index — ${SYNTAX_TABLE.length} entries`)),console.log(chalk.gray(e?" 左边是主词,右边任一别名也能敲。方法名(如 list.pop)直接查本机文档。":" Type the left word, or any alias on the right. Any name (list.pop) hits your own docs."));for(const e of o){const t=e.split("\0")[1];console.log(),console.log(chalk.bold.cyan(` ── ${t} ──`));for(const t of n.get(e)??[]){const e=t.keys.slice(1).join(" · ");console.log(chalk.bold.green(` ${t.keys[0].padEnd(15)}`)+chalk.gray(e))}}console.log()}function n(e){return o(e).toLowerCase()}function o(e){return e.trim().replace(/^\/+/,"").replace(/[?。?]+$/,"").replace(/\s+/g," ")}export function lookupRanked(e){const t=n(e);if(!t)return[];const s=SYNTAX_TABLE.filter(e=>e.keys.some(e=>e===t)),o=t.split(" ").filter(Boolean),r=[];for(const e of SYNTAX_TABLE){if(s.includes(e))continue;let n=0;for(const s of e.keys)s.includes(" ")?t.includes(s)&&(n+=2*s.length):o.includes(s)&&(n+=s.length);n>0&&r.push({e:e,score:n})}return r.sort((e,t)=>t.score-e.score),[...s,...r.map(e=>e.e)]}export function nearKeys(e,t=6){const s=n(e).split(" ").filter(e=>e.length>=3),o=SYNTAX_INDEX.filter(e=>s.some(t=>e.includes(t)||t.includes(e)));return(o.length?o:SYNTAX_INDEX).slice(0,t)}export function lookupPydoc(t,s,n=14){const r=o(s);return r.length>60||!/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,2}$/.test(r)?Promise.resolve(null):new Promise(s=>{let o="",i=!1;const a=e=>{i||(i=!0,s(e))};let l;try{l=e(t,["-c","\nimport io, sys, contextlib, pydoc\nq = sys.argv[1] if len(sys.argv) > 1 else ''\ncands = [q] + ([] if '.' in q else ['list.' + q, 'str.' + q, 'dict.' + q, 'set.' + q])\nfor c in cands:\n try:\n txt = pydoc.render_doc(c, renderer=pydoc.plaintext)\n except Exception:\n continue\n print('OBJ ' + c); print(txt); sys.exit(0)\nbuf = io.StringIO()\ntry:\n with contextlib.redirect_stdout(buf):\n pydoc.Helper(output=buf).help(q.upper())\n out = buf.getvalue()\nexcept Exception:\n out = ''\nif out.strip() and 'no python documentation' not in out.lower():\n print('TOPIC ' + q.upper()); print(out); sys.exit(0)\nsys.exit(1)\n",r],{stdio:["ignore","pipe","ignore"]})}catch{return void a(null)}const d=setTimeout(()=>{try{l.kill("SIGKILL")}catch{}a(null)},4e3);l.stdout?.on("data",e=>{o+=String(e)}),l.on("error",()=>{clearTimeout(d),a(null)}),l.on("close",e=>{if(clearTimeout(d),0!==e||!o.trim())return void a(null);const t=o.split("\n"),s=(t[0]??"").replace(/^(OBJ|TOPIC)\s+/,"").trim(),r=/^\s*\|?\s*(Method resolution order|Methods? (defined here|inherited)|Data (descriptors|and other attributes)|Static methods|Class methods|Readonly properties|-{3,}|_{2})/,i=[];for(const e of t.slice(1)){if(/^Python Library Documentation/.test(e))continue;if(r.test(e))break;const t=e.replace(/^\s*\|\s?/," ");(t.trim()||i.length&&i[i.length-1].trim())&&i.push(t)}for(;i.length&&!i[0].trim();)i.shift();for(;i.length&&!i[i.length-1].trim();)i.pop();a({title:s,lines:i.slice(0,n)})})})}export function renderSyntax(e,t){console.log(),console.log(chalk.bold.white(` ${e.keys[0]}`)+chalk.gray(t?" (语法速查)":" (syntax lookup)")),console.log(chalk.gray(` ${t?e.zh:e.en}`)),console.log();for(const t of e.demo)console.log(t.trim()?chalk.cyan(` ${t}`):"");console.log()}export function renderPydoc(e,t){console.log(),console.log(chalk.bold.white(` ${e.title}`)+chalk.gray(t?" (你本机 Python 的官方文档)":" (your own Python's official doc)")),console.log();for(const t of e.lines)console.log(t.trim()?chalk.white(` ${t}`):"");console.log()}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icoa-cli",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.459",
|
|
4
4
|
"description": "ICOA CLI — The world's first CLI-native cyber & AI security olympiad terminal: AI4CTF (Day 1), CTF4AI (Day 2), VLA4CTF (Pioneer Round — embodied AI)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
export declare function ai4ioaiPromptLabel(): string;
|
|
2
|
-
/** The contest cap, re-exported so callers can trim their context to fit
|
|
3
|
-
* instead of getting a refusal after the fact. */
|
|
4
|
-
export declare const AI_MAX_INPUT_CHARS = 2000;
|
|
5
|
-
/**
|
|
6
|
-
* One-shot ask — no chat REPL, no shared history, same model and same contest
|
|
7
|
-
* caps. The notebook's cell-level `ai` runs through here: single-turn is not a
|
|
8
|
-
* limitation to work around, it IS the contest shape (2000 chars in, 1000
|
|
9
|
-
* tokens out), so a student who learns to compress here is training for the day.
|
|
10
|
-
*/
|
|
11
|
-
export declare function askIoaiOneShot(userText: string): Promise<{
|
|
12
|
-
ok: boolean;
|
|
13
|
-
text: string;
|
|
14
|
-
}>;
|
|
15
|
-
export declare function startAi4ioaiChat(): Promise<boolean>;
|
|
16
|
-
export declare function handleAi4ioaiMessage(input: string): Promise<'continue' | 'exit'>;
|
|
17
|
-
/**
|
|
18
|
-
* Standalone AI4IOAI session — entered by typing `ai4ioai` at the boot Learn
|
|
19
|
-
* token prompt (repl.ts picker), so students reach it WITHOUT first loading a
|
|
20
|
-
* curriculum. (The in-learn `ai4ioai` command still works too.) Owns its own
|
|
21
|
-
* readline loop; resolves when the user exits, so the picker can
|
|
22
|
-
* returnToMainMenu() afterwards.
|
|
23
|
-
*
|
|
24
|
-
* BUG-008-safe: reuses the main readline via getMainRl() when one exists
|
|
25
|
-
* (listener-swap + native-prompt-swap), else creates its own on process.stdin.
|
|
26
|
-
* At the boot picker, getMainRl() is null (setMainRl runs later), so this takes
|
|
27
|
-
* the own-rl branch.
|
|
28
|
-
*/
|
|
29
|
-
export declare function runAi4ioaiStandalone(): Promise<void>;
|