icoa-cli 2.19.404 → 2.19.405
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/commands/learn.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{getMainRl as s}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as l,handleAi4ioaiMessage as a,startAi4ioaiChat as i}from"./ai4ioai.js";import{existsSync as c,mkdirSync as d,readFileSync as u,writeFileSync as g}from"node:fs";import{dirname as m,join as y}from"node:path";import{fileURLToPath as p}from"node:url";import{loadCurriculumById as h,validateEAToken as f,syncProgress as b,syncCardFeedback as w}from"../lib/learn-curricula.js";import{normalizeTokenBody as $}from"../lib/token-format.js";import{fetchMyScores as k,setNickname as v,streamLearnTutor as C,submitPqs as A,viewPqsTop as _,viewHonors as I}from"../lib/learn-ai.js";import{contestReset as x,contestStart as T,contestSubmit as E,fetchGate as M,timeLeft as R}from"../lib/learn-contest.js";import{getConfig as S,saveConfig as P}from"../lib/config.js";import{loadLearnState as q,saveLearnState as L,newLearnState as j,updateStreak as D,markCardComplete as O,recordMCQ as N,recordCheck as W,markPracticalComplete as Y,addAchievement as B}from"../lib/learn-state.js";import{renderWelcome as F,renderKnowledgeCard as U,renderMCQCard as z,renderMCQFeedback as H,renderPracticalCard as J,renderPracticalSuccess as Z,renderSimDemoCard as K,renderMilestone as Q,renderArenaTaskCard as V,renderComingSoonCard as X,renderStatus as G,renderPhaseComplete as ee,renderCurriculumComplete as oe,setLearnAiEnabled as te,setLearnHonorRanks as ne,setLearnPqsViewCards as re,renderHonorWall as se}from"../lib/learn-render.js";import{printError as le}from"../lib/ui.js";export function registerLearnCommand(ae){ae.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ae=>{ae&&ae.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(),ae="LEARNDEMO01");let ie=ae.trim().toUpperCase(),ce=null;const de=/^[A-Z0-9]+DEMO01$/i.test(ie),ue=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(ie);let ge=!1,me=!1;if(de)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),ce=await h(ie,ie);else if(ue){console.log(),console.log(chalk.gray(" Validating token..."));let e=await f(ie);if(!e.ok){const o=$(ie);if(o!==ie){const t=await f(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${ie} → ${o}`)),e=t,ie=o)}}if(!e.ok)return le(`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 tutor"):"")),ge=!0===e.aiEnabled,me=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),ce=await h(e.curriculumId||"LEARNDEMO01",ie),!ce)return le(`Could not open a learn curriculum for token '${ie}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${ie}`)+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 ${ie}`)+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(!ce)return le(`Unknown learn token: ${ie}`),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(" Every track has a free demo — ask for its name if you were not given one.")),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 ye=q(),pe=!1;try{ye&&ye.token===ie?D(ye):(ye=j(ie,ce.id,ce.totalCards),pe=!0),L(ye),F(ce,ye,pe)}catch{return le("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 ${ie}`)+chalk.gray(".")),void console.log()}const he=s(),fe=null!==he,be=fe?he.listeners("line").slice():[];fe&&he.removeAllListeners("line");const we=fe?he:o({input:process.stdin,output:process.stdout,terminal:!0}),$e=fe?we.prompt:null;fe&&(we.prompt=e.prototype.prompt);const ke=()=>{fe&&$e&&(we.prompt=$e)},ve=()=>{we.setPrompt(qe?chalk.bold.green(`icoa ${l()}> `):Ee?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(xe?"icoa learn ai> ":"icoa learn> ")),we.prompt()};let Ce=null,Ae=null,_e=null,Ie=null,xe=!1,Te=!1,Ee=!1,Me=null,Re=!1,Se=0,Pe=!1,qe=!1;const Le=new Map,je=()=>{let e=Le.get(ye.currentCard);return e||(e=[],Le.set(ye.currentCard,e)),e};let De=!1;const Oe=new Set;let Ne=!1,We=0;const Ye=()=>(S().language||"en").toLowerCase().startsWith("zh");te(ge),re(Oe);const Be=new Map;ne(Be);const Fe=[];let Ue=null;const ze=new Promise(e=>{Ue=e}),He=()=>{const e=Ue;Ue=null,e?.()},Je="1"===process.env.ICOA_LEARN_EMBEDDED,Ze=e=>ce.cards.find(o=>o.number===e);let Ke=null,Qe=null;const Ve=!ie.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(ie),Xe=async()=>{if(!Ve)return;const e=await M(ie);e.ok&&e.data&&(Ke=e.data)},Ge=e=>{const o=ce.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},eo=e=>{if(!me||!Ke)return null;const o=Ge(e);if(o<=Ke.unlocked_through_phase)return null;const t=Ke.phases.find(e=>e.phase===Ke.unlocked_through_phase),n=[chalk.yellow(Ye()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${Ke.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${Ke.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(Ye()?` ⚔ 练习赛 ${Ke.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${Ke.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(Ye()?` ⚖ 判分赛: 最好 ${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"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(Ye()?` ⭐ 提问研究: ${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")},oo=async e=>me?null===eo(e)?null:(await Xe(),eo(e)):null;me&&await Xe();const to=async e=>{const o=ce.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=ce.modules.find(e=>e.number===o.number+1);let n;if(ge){const e=await k({token:ie,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}Ve&&await Xe();const r=Ke?.phases.find(e=>e.phase===o.number);return ee(ce,ye,o,t,n,r),!0},no=()=>{Ne=!0,console.log(chalk.gray(Ye()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},ro=()=>{Me=null;const e=Ze(ye.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":U(e,ce),e.check?(_e=e.number,We=Date.now()):(O(ye,e.number),L(ye));break;case"mcq":z(e,ce),Ce=e.number;break;case"practical":J(e,ce),Ae=e.number;break;case"sim_demo":K(e,ce),O(ye,e.number),L(ye);break;case"milestone":Q(e,ce),B(ye,e.badge),O(ye,e.number),L(ye);break;case"arena_task":V(e,ce),O(ye,e.number),L(ye);break;case"coming_soon":X(e,ce),O(ye,e.number),L(ye)}so(e.number)},so=e=>{if(!me||!Ve||!Ke)return;const o=ce.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=Ke.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n);if(!s||s.passed)return;const l=chalk.bold.yellow(" ║ ");console.log(chalk.bold.yellow(" ╔═══════════════════════════════════════")),console.log(l+chalk.bold.white(`⚔ ${Ye()?"练习赛":"PY Arena"} ${o.number}-${n}`)),console.log(l+chalk.white(Ye()?"卡片你已学完 — 现在证明它。输入指令那刻计时开始。":"You learned the cards — now prove it. The clock starts when you type the command.")),console.log(l+chalk.gray(Ye()?`${s.n} 题 · AC ${s.need} 过关 · 限时 ${s.duration_minutes} 分钟 · 无限重开`:`${s.n} problems · AC ${s.need} to pass · ${s.duration_minutes} min · unlimited retries`)),console.log(l+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+chalk.gray(Ye()?" 开赛 ":" enter ")+chalk.gray("▸ ")+chalk.bold.green("ok")+chalk.gray(Ye()?" 先继续学(检查点不锁段内翻卡)":" keep studying (checkpoints never lock cards)")),console.log(chalk.bold.yellow(" ╚═══════════════════════════════════════")),console.log()},lo=()=>{ie.endsWith("DEMO01")?console.log(chalk.yellow(Ye()?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Ye()?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Ye()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},ao=async(e,o)=>{if(ge){Te=!0;try{console.log(),console.log(chalk.gray("deep"===o?Ye()?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Ye()?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await C({token:ie,cardNumber:ye.currentCard,question:e,mode:o,history:je().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(Ye()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(je().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(` (${Ye()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Ye()?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==_e&&console.log(chalk.gray(Ye()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Te=!1}}else lo()},io=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],co=async()=>{Te=!0;try{console.log();const e=await I({token:ie,curriculumId:ce.id,cardNumber:ye.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Ye()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Ye()?` 🏆 本卡实时 Top-3 — 第 ${ye.currentCard} 张`:` 🏆 Live top-3 — card ${ye.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(Ye()?" (你)":" (you)"):""))}else console.log(chalk.gray(Ye()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Be.set(ye.currentCard,e.mine.rank),console.log(chalk.white(Ye()?" 你: ":" You: ")+chalk.bold.yellow(Ye()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Ye()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):ge&&console.log(chalk.gray(Ye()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),se({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Ye()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Ye()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Ye()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Me="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("back")+chalk.gray(Ye()?" 返回卡片":" returns to the card")),console.log()}finally{Te=!1}},uo=(e,o)=>{const t=[];for(const n of e.split("\n")){if(""===n.trim()){t.push("");continue}let e="";for(const r of n.split(/\s+/))e&&e.length+1+r.length>o?(t.push(e),e=r):e=e?`${e} ${r}`:r;e&&t.push(e)}return t},go=e=>Qe.data.solved.includes(e.id)?"✅":Qe.tried.has(e.id)?"❌":"⬜",mo=()=>{const e=Qe.data,o=R(e.deadline),t=e.solved.length,n=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(Ye()?` · 第 ${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(Ye()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(Ye()?`(共 ${e.n} 题)`:` (of ${e.n})`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+go(e)+chalk.white(` ${e.title}`))}),console.log(),yo()},yo=()=>{console.log(chalk.gray(Ye()?" /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(Ye()?" /list 花名册 · 直接敲题号 = 读题 · ":" /list roster · a bare number reads it · ")+chalk.bold.cyan("back")+chalk.gray(Ye()?" 返回课程":" returns to the lesson")),console.log()},po=e=>{const o=parseInt(e,10),t=Qe.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(Ye()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}},ho=e=>{const o=po(e);if(!o)return;const{p:t,n:n}=o;console.log(),console.log(chalk.bold.white(` ${go(t)} ${t.title}`)),console.log();for(const e of uo(t.statement,66))console.log(chalk.white(` ${e}`));let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(Ye()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Ye()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(Ye()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(Ye()?" 四步:":" Four steps:")+chalk.gray((Ye()," ① "))+chalk.bold.green(`/edit ${n}`)+chalk.gray(Ye()?" 写码(vi:i 编辑 · Esc · :wq 存盘退出)":" write (vi: i to edit · Esc · :wq saves)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`)+chalk.gray(Ye()?" 样例自测 ③ ":" sample check ③ ")+chalk.bold.green(`/debug ${n}`)+chalk.gray(Ye()?" 自己输入调试(可选) ④ ":" free-input run (optional) ④ ")+chalk.bold.green(`/submit ${n}`)+chalk.gray(Ye()?" 判分":" judge")),console.log()},fo=async(e,o)=>{await new Promise(t=>{const n=process.stdin,s=!!n.isTTY&&!!n.isRaw;if(we.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e,o,{stdio:"inherit",cwd:Qe.dir}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&s)try{n.setRawMode(!0)}catch{}we.resume(),t()};l.on("close",a),l.on("error",a)})},bo=async e=>{const o=e.trim().toLowerCase(),s=Ee&&o.startsWith("/")?o.slice(1):o;if(!Te){if(null!==Ie){const o=e.trim(),t=Ie;if(Ie=null,""===o)console.log(chalk.gray(Ye()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=We>0?Date.now()-We:void 0;await w(ie,{curriculum_id:ce.id,card_number:t,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(Ye()?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Ye()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void ve()}if(Re){const o=e.trim();if(!o)return Re=!1,console.log(chalk.gray(Ye()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void ve();const t=await v({token:ie,nickname:o});if(t.ok)Re=!1,console.log(chalk.bold.green(Ye()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Ye()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Se+=1;const e="taken"===t.code?Ye()?"已被占用":"already taken":"bad_charset"===t.code?Ye()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?Ye()?"未通过审核":"did not pass review":t.message||"error";if(!(Se>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ye()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void ve();Re=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ye()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void ve()}if(De){De=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Te=!0;try{console.log(),console.log(chalk.gray(Ye()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await A({token:ie,cardNumber:ye.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Ye()?"评审暂不可用。":"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(Ye()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(Ye()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Ye()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Ye()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Ye()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(Ye()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=Ye()?` 本卡排名 #${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(Ye()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Ye()?` 第 ${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 io(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(Ye()?" 改进提问: ":" 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(` (${Ye()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Oe.add(ye.currentCard):Oe.delete(ye.currentCard),"number"==typeof e.rank&&Be.set(ye.currentCard,e.rank);const o=await I({token:ie,curriculumId:ce.id,cardNumber:ye.currentCard});o.ok&&o.totals&&o.chapters&&(se({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!de&&(Re=!0,Se=0,console.log(chalk.bold.yellow(Ye()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Ye()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Ye()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Te=!1}})():(console.log(chalk.gray(Ye()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==_e&&(console.log(chalk.gray(Ye()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ve()}if(Ne)return Ne=!1,ro(),void ve();if(o){if(qe)return"exit"===await a(e.trim())&&(qe=!1),void ve();if(xe){if(["q","quit","exit","back","b","menu"].includes(o))return xe=!1,console.log(chalk.gray(Ye()?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ve();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await ao(n,t?"fast":"deep"),console.log(chalk.gray(Ye()?" (q = 返回卡片 · ! 开头 = 快答)":" (q = back to card · prefix ! = quick answer)"))),void ve()}if(Ee&&Qe){if("back"===o||"b"===o||"exit"===o)return Ee=!1,console.log(chalk.gray(Ye()?" 已离开竞技场,回到课程。":" Left the arena — back to the lesson.")),ro(),void ve();if(/^\d+$/.test(o))return ho(o),void ve();const e=/^\/?(read|open|edit|run|debug|list)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,r]=e;return"list"===o?mo():r?"read"===o||"open"===o?ho(r):"edit"===o?await(async e=>{const o=po(e);if(o){try{n("command -v vi",{stdio:"ignore"})}catch{return console.log(chalk.yellow(Ye()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),void console.log(chalk.bold.white(` ${y(Qe.dir,`sol-${o.n}.py`)}`))}console.log(chalk.gray(Ye()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await fo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(Ye()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Ye()?" 自测样例。":" to self-check the sample.")),console.log()}})(r):"run"===o?(e=>{const o=po(e);if(!o)return;const{p:n,n:r}=o,s=y(Qe.dir,`sol-${r}.py`);if(!c(s))return void console.log(chalk.yellow(Ye()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const l=(n.samples??[])[0];if(!l)return void console.log(chalk.gray(Ye()?` 本题无样例(设计如此)— 用 /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",[s],{input:l.in.endsWith("\n")?l.in:l.in+"\n",timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if(o.killed)console.log(chalk.yellow(Ye()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Ye()?" ✗ 程序报错:":" ✗ 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(),d=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(Ye()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Ye()?" 样例应输出:":" Sample expects:"));for(const e of d.split("\n"))console.log(chalk.green(` ${e}`));i===d?console.log(chalk.bold.green(Ye()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Ye()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Ye()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Ye()?" 改完再 /run。":" then /run again.")),console.log()})(r):"debug"===o&&await(async e=>{const o=po(e);if(!o)return;const t=y(Qe.dir,`sol-${o.n}.py`);c(t)?(console.log(chalk.gray(Ye()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log(),await fo("python3",[`sol-${o.n}.py`]),console.log(),console.log(chalk.gray(Ye()?" 回到竞技场。":" Back in the arena.")),console.log()):console.log(chalk.yellow(Ye()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`))})(r):console.log(chalk.yellow(Ye()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(Ye()?" (花名册: /list)":" (roster: /list)")),void ve()}if("contest"===o||"/contest"===o)return mo(),void ve();if("submit"!==s&&!s.startsWith("submit ")&&!o.startsWith("contest ")&&"contest reset"!==o&&"quit"!==o&&"q"!==o&&"exit"!==o&&"menu"!==o&&"menu confirm"!==o)return console.log(chalk.gray(Ye()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void ve()}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(Ye()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void ve()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(we.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}we.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void ve()}if("ai4ioai"===o||"/ai4ioai"===o)return await i()&&(qe=!0),void ve();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!ge)return lo(),void ve();Pe||(Pe=!0,console.log(),console.log(chalk.bold.cyan(Ye()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Ye()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Ye()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Ye()||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){xe=!0;const e=Ze(ye.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Ye()?"AI 导师":"AI tutor")+(o?chalk.gray(Ye()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ye()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void ve()}return await ao(n,t?"fast":"deep"),void ve()}if(!Ee&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!ge)return lo(),void ve();const e=Ze(ye.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Ye()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Ye()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ye()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Ye()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Ye()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Ye()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Ye()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),De=!0,void ve()}if(!Ee&&("/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!ge)return lo(),void ve();const e=/^\/?view ([1-3])$/.exec(o);return await(async e=>{Te=!0;try{console.log();const o=await _({token:ie,cardNumber:ye.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Ye()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Oe.delete(ye.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Oe.add(ye.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Ye()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${ye.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${ye.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Ye()?` (第 ${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(Ye()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=io(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(Ye()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Me="view",console.log(chalk.gray((Ye()," "))+chalk.bold.cyan("back")+chalk.gray(Ye()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Te=!1}})(e?parseInt(e[1],10):void 0),void ve()}if("/honors"===o||"honors"===o)return de?(console.log(),console.log(chalk.gray(Ye()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void ve()):(await co(),void ve());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return G(ce,ye),void ve();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(S().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ve();const t=ce.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,s=r?n:"en";return P({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),_e=null,Ce=null,Ae=null,Ie=null,Ne=!1,De=!1,ro(),void ve()}if("sim"===o){const e=Ze(ye.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=m(p(import.meta.url)),o=[y(e,"..","..","panda","mujoco-launcher.py"),y(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(c(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 ve()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ve())}if("bookmark"===o){const e=ye.currentCard;return ye.bookmarks.includes(e)||ye.bookmarks.push(e),L(ye),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ve()}if("e"===o)return Ie=ye.currentCard,console.log(chalk.gray(Ye()?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ve();if("back"===o||"b"===o)return"view"===Me?(await co(),void ve()):"honors"===Me?(Me=null,ro(),void ve()):(ye.currentCard>1&&(ye.currentCard-=1),Ce=null,Ae=null,_e=null,L(ye),ro(),void ve());if("contest"===o||"contest start"===o||"contest status"===o||"contest reset"===o||/^contest [1-9]$/.test(o)){if(!Ve)return console.log(chalk.yellow(Ye()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void ve();const e=Ge(ye.currentCard);if("contest reset"===o){const o=await x(ie,e);return o.ok?(console.log(chalk.yellow(Ye()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`)),Qe=null,Ee=!1):console.log(chalk.red(` ✗ ${o.message||"reset failed"}`)),void ve()}const t=/^contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Ye()?" 连接判分赛…":" Contacting contest server…"));const n=await T(ie,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(Ye()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void ve();const r=n.data,s=y(process.cwd(),"icoa-contest",`${ce.id}-phase${e}-g${r.slot}`);d(s,{recursive:!0});const l=Qe&&Qe.phase===e&&Qe.data.slot===r.slot?Qe.tried:new Set;Qe={phase:e,dir:s,data:r,tried:l},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,s=(t.samples??[])[0];s&&g(y(o,`sample-${r}.txt`),s.in.endsWith("\n")?s.in:s.in+"\n");const l=y(o,`sol-${r}.py`);if(c(l))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...uo(t.statement,72).map(e=>e?`# ${e}`:"#")];if(s){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of s.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of s.out.split("\n"))a.push(`# ${e}`)}a.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),g(l,a.join("\n"))})})(r,s),Ee=!0,mo(),console.log(chalk.gray(Ye()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(s));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(Ye()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(Ye()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void ve()}if("submit"===s)return console.log(chalk.yellow(Ye()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(Ye()?" 例如 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)")),Qe||console.log(chalk.gray(Ye()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void ve();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!Qe)return console.log(chalk.yellow(Ye()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void ve();const n=Qe.data.problems,r=parseInt(o,10);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(Ye()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void ve();const l=n.findIndex(e=>e.id===o)+1,a=t||y(Qe.dir,`sol-${l}.py`);let i;try{i=u(a,"utf-8")}catch{return console.log(chalk.red(Ye()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void ve()}console.log(chalk.gray(Ye()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await E(ie,Qe.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(Ye()?" 没有进行中的计时(可能已超时)— 输入 contest 查看/重开。":" No live timed attempt (time may be up) — type contest.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void ve();const d=c.data;if(d.already_ac)console.log(chalk.green(Ye()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(" ✓ AC")+chalk.gray(` · ${d.total_tests??"?"} tests · ${d.time_ms??"?"}ms`)),Qe.data.solved.includes(o)||Qe.data.solved.push(o),Qe.tried.delete(o);else{Qe.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?Ye()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(Ye()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=R(d.deadline||"");if(console.log(chalk.white(Ye()?` 进度: ${d.ac_count}/${d.need} 题(共 ${d.n})`:` Progress: ${d.ac_count}/${d.need} AC (of ${d.n})`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(Ye()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Xe();else if(!d.late){const e=n.findIndex(e=>!Qe.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Ye()?" 下一题: ":" Next: ")+chalk.bold.green(`submit ${e+1}`)+chalk.gray(` ${n[e].title}`))}return void ve()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>ce.totalCards)return console.log(chalk.yellow(` Card number must be 1..${ce.totalCards}. Try: `)+chalk.bold.green("card 1")),void ve();const n=await oo(t);return n?(console.log(n),void ve()):(ye.currentCard=t,Ce=null,Ae=null,_e=null,L(ye),ro(),void ve())}if(null!==_e&&["y","yes","n","no"].includes(o)){const e=Ze(_e);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-We;O(ye,e.number),W(ye,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),L(ye);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),Fe.push(b(ie,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),_e=null,e.solution&&e.solution.length>0)return void ve();if(ye.currentCard<ce.totalCards){const e=ye.currentCard,o=await oo(e+1);if(o)return await to(e),console.log(o),void ve();ye.currentCard+=1,L(ye),await to(e)?no():ro(),ve()}else oe(ce,ye),ve();return}}if(null!==Ce&&["a","b","c","d"].includes(o)){const e=Ze(Ce);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(N(ye,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),O(ye,e.number),L(ye),H(e,t,n,ye),Fe.push(b(ie,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Ce=null,n)if(ye.currentCard<ce.totalCards){const e=await oo(ye.currentCard+1);if(e)return console.log(e),void ve();ye.currentCard+=1,L(ye),ro()}else oe(ce,ye),ve();else ve();return}}if(null!==Ae){if("done"===o){const e=Ze(Ae);if(e&&"practical"===e.type)return Y(ye,e.number),O(ye,e.number),L(ye),Z(e),Ae=null,void ve()}if("skip"===o)return O(ye,Ae),L(ye),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Ae=null,void ve()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==Ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ve();if(null!==Ae)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ve();if(null!==_e)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ve();const e=ye.currentCard,o=e<ce.totalCards?await oo(e+1):null;return o?(await to(e),console.log(o),void ve()):(ye.currentCard+=1,L(ye),ye.currentCard>ce.totalCards?oe(ce,ye):await to(e)?no():ro(),void ve())}if(null!==_e)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ve();if(null!==Ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ve();if(null!==Ae)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ve();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")),ve()}else if(Fe.length>0&&await Promise.race([Promise.allSettled(Fe),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ye.streakDays} day(s)`)),console.log(),fe){we.removeAllListeners("line"),ke();for(const e of be)we.on("line",e);we.prompt(),He()}else we.removeAllListeners("line"),we.close();else if(Fe.length>0&&await Promise.race([Promise.allSettled(Fe),new Promise(e=>setTimeout(e,3e3))]),we.removeAllListeners("line"),ke(),fe||!Je){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(fe?we:void 0),He()}else we.close()}else ve()}};we.on("line",e=>{bo(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.")),ve()})}),fe||we.on("close",async()=>{Fe.length>0&&await Promise.race([Promise.allSettled(Fe),new Promise(e=>setTimeout(e,5e3))]),Je?He():process.exit(0)});try{ro(),ve();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(le("Could not render this card — the curriculum may be malformed."),fe){we.removeAllListeners("line"),ke();for(const e of be)we.on("line",e);we.prompt()}else we.close();He()}await ze}),ae.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(),s=await h(e),l=Date.now()-o;if(s){const e=s.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(s).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${l.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
|
1
|
+
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{getMainRl as s}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as l,handleAi4ioaiMessage as a,startAi4ioaiChat as i}from"./ai4ioai.js";import{existsSync as c,mkdirSync as d,readFileSync as u,writeFileSync as g}from"node:fs";import{dirname as m,join as y}from"node:path";import{fileURLToPath as p}from"node:url";import{loadCurriculumById as h,validateEAToken as f,syncProgress as b,syncCardFeedback as w}from"../lib/learn-curricula.js";import{normalizeTokenBody as $}from"../lib/token-format.js";import{fetchMyScores as k,setNickname as v,streamLearnTutor as C,submitPqs as A,viewPqsTop as _,viewHonors as I}from"../lib/learn-ai.js";import{contestReset as x,contestStart as T,contestSubmit as E,fetchGate as M,timeLeft as R}from"../lib/learn-contest.js";import{getConfig as S,saveConfig as P}from"../lib/config.js";import{loadLearnState as q,saveLearnState as L,newLearnState as j,updateStreak as D,markCardComplete as O,recordMCQ as N,recordCheck as W,markPracticalComplete as Y,addAchievement as B}from"../lib/learn-state.js";import{renderWelcome as F,renderKnowledgeCard as U,renderMCQCard as z,renderMCQFeedback as H,renderPracticalCard as J,renderPracticalSuccess as Z,renderSimDemoCard as K,renderMilestone as Q,renderArenaTaskCard as V,renderComingSoonCard as X,renderStatus as G,renderPhaseComplete as ee,renderCurriculumComplete as oe,setLearnAiEnabled as te,setLearnHonorRanks as ne,setLearnPqsViewCards as re,renderHonorWall as se}from"../lib/learn-render.js";import{printError as le}from"../lib/ui.js";export function registerLearnCommand(ae){ae.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ae=>{ae&&ae.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(),ae="LEARNDEMO01");let ie=ae.trim().toUpperCase(),ce=null;const de=/^[A-Z0-9]+DEMO01$/i.test(ie),ue=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(ie);let ge=!1,me=!1;if(de)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),ce=await h(ie,ie);else if(ue){console.log(),console.log(chalk.gray(" Validating token..."));let e=await f(ie);if(!e.ok){const o=$(ie);if(o!==ie){const t=await f(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${ie} → ${o}`)),e=t,ie=o)}}if(!e.ok)return le(`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 tutor"):"")),ge=!0===e.aiEnabled,me=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),ce=await h(e.curriculumId||"LEARNDEMO01",ie),!ce)return le(`Could not open a learn curriculum for token '${ie}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${ie}`)+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 ${ie}`)+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(!ce)return le(`Unknown learn token: ${ie}`),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(" Every track has a free demo — ask for its name if you were not given one.")),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 ye=q(),pe=!1;try{ye&&ye.token===ie?D(ye):(ye=j(ie,ce.id,ce.totalCards),pe=!0),L(ye),F(ce,ye,pe)}catch{return le("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 ${ie}`)+chalk.gray(".")),void console.log()}const he=s(),fe=null!==he,be=fe?he.listeners("line").slice():[];fe&&he.removeAllListeners("line");const we=fe?he:o({input:process.stdin,output:process.stdout,terminal:!0}),$e=fe?we.prompt:null;fe&&(we.prompt=e.prototype.prompt);const ke=()=>{fe&&$e&&(we.prompt=$e)},ve=()=>{we.setPrompt(qe?chalk.bold.green(`icoa ${l()}> `):Ee?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(xe?"icoa learn ai> ":"icoa learn> ")),we.prompt()};let Ce=null,Ae=null,_e=null,Ie=null,xe=!1,Te=!1,Ee=!1,Me=null,Re=!1,Se=0,Pe=!1,qe=!1;const Le=new Map,je=()=>{let e=Le.get(ye.currentCard);return e||(e=[],Le.set(ye.currentCard,e)),e};let De=!1;const Oe=new Set;let Ne=!1,We=0;const Ye=()=>(S().language||"en").toLowerCase().startsWith("zh");te(ge),re(Oe);const Be=new Map;ne(Be);const Fe=[];let Ue=null;const ze=new Promise(e=>{Ue=e}),He=()=>{const e=Ue;Ue=null,e?.()},Je="1"===process.env.ICOA_LEARN_EMBEDDED,Ze=e=>ce.cards.find(o=>o.number===e);let Ke=null,Qe=null;const Ve=!ie.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(ie),Xe=async()=>{if(!Ve)return;const e=await M(ie);e.ok&&e.data&&(Ke=e.data)},Ge=e=>{const o=ce.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},eo=e=>{if(!me||!Ke)return null;const o=Ge(e);if(o<=Ke.unlocked_through_phase)return null;const t=Ke.phases.find(e=>e.phase===Ke.unlocked_through_phase),n=[chalk.yellow(Ye()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${Ke.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${Ke.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(Ye()?` ⚔ 练习赛 ${Ke.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${Ke.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(Ye()?` ⚖ 判分赛: 最好 ${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"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(Ye()?` ⭐ 提问研究: ${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")},oo=async e=>me?null===eo(e)?null:(await Xe(),eo(e)):null;me&&await Xe();const to=async e=>{const o=ce.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=ce.modules.find(e=>e.number===o.number+1);let n;if(ge){const e=await k({token:ie,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}Ve&&await Xe();const r=Ke?.phases.find(e=>e.phase===o.number);return ee(ce,ye,o,t,n,r),!0},no=()=>{Ne=!0,console.log(chalk.gray(Ye()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},ro=()=>{Me=null;const e=Ze(ye.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":U(e,ce),e.check?(_e=e.number,We=Date.now()):(O(ye,e.number),L(ye));break;case"mcq":z(e,ce),Ce=e.number;break;case"practical":J(e,ce),Ae=e.number;break;case"sim_demo":K(e,ce),O(ye,e.number),L(ye);break;case"milestone":Q(e,ce),B(ye,e.badge),O(ye,e.number),L(ye);break;case"arena_task":V(e,ce),O(ye,e.number),L(ye);break;case"coming_soon":X(e,ce),O(ye,e.number),L(ye)}so(e.number)},so=e=>{if(!me||!Ve||!Ke)return;const o=ce.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=Ke.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n);if(!s||s.passed)return;const l=chalk.bold.yellow(" ║ "),a="═".repeat(64);console.log(chalk.bold.yellow(` ╔${a}`)),console.log(l+chalk.bold.white(`⚔ ${Ye()?"练习赛":"PY Arena"} ${o.number}-${n}`)),Ye()?console.log(l+chalk.white("卡片你已学完 — 现在证明它。输入指令那刻计时开始。")):(console.log(l+chalk.white("You learned the cards — now prove it.")),console.log(l+chalk.white("The clock starts the moment you type the command."))),console.log(l+chalk.gray(Ye()?`${s.n} 题 · AC ${s.need} 过关 · 限时 ${s.duration_minutes} 分钟 · 无限重开`:`${s.n} problems · AC ${s.need} to pass · ${s.duration_minutes} min · unlimited retries`)),console.log(l+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+chalk.gray(Ye()?" 开赛 · ":" enter · ")+chalk.gray("▸ ")+chalk.bold.green("ok")+chalk.gray(Ye()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)")),console.log(chalk.bold.yellow(` ╚${a}`)),console.log()},lo=()=>{ie.endsWith("DEMO01")?console.log(chalk.yellow(Ye()?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Ye()?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Ye()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},ao=async(e,o)=>{if(ge){Te=!0;try{console.log(),console.log(chalk.gray("deep"===o?Ye()?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Ye()?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await C({token:ie,cardNumber:ye.currentCard,question:e,mode:o,history:je().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(Ye()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(je().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(` (${Ye()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Ye()?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==_e&&console.log(chalk.gray(Ye()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Te=!1}}else lo()},io=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],co=async()=>{Te=!0;try{console.log();const e=await I({token:ie,curriculumId:ce.id,cardNumber:ye.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Ye()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Ye()?` 🏆 本卡实时 Top-3 — 第 ${ye.currentCard} 张`:` 🏆 Live top-3 — card ${ye.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(Ye()?" (你)":" (you)"):""))}else console.log(chalk.gray(Ye()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Be.set(ye.currentCard,e.mine.rank),console.log(chalk.white(Ye()?" 你: ":" You: ")+chalk.bold.yellow(Ye()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Ye()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):ge&&console.log(chalk.gray(Ye()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),se({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Ye()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Ye()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Ye()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Me="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("back")+chalk.gray(Ye()?" 返回卡片":" returns to the card")),console.log()}finally{Te=!1}},uo=(e,o)=>{const t=[];for(const n of e.split("\n")){if(""===n.trim()){t.push("");continue}let e="";for(const r of n.split(/\s+/))e&&e.length+1+r.length>o?(t.push(e),e=r):e=e?`${e} ${r}`:r;e&&t.push(e)}return t},go=e=>Qe.data.solved.includes(e.id)?"✅":Qe.tried.has(e.id)?"❌":"⬜",mo=()=>{const e=Qe.data,o=R(e.deadline),t=e.solved.length,n=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(Ye()?` · 第 ${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(Ye()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(Ye()?`(共 ${e.n} 题)`:` (of ${e.n})`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+go(e)+chalk.white(` ${e.title}`))}),console.log(),yo()},yo=()=>{console.log(chalk.gray(Ye()?" /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(Ye()?" /list 花名册 · 直接敲题号 = 读题 · ":" /list roster · a bare number reads it · ")+chalk.bold.cyan("back")+chalk.gray(Ye()?" 返回课程":" returns to the lesson")),console.log()},po=e=>{const o=parseInt(e,10),t=Qe.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(Ye()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}},ho=e=>{const o=po(e);if(!o)return;const{p:t,n:n}=o;console.log(),console.log(chalk.bold.white(` ${go(t)} ${t.title}`)),console.log();for(const e of uo(t.statement,66))console.log(chalk.white(` ${e}`));let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(Ye()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Ye()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(Ye()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(Ye()?" 四步:":" Four steps:")+chalk.gray((Ye()," ① "))+chalk.bold.green(`/edit ${n}`)+chalk.gray(Ye()?" 写码(vi:i 编辑 · Esc · :wq 存盘退出)":" write (vi: i to edit · Esc · :wq saves)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`)+chalk.gray(Ye()?" 样例自测 ③ ":" sample check ③ ")+chalk.bold.green(`/debug ${n}`)+chalk.gray(Ye()?" 自己输入调试(可选) ④ ":" free-input run (optional) ④ ")+chalk.bold.green(`/submit ${n}`)+chalk.gray(Ye()?" 判分":" judge")),console.log()},fo=async(e,o)=>{await new Promise(t=>{const n=process.stdin,s=!!n.isTTY&&!!n.isRaw;if(we.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e,o,{stdio:"inherit",cwd:Qe.dir}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&s)try{n.setRawMode(!0)}catch{}we.resume(),t()};l.on("close",a),l.on("error",a)})},bo=async e=>{const o=e.trim().toLowerCase(),s=Ee&&o.startsWith("/")?o.slice(1):o;if(!Te){if(null!==Ie){const o=e.trim(),t=Ie;if(Ie=null,""===o)console.log(chalk.gray(Ye()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=We>0?Date.now()-We:void 0;await w(ie,{curriculum_id:ce.id,card_number:t,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(Ye()?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Ye()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void ve()}if(Re){const o=e.trim();if(!o)return Re=!1,console.log(chalk.gray(Ye()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void ve();const t=await v({token:ie,nickname:o});if(t.ok)Re=!1,console.log(chalk.bold.green(Ye()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Ye()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Se+=1;const e="taken"===t.code?Ye()?"已被占用":"already taken":"bad_charset"===t.code?Ye()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?Ye()?"未通过审核":"did not pass review":t.message||"error";if(!(Se>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ye()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void ve();Re=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ye()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void ve()}if(De){De=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Te=!0;try{console.log(),console.log(chalk.gray(Ye()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await A({token:ie,cardNumber:ye.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Ye()?"评审暂不可用。":"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(Ye()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(Ye()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Ye()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Ye()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Ye()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(Ye()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=Ye()?` 本卡排名 #${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(Ye()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Ye()?` 第 ${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 io(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(Ye()?" 改进提问: ":" 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(` (${Ye()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Oe.add(ye.currentCard):Oe.delete(ye.currentCard),"number"==typeof e.rank&&Be.set(ye.currentCard,e.rank);const o=await I({token:ie,curriculumId:ce.id,cardNumber:ye.currentCard});o.ok&&o.totals&&o.chapters&&(se({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!de&&(Re=!0,Se=0,console.log(chalk.bold.yellow(Ye()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Ye()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Ye()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Te=!1}})():(console.log(chalk.gray(Ye()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==_e&&(console.log(chalk.gray(Ye()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ve()}if(Ne)return Ne=!1,ro(),void ve();if(o){if(qe)return"exit"===await a(e.trim())&&(qe=!1),void ve();if(xe){if(["q","quit","exit","back","b","menu"].includes(o))return xe=!1,console.log(chalk.gray(Ye()?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ve();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await ao(n,t?"fast":"deep"),console.log(chalk.gray(Ye()?" (q = 返回卡片 · ! 开头 = 快答)":" (q = back to card · prefix ! = quick answer)"))),void ve()}if(Ee&&Qe){if("back"===o||"b"===o||"exit"===o)return Ee=!1,console.log(chalk.gray(Ye()?" 已离开竞技场,回到课程。":" Left the arena — back to the lesson.")),ro(),void ve();if(/^\d+$/.test(o))return ho(o),void ve();const e=/^\/?(read|open|edit|run|debug|list)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,r]=e;return"list"===o?mo():r?"read"===o||"open"===o?ho(r):"edit"===o?await(async e=>{const o=po(e);if(o){try{n("command -v vi",{stdio:"ignore"})}catch{return console.log(chalk.yellow(Ye()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),void console.log(chalk.bold.white(` ${y(Qe.dir,`sol-${o.n}.py`)}`))}console.log(chalk.gray(Ye()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await fo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(Ye()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Ye()?" 自测样例。":" to self-check the sample.")),console.log()}})(r):"run"===o?(e=>{const o=po(e);if(!o)return;const{p:n,n:r}=o,s=y(Qe.dir,`sol-${r}.py`);if(!c(s))return void console.log(chalk.yellow(Ye()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const l=(n.samples??[])[0];if(!l)return void console.log(chalk.gray(Ye()?` 本题无样例(设计如此)— 用 /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",[s],{input:l.in.endsWith("\n")?l.in:l.in+"\n",timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if(o.killed)console.log(chalk.yellow(Ye()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Ye()?" ✗ 程序报错:":" ✗ 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(),d=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(Ye()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Ye()?" 样例应输出:":" Sample expects:"));for(const e of d.split("\n"))console.log(chalk.green(` ${e}`));i===d?console.log(chalk.bold.green(Ye()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Ye()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Ye()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Ye()?" 改完再 /run。":" then /run again.")),console.log()})(r):"debug"===o&&await(async e=>{const o=po(e);if(!o)return;const t=y(Qe.dir,`sol-${o.n}.py`);c(t)?(console.log(chalk.gray(Ye()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log(),await fo("python3",[`sol-${o.n}.py`]),console.log(),console.log(chalk.gray(Ye()?" 回到竞技场。":" Back in the arena.")),console.log()):console.log(chalk.yellow(Ye()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`))})(r):console.log(chalk.yellow(Ye()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(Ye()?" (花名册: /list)":" (roster: /list)")),void ve()}if("contest"===o||"/contest"===o)return mo(),void ve();if("submit"!==s&&!s.startsWith("submit ")&&!o.startsWith("contest ")&&"contest reset"!==o&&"quit"!==o&&"q"!==o&&"exit"!==o&&"menu"!==o&&"menu confirm"!==o)return console.log(chalk.gray(Ye()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void ve()}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(Ye()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void ve()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(we.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}we.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void ve()}if("ai4ioai"===o||"/ai4ioai"===o)return await i()&&(qe=!0),void ve();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!ge)return lo(),void ve();Pe||(Pe=!0,console.log(),console.log(chalk.bold.cyan(Ye()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Ye()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Ye()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Ye()||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){xe=!0;const e=Ze(ye.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Ye()?"AI 导师":"AI tutor")+(o?chalk.gray(Ye()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ye()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void ve()}return await ao(n,t?"fast":"deep"),void ve()}if(!Ee&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!ge)return lo(),void ve();const e=Ze(ye.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Ye()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Ye()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ye()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Ye()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Ye()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Ye()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Ye()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),De=!0,void ve()}if(!Ee&&("/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!ge)return lo(),void ve();const e=/^\/?view ([1-3])$/.exec(o);return await(async e=>{Te=!0;try{console.log();const o=await _({token:ie,cardNumber:ye.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Ye()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Oe.delete(ye.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Oe.add(ye.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Ye()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${ye.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${ye.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Ye()?` (第 ${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(Ye()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=io(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(Ye()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Me="view",console.log(chalk.gray((Ye()," "))+chalk.bold.cyan("back")+chalk.gray(Ye()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Te=!1}})(e?parseInt(e[1],10):void 0),void ve()}if("/honors"===o||"honors"===o)return de?(console.log(),console.log(chalk.gray(Ye()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void ve()):(await co(),void ve());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return G(ce,ye),void ve();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(S().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ve();const t=ce.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,s=r?n:"en";return P({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),_e=null,Ce=null,Ae=null,Ie=null,Ne=!1,De=!1,ro(),void ve()}if("sim"===o){const e=Ze(ye.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=m(p(import.meta.url)),o=[y(e,"..","..","panda","mujoco-launcher.py"),y(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(c(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 ve()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ve())}if("bookmark"===o){const e=ye.currentCard;return ye.bookmarks.includes(e)||ye.bookmarks.push(e),L(ye),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ve()}if("e"===o)return Ie=ye.currentCard,console.log(chalk.gray(Ye()?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ve();if("back"===o||"b"===o)return"view"===Me?(await co(),void ve()):"honors"===Me?(Me=null,ro(),void ve()):(ye.currentCard>1&&(ye.currentCard-=1),Ce=null,Ae=null,_e=null,L(ye),ro(),void ve());if("contest"===o||"contest start"===o||"contest status"===o||"contest reset"===o||/^contest [1-9]$/.test(o)){if(!Ve)return console.log(chalk.yellow(Ye()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void ve();const e=Ge(ye.currentCard);if("contest reset"===o){const o=await x(ie,e);return o.ok?(console.log(chalk.yellow(Ye()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`)),Qe=null,Ee=!1):console.log(chalk.red(` ✗ ${o.message||"reset failed"}`)),void ve()}const t=/^contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Ye()?" 连接判分赛…":" Contacting contest server…"));const n=await T(ie,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(Ye()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void ve();const r=n.data,s=y(process.cwd(),"icoa-contest",`${ce.id}-phase${e}-g${r.slot}`);d(s,{recursive:!0});const l=Qe&&Qe.phase===e&&Qe.data.slot===r.slot?Qe.tried:new Set;Qe={phase:e,dir:s,data:r,tried:l},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,s=(t.samples??[])[0];s&&g(y(o,`sample-${r}.txt`),s.in.endsWith("\n")?s.in:s.in+"\n");const l=y(o,`sol-${r}.py`);if(c(l))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...uo(t.statement,72).map(e=>e?`# ${e}`:"#")];if(s){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of s.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of s.out.split("\n"))a.push(`# ${e}`)}a.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),g(l,a.join("\n"))})})(r,s),Ee=!0,mo(),console.log(chalk.gray(Ye()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(s));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(Ye()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(Ye()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void ve()}if("submit"===s)return console.log(chalk.yellow(Ye()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(Ye()?" 例如 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)")),Qe||console.log(chalk.gray(Ye()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void ve();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!Qe)return console.log(chalk.yellow(Ye()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void ve();const n=Qe.data.problems,r=parseInt(o,10);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(Ye()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void ve();const l=n.findIndex(e=>e.id===o)+1,a=t||y(Qe.dir,`sol-${l}.py`);let i;try{i=u(a,"utf-8")}catch{return console.log(chalk.red(Ye()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void ve()}console.log(chalk.gray(Ye()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await E(ie,Qe.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(Ye()?" 没有进行中的计时(可能已超时)— 输入 contest 查看/重开。":" No live timed attempt (time may be up) — type contest.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void ve();const d=c.data;if(d.already_ac)console.log(chalk.green(Ye()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(" ✓ AC")+chalk.gray(` · ${d.total_tests??"?"} tests · ${d.time_ms??"?"}ms`)),Qe.data.solved.includes(o)||Qe.data.solved.push(o),Qe.tried.delete(o);else{Qe.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?Ye()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(Ye()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=R(d.deadline||"");if(console.log(chalk.white(Ye()?` 进度: ${d.ac_count}/${d.need} 题(共 ${d.n})`:` Progress: ${d.ac_count}/${d.need} AC (of ${d.n})`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(Ye()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Xe();else if(!d.late){const e=n.findIndex(e=>!Qe.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Ye()?" 下一题: ":" Next: ")+chalk.bold.green(`submit ${e+1}`)+chalk.gray(` ${n[e].title}`))}return void ve()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>ce.totalCards)return console.log(chalk.yellow(` Card number must be 1..${ce.totalCards}. Try: `)+chalk.bold.green("card 1")),void ve();const n=await oo(t);return n?(console.log(n),void ve()):(ye.currentCard=t,Ce=null,Ae=null,_e=null,L(ye),ro(),void ve())}if(null!==_e&&["y","yes","n","no"].includes(o)){const e=Ze(_e);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-We;O(ye,e.number),W(ye,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),L(ye);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),Fe.push(b(ie,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),_e=null,e.solution&&e.solution.length>0)return void ve();if(ye.currentCard<ce.totalCards){const e=ye.currentCard,o=await oo(e+1);if(o)return await to(e),console.log(o),void ve();ye.currentCard+=1,L(ye),await to(e)?no():ro(),ve()}else oe(ce,ye),ve();return}}if(null!==Ce&&["a","b","c","d"].includes(o)){const e=Ze(Ce);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(N(ye,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),O(ye,e.number),L(ye),H(e,t,n,ye),Fe.push(b(ie,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Ce=null,n)if(ye.currentCard<ce.totalCards){const e=await oo(ye.currentCard+1);if(e)return console.log(e),void ve();ye.currentCard+=1,L(ye),ro()}else oe(ce,ye),ve();else ve();return}}if(null!==Ae){if("done"===o){const e=Ze(Ae);if(e&&"practical"===e.type)return Y(ye,e.number),O(ye,e.number),L(ye),Z(e),Ae=null,void ve()}if("skip"===o)return O(ye,Ae),L(ye),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Ae=null,void ve()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==Ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ve();if(null!==Ae)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ve();if(null!==_e)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ve();const e=ye.currentCard,o=e<ce.totalCards?await oo(e+1):null;return o?(await to(e),console.log(o),void ve()):(ye.currentCard+=1,L(ye),ye.currentCard>ce.totalCards?oe(ce,ye):await to(e)?no():ro(),void ve())}if(null!==_e)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ve();if(null!==Ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ve();if(null!==Ae)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ve();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")),ve()}else if(Fe.length>0&&await Promise.race([Promise.allSettled(Fe),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ye.streakDays} day(s)`)),console.log(),fe){we.removeAllListeners("line"),ke();for(const e of be)we.on("line",e);we.prompt(),He()}else we.removeAllListeners("line"),we.close();else if(Fe.length>0&&await Promise.race([Promise.allSettled(Fe),new Promise(e=>setTimeout(e,3e3))]),we.removeAllListeners("line"),ke(),fe||!Je){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(fe?we:void 0),He()}else we.close()}else ve()}};we.on("line",e=>{bo(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.")),ve()})}),fe||we.on("close",async()=>{Fe.length>0&&await Promise.race([Promise.allSettled(Fe),new Promise(e=>setTimeout(e,5e3))]),Je?He():process.exit(0)});try{ro(),ve();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(le("Could not render this card — the curriculum may be malformed."),fe){we.removeAllListeners("line"),ke();for(const e of be)we.on("line",e);we.prompt()}else we.close();He()}await ze}),ae.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(),s=await h(e),l=Date.now()-o;if(s){const e=s.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(s).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${l.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()})}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icoa-cli",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.405",
|
|
4
4
|
"description": "ICOA CLI — The world's first CLI-native cyber & AI security olympiad terminal: AI4CTF (Day 1), CTF4AI (Day 2), VLA4CTF (Pioneer Round — embodied AI)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|