From b242b0ca21a302456a9845ffa123c6bb0686df71 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Sat, 14 Nov 2026 21:41:02 +0000 Subject: [PATCH 1/2] feat(agents c0mpute): every c0mpute chat command, out of the box (v0.126.0) `moshcode agents c0mpute` now takes the same lines as c0mpute.com/chat: /image, /video, /music, /album, /promo (and their aliases), /push hosting, /connect hosting, /plugin, plus /login. Parsers are ports of c0mpute's apps/web/src/lib/chat/*.ts with the same regexes; plain text asking for a promo video of a link becomes /promo, as in the chat. Media jobs run as background tasks on the task board and save to ./c0mpute-media/. With no sign-in they go to Infernet /api/chat/* with the ik_live_ key moshcode already has (or the free tier); with a c0mpute.com key (/login device flow, `c0mpute chat login`, or C0MPUTE_CHAT_KEY) they run on the account via /api/v1/*, which /push, /connect and /plugin need. Print mode runs a media line in the foreground and prints the saved paths. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 ++ package.json | 2 +- src/c0agent-repl.mjs | 42 ++- src/c0chat-commands.mjs | 598 ++++++++++++++++++++++++++++++++++ src/c0chat-handler.mjs | 216 ++++++++++++ test/c0chat-commands.test.mjs | 223 +++++++++++++ 6 files changed, 1100 insertions(+), 3 deletions(-) create mode 100644 src/c0chat-commands.mjs create mode 100644 src/c0chat-handler.mjs create mode 100644 test/c0chat-commands.test.mjs diff --git a/README.md b/README.md index 9e8d09af..30445686 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,28 @@ Inside a session: | `/model`, `/models` | switch the model (saved), list what nodes serve | | `/todos`, `/compact`, `/clear`, `/cost`, `/key`, `/cwd` | checklist, shrink context, fresh chat, usage, key, directory | +The session also takes every command c0mpute.com/chat does, out of the box. Media +jobs run in the background (keep working; `/tasks` shows them) and save to +`./c0mpute-media/`: + +| | | +|---|---| +| `/image ` | a picture from a c0mpute CPU worker (also `/img`, `/draw`) | +| `/video [--model wan2.2-ti2v-5b]` | a short clip (also `/clip`, `/vid`) | +| `/music +

${t}

