icoa-cli 2.19.431 → 2.19.432

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{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as l,writeFileSync as t}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{logCommand as i}from"../lib/logger.js";import{openFile as r}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{loadLearnState as g}from"../lib/learn-state.js";import{buildStarterCells as u,dataFileUrls as y,parseKaggleTaskList as d,parseSubmitResponse as h,validateSubmissionText as b}from"../lib/kaggle.js";function m(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function p(o){try{const e=await fetch(m()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function f(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function k(){console.log(),console.log(chalk.yellow(" The practice server is not reachable right now.")),console.log(chalk.gray(" Check your connection, or try again later.")),console.log()}function w(o){return s(process.cwd(),"icoa-kaggle",o)}function v(o,e){const n=[];let l="";for(const t of o.split(/\s+/))""!==l&&l.length+1+t.length>e?(n.push(l),l=t):l=""===l?t:`${l} ${t}`;return""!==l&&n.push(l),n}function $(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(" Scoring (inside the notebook):")),void console.log(chalk.gray(" run the final cell — the ")+chalk.white("FINAL")+chalk.gray(" line is your score. Nothing to upload."))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(" Submit to ICOA (scored on the server):")),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(" scores vs the secret test labels → live rank on ")+chalk.cyan("board"))):"nitro"===o?.judge?(console.log(chalk.bold.white(" 怎么知道做得对不对:")),console.log(chalk.gray(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上")),console.log(chalk.gray(" · 想要真分数:去 ")+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" 注册后提交")),void console.log(chalk.gray(" · 冲刺期更快的办法:做完对照官方解答,或问 ")+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(" Submit on Kaggle (manual, your own account):")),void(o?.kaggle_url?(console.log(chalk.gray(" 1. open ")+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(" 2. submit the file your notebook produced")+chalk.gray(" — its final cell has the exact steps")):console.log(chalk.gray(" 2. Submit Predictions → upload ")+chalk.white("submission.csv")),console.log(chalk.gray(" 3. read your score, improve the MODEL cell, re-run, repeat."))):(console.log(chalk.gray(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。")),console.log(chalk.gray(" 卡住了问 ")+chalk.cyan("ai4ioai")+chalk.gray(" —— 它是弱模型,把问题问准是这次要练的本事。")))))}export async function runKaggle(n){const l=a(),r=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · real ML competitions, a runnable starter notebook")),console.log(chalk.gray(" Small tasks run on your CPU; ")+chalk.magenta("⚡ GPU tasks")+chalk.gray(" run on the ICOA GPU box.")),console.log();const l=await p("/api/icoa/kaggle/tasks");if(!l)return k();const a=d(l);if(0===a.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let g=n?a.find(o=>o.comp_id===n):void 0;if(n&&!g&&console.log(chalk.yellow(` No competition called "${n}".`)),!g){console.log(chalk.white(" Live practice competitions:")),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!g;o++){const o=(await r(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);g=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,g||console.log(chalk.gray(` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`))}if(!g)return}const h=g.comp_id;if(i(`kaggle: download ${h}`),g.needs_gpu)return void await async function(n,l){const a=w(n);if(console.log(),console.log(chalk.white(` ${l.title}`)+chalk.gray(` · ${l.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),l.description){console.log();for(const o of v(l.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Fetching the notebook…")+chalk.gray(" (the dataset stays on the GPU box — no download)"));const i=await p(`/api/icoa/kaggle/${n}/starter`),r=i?.data?.starter??i?.starter;if("string"!=typeof r||0===r.length)return k();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:t(c,r),t(s(a,"meta.json"),`${JSON.stringify(l,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the notebook here — check directory permissions."))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?" (kept your existing one)":" (the real IOAI task inside)")),console.log(chalk.green(" ✓ dataset: ")+chalk.white("already on the GPU box")+chalk.gray(" — no download needed")),console.log(),console.log(chalk.bold.white(" This is a GPU task — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" (connects you to the box where the data lives)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(" → the notebook trains on the GPU.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting")),console.log(),l.kaggle_url&&(console.log(chalk.gray(" Submit on Kaggle: ")+chalk.cyan(l.kaggle_url)),console.log())}(h,g);if(console.log(),console.log(chalk.white(` ${g.title}`)+chalk.gray(` · ${g.metric}`)),g.description){console.log();for(const o of v(g.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Downloading data…"));let b=null;const m=y(g);if(m){const[o,e,n]=await Promise.all([f(m.train),f(m.test),f(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await p(`/api/icoa/kaggle/${h}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return k();const $=w(h),j={...g,...b.meta??{}};try{e($,{recursive:!0}),t(s($,"train.csv"),b.train),t(s($,"test.csv"),b.test),t(s($,"sample_submission.csv"),b.sample_submission),t(s($,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const S=s($,"starter.ipynb");let x=!1;if(o(S))x=!0;else{const o=await p(`/api/icoa/kaggle/${h}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?t(S,e):t(S,c(u($,j)))}const G="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",N="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s($,"train.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s($,"test.csv"))+chalk.gray(` (${N})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s($,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(S)+chalk.gray(x?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),_(h,j,S),console.log()}finally{l.close()}}function _(o,e,n){e?.needs_gpu?(console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"))):(console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline."))),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),$(e)}export async function runKaggleGuide(e){console.log();const l=j(e,"guide");if(!l)return;const t=w(l);let a=null;try{a=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{a=null}i(`kaggle: guide ${l}`);const r=s(t,"starter.ipynb"),c=o(s(t,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??l} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),_(l,a,r),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function j(e,n){if(e)return e;const t=s(process.cwd(),"icoa-kaggle"),a=o(t)?l(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(t,e.name,"sample_submission.csv"))||o(s(t,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const l=j(e,"check");if(!l)return;const t=w(l),a=s(t,"submission.csv"),c=s(t,"sample_submission.csv");try{if(JSON.parse(n(s(t,"meta.json"),"utf-8")).needs_gpu&&!o(c))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const g=b(n(a,"utf-8"),n(c,"utf-8"));i(`kaggle: check ${l} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv is Kaggle-ready")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),$(u),r(t);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const l=j(e,"submit");if(!l)return;const t=w(l),r=s(t,"submission.csv"),c=s(t,"sample_submission.csv");let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if("local-eval"===u?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),$(u),void console.log();if(!u||!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==u.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),$(u),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const y=n(r,"utf-8"),d=b(y,n(c,"utf-8"));if(!d.ok){i(`kaggle: submit ${l} → local-reject: ${d.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of d.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let p=g()?.token??"";if(!p){const o=a();try{p=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!p)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const f=await async function(o,e){try{const n=await fetch(m()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${l}/submit`,{token:p,submission_csv:y}),k=h(f);if(i(`kaggle: submit ${l} → ${k.ok?`${k.metric}=${k.score}${k.deduped?" (deduped)":""} rank=${k.rank??"-"}`:k.reason??"error"}`),console.log(),k.ok){const o=`${k.metric}: ${Number(k.score).toFixed(4).replace(/\.?0+$/,"")}`;k.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof k.rank&&"number"==typeof k.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${k.rank}`)+chalk.gray(` of ${k.fieldSize}`))),k.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${k.boardEvent} ${l}`))}else switch(k.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of k.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as l,writeFileSync as t}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as a}from"../lib/repl-asker.js";import{logCommand as r}from"../lib/logger.js";import{openFile as i}from"../lib/open-file.js";import{serializeIpynb as c}from"../lib/notebook-doc.js";import{loadLearnState as g}from"../lib/learn-state.js";import{buildStarterCells as u,dataFileUrls as y,parseKaggleTaskList as d,parseSubmitResponse as h,validateSubmissionText as b}from"../lib/kaggle.js";function m(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function p(o){try{const e=await fetch(m()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function f(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function w(){console.log(),console.log(chalk.yellow(" The practice server is not reachable right now.")),console.log(chalk.gray(" Check your connection, or try again later.")),console.log()}function k(o){return s(process.cwd(),"icoa-kaggle",o)}function v(o,e){const n=[];let l="";for(const t of o.split(/\s+/))""!==l&&l.length+1+t.length>e?(n.push(l),l=t):l=""===l?t:`${l} ${t}`;return""!==l&&n.push(l),n}function $(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(" Scoring (inside the notebook):")),void console.log(chalk.gray(" run the final cell — the ")+chalk.white("FINAL")+chalk.gray(" line is your score. Nothing to upload."))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(" Submit to ICOA (scored on the server):")),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),void console.log(chalk.gray(" scores vs the secret test labels → live rank on ")+chalk.cyan("board"))):"nitro"===o?.judge?(console.log(chalk.bold.white(" 怎么知道做得对不对:")),console.log(chalk.gray(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上")),console.log(chalk.gray(" · 想要真分数:去 ")+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" 注册后提交")),void console.log(chalk.gray(" · 冲刺期更快的办法:做完对照官方解答,或问 ")+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(" Submit on Kaggle (manual, your own account):")),void(o?.kaggle_url?(console.log(chalk.gray(" 1. open ")+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(" 2. submit the file your notebook produced")+chalk.gray(" — its final cell has the exact steps")):console.log(chalk.gray(" 2. Submit Predictions → upload ")+chalk.white("submission.csv")),console.log(chalk.gray(" 3. read your score, improve the MODEL cell, re-run, repeat."))):(console.log(chalk.gray(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。")),console.log(chalk.gray(" 卡住了问 ")+chalk.cyan("ai4ioai")+chalk.gray(" —— 它是弱模型,把问题问准是这次要练的本事。")))))}export async function runKaggle(n){const l=a(),i=async o=>await l.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(" · real ML competitions, a runnable starter notebook")),console.log(chalk.gray(" Small tasks run on your CPU; ")+chalk.magenta("⚡ GPU tasks")+chalk.gray(" run on the ICOA GPU box.")),console.log();const l=await p("/api/icoa/kaggle/tasks");if(!l)return w();const a=d(l);if(0===a.length)return console.log(chalk.yellow(" No practice competitions are live yet — check back soon.")),void console.log();let g=n?a.find(o=>o.comp_id===n):void 0;if(n&&!g&&console.log(chalk.yellow(` No competition called "${n}".`)),!g){console.log(chalk.white(" Live practice competitions:")),a.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!g;o++){const o=(await i(chalk.cyan(" Pick one (number or id): "))).trim();if(!o)return;const e=Number(o);g=!Number.isNaN(e)&&a[e-1]||a.find(e=>e.comp_id===o.toLowerCase())||void 0,g||console.log(chalk.gray(` Try a number 1-${a.length} or an id like "${a[0].comp_id}".`))}if(!g)return}const h=g.comp_id;if(r(`kaggle: download ${h}`),g.needs_gpu)return void await async function(n,l){const a=k(n);if(console.log(),console.log(chalk.white(` ${l.title}`)+chalk.gray(` · ${l.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),l.description){console.log();for(const o of v(l.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Fetching the notebook…")+chalk.gray(" (the dataset stays on the GPU box — no download)"));const r=await p(`/api/icoa/kaggle/${n}/starter`),i=r?.data?.starter??r?.starter;if("string"!=typeof i||0===i.length)return w();const c=s(a,"starter.ipynb");let g=!1;try{e(a,{recursive:!0}),o(c)?g=!0:t(c,i),t(s(a,"meta.json"),`${JSON.stringify(l,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the notebook here — check directory permissions."))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?" (kept your existing one)":" (the real IOAI task inside)")),console.log(chalk.green(" ✓ dataset: ")+chalk.white("already on the GPU box")+chalk.gray(" — no download needed")),console.log(),console.log(chalk.bold.white(" This is a GPU task — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" (connects you to the box where the data lives)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(" → the notebook trains on the GPU.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting")),console.log(),l.kaggle_url&&(console.log(chalk.gray(" Submit on Kaggle: ")+chalk.cyan(l.kaggle_url)),console.log())}(h,g);if(console.log(),console.log(chalk.white(` ${g.title}`)+chalk.gray(` · ${g.metric}`)),g.description){console.log();for(const o of v(g.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(" Downloading data…"));let b=null;const m=y(g);if(m){const[o,e,n]=await Promise.all([f(m.train),f(m.test),f(m.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await p(`/api/icoa/kaggle/${h}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return w();const $=k(h),j={...g,...b.meta??{}};try{e($,{recursive:!0}),t(s($,"train.csv"),b.train),t(s($,"test.csv"),b.test),t(s($,"sample_submission.csv"),b.sample_submission),t(s($,"meta.json"),`${JSON.stringify(j,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const S=s($,"starter.ipynb");let x=!1;if(o(S))x=!0;else{const o=await p(`/api/icoa/kaggle/${h}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?t(S,e):t(S,c(u($,j)))}const G="number"==typeof j.n_train?`${j.n_train} rows`:"labelled",N="number"==typeof j.n_test?`${j.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s($,"train.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s($,"test.csv"))+chalk.gray(` (${N})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s($,"sample_submission.csv"))),console.log(chalk.green(" ✓ notebook: ")+chalk.white(S)+chalk.gray(x?" (kept your existing one)":" (runnable baseline inside)")),(j.licence||j.attribution)&&console.log(chalk.gray(` licence: ${j.licence??"—"} · ${j.attribution??""}`)),console.log(),_(h,j,S),console.log()}finally{l.close()}}function _(o,e,n){e?.needs_gpu?(console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"))):(console.log(chalk.bold.white(" Your move — 3 steps:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(" → run all (baseline trains)")),console.log(chalk.gray(" 2. it writes ")+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(" 3. ")+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(" 3. scored at ")+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(" 3. upload it on Kaggle yourself — then beat the baseline."))),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),$(e)}export async function runKaggleGuide(e){console.log();const l=j(e,"guide");if(!l)return;const t=k(l);let a=null;try{a=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{a=null}r(`kaggle: guide ${l}`);const i=s(t,"starter.ipynb"),c=o(s(t,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${a?.title??l} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),_(l,a,i),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function j(e,n){if(e)return e;const t=s(process.cwd(),"icoa-kaggle"),a=o(t)?l(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(t,e.name,"sample_submission.csv"))||o(s(t,e.name,"meta.json")))).map(o=>o.name):[];if(1===a.length)return a[0];if(0===a.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of a)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const l=j(e,"check");if(!l)return;const t=k(l),a=s(t,"submission.csv"),c=s(t,"sample_submission.csv");try{if(JSON.parse(n(s(t,"meta.json"),"utf-8")).needs_gpu&&!o(c))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if(!o(a))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const g=b(n(a,"utf-8"),n(c,"utf-8"));r(`kaggle: check ${l} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(a)),console.log(),$(u),i(t);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e){console.log();const l=j(e,"submit");if(!l)return;const t=k(l),i=s(t,"submission.csv"),c=s(t,"sample_submission.csv");let u=null;try{u=JSON.parse(n(s(t,"meta.json"),"utf-8"))}catch{u=null}if("local-eval"===u?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),$(u),void console.log();if(!u||!o(c))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==u.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),$(u),void console.log();if(!o(i))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(t,"starter.ipynb")}`)),void console.log();const y=n(i,"utf-8"),d=b(y,n(c,"utf-8"));if(!d.ok){r(`kaggle: submit ${l} → local-reject: ${d.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of d.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let p=g()?.token??"";if(!p){const o=a();try{p=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!p)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}console.log(chalk.gray(" Scoring on the server…"));const f=await async function(o,e){try{const n=await fetch(m()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}(`/api/icoa/kaggle/${l}/submit`,{token:p,submission_csv:y}),w=h(f);if(r(`kaggle: submit ${l} → ${w.ok?`${w.metric}=${w.score}${w.deduped?" (deduped)":""} rank=${w.rank??"-"}`:w.reason??"error"}`),console.log(),w.ok){const o=`${w.metric}: ${Number(w.score).toFixed(4).replace(/\.?0+$/,"")}`;w.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)),"number"==typeof w.rank&&"number"==typeof w.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${w.rank}`)+chalk.gray(` of ${w.fieldSize}`))),w.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`board ${w.boardEvent} ${l}`))}else switch(w.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of w.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit"').argument("[comp]",'competition id (with "check" / "submit")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit").action(async(o,e)=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as l}from"node:child_process";import{logCommand as r}from"../lib/logger.js";import{getMainRl as s}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as a,handleAi4ioaiMessage as i,startAi4ioaiChat as c}from"./ai4ioai.js";import{existsSync as d,mkdirSync as g,readdirSync as u,readFileSync as y,renameSync as m,writeFileSync as h}from"node:fs";import{dirname as p,join as f}from"node:path";import{fileURLToPath as b}from"node:url";import{loadCurriculumById as w,validateEAToken as $,syncProgress as k,syncCardFeedback as v}from"../lib/learn-curricula.js";import{normalizeTokenBody as C}from"../lib/token-format.js";import{fetchMyScores as A,recallCoach as T,setNickname as _,streamLearnTutor as I,submitPqs as x,viewPqsTop as E,viewHonors as P}from"../lib/learn-ai.js";import{contestReset as S,contestStart as q,contestSubmit as W,fetchGate as M,timeLeft as L}from"../lib/learn-contest.js";import{getConfig as R,saveConfig as O}from"../lib/config.js";import{isNativeWindows as N,isWindowsBuildInWslShell as j,whichBinary as D}from"../lib/platform.js";import{loadLearnState as Y,saveLearnState as U,newLearnState as F,updateStreak as z,markCardComplete as B,recordMCQ as H,recordCheck as Z,markPracticalComplete as J,addAchievement as K}from"../lib/learn-state.js";import{renderWelcome as Q,renderKnowledgeCard as V,renderMCQCard as G,renderMCQFeedback as X,renderPracticalCard as ee,renderPracticalSuccess as oe,renderSimDemoCard as te,renderMilestone as ne,renderArenaTaskCard as le,renderComingSoonCard as re,renderStatus as se,renderPhaseComplete as ae,renderCurriculumComplete as ie,setLearnAiEnabled as ce,setLearnHonorRanks as de,setLearnPqsViewCards as ge,setLearnWide as ue,learnW as ye,renderHonorWall as me,wrapMixed as he}from"../lib/learn-render.js";import{printError as pe}from"../lib/ui.js";export function registerLearnCommand(fe){fe.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async fe=>{fe?.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(),fe="LEARNDEMO01");let be=fe.trim().toUpperCase(),we=null;const $e=/^[A-Z0-9]+DEMO01$/i.test(be),ke=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(be);let ve=!1,Ce=!1;if($e)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),we=await w(be,be);else if(ke){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(be);if(!e.ok){const o=C(be);if(o!==be){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${be} → ${o}`)),e=t,be=o)}}if(!e.ok)return pe(`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 🐼"):"")),ve=!0===e.aiEnabled,Ce=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),we=await w(e.curriculumId||"LEARNDEMO01",be),!we)return pe(`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(!we){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(pe(`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()):(pe(`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 Ae=Y(),Te=!1;try{Ae&&Ae.token===be?z(Ae):(Ae=F(be,we.id,we.totalCards),Te=!0),U(Ae),Q(we,Ae,Te)}catch{return pe("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 _e=s(),Ie=null!==_e,xe=Ie?_e.listeners("line").slice():[];Ie&&_e.removeAllListeners("line");const Ee=Ie?_e:o({input:process.stdin,output:process.stdout,terminal:!0}),Pe=Ie?Ee.prompt:null;Ie&&(Ee.prompt=e.prototype.prompt);const Se=()=>{Ie&&Pe&&(Ee.prompt=Pe)},qe=()=>{Ee.setPrompt(Je?chalk.bold.green(`icoa ${a()}> `):Fe?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Ye?"icoa learn ai> ":"icoa learn> ")),Ee.prompt()};let We=null,Me=null,Le=null,Re=null,Oe=[],Ne=!1,je=null;const De=()=>{je&&clearTimeout(je),je=null,Oe=[],Ne=!1,Re=null};let Ye=!1,Ue=!1,Fe=!1,ze=null,Be=!1,He=0,Ze=!1,Je=!1;const Ke=new Map,Qe=()=>{let e=Ke.get(Ae.currentCard);return e||(e=[],Ke.set(Ae.currentCard,e)),e};let Ve=!1;const Ge=new Set;let Xe=!1,eo=0;const oo=()=>(R().language||"en").toLowerCase().startsWith("zh");ce(ve),ue(!!R().learnWide),ge(Ge);const to=new Map;de(to);const no=[];let lo=null;const ro=new Promise(e=>{lo=e}),so=()=>{const e=lo;lo=null,e?.()},ao="1"===process.env.ICOA_LEARN_EMBEDDED,io=e=>we.cards.find(o=>o.number===e);let co=null,go=null;const uo=!be.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(be),yo=async()=>{if(!uo)return;const e=await M(be);e.ok&&e.data&&(co=e.data)},mo=e=>{const o=we.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},ho=e=>{if(!Ce||!co)return null;const o=mo(e);if(o<=co.unlocked_through_phase)return null;const t=co.phases.find(e=>e.phase===co.unlocked_through_phase),n=[chalk.yellow(oo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${co.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${co.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(oo()?` ⚔ 练习赛 ${co.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${co.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(oo()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(oo()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},po=async e=>Ce?null===ho(e)?null:(await yo(),ho(e)):null;Ce&&await yo();const fo=async e=>{const o=we.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=we.modules.find(e=>e.number===o.number+1);let n;if(ve){const e=await A({token:be,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}uo&&await yo();const l=co?.phases.find(e=>e.phase===o.number);return ae(we,Ae,o,t,n,l),!0},bo=()=>{Xe=!0,console.log(chalk.gray(oo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},wo=()=>{ze=null;const e=io(Ae.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":V(e,we),e.check?(Le=e.number,eo=Date.now()):(B(Ae,e.number),U(Ae));break;case"mcq":G(e,we),We=e.number;break;case"practical":ee(e,we),Me=e.number;break;case"sim_demo":te(e,we),B(Ae,e.number),U(Ae);break;case"milestone":ne(e,we),K(Ae,e.badge),B(Ae,e.number),U(Ae);break;case"arena_task":le(e,we),B(Ae,e.number),U(Ae);break;case"coming_soon":re(e,we),B(Ae,e.number),U(Ae)}$o(e.number)},$o=e=>{if(!Ce||!uo||!co)return;const o=we.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1;if(t%4!=0)return;const n=t/4,l=co.phases.find(e=>e.phase===o.number),r=l?.contest?.slots?.find(e=>e.slot===n);if(!r)return;const s=(e,o,t,n)=>{const l=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),s=(n||"").slice(0,10);return`🏆 ${e} ${o}/${r.n}`+(l?oo()?` · 用时 ${l}`:` · ${l}`:"")+(s?` · ${s}`:"")},a=r.perfect_runs??[],i=!!r.best&&(r.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(ye());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${oo()?"练习赛":"PY Arena"} ${o.number}-${n}`)+(r.passed?chalk.bold.green(oo()?" ✅ 已通过":" ✅ passed"):"")),r.passed||(oo()?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(oo()?`${r.n} 题 · AC ${r.need} 过关 · 限时 ${r.duration_minutes} 分钟 · 无限重开`:`${r.n} problems · AC ${r.need} to pass · ${r.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(oo()?"✍ 第一次用 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(oo()?"满分":"Perfect",r.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(oo()?"最好":"Best",r.best.ac??0,r.best.ms,r.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(r.passed?chalk.gray(oo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(oo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(r.passed?chalk.gray(oo()?" 继续学习":" keep going"):chalk.gray(oo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(oo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},ko=()=>{be.endsWith("DEMO01")?console.log(chalk.yellow(oo()?" 🐼 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(oo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(oo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},vo=async(e,o)=>{if(ve){Ue=!0;try{console.log(),console.log(chalk.gray("deep"===o?oo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":oo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const l=await I({token:be,cardNumber:Ae.currentCard,question:e,mode:o,history:Qe().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),l.ok?l.offtopic?(console.log(),console.log(chalk.yellow(oo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Qe().push({role:"user",content:e},{role:"assistant",content:l.answer}),null!=l.spent&&null!=l.cap&&l.spent/l.cap>.8&&console.log(chalk.gray(` (${oo()?"AI 额度":"AI budget"}: ${Math.round(l.spent/1e3)}k / ${Math.round(l.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${l.message||(oo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Le&&console.log(chalk.gray(oo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ue=!1}}else ko()},Co=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ao=async()=>{Fe&&go?qo?Wo(qo):Eo():ze?await To():wo()},To=async()=>{Ue=!0;try{console.log();const e=await P({token:be,curriculumId:we.id,cardNumber:Ae.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(oo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(oo()?` 🏆 本卡实时 Top-3 — 第 ${Ae.currentCard} 张`:` 🏆 Live top-3 — card ${Ae.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(oo()?" (你)":" (you)"):""))}else console.log(chalk.gray(oo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(to.set(Ae.currentCard,e.mine.rank),console.log(chalk.white(oo()?" 你: ":" You: ")+chalk.bold.yellow(oo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(oo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):ve&&console.log(chalk.gray(oo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),me({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(oo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(oo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(oo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),ze="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(oo()?" 返回卡片":" returns to the card")),console.log()}finally{Ue=!1}},_o=e=>oo()&&e.title_zh||e.title,Io=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of he(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},xo=e=>go.data.solved.includes(e.id)?"✅":go.tried.has(e.id)?"❌":"⬜",Eo=()=>{const e=go.data,o=L(e.deadline),t=e.solved.length,n=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(oo()?` · 第 ${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(oo()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(oo()?`(共 ${e.n} 题)`:` (of ${e.n})`));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(oo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(oo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(oo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(oo()?` 满血重开本组(${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)} `)+xo(e)+chalk.white(` ${_o(e)}`))}),console.log(),Po()},Po=()=>{console.log(chalk.gray(oo()?" /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(oo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(oo()?" 返回课程":" returns to the lesson")),console.log()},So=e=>{const o=parseInt(e,10),t=go.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(oo()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}};let qo=null;const Wo=e=>{const o=So(e);if(!o)return;const{p:t,n:n}=o;qo=String(n),console.log(),console.log(chalk.bold.white(` ${xo(t)} ${_o(t)}`)),console.log();for(const e of(e=>oo()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of he(e,ye()+2))console.log(chalk.white(` ${o}`));else console.log();let l=0;for(const e of t.samples??[]){l+=1,console.log(),console.log(chalk.gray(oo()?` 样例 ${l} 输入:`:` Sample ${l} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(oo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(oo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(oo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(oo()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(oo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(oo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(oo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((oo()," ↩ "))+chalk.bold.green("back")+chalk.gray(oo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(oo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((oo()," / "))+chalk.bold.green("wide")+chalk.gray(oo()?" 换语言/宽度":" language / width")),console.log()},Mo=async(e,o)=>await new Promise(t=>{const n=process.stdin,r=!!n.isTTY&&!!n.isRaw;if(Ee.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const s=l(e,o,{stdio:"inherit",cwd:go.dir}),a=e=>{if(n.isTTY&&"function"==typeof n.setRawMode&&r)try{n.setRawMode(!0)}catch{}Ee.resume(),t(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Lo=()=>{console.log(chalk.yellow(oo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(oo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(oo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(oo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Ro=new Map,Oo=async e=>{const o=e.trim().toLowerCase(),s=Fe&&o.startsWith("/")?o.slice(1):o;if(Ue)return;if(null!==Re){if(Oe.push(e.replace(/\s+$/,"")),je&&clearTimeout(je),je=null,Ne){const e=Oe[Oe.length-1]??"";return"/cancel"===e.trim()?(De(),console.log(chalk.gray(oo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void qe()):""!==e.trim()?void qe():(Oe.pop(),void await a())}return void(je=setTimeout(()=>{if(je=null,Oe.length>1){Ne=!0;const e=Oe.length;return console.log(chalk.cyan(oo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(oo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void qe()}a()},140))}async function a(){const e=Oe.join("\n").replace(/^\s+|\s+$/g,""),o=Re??Ae.currentCard,t=Oe.length;if(De(),""===e)console.log(chalk.gray(oo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(oo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(oo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(oo()?" 即可执行。":" again to run it."));else{const n=eo>0?Date.now()-eo:void 0;if(await v(be,{curriculum_id:we.id,card_number:o,feedback_text:e,time_on_card_ms:n})){const e=t>1?oo()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(oo()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(oo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),qe()}if(Be){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Be=!1,console.log(),console.log(chalk.yellow(oo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(oo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(oo()?" 即可执行该命令。":" again to run it.")),console.log(),void qe();if(!o)return Be=!1,console.log(chalk.gray(oo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void qe();const t=await _({token:be,nickname:o});if(t.ok)Be=!1,console.log(chalk.bold.green(oo()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(oo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{He+=1;const e="taken"===t.code?oo()?"已被占用":"already taken":"bad_charset"===t.code?oo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?oo()?"未通过审核":"did not pass review":t.message||"error";if(!(He>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(oo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void qe();Be=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(oo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void qe()}if(Ve){Ve=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ue=!0;try{console.log(),console.log(chalk.gray(oo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await x({token:be,cardNumber:Ae.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(oo()?"评审暂不可用。":"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(oo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(oo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(oo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(oo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(oo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(oo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=oo()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(oo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(oo()?` 第 ${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 Co(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(oo()?" 改进提问: ":" 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(` (${oo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Ge.add(Ae.currentCard):Ge.delete(Ae.currentCard),"number"==typeof e.rank&&to.set(Ae.currentCard,e.rank);const o=await P({token:be,curriculumId:we.id,cardNumber:Ae.currentCard});o.ok&&o.totals&&o.chapters&&(me({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!$e&&(Be=!0,He=0,console.log(chalk.bold.yellow(oo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(oo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(oo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Ue=!1}})():(console.log(chalk.gray(oo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Le&&(console.log(chalk.gray(oo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void qe()}if(Xe)return Xe=!1,wo(),void qe();if(!o)return void qe();if(Je)return"exit"===await i(e.trim())&&(Je=!1),void qe();if(Ye){if(["q","quit","exit","back","b","menu"].includes(o))return Ye=!1,console.log(chalk.gray(oo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void qe();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await vo(n,t?"fast":"deep"),console.log(chalk.gray(oo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void qe()}if(Fe&&go){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&r(`learn-arena p${go.phase}s${go.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Fe=!1,console.log(chalk.gray(oo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),wo(),void qe();if(/^\d+$/.test(o))return Wo(o),void qe();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,n]=e;return"list"===o?Eo():n?"read"===o||"open"===o?Wo(n):"edit"===o?await(async e=>{const o=So(e);if(!o)return;const t=f(go.dir,`sol-${o.n}.py`);return N()?j()?(console.log(chalk.yellow(oo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(oo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(),console.log(chalk.gray(oo()?" 修法 — 在 Ubuntu 里装一份:":" Fix — install icoa inside Ubuntu:")),console.log(chalk.bold.cyan(" npm install -g icoa-cli")),console.log(chalk.gray(oo()?" 然后确认: ":" Then check: ")+chalk.bold.cyan("which icoa")+chalk.gray(oo()?" (不能是 /mnt/c 开头)":" (must NOT start with /mnt/c)")),console.log(),console.log(chalk.gray(oo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(oo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(oo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(oo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(oo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(oo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log()):D("vi")?(console.log(chalk.gray(oo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await Mo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(oo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(oo()?" 自测样例。":" to self-check the sample.")),void console.log()):(console.log(chalk.yellow(oo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(oo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim")))})(n):"run"===o?(e=>{const o=So(e);if(!o)return;const{p:n,n:l}=o,r=f(go.dir,`sol-${l}.py`);if(!d(r))return void console.log(chalk.yellow(oo()?` 还没有 sol-${l}.py — 先 /edit ${l}。`:` No sol-${l}.py yet — /edit ${l} first.`));const s=(n.samples??[])[0];if(!s)return void console.log(chalk.gray(oo()?` 本题无样例(设计如此)— 用 /debug ${l} 自己试,或直接 /submit ${l}。`:` This problem ships no sample (by design) — try /debug ${l}, or go straight to /submit ${l}.`));let a="";try{a=t("python3",[r],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if("ENOENT"===o.code)Lo();else if(o.killed)console.log(chalk.yellow(oo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(oo()?" ✗ 程序报错:":" ✗ 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(oo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(oo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(oo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(oo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${l}`)):console.log(chalk.yellow(oo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${l}`)+chalk.gray(oo()?" 改完再 /run。":" then /run again.")),console.log()})(n):"debug"===o?await(async e=>{const o=So(e);if(!o)return;const t=f(go.dir,`sol-${o.n}.py`);if(!d(t))return void console.log(chalk.yellow(oo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(oo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const n=await Mo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==n?.code?(console.log(chalk.gray(oo()?" 回到竞技场。":" Back in the arena.")),console.log()):Lo()})(n):"recall"===o&&await(async e=>{const o=So(e);if(!o)return;if(!ve)return void ko();const{p:t,n:n}=o,l=f(process.cwd(),"icoa-contest"),r=`${we.id}-phase${go.phase}-g${go.data.slot}-archived-`;let s=null;try{for(const e of u(l))e.startsWith(r)&&(!s||e>s)&&(s=e)}catch{}const a=s?f(l,s,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(oo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${go.phase}-${go.data.slot}-${n}`,g=Math.min(3,(Ro.get(c)??0)+1);console.log(chalk.gray(oo()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await T({token:be,phase:go.phase,slot:go.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:oo()?"zh":"en"});if(m.ok){Ro.set(c,g),console.log();for(const e of he(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(oo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(oo()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(oo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(n):console.log(chalk.yellow(oo()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(oo()?" (花名册: /list)":" (roster: /list)")),void qe()}if("contest"===o||"/contest"===o)return Eo(),void qe();const n="lang"===o||/^lang\s+\S+$/.test(o),l=/^(wide|wide on|wide off|normal|narrow)$/.test(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||n||l||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(oo()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void qe()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(oo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void qe()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(Ee.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const r=l(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Ee.resume(),o()};r.on("close",s),r.on("error",s)}),console.log(),void qe()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Je=!0),void qe();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!ve)return ko(),void qe();Ze||(Ze=!0,console.log(),console.log(chalk.bold.cyan(oo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(oo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(oo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),oo()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Ye=!0;const e=io(Ae.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(oo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(oo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(oo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void qe()}return await vo(n,t?"fast":"deep"),void qe()}if(!Fe&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!ve)return ko(),void qe();const e=io(Ae.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(oo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(oo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(oo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(oo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(oo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(oo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(oo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Ve=!0,void qe()}const w=!Fe&&"honors"===ze&&/^[1-3]$/.test(o);if(!Fe&&ze&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(oo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(oo()?" ↩ back 回上一层":" ↩ back goes up one level")),void qe();if(!Fe&&(w||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!ve)return ko(),void qe();const e=/^\/?view ([1-3])$/.exec(o),t=w?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Ue=!0;try{console.log();const o=await E({token:be,cardNumber:Ae.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(oo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Ge.delete(Ae.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Ge.add(Ae.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(oo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${Ae.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${Ae.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(oo()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(oo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Co(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(oo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),ze="view",console.log(chalk.gray((oo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(oo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Ue=!1}})(t),void qe()}if("/honors"===o||"honors"===o)return $e?(console.log(),console.log(chalk.gray(oo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void qe()):(await To(),void qe());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return se(we,Ae),void qe();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(R().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void qe();const t=we.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),l="en"===n||"zh"===n&&t,r=l?n:"en";return O({language:r}),l?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(r)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Le=null,We=null,Me=null,De(),Xe=!1,Ve=!1,await Ao(),void qe()}if(["wide","wide on","normal","narrow","wide off"].includes(o)){const e="wide"===o||"wide on"===o;return e===!!R().learnWide?(console.log(chalk.gray(e?oo()?ye()<=64?` 宽屏已开,但终端只有 ${process.stdout.columns||64} 列 — 画面已是最大可用宽度。输 normal 关闭。`:` 已是宽屏(${ye()} 列)。输 normal 恢复 64 列。`:ye()<=64?` Wide is on, but your terminal is only ${process.stdout.columns||64} cols — already at max usable width. Type normal to switch it off.`:` Already wide (${ye()} cols). Type normal to restore 64.`:oo()?" 已是标准 64 列。输 wide 拉伸到终端宽度。":" Already at the standard 64 cols. Type wide to stretch.")),void qe()):(O({learnWide:e}),ue(e),e&&ye()<=64?(console.log(chalk.yellow(oo()?` 终端只有 ${process.stdout.columns||64} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${process.stdout.columns||64} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray(oo()?" 拉宽窗口后会自动生效;输 normal 关闭宽屏。":" Widen the window and it takes effect automatically; type normal to switch it off.")),void qe()):(console.log(chalk.green(" ✓ ")+chalk.gray(e?oo()?`宽屏开 — 卡片拉伸到终端宽度(现在 ${ye()} 列,上限 96)。输 normal 恢复。`:`Wide mode ON — cards stretch to your terminal (now ${ye()} cols, max 96). Type normal to restore.`:oo()?"已恢复 64 列标准宽。输 wide 再拉伸。":"Back to the 64-col standard width. Type wide to stretch again.")),Le=null,We=null,Me=null,De(),Xe=!1,Ve=!1,await Ao(),void qe()))}if("sim"===o){const e=io(Ae.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=p(b(import.meta.url)),o=[f(e,"..","..","panda","mujoco-launcher.py"),f(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),l("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void qe()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void qe())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=Ae.currentCard,t=Ae.bookmarks.includes(e),n="bookmark"!==o;return n?Ae.bookmarks=Ae.bookmarks.filter(o=>o!==e):t||Ae.bookmarks.push(e),U(Ae),n?console.log(t?chalk.gray(oo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(oo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(oo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(oo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void qe()}if("e"===o)return Re=Ae.currentCard,console.log(chalk.gray(oo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void qe();if("back"===o||"b"===o)return"view"===ze?(await To(),void qe()):"honors"===ze?(ze=null,wo(),void qe()):(Ae.currentCard>1&&(Ae.currentCard-=1),We=null,Me=null,Le=null,U(Ae),wo(),void qe());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(!uo)return console.log(chalk.yellow(oo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void qe();const e=mo(Ae.currentCard);if("contest reset"===o){const o=await S(be,e);if(o.ok){console.log(chalk.yellow(oo()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let t=1;t<=3;t++){const n=f(process.cwd(),"icoa-contest",`${we.id}-phase${e}-g${t}`);if(d(n))try{m(n,`${n}-archived-${o}`),console.log(chalk.gray(oo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(oo()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(oo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),go=null,Fe=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void qe()}const t=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(oo()?" 连接判分赛…":" Contacting contest server…"));const n=await q(be,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(oo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void qe();const l=n.data,r=f(process.cwd(),"icoa-contest",`${we.id}-phase${e}-g${l.slot}`);g(r,{recursive:!0});const s=go&&go.phase===e&&go.data.slot===l.slot?go.tried:new Set;go={phase:e,dir:r,data:l,tried:s},((e,o)=>{e.problems.forEach((t,n)=>{const l=n+1,r=(t.samples??[])[0];r&&h(f(o,`sample-${l}.txt`),r.in.endsWith("\n")?r.in:`${r.in}\n`);const s=f(o,`sol-${l}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Io(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${l} for the Chinese statement.`),r){a.push("#",`# Sample input (also in sample-${l}.txt):`);for(const e of r.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of r.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 ${l} = sample self-check · /debug ${l} = free-input run · /submit ${l} = judge`,"",""),h(s,a.join("\n"))})})(l,r),Fe=!0,Eo(),console.log(chalk.gray(oo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(r));const a=l.problems.findIndex(e=>!l.solved.includes(e.id))+1||1;return console.log(chalk.white(oo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(oo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void qe()}if("submit"===s)return console.log(chalk.yellow(oo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(oo()?" 例如 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)")),go||console.log(chalk.gray(oo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void qe();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!go)return console.log(chalk.yellow(oo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void qe();const n=go.data.problems,l=parseInt(o,10);if(Number.isInteger(l)&&l>=1&&l<=n.length&&!n.some(e=>e.id===o)&&(o=n[l-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(oo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void qe();const r=n.findIndex(e=>e.id===o)+1,a=t||f(go.dir,`sol-${r}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(oo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void qe()}console.log(chalk.gray(oo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await W(be,go.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(oo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((oo()," "))+chalk.bold.green("contest")+chalk.gray(oo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(oo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void qe();const d=c.data;if(d.already_ac)console.log(chalk.green(oo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(oo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(oo()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),go.data.solved.includes(o)||go.data.solved.push(o),go.tried.delete(o);else{go.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?oo()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(oo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=L(d.deadline||"");if(console.log(chalk.white(oo()?` 本组进度: 已过 ${d.ac_count} 题 · 过 ${d.need} 题过关(共 ${d.n} 题)`:` Group progress: ${d.ac_count} solved · ${d.need} needed to pass (${d.n} problems)`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(oo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await yo();else if(!d.late){const e=n.findIndex(e=>!go.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(oo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${_o(n[e])}`))}return void qe()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>we.totalCards)return console.log(chalk.yellow(` Card number must be 1..${we.totalCards}. Try: `)+chalk.bold.green("card 1")),void qe();const n=await po(t);return n?(console.log(n),void qe()):(Ae.currentCard=t,We=null,Me=null,Le=null,U(Ae),wo(),void qe())}if(null!==Le&&["y","yes","n","no"].includes(o)){const e=io(Le);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,l=Date.now()-eo;B(Ae,e.number),Z(Ae,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),U(Ae);const{renderCheckFeedback:r}=await import("../lib/learn-render.js");if(r(e,t,n,!1),no.push(k(be,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:l}).catch(()=>{})),Le=null,e.solution&&e.solution.length>0)return void qe();if(Ae.currentCard<we.totalCards){const e=Ae.currentCard,o=await po(e+1);if(o)return await fo(e),console.log(o),void qe();Ae.currentCard+=1,U(Ae),await fo(e)?bo():wo(),qe()}else ie(we,Ae),qe();return}}if(null!==We&&["a","b","c","d"].includes(o)){const e=io(We);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(H(Ae,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),B(Ae,e.number),U(Ae),X(e,t,n,Ae),no.push(k(be,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),We=null,n)if(Ae.currentCard<we.totalCards){const e=await po(Ae.currentCard+1);if(e)return console.log(e),void qe();Ae.currentCard+=1,U(Ae),wo()}else ie(we,Ae),qe();else qe();return}}if(null!==Me){if("done"===o){const e=io(Me);if(e&&"practical"===e.type)return J(Ae,e.number),B(Ae,e.number),U(Ae),oe(e),Me=null,void qe()}if("skip"===o)return B(Ae,Me),U(Ae),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Me=null,void qe()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==We)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void qe();if(null!==Me)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void qe();if(null!==Le)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void qe();const e=Ae.currentCard,o=e<we.totalCards?await po(e+1):null;return o?(await fo(e),console.log(o),void qe()):(Ae.currentCard+=1,U(Ae),Ae.currentCard>we.totalCards?ie(we,Ae):await fo(e)?bo():wo(),void qe())}if(null!==Le)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void qe();if(null!==We)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void qe();if(null!==Me)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void qe();"view"===ze?console.log(chalk.gray(oo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(oo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(oo()?" 回卡片":" to the card")):"honors"===ze?console.log(chalk.gray(oo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(oo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(oo()?" 回卡片":" 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")),qe()}else{if("view"===ze)return await To(),void qe();if("honors"===ze)return ze=null,wo(),void qe();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(`🔥 ${Ae.streakDays} day(s)`)),console.log(),Ie){Ee.removeAllListeners("line"),Se();for(const e of xe)Ee.on("line",e);Ee.prompt(),so()}else Ee.removeAllListeners("line"),Ee.close()}else if(no.length>0&&await Promise.race([Promise.allSettled(no),new Promise(e=>setTimeout(e,3e3))]),Ee.removeAllListeners("line"),Se(),Ie||!ao){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Ie?Ee:void 0),so()}else Ee.close()};Ee.on("line",e=>{Oo(e).catch(e=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),qe()})}),Ie||Ee.on("close",async()=>{no.length>0&&await Promise.race([Promise.allSettled(no),new Promise(e=>setTimeout(e,5e3))]),ao?so():process.exit(0)});try{wo(),qe();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(pe("Could not render this card — the curriculum may be malformed."),Ie){Ee.removeAllListeners("line"),Se();for(const e of xe)Ee.on("line",e);Ee.prompt()}else Ee.close();so()}await ro}),fe.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,l=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),r=await w(e),s=Date.now()-o;if(r){const e=r.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(r).length;l+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(l/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as l}from"node:child_process";import{logCommand as r}from"../lib/logger.js";import{getMainRl as s}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as a,handleAi4ioaiMessage as i,startAi4ioaiChat as c}from"./ai4ioai.js";import{existsSync as d,mkdirSync as g,readdirSync as u,readFileSync as y,renameSync as m,writeFileSync as h}from"node:fs";import{dirname as p,join as f}from"node:path";import{fileURLToPath as b}from"node:url";import{loadCurriculumById as w,validateEAToken as $,syncProgress as k,syncCardFeedback as v}from"../lib/learn-curricula.js";import{normalizeTokenBody as C}from"../lib/token-format.js";import{fetchMyScores as A,recallCoach as T,setNickname as _,streamLearnTutor as I,submitPqs as x,viewPqsTop as E,viewHonors as P}from"../lib/learn-ai.js";import{contestReset as S,contestStart as q,contestSubmit as W,fetchGate as M,timeLeft as L}from"../lib/learn-contest.js";import{getConfig as R,saveConfig as O}from"../lib/config.js";import{isNativeWindows as N,isWindowsBuildInWslShell as j,whichBinary as D}from"../lib/platform.js";import{loadLearnState as Y,saveLearnState as U,newLearnState as F,updateStreak as z,markCardComplete as B,recordMCQ as H,recordCheck as Z,markPracticalComplete as J,addAchievement as K}from"../lib/learn-state.js";import{renderWelcome as Q,renderKnowledgeCard as V,renderMCQCard as G,renderMCQFeedback as X,renderPracticalCard as ee,renderPracticalSuccess as oe,renderSimDemoCard as te,renderMilestone as ne,renderArenaTaskCard as le,renderComingSoonCard as re,renderStatus as se,renderPhaseComplete as ae,renderCurriculumComplete as ie,setLearnAiEnabled as ce,setLearnHonorRanks as de,setLearnPqsViewCards as ge,setLearnWide as ue,learnW as ye,renderHonorWall as me,wrapMixed as he}from"../lib/learn-render.js";import{printError as pe}from"../lib/ui.js";export function registerLearnCommand(fe){fe.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async fe=>{fe?.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(),fe="LEARNDEMO01");let be=fe.trim().toUpperCase(),we=null;const $e=/^[A-Z0-9]+DEMO01$/i.test(be),ke=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(be);let ve=!1,Ce=!1;if($e)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),we=await w(be,be);else if(ke){console.log(),console.log(chalk.gray(" Validating token..."));let e=await $(be);if(!e.ok){const o=C(be);if(o!==be){const t=await $(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${be} → ${o}`)),e=t,be=o)}}if(!e.ok)return pe(`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 🐼"):"")),ve=!0===e.aiEnabled,Ce=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),we=await w(e.curriculumId||"LEARNDEMO01",be),!we)return pe(`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(!we){const{getLastCurriculumFailure:e}=await import("../lib/learn-curricula.js");return"offline"===e()?(pe(`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()):(pe(`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 Ae=Y(),Te=!1;try{Ae&&Ae.token===be?z(Ae):(Ae=F(be,we.id,we.totalCards),Te=!0),U(Ae),Q(we,Ae,Te)}catch{return pe("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 _e=s(),Ie=null!==_e,xe=Ie?_e.listeners("line").slice():[];Ie&&_e.removeAllListeners("line");const Ee=Ie?_e:o({input:process.stdin,output:process.stdout,terminal:!0}),Pe=Ie?Ee.prompt:null;Ie&&(Ee.prompt=e.prototype.prompt);const Se=()=>{Ie&&Pe&&(Ee.prompt=Pe)},qe=()=>{Ee.setPrompt(Je?chalk.bold.green(`icoa ${a()}> `):Fe?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(Ye?"icoa learn ai> ":"icoa learn> ")),Ee.prompt()};let We=null,Me=null,Le=null,Re=null,Oe=[],Ne=!1,je=null;const De=()=>{je&&clearTimeout(je),je=null,Oe=[],Ne=!1,Re=null};let Ye=!1,Ue=!1,Fe=!1,ze=null,Be=!1,He=0,Ze=!1,Je=!1;const Ke=new Map,Qe=()=>{let e=Ke.get(Ae.currentCard);return e||(e=[],Ke.set(Ae.currentCard,e)),e};let Ve=!1;const Ge=new Set;let Xe=!1,eo=0;const oo=()=>(R().language||"en").toLowerCase().startsWith("zh");ce(ve),ue(!!R().learnWide),ge(Ge);const to=new Map;de(to);const no=[];let lo=null;const ro=new Promise(e=>{lo=e}),so=()=>{const e=lo;lo=null,e?.()},ao="1"===process.env.ICOA_LEARN_EMBEDDED,io=e=>we.cards.find(o=>o.number===e);let co=null,go=null;const uo=!be.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(be),yo=async()=>{if(!uo)return;const e=await M(be);e.ok&&e.data&&(co=e.data)},mo=e=>{const o=we.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},ho=e=>{if(!Ce||!co)return null;const o=mo(e);if(o<=co.unlocked_through_phase)return null;const t=co.phases.find(e=>e.phase===co.unlocked_through_phase),n=[chalk.yellow(oo()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${co.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${co.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(oo()?` ⚔ 练习赛 ${co.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${co.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(oo()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(oo()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},po=async e=>Ce?null===ho(e)?null:(await yo(),ho(e)):null;Ce&&await yo();const fo=async e=>{const o=we.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=we.modules.find(e=>e.number===o.number+1);let n;if(ve){const e=await A({token:be,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}uo&&await yo();const l=co?.phases.find(e=>e.phase===o.number);return ae(we,Ae,o,t,n,l),!0},bo=()=>{Xe=!0,console.log(chalk.gray(oo()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},wo=()=>{ze=null;const e=io(Ae.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":V(e,we),e.check?(Le=e.number,eo=Date.now()):(B(Ae,e.number),U(Ae));break;case"mcq":G(e,we),We=e.number;break;case"practical":ee(e,we),Me=e.number;break;case"sim_demo":te(e,we),B(Ae,e.number),U(Ae);break;case"milestone":ne(e,we),K(Ae,e.badge),B(Ae,e.number),U(Ae);break;case"arena_task":le(e,we),B(Ae,e.number),U(Ae);break;case"coming_soon":re(e,we),B(Ae,e.number),U(Ae)}$o(e.number)},$o=e=>{if(!Ce||!uo||!co)return;const o=we.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1;if(t%4!=0)return;const n=t/4,l=co.phases.find(e=>e.phase===o.number),r=l?.contest?.slots?.find(e=>e.slot===n);if(!r)return;const s=(e,o,t,n)=>{const l=(e=>{if(null==e||e<=0)return null;const o=Math.floor(e/6e4),t=Math.floor(e%6e4/1e3);return`${o}:${String(t).padStart(2,"0")}`})(t),s=(n||"").slice(0,10);return`🏆 ${e} ${o}/${r.n}`+(l?oo()?` · 用时 ${l}`:` · ${l}`:"")+(s?` · ${s}`:"")},a=r.perfect_runs??[],i=!!r.best&&(r.best.ac??0)>0,c=chalk.bold.yellow(" ║ "),d="═".repeat(ye());if(console.log(chalk.bold.yellow(` ╔${d}`)),console.log(c+chalk.bold.white(`⚔ ${oo()?"练习赛":"PY Arena"} ${o.number}-${n}`)+(r.passed?chalk.bold.green(oo()?" ✅ 已通过":" ✅ passed"):"")),r.passed||(oo()?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(oo()?`${r.n} 题 · AC ${r.need} 过关 · 限时 ${r.duration_minutes} 分钟 · 无限重开`:`${r.n} problems · AC ${r.need} to pass · ${r.duration_minutes} min · unlimited retries`)),1===o.number&&console.log(c+chalk.gray(oo()?"✍ 第一次用 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(oo()?"满分":"Perfect",r.n,e.ms,e.ts)));else i&&console.log(c+chalk.yellow(s(oo()?"最好":"Best",r.best.ac??0,r.best.ms,r.best.ts)));console.log(c+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+(r.passed?chalk.gray(oo()?" 再战刷成绩 · ":" race it again · "):chalk.gray(oo()?" 开赛 · ":" enter · "))+chalk.gray("▸ ")+chalk.bold.green("ok")+(r.passed?chalk.gray(oo()?" 继续学习":" keep going"):chalk.gray(oo()?" 先继续学(不锁翻卡)":" keep studying (no cards locked)"))),(a.length>0||i)&&console.log(c+chalk.gray("▸ ")+chalk.bold.green("contest reset")+chalk.gray(oo()?" 满时重开 · 全新模板(旧文件自动归档)":" fresh clock & templates (old files archived)")),console.log(chalk.bold.yellow(` ╚${d}`)),console.log()},ko=()=>{be.endsWith("DEMO01")?console.log(chalk.yellow(oo()?" 🐼 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(oo()?" 此 token 未开通 🐼 AI 熊猫导师(高级功能)。":" This token does not include the 🐼 AI Panda Tutor (premium).")),console.log(chalk.gray(oo()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},vo=async(e,o)=>{if(ve){Ue=!0;try{console.log(),console.log(chalk.gray("deep"===o?oo()?" 🐼 AI 熊猫导师(深度思考中,思考过程为灰色小字)…":" 🐼 AI Panda Tutor (deepthink — reasoning shown in gray)…":oo()?" 🐼 AI 熊猫导师(快速模式)…":" 🐼 AI Panda Tutor (quick mode)…")),console.log();let t=!1,n=!1;const l=await I({token:be,cardNumber:Ae.currentCard,question:e,mode:o,history:Qe().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),l.ok?l.offtopic?(console.log(),console.log(chalk.yellow(oo()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Qe().push({role:"user",content:e},{role:"assistant",content:l.answer}),null!=l.spent&&null!=l.cap&&l.spent/l.cap>.8&&console.log(chalk.gray(` (${oo()?"AI 额度":"AI budget"}: ${Math.round(l.spent/1e3)}k / ${Math.round(l.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${l.message||(oo()?"🐼 AI 熊猫导师暂不可用。":"🐼 AI Panda Tutor unavailable.")}`))),null!==Le&&console.log(chalk.gray(oo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ue=!1}}else ko()},Co=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ao=async()=>{Fe&&go?qo?Wo(qo):Eo():ze?await To():wo()},To=async()=>{Ue=!0;try{console.log();const e=await P({token:be,curriculumId:we.id,cardNumber:Ae.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(oo()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(oo()?` 🏆 本卡实时 Top-3 — 第 ${Ae.currentCard} 张`:` 🏆 Live top-3 — card ${Ae.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(oo()?" (你)":" (you)"):""))}else console.log(chalk.gray(oo()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(to.set(Ae.currentCard,e.mine.rank),console.log(chalk.white(oo()?" 你: ":" You: ")+chalk.bold.yellow(oo()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(oo()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):ve&&console.log(chalk.gray(oo()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),me({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(oo()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(oo()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(oo()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),ze="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("↩ back")+chalk.gray(oo()?" 返回卡片":" returns to the card")),console.log()}finally{Ue=!1}},_o=e=>oo()&&e.title_zh||e.title,Io=(e,o)=>{const t=[];for(const n of e.split("\n"))if(n.trim())for(const e of he(n,o))t.push(e.trim()?`# ${e}`:"#");else t.push("#");return t},xo=e=>go.data.solved.includes(e.id)?"✅":go.tried.has(e.id)?"❌":"⬜",Eo=()=>{const e=go.data,o=L(e.deadline),t=e.solved.length,n=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(oo()?` · 第 ${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(oo()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(oo()?`(共 ${e.n} 题)`:` (of ${e.n})`));const l=Date.parse(e.deadline)-Date.now();o?e.resumed&&l<6e4*e.duration_minutes*.25&&console.log(chalk.yellow(oo()?` ⚠ 续场 — 只剩 ${o}。`:` ⚠ Resumed session — only ${o} left. `)+chalk.gray(oo()?"不够就 ":"Short on time? ")+chalk.bold.green("contest reset")+chalk.gray(oo()?" 满血重开。":" restarts the clock fresh.")):console.log(chalk.gray(" ▸ ")+chalk.bold.green("contest reset")+chalk.gray(oo()?` 满血重开本组(${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)} `)+xo(e)+chalk.white(` ${_o(e)}`))}),console.log(),Po()},Po=()=>{console.log(chalk.gray(oo()?" /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(oo()?" /list 花名册 · /recall <n> 🧭教练回忆旧解(不给原码) · 直接敲题号 = 读题 · ":" /list roster · /recall <n> 🧭 coach recall (never your old code) · bare number reads it · ")+chalk.bold.cyan("↩ back")+chalk.gray(oo()?" 返回课程":" returns to the lesson")),console.log()},So=e=>{const o=parseInt(e,10),t=go.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(oo()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}};let qo=null;const Wo=e=>{const o=So(e);if(!o)return;const{p:t,n:n}=o;qo=String(n),console.log(),console.log(chalk.bold.white(` ${xo(t)} ${_o(t)}`)),console.log();for(const e of(e=>oo()&&e.statement_zh||e.statement)(t).split("\n"))if(e.trim())for(const o of he(e,ye()+2))console.log(chalk.white(` ${o}`));else console.log();let l=0;for(const e of t.samples??[]){l+=1,console.log(),console.log(chalk.gray(oo()?` 样例 ${l} 输入:`:` Sample ${l} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(oo()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(oo()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(oo()?" 四步:":" Four steps:")),console.log(chalk.gray(" ① ")+chalk.bold.green(`/edit ${n}`.padEnd(11))+chalk.gray(oo()?"写码(vi:i 编辑 · Esc · :wq 存盘退出)":"write your code (vi: i = edit · Esc · :wq = save+leave)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`.padEnd(11))+chalk.gray(oo()?"样例自测":"sample self-check")),console.log(chalk.gray(" ③ ")+chalk.bold.green(`/debug ${n}`.padEnd(11))+chalk.gray(oo()?"自己输入调试(可选)":"free-input run (optional)")),console.log(chalk.gray(" ④ ")+chalk.bold.green(`/submit ${n}`.padEnd(11))+chalk.gray(oo()?"正式判分(隐藏用例)":"official judging (hidden tests)")),console.log(),console.log(chalk.gray((oo()," ↩ "))+chalk.bold.green("back")+chalk.gray(oo()?" 回课程 · ":" to the lesson · ")+chalk.bold.green("/list")+chalk.gray(oo()?" 看花名册 · ":" roster · ")+chalk.bold.green("lang zh")+chalk.gray((oo()," / "))+chalk.bold.green("wide")+chalk.gray(oo()?" 换语言/宽度":" language / width")),console.log()},Mo=async(e,o)=>await new Promise(t=>{const n=process.stdin,r=!!n.isTTY&&!!n.isRaw;if(Ee.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const s=l(e,o,{stdio:"inherit",cwd:go.dir}),a=e=>{if(n.isTTY&&"function"==typeof n.setRawMode&&r)try{n.setRawMode(!0)}catch{}Ee.resume(),t(e)};s.on("close",()=>a(null)),s.on("error",e=>a(e))}),Lo=()=>{console.log(chalk.yellow(oo()?" 找不到 python3 — 不是你的代码有问题。":" python3 not found — this is not your code.")),console.log(chalk.gray(oo()?" 这台机器的 PATH 上没有 Python 3。":" This machine has no Python 3 on PATH.")),console.log(chalk.gray(oo()?" 装一下: ":" Install it: ")+chalk.bold.cyan("darwin"===process.platform?"brew install python@3.12":"sudo apt install python3")),console.log(chalk.gray(oo()?" 判分在服务器上跑,所以 /submit 照样能用 — 只是没法先本地自测。":" Judging is server-side — /submit still works, only self-check is off.")),console.log()},Ro=new Map,Oo=async e=>{const o=e.trim().toLowerCase(),s=Fe&&o.startsWith("/")?o.slice(1):o;if(Ue)return;if(null!==Re){if(Oe.push(e.replace(/\s+$/,"")),je&&clearTimeout(je),je=null,Ne){const e=Oe[Oe.length-1]??"";return"/cancel"===e.trim()?(De(),console.log(chalk.gray(oo()?" 已取消(未提交)。":" Cancelled (nothing submitted).")),console.log(),void qe()):""!==e.trim()?void qe():(Oe.pop(),void await a())}return void(je=setTimeout(()=>{if(je=null,Oe.length>1){Ne=!0;const e=Oe.length;return console.log(chalk.cyan(oo()?` [已粘贴 ${e} 行]`:` [Pasted ${e} lines]`)+chalk.gray(oo()?" 继续输入可补充 · 空行提交 · /cancel 取消":" keep typing to add · blank line to submit · /cancel to abort")),void qe()}a()},140))}async function a(){const e=Oe.join("\n").replace(/^\s+|\s+$/g,""),o=Re??Ae.currentCard,t=Oe.length;if(De(),""===e)console.log(chalk.gray(oo()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else if(1===t&&/^(quit|exit|q|back|b|menu|home)$/i.test(e))console.log(chalk.yellow(oo()?` ⚠ "${e}" 像是导航命令,不是问题描述 — 未提交。`:` ⚠ "${e}" looks like a navigation command, not a report — nothing sent.`)),console.log(chalk.gray(oo()?" 已退出报告模式。再输入一次 ":" Left report mode. Type ")+chalk.white(e)+chalk.gray(oo()?" 即可执行。":" again to run it."));else{const n=eo>0?Date.now()-eo:void 0;if(await v(be,{curriculum_id:we.id,card_number:o,feedback_text:e,time_on_card_ms:n})){const e=t>1?oo()?`(${t} 行) `:`(${t} lines) `:"";console.log(chalk.green(oo()?` ✓ 已收到${e},谢谢帮助完善这张卡。`:` ✓ Thanks ${e}— your report was recorded.`))}else console.log(chalk.yellow(oo()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}console.log(),qe()}if(Be){const o=e.trim();if(/^(quit|exit|q|back|b|menu|home)$/i.test(o))return Be=!1,console.log(),console.log(chalk.yellow(oo()?` ⚠ "${o}" 看起来是导航命令,不是昵称 — 未提交。`:` ⚠ "${o}" looks like a navigation command, not a nickname — nothing submitted.`)),console.log(chalk.gray(oo()?" 已跳过昵称(下次上榜会再问)。再输入一次 ":" Nickname skipped (asked again next time you medal). Type ")+chalk.white(o)+chalk.gray(oo()?" 即可执行该命令。":" again to run it.")),console.log(),void qe();if(!o)return Be=!1,console.log(chalk.gray(oo()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void qe();const t=await _({token:be,nickname:o});if(t.ok)Be=!1,console.log(chalk.bold.green(oo()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(oo()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{He+=1;const e="taken"===t.code?oo()?"已被占用":"already taken":"bad_charset"===t.code?oo()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?oo()?"未通过审核":"did not pass review":t.message||"error";if(!(He>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(oo()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void qe();Be=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(oo()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void qe()}if(Ve){Ve=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ue=!0;try{console.log(),console.log(chalk.gray(oo()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await x({token:be,cardNumber:Ae.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(oo()?"评审暂不可用。":"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(oo()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(` ${(e=>{switch(e){case"green":return"🟢 "+(oo()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(oo()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(oo()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(oo()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier)}`)),e.manipulation&&console.log(chalk.red(oo()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=oo()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(oo()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(oo()?` 第 ${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 Co(e.feedback))console.log(chalk.white(` ${o}`))}e.improve&&(console.log(),console.log(chalk.cyan(oo()?" 改进提问: ":" 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(` (${oo()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Ge.add(Ae.currentCard):Ge.delete(Ae.currentCard),"number"==typeof e.rank&&to.set(Ae.currentCard,e.rank);const o=await P({token:be,curriculumId:we.id,cardNumber:Ae.currentCard});o.ok&&o.totals&&o.chapters&&(me({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!$e&&(Be=!0,He=0,console.log(chalk.bold.yellow(oo()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(oo()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(oo()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Ue=!1}})():(console.log(chalk.gray(oo()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==Le&&(console.log(chalk.gray(oo()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void qe()}if(Xe)return Xe=!1,wo(),void qe();if(!o)return void qe();if(Je)return"exit"===await i(e.trim())&&(Je=!1),void qe();if(Ye){if(["q","quit","exit","back","b","menu"].includes(o))return Ye=!1,console.log(chalk.gray(oo()?" 已退出 🐼 AI 熊猫导师,回到卡片。":" Left the 🐼 AI Panda Tutor — back to the card.")),console.log(),void qe();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await vo(n,t?"fast":"deep"),console.log(chalk.gray(oo()?" (↩ q = 返回卡片 · ! 开头 = 快答)":" (↩ q = back to card · prefix ! = quick answer)"))),void qe()}if(Fe&&go){if(/^(\/?(read|open|edit|run|debug|list|submit|recall)\b|contest\b|back$|b$|exit$|\d+$)/.test(o)&&r(`learn-arena p${go.phase}s${go.data.slot}: ${o}`),"back"===o||"b"===o||"exit"===o||"quit"===o||"q"===o)return Fe=!1,console.log(chalk.gray(oo()?" ↩ 已离开竞技场,回到课程。":" ↩ Left the arena — back to the lesson.")),wo(),void qe();if(/^\d+$/.test(o))return Wo(o),void qe();const e=/^\/?(read|open|edit|run|debug|list|recall)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,n]=e;return"list"===o?Eo():n?"read"===o||"open"===o?Wo(n):"edit"===o?await(async e=>{const o=So(e);if(!o)return;const t=f(go.dir,`sol-${o.n}.py`);return N()?j()?(console.log(chalk.yellow(oo()?" 你确实在 Ubuntu 里 — 但这个 icoa 是 Windows 版。":" You ARE inside Ubuntu — but this icoa is the Windows build.")),console.log(chalk.gray(oo()?" WSL 会把 Windows 的 PATH 接上,所以先找到了 Windows 那份。":" WSL appends the Windows PATH, so it found the Windows copy first.")),console.log(chalk.gray(oo()?" 当前跑的是: ":" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.gray(oo()?" 修法 — 先确认 npm 本身是 Linux 的:":" Fix — check npm ITSELF is Linux first:")),console.log(chalk.bold.cyan(" which npm")+chalk.gray(oo()?" ← 不能是 /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(oo()?" ← bash 缓存了旧路径":" bash caches the old path")),console.log(chalk.gray(oo()?" 然后重启 icoa,查 ":" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(),console.log(chalk.gray(oo()?" 你的代码没丢 — 就在 ~/icoa-contest/,换成 Linux 版后照样在。":" Your code is safe in ~/icoa-contest/ — the Linux build sees it too.")),void console.log()):(console.log(chalk.yellow(oo()?" icoa 正跑在 Windows 上,不在 Ubuntu(WSL)里。":" icoa is running on Windows, not inside Ubuntu (WSL).")),console.log(chalk.gray(oo()?" 竞技场的编辑器和本地试跑都在 Linux 那一侧。":" The arena's editor and local test run both live on the Linux side.")),console.log(chalk.gray(oo()?" 修法:开 Ubuntu 终端,再在里面跑 ":" Fix: open your Ubuntu shell and run ")+chalk.bold.cyan("icoa")),console.log(chalk.gray(oo()?" (Windows 终端里输 wsl 就进去了;进度不会丢。)":" (Type wsl in Windows Terminal. Your progress is safe.)")),console.log(),console.log(chalk.gray(oo()?" 临时办法 — 用记事本打开这个文件:":" Stopgap — open this file in Notepad:")),console.log(chalk.bold.white(` ${t}`)),void console.log()):D("vi")?(console.log(chalk.gray(oo()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await Mo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(oo()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(oo()?" 自测样例。":" to self-check the sample.")),void console.log()):(console.log(chalk.yellow(oo()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),console.log(chalk.bold.white(` ${t}`)),void console.log(chalk.gray(oo()?" 想装上 vi: sudo apt install vim":" To install vi: sudo apt install vim")))})(n):"run"===o?(e=>{const o=So(e);if(!o)return;const{p:n,n:l}=o,r=f(go.dir,`sol-${l}.py`);if(!d(r))return void console.log(chalk.yellow(oo()?` 还没有 sol-${l}.py — 先 /edit ${l}。`:` No sol-${l}.py yet — /edit ${l} first.`));const s=(n.samples??[])[0];if(!s)return void console.log(chalk.gray(oo()?` 本题无样例(设计如此)— 用 /debug ${l} 自己试,或直接 /submit ${l}。`:` This problem ships no sample (by design) — try /debug ${l}, or go straight to /submit ${l}.`));let a="";try{a=t("python3",[r],{input:s.in.endsWith("\n")?s.in:`${s.in}\n`,timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if("ENOENT"===o.code)Lo();else if(o.killed)console.log(chalk.yellow(oo()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(oo()?" ✗ 程序报错:":" ✗ 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(oo()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(oo()?" 样例应输出:":" Sample expects:"));for(const e of c.split("\n"))console.log(chalk.green(` ${e}`));i===c?console.log(chalk.bold.green(oo()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(oo()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${l}`)):console.log(chalk.yellow(oo()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${l}`)+chalk.gray(oo()?" 改完再 /run。":" then /run again.")),console.log()})(n):"debug"===o?await(async e=>{const o=So(e);if(!o)return;const t=f(go.dir,`sol-${o.n}.py`);if(!d(t))return void console.log(chalk.yellow(oo()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`));console.log(chalk.gray(oo()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log();const n=await Mo("python3",[`sol-${o.n}.py`]);console.log(),"ENOENT"!==n?.code?(console.log(chalk.gray(oo()?" 回到竞技场。":" Back in the arena.")),console.log()):Lo()})(n):"recall"===o&&await(async e=>{const o=So(e);if(!o)return;if(!ve)return void ko();const{p:t,n:n}=o,l=f(process.cwd(),"icoa-contest"),r=`${we.id}-phase${go.phase}-g${go.data.slot}-archived-`;let s=null;try{for(const e of u(l))e.startsWith(r)&&(!s||e>s)&&(s=e)}catch{}const a=s?f(l,s,`sol-${n}.py`):null;if(!a||!d(a))return void console.log(chalk.gray(oo()?" 还没有这题的归档旧解 — 归档在 contest reset 时产生。":" No archived solution for this problem yet — archives are created on contest reset."));const i=y(a,"utf-8"),c=`${go.phase}-${go.data.slot}-${n}`,g=Math.min(3,(Ro.get(c)??0)+1);console.log(chalk.gray(oo()?` 🧭 教练回忆中(第 ${g} 级提示,不给原码)…`:` 🧭 Coach recalling (level ${g} hint — never your old code)…`));const m=await T({token:be,phase:go.phase,slot:go.data.slot,problemTitle:t.title,statement:t.statement,code:i,level:g,lang:oo()?"zh":"en"});if(m.ok){Ro.set(c,g),console.log();for(const e of he(m.hint??"",64))console.log(chalk.white(` ${e}`));console.log(),g<3&&console.log(chalk.gray(oo()?" 还想更具体?再输一次 ":" Want more? Type again: ")+chalk.bold.green(`/recall ${n}`)+chalk.gray(oo()?`(第 ${g+1} 级)`:` (level ${g+1})`)),console.log()}else"live_contest"===m.code?console.log(chalk.yellow(oo()?" ⚔ 比赛计时中 — 先靠自己,赛后再回忆。":` ⚔ ${m.message}`)):console.log(chalk.yellow(` ${m.message||"Coach unavailable."}`))})(n):console.log(chalk.yellow(oo()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(oo()?" (花名册: /list)":" (roster: /list)")),void qe()}if("contest"===o||"/contest"===o)return Eo(),void qe();const n="lang"===o||/^lang\s+\S+$/.test(o),l=/^(wide|wide on|wide off|normal|narrow)$/.test(o);if(!("submit"===s||s.startsWith("submit ")||o.startsWith("contest ")||"contest reset"===o||n||l||"menu"===o||"menu confirm"===o))return console.log(chalk.gray(oo()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void qe()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(oo()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void qe()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(Ee.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const r=l(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}Ee.resume(),o()};r.on("close",s),r.on("error",s)}),console.log(),void qe()}if("ai4ioai"===o||"/ai4ioai"===o)return await c()&&(Je=!0),void qe();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!ve)return ko(),void qe();Ze||(Ze=!0,console.log(),console.log(chalk.bold.cyan(oo()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(oo()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(oo()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),oo()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Ye=!0;const e=io(Ae.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(oo()?"🐼 AI 熊猫导师":"🐼 AI Panda Tutor")+(o?chalk.gray(oo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(oo()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void qe()}return await vo(n,t?"fast":"deep"),void qe()}if(!Fe&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!ve)return ko(),void qe();const e=io(Ae.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(oo()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(oo()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(oo()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(oo()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(oo()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(oo()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(oo()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Ve=!0,void qe()}const w=!Fe&&"honors"===ze&&/^[1-3]$/.test(o);if(!Fe&&ze&&/^\/?view\s+([4-9]|\d{2,})$/.test(o))return console.log(chalk.yellow(oo()?" 只有 view 1 / view 2 / view 3。":" Only view 1, view 2 and view 3 exist.")),console.log(chalk.gray(oo()?" ↩ back 回上一层":" ↩ back goes up one level")),void qe();if(!Fe&&(w||"/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!ve)return ko(),void qe();const e=/^\/?view ([1-3])$/.exec(o),t=w?parseInt(o,10):e?parseInt(e[1],10):void 0;return await(async e=>{Ue=!0;try{console.log();const o=await E({token:be,cardNumber:Ae.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(oo()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Ge.delete(Ae.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Ge.add(Ae.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(oo()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${Ae.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${Ae.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(oo()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(oo()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=Co(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(` ${e}`))}),0===e.questions.length&&console.log(chalk.gray(oo()?" (无可显示的提问)":" (no questions to show)"))}console.log(),ze="view",console.log(chalk.gray((oo()," "))+chalk.bold.cyan("↩ back")+chalk.gray(oo()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Ue=!1}})(t),void qe()}if("/honors"===o||"honors"===o)return $e?(console.log(),console.log(chalk.gray(oo()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void qe()):(await To(),void qe());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return se(we,Ae),void qe();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(R().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void qe();const t=we.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),l="en"===n||"zh"===n&&t,r=l?n:"en";return O({language:r}),l?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(r)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),Le=null,We=null,Me=null,De(),Xe=!1,Ve=!1,await Ao(),void qe()}if(["wide","wide on","normal","narrow","wide off"].includes(o)){const e="wide"===o||"wide on"===o;return e===!!R().learnWide?(console.log(chalk.gray(e?oo()?ye()<=64?` 宽屏已开,但终端只有 ${process.stdout.columns||64} 列 — 画面已是最大可用宽度。输 normal 关闭。`:` 已是宽屏(${ye()} 列)。输 normal 恢复 64 列。`:ye()<=64?` Wide is on, but your terminal is only ${process.stdout.columns||64} cols — already at max usable width. Type normal to switch it off.`:` Already wide (${ye()} cols). Type normal to restore 64.`:oo()?" 已是标准 64 列。输 wide 拉伸到终端宽度。":" Already at the standard 64 cols. Type wide to stretch.")),void qe()):(O({learnWide:e}),ue(e),e&&ye()<=64?(console.log(chalk.yellow(oo()?` 终端只有 ${process.stdout.columns||64} 列 — 已是可用最大宽度,画面不会变化。`:` Your terminal is only ${process.stdout.columns||64} cols — already at the maximum usable width, so nothing changes.`)),console.log(chalk.gray(oo()?" 拉宽窗口后会自动生效;输 normal 关闭宽屏。":" Widen the window and it takes effect automatically; type normal to switch it off.")),void qe()):(console.log(chalk.green(" ✓ ")+chalk.gray(e?oo()?`宽屏开 — 卡片拉伸到终端宽度(现在 ${ye()} 列,上限 96)。输 normal 恢复。`:`Wide mode ON — cards stretch to your terminal (now ${ye()} cols, max 96). Type normal to restore.`:oo()?"已恢复 64 列标准宽。输 wide 再拉伸。":"Back to the 64-col standard width. Type wide to stretch again.")),Le=null,We=null,Me=null,De(),Xe=!1,Ve=!1,await Ao(),void qe()))}if("sim"===o){const e=io(Ae.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=p(b(import.meta.url)),o=[f(e,"..","..","panda","mujoco-launcher.py"),f(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(d(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),l("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void qe()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void qe())}if("bookmark"===o||"unbookmark"===o||"bookmark off"===o){const e=Ae.currentCard,t=Ae.bookmarks.includes(e),n="bookmark"!==o;return n?Ae.bookmarks=Ae.bookmarks.filter(o=>o!==e):t||Ae.bookmarks.push(e),U(Ae),n?console.log(t?chalk.gray(oo()?` ✓ 已取消收藏第 ${e} 卡。`:` ✓ Card ${e} un-bookmarked.`):chalk.gray(oo()?` 第 ${e} 卡本就没有收藏。输 bookmark 可收藏。`:` Card ${e} was not bookmarked. Type bookmark to add one.`)):console.log(t?chalk.gray(oo()?` 第 ${e} 卡已在收藏中。输 unbookmark 取消。`:` Card ${e} is already bookmarked. Type unbookmark to remove it.`):chalk.gray(oo()?` ✓ 已收藏第 ${e} 卡。输 unbookmark 取消。`:` ✓ Card ${e} bookmarked. Type unbookmark to remove it.`)),void qe()}if("e"===o)return Re=Ae.currentCard,console.log(chalk.gray(oo()?" 描述问题(回车提交 / 空行取消 / 可直接粘贴多行):":" Describe the issue (Enter to submit / blank to cancel / paste multi-line is fine):")),void qe();if("back"===o||"b"===o)return"view"===ze?(await To(),void qe()):"honors"===ze?(ze=null,wo(),void qe()):(Ae.currentCard>1&&(Ae.currentCard-=1),We=null,Me=null,Le=null,U(Ae),wo(),void qe());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(!uo)return console.log(chalk.yellow(oo()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void qe();const e=mo(Ae.currentCard);if("contest reset"===o){const o=await S(be,e);if(o.ok){console.log(chalk.yellow(oo()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`));const o=(new Date).toISOString().replace(/[:.]/g,"-").slice(0,19);for(let t=1;t<=3;t++){const n=f(process.cwd(),"icoa-contest",`${we.id}-phase${e}-g${t}`);if(d(n))try{m(n,`${n}-archived-${o}`),console.log(chalk.gray(oo()?" 📦 旧答题文件已归档: ":" 📦 Old solution files archived: ")+chalk.gray(`${n}-archived-${o}`))}catch{console.log(chalk.yellow(oo()?` ⚠ 归档失败(不影响重开): ${n}`:` ⚠ Could not archive (reset still fine): ${n}`))}}console.log(chalk.gray(oo()?" 新场次将生成全新模板 — 计时窗口内写的才算数。":" A fresh window gets fresh templates — only work done on the clock counts.")),go=null,Fe=!1}else console.log(chalk.red(` ✗ ${o.message||"reset failed"}`));return void qe()}const t=/^\/?contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(oo()?" 连接判分赛…":" Contacting contest server…"));const n=await q(be,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(oo()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void qe();const l=n.data,r=f(process.cwd(),"icoa-contest",`${we.id}-phase${e}-g${l.slot}`);g(r,{recursive:!0});const s=go&&go.phase===e&&go.data.slot===l.slot?go.tried:new Set;go={phase:e,dir:r,data:l,tried:s},((e,o)=>{e.problems.forEach((t,n)=>{const l=n+1,r=(t.samples??[])[0];r&&h(f(o,`sample-${l}.txt`),r.in.endsWith("\n")?r.in:`${r.in}\n`);const s=f(o,`sol-${l}.py`);if(d(s))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...Io(t.statement,72)];if(t.statement_zh&&a.push("#",`# Other language: type "lang zh" in icoa, then /read ${l} for the Chinese statement.`),r){a.push("#",`# Sample input (also in sample-${l}.txt):`);for(const e of r.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of r.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 ${l} = sample self-check · /debug ${l} = free-input run · /submit ${l} = judge`,"",""),h(s,a.join("\n"))})})(l,r),Fe=!0,Eo(),console.log(chalk.gray(oo()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(r));const a=l.problems.findIndex(e=>!l.solved.includes(e.id))+1||1;return console.log(chalk.white(oo()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(oo()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void qe()}if("submit"===s)return console.log(chalk.yellow(oo()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(oo()?" 例如 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)")),go||console.log(chalk.gray(oo()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void qe();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!go)return console.log(chalk.yellow(oo()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void qe();const n=go.data.problems,l=parseInt(o,10);if(Number.isInteger(l)&&l>=1&&l<=n.length&&!n.some(e=>e.id===o)&&(o=n[l-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(oo()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void qe();const r=n.findIndex(e=>e.id===o)+1,a=t||f(go.dir,`sol-${r}.py`);let i;try{i=y(a,"utf-8")}catch{return console.log(chalk.red(oo()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void qe()}console.log(chalk.gray(oo()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await W(be,go.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(oo()?" ⏱ 没有进行中的计时(可能已超时)。":" ⏱ No live timed attempt (time may be up).")+chalk.gray((oo()," "))+chalk.bold.green("contest")+chalk.gray(oo()?" 看花名册 · ":" shows the roster · ")+chalk.bold.green("contest reset")+chalk.gray(oo()?" 满血重开计时。":" restarts the clock fresh.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void qe();const d=c.data;if(d.already_ac)console.log(chalk.green(oo()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(oo()?" ✓ AC — 本题满分":" ✓ AC — full marks on this problem")+chalk.gray(` · ${d.passed_tests??d.total_tests??"?"}/${d.total_tests??"?"} `+(oo()?"隐藏用例全过":"hidden tests passed")+` · ${d.time_ms??"?"}ms`)),go.data.solved.includes(o)||go.data.solved.push(o),go.tried.delete(o);else{go.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?oo()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(oo()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=L(d.deadline||"");if(console.log(chalk.white(oo()?` 本组进度: 已过 ${d.ac_count} 题 · 过 ${d.need} 题过关(共 ${d.n} 题)`:` Group progress: ${d.ac_count} solved · ${d.need} needed to pass (${d.n} problems)`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(oo()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await yo();else if(!d.late){const e=n.findIndex(e=>!go.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(oo()?" 下一题: ":" Next: ")+chalk.bold.green(`/read ${e+1}`)+chalk.gray(` ${_o(n[e])}`))}return void qe()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>we.totalCards)return console.log(chalk.yellow(` Card number must be 1..${we.totalCards}. Try: `)+chalk.bold.green("card 1")),void qe();const n=await po(t);return n?(console.log(n),void qe()):(Ae.currentCard=t,We=null,Me=null,Le=null,U(Ae),wo(),void qe())}if(null!==Le&&["y","yes","n","no"].includes(o)){const e=io(Le);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,l=Date.now()-eo;B(Ae,e.number),Z(Ae,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),U(Ae);const{renderCheckFeedback:r}=await import("../lib/learn-render.js");if(r(e,t,n,!1),no.push(k(be,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:l}).catch(()=>{})),Le=null,e.solution&&e.solution.length>0)return void qe();if(Ae.currentCard<we.totalCards){const e=Ae.currentCard,o=await po(e+1);if(o)return await fo(e),console.log(o),void qe();Ae.currentCard+=1,U(Ae),await fo(e)?bo():wo(),qe()}else ie(we,Ae),qe();return}}if(null!==We&&["a","b","c","d"].includes(o)){const e=io(We);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(H(Ae,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),B(Ae,e.number),U(Ae),X(e,t,n,Ae),no.push(k(be,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),We=null,n)if(Ae.currentCard<we.totalCards){const e=await po(Ae.currentCard+1);if(e)return console.log(e),void qe();Ae.currentCard+=1,U(Ae),wo()}else ie(we,Ae),qe();else qe();return}}if(null!==Me){if("done"===o){const e=io(Me);if(e&&"practical"===e.type)return J(Ae,e.number),B(Ae,e.number),U(Ae),oe(e),Me=null,void qe()}if("skip"===o)return B(Ae,Me),U(Ae),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Me=null,void qe()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==We)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void qe();if(null!==Me)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void qe();if(null!==Le)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void qe();const e=Ae.currentCard,o=e<we.totalCards?await po(e+1):null;return o?(await fo(e),console.log(o),void qe()):(Ae.currentCard+=1,U(Ae),Ae.currentCard>we.totalCards?ie(we,Ae):await fo(e)?bo():wo(),void qe())}if(null!==Le)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void qe();if(null!==We)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void qe();if(null!==Me)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void qe();"view"===ze?console.log(chalk.gray(oo()?" 这一层可用: ":" On this screen: ")+chalk.white("back")+chalk.gray(oo()?" 回榜单 · ":" to the board · ")+chalk.white("quit")+chalk.gray(oo()?" 回卡片":" to the card")):"honors"===ze?console.log(chalk.gray(oo()?" 这一层可用: ":" On this screen: ")+chalk.white("view 1 / view 2 / view 3")+chalk.gray(oo()?" 看详情 · ":" details · ")+chalk.white("back")+chalk.gray(oo()?" 回卡片":" 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")),qe()}else{if("view"===ze)return await To(),void qe();if("honors"===ze)return ze=null,wo(),void qe();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(`🔥 ${Ae.streakDays} day(s)`)),console.log(),Ie){Ee.removeAllListeners("line"),Se();for(const e of xe)Ee.on("line",e);Ee.prompt(),so()}else Ee.removeAllListeners("line"),Ee.close()}else if(no.length>0&&await Promise.race([Promise.allSettled(no),new Promise(e=>setTimeout(e,3e3))]),Ee.removeAllListeners("line"),Se(),Ie||!ao){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Ie?Ee:void 0),so()}else Ee.close()};Ee.on("line",e=>{Oo(e).catch(e=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),qe()})}),Ie||Ee.on("close",async()=>{no.length>0&&await Promise.race([Promise.allSettled(no),new Promise(e=>setTimeout(e,5e3))]),ao?so():process.exit(0)});try{wo(),qe();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(pe("Could not render this card — the curriculum may be malformed."),Ie){Ee.removeAllListeners("line"),Se();for(const e of xe)Ee.on("line",e);Ee.prompt()}else Ee.close();so()}await ro}),fe.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,l=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),r=await w(e),s=Date.now()-o;if(r){const e=r.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(r).length;l+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(l/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as l}from"./commands/connect.js";import{registerChallengeCommand as i}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerNoteCommand as m}from"./commands/note.js";import{registerLogCommand as c}from"./commands/log.js";import{registerLangCommand as g}from"./commands/lang.js";import{registerSetupCommand as d}from"./commands/setup.js";import{registerEnvCommand as p}from"./commands/env.js";import{registerAienvCommand as y}from"./commands/aienv.js";import{registerIpynbCommand as f}from"./commands/ipynb.js";import{registerAi4ctfCommand as h}from"./commands/ai4ctf.js";import{registerExamCommand as u}from"./commands/exam.js";import{registerCtf4aiDemoCommand as w}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as b}from"./commands/theme.js";import{registerLearnCommand as v}from"./commands/learn.js";import{registerCtf4VlaCommand as T}from"./commands/ctf4vla.js";import{registerDemo2Command as j}from"./commands/demo2.js";import{registerDemo4Command as A}from"./commands/demo4.js";import{registerDemo5Command as $}from"./commands/demo5.js";import{registerSimCommand as I}from"./commands/sim.js";import{registerArenaCommand as C}from"./commands/arena.js";import{registerKaggleCommand as E}from"./commands/kaggle.js";import{registerSprintCommand as _}from"./commands/sprint.js";import{registerTeleloadCommand as S}from"./commands/teleload.js";import{registerBoardCommand as x}from"./commands/board.js";import{getConfig as O,saveConfig as k}from"./lib/config.js";import{startRepl as L}from"./repl.js";import{RELAUNCH_CODE as N}from"./lib/menu-nav.js";import{setTerminalTheme as R}from"./lib/theme.js";import{cleanupTerminal as F}from"./lib/terminal-cleanup.js";import{checkForUpdates as U}from"./lib/update-check.js";import{detectIcoaInstalls as P,isWindowsBuildInWslShell as M}from"./lib/platform.js";import{ICOA_BIG as D}from"./lib/banner.js";import{readFileSync as G}from"node:fs";import{fileURLToPath as W}from"node:url";import{dirname as H,join as Y}from"node:path";const J=H(W(import.meta.url)),V=JSON.parse(G(Y(J,"..","package.json"),"utf-8")).version,X=chalk.cyan(" ─────────────────────────────────────────────────────"),q=`\n${X}\n\n${D.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${V}`)}\n\n${X}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=n?process.argv.slice(1,2):process.argv.slice(1),r=o(process.execPath,s,{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(r.signal){e=0;break}e=r.status,n=!0}while(e===N);F(),process.exit(e??0)}}const z=new o;if(z.name("icoa").version(V).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=O();R("high-contrast"===e.themeVariant?"high-contrast":"dark"),U(),function(){const o=P();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}(),function(){if(!M())return;const o="─".repeat(52);console.log(),console.log(chalk.yellow(` ${o}`)),console.log(chalk.yellow.bold(" ⚠ You ARE inside Ubuntu — but this icoa")),console.log(chalk.yellow.bold(" is the WINDOWS build.")),console.log(),console.log(chalk.gray(" WSL appends the Windows PATH, so ")+chalk.cyan("icoa")),console.log(chalk.gray(" found the Windows copy first. Almost")),console.log(chalk.gray(" nothing will work: no vi, no python3,")),console.log(chalk.gray(" env setup cannot install.")),console.log(),console.log(chalk.white(" Fix — inside Ubuntu:")),console.log(` ${chalk.bold.cyan("npm install -g icoa-cli")}`),console.log(chalk.gray(" Check: ")+chalk.bold.cyan("which icoa")+chalk.gray(" (not /mnt/c/...)")),console.log(chalk.yellow(` ${o}`)),console.log()}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();console.log(q);const s=!!o.resume||!!o.continue;if(process.argv.length<=2||s)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),s||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void L(z,s)}),e(z),n(z),s(z),r(z),t(z),l(z),i(z),a(z),m(z),c(z),g(z),d(z),p(z),y(z),f(z),h(z),u(z),w(z),b(z),v(z),T(z),j(z),A(z),$(z),I(z),C(z),E(z),S(z),_(z),x(z),z.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=O().geminiModel||"gemini-2.5-flash-lite";o?(k({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}z.parse();
2
+ import{Command as o}from"commander";import chalk from"chalk";import{registerCtfCommands as e}from"./commands/ctf.js";import{registerRefCommand as n}from"./commands/ref.js";import{registerShellCommand as s}from"./commands/shell.js";import{registerFilesCommand as r}from"./commands/files.js";import{registerViewCommand as t}from"./commands/view.js";import{registerConnectCommand as l}from"./commands/connect.js";import{registerChallengeCommand as i}from"./commands/challenge.js";import{registerDoctorCommand as a}from"./commands/doctor.js";import{registerNoteCommand as c}from"./commands/note.js";import{registerLogCommand as m}from"./commands/log.js";import{registerLangCommand as g}from"./commands/lang.js";import{registerSetupCommand as d}from"./commands/setup.js";import{registerEnvCommand as p}from"./commands/env.js";import{registerAienvCommand as h}from"./commands/aienv.js";import{registerIpynbCommand as y}from"./commands/ipynb.js";import{registerAi4ctfCommand as f}from"./commands/ai4ctf.js";import{registerExamCommand as u}from"./commands/exam.js";import{registerCtf4aiDemoCommand as w}from"./commands/ctf4ai-demo.js";import{registerThemeCommand as b}from"./commands/theme.js";import{registerLearnCommand as T}from"./commands/learn.js";import{registerCtf4VlaCommand as v}from"./commands/ctf4vla.js";import{registerDemo2Command as j}from"./commands/demo2.js";import{registerDemo4Command as $}from"./commands/demo4.js";import{registerDemo5Command as A}from"./commands/demo5.js";import{registerSimCommand as I}from"./commands/sim.js";import{registerArenaCommand as E}from"./commands/arena.js";import{registerKaggleCommand as C}from"./commands/kaggle.js";import{registerSprintCommand as _}from"./commands/sprint.js";import{registerTeleloadCommand as S}from"./commands/teleload.js";import{registerBoardCommand as x}from"./commands/board.js";import{getConfig as k,saveConfig as L}from"./lib/config.js";import{startRepl as O}from"./repl.js";import{RELAUNCH_CODE as R}from"./lib/menu-nav.js";import{setTerminalTheme as F}from"./lib/theme.js";import{cleanupTerminal as N}from"./lib/terminal-cleanup.js";import{checkForUpdates as U}from"./lib/update-check.js";import{detectIcoaInstalls as P,isWindowsBuildInWslShell as M}from"./lib/platform.js";import{ICOA_BIG as D}from"./lib/banner.js";import{readFileSync as G}from"node:fs";import{fileURLToPath as W}from"node:url";import{dirname as H,join as Y}from"node:path";const J=H(W(import.meta.url)),V=JSON.parse(G(Y(J,"..","package.json"),"utf-8")).version,X=chalk.cyan(" ─────────────────────────────────────────────────────"),q=`\n${X}\n\n${D.map(o=>` ${chalk.bold.white(o)}`).join("\n")}\n\n ${chalk.yellow("International Cyber Olympiad in AI 2026")}\n ${chalk.bold.magenta("The World's First AI-Native CLI Operating System")}\n ${chalk.bold.magenta("for Cybersecurity & AI Security Competition")}\n ${chalk.bold.magenta("and Olympiad for K-12")}\n\n ${chalk.green.bold("AI4CTF")} ${chalk.gray("[Day 1]")} ${chalk.white("AI as your teammate")}\n ${chalk.red.bold("CTF4AI")} ${chalk.gray("[Day 2]")} ${chalk.white("Challenge & evaluate AI systems")}\n ${chalk.cyan.bold("CTF4EAI")} ${chalk.gray("[Pioneer]")} ${chalk.white("Embodied AI security")}\n ${chalk.bold.yellow("AI is your teammate. AI is your target. AI is embodied.")}\n\n ${chalk.white("Sydney, Australia")} ${chalk.gray("Jun 27 - Jul 2, 2026")}\n ${chalk.cyan.underline("https://icoa2026.au")}\n\n ${chalk.gray(`CLI-Native Competition Terminal v${V}`)}\n\n${X}\n`;process.on("uncaughtException",o=>{"__REPL_NO_EXIT__"!==o.message&&(console.error(chalk.red("Error:"),o.message),process.exit(1))}),process.on("unhandledRejection",o=>{const e=o instanceof Error?o.message:String(o);"__REPL_NO_EXIT__"!==e&&(console.error(chalk.red("Error:"),e),process.exit(1))});{const o=process.argv.slice(2).some(o=>["-V","--version","-h","--help"].includes(o));if(!0===process.stdin.isTTY&&"1"!==process.env.ICOA_SUPERVISED&&!o){const{spawnSync:o}=await import("node:child_process");process.on("SIGINT",()=>{}),process.on("SIGTERM",()=>{});let e=0,n=!1;do{const s=n?process.argv.slice(1,2):process.argv.slice(1),r=o(process.execPath,s,{stdio:"inherit",env:{...process.env,ICOA_SUPERVISED:"1",...n?{ICOA_RELAUNCH:"1"}:{}}});if(r.signal){e=0;break}e=r.status,n=!0}while(e===R);N(),process.exit(e??0)}}const z=new o;if(z.name("icoa").version(V).description("ICOA CLI — CLI-Native CTF Competition Terminal").option("--resume","Resume previous session").option("--continue","Continue where you left off — jump straight to your last learn card / exam").action(async o=>{const e=k();F("high-contrast"===e.themeVariant?"high-contrast":"dark"),U(),function(){const o=P();if(o.length<=1)return;const e=o[0];if([...o.map(o=>o.version||"0.0.0")].sort((o,e)=>function(o,e){const n=o.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0);for(let o=0;o<3;o++)if((n[o]||0)!==(s[o]||0))return(n[o]||0)-(s[o]||0);return 0}(e,o))[0]!==e.version){console.log(),console.log(chalk.yellow.bold(" ⚠ Multiple icoa installations detected on PATH:"));for(let e=0;e<o.length;e++){const n=o[e],s=n.version?`v${n.version}`:"(version unreadable)",r=0===e?chalk.yellow("→"):" ",t=0===e?chalk.gray(" ← currently running (older — shadowing newer install)"):chalk.gray(" ← shadowed");console.log(` ${r} ${chalk.cyan(n.path.padEnd(28))} ${chalk.white(s)}${t}`)}console.log(),console.log(chalk.yellow(" The first install on PATH wins. To use the newer one, remove the older:")),console.log(),e.pkgDir?console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.pkgDir} ${e.path}`)}`):console.log(` ${chalk.bold.cyan(`sudo rm -rf ${e.path} # also delete its node_modules dir`)}`),console.log(),console.log(chalk.gray(" Then re-run icoa to confirm version banner shows the newer release.")),console.log()}}();const n=process.env.LANG||process.env.LC_ALL||process.env.LC_CTYPE||"";if(!/UTF-?8/i.test(n))if("win32"===process.platform){let o="";try{const{execFileSync:e}=await import("node:child_process");o=e("chcp.com",[],{encoding:"utf-8",timeout:1500,stdio:["ignore","pipe","ignore"]}).trim()}catch{}o.includes("65001")||(console.log(chalk.yellow(`⚠ Windows terminal is not using UTF-8 (current: ${o||"unknown"}).`)),console.log(chalk.gray(' Non-English text (Ukrainian, Chinese, Japanese, etc.) may show as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix (run before ")+chalk.cyan("icoa")+chalk.gray("): ")+chalk.cyan("chcp 65001")),console.log(chalk.gray(" Or stay in English inside the CLI: ")+chalk.cyan("lang en")),console.log())}else console.log(chalk.yellow(`⚠ Your terminal locale is not UTF-8 (LANG=${n||"(unset)"}).`)),console.log(chalk.gray(' Non-English text and box characters may display as "?" or garbled glyphs.')),console.log(chalk.gray(" Fix: ")+chalk.cyan("export LANG=en_US.UTF-8")+chalk.gray(" (or your locale, e.g. ")+chalk.cyan("zh_CN.UTF-8")+chalk.gray(", ")+chalk.cyan("uk_UA.UTF-8")+chalk.gray(")")),console.log();console.log(q);const s=!!o.resume||!!o.continue;if(process.argv.length<=2||s)return o.continue&&(process.env.ICOA_AUTO_RESUME="1"),s||"1"===process.env.ICOA_RELAUNCH||await async function(){const o=process.stdin;if(o.isTTY&&"function"==typeof o.setRawMode)return new Promise(e=>{let n=!1;const s=()=>{if(!n){n=!0,o.removeListener("data",r);try{o.setRawMode(!1)}catch{}o.pause(),e()}},r=()=>s();o.setRawMode(!0),o.resume(),o.once("data",r),console.log(chalk.gray(" (press any key to continue...)")),setTimeout(s,3e3)});await new Promise(o=>setTimeout(o,3e3))}(),void O(z,s)}),e(z),n(z),s(z),r(z),t(z),l(z),i(z),a(z),c(z),m(z),g(z),d(z),p(z),h(z),y(z),f(z),u(z),w(z),b(z),T(z),v(z),j(z),$(z),A(z),I(z),E(z),C(z),S(z),_(z),x(z),z.command("model",{hidden:!0}).argument("[name]","model name to switch to").action(o=>{const e=k().geminiModel||"gemini-2.5-flash-lite";o?(L({geminiModel:o}),console.log(),console.log(chalk.green(" Model switched: ")+chalk.gray(e)+chalk.white(" -> ")+chalk.bold.white(o)),console.log()):(console.log(),console.log(chalk.gray(" Current model: ")+chalk.white(e)),console.log(),console.log(chalk.gray(" Available models:")),console.log(chalk.bold.white(" Gemini 3.x (Latest)")),console.log(chalk.white(" model gemini-3.5-flash ")+chalk.gray("Newest stable, paid Tier 1+")),console.log(chalk.white(" model gemini-3-flash-preview ")+chalk.gray("Preview")),console.log(chalk.bold.white(" Gemini 2.5 (Stable)")),console.log(chalk.white(" model gemini-2.5-flash-lite ")+chalk.gray("Fastest, default, free tier")),console.log(chalk.white(" model gemini-2.5-flash ")+chalk.gray("Heavier, thinking enabled")),console.log(chalk.white(" model gemini-2.5-pro ")+chalk.gray("Strong reasoning, paid")),console.log(chalk.bold.white(" Open Source")),console.log(chalk.white(" model gemma-4-31b-it ")+chalk.gray("Free, open-source")),console.log(chalk.white(" model <any-model-id> ")+chalk.gray("Custom model")),console.log(),console.log(chalk.gray(" Translation uses gemini-3.5-flash for best quality.")),console.log())}),"1"===process.env.ICOA_RESET_STATE)try{const{clearExamState:o}=await import("./lib/exam-state.js");o(),console.log(chalk.yellow("⚠ ICOA_RESET_STATE=1 — local exam state wiped.")),console.log(chalk.gray(" (Token NOT revoked server-side. Re-enter a fresh token with `exam <token>`.)")),console.log()}catch(o){console.log(chalk.red("⚠ ICOA_RESET_STATE: could not clear state — ")+chalk.gray(String(o)))}z.hook("preAction",()=>{!function(){if(!M())return;const o="─".repeat(52);console.log(),console.log(chalk.yellow(` ${o}`)),console.log(chalk.yellow.bold(" ⚠ You ARE inside Ubuntu — but this icoa")),console.log(chalk.yellow.bold(" is the WINDOWS build.")),console.log(),console.log(chalk.gray(" WSL appends the Windows PATH, so ")+chalk.cyan("icoa")),console.log(chalk.gray(" found the Windows copy first. Almost")),console.log(chalk.gray(" nothing will work: no vi, no python3,")),console.log(chalk.gray(" env setup cannot install.")),console.log(),console.log(chalk.gray(" Running: ")+chalk.white(process.execPath)),console.log(),console.log(chalk.white(" Fix — inside Ubuntu, check npm is Linux FIRST:")),console.log(` ${chalk.bold.cyan("which npm")}${chalk.gray(" → must not be /mnt/c/...")}`),console.log(` ${chalk.bold.cyan("sudo npm install -g icoa-cli")}`),console.log(` ${chalk.bold.cyan("hash -r")}${chalk.gray(" → bash caches the old path")}`),console.log(chalk.gray(" Then restart icoa and check ")+chalk.bold.cyan("which icoa")),console.log(chalk.yellow(` ${o}`)),console.log()}()}),z.parse();
@@ -1 +1 @@
1
- export function parseKaggleTaskList(e){const t=e??{},s=(t.data??t).tasks;if(!Array.isArray(s))return[];const n=[];for(const e of s){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&n.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",description:"string"==typeof t.description&&""!==t.description?t.description:void 0,kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0,data_base:"string"==typeof t.data_base&&""!==t.data_base?t.data_base:null,id_col:"string"==typeof t.id_col?t.id_col:void 0,target_col:"string"==typeof t.target_col?t.target_col:void 0,n_train:"number"==typeof t.n_train?t.n_train:void 0,n_test:"number"==typeof t.n_test?t.n_test:void 0,judge:"string"==typeof t.judge&&""!==t.judge?t.judge:void 0,board_event:"string"==typeof t.board_event&&""!==t.board_event?t.board_event:null,needs_gpu:!0===t.needs_gpu})}return n}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const s=t.replace(/\/$/,"");return{train:`${s}/train.csv`,test:`${s}/test.csv`,sample_submission:`${s}/sample_submission.csv`}}export function buildStarterCells(e,t){const s=t.id_col??"id",n=t.target_col??"target";var a;a=t.metric,/rmse|mse|mae|error/i.test(a);const i="icoa-holdout"===t.judge,r=e=>({kind:"markdown",source:e,result:null}),o=e=>({kind:"code",source:e.join("\n"),result:null}),l=[`# ${t.title}`,"",...t.description?[t.description,""]:[],`Kaggle-style practice — metric: **${t.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${n}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...i?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],"","**AI help:** split your terminal (`Ctrl-b %`), run `icoa` in the right pane","and type `ai4ioai` for a live Gemma 3n E4B. Ask it for feature ideas or bug fixes —","then verify every suggestion with the val score. A tip that lowers it, drop it.",...t.licence?["",`**Data licence:** ${t.licence}`]:[],...t.attribution?[`**Attribution:** ${t.attribution}`]:[]].join("\n"),c=o(["# setup — load the data (leave as is)","import os","import numpy as np","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.feature_extraction.text import TfidfVectorizer","from sklearn.model_selection import train_test_split","from sklearn.metrics import accuracy_score, mean_squared_error","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${e}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...t.data_base?[`DATA_BASE = "${t.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")','sub_fmt = pd.read_csv(DIR + "/sample_submission.csv")',"","# 🔴 The submission column names are NOT always the training column names.","# On tasks imported from other platforms the two genuinely differ: train.csv",'# labels the answer "class" or "result" while sample_submission.csv calls it','# "answer". Hard-coding the submission name here used to raise KeyError on the',"# very first cell. So trust the DATA: whatever column train has and test lacks","# is the thing to predict.",`SUB_ID, SUB_TARGET = "${s}", "${n}" # names the submission file wants`,"only_train = [c for c in train.columns if c not in test.columns]","TARGET = only_train[-1] if only_train else SUB_TARGET","shared = [c for c in train.columns if c in test.columns]","# Only treat a column as the row id when the submission actually names it AND",'# both files carry it. Falling back to "first shared column" silently spent a',"# real feature as an id on tasks whose id lives only in test.csv.","ID = SUB_ID if SUB_ID in shared else None",'assert TARGET in train.columns, f"cannot find the label column in {list(train.columns)}"',"","# Regression or classification? Decided from the labels, not from metadata —","# several tasks ship continuous labels, and handing those to a classifier",'# raises "Unknown label type: continuous".',"REG = is_numeric_dtype(train[TARGET]) and train[TARGET].nunique() > 20",'print(f"train {train.shape} · test {test.shape} · predicting {TARGET!r} "'," f\"({'regression' if REG else 'classification'})\")"]),d=o(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Category (<= 20 distinct): one-hot.","# Free text: TF-IDF — on a text task the sentences ARE the signal, and dropping",'# them as "high-cardinality" leaves nothing to train on (that used to crash the','# whole notebook with "No objects to concatenate").',"# only columns present in BOTH files — a train-only column cannot be a feature","# at prediction time, and indexing test with it raises KeyError.","feat = [c for c in shared if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","# Everything else is vectorised as text. Requiring a long average length here","# used to throw away high-cardinality SHORT strings — ingredient names, single","# words, category codes — which on several tasks are the entire signal, leaving","# the notebook with zero features.","txt = [c for c in feat if c not in num and c not in cat]","for c in num:"," med = Xtr_raw[c].median()"," Xtr_raw[c] = Xtr_raw[c].fillna(med)"," Xte_raw[c] = Xte_raw[c].fillna(med)","blocks_tr, blocks_te = [], []","if num or cat:"," d_tr = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)"," d_te = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",' d_tr, d_te = d_tr.align(d_te, join="left", axis=1, fill_value=0)'," blocks_tr.append(d_tr.to_numpy(dtype=float))"," blocks_te.append(d_te.to_numpy(dtype=float))","for c in txt:"," # fillna BEFORE astype(str): a real NaN reaching the vectoriser raises",' # "np.nan is an invalid document", and astype alone does not catch it.',' tr_txt = Xtr_raw[c].fillna("").astype(str)',' te_txt = Xte_raw[c].fillna("").astype(str)'," # min_df=1: on a short-token column (one ingredient per row) min_df=2 can"," # filter the vocabulary down to nothing."," long_col = tr_txt.str.len().mean() >= 12"," # Try the good settings, then a permissive fallback, then give up on THIS"," # column only. A column whose vocabulary prunes to nothing used to abort the",' # whole run with "After pruning, no terms remain".',' for kw in ({"min_df": 2 if long_col else 1,',' "analyzer": "word" if long_col else "char_wb"},',' {"min_df": 1, "analyzer": "char_wb"}):'," try:"," vec = TfidfVectorizer(max_features=3000, ngram_range=(1, 2), **kw)"," b_tr = vec.fit_transform(tr_txt).toarray()"," blocks_tr.append(b_tr)"," blocks_te.append(vec.transform(te_txt).toarray())"," break"," except ValueError as e:"," last = e"," else:",' print(f" skipped text column {c!r}: {last}")',"if not blocks_tr:"," raise SystemExit(",' f"No usable feature columns. The shared columns are {feat} — none of them "',' f"is numeric, categorical or text.\\n"',' f"Two kinds of task land here, and both are real work rather than a bug:\\n"',' f" 1. audio/image — train.csv only lists sample ids and labels, and the "',' f"signal is in the media files shipped with the task. Load them "',' f"(librosa / PIL), turn each file into a feature row.\\n"',' f" 2. train.csv and test.csv describe different things (a retrieval or "',' f"matching task). Read both files, work out what links a test row to a "',' f"train row, and build that mapping yourself.\\n"',' f"Either way: replace this cell. train={list(train.columns)} "',' f"test={list(test.columns)}"'," )","X = np.hstack(blocks_tr)","X_test = np.hstack(blocks_te)","y = train[TARGET]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"{X.shape[1]} model-ready features "',' f"({len(num)} numeric, {len(cat)} one-hot, {len(txt)} TF-IDF text)")']),u=o(["# MODEL — a working baseline. Improve THIS cell to climb the board.","from sklearn.linear_model import LogisticRegression, Ridge","# REG was decided from the labels back in setup.","model = Ridge() if REG else LogisticRegression(max_iter=2000)"]),m=o(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)","p_val = model.predict(X_val)","if REG:",' print("val RMSE:", round(mean_squared_error(y_val, p_val) ** 0.5, 4))',"else:"," acc = accuracy_score(y_val, p_val)",' print("val accuracy:", round(acc, 4))'," if acc < 0.3:"," # A near-zero baseline is the expected result on several of these tasks,"," # not a broken notebook — say so, or the student reads it as a bug.",' print(" A score this low usually means the linear baseline cannot "',' "represent the pattern at all (combination rules, sequences, "',' "spelling). That IS the task: build features that expose it, "',' "or switch to a model that can. The chain itself works — "',' "submission.csv is written either way.")']),p=o(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',"# Copy the layout of sample_submission.csv and swap in the predictions, rather","# than rebuilding the file from column names. Some tasks want more than two","# columns (e.g. subtaskID,datapointID,answer) and a hand-built 2-column frame","# is rejected by the grader even when every prediction is right.","if len(sub_fmt) == len(pred):"," sub = sub_fmt.copy()"," sub[sub.columns[-1]] = pred","else:"," keys = {}"," if ID is not None and ID in test.columns:"," keys[SUB_ID] = test[ID]"," keys[SUB_TARGET] = pred"," sub = pd.DataFrame(keys)",' print(f"NOTE: sample_submission has {len(sub_fmt)} rows but test has "',' f"{len(pred)} — built the file from column names instead; "',' f"check it against the task page before submitting.")',"sub.to_csv(out, index=False)",'print("wrote", out, "·", list(sub.columns))',i?`print("score it: icoa kaggle submit ${t.comp_id}")`:'print("format check: icoa kaggle check")']),h=i?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${t.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:t.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${t.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This is a placeholder practice dataset — it has no live Kaggle page yet._","When the real competition dataset lands, this cell will link straight to","its Kaggle submission page. The loop is identical: upload `submission.csv`,","read the score, improve the MODEL cell, repeat."];return[r(l),c,d,u,m,p,r(h.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},s=t.data??t,n=s&&"object"==typeof s?s:{};return"number"==typeof n.score&&"string"==typeof n.metric?{ok:!0,score:n.score,metric:n.metric,rank:"number"==typeof n.rank_at_time?n.rank_at_time:null,fieldSize:"number"==typeof n.field_size?n.field_size:null,deduped:!0===n.deduped,boardEvent:"string"==typeof n.board_event?n.board_event:null}:"string"==typeof n.reason&&""!==n.reason?{ok:!1,reason:n.reason,error:"string"==typeof n.error?n.error:void 0,problems:Array.isArray(n.problems)?n.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const s=[],n=e.trim().split(/\r?\n/),a=t.trim().split(/\r?\n/),i=n[0]??"",r=a[0]??"";i.trim()!==r.trim()&&s.push(`header mismatch: expected "${r}", got "${i}"`);const o=n.slice(1).filter(e=>""!==e.trim()),l=a.slice(1).filter(e=>""!==e.trim());o.length!==l.length&&s.push(`row count mismatch: expected ${l.length}, got ${o.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),d=c(o),u=c(l),m=[...u].filter(e=>!d.has(e)),p=[...d].filter(e=>!u.has(e));if(m.length>0||p.length>0){const e=[];m.length>0&&e.push(`${m.length} missing (e.g. ${m[0]})`),p.length>0&&e.push(`${p.length} unknown (e.g. ${p[0]})`),s.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<o.length;e++)if(o[e].split(",").some(e=>""===e.trim())){s.push(`empty cell in data row ${e+1}`);break}return{ok:0===s.length,problems:s}}
1
+ export function parseKaggleTaskList(e){const t=e??{},a=(t.data??t).tasks;if(!Array.isArray(a))return[];const s=[];for(const e of a){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&s.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",description:"string"==typeof t.description&&""!==t.description?t.description:void 0,kaggle_url:"string"==typeof t.kaggle_url?t.kaggle_url:null,licence:"string"==typeof t.licence?t.licence:void 0,attribution:"string"==typeof t.attribution?t.attribution:void 0,data_base:"string"==typeof t.data_base&&""!==t.data_base?t.data_base:null,id_col:"string"==typeof t.id_col?t.id_col:void 0,target_col:"string"==typeof t.target_col?t.target_col:void 0,n_train:"number"==typeof t.n_train?t.n_train:void 0,n_test:"number"==typeof t.n_test?t.n_test:void 0,judge:"string"==typeof t.judge&&""!==t.judge?t.judge:void 0,board_event:"string"==typeof t.board_event&&""!==t.board_event?t.board_event:null,needs_gpu:!0===t.needs_gpu})}return s}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const a=t.replace(/\/$/,"");return{train:`${a}/train.csv`,test:`${a}/test.csv`,sample_submission:`${a}/sample_submission.csv`}}export function buildStarterCells(e,t){const a=t.id_col??"id",s=t.target_col??"target";var r;r=t.metric,/rmse|mse|mae|error/i.test(r);const n="icoa-holdout"===t.judge,i=e=>({kind:"markdown",source:e,result:null}),o=e=>({kind:"code",source:e.join("\n"),result:null}),l=[`# ${t.title}`,"",...t.description?[t.description,""]:[],`Kaggle-style practice — metric: **${t.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${s}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...n?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],"","**AI help:** split your terminal (`Ctrl-b %`), run `icoa` in the right pane","and type `ai4ioai` for a live Gemma 3n E4B. Ask it for feature ideas or bug fixes —","then verify every suggestion with the val score. A tip that lowers it, drop it.",...t.licence?["",`**Data licence:** ${t.licence}`]:[],...t.attribution?[`**Attribution:** ${t.attribution}`]:[]].join("\n"),c=o(["# setup — load the data (leave as is)","import os","import numpy as np","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.feature_extraction.text import TfidfVectorizer","from sklearn.model_selection import train_test_split","from sklearn.metrics import accuracy_score, mean_squared_error","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${e}"`,'OUT = os.environ.get("ICOA_KAGGLE_OUT") or DIR',...t.data_base?[`DATA_BASE = "${t.data_base.replace(/\/$/,"")}"`,'if not os.path.exists(DIR + "/train.csv"):'," import urllib.request"," os.makedirs(DIR, exist_ok=True)",' for f in ("train.csv", "test.csv", "sample_submission.csv"):',' urllib.request.urlretrieve(DATA_BASE + "/" + f, DIR + "/" + f)']:[],'train = pd.read_csv(DIR + "/train.csv")','test = pd.read_csv(DIR + "/test.csv")','sub_fmt = pd.read_csv(DIR + "/sample_submission.csv")',"","# 🔴 The submission column names are NOT always the training column names.","# On tasks imported from other platforms the two genuinely differ: train.csv",'# labels the answer "class" or "result" while sample_submission.csv calls it','# "answer". Hard-coding the submission name here used to raise KeyError on the',"# very first cell. So trust the DATA: whatever column train has and test lacks","# is the thing to predict.",`SUB_ID, SUB_TARGET = "${a}", "${s}" # names the submission file wants`,"only_train = [c for c in train.columns if c not in test.columns]","TARGET = only_train[-1] if only_train else SUB_TARGET","shared = [c for c in train.columns if c in test.columns]","# Only treat a column as the row id when the submission actually names it AND",'# both files carry it. Falling back to "first shared column" silently spent a',"# real feature as an id on tasks whose id lives only in test.csv.","ID = SUB_ID if SUB_ID in shared else None",'assert TARGET in train.columns, f"cannot find the label column in {list(train.columns)}"',"","# Regression or classification? Decided from the labels, not from metadata —","# several tasks ship continuous labels, and handing those to a classifier",'# raises "Unknown label type: continuous".',"REG = is_numeric_dtype(train[TARGET]) and train[TARGET].nunique() > 20",'print(f"train {train.shape} · test {test.shape} · predicting {TARGET!r} "'," f\"({'regression' if REG else 'classification'})\")"]),u=o(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Category (<= 20 distinct): one-hot.","# Free text: TF-IDF — on a text task the sentences ARE the signal, and dropping",'# them as "high-cardinality" leaves nothing to train on (that used to crash the','# whole notebook with "No objects to concatenate").',"# only columns present in BOTH files — a train-only column cannot be a feature","# at prediction time, and indexing test with it raises KeyError.","feat = [c for c in shared if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","# Everything else is vectorised as text. Requiring a long average length here","# used to throw away high-cardinality SHORT strings — ingredient names, single","# words, category codes — which on several tasks are the entire signal, leaving","# the notebook with zero features.","txt = [c for c in feat if c not in num and c not in cat]","for c in num:"," med = Xtr_raw[c].median()"," Xtr_raw[c] = Xtr_raw[c].fillna(med)"," Xte_raw[c] = Xte_raw[c].fillna(med)","blocks_tr, blocks_te = [], []","if num or cat:"," d_tr = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)"," d_te = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",' d_tr, d_te = d_tr.align(d_te, join="left", axis=1, fill_value=0)'," blocks_tr.append(d_tr.to_numpy(dtype=float))"," blocks_te.append(d_te.to_numpy(dtype=float))","for c in txt:"," # fillna BEFORE astype(str): a real NaN reaching the vectoriser raises",' # "np.nan is an invalid document", and astype alone does not catch it.',' tr_txt = Xtr_raw[c].fillna("").astype(str)',' te_txt = Xte_raw[c].fillna("").astype(str)'," # min_df=1: on a short-token column (one ingredient per row) min_df=2 can"," # filter the vocabulary down to nothing."," long_col = tr_txt.str.len().mean() >= 12"," # Try the good settings, then a permissive fallback, then give up on THIS"," # column only. A column whose vocabulary prunes to nothing used to abort the",' # whole run with "After pruning, no terms remain".',' for kw in ({"min_df": 2 if long_col else 1,',' "analyzer": "word" if long_col else "char_wb"},',' {"min_df": 1, "analyzer": "char_wb"}):'," try:"," vec = TfidfVectorizer(max_features=3000, ngram_range=(1, 2), **kw)"," b_tr = vec.fit_transform(tr_txt).toarray()"," blocks_tr.append(b_tr)"," blocks_te.append(vec.transform(te_txt).toarray())"," break"," except ValueError as e:"," last = e"," else:",' print(f" skipped text column {c!r}: {last}")',"if not blocks_tr:"," raise SystemExit(",' f"No usable feature columns. The shared columns are {feat} — none of them "',' f"is numeric, categorical or text.\\n"',' f"Two kinds of task land here, and both are real work rather than a bug:\\n"',' f" 1. audio/image — train.csv only lists sample ids and labels, and the "',' f"signal is in the media files shipped with the task. Load them "',' f"(librosa / PIL), turn each file into a feature row.\\n"',' f" 2. train.csv and test.csv describe different things (a retrieval or "',' f"matching task). Read both files, work out what links a test row to a "',' f"train row, and build that mapping yourself.\\n"',' f"Either way: replace this cell. train={list(train.columns)} "',' f"test={list(test.columns)}"'," )","X = np.hstack(blocks_tr)","X_test = np.hstack(blocks_te)","y = train[TARGET]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"{X.shape[1]} model-ready features "',' f"({len(num)} numeric, {len(cat)} one-hot, {len(txt)} TF-IDF text)")']),d=o(["# MODEL — a working baseline. Improve THIS cell to climb the board.","from sklearn.linear_model import LogisticRegression, Ridge","# REG was decided from the labels back in setup.","model = Ridge() if REG else LogisticRegression(max_iter=2000)"]),m=o(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)","p_val = model.predict(X_val)","if REG:",' print("val RMSE:", round(mean_squared_error(y_val, p_val) ** 0.5, 4))',"else:"," acc = accuracy_score(y_val, p_val)",' print("val accuracy:", round(acc, 4))'," if acc < 0.3:"," # A near-zero baseline is the expected result on several of these tasks,"," # not a broken notebook — say so, or the student reads it as a bug.",' print(" A score this low usually means the linear baseline cannot "',' "represent the pattern at all (combination rules, sequences, "',' "spelling). That IS the task: build features that expose it, "',' "or switch to a model that can. The chain itself works — "',' "submission.csv is written either way.")']),p=o(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',"# Copy the layout of sample_submission.csv and swap in the predictions, rather","# than rebuilding the file from column names. Some tasks want more than two","# columns (e.g. subtaskID,datapointID,answer) and a hand-built 2-column frame","# is rejected by the grader even when every prediction is right.","if len(sub_fmt) == len(pred):"," sub = sub_fmt.copy()"," sub[sub.columns[-1]] = pred","else:"," keys = {}"," if ID is not None and ID in test.columns:"," keys[SUB_ID] = test[ID]"," keys[SUB_TARGET] = pred"," sub = pd.DataFrame(keys)",' print(f"NOTE: sample_submission has {len(sub_fmt)} rows but test has "',' f"{len(pred)} — built the file from column names instead; "',' f"check it against the task page before submitting.")',"sub.to_csv(out, index=False)",'print("wrote", out, "·", list(sub.columns))',n?`print("score it: icoa kaggle submit ${t.comp_id}")`:'print("format check: icoa kaggle check")']),h=n?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${t.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:"nitro"===t.judge?["## Where this one gets scored","","This task comes from **judge.nitro-ai.org** and the answer key stays on","their server, so ICOA cannot score it for you. That does not make it a","practice stub — it is a real task, just judged elsewhere.","",`1. \`icoa kaggle check ${t.comp_id}\` — checks the FORMAT of`," `submission.csv` (headers, row count, ids). Format errors are the most"," common way a correct answer still scores zero.","2. Watch the **val score** printed above — that is your real feedback loop"," during the sprint, and it needs no account anywhere.","3. Want the official number? Register at judge.nitro-ai.org and submit"," there. Otherwise compare against the official solution, or ask"," `ai4ioai` to review your approach."]:t.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${t.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This dataset has no live Kaggle page linked yet._","The loop is identical: upload `submission.csv`, read the score, improve","the MODEL cell, repeat. Meanwhile the **val score** printed above is a","real signal you can work against with no account at all."];return[i(l),c,u,d,m,p,i(h.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},a=t.data??t,s=a&&"object"==typeof a?a:{};return"number"==typeof s.score&&"string"==typeof s.metric?{ok:!0,score:s.score,metric:s.metric,rank:"number"==typeof s.rank_at_time?s.rank_at_time:null,fieldSize:"number"==typeof s.field_size?s.field_size:null,deduped:!0===s.deduped,boardEvent:"string"==typeof s.board_event?s.board_event:null}:"string"==typeof s.reason&&""!==s.reason?{ok:!1,reason:s.reason,error:"string"==typeof s.error?s.error:void 0,problems:Array.isArray(s.problems)?s.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const a=[],s=e.trim().split(/\r?\n/),r=t.trim().split(/\r?\n/),n=s[0]??"",i=r[0]??"";n.trim()!==i.trim()&&a.push(`header mismatch: expected "${i}", got "${n}"`);const o=s.slice(1).filter(e=>""!==e.trim()),l=r.slice(1).filter(e=>""!==e.trim());o.length!==l.length&&a.push(`row count mismatch: expected ${l.length}, got ${o.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),u=c(o),d=c(l),m=[...d].filter(e=>!u.has(e)),p=[...u].filter(e=>!d.has(e));if(m.length>0||p.length>0){const e=[];m.length>0&&e.push(`${m.length} missing (e.g. ${m[0]})`),p.length>0&&e.push(`${p.length} unknown (e.g. ${p[0]})`),a.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<o.length;e++)if(o[e].split(",").some(e=>""===e.trim())){a.push(`empty cell in data row ${e+1}`);break}return{ok:0===a.length,problems:a}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "icoa-cli",
3
- "version": "2.19.431",
3
+ "version": "2.19.432",
4
4
  "description": "ICOA CLI — The world's first CLI-native cyber & AI security olympiad terminal: AI4CTF (Day 1), CTF4AI (Day 2), VLA4CTF (Pioneer Round — embodied AI)",
5
5
  "type": "module",
6
6
  "bin": {