icoa-cli 2.19.372 → 2.19.374
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 +3 -1
- package/dist/commands/ipynb.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/lib/access.js +1 -1
- package/dist/lib/config.d.ts +1 -0
- package/dist/lib/config.js +1 -1
- package/dist/lib/demo2-progress.js +1 -1
- package/dist/lib/exam-state.js +1 -1
- package/dist/lib/input-dynamics.d.ts +9 -0
- package/dist/lib/input-dynamics.js +1 -0
- package/dist/lib/integrity-snapshot.d.ts +16 -0
- package/dist/lib/integrity-snapshot.js +1 -1
- package/dist/lib/learn-state.js +1 -1
- package/dist/lib/log-sync.js +1 -1
- package/dist/lib/logger.d.ts +8 -0
- package/dist/lib/logger.js +1 -1
- package/dist/lib/md-term.d.ts +17 -0
- package/dist/lib/md-term.js +1 -0
- package/dist/lib/secure-store.d.ts +18 -0
- package/dist/lib/secure-store.js +1 -0
- package/dist/lib/sim-cooldown.js +1 -1
- package/dist/repl.js +1 -1
- package/dist/types/index.d.ts +12 -0
- package/package.json +1 -1
package/dist/commands/ipynb.d.ts
CHANGED
|
@@ -8,7 +8,9 @@
|
|
|
8
8
|
* `cells / show / edit / add / del / run / save` step through them, `edit N`
|
|
9
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
|
-
* arena starter ships with them).
|
|
11
|
+
* arena starter ships with them). Markdown cells are first-class: `add md`
|
|
12
|
+
* writes one, `md N`/`py N` convert, and `run`/`show` render them in-terminal
|
|
13
|
+
* via md-term (Jupyter semantics — running a markdown cell = rendering it).
|
|
12
14
|
*
|
|
13
15
|
* Runs against the aienv venv kernel via NotebookKernel (Node ↔ Python bridge).
|
|
14
16
|
* Lives in the main REPL using the BUG-008 listener-swap (no second readline).
|
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 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"]}`))}
|
|
1
|
+
import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as r}from"node:os";import{Interface as t,createInterface as c}from"node:readline";import{isAbsolute as a,join as s,resolve as i}from"node:path";import chalk from"chalk";import{aienvPaths as y}from"../lib/aienv.js";import{editTextInEditor as d}from"../lib/editor-spawn.js";import{shouldExecuteCell as g}from"../lib/ipynb-input.js";import{looksLikeMarkdown as u,renderMarkdown as p}from"../lib/md-term.js";import{NotebookKernel as m}from"../lib/kernel.js";import{getMainRl as h}from"../lib/main-rl.js";import{cellPreview as f,parseIpynb as w,parsePercentPy as v,parseRunRange as k,serializeIpynb as b,statusChar as $}from"../lib/notebook-doc.js";import{openFile as x}from"../lib/open-file.js";const N=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 N=y(r()),P=s(r(),".icoa","ipynb-out");if(E(),!e(N.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 j=o?function(o){const l=a(o)?o:i(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")?w(e):v(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,S=j?j.doc:{cells:[],path:null,dirty:!1},L=new m({venvPython:N.python,venvRoot:N.root});process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await L.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.")),j&&console.log(j.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("add md")+chalk.gray(" notes · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" · ")+chalk.cyan("quit")),console.log();const O=h(),q=null!==O,R=q?O.listeners("line").slice():[];q&&O.removeAllListeners("line");const A=q?O:c({input:process.stdin,output:process.stdout,terminal:!0}),T=q?A.prompt:null;q&&(A.prompt=t.prototype.prompt);const M=[];let B=!1,D=!1;const K=()=>{A.setPrompt(chalk.bold.cyan(M.length?"icoa ipynb ...> ":"icoa ipynb> ")),A.prompt()};let W=()=>{};const F=new Promise(e=>{W=e}),z=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>S.cells.length?(console.log(0===S.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${S.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:S.cells[o-1],idx:o}},G=(e,o)=>{e.result&&!e.result.ok&&e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)&&u(e.source)&&console.log(chalk.gray(" ✎ looks like text/markdown, not Python — ")+chalk.cyan(`md ${o}`)+chalk.gray(" converts this cell to markdown (new note: ")+chalk.cyan("add md")+chalk.gray(")."))},H=async e=>{if(B)return void(e.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));const o=e.trim();if(0===M.length){const e=o.split(/\s+/),n=(e[0]??"").toLowerCase(),r=o.slice(e[0]?.length??0).trim();if("quit"!==n&&"exit"!==n&&"q"!==n&&(D=!1),"quit"===n||"exit"===n||"back"===n||"q"===n)return S.dirty&&!D?(D=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void K()):void await(async()=>{if(A.removeAllListeners("line"),console.log(),console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await L.shutdown().catch(()=>{}),q){T&&(A.prompt=T);for(const e of R)A.on("line",e);A.prompt(),W()}else W(),A.close()})();if("clear"===n||"cls"===n)return console.clear(),E(),void K();if("restart"===n)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await L.shutdown().catch(()=>{});try{await L.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 K();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 Python cell in your editor")),console.log(chalk.cyan(" add md")+chalk.gray(" write a markdown/text cell (notes, headings)")),console.log(chalk.cyan(" md N / py N")+chalk.gray(" convert cell N to markdown / Python")),console.log(chalk.cyan(" del N")+chalk.gray(" delete cell N")),console.log(chalk.cyan(" run N")+chalk.gray(" run cell N — markdown cells render (also: run 2-5, run all)")),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 K();if("open"===n)return C&&x(C)?console.log(chalk.gray(" reopening ")+chalk.cyan(C)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void K();if("cells"===n||"ls"===n)return(()=>{if(0===S.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);S.cells.forEach((o,n)=>{const l=$(o),r="✓"===l?chalk.green(l.padEnd(2)):"✗"===l?chalk.red(l.padEnd(2)):"md"===l?chalk.magenta(l.padEnd(2)):chalk.gray(l.padEnd(2));console.log(`${chalk.cyan(String(n+1).padStart(4))} ${r} ${chalk.white(f(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 K();if("show"===n)return(e=>{const o=z(e);if(o){if(console.log(),console.log(chalk.gray(` ── cell ${o.idx} ${"markdown"===o.cell.kind?"(markdown) ":""}──`)),"markdown"===o.cell.kind){for(const e of p(o.cell.source))console.log(e);console.log(chalk.gray(" (rendered — ")+chalk.cyan(`edit ${o.idx}`)+chalk.gray(" for the raw source)"))}else for(const e of o.cell.source.split("\n"))console.log(chalk.white(` ${e}`));o.cell.result&&(console.log(chalk.gray(" ── output ──")),I(o.cell.result,P)),console.log()}})(r),void K();if("edit"===n)return(e=>{const o=z(e);if(!o)return;A.pause();const n=d(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(A.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,S.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."))})(r),void K();if("add"===n)return(e=>{const o=e.trim().toLowerCase(),n="md"===o||"markdown"===o||"text"===o||"txt"===o;if(o&&!n&&"py"!==o&&"code"!==o&&"python"!==o)return void console.log(chalk.yellow(" usage: ")+chalk.cyan("add")+chalk.yellow(" (Python cell) · ")+chalk.cyan("add md")+chalk.yellow(" (markdown/text cell)"));A.pause();const l=d(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");A.resume();const r=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");r?(S.cells.push({kind:n?"markdown":"code",source:r,result:null}),S.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${S.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${S.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(r),void K();if("del"===n||"delete"===n)return(e=>{const o=z(e);o&&(S.cells.splice(o.idx-1,1),S.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${S.cells.length} left.`)))})(r),void K();if(("md"===n||"py"===n)&&/^\d+$/.test(r))return((e,o)=>{const n=z(e);if(!n)return;const l="markdown"===o?"markdown":"Python";n.cell.kind!==o?(n.cell.kind=o,n.cell.result=null,n.cell.rawOutputs=void 0,n.cell.rawExecCount=void 0,S.dirty=!0,console.log(chalk.green(` ✓ cell ${n.idx} → ${l}`)+chalk.gray(" — ")+chalk.cyan(`run ${n.idx}`)+chalk.gray("markdown"===o?" to render it.":" to execute."))):console.log(chalk.gray(` cell ${n.idx} is already ${l}.`))})(r,"md"===n?"markdown":"code"),void K();if("run"===n)return B=!0,await(async e=>{const o=k(e,S.cells.length);if(o)for(const e of o){const n=S.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(f(n,50))+chalk.gray(" ──"));try{n.result=await L.execute(n.source)}catch(e){return void console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}if(S.dirty=!0,I(n.result,P),G(n,e),!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{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of p(n.source))console.log(e);console.log()}}else console.log(0===S.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"))})(r),B=!1,void K();if("save"===n)return(e=>{if(0===S.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?a(e.trim())?e.trim():i(process.cwd(),e.trim()):S.path?S.path.endsWith(".ipynb")?S.path:`${S.path.replace(/\.[^./]+$/,"")}.ipynb`:i(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,b(S.cells)),S.path=o,S.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${S.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(r),void K();if(""===o)return void K()}if(M.push(e),!g(M))return void K();const n=M.join("\n").replace(/\s+$/,"");if(M.length=0,""!==n.trim()){B=!0;try{const e=await L.execute(n);S.cells.push({kind:"code",source:n,result:e}),S.dirty=!0,I(e,P),G(S.cells[S.cells.length-1],S.cells.length)}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e)))}B=!1,K()}else K()};A.on("line",e=>{H(e)}),q||A.on("close",async()=>{await L.shutdown().catch(()=>{}),process.exit(0)}),K(),await F}(o)})}function E(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}let P=0,C=null;function I(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(N,"")}`))}else"display"===n.kind&&j(n.data,o)}function j(e,n){if(e["image/png"])try{o(n,{recursive:!0}),P+=1;const r=s(n,`figure-${P}.png`);return l(r,Buffer.from(e["image/png"],"base64")),C=r,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(r)),void(x(r)?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 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()})}
|
|
1
|
+
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{spawn as n}from"node:child_process";import{getMainRl as r}from"../lib/main-rl.js";import{existsSync as t}from"node:fs";import{dirname as l,join as a}from"node:path";import{fileURLToPath as s}from"node:url";import{loadCurriculumById as c,validateEAToken as i,syncProgress as u,syncCardFeedback as d}from"../lib/learn-curricula.js";import{normalizeTokenBody as g}from"../lib/token-format.js";import{streamLearnTutor as m,submitPqs as y,viewPqsTop as h,viewHonors as f}from"../lib/learn-ai.js";import{getConfig as p,saveConfig as b}from"../lib/config.js";import{loadLearnState as w,saveLearnState as k,newLearnState as v,updateStreak as A,markCardComplete as C,recordMCQ as I,recordCheck as $,markPracticalComplete as E,addAchievement as _}from"../lib/learn-state.js";import{renderWelcome as T,renderKnowledgeCard as M,renderMCQCard as P,renderMCQFeedback as L,renderPracticalCard as O,renderPracticalSuccess as x,renderSimDemoCard as D,renderMilestone as S,renderArenaTaskCard as q,renderComingSoonCard as j,renderStatus as N,renderPhaseComplete as R,renderCurriculumComplete as W,setLearnAiEnabled as F,setLearnPqsViewCards as B,renderHonorWall as z}from"../lib/learn-render.js";import{printError as U}from"../lib/ui.js";export function registerLearnCommand(J){J.command("learn [token]").description("Enter learn mode (free demo, or team-issued EA/EI/AC/CA/IO/IA token for full curriculum)").action(async J=>{J&&J.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(),J="LEARNDEMO01");let Q=J.trim().toUpperCase(),V=null;const H=/^(LEARNDEMO01|AI4CTFDEMO01|CTF4AIDEMO01)$/i.test(Q),K=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(Q);let X=!1;if(H)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),V=await c(Q,Q);else if(K){console.log(),console.log(chalk.gray(" Validating token..."));let e=await i(Q);if(!e.ok){const o=g(Q);if(o!==Q){const n=await i(o);n.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${Q} → ${o}`)),e=n,Q=o)}}if(!e.ok)return U(`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"):"")),X=!0===e.aiEnabled,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),V=await c(e.curriculumId||"LEARNDEMO01",Q),!V)return U(`Could not open a learn curriculum for token '${Q}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${Q}`)+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 ${Q}`)+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(!V)return U(`Unknown learn token: ${Q}`),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 Z=w(),G=!1;try{Z&&Z.token===Q?A(Z):(Z=v(Q,V.id,V.totalCards),G=!0),k(Z),T(V,Z,G)}catch{return U("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 ${Q}`)+chalk.gray(".")),void console.log()}const Y=r(),ee=null!==Y,oe=ee?Y.listeners("line").slice():[];ee&&Y.removeAllListeners("line");const ne=ee?Y:o({input:process.stdin,output:process.stdout,terminal:!0}),re=ee?ne.prompt:null;ee&&(ne.prompt=e.prototype.prompt);const te=()=>{ee&&re&&(ne.prompt=re)},le=()=>{ne.setPrompt(chalk.bold.cyan(ue?"icoa learn ai> ":"icoa learn> ")),ne.prompt()};let ae=null,se=null,ce=null,ie=null,ue=!1,de=!1;const ge=new Map,me=()=>{let e=ge.get(Z.currentCard);return e||(e=[],ge.set(Z.currentCard,e)),e};let ye=!1;const he=new Set;let fe=!1,pe=0;const be=(p().language||"en").toLowerCase().startsWith("zh");F(X),B(he);const we=[];let ke=null;const ve=new Promise(e=>{ke=e}),Ae=()=>{const e=ke;ke=null,e?.()},Ce="1"===process.env.ICOA_LEARN_EMBEDDED,Ie=e=>V.cards.find(o=>o.number===e),$e=e=>{const o=V.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const n=V.modules.find(e=>e.number===o.number+1);return R(V,Z,o,n),!0},Ee=()=>{fe=!0,console.log(chalk.gray(be?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},_e=()=>{const e=Ie(Z.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":M(e,V),e.check?(ce=e.number,pe=Date.now()):(C(Z,e.number),k(Z));break;case"mcq":P(e,V),ae=e.number;break;case"practical":O(e,V),se=e.number;break;case"sim_demo":D(e,V),C(Z,e.number),k(Z);break;case"milestone":S(e,V),_(Z,e.badge),C(Z,e.number),k(Z);break;case"arena_task":q(e,V),C(Z,e.number),k(Z);break;case"coming_soon":j(e,V),C(Z,e.number),k(Z)}},Te=()=>{Q.endsWith("DEMO01")?console.log(chalk.yellow(be?" 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(be?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(be?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Me=async(e,o)=>{if(X){de=!0;try{console.log(),console.log(chalk.gray("deep"===o?be?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":be?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let n=!1,r=!1;const t=await m({token:Q,cardNumber:Z.currentCard,question:e,mode:o,history:me().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(be?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(me().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(` (${be?"AI 额度":"AI budget"}: ${Math.round(t.spent/1e3)}k / ${Math.round(t.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${t.message||(be?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==ce&&console.log(chalk.gray(be?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{de=!1}}else Te()},Pe=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Le=async e=>{const o=e.trim().toLowerCase();if(!de){if(null!==ie){const o=e.trim(),n=ie;if(ie=null,""===o)console.log(chalk.gray(be?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=pe>0?Date.now()-pe:void 0;we.push(d(Q,{curriculum_id:V.id,card_number:n,feedback_text:o,time_on_card_ms:e}).catch(()=>{})),console.log(chalk.green(be?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded."))}return console.log(),void le()}if(ye){ye=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{de=!0;try{console.log(),console.log(chalk.gray(be?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await y({token:Q,cardNumber:Z.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(be?"评审暂不可用。":"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(be?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(be?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(be?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(be?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(be?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(be?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ 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=be?` 本卡排名 #${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(be?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(be?` 第 ${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 Pe(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(be?" 改进提问: ":" 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(` (${be?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?he.add(Z.currentCard):he.delete(Z.currentCard);const o=await f({token:Q,curriculumId:V.id,cardNumber:Z.currentCard});o.ok&&o.totals&&o.chapters&&(z({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log())}finally{de=!1}})():(console.log(chalk.gray(be?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==ce&&(console.log(chalk.gray(be?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void le()}if(fe)return fe=!1,_e(),void le();if(o){if(ue){if(["q","quit","exit","back","b","menu"].includes(o))return ue=!1,console.log(chalk.gray(be?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void le();const n=e.trim().startsWith("!"),r=n?e.trim().slice(1).trim():e.trim();return r&&await Me(r,n?"fast":"deep"),void le()}if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!X)return Te(),void le();const n=o.startsWith("/ai!"),r=e.trim().slice(n?4:3).trim();if(!r){ue=!0;const e=Ie(Z.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(be?"AI 导师":"AI tutor")+(o?chalk.gray(be?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(be?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void le()}return await Me(r,n?"fast":"deep"),void le()}if("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research ")){if(!X)return Te(),void le();const e=Ie(Z.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(be?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(be?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(be?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(be?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(be?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(be?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(be?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),ye=!0,void le()}if("/view"===o)return X?(await(async()=>{de=!0;try{console.log();const e=await h({token:Q,cardNumber:Z.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(be?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&he.delete(Z.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&he.add(Z.currentCard),console.log(chalk.bold.white(be?` 🏆 本卡 Top-3 提问 — 第 ${Z.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${Z.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=Pe(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(be?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{de=!1}})(),void le()):(Te(),void le());if("/honors"===o||"honors"===o)return H?(console.log(),console.log(chalk.gray(be?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void le()):(await(async()=>{de=!0;try{console.log();const e=await f({token:Q,curriculumId:V.id,cardNumber:Z.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(be?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(be?` 🏆 本卡实时 Top-3 — 第 ${Z.currentCard} 张`:` 🏆 Live top-3 — card ${Z.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(be?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),z({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log()}finally{de=!1}})(),void le());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return N(V,Z),void le();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(p().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void le();const n=V.cards.some(e=>null!=e._zh),r=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),t="en"===r||"zh"===r&&n,l=t?r:"en";return b({language:l}),t?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),ce=null,ae=null,se=null,ie=null,fe=!1,ye=!1,_e(),void le()}if("sim"===o){const e=Ie(Z.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=l(s(import.meta.url)),o=[a(e,"..","..","panda","mujoco-launcher.py"),a(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(t(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const r={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${r})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),n("python3",[o,r,"--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 le()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void le())}if("bookmark"===o){const e=Z.currentCard;return Z.bookmarks.includes(e)||Z.bookmarks.push(e),k(Z),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void le()}if("e"===o)return ie=Z.currentCard,console.log(chalk.gray(be?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void le();if("back"===o||"b"===o)return Z.currentCard>1&&(Z.currentCard-=1),ae=null,se=null,ce=null,k(Z),_e(),void le();if(o.startsWith("card ")){const e=o.slice(5).trim(),n=parseInt(e,10);return!Number.isInteger(n)||n<1||n>V.totalCards?(console.log(chalk.yellow(` Card number must be 1..${V.totalCards}. Try: `)+chalk.bold.green("card 1")),void le()):(Z.currentCard=n,ae=null,se=null,ce=null,k(Z),_e(),void le())}if(null!==ce&&["y","yes","n","no"].includes(o)){const e=Ie(ce);if(e&&"knowledge"===e.type&&e.check){const n=o.startsWith("y")?"y":"n",r=n===e.check.answer,t=Date.now()-pe;C(Z,e.number),$(Z,e.number,{answer:n,correct:r,submittedAt:(new Date).toISOString()}),k(Z);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,n,r,!1),we.push(u(Q,{card_number:e.number,event_type:"check_answered",check_answer:n,check_correct:r,time_on_card_ms:t}).catch(()=>{})),ce=null,e.solution&&e.solution.length>0)return void le();if(Z.currentCard<V.totalCards){const e=Z.currentCard;Z.currentCard+=1,k(Z),$e(e)?Ee():_e(),le()}else W(V,Z),le();return}}if(null!==ae&&["a","b","c","d"].includes(o)){const e=Ie(ae);if(e&&"mcq"===e.type){const n=o.toUpperCase(),r=n===e.answer;return I(Z,e.number,{answer:n,correct:r,submittedAt:(new Date).toISOString()}),C(Z,e.number),k(Z),L(e,n,r,Z),we.push(u(Q,{card_number:e.number,event_type:"mcq_answered",mcq_answer:n,mcq_correct:r}).catch(()=>{})),ae=null,void(r?Z.currentCard<V.totalCards?(Z.currentCard+=1,k(Z),_e()):(W(V,Z),le()):le())}}if(null!==se){if("done"===o){const e=Ie(se);if(e&&"practical"===e.type)return E(Z,e.number),C(Z,e.number),k(Z),x(e),se=null,void le()}if("skip"===o)return C(Z,se),k(Z),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),se=null,void le()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ae)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void le();if(null!==se)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void le();if(null!==ce)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void le();const e=Z.currentCard;return Z.currentCard+=1,k(Z),Z.currentCard>V.totalCards?W(V,Z):$e(e)?Ee():_e(),void le()}if(null!==ce)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void le();if(null!==ae)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void le();if(null!==se)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void le();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")),le()}else if(we.length>0&&await Promise.race([Promise.allSettled(we),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${Z.streakDays} day(s)`)),console.log(),ee){ne.removeAllListeners("line"),te();for(const e of oe)ne.on("line",e);ne.prompt(),Ae()}else ne.removeAllListeners("line"),ne.close();else if(we.length>0&&await Promise.race([Promise.allSettled(we),new Promise(e=>setTimeout(e,3e3))]),ne.removeAllListeners("line"),te(),ee||!Ce){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ee?ne:void 0),Ae()}else ne.close()}else le()}};ne.on("line",e=>{Le(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.")),le()})}),ee||ne.on("close",async()=>{we.length>0&&await Promise.race([Promise.allSettled(we),new Promise(e=>setTimeout(e,5e3))]),Ce?Ae():process.exit(0)});try{_e(),le()}catch{if(U("Could not render this card — the curriculum may be malformed."),ee){ne.removeAllListeners("line"),te();for(const e of oe)ne.on("line",e);ne.prompt()}else ne.close();Ae()}await ve}),J.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 c(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()})}
|
package/dist/lib/access.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as t
|
|
1
|
+
import{createHash as t}from"node:crypto";import{execSync as e}from"node:child_process";import{platform as n}from"node:os";import{getConfig as r,saveConfig as i,getIcoaDir as o,getInstallSalt as s}from"./config.js";import{readFileSync as c,existsSync as a}from"node:fs";import{join as u}from"node:path";import{deriveFileKey as d,readSignedFile as p,writeSignedFile as f,recordVerdict as m}from"./secure-store.js";const l=/^ICOA-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;export function isFirstRunOrUpgrade(t){return r().lastVersion!==t}export function markVersionSeen(t){i({lastVersion:t})}const g=new Set(["ref","help","exit","quit","q","clear","cls","activate","doctor","aienv","ipynb"]);export function isActivated(){return!!r().accessToken}export function getDeviceFingerprint(){const i=r();if(i.deviceFingerprint)return i.deviceFingerprint;const o=s(),u=function(){try{if("darwin"===n()){const t=e("ioreg -rd1 -c IOPlatformExpertDevice | grep IOPlatformUUID",{encoding:"utf-8"}).match(/"([A-F0-9-]+)"/);if(t)return t[1]}else if("linux"===n()){if(a("/etc/machine-id"))return c("/etc/machine-id","utf-8").trim()}else if("win32"===n())return e('powershell -Command "(Get-CimInstance Win32_ComputerSystemProduct).UUID"',{encoding:"utf-8"}).trim()}catch{}return""}();return t("sha256").update(`${u}|${o}`).digest("hex")}const x="token-bindings";export function activateToken(e){if(!function(t){return l.test(t.trim().toUpperCase())}(e))return"invalid";const n=getDeviceFingerprint(),r=u(o(),"token-bindings.json"),c=d(s(),x),{data:a,verdict:g}=p(r,c);m(x,g);const v=a||{},h=function(e){return t("sha256").update(e.trim().toUpperCase()).digest("hex")}(e),A=v[h];return A&&A!==n?"already_bound":(v[h]=n,f(r,v,c),i({accessToken:e.trim().toUpperCase(),deviceFingerprint:n}),"ok")}export function isDeviceMatch(){const t=r();return!t.deviceFingerprint||t.deviceFingerprint===getDeviceFingerprint()}export function isFreeCommand(t){return g.has(t.toLowerCase())}const v=()=>u(o(),"session-state.json"),h="session-state";function A(){return d(s(),h)}function w(){return{startedAt:(new Date).toISOString(),lastExitAt:null,lastResumeAt:null,exitCount:0,totalAwaySeconds:0}}function C(){const{data:t,verdict:e}=p(v(),A());return m(h,e),t?{...w(),...t}:w()}function D(t){const e={...C(),...t};f(v(),e,A())}export function recordExit(){const t=C();t.lastExitAt=(new Date).toISOString(),t.exitCount++,D(t)}export function recordResume(){const t=C();if(!t.lastExitAt)return null;const e=new Date(t.lastExitAt).getTime(),n=Date.now(),r=Math.round((n-e)/1e3);return t.lastResumeAt=(new Date).toISOString(),t.totalAwaySeconds+=r,D(t),{awaySeconds:r,exitCount:t.exitCount}}
|
package/dist/lib/config.d.ts
CHANGED
|
@@ -4,4 +4,5 @@ export declare function saveConfig(config: Partial<IcoaConfig>): void;
|
|
|
4
4
|
export declare function getBudget(): HintBudget;
|
|
5
5
|
export declare function saveBudget(budget: HintBudget): void;
|
|
6
6
|
export declare function getIcoaDir(): string;
|
|
7
|
+
export declare function getInstallSalt(): string;
|
|
7
8
|
export declare function isConnected(): boolean;
|
package/dist/lib/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as t,readFileSync as n,writeFileSync as o,existsSync as
|
|
1
|
+
import{mkdirSync as t,readFileSync as n,writeFileSync as o,existsSync as e,chmodSync as r,statSync as i}from"node:fs";import{join as l}from"node:path";import{homedir as s}from"node:os";import{randomUUID as a}from"node:crypto";import{DEFAULT_CONFIG as c,DEFAULT_BUDGET as f}from"../types/index.js";import{deriveFileKey as u,writeSignedFile as g,readSignedFile as d,verifyObject as p,recordVerdict as S}from"./secure-store.js";const m=l(s(),".icoa"),y=l(m,"config.json"),x=l(m,"budget.json"),C="config",h="budget";function v(){e(m)||t(m,{recursive:!0,mode:448})}export function getConfig(){if(v(),!e(y)){const t={...c,sessionId:a(),installSalt:a()};try{g(y,t,u(t.installSalt,C))}catch{}return t}let t;!function(t){try{63&i(t).mode&&r(t,384)}catch{}}(y);try{t=JSON.parse(n(y,"utf-8"))}catch{return S(C,"corrupt"),{...c,sessionId:a()}}let l="string"==typeof t.installSalt?t.installSalt:void 0;if(!l){l=a(),t={...t,installSalt:l};try{!function(t,n){o(t,n);try{r(t,384)}catch{}}(y,JSON.stringify(t,null,2))}catch{}}const s=u(l,C),f=p(t,s);S(C,f);const d={...c,...t};return delete d._sig,d}export function saveConfig(t){v();const n={...getConfig(),...t};n.installSalt||(n.installSalt=a()),g(y,n,u(n.installSalt,C))}export function getBudget(){v();const t=u(getInstallSalt(),h),{data:n,verdict:o}=d(x,t);return S(h,o),n?{...f,...n}:(g(x,{...f},t),{...f})}export function saveBudget(t){v(),g(x,t,u(getInstallSalt(),h))}export function getIcoaDir(){return v(),m}export function getInstallSalt(){const t=getConfig();if(t.installSalt)return t.installSalt;const n=a();return saveConfig({installSalt:n}),n}export function isConnected(){const t=getConfig();return!(!t.ctfdUrl||!t.token)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{unlinkSync as e}from"node:fs";import{join as t}from"node:path";import{getIcoaDir as r,getInstallSalt as o}from"./config.js";import{deriveFileKey as n,readSignedFile as s,writeSignedFile as a,recordVerdict as d}from"./secure-store.js";const m="demo2-progress";function l(){return t(r(),"demo2-progress.json")}function c(){return n(o(),m)}export function loadDemo2Progress(){const{data:e,verdict:t}=s(l(),c());if(d(m,t),"corrupt"===t)return clearDemo2Progress(),null;if(!e)return null;const r=e;if("number"!=typeof r.nextCardIndex||"number"!=typeof r.totalCards||"string"!=typeof r.lang||"number"!=typeof r.startedAt)return clearDemo2Progress(),null;const o=r.completedAt??r.startedAt;return"number"==typeof o&&Date.now()-o>6048e5?(clearDemo2Progress(),null):{nextCardIndex:r.nextCardIndex,totalCards:r.totalCards,lang:r.lang,startedAt:r.startedAt,completedAt:"number"==typeof r.completedAt?r.completedAt:void 0}}export function saveDemo2Progress(e){try{a(l(),e,c())}catch{}}export function clearDemo2Progress(){try{e(l())}catch{}}export function markCardDone(e,t,r,o){saveDemo2Progress({nextCardIndex:e+1,totalCards:t,lang:r,startedAt:o})}export function markDemo2Complete(e,t,r){saveDemo2Progress({nextCardIndex:e,totalCards:e,lang:t,startedAt:r,completedAt:Date.now()})}
|
package/dist/lib/exam-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{writeFileSync as t,existsSync as e,unlinkSync as n,mkdirSync as a}from"node:fs";import{execFileSync as o}from"node:child_process";import{join as r}from"node:path";import{homedir as i}from"node:os";import{getIcoaDir as s,getInstallSalt as c}from"./config.js";import{deriveFileKey as u,readSignedFile as f,writeSignedFile as m,recordVerdict as l}from"./secure-store.js";export function practicalChatCommand(t,e){return e?"ctf4ai"===t?"ctf4ai":"ai4ctf"===t?"ai4ctf":"vla"===t?"ctf4eai":null:null}export function materializeAttachedData(n,s){if(!s)return null;let c;try{const o=getRealExamState(),u=o?.session?.workspaceDir,f=u&&e(u)?u:r(i(),"icoa-workspace");a(f,{recursive:!0}),c=r(f,`q${n}.txt`),t(c,s,"utf-8")}catch{return null}try{return o("docker",["cp",c,`icoa-sandbox:/home/competitor/challenges/q${n}.txt`],{stdio:"ignore",timeout:3e3}),`challenges/q${n}.txt`}catch{return c}}function d(){return r(s(),"exam-state.json")}function p(){return r(s(),"demo-state.json")}function x(t){return"demo-free"===t?p():d()}export function getRealExamState(){const t=d(),{data:e,verdict:a}=f(t,u(c(),"exam-state"));if(l("exam-state",a),!e)return null;if("demo-free"===e?.session?.examId){try{n(t)}catch{}return null}return e}export function getDemoState(){const t=p(),{data:e,verdict:n}=f(t,u(c(),"demo-state"));return l("demo-state",n),e}export function getExamState(){return getRealExamState()||getDemoState()}export function saveExamState(t){const e=t.session.examId,n=x(e);m(n,t,u(c(),function(t){return"demo-free"===t?"demo-state":"exam-state"}(e)))}export function clearExamState(t){if(t){const a=x(t);e(a)&&n(a)}else{const t=getExamState();if(t){const a=x(t.session.examId);e(a)&&n(a)}}}function g(t){if(!t.session.durationMinutes)return null;const{deadlineServerMs:e,clockOffsetMs:n}=t.session;if("number"==typeof e&&"number"==typeof n)return new Date(e-n);const a=t.session.confirmedAt||t.session.startedAt,o=new Date(a).getTime();return new Date(o+60*t.session.durationMinutes*1e3)}export function getExamDeadline(){const t=getExamState();return t?g(t):null}export function getRealExamDeadline(){const t=getRealExamState();return t?g(t):null}let h=!1;export async function refetchQuestionDataIfStale(){const t=getRealExamState();if(!t)return null;if(h)return t;const e=t.session.token;if(!e)return t;if(!t.questions.some(t=>{if("ai4ctf"!==t.type&&"ctf4ai"!==t.type)return!1;const e=String(t.description||"");return(e.includes("attachedData")||/base64 blob/i.test(e))&&!t.attachedData}))return t;h=!0;try{const{getConfig:n}=await import("./config.js"),a=n(),o=a.ctfdUrl||"https://practice.icoa2026.au",r=a.language||"en",i=await fetch(`${o}/api/icoa/exam-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e,deviceHash:"",lang:r}),signal:AbortSignal.timeout(8e3)});if(!i.ok)return t;const s=await i.json(),c=s?.data?.questions||[];if(0===c.length)return t;const u=new Map;for(const t of c)u.set(t.number,t);let f=0;for(const e of t.questions){const t=u.get(e.number);t&&(t.attachedData&&!e.attachedData&&(e.attachedData=t.attachedData,f++),t.description&&(!e.description||t.description.length>e.description.length)&&(e.description=t.description))}return f>0&&saveExamState(t),t}catch{return t}}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { InputDynamics } from '../types/index.js';
|
|
2
|
+
export declare function classifyBurst(interKeyMs: number[]): {
|
|
3
|
+
maxBurst: number;
|
|
4
|
+
suspectPaste: boolean;
|
|
5
|
+
};
|
|
6
|
+
export declare function stripPasteMarkers(line: string): string;
|
|
7
|
+
export declare function installInputDynamics(enableBracketed?: boolean): void;
|
|
8
|
+
export declare function uninstallInputDynamics(): void;
|
|
9
|
+
export declare function consumeLineDynamics(): InputDynamics | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let s=!1,t=0,e=null,n=[];function a(){return{start:Date.now(),keys:0,backspaces:0,pastes:0,pasteChars:0}}export function classifyBurst(s){let t=1,e=1;for(let n=1;n<s.length;n++)s[n]<5?(t++,t>e&&(e=t)):t=1;return{maxBurst:e,suspectPaste:e>=8}}export function stripPasteMarkers(s){return s.replace(/\x1b?\[20[01]~/g,"")}function r(s,r){e||(e=a());const c=Date.now();t&&n.push(c-t),t=c,e.keys++,"backspace"===r?.name&&e.backspaces++}function c(s){const t=s.toString("latin1");let n=t.indexOf("[200~");for(;-1!==n;){e||(e=a()),e.pastes++;const s=t.indexOf("[201~",n);-1!==s&&(e.pasteChars+=s-(n+6)),n=t.indexOf("[200~",n+6)}}export function installInputDynamics(a=!0){if(!s&&(s=!0,e=null,n=[],t=0,process.stdin.on("keypress",r),process.stdin.on("data",c),a&&process.stdout.isTTY))try{process.stdout.write("[?2004h")}catch{}}export function uninstallInputDynamics(){if(s&&(s=!1,process.stdin.removeListener("keypress",r),process.stdin.removeListener("data",c),process.stdout.isTTY))try{process.stdout.write("[?2004l")}catch{}}export function consumeLineDynamics(){if(!e)return;const{maxBurst:s,suspectPaste:a}=classifyBurst(n),r={ms:Date.now()-e.start,keys:e.keys,backspaces:e.backspaces,pastes:e.pastes,pasteChars:e.pasteChars,maxBurst:s,suspectPaste:a||e.pastes>0};return e=null,n=[],t=0,r}
|
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure payload builder — no I/O, no network. Extracted from
|
|
3
|
+
* `postIntegritySnapshot` so the SCRUBBED shape (and the secret-exclusion
|
|
4
|
+
* invariant: config.accessToken / config.token never enter this object) is
|
|
5
|
+
* unit-testable without a live server or filesystem.
|
|
6
|
+
*/
|
|
7
|
+
export declare function buildSnapshotPayload(cfg: {
|
|
8
|
+
deviceFingerprint?: string;
|
|
9
|
+
installSalt?: string;
|
|
10
|
+
}, budget: {
|
|
11
|
+
tokensUsed: number;
|
|
12
|
+
tokenCap: number;
|
|
13
|
+
}, extras?: {
|
|
14
|
+
simCooldown?: unknown;
|
|
15
|
+
tokenBindings?: unknown;
|
|
16
|
+
}): Record<string, unknown>;
|
|
1
17
|
/**
|
|
2
18
|
* Fire a scrubbed integrity snapshot to the server. Best-effort, non-blocking,
|
|
3
19
|
* and self-swallowing — callers may `await` it inside an existing try/catch
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as
|
|
1
|
+
import{readFileSync as n}from"node:fs";import{join as o}from"node:path";import{homedir as t}from"node:os";import{getConfig as i,getBudget as e}from"./config.js";import{getCliVersion as r}from"./version.js";import{collectVerdicts as s}from"./secure-store.js";function a(o){try{return JSON.parse(n(o,"utf-8"))}catch{return null}}export function buildSnapshotPayload(n,o,t){return{deviceFingerprint:n.deviceFingerprint||"",installSalt:n.installSalt||"",budget:{tokensUsed:o.tokensUsed,tokenCap:o.tokenCap},simCooldown:t?.simCooldown??null,tokenBindings:t?.tokenBindings??null,integrity:s()}}export async function postIntegritySnapshot(){try{const n=i();if("live"!==n.competitionState)return;const s=n.ctfdUrl;if(!s)return;const c=o(t(),".icoa"),l=buildSnapshotPayload(n,e(),{simCooldown:a(o(c,"sim-cooldown.json")),tokenBindings:a(o(c,"token-bindings.json"))}),p={"Content-Type":"application/json","User-Agent":`icoa-cli/${r()}`,"X-Device-Fingerprint":n.deviceFingerprint||""};n.token&&n.userName&&(l.account=n.userName,p.Authorization=`Token ${n.token}`),await fetch(`${s}/api/icoa/snapshot`,{method:"POST",headers:p,body:JSON.stringify(l),signal:AbortSignal.timeout(8e3)})}catch{}}
|
package/dist/lib/learn-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{join as e}from"node:path";import{getIcoaDir as t,getInstallSalt as r}from"./config.js";import{deriveFileKey as a,readSignedFile as n,writeSignedFile as o,recordVerdict as s}from"./secure-store.js";const c="learn-state";function i(){return e(t(),"learn-state.json")}function l(){return a(r(),c)}export function loadLearnState(){const{data:e,verdict:t}=n(i(),l());return s(c,t),e}export function saveLearnState(e){e.lastSeenAt=(new Date).toISOString(),o(i(),e,l())}export function newLearnState(e,t,r){const a=(new Date).toISOString();return{token:e,curriculumId:t,currentCard:1,totalCards:r,startedAt:a,lastSeenAt:a,streakDays:1,longestStreak:1,cardsCompleted:[],mcqResults:{},checkResults:{},practicalsCompleted:[],bookmarks:[],achievements:[],totalSecondsActive:0}}export function updateStreak(e){const t=new Date(e.lastSeenAt),r=new Date,a=Math.floor(t.getTime()/864e5),n=Math.floor(r.getTime()/864e5)-a;0!==n&&(1===n?(e.streakDays+=1,e.streakDays>e.longestStreak&&(e.longestStreak=e.streakDays)):e.streakDays=1)}export function markCardComplete(e,t){e.cardsCompleted.includes(t)||e.cardsCompleted.push(t)}export function recordMCQ(e,t,r){e.mcqResults[String(t)]=r}export function recordCheck(e,t,r){e.checkResults||(e.checkResults={}),e.checkResults[String(t)]=r}export function markPracticalComplete(e,t){e.practicalsCompleted.includes(t)||e.practicalsCompleted.push(t)}export function addAchievement(e,t){e.achievements.includes(t)||e.achievements.push(t)}
|
package/dist/lib/log-sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readFileSync as t,existsSync as n,writeFileSync as e,chmodSync as s}from"node:fs";import{join as i}from"node:path";import{getIcoaDir as o,getConfig as c}from"./config.js";import{getDeviceFingerprint as r}from"./access.js";import{getCliVersion as
|
|
1
|
+
import{readFileSync as t,existsSync as n,writeFileSync as e,chmodSync as s}from"node:fs";import{join as i}from"node:path";import{getIcoaDir as o,getConfig as a,getInstallSalt as c}from"./config.js";import{getDeviceFingerprint as r}from"./access.js";import{getCliVersion as l}from"./version.js";const u=()=>i(o(),"sync-state.json");let f=null;function y(t){const n=u();e(n,JSON.stringify(t,null,2));try{s(n,384)}catch{}}async function d(){const e=a(),s=e.ctfdUrl||"https://practice.icoa2026.au",f=i(o(),"session.log");if(!n(f))return;const d=function(){const e=u();if(!n(e))return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0};try{const n=JSON.parse(t(e,"utf-8"));return{lastSyncedLine:n.lastSyncedLine??0,lastSyncAt:n.lastSyncAt??null,syncCount:n.syncCount??0,failCount:n.failCount??0,seq:n.seq??0}}catch{return{lastSyncedLine:0,lastSyncAt:null,syncCount:0,failCount:0,seq:0}}}(),S=t(f,"utf-8").trim().split("\n").filter(Boolean);S.length<d.lastSyncedLine&&(d.lastSyncedLine=0);const p=S.slice(d.lastSyncedLine);if(0===p.length)return;const m={"Content-Type":"application/json"};let g;if(e.token)m.Authorization=`Token ${e.token}`,g=`user:${e.userId??"unknown"}`;else{const t=e.deviceFingerprint||r();m["X-Device-Fingerprint"]=t,g=`demo:${t.slice(0,12)}`}const h=d.seq??0,C=p.map((t,n)=>{let e;try{e=JSON.parse(t)}catch{e={raw:t}}return{...e,_seq:h+n+1}}),I=l(),L=C.map(t=>({...t,_cli:I})),q={identity:g,userId:e.userId,userName:e.userName,teamId:e.teamId,sessionId:e.sessionId,deviceFingerprint:e.deviceFingerprint||r(),installSalt:e.installSalt||c(),lang:e.language||"en",clientVersion:I,timestamp:(new Date).toISOString(),seqRange:{from:h+1,to:h+C.length},entries:L};try{const t=new URL("/api/icoa/audit",s).href;(await fetch(t,{method:"POST",headers:m,body:JSON.stringify(q),signal:AbortSignal.timeout(1e4)})).ok?(d.lastSyncedLine=S.length,d.lastSyncAt=(new Date).toISOString(),d.syncCount++,d.seq=h+C.length,y(d)):(d.failCount++,y(d))}catch{d.failCount++,y(d)}}export function startLogSync(){setTimeout(()=>d(),5e3),f=setInterval(()=>d(),3e4)}export function stopLogSync(){f&&(clearInterval(f),f=null),d()}
|
package/dist/lib/logger.d.ts
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import type { LogEntry } from '../types/index.js';
|
|
2
|
+
/** Test-only: force the next currentLastMac() call to re-seed from the log
|
|
3
|
+
* tail, simulating a fresh process picking up an existing session.log. */
|
|
4
|
+
export declare function __resetChainHeadForTest(): void;
|
|
5
|
+
export declare function chainMac(prevMac: string, entry: object, key: Buffer): string;
|
|
6
|
+
export declare function verifyChain(entries: Array<Record<string, unknown>>, startMac: string, key: Buffer): {
|
|
7
|
+
ok: boolean;
|
|
8
|
+
brokenAt: number;
|
|
9
|
+
};
|
|
2
10
|
export declare function logCommand(command: string): void;
|
|
3
11
|
export declare function logSubmission(challengeId: number, flag: string): void;
|
|
4
12
|
export declare function getSessionLog(): LogEntry[];
|
package/dist/lib/logger.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{appendFileSync as t,readFileSync as n,existsSync as
|
|
1
|
+
import{appendFileSync as t,readFileSync as n,existsSync as e}from"node:fs";import{join as o}from"node:path";import{createHmac as r}from"node:crypto";import{getConfig as i,getIcoaDir as s,getInstallSalt as c}from"./config.js";import{deriveFileKey as a,canonicalize as u}from"./secure-store.js";import{consumeLineDynamics as l}from"./input-dynamics.js";function m(){return o(s(),"session.log")}let f=null;export function __resetChainHeadForTest(){f=null}export function chainMac(t,n,e){const o={...n};return delete o._mac,r("sha256",e).update(t).update("\n").update(u(o)).digest("hex")}export function verifyChain(t,n,e){let o=n;for(let n=0;n<t.length;n++){const r=chainMac(o,t[n],e);if(t[n]._mac!==r)return{ok:!1,brokenAt:n};o=r}return{ok:!0,brokenAt:-1}}function p(e){try{const o=a(c(),"session-log"),r=chainMac(function(){if(null!==f)return f;try{const t=n(m(),"utf-8").split("\n").filter(t=>t.trim().length>0),e=t[t.length-1],o=JSON.parse(e);f=o._mac??""}catch{f=""}return f}(),e,o),i={...e,_mac:r};t(m(),`${JSON.stringify(i)}\n`),f=r}catch{try{t(m(),`${JSON.stringify(e)}\n`)}catch{}f=null}}export function logCommand(t){const n=i();p({timestamp:(new Date).toISOString(),level:"command",input:t,sessionId:n.sessionId,dyn:l()})}export function logSubmission(t,n){const e=i();p({timestamp:(new Date).toISOString(),level:"submit",input:n,challengeId:t,sessionId:e.sessionId,dyn:l()})}export function getSessionLog(){const t=m();if(!e(t))return[];try{return n(t,"utf-8").trim().split("\n").filter(Boolean).map(t=>JSON.parse(t))}catch{return[]}}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* md-term — tiny markdown → ANSI renderer for `icoa ipynb` markdown cells.
|
|
3
|
+
* Deliberately minimal (headers, bold/italic, inline + fenced code, lists,
|
|
4
|
+
* quotes, rules, links); full CommonMark is a non-goal — an unrecognized line
|
|
5
|
+
* degrades to plain styled text, never an error. chalk-only styling per the
|
|
6
|
+
* terminal color rules (black background — no default-color text), UTF-8
|
|
7
|
+
* box/bullet chars only (4-platform baseline, no images/sixel).
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Render markdown source to display lines (already indented + chalk-styled).
|
|
11
|
+
* Pure w.r.t. the terminal: caller prints. `width` bounds rules/underlines.
|
|
12
|
+
*/
|
|
13
|
+
export declare function renderMarkdown(src: string, indent?: string, width?: number): string[];
|
|
14
|
+
/** Heuristic: does this (failed-as-Python) source look like markdown/prose?
|
|
15
|
+
* Markdown markers, or a plain multi-word line with no code-ish characters.
|
|
16
|
+
* Only consulted AFTER a SyntaxError, so a false positive costs one gray hint. */
|
|
17
|
+
export declare function looksLikeMarkdown(src: string): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import chalk from"chalk";function t(t){return t.replace(/`([^`]+)`/g,(t,n)=>chalk.cyan(n)).replace(/\*\*([^*]+)\*\*/g,(t,n)=>chalk.bold.white(n)).replace(/(^|\W)\*([^*\s][^*]*)\*/g,(t,n,s)=>n+chalk.italic.white(s)).replace(/(^|\W)_([^_\s][^_]*)_/g,(t,n,s)=>n+chalk.italic.white(s)).replace(/!?\[([^\]]*)\]\(([^)\s]+)\)/g,(t,n,s)=>chalk.cyan(n||s)+chalk.gray(` (${s})`))}export function renderMarkdown(n,s=" ",e=60){const c=[];let i=!1;for(const r of n.split("\n")){if(/^\s*(```|~~~)/.test(r)){i=!i,c.push(s+chalk.gray(r.trim()));continue}if(i){c.push(s+chalk.cyan(` ${r}`));continue}const n=r.match(/^(#{1,6})\s+(.*)$/);if(n){const t=n[1].length,i=n[2].trim();c.push(s+(1===t?chalk.bold.white(i):chalk.bold.cyan(i))),t<=2&&c.push(s+chalk.gray("─".repeat(Math.max(4,Math.min(i.length,e)))));continue}if(/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(r)){c.push(s+chalk.gray("─".repeat(e)));continue}const a=r.match(/^\s*>\s?(.*)$/);if(a){c.push(s+chalk.gray(`│ ${a[1]}`));continue}const o=r.match(/^(\s*)[-*+]\s+(.*)$/);if(o){c.push(s+o[1]+chalk.cyan("•")+` ${t(o[2])}`);continue}const h=r.match(/^(\s*)(\d+)[.)]\s+(.*)$/);h?c.push(s+h[1]+chalk.cyan(`${h[2]}.`)+` ${t(h[3])}`):c.push(""===r.trim()?"":s+chalk.white(t(r)))}return c}export function looksLikeMarkdown(t){const n=t.split("\n").find(t=>""!==t.trim())??"";if(/^\s*(#{1,6}\s|\*\*|[-*+]\s|>\s|```|\[[^\]]*\]\()/.test(n))return!0;const s=n.trim();return/^[A-Za-z一-鿿]/.test(s)&&/\s/.test(s)&&!/[=()[\]{}:'"#`\\]/.test(s)}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type IntegrityVerdict = 'ok' | 'tampered' | 'unsigned' | 'absent' | 'corrupt';
|
|
2
|
+
export interface SigBlock {
|
|
3
|
+
v: 1;
|
|
4
|
+
alg: 'HS256';
|
|
5
|
+
mac: string;
|
|
6
|
+
ts: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function deriveFileKey(installSalt: string, fileId: string): Buffer;
|
|
9
|
+
export declare function canonicalize(obj: unknown): string;
|
|
10
|
+
export declare function signObject(payload: object, key: Buffer): SigBlock;
|
|
11
|
+
export declare function verifyObject(payloadWithSig: object, key: Buffer): IntegrityVerdict;
|
|
12
|
+
export declare function writeSignedFile(path: string, payload: object, key: Buffer): void;
|
|
13
|
+
export declare function readSignedFile<T>(path: string, key: Buffer): {
|
|
14
|
+
data: T | null;
|
|
15
|
+
verdict: IntegrityVerdict;
|
|
16
|
+
};
|
|
17
|
+
export declare function recordVerdict(fileId: string, verdict: IntegrityVerdict): void;
|
|
18
|
+
export declare function collectVerdicts(): Record<string, IntegrityVerdict>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{writeFileSync as e,readFileSync as t,existsSync as r,chmodSync as n}from"node:fs";import{hkdfSync as o,createHmac as i,timingSafeEqual as c}from"node:crypto";export function deriveFileKey(e,t){const r=o("sha256",Buffer.from(e,"utf-8"),Buffer.from("icoa-secure-store-v1"),Buffer.from(t),32);return Buffer.from(r)}export function canonicalize(e){const t=new Set,r=e=>{if(null===e||"object"!=typeof e)return e;if(t.has(e))return null;let n;if(t.add(e),Array.isArray(e))n=e.map(r);else{const t=e,o={};for(const e of Object.keys(t).sort())"_sig"!==e&&(o[e]=r(t[e]));n=o}return t.delete(e),n};return JSON.stringify(r(e))}function f(e,t){return i("sha256",t).update(canonicalize(e)).digest("hex")}export function signObject(e,t){return{v:1,alg:"HS256",mac:f(e,t),ts:(new Date).toISOString()}}export function verifyObject(e,t){const r=e._sig;if(!r||"string"!=typeof r.mac)return"unsigned";const n=f(e,t),o=Buffer.from(r.mac,"hex"),i=Buffer.from(n,"hex");return o.length!==i.length?"tampered":c(o,i)?"ok":"tampered"}export function writeSignedFile(t,r,o){const i={...r};delete i._sig;const c=signObject(i,o);e(t,JSON.stringify({...i,_sig:c},null,2));try{n(t,384)}catch{}}export function readSignedFile(e,n){if(!r(e))return{data:null,verdict:"absent"};let o;try{o=JSON.parse(t(e,"utf-8"))}catch{return{data:null,verdict:"corrupt"}}const i=verifyObject(o,n),c={...o};return delete c._sig,{data:c,verdict:i}}const u=new Map,s={ok:0,absent:0,unsigned:1,corrupt:2,tampered:3};export function recordVerdict(e,t){if(0===s[t])return;const r=u.get(e);(!r||s[t]>s[r])&&u.set(e,t)}export function collectVerdicts(){return Object.fromEntries(u)}
|
package/dist/lib/sim-cooldown.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{join as t}from"node:path";import{getIcoaDir as n,getInstallSalt as o}from"./config.js";import{deriveFileKey as r,readSignedFile as e,writeSignedFile as l,recordVerdict as a}from"./secure-store.js";export const COOLDOWN_SECONDS=60;const s="sim-cooldown";function u(){return t(n(),"sim-cooldown.json")}function c(){return r(o(),s)}function m(){try{const{data:t,verdict:n}=e(u(),c());return a(s,n),t||{}}catch{return{}}}function A(t){try{const n={...m(),...t};l(u(),n,c())}catch{}}export function lastSimAt(){const t=m();return"number"==typeof t.lastCallAt?t.lastCallAt:0}export function markSimAt(t){A({lastCallAt:t})}export function cooldownRemaining(){const t=(Date.now()-lastSimAt())/1e3;return Math.max(0,Math.ceil(60-t))}export function lastBundledAt(){const t=m();return"number"==typeof t.lastBundledAt?t.lastBundledAt:0}export function markBundledAt(t){A({lastBundledAt:t})}export function lastArmAt(){const t=m();return"number"==typeof t.lastArmAt?t.lastArmAt:0}export function markArmAt(t){A({lastArmAt:t})}export function hasAnySimHistory(){const t=m();return"number"==typeof t.lastBundledAt&&t.lastBundledAt>0||"number"==typeof t.lastCallAt&&t.lastCallAt>0||"number"==typeof t.lastArmAt&&t.lastArmAt>0}
|