+${body} + + +`; + // Inline text is capped at 1 MiB per push: keep the transcript under it. + const cap = (s) => (Buffer.byteLength(s) > 400_000 ? `${s.slice(0, 400_000)}\n…` : s); + return [ + { path: "index.html", type: "text/html", text: cap(html) }, + { path: "chat.md", type: "text/markdown", text: cap(`# ${title || "c0mpute chat"}\n\n${md}\n`) }, + ...files, + ]; +} diff --git a/src/c0chat-handler.mjs b/src/c0chat-handler.mjs new file mode 100644 index 00000000..bcf7b0e9 --- /dev/null +++ b/src/c0chat-handler.mjs @@ -0,0 +1,216 @@ +// Runs the c0mpute chat's slash commands (src/c0chat-commands.mjs) for the +// `moshcode agents c0mpute` REPL and its print mode. Media jobs take minutes +// (a clip: half an hour), so in the REPL each one is a background task on the +// task board, the way the chat keeps a card rendering while you type. + +import path from "node:path"; +import { saveConfig } from "./c0agent.mjs"; +import { + CHAT_HELP, PLUGIN_HELP, chatApi, chatKeyConfig, collectPushFiles, deviceLogin, mediaBackend, runMediaJob, +} from "./c0chat-commands.mjs"; +import { acid, amber, ash, bone, danger, dim, err, ok, warn } from "./ui.mjs"; + +const LABEL = { image: "image", video: "video", music: "song", album: "album", promo: "promo video" }; +const sleep = (ms, signal) => new Promise((resolve, reject) => { + const t = setTimeout(resolve, ms); + signal?.addEventListener("abort", () => { clearTimeout(t); reject(new Error("stopped")); }, { once: true }); +}); + +/** + * `ctx`: { cfg, cwd(): string, log(line), board?, transcript: [], media: [], + * foreground(fn): runs fn(signal) as an interruptible foreground step, + * fetchImpl?, home? } + * Returns handle(parsed) → Promise; `parsed` comes from parseChatCommand. + */ +export function createChatHandler(ctx) { + const fetchImpl = ctx.fetchImpl ?? globalThis.fetch; + const log = ctx.log; + const chat = () => chatKeyConfig(ctx.home ? { home: ctx.home } : undefined); + const outDir = () => path.join(ctx.cwd(), "c0mpute-media"); + const rel = (p) => { const r = path.relative(ctx.cwd(), p); return r.startsWith("..") ? p : r; }; + + function mediaTask(parsed) { + const backend = mediaBackend(ctx.cfg, chat()); + const title = `/${parsed.media} ${parsed.prompt}`.slice(0, 200); + ctx.transcript.push({ role: "user", content: title }); + const turn = ctx.transcript.length - 1; + const run = (signal, onStatus) => runMediaJob({ + kind: parsed.media, body: parsed.body, prompt: parsed.prompt, backend, outDir: outDir(), onStatus, signal, fetchImpl, + }).then((r) => { + ctx.media.push({ ...r.record, turn }); + const lines = [`saved ${r.files.map((f) => rel(f.path)).join(", ")}`, r.summary]; + ctx.transcript.push({ role: "assistant", content: `${LABEL[parsed.media]}: ${r.title ?? parsed.prompt}` }); + return { ...r, text: lines.join("\n") }; + }); + if (!ctx.board) return { backend, run }; + const t = ctx.board.add({ title, agent: `c0mpute ${LABEL[parsed.media]}`, background: true, cwd: ctx.cwd() }); + const controller = new AbortController(); + t.controller = controller; + ctx.board.update(t, { activity: `sending to ${backend.name}` }); + let lastLine = ""; + run(controller.signal, (line) => { + if (!line || line === lastLine) return; + lastLine = line; + ctx.board.update(t, { activity: line }); + ctx.board.note(t, line); + }).then( + (r) => ctx.board.update(t, { state: "completed", activity: "done", result: r.text }), + (e) => ctx.board.update(t, controller.signal.aborted ? { state: "stopped", activity: "stopped" } : { state: "failed", error: String(e?.message || e) }), + ); + log(`${acid("◐")} ${ash(`#${t.id}`)} ${bone(`${LABEL[parsed.media]} started on ${backend.name}`)} ${ash(`— keep working; it saves to ./${rel(outDir())}/ · /tasks ${t.id} to watch`)}`); + if (!backend.key) log(ash(" no key: the free tier allows 10 a day · /key ik_live_… or /login for more")); + return t; + } + + async function push(cmd) { + const api = chatApi(chat(), { fetchImpl }); + if (cmd.kind === "help") { + if (cmd.error) log(err(cmd.error)); + log(ash(" usage: /push hosting · /push hosting ls · /push hosting rm ")); + return; + } + if (cmd.kind === "ls") { + const r = await api.must("/api/v1/hosting/pushes"); + const list = r.pushes ?? []; + if (!list.length) { log(ash(" no sites yet: /push hosting ")); return; } + for (const p of list) log(` ${p.status === "live" ? acid("●") : p.status === "failed" ? danger("✗") : amber("◐")} ${bone(p.name)} ${ash(p.status)}${p.url ? ` ${p.url}` : ""}${p.error ? ` ${danger(p.error)}` : ""}`); + return; + } + if (cmd.kind === "rm") { + const r = await api.call(`/api/v1/hosting/pushes/${encodeURIComponent(cmd.name)}`, { method: "DELETE" }); + if (!r.ok) throw new Error(r.body?.error?.message || `HTTP ${r.status}`); + log(ok(r.status === 202 ? `${cmd.name} is being taken down` : `${cmd.name} deleted`)); + return; + } + const mine = ctx.media.filter((m) => m.pushable); + const skipped = ctx.media.length - mine.length; + if (skipped) log(warn(` ${skipped} result${skipped === 1 ? " was" : "s were"} made before /login (on the open network), so ${skipped === 1 ? "it stays" : "they stay"} out of the site`)); + const files = collectPushFiles(cmd.name, ctx.transcript, ctx.media); + const node = ctx.pushNode?.() ?? null; + const r = await api.call("/api/v1/hosting/pushes", { method: "POST", body: { name: cmd.name, files, ...(node ? { node } : {}) } }); + if (r.status === 409) throw new Error(`${r.body?.error?.message || "no hosting node"} — link one with \`c0mpute chat connect hosting\` on a node, then /connect hosting`); + if (!r.ok) throw new Error(r.body?.error?.message || `HTTP ${r.status}`); + const id = r.body?.push?.id ?? cmd.name; + log(`${acid("◐")} ${bone(`publishing ${cmd.name}`)} ${ash(`(${files.length} files${r.body?.push?.node ? ` on ${r.body.push.node}` : ""})`)}`); + await ctx.foreground(async (signal) => { + const until = Date.now() + 2 * 3600_000; + let last = ""; + while (Date.now() < until) { + await sleep(3000, signal); + const s = await api.call(`/api/v1/hosting/pushes/${encodeURIComponent(id)}`, { signal }).catch(() => null); + if (!s || s.status >= 500) continue; + if (!s.ok) throw new Error(s.body?.error?.message || `HTTP ${s.status}`); + const p = s.body?.push ?? {}; + const line = `${p.status}${p.progress ? ` · ${p.progress}` : ""}`; + if (line !== last) { last = line; ctx.status?.(line); } + if (p.status === "live") { log(ok(`${cmd.name} is live: ${p.url}${p.copies ? ash(` (${p.copies} copies)`) : ""}`)); return; } + if (p.status === "failed") throw new Error(p.error || "the push failed"); + } + throw new Error("still not live after 2 h — /push hosting ls"); + }); + } + + async function connect(cmd) { + if (cmd.error) { log(err(cmd.error)); return; } + const api = chatApi(chat(), { fetchImpl }); + const r = await api.must("/api/v1/hosting/nodes"); + const nodes = r.nodes ?? []; + if (!cmd.node) { + if (!nodes.length) { log(ash(" no hosting nodes: run `c0mpute chat connect hosting --name ` on the machine that should publish (pushes fall back to the shared cloud node)")); return; } + const cur = ctx.pushNode?.(); + for (const n of nodes) log(` ${n.name === cur ? acid("●") : " "} ${bone(n.name)} ${n.online ? acid("online") : ash("offline")}${n.version ? ash(` v${n.version}`) : ""}${n.payments ? ash(` · ${n.payments}`) : ""}`); + log(ash(" /connect hosting picks the one /push uses")); + return; + } + const n = nodes.find((x) => x.name === cmd.node); + if (!n) throw new Error(`no hosting node "${cmd.node}" on your account — /connect hosting lists them`); + saveConfig({ pushNode: n.name }, ctx.home ? { home: ctx.home } : undefined); + log(ok(`/push will publish on ${n.name}${n.online ? "" : ash(" (offline right now)")}`)); + } + + async function plugin(cmd) { + const api = chatApi(chat(), { fetchImpl }); + if (cmd.kind === "help") { if (cmd.error) log(err(cmd.error)); for (const l of PLUGIN_HELP.split("\n")) log(ash(` ${l}`)); return; } + if (cmd.kind === "ls") { + const r = await api.must("/api/v1/chat/plugins"); + const mine = r.plugins ?? []; + if (mine.length) log(bone("your plugins")); + for (const p of mine) log(` ${p.status === "on" ? acid("●") : p.status === "needs_sign_in" ? amber("●") : ash("○")} ${bone(p.slug)} ${ash(p.status)}${p.tools?.length ? ash(` · ${p.tools.length} tools`) : ""}${p.connect_url && p.status === "needs_sign_in" ? `\n sign in: ${p.connect_url}` : ""}`); + const cat = (r.catalog ?? []).filter((c) => !c.added); + if (cat.length) { log(bone("catalog")); for (const c of cat) log(` ${bone(c.slug ?? c.name)} ${ash(c.title ?? c.description ?? "")}`); } + if (!mine.length && !cat.length) log(ash(" none yet: /plugin add ")); + log(ash(" plugins give tools to chats on c0mpute.com (web chat, TUI, /v1 API)")); + return; + } + if (cmd.kind === "add") { + const body = /^https?:\/\//i.test(cmd.target) ? { url: cmd.target } : { slug: cmd.target.toLowerCase() }; + const r = await api.must("/api/v1/chat/plugins", { method: "POST", body }); + log(ok(`added ${r.plugin?.slug ?? cmd.target}`)); + if (r.connect_url) log(` ${amber("sign in")} ${r.connect_url} ${ash("(link valid 10 min)")}`); + return; + } + if (cmd.kind === "rm") { await api.must(`/api/v1/chat/plugins/${cmd.slug}`, { method: "DELETE" }); log(ok(`removed ${cmd.slug}`)); return; } + if (cmd.kind === "on" || cmd.kind === "off") { + await api.must(`/api/v1/chat/plugins/${cmd.slug}/toggle`, { method: "POST", body: { enabled: cmd.kind === "on" } }); + log(ok(`${cmd.slug} ${cmd.kind}`)); + return; + } + if (cmd.kind === "connect") { const r = await api.must(`/api/v1/chat/plugins/${cmd.slug}/connect`); log(` ${amber("sign in")} ${r.connect_url}`); } + } + + async function login() { + const c = chat(); + if (c.key) log(ash(` already signed in (${c.source}); signing in again replaces moshcode's copy`)); + await ctx.foreground(async (signal) => { + const key = await deviceLogin(c, { + signal, fetchImpl, + onCode: ({ url, code }) => { log(` open ${bone(url)}`); log(ash(` code ${code} · waiting for the browser (esc to cancel)`)); }, + }); + const file = saveConfig({ chatKey: key }, ctx.home ? { home: ctx.home } : undefined); + log(ok(`signed in to c0mpute.com · key saved to ${file} (0600)`)); + log(ash(" /image /music /album /promo /video now run on your c0mpute.com account, and /push, /connect, /plugin work")); + }); + } + + return async function handle(parsed) { + switch (parsed.kind) { + case "usage": log(ash(` ${parsed.message}`)); return null; + case "media": return mediaTask(parsed); + case "push": return push(parsed.cmd); + case "connect": return connect(parsed.cmd); + case "plugin": return plugin(parsed.cmd); + case "login": return login(); + default: return null; + } + }; +} + +export const CHAT_HELP_ROWS = CHAT_HELP; + +/** Print mode: run a media line in the foreground, file paths on stdout. */ +export async function runChatPrint(parsed, { cfg, cwd }) { + const transcript = []; + const media = []; + const errLog = (l) => process.stderr.write(`${l}\n`); + const controller = new AbortController(); + process.once("SIGINT", () => controller.abort()); + const handle = createChatHandler({ + cfg, cwd: () => cwd, log: errLog, transcript, media, + foreground: (fn) => fn(controller.signal), + status: (l) => errLog(dim(` ${l}`)), + pushNode: () => null, + }); + try { + if (parsed.kind !== "media") { await handle(parsed); return 0; } + const { backend, run } = await handle(parsed); + errLog(ash(`${LABEL[parsed.media]} on ${backend.name}…`)); + let last = ""; + const r = await run(controller.signal, (l) => { if (l && l !== last) { last = l; errLog(dim(` ${l}`)); } }); + for (const f of r.files) process.stdout.write(`${f.path}\n`); + errLog(ok(r.summary)); + return 0; + } catch (e) { + errLog(err(String(e?.message || e))); + return 1; + } +} diff --git a/test/c0chat-commands.test.mjs b/test/c0chat-commands.test.mjs new file mode 100644 index 00000000..d68cface --- /dev/null +++ b/test/c0chat-commands.test.mjs @@ -0,0 +1,223 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { + chatKeyConfig, collectPushFiles, describePending, deviceLogin, mediaBackend, parseChatCommand, parseMusicCommand, + parsePluginCommand, parsePromoCommand, parsePushCommand, parseVideoCommand, runMediaJob, +} from "../src/c0chat-commands.mjs"; + +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "c0chat-")); +const noSleep = async () => {}; +const ID = "0f8fad5b-d9cb-469f-a165-70867728950e"; + +/** A fetch that answers from a list of [method path, response] rules, in order per path. */ +function fakeFetch(routes) { + const calls = []; + const queues = new Map(Object.entries(routes).map(([k, v]) => [k, Array.isArray(v) ? [...v] : [v]])); + const impl = async (url, init = {}) => { + const u = new URL(url); + const key = `${init.method || "GET"} ${u.pathname}`; + calls.push({ key, init, url }); + const q = queues.get(key); + if (!q || !q.length) return new Response("not found", { status: 404 }); + const r = q.length > 1 ? q.shift() : q[0]; + const { status = 200, json, body, type } = r; + if (json !== undefined) return new Response(JSON.stringify(json), { status, headers: { "content-type": "application/json" } }); + return new Response(body ?? "", { status, headers: { "content-type": type ?? "application/octet-stream" } }); + }; + return { impl, calls }; +} + +const infernet = { name: "c0mpute network", base: "https://inf.test", key: "ik_live_x", paths: mediaBackend({ baseUrl: "https://inf.test" }, { key: null }).paths, pushable: false }; + +test("parseChatCommand routes every chat command the way c0mpute.com/chat does", () => { + assert.deepEqual(parseChatCommand("/image a red bicycle"), { kind: "media", media: "image", prompt: "a red bicycle", body: { prompt: "a red bicycle", size: "landscape" } }); + assert.equal(parseChatCommand("/img cat").media, "image"); + assert.equal(parseChatCommand("/draw cat").media, "image"); + assert.equal(parseChatCommand("/song lo-fi").media, "music"); + assert.equal(parseChatCommand("/lp drowned city synthwave").media, "album"); + assert.equal(parseChatCommand("/clip a paper boat").media, "video"); + assert.equal(parseChatCommand("/promo c0mpute.com anime vertical").media, "promo"); + assert.equal(parseChatCommand("/push hosting mysite").kind, "push"); + assert.equal(parseChatCommand("/connect hosting").kind, "connect"); + assert.equal(parseChatCommand("/plugins").kind, "plugin"); + assert.equal(parseChatCommand("/login").kind, "login"); + // bare commands give the chat's usage line, never the model + assert.deepEqual(parseChatCommand("/image"), { kind: "usage", message: "usage: /image " }); + assert.deepEqual(parseChatCommand("/video"), { kind: "usage", message: "usage: /video " }); + assert.equal(parseChatCommand("/album").kind, "usage"); + // the agent's own commands and plain tasks are not chat commands + for (const l of ["/help", "/agents", "/clear", "/model x", "fix the failing test in src/app.js", "@explore find the router"]) assert.equal(parseChatCommand(l), null, l); + // plain text asking for a promo of a link becomes /promo, as in the chat + const p = parseChatCommand("make a claymation promo video for https://moshcode.sh"); + assert.equal(p.media, "promo"); + assert.deepEqual({ url: p.body.url, style: p.body.style }, { url: "https://moshcode.sh", style: "claymation" }); +}); + +test("argument rules match the chat's parsers", () => { + assert.deepEqual(parseMusicCommand("/music lo-fi hip hop lyrics: la la la"), { prompt: "lo-fi hip hop", lyrics: "la la la" }); + assert.deepEqual(parseMusicCommand("/music jazz\nlyrics:\nhello\nworld"), { prompt: "jazz", lyrics: "hello\nworld" }); + assert.deepEqual(parseVideoCommand("/video --model wan2.2-ti2v-5b a fox"), { prompt: "a fox", model: "wan2.2-ti2v-5b" }); + assert.match(parseVideoCommand("/video --model nope a fox"), /model must be one of/); + assert.deepEqual(parsePromoCommand("/promo https://c0mpute.com ghibli tiktok"), { url: "https://c0mpute.com", style: "anime", vertical: true, brief: "ghibli tiktok" }); + assert.deepEqual(parsePromoCommand("/promo example.dev"), { url: "https://example.dev", style: "pixar", vertical: false, brief: "example.dev" }); + assert.deepEqual(parsePushCommand("/push ls"), { kind: "ls" }); + assert.deepEqual(parsePushCommand("/push hosting rm my-site"), { kind: "rm", name: "my-site" }); + assert.equal(parsePushCommand("/push hosting Bad_Name").kind, "help"); + assert.deepEqual(parsePluginCommand("/plugin https://mcp.example.com/mcp"), { kind: "add", target: "https://mcp.example.com/mcp" }); + assert.deepEqual(parsePluginCommand("/plugin off github"), { kind: "off", slug: "github" }); +}); + +test("mediaBackend: Infernet with the model key out of the box, c0mpute.com once signed in", () => { + const open = mediaBackend({ baseUrl: "https://infernetprotocol.com/", apiKey: "ik_live_a" }, { key: null }); + assert.equal(open.base, "https://infernetprotocol.com"); + assert.equal(open.paths.image, "/api/chat/image"); + assert.equal(open.key, "ik_live_a"); + const signedIn = mediaBackend({ apiKey: "ik_live_a" }, { key: "c0k_b", url: "https://c0mpute.com" }); + assert.equal(signedIn.paths.image, "/api/v1/images"); + assert.equal(signedIn.key, "c0k_b"); + assert.equal(signedIn.pushable, true); +}); + +test("chatKeyConfig: env, then moshcode's /login copy, then `c0mpute chat login`; never an ik_live_ key", () => { + const home = tmp(); + assert.equal(chatKeyConfig({ env: {}, home }).key, null); + fs.mkdirSync(path.join(home, ".c0mpute")); + fs.writeFileSync(path.join(home, ".c0mpute", "chat.json"), JSON.stringify({ key: "c0k_cli", url: "https://staging.c0mpute.com/" })); + assert.deepEqual(chatKeyConfig({ env: {}, home }).key, "c0k_cli"); + assert.equal(chatKeyConfig({ env: {}, home }).url, "https://staging.c0mpute.com"); + fs.mkdirSync(path.join(home, ".moshcode")); + fs.writeFileSync(path.join(home, ".moshcode", "c0mpute.json"), JSON.stringify({ apiKey: "ik_live_z", chatKey: "c0k_mosh" })); + assert.equal(chatKeyConfig({ env: {}, home }).key, "c0k_mosh"); + assert.equal(chatKeyConfig({ env: { C0MPUTE_CHAT_KEY: "c0k_env", C0MPUTE_API_KEY: "c0k_ignored" }, home }).key, "c0k_env"); + assert.equal(chatKeyConfig({ env: { C0MPUTE_CHAT_KEY: "ik_live_wrong" }, home }).key, "c0k_mosh"); +}); + +test("runMediaJob /image: polls through queued + a deploy 503, saves the one-shot PNG", async () => { + const dir = tmp(); + const { impl, calls } = fakeFetch({ + "POST /api/chat/image": { status: 202, json: { id: ID, status: "pending", poll: `/api/chat/image/${ID}` } }, + [`GET /api/chat/image/${ID}`]: [ + { status: 202, json: { stage: "queued", queue_position: 2 } }, + { status: 503, body: "deploying", type: "text/html" }, + { status: 200, body: "PNGDATA", type: "image/png" }, + ], + }); + const lines = []; + const r = await runMediaJob({ kind: "image", body: { prompt: "a red bicycle" }, prompt: "a red bicycle", backend: infernet, outDir: dir, onStatus: (l) => lines.push(l), fetchImpl: impl, sleep: noSleep }); + assert.equal(r.files.length, 1); + assert.match(path.basename(r.files[0].path), /^a-red-bicycle-0f8fad5b\.png$/); + assert.equal(fs.readFileSync(r.files[0].path, "utf8"), "PNGDATA"); + assert.ok(lines.some((l) => /#2 in line/.test(l))); + assert.ok(lines.some((l) => /restarting \(HTTP 503\)/.test(l))); + assert.equal(calls[0].init.headers.authorization, "Bearer ik_live_x"); + assert.equal(JSON.parse(calls[0].init.body).prompt, "a red bicycle"); +}); + +test("runMediaJob /music keeps the title and lyrics from the 202s and saves song, cover and lyrics", async () => { + const dir = tmp(); + const { impl } = fakeFetch({ + "POST /api/chat/music": { status: 202, json: { id: ID, poll: `/api/chat/music/${ID}` } }, + [`GET /api/chat/music/${ID}`]: [ + { status: 202, json: { stage: "writing" } }, + { status: 202, json: { title: "Neon Rain", lyrics: "la la", node: { stage: "rendering", worker: "12D3KooWabcdefgh", eta_s: 120, stage_elapsed_s: 30 } } }, + { status: 200, body: "MP3", type: "audio/mpeg" }, + ], + [`GET /api/chat/music/${ID}/cover`]: { status: 200, body: "COVER", type: "image/png" }, + }); + const lines = []; + const r = await runMediaJob({ kind: "music", body: { prompt: "synthwave", lyrics: "" }, prompt: "synthwave", backend: infernet, outDir: dir, onStatus: (l) => lines.push(l), fetchImpl: impl, sleep: noSleep }); + assert.deepEqual(r.files.map((f) => path.basename(f.path)), ["Neon Rain-0f8fad5b.mp3", "Neon Rain-0f8fad5b.png", "Neon Rain-0f8fad5b-lyrics.txt"]); + assert.equal(r.title, "Neon Rain"); + assert.ok(lines.some((l) => /rendering on node …abcdefgh/.test(l))); + assert.match(fs.readFileSync(path.join(dir, "Neon Rain-0f8fad5b-lyrics.txt"), "utf8"), /Neon Rain\n\nla la/); +}); + +test("runMediaJob /album downloads the zip and the cover named after the band", async () => { + const dir = tmp(); + const { impl } = fakeFetch({ + "POST /api/chat/album": { status: 202, json: { id: ID, poll: `/api/chat/album/${ID}`, tracks: 3, limited: true } }, + [`GET /api/chat/album/${ID}`]: [ + { status: 202, json: { stage: "recording", band: "Rusty Waves", album: "Metal Tides", tracks: [{ status: "done" }, { status: "pending" }, { status: "planned" }] } }, + { status: 200, json: { stage: "done", band: "Rusty Waves", album: "Metal Tides", zip: `/api/chat/album/${ID}/zip`, cover: "ready" } }, + ], + [`GET /api/chat/album/${ID}/zip`]: { status: 200, body: "ZIP", type: "application/zip" }, + [`GET /api/chat/album/${ID}/cover`]: { status: 200, body: "PNG", type: "image/png" }, + }); + const lines = []; + const r = await runMediaJob({ kind: "album", body: { prompt: "sea metal" }, prompt: "sea metal", backend: infernet, outDir: dir, onStatus: (l) => lines.push(l), fetchImpl: impl, sleep: noSleep }); + assert.deepEqual(r.files.map((f) => path.basename(f.path)), ["Rusty Waves - Metal Tides.zip", "Rusty Waves - Metal Tides.png"]); + assert.equal(r.title, '"Metal Tides" by Rusty Waves'); + assert.ok(lines.some((l) => /only 3 free songs left/.test(l))); + assert.ok(lines.some((l) => /1\/3 done/.test(l))); +}); + +test("runMediaJob /promo and /video fetch the MP4 the done body points at", async () => { + const dir = tmp(); + const { impl } = fakeFetch({ + "POST /api/chat/promo": { status: 202, json: { id: ID, poll: `/api/chat/promo/${ID}` } }, + [`GET /api/chat/promo/${ID}`]: [ + { status: 202, json: { stages: { brand: { state: "done" }, script: { state: "running", detail: "writing scenes" } } } }, + { status: 200, json: { status: "done", title: "moshcode", duration: 30 } }, + ], + [`GET /api/chat/promo/${ID}/video`]: { status: 200, body: "MP4", type: "video/mp4" }, + "POST /api/chat/video": { status: 202, json: { id: ID, poll: `/api/chat/video/${ID}`, video: `/api/chat/video/${ID}/video` } }, + [`GET /api/chat/video/${ID}`]: { status: 200, json: { status: "done", video: `/api/chat/video/${ID}/video` } }, + [`GET /api/chat/video/${ID}/video`]: { status: 200, body: "CLIP", type: "video/mp4" }, + }); + const lines = []; + const p = await runMediaJob({ kind: "promo", body: { url: "https://moshcode.sh" }, prompt: "moshcode.sh", backend: infernet, outDir: dir, onStatus: (l) => lines.push(l), fetchImpl: impl, sleep: noSleep }); + assert.deepEqual(p.files.map((f) => path.basename(f.path)), ["moshcode-0f8fad5b.mp4"]); + assert.ok(lines.some((l) => l === "script: writing scenes · 1/7 stages")); + const v = await runMediaJob({ kind: "video", body: { prompt: "a fox" }, prompt: "a fox", backend: infernet, outDir: dir, fetchImpl: impl, sleep: noSleep }); + assert.equal(fs.readFileSync(v.files[0].path, "utf8"), "CLIP"); +}); + +test("runMediaJob turns 429 / 402 / a job failure into a readable error", async () => { + const dir = tmp(); + const limited = fakeFetch({ "POST /api/chat/image": { status: 429, json: { error: "free daily limit reached" } } }); + await assert.rejects(runMediaJob({ kind: "image", body: {}, prompt: "x", backend: infernet, outDir: dir, fetchImpl: limited.impl, sleep: noSleep }), /free daily limit reached/); + const failed = fakeFetch({ + "POST /api/chat/image": { status: 202, json: { id: ID, poll: `/api/chat/image/${ID}` } }, + [`GET /api/chat/image/${ID}`]: { status: 500, json: { error: "diffusion worker crashed" } }, + }); + await assert.rejects(runMediaJob({ kind: "image", body: {}, prompt: "x", backend: infernet, outDir: dir, fetchImpl: failed.impl, sleep: noSleep }), /diffusion worker crashed/); +}); + +test("describePending covers every kind", () => { + assert.match(describePending("image", { stage: "rendering", detail: "step 4/20" }), /step 4\/20/); + assert.match(describePending("video", { stage: "rendering", eta_s: 600 }), /about 10 min left/); + assert.match(describePending("music", { stage: "writing" }), /writing lyrics/); + assert.match(describePending("album", { stage: "planning", tracksWanted: 8 }), /8 songs/); +}); + +test("collectPushFiles: c0mpute.com results by src, open-network ones left out, page + chat.md first", () => { + const files = collectPushFiles("demo", [ + { role: "user", content: "/image a cat" }, + { role: "assistant", content: "image: a cat" }, + { role: "user", content: "/music lo-fi" }, + ], [ + { kind: "image", id: "img1", pushable: true, turn: 0 }, + { kind: "music", id: "song1", title: "Night Drive", audioType: "audio/mpeg", pushable: true, turn: 2 }, + { kind: "image", id: "open1", pushable: false, turn: 0 }, + { kind: "album", id: "alb1", album: { band: "B", album: "A", zip: "/x", cover: true }, pushable: true }, + ]); + assert.deepEqual(files.map((f) => f.path), ["index.html", "chat.md", "images/01.png", "music/01 - Night Drive.mp3", "music/01 - Night Drive.png", "albums/B - A.zip", "albums/B - A.png"]); + assert.equal(files[2].src, "/api/v1/images/img1"); + assert.match(files[0].text, / { + const { impl, calls } = fakeFetch({ + "POST /api/v1/cli/device": { status: 200, json: { device_code: "dc", user_code: "ABCD-EFGH", verification_uri_complete: "https://c0mpute.com/device?code=ABCD-EFGH", interval: 1, expires_in: 60 } }, + "POST /api/v1/cli/token": [{ status: 428, json: { error: { message: "pending" } } }, { status: 200, json: { key: "c0k_new" } }], + }); + let shown; + const key = await deviceLogin({ url: "https://c0mpute.com", key: null }, { fetchImpl: impl, sleep: noSleep, onCode: (c) => { shown = c; } }); + assert.equal(key, "c0k_new"); + assert.equal(shown.code, "ABCD-EFGH"); + assert.equal(calls.filter((c) => c.key === "POST /api/v1/cli/token").length, 2); + assert.equal(calls[0].init.headers.authorization, undefined); +}); From 524ee45f9a512c5cd73e4d95099c25cc95ca2410 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Sat, 14 Nov 2026 22:04:12 +0000 Subject: [PATCH 2/2] fix(agents c0mpute): print mode prints a queued job's line once, not every timer tick Co-Authored-By: Claude Opus 5.5 --- src/c0chat-handler.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/c0chat-handler.mjs b/src/c0chat-handler.mjs index bcf7b0e9..76b8c531 100644 --- a/src/c0chat-handler.mjs +++ b/src/c0chat-handler.mjs @@ -205,7 +205,9 @@ export async function runChatPrint(parsed, { cfg, cwd }) { const { backend, run } = await handle(parsed); errLog(ash(`${LABEL[parsed.media]} on ${backend.name}…`)); let last = ""; - const r = await run(controller.signal, (l) => { if (l && l !== last) { last = l; errLog(dim(` ${l}`)); } }); + // A queued job's line only changes its m:ss timer: print it when the words change. + const key = (l) => String(l).replace(/\b\d+:\d\d\b/g, ""); + const r = await run(controller.signal, (l) => { if (l && key(l) !== last) { last = key(l); errLog(dim(` ${l}`)); } }); for (const f of r.files) process.stdout.write(`${f.path}\n`); errLog(ok(r.summary)); return 0;