icoa-cli 2.19.706 → 2.19.707

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as p}from"../lib/kaggle.js";import{mediaHelpLines as m,sprintTaskForComp as f}from"../lib/sprint-meta.js";function k(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):"https://practice.icoa2026.au"}async function w(o){try{const e=await fetch(k()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function $(o,e){try{const n=await fetch(k()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}async function v(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function _(){return(a().language||"en").toLowerCase().startsWith("zh")}function S(o,e){return _()?o:e}function j(){console.log(),console.log(chalk.yellow(S(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(S(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function A(o){return s(process.cwd(),"icoa-kaggle",o)}function x(o,e){const n=[];let t="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const r of o){const o=s(r)?2:1;if(l+o>e){const o=t.lastIndexOf(" ");if(!s(r)&&" "!==r&&o>e/3){const e=t.slice(o+1);n.push(t.slice(0,o)),t=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else n.push(t),t="",l=0;if(" "===r&&""===t)continue}t+=r,l+=o}return""!==t.trim()&&n.push(t),n}function E(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(S(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(S(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(S(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(S(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),console.log(chalk.gray(S(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board")),void console.log(chalk.gray(S(" 在 notebook 里可直接敲 "," inside the notebook just type "))+chalk.cyan("submit")+chalk.gray(S(" —— 不用退出来"," — no need to leave")))):"nitro"===o?.judge?(console.log(chalk.bold.white(S(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(S(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(S(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(S(" 注册后提交"," and submit there"))),void console.log(chalk.gray(S(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(S(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(S(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(S(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(S(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(S(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(S(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(S(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(S(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(n){const t=r(),a=async o=>await t.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(S(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(S(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(S("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(S("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await w("/api/icoa/kaggle/tasks");if(!t)return j();const r=h(t);if(0===r.length)return console.log(chalk.yellow(S(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=n?r.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(S(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(S(" 正在开放的练习赛:"," Live practice competitions:"))),r.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!c;o++){const o=(await a(chalk.cyan(S(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&r[e-1]||r.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(S(` 输 1-${r.length} 之间的序号,或者一个 id,比如 "${r[0].comp_id}"。`,` Try a number 1-${r.length} or an id like "${r[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(i(`kaggle: download ${u}`),c.needs_gpu)return void await async function(n,t){const r=A(n);if(console.log(),console.log(chalk.white(` ${t.title}`)+chalk.gray(` · ${t.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),t.description){console.log();for(const o of x(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(S(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(S(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const a=await w(`/api/icoa/kaggle/${n}/starter`),i=a?.data?.starter??a?.starter;if("string"!=typeof i||0===i.length)return j();const c=s(r,"starter.ipynb");let g=!1;try{e(r,{recursive:!0}),o(c)?g=!0:l(c,i),l(s(r,"meta.json"),`${JSON.stringify(t,null,2)}\n`)}catch{return void console.log(chalk.yellow(S(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?S(" (保留了你原来那本)"," (kept your existing one)"):S(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(S("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(S(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(S(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(S(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(S(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(S(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(S(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(S(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(S(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(S(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(t.kaggle_url)),console.log())}(u,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of x(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(S(" 正在下载数据…"," Downloading data…")));let b=null;const p=y(c);if(p){const[o,e,n]=await Promise.all([v(p.train),v(p.test),v(p.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await w(`/api/icoa/kaggle/${u}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return j();const m=A(u),k={...c,...b.meta??{}};try{e(m,{recursive:!0}),l(s(m,"train.csv"),b.train),l(s(m,"test.csv"),b.test),l(s(m,"sample_submission.csv"),b.sample_submission),l(s(m,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const $=s(m,"starter.ipynb");let _=!1;if(o($))_=!0;else{const o=await w(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l($,e):l($,g(d(m,k)))}const E="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",G="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(m,"train.csv"))+chalk.gray(` (${E})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(m,"test.csv"))+chalk.gray(` (${G})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(m,"sample_submission.csv")));const I=f(u),N="none"===(I?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white($)+chalk.gray(_?" (kept your existing one)":N?S(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),P(u,k,$),console.log()}finally{t.close()}}function G(o){const e=_();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function P(o,e,n){const t=f(o),l=t?m(t,_()):[];if(l.length>0){for(const o of l)for(const e of x(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(e?.needs_gpu)console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"));else{const l=t?.media?.pack,s="none"===(t?.baseline||"").trim();console.log(chalk.bold.white(l?S(" 接下来 4 步:"," Your move — 4 steps:"):S(" 接下来 3 步:"," Your move — 3 steps:")));let r=1;l&&console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(S(` → 把${G(t?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${G(t?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(s?S(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${r++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${r}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${r}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${r}. upload it on Kaggle yourself — then beat the baseline.`))}console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick ")+chalk.bold.white("🧠 Learn")+chalk.gray(" → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),E(e)}export async function runKaggleGuide(e){console.log();const t=I(e,"guide");if(!t)return;const l=A(t);let r=null;try{r=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{r=null}i(`kaggle: guide ${t}`);const a=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${r?.title??t} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),P(t,r,a),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function I(e,n){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),r=o(l)?t(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===r.length)return r[0];if(0===r.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of r)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const t=I(e,"check");if(!t)return;const l=A(t),r=s(l,"submission.csv"),a=s(l,"sample_submission.csv");try{if(JSON.parse(n(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(a))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(a))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=p(n(r,"utf-8"),n(a,"utf-8"));i(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(r)),console.log(),E(u),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e,t){console.log();const l=I(e,"submit");if(!l)return;const a=A(l),c=s(a,"submission.csv"),g=s(a,"sample_submission.csv");let d=null;try{d=JSON.parse(n(s(a,"meta.json"),"utf-8"))}catch{d=null}if("local-eval"===d?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),E(d),void console.log();if(!d||!o(g))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==d.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),E(d),void console.log();if(!o(c))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(a,"starter.ipynb")}`)),void console.log();const y=n(c,"utf-8"),h=p(y,n(g,"utf-8"));if(!h.ok){i(`kaggle: submit ${l} → local-reject: ${h.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of h.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let m=u()?.token??"";if(!m){const o=r();try{m=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!m)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}const f=Date.now();let k,w=null;process.stdout.isTTY?(process.stdout.write(chalk.gray(" ⚖ scoring on the server… 0.0s")),w=setInterval(()=>{process.stdout.write(chalk.gray(`\r ⚖ scoring on the server… ${((Date.now()-f)/1e3).toFixed(1)}s `))},200)):console.log(chalk.gray(" Scoring on the server…"));try{k=await $(`/api/icoa/kaggle/${l}/submit`,{token:m,submission_csv:y,...t?{job:t}:{}})}finally{w&&(clearInterval(w),process.stdout.write(`\r ${chalk.gray(`⚖ scored in ${((Date.now()-f)/1e3).toFixed(1)}s`)}${" ".repeat(12)}\n`))}const v=b(k);if(i(`kaggle: submit ${l} → ${v.ok?`${v.metric}=${v.score}${v.deduped?" (deduped)":""} rank=${v.rank??"-"}`:v.reason??"error"}`),console.log(),v.ok){const o=`${v.metric}: ${Number(v.score).toFixed(4).replace(/\.?0+$/,"")}`,e="public"===v.leaderboard?chalk.gray(" (public leaderboard — the private split is revealed after the event)"):"";v.deduped&&v.sameCode?(console.log(chalk.bold.white(` ✓ same code as before — ${o}`)+e),console.log(chalk.gray(" The notebook code is unchanged, so this is the earlier result; it does not count as a submission."))):v.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)+e),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)+e),"number"==typeof v.rank&&"number"==typeof v.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${v.rank}`)+chalk.gray(` of ${v.fieldSize}`))),"number"==typeof v.used&&"number"==typeof v.cap&&console.log(chalk.gray(` ⚖ submissions used ${v.used}/${v.cap}`)),v.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`kaggle board ${l}`)+chalk.gray(" (or ")+chalk.cyan(`board ${v.boardEvent} ${l}`)+chalk.gray(")")),v.submissionId&&"public"===v.leaderboard&&console.log(chalk.gray(` id ${v.submissionId} · pick the two that count on the private board: `)+chalk.cyan(`kaggle final ${l} ${v.submissionId}`)+chalk.gray(" [<id2>] (unpicked = public best + last)"))}else switch(v.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of v.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export async function runKaggleFinal(o,e=[]){console.log();const n=I(o,"final");if(!n)return;const t=u()?.token??"";if(!t)return console.log(chalk.gray(" A learn token identifies you on the board — open Learn once with your token first.")),void console.log();const l=await $(`/api/icoa/kaggle/${n}/final`,{token:t,ids:e.slice(0,2)})??{},s=l.data??l??{};if("string"==typeof s.reason){if("bad_id"===s.reason){console.log(chalk.bold.red(` ✗ ${String(s.error)}`));const o=Array.isArray(s.yours)?s.yours:[];o.length>0&&console.log(chalk.gray(` your scored ids: ${o.join(", ")}`))}else"bad_token"===s.reason?console.log(chalk.bold.red(" ✗ that learn token was not accepted")):console.log(chalk.yellow(` ${String(s.error??s.reason)}`));return void console.log()}if(!Array.isArray(s.final))return console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const r=s.final;if(s.chosen&&r.length>0){console.log(chalk.bold.green(" ✓ your final picks for the private board:"));for(const o of r)console.log(chalk.white(` ${o.id}`)+chalk.gray(` public ${Number(o.score).toFixed(4)}`))}else console.log(chalk.white(" No picks yet — the auto rule applies: ")+chalk.gray(String(s.rule_if_unchosen??"public best + last")));const a=Array.isArray(s.yours)?s.yours:[];a.length>0&&(console.log(chalk.gray(` your last ${a.length} scored: `)+a.map(o=>`${o.id} ${Number(o.score).toFixed(4)}`).join(chalk.gray(" · "))),console.log(chalk.gray(" change: ")+chalk.cyan(`kaggle final ${n} <id> [<id>]`))),i(`kaggle: final ${n} → ${r.map(o=>o.id).join(",")||"auto"}`),console.log()}const N=o=>"number"==typeof o?o.toFixed(4):" – ";export async function runKaggleBoard(o){console.log();const e=o?.trim()||I(void 0,"board");if(!e)return;const n=u()?.token??"",t=await $(`/api/icoa/kaggle/${e}/board`,n?{token:n}:{})??{},l=t.data??t??{};if(!Array.isArray(l.public))return"unknown_comp"===l.reason?console.log(chalk.bold.red(` ✗ no competition called ${e}`)):console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const s=l.public,r="public"===l.leaderboard,a="number"==typeof l.public_fraction?Math.round(100*l.public_fraction):null;if(console.log(chalk.bold.white(` 🏆 ${String(l.title??e)}`)+chalk.gray(` · ${r?`public leaderboard (${a??"?"}% of the test set)`:"leaderboard (whole test set)"} · ${String(l.metric??"")}`)),l.closed&&console.log(chalk.yellow(" ⏹ closed — no more submissions are accepted")),0===s.length)console.log(chalk.gray(" nobody has scored yet — be the first: ")+chalk.cyan(`kaggle submit ${e}`));else{console.log(chalk.gray(" # who score subs"));for(const o of s){const e=` ${String(o.rank).padStart(3)} ${o.who.padEnd(9)} ${N(o.score)} ${String(o.n).padStart(3)}`;console.log(o.you?chalk.bold.green(`${e} ◀ you`):chalk.white(e))}}if(Array.isArray(l.private)){const o=l.private;console.log(),console.log(chalk.bold.white(" 🔒 private leaderboard — FINAL")+chalk.gray(r?` (the other ${100-(a??0)}% of the test set)`:"")),console.log(chalk.gray(" # who private public sub id code seat picked"));for(const e of o){const o=` ${String(e.rank).padStart(3)} ${e.who.padEnd(9)} ${N(e.score)} ${N(e.public_score)} ${(e.sub_id??"-").padEnd(12)} ${(e.code_sha??"-").padEnd(12)} ${(e.job_sid??"-").padEnd(20)} ${e.how??""}`;console.log(e.you?chalk.bold.green(`${o} ◀ you`):chalk.white(o))}console.log(chalk.gray(" picked = chosen (kaggle final) or auto (public best + last) · code = sha of the notebook cells that made it"))}else r&&(console.log(chalk.gray(" (private split is revealed by the organiser after the event — then it shows here)")),n&&console.log(chalk.gray(" pick the two that count: ")+chalk.cyan(`kaggle final ${e} <id> [<id>]`)));i(`kaggle: board ${e} → ${s.length} rows${Array.isArray(l.private)?" + private":""}`),console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit" / "board" / "final"').argument("[comp]",'competition id (with "check" / "submit" / "board" / "final")').argument("[ids...]",'submission ids (with "final")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit & board & final").action(async(o,e,n=[])=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"board"===o?await runKaggleBoard(e):"final"===o?await runKaggleFinal(e,n):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}
1
+ import{existsSync as o,mkdirSync as e,readFileSync as n,readdirSync as t,writeFileSync as l}from"node:fs";import{join as s}from"node:path";import chalk from"chalk";import{makeReplAsker as r}from"../lib/repl-asker.js";import{getConfig as a}from"../lib/config.js";import{logCommand as i}from"../lib/logger.js";import{openFile as c}from"../lib/open-file.js";import{serializeIpynb as g}from"../lib/notebook-doc.js";import{loadLearnState as u}from"../lib/learn-state.js";import{buildStarterCells as d,dataFileUrls as y,parseKaggleTaskList as h,parseSubmitResponse as b,validateSubmissionText as p}from"../lib/kaggle.js";import{mediaHelpLines as m,sprintTaskForComp as f}from"../lib/sprint-meta.js";import{siteBase as k}from"../lib/site.js";const w=k();function $(){return process.env.ICOA_KAGGLE_SERVER?process.env.ICOA_KAGGLE_SERVER.replace(/\/$/,""):w}async function v(o){try{const e=await fetch($()+o,{signal:AbortSignal.timeout(3e4)});return await e.json()}catch{return null}}async function _(o,e){try{const n=await fetch($()+o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(6e4)});return await n.json()}catch{return null}}async function S(o){try{const e=await fetch(o,{signal:AbortSignal.timeout(6e4)});return e.ok?await e.text():null}catch{return null}}function j(){return(a().language||"en").toLowerCase().startsWith("zh")}function A(o,e){return j()?o:e}function x(){console.log(),console.log(chalk.yellow(A(" 练习服务器现在连不上。"," The practice server is not reachable right now."))),console.log(chalk.gray(A(" 检查一下网络,或者过一会儿再试。"," Check your connection, or try again later."))),console.log()}function E(o){return s(process.cwd(),"icoa-kaggle",o)}function G(o,e){const n=[];let t="",l=0;const s=o=>/[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(o);for(const r of o){const o=s(r)?2:1;if(l+o>e){const o=t.lastIndexOf(" ");if(!s(r)&&" "!==r&&o>e/3){const e=t.slice(o+1);n.push(t.slice(0,o)),t=e,l=[...e].reduce((o,e)=>o+(s(e)?2:1),0)}else n.push(t),t="",l=0;if(" "===r&&""===t)continue}t+=r,l+=o}return""!==t.trim()&&n.push(t),n}function P(o){return"local-eval"===o?.judge?(console.log(chalk.bold.white(A(" 出分(就在 notebook 里):"," Scoring (inside the notebook):"))),void console.log(chalk.gray(A(" 跑最后一格 —— "," run the final cell — the "))+chalk.white("FINAL")+chalk.gray(A(" 那一行就是你的分数,没有东西要上传。"," line is your score. Nothing to upload.")))):"icoa-holdout"===o?.judge?(console.log(chalk.bold.white(A(" 交给 ICOA 判分(服务端评分):"," Submit to ICOA (scored on the server):"))),console.log(chalk.gray(" ")+chalk.bold.cyan(`kaggle submit ${o.comp_id}`)),console.log(chalk.gray(A(" 与秘密测试标签比对 → 实时排名看 "," scores vs the secret test labels → live rank on "))+chalk.cyan("board")),void console.log(chalk.gray(A(" 在 notebook 里可直接敲 "," inside the notebook just type "))+chalk.cyan("submit")+chalk.gray(A(" —— 不用退出来"," — no need to leave")))):"nitro"===o?.judge?(console.log(chalk.bold.white(A(" 怎么知道做得对不对:"," How to tell whether you got it right:"))),console.log(chalk.gray(A(" · 这道题来自 judge.nitro-ai.org,判分在他们服务器上"," · this task comes from judge.nitro-ai.org — the judging lives on their server"))),console.log(chalk.gray(A(" · 想要真分数:去 "," · for a real score: register at "))+chalk.cyan("judge.nitro-ai.org")+chalk.gray(A(" 注册后提交"," and submit there"))),void console.log(chalk.gray(A(" · 冲刺期更快的办法:做完对照官方解答,或问 "," · faster right now: compare against the official solution, or ask "))+chalk.cyan("ai4ioai"))):(console.log(chalk.bold.white(A(" 去 Kaggle 提交(手动,用你自己的账号):"," Submit on Kaggle (manual, your own account):"))),void(o?.kaggle_url?(console.log(chalk.gray(A(" 1. 打开 "," 1. open "))+chalk.cyan(o.kaggle_url)),o?.needs_gpu?console.log(chalk.gray(A(" 2. 交 notebook 产出的那个文件 —— 最后一格写了确切步骤"," 2. submit the file your notebook produced — its final cell has the exact steps"))):console.log(chalk.gray(A(" 2. Submit Predictions → 上传 "," 2. Submit Predictions → upload "))+chalk.white("submission.csv")),console.log(chalk.gray(A(" 3. 看分数,改 MODEL 那一格,重跑,再来一轮。"," 3. read your score, improve the MODEL cell, re-run, repeat.")))):(console.log(chalk.gray(A(" 在 kaggle.com 搜这个比赛名提交,或做完对照官方解答自查。"," Search kaggle.com for this competition, or check yourself against the official solution."))),console.log(chalk.gray(A(" 卡住了问 "," Stuck? ask "))+chalk.cyan("ai4ioai")+chalk.gray(A(" —— 它是弱模型,把问题问准是这次要练的本事。"," — a deliberately weak model; asking precisely is the skill you are training."))))))}export async function runKaggle(n){const t=r(),a=async o=>await t.ask(o)??"";try{console.log(),console.log(chalk.bold.cyan(" 📊 KAGGLE PRACTICE")+chalk.gray(A(" · 真实的 ML 比赛,配一本能直接跑的 starter notebook"," · real ML competitions, a runnable starter notebook"))),console.log(chalk.gray(A(" 小题在你自己的 CPU 上跑;"," Small tasks run on your CPU; "))+chalk.magenta(A("⚡ GPU 题","⚡ GPU tasks"))+chalk.gray(A("在 ICOA 的 GPU 箱上跑。"," run on the ICOA GPU box."))),console.log();const t=await v("/api/icoa/kaggle/tasks");if(!t)return x();const r=h(t);if(0===r.length)return console.log(chalk.yellow(A(" 现在还没有上线的练习赛 —— 过一会儿再来。"," No practice competitions are live yet — check back soon."))),void console.log();let c=n?r.find(o=>o.comp_id===n):void 0;if(n&&!c&&console.log(chalk.yellow(A(` 没有叫 "${n}" 的比赛。`,` No competition called "${n}".`))),!c){console.log(chalk.white(A(" 正在开放的练习赛:"," Live practice competitions:"))),r.forEach((o,e)=>{const n=o.needs_gpu?chalk.magenta(" ⚡GPU"):"";console.log(chalk.gray(` ${e+1}. `)+chalk.cyan(o.comp_id)+chalk.gray(` — ${o.title} · ${o.metric}`)+n)});for(let o=0;o<3&&!c;o++){const o=(await a(chalk.cyan(A(" 选一个(序号或 id): "," Pick one (number or id): ")))).trim();if(!o)return;const e=Number(o);c=!Number.isNaN(e)&&r[e-1]||r.find(e=>e.comp_id===o.toLowerCase())||void 0,c||console.log(chalk.gray(A(` 输 1-${r.length} 之间的序号,或者一个 id,比如 "${r[0].comp_id}"。`,` Try a number 1-${r.length} or an id like "${r[0].comp_id}".`)))}if(!c)return}const u=c.comp_id;if(i(`kaggle: download ${u}`),c.needs_gpu)return void await async function(n,t){const r=E(n);if(console.log(),console.log(chalk.white(` ${t.title}`)+chalk.gray(` · ${t.metric}`)+chalk.bold.magenta(" ⚡ GPU task")),t.description){console.log();for(const o of G(t.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(A(" 正在取 notebook…"," Fetching the notebook…"))+chalk.gray(A(" (数据留在 GPU 箱上,不下载)"," (the dataset stays on the GPU box — no download)")));const a=await v(`/api/icoa/kaggle/${n}/starter`),i=a?.data?.starter??a?.starter;if("string"!=typeof i||0===i.length)return x();const c=s(r,"starter.ipynb");let g=!1;try{e(r,{recursive:!0}),o(c)?g=!0:l(c,i),l(s(r,"meta.json"),`${JSON.stringify(t,null,2)}\n`)}catch{return void console.log(chalk.yellow(A(" 写不进 notebook —— 检查一下这个目录的写权限。"," Could not write the notebook here — check directory permissions.")))}console.log(chalk.green(" ✓ notebook: ")+chalk.white(c)+chalk.gray(g?A(" (保留了你原来那本)"," (kept your existing one)"):A(" (里面是真正的 IOAI 题)"," (the real IOAI task inside)"))),console.log(chalk.green(" ✓ dataset: ")+chalk.white(A("已经在 GPU 箱上","already on the GPU box"))+chalk.gray(A(" —— 不用下载"," — no download needed"))),console.log(),console.log(chalk.bold.white(A(" 这是 GPU 题 —— 三步:"," This is a GPU task — 3 steps:"))),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${c}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(A(" 然后 "," then "))+chalk.bold.cyan("gpu on")+chalk.gray(A(" (连到数据所在的那台箱子)"," (connects you to the box where the data lives)"))),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("run all")+chalk.gray(A(" → notebook 在 GPU 上训练。"," → the notebook trains on the GPU."))),console.log(),console.log(chalk.gray(A(" 做题时随时看: "," While you work: "))+chalk.cyan("gpu status")+chalk.gray(A(" 你还剩多少时间 · "," your time left · "))+chalk.cyan("gpu queue")+chalk.gray(A(" 谁在用,谁在等"," who is on, who is waiting"))),console.log(),t.kaggle_url&&(console.log(chalk.gray(A(" 去 Kaggle 提交: "," Submit on Kaggle: "))+chalk.cyan(t.kaggle_url)),console.log())}(u,c);if(console.log(),console.log(chalk.white(` ${c.title}`)+chalk.gray(` · ${c.metric}`)),c.description){console.log();for(const o of G(c.description,74))console.log(chalk.white(` ${o}`))}console.log(),console.log(chalk.gray(A(" 正在下载数据…"," Downloading data…")));let b=null;const p=y(c);if(p){const[o,e,n]=await Promise.all([S(p.train),S(p.test),S(p.sample_submission)]);o&&e&&n&&(b={train:o,test:e,sample_submission:n})}if(!b){const o=await v(`/api/icoa/kaggle/${u}/data`);b=o?.data??o}if(!b?.train||!b?.test||!b?.sample_submission)return x();const m=E(u),k={...c,...b.meta??{}};try{e(m,{recursive:!0}),l(s(m,"train.csv"),b.train),l(s(m,"test.csv"),b.test),l(s(m,"sample_submission.csv"),b.sample_submission),l(s(m,"meta.json"),`${JSON.stringify(k,null,2)}\n`)}catch{return void console.log(chalk.yellow(" Could not write the data files here — check directory permissions."))}const w=s(m,"starter.ipynb");let $=!1;if(o(w))$=!0;else{const o=await v(`/api/icoa/kaggle/${u}/starter`),e=o?.data?.starter??o?.starter;"string"==typeof e&&e.length>0?l(w,e):l(w,g(d(m,k)))}const _="number"==typeof k.n_train?`${k.n_train} rows`:"labelled",j="number"==typeof k.n_test?`${k.n_test} rows`:"predict these";console.log(chalk.green(" ✓ train: ")+chalk.white(s(m,"train.csv"))+chalk.gray(` (${_})`)),console.log(chalk.green(" ✓ test: ")+chalk.white(s(m,"test.csv"))+chalk.gray(` (${j})`)),console.log(chalk.green(" ✓ format: ")+chalk.white(s(m,"sample_submission.csv")));const P=f(u),I="none"===(P?.baseline||"").trim();console.log(chalk.green(" ✓ notebook: ")+chalk.white(w)+chalk.gray($?" (kept your existing one)":I?A(" (starter 在里面,FEATURES 那一格要你自己写)"," (starter inside — the FEATURES cell is yours to write)"):" (runnable baseline inside)")),(k.licence||k.attribution)&&console.log(chalk.gray(` licence: ${k.licence??"—"} · ${k.attribution??""}`)),console.log(),N(u,k,w),console.log()}finally{t.close()}}function I(o){const e=j();switch(o){case"audio":return e?"音频":"audio";case"image":return e?"图片":"images";case"weights":return e?"模型权重":"model weights";default:return e?"附件":"the extra files"}}function N(o,e,n){const t=f(o),l=t?m(t,j()):[];if(l.length>0){for(const o of l)for(const e of G(o,74))console.log(chalk.yellow(` ${e}`));console.log()}if(e?.needs_gpu)console.log(chalk.bold.white(" Your move — 4 steps (⚡ GPU task):")),console.log(chalk.gray(" 1. ")+chalk.bold.cyan(`icoa ipynb ${n}`)),console.log(chalk.gray(" 2. ")+chalk.bold.cyan("gpu key <your-key>")+chalk.gray(" then ")+chalk.bold.cyan("gpu on")+chalk.gray(" → ")+chalk.bold.cyan("run all")+chalk.gray(" (trains on the GPU box)")),console.log(chalk.gray(" 3. ")+chalk.bold.cyan("download <file>")+chalk.gray(" → pulls your results (submission.csv / predictions.zip) here")),console.log(chalk.gray(" 4. submit on kaggle.com — the notebook's final cell has the exact steps.")),console.log(),console.log(chalk.gray(" While you work: ")+chalk.cyan("gpu status")+chalk.gray(" your time left · ")+chalk.cyan("gpu queue")+chalk.gray(" who is on, who is waiting"));else{const l=t?.media?.pack,s="none"===(t?.baseline||"").trim();console.log(chalk.bold.white(l?A(" 接下来 4 步:"," Your move — 4 steps:"):A(" 接下来 3 步:"," Your move — 3 steps:")));let r=1;l&&console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`teleload ${l}`)+chalk.gray(A(` → 把${I(t?.media?.kind)}拉下来(CSV 里没有)`,` → fetch the ${I(t?.media?.kind)} (the CSVs do not carry it)`))),console.log(chalk.gray(` ${r++}. `)+chalk.bold.cyan(`icoa ipynb ${n}`)+chalk.gray(s?A(" → run all 到 FEATURES 那格会停,那格是你的活"," → run all stops at FEATURES — that cell is your job"):" → run all (baseline trains)")),console.log(chalk.gray(` ${r++}. it writes `)+chalk.white("submission.csv")+chalk.gray(" → verify with ")+chalk.cyan(`kaggle check ${o}`)),"icoa-holdout"===e?.judge?console.log(chalk.gray(` ${r}. `)+chalk.bold.cyan(`kaggle submit ${o}`)+chalk.gray(" → scored + ranked live.")):"nitro"===e?.judge?console.log(chalk.gray(` ${r}. scored at `)+chalk.cyan("judge.nitro-ai.org")+chalk.gray(" (not Kaggle) — or just work the val score. See below.")):console.log(chalk.gray(` ${r}. upload it on Kaggle yourself — then beat the baseline.`))}console.log(),console.log(chalk.bold.white(" 🤝 Want AI help? Set up your cockpit:")),console.log(chalk.gray(" 1. split the screen: ")+chalk.bold.cyan("Ctrl-b %")+chalk.gray(" (lesson/work left · AI right)")),console.log(chalk.gray(" 2. in the right pane: ")+chalk.bold.cyan("icoa")+chalk.gray(" → ↑↓ pick ")+chalk.bold.white("🧠 Learn")+chalk.gray(" → at ")+chalk.cyan("icoa learn>")+chalk.gray(" type ")+chalk.bold.cyan("ai4ioai")+chalk.gray(" → live Gemma 3")),console.log(chalk.gray(" 3. ask it for feature ideas or bug fixes — then ")+chalk.bold.white("VERIFY")+chalk.gray(" with your val score (a tip that lowers it, drop it).")),console.log(),P(e)}export async function runKaggleGuide(e){console.log();const t=C(e,"guide");if(!t)return;const l=E(t);let r=null;try{r=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{r=null}i(`kaggle: guide ${t}`);const a=s(l,"starter.ipynb"),c=o(s(l,"submission.csv"));console.log(chalk.bold.white(` ═══ 📖 ${r?.title??t} — walkthrough ═══`)),console.log(),console.log(chalk.gray(" Where you are: data ")+chalk.green("downloaded ✓")+chalk.gray(" · submission.csv: ")+(c?chalk.green("written ✓"):chalk.yellow("not yet — run the notebook"))),console.log(),N(t,r,a),console.log(),console.log(chalk.gray(" Inside the notebook, ")+chalk.cyan("guide")+chalk.gray(" shows the notebook-level guide.")),console.log()}function C(e,n){if(e)return e;const l=s(process.cwd(),"icoa-kaggle"),r=o(l)?t(l,{withFileTypes:!0}).filter(e=>e.isDirectory()&&(o(s(l,e.name,"sample_submission.csv"))||o(s(l,e.name,"meta.json")))).map(o=>o.name):[];if(1===r.length)return r[0];if(0===r.length)return console.log(chalk.yellow(" No downloaded competition found here — run ")+chalk.cyan("kaggle")+chalk.yellow(" first.")),console.log(),null;console.log(chalk.white(" Several competitions downloaded — pick one:"));for(const o of r)console.log(chalk.gray(` kaggle ${n} `)+chalk.cyan(o));return console.log(),null}export async function runKaggleCheck(e){console.log();const t=C(e,"check");if(!t)return;const l=E(t),r=s(l,"submission.csv"),a=s(l,"sample_submission.csv");try{if(JSON.parse(n(s(l,"meta.json"),"utf-8")).needs_gpu&&!o(a))return console.log(chalk.gray(" ⚡ GPU task — results are produced and validated by the notebook itself.")),console.log(chalk.gray(" Pull them with ")+chalk.cyan("download <file>")+chalk.gray(" inside ")+chalk.cyan("icoa ipynb")+chalk.gray(", then submit on kaggle.com (final cell has the steps).")),void console.log()}catch{}if(!o(a))return console.log(chalk.yellow(` No data for "${t}" here — run `)+chalk.cyan(`kaggle ${t}`)+chalk.yellow(" first.")),void console.log();if(!o(r))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(l,"starter.ipynb")}`)),void console.log();const g=p(n(r,"utf-8"),n(a,"utf-8"));i(`kaggle: check ${t} → ${g.ok?"ok":`rejected: ${g.problems[0]??"format"}`}`);let u=null;try{u=JSON.parse(n(s(l,"meta.json"),"utf-8"))}catch{u=null}if(g.ok)console.log(chalk.bold.green(" ✓ submission.csv has the right format")+chalk.gray(" (matches sample_submission.csv)")),console.log(chalk.gray(" ")+chalk.white(r)),console.log(),P(u),c(l);else{console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of g.problems)console.log(chalk.yellow(` · ${o}`));console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it."))}console.log()}export async function runKaggleSubmit(e,t){console.log();const l=C(e,"submit");if(!l)return;const a=E(l),c=s(a,"submission.csv"),g=s(a,"sample_submission.csv");let d=null;try{d=JSON.parse(n(s(a,"meta.json"),"utf-8"))}catch{d=null}if("local-eval"===d?.judge)return console.log(chalk.yellow(" This task is scored inside the notebook — nothing to upload.")),P(d),void console.log();if(!d||!o(g))return console.log(chalk.yellow(` No data for "${l}" here — run `)+chalk.cyan(`kaggle ${l}`)+chalk.yellow(" first.")),void console.log();if("icoa-holdout"!==d.judge)return console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here.")),console.log(),P(d),void console.log();if(!o(c))return console.log(chalk.yellow(" No submission.csv yet — open the notebook and run all cells:")),console.log(chalk.gray(" ")+chalk.cyan(`icoa ipynb ${s(a,"starter.ipynb")}`)),void console.log();const y=n(c,"utf-8"),h=p(y,n(g,"utf-8"));if(!h.ok){i(`kaggle: submit ${l} → local-reject: ${h.problems[0]??"format"}`),console.log(chalk.bold.red(" ✗ submission.csv would be rejected:"));for(const o of h.problems)console.log(chalk.yellow(` · ${o}`));return console.log(),console.log(chalk.gray(" Fix the submission cell in the notebook and re-run it.")),void console.log()}let m=u()?.token??"";if(!m){const o=r();try{m=(await o.ask(chalk.cyan(" Your learn token: "))??"").trim()}finally{o.close()}if(!m)return console.log(chalk.gray(" A learn token identifies you on the board — ask your coach for one.")),void console.log()}const f=Date.now();let k,w=null;process.stdout.isTTY?(process.stdout.write(chalk.gray(" ⚖ scoring on the server… 0.0s")),w=setInterval(()=>{process.stdout.write(chalk.gray(`\r ⚖ scoring on the server… ${((Date.now()-f)/1e3).toFixed(1)}s `))},200)):console.log(chalk.gray(" Scoring on the server…"));try{k=await _(`/api/icoa/kaggle/${l}/submit`,{token:m,submission_csv:y,...t?{job:t}:{}})}finally{w&&(clearInterval(w),process.stdout.write(`\r ${chalk.gray(`⚖ scored in ${((Date.now()-f)/1e3).toFixed(1)}s`)}${" ".repeat(12)}\n`))}const $=b(k);if(i(`kaggle: submit ${l} → ${$.ok?`${$.metric}=${$.score}${$.deduped?" (deduped)":""} rank=${$.rank??"-"}`:$.reason??"error"}`),console.log(),$.ok){const o=`${$.metric}: ${Number($.score).toFixed(4).replace(/\.?0+$/,"")}`,e="public"===$.leaderboard?chalk.gray(" (public leaderboard — the private split is revealed after the event)"):"";$.deduped&&$.sameCode?(console.log(chalk.bold.white(` ✓ same code as before — ${o}`)+e),console.log(chalk.gray(" The notebook code is unchanged, so this is the earlier result; it does not count as a submission."))):$.deduped?(console.log(chalk.bold.white(` ✓ already scored — ${o}`)+e),console.log(chalk.gray(" These exact predictions were scored before. Improve the MODEL cell and re-run."))):(console.log(chalk.bold.green(` ✓ scored — ${o}`)+e),"number"==typeof $.rank&&"number"==typeof $.fieldSize&&console.log(chalk.bold.white(` 🏁 board rank #${$.rank}`)+chalk.gray(` of ${$.fieldSize}`))),"number"==typeof $.used&&"number"==typeof $.cap&&console.log(chalk.gray(` ⚖ submissions used ${$.used}/${$.cap}`)),$.boardEvent&&console.log(chalk.gray(" standings: ")+chalk.cyan(`kaggle board ${l}`)+chalk.gray(" (or ")+chalk.cyan(`board ${$.boardEvent} ${l}`)+chalk.gray(")")),$.submissionId&&"public"===$.leaderboard&&console.log(chalk.gray(` id ${$.submissionId} · pick the two that count on the private board: `)+chalk.cyan(`kaggle final ${l} ${$.submissionId}`)+chalk.gray(" [<id2>] (unpicked = public best + last)"))}else switch($.reason){case"bad_token":console.log(chalk.bold.red(" ✗ that learn token was not accepted")+chalk.gray(" (invalid or expired)")),console.log(chalk.gray(" Check the token with your coach, then try again."));break;case"format":console.log(chalk.bold.red(" ✗ the server rejected submission.csv:"));for(const o of $.problems??[])console.log(chalk.yellow(` · ${o}`));break;case"event_closed":case"outside_window":console.log(chalk.bold.yellow(" ⏱ the submission window for this competition is closed."));break;case"cap_reached":console.log(chalk.bold.yellow(" ⏱ you have used all your submissions for this competition."));break;case"kaggle_judged":console.log(chalk.yellow(" This competition is judged on kaggle.com — nothing to submit here."));break;default:console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute."))}console.log()}export async function runKaggleFinal(o,e=[]){console.log();const n=C(o,"final");if(!n)return;const t=u()?.token??"";if(!t)return console.log(chalk.gray(" A learn token identifies you on the board — open Learn once with your token first.")),void console.log();const l=await _(`/api/icoa/kaggle/${n}/final`,{token:t,ids:e.slice(0,2)})??{},s=l.data??l??{};if("string"==typeof s.reason){if("bad_id"===s.reason){console.log(chalk.bold.red(` ✗ ${String(s.error)}`));const o=Array.isArray(s.yours)?s.yours:[];o.length>0&&console.log(chalk.gray(` your scored ids: ${o.join(", ")}`))}else"bad_token"===s.reason?console.log(chalk.bold.red(" ✗ that learn token was not accepted")):console.log(chalk.yellow(` ${String(s.error??s.reason)}`));return void console.log()}if(!Array.isArray(s.final))return console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const r=s.final;if(s.chosen&&r.length>0){console.log(chalk.bold.green(" ✓ your final picks for the private board:"));for(const o of r)console.log(chalk.white(` ${o.id}`)+chalk.gray(` public ${Number(o.score).toFixed(4)}`))}else console.log(chalk.white(" No picks yet — the auto rule applies: ")+chalk.gray(String(s.rule_if_unchosen??"public best + last")));const a=Array.isArray(s.yours)?s.yours:[];a.length>0&&(console.log(chalk.gray(` your last ${a.length} scored: `)+a.map(o=>`${o.id} ${Number(o.score).toFixed(4)}`).join(chalk.gray(" · "))),console.log(chalk.gray(" change: ")+chalk.cyan(`kaggle final ${n} <id> [<id>]`))),i(`kaggle: final ${n} → ${r.map(o=>o.id).join(",")||"auto"}`),console.log()}const K=o=>"number"==typeof o?o.toFixed(4):" – ";export async function runKaggleBoard(o){console.log();const e=o?.trim()||C(void 0,"board");if(!e)return;const n=u()?.token??"",t=await _(`/api/icoa/kaggle/${e}/board`,n?{token:n}:{})??{},l=t.data??t??{};if(!Array.isArray(l.public))return"unknown_comp"===l.reason?console.log(chalk.bold.red(` ✗ no competition called ${e}`)):console.log(chalk.yellow(" The scoring server is not reachable right now — try again in a minute.")),void console.log();const s=l.public,r="public"===l.leaderboard,a="number"==typeof l.public_fraction?Math.round(100*l.public_fraction):null;if(console.log(chalk.bold.white(` 🏆 ${String(l.title??e)}`)+chalk.gray(` · ${r?`public leaderboard (${a??"?"}% of the test set)`:"leaderboard (whole test set)"} · ${String(l.metric??"")}`)),l.closed&&console.log(chalk.yellow(" ⏹ closed — no more submissions are accepted")),0===s.length)console.log(chalk.gray(" nobody has scored yet — be the first: ")+chalk.cyan(`kaggle submit ${e}`));else{console.log(chalk.gray(" # who score subs"));for(const o of s){const e=` ${String(o.rank).padStart(3)} ${o.who.padEnd(9)} ${K(o.score)} ${String(o.n).padStart(3)}`;console.log(o.you?chalk.bold.green(`${e} ◀ you`):chalk.white(e))}}if(Array.isArray(l.private)){const o=l.private;console.log(),console.log(chalk.bold.white(" 🔒 private leaderboard — FINAL")+chalk.gray(r?` (the other ${100-(a??0)}% of the test set)`:"")),console.log(chalk.gray(" # who private public sub id code seat picked"));for(const e of o){const o=` ${String(e.rank).padStart(3)} ${e.who.padEnd(9)} ${K(e.score)} ${K(e.public_score)} ${(e.sub_id??"-").padEnd(12)} ${(e.code_sha??"-").padEnd(12)} ${(e.job_sid??"-").padEnd(20)} ${e.how??""}`;console.log(e.you?chalk.bold.green(`${o} ◀ you`):chalk.white(o))}console.log(chalk.gray(" picked = chosen (kaggle final) or auto (public best + last) · code = sha of the notebook cells that made it"))}else r&&(console.log(chalk.gray(" (private split is revealed by the organiser after the event — then it shows here)")),n&&console.log(chalk.gray(" pick the two that count: ")+chalk.cyan(`kaggle final ${e} <id> [<id>]`)));i(`kaggle: board ${e} → ${s.length} rows${Array.isArray(l.private)?" + private":""}`),console.log()}export function registerKaggleCommand(o){o.command("kaggle").argument("[action]",'competition id, or "check" / "submit" / "board" / "final"').argument("[comp]",'competition id (with "check" / "submit" / "board" / "final")').argument("[ids...]",'submission ids (with "final")').description("Kaggle-style ML practice — dataset + starter notebook, check & submit & board & final").action(async(o,e,n=[])=>{"check"===o?await runKaggleCheck(e):"submit"===o?await runKaggleSubmit(e):"board"===o?await runKaggleBoard(e):"final"===o?await runKaggleFinal(e,n):"guide"===o?await runKaggleGuide(e):await runKaggle(o)}),o.command("guide").argument("[comp]","competition id").description("Show the competition walkthrough (3 steps + AI cockpit)").action(async o=>{await runKaggleGuide(o)})}