import path from "node:path"; import { getJob, jobView, runningJob, startJob } from "@/lib/jobs"; import { buildArgv, cliLine, confirmOf, pathArgsOf } from "@/lib/cli/argv.mjs"; import { confineToProject } from "@/lib/cli/confine.mjs"; import { formVerbs, verbRow } from "@/lib/cli/verbs.mjs"; import { resolveProject } from "@/lib/projects/core.mjs"; import { resolveProjectPath } from "@/lib/projects"; import { addStep, getStep, isQid, listSteps, logFileOf, logTail } from "@/lib/queue/store.mjs"; import { kickQueue, queueDir, queueRunnerStatus } from "@/lib/queue/runner"; import { UMTOOL_DIR } from "@/lib/report/driver.mjs"; import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs"; export const dynamic = "force-dynamic"; // ⌘K COMMANDS (umtool redesign, lane palette L8a; umtool/docs/knobs.md, "⌘K commands"): // the verb registry's forms, run. // // GET { verbs, context, queue }: every ui:"form" row (lib/cli/verbs.mjs: // verb, summary, target, queue, args) and, with ?path=, what the page is about -- { project, clip, post, take } // GET ?job=[&since=N] { job }: the app job a form started (lib/jobs.ts jobView, its log from N) // GET ?qid= { step, log }: a queued form's step and its log's last lines // POST { verb, values, confirm? } -> 202 { job, line, project } | 202 { queued: { qid }, line, project } // (`project`: the resolved id of the project it names, or null -- the page announces a // write to that project when the run ends done) // the row's args validated and built into argv HERE (lib/cli/argv.mjs); // a row with `queue` (it renders, or holds the heavy slot) is added to the // durable queue, any other runs as one job on the app's runner // | 400 not a form verb, a value its schema refuses, a raw argv, a path // outside the project | 409 a row with `confirm` sent without confirm: true // | 403 not this app's own page, or a host that is not this machine (DNS // rebinding: lib/report/sameOrigin.mjs, UMTOOL_ALLOWED_HOSTS) | 409 another job runs // The same queued command asked again within 5 s is the step already there. // // The page never sends argv: a body that carries one is refused, and app/api/queue/route.ts // still refuses to add a step from a page. What runs is a registry row's argv, nothing else. const headers = { "cache-control": "no-store" }; const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"); type Row = { verb: string; summary: string; ui: string; reason?: string; queue?: boolean; timeoutMin?: number; confirm?: { what: string } | null; args: Array<{ name: string; type: string; context?: string; pass?: string }> }; /** A double Enter: the same command queued again this soon is the step already there. */ const DEDUPE_MS = 5000; /** The project, and the selection, a page's address is about. */ async function contextOf(raw: string | null) { const ctx: { project: string | null; clip: string | null; post: string | null; take: string | null } = { project: null, clip: null, post: null, take: null }; if (!raw) return ctx; let url: URL; try { url = new URL(raw, "http://x"); } catch { return ctx; } const q = url.searchParams; ctx.clip = q.get("clip"); ctx.take = q.get("take"); const segments = url.pathname.split("/").filter(Boolean).map((s) => { try { return decodeURIComponent(s); } catch { return s; } }); let rest: string[] = []; if (segments[0] === "projects" && segments[1] === "at") { ctx.project = q.get("path"); } else if (segments[0] === "projects" && segments.length > 1) { const r = await resolveProjectPath(segments.slice(1)).catch(() => null); if (r && "project" in r && r.project) { ctx.project = r.project.id; rest = (r as { rest?: string[] }).rest ?? []; } } const [view, id] = rest; if (id && view === "clip") ctx.clip = id; if (id && view === "post") ctx.post = id; if (id && view === "takes") ctx.take = id; return ctx; } export async function GET(request: Request) { const url = new URL(request.url); const jobId = url.searchParams.get("job"); if (jobId) { const job = getJob(jobId); if (!job) return Response.json({ error: "no such job" }, { status: 404, headers }); return Response.json({ job: jobView(job, Math.max(0, Number(url.searchParams.get("since") ?? 0) || 0)) }, { headers }); } const qid = url.searchParams.get("qid"); if (qid !== null) { if (!isQid(qid)) return Response.json({ error: "?qid=" }, { status: 400, headers }); const step = (await getStep(queueDir(), qid)) as Record | null; if (!step) return Response.json({ error: "no such step" }, { status: 404, headers }); const log = await logTail(logFileOf(queueDir(), qid), 32 * 1024); const pick = ["qid", "label", "state", "exitCode", "error", "blockedBy", "createdAt", "startedAt", "endedAt"] as const; return Response.json({ step: Object.fromEntries(pick.map((k) => [k, step[k] ?? null])), log: log.slice(-200), runner: queueRunnerStatus() }, { headers }); } return Response.json({ verbs: formVerbs(), context: await contextOf(url.searchParams.get("path")), queue: queueRunnerStatus() }, { headers }); } /** Same-origin only: the browser says where a POST comes from, and one that says nothing is not a page of this app. */ function refuseOrigin(request: Request): string | null { const refused = crossSiteRefusal(request.headers); if (refused) return refused; const site = (request.headers.get("sec-fetch-site") ?? "").trim().toLowerCase(); if (site === "same-origin" || request.headers.get("origin")) return null; return "refused: POST /api/cli runs only from this app's own pages -- in a terminal, run the command itself"; } export async function POST(request: Request) { const refused = refuseOrigin(request); if (refused) return Response.json({ error: refused }, { status: 403, headers }); const body = (await request.json().catch(() => null)) as Record | null; if (!body || typeof body !== "object" || Array.isArray(body)) return Response.json({ error: "expected JSON: { verb, values }" }, { status: 400, headers }); if ("argv" in body || "args" in body || "cmd" in body || "command" in body) { return Response.json({ error: "a raw command line is refused: name a verb of the registry and its values ({ verb, values })" }, { status: 400, headers }); } const extra = Object.keys(body).filter((k) => k !== "verb" && k !== "values" && k !== "confirm"); if (extra.length) return Response.json({ error: `unexpected ${extra.join(", ")}: the body is { verb, values, confirm? }` }, { status: 400, headers }); const verb = typeof body.verb === "string" ? body.verb.trim() : ""; const row = verbRow(verb) as Row | null; if (!row) return Response.json({ error: `no verb "${verb}" in the registry (umtool/lib/cli/verbs.mjs)` }, { status: 400, headers }); if (row.ui !== "form") return Response.json({ error: `umtool ${verb} has no form: ${row.reason}` }, { status: 400, headers }); const values = (body.values ?? {}) as Record; const pre = buildArgv(row, values); if (!pre.ok) return Response.json({ error: pre.error, field: pre.field ?? null }, { status: 400, headers }); const confirmWhat = confirmOf(row, values); if (confirmWhat && body.confirm !== true) { return Response.json({ error: `this would ${confirmWhat}, with no undo: send it again with confirm: true`, confirm: confirmWhat }, { status: 409, headers }); } // A project arg is one the CLI will find: said here, not as the job's first line. let project: string | null = null; let projectDir: string | null = null; // The project the run is about, for the page (the positional's, else a flag's: `cast audition --project`). let named: string | null = null; for (const a of row.args) { const v = values[a.name]; if (a.type !== "project" || typeof v !== "string" || !v.trim()) continue; const r = (await resolveProject(v.trim())) as { project?: { id: string; dir: string }; ambiguous?: unknown[] }; if (r.ambiguous) return Response.json({ error: `"${v}" is the name of ${r.ambiguous.length} projects — give its id`, field: a.name }, { status: 400, headers }); if (!r.project) return Response.json({ error: `no project matches "${v}"`, field: a.name }, { status: 400, headers }); if (a.name === "project") { project = r.project.id; projectDir = r.project.dir; } else named ??= r.project.id; } // A file a form names is a file of THE project, by its realpath; it runs as that absolute path // (a row whose CLI joins it to the project itself: as typed). const run: Record = { ...values }; for (const a of pathArgsOf(row, values) as Row["args"]) { if (!projectDir) return Response.json({ error: `${a.name}: a file names a project's file -- name the project`, field: a.name }, { status: 400, headers }); const c = await confineToProject(projectDir, String(values[a.name])); if (!c.ok) return Response.json({ error: `${a.name}: ${c.error}`, field: a.name }, { status: 400, headers }); if (a.pass !== "relative") run[a.name] = c.abs; } const built = buildArgv(row, run); if (!built.ok) return Response.json({ error: built.error, field: built.field ?? null }, { status: 400, headers }); named = project ?? named; const take = row.args.filter((a) => a.context === "take").map((a) => values[a.name]).find((v): v is string => typeof v === "string" && !!v.trim()) ?? null; const line = cliLine(built.argv); const label = `⌘K: umtool ${built.argv.join(" ")}`.slice(0, 160); if (row.queue) { try { const same = JSON.stringify(built.argv); const recent = ((await listSteps(queueDir())) as Array<{ qid: string; argv: string[]; state: string; createdAt: string; by?: string }>).find( (s) => (s.state === "queued" || s.state === "running") && JSON.stringify(s.argv) === same && Date.now() - Date.parse(s.createdAt) < DEDUPE_MS, ); if (recent) return Response.json({ ok: true, queued: { qid: recent.qid }, deduped: true, line, project: named, queue: queueRunnerStatus() }, { status: 200, headers }); const step = (await addStep(queueDir(), { argv: built.argv, label, by: "the umtool app (⌘K)", cwd: UMTOOL_DIR, target: project ? { project, take } : null, ...(row.timeoutMin ? { timeoutMin: row.timeoutMin } : {}), })) as { qid: string }; kickQueue(); return Response.json({ ok: true, queued: { qid: step.qid }, line, project: named, queue: queueRunnerStatus() }, { status: 202, headers }); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers }); } } const running = runningJob(); if (running) return Response.json({ error: `a job is already running (${running.kind}) — run this when it is done`, running: jobView(running, running.log.length) }, { status: 409, headers }); const job = startJob(`umtool ${verb}`, [{ cwd: UMTOOL_DIR, env: {}, label: `umtool ${built.argv.join(" ")}`.slice(0, 200), argv: [process.execPath, umtoolCli(), ...built.argv], timeoutMs: (row.timeoutMin ?? 15) * 60_000 }], { project }); return Response.json({ ok: true, job: jobView(job), line, project: named }, { status: 202, headers }); }