icoa-cli 2.19.464 → 2.19.465

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as 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{JudgeWaitLine as i}from"../lib/judge-wait.js";import{ai4ioaiPromptLabel as c,handleAi4ioaiMessage as d,startAi4ioaiChat as g}from"./ai4ioai.js";import{existsSync as u,mkdirSync as y,readdirSync as h,readFileSync as m,renameSync as p,statSync as f,writeFileSync as b}from"node:fs";import{emptyDynamics as w,foldEditSession as $,isEmpty as k,noteRun as v}from"../lib/arena-edit-dynamics.js";import{dirname as A,join as C}from"node:path";import{fileURLToPath as _}from"node:url";import{loadCurriculumById as T,validateEAToken as x,syncProgress as I,syncCardFeedback as E,fetchCardFaqs as S}from"../lib/learn-curricula.js";import{parseReplyCommand as P,renderReplyLines as q,replyPushLine as j}from"../lib/learn-replies.js";import{ensureFullTable as M,lookupPydoc as L,lookupRanked as N,nearKeys as R,renderIndex as W,renderPydoc as O,renderSyntax as D,tableSize as Y}from"../lib/py-syntax.js";import{normalizeTokenBody as U}from"../lib/token-format.js";import{fetchMyScores as F,recallCoach as z,setNickname as H,streamLearnTutor as B,submitPqs as Z,viewPqsTop as K,viewHonors as J}from"../lib/learn-ai.js";import{contestReset as Q,contestStart as V,contestSubmit as X,linkByIndex as G,linkSuggest as ee,linkToken as oe,fetchGate as ne,timeLeft as te}from"../lib/learn-contest.js";import{getConfig as re,saveConfig as le}from"../lib/config.js";import{isNativeWindows as se,isWindowsBuildInWslShell as ae,whichBinary as ie}from"../lib/platform.js";import{loadLearnState as ce,saveLearnState as de,newLearnState as ge,activateSession as ue,updateStreak as ye,markCardComplete as he,recordMCQ as me,recordCheck as pe,markPracticalComplete as fe,addAchievement as be}from"../lib/learn-state.js";import{renderWelcome as we,renderKnowledgeCard as $e,renderMCQCard as ke,renderMCQFeedback as ve,renderPracticalCard as Ae,renderPracticalSuccess as Ce,renderSimDemoCard as _e,renderMilestone as Te,renderArenaTaskCard as xe,renderComingSoonCard as Ie,renderStatus as Ee,renderPhaseComplete as Se,renderCurriculumComplete as Pe,setLearnAiEnabled as qe,setLearnFaqs as je,setLearnHonorRanks as Me,setLearnPqsViewCards as Le,setLearnReplies as Ne,setLearnWidth as Re,resolveLearnWidth as We,learnWidthCap as Oe,learnW as De,renderHonorWall as Ye,wrapMixed as Ue}from"../lib/learn-render.js";import{printError as Fe}from"../lib/ui.js";const ze=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(He){He.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async He=>{He?.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(),He="LEARNDEMO01");let Be=He.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Be)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Ze=null;const Ke=/^[A-Z0-9]+DEMO01$/i.test(Be),Je=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Be);let Qe=!1,Ve=!1,Xe=[],Ge=-1,eo=Promise.resolve([]);if(Ke)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),eo=S(Be),Ze=await T(Be,Be,!0);else if(Je){console.log(),console.log(chalk.gray(" Validating token..."));let e=await x(Be);if(!e.ok){const o=U(Be);if(o!==Be){const n=await x(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Be} → ${o}`)),e=n,Be=o)}}if(!e.ok)return Fe(`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 🐼"):"")),Qe=!0===e.aiEnabled,Ve=!0===e.gated,Xe=e.replies??[],eo=S(Be),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Ze=await T(e.curriculumId||"LEARNDEMO01",Be,!0),!Ze)return Fe(`Could not open a learn curriculum for token '${Be}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Be}`)+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 ${Be}`)+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(!Ze){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Fe(`Could not reach the learn server to open ${Be}.`),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 ${Be}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Fe(`Unknown learn token: ${Be}`),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 oo=ce(),no=!1;try{if(oo&&oo.token===Be)ye(oo);else{const e=ue(Be);e?(oo=e,oo.totalCards=Ze.totalCards,ye(oo)):(oo=ge(Be,Ze.id,Ze.totalCards),no=!0)}de(oo),we(Ze,oo,no)}catch{return Fe("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 ${Be}`)+chalk.gray(".")),void console.log()}const to=a(),ro=null!==to,lo=ro?to.listeners("line").slice():[];ro&&to.removeAllListeners("line");const so=ro?to:o({input:process.stdin,output:process.stdout,terminal:!0}),ao=ro?so.prompt:null;ro&&(so.prompt=e.prototype.prompt);const io=()=>{ro&&ao&&(so.prompt=ao)},co=()=>{so.setPrompt(To?chalk.bold.green(`icoa ${c()}> `):ko?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(wo?"icoa learn ai> ":"icoa learn> ")),so.prompt()};let go=null,uo=null,yo=null,ho=null,mo=[],po=!1,fo=null;const bo=()=>{fo&&clearTimeout(fo),fo=null,mo=[],po=!1,ho=null};let wo=!1,$o=!1,ko=!1,vo=null,Ao=!1,Co=0,_o=!1,To=!1;const xo=new Map,Io=()=>{let e=xo.get(oo.currentCard);return e||(e=[],xo.set(oo.currentCard,e)),e};let Eo=!1;const So=new Set;let Po=!1,qo=0;const jo=()=>(re().language||"en").toLowerCase().startsWith("zh");qe(Qe),Re(We(re())),Le(So);const Mo=new Map;Me(Mo),Ne(Xe);const Lo=await eo;je(Lo);const No=[];let Ro=null;const Wo=new Promise(e=>{Ro=e}),Oo=()=>{const e=Ro;Ro=null,e?.()},Do="1"===process.env.ICOA_LEARN_EMBEDDED,Yo=e=>Ze.cards.find(o=>o.number===e);let Uo=null,Fo=null;const zo=new Map,Ho=!Be.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Be),Bo=async()=>{if(!Ho)return;const e=await ne(Be);e.ok&&e.data&&(Uo=e.data)},Zo=e=>{const o=Ze.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Ko=e=>{if(!Ve||!Uo)return null;const o=Zo(e);if(o<=Uo.unlocked_through_phase)return null;const n=Uo.phases.find(e=>e.phase===Uo.unlocked_through_phase),t=[chalk.yellow(jo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${Uo.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${Uo.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(jo()?` ⚔ 练习赛 ${Uo.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${Uo.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(jo()?` ⚖ 判分赛: 最好 ${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(jo()?"、":", "),r=e.length>8?jo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:jo()?" 张":"";t.push(chalk.gray(jo()?` ✓ 逐卡自测: ${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(jo()?` ⭐ 提问研究: ${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")},Jo=async e=>Ve?null===Ko(e)?null:(await Bo(),Ko(e)):null;Ho&&await Bo();const Qo=async e=>{const o=Ze.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Ze.modules.find(e=>e.number===o.number+1);let t;if(Qe){const e=await F({token:Be,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}Ho&&await Bo();const r=Uo?.phases.find(e=>e.phase===o.number);return Se(Ze,oo,o,n,t,r),!0},Vo=()=>{Po=!0,console.log(chalk.gray(jo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Xo=()=>{vo=null;const e=Yo(oo.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":$e(e,Ze),e.check?(yo=e.number,qo=Date.now()):(he(oo,e.number),de(oo));break;case"mcq":ke(e,Ze),go=e.number;break;case"practical":Ae(e,Ze),uo=e.number;break;case"sim_demo":_e(e,Ze),he(oo,e.number),de(oo);break;case"milestone":Te(e,Ze),be(oo,e.badge),he(oo,e.number),de(oo);break;case"arena_task":xe(e,Ze),he(oo,e.number),de(oo);break;case"coming_soon":Ie(e,Ze),he(oo,e.number),de(oo)}Go(e.number)},Go=e=>{if(!Ho||!Uo)return;const o=Ze.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=Uo.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?jo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(De());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${jo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(jo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(jo()?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(jo()?`${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(jo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(jo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(jo()?"✍ 第一次用 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(jo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(jo()?"最好":"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(jo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(jo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(jo()?" 继续学习":" keep going"):chalk.gray(jo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(jo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},en=()=>{Be.endsWith("DEMO01")?console.log(chalk.yellow(jo()?" 🐼 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(jo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(jo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},on=async(e,o)=>{if(Qe){$o=!0;try{console.log(),console.log(chalk.gray("deep"===o?jo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":jo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await B({token:Be,cardNumber:oo.currentCard,question:e,mode:o,history:Io().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(jo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Io().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(` (${jo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(jo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==yo&&console.log(chalk.gray(jo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{$o=!1}}else en()},nn=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],tn=async()=>{ko&&Fo?yn?mn(yn):dn():vo?await rn():Xo()},rn=async()=>{$o=!0;try{console.log();const e=await J({token:Be,curriculumId:Ze.id,cardNumber:oo.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(jo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(jo()?` 🏆 本卡实时 Top-3 — 第 ${oo.currentCard} 张`:` 🏆 Live top-3 — card ${oo.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(jo()?" (你)":" (you)"):""))}else console.log(chalk.gray(jo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Mo.set(oo.currentCard,e.mine.rank),console.log(chalk.white(jo()?" 你: ":" You: ")+chalk.bold.yellow(jo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(jo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Qe&&console.log(chalk.gray(jo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ye({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(jo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(jo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(jo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),vo="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(jo()?" 返回卡片":" returns to the card")),console.log()}finally{$o=!1}},ln=e=>jo()&&e.title_zh||e.title,sn=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of Ue(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},an=e=>{console.log(),console.log(chalk.bold.green(jo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(jo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},cn=e=>Fo.data.solved.includes(e.id)?"✅":Fo.data.carried?.includes(e.id)?"✅↗":Fo.tried.has(e.id)?"❌":"⬜",dn=()=>{const e=Fo.data,o=te(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(jo()?` · 第 ${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(jo()?" ⏱ 已超时 — 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(jo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(jo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(jo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(jo()?" 带过来,不必重做":" 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(jo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(jo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(jo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(jo()?` 满血重开本组(${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)} `)+cn(e)+chalk.white(` ${ln(e)}`))}),console.log(),gn()},gn=()=>{console.log(chalk.gray(jo()?" /read <n> 读题 · /edit <n> 写码(vi) · /run <n> 样例自测 · /debug <n> 自由调试 · /submit <n> 判分":" /read <n> statement · /edit <n> code (vi) · /run <n> sample check · /debug <n> free run · /submit <n> judge")),console.log(chalk.gray(" ")+chalk.bold.green(jo()?"/syntax <词>":"/syntax <word>")+chalk.gray(jo()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(jo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(jo()?" 返回课程":" returns to the lesson")),console.log()},un=e=>{const o=parseInt(e,10),n=Fo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(jo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let yn=null,hn=!1;const mn=e=>{const o=un(e);if(!o)return;const{p:n,n:t}=o;yn=String(t),console.log(),console.log(chalk.bold.white(` ${cn(n)} ${ln(n)}`)),console.log();for(const e of(e=>jo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of Ue(e,De()+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(jo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(jo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(0===(n.samples??[]).length&&(console.log(),console.log(chalk.gray(jo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),n.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(jo()?"本题推荐:":"Recommended here: "))+chalk.bold.white(n.toolkit.join(", ")));const e=jo()&&n.toolkit_note_zh||n.toolkit_note;if(e)for(const o of Ue(e,De()))console.log(chalk.gray(` ${o}`))}console.log(),console.log(chalk.white(jo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(jo()?"写码(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(jo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(jo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(jo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray(jo()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(jo()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((jo()," ↩ "))+chalk.bold.green("back")+chalk.gray(jo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(jo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((jo()," / "))+chalk.bold.green("wide")+chalk.gray(jo()?" 换语言/宽度":" language / width")),console.log()},pn=async(e,o)=>await new Promise(n=>{const t=process.stdin,s=!!t.isTTY&&!!t.isRaw;if(so.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const a=r(e,o,{stdio:"inherit",cwd:Fo.dir}),i=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&s)try{t.setRawMode(!0)}catch{}l(),so.resume(),n(e)};a.on("close",()=>i(null)),a.on("error",e=>i(e))}),fn=()=>{console.log(chalk.yellow(jo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(jo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(jo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(jo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},bn=new Map,wn=async e=>{const o=e.trim().toLowerCase(),l=ko&&o.startsWith("/")?o.slice(1):o;if($o)return;if(null!==ho){if(mo.push(e.replace(/\s+$/,"")),fo&&clearTimeout(fo),fo=null,po){const e=mo[mo.length-1]??"";return"/cancel"===e.trim()?(bo(),console.log(chalk.gray(jo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void co()):""!==e.trim()?void co():(mo.pop(),void await a())}return void(fo=setTimeout(()=>{if(fo=null,mo.length>1){po=!0;const e=mo.length;return console.log(chalk.cyan(jo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(jo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void co()}a()},140))}async function a(){const e=mo.join("\n").replace(/^\s+|\s+$/g,""),o=ho??oo.currentCard,n=mo.length;if(bo(),""===e)console.log(chalk.gray(jo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(jo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(jo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(jo()?" 即可执行。":" again to run it."));else{const t=qo>0?Date.now()-qo:void 0;if(await E(Be,{curriculum_id:Ze.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const t=n>1?jo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(jo()?` ✓ 已收到${t},谢谢帮助完善这张卡。`:` ✓ Thanks ${t}— your report was recorded.`)),console.log(chalk.gray(jo()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),Xe=[...Xe,{id:Ge--,curriculumId:Ze.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Ne(Xe)}else console.log(chalk.yellow(jo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),co()}if(Ao){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Ao=!1,console.log(),console.log(chalk.yellow(jo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(jo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(jo()?" 即可执行该命令。":" again to run it.")),console.log(),void co();if(!o)return Ao=!1,console.log(chalk.gray(jo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void co();const n=await H({token:Be,nickname:o});if(n.ok)Ao=!1,console.log(chalk.bold.green(jo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(jo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Co+=1;const e="taken"===n.code?jo()?"已被占用":"already taken":"bad_charset"===n.code?jo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?jo()?"未通过审核":"did not pass review":n.message||"error";if(!(Co>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(jo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void co();Ao=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(jo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void co()}if(Eo){Eo=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{$o=!0;try{console.log(),console.log(chalk.gray(jo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await Z({token:Be,cardNumber:oo.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(jo()?"评审暂不可用。":"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(jo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(jo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(jo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(jo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(jo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(jo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=jo()?` 本卡排名 #${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(jo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(jo()?` 第 ${e.submissionIndex??"?"} / 2 次提交 · 剩余 ${e.submissionsLeft??0} 次(可先追加 /ai 对话再交)`:` Attempt ${e.submissionIndex??"?"} of 2 · ${e.submissionsLeft??0} left (extend the /ai conversation before your next one)`)),e.feedback){console.log();for(const o of nn(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(jo()?" 改进提问: ":" 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(` (${jo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?So.add(oo.currentCard):So.delete(oo.currentCard),"number"==typeof e.rank&&Mo.set(oo.currentCard,e.rank);const o=await J({token:Be,curriculumId:Ze.id,cardNumber:oo.currentCard});o.ok&&o.totals&&o.chapters&&(Ye({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Ke&&(Ao=!0,Co=0,console.log(chalk.bold.yellow(jo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(jo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(jo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{$o=!1}})():(console.log(chalk.gray(jo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==yo&&(console.log(chalk.gray(jo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void co()}if(Po)return Po=!1,Xo(),void co();if(!o)return void co();if(To)return"exit"===await d(e.trim())&&(To=!1),void co();if(wo){if(["q","quit","exit","back","b","menu"].includes(o))return wo=!1,console.log(chalk.gray(jo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void co();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(jo()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?jo()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":jo()?`「${t}」是卡片命令,不是问题,没有送出去。`:`“${t}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(jo()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(jo()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void co()):(t&&(await on(t,n?"fast":"deep"),console.log(chalk.gray(jo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void co())}if(ko&&Fo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${Fo.phase}s${Fo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return ko=!1,console.log(chalk.gray(jo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Xo(),void co();if(/^\d+$/.test(o))return mn(o),void co();const t=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(t)return await(async e=>{const o=e.trim();if(await M()||hn||(hn=!0,console.log(chalk.gray(jo()?` (离线:只有 ${Y()} 条核心速查可用;联网后自动补全)`:` (offline: ${Y()} core entries available; the rest arrive when you have a connection)`))),!o)return void W(jo());const n=N(o);if(n.length){D(n[0],jo());const e=n.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(jo()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const t=await L("python3",o);t?O(t,jo()):(console.log(),console.log(chalk.yellow(jo()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(jo()?" 试试: ":" Try: ")+chalk.cyan(R(o).join(" · "))),console.log(chalk.gray(jo()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log())})(t[1]??""),void co();const r=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(r){const[,e,o]=r;return"list"===e?dn():o?"read"===e||"open"===e?mn(o):"edit"===e?await(async e=>{const o=un(e);if(!o)return;const n=C(Fo.dir,`sol-${o.n}.py`);if(se())return ae()?(console.log(chalk.yellow(jo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(jo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(jo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(jo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(jo()?" ← 不能是 /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(jo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(jo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(jo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(jo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(jo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(jo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(jo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(jo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!ie("vi"))return console.log(chalk.yellow(jo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(jo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(jo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return f(e).size}catch{return 0}},r=t(n),l=Date.now();await pn("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),zo.set(o.n,$(zo.get(o.n)??w(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(jo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(jo()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=un(e);if(!o)return;const{p:t,n:r}=o,l=C(Fo.dir,`sol-${r}.py`);if(!u(l))return void console.log(chalk.yellow(jo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));zo.set(r,v(zo.get(r)??w()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(jo()?` 本题无样例(设计如此)— 用 /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)fn();else if(o.killed)console.log(chalk.yellow(jo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(jo()?" ✗ 程序报错:":" ✗ 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(jo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(jo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(jo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(jo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(jo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(jo()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=un(e);if(!o)return;const n=C(Fo.dir,`sol-${o.n}.py`);if(!u(n))return void console.log(chalk.yellow(jo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(jo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 pn("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(jo()?" 回到竞技场。":" Back in the arena.")),console.log()):fn()})(o):"recall"===e&&await(async e=>{const o=un(e);if(!o)return;if(!Qe)return void en();const{p:n,n:t}=o,r=C(process.cwd(),"icoa-contest"),l=`${Ze.id}-phase${Fo.phase}-g${Fo.data.slot}-archived-`;let s=null;try{for(const e of h(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?C(r,s,`sol-${t}.py`):null;if(!a||!u(a))return void console.log(chalk.gray(jo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${Fo.phase}-${Fo.data.slot}-${t}`,d=Math.min(3,(bn.get(c)??0)+1);console.log(chalk.gray(jo()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await z({token:Be,phase:Fo.phase,slot:Fo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:d,lang:jo()?"zh":"en"});if(g.ok){bn.set(c,d),console.log();for(const e of Ue(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(jo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(jo()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(jo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(jo()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(jo()?" (花名册: /list)":" (roster: /list)")),void co()}if("contest"===o||"/contest"===o)return dn(),void co();const a="lang"===o||/^lang\s+\S+$/.test(o),i=ze.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(jo()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void co()}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(jo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void co()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(so.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{}so.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void co()}if("ai4ioai"===o||"/ai4ioai"===o)return await g()&&(To=!0),void co();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Qe)return en(),void co();_o||(_o=!0,console.log(),console.log(chalk.bold.cyan(jo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(jo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(jo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),jo()||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){wo=!0;const e=Yo(oo.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(jo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(jo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(jo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void co()}return await on(t,n?"fast":"deep"),void co()}if(!ko&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Qe)return en(),void co();const e=Yo(oo.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(jo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(jo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(jo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(jo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(jo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(jo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(jo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Eo=!0,void co()}const c=!ko&&"honors"===vo&&/^[1-3]$/.test(o);if(!ko&&vo&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(jo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(jo()?" ↩ back 回上一层":" ↩ back goes up one level")),void co();if(!ko&&(c||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Qe)return en(),void co();const e=/^\/?view ([1-3])$/.exec(o),n=c?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{$o=!0;try{console.log();const o=await K({token:Be,cardNumber:oo.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(jo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&So.delete(oo.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&So.add(oo.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(jo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${oo.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${oo.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(jo()?` (第 ${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(jo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=nn(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(jo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),vo="view",console.log(chalk.gray((jo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(jo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{$o=!1}})(n),void co()}if("/honors"===o||"honors"===o)return Ke?(console.log(),console.log(chalk.gray(jo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void co()):(await rn(),void co());if("menu"===o||"menu confirm"===o){if(No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,3e3))]),so.removeAllListeners("line"),io(),ro||!Do){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ro?so:void 0),Oo()}else so.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===vo)return await rn(),void co();if("honors"===vo)return vo=null,Xo(),void co();if(No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${oo.streakDays} day(s)`)),console.log(),ro){so.removeAllListeners("line"),io();for(const e of lo)so.on("line",e);so.prompt(),Oo()}else so.removeAllListeners("line"),so.close();return}if("status"===o)return Ee(Ze,oo),void co();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await T(Ze.id,Be,!0);return void(e?(Object.assign(Ze,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Xo()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),co()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(re().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void co();const n=Ze.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 le({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),yo=null,go=null,uo=null,bo(),Po=!1,Eo=!1,await tn(),void co()}if(ze.has(o)){const e=ze.get(o),n=We(re()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return jo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((jo()?"normal"===e?" 已是标准 64 列。":De()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${De()} 列,上限 ${Oe(e)})。`:"normal"===e?" Already at the standard 64 cols. ":De()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${De()} cols, cap ${Oe(e)}). `)+t(e))),void co()):(le({learnWidth:e,learnWide:"normal"!==e}),Re(e),"normal"!==e&&De()<=64?(console.log(chalk.yellow(jo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((jo()?` 设置已记住(${e},上限 ${Oe(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Oe(e)} cols) and applies once you widen the window. `)+t(e))),void co()):(console.log(chalk.green(" ✓ ")+chalk.gray((jo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${De()} 列,上限 ${Oe(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${De()} cols, cap ${Oe(e)}). `)+t(e))),yo=null,go=null,uo=null,bo(),Po=!1,Eo=!1,await tn(),void co()))}if("sim"===o){const e=Yo(oo.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=A(_(import.meta.url)),o=[C(e,"..","..","panda","mujoco-launcher.py"),C(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(u(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 co()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void co())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=oo.currentCard,n=oo.bookmarks.includes(e),t="bookmark"!==o;return t?oo.bookmarks=oo.bookmarks.filter(o=>o!==e):n||oo.bookmarks.push(e),de(oo),t?console.log(n?chalk.gray(jo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(jo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(jo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(jo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void co()}const x=P(o);if(x){const e="current"===x.target?oo.currentCard:x.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>Ze.cards.length))return console.log(chalk.yellow(jo()?` 本课共 ${Ze.cards.length} 张,请输 r 1–${Ze.cards.length} 或 r all。`:` This course has ${Ze.cards.length} cards. Try r 1–${Ze.cards.length} or r all.`)),console.log(),void co();for(const o of q(Xe,Lo,e,jo(),De()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?Xe:Xe.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(Xe=Xe.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Ne(Xe),No.push(I(Be,{card_number:oo.currentCard,event_type:"viewed"},o).catch(()=>{}))),void co()}if("e"===o)return ho=oo.currentCard,console.log(chalk.gray(jo()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(jo()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void co();if("back"===o||"b"===o)return"view"===vo?(await rn(),void co()):"honors"===vo?(vo=null,Xo(),void co()):(oo.currentCard>1&&(oo.currentCard-=1),go=null,uo=null,yo=null,de(oo),Xo(),void co());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Ho)return console.log(chalk.yellow(jo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void co();if(!e){const e=await ee(Be),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(jo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(jo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(jo()?` 这台电脑上有 ${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(jo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(jo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(jo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(jo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(jo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(jo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(jo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void co()}if(/^\d{1,2}$/.test(e)){const o=await G(Be,Number(e));return o.ok&&o.data?(an(o.data),await Bo(),void co()):(console.log(chalk.red(` ✗ ${o.message||(jo()?"关联失败":"Link failed")}`)),void co())}const n=await oe(Be,e);return n.ok&&n.data?(an(n.data),await Bo(),void co()):(console.log(chalk.red(` ✗ ${n.message||(jo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(jo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void co())}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(!Ho)return console.log(chalk.yellow(jo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void co();const e=Zo(oo.currentCard);if("contest reset"===o){const o=await Q(Be,e);if(o.ok){console.log(chalk.yellow(jo()?` 已放弃当前计时(阶段 ${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",`${Ze.id}-phase${e}-g${n}`);if(u(t))try{p(t,`${t}-archived-${o}`),console.log(chalk.gray(jo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(jo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(jo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),Fo=null,ko=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void co()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(jo()?" 连接判分赛…":" Contacting contest server…"));const t=await V(Be,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(jo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void co();const r=t.data,l=C(process.cwd(),"icoa-contest",`${Ze.id}-phase${e}-g${r.slot}`);y(l,{recursive:!0});const s=Fo&&Fo.phase===e&&Fo.data.slot===r.slot?Fo.tried:new Set;Fo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.samples??[])[0];l&&b(C(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=C(o,`sol-${r}.py`);if(u(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${n.title} ══`,"#",...sn(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}`)}if(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","#","# ── toolkit ──",...e.toolkit_available?.length?[`# Available on the judge: ${e.toolkit_available.join(", ")}`]:["# The judge runs the Python standard library only."],...e.toolkit_available?.includes("chepy")?["# from chepy import Chepy — chain ops on the DATA block;","# /syntax chepy = op index · plain stdlib always works too."]:["# 'array', 'bisect', 'heapq' and sys.stdin.buffer.read() are the","# standard speed-ups; none is ever required to solve a problem."]),n.toolkit?.length&&(a.push(`# Recommended for THIS problem: ${n.toolkit.join(", ")}`),n.toolkit_note))for(const e of Ue(n.toolkit_note,68))a.push(`# ${e}`);a.push("#","# 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`,"",""),b(s,a.join("\n"))})})(r,l),ko=!0,dn(),console.log(chalk.gray(jo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(jo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(jo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void co()}if("submit"===l)return console.log(chalk.yellow(jo()?" 用法: ":" Usage: ")+chalk.bold.green(jo()?"submit <题号>":"submit <n>")+chalk.gray(jo()?" 例如 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)")),Fo||console.log(chalk.gray(jo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void co();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const n=e[2];if(!Fo)return console.log(chalk.yellow(jo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void co();const t=Fo.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(jo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void co();const s=t.findIndex(e=>e.id===o)+1,a=n||C(Fo.dir,`sol-${s}.py`);let c;try{c=m(a,"utf-8")}catch{return console.log(chalk.red(jo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void co()}const d=new i(Be);d.start();const g=zo.get(s),u=await X(Be,Fo.phase,o,c,void 0,g&&!k(g)?g:void 0);if(d.stop(),!u.ok||!u.data)return"no_active_session"===u.code?console.log(chalk.yellow(jo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((jo()," "))+chalk.bold.green("contest")+chalk.gray(jo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(jo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${u.message||"judging failed"}`)),void co();const y=u.data;if(y.already_ac)console.log(chalk.green(jo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===y.verdict)console.log(chalk.bold.green(jo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${y.passed_tests??y.total_tests??"?"}/${y.total_tests??"?"} `+(jo()?"隐藏用例全过":"hidden tests passed")+` · ${y.time_ms??"?"}ms`)),Fo.data.solved.includes(o)||Fo.data.solved.push(o),Fo.tried.delete(o);else{Fo.tried.add(o);const e="TLE"===y.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${y.verdict}`)+chalk.gray(y.test?jo()?` · 挂在第 ${y.test} 个用例(过 ${y.passed_tests}/${y.total_tests})`:` · failed test ${y.test} (passed ${y.passed_tests}/${y.total_tests})`:""))}y.late&&console.log(chalk.yellow(jo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const h=te(y.deadline||"");if(console.log(chalk.white(jo()?` 本组进度: 已过 ${y.ac_count} 题 · 过 ${y.need} 题过关(共 ${y.n} 题)`:` Group progress: ${y.ac_count} solved · ${y.need} needed to pass (${y.n} problems)`)+(h?chalk.gray(` · ⏱ ${h}`):"")),y.passed&&!y.late)console.log(chalk.bold.green(jo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Bo();else if(!y.late){const e=t.findIndex(e=>!Fo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(jo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${ln(t[e])}`))}return void co()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Ze.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Ze.totalCards}. Try: `)+chalk.bold.green("card 1")),void co();const t=await Jo(n);return t?(console.log(t),void co()):(oo.currentCard=n,go=null,uo=null,yo=null,de(oo),Xo(),void co())}if(null!==yo&&["y","yes","n","no"].includes(o)){const e=Yo(yo);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-qo;he(oo,e.number),pe(oo,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),de(oo);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),No.push(I(Be,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),yo=null,e.solution&&e.solution.length>0)return void co();if(oo.currentCard<Ze.totalCards){const e=oo.currentCard,o=await Jo(e+1);if(o)return await Qo(e),console.log(o),void co();oo.currentCard+=1,de(oo),await Qo(e)?Vo():Xo(),co()}else Pe(Ze,oo),co();return}}if(null!==go&&["a","b","c","d"].includes(o)){const e=Yo(go);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(me(oo,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),he(oo,e.number),de(oo),ve(e,n,t,oo),No.push(I(Be,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),go=null,t)if(oo.currentCard<Ze.totalCards){const e=await Jo(oo.currentCard+1);if(e)return console.log(e),void co();oo.currentCard+=1,de(oo),Xo()}else Pe(Ze,oo),co();else co();return}}if(null!==uo){if("done"===o){const e=Yo(uo);if(e&&"practical"===e.type)return fe(oo,e.number),he(oo,e.number),de(oo),Ce(e),uo=null,void co()}if("skip"===o)return he(oo,uo),de(oo),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),uo=null,void co()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==go)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void co();if(null!==uo)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void co();if(null!==yo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void co();const e=oo.currentCard,o=e<Ze.totalCards?await Jo(e+1):null;return o?(await Qo(e),console.log(o),void co()):(oo.currentCard+=1,de(oo),oo.currentCard>Ze.totalCards?Pe(Ze,oo):await Qo(e)?Vo():Xo(),void co())}return null!==yo?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void co()):null!==go?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void co()):null!==uo?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void co()):("view"===vo?console.log(chalk.gray(jo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(jo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(jo()?" 回卡片":" to the card")):"honors"===vo?console.log(chalk.gray(jo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(jo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(jo()?" 回卡片":" 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 co())};so.on("line",e=>{wn(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.")),co()})}),ro||so.on("close",async()=>{No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,5e3))]),Do?Oo():process.exit(0)});const $n=j(Xe,jo());$n&&(console.log(chalk.bold.cyan(` ${$n}`)),console.log());try{Xo(),co();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Fe("Could not render this card — the curriculum may be malformed."),ro){so.removeAllListeners("line"),io();for(const e of lo)so.on("line",e);so.prompt()}else so.close();Oo()}await Wo}),He.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 T(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{JudgeWaitLine as i}from"../lib/judge-wait.js";import{ai4ioaiPromptLabel as c,handleAi4ioaiMessage as d,startAi4ioaiChat as g}from"./ai4ioai.js";import{existsSync as u,mkdirSync as y,readdirSync as h,readFileSync as m,renameSync as p,statSync as f,writeFileSync as b}from"node:fs";import{emptyDynamics as w,foldEditSession as $,isEmpty as k,noteRun as v}from"../lib/arena-edit-dynamics.js";import{dirname as A,join as C}from"node:path";import{fileURLToPath as _}from"node:url";import{loadCurriculumById as T,validateEAToken as x,syncProgress as I,syncCardFeedback as E,fetchCardFaqs as S}from"../lib/learn-curricula.js";import{parseReplyCommand as P,renderReplyLines as q,replyPushLine as j}from"../lib/learn-replies.js";import{ensureFullTable as M,lookupPydoc as L,lookupRanked as N,refetchTableOnMiss as R,nearKeys as W,renderIndex as O,renderPydoc as D,renderSyntax as Y,tableSize as U}from"../lib/py-syntax.js";import{normalizeTokenBody as F}from"../lib/token-format.js";import{fetchMyScores as z,recallCoach as H,setNickname as B,streamLearnTutor as Z,submitPqs as K,viewPqsTop as J,viewHonors as Q}from"../lib/learn-ai.js";import{contestReset as V,contestStart as X,contestSubmit as G,linkByIndex as ee,linkSuggest as oe,linkToken as ne,fetchGate as te,timeLeft as re}from"../lib/learn-contest.js";import{getConfig as le,saveConfig as se}from"../lib/config.js";import{isNativeWindows as ae,isWindowsBuildInWslShell as ie,whichBinary as ce}from"../lib/platform.js";import{loadLearnState as de,saveLearnState as ge,newLearnState as ue,activateSession as ye,updateStreak as he,markCardComplete as me,recordMCQ as pe,recordCheck as fe,markPracticalComplete as be,addAchievement as we}from"../lib/learn-state.js";import{renderWelcome as $e,renderKnowledgeCard as ke,renderMCQCard as ve,renderMCQFeedback as Ae,renderPracticalCard as Ce,renderPracticalSuccess as _e,renderSimDemoCard as Te,renderMilestone as xe,renderArenaTaskCard as Ie,renderComingSoonCard as Ee,renderStatus as Se,renderPhaseComplete as Pe,renderCurriculumComplete as qe,setLearnAiEnabled as je,setLearnFaqs as Me,setLearnHonorRanks as Le,setLearnPqsViewCards as Ne,setLearnReplies as Re,setLearnWidth as We,resolveLearnWidth as Oe,learnWidthCap as De,learnW as Ye,renderHonorWall as Ue,wrapMixed as Fe}from"../lib/learn-render.js";import{printError as ze}from"../lib/ui.js";const He=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(Be){Be.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async Be=>{Be?.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(),Be="LEARNDEMO01");let Ze=Be.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ze)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Ke=null;const Je=/^[A-Z0-9]+DEMO01$/i.test(Ze),Qe=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ze);let Ve=!1,Xe=!1,Ge=[],eo=-1,oo=Promise.resolve([]);if(Je)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),oo=S(Ze),Ke=await T(Ze,Ze,!0);else if(Qe){console.log(),console.log(chalk.gray(" Validating token..."));let e=await x(Ze);if(!e.ok){const o=F(Ze);if(o!==Ze){const n=await x(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ze} → ${o}`)),e=n,Ze=o)}}if(!e.ok)return ze(`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 🐼"):"")),Ve=!0===e.aiEnabled,Xe=!0===e.gated,Ge=e.replies??[],oo=S(Ze),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Ke=await T(e.curriculumId||"LEARNDEMO01",Ze,!0),!Ke)return ze(`Could not open a learn curriculum for token '${Ze}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ze}`)+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 ${Ze}`)+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(!Ke){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(ze(`Could not reach the learn server to open ${Ze}.`),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 ${Ze}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(ze(`Unknown learn token: ${Ze}`),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 no=de(),to=!1;try{if(no&&no.token===Ze)he(no);else{const e=ye(Ze);e?(no=e,no.totalCards=Ke.totalCards,he(no)):(no=ue(Ze,Ke.id,Ke.totalCards),to=!0)}ge(no),$e(Ke,no,to)}catch{return ze("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 ${Ze}`)+chalk.gray(".")),void console.log()}const ro=a(),lo=null!==ro,so=lo?ro.listeners("line").slice():[];lo&&ro.removeAllListeners("line");const ao=lo?ro:o({input:process.stdin,output:process.stdout,terminal:!0}),io=lo?ao.prompt:null;lo&&(ao.prompt=e.prototype.prompt);const co=()=>{lo&&io&&(ao.prompt=io)},go=()=>{ao.setPrompt(xo?chalk.bold.green(`icoa ${c()}> `):vo?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan($o?"icoa learn ai> ":"icoa learn> ")),ao.prompt()};let uo=null,yo=null,ho=null,mo=null,po=[],fo=!1,bo=null;const wo=()=>{bo&&clearTimeout(bo),bo=null,po=[],fo=!1,mo=null};let $o=!1,ko=!1,vo=!1,Ao=null,Co=!1,_o=0,To=!1,xo=!1;const Io=new Map,Eo=()=>{let e=Io.get(no.currentCard);return e||(e=[],Io.set(no.currentCard,e)),e};let So=!1;const Po=new Set;let qo=!1,jo=0;const Mo=()=>(le().language||"en").toLowerCase().startsWith("zh");je(Ve),We(Oe(le())),Ne(Po);const Lo=new Map;Le(Lo),Re(Ge);const No=await oo;Me(No);const Ro=[];let Wo=null;const Oo=new Promise(e=>{Wo=e}),Do=()=>{const e=Wo;Wo=null,e?.()},Yo="1"===process.env.ICOA_LEARN_EMBEDDED,Uo=e=>Ke.cards.find(o=>o.number===e);let Fo=null,zo=null;const Ho=new Map,Bo=!Ze.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ze),Zo=async()=>{if(!Bo)return;const e=await te(Ze);e.ok&&e.data&&(Fo=e.data)},Ko=e=>{const o=Ke.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Jo=e=>{if(!Xe||!Fo)return null;const o=Ko(e);if(o<=Fo.unlocked_through_phase)return null;const n=Fo.phases.find(e=>e.phase===Fo.unlocked_through_phase),t=[chalk.yellow(Mo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${Fo.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${Fo.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(Mo()?` ⚔ 练习赛 ${Fo.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${Fo.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(Mo()?` ⚖ 判分赛: 最好 ${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(Mo()?"、":", "),r=e.length>8?Mo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:Mo()?" 张":"";t.push(chalk.gray(Mo()?` ✓ 逐卡自测: ${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(Mo()?` ⭐ 提问研究: ${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")},Qo=async e=>Xe?null===Jo(e)?null:(await Zo(),Jo(e)):null;Bo&&await Zo();const Vo=async e=>{const o=Ke.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Ke.modules.find(e=>e.number===o.number+1);let t;if(Ve){const e=await z({token:Ze,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}Bo&&await Zo();const r=Fo?.phases.find(e=>e.phase===o.number);return Pe(Ke,no,o,n,t,r),!0},Xo=()=>{qo=!0,console.log(chalk.gray(Mo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Go=()=>{Ao=null;const e=Uo(no.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":ke(e,Ke),e.check?(ho=e.number,jo=Date.now()):(me(no,e.number),ge(no));break;case"mcq":ve(e,Ke),uo=e.number;break;case"practical":Ce(e,Ke),yo=e.number;break;case"sim_demo":Te(e,Ke),me(no,e.number),ge(no);break;case"milestone":xe(e,Ke),we(no,e.badge),me(no,e.number),ge(no);break;case"arena_task":Ie(e,Ke),me(no,e.number),ge(no);break;case"coming_soon":Ee(e,Ke),me(no,e.number),ge(no)}en(e.number)},en=e=>{if(!Bo||!Fo)return;const o=Ke.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=Fo.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?Mo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Ye());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${Mo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(Mo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(Mo()?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(Mo()?`${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(Mo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Mo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(Mo()?"✍ 第一次用 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(Mo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(Mo()?"最好":"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(Mo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Mo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(Mo()?" 继续学习":" keep going"):chalk.gray(Mo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(Mo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},on=()=>{Ze.endsWith("DEMO01")?console.log(chalk.yellow(Mo()?" 🐼 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(Mo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(Mo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},nn=async(e,o)=>{if(Ve){ko=!0;try{console.log(),console.log(chalk.gray("deep"===o?Mo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":Mo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await Z({token:Ze,cardNumber:no.currentCard,question:e,mode:o,history:Eo().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(Mo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Eo().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(` (${Mo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Mo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==ho&&console.log(chalk.gray(Mo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{ko=!1}}else on()},tn=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],rn=async()=>{vo&&zo?hn?pn(hn):gn():Ao?await ln():Go()},ln=async()=>{ko=!0;try{console.log();const e=await Q({token:Ze,curriculumId:Ke.id,cardNumber:no.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Mo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Mo()?` 🏆 本卡实时 Top-3 — 第 ${no.currentCard} 张`:` 🏆 Live top-3 — card ${no.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(Mo()?" (你)":" (you)"):""))}else console.log(chalk.gray(Mo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Lo.set(no.currentCard,e.mine.rank),console.log(chalk.white(Mo()?" 你: ":" You: ")+chalk.bold.yellow(Mo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Mo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Ve&&console.log(chalk.gray(Mo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ue({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Mo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Mo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Mo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Ao="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Mo()?" 返回卡片":" returns to the card")),console.log()}finally{ko=!1}},sn=e=>Mo()&&e.title_zh||e.title,an=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of Fe(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},cn=e=>{console.log(),console.log(chalk.bold.green(Mo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(Mo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},dn=e=>zo.data.solved.includes(e.id)?"✅":zo.data.carried?.includes(e.id)?"✅↗":zo.tried.has(e.id)?"❌":"⬜",gn=()=>{const e=zo.data,o=re(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(Mo()?` · 第 ${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(Mo()?" ⏱ 已超时 — 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(Mo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(Mo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(Mo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Mo()?" 带过来,不必重做":" 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(Mo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Mo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(Mo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(Mo()?` 满血重开本组(${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)} `)+dn(e)+chalk.white(` ${sn(e)}`))}),console.log(),un()},un=()=>{console.log(chalk.gray(Mo()?" /read <n> 读题 · /edit <n> 写码(vi) · /run <n> 样例自测 · /debug <n> 自由调试 · /submit <n> 判分":" /read <n> statement · /edit <n> code (vi) · /run <n> sample check · /debug <n> free run · /submit <n> judge")),console.log(chalk.gray(" ")+chalk.bold.green(Mo()?"/syntax <词>":"/syntax <word>")+chalk.gray(Mo()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(Mo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Mo()?" 返回课程":" returns to the lesson")),console.log()},yn=e=>{const o=parseInt(e,10),n=zo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(Mo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let hn=null,mn=!1;const pn=e=>{const o=yn(e);if(!o)return;const{p:n,n:t}=o;hn=String(t),console.log(),console.log(chalk.bold.white(` ${dn(n)} ${sn(n)}`)),console.log();for(const e of(e=>Mo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of Fe(e,Ye()+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(Mo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Mo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(0===(n.samples??[]).length&&(console.log(),console.log(chalk.gray(Mo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),n.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(Mo()?"本题推荐:":"Recommended here: "))+chalk.bold.white(n.toolkit.join(", ")));const e=Mo()&&n.toolkit_note_zh||n.toolkit_note;if(e)for(const o of Fe(e,Ye()))console.log(chalk.gray(` ${o}`))}console.log(),console.log(chalk.white(Mo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(Mo()?"写码(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(Mo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(Mo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(Mo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray(Mo()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(Mo()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((Mo()," ↩ "))+chalk.bold.green("back")+chalk.gray(Mo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(Mo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((Mo()," / "))+chalk.bold.green("wide")+chalk.gray(Mo()?" 换语言/宽度":" language / width")),console.log()},fn=async(e,o)=>await new Promise(n=>{const t=process.stdin,s=!!t.isTTY&&!!t.isRaw;if(ao.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const a=r(e,o,{stdio:"inherit",cwd:zo.dir}),i=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&s)try{t.setRawMode(!0)}catch{}l(),ao.resume(),n(e)};a.on("close",()=>i(null)),a.on("error",e=>i(e))}),bn=()=>{console.log(chalk.yellow(Mo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(Mo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(Mo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(Mo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},wn=new Map,$n=async e=>{const o=e.trim().toLowerCase(),l=vo&&o.startsWith("/")?o.slice(1):o;if(ko)return;if(null!==mo){if(po.push(e.replace(/\s+$/,"")),bo&&clearTimeout(bo),bo=null,fo){const e=po[po.length-1]??"";return"/cancel"===e.trim()?(wo(),console.log(chalk.gray(Mo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void go()):""!==e.trim()?void go():(po.pop(),void await a())}return void(bo=setTimeout(()=>{if(bo=null,po.length>1){fo=!0;const e=po.length;return console.log(chalk.cyan(Mo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(Mo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void go()}a()},140))}async function a(){const e=po.join("\n").replace(/^\s+|\s+$/g,""),o=mo??no.currentCard,n=po.length;if(wo(),""===e)console.log(chalk.gray(Mo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(Mo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(Mo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(Mo()?" 即可执行。":" again to run it."));else{const t=jo>0?Date.now()-jo:void 0;if(await E(Ze,{curriculum_id:Ke.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const t=n>1?Mo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(Mo()?` ✓ 已收到${t},谢谢帮助完善这张卡。`:` ✓ Thanks ${t}— your report was recorded.`)),console.log(chalk.gray(Mo()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),Ge=[...Ge,{id:eo--,curriculumId:Ke.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Re(Ge)}else console.log(chalk.yellow(Mo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),go()}if(Co){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Co=!1,console.log(),console.log(chalk.yellow(Mo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(Mo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(Mo()?" 即可执行该命令。":" again to run it.")),console.log(),void go();if(!o)return Co=!1,console.log(chalk.gray(Mo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void go();const n=await B({token:Ze,nickname:o});if(n.ok)Co=!1,console.log(chalk.bold.green(Mo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(Mo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{_o+=1;const e="taken"===n.code?Mo()?"已被占用":"already taken":"bad_charset"===n.code?Mo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?Mo()?"未通过审核":"did not pass review":n.message||"error";if(!(_o>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Mo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void go();Co=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Mo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void go()}if(So){So=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{ko=!0;try{console.log(),console.log(chalk.gray(Mo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await K({token:Ze,cardNumber:no.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Mo()?"评审暂不可用。":"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(Mo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Mo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Mo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Mo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Mo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Mo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=Mo()?` 本卡排名 #${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(Mo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Mo()?` 第 ${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 tn(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Mo()?" 改进提问: ":" 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(` (${Mo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Po.add(no.currentCard):Po.delete(no.currentCard),"number"==typeof e.rank&&Lo.set(no.currentCard,e.rank);const o=await Q({token:Ze,curriculumId:Ke.id,cardNumber:no.currentCard});o.ok&&o.totals&&o.chapters&&(Ue({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Je&&(Co=!0,_o=0,console.log(chalk.bold.yellow(Mo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Mo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Mo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{ko=!1}})():(console.log(chalk.gray(Mo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==ho&&(console.log(chalk.gray(Mo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void go()}if(qo)return qo=!1,Go(),void go();if(!o)return void go();if(xo)return"exit"===await d(e.trim())&&(xo=!1),void go();if($o){if(["q","quit","exit","back","b","menu"].includes(o))return $o=!1,console.log(chalk.gray(Mo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void go();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(Mo()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?Mo()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":Mo()?`「${t}」是卡片命令,不是问题,没有送出去。`:`“${t}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(Mo()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(Mo()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void go()):(t&&(await nn(t,n?"fast":"deep"),console.log(chalk.gray(Mo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void go())}if(vo&&zo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${zo.phase}s${zo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return vo=!1,console.log(chalk.gray(Mo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Go(),void go();if(/^\d+$/.test(o))return pn(o),void go();const t=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(t)return await(async e=>{const o=e.trim();if(await M()||mn||(mn=!0,console.log(chalk.gray(Mo()?` (离线:只有 ${U()} 条核心速查可用;联网后自动补全)`:` (offline: ${U()} core entries available; the rest arrive when you have a connection)`))),!o)return void O(Mo());const n=N(o);if(n.length){Y(n[0],Mo());const e=n.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(Mo()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const t=await L("python3",o);if(t)D(t,Mo());else{if(await R()){const e=N(o);if(e.length)return void Y(e[0],Mo())}console.log(),console.log(chalk.yellow(Mo()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(Mo()?" 试试: ":" Try: ")+chalk.cyan(W(o).join(" · "))),console.log(chalk.gray(Mo()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(t[1]??""),void go();const r=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(r){const[,e,o]=r;return"list"===e?gn():o?"read"===e||"open"===e?pn(o):"edit"===e?await(async e=>{const o=yn(e);if(!o)return;const n=C(zo.dir,`sol-${o.n}.py`);if(ae())return ie()?(console.log(chalk.yellow(Mo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(Mo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(Mo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(Mo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(Mo()?" ← 不能是 /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(Mo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(Mo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(Mo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(Mo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(Mo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(Mo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(Mo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(Mo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!ce("vi"))return console.log(chalk.yellow(Mo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(Mo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(Mo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return f(e).size}catch{return 0}},r=t(n),l=Date.now();await fn("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),Ho.set(o.n,$(Ho.get(o.n)??w(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(Mo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Mo()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=yn(e);if(!o)return;const{p:t,n:r}=o,l=C(zo.dir,`sol-${r}.py`);if(!u(l))return void console.log(chalk.yellow(Mo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Ho.set(r,v(Ho.get(r)??w()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(Mo()?` 本题无样例(设计如此)— 用 /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)bn();else if(o.killed)console.log(chalk.yellow(Mo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Mo()?" ✗ 程序报错:":" ✗ 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(Mo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Mo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(Mo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Mo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Mo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Mo()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=yn(e);if(!o)return;const n=C(zo.dir,`sol-${o.n}.py`);if(!u(n))return void console.log(chalk.yellow(Mo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(Mo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 fn("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(Mo()?" 回到竞技场。":" Back in the arena.")),console.log()):bn()})(o):"recall"===e&&await(async e=>{const o=yn(e);if(!o)return;if(!Ve)return void on();const{p:n,n:t}=o,r=C(process.cwd(),"icoa-contest"),l=`${Ke.id}-phase${zo.phase}-g${zo.data.slot}-archived-`;let s=null;try{for(const e of h(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?C(r,s,`sol-${t}.py`):null;if(!a||!u(a))return void console.log(chalk.gray(Mo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${zo.phase}-${zo.data.slot}-${t}`,d=Math.min(3,(wn.get(c)??0)+1);console.log(chalk.gray(Mo()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await H({token:Ze,phase:zo.phase,slot:zo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:d,lang:Mo()?"zh":"en"});if(g.ok){wn.set(c,d),console.log();for(const e of Fe(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(Mo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(Mo()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(Mo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(Mo()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(Mo()?" (花名册: /list)":" (roster: /list)")),void go()}if("contest"===o||"/contest"===o)return gn(),void go();const a="lang"===o||/^lang\s+\S+$/.test(o),i=He.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(Mo()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void go()}if("tmux"===o||o.startsWith("tmux ")){try{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(Mo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void go()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(ao.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{}ao.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void go()}if("ai4ioai"===o||"/ai4ioai"===o)return await g()&&(xo=!0),void go();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Ve)return on(),void go();To||(To=!0,console.log(),console.log(chalk.bold.cyan(Mo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Mo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Mo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Mo()||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){$o=!0;const e=Uo(no.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Mo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(Mo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Mo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void go()}return await nn(t,n?"fast":"deep"),void go()}if(!vo&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Ve)return on(),void go();const e=Uo(no.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Mo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Mo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Mo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Mo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Mo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Mo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Mo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),So=!0,void go()}const c=!vo&&"honors"===Ao&&/^[1-3]$/.test(o);if(!vo&&Ao&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(Mo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(Mo()?" ↩ back 回上一层":" ↩ back goes up one level")),void go();if(!vo&&(c||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Ve)return on(),void go();const e=/^\/?view ([1-3])$/.exec(o),n=c?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{ko=!0;try{console.log();const o=await J({token:Ze,cardNumber:no.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Mo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Po.delete(no.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Po.add(no.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Mo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${no.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${no.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(Mo()?` (第 ${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(Mo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=tn(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(Mo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Ao="view",console.log(chalk.gray((Mo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Mo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{ko=!1}})(n),void go()}if("/honors"===o||"honors"===o)return Je?(console.log(),console.log(chalk.gray(Mo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void go()):(await ln(),void go());if("menu"===o||"menu confirm"===o){if(Ro.length>0&&await Promise.race([Promise.allSettled(Ro),new Promise(e=>setTimeout(e,3e3))]),ao.removeAllListeners("line"),co(),lo||!Yo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(lo?ao:void 0),Do()}else ao.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===Ao)return await ln(),void go();if("honors"===Ao)return Ao=null,Go(),void go();if(Ro.length>0&&await Promise.race([Promise.allSettled(Ro),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${no.streakDays} day(s)`)),console.log(),lo){ao.removeAllListeners("line"),co();for(const e of so)ao.on("line",e);ao.prompt(),Do()}else ao.removeAllListeners("line"),ao.close();return}if("status"===o)return Se(Ke,no),void go();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await T(Ke.id,Ze,!0);return void(e?(Object.assign(Ke,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Go()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),go()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(le().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void go();const n=Ke.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 se({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),ho=null,uo=null,yo=null,wo(),qo=!1,So=!1,await rn(),void go()}if(He.has(o)){const e=He.get(o),n=Oe(le()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return Mo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((Mo()?"normal"===e?" 已是标准 64 列。":Ye()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Ye()} 列,上限 ${De(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Ye()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Ye()} cols, cap ${De(e)}). `)+t(e))),void go()):(se({learnWidth:e,learnWide:"normal"!==e}),We(e),"normal"!==e&&Ye()<=64?(console.log(chalk.yellow(Mo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((Mo()?` 设置已记住(${e},上限 ${De(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${De(e)} cols) and applies once you widen the window. `)+t(e))),void go()):(console.log(chalk.green(" ✓ ")+chalk.gray((Mo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Ye()} 列,上限 ${De(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Ye()} cols, cap ${De(e)}). `)+t(e))),ho=null,uo=null,yo=null,wo(),qo=!1,So=!1,await rn(),void go()))}if("sim"===o){const e=Uo(no.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=A(_(import.meta.url)),o=[C(e,"..","..","panda","mujoco-launcher.py"),C(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(u(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 go()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void go())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=no.currentCard,n=no.bookmarks.includes(e),t="bookmark"!==o;return t?no.bookmarks=no.bookmarks.filter(o=>o!==e):n||no.bookmarks.push(e),ge(no),t?console.log(n?chalk.gray(Mo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(Mo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(Mo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(Mo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void go()}const x=P(o);if(x){const e="current"===x.target?no.currentCard:x.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>Ke.cards.length))return console.log(chalk.yellow(Mo()?` 本课共 ${Ke.cards.length} 张,请输 r 1–${Ke.cards.length} 或 r all。`:` This course has ${Ke.cards.length} cards. Try r 1–${Ke.cards.length} or r all.`)),console.log(),void go();for(const o of q(Ge,No,e,Mo(),Ye()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?Ge:Ge.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(Ge=Ge.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Re(Ge),Ro.push(I(Ze,{card_number:no.currentCard,event_type:"viewed"},o).catch(()=>{}))),void go()}if("e"===o)return mo=no.currentCard,console.log(chalk.gray(Mo()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(Mo()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void go();if("back"===o||"b"===o)return"view"===Ao?(await ln(),void go()):"honors"===Ao?(Ao=null,Go(),void go()):(no.currentCard>1&&(no.currentCard-=1),uo=null,yo=null,ho=null,ge(no),Go(),void go());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Bo)return console.log(chalk.yellow(Mo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void go();if(!e){const e=await oe(Ze),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(Mo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(Mo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(Mo()?` 这台电脑上有 ${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(Mo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(Mo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(Mo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(Mo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(Mo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(Mo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(Mo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void go()}if(/^\d{1,2}$/.test(e)){const o=await ee(Ze,Number(e));return o.ok&&o.data?(cn(o.data),await Zo(),void go()):(console.log(chalk.red(` ✗ ${o.message||(Mo()?"关联失败":"Link failed")}`)),void go())}const n=await ne(Ze,e);return n.ok&&n.data?(cn(n.data),await Zo(),void go()):(console.log(chalk.red(` ✗ ${n.message||(Mo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(Mo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void go())}if("contest"===o||"/contest"===o||"arena"===o||"contest start"===o||"/contest start"===o||"contest status"===o||"contest reset"===o||/^\/?contest [1-9]$/.test(o)){if(!Bo)return console.log(chalk.yellow(Mo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void go();const e=Ko(no.currentCard);if("contest reset"===o){const o=await V(Ze,e);if(o.ok){console.log(chalk.yellow(Mo()?` 已放弃当前计时(阶段 ${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",`${Ke.id}-phase${e}-g${n}`);if(u(t))try{p(t,`${t}-archived-${o}`),console.log(chalk.gray(Mo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(Mo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(Mo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),zo=null,vo=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void go()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Mo()?" 连接判分赛…":" Contacting contest server…"));const t=await X(Ze,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(Mo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void go();const r=t.data,l=C(process.cwd(),"icoa-contest",`${Ke.id}-phase${e}-g${r.slot}`);y(l,{recursive:!0});const s=zo&&zo.phase===e&&zo.data.slot===r.slot?zo.tried:new Set;zo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.samples??[])[0];l&&b(C(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=C(o,`sol-${r}.py`);if(u(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${n.title} ══`,"#",...an(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}`)}if(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","#","# ── toolkit ──",...e.toolkit_available?.length?[`# Available on the judge: ${e.toolkit_available.join(", ")}`]:["# The judge runs the Python standard library only."],...e.toolkit_available?.includes("chepy")?["# from chepy import Chepy — chain ops on the DATA block;","# /syntax chepy = op index · plain stdlib always works too."]:["# 'array', 'bisect', 'heapq' and sys.stdin.buffer.read() are the","# standard speed-ups; none is ever required to solve a problem."]),n.toolkit?.length&&(a.push(`# Recommended for THIS problem: ${n.toolkit.join(", ")}`),n.toolkit_note))for(const e of Fe(n.toolkit_note,68))a.push(`# ${e}`);a.push("#","# 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`,"",""),b(s,a.join("\n"))})})(r,l),vo=!0,gn(),console.log(chalk.gray(Mo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(Mo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(Mo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void go()}if("submit"===l)return console.log(chalk.yellow(Mo()?" 用法: ":" Usage: ")+chalk.bold.green(Mo()?"submit <题号>":"submit <n>")+chalk.gray(Mo()?" 例如 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)")),zo||console.log(chalk.gray(Mo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void go();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const n=e[2];if(!zo)return console.log(chalk.yellow(Mo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void go();const t=zo.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(Mo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void go();const s=t.findIndex(e=>e.id===o)+1,a=n||C(zo.dir,`sol-${s}.py`);let c;try{c=m(a,"utf-8")}catch{return console.log(chalk.red(Mo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void go()}const d=new i(Ze);d.start();const g=Ho.get(s),u=await G(Ze,zo.phase,o,c,void 0,g&&!k(g)?g:void 0);if(d.stop(),!u.ok||!u.data)return"no_active_session"===u.code?console.log(chalk.yellow(Mo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((Mo()," "))+chalk.bold.green("contest")+chalk.gray(Mo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(Mo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${u.message||"judging failed"}`)),void go();const y=u.data;if(y.already_ac)console.log(chalk.green(Mo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===y.verdict)console.log(chalk.bold.green(Mo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${y.passed_tests??y.total_tests??"?"}/${y.total_tests??"?"} `+(Mo()?"隐藏用例全过":"hidden tests passed")+` · ${y.time_ms??"?"}ms`)),zo.data.solved.includes(o)||zo.data.solved.push(o),zo.tried.delete(o);else{zo.tried.add(o);const e="TLE"===y.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${y.verdict}`)+chalk.gray(y.test?Mo()?` · 挂在第 ${y.test} 个用例(过 ${y.passed_tests}/${y.total_tests})`:` · failed test ${y.test} (passed ${y.passed_tests}/${y.total_tests})`:""))}y.late&&console.log(chalk.yellow(Mo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const h=re(y.deadline||"");if(console.log(chalk.white(Mo()?` 本组进度: 已过 ${y.ac_count} 题 · 过 ${y.need} 题过关(共 ${y.n} 题)`:` Group progress: ${y.ac_count} solved · ${y.need} needed to pass (${y.n} problems)`)+(h?chalk.gray(` · ⏱ ${h}`):"")),y.passed&&!y.late)console.log(chalk.bold.green(Mo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Zo();else if(!y.late){const e=t.findIndex(e=>!zo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Mo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${sn(t[e])}`))}return void go()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Ke.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Ke.totalCards}. Try: `)+chalk.bold.green("card 1")),void go();const t=await Qo(n);return t?(console.log(t),void go()):(no.currentCard=n,uo=null,yo=null,ho=null,ge(no),Go(),void go())}if(null!==ho&&["y","yes","n","no"].includes(o)){const e=Uo(ho);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-jo;me(no,e.number),fe(no,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),ge(no);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),Ro.push(I(Ze,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),ho=null,e.solution&&e.solution.length>0)return void go();if(no.currentCard<Ke.totalCards){const e=no.currentCard,o=await Qo(e+1);if(o)return await Vo(e),console.log(o),void go();no.currentCard+=1,ge(no),await Vo(e)?Xo():Go(),go()}else qe(Ke,no),go();return}}if(null!==uo&&["a","b","c","d"].includes(o)){const e=Uo(uo);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(pe(no,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),me(no,e.number),ge(no),Ae(e,n,t,no),Ro.push(I(Ze,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),uo=null,t)if(no.currentCard<Ke.totalCards){const e=await Qo(no.currentCard+1);if(e)return console.log(e),void go();no.currentCard+=1,ge(no),Go()}else qe(Ke,no),go();else go();return}}if(null!==yo){if("done"===o){const e=Uo(yo);if(e&&"practical"===e.type)return be(no,e.number),me(no,e.number),ge(no),_e(e),yo=null,void go()}if("skip"===o)return me(no,yo),ge(no),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),yo=null,void go()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==uo)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void go();if(null!==yo)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void go();if(null!==ho)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void go();const e=no.currentCard,o=e<Ke.totalCards?await Qo(e+1):null;return o?(await Vo(e),console.log(o),void go()):(no.currentCard+=1,ge(no),no.currentCard>Ke.totalCards?qe(Ke,no):await Vo(e)?Xo():Go(),void go())}return null!==ho?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void go()):null!==uo?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void go()):null!==yo?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void go()):("view"===Ao?console.log(chalk.gray(Mo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(Mo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(Mo()?" 回卡片":" to the card")):"honors"===Ao?console.log(chalk.gray(Mo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(Mo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(Mo()?" 回卡片":" to the card")):console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("/ai")+chalk.gray(" / ")+chalk.white("quit")),void go())};ao.on("line",e=>{$n(e).catch(e=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),go()})}),lo||ao.on("close",async()=>{Ro.length>0&&await Promise.race([Promise.allSettled(Ro),new Promise(e=>setTimeout(e,5e3))]),Yo?Do():process.exit(0)});const kn=j(Ge,Mo());kn&&(console.log(chalk.bold.cyan(` ${kn}`)),console.log());try{Go(),go();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(ze("Could not render this card — the curriculum may be malformed."),lo){ao.removeAllListeners("line"),co();for(const e of so)ao.on("line",e);ao.prompt()}else ao.close();Do()}await Oo}),Be.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 T(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 +1 @@
1
- import{spawnSync as t}from"node:child_process";import{existsSync as r,mkdirSync as n,readFileSync as e,renameSync as o,statSync as a,writeFileSync as s}from"node:fs";import{homedir as c}from"node:os";import{join as i}from"node:path";const u="https://practice.icoa2026.au/assets/translations";export function assetDir(){const t=i(c(),".icoa","assets");return r(t)||n(t,{recursive:!0}),t}export async function lazyJson(t,n=6e3){const e=i(assetDir(),t),o=r(e);return o&&function(t){try{return Date.now()-a(t).mtimeMs<6048e5}catch{return!1}}(e)||await f(`${u}/${t}`,e,n)||o?l(e):null}function l(t){try{return JSON.parse(e(t,"utf8"))}catch{return null}}async function f(t,r,n){const e=`${r}.part`;try{const a=new AbortController,c=setTimeout(()=>a.abort(),n),i=await fetch(t,{signal:a.signal});if(clearTimeout(c),!i.ok)return!1;const u=Buffer.from(await i.arrayBuffer());return!!u.length&&(s(e,u),o(e,r),!0)}catch{return!1}}export async function lazyTarball(e,a,c=15e3){const l=i(assetDir(),a),m=i(l,".complete");if(r(m))return l;const p=i(assetDir(),e);if(!await f(`${u}/${e}`,p,c))return null;const y=`${l}.staging`;try{return n(y,{recursive:!0}),0!==t("tar",["-xzf",p,"-C",y],{stdio:"ignore"}).status?null:(r(l)&&o(l,`${l}.old-${Date.now()}`),o(y,l),s(m,(new Date).toISOString()),l)}catch{return null}}
1
+ import{spawnSync as t}from"node:child_process";import{existsSync as r,mkdirSync as n,readFileSync as e,renameSync as o,statSync as a,writeFileSync as s}from"node:fs";import{homedir as c}from"node:os";import{join as i}from"node:path";const u="https://practice.icoa2026.au/assets/translations";export function assetDir(){const t=i(c(),".icoa","assets");return r(t)||n(t,{recursive:!0}),t}export async function lazyJson(t,n=6e3,e){const o=i(assetDir(),t),s=r(o);return s&&function(t){try{return Date.now()-a(t).mtimeMs<6048e5}catch{return!1}}(o)&&!e?.force||await f(`${u}/${t}`,o,n)||s?l(o):null}function l(t){try{return JSON.parse(e(t,"utf8"))}catch{return null}}async function f(t,r,n){const e=`${r}.part`;try{const a=new AbortController,c=setTimeout(()=>a.abort(),n),i=await fetch(t,{signal:a.signal});if(clearTimeout(c),!i.ok)return!1;const u=Buffer.from(await i.arrayBuffer());return!!u.length&&(s(e,u),o(e,r),!0)}catch{return!1}}export async function lazyTarball(e,a,c=15e3){const l=i(assetDir(),a),m=i(l,".complete");if(r(m))return l;const p=i(assetDir(),e);if(!await f(`${u}/${e}`,p,c))return null;const y=`${l}.staging`;try{return n(y,{recursive:!0}),0!==t("tar",["-xzf",p,"-C",y],{stdio:"ignore"}).status?null:(r(l)&&o(l,`${l}.old-${Date.now()}`),o(y,l),s(m,(new Date).toISOString()),l)}catch{return null}}
@@ -1 +1 @@
1
- import{spawn as e}from"node:child_process";import chalk from"chalk";import{lazyJson as t}from"./lazy-assets.js";const o=[{keys:["del","delete","remove index"],en:"Statement, not a method: deletes without returning. Only `del` can delete a slice.",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).",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:["dict","hashmap","map","key value"],en:"Key→value with O(1) lookup. Iterating gives keys; use .items() for pairs.",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:["pop","list.pop"],en:"Method: removes AND returns. O(1) at the end, O(n) anywhere else.",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.",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.',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.",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.",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.",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.",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.",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:["dict get","keyerror","default","setdefault"],en:"d[k] raises KeyError; d.get(k, default) does not. Counting? use a 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"]}];let n=o,s=!1;export async function ensureFullTable(){if(s)return!0;const e=await t("syntax-table.v1.json");if(s=!0,!e||!Array.isArray(e.entries)||!e.entries.length)return!1;const r=new Set(o.map(e=>e.keys[0]));return n=[...o,...e.entries.filter(e=>e?.keys?.length&&!r.has(e.keys[0]))],!0}export function tableSize(){return n.length}export function syntaxIndex(){return n.map(e=>e.keys[0])}const r={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","其他"]},i=["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 t=new Map;for(const o of n){const[n,s]=r[o.keys[0]]??["Misc","其他"],l=i.indexOf(n),a=l<0?i.length:l,d=t.get(a)??{name:e?s:n,items:[]};d.items.push(o),t.set(a,d)}console.log(),console.log(chalk.bold.white(e?` /syntax 全部关键词 — ${n.length} 条`:` /syntax keyword index — ${n.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[...t.keys()].sort((e,t)=>e-t)){const o=t.get(e);if(o){console.log(),console.log(chalk.bold.cyan(` ── ${o.name} ──`));for(const e of o.items)console.log(chalk.bold.green(` ${e.keys[0].padEnd(15)}`)+chalk.gray(e.keys.slice(1).join(" · ")))}}console.log()}function l(e){return a(e).toLowerCase()}function a(e){return e.trim().replace(/^\/+/,"").replace(/[?。?]+$/,"").replace(/\s+/g," ")}export function lookupRanked(e){const t=l(e);if(!t)return[];const o=n.filter(e=>e.keys.some(e=>e===t)),s=t.split(" ").filter(Boolean),r=[];for(const e of n){if(o.includes(e))continue;let n=0;for(const o of e.keys)o.includes(" ")?t.includes(o)&&(n+=2*o.length):s.includes(o)&&(n+=o.length);n>0&&r.push({e:e,score:n})}return r.sort((e,t)=>t.score-e.score),[...o,...r.map(e=>e.e)]}export function nearKeys(e,t=6){const o=l(e).split(" ").filter(e=>e.length>=3),n=syntaxIndex().filter(e=>o.some(t=>e.includes(t)||t.includes(e)));return(n.length?n:syntaxIndex()).slice(0,t)}export function lookupPydoc(t,o,n=14){const s=a(o);return s.length>60||!/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,2}$/.test(s)?Promise.resolve(null):new Promise(o=>{let r="",i=!1;const l=e=>{i||(i=!0,o(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",s],{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=>{r+=String(e)}),a.on("error",()=>{clearTimeout(d),l(null)}),a.on("close",e=>{if(clearTimeout(d),0!==e||!r.trim())return void l(null);const t=r.split("\n"),o=(t[0]??"").replace(/^(OBJ|TOPIC)\s+/,"").trim(),s=/^\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(s.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();l({title:o,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(` ${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";import{lazyJson as t}from"./lazy-assets.js";const n=[{keys:["del","delete","remove index"],en:"Statement, not a method: deletes without returning. Only `del` can delete a slice.",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).",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:["dict","hashmap","map","key value"],en:"Key→value with O(1) lookup. Iterating gives keys; use .items() for pairs.",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:["pop","list.pop"],en:"Method: removes AND returns. O(1) at the end, O(n) anywhere else.",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.",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.',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.",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.",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.",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.",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.",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:["dict get","keyerror","default","setdefault"],en:"d[k] raises KeyError; d.get(k, default) does not. Counting? use a 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"]}];let s=n,o=!1;export async function ensureFullTable(){if(o)return!0;const e=await t("syntax-table.v1.json");if(o=!0,!e||!Array.isArray(e.entries)||!e.entries.length)return!1;const r=new Set(n.map(e=>e.keys[0]));return s=[...n,...e.entries.filter(e=>e?.keys?.length&&!r.has(e.keys[0]))],!0}let r=!1;export async function refetchTableOnMiss(){if(r)return!1;r=!0;const e=await t("syntax-table.v1.json",6e3,{force:!0});if(!e||!Array.isArray(e.entries)||!e.entries.length)return!1;const o=s.length,i=new Set(n.map(e=>e.keys[0]));return s=[...n,...e.entries.filter(e=>e?.keys?.length&&!i.has(e.keys[0]))],s.length!==o}export function tableSize(){return s.length}export function syntaxIndex(){return s.map(e=>e.keys[0])}const i={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","其他"]},l=["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 t=new Map;for(const n of s){const[s,o]=i[n.keys[0]]??["Misc","其他"],r=l.indexOf(s),a=r<0?l.length:r,d=t.get(a)??{name:e?o:s,items:[]};d.items.push(n),t.set(a,d)}console.log(),console.log(chalk.bold.white(e?` /syntax 全部关键词 — ${s.length} 条`:` /syntax keyword index — ${s.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[...t.keys()].sort((e,t)=>e-t)){const n=t.get(e);if(n){console.log(),console.log(chalk.bold.cyan(` ── ${n.name} ──`));for(const e of n.items)console.log(chalk.bold.green(` ${e.keys[0].padEnd(15)}`)+chalk.gray(e.keys.slice(1).join(" · ")))}}console.log()}function a(e){return d(e).toLowerCase()}function d(e){return e.trim().replace(/^\/+/,"").replace(/[?。?]+$/,"").replace(/\s+/g," ")}export function lookupRanked(e){const t=a(e);if(!t)return[];const n=s.filter(e=>e.keys.some(e=>e===t)),o=t.split(" ").filter(Boolean),r=[];for(const e of s){if(n.includes(e))continue;let s=0;for(const n of e.keys)n.includes(" ")?t.includes(n)&&(s+=2*n.length):o.includes(n)&&(s+=n.length);s>0&&r.push({e:e,score:s})}return r.sort((e,t)=>t.score-e.score),[...n,...r.map(e=>e.e)]}export function nearKeys(e,t=6){const n=a(e).split(" ").filter(e=>e.length>=3),s=syntaxIndex().filter(e=>n.some(t=>e.includes(t)||t.includes(e)));return(s.length?s:syntaxIndex()).slice(0,t)}export function lookupPydoc(t,n,s=14){const o=d(n);return o.length>60||!/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*){0,2}$/.test(o)?Promise.resolve(null):new Promise(n=>{let r="",i=!1;const l=e=>{i||(i=!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",o],{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=>{r+=String(e)}),a.on("error",()=>{clearTimeout(d),l(null)}),a.on("close",e=>{if(clearTimeout(d),0!==e||!r.trim())return void l(null);const t=r.split("\n"),n=(t[0]??"").replace(/^(OBJ|TOPIC)\s+/,"").trim(),o=/^\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(o.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();l({title:n,lines:i.slice(0,s)})})})}export function renderSyntax(e,t){console.log(),console.log(chalk.bold.white(` ${e.keys[0]}`)+chalk.gray(t?" (语法速查)":" (syntax lookup)")),console.log(chalk.gray(` ${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.464",
3
+ "version": "2.19.465",
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": {