icoa-cli 2.19.382 → 2.19.384

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{spawn as r}from"node:child_process";import{getMainRl as n}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as t,handleAi4ioaiMessage as l,startAi4ioaiChat as a}from"./ai4ioai.js";import{existsSync as s}from"node:fs";import{dirname as i,join as c}from"node:path";import{fileURLToPath as u}from"node:url";import{loadCurriculumById as d,validateEAToken as g,syncProgress as m,syncCardFeedback as y}from"../lib/learn-curricula.js";import{normalizeTokenBody as h}from"../lib/token-format.js";import{streamLearnTutor as f,submitPqs as p,viewPqsTop as w,viewHonors as b}from"../lib/learn-ai.js";import{getConfig as k,saveConfig as v}from"../lib/config.js";import{loadLearnState as A,saveLearnState as C,newLearnState as I,updateStreak as $,markCardComplete as E,recordMCQ as _,recordCheck as T,markPracticalComplete as M,addAchievement as P}from"../lib/learn-state.js";import{renderWelcome as x,renderKnowledgeCard as L,renderMCQCard as O,renderMCQFeedback as D,renderPracticalCard as S,renderPracticalSuccess as q,renderSimDemoCard as j,renderMilestone as N,renderArenaTaskCard as R,renderComingSoonCard as W,renderStatus as F,renderPhaseComplete as B,renderCurriculumComplete as z,setLearnAiEnabled as U,setLearnPqsViewCards as J,renderHonorWall as Q}from"../lib/learn-render.js";import{printError as V}from"../lib/ui.js";export function registerLearnCommand(H){H.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async H=>{H&&H.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 EA|EI|AC|CA|IO|IA + 8 chars")+chalk.gray(" — token from your country team leader.")),console.log(),H="LEARNDEMO01");let K=H.trim().toUpperCase(),X=null;const Z=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(K),G=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(K);let Y=!1;if(Z)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),X=await d(K,K);else if(G){console.log(),console.log(chalk.gray(" Validating token..."));let e=await g(K);if(!e.ok){const o=h(K);if(o!==K){const r=await g(o);r.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${K} → ${o}`)),e=r,K=o)}}if(!e.ok)return V(`Token validation failed: ${e.message}`),console.log(),"device_bound"===e.code?(console.log(chalk.gray(" This learn token is bound to the first computer it was used on,")),console.log(chalk.gray(" and this is a different computer.")),console.log(),console.log(chalk.gray(" If you changed computers or reinstalled, ask the coordinator who")),console.log(chalk.gray(" issued your token to move it to this device, then try again."))):(console.log(chalk.gray(" Possible causes:")),console.log(chalk.gray(" · Token expired or revoked")),console.log(chalk.gray(" · Network down (check connection)")),console.log(chalk.gray(" · Typo in token (check 0/O, 1/I/L, V/U)"))),void console.log();if(console.log(chalk.green(` ✓ Token valid · curriculum: ${e.curriculumId} · status: ${e.status}`)+(!0===e.aiEnabled?chalk.bold.magenta(" · ⭐ AI tutor"):"")),Y=!0===e.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),X=await d(e.curriculumId||"LEARNDEMO01",K),!X)return V(`Could not open a learn curriculum for token '${K}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${K}`)+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 ${K}`)+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(!X)return V(`Unknown learn token: ${K}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("LEARNDEMO01")+chalk.gray(" free 11-card demo (anyone can use)")),console.log(chalk.gray(" ")+chalk.bold.yellow("EA|EI|AC|CA|IO|IA")+chalk.gray(" + 8 chars full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Tracks: ")+chalk.cyan("EA")+chalk.gray("=ctf4eai · ")+chalk.cyan("AC")+chalk.gray("=ai4ctf · ")+chalk.cyan("CA")+chalk.gray("=ctf4ai · ")+chalk.cyan("IO")+chalk.gray("=ioai · ")+chalk.cyan("IA")+chalk.gray("=iaio")),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 ee=A(),oe=!1;try{ee&&ee.token===K?$(ee):(ee=I(K,X.id,X.totalCards),oe=!0),C(ee),x(X,ee,oe)}catch{return V("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 ${K}`)+chalk.gray(".")),void console.log()}const re=n(),ne=null!==re,te=ne?re.listeners("line").slice():[];ne&&re.removeAllListeners("line");const le=ne?re:o({input:process.stdin,output:process.stdout,terminal:!0}),ae=ne?le.prompt:null;ne&&(le.prompt=e.prototype.prompt);const se=()=>{ne&&ae&&(le.prompt=ae)},ie=()=>{le.setPrompt(he?chalk.bold.green(`icoa ${t()}> `):chalk.bold.cyan(me?"icoa learn ai> ":"icoa learn> ")),le.prompt()};let ce=null,ue=null,de=null,ge=null,me=!1,ye=!1,he=!1;const fe=new Map,pe=()=>{let e=fe.get(ee.currentCard);return e||(e=[],fe.set(ee.currentCard,e)),e};let we=!1;const be=new Set;let ke=!1,ve=0;const Ae=(k().language||"en").toLowerCase().startsWith("zh");U(Y),J(be);const Ce=[];let Ie=null;const $e=new Promise(e=>{Ie=e}),Ee=()=>{const e=Ie;Ie=null,e?.()},_e="1"===process.env.ICOA_LEARN_EMBEDDED,Te=e=>X.cards.find(o=>o.number===e),Me=e=>{const o=X.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const r=X.modules.find(e=>e.number===o.number+1);return B(X,ee,o,r),!0},Pe=()=>{ke=!0,console.log(chalk.gray(Ae?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},xe=()=>{const e=Te(ee.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":L(e,X),e.check?(de=e.number,ve=Date.now()):(E(ee,e.number),C(ee));break;case"mcq":O(e,X),ce=e.number;break;case"practical":S(e,X),ue=e.number;break;case"sim_demo":j(e,X),E(ee,e.number),C(ee);break;case"milestone":N(e,X),P(ee,e.badge),E(ee,e.number),C(ee);break;case"arena_task":R(e,X),E(ee,e.number),C(ee);break;case"coming_soon":W(e,X),E(ee,e.number),C(ee)}},Le=()=>{K.endsWith("DEMO01")?console.log(chalk.yellow(Ae?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Ae?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Ae?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Oe=async(e,o)=>{if(Y){ye=!0;try{console.log(),console.log(chalk.gray("deep"===o?Ae?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Ae?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let r=!1,n=!1;const t=await f({token:K,cardNumber:ee.currentCard,question:e,mode:o,history:pe().slice(-8)},e=>{"reasoning"===e.kind?(r||(process.stdout.write(" "),r=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(r?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(r||n)&&console.log(),t.ok?t.offtopic?(console.log(),console.log(chalk.yellow(Ae?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(pe().push({role:"user",content:e},{role:"assistant",content:t.answer}),null!=t.spent&&null!=t.cap&&t.spent/t.cap>.8&&console.log(chalk.gray(` (${Ae?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(Ae?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==de&&console.log(chalk.gray(Ae?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{ye=!1}}else Le()},De=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Se=async e=>{const o=e.trim().toLowerCase();if(!ye){if(null!==ge){const o=e.trim(),r=ge;if(ge=null,""===o)console.log(chalk.gray(Ae?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=ve>0?Date.now()-ve:void 0;Ce.push(y(K,{curriculum_id:X.id,card_number:r,feedback_text:o,time_on_card_ms:e}).catch(()=>{})),console.log(chalk.green(Ae?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void ie()}if(we){we=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{ye=!0;try{console.log(),console.log(chalk.gray(Ae?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await p({token:K,cardNumber:ee.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Ae?"评审暂不可用。":"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(Ae?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(Ae?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Ae?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Ae?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Ae?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(Ae?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,r=Ae?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(r):chalk.white(r))+(o?chalk.bold.magenta(Ae?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Ae?` 第 ${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 De(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(Ae?" 改进提问: ":" 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(` (${Ae?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?be.add(ee.currentCard):be.delete(ee.currentCard);const o=await b({token:K,curriculumId:X.id,cardNumber:ee.currentCard});o.ok&&o.totals&&o.chapters&&(Q({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log())}finally{ye=!1}})():(console.log(chalk.gray(Ae?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==de&&(console.log(chalk.gray(Ae?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ie()}if(ke)return ke=!1,xe(),void ie();if(o){if(he)return"exit"===await l(e.trim())&&(he=!1),void ie();if(me){if(["q","quit","exit","back","b","menu"].includes(o))return me=!1,console.log(chalk.gray(Ae?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ie();const r=e.trim().startsWith("!"),n=r?e.trim().slice(1).trim():e.trim();return n&&await Oe(n,r?"fast":"deep"),void ie()}if("ai4ioai"===o||"/ai4ioai"===o)return await a()&&(he=!0),void ie();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!Y)return Le(),void ie();const r=o.startsWith("/ai!"),n=e.trim().slice(r?4:3).trim();if(!n){me=!0;const e=Te(ee.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Ae?"AI 导师":"AI tutor")+(o?chalk.gray(Ae?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ae?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void ie()}return await Oe(n,r?"fast":"deep"),void ie()}if("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research ")){if(!Y)return Le(),void ie();const e=Te(ee.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Ae?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Ae?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ae?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Ae?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Ae?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Ae?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Ae?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),we=!0,void ie()}if("/view"===o)return Y?(await(async()=>{ye=!0;try{console.log();const e=await w({token:K,cardNumber:ee.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(Ae?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&be.delete(ee.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&be.add(ee.currentCard),console.log(chalk.bold.white(Ae?` 🏆 本卡 Top-3 提问 — 第 ${ee.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${ee.currentCard} · ${e.entrants??0} entrant(s)`));for(const o of e.top3??[]){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── Rank ${o.rank}`)+(o.me?chalk.bold.magenta(" (me)"):"")+chalk.white(` · ${o.score}`)+` ${e}`),o.questions.forEach((e,o)=>{const r=De(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(r[0]??""));for(const e of r.slice(1))console.log(chalk.white(" "+e))}),0===o.questions.length&&console.log(chalk.gray(Ae?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{ye=!1}})(),void ie()):(Le(),void ie());if("/honors"===o||"honors"===o)return Z?(console.log(),console.log(chalk.gray(Ae?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void ie()):(await(async()=>{ye=!0;try{console.log();const e=await b({token:K,curriculumId:X.id,cardNumber:ee.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Ae?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Ae?` 🏆 本卡实时 Top-3 — 第 ${ee.currentCard} 张`:` 🏆 Live top-3 — card ${ee.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.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(" (me)"):""))}else console.log(chalk.gray(Ae?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),Q({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log()}finally{ye=!1}})(),void ie());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return F(X,ee),void ie();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(k().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ie();const r=X.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),t="en"===n||"zh"===n&&r,l=t?n:"en";return v({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),de=null,ce=null,ue=null,ge=null,ke=!1,we=!1,xe(),void ie()}if("sim"===o){const e=Te(ee.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=i(u(import.meta.url)),o=[c(e,"..","..","panda","mujoco-launcher.py"),c(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(s(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const n={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${n})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,n,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void ie()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ie())}if("bookmark"===o){const e=ee.currentCard;return ee.bookmarks.includes(e)||ee.bookmarks.push(e),C(ee),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ie()}if("e"===o)return ge=ee.currentCard,console.log(chalk.gray(Ae?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ie();if("back"===o||"b"===o)return ee.currentCard>1&&(ee.currentCard-=1),ce=null,ue=null,de=null,C(ee),xe(),void ie();if(o.startsWith("card ")){const e=o.slice(5).trim(),r=parseInt(e,10);return!Number.isInteger(r)||r<1||r>X.totalCards?(console.log(chalk.yellow(` Card number must be 1..${X.totalCards}. Try: `)+chalk.bold.green("card 1")),void ie()):(ee.currentCard=r,ce=null,ue=null,de=null,C(ee),xe(),void ie())}if(null!==de&&["y","yes","n","no"].includes(o)){const e=Te(de);if(e&&"knowledge"===e.type&&e.check){const r=o.startsWith("y")?"y":"n",n=r===e.check.answer,t=Date.now()-ve;E(ee,e.number),T(ee,e.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),C(ee);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,r,n,!1),Ce.push(m(K,{card_number:e.number,event_type:"check_answered",check_answer:r,check_correct:n,time_on_card_ms:t}).catch(()=>{})),de=null,e.solution&&e.solution.length>0)return void ie();if(ee.currentCard<X.totalCards){const e=ee.currentCard;ee.currentCard+=1,C(ee),Me(e)?Pe():xe(),ie()}else z(X,ee),ie();return}}if(null!==ce&&["a","b","c","d"].includes(o)){const e=Te(ce);if(e&&"mcq"===e.type){const r=o.toUpperCase(),n=r===e.answer;return _(ee,e.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),E(ee,e.number),C(ee),D(e,r,n,ee),Ce.push(m(K,{card_number:e.number,event_type:"mcq_answered",mcq_answer:r,mcq_correct:n}).catch(()=>{})),ce=null,void(n?ee.currentCard<X.totalCards?(ee.currentCard+=1,C(ee),xe()):(z(X,ee),ie()):ie())}}if(null!==ue){if("done"===o){const e=Te(ue);if(e&&"practical"===e.type)return M(ee,e.number),E(ee,e.number),C(ee),q(e),ue=null,void ie()}if("skip"===o)return E(ee,ue),C(ee),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),ue=null,void ie()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ie();if(null!==ue)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ie();if(null!==de)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ie();const e=ee.currentCard;return ee.currentCard+=1,C(ee),ee.currentCard>X.totalCards?z(X,ee):Me(e)?Pe():xe(),void ie()}if(null!==de)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ie();if(null!==ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ie();if(null!==ue)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ie();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")),ie()}else if(Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ee.streakDays} day(s)`)),console.log(),ne){le.removeAllListeners("line"),se();for(const e of te)le.on("line",e);le.prompt(),Ee()}else le.removeAllListeners("line"),le.close();else if(Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,3e3))]),le.removeAllListeners("line"),se(),ne||!_e){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ne?le:void 0),Ee()}else le.close()}else ie()}};le.on("line",e=>{Se(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.")),ie()})}),ne||le.on("close",async()=>{Ce.length>0&&await Promise.race([Promise.allSettled(Ce),new Promise(e=>setTimeout(e,5e3))]),_e?Ee():process.exit(0)});try{xe(),ie()}catch{if(V("Could not render this card — the curriculum may be malformed."),ne){le.removeAllListeners("line"),se();for(const e of te)le.on("line",e);le.prompt()}else le.close();Ee()}await $e}),H.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 r=0,n=0,t=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await d(e),a=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;t+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),r++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${r} cached`)+chalk.gray(` · ${n} failed · total ${(t/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
1
+ import chalk from"chalk";import{Interface as o,createInterface as e}from"node:readline";import{execSync as r,spawn as n}from"node:child_process";import{getMainRl as t}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as l,handleAi4ioaiMessage as a,startAi4ioaiChat as s}from"./ai4ioai.js";import{existsSync as i}from"node:fs";import{dirname as c,join as u}from"node:path";import{fileURLToPath as d}from"node:url";import{loadCurriculumById as g,validateEAToken as m,syncProgress as y,syncCardFeedback as h}from"../lib/learn-curricula.js";import{normalizeTokenBody as f}from"../lib/token-format.js";import{streamLearnTutor as p,submitPqs as w,viewPqsTop as b,viewHonors as k}from"../lib/learn-ai.js";import{getConfig as v,saveConfig as A}from"../lib/config.js";import{loadLearnState as C,saveLearnState as I,newLearnState as $,updateStreak as E,markCardComplete as T,recordMCQ as _,recordCheck as x,markPracticalComplete as M,addAchievement as P}from"../lib/learn-state.js";import{renderWelcome as O,renderKnowledgeCard as L,renderMCQCard as D,renderMCQFeedback as S,renderPracticalCard as q,renderPracticalSuccess as j,renderSimDemoCard as N,renderMilestone as R,renderArenaTaskCard as W,renderComingSoonCard as F,renderStatus as B,renderPhaseComplete as z,renderCurriculumComplete as U,setLearnAiEnabled as J,setLearnPqsViewCards as Q,renderHonorWall as V}from"../lib/learn-render.js";import{printError as Y}from"../lib/ui.js";export function registerLearnCommand(H){H.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async H=>{H&&H.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 EA|EI|AC|CA|IO|IA + 8 chars")+chalk.gray(" — token from your country team leader.")),console.log(),H="LEARNDEMO01");let K=H.trim().toUpperCase(),X=null;const Z=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(K),G=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(K);let oo=!1;if(Z)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),X=await g(K,K);else if(G){console.log(),console.log(chalk.gray(" Validating token..."));let o=await m(K);if(!o.ok){const e=f(K);if(e!==K){const r=await m(e);r.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${K} → ${e}`)),o=r,K=e)}}if(!o.ok)return Y(`Token validation failed: ${o.message}`),console.log(),"device_bound"===o.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: ${o.curriculumId} · status: ${o.status}`)+(!0===o.aiEnabled?chalk.bold.magenta(" · ⭐ AI tutor"):"")),oo=!0===o.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),X=await g(o.curriculumId||"LEARNDEMO01",K),!X)return Y(`Could not open a learn curriculum for token '${K}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${K}`)+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 ${K}`)+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(!X)return Y(`Unknown learn token: ${K}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("LEARNDEMO01")+chalk.gray(" free 11-card demo (anyone can use)")),console.log(chalk.gray(" ")+chalk.bold.yellow("EA|EI|AC|CA|IO|IA")+chalk.gray(" + 8 chars full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Tracks: ")+chalk.cyan("EA")+chalk.gray("=ctf4eai · ")+chalk.cyan("AC")+chalk.gray("=ai4ctf · ")+chalk.cyan("CA")+chalk.gray("=ctf4ai · ")+chalk.cyan("IO")+chalk.gray("=ioai · ")+chalk.cyan("IA")+chalk.gray("=iaio")),console.log(),console.log(chalk.gray(" To get a full curriculum, email ")),console.log(chalk.gray(" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" or ask your country's team leader.")),void console.log();let eo=C(),ro=!1;try{eo&&eo.token===K?E(eo):(eo=$(K,X.id,X.totalCards),ro=!0),I(eo),O(X,eo,ro)}catch{return Y("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 ${K}`)+chalk.gray(".")),void console.log()}const no=t(),to=null!==no,lo=to?no.listeners("line").slice():[];to&&no.removeAllListeners("line");const ao=to?no:e({input:process.stdin,output:process.stdout,terminal:!0}),so=to?ao.prompt:null;to&&(ao.prompt=o.prototype.prompt);const io=()=>{to&&so&&(ao.prompt=so)},co=()=>{ao.setPrompt(po?chalk.bold.green(`icoa ${l()}> `):chalk.bold.cyan(ho?"icoa learn ai> ":"icoa learn> ")),ao.prompt()};let uo=null,go=null,mo=null,yo=null,ho=!1,fo=!1,po=!1;const wo=new Map,bo=()=>{let o=wo.get(eo.currentCard);return o||(o=[],wo.set(eo.currentCard,o)),o};let ko=!1;const vo=new Set;let Ao=!1,Co=0;const Io=(v().language||"en").toLowerCase().startsWith("zh");J(oo),Q(vo);const $o=[];let Eo=null;const To=new Promise(o=>{Eo=o}),_o=()=>{const o=Eo;Eo=null,o?.()},xo="1"===process.env.ICOA_LEARN_EMBEDDED,Mo=o=>X.cards.find(e=>e.number===o),Po=o=>{const e=X.modules.find(e=>e.cardRange[1]===o);if(!e)return!1;const r=X.modules.find(o=>o.number===e.number+1);return z(X,eo,e,r),!0},Oo=()=>{Ao=!0,console.log(chalk.gray(Io?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Lo=()=>{const o=Mo(eo.currentCard);if(!o)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(o.type){case"knowledge":L(o,X),o.check?(mo=o.number,Co=Date.now()):(T(eo,o.number),I(eo));break;case"mcq":D(o,X),uo=o.number;break;case"practical":q(o,X),go=o.number;break;case"sim_demo":N(o,X),T(eo,o.number),I(eo);break;case"milestone":R(o,X),P(eo,o.badge),T(eo,o.number),I(eo);break;case"arena_task":W(o,X),T(eo,o.number),I(eo);break;case"coming_soon":F(o,X),T(eo,o.number),I(eo)}},Do=()=>{K.endsWith("DEMO01")?console.log(chalk.yellow(Io?" AI 导师需要开通 AI 的正式课程 token(demo 是共享的,没有 AI 额度)。":" The AI tutor needs an AI-enabled curriculum token — demos are shared and carry no AI budget.")):(console.log(chalk.yellow(Io?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Io?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},So=async(o,e)=>{if(oo){fo=!0;try{console.log(),console.log(chalk.gray("deep"===e?Io?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Io?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let r=!1,n=!1;const t=await p({token:K,cardNumber:eo.currentCard,question:o,mode:e,history:bo().slice(-8)},o=>{"reasoning"===o.kind?(r||(process.stdout.write(" "),r=!0),process.stdout.write(chalk.dim(o.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(r?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(o.text.replace(/\n/g,"\n "))))});(r||n)&&console.log(),t.ok?t.offtopic?(console.log(),console.log(chalk.yellow(Io?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(bo().push({role:"user",content:o},{role:"assistant",content:t.answer}),null!=t.spent&&null!=t.cap&&t.spent/t.cap>.8&&console.log(chalk.gray(` (${Io?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(Io?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==mo&&console.log(chalk.gray(Io?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{fo=!1}}else Do()},qo=o=>o.match(/.{1,64}(\s|$)/g)?.map(o=>o.trim())??[o],jo=async o=>{const e=o.trim().toLowerCase();if(!fo){if(null!==yo){const e=o.trim(),r=yo;if(yo=null,""===e)console.log(chalk.gray(Io?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const o=Co>0?Date.now()-Co:void 0;await h(K,{curriculum_id:X.id,card_number:r,feedback_text:e,time_on_card_ms:o})?console.log(chalk.green(Io?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Io?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void co()}if(ko){ko=!1;const e=o.trim().toLowerCase();return"y"===e||"yes"===e?await(async()=>{fo=!0;try{console.log(),console.log(chalk.gray(Io?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const o=await w({token:K,cardNumber:eo.currentCard});if(console.log(),!o.ok)return console.log(chalk.yellow(` ${o.message||(Io?"评审暂不可用。":"Review unavailable.")}`)),void console.log();(o=>{const e="green"===o.tier?chalk.bold.green:"blue"===o.tier?chalk.bold.cyan:"yellow"===o.tier?chalk.bold.yellow:chalk.bold.red;if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.white(Io?" 提问评分 ":" Prompt score ")+e(`${o.score??0} / 100`)+chalk.gray(" "+(o=>{switch(o){case"green":return"🟢 "+(Io?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Io?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Io?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Io?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(o.tier))),o.manipulation&&console.log(chalk.red(Io?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=o.rank&&null!=o.entrants){const e=!0===o.inTop3,r=Io?` 本卡排名 #${o.rank} / ${o.entrants}`:` Rank on this card: #${o.rank} of ${o.entrants}`;console.log((e?chalk.bold.green(r):chalk.white(r))+(e?chalk.bold.magenta(Io?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Io?` 第 ${o.submissionIndex??"?"} / 2 次提交 · 剩余 ${o.submissionsLeft??0} 次(可先追加 /ai 对话再交)`:` Attempt ${o.submissionIndex??"?"} of 2 · ${o.submissionsLeft??0} left (extend the /ai conversation before your next one)`)),o.feedback){console.log();for(const e of qo(o.feedback))console.log(chalk.white(" "+e))}o.improve&&(console.log(),console.log(chalk.cyan(Io?" 改进提问: ":" Ask better: ")+chalk.gray(o.improve))),console.log(chalk.gray(" ─────────────────────────────────────────")),null!=o.spent&&null!=o.cap&&o.spent/o.cap>.8&&console.log(chalk.gray(` (${Io?"AI 额度":"AI budget"}: ${Math.round(o.spent/1e3)}k / ${Math.round(o.cap/1e3)}k tokens)`)),console.log()})(o),!0===o.inTop3?vo.add(eo.currentCard):vo.delete(eo.currentCard);const e=await k({token:K,curriculumId:X.id,cardNumber:eo.currentCard});e.ok&&e.totals&&e.chapters&&(V({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log())}finally{fo=!1}})():(console.log(chalk.gray(Io?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==mo&&(console.log(chalk.gray(Io?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void co()}if(Ao)return Ao=!1,Lo(),void co();if(e){if(po)return"exit"===await a(o.trim())&&(po=!1),void co();if(ho){if(["q","quit","exit","back","b","menu"].includes(e))return ho=!1,console.log(chalk.gray(Io?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void co();const r=o.trim().startsWith("!"),n=r?o.trim().slice(1).trim():o.trim();return n&&await So(n,r?"fast":"deep"),void co()}if("tmux"===e||e.startsWith("tmux ")){try{r("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(Io?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void co()}return await new Promise(e=>{const r=process.stdin,t=!!r.isTTY&&!!r.isRaw;if(ao.pause(),r.isTTY&&"function"==typeof r.setRawMode)try{r.setRawMode(!1)}catch{}const l=n(o.trim(),{shell:!0,stdio:"inherit"}),a=()=>{if(r.isTTY&&"function"==typeof r.setRawMode&&t)try{r.setRawMode(!0)}catch{}ao.resume(),e()};l.on("close",a),l.on("error",a)}),console.log(),void co()}if("ai4ioai"===e||"/ai4ioai"===e)return await s()&&(po=!0),void co();if("/ai"===e||"/ai!"===e||e.startsWith("/ai ")||e.startsWith("/ai! ")){if(!oo)return Do(),void co();const r=e.startsWith("/ai!"),n=o.trim().slice(r?4:3).trim();if(!n){ho=!0;const o=Mo(eo.currentCard),e=o?o.title??o.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Io?"AI 导师":"AI tutor")+(e?chalk.gray(Io?` — 主题「${e}」`:` — topic “${e}”`):"")),console.log(chalk.gray(Io?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void co()}return await So(n,r?"fast":"deep"),void co()}if("/submit"===e||e.startsWith("/submit ")||"/research"===e||e.startsWith("/research ")){if(!oo)return Do(),void co();const o=Mo(eo.currentCard),e=o?o.title??o.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Io?"Panda 提问评审":"Panda's prompt review")+(e?chalk.gray(Io?` — 主题「${e}」`:` — topic “${e}”`):"")),console.log(chalk.gray(Io?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Io?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Io?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Io?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Io?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),ko=!0,void co()}if("/view"===e)return oo?(await(async()=>{fo=!0;try{console.log();const o=await b({token:K,cardNumber:eo.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Io?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&vo.delete(eo.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&vo.add(eo.currentCard),console.log(chalk.bold.white(Io?` 🏆 本卡 Top-3 提问 — 第 ${eo.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${eo.currentCard} · ${o.entrants??0} entrant(s)`));for(const e of o.top3??[]){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── Rank ${e.rank}`)+(e.me?chalk.bold.magenta(" (me)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((o,e)=>{const r=qo(o);console.log(chalk.gray(` Q${e+1} `)+chalk.white(r[0]??""));for(const o of r.slice(1))console.log(chalk.white(" "+o))}),0===e.questions.length&&console.log(chalk.gray(Io?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{fo=!1}})(),void co()):(Do(),void co());if("/honors"===e||"honors"===e)return Z?(console.log(),console.log(chalk.gray(Io?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void co()):(await(async()=>{fo=!0;try{console.log();const o=await k({token:K,curriculumId:X.id,cardNumber:eo.currentCard});if(!o.ok||!o.totals||!o.chapters)return console.log(chalk.yellow(` ${o.message||(Io?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Io?` 🏆 本卡实时 Top-3 — 第 ${eo.currentCard} 张`:` 🏆 Live top-3 — card ${eo.currentCard}`)),o.board&&0!==o.board.length)for(const e of o.board){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(chalk.white(` ${e.icon} `)+chalk.bold.cyan(`#${e.rank}`)+chalk.white(` · ${e.score} `)+o+(e.me?chalk.bold.magenta(" (me)"):""))}else console.log(chalk.gray(Io?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),V({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()}finally{fo=!1}})(),void co());if("menu"!==e&&"menu confirm"!==e)if("quit"!==e&&"exit"!==e&&"q"!==e){if("status"===e)return B(X,eo),void co();if("lang"===e||e.startsWith("lang ")){const o=e.slice(4).trim();if(!o)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(v().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void co();const r=X.cards.some(o=>null!=o._zh),n=o.toLowerCase().startsWith("zh")?"zh":o.toLowerCase(),t="en"===n||"zh"===n&&r,l=t?n:"en";return A({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${o} 本课暂无翻译,已用英文 / not available — using English`)),mo=null,uo=null,go=null,yo=null,Ao=!1,ko=!1,Lo(),void co()}if("sim"===e){const o=Mo(eo.currentCard);return o&&"sim_demo"===o.type?(function(o){const e=function(){const o=c(d(import.meta.url)),e=[u(o,"..","..","panda","mujoco-launcher.py"),u(o,"..","..","..","panda","mujoco-launcher.py")];for(const o of e)if(i(o))return o;return null}();if(!e)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 r={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[o]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${r})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),n("python3",[e,r,"--seconds","5"],{stdio:"inherit"}).on("exit",o=>{0!==o?console.log(chalk.yellow(` MuJoCo exited with code ${o} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(o.simAction),void co()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void co())}if("bookmark"===e){const o=eo.currentCard;return eo.bookmarks.includes(o)||eo.bookmarks.push(o),I(eo),console.log(chalk.gray(` ✓ Card ${o} bookmarked.`)),void co()}if("e"===e)return yo=eo.currentCard,console.log(chalk.gray(Io?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void co();if("back"===e||"b"===e)return eo.currentCard>1&&(eo.currentCard-=1),uo=null,go=null,mo=null,I(eo),Lo(),void co();if(e.startsWith("card ")){const o=e.slice(5).trim(),r=parseInt(o,10);return!Number.isInteger(r)||r<1||r>X.totalCards?(console.log(chalk.yellow(` Card number must be 1..${X.totalCards}. Try: `)+chalk.bold.green("card 1")),void co()):(eo.currentCard=r,uo=null,go=null,mo=null,I(eo),Lo(),void co())}if(null!==mo&&["y","yes","n","no"].includes(e)){const o=Mo(mo);if(o&&"knowledge"===o.type&&o.check){const r=e.startsWith("y")?"y":"n",n=r===o.check.answer,t=Date.now()-Co;T(eo,o.number),x(eo,o.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),I(eo);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(o,r,n,!1),$o.push(y(K,{card_number:o.number,event_type:"check_answered",check_answer:r,check_correct:n,time_on_card_ms:t}).catch(()=>{})),mo=null,o.solution&&o.solution.length>0)return void co();if(eo.currentCard<X.totalCards){const o=eo.currentCard;eo.currentCard+=1,I(eo),Po(o)?Oo():Lo(),co()}else U(X,eo),co();return}}if(null!==uo&&["a","b","c","d"].includes(e)){const o=Mo(uo);if(o&&"mcq"===o.type){const r=e.toUpperCase(),n=r===o.answer;return _(eo,o.number,{answer:r,correct:n,submittedAt:(new Date).toISOString()}),T(eo,o.number),I(eo),S(o,r,n,eo),$o.push(y(K,{card_number:o.number,event_type:"mcq_answered",mcq_answer:r,mcq_correct:n}).catch(()=>{})),uo=null,void(n?eo.currentCard<X.totalCards?(eo.currentCard+=1,I(eo),Lo()):(U(X,eo),co()):co())}}if(null!==go){if("done"===e){const o=Mo(go);if(o&&"practical"===o.type)return M(eo,o.number),T(eo,o.number),I(eo),j(o),go=null,void co()}if("skip"===e)return T(eo,go),I(eo),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),go=null,void co()}if("ok"===e||"next"===e||"continue"===e||"n"===e){if(null!==uo)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void co();if(null!==go)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void co();if(null!==mo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void co();const o=eo.currentCard;return eo.currentCard+=1,I(eo),eo.currentCard>X.totalCards?U(X,eo):Po(o)?Oo():Lo(),void co()}if(null!==mo)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void co();if(null!==uo)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void co();if(null!==go)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void co();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")),co()}else if($o.length>0&&await Promise.race([Promise.allSettled($o),new Promise(o=>setTimeout(o,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${eo.streakDays} day(s)`)),console.log(),to){ao.removeAllListeners("line"),io();for(const o of lo)ao.on("line",o);ao.prompt(),_o()}else ao.removeAllListeners("line"),ao.close();else if($o.length>0&&await Promise.race([Promise.allSettled($o),new Promise(o=>setTimeout(o,3e3))]),ao.removeAllListeners("line"),io(),to||!xo){const{returnToMainMenu:o}=await import("../lib/menu-nav.js");o(to?ao:void 0),_o()}else ao.close()}else co()}};ao.on("line",o=>{jo(o).catch(o=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),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.")),co()})}),to||ao.on("close",async()=>{$o.length>0&&await Promise.race([Promise.allSettled($o),new Promise(o=>setTimeout(o,5e3))]),xo?_o():process.exit(0)});try{Lo(),co()}catch{if(Y("Could not render this card — the curriculum may be malformed."),to){ao.removeAllListeners("line"),io();for(const o of lo)ao.on("line",o);ao.prompt()}else ao.close();_o()}await To}),H.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async o=>{const e=o?[o.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 r=0,n=0,t=0;for(const o of e){process.stdout.write(` ${o.padEnd(22)} `);const e=Date.now(),l=await g(o),a=Date.now()-e;if(l){const o=l.cards,e=Array.isArray(o)?o.length:0,n=JSON.stringify(l).length;t+=n,console.log(chalk.green("✓ ")+chalk.gray(`${e.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),r++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${r} cached`)+chalk.gray(` · ${n} failed · total ${(t/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
@@ -1 +1 @@
1
- import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb","kaggle"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
1
+ import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb","kaggle","tmux"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
@@ -1 +1 @@
1
- export function parseKaggleTaskList(e){const t=e??{},r=(t.data??t).tasks;if(!Array.isArray(r))return[];const o=[];for(const e of r){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&o.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",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})}return o}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const r=t.replace(/\/$/,"");return{train:`${r}/train.csv`,test:`${r}/test.csv`,sample_submission:`${r}/sample_submission.csv`}}export function buildStarterCells(e,t){const r=t.id_col??"id",o=t.target_col??"target",i=(s=t.metric,/rmse|mse|mae|error/i.test(s));var s;const a="icoa-holdout"===t.judge,n=e=>({kind:"markdown",source:e,result:null}),l=e=>({kind:"code",source:e.join("\n"),result:null}),c=[`# ${t.title}`,"",`Kaggle-style practice — metric: **${t.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${o}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...a?["and re-run — `icoa kaggle submit` scores it and ranks you on the board."]:["and re-run — your score is whatever Kaggle says it is."],...t.licence?["",`**Data licence:** ${t.licence}`]:[],...t.attribution?[`**Attribution:** ${t.attribution}`]:[]].join("\n"),d=l(["# setup — load the data (leave as is)","import os","import pandas as pd","from sklearn.model_selection import train_test_split",i?"from sklearn.metrics import mean_squared_error":"from sklearn.metrics import accuracy_score","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${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")',`features = [c for c in train.columns if c not in ("${r}", "${o}")]`,`X, y = train[features], train["${o}"]`,"X_test = test[features]","X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.2, random_state=0)",'print(f"train {train.shape} · test {test.shape} · {len(features)} features")']),u=l(i?["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import Ridge","model = Ridge()"]:["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import LogisticRegression","model = LogisticRegression(max_iter=2000)"]),m=l(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)",i?'print("val RMSE:", round(mean_squared_error(y_val, model.predict(X_val)) ** 0.5, 4))':'print("val accuracy:", round(accuracy_score(y_val, model.predict(X_val)), 4))']),p=l(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',`pd.DataFrame({"${r}": test["${r}"], "${o}": pred}).to_csv(out, index=False)`,'print("wrote", out)',a?`print("score it: icoa kaggle submit ${t.comp_id}")`:'print("format check: icoa kaggle check")']),g=a?["## Submit to ICOA (scored on the server)","",`1. In the ICOA CLI run \`icoa kaggle submit ${t.comp_id}\``,"2. The server scores `submission.csv` against the secret test labels"," and your rank lands on the live board (`icoa board`).","3. Improve the MODEL cell, re-run, submit again — best score counts."]:t.kaggle_url?["## Submit on Kaggle (manual, your own account)","",`1. Open ${t.kaggle_url}`,"2. **Submit Predictions** → upload `submission.csv`","3. Read your leaderboard score, come back, improve the MODEL cell, repeat."]:["## Submit on Kaggle (manual, your own account)","","_This is a placeholder practice dataset — it has no live Kaggle page yet._","When the real competition dataset lands, this cell will link straight to","its Kaggle submission page. The loop is identical: upload `submission.csv`,","read the score, improve the MODEL cell, repeat."];return[n(c),d,u,m,p,n(g.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},r=t.data??t,o=r&&"object"==typeof r?r:{};return"number"==typeof o.score&&"string"==typeof o.metric?{ok:!0,score:o.score,metric:o.metric,rank:"number"==typeof o.rank_at_time?o.rank_at_time:null,fieldSize:"number"==typeof o.field_size?o.field_size:null,deduped:!0===o.deduped,boardEvent:"string"==typeof o.board_event?o.board_event:null}:"string"==typeof o.reason&&""!==o.reason?{ok:!1,reason:o.reason,error:"string"==typeof o.error?o.error:void 0,problems:Array.isArray(o.problems)?o.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const r=[],o=e.trim().split(/\r?\n/),i=t.trim().split(/\r?\n/),s=o[0]??"",a=i[0]??"";s.trim()!==a.trim()&&r.push(`header mismatch: expected "${a}", got "${s}"`);const n=o.slice(1).filter(e=>""!==e.trim()),l=i.slice(1).filter(e=>""!==e.trim());n.length!==l.length&&r.push(`row count mismatch: expected ${l.length}, got ${n.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),d=c(n),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]})`),r.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<n.length;e++)if(n[e].split(",").some(e=>""===e.trim())){r.push(`empty cell in data row ${e+1}`);break}return{ok:0===r.length,problems:r}}
1
+ export function parseKaggleTaskList(e){const t=e??{},r=(t.data??t).tasks;if(!Array.isArray(r))return[];const i=[];for(const e of r){if(!e||"object"!=typeof e)continue;const t=e;"string"==typeof t.comp_id&&""!==t.comp_id&&i.push({comp_id:t.comp_id,title:"string"==typeof t.title?t.title:t.comp_id,metric:"string"==typeof t.metric?t.metric:"accuracy",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})}return i}export function dataFileUrls(e){const t=e.data_base;if("string"!=typeof t||""===t)return null;const r=t.replace(/\/$/,"");return{train:`${r}/train.csv`,test:`${r}/test.csv`,sample_submission:`${r}/sample_submission.csv`}}export function buildStarterCells(e,t){const r=t.id_col??"id",i=t.target_col??"target",a=(o=t.metric,/rmse|mse|mae|error/i.test(o));var o;const s="icoa-holdout"===t.judge,n=e=>({kind:"markdown",source:e,result:null}),l=e=>({kind:"code",source:e.join("\n"),result:null}),c=[`# ${t.title}`,"",`Kaggle-style practice — metric: **${t.metric}**.`,"","- `train.csv` — labelled training data",`- \`test.csv\` — rows to predict (no \`${i}\` column)`,"- `sample_submission.csv` — the exact format Kaggle expects","","Run all cells top to bottom: a baseline model trains on your CPU and","`submission.csv` appears next to the data. Then improve the model cell",...s?["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."],...t.licence?["",`**Data licence:** ${t.licence}`]:[],...t.attribution?[`**Attribution:** ${t.attribution}`]:[]].join("\n"),m=l(["# setup — load the data (leave as is)","import os","import pandas as pd","from pandas.api.types import is_numeric_dtype","from sklearn.model_selection import train_test_split",a?"from sklearn.metrics import mean_squared_error":"from sklearn.metrics import accuracy_score","","# same code everywhere: in a GPU session these env vars point at the","# box's own dataset copy + workspace — locally they are unset.",`DIR = os.environ.get("ICOA_KAGGLE_DATA") or r"${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")',`ID, TARGET = "${r}", "${i}"`,'print(f"train {train.shape} · test {test.shape}")']),d=l(["# FEATURES — turn raw columns into numbers a model can use (improve THIS cell).","# Numbers: fill gaps with the median. Text/category: one-hot the low-cardinality","# ones (<= 20 distinct); drop high-cardinality text like names/IDs (rarely helps","# a baseline). Train and test end up aligned to the exact same columns.","feat = [c for c in train.columns if c not in (ID, TARGET)]","Xtr_raw, Xte_raw = train[feat].copy(), test[feat].copy()","num = [c for c in feat if is_numeric_dtype(Xtr_raw[c])]","cat = [c for c in feat if c not in num and Xtr_raw[c].nunique() <= 20]","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)","X = pd.get_dummies(Xtr_raw[num + cat], columns=cat, dummy_na=True)","X_test = pd.get_dummies(Xte_raw[num + cat], columns=cat, dummy_na=True)",'X, X_test = X.align(X_test, join="left", axis=1, fill_value=0)',"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"(dropped {len(feat) - len(num) - len(cat)} high-cardinality/text cols)")']),u=l(a?["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import Ridge","model = Ridge()"]:["# MODEL — a working baseline. Improve THIS cell to climb the Kaggle board.","from sklearn.linear_model import LogisticRegression","model = LogisticRegression(max_iter=2000)"]),p=l(["# validate — quick local score on a held-out fifth of train","model.fit(X_tr, y_tr)",a?'print("val RMSE:", round(mean_squared_error(y_val, model.predict(X_val)) ** 0.5, 4))':'print("val accuracy:", round(accuracy_score(y_val, model.predict(X_val)), 4))']),_=l(["# submission — retrain on ALL data, write submission.csv (Kaggle format)","model.fit(X, y)","pred = model.predict(X_test)",'out = OUT + "/submission.csv"',`pd.DataFrame({"${r}": test["${r}"], "${i}": pred}).to_csv(out, index=False)`,'print("wrote", out)',s?`print("score it: icoa kaggle submit ${t.comp_id}")`:'print("format check: icoa kaggle check")']),g=s?["## 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[n(c),m,d,u,p,_,n(g.join("\n"))]}export function parseSubmitResponse(e){const t=e&&"object"==typeof e?e:{},r=t.data??t,i=r&&"object"==typeof r?r:{};return"number"==typeof i.score&&"string"==typeof i.metric?{ok:!0,score:i.score,metric:i.metric,rank:"number"==typeof i.rank_at_time?i.rank_at_time:null,fieldSize:"number"==typeof i.field_size?i.field_size:null,deduped:!0===i.deduped,boardEvent:"string"==typeof i.board_event?i.board_event:null}:"string"==typeof i.reason&&""!==i.reason?{ok:!1,reason:i.reason,error:"string"==typeof i.error?i.error:void 0,problems:Array.isArray(i.problems)?i.problems.filter(e=>"string"==typeof e):void 0}:{ok:!1,reason:"network"}}export function validateSubmissionText(e,t){const r=[],i=e.trim().split(/\r?\n/),a=t.trim().split(/\r?\n/),o=i[0]??"",s=a[0]??"";o.trim()!==s.trim()&&r.push(`header mismatch: expected "${s}", got "${o}"`);const n=i.slice(1).filter(e=>""!==e.trim()),l=a.slice(1).filter(e=>""!==e.trim());n.length!==l.length&&r.push(`row count mismatch: expected ${l.length}, got ${n.length}`);const c=e=>new Set(e.map(e=>(e.split(",")[0]??"").trim())),m=c(n),d=c(l),u=[...d].filter(e=>!m.has(e)),p=[...m].filter(e=>!d.has(e));if(u.length>0||p.length>0){const e=[];u.length>0&&e.push(`${u.length} missing (e.g. ${u[0]})`),p.length>0&&e.push(`${p.length} unknown (e.g. ${p[0]})`),r.push(`id mismatch vs sample_submission: ${e.join(", ")}`)}for(let e=0;e<n.length;e++)if(n[e].split(",").some(e=>""===e.trim())){r.push(`empty cell in data row ${e+1}`);break}return{ok:0===r.length,problems:r}}
@@ -242,10 +242,14 @@ export declare function syncProgress(token: string, event: {
242
242
  time_on_card_ms?: number;
243
243
  }): Promise<void>;
244
244
  /**
245
- * Best-effort card-feedback submission (the `e` "report a problem" channel).
245
+ * Card-feedback submission (the `e` "report a problem" channel).
246
246
  * Crowdsourced card QA — a learner flags an error/confusion on a card; we
247
247
  * record it server-side bound to (curriculum_id, card_number) so the author
248
- * team can triage. Fire-and-forget, same contract as syncProgress.
248
+ * team can triage.
249
+ *
250
+ * Returns whether the server actually accepted the report, so the caller can
251
+ * print an honest ack. (The route spent 43 days undeployed while an
252
+ * unconditional "✓ recorded" hid every 404 — never fake delivery again.)
249
253
  *
250
254
  * Unlike syncProgress, demo (LEARNDEMO01) feedback IS sent — the demo is the
251
255
  * highest-traffic curriculum, so its cards benefit most from crowdsourced QA.
@@ -260,5 +264,5 @@ export declare function syncCardFeedback(token: string, payload: {
260
264
  card_number: number;
261
265
  feedback_text: string;
262
266
  time_on_card_ms?: number;
263
- }): Promise<void>;
267
+ }): Promise<boolean>;
264
268
  export {};
@@ -1 +1 @@
1
- export function localized(r,e){if(!e.startsWith("zh")||!r._zh)return r;const t=r._zh,n={...r};for(const r of Object.keys(t))void 0!==t[r]&&(n[r]=t[r]);return n}export function isValidCurriculum(r){if(!r||"object"!=typeof r)return!1;const e=r;return"string"==typeof e.id&&"number"==typeof e.totalCards&&Array.isArray(e.cards)&&Array.isArray(e.modules)}import{readFileSync as r,writeFileSync as e,mkdirSync as t,existsSync as n,statSync as a,utimesSync as c}from"node:fs";import{join as i}from"node:path";import{homedir as o}from"node:os";import{getDeviceFingerprint as u}from"./access.js";import{getCliVersion as s}from"./version.js";const d=i(o(),".icoa","learn-cache");export const LEARN_SERVER="https://practice.icoa2026.au";function l(r){const e=r.replace(/[^A-Za-z0-9_-]/g,"_");return i(d,`${e}.json`)}function m(r){const e=r.replace(/[^A-Za-z0-9_-]/g,"_");return i(d,`${e}.etag`)}export async function loadCurriculumById(i,o){"ctf4eai-12"===i&&(i="LEARNDEMO01");const u=function(e){const t=l(e);if(!n(t))return null;try{const e=a(t),n=Date.now()-e.mtimeMs;return{curriculum:JSON.parse(r(t,"utf-8")),ageMs:n}}catch{return null}}(i);if(u&&u.ageMs<6048e5&&isValidCurriculum(u.curriculum))return u.curriculum;const f=await async function(e,t){const a=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/curriculum/"+encodeURIComponent(e),c={},i=function(e){const t=m(e);if(!n(t))return null;try{return r(t,"utf-8").trim()||null}catch{return null}}(e);i&&(c["If-None-Match"]=i),t&&(c["X-Learn-Token"]=t.toUpperCase()),c["X-ICOA-Client"]=s();try{const r=await fetch(a,{headers:c,signal:AbortSignal.timeout(6e4)});if(304===r.status)return{kind:"unchanged"};if(!r.ok)return{kind:"error"};const e=await r.json();if(!e.success||!e.data)return{kind:"error"};if(!isValidCurriculum(e.data))return{kind:"error"};const t=r.headers.get("etag")||r.headers.get("ETag")||void 0;return{kind:"fresh",curriculum:e.data,etag:t||void 0}}catch{return{kind:"error"}}}(i,o);return"fresh"===f.kind?(function(r,n,a){try{t(d,{recursive:!0}),e(l(r),JSON.stringify(n)),a&&e(m(r),a)}catch{}}(i,f.curriculum,f.etag),f.curriculum):"unchanged"===f.kind&&u&&isValidCurriculum(u.curriculum)?(function(r){try{const e=l(r);if(n(e)){const r=Date.now()/1e3;c(e,r,r)}}catch{}}(i),u.curriculum):u&&isValidCurriculum(u.curriculum)?u.curriculum:null}export async function validateEAToken(r){const e=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/validate";try{const t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r.toUpperCase(),device_fingerprint:u()}),signal:AbortSignal.timeout(8e3)});if(!t.ok){const r=await t.json().catch(()=>({}));return{ok:!1,message:r.message||`HTTP ${t.status}`,code:r.code}}const n=await t.json();return n.success&&n.data?{ok:!0,curriculumId:n.data.curriculum_id,status:n.data.status,validUntil:n.data.valid_until,aiEnabled:1===n.data.ai_enabled||!0===n.data.ai_enabled}:{ok:!1,message:n.message||"Validation failed"}}catch(r){return{ok:!1,message:`Network error: ${r instanceof Error?r.message:String(r)}`}}}export async function syncProgress(r,e){if("LEARNDEMO01"===r.toUpperCase())return;const t=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/progress/"+r.toUpperCase();try{await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({card_number:e.card_number,event_type:e.event_type,mcq_answer:e.mcq_answer,mcq_correct:e.mcq_correct?1:0,check_answer:e.check_answer,check_correct:e.check_correct?1:0,time_on_card_ms:e.time_on_card_ms,device_fingerprint:u()}),signal:AbortSignal.timeout(5e3)})}catch{}}export async function syncCardFeedback(r,e){const t=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/feedback/"+r.toUpperCase();try{await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({curriculum_id:e.curriculum_id,card_number:e.card_number,feedback_text:e.feedback_text,time_on_card_ms:e.time_on_card_ms}),signal:AbortSignal.timeout(5e3)})}catch{}}
1
+ export function localized(r,e){if(!e.startsWith("zh")||!r._zh)return r;const t=r._zh,n={...r};for(const r of Object.keys(t))void 0!==t[r]&&(n[r]=t[r]);return n}export function isValidCurriculum(r){if(!r||"object"!=typeof r)return!1;const e=r;return"string"==typeof e.id&&"number"==typeof e.totalCards&&Array.isArray(e.cards)&&Array.isArray(e.modules)}import{readFileSync as r,writeFileSync as e,mkdirSync as t,existsSync as n,statSync as a,utimesSync as c}from"node:fs";import{join as i}from"node:path";import{homedir as o}from"node:os";import{getDeviceFingerprint as u}from"./access.js";import{getCliVersion as s}from"./version.js";const d=i(o(),".icoa","learn-cache");export const LEARN_SERVER="https://practice.icoa2026.au";function l(r){const e=r.replace(/[^A-Za-z0-9_-]/g,"_");return i(d,`${e}.json`)}function m(r){const e=r.replace(/[^A-Za-z0-9_-]/g,"_");return i(d,`${e}.etag`)}export async function loadCurriculumById(i,o){"ctf4eai-12"===i&&(i="LEARNDEMO01");const u=function(e){const t=l(e);if(!n(t))return null;try{const e=a(t),n=Date.now()-e.mtimeMs;return{curriculum:JSON.parse(r(t,"utf-8")),ageMs:n}}catch{return null}}(i);if(u&&u.ageMs<6048e5&&isValidCurriculum(u.curriculum))return u.curriculum;const f=await async function(e,t){const a=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/curriculum/"+encodeURIComponent(e),c={},i=function(e){const t=m(e);if(!n(t))return null;try{return r(t,"utf-8").trim()||null}catch{return null}}(e);i&&(c["If-None-Match"]=i),t&&(c["X-Learn-Token"]=t.toUpperCase()),c["X-ICOA-Client"]=s();try{const r=await fetch(a,{headers:c,signal:AbortSignal.timeout(6e4)});if(304===r.status)return{kind:"unchanged"};if(!r.ok)return{kind:"error"};const e=await r.json();if(!e.success||!e.data)return{kind:"error"};if(!isValidCurriculum(e.data))return{kind:"error"};const t=r.headers.get("etag")||r.headers.get("ETag")||void 0;return{kind:"fresh",curriculum:e.data,etag:t||void 0}}catch{return{kind:"error"}}}(i,o);return"fresh"===f.kind?(function(r,n,a){try{t(d,{recursive:!0}),e(l(r),JSON.stringify(n)),a&&e(m(r),a)}catch{}}(i,f.curriculum,f.etag),f.curriculum):"unchanged"===f.kind&&u&&isValidCurriculum(u.curriculum)?(function(r){try{const e=l(r);if(n(e)){const r=Date.now()/1e3;c(e,r,r)}}catch{}}(i),u.curriculum):u&&isValidCurriculum(u.curriculum)?u.curriculum:null}export async function validateEAToken(r){const e=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/validate";try{const t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r.toUpperCase(),device_fingerprint:u()}),signal:AbortSignal.timeout(8e3)});if(!t.ok){const r=await t.json().catch(()=>({}));return{ok:!1,message:r.message||`HTTP ${t.status}`,code:r.code}}const n=await t.json();return n.success&&n.data?{ok:!0,curriculumId:n.data.curriculum_id,status:n.data.status,validUntil:n.data.valid_until,aiEnabled:1===n.data.ai_enabled||!0===n.data.ai_enabled}:{ok:!1,message:n.message||"Validation failed"}}catch(r){return{ok:!1,message:`Network error: ${r instanceof Error?r.message:String(r)}`}}}export async function syncProgress(r,e){if("LEARNDEMO01"===r.toUpperCase())return;const t=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/progress/"+r.toUpperCase();try{await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({card_number:e.card_number,event_type:e.event_type,mcq_answer:e.mcq_answer,mcq_correct:e.mcq_correct?1:0,check_answer:e.check_answer,check_correct:e.check_correct?1:0,time_on_card_ms:e.time_on_card_ms,device_fingerprint:u()}),signal:AbortSignal.timeout(5e3)})}catch{}}export async function syncCardFeedback(r,e){const t=LEARN_SERVER.replace(/\/$/,"")+"/api/icoa/learn/feedback/"+r.toUpperCase();try{return(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({curriculum_id:e.curriculum_id,card_number:e.card_number,feedback_text:e.feedback_text,time_on_card_ms:e.time_on_card_ms}),signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}