icoa-cli 2.19.370 → 2.19.372
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commands/ai4ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/ipynb.d.ts +1 -1
- package/dist/commands/ipynb.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/lib/editor-spawn.d.ts +4 -2
- package/dist/lib/editor-spawn.js +1 -1
- package/dist/lib/learn-ai.d.ts +39 -0
- package/dist/lib/learn-ai.js +1 -1
- package/dist/lib/learn-render.d.ts +22 -0
- package/dist/lib/learn-render.js +1 -1
- package/package.json +1 -1
package/dist/commands/ipynb.d.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* Cell-stepper: the session is a real document. Typed blocks append as cells;
|
|
8
8
|
* `cells / show / edit / add / del / run / save` step through them, `edit N`
|
|
9
|
-
* hands the terminal to $EDITOR (
|
|
9
|
+
* hands the terminal to $EDITOR (default vi) for that one cell, `save` writes a
|
|
10
10
|
* Jupyter-openable .ipynb. Opening a `.py` splits it on `# %%` markers (the
|
|
11
11
|
* arena starter ships with them).
|
|
12
12
|
*
|
package/dist/commands/ipynb.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{createInterface as r}from"node:readline";import{isAbsolute as s,join as c,resolve as a}from"node:path";import chalk from"chalk";import{aienvPaths as i}from"../lib/aienv.js";import{editTextInEditor as g}from"../lib/editor-spawn.js";import{shouldExecuteCell as y}from"../lib/ipynb-input.js";import{NotebookKernel as d}from"../lib/kernel.js";import{getMainRl as u}from"../lib/main-rl.js";import{cellPreview as p,parseIpynb as h,parsePercentPy as f,parseRunRange as m,serializeIpynb as w,statusChar as v}from"../lib/notebook-doc.js";import{openFile as b}from"../lib/open-file.js";const k=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(o){o.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async o=>{await async function(o){const k=i(t()),x=c(t(),".icoa","ipynb-out");if($(),!e(k.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const P=o?function(o){const l=s(o)?o:a(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?h(e):f(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(o):null,C=P?P.doc:{cells:[],path:null,dirty:!1},I=new d({venvPython:k.python,venvRoot:k.root});process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await I.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),P&&console.log(P.note),console.log(chalk.gray(" Type Python and press Enter. Blocks (def/for/…) continue until a blank line.")),console.log(chalk.gray(" Cells: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit in $EDITOR · ")+chalk.cyan("run N")+chalk.gray(" / ")+chalk.cyan("run all")+chalk.gray(" · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" · ")+chalk.cyan("quit")),console.log();const j=u(),S=null!==j,q=S?j.listeners("line").slice():[];S&&j.removeAllListeners("line");const L=S?j:r({input:process.stdin,output:process.stdout,terminal:!0}),O=[];let R=!1,A=!1;const T=()=>{L.setPrompt(chalk.bold.cyan(O.length?"icoa ipynb ...> ":"icoa ipynb> ")),L.prompt()};let M=()=>{};const B=new Promise(e=>{M=e}),D=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>C.cells.length?(console.log(0===C.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${C.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:C.cells[o-1],idx:o}},K=async e=>{if(R)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));const o=e.trim();if(0===O.length){const e=o.split(/\s+/),n=(e[0]??"").toLowerCase(),t=o.slice(e[0]?.length??0).trim();if("quit"!==n&&"exit"!==n&&"q"!==n&&(A=!1),"quit"===n||"exit"===n||"back"===n||"q"===n)return C.dirty&&!A?(A=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void T()):void await(async()=>{if(L.removeAllListeners("line"),console.log(),console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await I.shutdown().catch(()=>{}),S){L.setPrompt(chalk.bold.cyan("icoa> "));for(const e of q)L.on("line",e);L.prompt(),M()}else M(),L.close()})();if("clear"===n||"cls"===n)return console.clear(),$(),void T();if("restart"===n)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await I.shutdown().catch(()=>{});try{await I.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void T();if("help"===n||"?"===n)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default nano)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new cell in your editor")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N (also: run 2-5, run all — stops on error)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void T();if("open"===n)return N&&b(N)?console.log(chalk.gray(" reopening ")+chalk.cyan(N)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void T();if("cells"===n||"ls"===n)return(()=>{if(0===C.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);C.cells.forEach((o,n)=>{const l=v(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(p(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void T();if("show"===n)return(e=>{const o=D(e);if(o){console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`));for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),E(o.cell.result,x)),console.log()}})(t),void T();if("edit"===n)return(e=>{const o=D(e);if(!o)return;L.pause();const n=g(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(L.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,C.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(t),void T();if("add"===n)return(()=>{L.pause();const e=g("");L.resume();const o=null===e?"":e.replace(/\s+$/,"");o?(C.cells.push({kind:"code",source:o,result:null}),C.dirty=!0,console.log(chalk.green(` ✓ added cell ${C.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${C.cells.length}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" nothing added."))})(),void T();if("del"===n||"delete"===n)return(e=>{const o=D(e);o&&(C.cells.splice(o.idx-1,1),C.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${C.cells.length} left.`)))})(t),void T();if("run"===n)return R=!0,await(async e=>{const o=m(e,C.cells.length);if(o)for(const e of o){const n=C.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(p(n,50))+chalk.gray(" ──"));try{n.result=await I.execute(n.source)}catch(e){return void console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}if(C.dirty=!0,E(n.result,x),!n.result.ok)return void(e!==o[o.length-1]&&console.log(chalk.yellow(` ✗ cell ${e} raised — stopping here.`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")))}else{if(o.length>1)continue;console.log(chalk.gray(` cell ${e} is markdown — nothing to run.`))}}else console.log(0===C.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(t),R=!1,void T();if("save"===n)return(e=>{if(0===C.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?s(e.trim())?e.trim():a(process.cwd(),e.trim()):C.path?C.path.endsWith(".ipynb")?C.path:`${C.path.replace(/\.[^./]+$/,"")}.ipynb`:a(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,w(C.cells)),C.path=o,C.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${C.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(t),void T();if(""===o)return void T()}if(O.push(e),!y(O))return void T();const n=O.join("\n").replace(/\s+$/,"");if(O.length=0,""!==n.trim()){R=!0;try{const e=await I.execute(n);C.cells.push({kind:"code",source:n,result:e}),C.dirty=!0,E(e,x)}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}R=!1,T()}else T()};L.on("line",e=>{K(e)}),S||L.on("close",async()=>{await I.shutdown().catch(()=>{}),process.exit(0)}),T(),await B}(o)})}function $(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}let x=0,N=null;function E(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(k,"")}`))}else"display"===n.kind&&P(n.data,o)}function P(e,n){if(e["image/png"])try{o(n,{recursive:!0}),x+=1;const t=c(n,`figure-${x}.png`);return l(t,Buffer.from(e["image/png"],"base64")),N=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(b(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
|
|
1
|
+
import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{createInterface as r}from"node:readline";import{isAbsolute as s,join as c,resolve as a}from"node:path";import chalk from"chalk";import{aienvPaths as i}from"../lib/aienv.js";import{editTextInEditor as g}from"../lib/editor-spawn.js";import{shouldExecuteCell as y}from"../lib/ipynb-input.js";import{NotebookKernel as d}from"../lib/kernel.js";import{getMainRl as u}from"../lib/main-rl.js";import{cellPreview as p,parseIpynb as h,parsePercentPy as f,parseRunRange as m,serializeIpynb as w,statusChar as v}from"../lib/notebook-doc.js";import{openFile as b}from"../lib/open-file.js";const k=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(o){o.command("ipynb").argument("[file]","notebook (.ipynb) or script (.py, split on # %%) to open").description("Open an in-terminal Python notebook (AI/ML — needs `aienv setup`)").action(async o=>{await async function(o){const k=i(t()),x=c(t(),".icoa","ipynb-out");if($(),!e(k.python))return console.log(chalk.yellow(" The AI/ML environment is not set up yet.")),console.log(chalk.gray(" Run ")+chalk.bold.cyan("aienv setup")+chalk.gray(" first (one-time, ~300 MB).")),void console.log();const P=o?function(o){const l=s(o)?o:a(process.cwd(),o);if(!e(l))return{doc:{cells:[],path:l,dirty:!1},note:chalk.gray(" new notebook — will be created on ")+chalk.cyan("save")};try{const e=n(l,"utf8"),o=l.endsWith(".ipynb")?h(e):f(e);return{doc:{cells:o,path:l,dirty:!1},note:chalk.gray(" loaded ")+chalk.cyan(l)+chalk.gray(` — ${o.length} cell${1===o.length?"":"s"}. Type `)+chalk.cyan("cells")+chalk.gray(" to list them.")}}catch(e){return{doc:{cells:[],path:null,dirty:!1},note:chalk.yellow(` could not open ${l}: ${e instanceof Error?e.message:String(e)}`)+chalk.gray(" — starting an empty notebook.")}}}(o):null,C=P?P.doc:{cells:[],path:null,dirty:!1},I=new d({venvPython:k.python,venvRoot:k.root});process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await I.start()}catch{return console.log(chalk.red(" failed.")),console.log(chalk.gray(" Check the environment: ")+chalk.cyan("aienv status")),void console.log()}console.log(chalk.green(" ready.")),P&&console.log(P.note),console.log(chalk.gray(" Type Python and press Enter. Blocks (def/for/…) continue until a blank line.")),console.log(chalk.gray(" Cells: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit in $EDITOR · ")+chalk.cyan("run N")+chalk.gray(" / ")+chalk.cyan("run all")+chalk.gray(" · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" · ")+chalk.cyan("quit")),console.log();const j=u(),S=null!==j,q=S?j.listeners("line").slice():[];S&&j.removeAllListeners("line");const L=S?j:r({input:process.stdin,output:process.stdout,terminal:!0}),O=[];let R=!1,A=!1;const T=()=>{L.setPrompt(chalk.bold.cyan(O.length?"icoa ipynb ...> ":"icoa ipynb> ")),L.prompt()};let M=()=>{};const B=new Promise(e=>{M=e}),D=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>C.cells.length?(console.log(0===C.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${C.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:C.cells[o-1],idx:o}},K=async e=>{if(R)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));const o=e.trim();if(0===O.length){const e=o.split(/\s+/),n=(e[0]??"").toLowerCase(),t=o.slice(e[0]?.length??0).trim();if("quit"!==n&&"exit"!==n&&"q"!==n&&(A=!1),"quit"===n||"exit"===n||"back"===n||"q"===n)return C.dirty&&!A?(A=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void T()):void await(async()=>{if(L.removeAllListeners("line"),console.log(),console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await I.shutdown().catch(()=>{}),S){L.setPrompt(chalk.bold.cyan("icoa> "));for(const e of q)L.on("line",e);L.prompt(),M()}else M(),L.close()})();if("clear"===n||"cls"===n)return console.clear(),$(),void T();if("restart"===n)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await I.shutdown().catch(()=>{});try{await I.start(),console.log(chalk.green(" fresh kernel ready.")+chalk.gray(" (all variables cleared)"))}catch{console.log(chalk.red(" restart failed.")+chalk.gray(" Leave and re-enter the notebook."))}})(),void T();if("help"===n||"?"===n)return console.log(),console.log(chalk.bold.white(" Notebook commands")),console.log(chalk.cyan(" cells")+chalk.gray(" list cells (○ not run · ✓ ok · ✗ error)")),console.log(chalk.cyan(" show N")+chalk.gray(" print cell N source + outputs")),console.log(chalk.cyan(" edit N")+chalk.gray(" edit cell N in your editor ($EDITOR, default vi)")),console.log(chalk.cyan(" add")+chalk.gray(" write a new cell in your editor")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N (also: run 2-5, run all — stops on error)")),console.log(chalk.cyan(" save [file]")+chalk.gray(" save as a real .ipynb")),console.log(chalk.cyan(" restart")+chalk.gray(" restart the kernel (wipes all variables)")),console.log(chalk.cyan(" open")+chalk.gray(" reopen the last figure in your image viewer")),console.log(chalk.cyan(" clear")+chalk.gray(" clear the screen · ")+chalk.cyan("quit")+chalk.gray(" leave")),console.log(chalk.gray(" Everything else runs as Python in the persistent kernel (and is appended as a cell).")),console.log(),void T();if("open"===n)return N&&b(N)?console.log(chalk.gray(" reopening ")+chalk.cyan(N)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void T();if("cells"===n||"ls"===n)return(()=>{if(0===C.cells.length)return void console.log(chalk.gray(" no cells yet — type Python, or ")+chalk.cyan("add")+chalk.gray(" to write one in your editor."));console.log();const e=Math.max(20,(process.stdout.columns??80)-12);C.cells.forEach((o,n)=>{const l=v(o),t="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${t} ${chalk.white(p(o,e))}`)}),console.log(),console.log(chalk.gray(" ")+chalk.cyan("show N")+chalk.gray(" · ")+chalk.cyan("edit N")+chalk.gray(" · ")+chalk.cyan("run N")+chalk.gray(" · ")+chalk.cyan("run all"))})(),void T();if("show"===n)return(e=>{const o=D(e);if(o){console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`));for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),E(o.cell.result,x)),console.log()}})(t),void T();if("edit"===n)return(e=>{const o=D(e);if(!o)return;L.pause();const n=g(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(L.resume(),null===n)return void console.log(chalk.yellow(" editor cancelled or failed — cell unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));const l=n.replace(/\s+$/,"");l!==o.cell.source?(o.cell.source=l,o.cell.result=null,o.cell.rawOutputs=void 0,o.cell.rawExecCount=void 0,C.dirty=!0,console.log(chalk.green(` ✓ cell ${o.idx} updated`)+chalk.gray(" — ")+chalk.cyan(`run ${o.idx}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" no changes."))})(t),void T();if("add"===n)return(()=>{L.pause();const e=g("");L.resume();const o=null===e?"":e.replace(/\s+$/,"");o?(C.cells.push({kind:"code",source:o,result:null}),C.dirty=!0,console.log(chalk.green(` ✓ added cell ${C.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${C.cells.length}`)+chalk.gray(" to execute."))):console.log(chalk.gray(" nothing added."))})(),void T();if("del"===n||"delete"===n)return(e=>{const o=D(e);o&&(C.cells.splice(o.idx-1,1),C.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${C.cells.length} left.`)))})(t),void T();if("run"===n)return R=!0,await(async e=>{const o=m(e,C.cells.length);if(o)for(const e of o){const n=C.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(p(n,50))+chalk.gray(" ──"));try{n.result=await I.execute(n.source)}catch(e){return void console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}if(C.dirty=!0,E(n.result,x),!n.result.ok)return void(e!==o[o.length-1]&&console.log(chalk.yellow(` ✗ cell ${e} raised — stopping here.`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")))}else{if(o.length>1)continue;console.log(chalk.gray(` cell ${e} is markdown — nothing to run.`))}}else console.log(0===C.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(" usage: ")+chalk.cyan("run 3")+chalk.yellow(" · ")+chalk.cyan("run 1-5")+chalk.yellow(" · ")+chalk.cyan("run all"))})(t),R=!1,void T();if("save"===n)return(e=>{if(0===C.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?s(e.trim())?e.trim():a(process.cwd(),e.trim()):C.path?C.path.endsWith(".ipynb")?C.path:`${C.path.replace(/\.[^./]+$/,"")}.ipynb`:a(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,w(C.cells)),C.path=o,C.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${C.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(t),void T();if(""===o)return void T()}if(O.push(e),!y(O))return void T();const n=O.join("\n").replace(/\s+$/,"");if(O.length=0,""!==n.trim()){R=!0;try{const e=await I.execute(n);C.cells.push({kind:"code",source:n,result:e}),C.dirty=!0,E(e,x)}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}R=!1,T()}else T()};L.on("line",e=>{K(e)}),S||L.on("close",async()=>{await I.shutdown().catch(()=>{}),process.exit(0)}),T(),await B}(o)})}function $(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}let x=0,N=null;function E(e,o){for(const n of e.outputs)if("stream"===n.kind){const e=n.text.replace(/\n$/,"");if(0===e.length)continue;console.log("stderr"===n.name?chalk.yellow(e):chalk.white(e))}else if("result"===n.kind)console.log(chalk.cyan(` Out[${e.execCount??"*"}]: `)+chalk.white(n.text));else if("error"===n.kind){console.log(chalk.bold.red(` ${n.ename}: ${n.evalue}`));for(const e of n.traceback)console.log(chalk.gray(` ${e.replace(k,"")}`))}else"display"===n.kind&&P(n.data,o)}function P(e,n){if(e["image/png"])try{o(n,{recursive:!0}),x+=1;const t=c(n,`figure-${x}.png`);return l(t,Buffer.from(e["image/png"],"base64")),N=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(b(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
|
package/dist/commands/learn.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{createInterface as e}from"node:readline";import{spawn as o}from"node:child_process";import{getMainRl as n}from"../lib/main-rl.js";import{existsSync as r}from"node:fs";import{dirname as t,join as l}from"node:path";import{fileURLToPath as a}from"node:url";import{loadCurriculumById as s,validateEAToken as i,syncProgress as c,syncCardFeedback as u}from"../lib/learn-curricula.js";import{normalizeTokenBody as d}from"../lib/token-format.js";import{streamLearnTutor as g,submitPqs as m,viewPqsTop as y}from"../lib/learn-ai.js";import{getConfig as h,saveConfig as f}from"../lib/config.js";import{loadLearnState as p,saveLearnState as w,newLearnState as b,updateStreak as k,markCardComplete as v,recordMCQ as A,recordCheck as C,markPracticalComplete as I,addAchievement as $}from"../lib/learn-state.js";import{renderWelcome as E,renderKnowledgeCard as _,renderMCQCard as T,renderMCQFeedback as M,renderPracticalCard as P,renderPracticalSuccess as O,renderSimDemoCard as x,renderMilestone as L,renderArenaTaskCard as D,renderComingSoonCard as S,renderStatus as q,renderPhaseComplete as j,renderCurriculumComplete as N,setLearnAiEnabled as R,setLearnPqsViewCards as W}from"../lib/learn-render.js";import{printError as F}from"../lib/ui.js";export function registerLearnCommand(B){B.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async B=>{B&&B.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(),B="LEARNDEMO01");let z=B.trim().toUpperCase(),U=null;const J=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(z),Q=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(z);let V=!1;if(J)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),U=await s(z,z);else if(Q){console.log(),console.log(chalk.gray(" Validating token..."));let e=await i(z);if(!e.ok){const o=d(z);if(o!==z){const n=await i(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${z} → ${o}`)),e=n,z=o)}}if(!e.ok)return F(`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"):"")),V=!0===e.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),U=await s(e.curriculumId||"LEARNDEMO01",z),!U)return F(`Could not open a learn curriculum for token '${z}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${z}`)+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 ${z}`)+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(!U)return F(`Unknown learn token: ${z}`),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 K=p(),X=!1;try{K&&K.token===z?k(K):(K=b(z,U.id,U.totalCards),X=!0),w(K),E(U,K,X)}catch{return F("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 ${z}`)+chalk.gray(".")),void console.log()}const Z=n(),G=null!==Z,H=G?Z.listeners("line").slice():[];G&&Z.removeAllListeners("line");const Y=G?Z:e({input:process.stdin,output:process.stdout,terminal:!0}),ee=()=>{Y.setPrompt(chalk.bold.cyan(le?"icoa learn ai> ":"icoa learn> ")),Y.prompt()};let oe=null,ne=null,re=null,te=null,le=!1,ae=!1;const se=new Map,ie=()=>{let e=se.get(K.currentCard);return e||(e=[],se.set(K.currentCard,e)),e};let ce=!1;const ue=new Set;let de=!1,ge=0;const me=(h().language||"en").toLowerCase().startsWith("zh");R(V),W(ue);const ye=[];let he=null;const fe=new Promise(e=>{he=e}),pe=()=>{const e=he;he=null,e?.()},we="1"===process.env.ICOA_LEARN_EMBEDDED,be=e=>U.cards.find(o=>o.number===e),ke=e=>{const o=U.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=U.modules.find(e=>e.number===o.number+1);return j(U,K,o,n),!0},ve=()=>{de=!0,console.log(chalk.gray(me?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Ae=()=>{const e=be(K.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":_(e,U),e.check?(re=e.number,ge=Date.now()):(v(K,e.number),w(K));break;case"mcq":T(e,U),oe=e.number;break;case"practical":P(e,U),ne=e.number;break;case"sim_demo":x(e,U),v(K,e.number),w(K);break;case"milestone":L(e,U),$(K,e.badge),v(K,e.number),w(K);break;case"arena_task":D(e,U),v(K,e.number),w(K);break;case"coming_soon":S(e,U),v(K,e.number),w(K)}},Ce=()=>{z.endsWith("DEMO01")?console.log(chalk.yellow(me?" 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(me?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(me?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Ie=async(e,o)=>{if(V){ae=!0;try{console.log(),console.log(chalk.gray("deep"===o?me?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":me?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let n=!1,r=!1;const t=await g({token:z,cardNumber:K.currentCard,question:e,mode:o,history:ie().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(r||(process.stdout.write(n?"\n\n ":" "),r=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||r)&&console.log(),t.ok?t.offtopic?(console.log(),console.log(chalk.yellow(me?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(ie().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(` (${me?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(me?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==re&&console.log(chalk.gray(me?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{ae=!1}}else Ce()},$e=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ee=async e=>{const n=e.trim().toLowerCase();if(!ae){if(null!==te){const o=e.trim(),n=te;if(te=null,""===o)console.log(chalk.gray(me?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=ge>0?Date.now()-ge:void 0;ye.push(u(z,{curriculum_id:U.id,card_number:n,feedback_text:o,time_on_card_ms:e}).catch(()=>{})),console.log(chalk.green(me?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void ee()}if(ce){ce=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{ae=!0;try{console.log(),console.log(chalk.gray(me?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await m({token:z,cardNumber:K.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(me?"评审暂不可用。":"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(me?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(me?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(me?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(me?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(me?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(me?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=me?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(me?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(me?` 第 ${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 $e(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(me?" 改进提问: ":" 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(` (${me?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?ue.add(K.currentCard):ue.delete(K.currentCard)}finally{ae=!1}})():(console.log(chalk.gray(me?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==re&&(console.log(chalk.gray(me?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ee()}if(de)return de=!1,Ae(),void ee();if(n){if(le){if(["q","quit","exit","back","b","menu"].includes(n))return le=!1,console.log(chalk.gray(me?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ee();const o=e.trim().startsWith("!"),r=o?e.trim().slice(1).trim():e.trim();return r&&await Ie(r,o?"fast":"deep"),void ee()}if("/ai"===n||"/ai!"===n||n.startsWith("/ai ")||n.startsWith("/ai! ")){if(!V)return Ce(),void ee();const o=n.startsWith("/ai!"),r=e.trim().slice(o?4:3).trim();if(!r){le=!0;const e=be(K.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(me?"AI 导师":"AI tutor")+(o?chalk.gray(me?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(me?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void ee()}return await Ie(r,o?"fast":"deep"),void ee()}if("/submit"===n||n.startsWith("/submit ")||"/research"===n||n.startsWith("/research ")){if(!V)return Ce(),void ee();const e=be(K.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(me?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(me?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(me?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(me?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(me?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(me?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(me?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),ce=!0,void ee()}if("/view"===n)return V?(await(async()=>{ae=!0;try{console.log();const e=await y({token:z,cardNumber:K.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(me?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&ue.delete(K.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&ue.add(K.currentCard),console.log(chalk.bold.white(me?` 🏆 本卡 Top-3 提问 — 第 ${K.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${K.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 n=$e(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(" "+e))}),0===o.questions.length&&console.log(chalk.gray(me?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{ae=!1}})(),void ee()):(Ce(),void ee());if("menu"!==n&&"menu confirm"!==n)if("quit"!==n&&"exit"!==n&&"q"!==n){if("status"===n)return q(U,K),void ee();if("lang"===n||n.startsWith("lang ")){const e=n.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(h().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ee();const o=U.cards.some(e=>null!=e._zh),r=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),t="en"===r||"zh"===r&&o,l=t?r:"en";return f({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),re=null,oe=null,ne=null,te=null,de=!1,ce=!1,Ae(),void ee()}if("sim"===n){const e=be(K.currentCard);return e&&"sim_demo"===e.type?(function(e){const n=function(){const e=t(a(import.meta.url)),o=[l(e,"..","..","panda","mujoco-launcher.py"),l(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(r(e))return e;return null}();if(!n)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 s={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${s})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),o("python3",[n,s,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void ee()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ee())}if("bookmark"===n){const e=K.currentCard;return K.bookmarks.includes(e)||K.bookmarks.push(e),w(K),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ee()}if("e"===n)return te=K.currentCard,console.log(chalk.gray(me?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ee();if("back"===n||"b"===n)return K.currentCard>1&&(K.currentCard-=1),oe=null,ne=null,re=null,w(K),Ae(),void ee();if(n.startsWith("card ")){const e=n.slice(5).trim(),o=parseInt(e,10);return!Number.isInteger(o)||o<1||o>U.totalCards?(console.log(chalk.yellow(` Card number must be 1..${U.totalCards}. Try: `)+chalk.bold.green("card 1")),void ee()):(K.currentCard=o,oe=null,ne=null,re=null,w(K),Ae(),void ee())}if(null!==re&&["y","yes","n","no"].includes(n)){const e=be(re);if(e&&"knowledge"===e.type&&e.check){const o=n.startsWith("y")?"y":"n",r=o===e.check.answer,t=Date.now()-ge;v(K,e.number),C(K,e.number,{answer:o,correct:r,submittedAt:(new Date).toISOString()}),w(K);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,o,r,!1),ye.push(c(z,{card_number:e.number,event_type:"check_answered",check_answer:o,check_correct:r,time_on_card_ms:t}).catch(()=>{})),re=null,e.solution&&e.solution.length>0)return void ee();if(K.currentCard<U.totalCards){const e=K.currentCard;K.currentCard+=1,w(K),ke(e)?ve():Ae(),ee()}else N(U,K),ee();return}}if(null!==oe&&["a","b","c","d"].includes(n)){const e=be(oe);if(e&&"mcq"===e.type){const o=n.toUpperCase(),r=o===e.answer;return A(K,e.number,{answer:o,correct:r,submittedAt:(new Date).toISOString()}),v(K,e.number),w(K),M(e,o,r,K),ye.push(c(z,{card_number:e.number,event_type:"mcq_answered",mcq_answer:o,mcq_correct:r}).catch(()=>{})),oe=null,void(r?K.currentCard<U.totalCards?(K.currentCard+=1,w(K),Ae()):(N(U,K),ee()):ee())}}if(null!==ne){if("done"===n){const e=be(ne);if(e&&"practical"===e.type)return I(K,e.number),v(K,e.number),w(K),O(e),ne=null,void ee()}if("skip"===n)return v(K,ne),w(K),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),ne=null,void ee()}if("ok"===n||"next"===n||"continue"===n||"n"===n){if(null!==oe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ee();if(null!==ne)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ee();if(null!==re)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ee();const e=K.currentCard;return K.currentCard+=1,w(K),K.currentCard>U.totalCards?N(U,K):ke(e)?ve():Ae(),void ee()}if(null!==re)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ee();if(null!==oe)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ee();if(null!==ne)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ee();console.log(chalk.gray(" Unknown command. Try: ")+chalk.white("ok")+chalk.gray(" / ")+chalk.white("status")+chalk.gray(" / ")+chalk.white("card N")+chalk.gray(" / ")+chalk.white("/ai")+chalk.gray(" / ")+chalk.white("quit")),ee()}else if(ye.length>0&&await Promise.race([Promise.allSettled(ye),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${K.streakDays} day(s)`)),console.log(),G){Y.removeAllListeners("line");for(const e of H)Y.on("line",e);Y.prompt(),pe()}else Y.removeAllListeners("line"),Y.close();else if(ye.length>0&&await Promise.race([Promise.allSettled(ye),new Promise(e=>setTimeout(e,3e3))]),Y.removeAllListeners("line"),G||!we){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(G?Y:void 0),pe()}else Y.close()}else ee()}};Y.on("line",e=>{Ee(e).catch(e=>{console.log(),console.log(chalk.red(" ⚠ Something went wrong handling that input.")),console.log(chalk.gray(` ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Progress is saved. Type ")+chalk.bold.green("ok")+chalk.gray(" to continue or ")+chalk.bold.green("quit")+chalk.gray(" to exit.")),ee()})}),G||Y.on("close",async()=>{ye.length>0&&await Promise.race([Promise.allSettled(ye),new Promise(e=>setTimeout(e,5e3))]),we?pe():process.exit(0)});try{Ae(),ee()}catch{if(F("Could not render this card — the curriculum may be malformed."),G){Y.removeAllListeners("line");for(const e of H)Y.on("line",e);Y.prompt()}else Y.close();pe()}await fe}),B.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,r=0,t=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await s(e),a=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,r=JSON.stringify(l).length;t+=r,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(r/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),r++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${r} 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{createInterface as e}from"node:readline";import{spawn as o}from"node:child_process";import{getMainRl as n}from"../lib/main-rl.js";import{existsSync as r}from"node:fs";import{dirname as t,join as l}from"node:path";import{fileURLToPath as a}from"node:url";import{loadCurriculumById as s,validateEAToken as c,syncProgress as i,syncCardFeedback as u}from"../lib/learn-curricula.js";import{normalizeTokenBody as d}from"../lib/token-format.js";import{streamLearnTutor as g,submitPqs as m,viewPqsTop as y,viewHonors as h}from"../lib/learn-ai.js";import{getConfig as f,saveConfig as p}from"../lib/config.js";import{loadLearnState as b,saveLearnState as w,newLearnState as k,updateStreak as v,markCardComplete as A,recordMCQ as C,recordCheck as I,markPracticalComplete as $,addAchievement as E}from"../lib/learn-state.js";import{renderWelcome as _,renderKnowledgeCard as T,renderMCQCard as M,renderMCQFeedback as P,renderPracticalCard as L,renderPracticalSuccess as O,renderSimDemoCard as x,renderMilestone as D,renderArenaTaskCard as S,renderComingSoonCard as q,renderStatus as j,renderPhaseComplete as N,renderCurriculumComplete as R,setLearnAiEnabled as W,setLearnPqsViewCards as F,renderHonorWall as B}from"../lib/learn-render.js";import{printError as z}from"../lib/ui.js";export function registerLearnCommand(U){U.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async U=>{U&&U.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(),U="LEARNDEMO01");let J=U.trim().toUpperCase(),Q=null;const V=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(J),H=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(J);let K=!1;if(V)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),Q=await s(J,J);else if(H){console.log(),console.log(chalk.gray(" Validating token..."));let e=await c(J);if(!e.ok){const o=d(J);if(o!==J){const n=await c(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${J} → ${o}`)),e=n,J=o)}}if(!e.ok)return z(`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"):"")),K=!0===e.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),Q=await s(e.curriculumId||"LEARNDEMO01",J),!Q)return z(`Could not open a learn curriculum for token '${J}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${J}`)+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 ${J}`)+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(!Q)return z(`Unknown learn token: ${J}`),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 X=b(),Z=!1;try{X&&X.token===J?v(X):(X=k(J,Q.id,Q.totalCards),Z=!0),w(X),_(Q,X,Z)}catch{return z("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 ${J}`)+chalk.gray(".")),void console.log()}const G=n(),Y=null!==G,ee=Y?G.listeners("line").slice():[];Y&&G.removeAllListeners("line");const oe=Y?G:e({input:process.stdin,output:process.stdout,terminal:!0}),ne=()=>{oe.setPrompt(chalk.bold.cyan(se?"icoa learn ai> ":"icoa learn> ")),oe.prompt()};let re=null,te=null,le=null,ae=null,se=!1,ce=!1;const ie=new Map,ue=()=>{let e=ie.get(X.currentCard);return e||(e=[],ie.set(X.currentCard,e)),e};let de=!1;const ge=new Set;let me=!1,ye=0;const he=(f().language||"en").toLowerCase().startsWith("zh");W(K),F(ge);const fe=[];let pe=null;const be=new Promise(e=>{pe=e}),we=()=>{const e=pe;pe=null,e?.()},ke="1"===process.env.ICOA_LEARN_EMBEDDED,ve=e=>Q.cards.find(o=>o.number===e),Ae=e=>{const o=Q.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=Q.modules.find(e=>e.number===o.number+1);return N(Q,X,o,n),!0},Ce=()=>{me=!0,console.log(chalk.gray(he?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Ie=()=>{const e=ve(X.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":T(e,Q),e.check?(le=e.number,ye=Date.now()):(A(X,e.number),w(X));break;case"mcq":M(e,Q),re=e.number;break;case"practical":L(e,Q),te=e.number;break;case"sim_demo":x(e,Q),A(X,e.number),w(X);break;case"milestone":D(e,Q),E(X,e.badge),A(X,e.number),w(X);break;case"arena_task":S(e,Q),A(X,e.number),w(X);break;case"coming_soon":q(e,Q),A(X,e.number),w(X)}},$e=()=>{J.endsWith("DEMO01")?console.log(chalk.yellow(he?" 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(he?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(he?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Ee=async(e,o)=>{if(K){ce=!0;try{console.log(),console.log(chalk.gray("deep"===o?he?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":he?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let n=!1,r=!1;const t=await g({token:J,cardNumber:X.currentCard,question:e,mode:o,history:ue().slice(-8)},e=>{"reasoning"===e.kind?(n||(process.stdout.write(" "),n=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(r||(process.stdout.write(n?"\n\n ":" "),r=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(n||r)&&console.log(),t.ok?t.offtopic?(console.log(),console.log(chalk.yellow(he?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(ue().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(` (${he?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(he?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==le&&console.log(chalk.gray(he?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{ce=!1}}else $e()},_e=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Te=async e=>{const n=e.trim().toLowerCase();if(!ce){if(null!==ae){const o=e.trim(),n=ae;if(ae=null,""===o)console.log(chalk.gray(he?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=ye>0?Date.now()-ye:void 0;fe.push(u(J,{curriculum_id:Q.id,card_number:n,feedback_text:o,time_on_card_ms:e}).catch(()=>{})),console.log(chalk.green(he?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void ne()}if(de){de=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{ce=!0;try{console.log(),console.log(chalk.gray(he?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await m({token:J,cardNumber:X.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(he?"评审暂不可用。":"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(he?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(he?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(he?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(he?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(he?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(he?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,n=he?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(n):chalk.white(n))+(o?chalk.bold.magenta(he?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(he?` 第 ${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 _e(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(he?" 改进提问: ":" 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(` (${he?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?ge.add(X.currentCard):ge.delete(X.currentCard);const o=await h({token:J,curriculumId:Q.id,cardNumber:X.currentCard});o.ok&&o.totals&&o.chapters&&(B({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log())}finally{ce=!1}})():(console.log(chalk.gray(he?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==le&&(console.log(chalk.gray(he?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ne()}if(me)return me=!1,Ie(),void ne();if(n){if(se){if(["q","quit","exit","back","b","menu"].includes(n))return se=!1,console.log(chalk.gray(he?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ne();const o=e.trim().startsWith("!"),r=o?e.trim().slice(1).trim():e.trim();return r&&await Ee(r,o?"fast":"deep"),void ne()}if("/ai"===n||"/ai!"===n||n.startsWith("/ai ")||n.startsWith("/ai! ")){if(!K)return $e(),void ne();const o=n.startsWith("/ai!"),r=e.trim().slice(o?4:3).trim();if(!r){se=!0;const e=ve(X.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(he?"AI 导师":"AI tutor")+(o?chalk.gray(he?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(he?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void ne()}return await Ee(r,o?"fast":"deep"),void ne()}if("/submit"===n||n.startsWith("/submit ")||"/research"===n||n.startsWith("/research ")){if(!K)return $e(),void ne();const e=ve(X.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(he?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(he?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(he?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(he?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(he?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(he?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(he?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),de=!0,void ne()}if("/view"===n)return K?(await(async()=>{ce=!0;try{console.log();const e=await y({token:J,cardNumber:X.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(he?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&ge.delete(X.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&ge.add(X.currentCard),console.log(chalk.bold.white(he?` 🏆 本卡 Top-3 提问 — 第 ${X.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${X.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 n=_e(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(n[0]??""));for(const e of n.slice(1))console.log(chalk.white(" "+e))}),0===o.questions.length&&console.log(chalk.gray(he?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{ce=!1}})(),void ne()):($e(),void ne());if("/honors"===n||"honors"===n)return V?(console.log(),console.log(chalk.gray(he?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void ne()):(await(async()=>{ce=!0;try{console.log();const e=await h({token:J,curriculumId:Q.id,cardNumber:X.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(he?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(he?` 🏆 本卡实时 Top-3 — 第 ${X.currentCard} 张`:` 🏆 Live top-3 — card ${X.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(he?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),B({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log()}finally{ce=!1}})(),void ne());if("menu"!==n&&"menu confirm"!==n)if("quit"!==n&&"exit"!==n&&"q"!==n){if("status"===n)return j(Q,X),void ne();if("lang"===n||n.startsWith("lang ")){const e=n.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(f().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ne();const o=Q.cards.some(e=>null!=e._zh),r=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),t="en"===r||"zh"===r&&o,l=t?r:"en";return p({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),le=null,re=null,te=null,ae=null,me=!1,de=!1,Ie(),void ne()}if("sim"===n){const e=ve(X.currentCard);return e&&"sim_demo"===e.type?(function(e){const n=function(){const e=t(a(import.meta.url)),o=[l(e,"..","..","panda","mujoco-launcher.py"),l(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(r(e))return e;return null}();if(!n)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 s={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${s})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),o("python3",[n,s,"--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 ne()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ne())}if("bookmark"===n){const e=X.currentCard;return X.bookmarks.includes(e)||X.bookmarks.push(e),w(X),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ne()}if("e"===n)return ae=X.currentCard,console.log(chalk.gray(he?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ne();if("back"===n||"b"===n)return X.currentCard>1&&(X.currentCard-=1),re=null,te=null,le=null,w(X),Ie(),void ne();if(n.startsWith("card ")){const e=n.slice(5).trim(),o=parseInt(e,10);return!Number.isInteger(o)||o<1||o>Q.totalCards?(console.log(chalk.yellow(` Card number must be 1..${Q.totalCards}. Try: `)+chalk.bold.green("card 1")),void ne()):(X.currentCard=o,re=null,te=null,le=null,w(X),Ie(),void ne())}if(null!==le&&["y","yes","n","no"].includes(n)){const e=ve(le);if(e&&"knowledge"===e.type&&e.check){const o=n.startsWith("y")?"y":"n",r=o===e.check.answer,t=Date.now()-ye;A(X,e.number),I(X,e.number,{answer:o,correct:r,submittedAt:(new Date).toISOString()}),w(X);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,o,r,!1),fe.push(i(J,{card_number:e.number,event_type:"check_answered",check_answer:o,check_correct:r,time_on_card_ms:t}).catch(()=>{})),le=null,e.solution&&e.solution.length>0)return void ne();if(X.currentCard<Q.totalCards){const e=X.currentCard;X.currentCard+=1,w(X),Ae(e)?Ce():Ie(),ne()}else R(Q,X),ne();return}}if(null!==re&&["a","b","c","d"].includes(n)){const e=ve(re);if(e&&"mcq"===e.type){const o=n.toUpperCase(),r=o===e.answer;return C(X,e.number,{answer:o,correct:r,submittedAt:(new Date).toISOString()}),A(X,e.number),w(X),P(e,o,r,X),fe.push(i(J,{card_number:e.number,event_type:"mcq_answered",mcq_answer:o,mcq_correct:r}).catch(()=>{})),re=null,void(r?X.currentCard<Q.totalCards?(X.currentCard+=1,w(X),Ie()):(R(Q,X),ne()):ne())}}if(null!==te){if("done"===n){const e=ve(te);if(e&&"practical"===e.type)return $(X,e.number),A(X,e.number),w(X),O(e),te=null,void ne()}if("skip"===n)return A(X,te),w(X),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),te=null,void ne()}if("ok"===n||"next"===n||"continue"===n||"n"===n){if(null!==re)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ne();if(null!==te)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ne();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 ne();const e=X.currentCard;return X.currentCard+=1,w(X),X.currentCard>Q.totalCards?R(Q,X):Ae(e)?Ce():Ie(),void ne()}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 ne();if(null!==re)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ne();if(null!==te)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ne();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")),ne()}else if(fe.length>0&&await Promise.race([Promise.allSettled(fe),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${X.streakDays} day(s)`)),console.log(),Y){oe.removeAllListeners("line");for(const e of ee)oe.on("line",e);oe.prompt(),we()}else oe.removeAllListeners("line"),oe.close();else if(fe.length>0&&await Promise.race([Promise.allSettled(fe),new Promise(e=>setTimeout(e,3e3))]),oe.removeAllListeners("line"),Y||!ke){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(Y?oe:void 0),we()}else oe.close()}else ne()}};oe.on("line",e=>{Te(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.")),ne()})}),Y||oe.on("close",async()=>{fe.length>0&&await Promise.race([Promise.allSettled(fe),new Promise(e=>setTimeout(e,5e3))]),ke?we():process.exit(0)});try{Ie(),ne()}catch{if(z("Could not render this card — the curriculum may be malformed."),Y){oe.removeAllListeners("line");for(const e of ee)oe.on("line",e);oe.prompt()}else oe.close();we()}await be}),U.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let n=0,r=0,t=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await s(e),a=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,r=JSON.stringify(l).length;t+=r,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(r/1024).toFixed(1).padStart(6)} KB · ${a.toString().padStart(4)} ms`)),n++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),r++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${n} cached`)+chalk.gray(` · ${r} failed · total ${(t/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
|
@@ -12,8 +12,10 @@ export interface EditorCommand {
|
|
|
12
12
|
cmd: string;
|
|
13
13
|
args: string[];
|
|
14
14
|
}
|
|
15
|
-
/** $VISUAL → $EDITOR →
|
|
16
|
-
*
|
|
15
|
+
/** $VISUAL → $EDITOR → vi (notepad on native Windows). vi is the POSIX
|
|
16
|
+
* floor — present on every baseline terminal, and what the coretools track
|
|
17
|
+
* teaches — whereas nano isn't guaranteed installed. Values like "code -w"
|
|
18
|
+
* split on whitespace into cmd + args. Pure for testability. */
|
|
17
19
|
export declare function resolveEditor(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): EditorCommand;
|
|
18
20
|
/**
|
|
19
21
|
* Open `initial` in the user's editor; return the edited text, or null if the
|
package/dist/lib/editor-spawn.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync as r}from"node:child_process";import{mkdtempSync as o,readFileSync as t,rmSync as s,writeFileSync as e}from"node:fs";import{tmpdir as
|
|
1
|
+
import{spawnSync as r}from"node:child_process";import{mkdtempSync as o,readFileSync as t,rmSync as s,writeFileSync as e}from"node:fs";import{tmpdir as i}from"node:os";import{join as n}from"node:path";export function resolveEditor(r=process.env,o=process.platform){const t=(r.VISUAL??"").trim()||(r.EDITOR??"").trim();if(t){const r=t.split(/\s+/);return{cmd:r[0],args:r.slice(1)}}return"win32"===o?{cmd:"notepad",args:[]}:{cmd:"vi",args:[]}}export function editTextInEditor(c,d=".py"){const l=o(n(i(),"icoa-cell-")),m=n(l,`cell${d}`);e(m,""===c||c.endsWith("\n")?c:`${c}\n`);const p=resolveEditor(),a=process.stdin,f=!!a.isTTY&&a.isRaw;try{a.isTTY&&a.setRawMode(!1);const o=r(p.cmd,[...p.args,m],{stdio:"inherit"});return o.error||0!==o.status?null:t(m,"utf8")}catch{return null}finally{a.isTTY&&f&&a.setRawMode(!0),s(l,{recursive:!0,force:!0})}}
|
package/dist/lib/learn-ai.d.ts
CHANGED
|
@@ -59,6 +59,45 @@ export declare function viewPqsTop(opts: {
|
|
|
59
59
|
token: string;
|
|
60
60
|
cardNumber: number;
|
|
61
61
|
}): Promise<PqsTopResult>;
|
|
62
|
+
export type HonorBoardEntry = {
|
|
63
|
+
rank: number;
|
|
64
|
+
score: number;
|
|
65
|
+
tier: string;
|
|
66
|
+
icon: string;
|
|
67
|
+
me: boolean;
|
|
68
|
+
};
|
|
69
|
+
export type HonorCardMedal = {
|
|
70
|
+
card: number;
|
|
71
|
+
rank: number;
|
|
72
|
+
icon: string;
|
|
73
|
+
score: number;
|
|
74
|
+
since: string;
|
|
75
|
+
};
|
|
76
|
+
export type HonorChapter = {
|
|
77
|
+
chapter: number;
|
|
78
|
+
gold: number;
|
|
79
|
+
silver: number;
|
|
80
|
+
bronze: number;
|
|
81
|
+
cards: HonorCardMedal[];
|
|
82
|
+
};
|
|
83
|
+
export type HonorsResult = {
|
|
84
|
+
ok: boolean;
|
|
85
|
+
board?: HonorBoardEntry[];
|
|
86
|
+
totals?: {
|
|
87
|
+
gold: number;
|
|
88
|
+
silver: number;
|
|
89
|
+
bronze: number;
|
|
90
|
+
};
|
|
91
|
+
chapters?: HonorChapter[];
|
|
92
|
+
floor?: number;
|
|
93
|
+
message?: string;
|
|
94
|
+
code?: string;
|
|
95
|
+
};
|
|
96
|
+
export declare function viewHonors(opts: {
|
|
97
|
+
token: string;
|
|
98
|
+
curriculumId?: string;
|
|
99
|
+
cardNumber?: number;
|
|
100
|
+
}): Promise<HonorsResult>;
|
|
62
101
|
export declare function streamLearnTutor(opts: {
|
|
63
102
|
token: string;
|
|
64
103
|
cardNumber: number;
|
package/dist/lib/learn-ai.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getDeviceFingerprint as e}from"./access.js";import{LEARN_SERVER as t}from"./learn-curricula.js";export async function submitPqs(r){const
|
|
1
|
+
import{getDeviceFingerprint as e}from"./access.js";import{LEARN_SERVER as t}from"./learn-curricula.js";export async function submitPqs(r){const a=t.replace(/\/$/,"")+"/api/icoa/learn/submit";try{const t=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r.token.toUpperCase(),card_number:r.cardNumber,device_fingerprint:e()}),signal:AbortSignal.timeout(18e4)}),o=await t.json().catch(()=>({}));if(!t.ok||!o.success||!o.data)return{ok:!1,message:o.message||`HTTP ${t.status}`,code:o.code};const n=o.data;return{ok:!0,score:n.score,tier:n.tier,manipulation:n.manipulation,feedback:n.feedback,improve:n.improve,submissionIndex:n.submission_index,submissionsLeft:n.submissions_left,rank:n.rank,entrants:n.entrants,inTop3:n.in_top3,turns:n.turns,spent:n.spent,cap:n.cap}}catch(e){return{ok:!1,message:e instanceof Error&&"TimeoutError"===e.name?"PQS grading timed out — your conversation is safe on the server; try /submit again in a minute.":`Network error: ${e instanceof Error?e.message:String(e)}`}}}export async function viewPqsTop(r){const a=t.replace(/\/$/,"")+"/api/icoa/learn/view";try{const t=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r.token.toUpperCase(),card_number:r.cardNumber,device_fingerprint:e()}),signal:AbortSignal.timeout(3e4)}),o=await t.json().catch(()=>({}));return t.ok&&o.success&&o.data?{ok:!0,top3:o.data.top3,myRank:o.data.my_rank,entrants:o.data.entrants}:{ok:!1,message:o.message||`HTTP ${t.status}`,code:o.code,myRank:o.rank,entrants:o.entrants}}catch(e){return{ok:!1,message:`Network error: ${e instanceof Error?e.message:String(e)}`}}}export async function viewHonors(r){const a=t.replace(/\/$/,"")+"/api/icoa/learn/honors";try{const t=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r.token.toUpperCase(),curriculum_id:r.curriculumId,card_number:r.cardNumber,device_fingerprint:e()}),signal:AbortSignal.timeout(3e4)}),o=await t.json().catch(()=>({}));return t.ok&&o.success&&o.data?{ok:!0,board:o.data.board,totals:o.data.totals,chapters:o.data.chapters,floor:o.data.floor}:{ok:!1,message:o.message||`HTTP ${t.status}`,code:o.code}}catch(e){return{ok:!1,message:`Network error: ${e instanceof Error?e.message:String(e)}`}}}export async function streamLearnTutor(r,a){const o=t.replace(/\/$/,"")+"/api/icoa/learn/ai",n=new AbortController;let s=setTimeout(()=>n.abort(),6e4);const i=()=>{clearTimeout(s),s=setTimeout(()=>n.abort(),6e4)};try{const t=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:r.token.toUpperCase(),card_number:r.cardNumber,question:r.question,mode:r.mode,history:r.history?.slice(-6),device_fingerprint:e()}),signal:n.signal});if(!t.ok||!t.body){const e=await t.json().catch(()=>({}));return{ok:!1,answer:"",message:e.message||`HTTP ${t.status}`,code:e.code,spent:e.spent,cap:e.cap}}const s=t.body.getReader(),c=new TextDecoder;let d="",m="",u=null,p=null;for(;;){const e=await s.read();if(e.done)break;i(),d+=c.decode(e.value,{stream:!0});const t=d.split("\n");d=t.pop()??"";for(const e of t){const t=e.trim();if(!t.startsWith("data:"))continue;let r;try{r=JSON.parse(t.slice(5).trim())}catch{continue}r.r&&a({kind:"reasoning",text:r.r}),r.c&&(m+=r.c,a({kind:"content",text:r.c})),r.error&&(p=r.error),r.done&&(u=r)}}return p&&!m?{ok:!1,answer:"",message:p}:m?{ok:!0,answer:m,offtopic:!0===u?.offtopic,spent:u?.spent,cap:u?.cap}:{ok:!1,answer:"",message:"No answer received — try again."}}catch(e){return{ok:!1,answer:"",message:e instanceof Error&&"AbortError"===e.name?"AI tutor timed out (no data for 60s) — try again.":`Network error: ${e instanceof Error?e.message:String(e)}`}}finally{clearTimeout(s)}}
|
|
@@ -3,6 +3,28 @@ import type { LearnState } from './learn-state.js';
|
|
|
3
3
|
export declare function renderWelcome(curriculum: Curriculum, state: LearnState, isNewSession: boolean): void;
|
|
4
4
|
export declare function setLearnAiEnabled(on: boolean): void;
|
|
5
5
|
export declare function setLearnPqsViewCards(cards: ReadonlySet<number>): void;
|
|
6
|
+
export type HonorWallData = {
|
|
7
|
+
totals: {
|
|
8
|
+
gold: number;
|
|
9
|
+
silver: number;
|
|
10
|
+
bronze: number;
|
|
11
|
+
};
|
|
12
|
+
chapters: Array<{
|
|
13
|
+
chapter: number;
|
|
14
|
+
gold: number;
|
|
15
|
+
silver: number;
|
|
16
|
+
bronze: number;
|
|
17
|
+
cards: Array<{
|
|
18
|
+
card: number;
|
|
19
|
+
rank: number;
|
|
20
|
+
icon: string;
|
|
21
|
+
score: number;
|
|
22
|
+
since: string;
|
|
23
|
+
}>;
|
|
24
|
+
}>;
|
|
25
|
+
floor?: number;
|
|
26
|
+
};
|
|
27
|
+
export declare function renderHonorWall(data: HonorWallData): void;
|
|
6
28
|
export declare function renderKnowledgeCard(card: Extract<Card, {
|
|
7
29
|
type: 'knowledge';
|
|
8
30
|
}>, curriculum: Curriculum): void;
|
package/dist/lib/learn-render.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import o from"string-width";import{localized as e}from"./learn-curricula.js";import{t as n}from"./learn-i18n.js";import{getConfig as l}from"./config.js";import{icoaBannerLines as t}from"./banner.js";import{renderCharts as r,detectCaps as c}from"./render-card.js";function s(){return(l().language||"en").toLowerCase()}const a=64;function g(o="─"){return o.repeat(66)}function i(o,e,n=20){const l=e>0?o/e:0,t=Math.floor(l*n),r=n-t;return`${chalk.green("█".repeat(t))+chalk.gray("░".repeat(r))} ${(100*l).toFixed(1)}%`}function d(o){return o>=30?chalk.red("🔥🔥🔥 "+o+" days"):o>=7?chalk.yellow("🔥 "+o+" days"):o>=1?chalk.gray("· "+o+" day"+(o>1?"s":"")):chalk.gray("—")}export function renderWelcome(o,e,l){const t=s(),r=e.cardsCompleted.length,c=o.totalCards,a=c-r,y=o.modules.find(o=>e.currentCard>=o.cardRange[0]&&e.currentCard<=o.cardRange[1]),u=/demo/i.test(o.id);if(console.log(),console.log(chalk.cyan(" ╭"+g("═"))),console.log(chalk.cyan(" ║")),console.log(chalk.cyan(" ║ ")+chalk.bold.white(" "+(o.name?.trim()||n("academy_title",t)))),console.log(chalk.cyan(" ║")),l)console.log(chalk.cyan(" ║ ")+chalk.white(" "+n(u?"welcome_new_demo":"welcome_new",t)));else{const o=new Date(e.lastSeenAt),l=Math.floor((Date.now()-o.getTime())/36e5),r=l<1?n("just_now",t):l<24?`${l}${n("ago_hours",t)}`:`${Math.floor(l/24)}${n("ago_days",t)}`;console.log(chalk.cyan(" ║ ")+chalk.white(` ${n("welcome_back",t)} ${r}`))}console.log(chalk.cyan(" ║"));const h=y?`${y.number}. ${y.name}`:"—";console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("module",t).padEnd(11))+chalk.white(h)),console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("progress",t).padEnd(11))+i(r,c)+chalk.gray(` (${r}/${c})`)),console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("streak",t).padEnd(11))+d(e.streakDays)),a>0&&e.currentCard<=c&&console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("next_card",t).padEnd(11))+chalk.white(`#${e.currentCard} ${n("of",t)} ${c}`)),console.log(chalk.cyan(" ║")),console.log(chalk.cyan(" ╰"+g("═"))),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const m=0===r?n("continue_start",t):`${n("continue_resume",t)} ${e.currentCard}`;console.log(chalk.bold.green(" continue")+chalk.gray(" "+m)),console.log(chalk.yellow(" status")+chalk.gray(" "+n("status_full",t))),e.bookmarks.length>0&&console.log(chalk.yellow(" bookmarks")+chalk.gray(` ${e.bookmarks.length} ${n("bookmarks_desc",t)}`)),console.log(chalk.gray(" quit")+chalk.gray(" "+n("quit_desc",t))),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log()}function y(o,e){const l=s(),t=o.module,r=e.modules.find(o=>o.number===t),c=r?r.name:n("unknown_module",l),g=n("module",l).replace(":","").trim(),i=`${n("card",l)} ${o.number} / ${e.totalCards} · ${g} ${t} · ${c}`;console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(i)+" "+chalk.cyan("─".repeat(Math.max(0,a-i.length-4))))}function u(){console.log(chalk.cyan(" ╰"+g())),console.log()}function h(o){console.log(chalk.cyan(" │ ")+chalk.white(o))}function m(){console.log(chalk.cyan(" │"))}const f=/[┌┐└┘├┤┬┴┼─│╔╗╚╝═║╠╣╦╩╬▓▒░█]/;function b(o){return/^(?: {4}|\t)/.test(o)||f.test(o)||/ {3,}/.test(o)}function p(e,n){const l=[];let t="",r=0,c=!1;for(const s of function(e){const n=[],l=e=>{let l="";const t=()=>{l&&(n.push({t:"atom",s:l}),l="")};for(const r of e)" "===r?(t(),n.push({t:"space"})):2===o(r)?(t(),n.push({t:"wide",s:r})):l+=r;t()},t=/`[^`]*`/g;let r,c=0;for(;null!==(r=t.exec(e));)l(e.slice(c,r.index)),n.push({t:"code",s:r[0]}),c=r.index+r[0].length;return l(e.slice(c)),n}(e)){if("space"===s.t){""!==t&&(c=!0);continue}const e=s.s,a=o("code"===s.t?e.replace(/`/g,""):e),g=c?1:0,i="atom"===s.t&&e.length<=2&&/^[.,;:!?)\]}…'"]+$/.test(e);""!==t&&!i&&r+g+a>n?(l.push(t),t=e,r=a,c=!1):(c&&(t+=" ",r+=1,c=!1),t+=e,r+=a)}return t&&l.push(t),l}const w=/\b(?:Common bug|Common mistake|Common error|Pitfall|Gotcha|Footgun)\b[::]?|\b(?:Warning|Caution)\b[::]|(?:常见错误|常见陷阱|常见误区|陷阱|注意|警告|误区)[::]/gi;function _(o,e){const n=e?chalk.bold.white:chalk.white;let l,t="",r=0;for(w.lastIndex=0;null!==(l=w.exec(o));)l.index>r&&(t+=n(o.slice(r,l.index))),t+=chalk.bold.yellow(l[0]),r=l.index+l[0].length;return r<o.length&&(t+=n(o.slice(r))),t}function $(o,e=!1){let n="",l=0;const t=/`([^`]*)`/g;let r;for(;null!==(r=t.exec(o));)r.index>l&&(n+=_(o.slice(l,r.index),e)),n+=chalk.cyan(r[1]),l=r.index+r[0].length;return l<o.length&&(n+=_(o.slice(l),e)),n}function k(o,e=!1){let n=!1;for(const l of o.split("\n"))if(/^\s*```/.test(l))n=!n;else if(n)console.log(chalk.cyan(" │ ")+chalk.cyan(` ${l}`));else if(""!==l)if(b(l))console.log(chalk.cyan(" │ ")+chalk.white(l));else for(const o of p(l,60))console.log(chalk.cyan(" │ ")+` ${$(o,e)}`);else m()}function x(o,e){const n=[];for(const l of o.split("\n")){if(""===l){n.push("");continue}if(b(l)){n.push(l);continue}let o="";for(const t of l.split(" "))(o+" "+t).trim().length>e?(n.push(o.trim()),o=t):o=(o+" "+t).trim();o&&n.push(o)}return n}let C=!1;export function setLearnAiEnabled(o){C=o}let q=new Set;export function setLearnPqsViewCards(o){q=o}export function renderKnowledgeCard(l,t){const g=s(),i=e(l,g);y(i,t),m();const d=p(i.title,60);for(const o of d)h(chalk.bold.yellow(o));h(chalk.gray("─".repeat(Math.min(Math.max(...d.map(e=>o(e))),a))));const f=!!(l.chart_ids&&l.chart_ids.length>0);if(f&&r(l.chart_ids.slice(0,1),t.charts,c()),i.key_point&&""!==i.key_point.trim()?(f||m(),function(o,e,n){const l=s().startsWith("zh"),t=c().cols,r="-".repeat(Math.min(a,Math.max(24,t-6))),g=l?"要点":"KEY POINT",i=l?`第 ${e} / ${n} 张`:`Card ${e} / ${n}`;console.log(chalk.cyan(" │ ")+chalk.green(r)),console.log(chalk.cyan(" │ ")+chalk.green(`${g} · ${i}`));for(const e of p(o,60))console.log(chalk.cyan(" │ ")+chalk.bold.green(" "+e));console.log(chalk.cyan(" │ ")+chalk.green(r)),m()}(i.key_point,i.number,t.totalCards)):f||m(),i.body.filter(o=>null!=o&&""!==o.trim()).forEach((o,e)=>{const n=0===e?o.match(/^([\s\S]*?(?:[.!?](?=\s|$)|[。!?]))(\s[\s\S]*)?$/):null;if(n&&n[1].trim().length<=180){k(n[1],!0);const o=n[2]?.trimStart();o&&k(o,!1)}else k(o,!1);m()}),i.icoaConnection){h(chalk.magenta(" "+n("icoa_connection",g))),h(chalk.gray(" "+"─".repeat(20)));for(const o of p(i.icoaConnection,60))h(" "+chalk.magenta(o));m()}if(l.check){const o=g.startsWith("zh"),e=l._zh?.checkStatement??l._zh?.check?.statement,n=o?e??l.check.statement:l.check.statement;h(chalk.cyan(" 🤔 "+(o?"请回答 (输 y 或 n):":"Quick comprehension check (type y or n):"))),h(chalk.gray(" "+"─".repeat(20)));for(const o of p(n,60))h(" "+chalk.white(o));m()}u(),function(o,e){const n=s().startsWith("zh"),l=c().cols,t="-".repeat(Math.min(a,Math.max(24,l-6))),r=chalk.gray(" "),g=[];o.check?(g.push(chalk.bold.green("[y]")+chalk.gray(n?" 是":" yes")),g.push(chalk.bold.green("[n]")+chalk.gray(n?" 否":" no"))):g.push(chalk.bold.green("[ok]")+chalk.gray(n?" 继续":" next")),C&&(g.push(chalk.bold.magenta("[/ai]")+chalk.gray(n?" AI导师":" AI tutor")),g.push(chalk.bold.magenta("[/submit]")+chalk.gray(n?" 提问评分":" prompt score")),q.has(o.number)&&g.push(chalk.bold.magenta("[/view]")+chalk.gray(n?" 榜单":" top-3"))),g.push(chalk.bold.yellow("[e]")+chalk.gray(n?" 报告问题":" report")),g.push(chalk.bold.cyan("[b]")+chalk.gray(n?" 上一张":" back")),g.push(chalk.bold.cyan("[card N]")+chalk.gray(n?" 跳转":" jump")),g.push(chalk.gray("[quit]")+chalk.gray(n?" 退出":" quit")),console.log(chalk.gray(" "+t)),console.log(chalk.gray(" "+(n?`第 ${o.number} / ${e.totalCards} 张`:`Card ${o.number} / ${e.totalCards}`))),console.log(" "+g.join(r)),console.log(chalk.gray(" "+t)),console.log(chalk.gray(" "+(n?"e = 报告本卡错误,不算作答;提交后回到本题继续":"e = report a problem with this card (not an answer); you return here after"))),console.log(chalk.gray(" "+(n?"更多: bookmark · status · lang zh/en":"more: bookmark · status · lang zh/en"))),console.log()}(l,t)}export function renderCheckFeedback(o,e,n,l=!1){const t=s().startsWith("zh");if(console.log(),n)console.log(chalk.green(" ✓ ")+chalk.white(t?"答对了。":"Correct."));else if(console.log(chalk.yellow(" ✗ ")+chalk.white(t?"记下了,继续。":"Noted — moving on.")),l){const e="y"===o.check?.answer?t?"是":"Yes":t?"否":"No";console.log(chalk.gray(" "+(t?"正确答案: ":"Answer: ")+e+". "+(t?"回看上面那段。":"Re-read the paragraph above.")))}const r=t?o._zh?.solution??o.solution:o.solution;if(r&&r.length>0){console.log(),console.log(chalk.cyan(" 📝 "+(t?"解答:":"Worked solution:")));for(const o of r){for(const e of p(o,60))console.log(chalk.white(" "+e));console.log()}}console.log()}function M(o){return[chalk.white(" "+(o?"编著:Charlie Zhu":"Created & edited by Charlie Zhu")),chalk.gray(" "+(o?"ICOA 2026 创始人 · 课程总架构师":"Founder & Chief Curriculum Architect · ICOA 2026"))]}export function renderPhaseComplete(o,e,n,l){const r=s().startsWith("zh"),[c,a]=n.cardRange,g=e.checkResults||{};let i=0,d=0;for(let o=c;o<=a;o++){const e=g[String(o)];e&&(i++,e.correct&&d++)}const y="-".repeat(48);console.log();for(const o of t(" "))console.log(o);console.log(),console.log(chalk.bold.yellow(" "+y)),console.log(chalk.bold.yellow(" "+(r?`阶段 ${n.number} 完成`:`Phase ${n.number} complete`))+chalk.gray(" · ")+chalk.white(n.name));const u=i>0&&d===i?chalk.bold.green:chalk.bold.white;console.log(chalk.gray(" "+(r?"理解检查得分: ":"comprehension score: "))+u(`${d}/${i}`)+chalk.gray(0===i?r?" (本阶段未作答 y/n)":" (no y/n answered)":"")),l&&console.log(chalk.gray(" "+(r?"下一阶段: ":"next: "))+chalk.bold.cyan(r?`阶段 ${l.number}`:`Phase ${l.number}`)+chalk.gray(" · ")+chalk.white(l.name)),console.log(chalk.bold.yellow(" "+y));for(const o of M(r))console.log(o)}export function renderCurriculumComplete(o,e){const n=s().startsWith("zh"),l=e.checkResults||{},r="-".repeat(48);let c=0,a=0;console.log();for(const o of t(" "))console.log(o);console.log(),console.log(chalk.bold.green(" "+r)),console.log(chalk.bold.green(" 🏆 "+(n?`${o.name} — 全部完成!`:`${o.name} — complete!`))),console.log(chalk.bold.green(" "+r));for(const e of o.modules){const[o,t]=e.cardRange;let r=0,s=0;for(let e=o;e<=t;e++){const o=l[String(e)];o&&(r++,o.correct&&s++)}c+=r,a+=s;const g=r>0&&s===r?chalk.green:chalk.white;console.log(chalk.gray(" "+(n?`阶段 ${e.number}`:`Phase ${e.number}`).padEnd(8))+g(`${s}/${r}`.padEnd(7))+chalk.gray(e.name))}console.log(chalk.bold.green(" "+r)),console.log(chalk.bold.green(" "+(n?"总分 / overall: ":"Overall: "))+chalk.bold.white(`${a}/${c}`)),console.log(chalk.bold.green(" "+r));for(const o of M(n))console.log(o);console.log()}export function renderMCQCard(o,l){const t=s(),r=e(o,t);y(r,l),m(),h(chalk.bold.yellow("🎯 "+r.title)),h(chalk.gray("─".repeat(Math.min(r.title.length+4,a)))),m();for(const o of x(r.question,60))h(" "+o);m();for(const o of["A","B","C","D"])h(chalk.cyan(` ${o}.`)+" "+chalk.white(r.options[o]));m(),u(),console.log(chalk.gray(" "+(t.startsWith("zh")?"输入 ":"Type "))+chalk.bold.green("A")+chalk.gray(" / ")+chalk.bold.green("B")+chalk.gray(" / ")+chalk.bold.green("C")+chalk.gray(" / ")+chalk.bold.green("D")+chalk.gray(" "+n("type_to_answer",t))),console.log()}export function renderMCQFeedback(o,l,t,r){const c=s(),a=e(o,c);console.log(),t?console.log(" "+chalk.bold.green(n("correct",c)+" ")+chalk.gray(`${n("one_point",c)} · ${l} = ${a.options[l]}`)):console.log(" "+chalk.bold.red(n("not_quite",c)+" ")+chalk.gray(`${n("you_chose",c)} ${l}; ${n("answer_is",c)} ${a.answer}.`)),console.log(),console.log(chalk.gray(" "+n("explanation",c)));for(const o of x(a.explanation,60))console.log(chalk.gray(" "+o));const g=Object.values(r.mcqResults),i=g.filter(o=>o.correct).length;console.log(),console.log(chalk.gray(" "+n("mcq_accuracy_so_far",c)+" ")+chalk.white(`${i}/${g.length}`)),console.log(),t||(console.log(chalk.gray(" "+n("press_ok_continue",c)+" ")+chalk.bold.green("ok")+chalk.gray(" "+n("to_continue",c))),console.log())}export function renderPracticalCard(o,l){const t=s(),r=e(o,t);y(r,l),m(),h(chalk.bold.yellow("🛠 "+r.title)),h(chalk.gray("─".repeat(Math.min(r.title.length+4,a)))),m();for(const o of x(r.task,60))h(" "+o);if(r.starterCode){m(),h(chalk.gray(" "+n("starter_code",t))),m();for(const o of r.starterCode.split("\n"))h(" "+chalk.cyan(o))}m(),u(),console.log(chalk.gray(" "+n("try_in_sandbox",t)+" ")+chalk.bold.cyan("!python3")+chalk.gray(" "+n("drops_into_python",t))),console.log(chalk.gray(" "+n("when_done",t))),console.log(chalk.gray(" ")+chalk.bold.green("done")+chalk.gray(" "+n("done_desc",t))),console.log(chalk.gray(" ")+chalk.bold.yellow("skip")+chalk.gray(" "+n("skip_desc",t))),console.log(chalk.gray(" card N jump to a card by number")),console.log()}export function renderPracticalSuccess(o){const l=s(),t=e(o,l);console.log(),console.log(" "+chalk.bold.green(n("practical_recorded",l))),console.log(),console.log(chalk.gray(" "+n("reference_answer",l)));for(const o of x(t.successHint,60))console.log(chalk.gray(" "+o));console.log(),console.log(chalk.gray(" "+n("press_ok_continue",l)+" ")+chalk.bold.green("ok")+chalk.gray(" "+n("to_continue",l))),console.log()}export function renderSimDemoCard(o,l){const t=s(),r=e(o,t);y(r,l),m(),h(chalk.bold.yellow("🎬 "+r.title)),m();for(const o of x(r.description,60))h(" "+o);m(),h(chalk.gray(" "+n("sim_requires",t))),m(),u(),console.log(chalk.gray(" ")+chalk.bold.cyan("sim")+chalk.gray(" "+n("sim_launch_desc",t))),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(" "+n("continue_to_next",t))),console.log(chalk.gray(" bookmark "+n("bookmark_desc",t))),console.log(chalk.gray(" back "+n("back_desc",t))),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+n("quit_desc",t))),console.log()}export function renderArenaTaskCard(o,n){const l=s(),t=l.startsWith("zh"),r=e(o,l);y(r,n),m(),h(chalk.bold.cyan("🏟 "+r.title)),h(chalk.gray(" "+r.origin+" · "+r.domain+" · "+r.metric)),m();for(const o of r.statement){for(const e of x(o,60))h(" "+e);m()}h(chalk.bold.green(t?" 核心要点 — baseline → 解法的关键变化":" CORE DELTA — baseline → solution"));for(const o of r.core_delta)for(const e of x("• "+o,58))h(" "+chalk.white(e));m(),h(chalk.gray((t?" 提交格式: ":" Submission: ")+r.submission_format)),r.hints&&h(chalk.gray(t?" 本题有 5 级提示 (a–e),进入 arena 后逐级解锁。":" 5 progressive hints (a–e) unlock inside the arena.")),m(),u(),console.log(chalk.gray(" ")+chalk.bold.cyan("arena "+r.task_id)+chalk.gray(t?" 动手做这道题(下载 / 提示 / 提交 / 榜单)":" open the arena (download / hints / submit / board)")),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(t?" 继续下一张":" continue to next")),console.log(chalk.gray(" back "+(t?"上一张":"previous"))),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+(t?"退出":"exit"))),console.log()}export function renderComingSoonCard(o,n){const l=s(),t=l.startsWith("zh"),r=e(o,l);y(r,n),m(),h(chalk.bold.yellow("🔜 "+r.title)),m();const c=r.note||(t?"这道竞技场题目正在编写中,敬请期待。":"This arena task is coming soon.");for(const o of x(c,60))h(" "+chalk.gray(o));m(),u(),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(t?" 继续":" continue")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+(t?"退出":"exit"))),console.log()}export function renderMilestone(o,l){const t=s(),r=e(o,t),c=o.number===l.totalCards;console.log(),console.log(chalk.bold.yellow(" ╭"+g("═"))),console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+chalk.white(" "+n("milestone_header",t))),console.log(chalk.bold.yellow(" ║"));const a=` ${r.badge} ${r.emoji}`;console.log(chalk.bold.yellow(" ║ ")+chalk.bold.green(a)),console.log(chalk.bold.yellow(" ║ ")+chalk.gray(" ─".repeat(Math.max(1,Math.floor(r.badge.length/2+2))))),console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+" "+chalk.gray(n("in_wild_corresponds",t)));for(const o of x(r.realWorldLevel,60))console.log(chalk.bold.yellow(" ║ ")+" "+chalk.white(o));console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+" "+chalk.gray(n("whats_next",t)));for(const o of x(r.unlockedNext,60))console.log(chalk.bold.yellow(" ║ ")+" "+chalk.white(o));console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ╰"+g("═"))),console.log(),c?(console.log(chalk.gray(" "+n("demo_complete",t))),console.log(),console.log(chalk.gray(" "+n("unlock_full",t)+" ")+chalk.white(n("curriculum_name",t))+chalk.gray(",")),console.log(chalk.gray(" "+n("contact_team_leader",t)+" ")+chalk.bold.yellow("EA")+chalk.gray(" "+n("learn_token",t))),console.log(chalk.gray(" "+n("or_email",t)+" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" "+n("for_partnership",t))),console.log(),console.log(chalk.gray(" "+n("type_quit",t)+" ")+chalk.bold.green("quit")+chalk.gray(" "+n("to_exit",t)+" ")+chalk.bold.green("status")+chalk.gray(" "+n("for_dashboard",t)))):(console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(" "+n("continue_to_next",t))),console.log(chalk.gray(" status "+n("status_full",t))),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+n("quit_desc",t)))),console.log()}export function renderStatus(o,e){const l=s(),t=e.cardsCompleted.length,r=o.totalCards,c=Object.values(e.mcqResults),a=c.filter(o=>o.correct).length;console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(n("status_title",l))+" "+chalk.cyan("─".repeat(25))),m(),h(" "+chalk.gray(n("total_progress",l)+" ")+i(t,r)+chalk.gray(` (${t}/${r})`)),h(" "+chalk.gray(n("streak",l)+" ")+d(e.streakDays)+chalk.gray(` (${n("longest",l)} ${e.longestStreak})`)),h(" "+chalk.gray(n("mcq_accuracy",l)+" ")+chalk.white(`${a}/${c.length}`)),h(" "+chalk.gray(n("practicals_done",l)+" ")+chalk.white(`${e.practicalsCompleted.length}`)),h(" "+chalk.gray(n("bookmarked",l)+" ")+chalk.white(`${e.bookmarks.length}`)),m();const g=n("module",l).replace(":","").trim();for(const n of o.modules){const[o,l]=n.cardRange,t=e.cardsCompleted.filter(e=>e>=o&&e<=l).length,r=l-o+1;h(" "+(t===r?chalk.green("✓"):t>0?chalk.yellow("▶"):chalk.gray("□"))+" "+chalk.gray(`${g} ${n.number}: `)+chalk.white(`${t}/${r}`)+chalk.gray(" "+n.name))}if(m(),e.achievements.length>0){h(" "+chalk.gray(n("achievements",l)));for(const o of e.achievements)h(" "+chalk.bold.yellow("★ ")+chalk.white(o))}else h(" "+chalk.gray(n("achievements_none",l)));m(),u()}
|
|
1
|
+
import chalk from"chalk";import o from"string-width";import{localized as e}from"./learn-curricula.js";import{t as n}from"./learn-i18n.js";import{getConfig as l}from"./config.js";import{icoaBannerLines as t}from"./banner.js";import{renderCharts as r,detectCaps as c}from"./render-card.js";function a(){return(l().language||"en").toLowerCase()}const s=64;function g(o="─"){return o.repeat(66)}function i(o,e,n=20){const l=e>0?o/e:0,t=Math.floor(l*n),r=n-t;return`${chalk.green("█".repeat(t))+chalk.gray("░".repeat(r))} ${(100*l).toFixed(1)}%`}function d(o){return o>=30?chalk.red("🔥🔥🔥 "+o+" days"):o>=7?chalk.yellow("🔥 "+o+" days"):o>=1?chalk.gray("· "+o+" day"+(o>1?"s":"")):chalk.gray("—")}export function renderWelcome(o,e,l){const t=a(),r=e.cardsCompleted.length,c=o.totalCards,s=c-r,y=o.modules.find(o=>e.currentCard>=o.cardRange[0]&&e.currentCard<=o.cardRange[1]),u=/demo/i.test(o.id);if(console.log(),console.log(chalk.cyan(" ╭"+g("═"))),console.log(chalk.cyan(" ║")),console.log(chalk.cyan(" ║ ")+chalk.bold.white(" "+(o.name?.trim()||n("academy_title",t)))),console.log(chalk.cyan(" ║")),l)console.log(chalk.cyan(" ║ ")+chalk.white(" "+n(u?"welcome_new_demo":"welcome_new",t)));else{const o=new Date(e.lastSeenAt),l=Math.floor((Date.now()-o.getTime())/36e5),r=l<1?n("just_now",t):l<24?`${l}${n("ago_hours",t)}`:`${Math.floor(l/24)}${n("ago_days",t)}`;console.log(chalk.cyan(" ║ ")+chalk.white(` ${n("welcome_back",t)} ${r}`))}console.log(chalk.cyan(" ║"));const h=y?`${y.number}. ${y.name}`:"—";console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("module",t).padEnd(11))+chalk.white(h)),console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("progress",t).padEnd(11))+i(r,c)+chalk.gray(` (${r}/${c})`)),console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("streak",t).padEnd(11))+d(e.streakDays)),s>0&&e.currentCard<=c&&console.log(chalk.cyan(" ║ ")+" "+chalk.gray(n("next_card",t).padEnd(11))+chalk.white(`#${e.currentCard} ${n("of",t)} ${c}`)),console.log(chalk.cyan(" ║")),console.log(chalk.cyan(" ╰"+g("═"))),console.log(),console.log(chalk.gray(" ─────────────────────────────────────────────"));const m=0===r?n("continue_start",t):`${n("continue_resume",t)} ${e.currentCard}`;console.log(chalk.bold.green(" continue")+chalk.gray(" "+m)),console.log(chalk.yellow(" status")+chalk.gray(" "+n("status_full",t))),e.bookmarks.length>0&&console.log(chalk.yellow(" bookmarks")+chalk.gray(` ${e.bookmarks.length} ${n("bookmarks_desc",t)}`)),console.log(chalk.gray(" quit")+chalk.gray(" "+n("quit_desc",t))),console.log(chalk.gray(" ─────────────────────────────────────────────")),console.log()}function y(o,e){const l=a(),t=o.module,r=e.modules.find(o=>o.number===t),c=r?r.name:n("unknown_module",l),g=n("module",l).replace(":","").trim(),i=`${n("card",l)} ${o.number} / ${e.totalCards} · ${g} ${t} · ${c}`;console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(i)+" "+chalk.cyan("─".repeat(Math.max(0,s-i.length-4))))}function u(){console.log(chalk.cyan(" ╰"+g())),console.log()}function h(o){console.log(chalk.cyan(" │ ")+chalk.white(o))}function m(){console.log(chalk.cyan(" │"))}const f=/[┌┐└┘├┤┬┴┼─│╔╗╚╝═║╠╣╦╩╬▓▒░█]/;function b(o){return/^(?: {4}|\t)/.test(o)||f.test(o)||/ {3,}/.test(o)}function p(e,n){const l=[];let t="",r=0,c=!1;for(const a of function(e){const n=[],l=e=>{let l="";const t=()=>{l&&(n.push({t:"atom",s:l}),l="")};for(const r of e)" "===r?(t(),n.push({t:"space"})):2===o(r)?(t(),n.push({t:"wide",s:r})):l+=r;t()},t=/`[^`]*`/g;let r,c=0;for(;null!==(r=t.exec(e));)l(e.slice(c,r.index)),n.push({t:"code",s:r[0]}),c=r.index+r[0].length;return l(e.slice(c)),n}(e)){if("space"===a.t){""!==t&&(c=!0);continue}const e=a.s,s=o("code"===a.t?e.replace(/`/g,""):e),g=c?1:0,i="atom"===a.t&&e.length<=2&&/^[.,;:!?)\]}…'"]+$/.test(e);""!==t&&!i&&r+g+s>n?(l.push(t),t=e,r=s,c=!1):(c&&(t+=" ",r+=1,c=!1),t+=e,r+=s)}return t&&l.push(t),l}const w=/\b(?:Common bug|Common mistake|Common error|Pitfall|Gotcha|Footgun)\b[::]?|\b(?:Warning|Caution)\b[::]|(?:常见错误|常见陷阱|常见误区|陷阱|注意|警告|误区)[::]/gi;function $(o,e){const n=e?chalk.bold.white:chalk.white;let l,t="",r=0;for(w.lastIndex=0;null!==(l=w.exec(o));)l.index>r&&(t+=n(o.slice(r,l.index))),t+=chalk.bold.yellow(l[0]),r=l.index+l[0].length;return r<o.length&&(t+=n(o.slice(r))),t}function _(o,e=!1){let n="",l=0;const t=/`([^`]*)`/g;let r;for(;null!==(r=t.exec(o));)r.index>l&&(n+=$(o.slice(l,r.index),e)),n+=chalk.cyan(r[1]),l=r.index+r[0].length;return l<o.length&&(n+=$(o.slice(l),e)),n}function k(o,e=!1){let n=!1;for(const l of o.split("\n"))if(/^\s*```/.test(l))n=!n;else if(n)console.log(chalk.cyan(" │ ")+chalk.cyan(` ${l}`));else if(""!==l)if(b(l))console.log(chalk.cyan(" │ ")+chalk.white(l));else for(const o of p(l,60))console.log(chalk.cyan(" │ ")+` ${_(o,e)}`);else m()}function C(o,e){const n=[];for(const l of o.split("\n")){if(""===l){n.push("");continue}if(b(l)){n.push(l);continue}let o="";for(const t of l.split(" "))(o+" "+t).trim().length>e?(n.push(o.trim()),o=t):o=(o+" "+t).trim();o&&n.push(o)}return n}let x=!1;export function setLearnAiEnabled(o){x=o}let v=new Set;export function setLearnPqsViewCards(o){v=o}export function renderHonorWall(o){const e=a().startsWith("zh"),{totals:n,chapters:l}=o,t=n.gold+n.silver+n.bronze,r=(o,e)=>e>0?chalk.bold.white(`${o}×${e}`):chalk.gray(`${o}×0`);if(console.log(chalk.gray(" ─────────────────────────────────────────")),console.log(chalk.bold.white(e?" 🏅 奖牌墙 ":" 🏅 Medal wall ")+r("🥇",n.gold)+chalk.gray(" · ")+r("🥈",n.silver)+chalk.gray(" · ")+r("🥉",n.bronze)+chalk.gray(e?" (永久 — 挂上墙就不会摘下)":" (permanent — once earned, never removed)")),0===t){const n=null!=o.floor?`${o.floor}+`:e?"高分":"a high score";return console.log(chalk.gray(e?` 还没有奖牌 — 单卡提问评分 ${n} 并进入该卡前三,即可永久挂墙 🥇🥈🥉`:` No medals yet — score ${n} on a card and hold its top-3 to hang one 🥇🥈🥉`)),void console.log(chalk.gray(" ─────────────────────────────────────────"))}const c=l.map(o=>{const e=`Ch${o.chapter}`,n=(o.gold>0?`🥇${o.gold}`:"")+(o.silver>0?`🥈${o.silver}`:"")+(o.bronze>0?`🥉${o.bronze}`:"");return n?chalk.white(`${e} ${n}`):chalk.gray(`${e} —`)}).join(chalk.gray(" "));console.log(" "+c);const s=l.flatMap(o=>o.cards.map(e=>({...e,chapter:o.chapter})));s.sort((o,e)=>o.rank-e.rank||o.chapter-e.chapter||o.card-e.card);for(const o of s.slice(0,24)){const n=(o.since||"").slice(0,10);console.log(chalk.white(` ${o.icon} `)+chalk.gray(`Ch${o.chapter} · `)+chalk.white(e?`第 ${o.card} 张`:`card ${o.card}`)+chalk.gray(` · ${o.score}`)+(n?chalk.gray(e?` · 始于 ${n}`:` · since ${n}`):""))}s.length>24&&console.log(chalk.gray(e?` …还有 ${s.length-24} 枚`:` …and ${s.length-24} more`)),console.log(chalk.gray(" ─────────────────────────────────────────"))}export function renderKnowledgeCard(l,t){const g=a(),i=e(l,g);y(i,t),m();const d=p(i.title,60);for(const o of d)h(chalk.bold.yellow(o));h(chalk.gray("─".repeat(Math.min(Math.max(...d.map(e=>o(e))),s))));const f=!!(l.chart_ids&&l.chart_ids.length>0);if(f&&r(l.chart_ids.slice(0,1),t.charts,c()),i.key_point&&""!==i.key_point.trim()?(f||m(),function(o,e,n){const l=a().startsWith("zh"),t=c().cols,r="-".repeat(Math.min(s,Math.max(24,t-6))),g=l?"要点":"KEY POINT",i=l?`第 ${e} / ${n} 张`:`Card ${e} / ${n}`;console.log(chalk.cyan(" │ ")+chalk.green(r)),console.log(chalk.cyan(" │ ")+chalk.green(`${g} · ${i}`));for(const e of p(o,60))console.log(chalk.cyan(" │ ")+chalk.bold.green(" "+e));console.log(chalk.cyan(" │ ")+chalk.green(r)),m()}(i.key_point,i.number,t.totalCards)):f||m(),i.body.filter(o=>null!=o&&""!==o.trim()).forEach((o,e)=>{const n=0===e?o.match(/^([\s\S]*?(?:[.!?](?=\s|$)|[。!?]))(\s[\s\S]*)?$/):null;if(n&&n[1].trim().length<=180){k(n[1],!0);const o=n[2]?.trimStart();o&&k(o,!1)}else k(o,!1);m()}),i.icoaConnection){h(chalk.magenta(" "+n("icoa_connection",g))),h(chalk.gray(" "+"─".repeat(20)));for(const o of p(i.icoaConnection,60))h(" "+chalk.magenta(o));m()}if(l.check){const o=g.startsWith("zh"),e=l._zh?.checkStatement??l._zh?.check?.statement,n=o?e??l.check.statement:l.check.statement;h(chalk.cyan(" 🤔 "+(o?"请回答 (输 y 或 n):":"Quick comprehension check (type y or n):"))),h(chalk.gray(" "+"─".repeat(20)));for(const o of p(n,60))h(" "+chalk.white(o));m()}u(),function(o,e){const n=a().startsWith("zh"),l=c().cols,t="-".repeat(Math.min(s,Math.max(24,l-6))),r=chalk.gray(" "),g=[];o.check?(g.push(chalk.bold.green("[y]")+chalk.gray(n?" 是":" yes")),g.push(chalk.bold.green("[n]")+chalk.gray(n?" 否":" no"))):g.push(chalk.bold.green("[ok]")+chalk.gray(n?" 继续":" next")),x&&(g.push(chalk.bold.magenta("[/ai]")+chalk.gray(n?" AI导师":" AI tutor")),g.push(chalk.bold.magenta("[/submit]")+chalk.gray(n?" 提问评分":" prompt score")),v.has(o.number)&&g.push(chalk.bold.magenta("[/view]")+chalk.gray(n?" 榜单":" top-3"))),g.push(chalk.bold.yellow("[e]")+chalk.gray(n?" 报告问题":" report")),g.push(chalk.bold.cyan("[b]")+chalk.gray(n?" 上一张":" back")),g.push(chalk.bold.cyan("[card N]")+chalk.gray(n?" 跳转":" jump")),g.push(chalk.gray("[quit]")+chalk.gray(n?" 退出":" quit")),console.log(chalk.gray(" "+t)),console.log(chalk.gray(" "+(n?`第 ${o.number} / ${e.totalCards} 张`:`Card ${o.number} / ${e.totalCards}`))),console.log(" "+g.join(r)),console.log(chalk.gray(" "+t)),console.log(chalk.gray(" "+(n?"e = 报告本卡错误,不算作答;提交后回到本题继续":"e = report a problem with this card (not an answer); you return here after"))),console.log(chalk.gray(" "+(n?"更多: bookmark · status · /honors 奖牌墙 · lang zh/en":"more: bookmark · status · /honors · lang zh/en"))),console.log()}(l,t)}export function renderCheckFeedback(o,e,n,l=!1){const t=a().startsWith("zh");if(console.log(),n)console.log(chalk.green(" ✓ ")+chalk.white(t?"答对了。":"Correct."));else if(console.log(chalk.yellow(" ✗ ")+chalk.white(t?"记下了,继续。":"Noted — moving on.")),l){const e="y"===o.check?.answer?t?"是":"Yes":t?"否":"No";console.log(chalk.gray(" "+(t?"正确答案: ":"Answer: ")+e+". "+(t?"回看上面那段。":"Re-read the paragraph above.")))}const r=t?o._zh?.solution??o.solution:o.solution;if(r&&r.length>0){console.log(),console.log(chalk.cyan(" 📝 "+(t?"解答:":"Worked solution:")));for(const o of r){for(const e of p(o,60))console.log(chalk.white(" "+e));console.log()}}console.log()}function q(o){return[chalk.white(" "+(o?"编著:Charlie Zhu":"Created & edited by Charlie Zhu")),chalk.gray(" "+(o?"ICOA 2026 创始人 · 课程总架构师":"Founder & Chief Curriculum Architect · ICOA 2026"))]}export function renderPhaseComplete(o,e,n,l){const r=a().startsWith("zh"),[c,s]=n.cardRange,g=e.checkResults||{};let i=0,d=0;for(let o=c;o<=s;o++){const e=g[String(o)];e&&(i++,e.correct&&d++)}const y="-".repeat(48);console.log();for(const o of t(" "))console.log(o);console.log(),console.log(chalk.bold.yellow(" "+y)),console.log(chalk.bold.yellow(" "+(r?`阶段 ${n.number} 完成`:`Phase ${n.number} complete`))+chalk.gray(" · ")+chalk.white(n.name));const u=i>0&&d===i?chalk.bold.green:chalk.bold.white;console.log(chalk.gray(" "+(r?"理解检查得分: ":"comprehension score: "))+u(`${d}/${i}`)+chalk.gray(0===i?r?" (本阶段未作答 y/n)":" (no y/n answered)":"")),l&&console.log(chalk.gray(" "+(r?"下一阶段: ":"next: "))+chalk.bold.cyan(r?`阶段 ${l.number}`:`Phase ${l.number}`)+chalk.gray(" · ")+chalk.white(l.name)),console.log(chalk.bold.yellow(" "+y));for(const o of q(r))console.log(o)}export function renderCurriculumComplete(o,e){const n=a().startsWith("zh"),l=e.checkResults||{},r="-".repeat(48);let c=0,s=0;console.log();for(const o of t(" "))console.log(o);console.log(),console.log(chalk.bold.green(" "+r)),console.log(chalk.bold.green(" 🏆 "+(n?`${o.name} — 全部完成!`:`${o.name} — complete!`))),console.log(chalk.bold.green(" "+r));for(const e of o.modules){const[o,t]=e.cardRange;let r=0,a=0;for(let e=o;e<=t;e++){const o=l[String(e)];o&&(r++,o.correct&&a++)}c+=r,s+=a;const g=r>0&&a===r?chalk.green:chalk.white;console.log(chalk.gray(" "+(n?`阶段 ${e.number}`:`Phase ${e.number}`).padEnd(8))+g(`${a}/${r}`.padEnd(7))+chalk.gray(e.name))}console.log(chalk.bold.green(" "+r)),console.log(chalk.bold.green(" "+(n?"总分 / overall: ":"Overall: "))+chalk.bold.white(`${s}/${c}`)),console.log(chalk.bold.green(" "+r));for(const o of q(n))console.log(o);console.log()}export function renderMCQCard(o,l){const t=a(),r=e(o,t);y(r,l),m(),h(chalk.bold.yellow("🎯 "+r.title)),h(chalk.gray("─".repeat(Math.min(r.title.length+4,s)))),m();for(const o of C(r.question,60))h(" "+o);m();for(const o of["A","B","C","D"])h(chalk.cyan(` ${o}.`)+" "+chalk.white(r.options[o]));m(),u(),console.log(chalk.gray(" "+(t.startsWith("zh")?"输入 ":"Type "))+chalk.bold.green("A")+chalk.gray(" / ")+chalk.bold.green("B")+chalk.gray(" / ")+chalk.bold.green("C")+chalk.gray(" / ")+chalk.bold.green("D")+chalk.gray(" "+n("type_to_answer",t))),console.log()}export function renderMCQFeedback(o,l,t,r){const c=a(),s=e(o,c);console.log(),t?console.log(" "+chalk.bold.green(n("correct",c)+" ")+chalk.gray(`${n("one_point",c)} · ${l} = ${s.options[l]}`)):console.log(" "+chalk.bold.red(n("not_quite",c)+" ")+chalk.gray(`${n("you_chose",c)} ${l}; ${n("answer_is",c)} ${s.answer}.`)),console.log(),console.log(chalk.gray(" "+n("explanation",c)));for(const o of C(s.explanation,60))console.log(chalk.gray(" "+o));const g=Object.values(r.mcqResults),i=g.filter(o=>o.correct).length;console.log(),console.log(chalk.gray(" "+n("mcq_accuracy_so_far",c)+" ")+chalk.white(`${i}/${g.length}`)),console.log(),t||(console.log(chalk.gray(" "+n("press_ok_continue",c)+" ")+chalk.bold.green("ok")+chalk.gray(" "+n("to_continue",c))),console.log())}export function renderPracticalCard(o,l){const t=a(),r=e(o,t);y(r,l),m(),h(chalk.bold.yellow("🛠 "+r.title)),h(chalk.gray("─".repeat(Math.min(r.title.length+4,s)))),m();for(const o of C(r.task,60))h(" "+o);if(r.starterCode){m(),h(chalk.gray(" "+n("starter_code",t))),m();for(const o of r.starterCode.split("\n"))h(" "+chalk.cyan(o))}m(),u(),console.log(chalk.gray(" "+n("try_in_sandbox",t)+" ")+chalk.bold.cyan("!python3")+chalk.gray(" "+n("drops_into_python",t))),console.log(chalk.gray(" "+n("when_done",t))),console.log(chalk.gray(" ")+chalk.bold.green("done")+chalk.gray(" "+n("done_desc",t))),console.log(chalk.gray(" ")+chalk.bold.yellow("skip")+chalk.gray(" "+n("skip_desc",t))),console.log(chalk.gray(" card N jump to a card by number")),console.log()}export function renderPracticalSuccess(o){const l=a(),t=e(o,l);console.log(),console.log(" "+chalk.bold.green(n("practical_recorded",l))),console.log(),console.log(chalk.gray(" "+n("reference_answer",l)));for(const o of C(t.successHint,60))console.log(chalk.gray(" "+o));console.log(),console.log(chalk.gray(" "+n("press_ok_continue",l)+" ")+chalk.bold.green("ok")+chalk.gray(" "+n("to_continue",l))),console.log()}export function renderSimDemoCard(o,l){const t=a(),r=e(o,t);y(r,l),m(),h(chalk.bold.yellow("🎬 "+r.title)),m();for(const o of C(r.description,60))h(" "+o);m(),h(chalk.gray(" "+n("sim_requires",t))),m(),u(),console.log(chalk.gray(" ")+chalk.bold.cyan("sim")+chalk.gray(" "+n("sim_launch_desc",t))),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(" "+n("continue_to_next",t))),console.log(chalk.gray(" bookmark "+n("bookmark_desc",t))),console.log(chalk.gray(" back "+n("back_desc",t))),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+n("quit_desc",t))),console.log()}export function renderArenaTaskCard(o,n){const l=a(),t=l.startsWith("zh"),r=e(o,l);y(r,n),m(),h(chalk.bold.cyan("🏟 "+r.title)),h(chalk.gray(" "+r.origin+" · "+r.domain+" · "+r.metric)),m();for(const o of r.statement){for(const e of C(o,60))h(" "+e);m()}h(chalk.bold.green(t?" 核心要点 — baseline → 解法的关键变化":" CORE DELTA — baseline → solution"));for(const o of r.core_delta)for(const e of C("• "+o,58))h(" "+chalk.white(e));m(),h(chalk.gray((t?" 提交格式: ":" Submission: ")+r.submission_format)),r.hints&&h(chalk.gray(t?" 本题有 5 级提示 (a–e),进入 arena 后逐级解锁。":" 5 progressive hints (a–e) unlock inside the arena.")),m(),u(),console.log(chalk.gray(" ")+chalk.bold.cyan("arena "+r.task_id)+chalk.gray(t?" 动手做这道题(下载 / 提示 / 提交 / 榜单)":" open the arena (download / hints / submit / board)")),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(t?" 继续下一张":" continue to next")),console.log(chalk.gray(" back "+(t?"上一张":"previous"))),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+(t?"退出":"exit"))),console.log()}export function renderComingSoonCard(o,n){const l=a(),t=l.startsWith("zh"),r=e(o,l);y(r,n),m(),h(chalk.bold.yellow("🔜 "+r.title)),m();const c=r.note||(t?"这道竞技场题目正在编写中,敬请期待。":"This arena task is coming soon.");for(const o of C(c,60))h(" "+chalk.gray(o));m(),u(),console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(t?" 继续":" continue")),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+(t?"退出":"exit"))),console.log()}export function renderMilestone(o,l){const t=a(),r=e(o,t),c=o.number===l.totalCards;console.log(),console.log(chalk.bold.yellow(" ╭"+g("═"))),console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+chalk.white(" "+n("milestone_header",t))),console.log(chalk.bold.yellow(" ║"));const s=` ${r.badge} ${r.emoji}`;console.log(chalk.bold.yellow(" ║ ")+chalk.bold.green(s)),console.log(chalk.bold.yellow(" ║ ")+chalk.gray(" ─".repeat(Math.max(1,Math.floor(r.badge.length/2+2))))),console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+" "+chalk.gray(n("in_wild_corresponds",t)));for(const o of C(r.realWorldLevel,60))console.log(chalk.bold.yellow(" ║ ")+" "+chalk.white(o));console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ║ ")+" "+chalk.gray(n("whats_next",t)));for(const o of C(r.unlockedNext,60))console.log(chalk.bold.yellow(" ║ ")+" "+chalk.white(o));console.log(chalk.bold.yellow(" ║")),console.log(chalk.bold.yellow(" ╰"+g("═"))),console.log(),c?(console.log(chalk.gray(" "+n("demo_complete",t))),console.log(),console.log(chalk.gray(" "+n("unlock_full",t)+" ")+chalk.white(n("curriculum_name",t))+chalk.gray(",")),console.log(chalk.gray(" "+n("contact_team_leader",t)+" ")+chalk.bold.yellow("EA")+chalk.gray(" "+n("learn_token",t))),console.log(chalk.gray(" "+n("or_email",t)+" ")+chalk.cyan("australia@icoa2026.au")+chalk.gray(" "+n("for_partnership",t))),console.log(),console.log(chalk.gray(" "+n("type_quit",t)+" ")+chalk.bold.green("quit")+chalk.gray(" "+n("to_exit",t)+" ")+chalk.bold.green("status")+chalk.gray(" "+n("for_dashboard",t)))):(console.log(chalk.gray(" ")+chalk.bold.green("ok")+chalk.gray(" / ")+chalk.bold.green("next")+chalk.gray(" "+n("continue_to_next",t))),console.log(chalk.gray(" status "+n("status_full",t))),console.log(chalk.gray(" card N jump to a card by number")),console.log(chalk.gray(" quit "+n("quit_desc",t)))),console.log()}export function renderStatus(o,e){const l=a(),t=e.cardsCompleted.length,r=o.totalCards,c=Object.values(e.mcqResults),s=c.filter(o=>o.correct).length;console.log(),console.log(chalk.cyan(" ╭─ ")+chalk.bold.white(n("status_title",l))+" "+chalk.cyan("─".repeat(25))),m(),h(" "+chalk.gray(n("total_progress",l)+" ")+i(t,r)+chalk.gray(` (${t}/${r})`)),h(" "+chalk.gray(n("streak",l)+" ")+d(e.streakDays)+chalk.gray(` (${n("longest",l)} ${e.longestStreak})`)),h(" "+chalk.gray(n("mcq_accuracy",l)+" ")+chalk.white(`${s}/${c.length}`)),h(" "+chalk.gray(n("practicals_done",l)+" ")+chalk.white(`${e.practicalsCompleted.length}`)),h(" "+chalk.gray(n("bookmarked",l)+" ")+chalk.white(`${e.bookmarks.length}`)),m();const g=n("module",l).replace(":","").trim();for(const n of o.modules){const[o,l]=n.cardRange,t=e.cardsCompleted.filter(e=>e>=o&&e<=l).length,r=l-o+1;h(" "+(t===r?chalk.green("✓"):t>0?chalk.yellow("▶"):chalk.gray("□"))+" "+chalk.gray(`${g} ${n.number}: `)+chalk.white(`${t}/${r}`)+chalk.gray(" "+n.name))}if(m(),e.achievements.length>0){h(" "+chalk.gray(n("achievements",l)));for(const o of e.achievements)h(" "+chalk.bold.yellow("★ ")+chalk.white(o))}else h(" "+chalk.gray(n("achievements_none",l)));m(),u()}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "icoa-cli",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.372",
|
|
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": {
|