icoa-cli 2.19.468 → 2.19.470
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/commands/wm.js +1 -0
- package/dist/index.js +1 -1
- package/dist/lib/commands.js +1 -1
- package/dist/lib/judge-wait.js +1 -1
- package/dist/lib/learn-contest.js +1 -1
- package/dist/repl.js +1 -1
- package/package.json +1 -1
package/dist/commands/learn.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as n,execSync as t,spawn as r}from"node:child_process";import{rearmFocusMode as l}from"../lib/input-dynamics.js";import{logCommand as s}from"../lib/logger.js";import{getMainRl as a}from"../lib/main-rl.js";import{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 T}from"node:url";import{loadCurriculumById as _,validateEAToken as x,syncProgress as I,syncCardFeedback as E,fetchCardFaqs as P}from"../lib/learn-curricula.js";import{hometaskDetailLines as S,hometaskLines as j,isTaskCommand as q}from"../lib/learn-hometask.js";import{detectCaps as L}from"../lib/render-card.js";import{parseReplyCommand as N,renderReplyLines as M,replyPushLine as R}from"../lib/learn-replies.js";import{ensureFullTable as O,lookupPydoc as W,lookupRanked as D,refetchTableOnMiss as Y,nearKeys as U,renderIndex as F,renderPydoc as z,renderSyntax as H,tableSize as B}from"../lib/py-syntax.js";import{normalizeTokenBody as Z}from"../lib/token-format.js";import{fetchMyScores as K,recallCoach as J,setNickname as Q,streamLearnTutor as V,submitPqs as X,viewPqsTop as G,viewHonors as ee}from"../lib/learn-ai.js";import{contestReset as oe,contestStart as ne,contestSubmit as te,linkByIndex as re,linkSuggest as le,linkToken as se,fetchGate as ae,timeLeft as ie}from"../lib/learn-contest.js";import{WARMUP as ce,WARMUP_ID as de,WARMUP_N as ge,WARMUP_TESTS as ue,gradeWarmup as ye,warmupEnabled as he}from"../lib/warmup.js";import{getConfig as me,saveConfig as pe}from"../lib/config.js";import{isNativeWindows as fe,isWindowsBuildInWslShell as be,whichBinary as we}from"../lib/platform.js";import{loadLearnState as $e,saveLearnState as ke,newLearnState as ve,activateSession as Ae,updateStreak as Ce,markCardComplete as Te,recordMCQ as _e,recordCheck as xe,markPracticalComplete as Ie,addAchievement as Ee}from"../lib/learn-state.js";import{renderWelcome as Pe,renderKnowledgeCard as Se,renderMCQCard as je,renderMCQFeedback as qe,renderPracticalCard as Le,renderPracticalSuccess as Ne,renderSimDemoCard as Me,renderMilestone as Re,renderArenaTaskCard as Oe,renderComingSoonCard as We,renderStatus as De,renderPhaseComplete as Ye,renderCurriculumComplete as Ue,setLearnAiEnabled as Fe,setLearnFaqs as ze,setLearnHometask as He,setLearnHonorRanks as Be,setLearnPqsViewCards as Ze,setLearnReplies as Ke,setLearnWidth as Je,resolveLearnWidth as Qe,learnWidthCap as Ve,learnW as Xe,renderHonorWall as Ge,wrapMixed as eo}from"../lib/learn-render.js";import{printError as oo}from"../lib/ui.js";const no=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);function to(e,o){e.forEach((n,t)=>{const r=t===e.length-1;0===t?console.log(chalk.bold.cyan(` ${n}`)):/^[─-]+$/.test(n.trim())&&n.trim().length>3?console.log(chalk.gray(` ${n}`)):r?console.log((o?chalk.bold.green:chalk.yellow)(` ${n}`)):console.log(chalk.white(` ${n}`))}),console.log()}export function registerLearnCommand(ro){ro.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ro=>{ro?.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(),ro="LEARNDEMO01");let lo=ro.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(lo)){const{runSprint:e}=await import("./sprint.js");return void await e()}let so=null;const ao=/^[A-Z0-9]+DEMO01$/i.test(lo),io=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(lo);let co=!1,go=!1,uo=[],yo=null,ho=-1,mo=Promise.resolve([]);if(ao)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),mo=P(lo),so=await _(lo,lo,!0);else if(io){console.log(),console.log(chalk.gray(" Validating token..."));let e=await x(lo);if(!e.ok){const o=Z(lo);if(o!==lo){const n=await x(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${lo} → ${o}`)),e=n,lo=o)}}if(!e.ok)return oo(`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 🐼"):"")),co=!0===e.aiEnabled,go=!0===e.gated,uo=e.replies??[],yo=e.hometask??null,mo=P(lo),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),so=await _(e.curriculumId||"LEARNDEMO01",lo,!0),!so)return oo(`Could not open a learn curriculum for token '${lo}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${lo}`)+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 ${lo}`)+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(!so){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(oo(`Could not reach the learn server to open ${lo}.`),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 ${lo}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(oo(`Unknown learn token: ${lo}`),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 po=$e(),fo=!1;try{if(po&&po.token===lo)Ce(po);else{const e=Ae(lo);e?(po=e,po.totalCards=so.totalCards,Ce(po)):(po=ve(lo,so.id,so.totalCards),fo=!0)}ke(po),Pe(so,po,fo),function(e){if(!e)return;const o=(me().language||"en").toLowerCase().startsWith("zh"),n="T0"===L().tier;to(j(e,o,Xe(),n),!!e.completedAt)}(yo)}catch{return oo("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 ${lo}`)+chalk.gray(".")),void console.log()}const bo=a(),wo=null!==bo,$o=wo?bo.listeners("line").slice():[];wo&&bo.removeAllListeners("line");const ko=wo?bo:o({input:process.stdin,output:process.stdout,terminal:!0}),vo=wo?ko.prompt:null;wo&&(ko.prompt=e.prototype.prompt);const Ao=()=>{wo&&vo&&(ko.prompt=vo)},Co=()=>{ko.setPrompt(Do?chalk.bold.green(`icoa ${c()}> `):No?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(qo?"icoa learn ai> ":"icoa learn> ")),ko.prompt()};let To=null,_o=null,xo=null,Io=null,Eo=[],Po=!1,So=null;const jo=()=>{So&&clearTimeout(So),So=null,Eo=[],Po=!1,Io=null};let qo=!1,Lo=!1,No=!1,Mo=null,Ro=!1,Oo=0,Wo=!1,Do=!1;const Yo=new Map,Uo=()=>{let e=Yo.get(po.currentCard);return e||(e=[],Yo.set(po.currentCard,e)),e};let Fo=!1;const zo=new Set;let Ho=!1,Bo=0;const Zo=()=>(me().language||"en").toLowerCase().startsWith("zh");Fe(co),Je(Qe(me())),Ze(zo);const Ko=new Map;Be(Ko),Ke(uo),He(yo);const Jo=await mo;ze(Jo);const Qo=[];let Vo=null;const Xo=new Promise(e=>{Vo=e}),Go=()=>{const e=Vo;Vo=null,e?.()},en="1"===process.env.ICOA_LEARN_EMBEDDED,on=e=>so.cards.find(o=>o.number===e);let nn=null,tn=null;const rn=new Map,ln=!lo.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(lo),sn=async()=>{if(!ln)return;const e=await ae(lo);e.ok&&e.data&&(nn=e.data)},an=e=>{const o=so.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},cn=e=>{if(!go||!nn)return null;const o=an(e);if(o<=nn.unlocked_through_phase)return null;const n=nn.phases.find(e=>e.phase===nn.unlocked_through_phase),t=[chalk.yellow(Zo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${nn.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${nn.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(Zo()?` ⚔ 练习赛 ${nn.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${nn.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(Zo()?` ⚖ 判分赛: 最好 ${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(Zo()?"、":", "),r=e.length>8?Zo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:Zo()?" 张":"";t.push(chalk.gray(Zo()?` ✓ 逐卡自测: ${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(Zo()?` ⭐ 提问研究: ${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")},dn=async e=>go?null===cn(e)?null:(await sn(),cn(e)):null;ln&&await sn();const gn=async e=>{const o=so.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=so.modules.find(e=>e.number===o.number+1);let t;if(co){const e=await K({token:lo,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}ln&&await sn();const r=nn?.phases.find(e=>e.phase===o.number);return Ye(so,po,o,n,t,r),!0},un=()=>{Ho=!0,console.log(chalk.gray(Zo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},yn=()=>{Mo=null;const e=on(po.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":Se(e,so),e.check?(xo=e.number,Bo=Date.now()):(Te(po,e.number),ke(po));break;case"mcq":je(e,so),To=e.number;break;case"practical":Le(e,so),_o=e.number;break;case"sim_demo":Me(e,so),Te(po,e.number),ke(po);break;case"milestone":Re(e,so),Ee(po,e.badge),Te(po,e.number),ke(po);break;case"arena_task":Oe(e,so),Te(po,e.number),ke(po);break;case"coming_soon":We(e,so),Te(po,e.number),ke(po)}hn(e.number)},hn=e=>{if(!ln||!nn)return;const o=so.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=nn.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?Zo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Xe());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${Zo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(Zo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(Zo()?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(Zo()?`${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(Zo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Zo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(Zo()?"✍ 第一次用 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(Zo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(Zo()?"最好":"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(Zo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Zo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(Zo()?" 继续学习":" keep going"):chalk.gray(Zo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(Zo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},mn=()=>{lo.endsWith("DEMO01")?console.log(chalk.yellow(Zo()?" 🐼 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(Zo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(Zo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},pn=async(e,o)=>{if(co){Lo=!0;try{console.log(),console.log(chalk.gray("deep"===o?Zo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":Zo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await V({token:lo,cardNumber:po.currentCard,question:e,mode:o,history:Uo().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(Zo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Uo().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(` (${Zo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Zo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==xo&&console.log(chalk.gray(Zo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Lo=!1}}else mn()},fn=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],bn=async()=>{No&&tn?En?Sn(En):_n():Mo?await wn():yn()},wn=async()=>{Lo=!0;try{console.log();const e=await ee({token:lo,curriculumId:so.id,cardNumber:po.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Zo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Zo()?` 🏆 本卡实时 Top-3 — 第 ${po.currentCard} 张`:` 🏆 Live top-3 — card ${po.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(Zo()?" (你)":" (you)"):""))}else console.log(chalk.gray(Zo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Ko.set(po.currentCard,e.mine.rank),console.log(chalk.white(Zo()?" 你: ":" You: ")+chalk.bold.yellow(Zo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Zo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):co&&console.log(chalk.gray(Zo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ge({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Zo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Zo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Zo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Mo="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Zo()?" 返回卡片":" returns to the card")),console.log()}finally{Lo=!1}},$n=e=>Zo()&&e.title_zh||e.title,kn=he(so.id);let vn=!1;const An=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of eo(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},Cn=e=>{console.log(),console.log(chalk.bold.green(Zo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(Zo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Tn=e=>e.id===de?vn?"✅":"⬜":tn.data.solved.includes(e.id)?"✅":tn.data.carried?.includes(e.id)?"✅↗":tn.tried.has(e.id)?"❌":"⬜",_n=()=>{const e=tn.data,o=ie(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(Zo()?` · 第 ${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(Zo()?" ⏱ 已超时 — 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(Zo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(Zo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(Zo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Zo()?" 带过来,不必重做":" 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(Zo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Zo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(Zo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(Zo()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),kn&&(console.log(chalk.gray(" 0 ")+Tn(ce)+chalk.gray(` ${$n(ce)}`)+chalk.gray(Zo()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+Tn(e)+chalk.white(` ${$n(e)}`))}),console.log(),xn()},xn=()=>{console.log(chalk.gray(Zo()?" /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(Zo()?"/syntax <词>":"/syntax <word>")+chalk.gray(Zo()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(Zo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Zo()?" 返回课程":" returns to the lesson")),console.log()},In=e=>{const o=parseInt(e,10),n=tn.data.problems;if(o===ge&&kn)return{p:ce,n:ge};const t=kn?ge:1;return!Number.isInteger(o)||o<t||o>n.length?(console.log(chalk.yellow(Zo()?` 题号要在 ${t}..${n.length}。`:` Problem number must be ${t}..${n.length}.`)),kn&&console.log(chalk.gray(Zo()?" 0 = 热身题(不计分,证明环境通了)· 1 起是本组正式题目。":" 0 = the warm-up (unscored — proves your setup works) · 1 and up are the real problems.")),null):{p:n[o-1],n:o}};let En=null,Pn=!1;const Sn=e=>{const o=In(e);if(!o)return;const{p:n,n:t}=o;En=String(t),console.log(),console.log(chalk.bold.white(` ${Tn(n)} ${$n(n)}`)),console.log();for(const e of(e=>Zo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of eo(e,Xe()+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(Zo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Zo()?" 应输出:":" 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(Zo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),n.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(Zo()?"本题推荐:":"Recommended here: "))+chalk.bold.white(n.toolkit.join(", ")));const e=Zo()&&n.toolkit_note_zh||n.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of eo(o,Xe()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(n.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(Zo()?"数据就在上方 DATA 块(sol 文件里已赋给 data 变量)— 不用 input(),只 print flag{...} 本身":"The data is the DATA block above (already assigned to `data` in your sol file) — no input(); print ONLY the flag{...} token"))),console.log(),kn&&t===ge)return console.log(chalk.white(Zo()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(Zo()?"第 1 行已经写好了,把第 2 行的 ??? 换掉(vi:i 编辑 · Esc · :wq 存盘退出)":"line 1 is written for you — replace the ??? on line 2 (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green("/run 0".padEnd(11))+chalk.gray(Zo()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(Zo()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((Zo()," ↩ "))+chalk.bold.green("back")+chalk.gray(Zo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(Zo()?" 直接看正式题目":" skips straight to the real problems")),void console.log();console.log(chalk.white(Zo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(Zo()?"写码(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(Zo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(Zo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(Zo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray(Zo()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(Zo()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((Zo()," ↩ "))+chalk.bold.green("back")+chalk.gray(Zo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(Zo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((Zo()," / "))+chalk.bold.green("wide")+chalk.gray(Zo()?" 换语言/宽度":" language / width")),console.log()},jn=async(e,o)=>await new Promise(n=>{const t=process.stdin,s=!!t.isTTY&&!!t.isRaw;if(ko.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const a=r(e,o,{stdio:"inherit",cwd:tn.dir}),i=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&s)try{t.setRawMode(!0)}catch{}l(),ko.resume(),n(e)};a.on("close",()=>i(null)),a.on("error",e=>i(e))}),qn=()=>{console.log(chalk.yellow(Zo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(Zo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(Zo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(Zo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Ln=new Map,Nn=async e=>{const o=e.trim().toLowerCase(),l=No&&o.startsWith("/")?o.slice(1):o;if(Lo)return;if(null!==Io){if(Eo.push(e.replace(/\s+$/,"")),So&&clearTimeout(So),So=null,Po){const e=Eo[Eo.length-1]??"";return"/cancel"===e.trim()?(jo(),console.log(chalk.gray(Zo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Co()):""!==e.trim()?void Co():(Eo.pop(),void await a())}return void(So=setTimeout(()=>{if(So=null,Eo.length>1){Po=!0;const e=Eo.length;return console.log(chalk.cyan(Zo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(Zo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Co()}a()},140))}async function a(){const e=Eo.join("\n").replace(/^\s+|\s+$/g,""),o=Io??po.currentCard,n=Eo.length;if(jo(),""===e)console.log(chalk.gray(Zo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(Zo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(Zo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(Zo()?" 即可执行。":" again to run it."));else{const t=Bo>0?Date.now()-Bo:void 0;if(await E(lo,{curriculum_id:so.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const t=n>1?Zo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(Zo()?` ✓ 已收到${t},谢谢帮助完善这张卡。`:` ✓ Thanks ${t}— your report was recorded.`)),console.log(chalk.gray(Zo()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),uo=[...uo,{id:ho--,curriculumId:so.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Ke(uo)}else console.log(chalk.yellow(Zo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Co()}if(Ro){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Ro=!1,console.log(),console.log(chalk.yellow(Zo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(Zo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(Zo()?" 即可执行该命令。":" again to run it.")),console.log(),void Co();if(!o)return Ro=!1,console.log(chalk.gray(Zo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Co();const n=await Q({token:lo,nickname:o});if(n.ok)Ro=!1,console.log(chalk.bold.green(Zo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(Zo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Oo+=1;const e="taken"===n.code?Zo()?"已被占用":"already taken":"bad_charset"===n.code?Zo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?Zo()?"未通过审核":"did not pass review":n.message||"error";if(!(Oo>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Zo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Co();Ro=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Zo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Co()}if(Fo){Fo=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Lo=!0;try{console.log(),console.log(chalk.gray(Zo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await X({token:lo,cardNumber:po.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Zo()?"评审暂不可用。":"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(Zo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Zo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Zo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Zo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Zo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Zo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=Zo()?` 本卡排名 #${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(Zo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Zo()?` 第 ${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 fn(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Zo()?" 改进提问: ":" 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(` (${Zo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?zo.add(po.currentCard):zo.delete(po.currentCard),"number"==typeof e.rank&&Ko.set(po.currentCard,e.rank);const o=await ee({token:lo,curriculumId:so.id,cardNumber:po.currentCard});o.ok&&o.totals&&o.chapters&&(Ge({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!ao&&(Ro=!0,Oo=0,console.log(chalk.bold.yellow(Zo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Zo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Zo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Lo=!1}})():(console.log(chalk.gray(Zo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==xo&&(console.log(chalk.gray(Zo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Co()}if(Ho)return Ho=!1,yn(),void Co();if(!o)return void Co();if(Do)return"exit"===await d(e.trim())&&(Do=!1),void Co();if(qo){if(["q","quit","exit","back","b","menu"].includes(o))return qo=!1,console.log(chalk.gray(Zo()?" 已退出 🐼 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(Zo()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?Zo()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":Zo()?`「${t}」是卡片命令,不是问题,没有送出去。`:`“${t}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(Zo()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(Zo()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void Co()):(t&&(await pn(t,n?"fast":"deep"),console.log(chalk.gray(Zo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Co())}if(No&&tn){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${tn.phase}s${tn.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return No=!1,console.log(chalk.gray(Zo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),yn(),void Co();if(/^\d+$/.test(o))return Sn(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 O()||Pn||(Pn=!0,console.log(chalk.gray(Zo()?` (离线:只有 ${B()} 条核心速查可用;联网后自动补全)`:` (offline: ${B()} core entries available; the rest arrive when you have a connection)`))),!o)return void F(Zo());const n=D(o);if(n.length){H(n[0],Zo());const e=n.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(Zo()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const t=await W("python3",o);if(t)z(t,Zo());else{if(await Y()){const e=D(o);if(e.length)return void H(e[0],Zo())}console.log(),console.log(chalk.yellow(Zo()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(Zo()?" 试试: ":" Try: ")+chalk.cyan(U(o).join(" · "))),console.log(chalk.gray(Zo()?" /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?_n():o?"read"===e||"open"===e?Sn(o):"edit"===e?await(async e=>{const o=In(e);if(!o)return;const n=C(tn.dir,`sol-${o.n}.py`);if(fe())return be()?(console.log(chalk.yellow(Zo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(Zo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(Zo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(Zo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(Zo()?" ← 不能是 /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(Zo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(Zo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(Zo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(Zo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(Zo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(Zo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(Zo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(Zo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!we("vi"))return console.log(chalk.yellow(Zo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(Zo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(Zo()?" 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 jn("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),rn.set(o.n,$(rn.get(o.n)??w(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(Zo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Zo()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=In(e);if(!o)return;const{p:t,n:r}=o;if(kn&&r===ge)return void(()=>{const e=C(tn.dir,`sol-${ge}.py`);if(!u(e))return void console.log(chalk.yellow(Zo()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=[];for(const t of ue)try{o.push(n("python3",[e],{input:`${t.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}))}catch(e){const o=e;if("ENOENT"===o.code)return void qn();if(console.log(),o.killed)return void console.log(chalk.yellow(Zo()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(Zo()?` ✗ 输入 ${t.in} 时程序报错:`:` ✗ Your program crashed on input ${t.in}:`));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));return console.log(),console.log(chalk.gray(Zo()?" 改完再来: ":" Fix it and rerun: ")+chalk.bold.green("/edit 0")+chalk.gray(" → ")+chalk.bold.green("/run 0")),void console.log()}const{cases:t,passed:r}=ye(o);console.log();for(const e of t)console.log((e.ok?chalk.green(" ✓ "):chalk.red(" ✗ "))+chalk.gray(`n = ${e.in.padEnd(6)} → `)+(e.ok?chalk.cyan(e.got||"(empty)"):chalk.red(e.got||"(empty)"))+(e.ok?"":chalk.gray(Zo()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),r===t.length){const e=vn?null:1;vn=!0,console.log(chalk.bold.green(Zo()?` 🎉 ${r}/${t.length} 全过 — `:` 🎉 ${r}/${t.length} — `)+chalk.white(Zo()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(Zo()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(Zo()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(Zo()?` ${r}/${t.length} 通过 — 还差一点。`:` ${r}/${t.length} passed — not there yet.`)+chalk.gray(Zo()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(Zo()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const l=C(tn.dir,`sol-${r}.py`);if(!u(l))return void console.log(chalk.yellow(Zo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));rn.set(r,v(rn.get(r)??w()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(Zo()?` 本题无样例(设计如此)— 用 /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",stdio:["pipe","pipe","pipe"]})}catch(e){const o=e;if("ENOENT"===o.code)qn();else if(o.killed)console.log(chalk.yellow(Zo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Zo()?" ✗ 程序报错:":" ✗ 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(Zo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Zo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(Zo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Zo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Zo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Zo()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=In(e);if(!o)return;const n=C(tn.dir,`sol-${o.n}.py`);if(!u(n))return void console.log(chalk.yellow(Zo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(Zo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 jn("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(Zo()?" 回到竞技场。":" Back in the arena.")),console.log()):qn()})(o):"recall"===e&&await(async e=>{const o=In(e);if(!o)return;if(!co)return void mn();const{p:n,n:t}=o,r=C(process.cwd(),"icoa-contest"),l=`${so.id}-phase${tn.phase}-g${tn.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(Zo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${tn.phase}-${tn.data.slot}-${t}`,d=Math.min(3,(Ln.get(c)??0)+1);console.log(chalk.gray(Zo()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await J({token:lo,phase:tn.phase,slot:tn.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:d,lang:Zo()?"zh":"en"});if(g.ok){Ln.set(c,d),console.log();for(const e of eo(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(Zo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(Zo()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(Zo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(Zo()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(Zo()?" (花名册: /list)":" (roster: /list)")),void Co()}if("contest"===o||"/contest"===o)return _n(),void Co();const a="lang"===o||/^lang\s+\S+$/.test(o),i=no.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(Zo()?" 竞技场命令: /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(Zo()?" — 或 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(ko.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{}ko.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Co()}if("ai4ioai"===o||"/ai4ioai"===o)return await g()&&(Do=!0),void Co();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!co)return mn(),void Co();Wo||(Wo=!0,console.log(),console.log(chalk.bold.cyan(Zo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Zo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Zo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Zo()||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){qo=!0;const e=on(po.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Zo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(Zo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Zo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Co()}return await pn(t,n?"fast":"deep"),void Co()}if(!No&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!co)return mn(),void Co();const e=on(po.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Zo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Zo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Zo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Zo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Zo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Zo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Zo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Fo=!0,void Co()}const c=!No&&"honors"===Mo&&/^[1-3]$/.test(o);if(!No&&Mo&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(Zo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(Zo()?" ↩ back 回上一层":" ↩ back goes up one level")),void Co();if(!No&&(c||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!co)return mn(),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=>{Lo=!0;try{console.log();const o=await G({token:lo,cardNumber:po.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Zo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&zo.delete(po.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&zo.add(po.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Zo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${po.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${po.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(Zo()?` (第 ${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(Zo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=fn(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(Zo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Mo="view",console.log(chalk.gray((Zo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Zo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Lo=!1}})(n),void Co()}if("/honors"===o||"honors"===o)return ao?(console.log(),console.log(chalk.gray(Zo()?" 荣誉榜属于正式 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 wn(),void Co());if("menu"===o||"menu confirm"===o){if(Qo.length>0&&await Promise.race([Promise.allSettled(Qo),new Promise(e=>setTimeout(e,3e3))]),ko.removeAllListeners("line"),Ao(),wo||!en){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(wo?ko:void 0),Go()}else ko.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===Mo)return await wn(),void Co();if("honors"===Mo)return Mo=null,yn(),void Co();if(Qo.length>0&&await Promise.race([Promise.allSettled(Qo),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${po.streakDays} day(s)`)),console.log(),wo){ko.removeAllListeners("line"),Ao();for(const e of $o)ko.on("line",e);ko.prompt(),Go()}else ko.removeAllListeners("line"),ko.close();return}if(q(o))return yo?to(S(yo,Zo(),Xe(),"T0"===L().tier),!!yo.completedAt):(console.log(chalk.gray(Zo()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void Co();if("status"===o)return De(so,po),void Co();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await _(so.id,lo,!0);return void(e?(Object.assign(so,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),yn()):(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(me().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Co();const n=so.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 pe({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),xo=null,To=null,_o=null,jo(),Ho=!1,Fo=!1,await bn(),void Co()}if(no.has(o)){const e=no.get(o),n=Qe(me()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return Zo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((Zo()?"normal"===e?" 已是标准 64 列。":Xe()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Xe()} 列,上限 ${Ve(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Xe()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Xe()} cols, cap ${Ve(e)}). `)+t(e))),void Co()):(pe({learnWidth:e,learnWide:"normal"!==e}),Je(e),"normal"!==e&&Xe()<=64?(console.log(chalk.yellow(Zo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((Zo()?` 设置已记住(${e},上限 ${Ve(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Ve(e)} cols) and applies once you widen the window. `)+t(e))),void Co()):(console.log(chalk.green(" ✓ ")+chalk.gray((Zo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Xe()} 列,上限 ${Ve(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Xe()} cols, cap ${Ve(e)}). `)+t(e))),xo=null,To=null,_o=null,jo(),Ho=!1,Fo=!1,await bn(),void Co()))}if("sim"===o){const e=on(po.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=A(T(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=po.currentCard,n=po.bookmarks.includes(e),t="bookmark"!==o;return t?po.bookmarks=po.bookmarks.filter(o=>o!==e):n||po.bookmarks.push(e),ke(po),t?console.log(n?chalk.gray(Zo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(Zo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(Zo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(Zo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Co()}const x=N(o);if(x){const e="current"===x.target?po.currentCard:x.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>so.cards.length))return console.log(chalk.yellow(Zo()?` 本课共 ${so.cards.length} 张,请输 r 1–${so.cards.length} 或 r all。`:` This course has ${so.cards.length} cards. Try r 1–${so.cards.length} or r all.`)),console.log(),void Co();for(const o of M(uo,Jo,e,Zo(),Xe()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?uo:uo.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(uo=uo.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Ke(uo),Qo.push(I(lo,{card_number:po.currentCard,event_type:"viewed"},o).catch(()=>{}))),void Co()}if("e"===o)return Io=po.currentCard,console.log(chalk.gray(Zo()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(Zo()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void Co();if("back"===o||"b"===o)return"view"===Mo?(await wn(),void Co()):"honors"===Mo?(Mo=null,yn(),void Co()):(po.currentCard>1&&(po.currentCard-=1),To=null,_o=null,xo=null,ke(po),yn(),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(!ln)return console.log(chalk.yellow(Zo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Co();if(!e){const e=await le(lo),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(Zo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(Zo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(Zo()?` 这台电脑上有 ${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(Zo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(Zo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(Zo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(Zo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(Zo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(Zo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(Zo()?" 只能关联你在这台电脑上用的 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 re(lo,Number(e));return o.ok&&o.data?(Cn(o.data),await sn(),void Co()):(console.log(chalk.red(` ✗ ${o.message||(Zo()?"关联失败":"Link failed")}`)),void Co())}const n=await se(lo,e);return n.ok&&n.data?(Cn(n.data),await sn(),void Co()):(console.log(chalk.red(` ✗ ${n.message||(Zo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(Zo()?" 换设备了?请联系协调员释放绑定后再试。":" 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(!ln)return console.log(chalk.yellow(Zo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Co();const e=an(po.currentCard);if("contest reset"===o){const o=await oe(lo,e);if(o.ok){console.log(chalk.yellow(Zo()?` 已放弃当前计时(阶段 ${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",`${so.id}-phase${e}-g${n}`);if(u(t))try{p(t,`${t}-archived-${o}`),console.log(chalk.gray(Zo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(Zo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(Zo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),tn=null,No=!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(Zo()?" 连接判分赛…":" Contacting contest server…"));const t=await ne(lo,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(Zo()?` 本阶段(${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",`${so.id}-phase${e}-g${r.slot}`);y(l,{recursive:!0});const s=tn&&tn.phase===e&&tn.data.slot===r.slot?tn.tried:new Set;tn={phase:e,dir:l,data:r,tried:s},((e,o)=>{[...kn?[{p:ce,n:ge}]:[],...e.problems.map((e,o)=>({p:e,n:o+1}))].forEach(({p:n,n:t})=>{const r=kn&&t===ge,l=(n.samples??[])[0];l&&b(C(o,`sample-${t}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=C(o,`sol-${t}.py`);if(u(s))return;const a=[r?`# ══ ${n.title} ══`:`# ══ ${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 ${t} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${t}.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","#"),r||a.push("# ── toolkit ──",...e.toolkit_available?.length?[`# Available on the judge: ${e.toolkit_available.join(", ")}`]:["# The judge runs the Python standard library only."],...e.toolkit_available?.includes("chepy")?["# from chepy import Chepy — chain ops on the DATA block;","# /syntax chepy = op index · plain stdlib always works too."]:["# 'array', 'bisect', 'heapq' and sys.stdin.buffer.read() are the","# standard speed-ups; none is ever required to solve a problem."]),n.toolkit?.length&&(a.push(`# Recommended for THIS problem: ${n.toolkit.join(", ")}`),n.toolkit_note))for(const e of n.toolkit_note.split("\n"))for(const o of eo(e,68))a.push(`# ${o}`);const i=/\nDATA\n----\n([\s\S]+)$/.exec(n.statement??"");i?a.push("#","# No input() on this one — the DATA block is already assigned below.","# Compute, then print() ONLY the flag{...} token — nothing around it.",`# In icoa: /debug ${t} = free run · /submit ${t} = judge`,"",'data = """',...i[1].trim().split("\n"),'""".strip()',"",""):r?a.push("# Your first program. Line 1 is written for you: it reads the number.","# Replace the ??? on line 2 with the arithmetic, then :wq and /run 0.","","n = int(input())","print(???)",""):a.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${t} = sample self-check · /debug ${t} = free-input run · /submit ${t} = judge`,"",""),b(s,a.join("\n"))})})(r,l),No=!0,_n(),console.log(chalk.gray(Zo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1,i=kn&&!vn?ge:a;return console.log(chalk.white(Zo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${i}`)+chalk.gray(i===ge?Zo()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":Zo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Co()}if("submit"===l)return console.log(chalk.yellow(Zo()?" 用法: ":" Usage: ")+chalk.bold.green(Zo()?"submit <题号>":"submit <n>")+chalk.gray(Zo()?" 例如 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)")),tn||console.log(chalk.gray(Zo()?" 还没开赛 — 先输入 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(!tn)return console.log(chalk.yellow(Zo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Co();const t=tn.data.problems,r=parseInt(o,10);if(kn&&r===ge)return console.log(chalk.gray(Zo()?" 热身题不判分 — /run 0 就是它的完整判定(10 个用例全在本机)。":" The warm-up is not judged — /run 0 IS its full check (all ten cases, on your machine).")),console.log(chalk.white(Zo()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(Zo()?" 开始。":".")),void Co();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(Zo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Co();const s=t.findIndex(e=>e.id===o)+1,a=n||C(tn.dir,`sol-${s}.py`);let c;try{c=m(a,"utf-8")}catch{return console.log(chalk.red(Zo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Co()}const d=new i(lo);d.start();const g=rn.get(s),u=await te(lo,tn.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(Zo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((Zo()," "))+chalk.bold.green("contest")+chalk.gray(Zo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(Zo()?" 满血重开计时。":" 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(Zo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===y.verdict)console.log(chalk.bold.green(Zo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${y.passed_tests??y.total_tests??"?"}/${y.total_tests??"?"} `+(Zo()?"隐藏用例全过":"hidden tests passed")+` · ${y.time_ms??"?"}ms`)),tn.data.solved.includes(o)||tn.data.solved.push(o),tn.tried.delete(o);else{tn.tried.add(o);const e="TLE"===y.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${y.verdict}`)+chalk.gray(y.test?Zo()?` · 挂在第 ${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(Zo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const h=ie(y.deadline||"");if(console.log(chalk.white(Zo()?` 本组进度: 已过 ${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(Zo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await sn();else if(!y.late){const e=t.findIndex(e=>!tn.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Zo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${$n(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>so.totalCards)return console.log(chalk.yellow(` Card number must be 1..${so.totalCards}. Try: `)+chalk.bold.green("card 1")),void Co();const t=await dn(n);return t?(console.log(t),void Co()):(po.currentCard=n,To=null,_o=null,xo=null,ke(po),yn(),void Co())}if(null!==xo&&["y","yes","n","no"].includes(o)){const e=on(xo);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-Bo;Te(po,e.number),xe(po,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),ke(po);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),Qo.push(I(lo,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),xo=null,e.solution&&e.solution.length>0)return void Co();if(po.currentCard<so.totalCards){const e=po.currentCard,o=await dn(e+1);if(o)return await gn(e),console.log(o),void Co();po.currentCard+=1,ke(po),await gn(e)?un():yn(),Co()}else Ue(so,po),Co();return}}if(null!==To&&["a","b","c","d"].includes(o)){const e=on(To);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(_e(po,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),Te(po,e.number),ke(po),qe(e,n,t,po),Qo.push(I(lo,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),To=null,t)if(po.currentCard<so.totalCards){const e=await dn(po.currentCard+1);if(e)return console.log(e),void Co();po.currentCard+=1,ke(po),yn()}else Ue(so,po),Co();else Co();return}}if(null!==_o){if("done"===o){const e=on(_o);if(e&&"practical"===e.type)return Ie(po,e.number),Te(po,e.number),ke(po),Ne(e),_o=null,void Co()}if("skip"===o)return Te(po,_o),ke(po),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),_o=null,void Co()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==To)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Co();if(null!==_o)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!==xo)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=po.currentCard,o=e<so.totalCards?await dn(e+1):null;return o?(await gn(e),console.log(o),void Co()):(po.currentCard+=1,ke(po),po.currentCard>so.totalCards?Ue(so,po):await gn(e)?un():yn(),void Co())}return null!==xo?(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!==To?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Co()):null!==_o?(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"===Mo?console.log(chalk.gray(Zo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(Zo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(Zo()?" 回卡片":" to the card")):"honors"===Mo?console.log(chalk.gray(Zo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(Zo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(Zo()?" 回卡片":" 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())};ko.on("line",e=>{Nn(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()})}),wo||ko.on("close",async()=>{Qo.length>0&&await Promise.race([Promise.allSettled(Qo),new Promise(e=>setTimeout(e,5e3))]),en?Go():process.exit(0)});const Mn=R(uo,Zo());Mn&&(console.log(chalk.bold.cyan(` ${Mn}`)),console.log());try{yn(),Co();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(oo("Could not render this card — the curriculum may be malformed."),wo){ko.removeAllListeners("line"),Ao();for(const e of $o)ko.on("line",e);ko.prompt()}else ko.close();Go()}await Xo}),ro.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await _(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
|
1
|
+
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{rearmFocusMode as l}from"../lib/input-dynamics.js";import{logCommand as s}from"../lib/logger.js";import{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 p,renameSync as m,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 _}from"node:path";import{fileURLToPath as C}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{hometaskDetailLines as P,hometaskLines as j,isTaskCommand as q}from"../lib/learn-hometask.js";import{detectCaps as M}from"../lib/render-card.js";import{parseReplyCommand as N,renderReplyLines as L,replyPushLine as O}from"../lib/learn-replies.js";import{ensureFullTable as R,lookupPydoc as W,lookupRanked as D,refetchTableOnMiss as Y,nearKeys as U,renderIndex as F,renderPydoc as z,renderSyntax as B,tableSize as H}from"../lib/py-syntax.js";import{normalizeTokenBody as Z}from"../lib/token-format.js";import{fetchMyScores as K,recallCoach as J,setNickname as Q,streamLearnTutor as V,submitPqs as X,viewPqsTop as G,viewHonors as ee}from"../lib/learn-ai.js";import{contestReset as oe,contestStart as te,contestSubmit as ne,linkByIndex as re,linkSuggest as le,linkToken as se,fetchGate as ae,timeLeft as ie}from"../lib/learn-contest.js";import{WARMUP as ce,WARMUP_ID as de,WARMUP_N as ge,WARMUP_TESTS as ue,gradeWarmup as ye,warmupEnabled as he}from"../lib/warmup.js";import{getConfig as pe,saveConfig as me}from"../lib/config.js";import{isNativeWindows as fe,isWindowsBuildInWslShell as be,whichBinary as we}from"../lib/platform.js";import{loadLearnState as $e,saveLearnState as ke,newLearnState as ve,activateSession as Ae,updateStreak as _e,markCardComplete as Ce,recordMCQ as Te,recordCheck as xe,markPracticalComplete as Ie,addAchievement as Ee}from"../lib/learn-state.js";import{renderWelcome as Se,renderKnowledgeCard as Pe,renderMCQCard as je,renderMCQFeedback as qe,renderPracticalCard as Me,renderPracticalSuccess as Ne,renderSimDemoCard as Le,renderMilestone as Oe,renderArenaTaskCard as Re,renderComingSoonCard as We,renderStatus as De,renderPhaseComplete as Ye,renderCurriculumComplete as Ue,setLearnAiEnabled as Fe,setLearnFaqs as ze,setLearnHometask as Be,setLearnHonorRanks as He,setLearnPqsViewCards as Ze,setLearnReplies as Ke,setLearnWidth as Je,resolveLearnWidth as Qe,learnWidthCap as Ve,learnW as Xe,renderHonorWall as Ge,wrapMixed as eo}from"../lib/learn-render.js";import{printError as oo}from"../lib/ui.js";const to=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);function no(e,o){e.forEach((t,n)=>{const r=n===e.length-1;0===n?console.log(chalk.bold.cyan(` ${t}`)):/^[─-]+$/.test(t.trim())&&t.trim().length>3?console.log(chalk.gray(` ${t}`)):r?console.log((o?chalk.bold.green:chalk.yellow)(` ${t}`)):console.log(chalk.white(` ${t}`))}),console.log()}export function registerLearnCommand(ro){ro.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ro=>{ro?.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(),ro="LEARNDEMO01");let lo=ro.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(lo)){const{runSprint:e}=await import("./sprint.js");return void await e()}let so=null;const ao=/^[A-Z0-9]+DEMO01$/i.test(lo),io=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(lo);let co=!1,go=!1,uo=[],yo=null,ho=-1,po=Promise.resolve([]);if(ao)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),po=S(lo),so=await T(lo,lo,!0);else if(io){console.log(),console.log(chalk.gray(" Validating token..."));let e=await x(lo);if(!e.ok){const o=Z(lo);if(o!==lo){const t=await x(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${lo} → ${o}`)),e=t,lo=o)}}if(!e.ok)return oo(`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 🐼"):"")),co=!0===e.aiEnabled,go=!0===e.gated,uo=e.replies??[],yo=e.hometask??null,po=S(lo),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),so=await T(e.curriculumId||"LEARNDEMO01",lo,!0),!so)return oo(`Could not open a learn curriculum for token '${lo}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${lo}`)+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 ${lo}`)+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(!so){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(oo(`Could not reach the learn server to open ${lo}.`),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 ${lo}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(oo(`Unknown learn token: ${lo}`),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 mo=$e(),fo=!1;try{if(mo&&mo.token===lo)_e(mo);else{const e=Ae(lo);e?(mo=e,mo.totalCards=so.totalCards,_e(mo)):(mo=ve(lo,so.id,so.totalCards),fo=!0)}ke(mo),Se(so,mo,fo),function(e){if(!e)return;const o=(pe().language||"en").toLowerCase().startsWith("zh"),t="T0"===M().tier;no(j(e,o,Xe(),t),!!e.completedAt)}(yo)}catch{return oo("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 ${lo}`)+chalk.gray(".")),void console.log()}const bo=a(),wo=null!==bo,$o=wo?bo.listeners("line").slice():[];wo&&bo.removeAllListeners("line");const ko=wo?bo:o({input:process.stdin,output:process.stdout,terminal:!0}),vo=wo?ko.prompt:null;wo&&(ko.prompt=e.prototype.prompt);const Ao=()=>{wo&&vo&&(ko.prompt=vo)},_o=()=>{ko.setPrompt(Do?chalk.bold.green(`icoa ${c()}> `):No?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(qo?"icoa learn ai> ":"icoa learn> ")),ko.prompt()};let Co=null,To=null,xo=null,Io=null,Eo=[],So=!1,Po=null;const jo=()=>{Po&&clearTimeout(Po),Po=null,Eo=[],So=!1,Io=null};let qo=!1,Mo=!1,No=!1,Lo=null,Oo=!1,Ro=0,Wo=!1,Do=!1;const Yo=new Map,Uo=()=>{let e=Yo.get(mo.currentCard);return e||(e=[],Yo.set(mo.currentCard,e)),e};let Fo=!1;const zo=new Set;let Bo=!1,Ho=0;const Zo=()=>(pe().language||"en").toLowerCase().startsWith("zh");Fe(co),Je(Qe(pe())),Ze(zo);const Ko=new Map;He(Ko),Ke(uo),Be(yo);const Jo=await po;ze(Jo);const Qo=[];let Vo=null;const Xo=new Promise(e=>{Vo=e}),Go=()=>{const e=Vo;Vo=null,e?.()},et="1"===process.env.ICOA_LEARN_EMBEDDED,ot=e=>so.cards.find(o=>o.number===e);let tt=null,nt=null;const rt=new Map,lt=!lo.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(lo),st=async()=>{if(!lt)return;const e=await ae(lo);e.ok&&e.data&&(tt=e.data)},at=e=>{const o=so.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},it=e=>{if(!go||!tt)return null;const o=at(e);if(o<=tt.unlocked_through_phase)return null;const t=tt.phases.find(e=>e.phase===tt.unlocked_through_phase),n=[chalk.yellow(Zo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${tt.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${tt.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(Zo()?` ⚔ 练习赛 ${tt.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${tt.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(Zo()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}if(t?.checks?.enabled&&!t.checks.passed){const e=t.checks.missing??[],o=e.slice(0,8).join(Zo()?"、":", "),r=e.length>8?Zo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:Zo()?" 张":"";n.push(chalk.gray(Zo()?` ✓ 逐卡自测: ${t.checks.good}/${t.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${t.checks.good}/${t.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return t?.research&&!t.research.passed&&n.push(chalk.gray(Zo()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},ct=async e=>go?null===it(e)?null:(await st(),it(e)):null;lt&&await st();const dt=async e=>{const o=so.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=so.modules.find(e=>e.number===o.number+1);let n;if(co){const e=await K({token:lo,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}lt&&await st();const r=tt?.phases.find(e=>e.phase===o.number);return Ye(so,mo,o,t,n,r),!0},gt=()=>{Bo=!0,console.log(chalk.gray(Zo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},ut=()=>{Lo=null;const e=ot(mo.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":Pe(e,so),e.check?(xo=e.number,Ho=Date.now()):(Ce(mo,e.number),ke(mo));break;case"mcq":je(e,so),Co=e.number;break;case"practical":Me(e,so),To=e.number;break;case"sim_demo":Le(e,so),Ce(mo,e.number),ke(mo);break;case"milestone":Oe(e,so),Ee(mo,e.badge),Ce(mo,e.number),ke(mo);break;case"arena_task":Re(e,so),Ce(mo,e.number),ke(mo);break;case"coming_soon":We(e,so),Ce(mo,e.number),ke(mo)}yt(e.number),Pt(e)},yt=e=>{if(!lt||!tt)return;const o=so.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1;if(t%4!=0)return;const n=t/4,r=tt.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===n);if(!l)return;const s=(e,o,t,n)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const t=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${t(o.getMonth()+1)}-${t(o.getDate())} ${t(o.getHours())}:${t(o.getMinutes())}`})(n);return`🏆 ${e} ${o}/${l.n}`+(r?Zo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Xe());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${Zo()?`练习赛 ${o.number}-${n}`:l.title||`PY Arena ${o.number}-${n}`}`)+(l.passed?chalk.bold.green(Zo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(Zo()?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(Zo()?`${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(Zo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Zo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(Zo()?"✍ 第一次用 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(Zo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(Zo()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(l.passed?chalk.gray(Zo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Zo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(Zo()?" 继续学习":" keep going"):chalk.gray(Zo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(Zo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},ht=()=>{lo.endsWith("DEMO01")?console.log(chalk.yellow(Zo()?" 🐼 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(Zo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(Zo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},pt=async(e,o)=>{if(co){Mo=!0;try{console.log(),console.log(chalk.gray("deep"===o?Zo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":Zo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await V({token:lo,cardNumber:mo.currentCard,question:e,mode:o,history:Uo().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(Zo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Uo().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(` (${Zo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Zo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==xo&&console.log(chalk.gray(Zo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Mo=!1}}else ht()},mt=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],ft=async()=>{No&&nt?Nt?Ot(Nt):jt():Lo?await bt():ut()},bt=async()=>{Mo=!0;try{console.log();const e=await ee({token:lo,curriculumId:so.id,cardNumber:mo.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Zo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Zo()?` 🏆 本卡实时 Top-3 — 第 ${mo.currentCard} 张`:` 🏆 Live top-3 — card ${mo.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(Zo()?" (你)":" (you)"):""))}else console.log(chalk.gray(Zo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Ko.set(mo.currentCard,e.mine.rank),console.log(chalk.white(Zo()?" 你: ":" You: ")+chalk.bold.yellow(Zo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Zo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):co&&console.log(chalk.gray(Zo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ge({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Zo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Zo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Zo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Lo="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Zo()?" 返回卡片":" returns to the card")),console.log()}finally{Mo=!1}},wt=e=>Zo()&&e.title_zh||e.title,$t=he(so.id);let kt=!1;const vt=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of eo(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},At=(e,o)=>{[...$t?[{p:ce,n:ge}]:[],...e.problems.map((e,o)=>({p:e,n:o+1}))].forEach(({p:t,n:n})=>{const r=$t&&n===ge,l=(t.samples??[])[0];l&&b(_(o,`sample-${n}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=_(o,`sol-${n}.py`);if(u(s))return;const a=[r?`# ══ ${t.title} ══`:`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...vt(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${n} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${n}.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","#"),r||a.push("# ── toolkit ──",...e.toolkit_available?.length?[`# Available on the judge: ${e.toolkit_available.join(", ")}`]:["# The judge runs the Python standard library only."],...e.toolkit_available?.includes("chepy")?["# from chepy import Chepy — chain ops on the DATA block;","# /syntax chepy = op index · plain stdlib always works too."]:["# 'array', 'bisect', 'heapq' and sys.stdin.buffer.read() are the","# standard speed-ups; none is ever required to solve a problem."]),t.toolkit?.length&&(a.push(`# Recommended for THIS problem: ${t.toolkit.join(", ")}`),t.toolkit_note))for(const e of t.toolkit_note.split("\n"))for(const o of eo(e,68))a.push(`# ${o}`);const i=/\nDATA\n----\n([\s\S]+)$/.exec(t.statement??"");i?a.push("#","# No input() on this one — the DATA block is already assigned below.","# Compute, then print() ONLY the flag{...} token — nothing around it.",`# In icoa: /debug ${n} = free run · /submit ${n} = judge`,"",'data = """',...i[1].trim().split("\n"),'""".strip()',"",""):r?a.push("# Your first program. Line 1 is written for you: it reads the number.","# Replace the ??? on line 2 with the arithmetic, then :wq and /run 0.","","n = int(input())","print(???)",""):a.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${n} = sample self-check · /debug ${n} = free-input run · /submit ${n} = judge`,"",""),b(s,a.join("\n"))})},_t=e=>{console.log(),console.log(chalk.bold.green(Zo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(Zo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Ct=e=>e.id===de?kt?"✅":"⬜":nt.data.solved.includes(e.id)?"✅":nt.data.carried?.includes(e.id)?"✅↗":nt.tried.has(e.id)?"❌":"⬜",Tt=100,xt=()=>!!nt&&nt.data.slot>=Tt,It=new Map,Et=e=>`ref:${Buffer.from(e,"utf-8").toString("base64")}`,St=e=>{const o=e?.practice;return o&&Array.isArray(o.problems)&&0!==o.problems.length?[...o.problems.filter(e=>e.is_signature),...o.problems.filter(e=>!e.is_signature).sort((e,o)=>(e.difficulty??0)-(o.difficulty??0)||(e.order??0)-(o.order??0))]:null},Pt=e=>{const o=St(e);if(!o)return;const t=e.practice?.per_problem_minutes??20,n=It.get(Tt+e.number);console.log(chalk.bold.yellow(Zo()?" ⚔ 本卡练习题":" ⚔ Practice problems for this card")+chalk.gray(Zo()?` — 每题 ${t} 分钟 · 不计分`:` — ${t} min each · unscored`)),o.forEach((e,o)=>{const t=n?.has(Et(e.py_id))||n?.has(e.py_id)?"✅":"⬜",r=e.is_signature?"🎯":e.is_hardest?"🔥":" ",l="·".repeat(Math.min(5,Math.max(1,Math.round(e.difficulty??1))));console.log(`${chalk.gray(` ${String(o+1).padStart(2)} `)}${t} ${r} ${chalk.white(l.padEnd(5))}`)}),console.log(chalk.gray(" ▸ ")+chalk.bold.green("practice 1")+chalk.gray(Zo()?` 进第 1 题(practice <1-${o.length}> 任选 · 🎯 本卡招牌题 · 🔥 最难 · 点越多越难)`:` opens problem 1 (any of practice <1-${o.length}> · 🎯 signature · 🔥 hardest · more dots = harder)`)),console.log()},jt=()=>{const e=nt.data,o=ie(e.deadline),t=(e.carried??[]).filter(o=>!e.solved.includes(o)),n=e.solved.length+t.length,r=Math.min(20,Math.round(n/Math.max(1,e.need)*20));console.log();const l=e.slot>=Tt?e.slot-Tt:null;console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(null!=l?Zo()?` · 第 ${l} 张卡的练习(不计分) · 第 ${e.attempt} 次${e.resumed?"(续)":""}`:` · card ${l} practice (unscored) · attempt ${e.attempt}${e.resumed?" (resumed)":""}`:Zo()?` · 第 ${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(Zo()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${n}/${e.need} AC`)+chalk.gray(Zo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),t.length>0&&console.log(chalk.cyan(` ✅↗ ${t.length}`)+chalk.gray(Zo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(Zo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(Zo()?" 带过来,不必重做":" to carry them over instead of redoing them"));const s=Date.parse(e.deadline)-Date.now();o?e.resumed&&s<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(Zo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Zo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(Zo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(Zo()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),$t&&(console.log(chalk.gray(" 0 ")+Ct(ce)+chalk.gray(` ${wt(ce)}`)+chalk.gray(Zo()?" — 不计分":" — unscored")),console.log(chalk.gray(" ─────"))),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+Ct(e)+chalk.white(` ${wt(e)}`))}),console.log(),qt()},qt=()=>{console.log(chalk.gray(Zo()?" /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(Zo()?"/syntax <词>":"/syntax <word>")+chalk.gray(Zo()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(Zo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Zo()?" 返回课程":" returns to the lesson")),console.log()},Mt=e=>{const o=parseInt(e,10),t=nt.data.problems;if(o===ge&&$t)return{p:ce,n:ge};const n=$t?ge:1;return!Number.isInteger(o)||o<n||o>t.length?(console.log(chalk.yellow(Zo()?` 题号要在 ${n}..${t.length}。`:` Problem number must be ${n}..${t.length}.`)),$t&&console.log(chalk.gray(Zo()?" 0 = 热身题(不计分,证明环境通了)· 1 起是本组正式题目。":" 0 = the warm-up (unscored — proves your setup works) · 1 and up are the real problems.")),null):{p:t[o-1],n:o}};let Nt=null,Lt=!1;const Ot=e=>{const o=Mt(e);if(!o)return;const{p:t,n:n}=o;Nt=String(n),console.log(),console.log(chalk.bold.white(` ${Ct(t)} ${wt(t)}`)),console.log();for(const e of(e=>Zo()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of eo(e,Xe()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(Zo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Zo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}if(0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(Zo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),t.toolkit?.length){console.log(),console.log(chalk.yellow(" 🧭 "+(Zo()?"本题推荐:":"Recommended here: "))+chalk.bold.white(t.toolkit.join(", ")));const e=Zo()&&t.toolkit_note_zh||t.toolkit_note;if(e)for(const o of e.split("\n"))for(const e of eo(o,Xe()))console.log(chalk.gray(` ${e}`))}if(/\nDATA\n----\n/.test(t.statement??"")&&(console.log(),console.log(chalk.yellow(" ▸ ")+chalk.white(Zo()?"数据就在上方 DATA 块(sol 文件里已赋给 data 变量)— 不用 input(),只 print flag{...} 本身":"The data is the DATA block above (already assigned to `data` in your sol file) — no input(); print ONLY the flag{...} token"))),console.log(),$t&&n===ge)return console.log(chalk.white(Zo()?" 两步:":" Two steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green("/edit 0".padEnd(11))+chalk.gray(Zo()?"第 1 行已经写好了,把第 2 行的 ??? 换掉(vi:i 编辑 · Esc · :wq 存盘退出)":"line 1 is written for you — replace the ??? on line 2 (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green("/run 0".padEnd(11))+chalk.gray(Zo()?"本机跑全部 10 个用例 — 这就是完整判定":"runs all ten cases locally — that is the whole check")),console.log(),console.log(chalk.gray(Zo()?" 这道题不计分,也不上榜 — 它只用来证明:你能在终端里写 Python 并让它跑起来。":" Unscored, unranked — it exists only to prove you can write Python here and run it.")),console.log(),console.log(chalk.gray((Zo()," ↩ "))+chalk.bold.green("back")+chalk.gray(Zo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/read 1")+chalk.gray(Zo()?" 直接看正式题目":" skips straight to the real problems")),void console.log();console.log(chalk.white(Zo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Zo()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(Zo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(Zo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Zo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray(Zo()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(Zo()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((Zo()," ↩ "))+chalk.bold.green("back")+chalk.gray(xt()?Zo()?" 回花名册 · ":" to the roster · ":Zo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(Zo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((Zo()," / "))+chalk.bold.green("wide")+chalk.gray(Zo()?" 换语言/宽度":" language / width")),console.log()},Rt=async(e,o)=>await new Promise(t=>{const n=process.stdin,s=!!n.isTTY&&!!n.isRaw;if(ko.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const a=r(e,o,{stdio:"inherit",cwd:nt.dir}),i=e=>{if(n.isTTY&&"function"==typeof n.setRawMode&&s)try{n.setRawMode(!0)}catch{}l(),ko.resume(),t(e)};a.on("close",()=>i(null)),a.on("error",e=>i(e))}),Wt=()=>{console.log(chalk.yellow(Zo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(Zo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(Zo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(Zo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Dt=new Map,Yt=async e=>{const o=e.trim().toLowerCase(),l=No&&o.startsWith("/")?o.slice(1):o;if(Mo)return;if(null!==Io){if(Eo.push(e.replace(/\s+$/,"")),Po&&clearTimeout(Po),Po=null,So){const e=Eo[Eo.length-1]??"";return"/cancel"===e.trim()?(jo(),console.log(chalk.gray(Zo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void _o()):""!==e.trim()?void _o():(Eo.pop(),void await a())}return void(Po=setTimeout(()=>{if(Po=null,Eo.length>1){So=!0;const e=Eo.length;return console.log(chalk.cyan(Zo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(Zo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void _o()}a()},140))}async function a(){const e=Eo.join("\n").replace(/^\s+|\s+$/g,""),o=Io??mo.currentCard,t=Eo.length;if(jo(),""===e)console.log(chalk.gray(Zo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(Zo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(Zo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(Zo()?" 即可执行。":" again to run it."));else{const n=Ho>0?Date.now()-Ho:void 0;if(await E(lo,{curriculum_id:so.id,card_number:o,feedback_text:e,time_on_card_ms:n})){const n=t>1?Zo()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(Zo()?` ✓ 已收到${n},谢谢帮助完善这张卡。`:` ✓ Thanks ${n}— your report was recorded.`)),console.log(chalk.gray(Zo()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),uo=[...uo,{id:ho--,curriculumId:so.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Ke(uo)}else console.log(chalk.yellow(Zo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),_o()}if(Oo){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Oo=!1,console.log(),console.log(chalk.yellow(Zo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(Zo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(Zo()?" 即可执行该命令。":" again to run it.")),console.log(),void _o();if(!o)return Oo=!1,console.log(chalk.gray(Zo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void _o();const t=await Q({token:lo,nickname:o});if(t.ok)Oo=!1,console.log(chalk.bold.green(Zo()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Zo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Ro+=1;const e="taken"===t.code?Zo()?"已被占用":"already taken":"bad_charset"===t.code?Zo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?Zo()?"未通过审核":"did not pass review":t.message||"error";if(!(Ro>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Zo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void _o();Oo=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Zo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void _o()}if(Fo){Fo=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Mo=!0;try{console.log(),console.log(chalk.gray(Zo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await X({token:lo,cardNumber:mo.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Zo()?"评审暂不可用。":"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(Zo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Zo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Zo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Zo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Zo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Zo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=Zo()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(Zo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Zo()?` 第 ${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 mt(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Zo()?" 改进提问: ":" 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(` (${Zo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?zo.add(mo.currentCard):zo.delete(mo.currentCard),"number"==typeof e.rank&&Ko.set(mo.currentCard,e.rank);const o=await ee({token:lo,curriculumId:so.id,cardNumber:mo.currentCard});o.ok&&o.totals&&o.chapters&&(Ge({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!ao&&(Oo=!0,Ro=0,console.log(chalk.bold.yellow(Zo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Zo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Zo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Mo=!1}})():(console.log(chalk.gray(Zo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==xo&&(console.log(chalk.gray(Zo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void _o()}if(Bo)return Bo=!1,ut(),void _o();if(!o)return void _o();if(Do)return"exit"===await d(e.trim())&&(Do=!1),void _o();if(qo){if(["q","quit","exit","back","b","menu"].includes(o))return qo=!1,console.log(chalk.gray(Zo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void _o();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim(),r=/^(\/?(submit|read|edit|run|debug|list|honors|recall|view|ai|syntax|contest|practice|practise)\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(n),l=n.length>0&&!/[\p{L}\p{N}]/u.test(n);return r||l?(console.log(),console.log(chalk.yellow(Zo()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?Zo()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":Zo()?`「${n}」是卡片命令,不是问题,没有送出去。`:`“${n}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(Zo()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(Zo()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void _o()):(n&&(await pt(n,t?"fast":"deep"),console.log(chalk.gray(Zo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void _o())}if(No&&nt){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${nt.phase}s${nt.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return xt()&&null!==Nt?(Nt=null,jt(),void _o()):(No=!1,Nt=null,console.log(chalk.gray(Zo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),ut(),void _o());if(/^\d+$/.test(o))return Ot(o),void _o();const n=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(n)return xt()?n[1]?Ot(n[1]):jt():console.log(chalk.gray(Zo()?" practice 是卡片练习的入口 — 先 back 回课程,再在有练习的卡片上使用。":" practice belongs to the lesson cards — type back first, then use it on a card that lists practice problems.")),void _o();const r=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(r)return await(async e=>{const o=e.trim();if(await R()||Lt||(Lt=!0,console.log(chalk.gray(Zo()?` (离线:只有 ${H()} 条核心速查可用;联网后自动补全)`:` (offline: ${H()} core entries available; the rest arrive when you have a connection)`))),!o)return void F(Zo());const t=D(o);if(t.length){B(t[0],Zo());const e=t.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(Zo()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const n=await W("python3",o);if(n)z(n,Zo());else{if(await Y()){const e=D(o);if(e.length)return void B(e[0],Zo())}console.log(),console.log(chalk.yellow(Zo()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(Zo()?" 试试: ":" Try: ")+chalk.cyan(U(o).join(" · "))),console.log(chalk.gray(Zo()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log()}})(r[1]??""),void _o();const a=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(a){const[,e,o]=a;return"list"===e?jt():o?"read"===e||"open"===e?Ot(o):"edit"===e?await(async e=>{const o=Mt(e);if(!o)return;const t=_(nt.dir,`sol-${o.n}.py`);if(fe())return be()?(console.log(chalk.yellow(Zo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(Zo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(Zo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(Zo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(Zo()?" ← 不能是 /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(Zo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(Zo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(Zo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(Zo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(Zo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(Zo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(Zo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(Zo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log());if(!we("vi"))return console.log(chalk.yellow(Zo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(Zo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(Zo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const n=e=>{try{return f(e).size}catch{return 0}},r=n(t),l=Date.now();await Rt("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),rt.set(o.n,$(rt.get(o.n)??w(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:n(t)})),console.log(chalk.gray(Zo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Zo()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=Mt(e);if(!o)return;const{p:n,n:r}=o;if($t&&r===ge)return void(()=>{const e=_(nt.dir,`sol-${ge}.py`);if(!u(e))return void console.log(chalk.yellow(Zo()?" 还没有 sol-0.py — 先 /edit 0。":" No sol-0.py yet — /edit 0 first."));const o=[];for(const n of ue)try{o.push(t("python3",[e],{input:`${n.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}))}catch(e){const o=e;if("ENOENT"===o.code)return void Wt();if(console.log(),o.killed)return void console.log(chalk.yellow(Zo()?" ⏱ 超过 10 秒 — 检查死循环。":" ⏱ Over 10s — check for an infinite loop."));console.log(chalk.red(Zo()?` ✗ 输入 ${n.in} 时程序报错:`:` ✗ Your program crashed on input ${n.in}:`));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`));return console.log(),console.log(chalk.gray(Zo()?" 改完再来: ":" Fix it and rerun: ")+chalk.bold.green("/edit 0")+chalk.gray(" → ")+chalk.bold.green("/run 0")),void console.log()}const{cases:n,passed:r}=ye(o);console.log();for(const e of n)console.log((e.ok?chalk.green(" ✓ "):chalk.red(" ✗ "))+chalk.gray(`n = ${e.in.padEnd(6)} → `)+(e.ok?chalk.cyan(e.got||"(empty)"):chalk.red(e.got||"(empty)"))+(e.ok?"":chalk.gray(Zo()?` 应为 ${e.expected}`:` expected ${e.expected}`)));if(console.log(),r===n.length){const e=kt?null:1;kt=!0,console.log(chalk.bold.green(Zo()?` 🎉 ${r}/${n.length} 全过 — `:` 🎉 ${r}/${n.length} — `)+chalk.white(Zo()?"你刚在终端里写了一个 Python 程序,并且它跑对了。":"you just wrote a Python program in a terminal and it ran correctly.")),console.log(chalk.gray(Zo()?" 注意最后两个:答案超过 40 亿。Python 的整数没有上限 — 不会溢出。":" Look at the last two: the answers pass 4 billion. Python integers never overflow.")),e&&(console.log(),console.log(chalk.white(Zo()?" ▸ 正式题目从这里开始: ":" ▸ The real problems start here: ")+chalk.bold.green(`/read ${e}`)))}else console.log(chalk.yellow(Zo()?` ${r}/${n.length} 通过 — 还差一点。`:` ${r}/${n.length} passed — not there yet.`)+chalk.gray(Zo()?" 再看一眼样例: 3 排 → 每排 4 把 → 12。":" Re-read the sample: 3 rows → 4 each → 12.")),console.log(chalk.gray(" ▸ ")+chalk.bold.green("/edit 0")+chalk.gray(Zo()?" 改完再 /run 0。":" then /run 0 again."));console.log()})();const l=_(nt.dir,`sol-${r}.py`);if(!u(l))return void console.log(chalk.yellow(Zo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));rt.set(r,v(rt.get(r)??w()));const s=(n.samples??[])[0];if(!s)return void console.log(chalk.gray(Zo()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=t("python3",[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(e){const o=e;if("ENOENT"===o.code)Wt();else if(o.killed)console.log(chalk.yellow(Zo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Zo()?" ✗ 程序报错:":" ✗ 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(Zo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Zo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(Zo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Zo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Zo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Zo()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=Mt(e);if(!o)return;const t=_(nt.dir,`sol-${o.n}.py`);if(!u(t))return void console.log(chalk.yellow(Zo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(Zo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const n=await Rt("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==n?.code?(console.log(chalk.gray(Zo()?" 回到竞技场。":" Back in the arena.")),console.log()):Wt()})(o):"recall"===e&&await(async e=>{const o=Mt(e);if(!o)return;if(!co)return void ht();const{p:t,n:n}=o,r=_(process.cwd(),"icoa-contest"),l=`${so.id}-phase${nt.phase}-g${nt.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?_(r,s,`sol-${n}.py`):null;if(!a||!u(a))return void console.log(chalk.gray(Zo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=p(a,"utf-8"),c=`${nt.phase}-${nt.data.slot}-${n}`,d=Math.min(3,(Dt.get(c)??0)+1);console.log(chalk.gray(Zo()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const g=await J({token:lo,phase:nt.phase,slot:nt.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:d,lang:Zo()?"zh":"en"});if(g.ok){Dt.set(c,d),console.log();for(const e of eo(g.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(Zo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(Zo()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===g.code?console.log(chalk.yellow(Zo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${g.message}`)):console.log(chalk.yellow(` ${g.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(Zo()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(Zo()?" (花名册: /list)":" (roster: /list)")),void _o()}if("contest"===o||"/contest"===o)return jt(),void _o();const i="lang"===o||/^lang\s+\S+$/.test(o),c=to.has(o);if(!("submit"===l||l.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||i||c||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(Zo()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void _o()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(Zo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void _o()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(ko.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}ko.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void _o()}if("ai4ioai"===o||"/ai4ioai"===o)return await g()&&(Do=!0),void _o();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!co)return ht(),void _o();Wo||(Wo=!0,console.log(),console.log(chalk.bold.cyan(Zo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Zo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Zo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Zo()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){qo=!0;const e=ot(mo.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Zo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(Zo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Zo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void _o()}return await pt(n,t?"fast":"deep"),void _o()}if(!No&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!co)return ht(),void _o();const e=ot(mo.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Zo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Zo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Zo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Zo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Zo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Zo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Zo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Fo=!0,void _o()}const c=!No&&"honors"===Lo&&/^[1-3]$/.test(o);if(!No&&Lo&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(Zo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(Zo()?" ↩ back 回上一层":" ↩ back goes up one level")),void _o();if(!No&&(c||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!co)return ht(),void _o();const e=/^\/?view ([1-3])$/.exec(o),t=c?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Mo=!0;try{console.log();const o=await G({token:lo,cardNumber:mo.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Zo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&zo.delete(mo.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&zo.add(mo.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Zo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${mo.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${mo.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Zo()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(Zo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=mt(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(Zo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Lo="view",console.log(chalk.gray((Zo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Zo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Mo=!1}})(t),void _o()}if("/honors"===o||"honors"===o)return ao?(console.log(),console.log(chalk.gray(Zo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void _o()):(await bt(),void _o());if("menu"===o||"menu confirm"===o){if(Qo.length>0&&await Promise.race([Promise.allSettled(Qo),new Promise(e=>setTimeout(e,3e3))]),ko.removeAllListeners("line"),Ao(),wo||!et){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(wo?ko:void 0),Go()}else ko.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===Lo)return await bt(),void _o();if("honors"===Lo)return Lo=null,ut(),void _o();if(Qo.length>0&&await Promise.race([Promise.allSettled(Qo),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${mo.streakDays} day(s)`)),console.log(),wo){ko.removeAllListeners("line"),Ao();for(const e of $o)ko.on("line",e);ko.prompt(),Go()}else ko.removeAllListeners("line"),ko.close();return}if(q(o))return yo?no(P(yo,Zo(),Xe(),"T0"===M().tier),!!yo.completedAt):(console.log(chalk.gray(Zo()?" 这门课本周没有布置任务。":" No weekly task is set for this course right now.")),console.log()),void _o();if("status"===o)return De(so,mo),void _o();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await T(so.id,lo,!0);return void(e?(Object.assign(so,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),ut()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本 / fetch failed (offline?) — keeping the cached copy")),_o()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(pe().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void _o();const t=so.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,l=r?n:"en";return me({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),xo=null,Co=null,To=null,jo(),Bo=!1,Fo=!1,await ft(),void _o()}if(to.has(o)){const e=to.get(o),t=Qe(pe()),n=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return Zo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===t?(console.log(chalk.gray((Zo()?"normal"===e?" 已是标准 64 列。":Xe()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Xe()} 列,上限 ${Ve(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Xe()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Xe()} cols, cap ${Ve(e)}). `)+n(e))),void _o()):(me({learnWidth:e,learnWide:"normal"!==e}),Je(e),"normal"!==e&&Xe()<=64?(console.log(chalk.yellow(Zo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((Zo()?` 设置已记住(${e},上限 ${Ve(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${Ve(e)} cols) and applies once you widen the window. `)+n(e))),void _o()):(console.log(chalk.green(" ✓ ")+chalk.gray((Zo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Xe()} 列,上限 ${Ve(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Xe()} cols, cap ${Ve(e)}). `)+n(e))),xo=null,Co=null,To=null,jo(),Bo=!1,Fo=!1,await ft(),void _o()))}if("sim"===o){const e=ot(mo.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=A(C(import.meta.url)),o=[_(e,"..","..","panda","mujoco-launcher.py"),_(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 t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void _o()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void _o())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=mo.currentCard,t=mo.bookmarks.includes(e),n="bookmark"!==o;return n?mo.bookmarks=mo.bookmarks.filter(o=>o!==e):t||mo.bookmarks.push(e),ke(mo),n?console.log(t?chalk.gray(Zo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(Zo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(Zo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(Zo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void _o()}const b=N(o);if(b){const e="current"===b.target?mo.currentCard:b.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>so.cards.length))return console.log(chalk.yellow(Zo()?` 本课共 ${so.cards.length} 张,请输 r 1–${so.cards.length} 或 r all。`:` This course has ${so.cards.length} cards. Try r 1–${so.cards.length} or r all.`)),console.log(),void _o();for(const o of L(uo,Jo,e,Zo(),Xe()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?uo:uo.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(uo=uo.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Ke(uo),Qo.push(I(lo,{card_number:mo.currentCard,event_type:"viewed"},o).catch(()=>{}))),void _o()}if("e"===o)return Io=mo.currentCard,console.log(chalk.gray(Zo()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(Zo()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void _o();if("back"===o||"b"===o)return"view"===Lo?(await bt(),void _o()):"honors"===Lo?(Lo=null,ut(),void _o()):(mo.currentCard>1&&(mo.currentCard-=1),Co=null,To=null,xo=null,ke(mo),ut(),void _o());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!lt)return console.log(chalk.yellow(Zo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void _o();if(!e){const e=await le(lo),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(Zo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(Zo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(Zo()?` 这台电脑上有 ${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(Zo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(Zo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(Zo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(Zo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(Zo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(Zo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(Zo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void _o()}if(/^\d{1,2}$/.test(e)){const o=await re(lo,Number(e));return o.ok&&o.data?(_t(o.data),await st(),void _o()):(console.log(chalk.red(` ✗ ${o.message||(Zo()?"关联失败":"Link failed")}`)),void _o())}const t=await se(lo,e);return t.ok&&t.data?(_t(t.data),await st(),void _o()):(console.log(chalk.red(` ✗ ${t.message||(Zo()?"关联失败":"Link failed")}`)),"not_your_token"===t.code&&console.log(chalk.gray(Zo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void _o())}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(!lt)return console.log(chalk.yellow(Zo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void _o();const e=at(mo.currentCard);if("contest reset"===o&&No&&xt()){const e=nt.phase,o=nt.data.slot,t=await oe(lo,e,o);if(t.ok){console.log(chalk.yellow(Zo()?" 已放弃本卡练习计时。回卡片后输入 practice <题号> 重新开始。":" Practice attempt abandoned. From the card, practice <n> starts a fresh one."));const t=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19),n=_(process.cwd(),"icoa-contest",`${so.id}-phase${e}-g${o}`);if(u(n))try{m(n,`${n}-archived-${t}`),console.log(chalk.gray(Zo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${t}`))}catch{console.log(chalk.yellow(Zo()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}nt=null,No=!1,Nt=null,ut()}else console.log(chalk.red(` ✗ ${t.message||"reset failed"}`));return void _o()}if("contest reset"===o){const o=await oe(lo,e);if(o.ok){console.log(chalk.yellow(Zo()?` 已放弃当前计时(阶段 ${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 t=1;t<=3;t++){const n=_(process.cwd(),"icoa-contest",`${so.id}-phase${e}-g${t}`);if(u(n))try{m(n,`${n}-archived-${o}`),console.log(chalk.gray(Zo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(Zo()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(Zo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),nt=null,No=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void _o()}const t=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Zo()?" 连接判分赛…":" Contacting contest server…"));const n=await te(lo,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(Zo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void _o();const r=n.data,l=_(process.cwd(),"icoa-contest",`${so.id}-phase${e}-g${r.slot}`);y(l,{recursive:!0});const s=nt&&nt.phase===e&&nt.data.slot===r.slot?nt.tried:new Set;nt={phase:e,dir:l,data:r,tried:s},At(r,l),No=!0,jt(),console.log(chalk.gray(Zo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1,i=$t&&!kt?ge:a;return console.log(chalk.white(Zo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${i}`)+chalk.gray(i===ge?Zo()?" 热身题(不计分)— 一分钟证明环境是通的。每屏都会给下一步。":" — the unscored warm-up: one minute to prove your setup works. Every screen tells you the next step.":Zo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void _o()}const x=/^\/?(?:practice|practise)(?:\s+(\S+))?$/.exec(o);if(x){const e=ot(mo.currentCard),o=St(e);if(!o)return console.log(chalk.gray(Zo()?" 这张卡没有配套练习题 — 有练习的卡片会在卡片下方列出题目。":" No practice problems on this card — cards that have them list them under the card.")),void _o();if(!lt)return console.log(chalk.yellow(Zo()?" 练习题需要正式课程 token(demo 不支持)。":" Practice needs a full curriculum token (demos not supported).")),void _o();if(!x[1])return console.log(),Pt(e),console.log(chalk.gray(Zo()?" 用法: ":" Usage: ")+chalk.bold.green(Zo()?"practice <题号>":"practice <n>")+chalk.gray(Zo()?` 例如 practice 1(1-${o.length})`:` e.g. practice 1 (1-${o.length})`)),void _o();const t=parseInt(x[1],10);return!Number.isInteger(t)||t<1||t>o.length?(console.log(chalk.yellow(Zo()?` 题号要在 1..${o.length} — 再试一次,例如: `:` Practice number must be 1..${o.length} — try again, e.g. `)+chalk.bold.green("practice 1")),void _o()):(await(async(e,o,t)=>{const n=at(e.number),r=Tt+e.number;console.log(chalk.gray(Zo()?" 连接判分赛…":" Contacting contest server…"));const l=await te(lo,n,r,!0);if(!l.ok||!l.data)return void("no_contest"===l.code?console.log(chalk.gray(Zo()?" 本卡暂无练习题库。":" No practice set behind this card yet.")):console.log(chalk.red(` ✗ ${l.message||"practice unavailable"}`)));const a=l.data;if(0===a.problems.length)return void console.log(chalk.gray(Zo()?" 本卡练习题库是空的。":" This card practice set is empty."));const i=new Map(a.problems.map(e=>[e.id,e])),c=[];for(const e of o){const o=i.has(Et(e.py_id))?Et(e.py_id):i.has(e.py_id)?e.py_id:null;o&&(c.push(i.get(o)),i.delete(o))}for(const e of a.problems)i.has(e.id)&&c.push(e);a.problems=c;let d=It.get(r);d||(d=new Set,It.set(r,d));for(const e of a.solved)d.add(e);const g=_(process.cwd(),"icoa-contest",`${so.id}-phase${n}-g${r}`);y(g,{recursive:!0});const u=nt&&nt.phase===n&&nt.data.slot===r?nt.tried:new Set;nt={phase:n,dir:g,data:a,tried:u},At(a,g),No=!0,Nt=null,s(`learn-practice card${e.number}: enter p${n}s${r} #${t}`),console.log(),console.log(chalk.bold.yellow(Zo()?` ⚔ 卡片练习场 — 第 ${e.number} 张卡`:` ⚔ Card practice arena — card ${e.number}`)+chalk.gray(Zo()?"(不计分 · 不影响阶段门禁)":" (unscored · never gates a phase)")),console.log(chalk.gray(Zo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(g)),console.log(chalk.gray((Zo()," ↩ "))+chalk.bold.green("back")+chalk.gray(Zo()?" 一层层退回: 题目 → 花名册 → 卡片 · /list 看花名册":" retraces one level at a time: problem → roster → card · /list = roster")),Ot(String(Math.min(t,a.problems.length)))})(e,o,t),void _o())}if("submit"===l)return console.log(chalk.yellow(Zo()?" 用法: ":" Usage: ")+chalk.bold.green(Zo()?"submit <题号>":"submit <n>")+chalk.gray(Zo()?" 例如 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)")),nt||console.log(chalk.gray(Zo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void _o();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const t=e[2];if(!nt)return console.log(chalk.yellow(Zo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void _o();const n=nt.data.problems,r=parseInt(o,10);if($t&&r===ge)return console.log(chalk.gray(Zo()?" 热身题不判分 — /run 0 就是它的完整判定(10 个用例全在本机)。":" The warm-up is not judged — /run 0 IS its full check (all ten cases, on your machine).")),console.log(chalk.white(Zo()?" ▸ 计分的题目从 ":" ▸ The problems that count start at ")+chalk.bold.green("/read 1")+chalk.gray(Zo()?" 开始。":".")),void _o();if(Number.isInteger(r)&&r>=1&&r<=n.length&&!n.some(e=>e.id===o)&&(o=n[r-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(Zo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void _o();const s=n.findIndex(e=>e.id===o)+1,a=t||_(nt.dir,`sol-${s}.py`);let c;try{c=p(a,"utf-8")}catch{return console.log(chalk.red(Zo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void _o()}const d=new i(lo);d.start();const g=rt.get(s),u=await ne(lo,nt.phase,o,c,nt.data.slot>=Tt?nt.data.slot: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(Zo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((Zo()," "))+chalk.bold.green("contest")+chalk.gray(Zo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(Zo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${u.message||"judging failed"}`)),void _o();const y=u.data;if(y.already_ac)console.log(chalk.green(Zo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===y.verdict){if(console.log(chalk.bold.green(Zo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${y.passed_tests??y.total_tests??"?"}/${y.total_tests??"?"} `+(Zo()?"隐藏用例全过":"hidden tests passed")+` · ${y.time_ms??"?"}ms`)),nt.data.solved.includes(o)||nt.data.solved.push(o),nt.tried.delete(o),xt()){let e=It.get(nt.data.slot);e||(e=new Set,It.set(nt.data.slot,e)),e.add(o)}}else{nt.tried.add(o);const e="TLE"===y.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${y.verdict}`)+chalk.gray(y.test?Zo()?` · 挂在第 ${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(Zo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const h=ie(y.deadline||""),m=xt();if(console.log(chalk.white(m?Zo()?` 本卡练习: 已过 ${y.ac_count}/${y.n} 题(不计分)`:` Card practice: ${y.ac_count}/${y.n} solved (unscored)`:Zo()?` 本组进度: 已过 ${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}`):"")),m&&!y.late&&y.ac_count>=y.n)console.log(chalk.bold.green(Zo()?" 🎉 本卡练习题全部拿下!":" 🎉 Every practice problem on this card cleared!")+chalk.gray(Zo()?" ↩ back 回卡片":" ↩ back returns to the card"));else if(!y.passed||y.late||m){if(!y.late){const e=n.findIndex(e=>!nt.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Zo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${wt(n[e])}`))}}else console.log(chalk.bold.green(Zo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await st();return void _o()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>so.totalCards)return console.log(chalk.yellow(` Card number must be 1..${so.totalCards}. Try: `)+chalk.bold.green("card 1")),void _o();const n=await ct(t);return n?(console.log(n),void _o()):(mo.currentCard=t,Co=null,To=null,xo=null,ke(mo),ut(),void _o())}if(null!==xo&&["y","yes","n","no"].includes(o)){const e=ot(xo);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Ho;Ce(mo,e.number),xe(mo,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),ke(mo);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),Qo.push(I(lo,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),xo=null,e.solution&&e.solution.length>0)return void _o();if(mo.currentCard<so.totalCards){const e=mo.currentCard,o=await ct(e+1);if(o)return await dt(e),console.log(o),void _o();mo.currentCard+=1,ke(mo),await dt(e)?gt():ut(),_o()}else Ue(so,mo),_o();return}}if(null!==Co&&["a","b","c","d"].includes(o)){const e=ot(Co);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(Te(mo,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),Ce(mo,e.number),ke(mo),qe(e,t,n,mo),Qo.push(I(lo,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Co=null,n)if(mo.currentCard<so.totalCards){const e=await ct(mo.currentCard+1);if(e)return console.log(e),void _o();mo.currentCard+=1,ke(mo),ut()}else Ue(so,mo),_o();else _o();return}}if(null!==To){if("done"===o){const e=ot(To);if(e&&"practical"===e.type)return Ie(mo,e.number),Ce(mo,e.number),ke(mo),Ne(e),To=null,void _o()}if("skip"===o)return Ce(mo,To),ke(mo),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),To=null,void _o()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==Co)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void _o();if(null!==To)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void _o();if(null!==xo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void _o();const e=mo.currentCard,o=e<so.totalCards?await ct(e+1):null;return o?(await dt(e),console.log(o),void _o()):(mo.currentCard+=1,ke(mo),mo.currentCard>so.totalCards?Ue(so,mo):await dt(e)?gt():ut(),void _o())}return null!==xo?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void _o()):null!==Co?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void _o()):null!==To?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void _o()):("view"===Lo?console.log(chalk.gray(Zo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(Zo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(Zo()?" 回卡片":" to the card")):"honors"===Lo?console.log(chalk.gray(Zo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(Zo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(Zo()?" 回卡片":" 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 _o())};ko.on("line",e=>{Yt(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.")),_o()})}),wo||ko.on("close",async()=>{Qo.length>0&&await Promise.race([Promise.allSettled(Qo),new Promise(e=>setTimeout(e,5e3))]),et?Go():process.exit(0)});const Ut=O(uo,Zo());Ut&&(console.log(chalk.bold.cyan(` ${Ut}`)),console.log());try{ut(),_o();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(oo("Could not render this card — the curriculum may be malformed."),wo){ko.removeAllListeners("line"),Ao();for(const e of $o)ko.on("line",e);ko.prompt()}else ko.close();Go()}await Xo}),ro.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await T(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as o,mkdirSync as e,readFileSync as t,statSync as n,writeFileSync as s}from"node:fs";import{homedir as r}from"node:os";import{join as i}from"node:path";import chalk from"chalk";import{getConfig as c}from"../lib/config.js";import{logCommand as l}from"../lib/logger.js";import{makeReplAsker as a}from"../lib/repl-asker.js";const g=[{score:85,icon:"🥇",name:"gold"},{score:65,icon:"🥈",name:"silver"},{score:40,icon:"🥉",name:"bronze"}],u=new Set(["e3-c-toss","e4-c-push","e5-c-swing","s2-bodyswap"]);function d(){return process.env.ICOA_WM_SERVER?process.env.ICOA_WM_SERVER.replace(/\/$/,""):"http://172.237.95.164:9097"}const f=i(r(),".icoa","wm.json");function h(o){try{e(i(r(),".icoa"),{recursive:!0}),s(f,`${JSON.stringify(o,null,2)}\n`)}catch{}}function y(){return(c().language||"en").toLowerCase().startsWith("zh")}function m(o,e){return y()?o:e}async function b(o,e){try{return await fetch(d()+o,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(3e4)})}catch{return null}}function w(){console.log(),console.log(chalk.yellow(m(" 判题服务器现在连不上。"," The wm-judge server is not reachable right now."))),console.log(chalk.gray(m(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function p(o,e){const t=[];let n="",s=0;const r=o=>/[ᄀ-ᅟ⺀-가-힣豈-︰-﹏-⦆¢-₩]/.test(o);for(const i of o){const o=r(i)?2:1;if(s+o>e){const o=n.lastIndexOf(" ");if(!r(i)&&" "!==i&&o>e/3){const e=n.slice(o+1);t.push(n.slice(0,o)),n=e,s=[...e].reduce((o,e)=>o+(r(e)?2:1),0)}else t.push(n),n="",s=0;if(" "===i&&""===n)continue}n+=i,s+=o}return""!==n.trim()&&t.push(n),t}function v(o){const e=o.split("-")[0],t=e.startsWith("e")?`0${e}`:e.startsWith("r")?`1${e}`:`2${e}`,n=o.includes("-short")||o.includes("-next")?"0":"1";return`${t}-${o.includes("-p-")?`0${n}`:o.includes("-c-")?"2":"3"}-${o}`}function $(o){for(const e of g)if(o>=e.score)return e.icon;return""}function k(o){return i(process.cwd(),"wm",o)}function S(){return chalk.gray(m(" 动作: "," Verbs: "))+chalk.cyan("<slot>")+chalk.gray(m(" 打开一格(如 "," open a slot (e.g. "))+chalk.white("e1-p-short")+chalk.gray(m(",序号也行) · ",", a number works too) · "))+chalk.cyan("honors")+chalk.gray(m(" 我的奖牌 · "," your medals · "))+chalk.cyan("back")+chalk.gray(m(" ↩ 返回 icoa"," ↩ back to icoa"))}function j(o,e){const t=Object.keys(o).sort((o,e)=>v(o).localeCompare(v(e)));console.log(),console.log(chalk.bold.cyan(" ⚔ WM ARENA")+chalk.gray(m(" · 建世界模型 · 提交预测 · 服务端判分"," · build world models · submit predictions · server-judged"))),console.log(chalk.gray(m(" 这是 worldmodel-96 的实战场:每格一个世界,交的是数据(CSV),不是代码。"," The hands-on side of worldmodel-96: one world per slot. You submit data (a CSV), never code."))),console.log();let n="";return t.forEach((t,s)=>{const r=t.split("-")[0];r!==n&&(""!==n&&console.log(),n=r);const i=o[t],c=e[t],l=void 0===c?chalk.gray(" —"):chalk.white(`${c.toFixed(1).padStart(5)} `)+$(c),a=u.has(t)?chalk.magenta(m(" ⭐ research"," ⭐ research")):"";console.log(chalk.gray(` ${String(s+1).padStart(2)}. `)+`${function(o){return void 0===o?"⬜":o>=40?"✅":"❌"}(c)} `+chalk.cyan(t.padEnd(12))+chalk.gray(` ${i.env.padEnd(10)} ${i.mode.padEnd(8)} ${String(i.n_cases).padStart(3)} cases `)+l+a)}),console.log(),console.log(chalk.gray(" 🔒 ")+chalk.white("b1-boss")+chalk.gray(m(" —— 通关格。奖牌线之后解锁,R1 内测阶段还没开。"," — the boss slot. Unlocks past the medal lines; closed during the R1 beta."))),console.log(),console.log(chalk.gray(m(" 奖牌线(每格一样):"," Medal lines (same on every slot): "))+chalk.white("🥉 40 · 🥈 65 · 🥇 85")+chalk.gray(m(" —— 归一化 0-100 分。"," — normalized 0-100."))),console.log(S()),console.log(),t}function W(o,e){console.log(),console.log(chalk.bold.white(m(" 🏆 我的成绩(本机记录)"," 🏆 Your scores (recorded on this machine)"))+chalk.gray(m(" —— 判分记录以服务端为准。"," — the server holds the authoritative record.")));const t=Object.entries(e).sort((o,e)=>e[1]-o[1]);if(0===t.length)return console.log(chalk.gray(m(" 还没有提交过 —— 打开一格开始。"," No submissions yet — open a slot to start."))),void console.log();const n={"🥇":0,"🥈":0,"🥉":0};for(const[,o]of t){const e=$(o);e&&n[e]++}console.log(chalk.white(` 🥇 ${n["🥇"]} 🥈 ${n["🥈"]} 🥉 ${n["🥉"]}`)),console.log();for(const[e,n]of t){const t=o[e]?"":chalk.gray(" (slot retired)");console.log(chalk.gray(" ")+chalk.cyan(e.padEnd(12))+chalk.white(` ${n.toFixed(1).padStart(5)} `)+$(n)+t)}console.log(),console.log(chalk.gray(m(" ↩ 回到棋盘:back"," ↩ Back to the grid: back"))),console.log()}function x(o){return chalk.gray(m(" 动作: "," Verbs: "))+chalk.cyan("/run")+chalk.gray(m(" 自测思路 · "," self-eval recipe · "))+chalk.cyan("/submit <file>")+chalk.gray(m(" 交卷判分 · "," score it · "))+chalk.cyan("back")+chalk.gray(m(" ↩ 回棋盘"," ↩ back to the grid"))+chalk.gray(` (${o})`)}async function A(t,n){const r=y()?"zh":"en",c=await b(`/api/wm/statement/${n}?lang=${r}`,t);if(!c?.ok)return void w();const l=await c.text();console.log();for(const o of l.split("\n")){const e=o.trimEnd();if(e.startsWith("#"))console.log(chalk.bold.white(` ${e.replace(/^#+\s*/,"")}`));else if(e.startsWith("- ")||e.startsWith("* "))for(const o of p(e,72))console.log(chalk.white(` ${o}`));else if(""===e)console.log();else for(const o of p(e,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(m(" 正在取这一格的数据文件…"," Fetching this slot’s data files…")));const a=await async function(t,n){const r=await b(`/api/wm/files/${n}`,t);let c=[];if(r?.ok)try{const o=await r.json();Array.isArray(o.files)&&(c=o.files.filter(o=>"string"==typeof o))}catch{c=[]}0===c.length&&(c=["train.csv","eval_prefixes.csv","eval_actions.csv","eval_inits.csv","eval_cases.csv"]);const l=k(n),a=[];for(const r of c){const c=i(l,r);if(o(c)){a.push(r);continue}const g=await b(`/api/wm/data/${n}/${r}`,t);if(g?.ok)try{e(l,{recursive:!0}),s(c,await g.text()),a.push(r)}catch{}}return a}(t,n);if(0===a.length)console.log(chalk.yellow(m(" 数据文件取不下来 —— 检查网络,或看看这个目录能不能写。"," Could not fetch the data files — check your connection and that this directory is writable.")));else for(const o of a)console.log(chalk.green(" ✓ ")+chalk.white(i(k(n),o)));console.log(),console.log(x(n)),console.log()}function N(o){console.log(),console.log(chalk.bold.white(m(" 自测思路(本地,不算分):"," Self-eval recipe (local, unscored):"))),console.log(chalk.gray(m(" · 从 train.csv 切一段出来当自己的验证集,先量你的 1-step 误差;"," · carve a validation split out of train.csv and measure your 1-step error first;"))),console.log(chalk.gray(m(" · 再按题面滚多步 —— 多步误差涨得快是正常物理,不是 bug;"," · then roll multi-step exactly as the statement asks — error growth over steps is physics, not a bug;"))),console.log(chalk.gray(m(" · 真分数只来自 "," · the real score only comes from "))+chalk.cyan("/submit <file>")+chalk.gray(m(" —— 公开分即时返回,私榜分不返回。"," — public score returns instantly; the private split never does."))),console.log(),console.log(x(o)),console.log()}async function C(e,s,c,a){const u=[c.startsWith("/")||c.startsWith("~")?c.replace(/^~/,r()):i(process.cwd(),c),i(k(s),c)].find(e=>o(e));if(!u)return console.log(chalk.yellow(m(` 找不到文件:${c}`,` File not found: ${c}`))),void console.log(chalk.gray(m(" 给相对路径、绝对路径,或放进 "," Give a relative or absolute path, or drop it into "))+chalk.white(k(s)));if(n(u).size>8388608)return void console.log(chalk.yellow(m(" 文件超过 8MB —— 判题机不收这么大的提交。"," File exceeds 8MB — the judge rejects submissions this large.")));console.log(chalk.gray(m(" 上传判分中…"," Scoring on the server…")));const f=await async function(o,e,t){try{const n=await fetch(`${d()}/api/wm/score`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({slot:e,csv:t}),signal:AbortSignal.timeout(12e4)});return await n.json()}catch{return null}}(e,s,t(u,"utf-8"));if(!f)return void w();if(!0!==f.ok){const o=String(f.error??"error");if(l(`wm: submit ${s} → rejected: ${o.slice(0,80)}`),o.startsWith("daily cap"))console.log(chalk.bold.yellow(m(" ⏱ 这一格今天的提交次数用完了 —— 明天再来。"," ⏱ Daily submission cap reached for this slot — come back tomorrow.")));else if("unauthorized"===o)console.log(chalk.bold.red(m(" ✗ 邀请码失效了 —— 重新进入 wm 输入新的。"," ✗ Your invite key was rejected — re-enter wm with a fresh one.")));else{console.log(chalk.bold.red(m(" ✗ 判题机拒收了这份提交:"," ✗ The judge rejected this submission:")));for(const e of p(o,70))console.log(chalk.yellow(` ${e}`))}return}const y=Number(f.normalized_public),b=Number(f.raw_public),v=Number(f.remaining_today),S=a.best?.[s];if(l(`wm: submit ${s} → norm=${y} raw=${b} remaining=${v}`),console.log(),console.log(chalk.bold.green(m(" ✓ 已判分 —— "," ✓ scored — "))+chalk.bold.white(`${y.toFixed(1)} / 100`)+chalk.gray(` (raw ${b})`)+($(y)?` ${$(y)}`:"")),void 0===S||y>S){for(const o of g)if(y>=o.score&&(void 0===S||S<o.score)){console.log(chalk.bold.white(m(` 🎉 越过${o.icon}线(${o.score})!`,` 🎉 You crossed the ${o.icon} line (${o.score})!`)));break}a.best={...a.best??{},[s]:y},h(a)}else console.log(chalk.gray(m(` 本机最好成绩仍是 ${S.toFixed(1)}。`,` Your best on this machine stays ${S.toFixed(1)}.`)));console.log(chalk.gray(m(" 今天这格还能交 "," Submissions left today on this slot: "))+chalk.white(String(v))+chalk.gray(m(" 次 —— 公开分即时,私榜分不公开。"," — public score is instant; the private split stays hidden."))),console.log()}function E(o,e){const t=o.trim().toLowerCase().replace(/^\/?read\s+/,"");if(e.includes(t))return t;const n=Number(t);return!Number.isNaN(n)&&n>=1&&n<=e.length?e[n-1]:null}async function _(o,e,t,n){for(await A(o,e);;){const s=(await t(chalk.bold.cyan(`icoa wm ${e}> `))??"").trim();if(""===s)continue;const r=s.toLowerCase(),[i,...c]=r.split(/\s+/);if("back"===i||"quit"===i||"q"===i)return"grid";if("menu"===i||"exit"===i)return"leave";if("help"!==i&&"guide"!==i)if("/read"!==i&&"read"!==i)if("/run"!==i&&"run"!==i){if("/submit"===i||"submit"===i){const t=s.split(/\s+/).slice(1).join(" ");if(!t){console.log(chalk.gray(m(" 用法:/submit <预测文件.csv>"," Usage: /submit <predictions.csv>")));continue}await C(o,e,t,n);continue}0===c.length&&i.endsWith(".csv")?await C(o,e,s,n):console.log(chalk.gray(m(" 没懂。可用:"," Not a verb here. Try: "))+chalk.cyan("/read · /run · /submit <file> · back"))}else N(e);else await A(o,e);else console.log(),console.log(x(e)),console.log()}}export async function runWm(o){const e=a(),n=e.ask,s=function(){try{return JSON.parse(t(f,"utf-8"))}catch{return{}}}();try{let e=(o??"").trim()||s.invite||"",t=null;for(let o=0;o<3;o++){if(!e){console.log(),console.log(chalk.bold.cyan(" ⚔ WM ARENA")+chalk.gray(m(" · 邀请制内测"," · invite-only beta")));const o=(await n(chalk.cyan(m(" 你的邀请码"," Your invite key"))+chalk.gray(m(" · back 返回: "," · back to leave: ")))??"").trim();if(""===o||["back","quit","exit","menu","q"].includes(o.toLowerCase()))return;e=o.replace(/^wm\s+/i,"").replace(/^["']|["']$/g,"").trim()}const o=await b("/api/wm/slots",e);if(!o)return void w();if(401!==o.status){if(o.ok)try{t=await o.json()}catch{t=null}break}console.log(chalk.yellow(m(" 这个邀请码不对 —— 再试一次(back 返回)。"," That invite key was rejected — try again (back to leave)."))),e=""}if(!t)return void(e?w():(console.log(chalk.gray(m(" 三次没对上 —— 找发你邀请的人核对一下。"," Three misses — check the key with whoever invited you."))),console.log()));s.invite!==e&&(s.invite=e,h(s)),l("wm: enter");let r=j(t,s.best??{});for(;;){const o=(await n(chalk.bold.cyan("icoa wm> "))??"").trim();if(""===o)continue;const i=o.toLowerCase();if(["back","quit","q","exit","menu"].includes(i))break;if("help"===i||"guide"===i){console.log(),console.log(S()),console.log();continue}if("grid"===i||"list"===i||"contest"===i||"/list"===i){r=j(t,s.best??{});continue}if("honors"===i||"/honors"===i){W(t,s.best??{});continue}const c=E(o,r);if(c){if(l(`wm: read ${c}`),"leave"===await _(e,c,n,s))break;r=j(t,s.best??{})}else console.log(chalk.gray(m(" 没有这一格。输 slot 名(如 "," No such slot. Type a slot name (e.g. "))+chalk.white("e1-p-short")+chalk.gray(m(")、序号,或 honors / back。","), a row number, or honors / back.")))}console.log(),console.log(chalk.gray(m(" 已离开 WM Arena —— 回到 icoa。随时敲 "," Left the WM Arena — back at icoa. Return any time with "))+chalk.cyan("wm")),console.log()}finally{e.close()}}export function registerWmCommand(o){o.command("wm [invite]",{hidden:!0}).description("WM Arena — world-model contest slots, server-judged (invite beta)").action(async o=>{await runWm(o)})}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as l}from"./commands/connect.js";import{registerChallengeCommand as i}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerNoteCommand as c}from"./commands/note.js";import{registerLogCommand as m}from"./commands/log.js";import{registerLangCommand as g}from"./commands/lang.js";import{registerSetupCommand as d}from"./commands/setup.js";import{registerEnvCommand as p}from"./commands/env.js";import{registerAienvCommand as h}from"./commands/aienv.js";import{registerIpynbCommand as y}from"./commands/ipynb.js";import{registerAi4ctfCommand as f}from"./commands/ai4ctf.js";import{registerExamCommand as u}from"./commands/exam.js";import{registerCtf4aiDemoCommand as w}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as b}from"./commands/theme.js";import{registerLearnCommand as T}from"./commands/learn.js";import{registerCtf4VlaCommand as v}from"./commands/ctf4vla.js";import{registerDemo2Command as j}from"./commands/demo2.js";import{registerDemo4Command as $}from"./commands/demo4.js";import{registerDemo5Command as A}from"./commands/demo5.js";import{registerSimCommand as I}from"./commands/sim.js";import{registerArenaCommand as E}from"./commands/arena.js";import{registerKaggleCommand as C}from"./commands/kaggle.js";import{registerSprintCommand as _}from"./commands/sprint.js";import{registerTeleloadCommand as S}from"./commands/teleload.js";import{registerBoardCommand as x}from"./commands/board.js";import{getConfig as k,saveConfig as L}from"./lib/config.js";import{startRepl as O}from"./repl.js";import{RELAUNCH_CODE as R}from"./lib/menu-nav.js";import{setTerminalTheme as F}from"./lib/theme.js";import{cleanupTerminal as N}from"./lib/terminal-cleanup.js";import{checkForUpdates as U}from"./lib/update-check.js";import{detectIcoaInstalls as P,isWindowsBuildInWslShell as M}from"./lib/platform.js";import{ICOA_BIG as D}from"./lib/banner.js";import{readFileSync as G}from"node:fs";import{fileURLToPath as W}from"node:url";import{dirname as H,join as Y}from"node:path";const J=H(W(import.meta.url)),V=JSON.parse(G(Y(J,"..","package.json"),"utf-8")).version,X=chalk.cyan(" ─────────────────────────────────────────────────────"),q=`\n${X}\n\n${D.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${V}`)}\n\n${X}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=n?process.argv.slice(1,2):process.argv.slice(1),r=o(process.execPath,s,{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(r.signal){e=0;break}e=r.status,n=!0}while(e===R);N(),process.exit(e??0)}}const z=new o;if(z.name("icoa").version(V).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=k();F("high-contrast"===e.themeVariant?"high-contrast":"dark"),U(),function(){const o=P();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();console.log(q);const s=!!o.resume||!!o.continue;if(process.argv.length<=2||s)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),s||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void O(z,s)}),e(z),n(z),s(z),r(z),t(z),l(z),i(z),a(z),c(z),m(z),g(z),d(z),p(z),h(z),y(z),f(z),u(z),w(z),b(z),T(z),v(z),j(z),$(z),A(z),I(z),E(z),C(z),S(z),_(z),x(z),z.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=k().geminiModel||"gemini-2.5-flash-lite";o?(L({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}z.hook("preAction",()=>{!function(){if(!M())return;const o="─".repeat(52);console.log(),console.log(chalk.yellow(` ${o}`)),console.log(chalk.yellow.bold(" ⚠ You ARE inside Ubuntu — but this icoa")),console.log(chalk.yellow.bold(" is the WINDOWS build.")),console.log(),console.log(chalk.gray(" WSL appends the Windows PATH, so ")+chalk.cyan("icoa")),console.log(chalk.gray(" found the Windows copy first. Almost")),console.log(chalk.gray(" nothing will work: no vi, no python3,")),console.log(chalk.gray(" env setup cannot install.")),console.log(),console.log(chalk.gray(" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.white(" Fix — inside Ubuntu, check npm is Linux FIRST:")),console.log(` ${chalk.bold.cyan("which npm")}${chalk.gray(" → must not be /mnt/c/...")}`),console.log(` ${chalk.bold.cyan("sudo npm install -g icoa-cli")}`),console.log(` ${chalk.bold.cyan("hash -r")}${chalk.gray(" → bash caches the old path")}`),console.log(chalk.gray(" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(chalk.yellow(` ${o}`)),console.log()}()}),z.parse();
|
|
2
|
+
import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as l}from"./commands/connect.js";import{registerChallengeCommand as i}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerNoteCommand as c}from"./commands/note.js";import{registerLogCommand as m}from"./commands/log.js";import{registerLangCommand as g}from"./commands/lang.js";import{registerSetupCommand as d}from"./commands/setup.js";import{registerEnvCommand as p}from"./commands/env.js";import{registerAienvCommand as h}from"./commands/aienv.js";import{registerIpynbCommand as y}from"./commands/ipynb.js";import{registerAi4ctfCommand as f}from"./commands/ai4ctf.js";import{registerExamCommand as u}from"./commands/exam.js";import{registerCtf4aiDemoCommand as w}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as b}from"./commands/theme.js";import{registerLearnCommand as T}from"./commands/learn.js";import{registerCtf4VlaCommand as v}from"./commands/ctf4vla.js";import{registerDemo2Command as j}from"./commands/demo2.js";import{registerDemo4Command as $}from"./commands/demo4.js";import{registerDemo5Command as A}from"./commands/demo5.js";import{registerSimCommand as I}from"./commands/sim.js";import{registerArenaCommand as E}from"./commands/arena.js";import{registerKaggleCommand as C}from"./commands/kaggle.js";import{registerSprintCommand as _}from"./commands/sprint.js";import{registerTeleloadCommand as S}from"./commands/teleload.js";import{registerBoardCommand as x}from"./commands/board.js";import{registerWmCommand as k}from"./commands/wm.js";import{getConfig as L,saveConfig as O}from"./lib/config.js";import{startRepl as R}from"./repl.js";import{RELAUNCH_CODE as F}from"./lib/menu-nav.js";import{setTerminalTheme as N}from"./lib/theme.js";import{cleanupTerminal as U}from"./lib/terminal-cleanup.js";import{checkForUpdates as P}from"./lib/update-check.js";import{detectIcoaInstalls as M,isWindowsBuildInWslShell as D}from"./lib/platform.js";import{ICOA_BIG as G}from"./lib/banner.js";import{readFileSync as W}from"node:fs";import{fileURLToPath as H}from"node:url";import{dirname as Y,join as J}from"node:path";const V=Y(H(import.meta.url)),X=JSON.parse(W(J(V,"..","package.json"),"utf-8")).version,q=chalk.cyan(" ─────────────────────────────────────────────────────"),z=`\n${q}\n\n${G.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${X}`)}\n\n${q}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=n?process.argv.slice(1,2):process.argv.slice(1),r=o(process.execPath,s,{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(r.signal){e=0;break}e=r.status,n=!0}while(e===F);U(),process.exit(e??0)}}const K=new o;if(K.name("icoa").version(X).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=L();N("high-contrast"===e.themeVariant?"high-contrast":"dark"),P(),function(){const o=M();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();console.log(z);const s=!!o.resume||!!o.continue;if(process.argv.length<=2||s)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),s||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void R(K,s)}),e(K),n(K),s(K),r(K),t(K),l(K),i(K),a(K),c(K),m(K),g(K),d(K),p(K),h(K),y(K),f(K),u(K),w(K),b(K),T(K),v(K),j(K),$(K),A(K),I(K),E(K),C(K),S(K),_(K),x(K),k(K),K.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=L().geminiModel||"gemini-2.5-flash-lite";o?(O({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}K.hook("preAction",()=>{!function(){if(!D())return;const o="─".repeat(52);console.log(),console.log(chalk.yellow(` ${o}`)),console.log(chalk.yellow.bold(" ⚠ You ARE inside Ubuntu — but this icoa")),console.log(chalk.yellow.bold(" is the WINDOWS build.")),console.log(),console.log(chalk.gray(" WSL appends the Windows PATH, so ")+chalk.cyan("icoa")),console.log(chalk.gray(" found the Windows copy first. Almost")),console.log(chalk.gray(" nothing will work: no vi, no python3,")),console.log(chalk.gray(" env setup cannot install.")),console.log(),console.log(chalk.gray(" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.white(" Fix — inside Ubuntu, check npm is Linux FIRST:")),console.log(` ${chalk.bold.cyan("which npm")}${chalk.gray(" → must not be /mnt/c/...")}`),console.log(` ${chalk.bold.cyan("sudo npm install -g icoa-cli")}`),console.log(` ${chalk.bold.cyan("hash -r")}${chalk.gray(" → bash caches the old path")}`),console.log(chalk.gray(" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(chalk.yellow(` ${o}`)),console.log()}()}),K.parse();
|