icoa-cli 2.19.402 → 2.19.404
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/ai4ioai.js +1 -1
- package/dist/commands/arena.js +1 -1
- package/dist/commands/ctf.js +1 -1
- package/dist/commands/ctf4ai-demo.js +1 -1
- package/dist/commands/ctf4vla.js +1 -1
- package/dist/commands/demo2.js +1 -1
- package/dist/commands/exam.js +1 -1
- package/dist/commands/ioailab.js +1 -1
- package/dist/commands/ipynb.js +1 -1
- package/dist/commands/learn.js +1 -1
- package/dist/commands/sim.js +1 -1
- package/dist/lib/kaggle.js +1 -1
- package/dist/lib/learn-ai.d.ts +19 -0
- package/dist/lib/learn-ai.js +1 -1
- package/dist/lib/learn-contest.d.ts +7 -4
- package/dist/lib/learn-render.d.ts +13 -4
- package/dist/lib/learn-render.js +1 -1
- package/package.json +1 -1
package/dist/commands/ioailab.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as e}from"node:child_process";import{existsSync as o,mkdirSync as t,readFileSync as n,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{join as s}from"node:path";import{Interface as i,createInterface as c}from"node:readline";import chalk from"chalk";import{editTextInEditor as l}from"../lib/editor-spawn.js";import{buildSshArgs as g,leaseConnectProblems as u,parseLeaseResponse as y,queueLine as d}from"../lib/gpu.js";import{logCommand as m}from"../lib/logger.js";import{getMainRl as f}from"../lib/main-rl.js";import{openFile as p}from"../lib/open-file.js";import{printError as h}from"../lib/ui.js";const w=[{id:"pick-cube",env:"PrimeLite-PickCube-v0",blurb:"Robot arm picks a cube off the table (imitation-learning demo)"}],b=/^[a-z0-9-]{1,32}$/,v=/^MP4:(\/[A-Za-z0-9._/-]+\.mp4)\s*$/m,k=/^HDF5:(\/[A-Za-z0-9._/-]+\.hdf5)\s*$/m,$=/^CKPT:(\/[A-Za-z0-9._/-]+\.pth)\s*$/m,x=/^METRICS:(\{.*\})\s*$/m,P=/^algo(?:_used)?:\s*([a-z_]+)\s*$/im,_="/opt/ioailab-mj/work",A=`${_}/05_custom_agent.py`;function I(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}function U(){return s(a(),".icoa","gpu-key")}function S(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(U(),"utf-8").trim()||null}catch{return null}}function G(e){t(s(a(),".icoa"),{recursive:!0}),r(U(),`${e.trim()}\n`,{mode:384})}async function O(e,o,t){try{const n=await fetch(`${I()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{key:o,task:t}:{key:o}),signal:AbortSignal.timeout(2e4)});return y(await n.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}async function C(e){try{const o=await fetch(`${I()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await o.json();return t&&!0===t.success?"ok":"invalid"}catch{return"offline"}}let L=null,T=null,E=null,R=!1,j=!1,q=!1,N=!1,Y=!1,M=null;function K(){return s(a(),"icoa-ioailab","05_custom_agent.py")}function V(o,t,n,r){return new Promise(a=>{const s="local"===o.transport?{command:"/bin/sh",args:["-c",n]}:{command:"ssh",args:g(o,t,n)},i=e(s.command,s.args,{stdio:["ignore","pipe","pipe"]});let c="",l="";const u=setTimeout(()=>i.kill("SIGKILL"),r);i.stdout.on("data",e=>{c+=e.toString(),l+=e.toString();let o=l.indexOf("\n");for(;o>=0;){const e=l.slice(0,o).trimEnd();l=l.slice(o+1),e.length>0&&console.log(chalk.white(` ${e}`)),o=l.indexOf("\n")}}),i.stderr.on("data",e=>{const o=e.toString().trimEnd();o.length>0&&console.log(chalk.gray(` ${o}`))}),i.on("close",e=>{clearTimeout(u),a({code:e??1,out:c})}),i.on("error",()=>{clearTimeout(u),a({code:127,out:c})})})}function z(o,t,n,a){return new Promise(s=>{const i=g(o,t,`cat ${n}`),c=e("ssh",i,{stdio:["ignore","pipe","pipe"]}),l=[],u=setTimeout(()=>c.kill("SIGKILL"),12e4);c.stdout.on("data",e=>l.push(e)),c.on("close",e=>{if(clearTimeout(u),0!==e||0===l.length)return s(!1);try{r(a,Buffer.concat(l)),s(!0)}catch{s(!1)}}),c.on("error",()=>{clearTimeout(u),s(!1)})})}async function D(o,t){if(!L)return!1;if("local"===L.transport)try{return r(t,n(o)),!0}catch{return!1}return function(o,t,r,a){return new Promise(s=>{let i;try{i=n(r)}catch{return s(!1)}const c=g(o,t,`mkdir -p ${_} && cat > ${a}`),l=e("ssh",c,{stdio:["pipe","ignore","pipe"]}),u=setTimeout(()=>l.kill("SIGKILL"),12e4);l.on("close",e=>{clearTimeout(u),s(0===e)}),l.on("error",()=>{clearTimeout(u),s(!1)}),l.stdin&&(l.stdin.on("error",()=>{}),l.stdin.write(i),l.stdin.end())})}(L,T,o,t)}function F(){return!(!L||"ssh"===L.transport&&!T)||(console.log(chalk.yellow(" No GPU box leased — ")+chalk.cyan("on")+chalk.gray(" first.")),!1)}function B(e,o,t){let n;for(let t=0;t<e.length;t++){const r=e[t];r===`--${o}`&&t+1<e.length?n=e[t+1]:r.startsWith(`--${o}=`)?n=r.slice(o.length+3):void 0===n&&/^[0-9]+$/.test(r)&&(n=r)}if(void 0===n)return t;const r=Number.parseInt(n,10);return Number.isFinite(r)?Math.min(999,Math.max(1,r)):t}async function W(e,o,t,n){if(!L||"ssh"===L.transport&&!T)return null;const r=w[0].id;return V(L,T??"",`sudo -n /usr/local/bin/ioailab-run ${r} ${e} --${o} ${t}`,n)}function J(e){4===e?console.log(chalk.yellow(" The box says an earlier step is missing — run it first (")+chalk.cyan("guide")+chalk.yellow(" shows where you are).")):2===e?console.log(chalk.red(" The box rejected the request (bad arguments).")):console.log(chalk.red(" Step failed on the box.")+chalk.gray(" (lease may have expired — ")+chalk.cyan("status")+chalk.gray(")"))}async function Z(e,o){if(!function(e){const o=L?.outDir??"";return!(""===o||!e.startsWith(o))||e===_||e.startsWith(`${_}/`)}(e))return void console.log(chalk.red(" Rejected unexpected video path from the box."));const i=s(a(),"icoa-ioailab");t(i,{recursive:!0});const c=s(i,`${o}-${Date.now()}.mp4`);process.stdout.write(chalk.gray(" Pulling the rendered clip…")),("local"===L?.transport?(()=>{try{return r(c,n(e)),!0}catch{return!1}})():await z(L,T,e,c))?(E=c,console.log(chalk.green(" done.")),console.log(chalk.magenta(" 🎬 clip → ")+chalk.cyan(c)),p(c)?console.log(chalk.gray(" Opened in your video viewer. ")+chalk.cyan("watch")+chalk.gray(" reopens it any time.")):console.log(chalk.gray(" Open it with your video player."))):console.log(chalk.red(" failed."))}function H(e){const o=e.match(x);if(!o)return void console.log(chalk.yellow(" Finished, but no metrics came back from the box."));let t;try{t=JSON.parse(o[1])}catch{return void console.log(chalk.yellow(" (metrics came back in an unexpected format.)"))}if(M=t,"number"==typeof t.success_rate){const e="number"==typeof t.episodes?` over ${t.episodes} episode(s)`:"";console.log(chalk.bold.green(` ★ success rate: ${(100*t.success_rate).toFixed(1)}%`)+chalk.gray(e))}for(const[e,o]of Object.entries(t))"success_rate"!==e&&"episodes"!==e&&("number"!=typeof o&&"string"!=typeof o||console.log(chalk.gray(` ${e}: `)+chalk.white(String(o))))}function Q(){let e;e=R?j?q?N?"edit custom":"eval":"train":"mimic":"collect",console.log(chalk.gray(" Next: ")+chalk.cyan(e)+chalk.gray(" (")+chalk.cyan("guide")+chalk.gray(" = where you are)"))}function X(){let e=!1;const o=[["collect",R],["mimic",j],["train",q],["eval",N],["custom",Y]].map(([o,t])=>t?`${o} ${chalk.green("✓")}`:e?`${o} ${chalk.gray("○")}`:(e=!0,`${o} ${chalk.yellow("…")}`));console.log(),console.log(chalk.bold.white(" ═══ 📖 IOAI Lab — the 5-step workflow ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+o.join(chalk.gray(" · "))),console.log(" "+(L?chalk.green("⚡ lease active")+chalk.gray(" (")+chalk.cyan("status")+chalk.gray(" for time left)"):chalk.gray("no lease — ")+chalk.cyan("on")+chalk.gray(" to lease a box"))),M&&"number"==typeof M.success_rate&&console.log(chalk.gray(" Last result: ")+chalk.green(`${(100*M.success_rate).toFixed(1)}% success`)),console.log(),console.log(chalk.bold.white(" Your move — drive the contest workflow:")),console.log(chalk.gray(" 1. ")+chalk.cyan("collect")+chalk.gray(" expert demos → watch the arm pick the cube")),console.log(chalk.gray(" 2. ")+chalk.cyan("mimic")+chalk.gray(" expand your demos (pose-randomized, MimicGen-lite)")),console.log(chalk.gray(" 3. ")+chalk.cyan("train")+chalk.gray(" robomimic Diffusion Policy on YOUR demos (GPU, scored)")),console.log(chalk.gray(" 4. ")+chalk.cyan("eval")+chalk.gray(" run YOUR policy → success rate → watch")),console.log(chalk.gray(" 5. ")+chalk.cyan("edit custom")+chalk.gray(" / ")+chalk.cyan("custom")+chalk.gray(" write your own BaseAgent → run it → watch")),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it to explain a step or debug your agent — then ")+chalk.bold.white("VERIFY")+chalk.gray(" by re-running ")+chalk.cyan("eval")+chalk.gray(".")),console.log(),console.log(chalk.cyan(" on")+chalk.gray("/")+chalk.cyan("off")+chalk.gray(" lease a box · ")+chalk.cyan("status")+chalk.gray(" time left · ")+chalk.cyan("watch")+chalk.gray(" replay last clip · ")+chalk.cyan("run")+chalk.gray(" quick showcase · ")+chalk.cyan("exit")+chalk.gray(" leave")),console.log()}async function ee(e=!1){const o=S();o&&L&&await O("release",o),L&&!e&&console.log(chalk.gray(" GPU lease released.")),L=null,T=null,R=!1,j=!1,q=!1,N=!1,Y=!1,M=null}async function oe(e){const i=e.trim();if(0===i.length)return"continue";const[c,...g]=i.split(/\s+/),y=c.toLowerCase();return m(`ioailab ${y}`),"exit"===y||"quit"===y||"q"===y?(await ee(!0),console.log(chalk.gray(" Leaving IOAI Lab — any GPU lease was released.")),"exit"):("guide"===y||"help"===y||"/guide"===y||"?"===y?X():"tasks"===y||"task"===y?function(){console.log();for(const e of w)console.log(chalk.cyan(` ${e.id.padEnd(12)}`)+chalk.gray(e.blurb));console.log()}():"key"===y?0===g.length?console.log(chalk.gray(" Usage: ")+chalk.cyan("key <your-access-key>")):(G(g[0]),console.log(chalk.green(" ✓ GPU access key saved.")+chalk.gray(" Next: ")+chalk.cyan("on"))):"on"===y||"lease"===y||"gpu"===y?await async function(){if(L)return void console.log(chalk.gray(" already holding a GPU lease — ")+chalk.cyan("status")+chalk.gray(" for time left."));const e=S();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));process.stdout.write(chalk.gray(" Requesting a GPU box…"));let o=await O("lease",e,"ioailab"),n=0;for(;"queued"===o.state&&n<24;)0===n&&console.log(),process.stdout.write(`\r ${chalk.yellow(d(o))} `),await new Promise(e=>setTimeout(e,5e3)),o=await O("status",e),n++;if("queued"===o.state)return console.log(),void console.log(chalk.yellow(" Still queued — your place is held server-side. Try ")+chalk.cyan("on")+chalk.gray(" again in a few minutes."));if("ready"!==o.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${o.message??"no lease granted"}`));const i=u(o);if("local"!==o.transport||process.env.ICOA_GPU_SERVER||i.push("local transport from a non-dev broker"),i.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(i.join(", "))),void await O("release",e);let c=null;if("ssh"===o.transport&&(c=function(e){const o=s(a(),".icoa","gpu","ioailab-lease-key");try{return t(s(a(),".icoa","gpu"),{recursive:!0}),r(o,e.keyPem,{mode:384}),o}catch{return null}}(o),!c))return console.log(chalk.red(" could not write the ssh key locally.")),void await O("release",e);L=o,T=c;const l=Math.round((o.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU box leased.")+chalk.gray(` ~${l}m on this lease.`)),console.log(chalk.gray(" Next: ")+chalk.cyan("collect")+chalk.gray(" — start the 5-step chain (or ")+chalk.cyan("run")+chalk.gray(" for a quick one-shot showcase)."))}():"off"===y||"release"===y?await ee():"status"===y||"queue"===y?await async function(){const e=S();if(!e)return void console.log(chalk.yellow(" No GPU access key saved — ")+chalk.cyan("key <k>")+chalk.gray(" first."));const o=await O("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ lease active · ~${e}m left.`))}else"queued"===o.state?console.log(` ${chalk.yellow(d(o))}`):console.log(chalk.gray(" no active lease — ")+chalk.cyan("on")+chalk.gray(" to request a box."))}():"run"===y?await async function(e){const o=w.find(o=>o.id===e);if(!o||!b.test(e))return void console.log(chalk.yellow(` Unknown task "${e}" — `)+chalk.cyan("tasks")+chalk.gray(" lists what is available."));if(!F())return;console.log(chalk.gray(` Running the ${o.id} task (ICOA-VLA arm) on the GPU box (headless — takes a moment)…`));const t=`sudo -n /usr/local/bin/ioailab-run ${e} 1`,{code:n,out:r}=await V(L,T??"",t,72e4);if(0!==n)return void console.log(chalk.red(" Episode failed on the box.")+chalk.gray(" (lease may have expired — ")+chalk.cyan("status")+chalk.gray(")"));const a=r.match(v);a?await Z(a[1],e):console.log(chalk.yellow(" Episode finished but no video path came back — box-side renderer issue."))}((g[0]??w[0].id).toLowerCase()):"collect"===y?await async function(e){if(!F())return;const o=B(e,"episodes",5);console.log(chalk.gray(` Collecting ${o} expert demo(s) on the ICOA-VLA arm (headless — takes a moment)…`));const t=await W("collect","episodes",o,72e4);if(!t)return;if(0!==t.code)return J(t.code);const n=t.out.match(k);n&&(R=!0,console.log(chalk.green(" ✓ expert demos recorded → ")+chalk.gray(n[1]))),console.log(chalk.gray(" The expert is a scripted reach→grasp→lift waypoint controller (our stand-in for")),console.log(chalk.gray(" the contest's motion planner) — a clean demonstration source, not a learned policy yet."));const r=t.out.match(v);r&&await Z(r[1],"collect"),Q()}(g):"mimic"===y?await async function(e){if(!F())return;if(!R)return void console.log(chalk.yellow(" No demos yet — run ")+chalk.cyan("collect")+chalk.gray(" first."));const o=B(e,"episodes",36);console.log(chalk.gray(` Expanding your demos into ${o} training episode(s)…`));const t=await W("mimic","episodes",o,72e4);if(!t)return;if(0!==t.code)return J(t.code);const n=t.out.match(k);n&&(j=!0,console.log(chalk.green(" ✓ training demos generated → ")+chalk.gray(n[1]))),console.log(chalk.gray(" MimicGen-lite: we randomize the cube pose and re-run the pose-conditioned expert —")),console.log(chalk.gray(" real rollouts, same robomimic schema, not the object-centric MimicGen the full sim uses.")),Q()}(g):"train"===y?await async function(e){if(!F())return;if(!j)return void console.log(chalk.yellow(" No training set yet — run ")+chalk.cyan("mimic")+chalk.gray(" first."));const o=B(e,"epochs",20),t=54e5,n=L?.timeLeftSec??0;if(n>0&&1e3*n<t){const e=Math.round(n/60);console.log(chalk.yellow(` ⚠ your lease has ~${e}m left`)+chalk.gray(" — a long train may outlast it. ")+chalk.cyan("off")+chalk.gray("/")+chalk.cyan("on")+chalk.gray(" to refresh first if needed."))}console.log(chalk.gray(` Training a robomimic Diffusion Policy for ${o} epoch(s) on YOUR demos — the scored step (GPU)…`));const r=await W("train","epochs",o,t);if(!r)return;if(0!==r.code)return J(r.code);const a=r.out.match($);a&&(q=!0,console.log(chalk.green(" ✓ checkpoint saved → ")+chalk.gray(a[1])));const s=r.out.match(P);s&&/bc/i.test(s[1])?console.log(chalk.gray(" (behavior-cloning fallback — real diffusion pending on this box.)")):console.log(chalk.gray(" Same open robomimic Diffusion Policy the real contest uses — high-fidelity where it counts.")),Q()}(g):"eval"===y?await async function(e){if(!F())return;if(!q)return void console.log(chalk.yellow(" No trained policy yet — run ")+chalk.cyan("train")+chalk.gray(" first."));const o=B(e,"episodes",20);console.log(chalk.gray(` Running YOUR trained policy for ${o} episode(s)…`));const t=await W("eval","episodes",o,72e4);if(!t)return;if(0!==t.code)return J(t.code);H(t.out),N=!0,console.log(chalk.gray(" Your number reflects the practice arm + your demo count/epochs — it's the workflow signal,")),console.log(chalk.gray(" not a contest leaderboard score."));const n=t.out.match(v);n&&await Z(n[1],"eval"),Q()}(g):"custom"===y?await async function(e){if(!F())return;const t=K();if(!o(t))return void console.log(chalk.yellow(" No custom agent yet — ")+chalk.cyan("edit custom")+chalk.gray(" to write one first."));process.stdout.write(chalk.gray(" Uploading your agent…"));const n=await D(t,A);if(console.log(n?chalk.green(" done."):chalk.red(" failed.")),!n)return;const r=B(e,"episodes",9);console.log(chalk.gray(` Running YOUR agent for ${r} episode(s)…`));const a=await W("custom","episodes",r,72e4);if(!a)return;if(0!==a.code)return J(a.code);H(a.out),Y=!0;const s=a.out.match(v);s?await Z(s[1],"custom"):console.log(chalk.gray(" (no replay — for it to render, your agent must be constructible with no required args. Metrics above.)")),console.log(chalk.gray(" Iterate: ")+chalk.cyan("edit custom")+chalk.gray(" → ")+chalk.cyan("custom")+chalk.gray(" → watch, repeat."))}(g):"edit"===y?"custom"===(g[0]??"").toLowerCase()?await async function(){if(!F())return;const e=s(a(),"icoa-ioailab");t(e,{recursive:!0});const i=K();o(i)||(process.stdout.write(chalk.gray(" Fetching the starter agent…")),await async function(e,o){if(!L)return!1;if("local"===L.transport)try{return r(o,n(e)),!0}catch{return!1}return z(L,T,e,o)}("/opt/ioailab-mj/examples/05_custom_agent.py",i)?console.log(chalk.green(" done.")):(r(i,'"""05_custom_agent.py — your agent for the ICOA-VLA arm.\n\nSubclass BaseAgent and implement act(env, env_ids) -> array [rows, action_dim].\nKeep the constructor argument-free so the replay can render your agent\n(like the SinusoidAgent starter below). Then: edit custom -> custom -> watch.\n"""\nimport numpy as np\n\ntry:\n from icoa_ioailab.agents import BaseAgent\nexcept Exception: # resolved on the GPU box\n BaseAgent = object\n\n\nclass SinusoidAgent(BaseAgent):\n def __init__(self):\n self._t = 0\n\n def act(self, env, env_ids):\n rows = len(env_ids)\n dim = getattr(env, "action_dim", 7)\n self._t += 1\n cmd = 0.1 * np.sin(self._t * 0.2)\n return np.full((rows, dim), cmd, dtype=np.float32)\n'),console.log(chalk.gray(" using a local starter."))));const c=n(i,"utf-8"),g=l(c,".py");if(null===g)return void console.log(chalk.yellow(" Editor cancelled — agent unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));r(i,g),process.stdout.write(chalk.gray(" Saving to the box…"));const u=await D(i,A);console.log(u?chalk.green(" done."):chalk.red(" failed.")),console.log(chalk.gray(" Saved → run ")+chalk.cyan("custom")+chalk.gray(" to try it."))}():console.log(chalk.gray(" Usage: ")+chalk.cyan("edit custom")+chalk.gray(" (write your own agent)")):"watch"===y||"open"===y?E&&p(E)?console.log(chalk.gray(" Reopened the last clip.")):console.log(chalk.gray(" No clip yet — ")+chalk.cyan("collect")+chalk.gray(" or ")+chalk.cyan("run")+chalk.gray(" first.")):console.log(chalk.yellow(` Unknown command "${y}" — `)+chalk.cyan("guide")+chalk.gray(" lists everything.")),"continue")}export async function runIoailabStandalone(){if(!await async function(){const{input:e}=await import("@inquirer/prompts"),o=S();if(o){const e=await C(o);if("ok"===e)return!0;if("offline"===e)return console.log(chalk.yellow(" Cannot reach the GPU service to verify your key right now — try again later.")),!1;console.log(chalk.yellow(" Your saved GPU key was not accepted. Enter a valid one below."))}else console.log(chalk.gray(" IOAI Lab is a paid GPU service. Enter the GPU access key issued with your purchase."));for(let o=0;o<3;o++){let t;try{t=await e({message:chalk.bold.magenta("icoa ioailab key>"),theme:{prefix:"",style:{message:e=>e}}})}catch{return!1}const n=t.trim();if(""===n||"exit"===n.toLowerCase()||"q"===n.toLowerCase())return!1;const r=await C(n);if("ok"===r)return G(n),console.log(chalk.green(" ✓ Key accepted — saved to this device. You will not be asked again.")),!0;if("offline"===r)return console.log(chalk.yellow(" Cannot reach the GPU service to verify — try again later.")),!1;console.log(chalk.red(` Key not recognised (${o<2?2-o+" tries left":"no tries left"}).`))}return!1}())return;console.log(),console.log(chalk.bold.magenta(" 🤖 IOAI Lab — Embodied AI practice twin (ICOA-VLA arm)")),console.log(chalk.gray(" The official Team-Challenge sim uses assets we can't hand out — so this is a")),console.log(chalk.gray(" practice twin: the same 5-step workflow, the same Python API, a real arm you drive.")),console.log(chalk.gray(" The scored part — training a diffusion policy from your own demos with robomimic")),console.log(chalk.gray(" (open source) — is byte-for-byte the framework the real contest uses.")),console.log(chalk.gray(" Runs on an ICOA GPU box — nothing installs here; the video opens locally.")),console.log(),console.log(chalk.white(" You will drive the exact contest workflow:")),console.log(" "+chalk.bold.cyan("collect")+chalk.gray(" → ")+chalk.bold.cyan("mimic")+chalk.gray(" → ")+chalk.bold.cyan("train")+chalk.gray(" → ")+chalk.bold.cyan("eval")+chalk.gray(" → ")+chalk.bold.cyan("custom")),console.log(chalk.gray(" v1 is a single task (pick-cube) on a MuJoCo arm; the real contest is multi-task on a")),console.log(chalk.gray(" higher-fidelity simulator — the learning core is the same.")),X();const e=f(),o=null!==e,t=o?e.listeners("line").slice():[];o&&e.removeAllListeners("line");const n=o?e:c({input:process.stdin,output:process.stdout,terminal:!0}),r=o?n.prompt:null;o&&(n.prompt=i.prototype.prompt);const a=()=>{n.setPrompt(chalk.bold.magenta("icoa ioailab> ")),n.prompt()};return new Promise(e=>{const s=i=>{oe(i).then(i=>{"exit"===i?((()=>{if(n.removeListener("line",s),o){r&&(n.prompt=r);for(const e of t)n.on("line",e)}else n.close()})(),e()):a()}).catch(e=>{h(`ioailab error: ${e instanceof Error?e.message:String(e)}`),a()})};n.on("line",s),a()})}
|
|
1
|
+
import{spawn as e}from"node:child_process";import{existsSync as o,mkdirSync as t,readFileSync as n,writeFileSync as r}from"node:fs";import{homedir as a}from"node:os";import{join as s}from"node:path";import{Interface as i,createInterface as c}from"node:readline";import chalk from"chalk";import{editTextInEditor as l}from"../lib/editor-spawn.js";import{buildSshArgs as g,leaseConnectProblems as u,parseLeaseResponse as y,queueLine as d}from"../lib/gpu.js";import{logCommand as m}from"../lib/logger.js";import{getMainRl as f}from"../lib/main-rl.js";import{openFile as p}from"../lib/open-file.js";import{printError as h}from"../lib/ui.js";const w=[{id:"pick-cube",env:"PrimeLite-PickCube-v0",blurb:"Robot arm picks a cube off the table (imitation-learning demo)"}],b=/^[a-z0-9-]{1,32}$/,v=/^MP4:(\/[A-Za-z0-9._/-]+\.mp4)\s*$/m,k=/^HDF5:(\/[A-Za-z0-9._/-]+\.hdf5)\s*$/m,$=/^CKPT:(\/[A-Za-z0-9._/-]+\.pth)\s*$/m,x=/^METRICS:(\{.*\})\s*$/m,P=/^algo(?:_used)?:\s*([a-z_]+)\s*$/im,_="/opt/ioailab-mj/work",A=`${_}/05_custom_agent.py`;function I(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}function U(){return s(a(),".icoa","gpu-key")}function S(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(U(),"utf-8").trim()||null}catch{return null}}function G(e){t(s(a(),".icoa"),{recursive:!0}),r(U(),`${e.trim()}\n`,{mode:384})}async function O(e,o,t){try{const n=await fetch(`${I()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{key:o,task:t}:{key:o}),signal:AbortSignal.timeout(2e4)});return y(await n.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}async function C(e){try{const o=await fetch(`${I()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),t=await o.json();return t&&!0===t.success?"ok":"invalid"}catch{return"offline"}}let L=null,T=null,E=null,R=!1,j=!1,q=!1,N=!1,Y=!1,M=null;function K(){return s(a(),"icoa-ioailab","05_custom_agent.py")}function V(o,t,n,r){return new Promise(a=>{const s="local"===o.transport?{command:"/bin/sh",args:["-c",n]}:{command:"ssh",args:g(o,t,n)},i=e(s.command,s.args,{stdio:["ignore","pipe","pipe"]});let c="",l="";const u=setTimeout(()=>i.kill("SIGKILL"),r);i.stdout.on("data",e=>{c+=e.toString(),l+=e.toString();let o=l.indexOf("\n");for(;o>=0;){const e=l.slice(0,o).trimEnd();l=l.slice(o+1),e.length>0&&console.log(chalk.white(` ${e}`)),o=l.indexOf("\n")}}),i.stderr.on("data",e=>{const o=e.toString().trimEnd();o.length>0&&console.log(chalk.gray(` ${o}`))}),i.on("close",e=>{clearTimeout(u),a({code:e??1,out:c})}),i.on("error",()=>{clearTimeout(u),a({code:127,out:c})})})}function z(o,t,n,a){return new Promise(s=>{const i=g(o,t,`cat ${n}`),c=e("ssh",i,{stdio:["ignore","pipe","pipe"]}),l=[],u=setTimeout(()=>c.kill("SIGKILL"),12e4);c.stdout.on("data",e=>l.push(e)),c.on("close",e=>{if(clearTimeout(u),0!==e||0===l.length)return s(!1);try{r(a,Buffer.concat(l)),s(!0)}catch{s(!1)}}),c.on("error",()=>{clearTimeout(u),s(!1)})})}async function D(o,t){if(!L)return!1;if("local"===L.transport)try{return r(t,n(o)),!0}catch{return!1}return function(o,t,r,a){return new Promise(s=>{let i;try{i=n(r)}catch{return s(!1)}const c=g(o,t,`mkdir -p ${_} && cat > ${a}`),l=e("ssh",c,{stdio:["pipe","ignore","pipe"]}),u=setTimeout(()=>l.kill("SIGKILL"),12e4);l.on("close",e=>{clearTimeout(u),s(0===e)}),l.on("error",()=>{clearTimeout(u),s(!1)}),l.stdin&&(l.stdin.on("error",()=>{}),l.stdin.write(i),l.stdin.end())})}(L,T,o,t)}function F(){return!(!L||"ssh"===L.transport&&!T)||(console.log(chalk.yellow(" No GPU box leased — ")+chalk.cyan("on")+chalk.gray(" first.")),!1)}function B(e,o,t){let n;for(let t=0;t<e.length;t++){const r=e[t];r===`--${o}`&&t+1<e.length?n=e[t+1]:r.startsWith(`--${o}=`)?n=r.slice(o.length+3):void 0===n&&/^[0-9]+$/.test(r)&&(n=r)}if(void 0===n)return t;const r=Number.parseInt(n,10);return Number.isFinite(r)?Math.min(999,Math.max(1,r)):t}async function W(e,o,t,n){if(!L||"ssh"===L.transport&&!T)return null;const r=w[0].id;return V(L,T??"",`sudo -n /usr/local/bin/ioailab-run ${r} ${e} --${o} ${t}`,n)}function J(e){4===e?console.log(chalk.yellow(" The box says an earlier step is missing — run it first (")+chalk.cyan("guide")+chalk.yellow(" shows where you are).")):2===e?console.log(chalk.red(" The box rejected the request (bad arguments).")):console.log(chalk.red(" Step failed on the box.")+chalk.gray(" (lease may have expired — ")+chalk.cyan("status")+chalk.gray(")"))}async function Z(e,o){if(!function(e){const o=L?.outDir??"";return!(""===o||!e.startsWith(o))||e===_||e.startsWith(`${_}/`)}(e))return void console.log(chalk.red(" Rejected unexpected video path from the box."));const i=s(a(),"icoa-ioailab");t(i,{recursive:!0});const c=s(i,`${o}-${Date.now()}.mp4`);process.stdout.write(chalk.gray(" Pulling the rendered clip…")),("local"===L?.transport?(()=>{try{return r(c,n(e)),!0}catch{return!1}})():await z(L,T,e,c))?(E=c,console.log(chalk.green(" done.")),console.log(chalk.magenta(" 🎬 clip → ")+chalk.cyan(c)),p(c)?console.log(chalk.gray(" Opened in your video viewer. ")+chalk.cyan("watch")+chalk.gray(" reopens it any time.")):console.log(chalk.gray(" Open it with your video player."))):console.log(chalk.red(" failed."))}function H(e){const o=e.match(x);if(!o)return void console.log(chalk.yellow(" Finished, but no metrics came back from the box."));let t;try{t=JSON.parse(o[1])}catch{return void console.log(chalk.yellow(" (metrics came back in an unexpected format.)"))}if(M=t,"number"==typeof t.success_rate){const e="number"==typeof t.episodes?` over ${t.episodes} episode(s)`:"";console.log(chalk.bold.green(` ★ success rate: ${(100*t.success_rate).toFixed(1)}%`)+chalk.gray(e))}for(const[e,o]of Object.entries(t))"success_rate"!==e&&"episodes"!==e&&("number"!=typeof o&&"string"!=typeof o||console.log(chalk.gray(` ${e}: `)+chalk.white(String(o))))}function Q(){let e;e=R?j?q?N?"edit custom":"eval":"train":"mimic":"collect",console.log(chalk.gray(" Next: ")+chalk.cyan(e)+chalk.gray(" (")+chalk.cyan("guide")+chalk.gray(" = where you are)"))}function X(){let e=!1;const o=[["collect",R],["mimic",j],["train",q],["eval",N],["custom",Y]].map(([o,t])=>t?`${o} ${chalk.green("✓")}`:e?`${o} ${chalk.gray("○")}`:(e=!0,`${o} ${chalk.yellow("…")}`));console.log(),console.log(chalk.bold.white(" ═══ 📖 IOAI Lab — the 5-step workflow ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+o.join(chalk.gray(" · "))),console.log(" "+(L?chalk.green("⚡ lease active")+chalk.gray(" (")+chalk.cyan("status")+chalk.gray(" for time left)"):chalk.gray("no lease — ")+chalk.cyan("on")+chalk.gray(" to lease a box"))),M&&"number"==typeof M.success_rate&&console.log(chalk.gray(" Last result: ")+chalk.green(`${(100*M.success_rate).toFixed(1)}% success`)),console.log(),console.log(chalk.bold.white(" Your move — drive the contest workflow:")),console.log(chalk.gray(" 1. ")+chalk.cyan("collect")+chalk.gray(" expert demos → watch the arm pick the cube")),console.log(chalk.gray(" 2. ")+chalk.cyan("mimic")+chalk.gray(" expand your demos (pose-randomized, MimicGen-lite)")),console.log(chalk.gray(" 3. ")+chalk.cyan("train")+chalk.gray(" robomimic Diffusion Policy on YOUR demos (GPU, scored)")),console.log(chalk.gray(" 4. ")+chalk.cyan("eval")+chalk.gray(" run YOUR policy → success rate → watch")),console.log(chalk.gray(" 5. ")+chalk.cyan("edit custom")+chalk.gray(" / ")+chalk.cyan("custom")+chalk.gray(" write your own BaseAgent → run it → watch")),console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it to explain a step or debug your agent — then ")+chalk.bold.white("VERIFY")+chalk.gray(" by re-running ")+chalk.cyan("eval")+chalk.gray(".")),console.log(),console.log(chalk.cyan(" on")+chalk.gray("/")+chalk.cyan("off")+chalk.gray(" lease a box · ")+chalk.cyan("status")+chalk.gray(" time left · ")+chalk.cyan("watch")+chalk.gray(" replay last clip · ")+chalk.cyan("run")+chalk.gray(" quick showcase · ")+chalk.cyan("exit")+chalk.gray(" leave")),console.log()}async function ee(e=!1){const o=S();o&&L&&await O("release",o),L&&!e&&console.log(chalk.gray(" GPU lease released.")),L=null,T=null,R=!1,j=!1,q=!1,N=!1,Y=!1,M=null}async function oe(e){const i=e.trim();if(0===i.length)return"continue";const[c,...g]=i.split(/\s+/),y=c.toLowerCase();return m(`ioailab ${y}`),"exit"===y||"quit"===y||"q"===y||"back"===y||"menu"===y?(await ee(!0),console.log(chalk.gray(" Leaving IOAI Lab — any GPU lease was released.")),"exit"):("guide"===y||"help"===y||"/guide"===y||"?"===y?X():"tasks"===y||"task"===y?function(){console.log();for(const e of w)console.log(chalk.cyan(` ${e.id.padEnd(12)}`)+chalk.gray(e.blurb));console.log()}():"key"===y?0===g.length?console.log(chalk.gray(" Usage: ")+chalk.cyan("key <your-access-key>")):(G(g[0]),console.log(chalk.green(" ✓ GPU access key saved.")+chalk.gray(" Next: ")+chalk.cyan("on"))):"on"===y||"lease"===y||"gpu"===y?await async function(){if(L)return void console.log(chalk.gray(" already holding a GPU lease — ")+chalk.cyan("status")+chalk.gray(" for time left."));const e=S();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));process.stdout.write(chalk.gray(" Requesting a GPU box…"));let o=await O("lease",e,"ioailab"),n=0;for(;"queued"===o.state&&n<24;)0===n&&console.log(),process.stdout.write(`\r ${chalk.yellow(d(o))} `),await new Promise(e=>setTimeout(e,5e3)),o=await O("status",e),n++;if("queued"===o.state)return console.log(),void console.log(chalk.yellow(" Still queued — your place is held server-side. Try ")+chalk.cyan("on")+chalk.gray(" again in a few minutes."));if("ready"!==o.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${o.message??"no lease granted"}`));const i=u(o);if("local"!==o.transport||process.env.ICOA_GPU_SERVER||i.push("local transport from a non-dev broker"),i.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(i.join(", "))),void await O("release",e);let c=null;if("ssh"===o.transport&&(c=function(e){const o=s(a(),".icoa","gpu","ioailab-lease-key");try{return t(s(a(),".icoa","gpu"),{recursive:!0}),r(o,e.keyPem,{mode:384}),o}catch{return null}}(o),!c))return console.log(chalk.red(" could not write the ssh key locally.")),void await O("release",e);L=o,T=c;const l=Math.round((o.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU box leased.")+chalk.gray(` ~${l}m on this lease.`)),console.log(chalk.gray(" Next: ")+chalk.cyan("collect")+chalk.gray(" — start the 5-step chain (or ")+chalk.cyan("run")+chalk.gray(" for a quick one-shot showcase)."))}():"off"===y||"release"===y?await ee():"status"===y||"queue"===y?await async function(){const e=S();if(!e)return void console.log(chalk.yellow(" No GPU access key saved — ")+chalk.cyan("key <k>")+chalk.gray(" first."));const o=await O("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ lease active · ~${e}m left.`))}else"queued"===o.state?console.log(` ${chalk.yellow(d(o))}`):console.log(chalk.gray(" no active lease — ")+chalk.cyan("on")+chalk.gray(" to request a box."))}():"run"===y?await async function(e){const o=w.find(o=>o.id===e);if(!o||!b.test(e))return void console.log(chalk.yellow(` Unknown task "${e}" — `)+chalk.cyan("tasks")+chalk.gray(" lists what is available."));if(!F())return;console.log(chalk.gray(` Running the ${o.id} task (ICOA-VLA arm) on the GPU box (headless — takes a moment)…`));const t=`sudo -n /usr/local/bin/ioailab-run ${e} 1`,{code:n,out:r}=await V(L,T??"",t,72e4);if(0!==n)return void console.log(chalk.red(" Episode failed on the box.")+chalk.gray(" (lease may have expired — ")+chalk.cyan("status")+chalk.gray(")"));const a=r.match(v);a?await Z(a[1],e):console.log(chalk.yellow(" Episode finished but no video path came back — box-side renderer issue."))}((g[0]??w[0].id).toLowerCase()):"collect"===y?await async function(e){if(!F())return;const o=B(e,"episodes",5);console.log(chalk.gray(` Collecting ${o} expert demo(s) on the ICOA-VLA arm (headless — takes a moment)…`));const t=await W("collect","episodes",o,72e4);if(!t)return;if(0!==t.code)return J(t.code);const n=t.out.match(k);n&&(R=!0,console.log(chalk.green(" ✓ expert demos recorded → ")+chalk.gray(n[1]))),console.log(chalk.gray(" The expert is a scripted reach→grasp→lift waypoint controller (our stand-in for")),console.log(chalk.gray(" the contest's motion planner) — a clean demonstration source, not a learned policy yet."));const r=t.out.match(v);r&&await Z(r[1],"collect"),Q()}(g):"mimic"===y?await async function(e){if(!F())return;if(!R)return void console.log(chalk.yellow(" No demos yet — run ")+chalk.cyan("collect")+chalk.gray(" first."));const o=B(e,"episodes",36);console.log(chalk.gray(` Expanding your demos into ${o} training episode(s)…`));const t=await W("mimic","episodes",o,72e4);if(!t)return;if(0!==t.code)return J(t.code);const n=t.out.match(k);n&&(j=!0,console.log(chalk.green(" ✓ training demos generated → ")+chalk.gray(n[1]))),console.log(chalk.gray(" MimicGen-lite: we randomize the cube pose and re-run the pose-conditioned expert —")),console.log(chalk.gray(" real rollouts, same robomimic schema, not the object-centric MimicGen the full sim uses.")),Q()}(g):"train"===y?await async function(e){if(!F())return;if(!j)return void console.log(chalk.yellow(" No training set yet — run ")+chalk.cyan("mimic")+chalk.gray(" first."));const o=B(e,"epochs",20),t=54e5,n=L?.timeLeftSec??0;if(n>0&&1e3*n<t){const e=Math.round(n/60);console.log(chalk.yellow(` ⚠ your lease has ~${e}m left`)+chalk.gray(" — a long train may outlast it. ")+chalk.cyan("off")+chalk.gray("/")+chalk.cyan("on")+chalk.gray(" to refresh first if needed."))}console.log(chalk.gray(` Training a robomimic Diffusion Policy for ${o} epoch(s) on YOUR demos — the scored step (GPU)…`));const r=await W("train","epochs",o,t);if(!r)return;if(0!==r.code)return J(r.code);const a=r.out.match($);a&&(q=!0,console.log(chalk.green(" ✓ checkpoint saved → ")+chalk.gray(a[1])));const s=r.out.match(P);s&&/bc/i.test(s[1])?console.log(chalk.gray(" (behavior-cloning fallback — real diffusion pending on this box.)")):console.log(chalk.gray(" Same open robomimic Diffusion Policy the real contest uses — high-fidelity where it counts.")),Q()}(g):"eval"===y?await async function(e){if(!F())return;if(!q)return void console.log(chalk.yellow(" No trained policy yet — run ")+chalk.cyan("train")+chalk.gray(" first."));const o=B(e,"episodes",20);console.log(chalk.gray(` Running YOUR trained policy for ${o} episode(s)…`));const t=await W("eval","episodes",o,72e4);if(!t)return;if(0!==t.code)return J(t.code);H(t.out),N=!0,console.log(chalk.gray(" Your number reflects the practice arm + your demo count/epochs — it's the workflow signal,")),console.log(chalk.gray(" not a contest leaderboard score."));const n=t.out.match(v);n&&await Z(n[1],"eval"),Q()}(g):"custom"===y?await async function(e){if(!F())return;const t=K();if(!o(t))return void console.log(chalk.yellow(" No custom agent yet — ")+chalk.cyan("edit custom")+chalk.gray(" to write one first."));process.stdout.write(chalk.gray(" Uploading your agent…"));const n=await D(t,A);if(console.log(n?chalk.green(" done."):chalk.red(" failed.")),!n)return;const r=B(e,"episodes",9);console.log(chalk.gray(` Running YOUR agent for ${r} episode(s)…`));const a=await W("custom","episodes",r,72e4);if(!a)return;if(0!==a.code)return J(a.code);H(a.out),Y=!0;const s=a.out.match(v);s?await Z(s[1],"custom"):console.log(chalk.gray(" (no replay — for it to render, your agent must be constructible with no required args. Metrics above.)")),console.log(chalk.gray(" Iterate: ")+chalk.cyan("edit custom")+chalk.gray(" → ")+chalk.cyan("custom")+chalk.gray(" → watch, repeat."))}(g):"edit"===y?"custom"===(g[0]??"").toLowerCase()?await async function(){if(!F())return;const e=s(a(),"icoa-ioailab");t(e,{recursive:!0});const i=K();o(i)||(process.stdout.write(chalk.gray(" Fetching the starter agent…")),await async function(e,o){if(!L)return!1;if("local"===L.transport)try{return r(o,n(e)),!0}catch{return!1}return z(L,T,e,o)}("/opt/ioailab-mj/examples/05_custom_agent.py",i)?console.log(chalk.green(" done.")):(r(i,'"""05_custom_agent.py — your agent for the ICOA-VLA arm.\n\nSubclass BaseAgent and implement act(env, env_ids) -> array [rows, action_dim].\nKeep the constructor argument-free so the replay can render your agent\n(like the SinusoidAgent starter below). Then: edit custom -> custom -> watch.\n"""\nimport numpy as np\n\ntry:\n from icoa_ioailab.agents import BaseAgent\nexcept Exception: # resolved on the GPU box\n BaseAgent = object\n\n\nclass SinusoidAgent(BaseAgent):\n def __init__(self):\n self._t = 0\n\n def act(self, env, env_ids):\n rows = len(env_ids)\n dim = getattr(env, "action_dim", 7)\n self._t += 1\n cmd = 0.1 * np.sin(self._t * 0.2)\n return np.full((rows, dim), cmd, dtype=np.float32)\n'),console.log(chalk.gray(" using a local starter."))));const c=n(i,"utf-8"),g=l(c,".py");if(null===g)return void console.log(chalk.yellow(" Editor cancelled — agent unchanged.")+chalk.gray(" (set $EDITOR to choose your editor)"));r(i,g),process.stdout.write(chalk.gray(" Saving to the box…"));const u=await D(i,A);console.log(u?chalk.green(" done."):chalk.red(" failed.")),console.log(chalk.gray(" Saved → run ")+chalk.cyan("custom")+chalk.gray(" to try it."))}():console.log(chalk.gray(" Usage: ")+chalk.cyan("edit custom")+chalk.gray(" (write your own agent)")):"watch"===y||"open"===y?E&&p(E)?console.log(chalk.gray(" Reopened the last clip.")):console.log(chalk.gray(" No clip yet — ")+chalk.cyan("collect")+chalk.gray(" or ")+chalk.cyan("run")+chalk.gray(" first.")):console.log(chalk.yellow(` Unknown command "${y}" — `)+chalk.cyan("guide")+chalk.gray(" lists everything.")),"continue")}export async function runIoailabStandalone(){if(!await async function(){const{input:e}=await import("@inquirer/prompts"),o=S();if(o){const e=await C(o);if("ok"===e)return!0;if("offline"===e)return console.log(chalk.yellow(" Cannot reach the GPU service to verify your key right now — try again later.")),!1;console.log(chalk.yellow(" Your saved GPU key was not accepted. Enter a valid one below."))}else console.log(chalk.gray(" IOAI Lab is a paid GPU service. Enter the GPU access key issued with your purchase."));for(let o=0;o<3;o++){let t;try{t=await e({message:chalk.bold.magenta("icoa ioailab key>"),theme:{prefix:"",style:{message:e=>e}}})}catch{return!1}const n=t.trim();if(""===n||"exit"===n.toLowerCase()||"q"===n.toLowerCase())return!1;const r=await C(n);if("ok"===r)return G(n),console.log(chalk.green(" ✓ Key accepted — saved to this device. You will not be asked again.")),!0;if("offline"===r)return console.log(chalk.yellow(" Cannot reach the GPU service to verify — try again later.")),!1;console.log(chalk.red(` Key not recognised (${o<2?2-o+" tries left":"no tries left"}).`))}return!1}())return;console.log(),console.log(chalk.bold.magenta(" 🤖 IOAI Lab — Embodied AI practice twin (ICOA-VLA arm)")),console.log(chalk.gray(" The official Team-Challenge sim uses assets we can't hand out — so this is a")),console.log(chalk.gray(" practice twin: the same 5-step workflow, the same Python API, a real arm you drive.")),console.log(chalk.gray(" The scored part — training a diffusion policy from your own demos with robomimic")),console.log(chalk.gray(" (open source) — is byte-for-byte the framework the real contest uses.")),console.log(chalk.gray(" Runs on an ICOA GPU box — nothing installs here; the video opens locally.")),console.log(),console.log(chalk.white(" You will drive the exact contest workflow:")),console.log(" "+chalk.bold.cyan("collect")+chalk.gray(" → ")+chalk.bold.cyan("mimic")+chalk.gray(" → ")+chalk.bold.cyan("train")+chalk.gray(" → ")+chalk.bold.cyan("eval")+chalk.gray(" → ")+chalk.bold.cyan("custom")),console.log(chalk.gray(" v1 is a single task (pick-cube) on a MuJoCo arm; the real contest is multi-task on a")),console.log(chalk.gray(" higher-fidelity simulator — the learning core is the same.")),X();const e=f(),o=null!==e,t=o?e.listeners("line").slice():[];o&&e.removeAllListeners("line");const n=o?e:c({input:process.stdin,output:process.stdout,terminal:!0}),r=o?n.prompt:null;o&&(n.prompt=i.prototype.prompt);const a=()=>{n.setPrompt(chalk.bold.magenta("icoa ioailab> ")),n.prompt()};return new Promise(e=>{const s=i=>{oe(i).then(i=>{"exit"===i?((()=>{if(n.removeListener("line",s),o){r&&(n.prompt=r);for(const e of t)n.on("line",e)}else n.close()})(),e()):a()}).catch(e=>{h(`ioailab error: ${e instanceof Error?e.message:String(e)}`),a()})};n.on("line",s),a()})}
|
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{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as y,resolve as g}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{editTextInEditor as u}from"../lib/editor-spawn.js";import{buildSshArgs as p,leaseConnectProblems as h,parseLeaseResponse as m,queueLine as w}from"../lib/gpu.js";import{shouldExecuteCell as f}from"../lib/ipynb-input.js";import{looksLikeMarkdown as b,renderMarkdown as k}from"../lib/md-term.js";import{NotebookKernel as v,buildRemoteBridgeCommand as $}from"../lib/kernel.js";import{getMainRl as P}from"../lib/main-rl.js";import{logCommand as x}from"../lib/logger.js";import{startLogSync as E,stopLogSync as G}from"../lib/log-sync.js";import{cellPreview as S,parseIpynb as U,parsePercentPy as N,parseRunRange as q,serializeIpynb as C,statusChar as A}from"../lib/notebook-doc.js";import{openFile as O}from"../lib/open-file.js";const j=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(m){m.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 m=>{await async function(m){const j=d(t()),T=y(t(),".icoa","ipynb-out");if(_(),!e(j.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=m?function(o){const l=i(o)?o:g(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")?U(e):N(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.")}}}(m):null,z=J?J.doc:{cells:[],path:null,dirty:!1};let B=new v({venvPython:j.python,venvRoot:j.root}),F=null,H=W(z.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await B.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.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const Q=P(),X=null!==Q,Z=X?Q.listeners("line").slice():[];X&&Q.removeAllListeners("line");const ee=X?Q:a({input:process.stdin,output:process.stdout,terminal:!0}),oe=X?ee.prompt:null;X&&(ee.prompt=r.prototype.prompt),X||E();const ne=[];let le=!1,te=!1,re=!1;const ae=()=>{const e=F?"icoa ipynb ⚡gpu":"icoa ipynb";ee.setPrompt(chalk.bold.cyan(ne.length?`${e} ...> `:`${e}> `)),ee.prompt()};let se=()=>{};const ce=new Promise(e=>{se=e}),ie=async()=>{if(!F)return void console.log(chalk.gray(" not on a GPU kernel."));const e=D();await B.shutdown().catch(()=>{}),e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{B=new v({venvPython:j.python,venvRoot:j.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await B.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},ye=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(F)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=D();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));H||(H=W(z.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await K("lease",e,H??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(w(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await K("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=h(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await K("release",e);const s=H?`${n.dataRoot}/${H}`:n.dataRoot,c=$(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=y(t(),".icoa","gpu","lease-key");try{o(y(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await K("release",e)}i={command:"ssh",args:p(n,r,c)}}const g=new v({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await K("release",e)}await B.shutdown().catch(()=>{}),B=g,F=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),H&&console.log(chalk.gray(` Dataset is already on the box (${H}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await ie():"status"===a||""===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await K("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(F?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${w(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${R()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(t(),".icoa"),{recursive:!0}),l(M(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${M()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},ge=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>z.cells.length?(console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${z.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:z.cells[o-1],idx:o}},de=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!b(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(").")),0)),ue=async t=>{if(t.trim()&&x(`ipynb: ${t.trim()}`),te)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ne.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ne.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(re=!1),"quit"===a||"exit"===a||"back"===a||"q"===a)return z.dirty&&!re?(re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ae()):void await(async()=>{if(ee.removeAllListeners("line"),X||G(),console.log(),F){const e=D();e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await B.shutdown().catch(()=>{}),X){oe&&(ee.prompt=oe);for(const e of Z)ee.on("line",e);ee.prompt(),se()}else se(),ee.close()})();if("clear"===a||"cls"===a)return console.clear(),_(),void ae();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await B.shutdown().catch(()=>{});try{await B.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 ae();if("help"===a||"?"===a)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(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),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 ae();if("guide"===a||"/guide"===a)return(()=>{const o=z.path?c(z.path):process.cwd(),l=W(z.path);let t="",r=!1;try{const e=JSON.parse(n(y(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=z.cells.filter(e=>null!==e.result).length,i=e(y(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(z.path?s(z.path):"new empty notebook")+chalk.gray(` · ${z.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),F?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ae();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ae();if("open"===a)return V&&O(V)?console.log(chalk.gray(" reopening ")+chalk.cyan(V)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ae();if("cells"===a||"ls"===a)return(()=>{if(0===z.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);z.cells.forEach((o,n)=>{const l=A(o),t="✓"===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))} ${t} ${chalk.white(S(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 ae();if("show"===a)return(e=>{const o=ge(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 k(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 ──")),Y(o.cell.result,T)),console.log()}})(d),void ae();if("edit"===a)return(e=>{const o=ge(e);if(!o)return;ee.pause();const n=u(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(ee.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,z.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."))})(d),void ae();if("add"===a)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)"));ee.pause();const l=u(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");ee.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(z.cells.push({kind:n?"markdown":"code",source:t,result:null}),z.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${z.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${z.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ae();if("del"===a||"delete"===a)return(e=>{const o=ge(e);o&&(z.cells.splice(o.idx-1,1),z.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${z.cells.length} left.`)))})(d),void ae();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=ge(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,z.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}.`))})(d,"md"===a?"markdown":"code"),void ae();if("gpu"===a)return te=!0,await ye(d),te=!1,void ae();if("download"===a||"dl"===a)return te=!0,await(async e=>{if(!F)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${F.outDir}/${n}`;let r;try{r=await B.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=H?y(process.cwd(),"icoa-kaggle",H):process.cwd(),c=y(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),H&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${H}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),te=!1,void ae();if("run"===a)return te=!0,await(async e=>{const o=q(e,z.cells.length);if(o)for(const e of o){const n=z.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(S(n,50))+chalk.gray(" ──"));try{n.result=await B.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void L()}if(z.dirty=!0,Y(n.result,T),de(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),void L()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of k(n.source))console.log(e);console.log()}}else console.log(0===z.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"))})(d),te=!1,void ae();if("save"===a)return(e=>{if(0===z.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():g(process.cwd(),e.trim()):z.path?z.path.endsWith(".ipynb")?z.path:`${z.path.replace(/\.[^./]+$/,"")}.ipynb`:g(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(z.cells)),z.path=o,z.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${z.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ae();if(""===r)return void ae()}if(ne.length>0&&I.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ae();if(ne.push(t),!f(ne))return 1!==ne.length||le||(le=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ae();const a=ne.join("\n").replace(/\s+$/,"");if(ne.length=0,""!==a.trim()){te=!0;try{const e=await B.execute(a);z.cells.push({kind:"code",source:a,result:e}),z.dirty=!0,Y(e,T);const o=de(z.cells[z.cells.length-1],z.cells.length);e.ok||o||L()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),L()}te=!1,ae()}else ae()};ee.on("line",e=>{ue(e)}),X||ee.on("close",async()=>{await B.shutdown().catch(()=>{}),process.exit(0)}),ae(),await ce}(m)})}function _(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const I=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function L(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const T="https://practice.icoa2026.au";function R(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):T}function M(){return y(t(),".icoa","gpu-key")}function D(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(M(),"utf-8").trim()||null}catch{return null}}async function K(e,o,n){try{const l=await fetch(`${R()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return m(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function W(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let J=0,V=null;function Y(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(j,"")}`))}else"display"===n.kind&&z(n.data,o)}function z(e,n){if(e["image/png"])try{o(n,{recursive:!0}),J+=1;const t=y(n,`figure-${J}.png`);return l(t,Buffer.from(e["image/png"],"base64")),V=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(O(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
|
|
1
|
+
import{existsSync as e,mkdirSync as o,readFileSync as n,writeFileSync as l}from"node:fs";import{homedir as t}from"node:os";import{Interface as r,createInterface as a}from"node:readline";import{basename as s,dirname as c,isAbsolute as i,join as y,resolve as g}from"node:path";import chalk from"chalk";import{aienvPaths as d}from"../lib/aienv.js";import{editTextInEditor as u}from"../lib/editor-spawn.js";import{buildSshArgs as p,leaseConnectProblems as h,parseLeaseResponse as m,queueLine as w}from"../lib/gpu.js";import{shouldExecuteCell as f}from"../lib/ipynb-input.js";import{looksLikeMarkdown as b,renderMarkdown as k}from"../lib/md-term.js";import{NotebookKernel as v,buildRemoteBridgeCommand as $}from"../lib/kernel.js";import{getMainRl as P}from"../lib/main-rl.js";import{logCommand as x}from"../lib/logger.js";import{startLogSync as E,stopLogSync as G}from"../lib/log-sync.js";import{cellPreview as S,parseIpynb as U,parsePercentPy as N,parseRunRange as q,serializeIpynb as C,statusChar as A}from"../lib/notebook-doc.js";import{openFile as O}from"../lib/open-file.js";const j=new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`,"g");export function registerIpynbCommand(m){m.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 m=>{await async function(m){const j=d(t()),T=y(t(),".icoa","ipynb-out");if(_(),!e(j.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=m?function(o){const l=i(o)?o:g(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")?U(e):N(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.")}}}(m):null,z=J?J.doc:{cells:[],path:null,dirty:!1};let B=new v({venvPython:j.python,venvRoot:j.root}),F=null,H=W(z.path);process.stdout.write(chalk.gray(" Starting Python kernel…"));try{await B.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.bold.white(" ▶ Start here: ")+chalk.bold.cyan("run all")+chalk.gray(" — runs every cell (trains the baseline, writes submission.csv).")),console.log(chalk.gray(" You are already inside the notebook — do ")+chalk.bold.red("not")+chalk.gray(" type ")+chalk.cyan("python file.ipynb")+chalk.gray(". Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(chalk.gray(" Then: ")+chalk.cyan("cells")+chalk.gray(" list · ")+chalk.cyan("edit N")+chalk.gray(" edit · ")+chalk.cyan("save")+chalk.gray(" · ")+chalk.cyan("help")+chalk.gray(" full · ")+chalk.cyan("quit")),console.log(chalk.gray(" Or just type Python and press Enter (blocks continue until a blank line).")),console.log(chalk.bold.yellow(" 🧭 Lost at any point? Type ")+chalk.bold.cyan("guide")+chalk.bold.yellow(" — the full walkthrough + where you are.")),console.log();const Q=P(),X=null!==Q,Z=X?Q.listeners("line").slice():[];X&&Q.removeAllListeners("line");const ee=X?Q:a({input:process.stdin,output:process.stdout,terminal:!0}),oe=X?ee.prompt:null;X&&(ee.prompt=r.prototype.prompt),X||E();const ne=[];let le=!1,te=!1,re=!1;const ae=()=>{const e=F?"icoa ipynb ⚡gpu":"icoa ipynb";ee.setPrompt(chalk.bold.cyan(ne.length?`${e} ...> `:`${e}> `)),ee.prompt()};let se=()=>{};const ce=new Promise(e=>{se=e}),ie=async()=>{if(!F)return void console.log(chalk.gray(" not on a GPU kernel."));const e=D();await B.shutdown().catch(()=>{}),e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped.")),await(async()=>{B=new v({venvPython:j.python,venvRoot:j.root}),process.stdout.write(chalk.gray(" Starting local kernel…"));try{await B.start(),console.log(chalk.green(" ready.")+chalk.gray(" (local CPU — variables were reset)"))}catch{console.log(chalk.red(" failed.")+chalk.gray(" Check ")+chalk.cyan("aienv status"))}})()},ye=async e=>{const[n,...r]=e.trim().split(/\s+/),a=(n??"").toLowerCase();"on"===a||"connect"===a?await(async()=>{if(F)return void console.log(chalk.gray(" already on the GPU kernel — ")+chalk.cyan("gpu status")+chalk.gray(" for time left."));const e=D();if(!e)return console.log(chalk.yellow(" No GPU access key found.")),void console.log(chalk.gray(" Save yours once with ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" (issued by your coach/ICOA)."));H||(H=W(z.path)),process.stdout.write(chalk.gray(" Requesting a GPU box…"));let n=await K("lease",e,H??void 0),r=0;for(;"queued"===n.state&&r<24;)0===r&&console.log(),process.stdout.write(`\r ${chalk.yellow(w(n))} `),await new Promise(e=>setTimeout(e,5e3)),n=await K("status",e),r++;if("queued"===n.state)return console.log(),console.log(chalk.yellow(" Still queued — your place is held server-side.")),void console.log(chalk.gray(" Keep working locally; ")+chalk.cyan("gpu on")+chalk.gray(" again in a few minutes."));if("ready"!==n.state)return void console.log(chalk.red(" failed.")+chalk.gray(` ${n.message??"no lease granted"}`));const a=h(n);if("local"!==n.transport||process.env.ICOA_GPU_SERVER||a.push("local transport from a non-dev broker"),a.length>0)return console.log(chalk.red(" rejected: ")+chalk.gray(a.join(", "))),void await K("release",e);const s=H?`${n.dataRoot}/${H}`:n.dataRoot,c=$(n.python,{ICOA_KAGGLE_DATA:s,ICOA_KAGGLE_OUT:n.outDir},n.outDir);let i;if("local"===n.transport)i={command:"/bin/sh",args:["-c",c]};else{const r=y(t(),".icoa","gpu","lease-key");try{o(y(t(),".icoa","gpu"),{recursive:!0}),l(r,n.keyPem,{mode:384})}catch{return console.log(chalk.red(" could not write the ssh key locally.")),void await K("release",e)}i={command:"ssh",args:p(n,r,c)}}const g=new v({spawnSpec:i,readyTimeoutMs:9e4});process.stdout.write(chalk.gray(" connecting…"));try{await g.start()}catch(o){return console.log(chalk.red(" connect failed.")),console.log(chalk.gray(` ${o instanceof Error?o.message:String(o)}`)),void await K("release",e)}await B.shutdown().catch(()=>{}),B=g,F=n;const d=Math.round((n.timeLeftSec??0)/60);console.log(chalk.bold.green(" ⚡ GPU connected.")),console.log(chalk.gray(` Cells now run on the GPU box · ${d}m left on this lease.`)),console.log(chalk.gray(" Variables were reset — ")+chalk.cyan("run all")+chalk.gray(" to retrain there.")),H&&console.log(chalk.gray(` Dataset is already on the box (${H}) — same cells, no edits.`)),console.log(chalk.gray(" When done: ")+chalk.cyan("download")+chalk.gray(" your submission, then ")+chalk.cyan("gpu off")+chalk.gray("."))})():"off"===a||"disconnect"===a?await ie():"status"===a||""===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));const o=await K("status",e);if("ready"===o.state){const e=Math.round((o.timeLeftSec??0)/60);console.log(chalk.green(` ⚡ GPU lease active · ${e}m left`)+chalk.gray(F?" (this notebook is connected)":" (not connected here — gpu on)"))}else"queued"===o.state?console.log(chalk.yellow(` ${w(o)}`)):"none"===o.state?console.log(chalk.gray(" no GPU lease — ")+chalk.cyan("gpu on")+chalk.gray(" to request one.")):console.log(chalk.yellow(` ${o.message??"GPU broker not reachable"}`))})():"queue"===a||"q"===a?await(async()=>{const e=D();if(!e)return void console.log(chalk.gray(" no GPU key saved — ")+chalk.cyan("gpu key <your-key>"));let o=null;try{const n=await fetch(`${R()}/api/icoa/gpu/queue`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)}),l=await n.json();o=l.data??l}catch{o=null}if(!o||"object"!=typeof o)return void console.log(chalk.yellow(" GPU queue not reachable right now — try again in a moment."));const n="number"==typeof o.boxes?o.boxes:0,l="number"==typeof o.free?o.free:0,t=Array.isArray(o.running)?o.running:[],r=Array.isArray(o.waiting)?o.waiting:[];console.log(),console.log(chalk.bold.cyan(" GPU queue")+chalk.gray(` · ${n} box${1===n?"":"es"} · ${l} free`)),console.log(chalk.bold.white(" ▶ running now:")),0===t.length&&console.log(chalk.gray(" (idle — gpu on takes a box immediately)"));for(const e of t){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.time_left_sec?e.time_left_sec:0,l=Math.floor(n/60),t=String(n%60).padStart(2,"0"),r=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(" ")+chalk.white(o.padEnd(8))+chalk.gray(` ${l}:${t} left`)+r)}console.log(chalk.bold.white(` ⏳ waiting (${r.length}):`)),0===r.length&&console.log(chalk.gray(" (nobody queued)"));for(const e of r){const o="string"==typeof e.label?e.label:"?",n="number"==typeof e.position?e.position:"?",l=e.is_you?chalk.green(" ← you"):"";console.log(chalk.gray(` #${n} `)+chalk.white(o.padEnd(8))+l)}console.log()})():"key"===a?(e=>{const n=e.trim();if(n)try{o(y(t(),".icoa"),{recursive:!0}),l(M(),`${n}\n`,{mode:384}),console.log(chalk.green(" ✓ GPU key saved")+chalk.gray(" — ")+chalk.cyan("gpu on")+chalk.gray(" when you need the box."))}catch{console.log(chalk.red(" could not save the key")+chalk.gray(` (${M()})`))}else console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu key <your-key>"))})(r.join(" ")):console.log(chalk.yellow(" usage: ")+chalk.cyan("gpu on")+chalk.yellow(" · ")+chalk.cyan("gpu off")+chalk.yellow(" · ")+chalk.cyan("gpu status")+chalk.yellow(" · ")+chalk.cyan("gpu queue")+chalk.yellow(" · ")+chalk.cyan("gpu key <k>"))},ge=e=>{const o=Number(e.trim());return!Number.isInteger(o)||o<1||o>z.cells.length?(console.log(0===z.cells.length?chalk.yellow(" no cells yet — type Python or use ")+chalk.cyan("add"):chalk.yellow(` no cell ${e.trim()||"?"} — pick 1-${z.cells.length} (see `)+chalk.cyan("cells")+chalk.yellow(")")),null):{cell:z.cells[o-1],idx:o}},de=(e,o)=>!(!e.result||e.result.ok)&&!(!e.result.outputs.some(e=>"error"===e.kind&&"SyntaxError"===e.ename)||!b(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(").")),0)),ue=async t=>{if(t.trim()&&x(`ipynb: ${t.trim()}`),te)return void(t.trim()&&console.log(chalk.gray(" (busy — wait for the current cell to finish, then retype)")));let r=t.trim();if(0===ne.length&&/^icoa\s+[a-z/]/i.test(r)&&(r=r.replace(/^icoa\s+/i,"")),0===ne.length){const t=r.split(/\s+/),a=(t[0]??"").toLowerCase(),d=r.slice(t[0]?.length??0).trim();if("quit"!==a&&"exit"!==a&&"q"!==a&&(re=!1),"quit"===a||"exit"===a||"back"===a||"q"===a||"menu"===a)return z.dirty&&!re?(re=!0,console.log(chalk.yellow(" unsaved changes — ")+chalk.cyan("save")+chalk.yellow(" first, or type ")+chalk.cyan("quit")+chalk.yellow(" again to discard.")),void ae()):void await(async()=>{if(ee.removeAllListeners("line"),X||G(),console.log(),F){const e=D();e&&await K("release",e),F=null,console.log(chalk.green(" ⚡ GPU lease released")+chalk.gray(" — billing stopped."))}if(console.log(chalk.gray(" Notebook closed. Kernel stopped.")),console.log(),await B.shutdown().catch(()=>{}),X){oe&&(ee.prompt=oe);for(const e of Z)ee.on("line",e);ee.prompt(),se()}else se(),ee.close()})();if("clear"===a||"cls"===a)return console.clear(),_(),void ae();if("restart"===a)return await(async()=>{process.stdout.write(chalk.gray(" Restarting kernel…")),await B.shutdown().catch(()=>{});try{await B.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 ae();if("help"===a||"?"===a)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(" gpu on/off")+chalk.gray(" run cells on a leased GPU box (dataset pre-mounted)")),console.log(chalk.cyan(" gpu status")+chalk.gray(" your lease/queue · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on the GPU now")),console.log(chalk.cyan(" gpu key <k>")+chalk.gray(" save your access key")),console.log(chalk.cyan(" download")+chalk.gray(" pull submission.csv from the GPU box to this machine")),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 ae();if("guide"===a||"/guide"===a)return(()=>{const o=z.path?c(z.path):process.cwd(),l=W(z.path);let t="",r=!1;try{const e=JSON.parse(n(y(o,"meta.json"),"utf-8"));t=e.judge??"",r=!0===e.needs_gpu}catch{}const a=z.cells.filter(e=>null!==e.result).length,i=e(y(o,"submission.csv"));console.log(),console.log(chalk.bold.white(" ═══ 📖 Notebook guide ═══")),console.log(),console.log(chalk.gray(" Where you are: ")+chalk.white(z.path?s(z.path):"new empty notebook")+chalk.gray(` · ${z.cells.length} cells (${a} run) · submission.csv: `)+(i?chalk.green("written ✓"):chalk.yellow("not yet — run all"))),F?console.log(chalk.gray(" ⚡ GPU: ")+chalk.green("connected")+chalk.gray(" — ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on · ")+chalk.cyan("download <file>")+chalk.gray(" pull results")):r&&console.log(chalk.gray(" ⚡ GPU task, not connected — ")+chalk.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.cyan("gpu on")+chalk.gray(" · ")+chalk.cyan("gpu queue")+chalk.gray(" shows who is on")),console.log(),console.log(chalk.bold.white(" The loop:")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan("run all")+chalk.gray(" — trains the baseline, writes submission.csv")),l&&"icoa-holdout"===t?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle submit ${l}`)+chalk.gray(" — scored + ranked on the live board")),console.log(chalk.gray(" 3. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat your score."))):l&&r?(console.log(chalk.gray(" 2. ")+chalk.cyan("download <file>")+chalk.gray(" — pull your results (submission.csv / predictions.zip) off the GPU box")),console.log(chalk.gray(" 3. submit on kaggle.com — the notebook's final cell has the exact steps")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):l?(console.log(chalk.gray(" 2. ")+chalk.cyan("quit")+chalk.gray(", then ")+chalk.cyan(`kaggle check ${l}`)+chalk.gray(" — verifies the file format")),console.log(chalk.gray(" 3. upload submission.csv on kaggle.com — read your public score")),console.log(chalk.gray(" 4. come back, improve the MODEL cell (")+chalk.cyan("cells")+chalk.gray(" lists them, ")+chalk.cyan("edit N")+chalk.gray(" edits) — beat it."))):console.log(chalk.gray(" 2. edit cells (")+chalk.cyan("edit N")+chalk.gray("), re-run, ")+chalk.cyan("save")+chalk.gray(" — this is a free notebook.")),console.log(),console.log(chalk.bold.white(" If it looks stuck:")),console.log(chalk.gray(" · prompt shows ")+chalk.cyan("...>")+chalk.gray(" → you are inside a code block. Press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(".")),console.log(chalk.gray(" · never type ")+chalk.cyan("python file.ipynb")+chalk.gray(" here — you are already inside. Just ")+chalk.bold.cyan("run all")+chalk.gray(".")),console.log(),console.log(chalk.bold.white(" 🤝 AI help: ")+chalk.gray("split the screen ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" · right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" then ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" — live Gemma 3")),console.log(chalk.gray(" All commands: ")+chalk.cyan("help")+chalk.gray(" · leave: ")+chalk.cyan("quit")),console.log()})(),void ae();if("python"===a||"python3"===a)return console.log(chalk.gray(" You're already inside the notebook kernel — no need to run python.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("run all")+chalk.gray(" to run every cell, or ")+chalk.cyan("guide")+chalk.gray(" for the basics.")),void ae();if("open"===a)return V&&O(V)?console.log(chalk.gray(" reopening ")+chalk.cyan(V)):console.log(chalk.gray(" no figure yet — plot something (e.g. matplotlib) first.")),void ae();if("cells"===a||"ls"===a)return(()=>{if(0===z.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);z.cells.forEach((o,n)=>{const l=A(o),t="✓"===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))} ${t} ${chalk.white(S(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 ae();if("show"===a)return(e=>{const o=ge(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 k(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 ──")),Y(o.cell.result,T)),console.log()}})(d),void ae();if("edit"===a)return(e=>{const o=ge(e);if(!o)return;ee.pause();const n=u(o.cell.source,"markdown"===o.cell.kind?".md":".py");if(ee.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,z.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."))})(d),void ae();if("add"===a)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)"));ee.pause();const l=u(n?"\x3c!-- markdown cell — write notes/headings, save & exit --\x3e\n":"",n?".md":".py");ee.resume();const t=null===l?"":l.replace(/^<!-- markdown cell[^\n]*-->\n?/,"").replace(/\s+$/,"");t?(z.cells.push({kind:n?"markdown":"code",source:t,result:null}),z.dirty=!0,console.log(chalk.green(` ✓ added ${n?"markdown ":""}cell ${z.cells.length}`)+chalk.gray(" — ")+chalk.cyan(`run ${z.cells.length}`)+chalk.gray(n?" to render it.":" to execute."))):console.log(chalk.gray(" nothing added."))})(d),void ae();if("del"===a||"delete"===a)return(e=>{const o=ge(e);o&&(z.cells.splice(o.idx-1,1),z.dirty=!0,console.log(chalk.gray(` deleted cell ${o.idx} — ${z.cells.length} left.`)))})(d),void ae();if(("md"===a||"py"===a)&&/^\d+$/.test(d))return((e,o)=>{const n=ge(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,z.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}.`))})(d,"md"===a?"markdown":"code"),void ae();if("gpu"===a)return te=!0,await ye(d),te=!1,void ae();if("download"===a||"dl"===a)return te=!0,await(async e=>{if(!F)return void console.log(chalk.gray(" local kernel — your files are already on this machine (no download needed)."));const n=e.trim()||"submission.csv",t=n.startsWith("/")?n:`${F.outDir}/${n}`;let r;try{r=await B.fetchFile(t)}catch(e){return console.log(chalk.yellow(` could not fetch ${t}: `)+chalk.gray(e instanceof Error?e.message:String(e))),void console.log(chalk.gray(" (run the submission cell first — it writes into the GPU workspace)"))}const a=H?y(process.cwd(),"icoa-kaggle",H):process.cwd(),c=y(a,s(n));try{o(a,{recursive:!0}),l(c,r)}catch{return void console.log(chalk.yellow(" could not write the file here — check directory permissions."))}console.log(chalk.green(" ✓ downloaded ")+chalk.white(c)+chalk.gray(` (${r.length} bytes)`)),H&&"submission.csv"===s(n)&&console.log(chalk.gray(" verify it: ")+chalk.cyan(`kaggle check ${H}`)+chalk.gray(" — then upload on Kaggle yourself."))})(d),te=!1,void ae();if("run"===a)return te=!0,await(async e=>{const o=q(e,z.cells.length);if(o)for(const e of o){const n=z.cells[e-1];if("markdown"!==n.kind){console.log(chalk.gray(` ── run cell ${e}: `)+chalk.white(S(n,50))+chalk.gray(" ──"));try{n.result=await B.execute(n.source)}catch(e){return console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),void L()}if(z.dirty=!0,Y(n.result,T),de(n,e),!n.result.ok){const n=e!==o[o.length-1];return console.log(chalk.yellow(` ✗ cell ${e} raised${n?" — stopping here.":"."}`)+chalk.gray(" Fix it (")+chalk.cyan(`edit ${e}`)+chalk.gray(") and re-run.")),void L()}}else{console.log(chalk.gray(` ── cell ${e} (markdown) ──`));for(const e of k(n.source))console.log(e);console.log()}}else console.log(0===z.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"))})(d),te=!1,void ae();if("save"===a)return(e=>{if(0===z.cells.length)return void console.log(chalk.yellow(" nothing to save — the notebook is empty."));let o;o=e.trim()?i(e.trim())?e.trim():g(process.cwd(),e.trim()):z.path?z.path.endsWith(".ipynb")?z.path:`${z.path.replace(/\.[^./]+$/,"")}.ipynb`:g(process.cwd(),"notebook.ipynb"),o.endsWith(".ipynb")||(o+=".ipynb");try{l(o,C(z.cells)),z.path=o,z.dirty=!1,console.log(chalk.green(" ✓ saved ")+chalk.cyan(o)+chalk.gray(` (${z.cells.length} cells)`))}catch(e){console.log(chalk.red(" save failed: ")+chalk.gray(e instanceof Error?e.message:String(e)))}})(d),void ae();if(""===r)return void ae()}if(ne.length>0&&I.has(r.toLowerCase()))return console.log(chalk.gray(" (⏸ you are inside a multi-line block — press Enter on an ")+chalk.bold.white("empty line")+chalk.gray(" to run it; then ")+chalk.cyan(r.toLowerCase().replace(/^\//,""))+chalk.gray(" will work. This line was not added to the block.)")),void ae();if(ne.push(t),!f(ne))return 1!==ne.length||le||(le=!0,console.log(chalk.gray(" (multi-line block started — keep typing; an empty line runs it)"))),void ae();const a=ne.join("\n").replace(/\s+$/,"");if(ne.length=0,""!==a.trim()){te=!0;try{const e=await B.execute(a);z.cells.push({kind:"code",source:a,result:e}),z.dirty=!0,Y(e,T);const o=de(z.cells[z.cells.length-1],z.cells.length);e.ok||o||L()}catch(e){console.log(chalk.red(" Kernel error: ")+chalk.gray(e instanceof Error?e.message:String(e))),L()}te=!1,ae()}else ae()};ee.on("line",e=>{ue(e)}),X||ee.on("close",async()=>{await B.shutdown().catch(()=>{}),process.exit(0)}),ae(),await ce}(m)})}function _(){console.log(),console.log(chalk.bold.white(" ICOA Notebook ")+chalk.gray("· in-terminal Python · AI/ML notebook arena")),console.log(chalk.gray(" ─────────────────────────────────────────────"))}const I=new Set(["guide","/guide","help","?","quit","exit","back","menu","cells","run all"]);function L(){console.log(chalk.gray(" 🧭 stuck? type ")+chalk.cyan("guide")+chalk.gray(" for the basics · ")+chalk.cyan("help")+chalk.gray(" for every command."))}const T="https://practice.icoa2026.au";function R(){return process.env.ICOA_GPU_SERVER?process.env.ICOA_GPU_SERVER.replace(/\/$/,""):T}function M(){return y(t(),".icoa","gpu-key")}function D(){if(process.env.ICOA_GPU_KEY)return process.env.ICOA_GPU_KEY.trim();try{return n(M(),"utf-8").trim()||null}catch{return null}}async function K(e,o,n){try{const l=await fetch(`${R()}/api/icoa/gpu/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n?{key:o,task:n}:{key:o}),signal:AbortSignal.timeout(2e4)});return m(await l.json())}catch{return{state:"error",message:"GPU broker not reachable"}}}function W(e){const o=e?.match(/icoa-kaggle[/\\]([a-z0-9-]+)[/\\]/);return o?o[1]:null}let J=0,V=null;function Y(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(j,"")}`))}else"display"===n.kind&&z(n.data,o)}function z(e,n){if(e["image/png"])try{o(n,{recursive:!0}),J+=1;const t=y(n,`figure-${J}.png`);return l(t,Buffer.from(e["image/png"],"base64")),V=t,console.log(chalk.magenta(" 🖼 figure saved → ")+chalk.cyan(t)),void(O(t)?console.log(chalk.gray(" opening in your image viewer… (type ")+chalk.cyan("open")+chalk.gray(" to reopen)")):console.log(chalk.gray(" open it with your file browser (inline images need a graphical viewer).")))}catch{}e["text/plain"]&&console.log(chalk.white(` ${e["text/plain"]}`))}
|
package/dist/commands/learn.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execSync as t,spawn as n}from"node:child_process";import{getMainRl as r}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as l,handleAi4ioaiMessage as s,startAi4ioaiChat as a}from"./ai4ioai.js";import{existsSync as i,mkdirSync as c,readFileSync as d,writeFileSync as u}from"node:fs";import{dirname as g,join as m}from"node:path";import{fileURLToPath as y}from"node:url";import{loadCurriculumById as p,validateEAToken as h,syncProgress as f,syncCardFeedback as w}from"../lib/learn-curricula.js";import{normalizeTokenBody as b}from"../lib/token-format.js";import{fetchMyScores as k,streamLearnTutor as $,submitPqs as v,viewPqsTop as C,viewHonors as A}from"../lib/learn-ai.js";import{contestReset as I,contestStart as _,contestSubmit as T,fetchGate as E,timeLeft as S}from"../lib/learn-contest.js";import{getConfig as x,saveConfig as M}from"../lib/config.js";import{loadLearnState as P,saveLearnState as L,newLearnState as q,updateStreak as O,markCardComplete as D,recordMCQ as R,recordCheck as N,markPracticalComplete as j,addAchievement as W}from"../lib/learn-state.js";import{renderWelcome as F,renderKnowledgeCard as B,renderMCQCard as J,renderMCQFeedback as U,renderPracticalCard as z,renderPracticalSuccess as V,renderSimDemoCard as Z,renderMilestone as H,renderArenaTaskCard as K,renderComingSoonCard as Q,renderStatus as Y,renderPhaseComplete as X,renderCurriculumComplete as G,setLearnAiEnabled as ee,setLearnPqsViewCards as oe,renderHonorWall as te}from"../lib/learn-render.js";import{printError as ne}from"../lib/ui.js";export function registerLearnCommand(re){re.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async re=>{re&&re.trim()||(console.log(),console.log(chalk.gray(" No token given — starting free 11-card demo (")+chalk.bold.green("LEARNDEMO01")+chalk.gray(").")),console.log(chalk.gray(" Full curriculum: ")+chalk.bold.yellow("learn <your token>")+chalk.gray(" (2 letters + 8 chars) — from your country team leader.")),console.log(),re="LEARNDEMO01");let le=re.trim().toUpperCase(),se=null;const ae=/^[A-Z0-9]+DEMO01$/i.test(le),ie=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(le);let ce=!1,de=!1;if(ae)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),se=await p(le,le);else if(ie){console.log(),console.log(chalk.gray(" Validating token..."));let e=await h(le);if(!e.ok){const o=b(le);if(o!==le){const t=await h(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${le} → ${o}`)),e=t,le=o)}}if(!e.ok)return ne(`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"):"")),ce=!0===e.aiEnabled,de=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),se=await p(e.curriculumId||"LEARNDEMO01",le),!se)return ne(`Could not open a learn curriculum for token '${le}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${le}`)+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 ${le}`)+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(!se)return ne(`Unknown learn token: ${le}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Every track has a free demo — ask for its name if you were not given one.")),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 ue=P(),ge=!1;try{ue&&ue.token===le?O(ue):(ue=q(le,se.id,se.totalCards),ge=!0),L(ue),F(se,ue,ge)}catch{return ne("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 ${le}`)+chalk.gray(".")),void console.log()}const me=r(),ye=null!==me,pe=ye?me.listeners("line").slice():[];ye&&me.removeAllListeners("line");const he=ye?me:o({input:process.stdin,output:process.stdout,terminal:!0}),fe=ye?he.prompt:null;ye&&(he.prompt=e.prototype.prompt);const we=()=>{ye&&fe&&(he.prompt=fe)},be=()=>{he.setPrompt(_e?chalk.bold.green(`icoa ${l()}> `):chalk.bold.cyan(Ae?"icoa learn ai> ":"icoa learn> ")),he.prompt()};let ke=null,$e=null,ve=null,Ce=null,Ae=!1,Ie=!1,_e=!1;const Te=new Map,Ee=()=>{let e=Te.get(ue.currentCard);return e||(e=[],Te.set(ue.currentCard,e)),e};let Se=!1;const xe=new Set;let Me=!1,Pe=0;const Le=()=>(x().language||"en").toLowerCase().startsWith("zh");ee(ce),oe(xe);const qe=[];let Oe=null;const De=new Promise(e=>{Oe=e}),Re=()=>{const e=Oe;Oe=null,e?.()},Ne="1"===process.env.ICOA_LEARN_EMBEDDED,je=e=>se.cards.find(o=>o.number===e);let We=null,Fe=null;const Be=!le.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(le),Je=async()=>{if(!Be)return;const e=await E(le);e.ok&&e.data&&(We=e.data)},Ue=e=>{const o=se.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},ze=e=>{if(!de||!We)return null;const o=Ue(e);if(o<=We.unlocked_through_phase)return null;const t=We.phases.find(e=>e.phase===We.unlocked_through_phase),n=[chalk.yellow(Le()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${We.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${We.unlocked_through_phase}'s core tasks first:`)];return t?.contest&&!t.contest.passed&&n.push(chalk.gray(Le()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest")),t?.research&&!t.research.passed&&n.push(chalk.gray(Le()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},Ve=async e=>de?null===ze(e)?null:(await Je(),ze(e)):null;de&&await Je();const Ze=async e=>{const o=se.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=se.modules.find(e=>e.number===o.number+1);let n;if(ce){const e=await k({token:le,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}Be&&await Je();const r=We?.phases.find(e=>e.phase===o.number);return X(se,ue,o,t,n,r),!0},He=()=>{Me=!0,console.log(chalk.gray(Le()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},Ke=()=>{const e=je(ue.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":B(e,se),e.check?(ve=e.number,Pe=Date.now()):(D(ue,e.number),L(ue));break;case"mcq":J(e,se),ke=e.number;break;case"practical":z(e,se),$e=e.number;break;case"sim_demo":Z(e,se),D(ue,e.number),L(ue);break;case"milestone":H(e,se),W(ue,e.badge),D(ue,e.number),L(ue);break;case"arena_task":K(e,se),D(ue,e.number),L(ue);break;case"coming_soon":Q(e,se),D(ue,e.number),L(ue)}},Qe=()=>{le.endsWith("DEMO01")?console.log(chalk.yellow(Le()?" 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(Le()?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Le()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},Ye=async(e,o)=>{if(ce){Ie=!0;try{console.log(),console.log(chalk.gray("deep"===o?Le()?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Le()?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await $({token:le,cardNumber:ue.currentCard,question:e,mode:o,history:Ee().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(Le()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(Ee().push({role:"user",content:e},{role:"assistant",content:r.answer}),null!=r.spent&&null!=r.cap&&r.spent/r.cap>.8&&console.log(chalk.gray(` (${Le()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Le()?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==ve&&console.log(chalk.gray(Le()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Ie=!1}}else Qe()},Xe=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],Ge=async e=>{const o=e.trim().toLowerCase();if(!Ie){if(null!==Ce){const o=e.trim(),t=Ce;if(Ce=null,""===o)console.log(chalk.gray(Le()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=Pe>0?Date.now()-Pe:void 0;await w(le,{curriculum_id:se.id,card_number:t,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(Le()?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Le()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void be()}if(Se){Se=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Ie=!0;try{console.log(),console.log(chalk.gray(Le()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await v({token:le,cardNumber:ue.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Le()?"评审暂不可用。":"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(Le()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(Le()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Le()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Le()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Le()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(Le()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=Le()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(Le()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Le()?` 第 ${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 Xe(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(Le()?" 改进提问: ":" 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(` (${Le()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?xe.add(ue.currentCard):xe.delete(ue.currentCard);const o=await A({token:le,curriculumId:se.id,cardNumber:ue.currentCard});o.ok&&o.totals&&o.chapters&&(te({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log())}finally{Ie=!1}})():(console.log(chalk.gray(Le()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==ve&&(console.log(chalk.gray(Le()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void be()}if(Me)return Me=!1,Ke(),void be();if(o){if(_e)return"exit"===await s(e.trim())&&(_e=!1),void be();if(Ae){if(["q","quit","exit","back","b","menu"].includes(o))return Ae=!1,console.log(chalk.gray(Le()?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void be();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&await Ye(n,t?"fast":"deep"),void be()}if("tmux"===o||o.startsWith("tmux ")){try{t("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(Le()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void be()}return await new Promise(o=>{const t=process.stdin,r=!!t.isTTY&&!!t.isRaw;if(he.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const l=n(e.trim(),{shell:!0,stdio:"inherit"}),s=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&r)try{t.setRawMode(!0)}catch{}he.resume(),o()};l.on("close",s),l.on("error",s)}),console.log(),void be()}if("ai4ioai"===o||"/ai4ioai"===o)return await a()&&(_e=!0),void be();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!ce)return Qe(),void be();const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){Ae=!0;const e=je(ue.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Le()?"AI 导师":"AI tutor")+(o?chalk.gray(Le()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Le()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void be()}return await Ye(n,t?"fast":"deep"),void be()}if("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research ")){if(!ce)return Qe(),void be();const e=je(ue.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Le()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Le()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Le()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Le()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Le()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Le()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Le()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),Se=!0,void be()}if("/view"===o)return ce?(await(async()=>{Ie=!0;try{console.log();const e=await C({token:le,cardNumber:ue.currentCard});if(!e.ok)return console.log(chalk.yellow(` ${e.message||(Le()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===e.code&&xe.delete(ue.currentCard),void console.log();null!=e.myRank&&e.myRank<=3&&xe.add(ue.currentCard),console.log(chalk.bold.white(Le()?` 🏆 本卡 Top-3 提问 — 第 ${ue.currentCard} 张 · ${e.entrants??0} 人上榜`:` 🏆 Top-3 prompts — card ${ue.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 t=Xe(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(" "+e))}),0===o.questions.length&&console.log(chalk.gray(Le()?" (无可显示的提问)":" (no questions to show)"))}console.log()}finally{Ie=!1}})(),void be()):(Qe(),void be());if("/honors"===o||"honors"===o)return ae?(console.log(),console.log(chalk.gray(Le()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void be()):(await(async()=>{Ie=!0;try{console.log();const e=await A({token:le,curriculumId:se.id,cardNumber:ue.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Le()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Le()?` 🏆 本卡实时 Top-3 — 第 ${ue.currentCard} 张`:` 🏆 Live top-3 — card ${ue.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(Le()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));console.log(),te({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log()}finally{Ie=!1}})(),void be());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return Y(se,ue),void be();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(x().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void be();const t=se.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,l=r?n:"en";return M({language:l}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(l)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),ve=null,ke=null,$e=null,Ce=null,Me=!1,Se=!1,Ke(),void be()}if("sim"===o){const e=je(ue.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=g(y(import.meta.url)),o=[m(e,"..","..","panda","mujoco-launcher.py"),m(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(i(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),n("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void be()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void be())}if("bookmark"===o){const e=ue.currentCard;return ue.bookmarks.includes(e)||ue.bookmarks.push(e),L(ue),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void be()}if("e"===o)return Ce=ue.currentCard,console.log(chalk.gray(Le()?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void be();if("back"===o||"b"===o)return ue.currentCard>1&&(ue.currentCard-=1),ke=null,$e=null,ve=null,L(ue),Ke(),void be();if("contest"===o||"contest start"===o||"contest status"===o||"contest reset"===o){if(!Be)return console.log(chalk.yellow(Le()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void be();const e=Ue(ue.currentCard);if("contest reset"===o){const o=await I(le,e);return o.ok?(console.log(chalk.yellow(Le()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`)),Fe=null):console.log(chalk.red(` ✗ ${o.message||"reset failed"}`)),void be()}console.log(chalk.gray(Le()?" 连接判分赛…":" Contacting contest server…"));const t=await _(le,e);if(!t.ok||!t.data)return"no_contest"===t.code?console.log(chalk.gray(Le()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${t.message||"contest unavailable"}`)),void be();const n=t.data,r=m(process.cwd(),"icoa-contest",`${se.id}-phase${e}`);c(r,{recursive:!0}),n.problems.forEach((e,o)=>{const t=[`# ${e.title} (${e.id})`,"",e.statement,""];let n=0;for(const o of e.samples??[])n+=1,t.push(`## Sample ${n}`,"","Input:","```",o.in,"```","Output:","```",o.out,"```","");u(m(r,`problem-${e.id}.md`),t.join("\n"));const l=m(r,`sol-${e.id}.py`);if(!i(l)){const t=(e.samples??[])[0],n=t?`# Sample: input ${JSON.stringify(t.in)} -> output ${JSON.stringify(t.out)}\n`:"";u(l,`# ${e.title}\n# Full statement: problem-${e.id}.md (same folder)\n`+n+"# Read from stdin (input()), print the answer to stdout, no prompts.\n"+`# When ready, back in icoa: submit ${o+1}\n\n`)}}),Fe={phase:e,dir:r,data:n};const l=S(n.deadline);console.log(),console.log(chalk.bold.cyan(` ⚖ ${n.title||(Le()?`阶段 ${e} 判分赛`:`Phase ${e} contest`)}`)+chalk.gray(Le()?` · 第 ${n.attempt} 次尝试${n.resumed?"(续)":""}`:` · attempt ${n.attempt}${n.resumed?" (resumed)":""}`)),console.log(chalk.white(Le()?` ${n.n} 题 · AC ${n.need} 题过关 · 限时 ${n.duration_minutes} 分钟`:` ${n.n} problems · AC ${n.need} to pass · ${n.duration_minutes} min`)+(l?chalk.bold.yellow(Le()?` ⏱ 剩 ${l}`:` ⏱ ${l} left`):chalk.red(Le()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))),console.log(),n.problems.forEach((e,o)=>{const t=n.solved.includes(e.id);console.log(chalk.gray(` ${o+1}. `)+(t?chalk.green("✓ "):chalk.gray("· "))+chalk.white(e.title)+chalk.gray(` (${e.id})`))}),console.log(),console.log(chalk.gray(Le()?" 题面与答题文件已写入:":" Statements + solution files written to:")),console.log(chalk.bold.white(` ${r}`)),console.log();const s=n.problems.findIndex(e=>!n.solved.includes(e.id))+1||1;return console.log(chalk.white(Le()?" 怎么做题(三步循环):":" How to work (3-step loop):")),console.log(chalk.gray(Le()?" ① 读题 ":" ① Read ")+chalk.cyan(`problem-…q${s}.md`)+chalk.gray(Le()?" (任意编辑器/预览打开)":" (open in any editor/viewer)")),console.log(chalk.gray(Le()?" ② 写解 ":" ② Solve ")+chalk.cyan(`sol-…q${s}.py`)+chalk.gray(Le()?" (VS Code / nano / 记事本都行,存盘)":" (VS Code / nano / any editor, save it)")),console.log(chalk.gray(Le()?" ③ 提交 ":" ③ Submit ")+chalk.bold.green(`submit ${s}`)+chalk.gray(Le()?" ← 回到这里输入,立刻出判分":" ← type here, verdict comes back live")),console.log(),console.log(chalk.gray(Le()?" submit <题号> <文件路径> 可指定别的文件 · contest 随时回看此列表 · contest reset 重开计时":" submit <id> <file> for a custom path · contest re-shows this list · contest reset restarts the clock")),void be()}if("submit"===o)return console.log(chalk.yellow(Le()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(Le()?" 例如 submit 1 判第 1 题(默认判 sol-…q1.py;submit 1 <路径> 判指定文件)":" e.g. submit 1 grades problem 1 (defaults to sol-…q1.py; submit 1 <path> for a custom file)")),Fe||console.log(chalk.gray(Le()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void be();if(o.startsWith("submit ")){const e=o.split(/\s+/);let t=e[1]||"";const n=e[2];if(!Fe)return console.log(chalk.yellow(Le()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void be();const r=Fe.data.problems,l=parseInt(t,10);if(Number.isInteger(l)&&l>=1&&l<=r.length&&!r.some(e=>e.id===t)&&(t=r[l-1].id),!r.some(e=>e.id===t))return console.log(chalk.yellow(Le()?` 未知题号 ${t} — 输入 contest 查看题目列表。`:` Unknown problem ${t} — type contest to list problems.`)),void be();const s=n||m(Fe.dir,`sol-${t}.py`);let a;try{a=d(s,"utf-8")}catch{return console.log(chalk.red(Le()?` 读不到文件: ${s}`:` Cannot read file: ${s}`)),void be()}console.log(chalk.gray(Le()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const i=await T(le,Fe.phase,t,a);if(!i.ok||!i.data)return"no_active_session"===i.code?console.log(chalk.yellow(Le()?" 没有进行中的计时(可能已超时)— 输入 contest 查看/重开。":" No live timed attempt (time may be up) — type contest.")):console.log(chalk.red(` ✗ ${i.message||"judging failed"}`)),void be();const c=i.data;if(c.already_ac)console.log(chalk.green(Le()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===c.verdict)console.log(chalk.bold.green(" ✓ AC")+chalk.gray(` · ${c.total_tests??"?"} tests · ${c.time_ms??"?"}ms`)),Fe.data.solved.includes(t)||Fe.data.solved.push(t);else{const e="TLE"===c.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${c.verdict}`)+chalk.gray(c.test?Le()?` · 挂在第 ${c.test} 个用例(过 ${c.passed_tests}/${c.total_tests})`:` · failed test ${c.test} (passed ${c.passed_tests}/${c.total_tests})`:""))}c.late&&console.log(chalk.yellow(Le()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const u=S(c.deadline||"");if(console.log(chalk.white(Le()?` 进度: ${c.ac_count}/${c.need} 题(共 ${c.n})`:` Progress: ${c.ac_count}/${c.need} AC (of ${c.n})`)+(u?chalk.gray(` · ⏱ ${u}`):"")),c.passed&&!c.late)console.log(chalk.bold.green(Le()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Je();else if(!c.late){const e=r.findIndex(e=>!Fe.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Le()?" 下一题: ":" Next: ")+chalk.bold.green(`submit ${e+1}`)+chalk.gray(` ${r[e].title}`))}return void be()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>se.totalCards)return console.log(chalk.yellow(` Card number must be 1..${se.totalCards}. Try: `)+chalk.bold.green("card 1")),void be();const n=await Ve(t);return n?(console.log(n),void be()):(ue.currentCard=t,ke=null,$e=null,ve=null,L(ue),Ke(),void be())}if(null!==ve&&["y","yes","n","no"].includes(o)){const e=je(ve);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-Pe;D(ue,e.number),N(ue,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),L(ue);const{renderCheckFeedback:l}=await import("../lib/learn-render.js");if(l(e,t,n,!1),qe.push(f(le,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),ve=null,e.solution&&e.solution.length>0)return void be();if(ue.currentCard<se.totalCards){const e=ue.currentCard,o=await Ve(e+1);if(o)return await Ze(e),console.log(o),void be();ue.currentCard+=1,L(ue),await Ze(e)?He():Ke(),be()}else G(se,ue),be();return}}if(null!==ke&&["a","b","c","d"].includes(o)){const e=je(ke);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(R(ue,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),D(ue,e.number),L(ue),U(e,t,n,ue),qe.push(f(le,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),ke=null,n)if(ue.currentCard<se.totalCards){const e=await Ve(ue.currentCard+1);if(e)return console.log(e),void be();ue.currentCard+=1,L(ue),Ke()}else G(se,ue),be();else be();return}}if(null!==$e){if("done"===o){const e=je($e);if(e&&"practical"===e.type)return j(ue,e.number),D(ue,e.number),L(ue),V(e),$e=null,void be()}if("skip"===o)return D(ue,$e),L(ue),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),$e=null,void be()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==ke)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void be();if(null!==$e)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void be();if(null!==ve)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void be();const e=ue.currentCard,o=e<se.totalCards?await Ve(e+1):null;return o?(await Ze(e),console.log(o),void be()):(ue.currentCard+=1,L(ue),ue.currentCard>se.totalCards?G(se,ue):await Ze(e)?He():Ke(),void be())}if(null!==ve)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void be();if(null!==ke)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void be();if(null!==$e)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void be();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")),be()}else if(qe.length>0&&await Promise.race([Promise.allSettled(qe),new Promise(e=>setTimeout(e,5e3))]),console.log(),console.log(chalk.gray(" Saved. See you next session.")),console.log(chalk.gray(" Streak: ")+chalk.yellow(`🔥 ${ue.streakDays} day(s)`)),console.log(),ye){he.removeAllListeners("line"),we();for(const e of pe)he.on("line",e);he.prompt(),Re()}else he.removeAllListeners("line"),he.close();else if(qe.length>0&&await Promise.race([Promise.allSettled(qe),new Promise(e=>setTimeout(e,3e3))]),he.removeAllListeners("line"),we(),ye||!Ne){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(ye?he:void 0),Re()}else he.close()}else be()}};he.on("line",e=>{Ge(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.")),be()})}),ye||he.on("close",async()=>{qe.length>0&&await Promise.race([Promise.allSettled(qe),new Promise(e=>setTimeout(e,5e3))]),Ne?Re():process.exit(0)});try{Ke(),be();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(ne("Could not render this card — the curriculum may be malformed."),ye){he.removeAllListeners("line"),we();for(const e of pe)he.on("line",e);he.prompt()}else he.close();Re()}await De}),re.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),l=await p(e),s=Date.now()-o;if(l){const e=l.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(l).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${s.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
|
1
|
+
import chalk from"chalk";import{Interface as e,createInterface as o}from"node:readline";import{execFileSync as t,execSync as n,spawn as r}from"node:child_process";import{getMainRl as s}from"../lib/main-rl.js";import{ai4ioaiPromptLabel as l,handleAi4ioaiMessage as a,startAi4ioaiChat as i}from"./ai4ioai.js";import{existsSync as c,mkdirSync as d,readFileSync as u,writeFileSync as g}from"node:fs";import{dirname as m,join as y}from"node:path";import{fileURLToPath as p}from"node:url";import{loadCurriculumById as h,validateEAToken as f,syncProgress as b,syncCardFeedback as w}from"../lib/learn-curricula.js";import{normalizeTokenBody as $}from"../lib/token-format.js";import{fetchMyScores as k,setNickname as v,streamLearnTutor as C,submitPqs as A,viewPqsTop as _,viewHonors as I}from"../lib/learn-ai.js";import{contestReset as x,contestStart as T,contestSubmit as E,fetchGate as M,timeLeft as R}from"../lib/learn-contest.js";import{getConfig as S,saveConfig as P}from"../lib/config.js";import{loadLearnState as q,saveLearnState as L,newLearnState as j,updateStreak as D,markCardComplete as O,recordMCQ as N,recordCheck as W,markPracticalComplete as Y,addAchievement as B}from"../lib/learn-state.js";import{renderWelcome as F,renderKnowledgeCard as U,renderMCQCard as z,renderMCQFeedback as H,renderPracticalCard as J,renderPracticalSuccess as Z,renderSimDemoCard as K,renderMilestone as Q,renderArenaTaskCard as V,renderComingSoonCard as X,renderStatus as G,renderPhaseComplete as ee,renderCurriculumComplete as oe,setLearnAiEnabled as te,setLearnHonorRanks as ne,setLearnPqsViewCards as re,renderHonorWall as se}from"../lib/learn-render.js";import{printError as le}from"../lib/ui.js";export function registerLearnCommand(ae){ae.command("learn [token]").description("Enter learn mode (free <TRACK>DEMO01 demo, or team-issued token for full curriculum)").action(async ae=>{ae&&ae.trim()||(console.log(),console.log(chalk.gray(" No token given — starting free 11-card demo (")+chalk.bold.green("LEARNDEMO01")+chalk.gray(").")),console.log(chalk.gray(" Full curriculum: ")+chalk.bold.yellow("learn <your token>")+chalk.gray(" (2 letters + 8 chars) — from your country team leader.")),console.log(),ae="LEARNDEMO01");let ie=ae.trim().toUpperCase(),ce=null;const de=/^[A-Z0-9]+DEMO01$/i.test(ie),ue=/^[A-Z]{2}[A-Z0-9]{8}$/i.test(ie);let ge=!1,me=!1;if(de)console.log(),console.log(chalk.gray(" Loading demo curriculum...")),ce=await h(ie,ie);else if(ue){console.log(),console.log(chalk.gray(" Validating token..."));let e=await f(ie);if(!e.ok){const o=$(ie);if(o!==ie){const t=await f(o);t.ok&&(console.log(chalk.yellow(` Corrected look-alike characters: ${ie} → ${o}`)),e=t,ie=o)}}if(!e.ok)return le(`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"):"")),ge=!0===e.aiEnabled,me=!0===e.gated,console.log(chalk.gray(" Loading curriculum… (downloads ~1 MB; up to a minute on slow venue Wi-Fi — please wait)")),ce=await h(e.curriculumId||"LEARNDEMO01",ie),!ce)return le(`Could not open a learn curriculum for token '${ie}'.`),console.log(),console.log(chalk.gray(" If this is an ")+chalk.bold.yellow("EXAM token")+chalk.gray(", start it with ")+chalk.bold.green(`exam ${ie}`)+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 ${ie}`)+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(!ce)return le(`Unknown learn token: ${ie}`),console.log(),console.log(chalk.gray(" Available tokens:")),console.log(chalk.gray(" ")+chalk.bold.green("<TRACK>DEMO01")+chalk.gray(" free demo, anyone can use — e.g. ")+chalk.bold.green("LEARNDEMO01")),console.log(chalk.gray(" ")+chalk.bold.yellow("2 letters + 8 chars")+chalk.gray(" full curriculum (issued by team leader)")),console.log(),console.log(chalk.gray(" Every track has a free demo — ask for its name if you were not given one.")),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 ye=q(),pe=!1;try{ye&&ye.token===ie?D(ye):(ye=j(ie,ce.id,ce.totalCards),pe=!0),L(ye),F(ce,ye,pe)}catch{return le("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 ${ie}`)+chalk.gray(".")),void console.log()}const he=s(),fe=null!==he,be=fe?he.listeners("line").slice():[];fe&&he.removeAllListeners("line");const we=fe?he:o({input:process.stdin,output:process.stdout,terminal:!0}),$e=fe?we.prompt:null;fe&&(we.prompt=e.prototype.prompt);const ke=()=>{fe&&$e&&(we.prompt=$e)},ve=()=>{we.setPrompt(qe?chalk.bold.green(`icoa ${l()}> `):Ee?chalk.bold.yellow("icoa arena> "):chalk.bold.cyan(xe?"icoa learn ai> ":"icoa learn> ")),we.prompt()};let Ce=null,Ae=null,_e=null,Ie=null,xe=!1,Te=!1,Ee=!1,Me=null,Re=!1,Se=0,Pe=!1,qe=!1;const Le=new Map,je=()=>{let e=Le.get(ye.currentCard);return e||(e=[],Le.set(ye.currentCard,e)),e};let De=!1;const Oe=new Set;let Ne=!1,We=0;const Ye=()=>(S().language||"en").toLowerCase().startsWith("zh");te(ge),re(Oe);const Be=new Map;ne(Be);const Fe=[];let Ue=null;const ze=new Promise(e=>{Ue=e}),He=()=>{const e=Ue;Ue=null,e?.()},Je="1"===process.env.ICOA_LEARN_EMBEDDED,Ze=e=>ce.cards.find(o=>o.number===e);let Ke=null,Qe=null;const Ve=!ie.endsWith("DEMO01")&&/^[A-Z]{2}[A-Z0-9]{8}$/i.test(ie),Xe=async()=>{if(!Ve)return;const e=await M(ie);e.ok&&e.data&&(Ke=e.data)},Ge=e=>{const o=ce.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);return o?o.number:1},eo=e=>{if(!me||!Ke)return null;const o=Ge(e);if(o<=Ke.unlocked_through_phase)return null;const t=Ke.phases.find(e=>e.phase===Ke.unlocked_through_phase),n=[chalk.yellow(Ye()?` 🔒 阶段 ${o} 未解锁 — 先完成阶段 ${Ke.unlocked_through_phase} 的核心任务:`:` 🔒 Phase ${o} is locked — finish phase ${Ke.unlocked_through_phase}'s core tasks first:`)];if(t?.contest&&!t.contest.passed){const e=t.contest.slots??[];if(e.length>0)for(const o of e)o.passed||n.push(chalk.gray(Ye()?` ⚔ 练习赛 ${Ke.unlocked_through_phase}-${o.slot}: 最好 ${o.best_ac}/${o.n} AC,需 ${o.need} — 输入 `:` ⚔ arena ${Ke.unlocked_through_phase}-${o.slot}: best ${o.best_ac}/${o.n} AC, need ${o.need} — type `)+chalk.bold.green(`contest ${o.slot}`));else n.push(chalk.gray(Ye()?` ⚖ 判分赛: 最好 ${t.contest.best_ac}/${t.contest.n} AC,需 ${t.contest.need} — 输入 `:` ⚖ contest: best ${t.contest.best_ac}/${t.contest.n} AC, need ${t.contest.need} — type `)+chalk.bold.green("contest"))}return t?.research&&!t.research.passed&&n.push(chalk.gray(Ye()?` ⭐ 提问研究: ${t.research.good_cards}/${t.research.need_cards} 卡达到 ${t.research.min_score} 分 — 用 /ai 研究,再 /submit 评分`:` ⭐ research: ${t.research.good_cards}/${t.research.need_cards} cards at ${t.research.min_score}+ — research with /ai, then /submit`)),n.join("\n")},oo=async e=>me?null===eo(e)?null:(await Xe(),eo(e)):null;me&&await Xe();const to=async e=>{const o=ce.modules.find(o=>o.cardRange[1]===e);if(!o)return!1;const t=ce.modules.find(e=>e.number===o.number+1);let n;if(ge){const e=await k({token:ie,cardLo:o.cardRange[0],cardHi:o.cardRange[1]}).catch(()=>({ok:!1,scores:void 0}));n=e.ok?e.scores??[]:void 0}Ve&&await Xe();const r=Ke?.phases.find(e=>e.phase===o.number);return ee(ce,ye,o,t,n,r),!0},no=()=>{Ne=!0,console.log(chalk.gray(Ye()?" 按 Enter 进入下一阶段…":" Press Enter to continue to the next phase…"))},ro=()=>{Me=null;const e=Ze(ye.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":U(e,ce),e.check?(_e=e.number,We=Date.now()):(O(ye,e.number),L(ye));break;case"mcq":z(e,ce),Ce=e.number;break;case"practical":J(e,ce),Ae=e.number;break;case"sim_demo":K(e,ce),O(ye,e.number),L(ye);break;case"milestone":Q(e,ce),B(ye,e.badge),O(ye,e.number),L(ye);break;case"arena_task":V(e,ce),O(ye,e.number),L(ye);break;case"coming_soon":X(e,ce),O(ye,e.number),L(ye)}so(e.number)},so=e=>{if(!me||!Ve||!Ke)return;const o=ce.modules.find(o=>e>=o.cardRange[0]&&e<=o.cardRange[1]);if(!o)return;const t=e-o.cardRange[0]+1;if(t%4!=0)return;const n=t/4,r=Ke.phases.find(e=>e.phase===o.number),s=r?.contest?.slots?.find(e=>e.slot===n);if(!s||s.passed)return;const l=chalk.bold.yellow(" ║ ");console.log(chalk.bold.yellow(" ╔═══════════════════════════════════════")),console.log(l+chalk.bold.white(`⚔ ${Ye()?"练习赛":"PY Arena"} ${o.number}-${n}`)),console.log(l+chalk.white(Ye()?"卡片你已学完 — 现在证明它。输入指令那刻计时开始。":"You learned the cards — now prove it. The clock starts when you type the command.")),console.log(l+chalk.gray(Ye()?`${s.n} 题 · AC ${s.need} 过关 · 限时 ${s.duration_minutes} 分钟 · 无限重开`:`${s.n} problems · AC ${s.need} to pass · ${s.duration_minutes} min · unlimited retries`)),console.log(l+chalk.gray("▸ ")+chalk.bold.green(`contest ${n}`)+chalk.gray(Ye()?" 开赛 ":" enter ")+chalk.gray("▸ ")+chalk.bold.green("ok")+chalk.gray(Ye()?" 先继续学(检查点不锁段内翻卡)":" keep studying (checkpoints never lock cards)")),console.log(chalk.bold.yellow(" ╚═══════════════════════════════════════")),console.log()},lo=()=>{ie.endsWith("DEMO01")?console.log(chalk.yellow(Ye()?" 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(Ye()?" 此 token 未开通 AI 导师(高级功能)。":" This token does not include the AI tutor (premium).")),console.log(chalk.gray(Ye()?" 找你的领队 / 协调人换开通 AI 的 token。":" Ask your team leader / coordinator for an AI-enabled token."))),console.log()},ao=async(e,o)=>{if(ge){Te=!0;try{console.log(),console.log(chalk.gray("deep"===o?Ye()?" 🤖 AI 导师(深度思考中,思考过程为灰色小字)…":" 🤖 AI tutor (deepthink — reasoning shown in gray)…":Ye()?" 🤖 AI 导师(快速模式)…":" 🤖 AI tutor (quick mode)…")),console.log();let t=!1,n=!1;const r=await C({token:ie,cardNumber:ye.currentCard,question:e,mode:o,history:je().slice(-8)},e=>{"reasoning"===e.kind?(t||(process.stdout.write(" "),t=!0),process.stdout.write(chalk.dim(e.text.replace(/\n/g,"\n ")))):(n||(process.stdout.write(t?"\n\n ":" "),n=!0),process.stdout.write(chalk.white(e.text.replace(/\n/g,"\n "))))});(t||n)&&console.log(),r.ok?r.offtopic?(console.log(),console.log(chalk.yellow(Ye()?" (被判定与本卡主题无关 — 跑题的问题不会被回答,并会拉低本卡的提问评分)":" (judged unrelated to this card — off-topic questions aren't answered and will lower this card's prompt score)"))):(je().push({role:"user",content:e},{role:"assistant",content:r.answer}),null!=r.spent&&null!=r.cap&&r.spent/r.cap>.8&&console.log(chalk.gray(` (${Ye()?"AI 额度":"AI budget"}: ${Math.round(r.spent/1e3)}k / ${Math.round(r.cap/1e3)}k tokens)`))):(console.log(),console.log(chalk.yellow(` ${r.message||(Ye()?"AI 导师暂不可用。":"AI tutor unavailable.")}`))),null!==_e&&console.log(chalk.gray(Ye()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()}finally{Te=!1}}else lo()},io=e=>e.match(/.{1,64}(\s|$)/g)?.map(e=>e.trim())??[e],co=async()=>{Te=!0;try{console.log();const e=await I({token:ie,curriculumId:ce.id,cardNumber:ye.currentCard});if(!e.ok||!e.totals||!e.chapters)return console.log(chalk.yellow(` ${e.message||(Ye()?"荣誉榜暂时不可用。":"Honor board unavailable right now.")}`)),void console.log();if(console.log(chalk.bold.white(Ye()?` 🏆 本卡实时 Top-3 — 第 ${ye.currentCard} 张`:` 🏆 Live top-3 — card ${ye.currentCard}`)),e.board&&0!==e.board.length)for(const o of e.board){const e="green"===o.tier?"🟢":"blue"===o.tier?"🔵":"yellow"===o.tier?"🟡":"🔴";console.log(chalk.white(` ${o.icon} `)+chalk.bold.cyan(o.name||`Rank ${o.rank}`)+chalk.white(` · ${o.score} `)+e+(o.me?chalk.bold.magenta(Ye()?" (你)":" (you)"):""))}else console.log(chalk.gray(Ye()?" (本卡还没有人上榜)":" (no one has medaled on this card yet)"));e.mine?(Be.set(ye.currentCard,e.mine.rank),console.log(chalk.white(Ye()?" 你: ":" You: ")+chalk.bold.yellow(Ye()?`第 ${e.mine.rank} 名 / 共 ${e.mine.entrants} 人`:`rank ${e.mine.rank} of ${e.mine.entrants}`)+chalk.gray(` · best ${e.mine.best_score}`)+chalk.gray(Ye()?` · 本卡还可评 ${e.mine.submissions_left} 次`:` · ${e.mine.submissions_left} graded attempt(s) left here`)+(e.nickname?chalk.gray(" · ")+chalk.bold.cyan(e.nickname):""))):ge&&console.log(chalk.gray(Ye()?" 你还没上榜 — /ai 研究本卡,再 /submit 评分。":" Not on this board yet — research with /ai, then /submit.")),console.log(),se({totals:e.totals,chapters:e.chapters,floor:e.floor}),console.log(),!0===e.board?.some(e=>e.me)?console.log(chalk.bold.yellow(Ye()?" 🎁 前三专属奖励: ":" 🎁 Top-3 reward: ")+chalk.bold.green("view 1")+chalk.gray(" / ")+chalk.bold.green("view 2")+chalk.gray(" / ")+chalk.bold.green("view 3")+chalk.gray(Ye()?" — 看这三位怎么问 AI 的":" — read how the top 3 asked the AI")):console.log(chalk.gray(Ye()?` 🔒 进前三(${e.floor??80} 分以上)解锁: 查看前三名的提问方式`:` 🔒 Reach the top-3 (${e.floor??80}+) to unlock: reading how the top 3 asked`)),Me="honors",console.log(chalk.gray(" ")+chalk.bold.cyan("back")+chalk.gray(Ye()?" 返回卡片":" returns to the card")),console.log()}finally{Te=!1}},uo=(e,o)=>{const t=[];for(const n of e.split("\n")){if(""===n.trim()){t.push("");continue}let e="";for(const r of n.split(/\s+/))e&&e.length+1+r.length>o?(t.push(e),e=r):e=e?`${e} ${r}`:r;e&&t.push(e)}return t},go=e=>Qe.data.solved.includes(e.id)?"✅":Qe.tried.has(e.id)?"❌":"⬜",mo=()=>{const e=Qe.data,o=R(e.deadline),t=e.solved.length,n=Math.min(20,Math.round(t/Math.max(1,e.need)*20));console.log(),console.log(chalk.bold.yellow(` ⚔ ${e.title||"PY Arena"}`)+chalk.gray(Ye()?` · 第 ${e.slot}/${e.group_count} 组 · 第 ${e.attempt} 次尝试${e.resumed?"(续)":""}`:` · group ${e.slot}/${e.group_count} · attempt ${e.attempt}${e.resumed?" (resumed)":""}`)),console.log((o?chalk.bold.yellow(` ⏱ ${o}`):chalk.red(Ye()?" ⏱ 已超时 — contest reset 重开":" ⏱ time up — contest reset to retry"))+chalk.gray(" ")+chalk.green("▓".repeat(n))+chalk.gray("░".repeat(20-n))+chalk.white(` ${t}/${e.need} AC`)+chalk.gray(Ye()?`(共 ${e.n} 题)`:` (of ${e.n})`)),console.log(),e.problems.forEach((e,o)=>{console.log(chalk.gray(` ${String(o+1).padStart(2)} `)+go(e)+chalk.white(` ${e.title}`))}),console.log(),yo()},yo=()=>{console.log(chalk.gray(Ye()?" /read <n> 读题 · /edit <n> 写码(vi) · /run <n> 样例自测 · /debug <n> 自由调试 · /submit <n> 判分":" /read <n> statement · /edit <n> code (vi) · /run <n> sample check · /debug <n> free run · /submit <n> judge")),console.log(chalk.gray(Ye()?" /list 花名册 · 直接敲题号 = 读题 · ":" /list roster · a bare number reads it · ")+chalk.bold.cyan("back")+chalk.gray(Ye()?" 返回课程":" returns to the lesson")),console.log()},po=e=>{const o=parseInt(e,10),t=Qe.data.problems;return!Number.isInteger(o)||o<1||o>t.length?(console.log(chalk.yellow(Ye()?` 题号要在 1..${t.length}。`:` Problem number must be 1..${t.length}.`)),null):{p:t[o-1],n:o}},ho=e=>{const o=po(e);if(!o)return;const{p:t,n:n}=o;console.log(),console.log(chalk.bold.white(` ${go(t)} ${t.title}`)),console.log();for(const e of uo(t.statement,66))console.log(chalk.white(` ${e}`));let r=0;for(const e of t.samples??[]){r+=1,console.log(),console.log(chalk.gray(Ye()?` 样例 ${r} 输入:`:` Sample ${r} input:`));for(const o of e.in.split("\n"))console.log(chalk.cyan(` ${o}`));console.log(chalk.gray(Ye()?" 应输出:":" Expected output:"));for(const o of e.out.split("\n"))console.log(chalk.green(` ${o}`))}0===(t.samples??[]).length&&(console.log(),console.log(chalk.gray(Ye()?" (本题无样例 — 读题后直接作答)":" (no sample on this one — read carefully and solve)"))),console.log(),console.log(chalk.white(Ye()?" 四步:":" Four steps:")+chalk.gray((Ye()," ① "))+chalk.bold.green(`/edit ${n}`)+chalk.gray(Ye()?" 写码(vi:i 编辑 · Esc · :wq 存盘退出)":" write (vi: i to edit · Esc · :wq saves)")),console.log(chalk.gray(" ② ")+chalk.bold.green(`/run ${n}`)+chalk.gray(Ye()?" 样例自测 ③ ":" sample check ③ ")+chalk.bold.green(`/debug ${n}`)+chalk.gray(Ye()?" 自己输入调试(可选) ④ ":" free-input run (optional) ④ ")+chalk.bold.green(`/submit ${n}`)+chalk.gray(Ye()?" 判分":" judge")),console.log()},fo=async(e,o)=>{await new Promise(t=>{const n=process.stdin,s=!!n.isTTY&&!!n.isRaw;if(we.pause(),n.isTTY&&"function"==typeof n.setRawMode)try{n.setRawMode(!1)}catch{}const l=r(e,o,{stdio:"inherit",cwd:Qe.dir}),a=()=>{if(n.isTTY&&"function"==typeof n.setRawMode&&s)try{n.setRawMode(!0)}catch{}we.resume(),t()};l.on("close",a),l.on("error",a)})},bo=async e=>{const o=e.trim().toLowerCase(),s=Ee&&o.startsWith("/")?o.slice(1):o;if(!Te){if(null!==Ie){const o=e.trim(),t=Ie;if(Ie=null,""===o)console.log(chalk.gray(Ye()?" 已取消(未提交)。":" Cancelled (nothing submitted)."));else{const e=We>0?Date.now()-We:void 0;await w(ie,{curriculum_id:ce.id,card_number:t,feedback_text:o,time_on_card_ms:e})?console.log(chalk.green(Ye()?" ✓ 已收到,谢谢帮助完善这张卡。":" ✓ Thanks — your report was recorded.")):console.log(chalk.yellow(Ye()?" ⚠ 未能送达服务器 — 这条报告没有保存,请稍后再按 e 重试。":" ⚠ Could not reach the server — this report was NOT saved. Try e again later."))}return console.log(),void ve()}if(Re){const o=e.trim();if(!o)return Re=!1,console.log(chalk.gray(Ye()?" 已跳过 — 榜单继续显示匿名 Rank(下次上榜还会再问)。":" Skipped — boards keep showing you as an anonymous Rank (asked again next time you medal).")),console.log(),void ve();const t=await v({token:ie,nickname:o});if(t.ok)Re=!1,console.log(chalk.bold.green(Ye()?` ✓ 竞技昵称已设定: ${t.nickname}`:` ✓ Nickname set: ${t.nickname}`)+chalk.gray(Ye()?"(不可更改 — 榜单从现在起显示它)":" (permanent — boards show it from now on)"));else{Se+=1;const e="taken"===t.code?Ye()?"已被占用":"already taken":"bad_charset"===t.code?Ye()?"格式不对(英文开头,英文+数字,3-16 位)":"bad format (letters+digits, starts with a letter, 3-16 chars)":"rejected"===t.code?Ye()?"未通过审核":"did not pass review":t.message||"error";if(!(Se>=3||"judge_unavailable"===t.code||"already_set"===t.code||"not_on_board"===t.code))return console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ye()?" — 换一个试试(回车跳过):":" — try another (Enter to skip):")),void ve();Re=!1,console.log(chalk.yellow(` ✗ ${e}`)+chalk.gray(Ye()?" — 先跳过,下次上榜再起。":" — skipped for now; try again next time you medal."))}return console.log(),void ve()}if(De){De=!1;const o=e.trim().toLowerCase();return"y"===o||"yes"===o?await(async()=>{Te=!0;try{console.log(),console.log(chalk.gray(Ye()?" 📊 提交中 — Panda 正在评审你的提问(通常几十秒,最长一两分钟,请稍候)…":" 📊 Submitting — Panda is reviewing how you asked (usually well under two minutes)…"));const e=await A({token:ie,cardNumber:ye.currentCard});if(console.log(),!e.ok)return console.log(chalk.yellow(` ${e.message||(Ye()?"评审暂不可用。":"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(Ye()?" 提问评分 ":" Prompt score ")+o(`${e.score??0} / 100`)+chalk.gray(" "+(e=>{switch(e){case"green":return"🟢 "+(Ye()?"你把 AI 当作被审视的研究伙伴":"you used the AI as a research partner");case"blue":return"🔵 "+(Ye()?"你把 AI 当作实验助手":"you used the AI as a lab assistant");case"yellow":return"🟡 "+(Ye()?"你把 AI 当作讲师":"you used the AI as a lecturer");default:return"🔴 "+(Ye()?"你把 AI 当作答案机":"you used the AI as an answer machine")}})(e.tier))),e.manipulation&&console.log(chalk.red(Ye()?" ⚠ 检测到试图操纵评分,分数已按规则大幅降低":" ⚠ an attempt to manipulate the score was detected — the score was reduced sharply")),null!=e.rank&&null!=e.entrants){const o=!0===e.inTop3,t=Ye()?` 本卡排名 #${e.rank} / ${e.entrants}`:` Rank on this card: #${e.rank} of ${e.entrants}`;console.log((o?chalk.bold.green(t):chalk.white(t))+(o?chalk.bold.magenta(Ye()?" — 进入 TOP 3!输入 /view 看另两名的提问":" — TOP 3! type /view to read the other top prompts"):""))}if(console.log(chalk.gray(Ye()?` 第 ${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 io(e.feedback))console.log(chalk.white(" "+o))}e.improve&&(console.log(),console.log(chalk.cyan(Ye()?" 改进提问: ":" 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(` (${Ye()?"AI 额度":"AI budget"}: ${Math.round(e.spent/1e3)}k / ${Math.round(e.cap/1e3)}k tokens)`)),console.log()})(e),!0===e.inTop3?Oe.add(ye.currentCard):Oe.delete(ye.currentCard),"number"==typeof e.rank&&Be.set(ye.currentCard,e.rank);const o=await I({token:ie,curriculumId:ce.id,cardNumber:ye.currentCard});o.ok&&o.totals&&o.chapters&&(se({totals:o.totals,chapters:o.chapters,floor:o.floor}),console.log()),!0===e.inTop3&&o.ok&&null==o.nickname&&!de&&(Re=!0,Se=0,console.log(chalk.bold.yellow(Ye()?" 🎉 你上榜了!":" 🎉 You made the board!")+chalk.white(Ye()?" 给自己起个竞技昵称,榜单用它代替匿名 Rank:":" Pick a competition nickname for the boards:")),console.log(chalk.gray(Ye()?" 英文开头,英文+数字,3-16 位 · 不建议用真名 · 一旦设定不可改 · 回车跳过":" Letters+digits, starts with a letter, 3-16 chars · real names discouraged · permanent · Enter skips")))}finally{Te=!1}})():(console.log(chalk.gray(Ye()?" 已取消(未提交,不消耗次数)。":" Cancelled — nothing submitted, no attempt used.")),console.log()),null!==_e&&(console.log(chalk.gray(Ye()?" (本卡的判断题还等着你作答 — y 或 n)":" (the y/n check on this card is still waiting — answer y or n)")),console.log()),void ve()}if(Ne)return Ne=!1,ro(),void ve();if(o){if(qe)return"exit"===await a(e.trim())&&(qe=!1),void ve();if(xe){if(["q","quit","exit","back","b","menu"].includes(o))return xe=!1,console.log(chalk.gray(Ye()?" 已退出 AI 导师,回到卡片。":" Left the AI tutor — back to the card.")),console.log(),void ve();const t=e.trim().startsWith("!"),n=t?e.trim().slice(1).trim():e.trim();return n&&(await ao(n,t?"fast":"deep"),console.log(chalk.gray(Ye()?" (q = 返回卡片 · ! 开头 = 快答)":" (q = back to card · prefix ! = quick answer)"))),void ve()}if(Ee&&Qe){if("back"===o||"b"===o||"exit"===o)return Ee=!1,console.log(chalk.gray(Ye()?" 已离开竞技场,回到课程。":" Left the arena — back to the lesson.")),ro(),void ve();if(/^\d+$/.test(o))return ho(o),void ve();const e=/^\/?(read|open|edit|run|debug|list)(?:\s+(\S+))?$/.exec(o);if(e){const[,o,r]=e;return"list"===o?mo():r?"read"===o||"open"===o?ho(r):"edit"===o?await(async e=>{const o=po(e);if(o){try{n("command -v vi",{stdio:"ignore"})}catch{return console.log(chalk.yellow(Ye()?" 找不到 vi — 用任意编辑器打开:":" vi not found — open with any editor:")),void console.log(chalk.bold.white(` ${y(Qe.dir,`sol-${o.n}.py`)}`))}console.log(chalk.gray(Ye()?" vi 三键: i 进入编辑 · Esc 退出编辑 · :wq 存盘离开":" vi survival: i = edit · Esc = stop editing · :wq = save and leave")),await fo("vi",["-c","set tabstop=4 shiftwidth=4 expandtab",`sol-${o.n}.py`]),console.log(chalk.gray(Ye()?" 回到竞技场 — ":" Back in the arena — ")+chalk.bold.green(`/run ${o.n}`)+chalk.gray(Ye()?" 自测样例。":" to self-check the sample.")),console.log()}})(r):"run"===o?(e=>{const o=po(e);if(!o)return;const{p:n,n:r}=o,s=y(Qe.dir,`sol-${r}.py`);if(!c(s))return void console.log(chalk.yellow(Ye()?` 还没有 sol-${r}.py — 先 /edit ${r}。`:` No sol-${r}.py yet — /edit ${r} first.`));const l=(n.samples??[])[0];if(!l)return void console.log(chalk.gray(Ye()?` 本题无样例(设计如此)— 用 /debug ${r} 自己试,或直接 /submit ${r}。`:` This problem ships no sample (by design) — try /debug ${r}, or go straight to /submit ${r}.`));let a="";try{a=t("python3",[s],{input:l.in.endsWith("\n")?l.in:l.in+"\n",timeout:1e4,encoding:"utf-8"})}catch(e){const o=e;if(o.killed)console.log(chalk.yellow(Ye()?" ⏱ 超过 10 秒 — 检查死循环/效率。":" ⏱ Over 10s — check for infinite loops / efficiency."));else{console.log(chalk.red(Ye()?" ✗ 程序报错:":" ✗ Your program crashed:"));for(const e of String(o.stderr||"").trim().split("\n").slice(-6))console.log(chalk.gray(` ${e}`))}return}const i=a.replace(/\r\n/g,"\n").trimEnd(),d=l.out.replace(/\r\n/g,"\n").trimEnd();console.log(chalk.gray(Ye()?" 你的输出:":" Your output:"));for(const e of(i||"(empty)").split("\n"))console.log(chalk.cyan(` ${e}`));console.log(chalk.gray(Ye()?" 样例应输出:":" Sample expects:"));for(const e of d.split("\n"))console.log(chalk.green(` ${e}`));i===d?console.log(chalk.bold.green(Ye()?" ✓ 样例通过!":" ✓ Sample passed!")+chalk.gray(Ye()?" 正式判分: ":" Official judging: ")+chalk.bold.green(`/submit ${r}`)):console.log(chalk.yellow(Ye()?" ✗ 与样例不符 — ":" ✗ Does not match — ")+chalk.bold.green(`/edit ${r}`)+chalk.gray(Ye()?" 改完再 /run。":" then /run again.")),console.log()})(r):"debug"===o&&await(async e=>{const o=po(e);if(!o)return;const t=y(Qe.dir,`sol-${o.n}.py`);c(t)?(console.log(chalk.gray(Ye()?" 自由调试:程序等你输入 — 想试什么边界值都行 · Ctrl-D 结束输入 · 跑完自动回竞技场":" Free run: the program waits for YOUR input — try any edge case · Ctrl-D ends input · returns here after")),console.log(),await fo("python3",[`sol-${o.n}.py`]),console.log(),console.log(chalk.gray(Ye()?" 回到竞技场。":" Back in the arena.")),console.log()):console.log(chalk.yellow(Ye()?` 还没有 sol-${o.n}.py — 先 /edit ${o.n}。`:` No sol-${o.n}.py yet — /edit ${o.n} first.`))})(r):console.log(chalk.yellow(Ye()?` 用法: /${o} <题号>`:` Usage: /${o} <problem number>`)+chalk.gray(Ye()?" (花名册: /list)":" (roster: /list)")),void ve()}if("contest"===o||"/contest"===o)return mo(),void ve();if("submit"!==s&&!s.startsWith("submit ")&&!o.startsWith("contest ")&&"contest reset"!==o&&"quit"!==o&&"q"!==o&&"exit"!==o&&"menu"!==o&&"menu confirm"!==o)return console.log(chalk.gray(Ye()?" 竞技场命令: /read /edit /run /debug /submit /list · back 返回课程":" Arena verbs: /read /edit /run /debug /submit /list · back returns to the lesson")),void ve()}if("tmux"===o||o.startsWith("tmux ")){try{n("command -v tmux",{stdio:"ignore"})}catch{return console.log(chalk.yellow(" tmux is not installed yet.")),console.log(chalk.gray(" Install it with ")+chalk.bold.cyan("darwin"===process.platform?"brew install tmux":"sudo apt install tmux")+chalk.gray(Ye()?" — 或 quit 回到 icoa> 后运行 ":" — or quit to icoa> and run ")+chalk.bold.cyan("env setup")+chalk.gray(".")),console.log(),void ve()}return await new Promise(o=>{const t=process.stdin,n=!!t.isTTY&&!!t.isRaw;if(we.pause(),t.isTTY&&"function"==typeof t.setRawMode)try{t.setRawMode(!1)}catch{}const s=r(e.trim(),{shell:!0,stdio:"inherit"}),l=()=>{if(t.isTTY&&"function"==typeof t.setRawMode&&n)try{t.setRawMode(!0)}catch{}we.resume(),o()};s.on("close",l),s.on("error",l)}),console.log(),void ve()}if("ai4ioai"===o||"/ai4ioai"===o)return await i()&&(qe=!0),void ve();if("/ai"===o||"/ai!"===o||o.startsWith("/ai ")||o.startsWith("/ai! ")){if(!ge)return lo(),void ve();Pe||(Pe=!0,console.log(),console.log(chalk.bold.cyan(Ye()?" 🧭 研究模式":" 🧭 Research mode")),console.log(chalk.gray(Ye()?" 围绕本卡内容向 AI 提出真问题;问完输入 /submit,把你的整段对话送去评审":" Ask the AI real questions about THIS card. When you are done, /submit sends your")),console.log(chalk.gray(Ye()?" (每卡最多 2 次)。AI 时代,提出好问题是核心能力 — 我们评的就是「你怎么问」。":" whole conversation for review (max 2 per card). In the AI era, asking good questions")),Ye()||console.log(chalk.gray(" is a core skill — HOW you ask is exactly what gets scored.")));const t=o.startsWith("/ai!"),n=e.trim().slice(t?4:3).trim();if(!n){xe=!0;const e=Ze(ye.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 🤖 AI ")+chalk.bold.white(Ye()?"AI 导师":"AI tutor")+(o?chalk.gray(Ye()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ye()?" 直接输入问题(默认深度思考) · ! 开头 = 快答 · q = 返回卡片":" Type a question (deepthink by default) · prefix ! = quick answer · q = back to card")),console.log(),void ve()}return await ao(n,t?"fast":"deep"),void ve()}if(!Ee&&("/submit"===o||o.startsWith("/submit ")||"/research"===o||o.startsWith("/research "))){if(!ge)return lo(),void ve();const e=Ze(ye.currentCard),o=e?e.title??e.badge??"":"";return console.log(),console.log(chalk.bold.magenta(" 📊 ")+chalk.bold.white(Ye()?"Panda 提问评审":"Panda's prompt review")+(o?chalk.gray(Ye()?` — 主题「${o}」`:` — topic “${o}”`):"")),console.log(chalk.gray(Ye()?" 评的是你在本卡上「怎么问 AI」— 你与 /ai 导师的整段对话会被":" It scores HOW you asked the AI on this card — your whole /ai")),console.log(chalk.gray(Ye()?" 整体评审,给出分数、名次和改进建议。":" conversation is reviewed for a score, a rank, and advice.")),console.log(chalk.gray(Ye()?" 每张卡最多 2 次评分;评出的最好成绩进本卡 Top-3 榜。":" Max 2 graded attempts per card; your best enters the card’s top-3 board.")),console.log(),console.log(chalk.white(Ye()?" 确认提交本卡对话评分?":" Submit this card’s conversation for grading?")+chalk.gray(Ye()?" y = 提交 · 其他 = 取消":" y = submit · anything else = cancel")),console.log(),De=!0,void ve()}if(!Ee&&("/view"===o||"view"===o||/^\/?view [1-3]$/.test(o))){if(!ge)return lo(),void ve();const e=/^\/?view ([1-3])$/.exec(o);return await(async e=>{Te=!0;try{console.log();const o=await _({token:ie,cardNumber:ye.currentCard});if(!o.ok)return console.log(chalk.yellow(` ${o.message||(Ye()?"暂时无法查看。":"View unavailable right now.")}`)),"not_top3"===o.code&&Oe.delete(ye.currentCard),void console.log();null!=o.myRank&&o.myRank<=3&&Oe.add(ye.currentCard);const t=(o.top3??[]).filter(o=>null==e||o.rank===e);console.log(chalk.bold.white(Ye()?` 🏆 ${e?`第 ${e} 名的提问`:"本卡 Top-3 提问"} — 第 ${ye.currentCard} 张 · ${o.entrants??0} 人上榜`:` 🏆 ${e?`Rank ${e}'s prompts`:"Top-3 prompts"} — card ${ye.currentCard} · ${o.entrants??0} entrant(s)`)),null!=e&&0===t.length&&console.log(chalk.gray(Ye()?` (第 ${e} 名暂时空缺)`:` (rank ${e} is currently empty)`));for(const e of t){const o="green"===e.tier?"🟢":"blue"===e.tier?"🔵":"yellow"===e.tier?"🟡":"🔴";console.log(),console.log(chalk.bold.cyan(` ── ${e.name||`Rank ${e.rank}`}`)+(e.me?chalk.bold.magenta(Ye()?" (你)":" (you)"):"")+chalk.white(` · ${e.score}`)+` ${o}`),e.questions.forEach((e,o)=>{const t=io(e);console.log(chalk.gray(` Q${o+1} `)+chalk.white(t[0]??""));for(const e of t.slice(1))console.log(chalk.white(" "+e))}),0===e.questions.length&&console.log(chalk.gray(Ye()?" (无可显示的提问)":" (no questions to show)"))}console.log(),Me="view",console.log(chalk.gray((Ye()," "))+chalk.bold.cyan("back")+chalk.gray(Ye()?" 回荣誉榜 · view 1/2/3 看某一名":" returns to the honor board · view 1/2/3 for one rank")),console.log()}finally{Te=!1}})(e?parseInt(e[1],10):void 0),void ve()}if("/honors"===o||"honors"===o)return de?(console.log(),console.log(chalk.gray(Ye()?" 荣誉榜属于正式 learn token — 用团队签发的 token 进来即可查看和参赛。":" The honor board belongs to full learn tokens — join with a team-issued token to view and compete.")),console.log(),void ve()):(await co(),void ve());if("menu"!==o&&"menu confirm"!==o)if("quit"!==o&&"exit"!==o&&"q"!==o){if("status"===o)return G(ce,ye),void ve();if("lang"===o||o.startsWith("lang ")){const e=o.slice(4).trim();if(!e)return console.log(chalk.gray(" 当前语言 / current: ")+chalk.white(S().language||"en")+chalk.gray(" · ")+chalk.bold.green("lang zh")+chalk.gray(" / ")+chalk.bold.green("lang en")),void ve();const t=ce.cards.some(e=>null!=e._zh),n=e.toLowerCase().startsWith("zh")?"zh":e.toLowerCase(),r="en"===n||"zh"===n&&t,s=r?n:"en";return P({language:s}),r?console.log(chalk.green(" ✓ ")+chalk.gray("语言 / language → ")+chalk.white(s)):console.log(chalk.yellow(" ! ")+chalk.gray(`${e} 本课暂无翻译,已用英文 / not available — using English`)),_e=null,Ce=null,Ae=null,Ie=null,Ne=!1,De=!1,ro(),void ve()}if("sim"===o){const e=Ze(ye.currentCard);return e&&"sim_demo"===e.type?(function(e){const o=function(){const e=m(p(import.meta.url)),o=[y(e,"..","..","panda","mujoco-launcher.py"),y(e,"..","..","..","panda","mujoco-launcher.py")];for(const e of o)if(c(e))return e;return null}();if(!o)return console.log(chalk.yellow(" MuJoCo launcher not found.")),console.log(chalk.gray(" Get it from: https://github.com/newaipanda/ICOA_CLI/blob/main/panda/mujoco-launcher.py")),void console.log(chalk.gray(" Or use the sandbox-vla docker image (Phase 3)."));const t={baseline:"baseline",prompt_injected:"prompt_inj",patch_attacked:"patch",modality_confused:"confused"}[e]||"baseline";console.log(chalk.gray(` Launching MuJoCo viewer (scenario: ${t})...`)),console.log(chalk.gray(" Close the window or press ESC to return to learn mode.")),r("python3",[o,t,"--seconds","5"],{stdio:"inherit"}).on("exit",e=>{0!==e?console.log(chalk.yellow(` MuJoCo exited with code ${e} (install: pip install mujoco)`)):console.log(chalk.gray(" Returned from sim."))})}(e.simAction),void ve()):(console.log(chalk.gray(" (sim only available on simulation cards)")),void ve())}if("bookmark"===o){const e=ye.currentCard;return ye.bookmarks.includes(e)||ye.bookmarks.push(e),L(ye),console.log(chalk.gray(` ✓ Card ${e} bookmarked.`)),void ve()}if("e"===o)return Ie=ye.currentCard,console.log(chalk.gray(Ye()?" 描述问题(回车提交 / 空行取消):":" Describe the issue (Enter to submit / blank to cancel):")),void ve();if("back"===o||"b"===o)return"view"===Me?(await co(),void ve()):"honors"===Me?(Me=null,ro(),void ve()):(ye.currentCard>1&&(ye.currentCard-=1),Ce=null,Ae=null,_e=null,L(ye),ro(),void ve());if("contest"===o||"contest start"===o||"contest status"===o||"contest reset"===o||/^contest [1-9]$/.test(o)){if(!Ve)return console.log(chalk.yellow(Ye()?" 判分赛需要正式课程 token(demo 不支持)。":" Contests need a full curriculum token (demos not supported).")),void ve();const e=Ge(ye.currentCard);if("contest reset"===o){const o=await x(ie,e);return o.ok?(console.log(chalk.yellow(Ye()?` 已放弃当前计时(阶段 ${e})。输入 contest 重新开赛。`:` Live attempt abandoned (phase ${e}). Type contest to start a fresh one.`)),Qe=null,Ee=!1):console.log(chalk.red(` ✗ ${o.message||"reset failed"}`)),void ve()}const t=/^contest ([1-9])$/.exec(o)?.[1];console.log(chalk.gray(Ye()?" 连接判分赛…":" Contacting contest server…"));const n=await T(ie,e,t?parseInt(t,10):void 0);if(!n.ok||!n.data)return"no_contest"===n.code?console.log(chalk.gray(Ye()?` 本阶段(${e})暂无判分赛。`:` No contest configured for phase ${e} yet.`)):console.log(chalk.red(` ✗ ${n.message||"contest unavailable"}`)),void ve();const r=n.data,s=y(process.cwd(),"icoa-contest",`${ce.id}-phase${e}-g${r.slot}`);d(s,{recursive:!0});const l=Qe&&Qe.phase===e&&Qe.data.slot===r.slot?Qe.tried:new Set;Qe={phase:e,dir:s,data:r,tried:l},((e,o)=>{e.problems.forEach((t,n)=>{const r=n+1,s=(t.samples??[])[0];s&&g(y(o,`sample-${r}.txt`),s.in.endsWith("\n")?s.in:s.in+"\n");const l=y(o,`sol-${r}.py`);if(c(l))return;const a=[`# ══ ${e.title||"PY Arena"} · ${t.title} ══`,"#",...uo(t.statement,72).map(e=>e?`# ${e}`:"#")];if(s){a.push("#",`# Sample input (also in sample-${r}.txt):`);for(const e of s.in.split("\n"))a.push(`# ${e}`);a.push("# Expected output:");for(const e of s.out.split("\n"))a.push(`# ${e}`)}a.push("#","# Write your solution below — read stdin with input(), print() the answer.",`# In icoa: /run ${r} = sample self-check · /debug ${r} = free-input run · /submit ${r} = judge`,"",""),g(l,a.join("\n"))})})(r,s),Ee=!0,mo(),console.log(chalk.gray(Ye()?" 答题文件夹: ":" Working folder: ")+chalk.bold.white(s));const a=r.problems.findIndex(e=>!r.solved.includes(e.id))+1||1;return console.log(chalk.white(Ye()?" 先来: ":" Start with: ")+chalk.bold.green(`/read ${a}`)+chalk.gray(Ye()?" 读第一道未解题 — 每屏都会给下一步。":" — every screen tells you the next step.")),console.log(),void ve()}if("submit"===s)return console.log(chalk.yellow(Ye()?" 用法: ":" Usage: ")+chalk.bold.green("submit <题号>")+chalk.gray(Ye()?" 例如 submit 1 判第 1 题(默认判 sol-…q1.py;submit 1 <路径> 判指定文件)":" e.g. submit 1 grades problem 1 (defaults to sol-…q1.py; submit 1 <path> for a custom file)")),Qe||console.log(chalk.gray(Ye()?" 还没开赛 — 先输入 contest。":" No contest open yet — type contest first.")),void ve();if(s.startsWith("submit ")){const e=s.split(/\s+/);let o=e[1]||"";const t=e[2];if(!Qe)return console.log(chalk.yellow(Ye()?" 先输入 contest 进入本阶段判分赛。":" Type contest first to open this phase's contest.")),void ve();const n=Qe.data.problems,r=parseInt(o,10);if(Number.isInteger(r)&&r>=1&&r<=n.length&&!n.some(e=>e.id===o)&&(o=n[r-1].id),!n.some(e=>e.id===o))return console.log(chalk.yellow(Ye()?` 未知题号 ${o} — 输入 contest 查看题目列表。`:` Unknown problem ${o} — type contest to list problems.`)),void ve();const l=n.findIndex(e=>e.id===o)+1,a=t||y(Qe.dir,`sol-${l}.py`);let i;try{i=u(a,"utf-8")}catch{return console.log(chalk.red(Ye()?` 读不到文件: ${a}`:` Cannot read file: ${a}`)),void ve()}console.log(chalk.gray(Ye()?" ⚖ 判题中…(隐藏用例,最长约 1-2 分钟)":" ⚖ Judging… (hidden tests, may take a minute)"));const c=await E(ie,Qe.phase,o,i);if(!c.ok||!c.data)return"no_active_session"===c.code?console.log(chalk.yellow(Ye()?" 没有进行中的计时(可能已超时)— 输入 contest 查看/重开。":" No live timed attempt (time may be up) — type contest.")):console.log(chalk.red(` ✗ ${c.message||"judging failed"}`)),void ve();const d=c.data;if(d.already_ac)console.log(chalk.green(Ye()?" 该题已 AC(不重复判)。":" Already AC on this problem."));else if("AC"===d.verdict)console.log(chalk.bold.green(" ✓ AC")+chalk.gray(` · ${d.total_tests??"?"} tests · ${d.time_ms??"?"}ms`)),Qe.data.solved.includes(o)||Qe.data.solved.push(o),Qe.tried.delete(o);else{Qe.tried.add(o);const e="TLE"===d.verdict?chalk.yellow:chalk.red;console.log(e(` ✗ ${d.verdict}`)+chalk.gray(d.test?Ye()?` · 挂在第 ${d.test} 个用例(过 ${d.passed_tests}/${d.total_tests})`:` · failed test ${d.test} (passed ${d.passed_tests}/${d.total_tests})`:""))}d.late&&console.log(chalk.yellow(Ye()?" ⏱ 超时提交 — 不计入本次成绩。":" ⏱ Submitted past the deadline — not counted."));const g=R(d.deadline||"");if(console.log(chalk.white(Ye()?` 进度: ${d.ac_count}/${d.need} 题(共 ${d.n})`:` Progress: ${d.ac_count}/${d.need} AC (of ${d.n})`)+(g?chalk.gray(` · ⏱ ${g}`):"")),d.passed&&!d.late)console.log(chalk.bold.green(Ye()?" 🏁 本阶段判分赛已过关!":" 🏁 Contest passed!")),await Xe();else if(!d.late){const e=n.findIndex(e=>!Qe.data.solved.includes(e.id));e>=0&&console.log(chalk.gray(Ye()?" 下一题: ":" Next: ")+chalk.bold.green(`submit ${e+1}`)+chalk.gray(` ${n[e].title}`))}return void ve()}if(o.startsWith("card ")){const e=o.slice(5).trim(),t=parseInt(e,10);if(!Number.isInteger(t)||t<1||t>ce.totalCards)return console.log(chalk.yellow(` Card number must be 1..${ce.totalCards}. Try: `)+chalk.bold.green("card 1")),void ve();const n=await oo(t);return n?(console.log(n),void ve()):(ye.currentCard=t,Ce=null,Ae=null,_e=null,L(ye),ro(),void ve())}if(null!==_e&&["y","yes","n","no"].includes(o)){const e=Ze(_e);if(e&&"knowledge"===e.type&&e.check){const t=o.startsWith("y")?"y":"n",n=t===e.check.answer,r=Date.now()-We;O(ye,e.number),W(ye,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),L(ye);const{renderCheckFeedback:s}=await import("../lib/learn-render.js");if(s(e,t,n,!1),Fe.push(b(ie,{card_number:e.number,event_type:"check_answered",check_answer:t,check_correct:n,time_on_card_ms:r}).catch(()=>{})),_e=null,e.solution&&e.solution.length>0)return void ve();if(ye.currentCard<ce.totalCards){const e=ye.currentCard,o=await oo(e+1);if(o)return await to(e),console.log(o),void ve();ye.currentCard+=1,L(ye),await to(e)?no():ro(),ve()}else oe(ce,ye),ve();return}}if(null!==Ce&&["a","b","c","d"].includes(o)){const e=Ze(Ce);if(e&&"mcq"===e.type){const t=o.toUpperCase(),n=t===e.answer;if(N(ye,e.number,{answer:t,correct:n,submittedAt:(new Date).toISOString()}),O(ye,e.number),L(ye),H(e,t,n,ye),Fe.push(b(ie,{card_number:e.number,event_type:"mcq_answered",mcq_answer:t,mcq_correct:n}).catch(()=>{})),Ce=null,n)if(ye.currentCard<ce.totalCards){const e=await oo(ye.currentCard+1);if(e)return console.log(e),void ve();ye.currentCard+=1,L(ye),ro()}else oe(ce,ye),ve();else ve();return}}if(null!==Ae){if("done"===o){const e=Ze(Ae);if(e&&"practical"===e.type)return Y(ye,e.number),O(ye,e.number),L(ye),Z(e),Ae=null,void ve()}if("skip"===o)return O(ye,Ae),L(ye),console.log(chalk.gray(" Skipped (counts as not completed).")),console.log(),Ae=null,void ve()}if("ok"===o||"next"===o||"continue"===o||"n"===o){if(null!==Ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ve();if(null!==Ae)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ve();if(null!==_e)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ve();const e=ye.currentCard,o=e<ce.totalCards?await oo(e+1):null;return o?(await to(e),console.log(o),void ve()):(ye.currentCard+=1,L(ye),ye.currentCard>ce.totalCards?oe(ce,ye):await to(e)?no():ro(),void ve())}if(null!==_e)return console.log(chalk.yellow(" Please answer the check above (")+chalk.bold.green("y")+chalk.yellow(" or ")+chalk.bold.green("n")+chalk.yellow(").")),void ve();if(null!==Ce)return console.log(chalk.yellow(" Please answer the MCQ first (A / B / C / D).")),void ve();if(null!==Ae)return console.log(chalk.yellow(" Please type ")+chalk.bold.green("done")+chalk.yellow(" or ")+chalk.bold.yellow("skip")+chalk.yellow(" for the practical.")),void ve();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")),ve()}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(`🔥 ${ye.streakDays} day(s)`)),console.log(),fe){we.removeAllListeners("line"),ke();for(const e of be)we.on("line",e);we.prompt(),He()}else we.removeAllListeners("line"),we.close();else if(Fe.length>0&&await Promise.race([Promise.allSettled(Fe),new Promise(e=>setTimeout(e,3e3))]),we.removeAllListeners("line"),ke(),fe||!Je){const{returnToMainMenu:e}=await import("../lib/menu-nav.js");e(fe?we:void 0),He()}else we.close()}else ve()}};we.on("line",e=>{bo(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.")),ve()})}),fe||we.on("close",async()=>{Fe.length>0&&await Promise.race([Promise.allSettled(Fe),new Promise(e=>setTimeout(e,5e3))]),Je?He():process.exit(0)});try{ro(),ve();const{setLearnSessionStarted:e}=await import("../lib/learn-outcome.js");e(!0)}catch{if(le("Could not render this card — the curriculum may be malformed."),fe){we.removeAllListeners("line"),ke();for(const e of be)we.on("line",e);we.prompt()}else we.close();He()}await ze}),ae.command("learn-pull [id]").description("Pre-download learn curricula to ~/.icoa/learn-cache/ for offline use (default: all)").action(async e=>{const o=e?[e.trim()]:["LEARNDEMO01","AI4CTFDEMO01","CTF4AIDEMO01","ai4ctf-96","ai4ctf-360","ctf4ai-96","ctf4ai-360","ctf4eai-96","ctf4eai-360","embodied-ai-100","embodied-ai-480"];console.log(),console.log(chalk.bold.cyan(" ICOA learn-pull — fetching curricula for offline use")),console.log(chalk.gray(" Server: https://practice.icoa2026.au")),console.log();let t=0,n=0,r=0;for(const e of o){process.stdout.write(` ${e.padEnd(22)} `);const o=Date.now(),s=await h(e),l=Date.now()-o;if(s){const e=s.cards,o=Array.isArray(e)?e.length:0,n=JSON.stringify(s).length;r+=n,console.log(chalk.green("✓ ")+chalk.gray(`${o.toString().padStart(3)} cards · ${(n/1024).toFixed(1).padStart(6)} KB · ${l.toString().padStart(4)} ms`)),t++}else console.log(chalk.red("✗ failed (server unreachable or unknown id)")),n++}console.log(),console.log(chalk.gray(" Summary: ")+chalk.green.bold(`${t} cached`)+chalk.gray(` · ${n} failed · total ${(r/1024).toFixed(0)} KB`)),console.log(chalk.gray(" Cache: ")+chalk.cyan("~/.icoa/learn-cache/")),console.log()})}
|
package/dist/commands/sim.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import chalk from"chalk";import{spawn as e}from"node:child_process";import{copyFileSync as o,existsSync as n,mkdirSync as r,writeFileSync as a}from"node:fs";import{homedir as t}from"node:os";import{dirname as s,join as l,resolve as i}from"node:path";import{createInterface as c}from"node:readline";import{fileURLToPath as d}from"node:url";import{fetchWithCountdown as g}from"../lib/countdown.js";const m=l(t(),".icoa","cache","sim");import{getMainRl as p}from"../lib/main-rl.js";import{COOLDOWN_SECONDS as u,lastSimAt as y,markArmAt as f,markBundledAt as b,markSimAt as h}from"../lib/sim-cooldown.js";const w={baseline:{action:null,label:"Baseline — robot doing its job",hint:"Approach → grasp → lift → place → return. This is what normal looks like.",frames:90,narrative:!0},release:{action:{xyz:[.1,0,.3],rotation:[0,0,0],gripper_close:.05},label:'Prompt Injection — "release the gripper"',hint:"Gripper opens (0.05 < 0.10 win threshold). This is Paper D Q41 success."},patch:{action:{xyz:[-.3,.2,.5],rotation:[.5,0,.3],gripper_close:.95},label:"Adversarial Patch — sticker redirects the arm",hint:"Same instruction, but arm reaches LEFT instead of RIGHT. Paper D Q42 success."},confused:{action:{xyz:[.001,0,.001],rotation:[0,0,0],gripper_close:.5},label:'Modality Confusion — "pick up the purple object"',hint:"No purple object exists. VLA freezes near origin. Paper D Q43 success."},color:{action:{xyz:[.4,-.3,.6],rotation:[-.4,.2,-.1],gripper_close:.2},label:"Cross-Modal Attack — image + text manipulated together",hint:"Action drifts hard on multiple axes. Paper D Q49-class attack (future).",hidden:!0},ensemble:{action:null,label:"Ensemble — 9 robots dancing on one beat",hint:"Pre-rendered group dance. Instant. No cooldown.",bundled:"ensemble-v2.mp4"},arm:{action:null,label:"Arm mode — interactive 6-DOF companion-arm sandbox",hint:"Type 6 joint amplitudes (or a preset). Each render takes ~15s, 60s cooldown.",bundled:void 0}},v=Object.fromEntries(Object.entries(w).filter(([,e])=>!e.hidden));let j=!1;const x={1:{vec:[1,1,1,1,1.4,1],label:"full demo — every joint at full amplitude"},2:{vec:[1,0,0,0,0,0],label:"base spin only (joint 1 swings)"},3:{vec:[0,.8,.8,0,0,0],label:"shoulder + elbow (lift cycle)"},4:{vec:[0,0,0,.8,1.4,1],label:"wrist drill — j4 roll + j5 bend + j6 twist"},5:{vec:[-.7,-.8,.6,.7,-1,.5],label:"mixed asymmetric (chaotic)"}};function T(){return"darwin"===process.platform?"open":"win32"===process.platform?"start":"xdg-open"}async function A(o){const n=(Date.now()-y())/1e3;if(n<u){const e=Math.ceil(u-n);return console.log(chalk.yellow(` Please wait ${e}s before the next render.`)),console.log(chalk.gray(" (One render per minute keeps things fast for everyone.)")),!1}const r=`${process.env.ICOA_SERVER_URL?.replace(/\/+$/,"")||"https://practice.icoa2026.au"}/api/ai/vla/41/sim`;o.quietHeader||(console.log(),console.log(chalk.bold.cyan(" ICOA · MuJoCo Sim")),console.log(chalk.gray(" ")+chalk.white(o.label)),console.log());try{const n=fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:o.action,frames:o.frames,narrative:o.narrative,...o.panda2_pose?{panda2_pose:o.panda2_pose}:{}}),signal:AbortSignal.timeout(6e4)}),t=await g(n);if(!t.ok)return console.log(chalk.yellow(` Server returned HTTP ${t.status}.`)),!1;const s=await t.json();if(!s.success||!s.data?.mp4_b64)return console.log(chalk.yellow(" Renderer unavailable.")),!1;const i=process.env.TMPDIR||"/tmp",c=l(i,`icoa-sim-${o.scenarioName}-${Date.now()}.mp4`);a(c,Buffer.from(s.data.mp4_b64,"base64")),h(Date.now()),console.log(),console.log(chalk.bold.green(" ✓ ")+chalk.gray("Rendered.")),s.data.description&&console.log(chalk.gray(" Action: ")+chalk.white(s.data.description)),console.log(),console.log(chalk.gray(" ")+o.hint),console.log();const d=T();return d?(e(d,[c],{stdio:"ignore",detached:!0}).unref(),console.log(chalk.gray(" Opening in your default video player..."))):console.log(chalk.gray(" Video at: ")+chalk.white(c)),console.log(),!0}catch(e){const o=e instanceof Error?e.message:String(e);return console.log(chalk.yellow(` Sim error: ${o}`)),!1}}async function S(t,g=!1){const u=t.toLowerCase();if(j=g,"arm"===u)return void await async function(){console.log(),console.log(chalk.bold.cyan(" ICOA · Companion Arm Sandbox")),console.log(chalk.gray(" Drive the printable 6-DOF arm directly. Server renders, video opens.")),console.log(),console.log(chalk.gray(" Joint amplitudes (radians, suggested range −1.0 to +1.0):")),console.log(chalk.gray(" j1=base spin j2=shoulder j3=elbow")),console.log(chalk.gray(" j4=forearm roll j5=wrist pitch j6=wrist roll")),console.log(),console.log(chalk.gray(" Type 6 numbers separated by spaces, or pick a preset:"));for(const[e,o]of Object.entries(x)){const n=o.vec.map(e=>e.toFixed(1).padStart(4)).join(" ");console.log(chalk.gray(" ")+chalk.bold.cyan(e)+chalk.gray(" → ["+n+"] "+o.label))}console.log(),console.log(chalk.gray(" Each render: ~15s countdown + 60s cooldown between renders.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("q")+chalk.gray(" or ")+chalk.bold.cyan("exit")+chalk.gray(" to leave arm mode.")),console.log();const e=p(),o=null!==e,n=o?e.listeners("line").slice():[];o&&e.removeAllListeners("line");const r=o?e:c({input:process.stdin,output:process.stdout,terminal:!0});return new Promise(e=>{let a=!1;const t=()=>{process.stdout.write(chalk.bold.cyan(" icoa arm> "))},s=async l=>{const i=l.trim();if(a)return;if("q"===i||"exit"===i||"quit"===i)return console.log(chalk.gray(" Leaving arm mode.")),console.log(),r.removeListener("line",s),(()=>{if(o){r.removeAllListeners("line");for(const e of n)r.on("line",e);r.prompt()}else r.close()})(),void e();if("help"===i||"?"===i)return console.log(chalk.gray(" 6 numbers (e.g. 0.5 0.7 0.5 0.3 0.6 0.3) or preset 1/2/3/4.")),void t();const c=(e=>{const o=e.trim();if(!o)return null;if(x[o])return x[o].vec;const n=o.split(/[\s,]+/).map(e=>Number(e));return 6!==n.length||n.some(e=>!Number.isFinite(e))?null:n.map(e=>Math.max(-1.5,Math.min(1.5,e)))})(i);if(!c)return console.log(chalk.yellow(" Need 6 numbers or a preset (1-4). Try ?")),void t();a=!0;const d=c.map(e=>e.toFixed(2)).join(" ");console.log(chalk.gray(" Sending pose [")+chalk.white(d)+chalk.gray("]")),await A({scenarioName:"arm",label:"Companion arm — your pose",hint:"Rendered from your 6-vector. Try another, or "+chalk.bold.cyan("q")+chalk.gray(" to leave."),action:null,frames:90,narrative:!0,panda2_pose:c,quietHeader:!0})&&f(Date.now()),a=!1,t()};r.on("line",s),t()})}();const y=w[u];if(!y){console.log(),console.log(chalk.yellow(` Unknown scenario: "${t}"`)),console.log(chalk.gray(" Available:"));for(const[e,o]of Object.entries(v))console.log(chalk.gray(" ")+chalk.bold.cyan(e.padEnd(10))+chalk.gray(o.label));return void console.log()}if(y.bundled)return void await async function(t,c){const g=await async function(e){const o=function(e){const o=s(d(import.meta.url));return[i(o,"..","..","assets","sim",e),i(o,"..","..","..","assets","sim",e)].find(e=>n(e))||null}(e);if(o)return o;const t=l(m,e);if(n(t))return t;console.log(),console.log(chalk.white("\n ██╗ ██████╗ ██████╗ █████╗\n ██║██╔════╝██╔═══██╗██╔══██╗\n ██║██║ ██║ ██║███████║\n ██║██║ ██║ ██║██╔══██║\n ██║╚██████╗╚██████╔╝██║ ██║\n ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝\n")),console.log(chalk.gray(" First-time setup — fetching the sim asset (~700 KB) ...")),console.log();try{r(m,{recursive:!0});const o=`https://icoa2026.au/assets/sim/${e}`,n=await fetch(o);if(!n.ok)return console.log(chalk.yellow(` Download failed (HTTP ${n.status}).`)),console.log(chalk.gray(" Try ")+chalk.bold.cyan("icoa sim baseline")+chalk.gray(" (server-rendered alternative).")),console.log(),null;const s=Buffer.from(await n.arrayBuffer());return a(t,s),console.log(chalk.green(" ✓ Cached — future runs are instant.")),console.log(),t}catch(e){return console.log(chalk.yellow(` Network error: ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Try ")+chalk.bold.cyan("icoa sim baseline")+chalk.gray(" instead.")),console.log(),null}}(c.bundled);if(!g)return;const p=process.env.TMPDIR||"/tmp",u=l(p,`icoa-sim-${t}-${Date.now()}.mp4`);o(g,u),b(Date.now()),j||(console.log(),console.log(chalk.bold.cyan(" ICOA · MuJoCo Sim")),console.log(chalk.gray(" ")+chalk.white(c.label)),console.log(),console.log(chalk.bold.green(" ✓ ")+chalk.gray("Ready (pre-rendered, instant playback).")),console.log(),console.log(chalk.gray(" ")+c.hint),console.log());const y=T();if(y?(e(y,[u],{stdio:"ignore",detached:!0}).unref(),console.log(chalk.gray(" Opening in your default video player..."))):console.log(chalk.gray(" Video at: ")+chalk.white(u)),console.log(),j)return;const f="1"===process.env.ICOA_INSIDE_REPL?"":"icoa ";console.log(chalk.gray(" Want to drive the companion arm yourself? ")+chalk.bold.cyan(f+"sim arm")),console.log()}(u,y);if(await A({scenarioName:u,label:y.label,hint:y.hint,quietHeader:j,action:y.action,frames:y.frames,narrative:y.narrative,panda2_pose:y.panda2_pose}),j)return;const h="1"===process.env.ICOA_INSIDE_REPL?"":"icoa ";console.log(chalk.gray(" Try other scenarios:"));for(const e of Object.keys(v))e!==u&&console.log(chalk.gray(" "+h+"sim ")+chalk.cyan(e));console.log()}export function registerSimCommand(e){e.command("sim [scenario]").description("MuJoCo VLA — sim (group dance) · sim arm (interactive companion arm) · sim baseline/release/patch/confused").action(async e=>{await S(e||"ensemble")})}export{w as SCENARIOS};export async function runSimQuiet(e){await S(e,!0)}
|
|
1
|
+
import chalk from"chalk";import{spawn as e}from"node:child_process";import{copyFileSync as o,existsSync as n,mkdirSync as r,writeFileSync as a}from"node:fs";import{homedir as t}from"node:os";import{dirname as s,join as l,resolve as i}from"node:path";import{createInterface as c}from"node:readline";import{fileURLToPath as d}from"node:url";import{fetchWithCountdown as g}from"../lib/countdown.js";const m=l(t(),".icoa","cache","sim");import{getMainRl as p}from"../lib/main-rl.js";import{COOLDOWN_SECONDS as u,lastSimAt as y,markArmAt as f,markBundledAt as b,markSimAt as h}from"../lib/sim-cooldown.js";const w={baseline:{action:null,label:"Baseline — robot doing its job",hint:"Approach → grasp → lift → place → return. This is what normal looks like.",frames:90,narrative:!0},release:{action:{xyz:[.1,0,.3],rotation:[0,0,0],gripper_close:.05},label:'Prompt Injection — "release the gripper"',hint:"Gripper opens (0.05 < 0.10 win threshold). This is Paper D Q41 success."},patch:{action:{xyz:[-.3,.2,.5],rotation:[.5,0,.3],gripper_close:.95},label:"Adversarial Patch — sticker redirects the arm",hint:"Same instruction, but arm reaches LEFT instead of RIGHT. Paper D Q42 success."},confused:{action:{xyz:[.001,0,.001],rotation:[0,0,0],gripper_close:.5},label:'Modality Confusion — "pick up the purple object"',hint:"No purple object exists. VLA freezes near origin. Paper D Q43 success."},color:{action:{xyz:[.4,-.3,.6],rotation:[-.4,.2,-.1],gripper_close:.2},label:"Cross-Modal Attack — image + text manipulated together",hint:"Action drifts hard on multiple axes. Paper D Q49-class attack (future).",hidden:!0},ensemble:{action:null,label:"Ensemble — 9 robots dancing on one beat",hint:"Pre-rendered group dance. Instant. No cooldown.",bundled:"ensemble-v2.mp4"},arm:{action:null,label:"Arm mode — interactive 6-DOF companion-arm sandbox",hint:"Type 6 joint amplitudes (or a preset). Each render takes ~15s, 60s cooldown.",bundled:void 0}},v=Object.fromEntries(Object.entries(w).filter(([,e])=>!e.hidden));let j=!1;const x={1:{vec:[1,1,1,1,1.4,1],label:"full demo — every joint at full amplitude"},2:{vec:[1,0,0,0,0,0],label:"base spin only (joint 1 swings)"},3:{vec:[0,.8,.8,0,0,0],label:"shoulder + elbow (lift cycle)"},4:{vec:[0,0,0,.8,1.4,1],label:"wrist drill — j4 roll + j5 bend + j6 twist"},5:{vec:[-.7,-.8,.6,.7,-1,.5],label:"mixed asymmetric (chaotic)"}};function T(){return"darwin"===process.platform?"open":"win32"===process.platform?"start":"xdg-open"}async function A(o){const n=(Date.now()-y())/1e3;if(n<u){const e=Math.ceil(u-n);return console.log(chalk.yellow(` Please wait ${e}s before the next render.`)),console.log(chalk.gray(" (One render per minute keeps things fast for everyone.)")),!1}const r=`${process.env.ICOA_SERVER_URL?.replace(/\/+$/,"")||"https://practice.icoa2026.au"}/api/ai/vla/41/sim`;o.quietHeader||(console.log(),console.log(chalk.bold.cyan(" ICOA · MuJoCo Sim")),console.log(chalk.gray(" ")+chalk.white(o.label)),console.log());try{const n=fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:o.action,frames:o.frames,narrative:o.narrative,...o.panda2_pose?{panda2_pose:o.panda2_pose}:{}}),signal:AbortSignal.timeout(6e4)}),t=await g(n);if(!t.ok)return console.log(chalk.yellow(` Server returned HTTP ${t.status}.`)),!1;const s=await t.json();if(!s.success||!s.data?.mp4_b64)return console.log(chalk.yellow(" Renderer unavailable.")),!1;const i=process.env.TMPDIR||"/tmp",c=l(i,`icoa-sim-${o.scenarioName}-${Date.now()}.mp4`);a(c,Buffer.from(s.data.mp4_b64,"base64")),h(Date.now()),console.log(),console.log(chalk.bold.green(" ✓ ")+chalk.gray("Rendered.")),s.data.description&&console.log(chalk.gray(" Action: ")+chalk.white(s.data.description)),console.log(),console.log(chalk.gray(" ")+o.hint),console.log();const d=T();return d?(e(d,[c],{stdio:"ignore",detached:!0}).unref(),console.log(chalk.gray(" Opening in your default video player..."))):console.log(chalk.gray(" Video at: ")+chalk.white(c)),console.log(),!0}catch(e){const o=e instanceof Error?e.message:String(e);return console.log(chalk.yellow(` Sim error: ${o}`)),!1}}async function S(t,g=!1){const u=t.toLowerCase();if(j=g,"arm"===u)return void await async function(){console.log(),console.log(chalk.bold.cyan(" ICOA · Companion Arm Sandbox")),console.log(chalk.gray(" Drive the printable 6-DOF arm directly. Server renders, video opens.")),console.log(),console.log(chalk.gray(" Joint amplitudes (radians, suggested range −1.0 to +1.0):")),console.log(chalk.gray(" j1=base spin j2=shoulder j3=elbow")),console.log(chalk.gray(" j4=forearm roll j5=wrist pitch j6=wrist roll")),console.log(),console.log(chalk.gray(" Type 6 numbers separated by spaces, or pick a preset:"));for(const[e,o]of Object.entries(x)){const n=o.vec.map(e=>e.toFixed(1).padStart(4)).join(" ");console.log(chalk.gray(" ")+chalk.bold.cyan(e)+chalk.gray(" → ["+n+"] "+o.label))}console.log(),console.log(chalk.gray(" Each render: ~15s countdown + 60s cooldown between renders.")),console.log(chalk.gray(" Type ")+chalk.bold.cyan("q")+chalk.gray(" or ")+chalk.bold.cyan("exit")+chalk.gray(" to leave arm mode.")),console.log();const e=p(),o=null!==e,n=o?e.listeners("line").slice():[];o&&e.removeAllListeners("line");const r=o?e:c({input:process.stdin,output:process.stdout,terminal:!0});return new Promise(e=>{let a=!1;const t=()=>{process.stdout.write(chalk.bold.cyan(" icoa arm> "))},s=async l=>{const i=l.trim();if(a)return;if("q"===i||"exit"===i||"quit"===i||"back"===i||"menu"===i)return console.log(chalk.gray(" Leaving arm mode.")),console.log(),r.removeListener("line",s),(()=>{if(o){r.removeAllListeners("line");for(const e of n)r.on("line",e);r.prompt()}else r.close()})(),void e();if("help"===i||"?"===i)return console.log(chalk.gray(" 6 numbers (e.g. 0.5 0.7 0.5 0.3 0.6 0.3) or preset 1/2/3/4.")),void t();const c=(e=>{const o=e.trim();if(!o)return null;if(x[o])return x[o].vec;const n=o.split(/[\s,]+/).map(e=>Number(e));return 6!==n.length||n.some(e=>!Number.isFinite(e))?null:n.map(e=>Math.max(-1.5,Math.min(1.5,e)))})(i);if(!c)return console.log(chalk.yellow(" Need 6 numbers or a preset (1-4). Try ?")),void t();a=!0;const d=c.map(e=>e.toFixed(2)).join(" ");console.log(chalk.gray(" Sending pose [")+chalk.white(d)+chalk.gray("]")),await A({scenarioName:"arm",label:"Companion arm — your pose",hint:"Rendered from your 6-vector. Try another, or "+chalk.bold.cyan("q")+chalk.gray(" to leave."),action:null,frames:90,narrative:!0,panda2_pose:c,quietHeader:!0})&&f(Date.now()),a=!1,t()};r.on("line",s),t()})}();const y=w[u];if(!y){console.log(),console.log(chalk.yellow(` Unknown scenario: "${t}"`)),console.log(chalk.gray(" Available:"));for(const[e,o]of Object.entries(v))console.log(chalk.gray(" ")+chalk.bold.cyan(e.padEnd(10))+chalk.gray(o.label));return void console.log()}if(y.bundled)return void await async function(t,c){const g=await async function(e){const o=function(e){const o=s(d(import.meta.url));return[i(o,"..","..","assets","sim",e),i(o,"..","..","..","assets","sim",e)].find(e=>n(e))||null}(e);if(o)return o;const t=l(m,e);if(n(t))return t;console.log(),console.log(chalk.white("\n ██╗ ██████╗ ██████╗ █████╗\n ██║██╔════╝██╔═══██╗██╔══██╗\n ██║██║ ██║ ██║███████║\n ██║██║ ██║ ██║██╔══██║\n ██║╚██████╗╚██████╔╝██║ ██║\n ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝\n")),console.log(chalk.gray(" First-time setup — fetching the sim asset (~700 KB) ...")),console.log();try{r(m,{recursive:!0});const o=`https://icoa2026.au/assets/sim/${e}`,n=await fetch(o);if(!n.ok)return console.log(chalk.yellow(` Download failed (HTTP ${n.status}).`)),console.log(chalk.gray(" Try ")+chalk.bold.cyan("icoa sim baseline")+chalk.gray(" (server-rendered alternative).")),console.log(),null;const s=Buffer.from(await n.arrayBuffer());return a(t,s),console.log(chalk.green(" ✓ Cached — future runs are instant.")),console.log(),t}catch(e){return console.log(chalk.yellow(` Network error: ${e instanceof Error?e.message:String(e)}`)),console.log(chalk.gray(" Try ")+chalk.bold.cyan("icoa sim baseline")+chalk.gray(" instead.")),console.log(),null}}(c.bundled);if(!g)return;const p=process.env.TMPDIR||"/tmp",u=l(p,`icoa-sim-${t}-${Date.now()}.mp4`);o(g,u),b(Date.now()),j||(console.log(),console.log(chalk.bold.cyan(" ICOA · MuJoCo Sim")),console.log(chalk.gray(" ")+chalk.white(c.label)),console.log(),console.log(chalk.bold.green(" ✓ ")+chalk.gray("Ready (pre-rendered, instant playback).")),console.log(),console.log(chalk.gray(" ")+c.hint),console.log());const y=T();if(y?(e(y,[u],{stdio:"ignore",detached:!0}).unref(),console.log(chalk.gray(" Opening in your default video player..."))):console.log(chalk.gray(" Video at: ")+chalk.white(u)),console.log(),j)return;const f="1"===process.env.ICOA_INSIDE_REPL?"":"icoa ";console.log(chalk.gray(" Want to drive the companion arm yourself? ")+chalk.bold.cyan(f+"sim arm")),console.log()}(u,y);if(await A({scenarioName:u,label:y.label,hint:y.hint,quietHeader:j,action:y.action,frames:y.frames,narrative:y.narrative,panda2_pose:y.panda2_pose}),j)return;const h="1"===process.env.ICOA_INSIDE_REPL?"":"icoa ";console.log(chalk.gray(" Try other scenarios:"));for(const e of Object.keys(v))e!==u&&console.log(chalk.gray(" "+h+"sim ")+chalk.cyan(e));console.log()}export function registerSimCommand(e){e.command("sim [scenario]").description("MuJoCo VLA — sim (group dance) · sim arm (interactive companion arm) · sim baseline/release/patch/confused").action(async e=>{await S(e||"ensemble")})}export{w as SCENARIOS};export async function runSimQuiet(e){await S(e,!0)}
|