icoa-cli 2.19.461 → 2.19.463

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import chalk from"chalk";import{getConfig as e,saveConfig as o}from"../lib/config.js";import{COUNTRY_LANG as s}from"../lib/country-lang.js";import{getExamState as a,getRealExamState as t}from"../lib/exam-state.js";import{logCommand as n}from"../lib/logger.js";import{ensureLangCache as r}from"../lib/translations-fetcher.js";import{loadUiPack as i}from"../lib/i18n.js";import{printSuccess as l,printError as c,printInfo as g}from"../lib/ui.js";import{SUPPORTED_LANGUAGES as u}from"../types/index.js";const m={en:"English",zh:"中文 (Chinese)",ja:"日本語 (Japanese)",ko:"한국어 (Korean)",es:"Español (Spanish)",ar:"العربية (Arabic)",fr:"Français (French)",pt:"Português (Portuguese)",ru:"Русский (Russian)",hi:"हिन्दी (Hindi)",de:"Deutsch (German)",id:"Bahasa (Indonesian)",th:"ไทย (Thai)",vi:"Tiếng Việt (Vietnamese)",tr:"Türkçe (Turkish)",uk:"Українська (Ukrainian)",ht:"Kreyòl (Haitian Creole)",sw:"Kiswahili (Swahili)",uz:"Oʻzbek (Uzbek)",lo:"ລາວ (Lao)"};export function registerLangCommand(p){p.command("lang [code]").description("Switch display language").action(async p=>{if(n(`lang ${p||""}`),!p){const o=e();g(`Current language: ${chalk.white(m[o.language]||o.language)}`),console.log(),console.log(chalk.gray(" Supported languages:"));for(const e of u){const s=o.language===e?chalk.yellow(" ← current"):"";console.log(` ${chalk.white(e)} ${m[e]}${s}`)}return console.log(),console.log(chalk.gray(" Switch now: ")+chalk.cyan("lang <code>")+chalk.gray(" (e.g. ")+chalk.cyan("lang es")+chalk.gray(")")),console.log(chalk.gray(' No "back" needed — you are still at the ')+chalk.cyan("icoa>")+chalk.gray(" prompt.")),void console.log()}if(!u.includes(p)){c(`Unsupported language: ${p}`);const e=u.map(e=>`${e} (${m[e]?.split(" ")[0]||e})`).join(", ");return void g(`Supported: ${e}`)}const d=t(),y=d?.session?.token;if(y){const e=y.substring(0,2).toUpperCase(),o=s[e];if(o&&p!==o&&"en"!==p)return c("Language is locked during your exam."),g(`Your token (${e}xxx) supports two languages: ${chalk.cyan("en")} (English) or ${chalk.cyan(o)} (${m[o]||o}).`),void g("To change language, finish or quit the current exam first.")}o({language:p}),l(`Language set to: ${m[p]||p}`),await r(p),i(p);const h=a();if(h&&"demo-free"===h.session.examId)try{const{pickDemoQuestions:e,getLocalizedDemoSession:o,getLocalizedDemoQuestions:s,getLocalizedExplanations:a,DEMO_PICK_SIZE:t}=await import("../lib/demo-exam.js"),{saveExamState:n}=await import("../lib/exam-state.js");if(h.questions.every(e=>null!=e.sourceNumber&&Array.isArray(e.sourceOrder)&&4===e.sourceOrder.length)){const e=s(),t=a();h.questions=h.questions.map(o=>{const s=e.find(e=>e.number===o.sourceNumber);return s&&o.sourceOrder?{...o,text:s.text,category:s.category,options:{A:s.options[o.sourceOrder[0]],B:s.options[o.sourceOrder[1]],C:s.options[o.sourceOrder[2]],D:s.options[o.sourceOrder[3]]},explanation:t[o.sourceNumber]}:o}),h.session.examName=o().examName,n(h);const r=h._lastQ||1;console.log(),console.log(chalk.green(` Demo continues in ${m[p]||p}. Your progress is kept.`)),console.log(chalk.white(` Resume: exam q ${r}`))}else h.questions=e(t),h.answers={},h.session.examName=o().examName,h.session.startedAt=(new Date).toISOString(),h._lastQ=1,n(h),console.log(),console.log(chalk.green(` Demo restarted in ${m[p]||p}.`)),console.log(chalk.white(" Type: exam q 1"))}catch{console.log(chalk.gray(" Language changed. Type: demo"))}else if(h&&h.session.token)try{const{getConfig:e}=await import("../lib/config.js"),{saveExamState:o}=await import("../lib/exam-state.js"),{getDeviceFingerprint:s}=await import("../lib/access.js"),a=e().ctfdUrl||"https://practice.icoa2026.au",t=h.session.token,n=await fetch(`${a}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,deviceHash:s(),lang:p}),signal:AbortSignal.timeout(1e4)});if(n.ok){const e=(await n.json()).data.questions;h.questions=e,o(h);const s=h._lastQ||1;console.log(),l(`Exam questions updated to ${m[p]||p}. Your answers are kept.`),console.log(chalk.white(` Resume: exam q ${s}`))}else if(429===n.status){const e=await n.json().catch(()=>null),o=e?.message?.match(/(\d+)\s*s/i),s=o?parseInt(o[1],10):60;console.log(),g(`Server rate-limited that token (wait ~${s}s).`),g(`Your exam session is intact — try ${chalk.cyan(`lang ${p}`)} again after the cooldown.`)}else{const{clearExamState:e}=await import("../lib/exam-state.js");e(),console.log(),console.log(chalk.green(" ✓ Old session record cleared — your scores are safe.")),console.log(chalk.gray(" To start (or resume) your exam, type your token:")),console.log(chalk.gray(" → ")+chalk.bold.cyan("exam <your-token>"))}}catch{console.log(chalk.yellow(" Could not reach server. Language changed for UI only."))}else if(h){const e=h._lastQ||1;console.log(),console.log(chalk.gray(` Exam in progress — resuming Q${e}:`)),console.log(chalk.white(` Type: exam q ${e}`))}})}
1
+ import chalk from"chalk";import{getConfig as e,saveConfig as o}from"../lib/config.js";import{COUNTRY_LANG as s}from"../lib/country-lang.js";import{getExamState as a,getRealExamState as n}from"../lib/exam-state.js";import{logCommand as t}from"../lib/logger.js";import{ensureLangCache as r}from"../lib/translations-fetcher.js";import{loadUiPack as i}from"../lib/i18n.js";import{printSuccess as l,printError as c,printInfo as g}from"../lib/ui.js";import{SUPPORTED_LANGUAGES as u}from"../types/index.js";const m={en:"English",zh:"中文 (Chinese)",ja:"日本語 (Japanese)",ko:"한국어 (Korean)",es:"Español (Spanish)",ar:"العربية (Arabic)",fr:"Français (French)",pt:"Português (Portuguese)",ru:"Русский (Russian)",hi:"हिन्दी (Hindi)",de:"Deutsch (German)",id:"Bahasa (Indonesian)",th:"ไทย (Thai)",vi:"Tiếng Việt (Vietnamese)",tr:"Türkçe (Turkish)",uk:"Українська (Ukrainian)",ht:"Kreyòl (Haitian Creole)",sw:"Kiswahili (Swahili)",uz:"Oʻzbek (Uzbek)",lo:"ລາວ (Lao)"};export function registerLangCommand(p){p.command("lang [code]").description("Switch display language").action(async p=>{if(t(`lang ${p||""}`),!p){const o=e();g(`Current language: ${chalk.white(m[o.language]||o.language)}`),console.log(),console.log(chalk.gray(" Supported languages:"));for(const e of u){const s=o.language===e?chalk.yellow(" ← current"):"";console.log(` ${chalk.white(e)} ${m[e]}${s}`)}return console.log(),console.log(chalk.gray(" Switch now: ")+chalk.cyan("lang <code>")+chalk.gray(" (e.g. ")+chalk.cyan("lang es")+chalk.gray(")")),console.log(chalk.gray(' No "back" needed — you are still at the ')+chalk.cyan("icoa>")+chalk.gray(" prompt.")),void console.log()}if(!u.includes(p)){c(`Unsupported language: ${p}`);const e=u.map(e=>`${e} (${m[e]?.split(" ")[0]||e})`).join(", ");return void g(`Supported: ${e}`)}const d=n(),y=d?.session?.token;if(y){const e=y.substring(0,2).toUpperCase(),o=s[e];if(o&&p!==o&&"en"!==p)return c("Language is locked during your exam."),g(`Your token (${e}xxx) supports two languages: ${chalk.cyan("en")} (English) or ${chalk.cyan(o)} (${m[o]||o}).`),void g("To change language, finish or quit the current exam first.")}o({language:p}),l(`Language set to: ${m[p]||p}`),await r(p),i(p);const h=a();if(h&&"demo-free"===h.session.examId)try{const{pickDemoQuestions:e,getLocalizedDemoSession:o,getLocalizedDemoQuestions:s,getLocalizedExplanations:a,DEMO_PICK_SIZE:n}=await import("../lib/demo-exam.js"),{saveExamState:t}=await import("../lib/exam-state.js");if(h.questions.every(e=>null!=e.sourceNumber&&Array.isArray(e.sourceOrder)&&4===e.sourceOrder.length)){const e=s(),n=a();h.questions=h.questions.map(o=>{const s=e.find(e=>e.number===o.sourceNumber);return s&&o.sourceOrder?{...o,text:s.text,category:s.category,options:{A:s.options[o.sourceOrder[0]],B:s.options[o.sourceOrder[1]],C:s.options[o.sourceOrder[2]],D:s.options[o.sourceOrder[3]]},explanation:n[o.sourceNumber]}:o}),h.session.examName=o().examName,t(h);const r=h._lastQ||1;console.log(),console.log(chalk.green(` Demo continues in ${m[p]||p}. Your progress is kept.`)),console.log(chalk.white(` Resume: exam q ${r}`))}else h.questions=e(n),h.answers={},h.session.examName=o().examName,h.session.startedAt=(new Date).toISOString(),h._lastQ=1,t(h),console.log(),console.log(chalk.green(` Demo restarted in ${m[p]||p}.`)),console.log(chalk.white(" Type: exam q 1"))}catch{console.log(chalk.gray(" Language changed. Type: demo"))}else if(h&&h.session.token)try{const{saveExamState:e}=await import("../lib/exam-state.js"),{getDeviceFingerprint:o}=await import("../lib/access.js"),{EXAM_SERVER:s}=await import("../lib/exam-server.js"),a=s,n=h.session.token,t=await fetch(`${a}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:n,deviceHash:o(),lang:p}),signal:AbortSignal.timeout(1e4)});if(t.ok){const o=(await t.json()).data.questions;h.questions=o,e(h);const s=h._lastQ||1;console.log(),l(`Exam questions updated to ${m[p]||p}. Your answers are kept.`),console.log(chalk.white(` Resume: exam q ${s}`))}else if(429===t.status){const e=await t.json().catch(()=>null),o=e?.message?.match(/(\d+)\s*s/i),s=o?parseInt(o[1],10):60;console.log(),g(`Server rate-limited that token (wait ~${s}s).`),g(`Your exam session is intact — try ${chalk.cyan(`lang ${p}`)} again after the cooldown.`)}else{const{clearExamState:e}=await import("../lib/exam-state.js");e(),console.log(),console.log(chalk.green(" ✓ Old session record cleared — your scores are safe.")),console.log(chalk.gray(" To start (or resume) your exam, type your token:")),console.log(chalk.gray(" → ")+chalk.bold.cyan("exam <your-token>"))}}catch{console.log(chalk.yellow(" Could not reach server. Language changed for UI only."))}else if(h){const e=h._lastQ||1;console.log(),console.log(chalk.gray(` Exam in progress — resuming Q${e}:`)),console.log(chalk.white(` Type: exam q ${e}`))}})}
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as n,execSync as t,spawn as r}from"node:child_process";import{rearmFocusMode as l}from"../lib/input-dynamics.js";import{logCommand as s}from"../lib/logger.js";import{getMainRl as a}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as i,handleAi4ioaiMessage as c,startAi4ioaiChat as d}from"./ai4ioai.js";import{existsSync as g,mkdirSync as u,readdirSync as y,readFileSync as m,renameSync as h,statSync as p,writeFileSync as f}from"node:fs";import{emptyDynamics as b,foldEditSession as w,isEmpty as $,noteRun as k}from"../lib/arena-edit-dynamics.js";import{dirname as v,join as A}from"node:path";import{fileURLToPath as C}from"node:url";import{loadCurriculumById as _,validateEAToken as T,syncProgress as x,syncCardFeedback as I,fetchCardFaqs as E}from"../lib/learn-curricula.js";import{parseReplyCommand as S,renderReplyLines as P,replyPushLine as q}from"../lib/learn-replies.js";import{ensureFullTable as M,lookupPydoc as L,lookupRanked as N,nearKeys as j,renderIndex as R,renderPydoc as W,renderSyntax as O,tableSize as D}from"../lib/py-syntax.js";import{normalizeTokenBody as Y}from"../lib/token-format.js";import{fetchMyScores as U,recallCoach as F,setNickname as z,streamLearnTutor as B,submitPqs as H,viewPqsTop as Z,viewHonors as J}from"../lib/learn-ai.js";import{contestReset as K,contestStart as Q,contestSubmit as V,linkByIndex as X,linkSuggest as G,linkToken as ee,fetchGate as oe,timeLeft as ne}from"../lib/learn-contest.js";import{getConfig as te,saveConfig as re}from"../lib/config.js";import{isNativeWindows as le,isWindowsBuildInWslShell as se,whichBinary as ae}from"../lib/platform.js";import{loadLearnState as ie,saveLearnState as ce,newLearnState as de,activateSession as ge,updateStreak as ue,markCardComplete as ye,recordMCQ as me,recordCheck as he,markPracticalComplete as pe,addAchievement as fe}from"../lib/learn-state.js";import{renderWelcome as be,renderKnowledgeCard as we,renderMCQCard as $e,renderMCQFeedback as ke,renderPracticalCard as ve,renderPracticalSuccess as Ae,renderSimDemoCard as Ce,renderMilestone as _e,renderArenaTaskCard as Te,renderComingSoonCard as xe,renderStatus as Ie,renderPhaseComplete as Ee,renderCurriculumComplete as Se,setLearnAiEnabled as Pe,setLearnFaqs as qe,setLearnHonorRanks as Me,setLearnPqsViewCards as Le,setLearnReplies as Ne,setLearnWidth as je,resolveLearnWidth as Re,learnWidthCap as We,learnW as Oe,renderHonorWall as De,wrapMixed as Ye}from"../lib/learn-render.js";import{printError as Ue}from"../lib/ui.js";const Fe=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(ze){ze.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ze=>{ze?.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(),ze="LEARNDEMO01");let Be=ze.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Be)){const{runSprint:e}=await import("./sprint.js");return void await e()}let He=null;const Ze=/^[A-Z0-9]+DEMO01$/i.test(Be),Je=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Be);let Ke=!1,Qe=!1,Ve=[],Xe=-1,Ge=Promise.resolve([]);if(Ze)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Ge=E(Be),He=await _(Be,Be,!0);else if(Je){console.log(),console.log(chalk.gray(" Validating token..."));let e=await T(Be);if(!e.ok){const o=Y(Be);if(o!==Be){const n=await T(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Be} → ${o}`)),e=n,Be=o)}}if(!e.ok)return Ue(`Token validation failed: ${e.message}`),console.log(),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${e.curriculumId} · status: ${e.status}`)+(!0===e.aiEnabled?chalk.bold.magenta(" · ⭐ AI Panda Tutor 🐼"):"")),Ke=!0===e.aiEnabled,Qe=!0===e.gated,Ve=e.replies??[],Ge=E(Be),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),He=await _(e.curriculumId||"LEARNDEMO01",Be,!0),!He)return Ue(`Could not open a learn curriculum for token '${Be}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Be}`)+chalk.gray(" instead.")),console.log(chalk.gray(" Otherwise: the full curriculum is ~3 MB; on a slow link the download")),console.log(chalk.gray(" can take a while — stay on a stable connection and run ")+chalk.bold.yellow(`learn ${Be}`)+chalk.gray(" again")),console.log(chalk.gray(" (it caches after the first load). If it keeps failing, check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()}if(!He){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Ue(`Could not reach the learn server to open ${Be}.`),console.log(),console.log(chalk.gray(" Your token may be perfectly fine — we could not ask.")),console.log(chalk.gray(" Check your connection, then run ")+chalk.bold.yellow(`learn ${Be}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Ue(`Unknown learn token: ${Be}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Most tracks have a free demo. From the ")+chalk.bold.green("learn")+chalk.gray(" menu you can type the track name itself")),console.log(chalk.gray(" (e.g. ")+chalk.bold.green("biology")+chalk.gray(", ")+chalk.bold.green("ioipy")+chalk.gray(") and it opens that track's demo if one is published.")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log())}let eo=ie(),oo=!1;try{if(eo&&eo.token===Be)ue(eo);else{const e=ge(Be);e?(eo=e,eo.totalCards=He.totalCards,ue(eo)):(eo=de(Be,He.id,He.totalCards),oo=!0)}ce(eo),be(He,eo,oo)}catch{return Ue("Could not open this curriculum — it may be malformed or not a learn curriculum."),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Be}`)+chalk.gray(".")),void console.log()}const no=a(),to=null!==no,ro=to?no.listeners("line").slice():[];to&&no.removeAllListeners("line");const lo=to?no:o({input:process.stdin,output:process.stdout,terminal:!0}),so=to?lo.prompt:null;to&&(lo.prompt=e.prototype.prompt);const ao=()=>{to&&so&&(lo.prompt=so)},io=()=>{lo.setPrompt(_o?chalk.bold.green(`icoa ${i()}> `):$o?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(bo?"icoa learn ai> ":"icoa learn> ")),lo.prompt()};let co=null,go=null,uo=null,yo=null,mo=[],ho=!1,po=null;const fo=()=>{po&&clearTimeout(po),po=null,mo=[],ho=!1,yo=null};let bo=!1,wo=!1,$o=!1,ko=null,vo=!1,Ao=0,Co=!1,_o=!1;const To=new Map,xo=()=>{let e=To.get(eo.currentCard);return e||(e=[],To.set(eo.currentCard,e)),e};let Io=!1;const Eo=new Set;let So=!1,Po=0;const qo=()=>(te().language||"en").toLowerCase().startsWith("zh");Pe(Ke),je(Re(te())),Le(Eo);const Mo=new Map;Me(Mo),Ne(Ve);const Lo=await Ge;qe(Lo);const No=[];let jo=null;const Ro=new Promise(e=>{jo=e}),Wo=()=>{const e=jo;jo=null,e?.()},Oo="1"===process.env.ICOA_LEARN_EMBEDDED,Do=e=>He.cards.find(o=>o.number===e);let Yo=null,Uo=null;const Fo=new Map,zo=!Be.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Be),Bo=async()=>{if(!zo)return;const e=await oe(Be);e.ok&&e.data&&(Yo=e.data)},Ho=e=>{const o=He.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Zo=e=>{if(!Qe||!Yo)return null;const o=Ho(e);if(o<=Yo.unlocked_through_phase)return null;const n=Yo.phases.find(e=>e.phase===Yo.unlocked_through_phase),t=[chalk.yellow(qo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${Yo.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${Yo.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(qo()?` ⚔ 练习赛 ${Yo.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${Yo.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(qo()?` ⚖ 判分赛: 最好 ${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(qo()?"、":", "),r=e.length>8?qo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:qo()?" 张":"";t.push(chalk.gray(qo()?` ✓ 逐卡自测: ${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(qo()?` ⭐ 提问研究: ${n.research.good_cards}/${n.research.need_cards} 卡达到 ${n.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${n.research.good_cards}/${n.research.need_cards} cards at ${n.research.min_score}+ — research with /ai, then /submit`)),t.join("\n")},Jo=async e=>Qe?null===Zo(e)?null:(await Bo(),Zo(e)):null;zo&&await Bo();const Ko=async e=>{const o=He.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=He.modules.find(e=>e.number===o.number+1);let t;if(Ke){const e=await U({token:Be,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}zo&&await Bo();const r=Yo?.phases.find(e=>e.phase===o.number);return Ee(He,eo,o,n,t,r),!0},Qo=()=>{So=!0,console.log(chalk.gray(qo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Vo=()=>{ko=null;const e=Do(eo.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":we(e,He),e.check?(uo=e.number,Po=Date.now()):(ye(eo,e.number),ce(eo));break;case"mcq":$e(e,He),co=e.number;break;case"practical":ve(e,He),go=e.number;break;case"sim_demo":Ce(e,He),ye(eo,e.number),ce(eo);break;case"milestone":_e(e,He),fe(eo,e.badge),ye(eo,e.number),ce(eo);break;case"arena_task":Te(e,He),ye(eo,e.number),ce(eo);break;case"coming_soon":xe(e,He),ye(eo,e.number),ce(eo)}Xo(e.number)},Xo=e=>{if(!zo||!Yo)return;const o=He.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=Yo.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?qo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Oe());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${qo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(qo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(qo()?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(qo()?`${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(qo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(qo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(qo()?"✍ 第一次用 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(qo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(qo()?"最好":"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(qo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(qo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(qo()?" 继续学习":" keep going"):chalk.gray(qo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(qo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Go=()=>{Be.endsWith("DEMO01")?console.log(chalk.yellow(qo()?" 🐼 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(qo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(qo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},en=async(e,o)=>{if(Ke){wo=!0;try{console.log(),console.log(chalk.gray("deep"===o?qo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":qo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await B({token:Be,cardNumber:eo.currentCard,question:e,mode:o,history:xo().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(qo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(xo().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(` (${qo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(qo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==uo&&console.log(chalk.gray(qo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{wo=!1}}else Go()},on=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],nn=async()=>{$o&&Uo?un?mn(un):cn():ko?await tn():Vo()},tn=async()=>{wo=!0;try{console.log();const e=await J({token:Be,curriculumId:He.id,cardNumber:eo.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(qo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(qo()?` 🏆 本卡实时 Top-3 — 第 ${eo.currentCard} 张`:` 🏆 Live top-3 — card ${eo.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(qo()?" (你)":" (you)"):""))}else console.log(chalk.gray(qo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Mo.set(eo.currentCard,e.mine.rank),console.log(chalk.white(qo()?" 你: ":" You: ")+chalk.bold.yellow(qo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(qo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Ke&&console.log(chalk.gray(qo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),De({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(qo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(qo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(qo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),ko="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(qo()?" 返回卡片":" returns to the card")),console.log()}finally{wo=!1}},rn=e=>qo()&&e.title_zh||e.title,ln=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of Ye(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},sn=e=>{console.log(),console.log(chalk.bold.green(qo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(qo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},an=e=>Uo.data.solved.includes(e.id)?"✅":Uo.data.carried?.includes(e.id)?"✅↗":Uo.tried.has(e.id)?"❌":"⬜",cn=()=>{const e=Uo.data,o=ne(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(qo()?` · 第 ${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(qo()?" ⏱ 已超时 — 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(qo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(qo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(qo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(qo()?" 带过来,不必重做":" 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(qo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(qo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(qo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(qo()?` 满血重开本组(${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)} `)+an(e)+chalk.white(` ${rn(e)}`))}),console.log(),dn()},dn=()=>{console.log(chalk.gray(qo()?" /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((qo()," "))+chalk.bold.green("/syntax <词>")+chalk.gray(qo()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(qo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(qo()?" 返回课程":" returns to the lesson")),console.log()},gn=e=>{const o=parseInt(e,10),n=Uo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(qo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let un=null,yn=!1;const mn=e=>{const o=gn(e);if(!o)return;const{p:n,n:t}=o;un=String(t),console.log(),console.log(chalk.bold.white(` ${an(n)} ${rn(n)}`)),console.log();for(const e of(e=>qo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of Ye(e,Oe()+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(qo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(qo()?" 应输出:":" 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(qo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(qo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(qo()?"写码(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(qo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(qo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(qo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray(qo()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(qo()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((qo()," ↩ "))+chalk.bold.green("back")+chalk.gray(qo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(qo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((qo()," / "))+chalk.bold.green("wide")+chalk.gray(qo()?" 换语言/宽度":" language / width")),console.log()},hn=async(e,o)=>await new Promise(n=>{const t=process.stdin,s=!!t.isTTY&&!!t.isRaw;if(lo.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const a=r(e,o,{stdio:"inherit",cwd:Uo.dir}),i=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&s)try{t.setRawMode(!0)}catch{}l(),lo.resume(),n(e)};a.on("close",()=>i(null)),a.on("error",e=>i(e))}),pn=()=>{console.log(chalk.yellow(qo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(qo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(qo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(qo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},fn=new Map,bn=async e=>{const o=e.trim().toLowerCase(),l=$o&&o.startsWith("/")?o.slice(1):o;if(wo)return;if(null!==yo){if(mo.push(e.replace(/\s+$/,"")),po&&clearTimeout(po),po=null,ho){const e=mo[mo.length-1]??"";return"/cancel"===e.trim()?(fo(),console.log(chalk.gray(qo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void io()):""!==e.trim()?void io():(mo.pop(),void await a())}return void(po=setTimeout(()=>{if(po=null,mo.length>1){ho=!0;const e=mo.length;return console.log(chalk.cyan(qo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(qo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void io()}a()},140))}async function a(){const e=mo.join("\n").replace(/^\s+|\s+$/g,""),o=yo??eo.currentCard,n=mo.length;if(fo(),""===e)console.log(chalk.gray(qo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(qo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(qo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(qo()?" 即可执行。":" again to run it."));else{const t=Po>0?Date.now()-Po:void 0;if(await I(Be,{curriculum_id:He.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const t=n>1?qo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(qo()?` ✓ 已收到${t},谢谢帮助完善这张卡。`:` ✓ Thanks ${t}— your report was recorded.`)),console.log(chalk.gray(qo()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),Ve=[...Ve,{id:Xe--,curriculumId:He.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Ne(Ve)}else console.log(chalk.yellow(qo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),io()}if(vo){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return vo=!1,console.log(),console.log(chalk.yellow(qo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(qo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(qo()?" 即可执行该命令。":" again to run it.")),console.log(),void io();if(!o)return vo=!1,console.log(chalk.gray(qo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void io();const n=await z({token:Be,nickname:o});if(n.ok)vo=!1,console.log(chalk.bold.green(qo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(qo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Ao+=1;const e="taken"===n.code?qo()?"已被占用":"already taken":"bad_charset"===n.code?qo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?qo()?"未通过审核":"did not pass review":n.message||"error";if(!(Ao>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(qo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void io();vo=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(qo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void io()}if(Io){Io=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{wo=!0;try{console.log(),console.log(chalk.gray(qo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await H({token:Be,cardNumber:eo.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(qo()?"评审暂不可用。":"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(qo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(qo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(qo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(qo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(qo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(qo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=qo()?` 本卡排名 #${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(qo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(qo()?` 第 ${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 on(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(qo()?" 改进提问: ":" 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(` (${qo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Eo.add(eo.currentCard):Eo.delete(eo.currentCard),"number"==typeof e.rank&&Mo.set(eo.currentCard,e.rank);const o=await J({token:Be,curriculumId:He.id,cardNumber:eo.currentCard});o.ok&&o.totals&&o.chapters&&(De({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Ze&&(vo=!0,Ao=0,console.log(chalk.bold.yellow(qo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(qo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(qo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{wo=!1}})():(console.log(chalk.gray(qo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==uo&&(console.log(chalk.gray(qo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void io()}if(So)return So=!1,Vo(),void io();if(!o)return void io();if(_o)return"exit"===await c(e.trim())&&(_o=!1),void io();if(bo){if(["q","quit","exit","back","b","menu"].includes(o))return bo=!1,console.log(chalk.gray(qo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void io();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim(),r=/^(\/?(submit|read|edit|run|debug|list|honors|recall|view|ai|syntax|contest)\b\s*\d*|card\s+\d+|\d+|status|bookmark|unbookmark|reload|link|wide|wider|normal|narrow|next|ok|y|n|yes|no|menu|lang(\s+\S+)?)$/i.exec(t),l=t.length>0&&!/[\p{L}\p{N}]/u.test(t);return r||l?(console.log(),console.log(chalk.yellow(qo()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?qo()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":qo()?`「${t}」是卡片命令,不是问题,没有送出去。`:`“${t}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(qo()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(qo()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void io()):(t&&(await en(t,n?"fast":"deep"),console.log(chalk.gray(qo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void io())}if($o&&Uo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${Uo.phase}s${Uo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return $o=!1,console.log(chalk.gray(qo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Vo(),void io();if(/^\d+$/.test(o))return mn(o),void io();const t=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(t)return await(async e=>{const o=e.trim();if(await M()||yn||(yn=!0,console.log(chalk.gray(qo()?` (离线:只有 ${D()} 条核心速查可用;联网后自动补全)`:` (offline: ${D()} core entries available; the rest arrive when you have a connection)`))),!o)return void R(qo());const n=N(o);if(n.length){O(n[0],qo());const e=n.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(qo()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const t=await L("python3",o);t?W(t,qo()):(console.log(),console.log(chalk.yellow(qo()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(qo()?" 试试: ":" Try: ")+chalk.cyan(j(o).join(" · "))),console.log(chalk.gray(qo()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log())})(t[1]??""),void io();const r=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(r){const[,e,o]=r;return"list"===e?cn():o?"read"===e||"open"===e?mn(o):"edit"===e?await(async e=>{const o=gn(e);if(!o)return;const n=A(Uo.dir,`sol-${o.n}.py`);if(le())return se()?(console.log(chalk.yellow(qo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(qo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(qo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(qo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(qo()?" ← 不能是 /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(qo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(qo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(qo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(qo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(qo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(qo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(qo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(qo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!ae("vi"))return console.log(chalk.yellow(qo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(qo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(qo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return p(e).size}catch{return 0}},r=t(n),l=Date.now();await hn("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),Fo.set(o.n,w(Fo.get(o.n)??b(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(qo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(qo()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=gn(e);if(!o)return;const{p:t,n:r}=o,l=A(Uo.dir,`sol-${r}.py`);if(!g(l))return void console.log(chalk.yellow(qo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Fo.set(r,k(Fo.get(r)??b()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(qo()?` 本题无样例(设计如此)— 用 /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)pn();else if(o.killed)console.log(chalk.yellow(qo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(qo()?" ✗ 程序报错:":" ✗ 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(qo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(qo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(qo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(qo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(qo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(qo()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=gn(e);if(!o)return;const n=A(Uo.dir,`sol-${o.n}.py`);if(!g(n))return void console.log(chalk.yellow(qo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(qo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 hn("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(qo()?" 回到竞技场。":" Back in the arena.")),console.log()):pn()})(o):"recall"===e&&await(async e=>{const o=gn(e);if(!o)return;if(!Ke)return void Go();const{p:n,n:t}=o,r=A(process.cwd(),"icoa-contest"),l=`${He.id}-phase${Uo.phase}-g${Uo.data.slot}-archived-`;let s=null;try{for(const e of y(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?A(r,s,`sol-${t}.py`):null;if(!a||!g(a))return void console.log(chalk.gray(qo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${Uo.phase}-${Uo.data.slot}-${t}`,d=Math.min(3,(fn.get(c)??0)+1);console.log(chalk.gray(qo()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const u=await F({token:Be,phase:Uo.phase,slot:Uo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:d,lang:qo()?"zh":"en"});if(u.ok){fn.set(c,d),console.log();for(const e of Ye(u.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(qo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(qo()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===u.code?console.log(chalk.yellow(qo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${u.message}`)):console.log(chalk.yellow(` ${u.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(qo()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(qo()?" (花名册: /list)":" (roster: /list)")),void io()}if("contest"===o||"/contest"===o)return cn(),void io();const a="lang"===o||/^lang\s+\S+$/.test(o),i=Fe.has(o);if(!("submit"===l||l.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||a||i||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(qo()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void io()}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(qo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void io()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(lo.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{}lo.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void io()}if("ai4ioai"===o||"/ai4ioai"===o)return await d()&&(_o=!0),void io();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Ke)return Go(),void io();Co||(Co=!0,console.log(),console.log(chalk.bold.cyan(qo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(qo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(qo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),qo()||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){bo=!0;const e=Do(eo.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(qo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(qo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(qo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void io()}return await en(t,n?"fast":"deep"),void io()}if(!$o&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Ke)return Go(),void io();const e=Do(eo.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(qo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(qo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(qo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(qo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(qo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(qo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(qo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Io=!0,void io()}const i=!$o&&"honors"===ko&&/^[1-3]$/.test(o);if(!$o&&ko&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(qo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(qo()?" ↩ back 回上一层":" ↩ back goes up one level")),void io();if(!$o&&(i||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Ke)return Go(),void io();const e=/^\/?view ([1-3])$/.exec(o),n=i?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{wo=!0;try{console.log();const o=await Z({token:Be,cardNumber:eo.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(qo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Eo.delete(eo.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Eo.add(eo.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(qo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${eo.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${eo.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(qo()?` (第 ${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(qo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=on(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(qo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),ko="view",console.log(chalk.gray((qo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(qo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{wo=!1}})(n),void io()}if("/honors"===o||"honors"===o)return Ze?(console.log(),console.log(chalk.gray(qo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void io()):(await tn(),void io());if("menu"===o||"menu confirm"===o){if(No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,3e3))]),lo.removeAllListeners("line"),ao(),to||!Oo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(to?lo:void 0),Wo()}else lo.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===ko)return await tn(),void io();if("honors"===ko)return ko=null,Vo(),void io();if(No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${eo.streakDays} day(s)`)),console.log(),to){lo.removeAllListeners("line"),ao();for(const e of ro)lo.on("line",e);lo.prompt(),Wo()}else lo.removeAllListeners("line"),lo.close();return}if("status"===o)return Ie(He,eo),void io();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await _(He.id,Be,!0);return void(e?(Object.assign(He,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Vo()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本")),io()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(te().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void io();const n=He.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 re({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),uo=null,co=null,go=null,fo(),So=!1,Io=!1,await nn(),void io()}if(Fe.has(o)){const e=Fe.get(o),n=Re(te()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return qo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((qo()?"normal"===e?" 已是标准 64 列。":Oe()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Oe()} 列,上限 ${We(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Oe()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Oe()} cols, cap ${We(e)}). `)+t(e))),void io()):(re({learnWidth:e,learnWide:"normal"!==e}),je(e),"normal"!==e&&Oe()<=64?(console.log(chalk.yellow(qo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((qo()?` 设置已记住(${e},上限 ${We(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${We(e)} cols) and applies once you widen the window. `)+t(e))),void io()):(console.log(chalk.green(" ✓ ")+chalk.gray((qo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Oe()} 列,上限 ${We(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Oe()} cols, cap ${We(e)}). `)+t(e))),uo=null,co=null,go=null,fo(),So=!1,Io=!1,await nn(),void io()))}if("sim"===o){const e=Do(eo.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=v(C(import.meta.url)),o=[A(e,"..","..","panda","mujoco-launcher.py"),A(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(g(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 io()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void io())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=eo.currentCard,n=eo.bookmarks.includes(e),t="bookmark"!==o;return t?eo.bookmarks=eo.bookmarks.filter(o=>o!==e):n||eo.bookmarks.push(e),ce(eo),t?console.log(n?chalk.gray(qo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(qo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(qo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(qo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void io()}const T=S(o);if(T){const e="current"===T.target?eo.currentCard:T.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>He.cards.length))return console.log(chalk.yellow(qo()?` 本课共 ${He.cards.length} 张,请输 r 1–${He.cards.length} 或 r all。`:` This course has ${He.cards.length} cards. Try r 1–${He.cards.length} or r all.`)),console.log(),void io();for(const o of P(Ve,Lo,e,qo(),Oe()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?Ve:Ve.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(Ve=Ve.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Ne(Ve),No.push(x(Be,{card_number:eo.currentCard,event_type:"viewed"},o).catch(()=>{}))),void io()}if("e"===o)return yo=eo.currentCard,console.log(chalk.gray(qo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void io();if("back"===o||"b"===o)return"view"===ko?(await tn(),void io()):"honors"===ko?(ko=null,Vo(),void io()):(eo.currentCard>1&&(eo.currentCard-=1),co=null,go=null,uo=null,ce(eo),Vo(),void io());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!zo)return console.log(chalk.yellow(qo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void io();if(!e){const e=await G(Be),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(qo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(qo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(qo()?` 这台电脑上有 ${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(qo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(qo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(qo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(qo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(qo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(qo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(qo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void io()}if(/^\d{1,2}$/.test(e)){const o=await X(Be,Number(e));return o.ok&&o.data?(sn(o.data),await Bo(),void io()):(console.log(chalk.red(` ✗ ${o.message||(qo()?"关联失败":"Link failed")}`)),void io())}const n=await ee(Be,e);return n.ok&&n.data?(sn(n.data),await Bo(),void io()):(console.log(chalk.red(` ✗ ${n.message||(qo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(qo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void io())}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(!zo)return console.log(chalk.yellow(qo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void io();const e=Ho(eo.currentCard);if("contest reset"===o){const o=await K(Be,e);if(o.ok){console.log(chalk.yellow(qo()?` 已放弃当前计时(阶段 ${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=A(process.cwd(),"icoa-contest",`${He.id}-phase${e}-g${n}`);if(g(t))try{h(t,`${t}-archived-${o}`),console.log(chalk.gray(qo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(qo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(qo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),Uo=null,$o=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void io()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(qo()?" 连接判分赛…":" Contacting contest server…"));const t=await Q(Be,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(qo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void io();const r=t.data,l=A(process.cwd(),"icoa-contest",`${He.id}-phase${e}-g${r.slot}`);u(l,{recursive:!0});const s=Uo&&Uo.phase===e&&Uo.data.slot===r.slot?Uo.tried:new Set;Uo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.samples??[])[0];l&&f(A(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=A(o,`sol-${r}.py`);if(g(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${n.title} ══`,"#",...ln(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`,"",""),f(s,a.join("\n"))})})(r,l),$o=!0,cn(),console.log(chalk.gray(qo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(qo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(qo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void io()}if("submit"===l)return console.log(chalk.yellow(qo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(qo()?" 例如 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)")),Uo||console.log(chalk.gray(qo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void io();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const n=e[2];if(!Uo)return console.log(chalk.yellow(qo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void io();const t=Uo.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(qo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void io();const s=t.findIndex(e=>e.id===o)+1,a=n||A(Uo.dir,`sol-${s}.py`);let i;try{i=m(a,"utf-8")}catch{return console.log(chalk.red(qo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void io()}console.log(chalk.gray(qo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Fo.get(s),d=await V(Be,Uo.phase,o,i,void 0,c&&!$(c)?c:void 0);if(!d.ok||!d.data)return"no_active_session"===d.code?console.log(chalk.yellow(qo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((qo()," "))+chalk.bold.green("contest")+chalk.gray(qo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(qo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void io();const g=d.data;if(g.already_ac)console.log(chalk.green(qo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(qo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(qo()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),Uo.data.solved.includes(o)||Uo.data.solved.push(o),Uo.tried.delete(o);else{Uo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?qo()?` · 挂在第 ${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(qo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=ne(g.deadline||"");if(console.log(chalk.white(qo()?` 本组进度: 已过 ${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(qo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Bo();else if(!g.late){const e=t.findIndex(e=>!Uo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(qo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${rn(t[e])}`))}return void io()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>He.totalCards)return console.log(chalk.yellow(` Card number must be 1..${He.totalCards}. Try: `)+chalk.bold.green("card 1")),void io();const t=await Jo(n);return t?(console.log(t),void io()):(eo.currentCard=n,co=null,go=null,uo=null,ce(eo),Vo(),void io())}if(null!==uo&&["y","yes","n","no"].includes(o)){const e=Do(uo);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-Po;ye(eo,e.number),he(eo,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),ce(eo);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),No.push(x(Be,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),uo=null,e.solution&&e.solution.length>0)return void io();if(eo.currentCard<He.totalCards){const e=eo.currentCard,o=await Jo(e+1);if(o)return await Ko(e),console.log(o),void io();eo.currentCard+=1,ce(eo),await Ko(e)?Qo():Vo(),io()}else Se(He,eo),io();return}}if(null!==co&&["a","b","c","d"].includes(o)){const e=Do(co);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(me(eo,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),ye(eo,e.number),ce(eo),ke(e,n,t,eo),No.push(x(Be,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),co=null,t)if(eo.currentCard<He.totalCards){const e=await Jo(eo.currentCard+1);if(e)return console.log(e),void io();eo.currentCard+=1,ce(eo),Vo()}else Se(He,eo),io();else io();return}}if(null!==go){if("done"===o){const e=Do(go);if(e&&"practical"===e.type)return pe(eo,e.number),ye(eo,e.number),ce(eo),Ae(e),go=null,void io()}if("skip"===o)return ye(eo,go),ce(eo),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),go=null,void io()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==co)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void io();if(null!==go)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void io();if(null!==uo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void io();const e=eo.currentCard,o=e<He.totalCards?await Jo(e+1):null;return o?(await Ko(e),console.log(o),void io()):(eo.currentCard+=1,ce(eo),eo.currentCard>He.totalCards?Se(He,eo):await Ko(e)?Qo():Vo(),void io())}return null!==uo?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void io()):null!==co?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void io()):null!==go?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void io()):("view"===ko?console.log(chalk.gray(qo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(qo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(qo()?" 回卡片":" to the card")):"honors"===ko?console.log(chalk.gray(qo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(qo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(qo()?" 回卡片":" to the card")):console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("/ai")+chalk.gray(" / ")+chalk.white("quit")),void io())};lo.on("line",e=>{bn(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.")),io()})}),to||lo.on("close",async()=>{No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,5e3))]),Oo?Wo():process.exit(0)});const wn=q(Ve,qo());wn&&(console.log(chalk.bold.cyan(` ${wn}`)),console.log());try{Vo(),io();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Ue("Could not render this card — the curriculum may be malformed."),to){lo.removeAllListeners("line"),ao();for(const e of ro)lo.on("line",e);lo.prompt()}else lo.close();Wo()}await Ro}),ze.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await _(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as n,execSync as t,spawn as r}from"node:child_process";import{rearmFocusMode as l}from"../lib/input-dynamics.js";import{logCommand as s}from"../lib/logger.js";import{getMainRl as a}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as i,handleAi4ioaiMessage as c,startAi4ioaiChat as d}from"./ai4ioai.js";import{existsSync as g,mkdirSync as u,readdirSync as y,readFileSync as m,renameSync as h,statSync as p,writeFileSync as f}from"node:fs";import{emptyDynamics as b,foldEditSession as w,isEmpty as $,noteRun as k}from"../lib/arena-edit-dynamics.js";import{dirname as v,join as A}from"node:path";import{fileURLToPath as C}from"node:url";import{loadCurriculumById as _,validateEAToken as T,syncProgress as x,syncCardFeedback as I,fetchCardFaqs as E}from"../lib/learn-curricula.js";import{parseReplyCommand as S,renderReplyLines as P,replyPushLine as q}from"../lib/learn-replies.js";import{ensureFullTable as M,lookupPydoc as L,lookupRanked as N,nearKeys as j,renderIndex as R,renderPydoc as W,renderSyntax as O,tableSize as D}from"../lib/py-syntax.js";import{normalizeTokenBody as Y}from"../lib/token-format.js";import{fetchMyScores as U,recallCoach as F,setNickname as z,streamLearnTutor as B,submitPqs as H,viewPqsTop as Z,viewHonors as J}from"../lib/learn-ai.js";import{contestReset as K,contestStart as Q,contestSubmit as V,linkByIndex as X,linkSuggest as G,linkToken as ee,fetchGate as oe,timeLeft as ne}from"../lib/learn-contest.js";import{getConfig as te,saveConfig as re}from"../lib/config.js";import{isNativeWindows as le,isWindowsBuildInWslShell as se,whichBinary as ae}from"../lib/platform.js";import{loadLearnState as ie,saveLearnState as ce,newLearnState as de,activateSession as ge,updateStreak as ue,markCardComplete as ye,recordMCQ as me,recordCheck as he,markPracticalComplete as pe,addAchievement as fe}from"../lib/learn-state.js";import{renderWelcome as be,renderKnowledgeCard as we,renderMCQCard as $e,renderMCQFeedback as ke,renderPracticalCard as ve,renderPracticalSuccess as Ae,renderSimDemoCard as Ce,renderMilestone as _e,renderArenaTaskCard as Te,renderComingSoonCard as xe,renderStatus as Ie,renderPhaseComplete as Ee,renderCurriculumComplete as Se,setLearnAiEnabled as Pe,setLearnFaqs as qe,setLearnHonorRanks as Me,setLearnPqsViewCards as Le,setLearnReplies as Ne,setLearnWidth as je,resolveLearnWidth as Re,learnWidthCap as We,learnW as Oe,renderHonorWall as De,wrapMixed as Ye}from"../lib/learn-render.js";import{printError as Ue}from"../lib/ui.js";const Fe=new Map([["normal","normal"],["narrow","normal"],["wide off","normal"],["wide","wide"],["wide on","wide"],["wider","wider"],["widest","wider"],["wide max","wider"]]);export function registerLearnCommand(ze){ze.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ze=>{ze?.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(),ze="LEARNDEMO01");let Be=ze.trim().toUpperCase();if(/^PANDA\s*HELP\s*ME\s*31$/.test(Be)){const{runSprint:e}=await import("./sprint.js");return void await e()}let He=null;const Ze=/^[A-Z0-9]+DEMO01$/i.test(Be),Je=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Be);let Ke=!1,Qe=!1,Ve=[],Xe=-1,Ge=Promise.resolve([]);if(Ze)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Ge=E(Be),He=await _(Be,Be,!0);else if(Je){console.log(),console.log(chalk.gray(" Validating token..."));let e=await T(Be);if(!e.ok){const o=Y(Be);if(o!==Be){const n=await T(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Be} → ${o}`)),e=n,Be=o)}}if(!e.ok)return Ue(`Token validation failed: ${e.message}`),console.log(),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${e.curriculumId} · status: ${e.status}`)+(!0===e.aiEnabled?chalk.bold.magenta(" · ⭐ AI Panda Tutor 🐼"):"")),Ke=!0===e.aiEnabled,Qe=!0===e.gated,Ve=e.replies??[],Ge=E(Be),console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),He=await _(e.curriculumId||"LEARNDEMO01",Be,!0),!He)return Ue(`Could not open a learn curriculum for token '${Be}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Be}`)+chalk.gray(" instead.")),console.log(chalk.gray(" Otherwise: the full curriculum is ~3 MB; on a slow link the download")),console.log(chalk.gray(" can take a while — stay on a stable connection and run ")+chalk.bold.yellow(`learn ${Be}`)+chalk.gray(" again")),console.log(chalk.gray(" (it caches after the first load). If it keeps failing, check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()}if(!He){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(Ue(`Could not reach the learn server to open ${Be}.`),console.log(),console.log(chalk.gray(" Your token may be perfectly fine — we could not ask.")),console.log(chalk.gray(" Check your connection, then run ")+chalk.bold.yellow(`learn ${Be}`)+chalk.gray(" again.")),console.log(chalk.gray(" Still failing? Check ")+chalk.cyan("https://practice.icoa2026.au")+chalk.gray(" is reachable.")),void console.log()):(Ue(`Unknown learn token: ${Be}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Most tracks have a free demo. From the ")+chalk.bold.green("learn")+chalk.gray(" menu you can type the track name itself")),console.log(chalk.gray(" (e.g. ")+chalk.bold.green("biology")+chalk.gray(", ")+chalk.bold.green("ioipy")+chalk.gray(") and it opens that track's demo if one is published.")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log())}let eo=ie(),oo=!1;try{if(eo&&eo.token===Be)ue(eo);else{const e=ge(Be);e?(eo=e,eo.totalCards=He.totalCards,ue(eo)):(eo=de(Be,He.id,He.totalCards),oo=!0)}ce(eo),be(He,eo,oo)}catch{return Ue("Could not open this curriculum — it may be malformed or not a learn curriculum."),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Be}`)+chalk.gray(".")),void console.log()}const no=a(),to=null!==no,ro=to?no.listeners("line").slice():[];to&&no.removeAllListeners("line");const lo=to?no:o({input:process.stdin,output:process.stdout,terminal:!0}),so=to?lo.prompt:null;to&&(lo.prompt=e.prototype.prompt);const ao=()=>{to&&so&&(lo.prompt=so)},io=()=>{lo.setPrompt(_o?chalk.bold.green(`icoa ${i()}> `):$o?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(bo?"icoa learn ai> ":"icoa learn> ")),lo.prompt()};let co=null,go=null,uo=null,yo=null,mo=[],ho=!1,po=null;const fo=()=>{po&&clearTimeout(po),po=null,mo=[],ho=!1,yo=null};let bo=!1,wo=!1,$o=!1,ko=null,vo=!1,Ao=0,Co=!1,_o=!1;const To=new Map,xo=()=>{let e=To.get(eo.currentCard);return e||(e=[],To.set(eo.currentCard,e)),e};let Io=!1;const Eo=new Set;let So=!1,Po=0;const qo=()=>(te().language||"en").toLowerCase().startsWith("zh");Pe(Ke),je(Re(te())),Le(Eo);const Mo=new Map;Me(Mo),Ne(Ve);const Lo=await Ge;qe(Lo);const No=[];let jo=null;const Ro=new Promise(e=>{jo=e}),Wo=()=>{const e=jo;jo=null,e?.()},Oo="1"===process.env.ICOA_LEARN_EMBEDDED,Do=e=>He.cards.find(o=>o.number===e);let Yo=null,Uo=null;const Fo=new Map,zo=!Be.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Be),Bo=async()=>{if(!zo)return;const e=await oe(Be);e.ok&&e.data&&(Yo=e.data)},Ho=e=>{const o=He.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},Zo=e=>{if(!Qe||!Yo)return null;const o=Ho(e);if(o<=Yo.unlocked_through_phase)return null;const n=Yo.phases.find(e=>e.phase===Yo.unlocked_through_phase),t=[chalk.yellow(qo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${Yo.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${Yo.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(qo()?` ⚔ 练习赛 ${Yo.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${Yo.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(qo()?` ⚖ 判分赛: 最好 ${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(qo()?"、":", "),r=e.length>8?qo()?`… 共 ${e.length} 张`:` … (${e.length} cards)`:qo()?" 张":"";t.push(chalk.gray(qo()?` ✓ 逐卡自测: ${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(qo()?` ⭐ 提问研究: ${n.research.good_cards}/${n.research.need_cards} 卡达到 ${n.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${n.research.good_cards}/${n.research.need_cards} cards at ${n.research.min_score}+ — research with /ai, then /submit`)),t.join("\n")},Jo=async e=>Qe?null===Zo(e)?null:(await Bo(),Zo(e)):null;zo&&await Bo();const Ko=async e=>{const o=He.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=He.modules.find(e=>e.number===o.number+1);let t;if(Ke){const e=await U({token:Be,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));t=e.ok?e.scores??[]:void 0}zo&&await Bo();const r=Yo?.phases.find(e=>e.phase===o.number);return Ee(He,eo,o,n,t,r),!0},Qo=()=>{So=!0,console.log(chalk.gray(qo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Vo=()=>{ko=null;const e=Do(eo.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":we(e,He),e.check?(uo=e.number,Po=Date.now()):(ye(eo,e.number),ce(eo));break;case"mcq":$e(e,He),co=e.number;break;case"practical":ve(e,He),go=e.number;break;case"sim_demo":Ce(e,He),ye(eo,e.number),ce(eo);break;case"milestone":_e(e,He),fe(eo,e.badge),ye(eo,e.number),ce(eo);break;case"arena_task":Te(e,He),ye(eo,e.number),ce(eo);break;case"coming_soon":xe(e,He),ye(eo,e.number),ce(eo)}Xo(e.number)},Xo=e=>{if(!zo||!Yo)return;const o=He.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=Yo.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?qo()?` · 用时 ${r}`:` · in ${r}`:"")+(s?` · ${s}`:"")},a=l.perfect_runs??[],i=!!l.best&&(l.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(Oe());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${qo()?`练习赛 ${o.number}-${t}`:l.title||`PY Arena ${o.number}-${t}`}`)+(l.passed?chalk.bold.green(qo()?" ✅ 已通过":" ✅ passed"):"")),l.passed||(qo()?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(qo()?`${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(qo()?`🔗 你另一个 token 已做过这组的 ${l.carryable_ac} 道 — 输入 `:`🔗 Another of your tokens solved ${l.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(qo()?" 带过来(现在不做也行)":" to carry them over (or skip)")),1===o.number&&console.log(c+chalk.gray(qo()?"✍ 第一次用 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(qo()?"满分":"Perfect",l.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(qo()?"最好":"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(qo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(qo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(l.passed?chalk.gray(qo()?" 继续学习":" keep going"):chalk.gray(qo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(qo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},Go=()=>{Be.endsWith("DEMO01")?console.log(chalk.yellow(qo()?" 🐼 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(qo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(qo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},en=async(e,o)=>{if(Ke){wo=!0;try{console.log(),console.log(chalk.gray("deep"===o?qo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":qo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let n=!1,t=!1;const r=await B({token:Be,cardNumber:eo.currentCard,question:e,mode:o,history:xo().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(qo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(xo().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(` (${qo()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(qo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==uo&&console.log(chalk.gray(qo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{wo=!1}}else Go()},on=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],nn=async()=>{$o&&Uo?un?mn(un):cn():ko?await tn():Vo()},tn=async()=>{wo=!0;try{console.log();const e=await J({token:Be,curriculumId:He.id,cardNumber:eo.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(qo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(qo()?` 🏆 本卡实时 Top-3 — 第 ${eo.currentCard} 张`:` 🏆 Live top-3 — card ${eo.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(qo()?" (你)":" (you)"):""))}else console.log(chalk.gray(qo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Mo.set(eo.currentCard,e.mine.rank),console.log(chalk.white(qo()?" 你: ":" You: ")+chalk.bold.yellow(qo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(qo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):Ke&&console.log(chalk.gray(qo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),De({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(qo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(qo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(qo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),ko="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(qo()?" 返回卡片":" returns to the card")),console.log()}finally{wo=!1}},rn=e=>qo()&&e.title_zh||e.title,ln=(e,o)=>{const n=[];for(const t of e.split("\n"))if(t.trim())for(const e of Ye(t,o))n.push(e.trim()?`# ${e}`:"#");else n.push("#");return n},sn=e=>{console.log(),console.log(chalk.bold.green(qo()?" 🔗 已关联 — 成绩从现在起互通":" 🔗 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(qo()?" 同一道题在另一赛道做过 → 花名册显示 ✅↗,不必重做。解除关联请联系协调员。":" A problem solved on the other track shows ✅↗ here — no redo. Unlinking is coordinator-side.")),console.log()},an=e=>Uo.data.solved.includes(e.id)?"✅":Uo.data.carried?.includes(e.id)?"✅↗":Uo.tried.has(e.id)?"❌":"⬜",cn=()=>{const e=Uo.data,o=ne(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(qo()?` · 第 ${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(qo()?" ⏱ 已超时 — 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(qo()?`(共 ${e.n} 题)`:` (of ${e.n})`)),n.length>0&&console.log(chalk.cyan(` ✅↗ ${n.length}`)+chalk.gray(qo()?" 题已在你关联的其他赛道做过 — 成绩带过来了,不必重做":" already solved on a token you linked — carried over, no need to redo")),(e.carryable_ac??0)>0&&console.log(chalk.cyan(qo()?` 🔗 你另一个 token 已做过其中 ${e.carryable_ac} 道 — 输入 `:` 🔗 Another of your tokens solved ${e.carryable_ac} of these — type `)+chalk.bold.green("link")+chalk.cyan(qo()?" 带过来,不必重做":" 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(qo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(qo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(qo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(qo()?` 满血重开本组(${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)} `)+an(e)+chalk.white(` ${rn(e)}`))}),console.log(),dn()},dn=()=>{console.log(chalk.gray(qo()?" /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((qo()," "))+chalk.bold.green("/syntax <词>")+chalk.gray(qo()?" 查 Python 语法(本机文档 · 不联网 · 不给解法)— 不用离开赛场":" Python syntax from your own docs (offline · never a solution) — no need to leave the arena")),console.log(chalk.gray(qo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(qo()?" 返回课程":" returns to the lesson")),console.log()},gn=e=>{const o=parseInt(e,10),n=Uo.data.problems;return!Number.isInteger(o)||o<1||o>n.length?(console.log(chalk.yellow(qo()?` 题号要在 1..${n.length}。`:` Problem number must be 1..${n.length}.`)),null):{p:n[o-1],n:o}};let un=null,yn=!1;const mn=e=>{const o=gn(e);if(!o)return;const{p:n,n:t}=o;un=String(t),console.log(),console.log(chalk.bold.white(` ${an(n)} ${rn(n)}`)),console.log();for(const e of(e=>qo()&&e.statement_zh||e.statement)(n).split("\n"))if(e.trim())for(const o of Ye(e,Oe()+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(qo()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(qo()?" 应输出:":" 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(qo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(qo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${t}`.padEnd(11))+chalk.gray(qo()?"写码(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(qo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${t}`.padEnd(11))+chalk.gray(qo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${t}`.padEnd(11))+chalk.gray(qo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray(qo()?" 忘了语法? ":" Forgot the syntax? ")+chalk.bold.green("/syntax del")+chalk.gray(" · ")+chalk.bold.green("/syntax list.pop")+chalk.gray(qo()?" (本机文档,不给解法)":" (your own docs — never a solution)")),console.log(),console.log(chalk.gray((qo()," ↩ "))+chalk.bold.green("back")+chalk.gray(qo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(qo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((qo()," / "))+chalk.bold.green("wide")+chalk.gray(qo()?" 换语言/宽度":" language / width")),console.log()},hn=async(e,o)=>await new Promise(n=>{const t=process.stdin,s=!!t.isTTY&&!!t.isRaw;if(lo.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const a=r(e,o,{stdio:"inherit",cwd:Uo.dir}),i=e=>{if(t.isTTY&&"function"==typeof t.setRawMode&&s)try{t.setRawMode(!0)}catch{}l(),lo.resume(),n(e)};a.on("close",()=>i(null)),a.on("error",e=>i(e))}),pn=()=>{console.log(chalk.yellow(qo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(qo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(qo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(qo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},fn=new Map,bn=async e=>{const o=e.trim().toLowerCase(),l=$o&&o.startsWith("/")?o.slice(1):o;if(wo)return;if(null!==yo){if(mo.push(e.replace(/\s+$/,"")),po&&clearTimeout(po),po=null,ho){const e=mo[mo.length-1]??"";return"/cancel"===e.trim()?(fo(),console.log(chalk.gray(qo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void io()):""!==e.trim()?void io():(mo.pop(),void await a())}return void(po=setTimeout(()=>{if(po=null,mo.length>1){ho=!0;const e=mo.length;return console.log(chalk.cyan(qo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(qo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void io()}a()},140))}async function a(){const e=mo.join("\n").replace(/^\s+|\s+$/g,""),o=yo??eo.currentCard,n=mo.length;if(fo(),""===e)console.log(chalk.gray(qo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===n&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(qo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(qo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(qo()?" 即可执行。":" again to run it."));else{const t=Po>0?Date.now()-Po:void 0;if(await I(Be,{curriculum_id:He.id,card_number:o,feedback_text:e,time_on_card_ms:t})){const t=n>1?qo()?`(${n} 行) `:`(${n} lines) `:"";console.log(chalk.green(qo()?` ✓ 已收到${t},谢谢帮助完善这张卡。`:` ✓ Thanks ${t}— your report was recorded.`)),console.log(chalk.gray(qo()?" 有回复会出现在这张卡的 r 里(不保证每条都回)。":" Any reply will show up under r on this card (not every report gets one).")),Ve=[...Ve,{id:Xe--,curriculumId:He.id,cardNumber:o,myText:e,sentAt:(new Date).toISOString(),replyText:void 0,repliedBy:void 0,repliedAt:void 0,seen:!1}],Ne(Ve)}else console.log(chalk.yellow(qo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),io()}if(vo){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return vo=!1,console.log(),console.log(chalk.yellow(qo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(qo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(qo()?" 即可执行该命令。":" again to run it.")),console.log(),void io();if(!o)return vo=!1,console.log(chalk.gray(qo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void io();const n=await z({token:Be,nickname:o});if(n.ok)vo=!1,console.log(chalk.bold.green(qo()?` ✓ 竞技昵称已设定: ${n.nickname}`:` ✓ Nickname set: ${n.nickname}`)+chalk.gray(qo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Ao+=1;const e="taken"===n.code?qo()?"已被占用":"already taken":"bad_charset"===n.code?qo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===n.code?qo()?"未通过审核":"did not pass review":n.message||"error";if(!(Ao>=3||"judge_unavailable"===n.code||"already_set"===n.code||"not_on_board"===n.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(qo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void io();vo=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(qo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void io()}if(Io){Io=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{wo=!0;try{console.log(),console.log(chalk.gray(qo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await H({token:Be,cardNumber:eo.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(qo()?"评审暂不可用。":"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(qo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(qo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(qo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(qo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(qo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(qo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=qo()?` 本卡排名 #${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(qo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(qo()?` 第 ${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 on(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(qo()?" 改进提问: ":" 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(` (${qo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Eo.add(eo.currentCard):Eo.delete(eo.currentCard),"number"==typeof e.rank&&Mo.set(eo.currentCard,e.rank);const o=await J({token:Be,curriculumId:He.id,cardNumber:eo.currentCard});o.ok&&o.totals&&o.chapters&&(De({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!Ze&&(vo=!0,Ao=0,console.log(chalk.bold.yellow(qo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(qo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(qo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{wo=!1}})():(console.log(chalk.gray(qo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==uo&&(console.log(chalk.gray(qo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void io()}if(So)return So=!1,Vo(),void io();if(!o)return void io();if(_o)return"exit"===await c(e.trim())&&(_o=!1),void io();if(bo){if(["q","quit","exit","back","b","menu"].includes(o))return bo=!1,console.log(chalk.gray(qo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void io();const n=e.trim().startsWith("!"),t=n?e.trim().slice(1).trim():e.trim(),r=/^(\/?(submit|read|edit|run|debug|list|honors|recall|view|ai|syntax|contest)\b\s*\d*|card\s+\d+|\d+|status|bookmark|unbookmark|reload|link|wide|wider|normal|narrow|next|ok|y|n|yes|no|menu|lang(\s+\S+)?)$/i.exec(t),l=t.length>0&&!/[\p{L}\p{N}]/u.test(t);return r||l?(console.log(),console.log(chalk.yellow(qo()?" 你还在 🐼 AI 导师里 — ":" You are still inside the 🐼 AI tutor — ")+chalk.gray(l?qo()?"这行没有内容,没有送出去。":"that line had no content, so nothing was sent.":qo()?`「${t}」是卡片命令,不是问题,没有送出去。`:`“${t}” is a card command, not a question — nothing was sent.`)),console.log(chalk.gray(qo()?" 先输 ":" Type ")+chalk.bold.green("q")+chalk.gray(qo()?" 回到卡片,再敲它。":" to go back to the card, then run it there.")),console.log(),void io()):(t&&(await en(t,n?"fast":"deep"),console.log(chalk.gray(qo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void io())}if($o&&Uo){if(/^(\/?(read|open|edit|run|debug|list|submit|recall|syntax|syn)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&s(`learn-arena p${Uo.phase}s${Uo.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return $o=!1,console.log(chalk.gray(qo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),Vo(),void io();if(/^\d+$/.test(o))return mn(o),void io();const t=/^\/?(?:syntax|syn)\b\s*(.*)$/i.exec(e.trim());if(t)return await(async e=>{const o=e.trim();if(await M()||yn||(yn=!0,console.log(chalk.gray(qo()?` (离线:只有 ${D()} 条核心速查可用;联网后自动补全)`:` (offline: ${D()} core entries available; the rest arrive when you have a connection)`))),!o)return void R(qo());const n=N(o);if(n.length){O(n[0],qo());const e=n.slice(1,4).map(e=>e.keys[0]);return void(e.length&&(console.log(chalk.gray(qo()?" 相关: ":" Related: ")+e.map(e=>chalk.cyan(`/syntax ${e}`)).join(chalk.gray(" · "))),console.log()))}const t=await L("python3",o);t?W(t,qo()):(console.log(),console.log(chalk.yellow(qo()?` 索引里没有 "${o}"。`:` Nothing indexed for "${o}".`)),console.log(chalk.gray(qo()?" 试试: ":" Try: ")+chalk.cyan(j(o).join(" · "))),console.log(chalk.gray(qo()?" /syntax 只查语法,不解题 — 思路类问题赛后回课程再问。":" /syntax looks up syntax only, never solutions — bring approach questions back to the lesson afterwards.")),console.log())})(t[1]??""),void io();const r=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(r){const[,e,o]=r;return"list"===e?cn():o?"read"===e||"open"===e?mn(o):"edit"===e?await(async e=>{const o=gn(e);if(!o)return;const n=A(Uo.dir,`sol-${o.n}.py`);if(le())return se()?(console.log(chalk.yellow(qo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(qo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(qo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(qo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(qo()?" ← 不能是 /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(qo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(qo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(qo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(qo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(qo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(qo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(qo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(qo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${n}`)),void console.log());if(!ae("vi"))return console.log(chalk.yellow(qo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${n}`)),void console.log(chalk.gray(qo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim"));console.log(chalk.gray(qo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave"));const t=e=>{try{return p(e).size}catch{return 0}},r=t(n),l=Date.now();await hn("vi",["-c","set nocompatible backspace=indent,eol,start","-c","set tabstop=4 shiftwidth=4 expandtab background=dark",`sol-${o.n}.py`]),Fo.set(o.n,w(Fo.get(o.n)??b(),{ms:Date.now()-l,bytesBefore:r,bytesAfter:t(n)})),console.log(chalk.gray(qo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(qo()?" 自测样例。":" to self-check the sample.")),console.log()})(o):"run"===e?(e=>{const o=gn(e);if(!o)return;const{p:t,n:r}=o,l=A(Uo.dir,`sol-${r}.py`);if(!g(l))return void console.log(chalk.yellow(qo()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));Fo.set(r,k(Fo.get(r)??b()));const s=(t.samples??[])[0];if(!s)return void console.log(chalk.gray(qo()?` 本题无样例(设计如此)— 用 /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)pn();else if(o.killed)console.log(chalk.yellow(qo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(qo()?" ✗ 程序报错:":" ✗ 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(qo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(qo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(qo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(qo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(qo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(qo()?" 改完再 /run。":" then /run again.")),console.log()})(o):"debug"===e?await(async e=>{const o=gn(e);if(!o)return;const n=A(Uo.dir,`sol-${o.n}.py`);if(!g(n))return void console.log(chalk.yellow(qo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(qo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · 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 hn("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==t?.code?(console.log(chalk.gray(qo()?" 回到竞技场。":" Back in the arena.")),console.log()):pn()})(o):"recall"===e&&await(async e=>{const o=gn(e);if(!o)return;if(!Ke)return void Go();const{p:n,n:t}=o,r=A(process.cwd(),"icoa-contest"),l=`${He.id}-phase${Uo.phase}-g${Uo.data.slot}-archived-`;let s=null;try{for(const e of y(r))e.startsWith(l)&&(!s||e>s)&&(s=e)}catch{}const a=s?A(r,s,`sol-${t}.py`):null;if(!a||!g(a))return void console.log(chalk.gray(qo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=m(a,"utf-8"),c=`${Uo.phase}-${Uo.data.slot}-${t}`,d=Math.min(3,(fn.get(c)??0)+1);console.log(chalk.gray(qo()?` 🧭 教练回忆中(第 ${d} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${d} hint — never your old code)…`));const u=await F({token:Be,phase:Uo.phase,slot:Uo.data.slot,problemTitle:n.title,statement:n.statement,code:i,level:d,lang:qo()?"zh":"en"});if(u.ok){fn.set(c,d),console.log();for(const e of Ye(u.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),d<3&&console.log(chalk.gray(qo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${t}`)+chalk.gray(qo()?`(第 ${d+1} 级)`:` (level ${d+1})`)),console.log()}else"live_contest"===u.code?console.log(chalk.yellow(qo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${u.message}`)):console.log(chalk.yellow(` ${u.message||"Coach unavailable."}`))})(o):console.log(chalk.yellow(qo()?` 用法: /${e} <题号>`:` Usage: /${e} <problem number>`)+chalk.gray(qo()?" (花名册: /list)":" (roster: /list)")),void io()}if("contest"===o||"/contest"===o)return cn(),void io();const a="lang"===o||/^lang\s+\S+$/.test(o),i=Fe.has(o);if(!("submit"===l||l.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||a||i||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(qo()?" 竞技场命令: /read /edit /run /debug /submit /list /syntax · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list /syntax · back returns to the lesson")),void io()}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(qo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void io()}return await new Promise(o=>{const n=process.stdin,t=!!n.isTTY&&!!n.isRaw;if(lo.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{}lo.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void io()}if("ai4ioai"===o||"/ai4ioai"===o)return await d()&&(_o=!0),void io();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Ke)return Go(),void io();Co||(Co=!0,console.log(),console.log(chalk.bold.cyan(qo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(qo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(qo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),qo()||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){bo=!0;const e=Do(eo.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(qo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(qo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(qo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void io()}return await en(t,n?"fast":"deep"),void io()}if(!$o&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!Ke)return Go(),void io();const e=Do(eo.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(qo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(qo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(qo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(qo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(qo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(qo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(qo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Io=!0,void io()}const i=!$o&&"honors"===ko&&/^[1-3]$/.test(o);if(!$o&&ko&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(qo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(qo()?" ↩ back 回上一层":" ↩ back goes up one level")),void io();if(!$o&&(i||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!Ke)return Go(),void io();const e=/^\/?view ([1-3])$/.exec(o),n=i?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{wo=!0;try{console.log();const o=await Z({token:Be,cardNumber:eo.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(qo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Eo.delete(eo.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Eo.add(eo.currentCard);const n=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(qo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${eo.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${eo.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===n.length&&console.log(chalk.gray(qo()?` (第 ${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(qo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const n=on(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(qo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),ko="view",console.log(chalk.gray((qo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(qo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{wo=!1}})(n),void io()}if("/honors"===o||"honors"===o)return Ze?(console.log(),console.log(chalk.gray(qo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void io()):(await tn(),void io());if("menu"===o||"menu confirm"===o){if(No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,3e3))]),lo.removeAllListeners("line"),ao(),to||!Oo){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(to?lo:void 0),Wo()}else lo.close();return}if("quit"===o||"exit"===o||"q"===o){if("view"===ko)return await tn(),void io();if("honors"===ko)return ko=null,Vo(),void io();if(No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${eo.streakDays} day(s)`)),console.log(),to){lo.removeAllListeners("line"),ao();for(const e of ro)lo.on("line",e);lo.prompt(),Wo()}else lo.removeAllListeners("line"),lo.close();return}if("status"===o)return Ie(He,eo),void io();if("reload"===o||"refresh"===o){console.log(chalk.gray(" 拉取最新中… / fetching latest…"));const e=await _(He.id,Be,!0);return void(e?(Object.assign(He,e),console.log(chalk.green(" ✓ 已更新到最新版 / refreshed to latest")),Vo()):(console.log(chalk.yellow(" ⚠ 回源失败(可能离线)—— 仍用当前已缓存版本")),io()))}if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(te().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void io();const n=He.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 re({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),uo=null,co=null,go=null,fo(),So=!1,Io=!1,await nn(),void io()}if(Fe.has(o)){const e=Fe.get(o),n=Re(te()),t=e=>{const o=["normal","wide","wider"].filter(o=>o!==e);return qo()?`输 ${o.join(" 或 ")} 切换。`:`Type ${o.join(" or ")} to switch.`},r=process.stdout.columns||64;return e===n?(console.log(chalk.gray((qo()?"normal"===e?" 已是标准 64 列。":Oe()<=64?` ${e} 已开,但终端只有 ${r} 列 — 画面已是最大可用宽度。`:` 已是 ${e}(${Oe()} 列,上限 ${We(e)})。`:"normal"===e?" Already at the standard 64 cols. ":Oe()<=64?` ${e} is on, but your terminal is only ${r} cols — already at the max usable width. `:` Already ${e} (${Oe()} cols, cap ${We(e)}). `)+t(e))),void io()):(re({learnWidth:e,learnWide:"normal"!==e}),je(e),"normal"!==e&&Oe()<=64?(console.log(chalk.yellow(qo()?` 终端只有 ${r} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${r} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray((qo()?` 设置已记住(${e},上限 ${We(e)} 列),拉宽窗口后自动生效。`:` The setting is remembered (${e}, cap ${We(e)} cols) and applies once you widen the window. `)+t(e))),void io()):(console.log(chalk.green(" ✓ ")+chalk.gray((qo()?"normal"===e?"已恢复 64 列标准宽。":`${e} — 卡片拉伸到终端宽度(现在 ${Oe()} 列,上限 ${We(e)})。`:"normal"===e?"Back to the 64-col standard width. ":`${e} — cards stretch to your terminal (now ${Oe()} cols, cap ${We(e)}). `)+t(e))),uo=null,co=null,go=null,fo(),So=!1,Io=!1,await nn(),void io()))}if("sim"===o){const e=Do(eo.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=v(C(import.meta.url)),o=[A(e,"..","..","panda","mujoco-launcher.py"),A(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(g(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 io()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void io())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=eo.currentCard,n=eo.bookmarks.includes(e),t="bookmark"!==o;return t?eo.bookmarks=eo.bookmarks.filter(o=>o!==e):n||eo.bookmarks.push(e),ce(eo),t?console.log(n?chalk.gray(qo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(qo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(n?chalk.gray(qo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(qo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void io()}const T=S(o);if(T){const e="current"===T.target?eo.currentCard:T.target;if("all"!==e&&(!Number.isInteger(e)||e<1||e>He.cards.length))return console.log(chalk.yellow(qo()?` 本课共 ${He.cards.length} 张,请输 r 1–${He.cards.length} 或 r all。`:` This course has ${He.cards.length} cards. Try r 1–${He.cards.length} or r all.`)),console.log(),void io();for(const o of P(Ve,Lo,e,qo(),Oe()))console.log(chalk.gray(` ${o}`));console.log();const o=("all"===e?Ve:Ve.filter(o=>o.cardNumber===e)).filter(e=>!!e.replyText&&!e.seen).map(e=>e.id);return o.length>0&&(Ve=Ve.map(e=>o.includes(e.id)?{...e,seen:!0}:e),Ne(Ve),No.push(x(Be,{card_number:eo.currentCard,event_type:"viewed"},o).catch(()=>{}))),void io()}if("e"===o)return yo=eo.currentCard,console.log(chalk.gray(qo()?" 就这张卡提问,或报告问题:":" Ask a question about this card, or report a problem:")),console.log(chalk.gray(qo()?" (回车提交 · 空行取消 · 可直接粘贴多行)":" (Enter to submit · blank to cancel · multi-line paste is fine)")),void io();if("back"===o||"b"===o)return"view"===ko?(await tn(),void io()):"honors"===ko?(ko=null,Vo(),void io()):(eo.currentCard>1&&(eo.currentCard-=1),co=null,go=null,uo=null,ce(eo),Vo(),void io());if("link"===o||/^link\s+/i.test(o)){const e=o.replace(/^link\s*/i,"").replace(/^(icoa\s+)?learn\s+/i,"").trim().toUpperCase();if(!zo)return console.log(chalk.yellow(qo()?" 关联需要正式课程 token(demo 不支持)。":" Linking needs a full curriculum token (not demos).")),void io();if(!e){const e=await G(Be),o=e.ok?e.data?.candidates??[]:[];if(console.log(),console.log(chalk.bold.white(qo()?" 🔗 关联你的另一个赛道 token":" 🔗 Link another of YOUR track tokens")),console.log(chalk.gray(qo()?" 同一道挑战在两个赛道相遇时,做过一次就够了 — 成绩自动带过来。":" Meet the same challenge in two tracks and solving it once is enough — credit carries.")),console.log(),o.length>0){console.log(chalk.white(qo()?` 这台电脑上有 ${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(qo()?` · 有 ${e.carry_problems} 道题可以带过来`:` · ${e.carry_problems} solved problems would carry over`):chalk.gray(qo()?" · 目前没有可带的成绩":" · nothing to carry yet")));console.log(),console.log(chalk.gray(" ▸ ")+chalk.bold.green(`link ${o[0].index}`)+chalk.gray(qo()?" 关联它(现在不做也行)":" link it (or skip — nothing is blocked)"))}else console.log(chalk.gray(qo()?" 这台电脑上暂时没有别的 token 可关联。":" No other token of yours is on this computer yet.")),console.log(chalk.gray(qo()?" 用法: ":" Usage: ")+chalk.bold.green("link <TOKEN>")+chalk.gray(qo()?" 例: ":" e.g. ")+chalk.gray("link PYK2XF1ES9"));return console.log(chalk.gray(qo()?" 只能关联你在这台电脑上用的 token(绑在别的设备上的会被拒绝)。":" Only tokens you use on THIS computer can be linked (others are refused).")),console.log(),void io()}if(/^\d{1,2}$/.test(e)){const o=await X(Be,Number(e));return o.ok&&o.data?(sn(o.data),await Bo(),void io()):(console.log(chalk.red(` ✗ ${o.message||(qo()?"关联失败":"Link failed")}`)),void io())}const n=await ee(Be,e);return n.ok&&n.data?(sn(n.data),await Bo(),void io()):(console.log(chalk.red(` ✗ ${n.message||(qo()?"关联失败":"Link failed")}`)),"not_your_token"===n.code&&console.log(chalk.gray(qo()?" 换设备了?请联系协调员释放绑定后再试。":" Changed machines? Ask your coordinator to release the binding first.")),void io())}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(!zo)return console.log(chalk.yellow(qo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void io();const e=Ho(eo.currentCard);if("contest reset"===o){const o=await K(Be,e);if(o.ok){console.log(chalk.yellow(qo()?` 已放弃当前计时(阶段 ${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=A(process.cwd(),"icoa-contest",`${He.id}-phase${e}-g${n}`);if(g(t))try{h(t,`${t}-archived-${o}`),console.log(chalk.gray(qo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${t}-archived-${o}`))}catch{console.log(chalk.yellow(qo()?` ⚠ 归档失败(不影响重开): ${t}`:` ⚠ Could not archive (reset still fine): ${t}`))}}console.log(chalk.gray(qo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),Uo=null,$o=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void io()}const n=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(qo()?" 连接判分赛…":" Contacting contest server…"));const t=await Q(Be,e,n?parseInt(n,10):void 0);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(qo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void io();const r=t.data,l=A(process.cwd(),"icoa-contest",`${He.id}-phase${e}-g${r.slot}`);u(l,{recursive:!0});const s=Uo&&Uo.phase===e&&Uo.data.slot===r.slot?Uo.tried:new Set;Uo={phase:e,dir:l,data:r,tried:s},((e,o)=>{e.problems.forEach((n,t)=>{const r=t+1,l=(n.samples??[])[0];l&&f(A(o,`sample-${r}.txt`),l.in.endsWith("\n")?l.in:`${l.in}\n`);const s=A(o,`sol-${r}.py`);if(g(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${n.title} ══`,"#",...ln(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`,"",""),f(s,a.join("\n"))})})(r,l),$o=!0,cn(),console.log(chalk.gray(qo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(l));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(qo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(qo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void io()}if("submit"===l)return console.log(chalk.yellow(qo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(qo()?" 例如 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)")),Uo||console.log(chalk.gray(qo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void io();if(l.startsWith("submit ")){const e=l.split(/\s+/);let o=e[1]||"";const n=e[2];if(!Uo)return console.log(chalk.yellow(qo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void io();const t=Uo.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(qo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void io();const s=t.findIndex(e=>e.id===o)+1,a=n||A(Uo.dir,`sol-${s}.py`);let i;try{i=m(a,"utf-8")}catch{return console.log(chalk.red(qo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void io()}console.log(chalk.gray(qo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=Fo.get(s),d=await V(Be,Uo.phase,o,i,void 0,c&&!$(c)?c:void 0);if(!d.ok||!d.data)return"no_active_session"===d.code?console.log(chalk.yellow(qo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((qo()," "))+chalk.bold.green("contest")+chalk.gray(qo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(qo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${d.message||"judging failed"}`)),void io();const g=d.data;if(g.already_ac)console.log(chalk.green(qo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===g.verdict)console.log(chalk.bold.green(qo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${g.passed_tests??g.total_tests??"?"}/${g.total_tests??"?"} `+(qo()?"隐藏用例全过":"hidden tests passed")+` · ${g.time_ms??"?"}ms`)),Uo.data.solved.includes(o)||Uo.data.solved.push(o),Uo.tried.delete(o);else{Uo.tried.add(o);const e="TLE"===g.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${g.verdict}`)+chalk.gray(g.test?qo()?` · 挂在第 ${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(qo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=ne(g.deadline||"");if(console.log(chalk.white(qo()?` 本组进度: 已过 ${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(qo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Bo();else if(!g.late){const e=t.findIndex(e=>!Uo.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(qo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${rn(t[e])}`))}return void io()}if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);if(!Number.isInteger(n)||n<1||n>He.totalCards)return console.log(chalk.yellow(` Card number must be 1..${He.totalCards}. Try: `)+chalk.bold.green("card 1")),void io();const t=await Jo(n);return t?(console.log(t),void io()):(eo.currentCard=n,co=null,go=null,uo=null,ce(eo),Vo(),void io())}if(null!==uo&&["y","yes","n","no"].includes(o)){const e=Do(uo);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",t=n===e.check.answer,r=Date.now()-Po;ye(eo,e.number),he(eo,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),ce(eo);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,t,!1),No.push(x(Be,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:t,time_on_card_ms:r}).catch(()=>{})),uo=null,e.solution&&e.solution.length>0)return void io();if(eo.currentCard<He.totalCards){const e=eo.currentCard,o=await Jo(e+1);if(o)return await Ko(e),console.log(o),void io();eo.currentCard+=1,ce(eo),await Ko(e)?Qo():Vo(),io()}else Se(He,eo),io();return}}if(null!==co&&["a","b","c","d"].includes(o)){const e=Do(co);if(e&&"mcq"===e.type){const n=o.toUpperCase(),t=n===e.answer;if(me(eo,e.number,{answer:n,correct:t,submittedAt:(new Date).toISOString()}),ye(eo,e.number),ce(eo),ke(e,n,t,eo),No.push(x(Be,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:t}).catch(()=>{})),co=null,t)if(eo.currentCard<He.totalCards){const e=await Jo(eo.currentCard+1);if(e)return console.log(e),void io();eo.currentCard+=1,ce(eo),Vo()}else Se(He,eo),io();else io();return}}if(null!==go){if("done"===o){const e=Do(go);if(e&&"practical"===e.type)return pe(eo,e.number),ye(eo,e.number),ce(eo),Ae(e),go=null,void io()}if("skip"===o)return ye(eo,go),ce(eo),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),go=null,void io()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==co)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void io();if(null!==go)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void io();if(null!==uo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void io();const e=eo.currentCard,o=e<He.totalCards?await Jo(e+1):null;return o?(await Ko(e),console.log(o),void io()):(eo.currentCard+=1,ce(eo),eo.currentCard>He.totalCards?Se(He,eo):await Ko(e)?Qo():Vo(),void io())}return null!==uo?(console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void io()):null!==co?(console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void io()):null!==go?(console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void io()):("view"===ko?console.log(chalk.gray(qo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(qo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(qo()?" 回卡片":" to the card")):"honors"===ko?console.log(chalk.gray(qo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(qo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(qo()?" 回卡片":" to the card")):console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("/ai")+chalk.gray(" / ")+chalk.white("quit")),void io())};lo.on("line",e=>{bn(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.")),io()})}),to||lo.on("close",async()=>{No.length>0&&await Promise.race([Promise.allSettled(No),new Promise(e=>setTimeout(e,5e3))]),Oo?Wo():process.exit(0)});const wn=q(Ve,qo());wn&&(console.log(chalk.bold.cyan(` ${wn}`)),console.log());try{Vo(),io();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(Ue("Could not render this card — the curriculum may be malformed."),to){lo.removeAllListeners("line"),ao();for(const e of ro)lo.on("line",e);lo.prompt()}else lo.close();Wo()}await Ro}),ze.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,t=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await _(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,t=JSON.stringify(l).length;r+=t,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(t/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),t++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${t} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
@@ -0,0 +1 @@
1
+ export const EXAM_SERVER=process.env.ICOA_EXAM_SERVER||"https://practice.icoa2026.au";
@@ -1 +1 @@
1
- import{writeFileSync as t,existsSync as e,unlinkSync as n,mkdirSync as a}from"node:fs";import{execFileSync as o}from"node:child_process";import{join as r}from"node:path";import{homedir as i}from"node:os";import{getIcoaDir as s,getInstallSalt as c}from"./config.js";import{deriveFileKey as u,readSignedFile as f,writeSignedFile as m,recordVerdict as l}from"./secure-store.js";export function practicalChatCommand(t,e){return e?"ctf4ai"===t?"ctf4ai":"ai4ctf"===t?"ai4ctf":"vla"===t?"ctf4eai":null:null}export function materializeAttachedData(n,s){if(!s)return null;let c;try{const o=getRealExamState(),u=o?.session?.workspaceDir,f=u&&e(u)?u:r(i(),"icoa-workspace");a(f,{recursive:!0}),c=r(f,`q${n}.txt`),t(c,s,"utf-8")}catch{return null}try{return o("docker",["cp",c,`icoa-sandbox:/home/competitor/challenges/q${n}.txt`],{stdio:"ignore",timeout:3e3}),`challenges/q${n}.txt`}catch{return c}}function d(){return r(s(),"exam-state.json")}function p(){return r(s(),"demo-state.json")}function x(t){return"demo-free"===t?p():d()}export function getRealExamState(){const t=d(),{data:e,verdict:a}=f(t,u(c(),"exam-state"));if(l("exam-state",a),!e)return null;if("demo-free"===e?.session?.examId){try{n(t)}catch{}return null}return e}export function getDemoState(){const t=p(),{data:e,verdict:n}=f(t,u(c(),"demo-state"));return l("demo-state",n),e}export function getExamState(){return getRealExamState()||getDemoState()}export function saveExamState(t){const e=t.session.examId,n=x(e);m(n,t,u(c(),function(t){return"demo-free"===t?"demo-state":"exam-state"}(e)))}export function clearExamState(t){if(t){const a=x(t);e(a)&&n(a)}else{const t=getExamState();if(t){const a=x(t.session.examId);e(a)&&n(a)}}}function g(t){if(!t.session.durationMinutes)return null;const{deadlineServerMs:e,clockOffsetMs:n}=t.session;if("number"==typeof e&&"number"==typeof n)return new Date(e-n);const a=t.session.confirmedAt||t.session.startedAt,o=new Date(a).getTime();return new Date(o+60*t.session.durationMinutes*1e3)}export function getExamDeadline(){const t=getExamState();return t?g(t):null}export function getRealExamDeadline(){const t=getRealExamState();return t?g(t):null}let h=!1;export async function refetchQuestionDataIfStale(){const t=getRealExamState();if(!t)return null;if(h)return t;const e=t.session.token;if(!e)return t;if(!t.questions.some(t=>{if("ai4ctf"!==t.type&&"ctf4ai"!==t.type)return!1;const e=String(t.description||"");return(e.includes("attachedData")||/base64 blob/i.test(e))&&!t.attachedData}))return t;h=!0;try{const{getConfig:n}=await import("./config.js"),a=n(),o=a.ctfdUrl||"https://practice.icoa2026.au",r=a.language||"en",i=await fetch(`${o}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,deviceHash:"",lang:r}),signal:AbortSignal.timeout(8e3)});if(!i.ok)return t;const s=await i.json(),c=s?.data?.questions||[];if(0===c.length)return t;const u=new Map;for(const t of c)u.set(t.number,t);let f=0;for(const e of t.questions){const t=u.get(e.number);t&&(t.attachedData&&!e.attachedData&&(e.attachedData=t.attachedData,f++),t.description&&(!e.description||t.description.length>e.description.length)&&(e.description=t.description))}return f>0&&saveExamState(t),t}catch{return t}}
1
+ import{writeFileSync as t,existsSync as e,unlinkSync as n,mkdirSync as a}from"node:fs";import{execFileSync as o}from"node:child_process";import{join as r}from"node:path";import{homedir as i}from"node:os";import{getIcoaDir as s,getInstallSalt as c}from"./config.js";import{deriveFileKey as u,readSignedFile as f,writeSignedFile as m,recordVerdict as l}from"./secure-store.js";export function practicalChatCommand(t,e){return e?"ctf4ai"===t?"ctf4ai":"ai4ctf"===t?"ai4ctf":"vla"===t?"ctf4eai":null:null}export function materializeAttachedData(n,s){if(!s)return null;let c;try{const o=getRealExamState(),u=o?.session?.workspaceDir,f=u&&e(u)?u:r(i(),"icoa-workspace");a(f,{recursive:!0}),c=r(f,`q${n}.txt`),t(c,s,"utf-8")}catch{return null}try{return o("docker",["cp",c,`icoa-sandbox:/home/competitor/challenges/q${n}.txt`],{stdio:"ignore",timeout:3e3}),`challenges/q${n}.txt`}catch{return c}}function d(){return r(s(),"exam-state.json")}function p(){return r(s(),"demo-state.json")}function x(t){return"demo-free"===t?p():d()}export function getRealExamState(){const t=d(),{data:e,verdict:a}=f(t,u(c(),"exam-state"));if(l("exam-state",a),!e)return null;if("demo-free"===e?.session?.examId){try{n(t)}catch{}return null}return e}export function getDemoState(){const t=p(),{data:e,verdict:n}=f(t,u(c(),"demo-state"));return l("demo-state",n),e}export function getExamState(){return getRealExamState()||getDemoState()}export function saveExamState(t){const e=t.session.examId,n=x(e);m(n,t,u(c(),function(t){return"demo-free"===t?"demo-state":"exam-state"}(e)))}export function clearExamState(t){if(t){const a=x(t);e(a)&&n(a)}else{const t=getExamState();if(t){const a=x(t.session.examId);e(a)&&n(a)}}}function g(t){if(!t.session.durationMinutes)return null;const{deadlineServerMs:e,clockOffsetMs:n}=t.session;if("number"==typeof e&&"number"==typeof n)return new Date(e-n);const a=t.session.confirmedAt||t.session.startedAt,o=new Date(a).getTime();return new Date(o+60*t.session.durationMinutes*1e3)}export function getExamDeadline(){const t=getExamState();return t?g(t):null}export function getRealExamDeadline(){const t=getRealExamState();return t?g(t):null}let h=!1;export async function refetchQuestionDataIfStale(){const t=getRealExamState();if(!t)return null;if(h)return t;const e=t.session.token;if(!e)return t;if(!t.questions.some(t=>{if("ai4ctf"!==t.type&&"ctf4ai"!==t.type)return!1;const e=String(t.description||"");return(e.includes("attachedData")||/base64 blob/i.test(e))&&!t.attachedData}))return t;h=!0;try{const{getConfig:n}=await import("./config.js"),a=n(),{EXAM_SERVER:o}=await import("./exam-server.js"),r=o,i=a.language||"en",s=await fetch(`${r}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,deviceHash:"",lang:i}),signal:AbortSignal.timeout(8e3)});if(!s.ok)return t;const c=await s.json(),u=c?.data?.questions||[];if(0===u.length)return t;const f=new Map;for(const t of u)f.set(t.number,t);let m=0;for(const e of t.questions){const t=f.get(e.number);t&&(t.attachedData&&!e.attachedData&&(e.attachedData=t.attachedData,m++),t.description&&(!e.description||t.description.length>e.description.length)&&(e.description=t.description))}return m>0&&saveExamState(t),t}catch{return t}}
@@ -1 +1 @@
1
- import{GoogleGenAI as e}from"@google/genai";import chalk from"chalk";import{readFileSync as t}from"node:fs";import{dirname as n,join as o}from"node:path";import{fileURLToPath as a}from"node:url";import{getConfig as r,saveConfig as s}from"./config.js";import{getRealExamState as i}from"./exam-state.js";const c=n(a(import.meta.url));let l=null;function u(){if(l)return l;try{const e=JSON.parse(t(o(c,"..","..","package.json"),"utf-8"));l=e.version||"unknown"}catch{l="unknown"}return l}export async function translateText(e,t){throw new Error("Local AI model path has been disabled (2026-04-24). ICOA provides all AI server-side — no API key setup needed. Use `ai4ctf` (chat) or `exam` (with integrated help/hint) instead.")}export function setApiKey(e){s({geminiApiKey:e})}export async function createChatSession(e,t){const n=r();let o=t||"You are an AI teammate in the ICOA cybersecurity CTF competition (International Cyber Olympiad in AI 2026, Sydney).\n\nYou're a friendly, knowledgeable cybersecurity partner — like a fellow competitor sitting next to the user. Be conversational, encouraging, and collaborative.\n\nRULES:\n- Help the competitor think through challenges, brainstorm approaches, explain concepts\n- You MAY discuss vulnerability types, tools, techniques, and methodologies\n- You MAY suggest approaches and help debug code\n- Do NOT provide complete working exploits or full solution scripts\n- Do NOT provide flags or flag fragments\n- Never output anything matching flag format: icoa{...}\n- If you don't know something, say so honestly\n- Keep responses concise unless the user asks for detail\n- When the user opens a challenge, use the context to give relevant advice";e&&(o+=`\n\nThe competitor is currently working on:\nChallenge: ${e.name}\nCategory: ${e.category}`),o+='\n\nINTEGRITY — give method, not the produced answer:\n- You may name the tool/command/technique (e.g. "this is base64; run base64 -d on the file").\n- Do NOT perform a solution step for the competitor and hand back its result: never decode,\n decrypt, deobfuscate, run, execute, or compute over data they paste or that is attached,\n and then reveal the produced value. They must run it themselves and read the output.\n- Do NOT reveal the exact final answer, and never output icoa{...} / flag{...} in any case.\n- If asked to "just give the answer" / "solve it" / "decode this and tell me", refuse and\n nudge them to do the step themselves.';const a=n.ctfdUrl||"https://practice.icoa2026.au",s=n.deviceFingerprint||"",c=n.geminiModel||"gemini-2.5-flash-lite",l=[];return{async sendMessage(e){l.push({role:"user",text:e});const t=i(),r={systemPrompt:o,messages:l,model:c,maxTokens:2048,deviceFingerprint:s};t?.session?.token&&(r.examToken=t.session.token);const p={"Content-Type":"application/json","User-Agent":`icoa-cli/${u()}`,"X-Device-Fingerprint":s};!r.examToken&&n.ctfdUrl&&n.token&&n.userName&&(r.account=n.userName,p.Authorization=`Token ${n.token}`);const d=e=>new Promise(t=>setTimeout(t,e)),h=[2e3,5e3];let m=null,g=null;for(let e=0;e<=h.length&&(m=await fetch(`${a}/api/icoa/ai/chat`,{method:"POST",headers:p,body:JSON.stringify(r),signal:AbortSignal.timeout(6e4)}),!m.ok&&429===m.status);e++)e<h.length?await d(h[e]):g=m;if(!m)throw new Error("AI proxy: no response");if(!m.ok){const e=(await m.json().catch(()=>({message:"AI proxy error"}))).message||`AI proxy returned ${m.status}`;if(401===m.status)throw new Error(`${chalk.yellow("⚠ ")}Exam token expired. Re-enter via \`exam <token>\`.`);if(403===m.status)throw new Error(chalk.yellow("⚠ ")+e);if(429===m.status)throw new Error(chalk.yellow("⏳ ")+e+chalk.gray(" (retried twice — quota burst, try again in ~30s)"));throw new Error(e)}const f=await m.json(),y=function(e){return e.replace(/icoa\{[^}]*\}/gi,"[FLAG REDACTED]")}(f.data?.text||""),w=f.data?.tokensUsed||0,v="number"==typeof f.data?.accountSpent?f.data.accountSpent:void 0,k="number"==typeof f.data?.accountCap?f.data.accountCap:void 0;return l.push({role:"model",text:y}),{text:y,tokensUsed:w,accountSpent:v,accountCap:k}}}}
1
+ import{GoogleGenAI as e}from"@google/genai";import chalk from"chalk";import{readFileSync as t}from"node:fs";import{dirname as o,join as n}from"node:path";import{fileURLToPath as a}from"node:url";import{getConfig as r,saveConfig as s}from"./config.js";import{getRealExamState as i}from"./exam-state.js";import{EXAM_SERVER as c}from"./exam-server.js";const l=o(a(import.meta.url));let u=null;function p(){if(u)return u;try{const e=JSON.parse(t(n(l,"..","..","package.json"),"utf-8"));u=e.version||"unknown"}catch{u="unknown"}return u}export async function translateText(e,t){throw new Error("Local AI model path has been disabled (2026-04-24). ICOA provides all AI server-side — no API key setup needed. Use `ai4ctf` (chat) or `exam` (with integrated help/hint) instead.")}export function setApiKey(e){s({geminiApiKey:e})}export async function createChatSession(e,t){const o=r();let n=t||"You are an AI teammate in the ICOA cybersecurity CTF competition (International Cyber Olympiad in AI 2026, Sydney).\n\nYou're a friendly, knowledgeable cybersecurity partner — like a fellow competitor sitting next to the user. Be conversational, encouraging, and collaborative.\n\nRULES:\n- Help the competitor think through challenges, brainstorm approaches, explain concepts\n- You MAY discuss vulnerability types, tools, techniques, and methodologies\n- You MAY suggest approaches and help debug code\n- Do NOT provide complete working exploits or full solution scripts\n- Do NOT provide flags or flag fragments\n- Never output anything matching flag format: icoa{...}\n- If you don't know something, say so honestly\n- Keep responses concise unless the user asks for detail\n- When the user opens a challenge, use the context to give relevant advice";e&&(n+=`\n\nThe competitor is currently working on:\nChallenge: ${e.name}\nCategory: ${e.category}`),n+='\n\nINTEGRITY — give method, not the produced answer:\n- You may name the tool/command/technique (e.g. "this is base64; run base64 -d on the file").\n- Do NOT perform a solution step for the competitor and hand back its result: never decode,\n decrypt, deobfuscate, run, execute, or compute over data they paste or that is attached,\n and then reveal the produced value. They must run it themselves and read the output.\n- Do NOT reveal the exact final answer, and never output icoa{...} / flag{...} in any case.\n- If asked to "just give the answer" / "solve it" / "decode this and tell me", refuse and\n nudge them to do the step themselves.';const a=o.ctfdUrl||"https://practice.icoa2026.au",s=o.deviceFingerprint||"",l=o.geminiModel||"gemini-2.5-flash-lite",u=[];return{async sendMessage(e){u.push({role:"user",text:e});const t=i(),r={systemPrompt:n,messages:u,model:l,maxTokens:2048,deviceFingerprint:s};t?.session?.token&&(r.examToken=t.session.token);const d={"Content-Type":"application/json","User-Agent":`icoa-cli/${p()}`,"X-Device-Fingerprint":s};!r.examToken&&o.ctfdUrl&&o.token&&o.userName&&(r.account=o.userName,d.Authorization=`Token ${o.token}`);const m=e=>new Promise(t=>setTimeout(t,e)),h=[2e3,5e3],g=r.examToken?c:a;let f=null,y=null;for(let e=0;e<=h.length&&(f=await fetch(`${g}/api/icoa/ai/chat`,{method:"POST",headers:d,body:JSON.stringify(r),signal:AbortSignal.timeout(6e4)}),!f.ok&&429===f.status);e++)e<h.length?await m(h[e]):y=f;if(!f)throw new Error("AI proxy: no response");if(!f.ok){const e=(await f.json().catch(()=>({message:"AI proxy error"}))).message||`AI proxy returned ${f.status}`;if(401===f.status)throw new Error(`${chalk.yellow("⚠ ")}Exam token expired. Re-enter via \`exam <token>\`.`);if(403===f.status)throw new Error(chalk.yellow("⚠ ")+e);if(429===f.status)throw new Error(chalk.yellow("⏳ ")+e+chalk.gray(" (retried twice — quota burst, try again in ~30s)"));throw new Error(e)}const w=await f.json(),v=function(e){return e.replace(/icoa\{[^}]*\}/gi,"[FLAG REDACTED]")}(w.data?.text||""),k=w.data?.tokensUsed||0,x="number"==typeof w.data?.accountSpent?w.data.accountSpent:void 0,b="number"==typeof w.data?.accountCap?w.data.accountCap:void 0;return u.push({role:"model",text:v}),{text:v,tokensUsed:k,accountSpent:x,accountCap:b}}}}