icoa-cli 2.19.427 → 2.19.429

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{logCommand as l}from"../lib/logger.js";import{getMainRl as s}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as a,handleAi4ioaiMessage as i,startAi4ioaiChat as c}from"./ai4ioai.js";import{existsSync as d,mkdirSync as g,readdirSync as u,readFileSync as m,renameSync as y,writeFileSync as h}from"node:fs";import{dirname as p,join as f}from"node:path";import{fileURLToPath as b}from"node:url";import{loadCurriculumById as w,validateEAToken as $,syncProgress as k,syncCardFeedback as v}from"../lib/learn-curricula.js";import{normalizeTokenBody as C}from"../lib/token-format.js";import{fetchMyScores as A,recallCoach as _,setNickname as I,streamLearnTutor as T,submitPqs as x,viewPqsTop as E,viewHonors as q}from"../lib/learn-ai.js";import{contestReset as S,contestStart as M,contestSubmit as P,fetchGate as R,timeLeft as O}from"../lib/learn-contest.js";import{getConfig as W,saveConfig as L}from"../lib/config.js";import{loadLearnState as j,saveLearnState as D,newLearnState as N,updateStreak as Y,markCardComplete as z,recordMCQ as B,recordCheck as F,markPracticalComplete as U,addAchievement as Z}from"../lib/learn-state.js";import{renderWelcome as H,renderKnowledgeCard as J,renderMCQCard as K,renderMCQFeedback as Q,renderPracticalCard as V,renderPracticalSuccess as G,renderSimDemoCard as X,renderMilestone as ee,renderArenaTaskCard as oe,renderComingSoonCard as te,renderStatus as ne,renderPhaseComplete as re,renderCurriculumComplete as le,setLearnAiEnabled as se,setLearnHonorRanks as ae,setLearnPqsViewCards as ie,setLearnWide as ce,learnW as de,renderHonorWall as ge,wrapMixed as ue}from"../lib/learn-render.js";import{printError as me}from"../lib/ui.js";export function registerLearnCommand(ye){ye.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ye=>{ye?.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(),ye="LEARNDEMO01");let he=ye.trim().toUpperCase(),pe=null;const fe=/^[A-Z0-9]+DEMO01$/i.test(he),be=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(he);let we=!1,$e=!1;if(fe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),pe=await w(he,he);else if(be){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(he);if(!e.ok){const o=C(he);if(o!==he){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${he} → ${o}`)),e=t,he=o)}}if(!e.ok)return me(`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 🐼"):"")),we=!0===e.aiEnabled,$e=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),pe=await w(e.curriculumId||"LEARNDEMO01",he),!pe)return me(`Could not open a learn curriculum for token '${he}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${he}`)+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 ${he}`)+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(!pe){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(me(`Could not reach the learn server to open ${he}.`),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 ${he}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(me(`Unknown learn token: ${he}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Most tracks have a free demo. From the ")+chalk.bold.green("learn")+chalk.gray(" menu you can type the track name itself")),console.log(chalk.gray(" (e.g. ")+chalk.bold.green("biology")+chalk.gray(", ")+chalk.bold.green("ioipy")+chalk.gray(") and it opens that track's demo if one is published.")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log())}let ke=j(),ve=!1;try{ke&&ke.token===he?Y(ke):(ke=N(he,pe.id,pe.totalCards),ve=!0),D(ke),H(pe,ke,ve)}catch{return me("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 ${he}`)+chalk.gray(".")),void console.log()}const Ce=s(),Ae=null!==Ce,_e=Ae?Ce.listeners("line").slice():[];Ae&&Ce.removeAllListeners("line");const Ie=Ae?Ce:o({input:process.stdin,output:process.stdout,terminal:!0}),Te=Ae?Ie.prompt:null;Ae&&(Ie.prompt=e.prototype.prompt);const xe=()=>{Ae&&Te&&(Ie.prompt=Te)},Ee=()=>{Ie.setPrompt(Ue?chalk.bold.green(`icoa ${a()}> `):Ne?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(je?"icoa learn ai> ":"icoa learn> ")),Ie.prompt()};let qe=null,Se=null,Me=null,Pe=null,Re=[],Oe=!1,We=null;const Le=()=>{We&&clearTimeout(We),We=null,Re=[],Oe=!1,Pe=null};let je=!1,De=!1,Ne=!1,Ye=null,ze=!1,Be=0,Fe=!1,Ue=!1;const Ze=new Map,He=()=>{let e=Ze.get(ke.currentCard);return e||(e=[],Ze.set(ke.currentCard,e)),e};let Je=!1;const Ke=new Set;let Qe=!1,Ve=0;const Ge=()=>(W().language||"en").toLowerCase().startsWith("zh");se(we),ce(!!W().learnWide),ie(Ke);const Xe=new Map;ae(Xe);const eo=[];let oo=null;const to=new Promise(e=>{oo=e}),no=()=>{const e=oo;oo=null,e?.()},ro="1"===process.env.ICOA_LEARN_EMBEDDED,lo=e=>pe.cards.find(o=>o.number===e);let so=null,ao=null;const io=!he.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(he),co=async()=>{if(!io)return;const e=await R(he);e.ok&&e.data&&(so=e.data)},go=e=>{const o=pe.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},uo=e=>{if(!$e||!so)return null;const o=go(e);if(o<=so.unlocked_through_phase)return null;const t=so.phases.find(e=>e.phase===so.unlocked_through_phase),n=[chalk.yellow(Ge()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${so.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${so.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(Ge()?` ⚔ 练习赛 ${so.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${so.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(Ge()?` ⚖ 判分赛: 最好 ${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(Ge()?` ⭐ 提问研究: ${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")},mo=async e=>$e?null===uo(e)?null:(await co(),uo(e)):null;$e&&await co();const yo=async e=>{const o=pe.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=pe.modules.find(e=>e.number===o.number+1);let n;if(we){const e=await A({token:he,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}io&&await co();const r=so?.phases.find(e=>e.phase===o.number);return re(pe,ke,o,t,n,r),!0},ho=()=>{Qe=!0,console.log(chalk.gray(Ge()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},po=()=>{Ye=null;const e=lo(ke.currentCard);if(!e)return console.log(),console.log(chalk.gray(" No more cards in this curriculum.")),console.log(chalk.gray(" Type ")+chalk.bold.green("status")+chalk.gray(" for the dashboard or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),void console.log();switch(e.type){case"knowledge":J(e,pe),e.check?(Me=e.number,Ve=Date.now()):(z(ke,e.number),D(ke));break;case"mcq":K(e,pe),qe=e.number;break;case"practical":V(e,pe),Se=e.number;break;case"sim_demo":X(e,pe),z(ke,e.number),D(ke);break;case"milestone":ee(e,pe),Z(ke,e.badge),z(ke,e.number),D(ke);break;case"arena_task":oe(e,pe),z(ke,e.number),D(ke);break;case"coming_soon":te(e,pe),z(ke,e.number),D(ke)}fo(e.number)},fo=e=>{if(!$e||!io||!so)return;const o=pe.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=so.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=(n||"").slice(0,10);return`🏆 ${e} ${o}/${l.n}`+(r?Ge()?` · 用时 ${r}`:` · ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(de());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${Ge()?"练习赛":"PY Arena"} ${o.number}-${n}`)+(l.passed?chalk.bold.green(Ge()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(Ge()?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(Ge()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(Ge()?"✍ 第一次用 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(Ge()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(Ge()?"最好":"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(Ge()?" 再战刷成绩 · ":" race it again · "):chalk.gray(Ge()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(Ge()?" 继续学习":" keep going"):chalk.gray(Ge()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(Ge()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},bo=()=>{he.endsWith("DEMO01")?console.log(chalk.yellow(Ge()?" 🐼 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(Ge()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(Ge()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},wo=async(e,o)=>{if(we){De=!0;try{console.log(),console.log(chalk.gray("deep"===o?Ge()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":Ge()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await T({token:he,cardNumber:ke.currentCard,question:e,mode:o,history:He().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(Ge()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(He().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(` (${Ge()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Ge()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Me&&console.log(chalk.gray(Ge()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{De=!1}}else bo()},$o=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],ko=async()=>{Ne&&ao?Eo?qo(Eo):Io():Ye?await vo():po()},vo=async()=>{De=!0;try{console.log();const e=await q({token:he,curriculumId:pe.id,cardNumber:ke.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Ge()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Ge()?` 🏆 本卡实时 Top-3 — 第 ${ke.currentCard} 张`:` 🏆 Live top-3 — card ${ke.currentCard}`)),e.board&&0!==e.board.length)for(const o of e.board){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(chalk.white(` ${o.icon} `)+chalk.bold.cyan(o.name||`Rank ${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(Ge()?" (你)":" (you)"):""))}else console.log(chalk.gray(Ge()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Xe.set(ke.currentCard,e.mine.rank),console.log(chalk.white(Ge()?" 你: ":" You: ")+chalk.bold.yellow(Ge()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Ge()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):we&&console.log(chalk.gray(Ge()?" 你还没上榜 — /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(Ge()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Ge()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Ge()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Ye="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(Ge()?" 返回卡片":" returns to the card")),console.log()}finally{De=!1}},Co=e=>Ge()&&e.title_zh||e.title,Ao=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of ue(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},_o=e=>ao.data.solved.includes(e.id)?"✅":ao.tried.has(e.id)?"❌":"⬜",Io=()=>{const e=ao.data,o=O(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(Ge()?` · 第 ${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(Ge()?" ⏱ 已超时 — 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(Ge()?`(共 ${e.n} 题)`:` (of ${e.n})`));const r=Date.parse(e.deadline)-Date.now();o?e.resumed&&r<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(Ge()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(Ge()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(Ge()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(Ge()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+_o(e)+chalk.white(` ${Co(e)}`))}),console.log(),To()},To=()=>{console.log(chalk.gray(Ge()?" /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(Ge()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(Ge()?" 返回课程":" returns to the lesson")),console.log()},xo=e=>{const o=parseInt(e,10),t=ao.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(Ge()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}};let Eo=null;const qo=e=>{const o=xo(e);if(!o)return;const{p:t,n:n}=o;Eo=String(n),console.log(),console.log(chalk.bold.white(` ${_o(t)} ${Co(t)}`)),console.log();for(const e of(e=>Ge()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of ue(e,de()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(Ge()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Ge()?" 应输出:":" 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(Ge()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(Ge()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(Ge()?"写码(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(Ge()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(Ge()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(Ge()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((Ge()," ↩ "))+chalk.bold.green("back")+chalk.gray(Ge()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(Ge()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((Ge()," / "))+chalk.bold.green("wide")+chalk.gray(Ge()?" 换语言/宽度":" language / width")),console.log()},So=async(e,o)=>{await new Promise(t=>{const n=process.stdin,l=!!n.isTTY&&!!n.isRaw;if(Ie.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:ao.dir}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&l)try{n.setRawMode(!0)}catch{}Ie.resume(),t()};s.on("close",a),s.on("error",a)})},Mo=new Map,Po=async e=>{const o=e.trim().toLowerCase(),s=Ne&&o.startsWith("/")?o.slice(1):o;if(De)return;if(null!==Pe){if(Re.push(e.replace(/\s+$/,"")),We&&clearTimeout(We),We=null,Oe){const e=Re[Re.length-1]??"";return"/cancel"===e.trim()?(Le(),console.log(chalk.gray(Ge()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Ee()):""!==e.trim()?void Ee():(Re.pop(),void await a())}return void(We=setTimeout(()=>{if(We=null,Re.length>1){Oe=!0;const e=Re.length;return console.log(chalk.cyan(Ge()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(Ge()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Ee()}a()},140))}async function a(){const e=Re.join("\n").replace(/^\s+|\s+$/g,""),o=Pe??ke.currentCard,t=Re.length;if(Le(),""===e)console.log(chalk.gray(Ge()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(Ge()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(Ge()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(Ge()?" 即可执行。":" again to run it."));else{const n=Ve>0?Date.now()-Ve:void 0;if(await v(he,{curriculum_id:pe.id,card_number:o,feedback_text:e,time_on_card_ms:n})){const e=t>1?Ge()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(Ge()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(Ge()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Ee()}if(ze){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return ze=!1,console.log(),console.log(chalk.yellow(Ge()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(Ge()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(Ge()?" 即可执行该命令。":" again to run it.")),console.log(),void Ee();if(!o)return ze=!1,console.log(chalk.gray(Ge()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Ee();const t=await I({token:he,nickname:o});if(t.ok)ze=!1,console.log(chalk.bold.green(Ge()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Ge()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Be+=1;const e="taken"===t.code?Ge()?"已被占用":"already taken":"bad_charset"===t.code?Ge()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?Ge()?"未通过审核":"did not pass review":t.message||"error";if(!(Be>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ge()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Ee();ze=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ge()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Ee()}if(Je){Je=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{De=!0;try{console.log(),console.log(chalk.gray(Ge()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await x({token:he,cardNumber:ke.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Ge()?"评审暂不可用。":"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(Ge()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(Ge()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Ge()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Ge()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Ge()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(Ge()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=Ge()?` 本卡排名 #${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(Ge()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Ge()?` 第 ${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 $o(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(Ge()?" 改进提问: ":" 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(` (${Ge()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Ke.add(ke.currentCard):Ke.delete(ke.currentCard),"number"==typeof e.rank&&Xe.set(ke.currentCard,e.rank);const o=await q({token:he,curriculumId:pe.id,cardNumber:ke.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&&!fe&&(ze=!0,Be=0,console.log(chalk.bold.yellow(Ge()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Ge()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Ge()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{De=!1}})():(console.log(chalk.gray(Ge()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Me&&(console.log(chalk.gray(Ge()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Ee()}if(Qe)return Qe=!1,po(),void Ee();if(!o)return void Ee();if(Ue)return"exit"===await i(e.trim())&&(Ue=!1),void Ee();if(je){if(["q","quit","exit","back","b","menu"].includes(o))return je=!1,console.log(chalk.gray(Ge()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Ee();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await wo(n,t?"fast":"deep"),console.log(chalk.gray(Ge()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Ee()}if(Ne&&ao){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${ao.phase}s${ao.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Ne=!1,console.log(chalk.gray(Ge()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),po(),void Ee();if(/^\d+$/.test(o))return qo(o),void Ee();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,r]=e;return"list"===o?Io():r?"read"===o||"open"===o?qo(r):"edit"===o?await(async e=>{const o=xo(e);if(o){try{n("command -v vi",{stdio:"ignore"})}catch{return console.log(chalk.yellow(Ge()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),void console.log(chalk.bold.white(` ${f(ao.dir,`sol-${o.n}.py`)}`))}console.log(chalk.gray(Ge()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await So("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(Ge()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Ge()?" 自测样例。":" to self-check the sample.")),console.log()}})(r):"run"===o?(e=>{const o=xo(e);if(!o)return;const{p:n,n:r}=o,l=f(ao.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(Ge()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const s=(n.samples??[])[0];if(!s)return void console.log(chalk.gray(Ge()?` 本题无样例(设计如此)— 用 /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"})}catch(e){const o=e;if(o.killed)console.log(chalk.yellow(Ge()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Ge()?" ✗ 程序报错:":" ✗ 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(Ge()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Ge()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(Ge()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Ge()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Ge()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Ge()?" 改完再 /run。":" then /run again.")),console.log()})(r):"debug"===o?await(async e=>{const o=xo(e);if(!o)return;const t=f(ao.dir,`sol-${o.n}.py`);d(t)?(console.log(chalk.gray(Ge()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log(),await So("python3",[`sol-${o.n}.py`]),console.log(),console.log(chalk.gray(Ge()?" 回到竞技场。":" Back in the arena.")),console.log()):console.log(chalk.yellow(Ge()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`))})(r):"recall"===o&&await(async e=>{const o=xo(e);if(!o)return;if(!we)return void bo();const{p:t,n:n}=o,r=f(process.cwd(),"icoa-contest"),l=`${pe.id}-phase${ao.phase}-g${ao.data.slot}-archived-`;let s=null;try{for(const e of u(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?f(r,s,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(Ge()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${ao.phase}-${ao.data.slot}-${n}`,g=Math.min(3,(Mo.get(c)??0)+1);console.log(chalk.gray(Ge()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const y=await _({token:he,phase:ao.phase,slot:ao.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:Ge()?"zh":"en"});if(y.ok){Mo.set(c,g),console.log();for(const e of ue(y.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(Ge()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(Ge()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===y.code?console.log(chalk.yellow(Ge()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${y.message}`)):console.log(chalk.yellow(` ${y.message||"Coach unavailable."}`))})(r):console.log(chalk.yellow(Ge()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(Ge()?" (花名册: /list)":" (roster: /list)")),void Ee()}if("contest"===o||"/contest"===o)return Io(),void Ee();const r="lang"===o||/^lang\s+\S+$/.test(o),a=/^(wide|wide on|wide off|normal|narrow)$/.test(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||r||a||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(Ge()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Ee()}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(Ge()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Ee()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(Ie.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{}Ie.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Ee()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Ue=!0),void Ee();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!we)return bo(),void Ee();Fe||(Fe=!0,console.log(),console.log(chalk.bold.cyan(Ge()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Ge()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Ge()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Ge()||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){je=!0;const e=lo(ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Ge()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(Ge()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ge()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Ee()}return await wo(n,t?"fast":"deep"),void Ee()}if(!Ne&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!we)return bo(),void Ee();const e=lo(ke.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Ge()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Ge()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ge()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Ge()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Ge()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Ge()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Ge()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Je=!0,void Ee()}const w=!Ne&&"honors"===Ye&&/^[1-3]$/.test(o);if(!Ne&&Ye&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(Ge()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(Ge()?" ↩ back 回上一层":" ↩ back goes up one level")),void Ee();if(!Ne&&(w||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!we)return bo(),void Ee();const e=/^\/?view ([1-3])$/.exec(o),t=w?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{De=!0;try{console.log();const o=await E({token:he,cardNumber:ke.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Ge()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Ke.delete(ke.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Ke.add(ke.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Ge()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${ke.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${ke.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Ge()?` (第 ${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(Ge()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=$o(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(Ge()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Ye="view",console.log(chalk.gray((Ge()," "))+chalk.bold.cyan("↩ back")+chalk.gray(Ge()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{De=!1}})(t),void Ee()}if("/honors"===o||"honors"===o)return fe?(console.log(),console.log(chalk.gray(Ge()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Ee()):(await vo(),void Ee());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return ne(pe,ke),void Ee();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(W().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Ee();const t=pe.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 L({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Me=null,qe=null,Se=null,Le(),Qe=!1,Je=!1,await ko(),void Ee()}if(["wide","wide on","normal","narrow","wide off"].includes(o)){const e="wide"===o||"wide on"===o;return e===!!W().learnWide?(console.log(chalk.gray(e?Ge()?de()<=64?` 宽屏已开,但终端只有 ${process.stdout.columns||64} 列 — 画面已是最大可用宽度。输 normal 关闭。`:` 已是宽屏(${de()} 列)。输 normal 恢复 64 列。`:de()<=64?` Wide is on, but your terminal is only ${process.stdout.columns||64} cols — already at max usable width. Type normal to switch it off.`:` Already wide (${de()} cols). Type normal to restore 64.`:Ge()?" 已是标准 64 列。输 wide 拉伸到终端宽度。":" Already at the standard 64 cols. Type wide to stretch.")),void Ee()):(L({learnWide:e}),ce(e),e&&de()<=64?(console.log(chalk.yellow(Ge()?` 终端只有 ${process.stdout.columns||64} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${process.stdout.columns||64} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray(Ge()?" 拉宽窗口后会自动生效;输 normal 关闭宽屏。":" Widen the window and it takes effect automatically; type normal to switch it off.")),void Ee()):(console.log(chalk.green(" ✓ ")+chalk.gray(e?Ge()?`宽屏开 — 卡片拉伸到终端宽度(现在 ${de()} 列,上限 96)。输 normal 恢复。`:`Wide mode ON — cards stretch to your terminal (now ${de()} cols, max 96). Type normal to restore.`:Ge()?"已恢复 64 列标准宽。输 wide 再拉伸。":"Back to the 64-col standard width. Type wide to stretch again.")),Me=null,qe=null,Se=null,Le(),Qe=!1,Je=!1,await ko(),void Ee()))}if("sim"===o){const e=lo(ke.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=p(b(import.meta.url)),o=[f(e,"..","..","panda","mujoco-launcher.py"),f(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(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 Ee()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Ee())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=ke.currentCard,t=ke.bookmarks.includes(e),n="bookmark"!==o;return n?ke.bookmarks=ke.bookmarks.filter(o=>o!==e):t||ke.bookmarks.push(e),D(ke),n?console.log(t?chalk.gray(Ge()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(Ge()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(Ge()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(Ge()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Ee()}if("e"===o)return Pe=ke.currentCard,console.log(chalk.gray(Ge()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void Ee();if("back"===o||"b"===o)return"view"===Ye?(await vo(),void Ee()):"honors"===Ye?(Ye=null,po(),void Ee()):(ke.currentCard>1&&(ke.currentCard-=1),qe=null,Se=null,Me=null,D(ke),po(),void Ee());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(!io)return console.log(chalk.yellow(Ge()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Ee();const e=go(ke.currentCard);if("contest reset"===o){const o=await S(he,e);if(o.ok){console.log(chalk.yellow(Ge()?` 已放弃当前计时(阶段 ${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=f(process.cwd(),"icoa-contest",`${pe.id}-phase${e}-g${t}`);if(d(n))try{y(n,`${n}-archived-${o}`),console.log(chalk.gray(Ge()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(Ge()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(Ge()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),ao=null,Ne=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Ee()}const t=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Ge()?" 连接判分赛…":" Contacting contest server…"));const n=await M(he,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(Ge()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void Ee();const r=n.data,l=f(process.cwd(),"icoa-contest",`${pe.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=ao&&ao.phase===e&&ao.data.slot===r.slot?ao.tried:new Set;ao={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,l=(t.samples??[])[0];l&&h(f(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=f(o,`sol-${r}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Ao(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.out.split("\n"))a.push(`# ${e}`)}a.push("#","# ── vi quick guide ── (/edit opens this file in vi)","# i = insert mode — start typing","# Esc = back to command mode","# :wq or ZZ = save & quit · :q! = quit WITHOUT saving","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),h(s,a.join("\n"))})})(r,l),Ne=!0,Io(),console.log(chalk.gray(Ge()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(Ge()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(Ge()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Ee()}if("submit"===s)return console.log(chalk.yellow(Ge()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(Ge()?" 例如 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)")),ao||console.log(chalk.gray(Ge()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Ee();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!ao)return console.log(chalk.yellow(Ge()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Ee();const n=ao.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(Ge()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Ee();const l=n.findIndex(e=>e.id===o)+1,a=t||f(ao.dir,`sol-${l}.py`);let i;try{i=m(a,"utf-8")}catch{return console.log(chalk.red(Ge()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Ee()}console.log(chalk.gray(Ge()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await P(he,ao.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(Ge()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((Ge()," "))+chalk.bold.green("contest")+chalk.gray(Ge()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(Ge()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void Ee();const d=c.data;if(d.already_ac)console.log(chalk.green(Ge()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(Ge()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(Ge()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),ao.data.solved.includes(o)||ao.data.solved.push(o),ao.tried.delete(o);else{ao.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?Ge()?` · 挂在第 ${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(Ge()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=O(d.deadline||"");if(console.log(chalk.white(Ge()?` 本组进度: 已过 ${d.ac_count} 题 · 过 ${d.need} 题过关(共 ${d.n} 题)`:` Group progress: ${d.ac_count} solved · ${d.need} needed to pass (${d.n} problems)`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(Ge()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await co();else if(!d.late){const e=n.findIndex(e=>!ao.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Ge()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Co(n[e])}`))}return void Ee()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>pe.totalCards)return console.log(chalk.yellow(` Card number must be 1..${pe.totalCards}. Try: `)+chalk.bold.green("card 1")),void Ee();const n=await mo(t);return n?(console.log(n),void Ee()):(ke.currentCard=t,qe=null,Se=null,Me=null,D(ke),po(),void Ee())}if(null!==Me&&["y","yes","n","no"].includes(o)){const e=lo(Me);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Ve;z(ke,e.number),F(ke,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),D(ke);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),eo.push(k(he,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Me=null,e.solution&&e.solution.length>0)return void Ee();if(ke.currentCard<pe.totalCards){const e=ke.currentCard,o=await mo(e+1);if(o)return await yo(e),console.log(o),void Ee();ke.currentCard+=1,D(ke),await yo(e)?ho():po(),Ee()}else le(pe,ke),Ee();return}}if(null!==qe&&["a","b","c","d"].includes(o)){const e=lo(qe);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(B(ke,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),z(ke,e.number),D(ke),Q(e,t,n,ke),eo.push(k(he,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),qe=null,n)if(ke.currentCard<pe.totalCards){const e=await mo(ke.currentCard+1);if(e)return console.log(e),void Ee();ke.currentCard+=1,D(ke),po()}else le(pe,ke),Ee();else Ee();return}}if(null!==Se){if("done"===o){const e=lo(Se);if(e&&"practical"===e.type)return U(ke,e.number),z(ke,e.number),D(ke),G(e),Se=null,void Ee()}if("skip"===o)return z(ke,Se),D(ke),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Se=null,void Ee()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==qe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Ee();if(null!==Se)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Ee();if(null!==Me)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Ee();const e=ke.currentCard,o=e<pe.totalCards?await mo(e+1):null;return o?(await yo(e),console.log(o),void Ee()):(ke.currentCard+=1,D(ke),ke.currentCard>pe.totalCards?le(pe,ke):await yo(e)?ho():po(),void Ee())}if(null!==Me)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Ee();if(null!==qe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Ee();if(null!==Se)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Ee();"view"===Ye?console.log(chalk.gray(Ge()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(Ge()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(Ge()?" 回卡片":" to the card")):"honors"===Ye?console.log(chalk.gray(Ge()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(Ge()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(Ge()?" 回卡片":" 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")),Ee()}else{if("view"===Ye)return await vo(),void Ee();if("honors"===Ye)return Ye=null,po(),void Ee();if(eo.length>0&&await Promise.race([Promise.allSettled(eo),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ke.streakDays} day(s)`)),console.log(),Ae){Ie.removeAllListeners("line"),xe();for(const e of _e)Ie.on("line",e);Ie.prompt(),no()}else Ie.removeAllListeners("line"),Ie.close()}else if(eo.length>0&&await Promise.race([Promise.allSettled(eo),new Promise(e=>setTimeout(e,3e3))]),Ie.removeAllListeners("line"),xe(),Ae||!ro){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Ae?Ie:void 0),no()}else Ie.close()};Ie.on("line",e=>{Po(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.")),Ee()})}),Ae||Ie.on("close",async()=>{eo.length>0&&await Promise.race([Promise.allSettled(eo),new Promise(e=>setTimeout(e,5e3))]),ro?no():process.exit(0)});try{po(),Ee();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(me("Could not render this card — the curriculum may be malformed."),Ae){Ie.removeAllListeners("line"),xe();for(const e of _e)Ie.on("line",e);Ie.prompt()}else Ie.close();no()}await to}),ye.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 w(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{logCommand as l}from"../lib/logger.js";import{getMainRl as s}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as a,handleAi4ioaiMessage as i,startAi4ioaiChat as c}from"./ai4ioai.js";import{existsSync as d,mkdirSync as g,readdirSync as u,readFileSync as y,renameSync as m,writeFileSync as h}from"node:fs";import{dirname as p,join as f}from"node:path";import{fileURLToPath as b}from"node:url";import{loadCurriculumById as w,validateEAToken as $,syncProgress as k,syncCardFeedback as v}from"../lib/learn-curricula.js";import{normalizeTokenBody as C}from"../lib/token-format.js";import{fetchMyScores as A,recallCoach as _,setNickname as T,streamLearnTutor as I,submitPqs as x,viewPqsTop as E,viewHonors as P}from"../lib/learn-ai.js";import{contestReset as S,contestStart as q,contestSubmit as M,fetchGate as R,timeLeft as W}from"../lib/learn-contest.js";import{getConfig as O,saveConfig as L}from"../lib/config.js";import{isNativeWindows as N,whichBinary as j}from"../lib/platform.js";import{loadLearnState as D,saveLearnState as Y,newLearnState as U,updateStreak as z,markCardComplete as F,recordMCQ as B,recordCheck as H,markPracticalComplete as Z,addAchievement as J}from"../lib/learn-state.js";import{renderWelcome as K,renderKnowledgeCard as Q,renderMCQCard as V,renderMCQFeedback as G,renderPracticalCard as X,renderPracticalSuccess as ee,renderSimDemoCard as oe,renderMilestone as te,renderArenaTaskCard as ne,renderComingSoonCard as re,renderStatus as le,renderPhaseComplete as se,renderCurriculumComplete as ae,setLearnAiEnabled as ie,setLearnHonorRanks as ce,setLearnPqsViewCards as de,setLearnWide as ge,learnW as ue,renderHonorWall as ye,wrapMixed as me}from"../lib/learn-render.js";import{printError as he}from"../lib/ui.js";export function registerLearnCommand(pe){pe.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async pe=>{pe?.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(),pe="LEARNDEMO01");let fe=pe.trim().toUpperCase(),be=null;const we=/^[A-Z0-9]+DEMO01$/i.test(fe),$e=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(fe);let ke=!1,ve=!1;if(we)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),be=await w(fe,fe);else if($e){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(fe);if(!e.ok){const o=C(fe);if(o!==fe){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${fe} → ${o}`)),e=t,fe=o)}}if(!e.ok)return he(`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 🐼"):"")),ke=!0===e.aiEnabled,ve=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),be=await w(e.curriculumId||"LEARNDEMO01",fe),!be)return he(`Could not open a learn curriculum for token '${fe}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${fe}`)+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 ${fe}`)+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(!be){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(he(`Could not reach the learn server to open ${fe}.`),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 ${fe}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(he(`Unknown learn token: ${fe}`),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 Ce=D(),Ae=!1;try{Ce&&Ce.token===fe?z(Ce):(Ce=U(fe,be.id,be.totalCards),Ae=!0),Y(Ce),K(be,Ce,Ae)}catch{return he("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 ${fe}`)+chalk.gray(".")),void console.log()}const _e=s(),Te=null!==_e,Ie=Te?_e.listeners("line").slice():[];Te&&_e.removeAllListeners("line");const xe=Te?_e:o({input:process.stdin,output:process.stdout,terminal:!0}),Ee=Te?xe.prompt:null;Te&&(xe.prompt=e.prototype.prompt);const Pe=()=>{Te&&Ee&&(xe.prompt=Ee)},Se=()=>{xe.setPrompt(Ze?chalk.bold.green(`icoa ${a()}> `):Ue?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(De?"icoa learn ai> ":"icoa learn> ")),xe.prompt()};let qe=null,Me=null,Re=null,We=null,Oe=[],Le=!1,Ne=null;const je=()=>{Ne&&clearTimeout(Ne),Ne=null,Oe=[],Le=!1,We=null};let De=!1,Ye=!1,Ue=!1,ze=null,Fe=!1,Be=0,He=!1,Ze=!1;const Je=new Map,Ke=()=>{let e=Je.get(Ce.currentCard);return e||(e=[],Je.set(Ce.currentCard,e)),e};let Qe=!1;const Ve=new Set;let Ge=!1,Xe=0;const eo=()=>(O().language||"en").toLowerCase().startsWith("zh");ie(ke),ge(!!O().learnWide),de(Ve);const oo=new Map;ce(oo);const to=[];let no=null;const ro=new Promise(e=>{no=e}),lo=()=>{const e=no;no=null,e?.()},so="1"===process.env.ICOA_LEARN_EMBEDDED,ao=e=>be.cards.find(o=>o.number===e);let io=null,co=null;const go=!fe.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(fe),uo=async()=>{if(!go)return;const e=await R(fe);e.ok&&e.data&&(io=e.data)},yo=e=>{const o=be.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},mo=e=>{if(!ve||!io)return null;const o=yo(e);if(o<=io.unlocked_through_phase)return null;const t=io.phases.find(e=>e.phase===io.unlocked_through_phase),n=[chalk.yellow(eo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${io.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${io.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(eo()?` ⚔ 练习赛 ${io.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${io.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(eo()?` ⚖ 判分赛: 最好 ${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(eo()?` ⭐ 提问研究: ${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")},ho=async e=>ve?null===mo(e)?null:(await uo(),mo(e)):null;ve&&await uo();const po=async e=>{const o=be.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=be.modules.find(e=>e.number===o.number+1);let n;if(ke){const e=await A({token:fe,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}go&&await uo();const r=io?.phases.find(e=>e.phase===o.number);return se(be,Ce,o,t,n,r),!0},fo=()=>{Ge=!0,console.log(chalk.gray(eo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},bo=()=>{ze=null;const e=ao(Ce.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":Q(e,be),e.check?(Re=e.number,Xe=Date.now()):(F(Ce,e.number),Y(Ce));break;case"mcq":V(e,be),qe=e.number;break;case"practical":X(e,be),Me=e.number;break;case"sim_demo":oe(e,be),F(Ce,e.number),Y(Ce);break;case"milestone":te(e,be),J(Ce,e.badge),F(Ce,e.number),Y(Ce);break;case"arena_task":ne(e,be),F(Ce,e.number),Y(Ce);break;case"coming_soon":re(e,be),F(Ce,e.number),Y(Ce)}wo(e.number)},wo=e=>{if(!ve||!go||!io)return;const o=be.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=io.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=(n||"").slice(0,10);return`🏆 ${e} ${o}/${l.n}`+(r?eo()?` · 用时 ${r}`:` · ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(ue());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${eo()?"练习赛":"PY Arena"} ${o.number}-${n}`)+(l.passed?chalk.bold.green(eo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(eo()?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(eo()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(eo()?"✍ 第一次用 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(eo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(eo()?"最好":"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(eo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(eo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(eo()?" 继续学习":" keep going"):chalk.gray(eo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(eo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},$o=()=>{fe.endsWith("DEMO01")?console.log(chalk.yellow(eo()?" 🐼 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(eo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(eo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},ko=async(e,o)=>{if(ke){Ye=!0;try{console.log(),console.log(chalk.gray("deep"===o?eo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":eo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await I({token:fe,cardNumber:Ce.currentCard,question:e,mode:o,history:Ke().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(eo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Ke().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(` (${eo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(eo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Re&&console.log(chalk.gray(eo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ye=!1}}else $o()},vo=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Co=async()=>{Ue&&co?So?qo(So):xo():ze?await Ao():bo()},Ao=async()=>{Ye=!0;try{console.log();const e=await P({token:fe,curriculumId:be.id,cardNumber:Ce.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(eo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(eo()?` 🏆 本卡实时 Top-3 — 第 ${Ce.currentCard} 张`:` 🏆 Live top-3 — card ${Ce.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(eo()?" (你)":" (you)"):""))}else console.log(chalk.gray(eo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(oo.set(Ce.currentCard,e.mine.rank),console.log(chalk.white(eo()?" 你: ":" You: ")+chalk.bold.yellow(eo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(eo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):ke&&console.log(chalk.gray(eo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),ye({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(eo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(eo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(eo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),ze="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(eo()?" 返回卡片":" returns to the card")),console.log()}finally{Ye=!1}},_o=e=>eo()&&e.title_zh||e.title,To=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of me(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},Io=e=>co.data.solved.includes(e.id)?"✅":co.tried.has(e.id)?"❌":"⬜",xo=()=>{const e=co.data,o=W(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(eo()?` · 第 ${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(eo()?" ⏱ 已超时 — 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(eo()?`(共 ${e.n} 题)`:` (of ${e.n})`));const r=Date.parse(e.deadline)-Date.now();o?e.resumed&&r<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(eo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(eo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(eo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(eo()?` 满血重开本组(${e.duration_minutes} 分钟,无限次;已 AC 题目留档)`:` restart this group fresh (${e.duration_minutes} min, unlimited; ACs stay on record)`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+Io(e)+chalk.white(` ${_o(e)}`))}),console.log(),Eo()},Eo=()=>{console.log(chalk.gray(eo()?" /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(eo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(eo()?" 返回课程":" returns to the lesson")),console.log()},Po=e=>{const o=parseInt(e,10),t=co.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(eo()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}};let So=null;const qo=e=>{const o=Po(e);if(!o)return;const{p:t,n:n}=o;So=String(n),console.log(),console.log(chalk.bold.white(` ${Io(t)} ${_o(t)}`)),console.log();for(const e of(e=>eo()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of me(e,ue()+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(eo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(eo()?" 应输出:":" 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(eo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(eo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(eo()?"写码(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(eo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(eo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(eo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((eo()," ↩ "))+chalk.bold.green("back")+chalk.gray(eo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(eo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((eo()," / "))+chalk.bold.green("wide")+chalk.gray(eo()?" 换语言/宽度":" language / width")),console.log()},Mo=async(e,o)=>await new Promise(t=>{const n=process.stdin,l=!!n.isTTY&&!!n.isRaw;if(xe.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:co.dir}),a=e=>{if(n.isTTY&&"function"==typeof n.setRawMode&&l)try{n.setRawMode(!0)}catch{}xe.resume(),t(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Ro=()=>{console.log(chalk.yellow(eo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(eo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(eo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(eo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Wo=new Map,Oo=async e=>{const o=e.trim().toLowerCase(),s=Ue&&o.startsWith("/")?o.slice(1):o;if(Ye)return;if(null!==We){if(Oe.push(e.replace(/\s+$/,"")),Ne&&clearTimeout(Ne),Ne=null,Le){const e=Oe[Oe.length-1]??"";return"/cancel"===e.trim()?(je(),console.log(chalk.gray(eo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Se()):""!==e.trim()?void Se():(Oe.pop(),void await a())}return void(Ne=setTimeout(()=>{if(Ne=null,Oe.length>1){Le=!0;const e=Oe.length;return console.log(chalk.cyan(eo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(eo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Se()}a()},140))}async function a(){const e=Oe.join("\n").replace(/^\s+|\s+$/g,""),o=We??Ce.currentCard,t=Oe.length;if(je(),""===e)console.log(chalk.gray(eo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(eo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(eo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(eo()?" 即可执行。":" again to run it."));else{const n=Xe>0?Date.now()-Xe:void 0;if(await v(fe,{curriculum_id:be.id,card_number:o,feedback_text:e,time_on_card_ms:n})){const e=t>1?eo()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(eo()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(eo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Se()}if(Fe){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Fe=!1,console.log(),console.log(chalk.yellow(eo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(eo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(eo()?" 即可执行该命令。":" again to run it.")),console.log(),void Se();if(!o)return Fe=!1,console.log(chalk.gray(eo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Se();const t=await T({token:fe,nickname:o});if(t.ok)Fe=!1,console.log(chalk.bold.green(eo()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(eo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Be+=1;const e="taken"===t.code?eo()?"已被占用":"already taken":"bad_charset"===t.code?eo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?eo()?"未通过审核":"did not pass review":t.message||"error";if(!(Be>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(eo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Se();Fe=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(eo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Se()}if(Qe){Qe=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ye=!0;try{console.log(),console.log(chalk.gray(eo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await x({token:fe,cardNumber:Ce.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(eo()?"评审暂不可用。":"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(eo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(eo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(eo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(eo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(eo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(eo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=eo()?` 本卡排名 #${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(eo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(eo()?` 第 ${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 vo(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(eo()?" 改进提问: ":" 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(` (${eo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Ve.add(Ce.currentCard):Ve.delete(Ce.currentCard),"number"==typeof e.rank&&oo.set(Ce.currentCard,e.rank);const o=await P({token:fe,curriculumId:be.id,cardNumber:Ce.currentCard});o.ok&&o.totals&&o.chapters&&(ye({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!we&&(Fe=!0,Be=0,console.log(chalk.bold.yellow(eo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(eo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(eo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Ye=!1}})():(console.log(chalk.gray(eo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Re&&(console.log(chalk.gray(eo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Se()}if(Ge)return Ge=!1,bo(),void Se();if(!o)return void Se();if(Ze)return"exit"===await i(e.trim())&&(Ze=!1),void Se();if(De){if(["q","quit","exit","back","b","menu"].includes(o))return De=!1,console.log(chalk.gray(eo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Se();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await ko(n,t?"fast":"deep"),console.log(chalk.gray(eo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Se()}if(Ue&&co){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${co.phase}s${co.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Ue=!1,console.log(chalk.gray(eo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),bo(),void Se();if(/^\d+$/.test(o))return qo(o),void Se();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,n]=e;return"list"===o?xo():n?"read"===o||"open"===o?qo(n):"edit"===o?await(async e=>{const o=Po(e);if(!o)return;const t=f(co.dir,`sol-${o.n}.py`);return N()?(console.log(chalk.yellow(eo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(eo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(eo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(eo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(eo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log()):j("vi")?(console.log(chalk.gray(eo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await Mo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(eo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(eo()?" 自测样例。":" to self-check the sample.")),void console.log()):(console.log(chalk.yellow(eo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(eo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim")))})(n):"run"===o?(e=>{const o=Po(e);if(!o)return;const{p:n,n:r}=o,l=f(co.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(eo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const s=(n.samples??[])[0];if(!s)return void console.log(chalk.gray(eo()?` 本题无样例(设计如此)— 用 /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"})}catch(e){const o=e;if("ENOENT"===o.code)Ro();else if(o.killed)console.log(chalk.yellow(eo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(eo()?" ✗ 程序报错:":" ✗ 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(eo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(eo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(eo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(eo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(eo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(eo()?" 改完再 /run。":" then /run again.")),console.log()})(n):"debug"===o?await(async e=>{const o=Po(e);if(!o)return;const t=f(co.dir,`sol-${o.n}.py`);if(!d(t))return void console.log(chalk.yellow(eo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(eo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 Mo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==n?.code?(console.log(chalk.gray(eo()?" 回到竞技场。":" Back in the arena.")),console.log()):Ro()})(n):"recall"===o&&await(async e=>{const o=Po(e);if(!o)return;if(!ke)return void $o();const{p:t,n:n}=o,r=f(process.cwd(),"icoa-contest"),l=`${be.id}-phase${co.phase}-g${co.data.slot}-archived-`;let s=null;try{for(const e of u(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?f(r,s,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(eo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${co.phase}-${co.data.slot}-${n}`,g=Math.min(3,(Wo.get(c)??0)+1);console.log(chalk.gray(eo()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await _({token:fe,phase:co.phase,slot:co.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:eo()?"zh":"en"});if(m.ok){Wo.set(c,g),console.log();for(const e of me(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(eo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(eo()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(eo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(n):console.log(chalk.yellow(eo()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(eo()?" (花名册: /list)":" (roster: /list)")),void Se()}if("contest"===o||"/contest"===o)return xo(),void Se();const n="lang"===o||/^lang\s+\S+$/.test(o),r=/^(wide|wide on|wide off|normal|narrow)$/.test(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||n||r||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(eo()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Se()}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(eo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Se()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(xe.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{}xe.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Se()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Ze=!0),void Se();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!ke)return $o(),void Se();He||(He=!0,console.log(),console.log(chalk.bold.cyan(eo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(eo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(eo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),eo()||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){De=!0;const e=ao(Ce.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(eo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(eo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(eo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Se()}return await ko(n,t?"fast":"deep"),void Se()}if(!Ue&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!ke)return $o(),void Se();const e=ao(Ce.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(eo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(eo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(eo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(eo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(eo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(eo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(eo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Qe=!0,void Se()}const w=!Ue&&"honors"===ze&&/^[1-3]$/.test(o);if(!Ue&&ze&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(eo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(eo()?" ↩ back 回上一层":" ↩ back goes up one level")),void Se();if(!Ue&&(w||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!ke)return $o(),void Se();const e=/^\/?view ([1-3])$/.exec(o),t=w?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Ye=!0;try{console.log();const o=await E({token:fe,cardNumber:Ce.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(eo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Ve.delete(Ce.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Ve.add(Ce.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(eo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${Ce.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${Ce.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(eo()?` (第 ${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(eo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=vo(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(eo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),ze="view",console.log(chalk.gray((eo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(eo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Ye=!1}})(t),void Se()}if("/honors"===o||"honors"===o)return we?(console.log(),console.log(chalk.gray(eo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Se()):(await Ao(),void Se());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return le(be,Ce),void Se();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(O().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Se();const t=be.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 L({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Re=null,qe=null,Me=null,je(),Ge=!1,Qe=!1,await Co(),void Se()}if(["wide","wide on","normal","narrow","wide off"].includes(o)){const e="wide"===o||"wide on"===o;return e===!!O().learnWide?(console.log(chalk.gray(e?eo()?ue()<=64?` 宽屏已开,但终端只有 ${process.stdout.columns||64} 列 — 画面已是最大可用宽度。输 normal 关闭。`:` 已是宽屏(${ue()} 列)。输 normal 恢复 64 列。`:ue()<=64?` Wide is on, but your terminal is only ${process.stdout.columns||64} cols — already at max usable width. Type normal to switch it off.`:` Already wide (${ue()} cols). Type normal to restore 64.`:eo()?" 已是标准 64 列。输 wide 拉伸到终端宽度。":" Already at the standard 64 cols. Type wide to stretch.")),void Se()):(L({learnWide:e}),ge(e),e&&ue()<=64?(console.log(chalk.yellow(eo()?` 终端只有 ${process.stdout.columns||64} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${process.stdout.columns||64} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray(eo()?" 拉宽窗口后会自动生效;输 normal 关闭宽屏。":" Widen the window and it takes effect automatically; type normal to switch it off.")),void Se()):(console.log(chalk.green(" ✓ ")+chalk.gray(e?eo()?`宽屏开 — 卡片拉伸到终端宽度(现在 ${ue()} 列,上限 96)。输 normal 恢复。`:`Wide mode ON — cards stretch to your terminal (now ${ue()} cols, max 96). Type normal to restore.`:eo()?"已恢复 64 列标准宽。输 wide 再拉伸。":"Back to the 64-col standard width. Type wide to stretch again.")),Re=null,qe=null,Me=null,je(),Ge=!1,Qe=!1,await Co(),void Se()))}if("sim"===o){const e=ao(Ce.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=p(b(import.meta.url)),o=[f(e,"..","..","panda","mujoco-launcher.py"),f(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(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 Se()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Se())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=Ce.currentCard,t=Ce.bookmarks.includes(e),n="bookmark"!==o;return n?Ce.bookmarks=Ce.bookmarks.filter(o=>o!==e):t||Ce.bookmarks.push(e),Y(Ce),n?console.log(t?chalk.gray(eo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(eo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(eo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(eo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Se()}if("e"===o)return We=Ce.currentCard,console.log(chalk.gray(eo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void Se();if("back"===o||"b"===o)return"view"===ze?(await Ao(),void Se()):"honors"===ze?(ze=null,bo(),void Se()):(Ce.currentCard>1&&(Ce.currentCard-=1),qe=null,Me=null,Re=null,Y(Ce),bo(),void Se());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(!go)return console.log(chalk.yellow(eo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Se();const e=yo(Ce.currentCard);if("contest reset"===o){const o=await S(fe,e);if(o.ok){console.log(chalk.yellow(eo()?` 已放弃当前计时(阶段 ${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=f(process.cwd(),"icoa-contest",`${be.id}-phase${e}-g${t}`);if(d(n))try{m(n,`${n}-archived-${o}`),console.log(chalk.gray(eo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(eo()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(eo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),co=null,Ue=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Se()}const t=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(eo()?" 连接判分赛…":" Contacting contest server…"));const n=await q(fe,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(eo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void Se();const r=n.data,l=f(process.cwd(),"icoa-contest",`${be.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=co&&co.phase===e&&co.data.slot===r.slot?co.tried:new Set;co={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,l=(t.samples??[])[0];l&&h(f(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=f(o,`sol-${r}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...To(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.out.split("\n"))a.push(`# ${e}`)}a.push("#","# ── vi quick guide ── (/edit opens this file in vi)","# i = insert mode — start typing","# Esc = back to command mode","# :wq or ZZ = save & quit · :q! = quit WITHOUT saving","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),h(s,a.join("\n"))})})(r,l),Ue=!0,xo(),console.log(chalk.gray(eo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(eo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(eo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Se()}if("submit"===s)return console.log(chalk.yellow(eo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(eo()?" 例如 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)")),co||console.log(chalk.gray(eo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Se();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!co)return console.log(chalk.yellow(eo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Se();const n=co.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(eo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Se();const l=n.findIndex(e=>e.id===o)+1,a=t||f(co.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(eo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Se()}console.log(chalk.gray(eo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await M(fe,co.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(eo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((eo()," "))+chalk.bold.green("contest")+chalk.gray(eo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(eo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void Se();const d=c.data;if(d.already_ac)console.log(chalk.green(eo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(eo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(eo()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),co.data.solved.includes(o)||co.data.solved.push(o),co.tried.delete(o);else{co.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?eo()?` · 挂在第 ${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(eo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=W(d.deadline||"");if(console.log(chalk.white(eo()?` 本组进度: 已过 ${d.ac_count} 题 · 过 ${d.need} 题过关(共 ${d.n} 题)`:` Group progress: ${d.ac_count} solved · ${d.need} needed to pass (${d.n} problems)`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(eo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await uo();else if(!d.late){const e=n.findIndex(e=>!co.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(eo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${_o(n[e])}`))}return void Se()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>be.totalCards)return console.log(chalk.yellow(` Card number must be 1..${be.totalCards}. Try: `)+chalk.bold.green("card 1")),void Se();const n=await ho(t);return n?(console.log(n),void Se()):(Ce.currentCard=t,qe=null,Me=null,Re=null,Y(Ce),bo(),void Se())}if(null!==Re&&["y","yes","n","no"].includes(o)){const e=ao(Re);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Xe;F(Ce,e.number),H(Ce,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),Y(Ce);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),to.push(k(fe,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),Re=null,e.solution&&e.solution.length>0)return void Se();if(Ce.currentCard<be.totalCards){const e=Ce.currentCard,o=await ho(e+1);if(o)return await po(e),console.log(o),void Se();Ce.currentCard+=1,Y(Ce),await po(e)?fo():bo(),Se()}else ae(be,Ce),Se();return}}if(null!==qe&&["a","b","c","d"].includes(o)){const e=ao(qe);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(B(Ce,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),F(Ce,e.number),Y(Ce),G(e,t,n,Ce),to.push(k(fe,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),qe=null,n)if(Ce.currentCard<be.totalCards){const e=await ho(Ce.currentCard+1);if(e)return console.log(e),void Se();Ce.currentCard+=1,Y(Ce),bo()}else ae(be,Ce),Se();else Se();return}}if(null!==Me){if("done"===o){const e=ao(Me);if(e&&"practical"===e.type)return Z(Ce,e.number),F(Ce,e.number),Y(Ce),ee(e),Me=null,void Se()}if("skip"===o)return F(Ce,Me),Y(Ce),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Me=null,void Se()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==qe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Se();if(null!==Me)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Se();if(null!==Re)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Se();const e=Ce.currentCard,o=e<be.totalCards?await ho(e+1):null;return o?(await po(e),console.log(o),void Se()):(Ce.currentCard+=1,Y(Ce),Ce.currentCard>be.totalCards?ae(be,Ce):await po(e)?fo():bo(),void Se())}if(null!==Re)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Se();if(null!==qe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Se();if(null!==Me)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Se();"view"===ze?console.log(chalk.gray(eo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(eo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(eo()?" 回卡片":" to the card")):"honors"===ze?console.log(chalk.gray(eo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(eo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(eo()?" 回卡片":" 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")),Se()}else{if("view"===ze)return await Ao(),void Se();if("honors"===ze)return ze=null,bo(),void Se();if(to.length>0&&await Promise.race([Promise.allSettled(to),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Ce.streakDays} day(s)`)),console.log(),Te){xe.removeAllListeners("line"),Pe();for(const e of Ie)xe.on("line",e);xe.prompt(),lo()}else xe.removeAllListeners("line"),xe.close()}else if(to.length>0&&await Promise.race([Promise.allSettled(to),new Promise(e=>setTimeout(e,3e3))]),xe.removeAllListeners("line"),Pe(),Te||!so){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Te?xe:void 0),lo()}else xe.close()};xe.on("line",e=>{Oo(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.")),Se()})}),Te||xe.on("close",async()=>{to.length>0&&await Promise.race([Promise.allSettled(to),new Promise(e=>setTimeout(e,5e3))]),so?lo():process.exit(0)});try{bo(),Se();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(he("Could not render this card — the curriculum may be malformed."),Te){xe.removeAllListeners("line"),Pe();for(const e of Ie)xe.on("line",e);xe.prompt()}else xe.close();lo()}await ro}),pe.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 w(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
@@ -1 +1 @@
1
- export function parseKaggleTaskList(t){const e=t??{},r=(e.data??e).tasks;if(!Array.isArray(r))return[];const i=[];for(const t of r){if(!t||"object"!=typeof t)continue;const e=t;"string"==typeof e.comp_id&&""!==e.comp_id&&i.push({comp_id:e.comp_id,title:"string"==typeof e.title?e.title:e.comp_id,metric:"string"==typeof e.metric?e.metric:"accuracy",description:"string"==typeof e.description&&""!==e.description?e.description:void 0,kaggle_url:"string"==typeof e.kaggle_url?e.kaggle_url:null,licence:"string"==typeof e.licence?e.licence:void 0,attribution:"string"==typeof e.attribution?e.attribution:void 0,data_base:"string"==typeof e.data_base&&""!==e.data_base?e.data_base:null,id_col:"string"==typeof e.id_col?e.id_col:void 0,target_col:"string"==typeof e.target_col?e.target_col:void 0,n_train:"number"==typeof e.n_train?e.n_train:void 0,n_test:"number"==typeof e.n_test?e.n_test:void 0,judge:"string"==typeof e.judge&&""!==e.judge?e.judge:void 0,board_event:"string"==typeof e.board_event&&""!==e.board_event?e.board_event:null,needs_gpu:!0===e.needs_gpu})}return i}export function dataFileUrls(t){const e=t.data_base;if("string"!=typeof e||""===e)return null;const r=e.replace(/\/$/,"");return{train:`${r}/train.csv`,test:`${r}/test.csv`,sample_submission:`${r}/sample_submission.csv`}}export function buildStarterCells(t,e){const r=e.id_col??"id",i=e.target_col??"target",a=(o=e.metric,/rmse|mse|mae|error/i.test(o));var o;const n="icoa-holdout"===e.judge,s=t=>({kind:"markdown",source:t,result:null}),l=t=>({kind:"code",source:t.join("\n"),result:null}),c=[`# ${e.title}`,"",...e.description?[e.description,""]:[],`Kaggle-style practice — metric: **${e.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${i}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...n?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],"","**AI help:** split your terminal (`Ctrl-b %`), run `icoa` in the right pane","and type `ai4ioai` for a live Gemma 3n E4B. Ask it for feature ideas or bug fixes —","then verify every suggestion with the val score. A tip that lowers it, drop it.",...e.licence?["",`**Data licence:** ${e.licence}`]:[],...e.attribution?[`**Attribution:** ${e.attribution}`]:[]].join("\n"),d=l(["# setup — load the data (leave as is)","import os","import numpy as np","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.feature_extraction.text import TfidfVectorizer","from sklearn.model_selection import train_test_split",a?"from sklearn.metrics import mean_squared_error":"from sklearn.metrics import accuracy_score","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${t}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...e.data_base?[`DATA_BASE = "${e.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")',`ID, TARGET = "${r}", "${i}"`,'print(f"train {train.shape} · test {test.shape}")']),m=l(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Category (<= 20 distinct): one-hot.","# Free text: TF-IDF — on a text task the sentences ARE the signal, and dropping",'# them as "high-cardinality" leaves nothing to train on (that used to crash the','# whole notebook with "No objects to concatenate").',"feat = [c for c in train.columns if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","# long-ish strings with many distinct values = free text, worth vectorising","txt = [c for c in feat if c not in num and c not in cat"," and Xtr_raw[c].astype(str).str.len().mean() >= 12]","for c in num:"," med = Xtr_raw[c].median()"," Xtr_raw[c] = Xtr_raw[c].fillna(med)"," Xte_raw[c] = Xte_raw[c].fillna(med)","blocks_tr, blocks_te = [], []","if num or cat:"," d_tr = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)"," d_te = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",' d_tr, d_te = d_tr.align(d_te, join="left", axis=1, fill_value=0)'," blocks_tr.append(d_tr.to_numpy(dtype=float))"," blocks_te.append(d_te.to_numpy(dtype=float))","for c in txt:"," # fillna BEFORE astype(str): a real NaN reaching the vectoriser raises",' # "np.nan is an invalid document", and astype alone does not catch it.',' tr_txt = Xtr_raw[c].fillna("").astype(str)',' te_txt = Xte_raw[c].fillna("").astype(str)'," vec = TfidfVectorizer(max_features=3000, ngram_range=(1, 2), min_df=2)"," blocks_tr.append(vec.fit_transform(tr_txt).toarray())"," blocks_te.append(vec.transform(te_txt).toarray())","if not blocks_tr:",' raise SystemExit("no usable feature columns — look at train.csv and build them by hand")',"X = np.hstack(blocks_tr)","X_test = np.hstack(blocks_te)","y = train[TARGET]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"{X.shape[1]} model-ready features "',' f"({len(num)} numeric, {len(cat)} one-hot, {len(txt)} TF-IDF text)")']),p=l(a?["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import Ridge","model = Ridge()"]:["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import LogisticRegression","model = LogisticRegression(max_iter=2000)"]),u=l(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)",a?'print("val RMSE:", round(mean_squared_error(y_val, model.predict(X_val)) ** 0.5, 4))':'print("val accuracy:", round(accuracy_score(y_val, model.predict(X_val)), 4))']),_=l(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',`pd.DataFrame({"${r}": test["${r}"], "${i}": pred}).to_csv(out, index=False)`,'print("wrote", out)',n?`print("score it: icoa kaggle submit ${e.comp_id}")`:'print("format check: icoa kaggle check")']),g=n?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${e.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:e.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${e.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This is a placeholder practice dataset — it has no live Kaggle page yet._","When the real competition dataset lands, this cell will link straight to","its Kaggle submission page. The loop is identical: upload `submission.csv`,","read the score, improve the MODEL cell, repeat."];return[s(c),d,m,p,u,_,s(g.join("\n"))]}export function parseSubmitResponse(t){const e=t&&"object"==typeof t?t:{},r=e.data??e,i=r&&"object"==typeof r?r:{};return"number"==typeof i.score&&"string"==typeof i.metric?{ok:!0,score:i.score,metric:i.metric,rank:"number"==typeof i.rank_at_time?i.rank_at_time:null,fieldSize:"number"==typeof i.field_size?i.field_size:null,deduped:!0===i.deduped,boardEvent:"string"==typeof i.board_event?i.board_event:null}:"string"==typeof i.reason&&""!==i.reason?{ok:!1,reason:i.reason,error:"string"==typeof i.error?i.error:void 0,problems:Array.isArray(i.problems)?i.problems.filter(t=>"string"==typeof t):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(t,e){const r=[],i=t.trim().split(/\r?\n/),a=e.trim().split(/\r?\n/),o=i[0]??"",n=a[0]??"";o.trim()!==n.trim()&&r.push(`header mismatch: expected "${n}", got "${o}"`);const s=i.slice(1).filter(t=>""!==t.trim()),l=a.slice(1).filter(t=>""!==t.trim());s.length!==l.length&&r.push(`row count mismatch: expected ${l.length}, got ${s.length}`);const c=t=>new Set(t.map(t=>(t.split(",")[0]??"").trim())),d=c(s),m=c(l),p=[...m].filter(t=>!d.has(t)),u=[...d].filter(t=>!m.has(t));if(p.length>0||u.length>0){const t=[];p.length>0&&t.push(`${p.length} missing (e.g. ${p[0]})`),u.length>0&&t.push(`${u.length} unknown (e.g. ${u[0]})`),r.push(`id mismatch vs sample_submission: ${t.join(", ")}`)}for(let t=0;t<s.length;t++)if(s[t].split(",").some(t=>""===t.trim())){r.push(`empty cell in data row ${t+1}`);break}return{ok:0===r.length,problems:r}}
1
+ export function parseKaggleTaskList(e){const t=e??{},n=(t.data??t).tasks;if(!Array.isArray(n))return[];const i=[];for(const e of n){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&i.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",description:"string"==typeof t.description&&""!==t.description?t.description:void 0,kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0,data_base:"string"==typeof t.data_base&&""!==t.data_base?t.data_base:null,id_col:"string"==typeof t.id_col?t.id_col:void 0,target_col:"string"==typeof t.target_col?t.target_col:void 0,n_train:"number"==typeof t.n_train?t.n_train:void 0,n_test:"number"==typeof t.n_test?t.n_test:void 0,judge:"string"==typeof t.judge&&""!==t.judge?t.judge:void 0,board_event:"string"==typeof t.board_event&&""!==t.board_event?t.board_event:null,needs_gpu:!0===t.needs_gpu})}return i}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const n=t.replace(/\/$/,"");return{train:`${n}/train.csv`,test:`${n}/test.csv`,sample_submission:`${n}/sample_submission.csv`}}export function buildStarterCells(e,t){const n=t.id_col??"id",i=t.target_col??"target";var r;r=t.metric,/rmse|mse|mae|error/i.test(r);const a="icoa-holdout"===t.judge,s=e=>({kind:"markdown",source:e,result:null}),o=e=>({kind:"code",source:e.join("\n"),result:null}),l=[`# ${t.title}`,"",...t.description?[t.description,""]:[],`Kaggle-style practice — metric: **${t.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${i}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...a?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],"","**AI help:** split your terminal (`Ctrl-b %`), run `icoa` in the right pane","and type `ai4ioai` for a live Gemma 3n E4B. Ask it for feature ideas or bug fixes —","then verify every suggestion with the val score. A tip that lowers it, drop it.",...t.licence?["",`**Data licence:** ${t.licence}`]:[],...t.attribution?[`**Attribution:** ${t.attribution}`]:[]].join("\n"),c=o(["# setup — load the data (leave as is)","import os","import numpy as np","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.feature_extraction.text import TfidfVectorizer","from sklearn.model_selection import train_test_split","from sklearn.metrics import accuracy_score, mean_squared_error","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${e}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...t.data_base?[`DATA_BASE = "${t.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")','sub_fmt = pd.read_csv(DIR + "/sample_submission.csv")',"","# 🔴 The submission column names are NOT always the training column names.","# On tasks imported from other platforms the two genuinely differ: train.csv",'# labels the answer "class" or "result" while sample_submission.csv calls it','# "answer". Hard-coding the submission name here used to raise KeyError on the',"# very first cell. So trust the DATA: whatever column train has and test lacks","# is the thing to predict.",`SUB_ID, SUB_TARGET = "${n}", "${i}" # names the submission file wants`,"only_train = [c for c in train.columns if c not in test.columns]","TARGET = only_train[-1] if only_train else SUB_TARGET","shared = [c for c in train.columns if c in test.columns]","# Only treat a column as the row id when the submission actually names it AND",'# both files carry it. Falling back to "first shared column" silently spent a',"# real feature as an id on tasks whose id lives only in test.csv.","ID = SUB_ID if SUB_ID in shared else None",'assert TARGET in train.columns, f"cannot find the label column in {list(train.columns)}"',"","# Regression or classification? Decided from the labels, not from metadata —","# several tasks ship continuous labels, and handing those to a classifier",'# raises "Unknown label type: continuous".',"REG = is_numeric_dtype(train[TARGET]) and train[TARGET].nunique() > 20",'print(f"train {train.shape} · test {test.shape} · predicting {TARGET!r} "'," f\"({'regression' if REG else 'classification'})\")"]),d=o(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Category (<= 20 distinct): one-hot.","# Free text: TF-IDF — on a text task the sentences ARE the signal, and dropping",'# them as "high-cardinality" leaves nothing to train on (that used to crash the','# whole notebook with "No objects to concatenate").',"# only columns present in BOTH files — a train-only column cannot be a feature","# at prediction time, and indexing test with it raises KeyError.","feat = [c for c in shared if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","# Everything else is vectorised as text. Requiring a long average length here","# used to throw away high-cardinality SHORT strings — ingredient names, single","# words, category codes — which on several tasks are the entire signal, leaving","# the notebook with zero features.","txt = [c for c in feat if c not in num and c not in cat]","for c in num:"," med = Xtr_raw[c].median()"," Xtr_raw[c] = Xtr_raw[c].fillna(med)"," Xte_raw[c] = Xte_raw[c].fillna(med)","blocks_tr, blocks_te = [], []","if num or cat:"," d_tr = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)"," d_te = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",' d_tr, d_te = d_tr.align(d_te, join="left", axis=1, fill_value=0)'," blocks_tr.append(d_tr.to_numpy(dtype=float))"," blocks_te.append(d_te.to_numpy(dtype=float))","for c in txt:"," # fillna BEFORE astype(str): a real NaN reaching the vectoriser raises",' # "np.nan is an invalid document", and astype alone does not catch it.',' tr_txt = Xtr_raw[c].fillna("").astype(str)',' te_txt = Xte_raw[c].fillna("").astype(str)'," # min_df=1: on a short-token column (one ingredient per row) min_df=2 can"," # filter the vocabulary down to nothing."," long_col = tr_txt.str.len().mean() >= 12"," # Try the good settings, then a permissive fallback, then give up on THIS"," # column only. A column whose vocabulary prunes to nothing used to abort the",' # whole run with "After pruning, no terms remain".',' for kw in ({"min_df": 2 if long_col else 1,',' "analyzer": "word" if long_col else "char_wb"},',' {"min_df": 1, "analyzer": "char_wb"}):'," try:"," vec = TfidfVectorizer(max_features=3000, ngram_range=(1, 2), **kw)"," b_tr = vec.fit_transform(tr_txt).toarray()"," blocks_tr.append(b_tr)"," blocks_te.append(vec.transform(te_txt).toarray())"," break"," except ValueError as e:"," last = e"," else:",' print(f" skipped text column {c!r}: {last}")',"if not blocks_tr:"," raise SystemExit(",' f"No usable feature columns. The shared columns are {feat} — none of them "',' f"is numeric, categorical or text.\\n"',' f"Two kinds of task land here, and both are real work rather than a bug:\\n"',' f" 1. audio/image — train.csv only lists sample ids and labels, and the "',' f"signal is in the media files shipped with the task. Load them "',' f"(librosa / PIL), turn each file into a feature row.\\n"',' f" 2. train.csv and test.csv describe different things (a retrieval or "',' f"matching task). Read both files, work out what links a test row to a "',' f"train row, and build that mapping yourself.\\n"',' f"Either way: replace this cell. train={list(train.columns)} "',' f"test={list(test.columns)}"'," )","X = np.hstack(blocks_tr)","X_test = np.hstack(blocks_te)","y = train[TARGET]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"{X.shape[1]} model-ready features "',' f"({len(num)} numeric, {len(cat)} one-hot, {len(txt)} TF-IDF text)")']),u=o(["# MODEL — a working baseline. Improve THIS cell to climb the board.","from sklearn.linear_model import LogisticRegression, Ridge","# REG was decided from the labels back in setup.","model = Ridge() if REG else LogisticRegression(max_iter=2000)"]),m=o(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)","p_val = model.predict(X_val)","if REG:",' print("val RMSE:", round(mean_squared_error(y_val, p_val) ** 0.5, 4))',"else:",' print("val accuracy:", round(accuracy_score(y_val, p_val), 4))']),p=o(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',"# Copy the layout of sample_submission.csv and swap in the predictions, rather","# than rebuilding the file from column names. Some tasks want more than two","# columns (e.g. subtaskID,datapointID,answer) and a hand-built 2-column frame","# is rejected by the grader even when every prediction is right.","if len(sub_fmt) == len(pred):"," sub = sub_fmt.copy()"," sub[sub.columns[-1]] = pred","else:"," keys = {}"," if ID is not None and ID in test.columns:"," keys[SUB_ID] = test[ID]"," keys[SUB_TARGET] = pred"," sub = pd.DataFrame(keys)",' print(f"NOTE: sample_submission has {len(sub_fmt)} rows but test has "',' f"{len(pred)} — built the file from column names instead; "',' f"check it against the task page before submitting.")',"sub.to_csv(out, index=False)",'print("wrote", out, "·", list(sub.columns))',a?`print("score it: icoa kaggle submit ${t.comp_id}")`:'print("format check: icoa kaggle check")']),f=a?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${t.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:t.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${t.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This is a placeholder practice dataset — it has no live Kaggle page yet._","When the real competition dataset lands, this cell will link straight to","its Kaggle submission page. The loop is identical: upload `submission.csv`,","read the score, improve the MODEL cell, repeat."];return[s(l),c,d,u,m,p,s(f.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},n=t.data??t,i=n&&"object"==typeof n?n:{};return"number"==typeof i.score&&"string"==typeof i.metric?{ok:!0,score:i.score,metric:i.metric,rank:"number"==typeof i.rank_at_time?i.rank_at_time:null,fieldSize:"number"==typeof i.field_size?i.field_size:null,deduped:!0===i.deduped,boardEvent:"string"==typeof i.board_event?i.board_event:null}:"string"==typeof i.reason&&""!==i.reason?{ok:!1,reason:i.reason,error:"string"==typeof i.error?i.error:void 0,problems:Array.isArray(i.problems)?i.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const n=[],i=e.trim().split(/\r?\n/),r=t.trim().split(/\r?\n/),a=i[0]??"",s=r[0]??"";a.trim()!==s.trim()&&n.push(`header mismatch: expected "${s}", got "${a}"`);const o=i.slice(1).filter(e=>""!==e.trim()),l=r.slice(1).filter(e=>""!==e.trim());o.length!==l.length&&n.push(`row count mismatch: expected ${l.length}, got ${o.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),d=c(o),u=c(l),m=[...u].filter(e=>!d.has(e)),p=[...d].filter(e=>!u.has(e));if(m.length>0||p.length>0){const e=[];m.length>0&&e.push(`${m.length} missing (e.g. ${m[0]})`),p.length>0&&e.push(`${p.length} unknown (e.g. ${p[0]})`),n.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<o.length;e++)if(o[e].split(",").some(e=>""===e.trim())){n.push(`empty cell in data row ${e+1}`);break}return{ok:0===n.length,problems:n}}
@@ -1,2 +1 @@
1
1
  export declare function setLearnSessionStarted(v: boolean): void;
2
- export declare function learnSessionStarted(): boolean;
@@ -1 +1 @@
1
- let e=!1;export function setLearnSessionStarted(t){e=t}export function learnSessionStarted(){return e}
1
+ let e=!1;export function setLearnSessionStarted(t){e=t}
@@ -25,6 +25,34 @@ export declare function isInWSL(): boolean;
25
25
  * WSL distribution.
26
26
  */
27
27
  export declare function isNativeWindowsCmd(): boolean;
28
+ /**
29
+ * True on Windows Node, full stop — no WSL env override.
30
+ *
31
+ * Inside a WSL distribution Node reports `process.platform === 'linux'`, so
32
+ * `win32` on its own already means "not WSL". Prefer this over
33
+ * isNativeWindowsCmd() wherever a wrong answer HIDES a diagnosis: a Windows
34
+ * user who has set WSLENV on the Windows side (a documented way to configure
35
+ * env passing into WSL) trips isInWSL() and would be told they are on Linux.
36
+ * That is how the arena `/edit` "vi not found" message stayed wrong.
37
+ */
38
+ export declare function isNativeWindows(): boolean;
39
+ /**
40
+ * Every absolute path `bin` could occupy on PATH, in PATH order. Pure — takes
41
+ * env + platform so the win32 branch is unit-testable from a posix box.
42
+ *
43
+ * Windows needs PATHEXT expansion (`vi` never matches a bare `vi`; it would be
44
+ * `vi.exe` / `vi.cmd`) and `;` as the PATH delimiter, so the separator and the
45
+ * suffix set BOTH have to follow `plat`, not the host.
46
+ */
47
+ export declare function binaryCandidates(bin: string, env?: NodeJS.ProcessEnv, plat?: NodeJS.Platform): string[];
48
+ /**
49
+ * True when `bin` is reachable on PATH. A PATH scan, NOT a shell probe: the
50
+ * old `execSync('command -v vi')` idiom is a POSIX-shell builtin, and on
51
+ * Windows `execSync` routes through cmd.exe where `command` does not exist —
52
+ * so it reported EVERY binary as missing regardless of what was installed.
53
+ * (That is the v2.19.42x arena `/edit` "vi not found" false negative.)
54
+ */
55
+ export declare function whichBinary(bin: string, env?: NodeJS.ProcessEnv, plat?: NodeJS.Platform): boolean;
28
56
  /**
29
57
  * Probe whether any Python 3 binary is reachable. Silent — no stderr leaks
30
58
  * to the user. Used to decide whether Q31-35 practical questions are even
@@ -1 +1 @@
1
- import{execFileSync as o}from"node:child_process";import{lstatSync as t,realpathSync as n,readFileSync as r}from"node:fs";import{dirname as e}from"node:path";export function isInWSL(){return!(!process.env.WSL_DISTRO_NAME&&!process.env.WSLENV)}export function isNativeWindowsCmd(){return"win32"===process.platform&&!isInWSL()}export function hasPython(){const t=[["python3",["--version"]],["python",["--version"]],["py",["-3","--version"]]];for(const[n,r]of t)try{return o(n,r,{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}),!0}catch{}return!1}export function detectIcoaInstalls(){if(isNativeWindowsCmd())return[];let i=[];try{i=o("which",["-a","icoa"],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim().split("\n").filter(Boolean)}catch{return[]}return i.map(o=>{const i={path:o};try{let s=o;t(o).isSymbolicLink()&&(s=n(o));const c=e(s),p=e(c);i.pkgDir=p;const a=JSON.parse(r(`${p}/package.json`,"utf-8"));i.version=a.version}catch{}return i})}
1
+ import{execFileSync as o}from"node:child_process";import{lstatSync as t,realpathSync as n,readFileSync as r,statSync as i}from"node:fs";import{dirname as e,posix as s,win32 as c}from"node:path";export function isInWSL(){return!(!process.env.WSL_DISTRO_NAME&&!process.env.WSLENV)}export function isNativeWindowsCmd(){return"win32"===process.platform&&!isInWSL()}export function isNativeWindows(){return"win32"===process.platform}export function binaryCandidates(o,t=process.env,n=process.platform){const r="win32"===n,i=r?c:s,e=t.PATH??t.Path??"",p=r?(t.PATHEXT||".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean):[""],a=[];for(const t of e.split(r?";":":"))if(t)for(const n of p)a.push(i.join(t,o+n));return a}export function whichBinary(o,t=process.env,n=process.platform){for(const r of binaryCandidates(o,t,n))try{if(i(r).isFile())return!0}catch{}return!1}export function hasPython(){const t=[["python3",["--version"]],["python",["--version"]],["py",["-3","--version"]]];for(const[n,r]of t)try{return o(n,r,{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}),!0}catch{}return!1}export function detectIcoaInstalls(){if(isNativeWindowsCmd())return[];let i=[];try{i=o("which",["-a","icoa"],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim().split("\n").filter(Boolean)}catch{return[]}return i.map(o=>{const i={path:o};try{let s=o;t(o).isSymbolicLink()&&(s=n(o));const c=e(s),p=e(c);i.pkgDir=p;const a=JSON.parse(r(`${p}/package.json`,"utf-8"));i.version=a.version}catch{}return i})}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.427",
3
+ "version": "2.19.429",
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": {
@@ -24,7 +24,6 @@
24
24
  "smoke:offline": "tsc && SMOKE_NO_NETWORK=1 node --test test/smoke/*.test.js",
25
25
  "ux-audit": "node panda/ux-audit.js",
26
26
  "ux-record": "bash panda/ux-record.sh",
27
- "postinstall": "node -e \"try{require('./dist/postinstall.js')}catch(e){}\"",
28
27
  "prepublishOnly": "npm run build:release",
29
28
  "prepare": "husky"
30
29
  },
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Post-install script: shows a progress bar during ICOA CLI setup.
4
- * Runs automatically after `npm install -g icoa-cli`.
5
- */
6
- export {};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- const o=["Initializing ICOA CLI...","Loading competition modules...","Configuring exam system...","Setting up references...","Finalizing installation..."];function l(o,l){const e=Math.round(o/100*30),n=30-e,m=`${"█".repeat(e)}${"░".repeat(n)}`,t=`${String(o).padStart(3)}%`;process.stdout.write(`\r ${m} ${t} ${l}`)}(async function(){console.log(),console.log(" ██╗ ██████╗ ██████╗ █████╗"),console.log(" ██║██╔════╝██╔═══██╗██╔══██╗"),console.log(" ██║██║ ██║ ██║███████║"),console.log(" ██║██║ ██║ ██║██╔══██║"),console.log(" ██║╚██████╗╚██████╔╝██║ ██║"),console.log(" ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝"),console.log();for(let e=0;e<o.length;e++){const n=Math.round(e/o.length*100),m=Math.round((e+1)/o.length*100);for(let t=n;t<=m;t++)l(t,o[e]),await new Promise(o=>setTimeout(o,15))}console.log(),console.log(),console.log(" ✓ ICOA CLI installed successfully!"),console.log(),console.log(" Get started:"),console.log(" icoa Launch and select your mode"),console.log(" icoa --help Show all commands"),console.log()})().catch(()=>{});export{};