icoa-cli 2.19.450 → 2.19.452
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/demo2.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/commands/sim.js +1 -1
- package/dist/commands/sprint.js +1 -1
- package/dist/lib/open-file.d.ts +27 -1
- package/dist/lib/open-file.js +1 -1
- package/dist/lib/sprint-meta.d.ts +7 -0
- package/dist/lib/sprint-meta.js +1 -1
- package/package.json +1 -1
package/dist/commands/learn.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as n,execSync as t,spawn as r}from"node:child_process";import{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,statSync as h,writeFileSync as p}from"node:fs";import{emptyDynamics as f,foldEditSession as b,isEmpty as w,noteRun as $}from"../lib/arena-edit-dynamics.js";import{dirname as k,join as v}from"node:path";import{fileURLToPath as A}from"node:url";import{loadCurriculumById as C,validateEAToken as _,syncProgress as T,syncCardFeedback as I}from"../lib/learn-curricula.js";import{normalizeTokenBody as x}from"../lib/token-format.js";import{fetchMyScores as E,recallCoach as S,setNickname as P,streamLearnTutor as M,submitPqs as L,viewPqsTop as q,viewHonors as W}from"../lib/learn-ai.js";import{contestReset as R,contestStart as N,contestSubmit as O,linkByIndex as j,linkSuggest as D,linkToken as Y,fetchGate as U,timeLeft as F}from"../lib/learn-contest.js";import{getConfig as z,saveConfig as H}from"../lib/config.js";import{isNativeWindows as B,isWindowsBuildInWslShell as Z,whichBinary as J}from"../lib/platform.js";import{loadLearnState as K,saveLearnState as Q,newLearnState as V,updateStreak as X,markCardComplete as G,recordMCQ as ee,recordCheck as oe,markPracticalComplete as ne,addAchievement as te}from"../lib/learn-state.js";import{renderWelcome as re,renderKnowledgeCard as le,renderMCQCard as se,renderMCQFeedback as ae,renderPracticalCard as ie,renderPracticalSuccess as ce,renderSimDemoCard as de,renderMilestone as ge,renderArenaTaskCard as ue,renderComingSoonCard as ye,renderStatus as me,renderPhaseComplete as he,renderCurriculumComplete as pe,setLearnAiEnabled as fe,setLearnHonorRanks as be,setLearnPqsViewCards as we,setLearnWidth as $e,resolveLearnWidth as ke,learnWidthCap as ve,learnW as Ae,renderHonorWall as Ce,wrapMixed as _e}from"../lib/learn-render.js";import{printError as Te}from"../lib/ui.js";const Ie=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(xe){xe.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async xe=>{xe?.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(),xe="LEARNDEMO01");let Ee=xe.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ee)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Se=null;const Pe=/^[A-Z0-9]+DEMO01$/i.test(Ee),Me=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ee);let Le=!1,qe=!1;if(Pe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Se=await C(Ee,Ee,!0);else if(Me){console.log(),console.log(chalk.gray(" Validating token..."));let e=await _(Ee);if(!e.ok){const o=x(Ee);if(o!==Ee){const n=await _(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ee} → ${o}`)),e=n,Ee=o)}}if(!e.ok)return Te(`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 🐼"):"")),Le=!0===e.aiEnabled,qe=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Se=await C(e.curriculumId||"LEARNDEMO01",Ee,!0),!Se)return Te(`Could not open a learn curriculum for token '${Ee}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ee}`)+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 ${Ee}`)+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(!Se){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Te(`Could not reach the learn server to open ${Ee}.`),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 ${Ee}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Te(`Unknown learn token: ${Ee}`),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 We=K(),Re=!1;try{We&&We.token===Ee?X(We):(We=V(Ee,Se.id,Se.totalCards),Re=!0),Q(We),re(Se,We,Re)}catch{return Te("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 ${Ee}`)+chalk.gray(".")),void console.log()}const Ne=s(),Oe=null!==Ne,je=Oe?Ne.listeners("line").slice():[];Oe&&Ne.removeAllListeners("line");const De=Oe?Ne:o({input:process.stdin,output:process.stdout,terminal:!0}),Ye=Oe?De.prompt:null;Oe&&(De.prompt=e.prototype.prompt);const Ue=()=>{Oe&&Ye&&(De.prompt=Ye)},Fe=()=>{De.setPrompt(lo?chalk.bold.green(`icoa ${a()}> `):eo?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Xe?"icoa learn ai> ":"icoa learn> ")),De.prompt()};let ze=null,He=null,Be=null,Ze=null,Je=[],Ke=!1,Qe=null;const Ve=()=>{Qe&&clearTimeout(Qe),Qe=null,Je=[],Ke=!1,Ze=null};let Xe=!1,Ge=!1,eo=!1,oo=null,no=!1,to=0,ro=!1,lo=!1;const so=new Map,ao=()=>{let e=so.get(We.currentCard);return e||(e=[],so.set(We.currentCard,e)),e};let io=!1;const co=new Set;let go=!1,uo=0;const yo=()=>(z().language||"en").toLowerCase().startsWith("zh");fe(Le),$e(ke(z())),we(co);const mo=new Map;be(mo);const ho=[];let po=null;const fo=new Promise(e=>{po=e}),bo=()=>{const e=po;po=null,e?.()},wo="1"===process.env.ICOA_LEARN_EMBEDDED,$o=e=>Se.cards.find(o=>o.number===e);let ko=null,vo=null;const Ao=new Map,Co=!Ee.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ee),_o=async()=>{if(!Co)return;const e=await U(Ee);e.ok&&e.data&&(ko=e.data)},To=e=>{const o=Se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Io=e=>{if(!qe||!ko)return null;const o=To(e);if(o<=ko.unlocked_through_phase)return null;const n=ko.phases.find(e=>e.phase===ko.unlocked_through_phase),t=[chalk.yellow(yo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${ko.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${ko.unlocked_through_phase}'s core tasks first:`)];if(n?.contest&&!n.contest.passed){const e=n.contest.slots??[];if(e.length>0)for(const o of e)o.passed||t.push(chalk.gray(yo()?` ⚔ 练习赛 ${ko.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${ko.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else t.push(chalk.gray(yo()?` ⚖ 判分赛: 最好 ${n.contest.best_ac}/${n.contest.n} AC,需 ${n.contest.need} — 输入 `:` ⚖ contest: best ${n.contest.best_ac}/${n.contest.n} AC, need ${n.contest.need} — type `)+chalk.bold.green("contest"))}if(n?.checks?.enabled&&!n.checks.passed){const e=n.checks.missing??[],o=e.slice(0,8).join(yo()?"、":", "),r=e.length>8?yo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:yo()?" 张":"";t.push(chalk.gray(yo()?` ✓ 逐卡自测: ${n.checks.good}/${n.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${n.checks.good}/${n.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return n?.research&&!n.research.passed&&t.push(chalk.gray(yo()?` ⭐ 提问研究: ${n.research.good_cards}/${n.research.need_cards} 卡达到 ${n.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${n.research.good_cards}/${n.research.need_cards} cards at ${n.research.min_score}+ — research with /ai, then /submit`)),t.join("\n")},xo=async e=>qe?null===Io(e)?null:(await _o(),Io(e)):null;Co&&await _o();const Eo=async e=>{const o=Se.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Se.modules.find(e=>e.number===o.number+1);let t;if(Le){const e=await E({token:Ee,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}Co&&await _o();const r=ko?.phases.find(e=>e.phase===o.number);return he(Se,We,o,n,t,r),!0},So=()=>{go=!0,console.log(chalk.gray(yo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Po=()=>{oo=null;const e=$o(We.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":le(e,Se),e.check?(Be=e.number,uo=Date.now()):(G(We,e.number),Q(We));break;case"mcq":se(e,Se),ze=e.number;break;case"practical":ie(e,Se),He=e.number;break;case"sim_demo":de(e,Se),G(We,e.number),Q(We);break;case"milestone":ge(e,Se),te(We,e.badge),G(We,e.number),Q(We);break;case"arena_task":ue(e,Se),G(We,e.number),Q(We);break;case"coming_soon":ye(e,Se),G(We,e.number),Q(We)}Mo(e.number)},Mo=e=>{if(!Co||!ko)return;const o=Se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const n=e-o.cardRange[0]+1;if(n%4!=0)return;const t=n/4,r=ko.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===t);if(!l)return;const s=(e,o,n,t)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${o}:${String(n).padStart(2,"0")}`})(n),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${n(o.getMonth()+1)}-${n(o.getDate())} ${n(o.getHours())}:${n(o.getMinutes())}`})(t);return`🏆 ${e} ${o}/${l.n}`+(r?yo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Ae());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${yo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(yo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(yo()?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(yo()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),(l.carryable_ac??0)>0&&console.log(c+chalk.cyan(yo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(yo()?"✍ 第一次用 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(yo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(yo()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${t}`)+(l.passed?chalk.gray(yo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(yo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(yo()?" 继续学习":" keep going"):chalk.gray(yo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Lo=()=>{Ee.endsWith("DEMO01")?console.log(chalk.yellow(yo()?" 🐼 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(yo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(yo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},qo=async(e,o)=>{if(Le){Ge=!0;try{console.log(),console.log(chalk.gray("deep"===o?yo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":yo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await M({token:Ee,cardNumber:We.currentCard,question:e,mode:o,history:ao().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(t||(process.stdout.write(n?"\n\n ":" "),t=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||t)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(yo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(ao().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(` (${yo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(yo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Be&&console.log(chalk.gray(yo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ge=!1}}else Lo()},Wo=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ro=async()=>{eo&&vo?Ho?Bo(Ho):Uo():oo?await No():Po()},No=async()=>{Ge=!0;try{console.log();const e=await W({token:Ee,curriculumId:Se.id,cardNumber:We.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(yo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(yo()?` 🏆 本卡实时 Top-3 — 第 ${We.currentCard} 张`:` 🏆 Live top-3 — card ${We.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(yo()?" (你)":" (you)"):""))}else console.log(chalk.gray(yo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(mo.set(We.currentCard,e.mine.rank),console.log(chalk.white(yo()?" 你: ":" You: ")+chalk.bold.yellow(yo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(yo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Le&&console.log(chalk.gray(yo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ce({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(yo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(yo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(yo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),oo="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 返回卡片":" returns to the card")),console.log()}finally{Ge=!1}},Oo=e=>yo()&&e.title_zh||e.title,jo=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of _e(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},Do=e=>{console.log(),console.log(chalk.bold.green(yo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 Linked — credit now carries both ways"));for(const o of e.members)console.log(chalk.gray(" · ")+chalk.white(o.curriculum_id)+chalk.gray(` ${o.token}`));console.log(chalk.gray(yo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Yo=e=>vo.data.solved.includes(e.id)?"✅":vo.data.carried?.includes(e.id)?"✅↗":vo.tried.has(e.id)?"❌":"⬜",Uo=()=>{const e=vo.data,o=F(e.deadline),n=(e.carried??[]).filter(o=>!e.solved.includes(o)),t=e.solved.length+n.length,r=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(yo()?` · 第 ${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(yo()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(yo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(yo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(yo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yo()?" 带过来,不必重做":" to carry them over instead of redoing them"));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(yo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(yo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(yo()?` 满血重开本组(${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)} `)+Yo(e)+chalk.white(` ${Oo(e)}`))}),console.log(),Fo()},Fo=()=>{console.log(chalk.gray(yo()?" /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(yo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 返回课程":" returns to the lesson")),console.log()},zo=e=>{const o=parseInt(e,10),n=vo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(yo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let Ho=null;const Bo=e=>{const o=zo(e);if(!o)return;const{p:n,n:t}=o;Ho=String(t),console.log(),console.log(chalk.bold.white(` ${Yo(n)} ${Oo(n)}`)),console.log();for(const e of(e=>yo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of _e(e,Ae()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of n.samples??[]){r+=1,console.log(),console.log(chalk.gray(yo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(yo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(n.samples??[]).length&&(console.log(),console.log(chalk.gray(yo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(yo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(yo()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${t}`.padEnd(11))+chalk.gray(yo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(yo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(yo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((yo()," ↩ "))+chalk.bold.green("back")+chalk.gray(yo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(yo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((yo()," / "))+chalk.bold.green("wide")+chalk.gray(yo()?" 换语言/宽度":" language / width")),console.log()},Zo=async(e,o)=>await new Promise(n=>{const t=process.stdin,l=!!t.isTTY&&!!t.isRaw;if(De.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:vo.dir}),a=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&l)try{t.setRawMode(!0)}catch{}De.resume(),n(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Jo=()=>{console.log(chalk.yellow(yo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(yo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(yo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(yo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Ko=new Map,Qo=async e=>{const o=e.trim().toLowerCase(),s=eo&&o.startsWith("/")?o.slice(1):o;if(Ge)return;if(null!==Ze){if(Je.push(e.replace(/\s+$/,"")),Qe&&clearTimeout(Qe),Qe=null,Ke){const e=Je[Je.length-1]??"";return"/cancel"===e.trim()?(Ve(),console.log(chalk.gray(yo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Fe()):""!==e.trim()?void Fe():(Je.pop(),void await a())}return void(Qe=setTimeout(()=>{if(Qe=null,Je.length>1){Ke=!0;const e=Je.length;return console.log(chalk.cyan(yo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(yo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Fe()}a()},140))}async function a(){const e=Je.join("\n").replace(/^\s+|\s+$/g,""),o=Ze??We.currentCard,n=Je.length;if(Ve(),""===e)console.log(chalk.gray(yo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(yo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(yo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(yo()?" 即可执行。":" again to run it."));else{const t=uo>0?Date.now()-uo:void 0;if(await I(Ee,{curriculum_id:Se.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const e=n>1?yo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(yo()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(yo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Fe()}if(no){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return no=!1,console.log(),console.log(chalk.yellow(yo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(yo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(yo()?" 即可执行该命令。":" again to run it.")),console.log(),void Fe();if(!o)return no=!1,console.log(chalk.gray(yo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Fe();const n=await P({token:Ee,nickname:o});if(n.ok)no=!1,console.log(chalk.bold.green(yo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(yo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{to+=1;const e="taken"===n.code?yo()?"已被占用":"already taken":"bad_charset"===n.code?yo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?yo()?"未通过审核":"did not pass review":n.message||"error";if(!(to>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Fe();no=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Fe()}if(io){io=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ge=!0;try{console.log(),console.log(chalk.gray(yo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await L({token:Ee,cardNumber:We.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(yo()?"评审暂不可用。":"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(yo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(yo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(yo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(yo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(yo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(yo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=yo()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(yo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(yo()?` 第 ${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 Wo(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(yo()?" 改进提问: ":" 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(` (${yo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?co.add(We.currentCard):co.delete(We.currentCard),"number"==typeof e.rank&&mo.set(We.currentCard,e.rank);const o=await W({token:Ee,curriculumId:Se.id,cardNumber:We.currentCard});o.ok&&o.totals&&o.chapters&&(Ce({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Pe&&(no=!0,to=0,console.log(chalk.bold.yellow(yo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(yo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(yo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Ge=!1}})():(console.log(chalk.gray(yo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Be&&(console.log(chalk.gray(yo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Fe()}if(go)return go=!1,Po(),void Fe();if(!o)return void Fe();if(lo)return"exit"===await i(e.trim())&&(lo=!1),void Fe();if(Xe){if(["q","quit","exit","back","b","menu"].includes(o))return Xe=!1,console.log(chalk.gray(yo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Fe();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim();return t&&(await qo(t,n?"fast":"deep"),console.log(chalk.gray(yo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Fe()}if(eo&&vo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${vo.phase}s${vo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return eo=!1,console.log(chalk.gray(yo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Po(),void Fe();if(/^\d+$/.test(o))return Bo(o),void Fe();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,t]=e;return"list"===o?Uo():t?"read"===o||"open"===o?Bo(t):"edit"===o?await(async e=>{const o=zo(e);if(!o)return;const n=v(vo.dir,`sol-${o.n}.py`);if(B())return Z()?(console.log(chalk.yellow(yo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(yo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(yo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(yo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(yo()?" ← 不能是 /mnt/c":" not /mnt/c")),console.log(chalk.bold.cyan(" sudo npm install -g icoa-cli")),console.log(chalk.bold.cyan(" hash -r")+chalk.gray(yo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(yo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(yo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(yo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(yo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(yo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(yo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(yo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!J("vi"))return console.log(chalk.yellow(yo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(yo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(yo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return h(e).size}catch{return 0}},r=t(n),l=Date.now();await Zo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),Ao.set(o.n,b(Ao.get(o.n)??f(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(yo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(yo()?" 自测样例。":" to self-check the sample.")),console.log()})(t):"run"===o?(e=>{const o=zo(e);if(!o)return;const{p:t,n:r}=o,l=v(vo.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(yo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Ao.set(r,$(Ao.get(r)??f()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(yo()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=n("python3",[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if("ENOENT"===o.code)Jo();else if(o.killed)console.log(chalk.yellow(yo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(yo()?" ✗ 程序报错:":" ✗ 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(yo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(yo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(yo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(yo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(yo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(yo()?" 改完再 /run。":" then /run again.")),console.log()})(t):"debug"===o?await(async e=>{const o=zo(e);if(!o)return;const n=v(vo.dir,`sol-${o.n}.py`);if(!d(n))return void console.log(chalk.yellow(yo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(yo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const t=await Zo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(yo()?" 回到竞技场。":" Back in the arena.")),console.log()):Jo()})(t):"recall"===o&&await(async e=>{const o=zo(e);if(!o)return;if(!Le)return void Lo();const{p:n,n:t}=o,r=v(process.cwd(),"icoa-contest"),l=`${Se.id}-phase${vo.phase}-g${vo.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?v(r,s,`sol-${t}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(yo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${vo.phase}-${vo.data.slot}-${t}`,g=Math.min(3,(Ko.get(c)??0)+1);console.log(chalk.gray(yo()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await S({token:Ee,phase:vo.phase,slot:vo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:g,lang:yo()?"zh":"en"});if(m.ok){Ko.set(c,g),console.log();for(const e of _e(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(yo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(yo()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(yo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(t):console.log(chalk.yellow(yo()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(yo()?" (花名册: /list)":" (roster: /list)")),void Fe()}if("contest"===o||"/contest"===o)return Uo(),void Fe();const t="lang"===o||/^lang\s+\S+$/.test(o),r=Ie.has(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||t||r||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(yo()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Fe()}if("tmux"===o||o.startsWith("tmux ")){try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(yo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Fe()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(De.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&t)try{n.setRawMode(!0)}catch{}De.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Fe()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(lo=!0),void Fe();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Le)return Lo(),void Fe();ro||(ro=!0,console.log(),console.log(chalk.bold.cyan(yo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(yo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(yo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),yo()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const n=o.startsWith("/ai!"),t=e.trim().slice(n?4:3).trim();if(!t){Xe=!0;const e=$o(We.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(yo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(yo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Fe()}return await qo(t,n?"fast":"deep"),void Fe()}if(!eo&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Le)return Lo(),void Fe();const e=$o(We.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(yo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(yo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(yo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(yo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(yo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(yo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),io=!0,void Fe()}const _=!eo&&"honors"===oo&&/^[1-3]$/.test(o);if(!eo&&oo&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(yo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(yo()?" ↩ back 回上一层":" ↩ back goes up one level")),void Fe();if(!eo&&(_||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Le)return Lo(),void Fe();const e=/^\/?view ([1-3])$/.exec(o),n=_?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Ge=!0;try{console.log();const o=await q({token:Ee,cardNumber:We.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(yo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&co.delete(We.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&co.add(We.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(yo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${We.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${We.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(yo()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of n){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(yo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=Wo(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(yo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),oo="view",console.log(chalk.gray((yo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Ge=!1}})(n),void Fe()}if("/honors"===o||"honors"===o)return Pe?(console.log(),console.log(chalk.gray(yo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Fe()):(await No(),void Fe());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return me(Se,We),void Fe();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await C(Se.id,Ee,!0);return void(e?(Object.assign(Se,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Po()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本")),Fe()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(z().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Fe();const n=Se.cards.some(e=>null!=e._zh),t=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===t||"zh"===t&&n,l=r?t:"en";return H({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Be=null,ze=null,He=null,Ve(),go=!1,io=!1,await Ro(),void Fe()}if(Ie.has(o)){const e=Ie.get(o),n=ke(z()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return yo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((yo()?"normal"===e?" 已是标准 64 列。":Ae()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Ae()} 列,上限 ${ve(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Ae()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Ae()} cols, cap ${ve(e)}). `)+t(e))),void Fe()):(H({learnWidth:e,learnWide:"normal"!==e}),$e(e),"normal"!==e&&Ae()<=64?(console.log(chalk.yellow(yo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((yo()?` 设置已记住(${e},上限 ${ve(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${ve(e)} cols) and applies once you widen the window. `)+t(e))),void Fe()):(console.log(chalk.green(" ✓ ")+chalk.gray((yo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Ae()} 列,上限 ${ve(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Ae()} cols, cap ${ve(e)}). `)+t(e))),Be=null,ze=null,He=null,Ve(),go=!1,io=!1,await Ro(),void Fe()))}if("sim"===o){const e=$o(We.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=k(A(import.meta.url)),o=[v(e,"..","..","panda","mujoco-launcher.py"),v(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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void Fe()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Fe())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=We.currentCard,n=We.bookmarks.includes(e),t="bookmark"!==o;return t?We.bookmarks=We.bookmarks.filter(o=>o!==e):n||We.bookmarks.push(e),Q(We),t?console.log(n?chalk.gray(yo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(yo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(yo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(yo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Fe()}if("e"===o)return Ze=We.currentCard,console.log(chalk.gray(yo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void Fe();if("back"===o||"b"===o)return"view"===oo?(await No(),void Fe()):"honors"===oo?(oo=null,Po(),void Fe()):(We.currentCard>1&&(We.currentCard-=1),ze=null,He=null,Be=null,Q(We),Po(),void Fe());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Co)return console.log(chalk.yellow(yo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Fe();if(!e){const e=await D(Ee),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(yo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(yo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(yo()?` 这台电脑上有 ${o.length} 个你的 token 还没关联:`:` ${o.length} token${1===o.length?"":"s"} of yours on this computer `+(1===o.length?"is":"are")+" not linked yet:"));for(const e of o)console.log(chalk.bold.green(` ${e.index}. `)+chalk.white(e.curriculum_id.padEnd(12))+chalk.gray(e.token)+(e.carry_problems>0?chalk.cyan(yo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(yo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(yo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(yo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(yo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(yo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(yo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Fe()}if(/^\d{1,2}$/.test(e)){const o=await j(Ee,Number(e));return o.ok&&o.data?(Do(o.data),await _o(),void Fe()):(console.log(chalk.red(` ✗ ${o.message||(yo()?"关联失败":"Link failed")}`)),void Fe())}const n=await Y(Ee,e);return n.ok&&n.data?(Do(n.data),await _o(),void Fe()):(console.log(chalk.red(` ✗ ${n.message||(yo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(yo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Fe())}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(!Co)return console.log(chalk.yellow(yo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Fe();const e=To(We.currentCard);if("contest reset"===o){const o=await R(Ee,e);if(o.ok){console.log(chalk.yellow(yo()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let n=1;n<=3;n++){const t=v(process.cwd(),"icoa-contest",`${Se.id}-phase${e}-g${n}`);if(d(t))try{m(t,`${t}-archived-${o}`),console.log(chalk.gray(yo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(yo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(yo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),vo=null,eo=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Fe()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(yo()?" 连接判分赛…":" Contacting contest server…"));const t=await N(Ee,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(yo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void Fe();const r=t.data,l=v(process.cwd(),"icoa-contest",`${Se.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=vo&&vo.phase===e&&vo.data.slot===r.slot?vo.tried:new Set;vo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.samples??[])[0];l&&p(v(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=v(o,`sol-${r}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${n.title} ══`,"#",...jo(n.statement,72)];if(n.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.out.split("\n"))a.push(`# ${e}`)}a.push("#","# ── vi quick guide ── (/edit opens this file in vi)","# i = insert mode — start typing","# Esc = back to command mode","# :wq or ZZ = save & quit · :q! = quit WITHOUT saving","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),p(s,a.join("\n"))})})(r,l),eo=!0,Uo(),console.log(chalk.gray(yo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(yo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(yo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Fe()}if("submit"===s)return console.log(chalk.yellow(yo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(yo()?" 例如 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)")),vo||console.log(chalk.gray(yo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Fe();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const n=e[2];if(!vo)return console.log(chalk.yellow(yo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Fe();const t=vo.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=t.length&&!t.some(e=>e.id===o)&&(o=t[r-1].id),!t.some(e=>e.id===o))return console.log(chalk.yellow(yo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Fe();const l=t.findIndex(e=>e.id===o)+1,a=n||v(vo.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(yo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Fe()}console.log(chalk.gray(yo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Ao.get(l),d=await O(Ee,vo.phase,o,i,void 0,c&&!w(c)?c:void 0);if(!d.ok||!d.data)return"no_active_session"===d.code?console.log(chalk.yellow(yo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((yo()," "))+chalk.bold.green("contest")+chalk.gray(yo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void Fe();const g=d.data;if(g.already_ac)console.log(chalk.green(yo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(yo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(yo()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),vo.data.solved.includes(o)||vo.data.solved.push(o),vo.tried.delete(o);else{vo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?yo()?` · 挂在第 ${g.test} 个用例(过 ${g.passed_tests}/${g.total_tests})`:` · failed test ${g.test} (passed ${g.passed_tests}/${g.total_tests})`:""))}g.late&&console.log(chalk.yellow(yo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=F(g.deadline||"");if(console.log(chalk.white(yo()?` 本组进度: 已过 ${g.ac_count} 题 · 过 ${g.need} 题过关(共 ${g.n} 题)`:` Group progress: ${g.ac_count} solved · ${g.need} needed to pass (${g.n} problems)`)+(u?chalk.gray(` · ⏱ ${u}`):"")),g.passed&&!g.late)console.log(chalk.bold.green(yo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await _o();else if(!g.late){const e=t.findIndex(e=>!vo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(yo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Oo(t[e])}`))}return void Fe()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Se.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Se.totalCards}. Try: `)+chalk.bold.green("card 1")),void Fe();const t=await xo(n);return t?(console.log(t),void Fe()):(We.currentCard=n,ze=null,He=null,Be=null,Q(We),Po(),void Fe())}if(null!==Be&&["y","yes","n","no"].includes(o)){const e=$o(Be);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-uo;G(We,e.number),oe(We,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),Q(We);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),ho.push(T(Ee,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),Be=null,e.solution&&e.solution.length>0)return void Fe();if(We.currentCard<Se.totalCards){const e=We.currentCard,o=await xo(e+1);if(o)return await Eo(e),console.log(o),void Fe();We.currentCard+=1,Q(We),await Eo(e)?So():Po(),Fe()}else pe(Se,We),Fe();return}}if(null!==ze&&["a","b","c","d"].includes(o)){const e=$o(ze);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(ee(We,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),G(We,e.number),Q(We),ae(e,n,t,We),ho.push(T(Ee,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),ze=null,t)if(We.currentCard<Se.totalCards){const e=await xo(We.currentCard+1);if(e)return console.log(e),void Fe();We.currentCard+=1,Q(We),Po()}else pe(Se,We),Fe();else Fe();return}}if(null!==He){if("done"===o){const e=$o(He);if(e&&"practical"===e.type)return ne(We,e.number),G(We,e.number),Q(We),ce(e),He=null,void Fe()}if("skip"===o)return G(We,He),Q(We),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),He=null,void Fe()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ze)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Fe();if(null!==He)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Fe();if(null!==Be)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Fe();const e=We.currentCard,o=e<Se.totalCards?await xo(e+1):null;return o?(await Eo(e),console.log(o),void Fe()):(We.currentCard+=1,Q(We),We.currentCard>Se.totalCards?pe(Se,We):await Eo(e)?So():Po(),void Fe())}if(null!==Be)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Fe();if(null!==ze)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Fe();if(null!==He)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Fe();"view"===oo?console.log(chalk.gray(yo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(yo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(yo()?" 回卡片":" to the card")):"honors"===oo?console.log(chalk.gray(yo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(yo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(yo()?" 回卡片":" 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")),Fe()}else{if("view"===oo)return await No(),void Fe();if("honors"===oo)return oo=null,Po(),void Fe();if(ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${We.streakDays} day(s)`)),console.log(),Oe){De.removeAllListeners("line"),Ue();for(const e of je)De.on("line",e);De.prompt(),bo()}else De.removeAllListeners("line"),De.close()}else if(ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,3e3))]),De.removeAllListeners("line"),Ue(),Oe||!wo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Oe?De:void 0),bo()}else De.close()};De.on("line",e=>{Qo(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.")),Fe()})}),Oe||De.on("close",async()=>{ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,5e3))]),wo?bo():process.exit(0)});try{Po(),Fe();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Te("Could not render this card — the curriculum may be malformed."),Oe){De.removeAllListeners("line"),Ue();for(const e of je)De.on("line",e);De.prompt()}else De.close();bo()}await fo}),xe.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await C(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
|
1
|
+
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as n,execSync as t,spawn as r}from"node:child_process";import{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,statSync as h,writeFileSync as p}from"node:fs";import{emptyDynamics as f,foldEditSession as b,isEmpty as w,noteRun as $}from"../lib/arena-edit-dynamics.js";import{dirname as k,join as v}from"node:path";import{fileURLToPath as A}from"node:url";import{loadCurriculumById as C,validateEAToken as _,syncProgress as T,syncCardFeedback as I}from"../lib/learn-curricula.js";import{normalizeTokenBody as x}from"../lib/token-format.js";import{fetchMyScores as E,recallCoach as S,setNickname as P,streamLearnTutor as M,submitPqs as L,viewPqsTop as q,viewHonors as W}from"../lib/learn-ai.js";import{contestReset as R,contestStart as N,contestSubmit as O,linkByIndex as j,linkSuggest as D,linkToken as Y,fetchGate as U,timeLeft as F}from"../lib/learn-contest.js";import{getConfig as z,saveConfig as H}from"../lib/config.js";import{isNativeWindows as B,isWindowsBuildInWslShell as Z,whichBinary as J}from"../lib/platform.js";import{loadLearnState as K,saveLearnState as Q,newLearnState as V,updateStreak as X,markCardComplete as G,recordMCQ as ee,recordCheck as oe,markPracticalComplete as ne,addAchievement as te}from"../lib/learn-state.js";import{renderWelcome as re,renderKnowledgeCard as le,renderMCQCard as se,renderMCQFeedback as ae,renderPracticalCard as ie,renderPracticalSuccess as ce,renderSimDemoCard as de,renderMilestone as ge,renderArenaTaskCard as ue,renderComingSoonCard as ye,renderStatus as me,renderPhaseComplete as he,renderCurriculumComplete as pe,setLearnAiEnabled as fe,setLearnHonorRanks as be,setLearnPqsViewCards as we,setLearnWidth as $e,resolveLearnWidth as ke,learnWidthCap as ve,learnW as Ae,renderHonorWall as Ce,wrapMixed as _e}from"../lib/learn-render.js";import{printError as Te}from"../lib/ui.js";const Ie=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(xe){xe.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async xe=>{xe?.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(),xe="LEARNDEMO01");let Ee=xe.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Ee)){const{runSprint:e}=await import("./sprint.js");return void await e()}let Se=null;const Pe=/^[A-Z0-9]+DEMO01$/i.test(Ee),Me=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ee);let Le=!1,qe=!1;if(Pe)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Se=await C(Ee,Ee,!0);else if(Me){console.log(),console.log(chalk.gray(" Validating token..."));let e=await _(Ee);if(!e.ok){const o=x(Ee);if(o!==Ee){const n=await _(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Ee} → ${o}`)),e=n,Ee=o)}}if(!e.ok)return Te(`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 🐼"):"")),Le=!0===e.aiEnabled,qe=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Se=await C(e.curriculumId||"LEARNDEMO01",Ee,!0),!Se)return Te(`Could not open a learn curriculum for token '${Ee}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Ee}`)+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 ${Ee}`)+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(!Se){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Te(`Could not reach the learn server to open ${Ee}.`),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 ${Ee}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Te(`Unknown learn token: ${Ee}`),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 We=K(),Re=!1;try{We&&We.token===Ee?X(We):(We=V(Ee,Se.id,Se.totalCards),Re=!0),Q(We),re(Se,We,Re)}catch{return Te("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 ${Ee}`)+chalk.gray(".")),void console.log()}const Ne=s(),Oe=null!==Ne,je=Oe?Ne.listeners("line").slice():[];Oe&&Ne.removeAllListeners("line");const De=Oe?Ne:o({input:process.stdin,output:process.stdout,terminal:!0}),Ye=Oe?De.prompt:null;Oe&&(De.prompt=e.prototype.prompt);const Ue=()=>{Oe&&Ye&&(De.prompt=Ye)},Fe=()=>{De.setPrompt(lo?chalk.bold.green(`icoa ${a()}> `):eo?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Xe?"icoa learn ai> ":"icoa learn> ")),De.prompt()};let ze=null,He=null,Be=null,Ze=null,Je=[],Ke=!1,Qe=null;const Ve=()=>{Qe&&clearTimeout(Qe),Qe=null,Je=[],Ke=!1,Ze=null};let Xe=!1,Ge=!1,eo=!1,oo=null,no=!1,to=0,ro=!1,lo=!1;const so=new Map,ao=()=>{let e=so.get(We.currentCard);return e||(e=[],so.set(We.currentCard,e)),e};let io=!1;const co=new Set;let go=!1,uo=0;const yo=()=>(z().language||"en").toLowerCase().startsWith("zh");fe(Le),$e(ke(z())),we(co);const mo=new Map;be(mo);const ho=[];let po=null;const fo=new Promise(e=>{po=e}),bo=()=>{const e=po;po=null,e?.()},wo="1"===process.env.ICOA_LEARN_EMBEDDED,$o=e=>Se.cards.find(o=>o.number===e);let ko=null,vo=null;const Ao=new Map,Co=!Ee.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Ee),_o=async()=>{if(!Co)return;const e=await U(Ee);e.ok&&e.data&&(ko=e.data)},To=e=>{const o=Se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Io=e=>{if(!qe||!ko)return null;const o=To(e);if(o<=ko.unlocked_through_phase)return null;const n=ko.phases.find(e=>e.phase===ko.unlocked_through_phase),t=[chalk.yellow(yo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${ko.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${ko.unlocked_through_phase}'s core tasks first:`)];if(n?.contest&&!n.contest.passed){const e=n.contest.slots??[];if(e.length>0)for(const o of e)o.passed||t.push(chalk.gray(yo()?` ⚔ 练习赛 ${ko.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${ko.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else t.push(chalk.gray(yo()?` ⚖ 判分赛: 最好 ${n.contest.best_ac}/${n.contest.n} AC,需 ${n.contest.need} — 输入 `:` ⚖ contest: best ${n.contest.best_ac}/${n.contest.n} AC, need ${n.contest.need} — type `)+chalk.bold.green("contest"))}if(n?.checks?.enabled&&!n.checks.passed){const e=n.checks.missing??[],o=e.slice(0,8).join(yo()?"、":", "),r=e.length>8?yo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:yo()?" 张":"";t.push(chalk.gray(yo()?` ✓ 逐卡自测: ${n.checks.good}/${n.checks.need} 答对 — 还差第 ${o}${r},回去重答即可: `:` ✓ card checks: ${n.checks.good}/${n.checks.need} correct — still to fix: ${o}${r}, just answer them again: `)+chalk.bold.green(`card ${e[0]??1}`))}return n?.research&&!n.research.passed&&t.push(chalk.gray(yo()?` ⭐ 提问研究: ${n.research.good_cards}/${n.research.need_cards} 卡达到 ${n.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${n.research.good_cards}/${n.research.need_cards} cards at ${n.research.min_score}+ — research with /ai, then /submit`)),t.join("\n")},xo=async e=>qe?null===Io(e)?null:(await _o(),Io(e)):null;Co&&await _o();const Eo=async e=>{const o=Se.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Se.modules.find(e=>e.number===o.number+1);let t;if(Le){const e=await E({token:Ee,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}Co&&await _o();const r=ko?.phases.find(e=>e.phase===o.number);return he(Se,We,o,n,t,r),!0},So=()=>{go=!0,console.log(chalk.gray(yo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Po=()=>{oo=null;const e=$o(We.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":le(e,Se),e.check?(Be=e.number,uo=Date.now()):(G(We,e.number),Q(We));break;case"mcq":se(e,Se),ze=e.number;break;case"practical":ie(e,Se),He=e.number;break;case"sim_demo":de(e,Se),G(We,e.number),Q(We);break;case"milestone":ge(e,Se),te(We,e.badge),G(We,e.number),Q(We);break;case"arena_task":ue(e,Se),G(We,e.number),Q(We);break;case"coming_soon":ye(e,Se),G(We,e.number),Q(We)}Mo(e.number)},Mo=e=>{if(!Co||!ko)return;const o=Se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const n=e-o.cardRange[0]+1;if(n%4!=0)return;const t=n/4,r=ko.phases.find(e=>e.phase===o.number),l=r?.contest?.slots?.find(e=>e.slot===t);if(!l)return;const s=(e,o,n,t)=>{const r=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${o}:${String(n).padStart(2,"0")}`})(n),s=(e=>{const o=e?new Date(e):null;if(!o||Number.isNaN(o.getTime()))return"";const n=e=>String(e).padStart(2,"0");return`${o.getFullYear()}-${n(o.getMonth()+1)}-${n(o.getDate())} ${n(o.getHours())}:${n(o.getMinutes())}`})(t);return`🏆 ${e} ${o}/${l.n}`+(r?yo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Ae());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${yo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(yo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(yo()?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(yo()?`${l.n} 题 · AC ${l.need} 过关 · 限时 ${l.duration_minutes} 分钟 · 无限重开`:`${l.n} problems · AC ${l.need} to pass · ${l.duration_minutes} min · unlimited retries`)),(l.carryable_ac??0)>0&&console.log(c+chalk.cyan(yo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(yo()?"✍ 第一次用 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(yo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(yo()?"最好":"Best",l.best.ac??0,l.best.ms,l.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${t}`)+(l.passed?chalk.gray(yo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(yo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(yo()?" 继续学习":" keep going"):chalk.gray(yo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Lo=()=>{Ee.endsWith("DEMO01")?console.log(chalk.yellow(yo()?" 🐼 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(yo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(yo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},qo=async(e,o)=>{if(Le){Ge=!0;try{console.log(),console.log(chalk.gray("deep"===o?yo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":yo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await M({token:Ee,cardNumber:We.currentCard,question:e,mode:o,history:ao().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(t||(process.stdout.write(n?"\n\n ":" "),t=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||t)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(yo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(ao().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(` (${yo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(yo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Be&&console.log(chalk.gray(yo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ge=!1}}else Lo()},Wo=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ro=async()=>{eo&&vo?Ho?Bo(Ho):Uo():oo?await No():Po()},No=async()=>{Ge=!0;try{console.log();const e=await W({token:Ee,curriculumId:Se.id,cardNumber:We.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(yo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(yo()?` 🏆 本卡实时 Top-3 — 第 ${We.currentCard} 张`:` 🏆 Live top-3 — card ${We.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(yo()?" (你)":" (you)"):""))}else console.log(chalk.gray(yo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(mo.set(We.currentCard,e.mine.rank),console.log(chalk.white(yo()?" 你: ":" You: ")+chalk.bold.yellow(yo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(yo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Le&&console.log(chalk.gray(yo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),Ce({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(yo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(yo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(yo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),oo="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 返回卡片":" returns to the card")),console.log()}finally{Ge=!1}},Oo=e=>yo()&&e.title_zh||e.title,jo=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of _e(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},Do=e=>{console.log(),console.log(chalk.bold.green(yo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 Linked — credit now carries both ways"));for(const o of e.members)console.log(chalk.gray(" · ")+chalk.white(o.curriculum_id)+chalk.gray(` ${o.token}`));console.log(chalk.gray(yo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},Yo=e=>vo.data.solved.includes(e.id)?"✅":vo.data.carried?.includes(e.id)?"✅↗":vo.tried.has(e.id)?"❌":"⬜",Uo=()=>{const e=vo.data,o=F(e.deadline),n=(e.carried??[]).filter(o=>!e.solved.includes(o)),t=e.solved.length+n.length,r=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(yo()?` · 第 ${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(yo()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(r))+chalk.gray("░".repeat(20-r))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(yo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(yo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(yo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(yo()?" 带过来,不必重做":" to carry them over instead of redoing them"));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(yo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(yo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(yo()?` 满血重开本组(${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)} `)+Yo(e)+chalk.white(` ${Oo(e)}`))}),console.log(),Fo()},Fo=()=>{console.log(chalk.gray(yo()?" /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(yo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 返回课程":" returns to the lesson")),console.log()},zo=e=>{const o=parseInt(e,10),n=vo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(yo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let Ho=null;const Bo=e=>{const o=zo(e);if(!o)return;const{p:n,n:t}=o;Ho=String(t),console.log(),console.log(chalk.bold.white(` ${Yo(n)} ${Oo(n)}`)),console.log();for(const e of(e=>yo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of _e(e,Ae()+2))console.log(chalk.white(` ${o}`));else console.log();let r=0;for(const e of n.samples??[]){r+=1,console.log(),console.log(chalk.gray(yo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(yo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(n.samples??[]).length&&(console.log(),console.log(chalk.gray(yo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(yo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(yo()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${t}`.padEnd(11))+chalk.gray(yo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(yo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(yo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((yo()," ↩ "))+chalk.bold.green("back")+chalk.gray(yo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(yo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((yo()," / "))+chalk.bold.green("wide")+chalk.gray(yo()?" 换语言/宽度":" language / width")),console.log()},Zo=async(e,o)=>await new Promise(n=>{const t=process.stdin,l=!!t.isTTY&&!!t.isRaw;if(De.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e,o,{stdio:"inherit",cwd:vo.dir}),a=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&l)try{t.setRawMode(!0)}catch{}De.resume(),n(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Jo=()=>{console.log(chalk.yellow(yo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(yo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(yo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(yo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Ko=new Map,Qo=async e=>{const o=e.trim().toLowerCase(),s=eo&&o.startsWith("/")?o.slice(1):o;if(Ge)return;if(null!==Ze){if(Je.push(e.replace(/\s+$/,"")),Qe&&clearTimeout(Qe),Qe=null,Ke){const e=Je[Je.length-1]??"";return"/cancel"===e.trim()?(Ve(),console.log(chalk.gray(yo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void Fe()):""!==e.trim()?void Fe():(Je.pop(),void await a())}return void(Qe=setTimeout(()=>{if(Qe=null,Je.length>1){Ke=!0;const e=Je.length;return console.log(chalk.cyan(yo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(yo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void Fe()}a()},140))}async function a(){const e=Je.join("\n").replace(/^\s+|\s+$/g,""),o=Ze??We.currentCard,n=Je.length;if(Ve(),""===e)console.log(chalk.gray(yo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(yo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(yo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(yo()?" 即可执行。":" again to run it."));else{const t=uo>0?Date.now()-uo:void 0;if(await I(Ee,{curriculum_id:Se.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const e=n>1?yo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(yo()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(yo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),Fe()}if(no){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return no=!1,console.log(),console.log(chalk.yellow(yo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(yo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(yo()?" 即可执行该命令。":" again to run it.")),console.log(),void Fe();if(!o)return no=!1,console.log(chalk.gray(yo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void Fe();const n=await P({token:Ee,nickname:o});if(n.ok)no=!1,console.log(chalk.bold.green(yo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(yo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{to+=1;const e="taken"===n.code?yo()?"已被占用":"already taken":"bad_charset"===n.code?yo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?yo()?"未通过审核":"did not pass review":n.message||"error";if(!(to>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void Fe();no=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(yo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void Fe()}if(io){io=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ge=!0;try{console.log(),console.log(chalk.gray(yo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await L({token:Ee,cardNumber:We.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(yo()?"评审暂不可用。":"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(yo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(yo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(yo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(yo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(yo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(yo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=yo()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(yo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(yo()?` 第 ${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 Wo(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(yo()?" 改进提问: ":" 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(` (${yo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?co.add(We.currentCard):co.delete(We.currentCard),"number"==typeof e.rank&&mo.set(We.currentCard,e.rank);const o=await W({token:Ee,curriculumId:Se.id,cardNumber:We.currentCard});o.ok&&o.totals&&o.chapters&&(Ce({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Pe&&(no=!0,to=0,console.log(chalk.bold.yellow(yo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(yo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(yo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Ge=!1}})():(console.log(chalk.gray(yo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Be&&(console.log(chalk.gray(yo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void Fe()}if(go)return go=!1,Po(),void Fe();if(!o)return void Fe();if(lo)return"exit"===await i(e.trim())&&(lo=!1),void Fe();if(Xe){if(["q","quit","exit","back","b","menu"].includes(o))return Xe=!1,console.log(chalk.gray(yo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void Fe();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim();return t&&(await qo(t,n?"fast":"deep"),console.log(chalk.gray(yo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void Fe()}if(eo&&vo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&l(`learn-arena p${vo.phase}s${vo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return eo=!1,console.log(chalk.gray(yo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Po(),void Fe();if(/^\d+$/.test(o))return Bo(o),void Fe();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,t]=e;return"list"===o?Uo():t?"read"===o||"open"===o?Bo(t):"edit"===o?await(async e=>{const o=zo(e);if(!o)return;const n=v(vo.dir,`sol-${o.n}.py`);if(B())return Z()?(console.log(chalk.yellow(yo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(yo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(yo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(yo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(yo()?" ← 不能是 /mnt/c":" not /mnt/c")),console.log(chalk.bold.cyan(" sudo npm install -g icoa-cli")),console.log(chalk.bold.cyan(" hash -r")+chalk.gray(yo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(yo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(yo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(yo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(yo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(yo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(yo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(yo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!J("vi"))return console.log(chalk.yellow(yo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(yo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(yo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return h(e).size}catch{return 0}},r=t(n),l=Date.now();await Zo("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),Ao.set(o.n,b(Ao.get(o.n)??f(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(yo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(yo()?" 自测样例。":" to self-check the sample.")),console.log()})(t):"run"===o?(e=>{const o=zo(e);if(!o)return;const{p:t,n:r}=o,l=v(vo.dir,`sol-${r}.py`);if(!d(l))return void console.log(chalk.yellow(yo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Ao.set(r,$(Ao.get(r)??f()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(yo()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=n("python3",[l],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if("ENOENT"===o.code)Jo();else if(o.killed)console.log(chalk.yellow(yo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(yo()?" ✗ 程序报错:":" ✗ 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(yo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(yo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(yo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(yo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(yo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(yo()?" 改完再 /run。":" then /run again.")),console.log()})(t):"debug"===o?await(async e=>{const o=zo(e);if(!o)return;const n=v(vo.dir,`sol-${o.n}.py`);if(!d(n))return void console.log(chalk.yellow(yo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(yo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const t=await Zo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(yo()?" 回到竞技场。":" Back in the arena.")),console.log()):Jo()})(t):"recall"===o&&await(async e=>{const o=zo(e);if(!o)return;if(!Le)return void Lo();const{p:n,n:t}=o,r=v(process.cwd(),"icoa-contest"),l=`${Se.id}-phase${vo.phase}-g${vo.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?v(r,s,`sol-${t}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(yo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${vo.phase}-${vo.data.slot}-${t}`,g=Math.min(3,(Ko.get(c)??0)+1);console.log(chalk.gray(yo()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await S({token:Ee,phase:vo.phase,slot:vo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:g,lang:yo()?"zh":"en"});if(m.ok){Ko.set(c,g),console.log();for(const e of _e(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(yo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(yo()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(yo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(t):console.log(chalk.yellow(yo()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(yo()?" (花名册: /list)":" (roster: /list)")),void Fe()}if("contest"===o||"/contest"===o)return Uo(),void Fe();const t="lang"===o||/^lang\s+\S+$/.test(o),r=Ie.has(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||t||r||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(yo()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void Fe()}if("tmux"===o||o.startsWith("tmux ")){try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(yo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void Fe()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(De.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&t)try{n.setRawMode(!0)}catch{}De.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void Fe()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(lo=!0),void Fe();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Le)return Lo(),void Fe();ro||(ro=!0,console.log(),console.log(chalk.bold.cyan(yo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(yo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(yo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),yo()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const n=o.startsWith("/ai!"),t=e.trim().slice(n?4:3).trim();if(!t){Xe=!0;const e=$o(We.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(yo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(yo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void Fe()}return await qo(t,n?"fast":"deep"),void Fe()}if(!eo&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Le)return Lo(),void Fe();const e=$o(We.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(yo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(yo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(yo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(yo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(yo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(yo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(yo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),io=!0,void Fe()}const _=!eo&&"honors"===oo&&/^[1-3]$/.test(o);if(!eo&&oo&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(yo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(yo()?" ↩ back 回上一层":" ↩ back goes up one level")),void Fe();if(!eo&&(_||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Le)return Lo(),void Fe();const e=/^\/?view ([1-3])$/.exec(o),n=_?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Ge=!0;try{console.log();const o=await q({token:Ee,cardNumber:We.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(yo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&co.delete(We.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&co.add(We.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(yo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${We.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${We.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(yo()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of n){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(yo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=Wo(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(yo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),oo="view",console.log(chalk.gray((yo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(yo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Ge=!1}})(n),void Fe()}if("/honors"===o||"honors"===o)return Pe?(console.log(),console.log(chalk.gray(yo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void Fe()):(await No(),void Fe());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return me(Se,We),void Fe();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await C(Se.id,Ee,!0);return void(e?(Object.assign(Se,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Po()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本")),Fe()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(z().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void Fe();const n=Se.cards.some(e=>null!=e._zh),t=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===t||"zh"===t&&n,l=r?t:"en";return H({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Be=null,ze=null,He=null,Ve(),go=!1,io=!1,await Ro(),void Fe()}if(Ie.has(o)){const e=Ie.get(o),n=ke(z()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return yo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((yo()?"normal"===e?" 已是标准 64 列。":Ae()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Ae()} 列,上限 ${ve(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Ae()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Ae()} cols, cap ${ve(e)}). `)+t(e))),void Fe()):(H({learnWidth:e,learnWide:"normal"!==e}),$e(e),"normal"!==e&&Ae()<=64?(console.log(chalk.yellow(yo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((yo()?` 设置已记住(${e},上限 ${ve(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${ve(e)} cols) and applies once you widen the window. `)+t(e))),void Fe()):(console.log(chalk.green(" ✓ ")+chalk.gray((yo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Ae()} 列,上限 ${ve(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Ae()} cols, cap ${ve(e)}). `)+t(e))),Be=null,ze=null,He=null,Ve(),go=!1,io=!1,await Ro(),void Fe()))}if("sim"===o){const e=$o(We.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=k(A(import.meta.url)),o=[v(e,"..","..","panda","mujoco-launcher.py"),v(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 n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void Fe()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void Fe())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=We.currentCard,n=We.bookmarks.includes(e),t="bookmark"!==o;return t?We.bookmarks=We.bookmarks.filter(o=>o!==e):n||We.bookmarks.push(e),Q(We),t?console.log(n?chalk.gray(yo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(yo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(yo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(yo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void Fe()}if("e"===o)return Ze=We.currentCard,console.log(chalk.gray(yo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void Fe();if("back"===o||"b"===o)return"view"===oo?(await No(),void Fe()):"honors"===oo?(oo=null,Po(),void Fe()):(We.currentCard>1&&(We.currentCard-=1),ze=null,He=null,Be=null,Q(We),Po(),void Fe());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!Co)return console.log(chalk.yellow(yo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void Fe();if(!e){const e=await D(Ee),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(yo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(yo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(yo()?` 这台电脑上有 ${o.length} 个你的 token 还没关联:`:` ${o.length} token${1===o.length?"":"s"} of yours on this computer `+(1===o.length?"is":"are")+" not linked yet:"));for(const e of o)console.log(chalk.bold.green(` ${e.index}. `)+chalk.white(e.curriculum_id.padEnd(12))+chalk.gray(e.token)+(e.carry_problems>0?chalk.cyan(yo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(yo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(yo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(yo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(yo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(yo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(yo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void Fe()}if(/^\d{1,2}$/.test(e)){const o=await j(Ee,Number(e));return o.ok&&o.data?(Do(o.data),await _o(),void Fe()):(console.log(chalk.red(` ✗ ${o.message||(yo()?"关联失败":"Link failed")}`)),void Fe())}const n=await Y(Ee,e);return n.ok&&n.data?(Do(n.data),await _o(),void Fe()):(console.log(chalk.red(` ✗ ${n.message||(yo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(yo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void Fe())}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(!Co)return console.log(chalk.yellow(yo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void Fe();const e=To(We.currentCard);if("contest reset"===o){const o=await R(Ee,e);if(o.ok){console.log(chalk.yellow(yo()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let n=1;n<=3;n++){const t=v(process.cwd(),"icoa-contest",`${Se.id}-phase${e}-g${n}`);if(d(t))try{m(t,`${t}-archived-${o}`),console.log(chalk.gray(yo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(yo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(yo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),vo=null,eo=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void Fe()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(yo()?" 连接判分赛…":" Contacting contest server…"));const t=await N(Ee,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(yo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void Fe();const r=t.data,l=v(process.cwd(),"icoa-contest",`${Se.id}-phase${e}-g${r.slot}`);g(l,{recursive:!0});const s=vo&&vo.phase===e&&vo.data.slot===r.slot?vo.tried:new Set;vo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.samples??[])[0];l&&p(v(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=v(o,`sol-${r}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${n.title} ══`,"#",...jo(n.statement,72)];if(n.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${r} for the Chinese statement.`),l){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of l.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of l.out.split("\n"))a.push(`# ${e}`)}a.push("#","# ── vi quick guide ── (/edit opens this file in vi)","# i = insert mode — start typing","# Esc = back to command mode","# :wq or ZZ = save & quit · :q! = quit WITHOUT saving","#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),p(s,a.join("\n"))})})(r,l),eo=!0,Uo(),console.log(chalk.gray(yo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(yo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(yo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void Fe()}if("submit"===s)return console.log(chalk.yellow(yo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(yo()?" 例如 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)")),vo||console.log(chalk.gray(yo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void Fe();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const n=e[2];if(!vo)return console.log(chalk.yellow(yo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void Fe();const t=vo.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=t.length&&!t.some(e=>e.id===o)&&(o=t[r-1].id),!t.some(e=>e.id===o))return console.log(chalk.yellow(yo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void Fe();const l=t.findIndex(e=>e.id===o)+1,a=n||v(vo.dir,`sol-${l}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(yo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void Fe()}console.log(chalk.gray(yo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Ao.get(l),d=await O(Ee,vo.phase,o,i,void 0,c&&!w(c)?c:void 0);if(!d.ok||!d.data)return"no_active_session"===d.code?console.log(chalk.yellow(yo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((yo()," "))+chalk.bold.green("contest")+chalk.gray(yo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(yo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void Fe();const g=d.data;if(g.already_ac)console.log(chalk.green(yo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(yo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(yo()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),vo.data.solved.includes(o)||vo.data.solved.push(o),vo.tried.delete(o);else{vo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?yo()?` · 挂在第 ${g.test} 个用例(过 ${g.passed_tests}/${g.total_tests})`:` · failed test ${g.test} (passed ${g.passed_tests}/${g.total_tests})`:""))}g.late&&console.log(chalk.yellow(yo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=F(g.deadline||"");if(console.log(chalk.white(yo()?` 本组进度: 已过 ${g.ac_count} 题 · 过 ${g.need} 题过关(共 ${g.n} 题)`:` Group progress: ${g.ac_count} solved · ${g.need} needed to pass (${g.n} problems)`)+(u?chalk.gray(` · ⏱ ${u}`):"")),g.passed&&!g.late)console.log(chalk.bold.green(yo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await _o();else if(!g.late){const e=t.findIndex(e=>!vo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(yo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${Oo(t[e])}`))}return void Fe()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>Se.totalCards)return console.log(chalk.yellow(` Card number must be 1..${Se.totalCards}. Try: `)+chalk.bold.green("card 1")),void Fe();const t=await xo(n);return t?(console.log(t),void Fe()):(We.currentCard=n,ze=null,He=null,Be=null,Q(We),Po(),void Fe())}if(null!==Be&&["y","yes","n","no"].includes(o)){const e=$o(Be);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-uo;G(We,e.number),oe(We,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),Q(We);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),ho.push(T(Ee,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),Be=null,e.solution&&e.solution.length>0)return void Fe();if(We.currentCard<Se.totalCards){const e=We.currentCard,o=await xo(e+1);if(o)return await Eo(e),console.log(o),void Fe();We.currentCard+=1,Q(We),await Eo(e)?So():Po(),Fe()}else pe(Se,We),Fe();return}}if(null!==ze&&["a","b","c","d"].includes(o)){const e=$o(ze);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(ee(We,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),G(We,e.number),Q(We),ae(e,n,t,We),ho.push(T(Ee,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),ze=null,t)if(We.currentCard<Se.totalCards){const e=await xo(We.currentCard+1);if(e)return console.log(e),void Fe();We.currentCard+=1,Q(We),Po()}else pe(Se,We),Fe();else Fe();return}}if(null!==He){if("done"===o){const e=$o(He);if(e&&"practical"===e.type)return ne(We,e.number),G(We,e.number),Q(We),ce(e),He=null,void Fe()}if("skip"===o)return G(We,He),Q(We),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),He=null,void Fe()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ze)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Fe();if(null!==He)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Fe();if(null!==Be)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Fe();const e=We.currentCard,o=e<Se.totalCards?await xo(e+1):null;return o?(await Eo(e),console.log(o),void Fe()):(We.currentCard+=1,Q(We),We.currentCard>Se.totalCards?pe(Se,We):await Eo(e)?So():Po(),void Fe())}if(null!==Be)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void Fe();if(null!==ze)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void Fe();if(null!==He)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void Fe();"view"===oo?console.log(chalk.gray(yo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(yo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(yo()?" 回卡片":" to the card")):"honors"===oo?console.log(chalk.gray(yo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(yo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(yo()?" 回卡片":" 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")),Fe()}else{if("view"===oo)return await No(),void Fe();if("honors"===oo)return oo=null,Po(),void Fe();if(ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${We.streakDays} day(s)`)),console.log(),Oe){De.removeAllListeners("line"),Ue();for(const e of je)De.on("line",e);De.prompt(),bo()}else De.removeAllListeners("line"),De.close()}else if(ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,3e3))]),De.removeAllListeners("line"),Ue(),Oe||!wo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Oe?De:void 0),bo()}else De.close()};De.on("line",e=>{Qo(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.")),Fe()})}),Oe||De.on("close",async()=>{ho.length>0&&await Promise.race([Promise.allSettled(ho),new Promise(e=>setTimeout(e,5e3))]),wo?bo():process.exit(0)});try{Po(),Fe();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Te("Could not render this card — the curriculum may be malformed."),Oe){De.removeAllListeners("line"),Ue();for(const e of je)De.on("line",e);De.prompt()}else De.close();bo()}await fo}),xe.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await C(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
package/dist/commands/sim.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{
|
|
1
|
+
import chalk from"chalk";import{copyFileSync as o,existsSync as e,mkdirSync as n,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{dirname as t,join as l,resolve as s}from"node:path";import{createInterface as i}from"node:readline";import{fileURLToPath as c}from"node:url";import{fetchWithCountdown as m}from"../lib/countdown.js";const g=l(a(),".icoa","cache","sim");import{getMainRl as d}from"../lib/main-rl.js";import{COOLDOWN_SECONDS as p,lastSimAt as u,markArmAt as y,markBundledAt as f,markSimAt as b}from"../lib/sim-cooldown.js";import{httpFetch as h}from"../lib/http.js";import{openMedia as w}from"../lib/open-file.js";const v={baseline:{action:null,label:"Baseline — robot doing its job",hint:"Approach → grasp → lift → place → return. This is what normal looks like.",frames:90,narrative:!0},release:{action:{xyz:[.1,0,.3],rotation:[0,0,0],gripper_close:.05},label:'Prompt Injection — "release the gripper"',hint:"Gripper opens (0.05 < 0.10 win threshold). This is Paper D Q41 success."},patch:{action:{xyz:[-.3,.2,.5],rotation:[.5,0,.3],gripper_close:.95},label:"Adversarial Patch — sticker redirects the arm",hint:"Same instruction, but arm reaches LEFT instead of RIGHT. Paper D Q42 success."},confused:{action:{xyz:[.001,0,.001],rotation:[0,0,0],gripper_close:.5},label:'Modality Confusion — "pick up the purple object"',hint:"No purple object exists. VLA freezes near origin. Paper D Q43 success."},color:{action:{xyz:[.4,-.3,.6],rotation:[-.4,.2,-.1],gripper_close:.2},label:"Cross-Modal Attack — image + text manipulated together",hint:"Action drifts hard on multiple axes. Paper D Q49-class attack (future).",hidden:!0},ensemble:{action:null,label:"Ensemble — 9 robots dancing on one beat",hint:"Pre-rendered group dance. Instant. No cooldown.",bundled:"ensemble-v2.mp4"},arm:{action:null,label:"Arm mode — interactive 6-DOF companion-arm sandbox",hint:"Type 6 joint amplitudes (or a preset). Each render takes ~15s, 60s cooldown.",bundled:void 0}},j=Object.fromEntries(Object.entries(v).filter(([,o])=>!o.hidden));let T=!1;const x={1:{vec:[1,1,1,1,1.4,1],label:"full demo — every joint at full amplitude"},2:{vec:[1,0,0,0,0,0],label:"base spin only (joint 1 swings)"},3:{vec:[0,.8,.8,0,0,0],label:"shoulder + elbow (lift cycle)"},4:{vec:[0,0,0,.8,1.4,1],label:"wrist drill — j4 roll + j5 bend + j6 twist"},5:{vec:[-.7,-.8,.6,.7,-1,.5],label:"mixed asymmetric (chaotic)"}};async function A(o){const e=(Date.now()-u())/1e3;if(e<p){const o=Math.ceil(p-e);return console.log(chalk.yellow(` Please wait ${o}s before the next render.`)),console.log(chalk.gray(" (One render per minute keeps things fast for everyone.)")),!1}const n=`${process.env.ICOA_SERVER_URL?.replace(/\/+$/,"")||"https://practice.icoa2026.au"}/api/ai/vla/41/sim`;o.quietHeader||(console.log(),console.log(chalk.bold.cyan(" ICOA · MuJoCo Sim")),console.log(chalk.gray(" ")+chalk.white(o.label)),console.log());try{const e=fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:o.action,frames:o.frames,narrative:o.narrative,...o.panda2_pose?{panda2_pose:o.panda2_pose}:{}}),signal:AbortSignal.timeout(6e4)}),a=await m(e);if(!a.ok)return console.log(chalk.yellow(` Server returned HTTP ${a.status}.`)),!1;const t=await a.json();if(!t.success||!t.data?.mp4_b64)return console.log(chalk.yellow(" Renderer unavailable.")),!1;const s=process.env.TMPDIR||"/tmp",i=l(s,`icoa-sim-${o.scenarioName}-${Date.now()}.mp4`);return r(i,Buffer.from(t.data.mp4_b64,"base64")),b(Date.now()),console.log(),console.log(chalk.bold.green(" ✓ ")+chalk.gray("Rendered.")),t.data.description&&console.log(chalk.gray(" Action: ")+chalk.white(t.data.description)),console.log(),console.log(chalk.gray(" ")+o.hint),console.log(),w(i,o=>console.log(chalk.gray(o))),console.log(),!0}catch(o){const e=o instanceof Error?o.message:String(o);return console.log(chalk.yellow(` Sim error: ${e}`)),!1}}async function S(a,m=!1){const p=a.toLowerCase();if(T=m,"arm"===p)return void await async function(){console.log(),console.log(chalk.bold.cyan(" ICOA · Companion Arm Sandbox")),console.log(chalk.gray(" Drive the printable 6-DOF arm directly. Server renders, video opens.")),console.log(),console.log(chalk.gray(" Joint amplitudes (radians, suggested range −1.0 to +1.0):")),console.log(chalk.gray(" j1=base spin j2=shoulder j3=elbow")),console.log(chalk.gray(" j4=forearm roll j5=wrist pitch j6=wrist roll")),console.log(),console.log(chalk.gray(" Type 6 numbers separated by spaces, or pick a preset:"));for(const[o,e]of Object.entries(x)){const n=e.vec.map(o=>o.toFixed(1).padStart(4)).join(" ");console.log(chalk.gray(" ")+chalk.bold.cyan(o)+chalk.gray(" → ["+n+"] "+e.label))}console.log(),console.log(chalk.gray(" Each render: ~15s countdown + 60s cooldown between renders.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("q")+chalk.gray(" or ")+chalk.bold.cyan("exit")+chalk.gray(" to leave arm mode.")),console.log();const o=d(),e=null!==o,n=e?o.listeners("line").slice():[];e&&o.removeAllListeners("line");const r=e?o:i({input:process.stdin,output:process.stdout,terminal:!0});return new Promise(o=>{let a=!1;const t=()=>{process.stdout.write(chalk.bold.cyan(" icoa arm> "))},l=async s=>{const i=s.trim();if(a)return;if("q"===i||"exit"===i||"quit"===i||"back"===i||"menu"===i)return console.log(chalk.gray(" Leaving arm mode.")),console.log(),r.removeListener("line",l),(()=>{if(e){r.removeAllListeners("line");for(const o of n)r.on("line",o);r.prompt()}else r.close()})(),void o();if("help"===i||"?"===i)return console.log(chalk.gray(" 6 numbers (e.g. 0.5 0.7 0.5 0.3 0.6 0.3) or preset 1/2/3/4.")),void t();const c=(o=>{const e=o.trim();if(!e)return null;if(x[e])return x[e].vec;const n=e.split(/[\s,]+/).map(o=>Number(o));return 6!==n.length||n.some(o=>!Number.isFinite(o))?null:n.map(o=>Math.max(-1.5,Math.min(1.5,o)))})(i);if(!c)return console.log(chalk.yellow(" Need 6 numbers or a preset (1-4). Try ?")),void t();a=!0;const m=c.map(o=>o.toFixed(2)).join(" ");console.log(chalk.gray(" Sending pose [")+chalk.white(m)+chalk.gray("]")),await A({scenarioName:"arm",label:"Companion arm — your pose",hint:"Rendered from your 6-vector. Try another, or "+chalk.bold.cyan("q")+chalk.gray(" to leave."),action:null,frames:90,narrative:!0,panda2_pose:c,quietHeader:!0})&&y(Date.now()),a=!1,t()};r.on("line",l),t()})}();const u=v[p];if(!u){console.log(),console.log(chalk.yellow(` Unknown scenario: "${a}"`)),console.log(chalk.gray(" Available:"));for(const[o,e]of Object.entries(j))console.log(chalk.gray(" ")+chalk.bold.cyan(o.padEnd(10))+chalk.gray(e.label));return void console.log()}if(u.bundled)return void await async function(a,i){const m=await async function(o){const a=function(o){const n=t(c(import.meta.url));return[s(n,"..","..","assets","sim",o),s(n,"..","..","..","assets","sim",o)].find(o=>e(o))||null}(o);if(a)return a;const i=l(g,o);if(e(i))return i;console.log(),console.log(chalk.white("\n ██╗ ██████╗ ██████╗ █████╗\n ██║██╔════╝██╔═══██╗██╔══██╗\n ██║██║ ██║ ██║███████║\n ██║██║ ██║ ██║██╔══██║\n ██║╚██████╗╚██████╔╝██║ ██║\n ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝\n")),console.log(chalk.gray(" First-time setup — fetching the sim asset (~700 KB) ...")),console.log();try{n(g,{recursive:!0});const e=`https://icoa2026.au/assets/sim/${o}`,a=await h(e);if(!a.ok)return console.log(chalk.yellow(` Download failed (HTTP ${a.status}).`)),console.log(chalk.gray(" Try ")+chalk.bold.cyan("icoa sim baseline")+chalk.gray(" (server-rendered alternative).")),console.log(),null;const t=Buffer.from(await a.arrayBuffer());return r(i,t),console.log(chalk.green(" ✓ Cached — future runs are instant.")),console.log(),i}catch(o){return console.log(chalk.yellow(` Network error: ${o instanceof Error?o.message:String(o)}`)),console.log(chalk.gray(" Try ")+chalk.bold.cyan("icoa sim baseline")+chalk.gray(" instead.")),console.log(),null}}(i.bundled);if(!m)return;const d=process.env.TMPDIR||"/tmp",p=l(d,`icoa-sim-${a}-${Date.now()}.mp4`);if(o(m,p),f(Date.now()),T||(console.log(),console.log(chalk.bold.cyan(" ICOA · MuJoCo Sim")),console.log(chalk.gray(" ")+chalk.white(i.label)),console.log(),console.log(chalk.bold.green(" ✓ ")+chalk.gray("Ready (pre-rendered, instant playback).")),console.log(),console.log(chalk.gray(" ")+i.hint),console.log()),w(p,o=>console.log(chalk.gray(o))),console.log(),T)return;const u="1"===process.env.ICOA_INSIDE_REPL?"":"icoa ";console.log(chalk.gray(" Want to drive the companion arm yourself? ")+chalk.bold.cyan(u+"sim arm")),console.log()}(p,u);if(await A({scenarioName:p,label:u.label,hint:u.hint,quietHeader:T,action:u.action,frames:u.frames,narrative:u.narrative,panda2_pose:u.panda2_pose}),T)return;const b="1"===process.env.ICOA_INSIDE_REPL?"":"icoa ";console.log(chalk.gray(" Try other scenarios:"));for(const o of Object.keys(j))o!==p&&console.log(chalk.gray(" "+b+"sim ")+chalk.cyan(o));console.log()}export function registerSimCommand(o){o.command("sim [scenario]").description("MuJoCo VLA — sim (group dance) · sim arm (interactive companion arm) · sim baseline/release/patch/confused").action(async o=>{await S(o||"ensemble")})}export{v as SCENARIOS};export async function runSimQuiet(o){await S(o,!0)}
|
package/dist/commands/sprint.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as o,mkdirSync as e,readFileSync as n,writeFileSync as t}from"node:fs";import{createInterface as l}from"node:readline";import{dirname as a,join as s}from"node:path";import{fileURLToPath as r}from"node:url";import chalk from"chalk";import{getConfig as c}from"../lib/config.js";import{getMainRl as i,setMainRl as g}from"../lib/main-rl.js";import{logCommand as y}from"../lib/logger.js";import{baselineChip as d,computeChip as p,loadSprintTasks as u,mediaHelpLines as h,taskSteps as m}from"../lib/sprint-meta.js";let f=!1;export function isSprintActive(){return f}const b=a(r(import.meta.url)),w=s(process.env.HOME||".",".icoa"),k=s(w,"sprint-state.json"),$={"T-torch":"裸 torch:手写 attention / causal mask / perplexity","T-umap":"降维当特征提取器,不是画图工具","T-lora":"peft LoRA 参数高效微调","T-librosa":"音频特征流水线:mel / MFCC → 定长向量"},S=["",chalk.bold.cyan(" ASTANA 2027"),chalk.gray(" — 给还没出发的你"),"",chalk.white(" 草原的风从额尔齐斯河吹到阿斯塔纳的时候,会带着一点雪的味道。"),chalk.white(" 你还没去过那里。但那里已经有一个座位,写着你的名字。"),"",chalk.white(" 你现在坐在屏幕前,离比赛还有几天。"),chalk.white(" 你可能会想:几天能改变什么?"),"",chalk.white(" 足够让一个人从「看着题发呆」变成「看到题就知道该拆哪一层」。"),chalk.white(" 足够让手指记住 import torch 之后该敲什么。"),chalk.white(" 足够让你在比赛那天早上醒来时,不再害怕。"),"",chalk.bold.yellow(" M")+chalk.white(" —— 你总是第一个说「我先试试」的那个。别停。"),chalk.bold.yellow(" V")+chalk.white(" —— 你总是问「为什么是这样」的那个。继续问。"),chalk.bold.yellow(" A")+chalk.white(" —— 你总是在别人放弃时还在改最后一版的那个。改下去。"),"",chalk.white(" 你们三个人,一个人是一条腿走路,三个人是奔跑。"),"",chalk.white(" 你们要面对的不是一场考试,是一次证明:"),chalk.bold.white(" 中国的高中生,可以在 AI 的赛场上,和世界站在同一排。"),"",chalk.white(" 而 2027 年的阿斯塔纳,是我们下一个约定。"),"",chalk.gray(" 现在,把这行字关掉,去做第 1 题。"),chalk.gray(" — 熊猫教练"),""];function A(o){try{e(w,{recursive:!0}),t(k,`${JSON.stringify(o,null,1)}\n`)}catch{}}function q(){return(c().language||"en").toLowerCase().startsWith("zh")}function v(o,e){return q()?o:e}function j(o){return"★".repeat(Math.max(1,Math.min(5,o||3)))}const I=s(w,"sprint-memos.json");function C(o){try{e(w,{recursive:!0}),t(I,`${JSON.stringify(o,null,1)}\n`)}catch{}}function N(o,e){const n=new Set(e.done),t=new Set(e.opened);console.log(),console.log(chalk.bold.cyan(v(" ⚔ IOAI 2026 · 四工具冲刺"," ⚔ IOAI 2026 · four-tool sprint"))+chalk.gray(` ${v("已攻克","cleared")} ${n.size} / ${o.length}`));const l=new Map;for(const e of o)l.has(e.bullseye)||l.set(e.bullseye,[]),l.get(e.bullseye)?.push(e);for(const[o,e]of l){console.log(),console.log(chalk.bold.white(` ${o}`)+chalk.gray(` — ${$[o]||""}`));for(const o of e){const e=n.has(o.seq)?chalk.green("✓"):t.has(o.seq)?chalk.yellow("◐"):chalk.gray("⬜");console.log(` ${e} ${chalk.bold.white(String(o.seq).padStart(2))} `+chalk.white(o.title.slice(0,34).padEnd(34))+chalk.gray(j(o.difficulty).padEnd(5))+chalk.gray(o.needs_gpu?" ⚡":" ")+chalk.gray(` ${o.data_mb}M`)+("teleload"===o.status?chalk.gray(v(" · teleload"," · teleload")):"")+(o.judged?chalk.green(v(" · 可出分"," · scored")):""))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(v(" 看题 · "," view · "))+chalk.cyan("done <n>")+chalk.gray(v(" 标记攻克 · "," mark cleared · "))+chalk.cyan("ai4ioai")+chalk.gray(v(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan("memo")+chalk.gray(v(" 记问题 · "," report a problem · "))+chalk.cyan("back")+chalk.gray(v(" 退出"," leave"))),console.log(chalk.gray(v(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克"," ⬜ unseen ◐ opened ✓ cleared"))),console.log(chalk.gray(v(" ⚡ 要 GPU(notebook 里 gpu key → gpu on) · teleload 数据是大包,用 teleload 拉 · 可出分 交上去有真分数"," ⚡ needs GPU (inside the notebook: gpu key → gpu on) · teleload big pack, pull with teleload · scored real score on submit"))),console.log()}function O(o,e){const n=[];let t="",l=0;for(const a of o){const o=/[ -鿿-]/.test(a)?2:1;l+o>e&&(n.push(t),t="",l=0),t+=a,l+=o}return t&&n.push(t),n}export async function runSprint(){y("sprint");const e=function(){try{const e=u();try{const t=JSON.parse(n(function(e){const n=[s(b,"..","data",e),s(b,"..","..","src","data",e)];for(const e of n)if(o(e))return e;return n[0]}("sprint-cards.json"),"utf8")),l=new Map((t.cards||[]).map(o=>[o.seq,o]));for(const o of e){const e=l.get(o.seq);e&&Object.assign(o,{star:e.star,trap:e.trap,action:e.action,hint:e.hint,meta:e.meta})}}catch{}return e.sort((o,e)=>o.seq-e.seq)}catch{return[]}}();if(0===e.length)return console.log(),console.log(chalk.yellow(" 冲刺题单还没装进这个版本。")),console.log(chalk.gray(" 升级后再试:")+chalk.cyan("npm install -g icoa-cli@latest")),void console.log();const t=function(){try{const o=JSON.parse(n(k,"utf8"));return{who:o.who||"",opened:o.opened||[],done:o.done||[]}}catch{return{who:"",opened:[],done:[]}}}();if(0===t.opened.length&&0===t.done.length)for(const o of S)console.log(o);t.who||(t.who=""),N(e,t);const a=i(),r=null!==a,c=r?a:l({input:process.stdin,output:process.stdout,terminal:!0});r||g(c);const w=r?c.listeners("line").slice():[];c.removeAllListeners("line");const $=c.prompt.bind(c);f=!0;const T=chalk.bold.cyan("icoa ioai2026> ");c.setPrompt(T);let x=null;await new Promise(o=>{c.on("line",async l=>{const a=l.trim().replace(/^icoa\s+/i,""),[s,i]=[a.split(/\s+/)[0]?.toLowerCase()||"",a.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(s))return A(t),console.log(chalk.gray(" 进度已保存。")),(()=>{if(f=!1,c.removeAllListeners("line"),r){for(const o of w)c.on("line",o);c.setPrompt(chalk.green("icoa> ")),c.prompt()}else g(null),c.close()})(),void o();if(""===s||["challenges","list","ls"].includes(s))N(e,t);else if(["open","o"].includes(s)||/^\d+$/.test(s)){const o=Number.parseInt(/^\d+$/.test(s)?s:i,10),n=e.find(e=>e.seq===o);n?(t.opened.includes(o)||t.opened.push(o),A(t),x=o,function(o){console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(`${o.seq} · ${o.title}`)+chalk.gray(` · ${o.bullseye}`)+chalk.cyan(" ─────")),console.log(chalk.cyan(" │"));const e=m(o).length>1,n=[o.star,o.trap,e?"":o.action,o.hint?` ${o.hint}`:""].filter(Boolean);0===n.length&&o.topic_cn&&n.push(`▸ ${o.topic_cn}`);for(const o of n){for(const e of O(o,58))console.log(chalk.cyan(" │ ")+chalk.white(e));console.log(chalk.cyan(" │"))}const t=q();console.log(chalk.cyan(" │ ")+chalk.gray(p(o,t)));const l=d(o,t);if(l)for(const o of O(l,58))console.log(chalk.cyan(" │ ")+chalk.gray(o));console.log(chalk.cyan(" │ ")+chalk.gray(o.meta||`⏱ 难度 ${j(o.difficulty)}`)+chalk.gray(o.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────"));for(const e of h(o,t))for(const o of O(e,60))console.log(chalk.yellow(" ")+chalk.yellow(o));const a=m(o),s=function(o){const e=m(o);if(e.length>0)return e[0];const n=/(?:kaggle|teleload)\s+[a-z0-9][a-z0-9-]*/i.exec(o.action||"");return n?n[0]:null}(o);a.length>1?(console.log(chalk.bold.white(v(" ▸ 就在这里敲,两步:"," ▸ Type these here, in order:"))),a.forEach((o,e)=>{console.log(chalk.gray(` ${e+1}. `)+chalk.bold.cyan(o)+chalk.gray(0===e?v(" ← 先把数据拉下来"," ← fetch the data first"):v(" ← 题面 + notebook"," ← statement + notebook")))})):s&&console.log(chalk.bold.white(v(" ▸ 就在这里敲: "," ▸ Type it right here: "))+chalk.bold.cyan(s)+chalk.gray(v(" ← 数据 + notebook 落到本机"," ← pulls the data + notebook"))),console.log(chalk.gray(" ")+chalk.cyan("ai4ioai")+chalk.gray(v(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan(`done ${o.seq}`)+chalk.gray(v(" 标记攻克 · "," mark cleared · "))+chalk.cyan("memo")+chalk.gray(v(` 记问题(自动记在第 ${o.seq} 题) · `,` report (auto-filed under ${o.seq}) · `))+chalk.cyan("back")+chalk.gray(v(" 回列表"," back to list"))),console.log()}(n)):console.log(chalk.yellow(` 没有第 ${i||s} 题。`)+chalk.gray(` 题号 1-${e.length}。`))}else if("done"===s){const o=Number.parseInt(i,10);e.some(e=>e.seq===o)?(t.done.includes(o)||t.done.push(o),A(t),console.log(chalk.green(` ✓ 第 ${o} 题标记为攻克`)+chalk.gray(` (${t.done.length}/${e.length})`))):console.log(chalk.yellow(` 题号 1-${e.length}。`))}else["kaggle","teleload","ipynb"].includes(s)?await async function(o,e){const n=e.split(/\s+/).filter(Boolean);try{if("teleload"===o){const{runTeleload:o}=await import("./teleload.js");return void await o(n[0])}if("ipynb"===o){const{runIpynb:o}=await import("./ipynb.js");return void await o(n[0])}const e=await import("./kaggle.js"),t=(n[0]||"").toLowerCase();"submit"===t?await e.runKaggleSubmit(n[1]):"check"===t?await e.runKaggleCheck(n[1]):"guide"===t?await e.runKaggleGuide(n[1]):await e.runKaggle(n[0])}catch(o){console.log(),console.log(chalk.yellow(v(" 这条命令没跑成:"," That command failed: "))+chalk.gray(String(o))),console.log(chalk.gray(v(" 记一条给教练:"," Tell the coach: "))+chalk.cyan(v("memo …","memo …"))),console.log()}}(s,a.split(/\s+/).slice(1).join(" ")):"memo"===s||"note"===s?await async function(o,e,t,l){const a=function(){try{const o=JSON.parse(n(I,"utf8"));return Array.isArray(o)?o:[]}catch{return[]}}(),s=o.trim();if(["list","ls","all"].includes(s.toLowerCase())){if(console.log(),0===a.length)console.log(chalk.gray(v(" 还没有记录。"," Nothing noted yet.")));else{console.log(chalk.bold.white(v(` 📝 已记 ${a.length} 条`,` 📝 ${a.length} noted`)));for(const o of a.slice(-12)){const e=o.seq?chalk.cyan(`#${o.seq}`):chalk.gray("—");console.log(` ${e} ${chalk.white(o.text.slice(0,60))}`+chalk.gray(o.synced?v(" ·已上报"," ·sent"):v(" ·仅本地"," ·local only")))}console.log(chalk.gray(` ${I}`))}return console.log(chalk.gray(v(" 再记一条:"," Note another: "))+chalk.cyan("memo")+chalk.gray(v(" (光敲这一个词就给你写字的地方)"," (just the word — it gives you a place to type)"))),void console.log()}const r=s?s.split(/\s+/):[],c=r.length>0&&/^\d+$/.test(r[0])&&e.some(o=>o.seq===Number(r[0])),i=c?Number(r[0]):t;let g=(c?r.slice(1):r).join(" ").trim();if(""===g){const o=i?chalk.gray(v(` —— 记在第 ${i} 题下`,` — filed under task ${i}`)):chalk.gray(v(" —— 通用反馈"," — general feedback"));if(console.log(),console.log(chalk.bold.white(v(" 📝 撞到什么就写什么"," 📝 Say what you hit"))+o),console.log(chalk.gray(v(" 一行写完,回车就存下(不用等回复);直接回车 = 不记。"," One line, Enter files it (no reply comes back). Empty Enter cancels."))),g=await function(o,e){return new Promise(n=>{o.question(e,o=>n(o.trim()))})}(l,chalk.cyan(" memo > ")),""===g)return console.log(chalk.gray(v(" 没记。"," Nothing noted."))),void console.log()}const d={ts:(new Date).toISOString(),seq:i,text:g,synced:!1};a.push(d),C(a),y(`sprint: memo${i?` ${i}`:""} — ${g}`);let p=!1;try{const{loadLearnState:o}=await import("../lib/learn-state.js"),e=o()?.token??"";if(e){const{syncCardFeedback:o}=await import("../lib/learn-curricula.js");p=await o(e,{curriculum_id:"pandahelpme31",card_number:i??0,feedback_text:g})}}catch{}p&&(d.synced=!0,C(a)),console.log(),console.log(chalk.green(v(" ✓ 记下了"," ✓ noted"))+(i?chalk.gray(v(` (第 ${i} 题)`,` (task ${i})`)):"")+chalk.gray(p?v(" ·已上报"," ·sent"):v(" ·存在本机,教练可以来取"," ·saved on this machine"))),console.log(chalk.gray(v(" 继续做题就好。看全部:"," Carry on. See them all: "))+chalk.cyan("memo list")),console.log()}(a.split(/\s+/).slice(1).join(" "),e,x,c):["ai4ioai","/ai4ioai","ai"].includes(s)?(console.log(),console.log(chalk.bold.white(v(" 左右分屏,左边看题右边问 AI:"," Split the screen — tasks left, AI right:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(v(" 左右分屏(上下分屏是 "," split left/right (up/down is "))+chalk.cyan('Ctrl-b "')+chalk.gray(v(")",")"))),console.log(chalk.gray(" 2. ")+chalk.gray(v("右边那格输 ","in the right pane type "))+chalk.bold.cyan("icoa")+chalk.gray(v(" ,再输 "," , then "))+chalk.bold.cyan("ai4ioai")),console.log(chalk.gray(v(" 3. 两格之间切换:"," 3. move between panes: "))+chalk.cyan("Ctrl-b ←")+chalk.gray(" / ")+chalk.cyan("Ctrl-b →")),console.log(),console.log(chalk.gray(v(" 它是弱模型 —— 单轮、2000 字符以内。把问题问准,就是这次要练的本事。"," A deliberately weak model — single-turn, 2000 chars. Asking precisely is the skill."))),console.log(chalk.gray(v(" 在 notebook 里卡住时,那边可以直接敲 "," Stuck inside a notebook? there you can type "))+chalk.cyan("ai")+chalk.gray(v(" —— 它会把那一格的代码和报错一起带上。"," — it carries that cell and its traceback."))),console.log()):["help","?","guide"].includes(s)?N(e,t):(console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(v(" 看题 · "," view · "))+chalk.cyan("kaggle <题目id>")+chalk.gray(v(" 领数据 · "," get the data · "))+chalk.cyan("ipynb <路径>")+chalk.gray(v(" 开 notebook · "," open the notebook · "))+chalk.cyan("done <n>")+chalk.gray(v(" 标记 · "," mark · "))+chalk.cyan("memo")+chalk.gray(v(" 记问题 · "," report · "))+chalk.cyan("back")+chalk.gray(v(" 退出"," leave"))),console.log(chalk.gray(v(" 题目 id 在卡片的 ▸ 那一行,例如 "," The task id is on the card’s ▸ line, e.g. "))+chalk.cyan("open 17")+chalk.gray(" → ")+chalk.cyan("kaggle s17-bazarul-lui-riki")));c.prompt=$,c.setPrompt(T),c.prompt()}),r||c.once("close",()=>o()),c.prompt=$,c.prompt()})}export function registerSprintCommand(o){o.command("pandahelpme31",{hidden:!0}).action(async()=>{await runSprint()})}
|
|
1
|
+
import{existsSync as o,mkdirSync as e,readFileSync as n,writeFileSync as t}from"node:fs";import{createInterface as l}from"node:readline";import{dirname as a,join as r}from"node:path";import{fileURLToPath as s}from"node:url";import chalk from"chalk";import{getConfig as c}from"../lib/config.js";import{getMainRl as i,setMainRl as g}from"../lib/main-rl.js";import{logCommand as y}from"../lib/logger.js";import{baselineChip as d,computeChip as p,computeLegend as u,loadSprintTasks as h,mediaHelpLines as m,taskSteps as f}from"../lib/sprint-meta.js";let w=!1;export function isSprintActive(){return w}const b=a(s(import.meta.url)),$=r(process.env.HOME||".",".icoa"),k=r($,"sprint-state.json"),S={"T-torch":"裸 torch:手写 attention / causal mask / perplexity","T-umap":"降维当特征提取器,不是画图工具","T-lora":"peft LoRA 参数高效微调","T-librosa":"音频特征流水线:mel / MFCC → 定长向量"},A=["",chalk.bold.cyan(" ASTANA 2027"),chalk.gray(" — 给还没出发的你"),"",chalk.white(" 草原的风从额尔齐斯河吹到阿斯塔纳的时候,会带着一点雪的味道。"),chalk.white(" 你还没去过那里。但那里已经有一个座位,写着你的名字。"),"",chalk.white(" 你现在坐在屏幕前,离比赛还有几天。"),chalk.white(" 你可能会想:几天能改变什么?"),"",chalk.white(" 足够让一个人从「看着题发呆」变成「看到题就知道该拆哪一层」。"),chalk.white(" 足够让手指记住 import torch 之后该敲什么。"),chalk.white(" 足够让你在比赛那天早上醒来时,不再害怕。"),"",chalk.bold.yellow(" M")+chalk.white(" —— 你总是第一个说「我先试试」的那个。别停。"),chalk.bold.yellow(" V")+chalk.white(" —— 你总是问「为什么是这样」的那个。继续问。"),chalk.bold.yellow(" A")+chalk.white(" —— 你总是在别人放弃时还在改最后一版的那个。改下去。"),"",chalk.white(" 你们三个人,一个人是一条腿走路,三个人是奔跑。"),"",chalk.white(" 你们要面对的不是一场考试,是一次证明:"),chalk.bold.white(" 中国的高中生,可以在 AI 的赛场上,和世界站在同一排。"),"",chalk.white(" 而 2027 年的阿斯塔纳,是我们下一个约定。"),"",chalk.gray(" 现在,把这行字关掉,去做第 1 题。"),chalk.gray(" — 熊猫教练"),""];function q(o){try{e($,{recursive:!0}),t(k,`${JSON.stringify(o,null,1)}\n`)}catch{}}function v(){return(c().language||"en").toLowerCase().startsWith("zh")}function j(o,e){return v()?o:e}function I(o){return"★".repeat(Math.max(1,Math.min(5,o||3)))}const C=r($,"sprint-memos.json");function N(o){try{e($,{recursive:!0}),t(C,`${JSON.stringify(o,null,1)}\n`)}catch{}}function O(o,e){const n=new Set(e.done),t=new Set(e.opened);console.log(),console.log(chalk.bold.cyan(j(" ⚔ IOAI 2026 · 四工具冲刺"," ⚔ IOAI 2026 · four-tool sprint"))+chalk.gray(` ${j("已攻克","cleared")} ${n.size} / ${o.length}`));const l=new Map;for(const e of o)l.has(e.bullseye)||l.set(e.bullseye,[]),l.get(e.bullseye)?.push(e);for(const[o,e]of l){console.log(),console.log(chalk.bold.white(` ${o}`)+chalk.gray(` — ${S[o]||""}`));for(const o of e){const e=n.has(o.seq)?chalk.green("✓"):t.has(o.seq)?chalk.yellow("◐"):chalk.gray("⬜");console.log(` ${e} ${chalk.bold.white(String(o.seq).padStart(2))} `+chalk.white(o.title.slice(0,34).padEnd(34))+chalk.gray(I(o.difficulty).padEnd(5))+chalk.gray(o.needs_gpu?" ⚡":" ")+chalk.gray(` ${o.data_mb}M`)+("teleload"===o.status?chalk.gray(j(" · teleload"," · teleload")):"")+(o.judged?chalk.green(j(" · 可出分"," · scored")):""))}}console.log(),console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(j(" 看题 · "," view · "))+chalk.cyan("done <n>")+chalk.gray(j(" 标记攻克 · "," mark cleared · "))+chalk.cyan("ai4ioai")+chalk.gray(j(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan("memo")+chalk.gray(j(" 记问题 · "," report a problem · "))+chalk.cyan("back")+chalk.gray(j(" 退出"," leave"))),console.log(chalk.gray(j(" ⬜ 没看过 ◐ 看过没做完 ✓ 攻克"," ⬜ unseen ◐ opened ✓ cleared"))),console.log(chalk.gray(u(v()))),console.log()}function T(o,e){const n=[];let t="",l=0;for(const a of o){const o=/[ -鿿-]/.test(a)?2:1;l+o>e&&(n.push(t),t="",l=0),t+=a,l+=o}return t&&n.push(t),n}export async function runSprint(){y("sprint");const e=function(){try{const e=h();try{const t=JSON.parse(n(function(e){const n=[r(b,"..","data",e),r(b,"..","..","src","data",e)];for(const e of n)if(o(e))return e;return n[0]}("sprint-cards.json"),"utf8")),l=new Map((t.cards||[]).map(o=>[o.seq,o]));for(const o of e){const e=l.get(o.seq);e&&Object.assign(o,{star:e.star,trap:e.trap,action:e.action,hint:e.hint,meta:e.meta})}}catch{}return e.sort((o,e)=>o.seq-e.seq)}catch{return[]}}();if(0===e.length)return console.log(),console.log(chalk.yellow(" 冲刺题单还没装进这个版本。")),console.log(chalk.gray(" 升级后再试:")+chalk.cyan("npm install -g icoa-cli@latest")),void console.log();const t=function(){try{const o=JSON.parse(n(k,"utf8"));return{who:o.who||"",opened:o.opened||[],done:o.done||[]}}catch{return{who:"",opened:[],done:[]}}}();if(0===t.opened.length&&0===t.done.length)for(const o of A)console.log(o);t.who||(t.who=""),O(e,t);const a=i(),s=null!==a,c=s?a:l({input:process.stdin,output:process.stdout,terminal:!0});s||g(c);const u=s?c.listeners("line").slice():[];c.removeAllListeners("line");const $=c.prompt.bind(c);w=!0;const S=chalk.bold.cyan("icoa ioai2026> ");c.setPrompt(S);let x=null;await new Promise(o=>{c.on("line",async l=>{const a=l.trim().replace(/^icoa\s+/i,""),[r,i]=[a.split(/\s+/)[0]?.toLowerCase()||"",a.split(/\s+/)[1]||""];if(["back","quit","exit","menu"].includes(r))return q(t),console.log(chalk.gray(" 进度已保存。")),(()=>{if(w=!1,c.removeAllListeners("line"),s){for(const o of u)c.on("line",o);c.setPrompt(chalk.green("icoa> ")),c.prompt()}else g(null),c.close()})(),void o();if(""===r||["challenges","list","ls"].includes(r))O(e,t);else if(["open","o"].includes(r)||/^\d+$/.test(r)){const o=Number.parseInt(/^\d+$/.test(r)?r:i,10),n=e.find(e=>e.seq===o);n?(t.opened.includes(o)||t.opened.push(o),q(t),x=o,function(o){console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(`${o.seq} · ${o.title}`)+chalk.gray(` · ${o.bullseye}`)+chalk.cyan(" ─────")),console.log(chalk.cyan(" │"));const e=f(o).length>1,n=[o.star,o.trap,e?"":o.action,o.hint?` ${o.hint}`:""].filter(Boolean);0===n.length&&o.topic_cn&&n.push(`▸ ${o.topic_cn}`);for(const o of n){for(const e of T(o,58))console.log(chalk.cyan(" │ ")+chalk.white(e));console.log(chalk.cyan(" │"))}const t=v();console.log(chalk.cyan(" │ ")+chalk.gray(p(o,t)));const l=d(o,t);if(l)for(const o of T(l,58))console.log(chalk.cyan(" │ ")+chalk.gray(o));console.log(chalk.cyan(" │ ")+chalk.gray(o.meta||`⏱ 难度 ${I(o.difficulty)}`)+chalk.gray(o.needs_gpu?" ⚡ 需要 GPU":"")),console.log(chalk.cyan(" ╰──────────────────────────────────────────────────────"));for(const e of m(o,t))for(const o of T(e,60))console.log(chalk.yellow(" ")+chalk.yellow(o));const a=f(o),r=function(o){const e=f(o);if(e.length>0)return e[0];const n=/(?:kaggle|teleload)\s+[a-z0-9][a-z0-9-]*/i.exec(o.action||"");return n?n[0]:null}(o);a.length>1?(console.log(chalk.bold.white(j(" ▸ 就在这里敲,两步:"," ▸ Type these here, in order:"))),a.forEach((o,e)=>{console.log(chalk.gray(` ${e+1}. `)+chalk.bold.cyan(o)+chalk.gray(0===e?j(" ← 先把数据拉下来"," ← fetch the data first"):j(" ← 题面 + notebook"," ← statement + notebook")))})):r&&console.log(chalk.bold.white(j(" ▸ 就在这里敲: "," ▸ Type it right here: "))+chalk.bold.cyan(r)+chalk.gray(j(" ← 数据 + notebook 落到本机"," ← pulls the data + notebook"))),console.log(chalk.gray(" ")+chalk.cyan("ai4ioai")+chalk.gray(j(" 开 AI 分屏 · "," AI in a split · "))+chalk.cyan(`done ${o.seq}`)+chalk.gray(j(" 标记攻克 · "," mark cleared · "))+chalk.cyan("memo")+chalk.gray(j(` 记问题(自动记在第 ${o.seq} 题) · `,` report (auto-filed under ${o.seq}) · `))+chalk.cyan("back")+chalk.gray(j(" 回列表"," back to list"))),console.log()}(n)):console.log(chalk.yellow(` 没有第 ${i||r} 题。`)+chalk.gray(` 题号 1-${e.length}。`))}else if("done"===r){const o=Number.parseInt(i,10);e.some(e=>e.seq===o)?(t.done.includes(o)||t.done.push(o),q(t),console.log(chalk.green(` ✓ 第 ${o} 题标记为攻克`)+chalk.gray(` (${t.done.length}/${e.length})`))):console.log(chalk.yellow(` 题号 1-${e.length}。`))}else["kaggle","teleload","ipynb"].includes(r)?await async function(o,e){const n=e.split(/\s+/).filter(Boolean);try{if("teleload"===o){const{runTeleload:o}=await import("./teleload.js");return void await o(n[0])}if("ipynb"===o){const{runIpynb:o}=await import("./ipynb.js");return void await o(n[0])}const e=await import("./kaggle.js"),t=(n[0]||"").toLowerCase();"submit"===t?await e.runKaggleSubmit(n[1]):"check"===t?await e.runKaggleCheck(n[1]):"guide"===t?await e.runKaggleGuide(n[1]):await e.runKaggle(n[0])}catch(o){console.log(),console.log(chalk.yellow(j(" 这条命令没跑成:"," That command failed: "))+chalk.gray(String(o))),console.log(chalk.gray(j(" 记一条给教练:"," Tell the coach: "))+chalk.cyan(j("memo …","memo …"))),console.log()}}(r,a.split(/\s+/).slice(1).join(" ")):"memo"===r||"note"===r?await async function(o,e,t,l){const a=function(){try{const o=JSON.parse(n(C,"utf8"));return Array.isArray(o)?o:[]}catch{return[]}}(),r=o.trim();if(["list","ls","all"].includes(r.toLowerCase())){if(console.log(),0===a.length)console.log(chalk.gray(j(" 还没有记录。"," Nothing noted yet.")));else{console.log(chalk.bold.white(j(` 📝 已记 ${a.length} 条`,` 📝 ${a.length} noted`)));for(const o of a.slice(-12)){const e=o.seq?chalk.cyan(`#${o.seq}`):chalk.gray("—");console.log(` ${e} ${chalk.white(o.text.slice(0,60))}`+chalk.gray(o.synced?j(" ·已上报"," ·sent"):j(" ·仅本地"," ·local only")))}console.log(chalk.gray(` ${C}`))}return console.log(chalk.gray(j(" 再记一条:"," Note another: "))+chalk.cyan("memo")+chalk.gray(j(" (光敲这一个词就给你写字的地方)"," (just the word — it gives you a place to type)"))),void console.log()}const s=r?r.split(/\s+/):[],c=s.length>0&&/^\d+$/.test(s[0])&&e.some(o=>o.seq===Number(s[0])),i=c?Number(s[0]):t;let g=(c?s.slice(1):s).join(" ").trim();if(""===g){const o=i?chalk.gray(j(` —— 记在第 ${i} 题下`,` — filed under task ${i}`)):chalk.gray(j(" —— 通用反馈"," — general feedback"));if(console.log(),console.log(chalk.bold.white(j(" 📝 撞到什么就写什么"," 📝 Say what you hit"))+o),console.log(chalk.gray(j(" 一行写完,回车就存下(不用等回复);直接回车 = 不记。"," One line, Enter files it (no reply comes back). Empty Enter cancels."))),g=await function(o,e){return new Promise(n=>{o.question(e,o=>n(o.trim()))})}(l,chalk.cyan(" memo > ")),""===g)return console.log(chalk.gray(j(" 没记。"," Nothing noted."))),void console.log()}const d={ts:(new Date).toISOString(),seq:i,text:g,synced:!1};a.push(d),N(a),y(`sprint: memo${i?` ${i}`:""} — ${g}`);let p=!1;try{const{loadLearnState:o}=await import("../lib/learn-state.js"),e=o()?.token??"";if(e){const{syncCardFeedback:o}=await import("../lib/learn-curricula.js");p=await o(e,{curriculum_id:"pandahelpme31",card_number:i??0,feedback_text:g})}}catch{}p&&(d.synced=!0,N(a)),console.log(),console.log(chalk.green(j(" ✓ 记下了"," ✓ noted"))+(i?chalk.gray(j(` (第 ${i} 题)`,` (task ${i})`)):"")+chalk.gray(p?j(" ·已上报"," ·sent"):j(" ·存在本机,教练可以来取"," ·saved on this machine"))),console.log(chalk.gray(j(" 继续做题就好。看全部:"," Carry on. See them all: "))+chalk.cyan("memo list")),console.log()}(a.split(/\s+/).slice(1).join(" "),e,x,c):["ai4ioai","/ai4ioai","ai"].includes(r)?(console.log(),console.log(chalk.bold.white(j(" 左右分屏,左边看题右边问 AI:"," Split the screen — tasks left, AI right:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(j(" 左右分屏(上下分屏是 "," split left/right (up/down is "))+chalk.cyan('Ctrl-b "')+chalk.gray(j(")",")"))),console.log(chalk.gray(" 2. ")+chalk.gray(j("右边那格输 ","in the right pane type "))+chalk.bold.cyan("icoa")+chalk.gray(j(" ,再输 "," , then "))+chalk.bold.cyan("ai4ioai")),console.log(chalk.gray(j(" 3. 两格之间切换:"," 3. move between panes: "))+chalk.cyan("Ctrl-b ←")+chalk.gray(" / ")+chalk.cyan("Ctrl-b →")),console.log(),console.log(chalk.gray(j(" 它是弱模型 —— 单轮、2000 字符以内。把问题问准,就是这次要练的本事。"," A deliberately weak model — single-turn, 2000 chars. Asking precisely is the skill."))),console.log(chalk.gray(j(" 在 notebook 里卡住时,那边可以直接敲 "," Stuck inside a notebook? there you can type "))+chalk.cyan("ai")+chalk.gray(j(" —— 它会把那一格的代码和报错一起带上。"," — it carries that cell and its traceback."))),console.log()):["help","?","guide"].includes(r)?O(e,t):(console.log(chalk.gray(" ")+chalk.cyan("open <n>")+chalk.gray(j(" 看题 · "," view · "))+chalk.cyan("kaggle <题目id>")+chalk.gray(j(" 领数据 · "," get the data · "))+chalk.cyan("ipynb <路径>")+chalk.gray(j(" 开 notebook · "," open the notebook · "))+chalk.cyan("done <n>")+chalk.gray(j(" 标记 · "," mark · "))+chalk.cyan("memo")+chalk.gray(j(" 记问题 · "," report · "))+chalk.cyan("back")+chalk.gray(j(" 退出"," leave"))),console.log(chalk.gray(j(" 题目 id 在卡片的 ▸ 那一行,例如 "," The task id is on the card’s ▸ line, e.g. "))+chalk.cyan("open 17")+chalk.gray(" → ")+chalk.cyan("kaggle s17-bazarul-lui-riki")));c.prompt=$,c.setPrompt(S),c.prompt()}),s||c.once("close",()=>o()),c.prompt=$,c.prompt()})}export function registerSprintCommand(o){o.command("pandahelpme31",{hidden:!0}).action(async()=>{await runSprint()})}
|
package/dist/lib/open-file.d.ts
CHANGED
|
@@ -5,5 +5,31 @@ export interface OpenCommand {
|
|
|
5
5
|
/** Decide the OS "open" command for `path`. Pure — platform + env are injected
|
|
6
6
|
* so every baseline target (macOS / Linux / WSL / Windows) is unit-testable. */
|
|
7
7
|
export declare function openFileCommand(path: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): OpenCommand;
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* Open `path` in the OS default app (detached). Returns false when we could not
|
|
10
|
+
* launch an opener — callers MUST surface the path themselves in that case.
|
|
11
|
+
*
|
|
12
|
+
* 🔴 spawn() does NOT throw when the binary is missing. ENOENT arrives as an
|
|
13
|
+
* asynchronous 'error' event on the next tick, so a try/catch around spawn()
|
|
14
|
+
* catches nothing, and with no 'error' listener Node re-throws it as an
|
|
15
|
+
* UNCAUGHT EXCEPTION and dumps a full multi-block stack trace. That is exactly
|
|
16
|
+
* what a WSL student saw instead of the demo2 clip (2026-07-28): Ubuntu's WSL
|
|
17
|
+
* rootfs ships no xdg-utils, so `xdg-open` is absent on every fresh box.
|
|
18
|
+
*
|
|
19
|
+
* Two guards, both required:
|
|
20
|
+
* 1. whichBinary() — a PATH scan BEFORE spawning, so "no opener" is an
|
|
21
|
+
* honest synchronous false instead of a crash several ticks later.
|
|
22
|
+
* 2. an 'error' listener anyway — the PATH scan can still lose a race
|
|
23
|
+
* (binary removed, not executable), and one un-listened event kills icoa.
|
|
24
|
+
*/
|
|
9
25
|
export declare function openFile(path: string): boolean;
|
|
26
|
+
/** The line to print when no opener exists. Pure so every baseline target is
|
|
27
|
+
* unit-testable; WSL gets the Windows path because `\\wsl.localhost\...` is
|
|
28
|
+
* what a student can actually paste into Explorer. */
|
|
29
|
+
export declare function openFallbackHint(path: string, platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): string;
|
|
30
|
+
/**
|
|
31
|
+
* Open a rendered clip/figure and ALWAYS tell the student what happened.
|
|
32
|
+
* Silence is the bug: on a box with no opener the old code either said
|
|
33
|
+
* "Opening in your default video player..." and did nothing, or crashed.
|
|
34
|
+
*/
|
|
35
|
+
export declare function openMedia(path: string, log: (line: string) => void): boolean;
|
package/dist/lib/open-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as e,execFileSync as r}from"node:child_process";export function openFileCommand(e,r=process.platform,n=process.env){return"darwin"===r?{cmd:"open",args:[e]}:"win32"===r?{cmd:"cmd.exe",args:["/c","start","",e]}:
|
|
1
|
+
import{spawn as e,execFileSync as r}from"node:child_process";import{whichBinary as n}from"./platform.js";function o(e){return!(!e.WSL_DISTRO_NAME&&!e.WSL_INTEROP)}export function openFileCommand(e,r=process.platform,n=process.env){return"darwin"===r?{cmd:"open",args:[e]}:"win32"===r?{cmd:"cmd.exe",args:["/c","start","",e]}:o(n)?{cmd:"explorer.exe",args:[e]}:{cmd:"xdg-open",args:[e]}}export function openFile(o){const{cmd:t,args:i}=openFileCommand(o);if(!n(t))return!1;let p=i;if("explorer.exe"===t)try{const e=r("wslpath",["-w",o],{encoding:"utf-8"}).trim();e&&(p=[e])}catch{}try{const r=e(t,p,{stdio:"ignore",detached:!0});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}export function openFallbackHint(e,n=process.platform,t=process.env){if("win32"!==n&&o(t)){let n=e;try{n=r("wslpath",["-w",e],{encoding:"utf-8"}).trim()||e}catch{}return`No Linux video player under WSL. Open this from Windows:\n ${n}`}return`Open this file in your video player:\n ${e}`}export function openMedia(e,r){if(openFile(e))return r(" Opening in your default video player..."),!0;for(const n of openFallbackHint(e).split("\n"))r(n.startsWith(" ")?n:` ${n}`);return!1}
|
|
@@ -57,6 +57,13 @@ export declare function baselineChip(t: SprintTaskMeta, zh: boolean): string;
|
|
|
57
57
|
* back once the box-side hydration lands.
|
|
58
58
|
*/
|
|
59
59
|
export declare function computeChip(t: SprintTaskMeta, zh: boolean): string;
|
|
60
|
+
/**
|
|
61
|
+
* The list's legend for the same three marks the cards use. It lives here, next
|
|
62
|
+
* to `computeChip`, because the two were written apart and immediately drifted:
|
|
63
|
+
* the card said "GPU optional, the baseline runs on your laptop" while the
|
|
64
|
+
* legend two screens earlier still said "needs GPU — gpu key → gpu on".
|
|
65
|
+
*/
|
|
66
|
+
export declare function computeLegend(zh: boolean): string;
|
|
60
67
|
/**
|
|
61
68
|
* The media block: what is missing, the command that fetches it, and the first
|
|
62
69
|
* line of code that reads it. Used by the download guide AND baked into the
|