Skip to content

Open source CapCut alternative.

TypeScript

feat(site): shared framework-free router for the Cut APIs

David Lea8bdd8028e5b
diff --git a/site/src/app/api/ai/models/route.ts b/site/src/app/api/ai/models/route.ts
deleted file mode 100644
index 8a585550..00000000
--- a/site/src/app/api/ai/models/route.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { execFile } from "node:child_process";
-import { NextResponse } from "next/server";
-
-export const runtime = "nodejs";
-
-import { AI_MODELS } from "@/cut/server/ai/models";
-import { hostedApiBlock } from "@/cut/server/local-only";
-
-function probe(cmd: string, args: string[]): Promise<{ ok: boolean; note: string }> {
- return new Promise((resolve) => {
- execFile(cmd, args, { timeout: 8000 }, (err, stdout, stderr) => {
- if (err) {
- const note = err.message.includes("ENOENT")
- ? `${cmd} is not installed`
- : (stderr || err.message).trim().split("\n")[0];
- resolve({ ok: false, note });
- } else {
- // Some CLIs (codex) report status on stderr.
- resolve({ ok: true, note: (stdout.trim() || stderr.trim()).split("\n")[0] });
- }
- });
- });
-}
-
-// Providers rarely change mid-session; cache probes for a minute.
-const g = globalThis as unknown as {
- __veditorAiProbe?: { at: number; value: { claude: { ok: boolean; note: string }; codex: { ok: boolean; note: string } } };
-};
-
-export async function GET() {
- const blocked = hostedApiBlock();
- if (blocked) return blocked;
- const cached = g.__veditorAiProbe;
- let value = cached && Date.now() - cached.at < 60_000 ? cached.value : null;
- if (!value) {
- const [claude, codexLogin] = await Promise.all([
- probe("claude", ["--version"]),
- probe("codex", ["login", "status"]),
- ]);
- const codex = codexLogin.ok
- ? /logged in/i.test(codexLogin.note)
- ? { ok: true, note: codexLogin.note }
- : { ok: false, note: "Not signed in — run: codex login" }
- : codexLogin;
- value = { claude, codex };
- g.__veditorAiProbe = { at: Date.now(), value };
- }
- return NextResponse.json({
- models: AI_MODELS,
- providers: {
- claude: { available: value.claude.ok, note: value.claude.note },
- codex: { available: value.codex.ok, note: value.codex.note },
- test: { available: true, note: "hermetic test provider" },
- },
- });
-}
diff --git a/site/src/app/api/ai/proxy/route.ts b/site/src/app/api/ai/proxy/route.ts
deleted file mode 100644
index 6b65df51..00000000
--- a/site/src/app/api/ai/proxy/route.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { NextResponse } from "next/server";
-
-export const runtime = "nodejs";
-
-import { callBrowserTool } from "@/cut/server/ai/bridge";
-import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS } from "@/cut/server/ai/catalog";
-import { hostedApiBlock } from "@/cut/server/local-only";
-
-/** MCP-shaped tool catalog for the stdio proxy. */
-export async function GET(req: Request) {
- const blocked = hostedApiBlock();
- if (blocked) return blocked;
- const type = new URL(req.url).searchParams.get("type");
- if (type !== "catalog") return NextResponse.json({ error: "Bad request." }, { status: 400 });
- return NextResponse.json({
- tools: AI_TOOLS.map((t) => ({
- name: t.name,
- description: t.description,
- inputSchema: t.inputSchema,
- })),
- });
-}
-
-const text = (value: unknown) => ({
- content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }],
-});
-
-/** Execute one tool call: server-side skills directly, editor tools via the browser. */
-export async function POST(req: Request) {
- const blocked = hostedApiBlock();
- if (blocked) return blocked;
- const { sessionKey, name, args } = (await req.json()) as {
- sessionKey?: string;
- name?: string;
- args?: Record<string, unknown>;
- };
- const def = AI_TOOLS.find((t) => t.name === name);
- if (!name || !def) {
- return NextResponse.json({ ...text(`Unknown tool: ${name}`), isError: true });
- }
-
- if (def.server) {
- if (name === "list_skills") return NextResponse.json(text({ skills: AI_SKILL_INDEX }));
- if (name === "read_skill") {
- const doc = AI_SKILLS[String(args?.name ?? "")];
- return doc
- ? NextResponse.json(text(doc))
- : NextResponse.json({ ...text(`No such skill. Available: ${AI_SKILL_INDEX.join(", ")}`), isError: true });
- }
- }
-
- const result = await callBrowserTool(String(sessionKey ?? ""), name, args ?? {});
- if (result.errorText !== undefined) {
- return NextResponse.json({ ...text(result.errorText), isError: true });
- }
- // Screenshots come back as data URLs; hand them to the model as images.
- const out = result.output as { image?: string } | undefined;
- if (name === "capture_frame" && out?.image?.startsWith("data:image/")) {
- const [head, data] = out.image.split(",", 2);
- const mimeType = head.slice(5, head.indexOf(";"));
- return NextResponse.json({ content: [{ type: "image", data, mimeType }] });
- }
- return NextResponse.json(text(result.output ?? { ok: true }));
-}
diff --git a/site/src/app/api/ai/tool-result/route.ts b/site/src/app/api/ai/tool-result/route.ts
deleted file mode 100644
index 522d6404..00000000
--- a/site/src/app/api/ai/tool-result/route.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { NextResponse } from "next/server";
-
-export const runtime = "nodejs";
-
-import { resolveBrowserTool } from "@/cut/server/ai/bridge";
-import { hostedApiBlock } from "@/cut/server/local-only";
-
-/** The browser posts tool outputs here after executing them on the store. */
-export async function POST(req: Request) {
- const blocked = hostedApiBlock();
- if (blocked) return blocked;
- const { sessionKey, toolCallId, output, errorText } = (await req.json()) as {
- sessionKey?: string;
- toolCallId?: string;
- output?: unknown;
- errorText?: string;
- };
- if (!sessionKey || !toolCallId) {
- return NextResponse.json({ error: "sessionKey and toolCallId required." }, { status: 400 });
- }
- const ok = resolveBrowserTool(sessionKey, toolCallId, { output, errorText });
- return NextResponse.json({ ok });
-}
diff --git a/site/src/app/api/cut/[[...slug]]/route.ts b/site/src/app/api/cut/[[...slug]]/route.ts
new file mode 100644
index 00000000..7c768f59
--- /dev/null
+++ b/site/src/app/api/cut/[[...slug]]/route.ts
@@ -0,0 +1,10 @@
+import { cutCatchAll } from "@/cut/server/http/next";
+
+// The whole Cut API lives under /api/cut/* and routes through the shared table
+// (src/cut/server/http/routes.ts) — the same one the packaged engine mounts.
+export const runtime = "nodejs";
+
+export const GET = cutCatchAll;
+export const POST = cutCatchAll;
+export const PUT = cutCatchAll;
+export const DELETE = cutCatchAll;
diff --git a/site/src/app/api/export/[jobId]/file/route.ts b/site/src/app/api/export/[jobId]/file/route.ts
deleted file mode 100644
index aff84e0b..00000000
--- a/site/src/app/api/export/[jobId]/file/route.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { getJob } from "@/cut/server/jobs";
-import { serveFileRange } from "@/cut/server/serveFile";
-
-export const runtime = "nodejs";
-
-export async function GET(
- req: Request,
- { params }: { params: Promise<{ jobId: string }> }
-) {
- const { jobId } = await params;
- const job = getJob(jobId);
- if (!job || job.status !== "done") {
- return new Response("Export not ready.", { status: 404 });
- }
- return serveFileRange(job.outPath, req, {
- contentType: "video/mp4",
- downloadName: job.outName,
- });
-}
diff --git a/site/src/app/api/export/[jobId]/route.ts b/site/src/app/api/export/[jobId]/route.ts
deleted file mode 100644
index b303234d..00000000
--- a/site/src/app/api/export/[jobId]/route.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { NextResponse } from "next/server";
-import { cancelJob, getJob } from "@/cut/server/jobs";
-
-export const runtime = "nodejs";
-
-export async function GET(
- _req: Request,
- { params }: { params: Promise<{ jobId: string }> }
-) {
- const { jobId } = await params;
- const job = getJob(jobId);
- if (!job) return NextResponse.json({ error: "Unknown export." }, { status: 404 });
- return NextResponse.json({
- status: job.status,
- progress: job.progress,
- error: job.error,
- outName: job.outName,
- });
-}
-
-export async function DELETE(
- _req: Request,
- { params }: { params: Promise<{ jobId: string }> }
-) {
- const { jobId } = await params;
- cancelJob(jobId);
- return NextResponse.json({ ok: true });
-}
diff --git a/site/src/app/api/export/route.ts b/site/src/app/api/export/route.ts
deleted file mode 100644
index a479e02b..00000000
--- a/site/src/app/api/export/route.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { NextResponse } from "next/server";
-import { createJob } from "@/cut/server/jobs";
-
-export const runtime = "nodejs";
-export const maxDuration = 600;
-
-export async function POST(req: Request) {
- try {
- const form = await req.formData();
- const job = await createJob(form);
- if (job.status === "error") {
- return NextResponse.json({ error: job.error }, { status: 400 });
- }
- return NextResponse.json({ id: job.id });
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Export failed to start." },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/app/api/library/[id]/route.ts b/site/src/app/api/library/[id]/route.ts
deleted file mode 100644
index ac344138..00000000
--- a/site/src/app/api/library/[id]/route.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { NextResponse } from "next/server";
-import { removeAsset } from "@/cut/server/library";
-
-export const runtime = "nodejs";
-
-export async function DELETE(
- _req: Request,
- { params }: { params: Promise<{ id: string }> }
-) {
- const { id } = await params;
- try {
- await removeAsset(id);
- return NextResponse.json({ ok: true });
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Could not delete." },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/app/api/library/media/[file]/route.ts b/site/src/app/api/library/media/[file]/route.ts
deleted file mode 100644
index 9f14237d..00000000
--- a/site/src/app/api/library/media/[file]/route.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { libMediaPath } from "@/cut/server/library";
-import { serveFileRange } from "@/cut/server/serveFile";
-
-export const runtime = "nodejs";
-
-/** Serve a raw library media file with Range support. */
-export async function GET(
- req: Request,
- { params }: { params: Promise<{ file: string }> }
-) {
- const { file } = await params;
- let p: string;
- try {
- p = libMediaPath(decodeURIComponent(file));
- } catch {
- return new Response("Bad request.", { status: 400 });
- }
- return serveFileRange(p, req);
-}
diff --git a/site/src/app/api/library/route.ts b/site/src/app/api/library/route.ts
deleted file mode 100644
index d0d4851f..00000000
--- a/site/src/app/api/library/route.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { NextResponse } from "next/server";
-import { addUpload, listLibrary } from "@/cut/server/library";
-
-export const runtime = "nodejs";
-export const maxDuration = 300;
-
-export async function GET() {
- return NextResponse.json(await listLibrary());
-}
-
-export async function POST(req: Request) {
- try {
- const form = await req.formData();
- const file = form.get("file");
- if (!(file instanceof File)) {
- return NextResponse.json({ error: "No file in upload." }, { status: 400 });
- }
- return NextResponse.json(await addUpload(file));
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Upload failed." },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/app/api/library/save/route.ts b/site/src/app/api/library/save/route.ts
deleted file mode 100644
index ccbe9672..00000000
--- a/site/src/app/api/library/save/route.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { NextResponse } from "next/server";
-import { addFromProject } from "@/cut/server/library";
-
-export const runtime = "nodejs";
-
-/** Copy a project media file into the shared library. */
-export async function POST(req: Request) {
- try {
- const { projectId, fileName, name } = (await req.json()) as {
- projectId: string;
- fileName: string;
- name?: string;
- };
- return NextResponse.json(await addFromProject(projectId, fileName, name ?? fileName));
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Could not save to library." },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/app/api/library/use/route.ts b/site/src/app/api/library/use/route.ts
deleted file mode 100644
index f64bac62..00000000
--- a/site/src/app/api/library/use/route.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { NextResponse } from "next/server";
-import { useInProject } from "@/cut/server/library";
-
-export const runtime = "nodejs";
-
-/** Copy a library asset into a project's media folder. */
-export async function POST(req: Request) {
- try {
- const { assetId, projectId } = (await req.json()) as {
- assetId: string;
- projectId: string;
- };
- const fileName = await useInProject(assetId, projectId);
- return NextResponse.json({ fileName });
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Could not add from library." },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/app/api/projects/[id]/exports/[file]/route.ts b/site/src/app/api/projects/[id]/exports/[file]/route.ts
deleted file mode 100644
index 45eb4962..00000000
--- a/site/src/app/api/projects/[id]/exports/[file]/route.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { exportPath } from "@/cut/server/projects";
-import { serveFileRange } from "@/cut/server/serveFile";
-
-export const runtime = "nodejs";
-
-/** Serve a rendered export from the project folder, with Range support so
- * the platform-preview player can seek. */
-export async function GET(
- req: Request,
- { params }: { params: Promise<{ id: string; file: string }> }
-) {
- const { id, file } = await params;
- let p: string;
- try {
- p = exportPath(id, decodeURIComponent(file));
- } catch {
- return new Response("Bad request.", { status: 400 });
- }
- return serveFileRange(p, req, { contentType: "video/mp4" });
-}
diff --git a/site/src/app/api/projects/[id]/exports/route.ts b/site/src/app/api/projects/[id]/exports/route.ts
deleted file mode 100644
index a99d1982..00000000
--- a/site/src/app/api/projects/[id]/exports/route.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { NextResponse } from "next/server";
-import { listExports } from "@/cut/server/projects";
-
-export const runtime = "nodejs";
-
-/** Rendered exports for a project, newest first. */
-export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
- const { id } = await params;
- try {
- return NextResponse.json(await listExports(id));
- } catch {
- return NextResponse.json({ error: "Invalid project." }, { status: 400 });
- }
-}
diff --git a/site/src/app/api/projects/[id]/freeze/route.ts b/site/src/app/api/projects/[id]/freeze/route.ts
deleted file mode 100644
index 89a7ebb2..00000000
--- a/site/src/app/api/projects/[id]/freeze/route.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { NextResponse } from "next/server";
-
-export const runtime = "nodejs";
-
-import { makeFreezeFrame } from "@/cut/server/frames";
-import { readProject } from "@/cut/server/projects";
-
-/** Render a freeze-frame still clip from a media file's frame. */
-export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
- const { id } = await params;
- try {
- if (!(await readProject(id))) {
- return NextResponse.json({ error: "Project not found." }, { status: 404 });
- }
- const body = (await req.json()) as {
- file?: string;
- srcTime?: number;
- duration?: number;
- frame?: { w?: number; h?: number };
- framing?: { fit?: "fit" | "fill"; panX?: number; panY?: number };
- };
- if (!body.file || typeof body.srcTime !== "number") {
- return NextResponse.json({ error: "file and srcTime are required." }, { status: 400 });
- }
- const frame =
- typeof body.frame?.w === "number" && typeof body.frame?.h === "number"
- ? { w: Math.round(body.frame.w), h: Math.round(body.frame.h) }
- : undefined;
- const framing = frame
- ? {
- fit: body.framing?.fit === "fill" ? ("fill" as const) : ("fit" as const),
- panX: typeof body.framing?.panX === "number" ? body.framing.panX : 0,
- panY: typeof body.framing?.panY === "number" ? body.framing.panY : 0,
- }
- : undefined;
- const made = await makeFreezeFrame(id, body.file, body.srcTime, body.duration ?? 1, frame, framing);
- return NextResponse.json({
- id: crypto.randomUUID().slice(0, 8),
- fileName: made.fileName,
- name: made.fileName,
- type: "video",
- duration: made.duration,
- width: made.width,
- height: made.height,
- });
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : String(err) },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/app/api/projects/[id]/media/[file]/route.ts b/site/src/app/api/projects/[id]/media/[file]/route.ts
deleted file mode 100644
index 093ee6f6..00000000
--- a/site/src/app/api/projects/[id]/media/[file]/route.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { mediaPath } from "@/cut/server/projects";
-import { serveFileRange } from "@/cut/server/serveFile";
-
-export const runtime = "nodejs";
-
-/** Serve a raw media file from the project folder, with Range support so
- * <video>/<audio> elements can seek efficiently. */
-export async function GET(
- req: Request,
- { params }: { params: Promise<{ id: string; file: string }> }
-) {
- const { id, file } = await params;
- let p: string;
- try {
- p = mediaPath(id, decodeURIComponent(file));
- } catch {
- return new Response("Bad request.", { status: 400 });
- }
- return serveFileRange(p, req);
-}
diff --git a/site/src/app/api/projects/[id]/media/route.ts b/site/src/app/api/projects/[id]/media/route.ts
deleted file mode 100644
index 624d0fad..00000000
--- a/site/src/app/api/projects/[id]/media/route.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { NextResponse } from "next/server";
-import { readProject, saveMedia } from "@/cut/server/projects";
-
-export const runtime = "nodejs";
-export const maxDuration = 300;
-
-export async function POST(
- req: Request,
- { params }: { params: Promise<{ id: string }> }
-) {
- const { id } = await params;
- try {
- if (!(await readProject(id))) {
- return NextResponse.json({ error: "Project not found." }, { status: 404 });
- }
- const form = await req.formData();
- const file = form.get("file");
- if (!(file instanceof File)) {
- return NextResponse.json({ error: "No file in upload." }, { status: 400 });
- }
- const fileName = await saveMedia(id, file);
- return NextResponse.json({ fileName });
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Upload failed." },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/app/api/projects/[id]/route.ts b/site/src/app/api/projects/[id]/route.ts
deleted file mode 100644
index 847899ee..00000000
--- a/site/src/app/api/projects/[id]/route.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { NextResponse } from "next/server";
-import type { ProjectDoc } from "@/cut/lib/types";
-import { deleteProject, readProject, writeProject } from "@/cut/server/projects";
-
-export const runtime = "nodejs";
-
-type Ctx = { params: Promise<{ id: string }> };
-
-export async function GET(_req: Request, { params }: Ctx) {
- const { id } = await params;
- const doc = await readProject(id).catch(() => null);
- if (!doc) return NextResponse.json({ error: "Project not found." }, { status: 404 });
- return NextResponse.json(doc);
-}
-
-export async function PUT(req: Request, { params }: Ctx) {
- const { id } = await params;
- try {
- const existing = await readProject(id);
- if (!existing) return NextResponse.json({ error: "Project not found." }, { status: 404 });
- const body = (await req.json()) as Partial<ProjectDoc>;
- const doc: ProjectDoc = {
- ...existing,
- name: typeof body.name === "string" && body.name.trim() ? body.name.trim() : existing.name,
- assets: Array.isArray(body.assets) ? body.assets : existing.assets,
- clips: Array.isArray(body.clips) ? body.clips : existing.clips,
- audioClips: Array.isArray(body.audioClips) ? body.audioClips : existing.audioClips,
- overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
- subtitles:
- body.subtitles && typeof body.subtitles === "object"
- ? body.subtitles
- : existing.subtitles,
- // Per-project view metadata (timeline zoom, …) — not part of the cut.
- ui:
- body.ui && typeof body.ui === "object"
- ? { ...existing.ui, ...body.ui }
- : existing.ui,
- publish:
- body.publish && typeof body.publish === "object"
- ? { ...existing.publish, ...body.publish }
- : existing.publish,
- };
- await writeProject(id, doc);
- return NextResponse.json({ ok: true, updatedAt: doc.updatedAt });
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Could not save project." },
- { status: 500 }
- );
- }
-}
-
-export async function DELETE(_req: Request, { params }: Ctx) {
- const { id } = await params;
- try {
- await deleteProject(id);
- return NextResponse.json({ ok: true });
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Could not delete project." },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/app/api/projects/[id]/transcribe/route.ts b/site/src/app/api/projects/[id]/transcribe/route.ts
deleted file mode 100644
index 7042254e..00000000
--- a/site/src/app/api/projects/[id]/transcribe/route.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { NextResponse } from "next/server";
-
-export const runtime = "nodejs";
-
-import {
- createTranscribeJob,
- getTranscribeJob,
- type TranscribeSpec,
-} from "@/cut/server/transcribe";
-
-/** Start a background transcription of the current cut. */
-export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
- const { id } = await params;
- try {
- const body = (await req.json()) as Omit<TranscribeSpec, "projectId">;
- if (!Array.isArray(body.clips) || typeof body.duration !== "number") {
- return NextResponse.json({ error: "Bad transcribe spec." }, { status: 400 });
- }
- const job = await createTranscribeJob({ ...body, projectId: id });
- return NextResponse.json({ id: job.id });
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- return NextResponse.json({ error: message }, { status: 500 });
- }
-}
-
-/** Poll a transcription job: ?job=<id> */
-export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
- const { id } = await params;
- const jobId = new URL(req.url).searchParams.get("job");
- const job = jobId ? getTranscribeJob(jobId) : undefined;
- if (!job || job.projectId !== id) {
- return NextResponse.json({ error: "Unknown transcription job." }, { status: 404 });
- }
- return NextResponse.json({
- status: job.status,
- stage: job.stage,
- error: job.error,
- cues: job.status === "done" ? job.cues : undefined,
- });
-}
diff --git a/site/src/app/api/projects/route.ts b/site/src/app/api/projects/route.ts
deleted file mode 100644
index bd162a88..00000000
--- a/site/src/app/api/projects/route.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { NextResponse } from "next/server";
-import { createProject, listProjects } from "@/cut/server/projects";
-
-export const runtime = "nodejs";
-
-export async function GET() {
- return NextResponse.json(await listProjects());
-}
-
-export async function POST(req: Request) {
- try {
- const { name } = (await req.json()) as { name?: string };
- const project = await createProject(name ?? "Untitled");
- return NextResponse.json(project);
- } catch (err) {
- return NextResponse.json(
- { error: err instanceof Error ? err.message : "Could not create project." },
- { status: 500 }
- );
- }
-}
diff --git a/site/src/cut/lib/ports.ts b/site/src/cut/lib/ports.ts
new file mode 100644
index 00000000..213a1c0e
--- /dev/null
+++ b/site/src/cut/lib/ports.ts
@@ -0,0 +1,6 @@
+/**
+ * The engine's default loopback port. Shared by the engine (bind address and
+ * the mcp-proxy base URL) and the client (probe list) so the three of them
+ * cannot drift.
+ */
+export const DEFAULT_ENGINE_PORT = 41417;
diff --git a/site/src/cut/server/ai/bridge.ts b/site/src/cut/server/ai/bridge.ts
index 0631f5a4..1ebd4ca9 100644
--- a/site/src/cut/server/ai/bridge.ts
+++ b/site/src/cut/server/ai/bridge.ts
@@ -78,7 +78,7 @@ export function callBrowserTool(
});
}
-/** Called by /api/ai/tool-result when the browser finishes a tool. */
+/** Called by /api/cut/ai/tool-result when the browser finishes a tool. */
export function resolveBrowserTool(
sessionKey: string,
toolCallId: string,
diff --git a/site/src/cut/server/ai/mcp-proxy-core.mjs b/site/src/cut/server/ai/mcp-proxy-core.mjs
new file mode 100644
index 00000000..0a5991f9
--- /dev/null
+++ b/site/src/cut/server/ai/mcp-proxy-core.mjs
@@ -0,0 +1,76 @@
+/**
+ * Minimal stdio MCP server that proxies Cut's editor tools.
+ *
+ * Spawned by whichever model harness is chatting (Claude Agent SDK or the
+ * Codex CLI). Speaks newline-delimited JSON-RPC on stdio and forwards
+ * tools/list + tools/call to the local Cut server (Next dev server or the
+ * engine binary), which routes execution into the user's open editor tab.
+ *
+ * Two launchers share this core: mcp-proxy.mjs (dev, spawned by file path
+ * with node) and the engine binary's `mcp-proxy` subcommand.
+ */
+export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "") {
+ let buffer = "";
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", (chunk) => {
+ buffer += chunk;
+ let nl;
+ while ((nl = buffer.indexOf("\n")) !== -1) {
+ const line = buffer.slice(0, nl).trim();
+ buffer = buffer.slice(nl + 1);
+ if (line) void handle(line);
+ }
+ });
+ process.stdin.on("end", () => process.exit(0));
+
+ function send(msg) {
+ process.stdout.write(JSON.stringify(msg) + "\n");
+ }
+
+ async function handle(line) {
+ let req;
+ try {
+ req = JSON.parse(line);
+ } catch {
+ return;
+ }
+ const { id, method, params } = req;
+ const reply = (result) => id !== undefined && send({ jsonrpc: "2.0", id, result });
+ const fail = (message) =>
+ id !== undefined && send({ jsonrpc: "2.0", id, error: { code: -32000, message } });
+
+ try {
+ if (method === "initialize") {
+ reply({
+ protocolVersion: params?.protocolVersion ?? "2024-11-05",
+ capabilities: { tools: {} },
+ serverInfo: { name: "cut", version: "1.0.0" },
+ });
+ } else if (method === "notifications/initialized" || method === "notifications/cancelled") {
+ // notifications: no response
+ } else if (method === "ping") {
+ reply({});
+ } else if (method === "tools/list") {
+ const res = await fetch(`${BASE}/api/cut/ai/proxy?type=catalog`);
+ const { tools } = await res.json();
+ reply({ tools });
+ } else if (method === "tools/call") {
+ const res = await fetch(`${BASE}/api/cut/ai/proxy`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ sessionKey: SESSION,
+ name: params?.name,
+ args: params?.arguments ?? {},
+ }),
+ });
+ const body = await res.json();
+ reply(body); // { content: [...], isError? } — already MCP-shaped
+ } else if (id !== undefined) {
+ send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Unknown method ${method}` } });
+ }
+ } catch (err) {
+ fail(err instanceof Error ? err.message : String(err));
+ }
+ }
+}
diff --git a/site/src/cut/server/ai/mcp-proxy.mjs b/site/src/cut/server/ai/mcp-proxy.mjs
index ba0f0bd4..5c489b87 100644
--- a/site/src/cut/server/ai/mcp-proxy.mjs
+++ b/site/src/cut/server/ai/mcp-proxy.mjs
@@ -1,77 +1,12 @@
#!/usr/bin/env node
/**
- * Minimal stdio MCP server that proxies Cut's editor tools.
- *
- * Spawned by whichever model harness is chatting (Claude Agent SDK or the
- * Codex CLI). Speaks newline-delimited JSON-RPC on stdio and forwards
- * tools/list + tools/call to the local Next server, which routes execution
- * into the user's open editor tab.
+ * Dev launcher for the stdio MCP proxy: spawned by file path with node from
+ * the Next dev server. The engine binary launches the same core via its
+ * `mcp-proxy` subcommand instead.
*
* usage: node mcp-proxy.mjs <baseUrl> <sessionKey>
*/
+import { runMcpProxy } from "./mcp-proxy-core.mjs";
-const [, , BASE = "http://localhost:3000", SESSION = ""] = process.argv;
-
-let buffer = "";
-process.stdin.setEncoding("utf8");
-process.stdin.on("data", (chunk) => {
- buffer += chunk;
- let nl;
- while ((nl = buffer.indexOf("\n")) !== -1) {
- const line = buffer.slice(0, nl).trim();
- buffer = buffer.slice(nl + 1);
- if (line) void handle(line);
- }
-});
-process.stdin.on("end", () => process.exit(0));
-
-function send(msg) {
- process.stdout.write(JSON.stringify(msg) + "\n");
-}
-
-async function handle(line) {
- let req;
- try {
- req = JSON.parse(line);
- } catch {
- return;
- }
- const { id, method, params } = req;
- const reply = (result) => id !== undefined && send({ jsonrpc: "2.0", id, result });
- const fail = (message) =>
- id !== undefined && send({ jsonrpc: "2.0", id, error: { code: -32000, message } });
-
- try {
- if (method === "initialize") {
- reply({
- protocolVersion: params?.protocolVersion ?? "2024-11-05",
- capabilities: { tools: {} },
- serverInfo: { name: "cut", version: "1.0.0" },
- });
- } else if (method === "notifications/initialized" || method === "notifications/cancelled") {
- // notifications: no response
- } else if (method === "ping") {
- reply({});
- } else if (method === "tools/list") {
- const res = await fetch(`${BASE}/api/ai/proxy?type=catalog`);
- const { tools } = await res.json();
- reply({ tools });
- } else if (method === "tools/call") {
- const res = await fetch(`${BASE}/api/ai/proxy`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- sessionKey: SESSION,
- name: params?.name,
- args: params?.arguments ?? {},
- }),
- });
- const body = await res.json();
- reply(body); // { content: [...], isError? } — already MCP-shaped
- } else if (id !== undefined) {
- send({ jsonrpc: "2.0", id, error: { code: -32601, message: `Unknown method ${method}` } });
- }
- } catch (err) {
- fail(err instanceof Error ? err.message : String(err));
- }
-}
+const [, , BASE, SESSION] = process.argv;
+runMcpProxy(BASE, SESSION);
diff --git a/site/src/cut/server/cors.ts b/site/src/cut/server/cors.ts
new file mode 100644
index 00000000..946afacc
--- /dev/null
+++ b/site/src/cut/server/cors.ts
@@ -0,0 +1,33 @@
+/**
+ * One CORS policy for Cut's engine, shared by the Next dev server (src/proxy.ts)
+ * and the packaged engine's http server (src/cut/engine/serve.ts). The hosted
+ * Cut page is the only browser origin allowed to reach the engine cross-origin;
+ * every other origin is refused before any handler runs.
+ */
+export const CUT_CLIENT_ORIGINS = new Set(["https://cut.donkeyuse.com"]);
+
+/** The echo-back origin for an allowed caller, else null. */
+export function allowedOrigin(origin: string): string | null {
+ return CUT_CLIENT_ORIGINS.has(origin) ? origin : null;
+}
+
+/** Preflight (OPTIONS) response headers for an allowed origin. */
+export function preflightHeaders(
+ origin: string,
+ requestHeaders: string | null
+): Record<string, string> {
+ return {
+ "Access-Control-Allow-Origin": origin,
+ "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
+ "Access-Control-Allow-Headers": requestHeaders ?? "Content-Type",
+ // Chrome preflights public-site → local-network requests.
+ "Access-Control-Allow-Private-Network": "true",
+ "Access-Control-Max-Age": "86400",
+ Vary: "Origin",
+ };
+}
+
+/** Response headers that expose an allowed origin on a normal response. */
+export function corsHeaders(origin: string): Record<string, string> {
+ return { "Access-Control-Allow-Origin": origin, Vary: "Origin" };
+}
diff --git a/site/src/cut/server/dataDir.ts b/site/src/cut/server/dataDir.ts
new file mode 100644
index 00000000..a8d920aa
--- /dev/null
+++ b/site/src/cut/server/dataDir.ts
@@ -0,0 +1,16 @@
+import os from "node:os";
+import path from "node:path";
+
+/**
+ * Where Cut keeps its projects/ and library/ folders. The dev server keeps
+ * them next to the checkout (cwd, gitignored). The engine binary runs as a
+ * LaunchAgent whose cwd is "/", so it sets DONKEY_CUT_ENGINE and data lives in
+ * the user's Application Support instead. DONKEY_CUT_DATA_DIR overrides both.
+ */
+export function cutDataRoot(): string {
+ if (process.env.DONKEY_CUT_DATA_DIR) return process.env.DONKEY_CUT_DATA_DIR;
+ if (process.env.DONKEY_CUT_ENGINE) {
+ return path.join(os.homedir(), "Library", "Application Support", "DonkeyCut");
+ }
+ return process.cwd();
+}
diff --git a/site/src/app/api/ai/chat/route.ts b/site/src/cut/server/http/ai.ts
similarity index 52%
rename from site/src/app/api/ai/chat/route.ts
rename to site/src/cut/server/http/ai.ts
index 7eb555bd..a5bdc7a5 100644
--- a/site/src/app/api/ai/chat/route.ts
+++ b/site/src/cut/server/http/ai.ts
@@ -1,14 +1,18 @@
-import { spawn } from "node:child_process";
+import { spawn, execFile } from "node:child_process";
import os from "node:os";
import path from "node:path";
import { query } from "@anthropic-ai/claude-agent-sdk";
import { createUIMessageStream, createUIMessageStreamResponse, type UIMessage } from "ai";
-export const runtime = "nodejs";
-
-import { callBrowserTool, registerSession, unregisterSession, type UIChunkWriter } from "@/cut/server/ai/bridge";
-import { systemPrompt } from "@/cut/server/ai/catalog";
-import { hostedApiBlock } from "@/cut/server/local-only";
+import {
+ callBrowserTool,
+ registerSession,
+ resolveBrowserTool,
+ unregisterSession,
+ type UIChunkWriter,
+} from "../ai/bridge";
+import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, systemPrompt } from "../ai/catalog";
+import { AI_MODELS } from "../ai/models";
interface ChatBody {
messages: UIMessage[];
@@ -23,6 +27,14 @@ interface ChatBody {
const proxyPath = () =>
path.join(process.cwd(), "src", "cut", "server", "ai", "mcp-proxy.mjs");
+/** How to spawn the MCP proxy. The engine binary spawns itself with its
+ * mcp-proxy subcommand; the dev server spawns node on the proxy source. */
+function mcpCommand(base: string, sessionKey: string): { command: string; args: string[] } {
+ return process.env.DONKEY_CUT_ENGINE
+ ? { command: process.execPath, args: ["mcp-proxy", base, sessionKey] }
+ : { command: process.execPath, args: [proxyPath(), base, sessionKey] };
+}
+
function lastUserText(messages: UIMessage[]): string {
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
@@ -46,47 +58,6 @@ function lastUserAttachments(messages: UIMessage[]): unknown[] {
return [];
}
-export async function POST(req: Request) {
- const blocked = hostedApiBlock();
- if (blocked) return blocked;
- const body = (await req.json()) as ChatBody;
- const base = new URL(req.url).origin;
- const sessionKey = crypto.randomUUID();
- const userText = lastUserText(body.messages);
- const attachments = lastUserAttachments(body.messages);
- const attachBlock = attachments.length
- ? `\n\n<attached_assets>\nThe user attached these project media assets to this message (ids are usable with the editor tools):\n${JSON.stringify(attachments)}\n</attached_assets>`
- : "";
- const prompt = `${userText}${attachBlock}\n\n<editor_state>\n${JSON.stringify(body.context ?? {})}\n</editor_state>`;
-
- const stream = createUIMessageStream({
- execute: async ({ writer }) => {
- const emit: UIChunkWriter["write"] = (chunk) =>
- writer.write(chunk as Parameters<typeof writer.write>[0]);
- registerSession(sessionKey, { write: emit });
- emit({ type: "start" });
- // The browser posts tool outputs back to /api/ai/tool-result with this key.
- emit({ type: "data-session", data: { sessionKey }, transient: true });
- try {
- if (body.model.startsWith("claude")) {
- await runClaude(emit, prompt, body, base, sessionKey, req.signal);
- } else if (body.model === "cut-test") {
- await runFake(emit, sessionKey, userText);
- } else {
- await runCodex(emit, prompt, body, base, sessionKey, req.signal);
- }
- } catch (err) {
- emit({ type: "error", errorText: err instanceof Error ? err.message : String(err) });
- } finally {
- unregisterSession(sessionKey);
- emit({ type: "finish" });
- }
- },
- });
-
- return createUIMessageStreamResponse({ stream });
-}
-
/** Claude models through the Agent SDK — the user's Claude Code login. */
async function runClaude(
emit: UIChunkWriter["write"],
@@ -101,13 +72,17 @@ async function runClaude(
options: {
model: body.model,
...(body.providerSession ? { resume: body.providerSession } : {}),
+ // Inside the compiled engine the SDK can't resolve its built-in CLI;
+ // the engine resolves the user's own Claude Code install at startup.
+ ...(process.env.DONKEY_CUT_CLAUDE
+ ? { pathToClaudeCodeExecutable: process.env.DONKEY_CUT_CLAUDE }
+ : {}),
systemPrompt: systemPrompt(),
tools: [], // no built-in tools — the editor MCP server is the whole surface
mcpServers: {
cut: {
type: "stdio",
- command: process.execPath,
- args: [proxyPath(), base, sessionKey],
+ ...mcpCommand(base, sessionKey),
alwaysLoad: true,
},
},
@@ -164,6 +139,7 @@ async function runCodex(
sessionKey: string,
signal: AbortSignal
) {
+ const mcp = mcpCommand(base, sessionKey);
const args = ["exec"];
if (body.providerSession) args.push("resume", body.providerSession);
args.push(
@@ -176,9 +152,9 @@ async function runCodex(
"-C",
os.tmpdir(),
"-c",
- `mcp_servers.cut.command=${JSON.stringify(process.execPath)}`,
+ `mcp_servers.cut.command=${JSON.stringify(mcp.command)}`,
"-c",
- `mcp_servers.cut.args=${JSON.stringify([proxyPath(), base, sessionKey])}`,
+ `mcp_servers.cut.args=${JSON.stringify(mcp.args)}`,
body.providerSession ? prompt : `${systemPrompt()}\n\n${prompt}`
);
@@ -278,3 +254,163 @@ async function runFake(emit: UIChunkWriter["write"], sessionKey: string, userTex
say("t2", r.errorText ? `Tool failed: ${r.errorText}` : "Done: TESTMARK title added.");
}
}
+
+function probe(cmd: string, args: string[]): Promise<{ ok: boolean; note: string }> {
+ return new Promise((resolve) => {
+ execFile(cmd, args, { timeout: 8000 }, (err, stdout, stderr) => {
+ if (err) {
+ const note = err.message.includes("ENOENT")
+ ? `${cmd} is not installed`
+ : (stderr || err.message).trim().split("\n")[0];
+ resolve({ ok: false, note });
+ } else {
+ // Some CLIs (codex) report status on stderr.
+ resolve({ ok: true, note: (stdout.trim() || stderr.trim()).split("\n")[0] });
+ }
+ });
+ });
+}
+
+// Providers rarely change mid-session; cache probes for a minute.
+let aiProbe: {
+ at: number;
+ value: { claude: { ok: boolean; note: string }; codex: { ok: boolean; note: string } };
+} | null = null;
+
+const mcpText = (value: unknown) => ({
+ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }],
+});
+
+/** The AI assistant: chat streaming, provider probing, and the MCP bridge. */
+export const aiApi = {
+ async chat(req: Request) {
+ const body = (await req.json()) as ChatBody;
+ const base = new URL(req.url).origin;
+ const sessionKey = crypto.randomUUID();
+ const userText = lastUserText(body.messages);
+ const attachments = lastUserAttachments(body.messages);
+ const attachBlock = attachments.length
+ ? `\n\n<attached_assets>\nThe user attached these project media assets to this message (ids are usable with the editor tools):\n${JSON.stringify(attachments)}\n</attached_assets>`
+ : "";
+ const prompt = `${userText}${attachBlock}\n\n<editor_state>\n${JSON.stringify(body.context ?? {})}\n</editor_state>`;
+
+ const stream = createUIMessageStream({
+ execute: async ({ writer }) => {
+ const emit: UIChunkWriter["write"] = (chunk) =>
+ writer.write(chunk as Parameters<typeof writer.write>[0]);
+ registerSession(sessionKey, { write: emit });
+ emit({ type: "start" });
+ // The browser posts tool outputs back to /api/cut/ai/tool-result with this key.
+ emit({ type: "data-session", data: { sessionKey }, transient: true });
+ try {
+ if (body.model.startsWith("claude")) {
+ await runClaude(emit, prompt, body, base, sessionKey, req.signal);
+ } else if (body.model === "cut-test") {
+ await runFake(emit, sessionKey, userText);
+ } else {
+ await runCodex(emit, prompt, body, base, sessionKey, req.signal);
+ }
+ } catch (err) {
+ emit({ type: "error", errorText: err instanceof Error ? err.message : String(err) });
+ } finally {
+ unregisterSession(sessionKey);
+ emit({ type: "finish" });
+ }
+ },
+ });
+
+ return createUIMessageStreamResponse({ stream });
+ },
+
+ async models() {
+ let value = aiProbe && Date.now() - aiProbe.at < 60_000 ? aiProbe.value : null;
+ if (!value) {
+ const [claude, codexLogin] = await Promise.all([
+ probe("claude", ["--version"]),
+ probe("codex", ["login", "status"]),
+ ]);
+ const codex = codexLogin.ok
+ ? /logged in/i.test(codexLogin.note)
+ ? { ok: true, note: codexLogin.note }
+ : { ok: false, note: "Not signed in — run: codex login" }
+ : codexLogin;
+ value = { claude, codex };
+ aiProbe = { at: Date.now(), value };
+ }
+ return Response.json({
+ models: AI_MODELS,
+ providers: {
+ claude: { available: value.claude.ok, note: value.claude.note },
+ codex: { available: value.codex.ok, note: value.codex.note },
+ test: { available: true, note: "hermetic test provider" },
+ },
+ });
+ },
+
+ /** MCP-shaped tool catalog for the stdio proxy. */
+ async proxyCatalog(req: Request) {
+ const type = new URL(req.url).searchParams.get("type");
+ if (type !== "catalog") return Response.json({ error: "Bad request." }, { status: 400 });
+ return Response.json({
+ tools: AI_TOOLS.map((t) => ({
+ name: t.name,
+ description: t.description,
+ inputSchema: t.inputSchema,
+ })),
+ });
+ },
+
+ /** Execute one tool call: server-side skills directly, editor tools via the browser. */
+ async proxyCall(req: Request) {
+ const { sessionKey, name, args } = (await req.json()) as {
+ sessionKey?: string;
+ name?: string;
+ args?: Record<string, unknown>;
+ };
+ const def = AI_TOOLS.find((t) => t.name === name);
+ if (!name || !def) {
+ return Response.json({ ...mcpText(`Unknown tool: ${name}`), isError: true });
+ }
+
+ if (def.server) {
+ if (name === "list_skills") return Response.json(mcpText({ skills: AI_SKILL_INDEX }));
+ if (name === "read_skill") {
+ const doc = AI_SKILLS[String(args?.name ?? "")];
+ return doc
+ ? Response.json(mcpText(doc))
+ : Response.json({
+ ...mcpText(`No such skill. Available: ${AI_SKILL_INDEX.join(", ")}`),
+ isError: true,
+ });
+ }
+ }
+
+ const result = await callBrowserTool(String(sessionKey ?? ""), name, args ?? {});
+ if (result.errorText !== undefined) {
+ return Response.json({ ...mcpText(result.errorText), isError: true });
+ }
+ // Screenshots come back as data URLs; hand them to the model as images.
+ const out = result.output as { image?: string } | undefined;
+ if (name === "capture_frame" && out?.image?.startsWith("data:image/")) {
+ const [head, data] = out.image.split(",", 2);
+ const mimeType = head.slice(5, head.indexOf(";"));
+ return Response.json({ content: [{ type: "image", data, mimeType }] });
+ }
+ return Response.json(mcpText(result.output ?? { ok: true }));
+ },
+
+ /** The browser posts tool outputs here after executing them on the store. */
+ async toolResult(req: Request) {
+ const { sessionKey, toolCallId, output, errorText } = (await req.json()) as {
+ sessionKey?: string;
+ toolCallId?: string;
+ output?: unknown;
+ errorText?: string;
+ };
+ if (!sessionKey || !toolCallId) {
+ return Response.json({ error: "sessionKey and toolCallId required." }, { status: 400 });
+ }
+ const ok = resolveBrowserTool(sessionKey, toolCallId, { output, errorText });
+ return Response.json({ ok });
+ },
+};
diff --git a/site/src/cut/server/http/engine.ts b/site/src/cut/server/http/engine.ts
new file mode 100644
index 00000000..b6f59a46
--- /dev/null
+++ b/site/src/cut/server/http/engine.ts
@@ -0,0 +1,11 @@
+/** The engine's version: the Donkey app passes its own release version when it
+ * spawns the engine, so engine updates ride app updates. "dev" everywhere
+ * else (Next dev server, a hand-run engine). */
+const engineVersion = () => process.env.DONKEY_CUT_VERSION ?? "dev";
+
+export const engineApi = {
+ /** Probed by the client to find the engine; version feeds the update nudge. */
+ async health() {
+ return Response.json({ ok: true, engine: "donkey-cut", version: engineVersion() });
+ },
+};
diff --git a/site/src/cut/server/http/export.ts b/site/src/cut/server/http/export.ts
new file mode 100644
index 00000000..8e909421
--- /dev/null
+++ b/site/src/cut/server/http/export.ts
@@ -0,0 +1,48 @@
+import { cancelJob, createJob, getJob } from "../jobs";
+import { serveFileRange } from "../serveFile";
+
+/** Export rendering: start a job, poll it, cancel it, download the result. */
+export const exportApi = {
+ async create(req: Request) {
+ try {
+ const form = await req.formData();
+ const job = await createJob(form);
+ if (job.status === "error") {
+ return Response.json({ error: job.error }, { status: 400 });
+ }
+ return Response.json({ id: job.id });
+ } catch (e) {
+ return Response.json(
+ { error: e instanceof Error ? e.message : "Export failed to start." },
+ { status: 500 }
+ );
+ }
+ },
+
+ async status(_req: Request, { jobId }: { jobId: string }) {
+ const job = getJob(jobId);
+ if (!job) return Response.json({ error: "Unknown export." }, { status: 404 });
+ return Response.json({
+ status: job.status,
+ progress: job.progress,
+ error: job.error,
+ outName: job.outName,
+ });
+ },
+
+ async cancel(_req: Request, { jobId }: { jobId: string }) {
+ cancelJob(jobId);
+ return Response.json({ ok: true });
+ },
+
+ async file(req: Request, { jobId }: { jobId: string }) {
+ const job = getJob(jobId);
+ if (!job || job.status !== "done") {
+ return new Response("Export not ready.", { status: 404 });
+ }
+ return serveFileRange(job.outPath, req, {
+ contentType: "video/mp4",
+ downloadName: job.outName,
+ });
+ },
+};
diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.ts
new file mode 100644
index 00000000..ef4c4050
--- /dev/null
+++ b/site/src/cut/server/http/library.ts
@@ -0,0 +1,79 @@
+import {
+ addFromProject,
+ addUpload,
+ libMediaPath,
+ listLibrary,
+ removeAsset,
+ useInProject,
+} from "../library";
+import { serveFileRange } from "../serveFile";
+
+const err = (message: string, status: number) => Response.json({ error: message }, { status });
+const caught = (e: unknown, fallback: string) =>
+ err(e instanceof Error ? e.message : fallback, 500);
+
+/** The shared library: reusable media outside any project. */
+export const libraryApi = {
+ async list() {
+ return Response.json(await listLibrary());
+ },
+
+ async upload(req: Request) {
+ try {
+ const form = await req.formData();
+ const file = form.get("file");
+ if (!(file instanceof File)) return err("No file in upload.", 400);
+ return Response.json(await addUpload(file));
+ } catch (e) {
+ return caught(e, "Upload failed.");
+ }
+ },
+
+ async remove(_req: Request, { id }: { id: string }) {
+ try {
+ await removeAsset(id);
+ return Response.json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not delete.");
+ }
+ },
+
+ /** Copy a library asset into a project's media folder. */
+ async use(req: Request) {
+ try {
+ const { assetId, projectId } = (await req.json()) as {
+ assetId: string;
+ projectId: string;
+ };
+ const fileName = await useInProject(assetId, projectId);
+ return Response.json({ fileName });
+ } catch (e) {
+ return caught(e, "Could not add from library.");
+ }
+ },
+
+ /** Copy a project media file into the shared library. */
+ async save(req: Request) {
+ try {
+ const { projectId, fileName, name } = (await req.json()) as {
+ projectId: string;
+ fileName: string;
+ name?: string;
+ };
+ return Response.json(await addFromProject(projectId, fileName, name ?? fileName));
+ } catch (e) {
+ return caught(e, "Could not save to library.");
+ }
+ },
+
+ /** Raw library media file with Range support. */
+ async serveMedia(req: Request, { file }: { file: string }) {
+ let p: string;
+ try {
+ p = libMediaPath(decodeURIComponent(file));
+ } catch {
+ return new Response("Bad request.", { status: 400 });
+ }
+ return serveFileRange(p, req);
+ },
+};
diff --git a/site/src/cut/server/http/next.ts b/site/src/cut/server/http/next.ts
new file mode 100644
index 00000000..9b863f6b
--- /dev/null
+++ b/site/src/cut/server/http/next.ts
@@ -0,0 +1,32 @@
+import { hostedApiBlock } from "../local-only";
+import { matchCutRoute } from "./routes";
+
+/**
+ * The Cut API surface as a Next route handler. A single optional-catch-all route
+ * (src/app/api/cut/[[...slug]]/route.ts) delegates here, so the Next dev server
+ * dispatches through the exact same table (matchCutRoute) the packaged engine
+ * mounts — the two surfaces are one router and cannot drift. The hosted shut-off
+ * is applied once, here.
+ */
+export async function cutCatchAll(req: Request): Promise<Response> {
+ const blocked = hostedApiBlock();
+ if (blocked) return blocked;
+
+ const { pathname } = new URL(req.url);
+ const match = matchCutRoute(req.method, pathname);
+ if (!match) return new Response("Not found.", { status: 404 });
+ if ("methodNotAllowed" in match) {
+ return new Response("Method not allowed.", {
+ status: 405,
+ headers: { Allow: match.methodNotAllowed.join(", ") },
+ });
+ }
+
+ const res = await match.handler(req, match.params);
+ // A HEAD reply carries the GET headers but no body.
+ if (match.head && res.body) {
+ void res.body.cancel();
+ return new Response(null, { status: res.status, headers: res.headers });
+ }
+ return res;
+}
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
new file mode 100644
index 00000000..891c257c
--- /dev/null
+++ b/site/src/cut/server/http/projects.ts
@@ -0,0 +1,192 @@
+import type { ProjectDoc } from "@/cut/lib/types";
+import { makeFreezeFrame } from "../frames";
+import {
+ createProject,
+ deleteProject,
+ exportPath,
+ listExports,
+ listProjects,
+ mediaPath,
+ readProject,
+ saveMedia,
+ writeProject,
+} from "../projects";
+import { serveFileRange } from "../serveFile";
+import { createTranscribeJob, getTranscribeJob, type TranscribeSpec } from "../transcribe";
+
+const err = (message: string, status: number) => Response.json({ error: message }, { status });
+const caught = (e: unknown, fallback: string, status = 500) =>
+ err(e instanceof Error ? e.message : fallback, status);
+
+/** Project CRUD, media, exports, transcription, freeze-frames. */
+export const projectsApi = {
+ async list() {
+ return Response.json(await listProjects());
+ },
+
+ async create(req: Request) {
+ try {
+ const { name } = (await req.json()) as { name?: string };
+ return Response.json(await createProject(name ?? "Untitled"));
+ } catch (e) {
+ return caught(e, "Could not create project.");
+ }
+ },
+
+ async get(_req: Request, { id }: { id: string }) {
+ const doc = await readProject(id).catch(() => null);
+ if (!doc) return err("Project not found.", 404);
+ return Response.json(doc);
+ },
+
+ async put(req: Request, { id }: { id: string }) {
+ try {
+ const existing = await readProject(id);
+ if (!existing) return err("Project not found.", 404);
+ const body = (await req.json()) as Partial<ProjectDoc>;
+ const doc: ProjectDoc = {
+ ...existing,
+ name: typeof body.name === "string" && body.name.trim() ? body.name.trim() : existing.name,
+ assets: Array.isArray(body.assets) ? body.assets : existing.assets,
+ clips: Array.isArray(body.clips) ? body.clips : existing.clips,
+ audioClips: Array.isArray(body.audioClips) ? body.audioClips : existing.audioClips,
+ overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,
+ subtitles:
+ body.subtitles && typeof body.subtitles === "object"
+ ? body.subtitles
+ : existing.subtitles,
+ // Per-project view metadata (timeline zoom, …) — not part of the cut.
+ ui:
+ body.ui && typeof body.ui === "object" ? { ...existing.ui, ...body.ui } : existing.ui,
+ publish:
+ body.publish && typeof body.publish === "object"
+ ? { ...existing.publish, ...body.publish }
+ : existing.publish,
+ };
+ await writeProject(id, doc);
+ return Response.json({ ok: true, updatedAt: doc.updatedAt });
+ } catch (e) {
+ return caught(e, "Could not save project.");
+ }
+ },
+
+ async remove(_req: Request, { id }: { id: string }) {
+ try {
+ await deleteProject(id);
+ return Response.json({ ok: true });
+ } catch (e) {
+ return caught(e, "Could not delete project.");
+ }
+ },
+
+ async uploadMedia(req: Request, { id }: { id: string }) {
+ try {
+ if (!(await readProject(id))) return err("Project not found.", 404);
+ const form = await req.formData();
+ const file = form.get("file");
+ if (!(file instanceof File)) return err("No file in upload.", 400);
+ const fileName = await saveMedia(id, file);
+ return Response.json({ fileName });
+ } catch (e) {
+ return caught(e, "Upload failed.");
+ }
+ },
+
+ /** Raw media file with Range support so <video>/<audio> can seek. */
+ async serveMedia(req: Request, { id, file }: { id: string; file: string }) {
+ let p: string;
+ try {
+ p = mediaPath(id, decodeURIComponent(file));
+ } catch {
+ return new Response("Bad request.", { status: 400 });
+ }
+ return serveFileRange(p, req);
+ },
+
+ /** Rendered exports for a project, newest first. */
+ async listExports(_req: Request, { id }: { id: string }) {
+ try {
+ return Response.json(await listExports(id));
+ } catch {
+ return err("Invalid project.", 400);
+ }
+ },
+
+ /** A rendered export with Range support so the preview player can seek. */
+ async serveExport(req: Request, { id, file }: { id: string; file: string }) {
+ let p: string;
+ try {
+ p = exportPath(id, decodeURIComponent(file));
+ } catch {
+ return new Response("Bad request.", { status: 400 });
+ }
+ return serveFileRange(p, req, { contentType: "video/mp4" });
+ },
+
+ /** Start a background transcription of the current cut. */
+ async transcribeStart(req: Request, { id }: { id: string }) {
+ try {
+ const body = (await req.json()) as Omit<TranscribeSpec, "projectId">;
+ if (!Array.isArray(body.clips) || typeof body.duration !== "number") {
+ return err("Bad transcribe spec.", 400);
+ }
+ const job = await createTranscribeJob({ ...body, projectId: id });
+ return Response.json({ id: job.id });
+ } catch (e) {
+ return caught(e, String(e));
+ }
+ },
+
+ /** Poll a transcription job: ?job=<id> */
+ async transcribePoll(req: Request, { id }: { id: string }) {
+ const jobId = new URL(req.url).searchParams.get("job");
+ const job = jobId ? getTranscribeJob(jobId) : undefined;
+ if (!job || job.projectId !== id) return err("Unknown transcription job.", 404);
+ return Response.json({
+ status: job.status,
+ stage: job.stage,
+ error: job.error,
+ cues: job.status === "done" ? job.cues : undefined,
+ });
+ },
+
+ /** Render a freeze-frame still clip from a media file's frame. */
+ async freeze(req: Request, { id }: { id: string }) {
+ try {
+ if (!(await readProject(id))) return err("Project not found.", 404);
+ const body = (await req.json()) as {
+ file?: string;
+ srcTime?: number;
+ duration?: number;
+ frame?: { w?: number; h?: number };
+ framing?: { fit?: "fit" | "fill"; panX?: number; panY?: number };
+ };
+ if (!body.file || typeof body.srcTime !== "number") {
+ return err("file and srcTime are required.", 400);
+ }
+ const frame =
+ typeof body.frame?.w === "number" && typeof body.frame?.h === "number"
+ ? { w: Math.round(body.frame.w), h: Math.round(body.frame.h) }
+ : undefined;
+ const framing = frame
+ ? {
+ fit: body.framing?.fit === "fill" ? ("fill" as const) : ("fit" as const),
+ panX: typeof body.framing?.panX === "number" ? body.framing.panX : 0,
+ panY: typeof body.framing?.panY === "number" ? body.framing.panY : 0,
+ }
+ : undefined;
+ const made = await makeFreezeFrame(id, body.file, body.srcTime, body.duration ?? 1, frame, framing);
+ return Response.json({
+ id: crypto.randomUUID().slice(0, 8),
+ fileName: made.fileName,
+ name: made.fileName,
+ type: "video",
+ duration: made.duration,
+ width: made.width,
+ height: made.height,
+ });
+ } catch (e) {
+ return caught(e, String(e));
+ }
+ },
+};
diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.ts
new file mode 100644
index 00000000..4ae878d4
--- /dev/null
+++ b/site/src/cut/server/http/routes.ts
@@ -0,0 +1,108 @@
+import { aiApi } from "./ai";
+import { engineApi } from "./engine";
+import { exportApi } from "./export";
+import { libraryApi } from "./library";
+import { projectsApi } from "./projects";
+
+type TableHandler = (req: Request, params: Record<string, string>) => Response | Promise<Response>;
+
+interface CutRoute {
+ method: "GET" | "POST" | "PUT" | "DELETE";
+ path: string; // ":name" segments bind params
+ handler: TableHandler;
+}
+
+/**
+ * The whole Cut API surface in one table, namespaced under /api/cut/* to keep it
+ * clear of Donkey's own APIs. Both mounts dispatch through it — the Next
+ * catch-all route and the packaged engine — so the two surfaces cannot drift.
+ */
+export const CUT_ROUTES: CutRoute[] = [
+ { method: "GET", path: "/api/cut/engine/health", handler: () => engineApi.health() },
+
+ { method: "GET", path: "/api/cut/projects", handler: () => projectsApi.list() },
+ { method: "POST", path: "/api/cut/projects", handler: (req) => projectsApi.create(req) },
+ { method: "GET", path: "/api/cut/projects/:id", handler: (req, p) => projectsApi.get(req, { id: p.id }) },
+ { method: "PUT", path: "/api/cut/projects/:id", handler: (req, p) => projectsApi.put(req, { id: p.id }) },
+ { method: "DELETE", path: "/api/cut/projects/:id", handler: (req, p) => projectsApi.remove(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/projects/:id/media", handler: (req, p) => projectsApi.uploadMedia(req, { id: p.id }) },
+ { method: "GET", path: "/api/cut/projects/:id/media/:file", handler: (req, p) => projectsApi.serveMedia(req, { id: p.id, file: p.file }) },
+ { method: "GET", path: "/api/cut/projects/:id/exports", handler: (req, p) => projectsApi.listExports(req, { id: p.id }) },
+ { method: "GET", path: "/api/cut/projects/:id/exports/:file", handler: (req, p) => projectsApi.serveExport(req, { id: p.id, file: p.file }) },
+ { method: "POST", path: "/api/cut/projects/:id/transcribe", handler: (req, p) => projectsApi.transcribeStart(req, { id: p.id }) },
+ { method: "GET", path: "/api/cut/projects/:id/transcribe", handler: (req, p) => projectsApi.transcribePoll(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/projects/:id/freeze", handler: (req, p) => projectsApi.freeze(req, { id: p.id }) },
+
+ { method: "GET", path: "/api/cut/library", handler: () => libraryApi.list() },
+ { method: "POST", path: "/api/cut/library", handler: (req) => libraryApi.upload(req) },
+ { method: "DELETE", path: "/api/cut/library/:id", handler: (req, p) => libraryApi.remove(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/library/use", handler: (req) => libraryApi.use(req) },
+ { method: "POST", path: "/api/cut/library/save", handler: (req) => libraryApi.save(req) },
+ { method: "GET", path: "/api/cut/library/media/:file", handler: (req, p) => libraryApi.serveMedia(req, { file: p.file }) },
+
+ { method: "POST", path: "/api/cut/export", handler: (req) => exportApi.create(req) },
+ { method: "GET", path: "/api/cut/export/:jobId", handler: (req, p) => exportApi.status(req, { jobId: p.jobId }) },
+ { method: "DELETE", path: "/api/cut/export/:jobId", handler: (req, p) => exportApi.cancel(req, { jobId: p.jobId }) },
+ { method: "GET", path: "/api/cut/export/:jobId/file", handler: (req, p) => exportApi.file(req, { jobId: p.jobId }) },
+
+ { method: "POST", path: "/api/cut/ai/chat", handler: (req) => aiApi.chat(req) },
+ { method: "GET", path: "/api/cut/ai/models", handler: () => aiApi.models() },
+ { method: "GET", path: "/api/cut/ai/proxy", handler: (req) => aiApi.proxyCatalog(req) },
+ { method: "POST", path: "/api/cut/ai/proxy", handler: (req) => aiApi.proxyCall(req) },
+ { method: "POST", path: "/api/cut/ai/tool-result", handler: (req) => aiApi.toolResult(req) },
+];
+
+export type RouteMatch =
+ | { handler: TableHandler; params: Record<string, string>; head: boolean }
+ | { methodNotAllowed: string[] };
+
+/** Bind a pattern against path segments. Returns the bound params and a
+ * specificity score (count of literal segment matches) so more-literal paths
+ * win, or null when the shape doesn't match. Params bind RAW (percent-encoded),
+ * matching what Next hands its route files — handlers decode themselves. */
+function bindPath(
+ pattern: string,
+ segs: string[]
+): { params: Record<string, string>; score: number } | null {
+ const pat = pattern.split("/").filter(Boolean);
+ if (pat.length !== segs.length) return null;
+ const params: Record<string, string> = {};
+ let score = 0;
+ for (let i = 0; i < pat.length; i++) {
+ const p = pat[i];
+ if (p.startsWith(":")) params[p.slice(1)] = segs[i];
+ else if (p === segs[i]) score++;
+ else return null;
+ }
+ return { params, score };
+}
+
+/**
+ * Match a request against the table, mirroring Next's routing so the engine and
+ * dev server behave identically: static path segments win over dynamic ones,
+ * HEAD is served by the GET handler, and a path that exists for other methods
+ * returns 405 (not a dynamic-route false match).
+ */
+export function matchCutRoute(method: string, pathname: string): RouteMatch | null {
+ const segs = pathname.split("/").filter(Boolean);
+ const wanted = method === "HEAD" ? "GET" : method;
+
+ const matches = CUT_ROUTES.map((route) => {
+ const bound = bindPath(route.path, segs);
+ return bound ? { route, params: bound.params, score: bound.score } : null;
+ }).filter((m) => m !== null);
+ if (matches.length === 0) return null;
+
+ // The most-literal path is the single route Next would pick for this URL.
+ const top = Math.max(...matches.map((m) => m.score));
+ const chosen = matches.filter((m) => m.score === top);
+
+ const hit = chosen.find((m) => m.route.method === wanted);
+ if (hit) return { handler: hit.route.handler, params: hit.params, head: method === "HEAD" };
+
+ // Path matched but this method has no handler → 405, as Next returns.
+ const allow = new Set<string>(chosen.map((m) => m.route.method));
+ if (allow.has("GET")) allow.add("HEAD");
+ allow.add("OPTIONS");
+ return { methodNotAllowed: [...allow] };
+}
diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.ts
index 56569b8b..0fcfe369 100644
--- a/site/src/cut/server/library.ts
+++ b/site/src/cut/server/library.ts
@@ -1,12 +1,13 @@
import { spawn } from "node:child_process";
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
+import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
import { mediaPath as projectMediaPath, readProject } from "./projects";
import { exists, uniqueName } from "./util";
/** The shared library: reusable media that lives outside any project. */
-export const LIBRARY_ROOT = path.join(process.cwd(), "library");
+export const LIBRARY_ROOT = path.join(cutDataRoot(), "library");
const LIB_MEDIA = path.join(LIBRARY_ROOT, "media");
const INDEX = path.join(LIBRARY_ROOT, "library.json");
diff --git a/site/src/cut/server/projects.ts b/site/src/cut/server/projects.ts
index 18c12a6c..d463868c 100644
--- a/site/src/cut/server/projects.ts
+++ b/site/src/cut/server/projects.ts
@@ -1,12 +1,13 @@
import { mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import type { ProjectDoc, ProjectSummary } from "@/cut/lib/types";
+import { cutDataRoot } from "./dataDir";
import { assertLocalRuntime } from "./local-only";
import { exists, uniqueName } from "./util";
/** All projects live here; each project is one folder holding project.json,
* its raw media files, and its exports. */
-export const PROJECTS_ROOT = path.join(process.cwd(), "projects");
+export const PROJECTS_ROOT = path.join(cutDataRoot(), "projects");
const ID_RE = /^[a-z0-9][a-z0-9-]{2,40}$/;
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index 9e76e97a..b3e2881d 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path";
import { assertLocalRuntime } from "./local-only";
import { mediaPath, readProject } from "./projects";
-import { hasStream, num, round } from "./util";
+import { findOnPath, hasStream, num, round } from "./util";
/** The audible slice of the cut, in timeline time (mirrors ExportSpec). */
export interface TranscribeSpec {
@@ -65,14 +65,21 @@ function run(cmd: string, args: string[], notFound?: string): Promise<string> {
/**
* The speech engine: Apple's on-device SpeechAnalyzer (macOS 26+), wrapped by
- * a tiny Swift CLI compiled on first use into ~/.cache/cut. Nothing ever
- * leaves the machine.
+ * a tiny Swift CLI. A prebuilt cut-stt (shipped with the app's bundled tools,
+ * on PATH) wins; the dev fallback compiles the source on first use into
+ * ~/.cache/cut. Nothing ever leaves the machine.
*/
async function ensureStt(): Promise<string> {
+ const prebuilt = await findOnPath("cut-stt");
+ if (prebuilt) return prebuilt;
+
const src = path.join(process.cwd(), "src", "cut", "server", "native", "cut-stt.swift");
const bin = path.join(os.homedir(), ".cache", "cut", "cut-stt");
- const [b, s] = await Promise.all([stat(bin).catch(() => null), stat(src)]);
- if (b?.isFile() && b.mtimeMs >= s.mtimeMs) return bin;
+ const [b, s] = await Promise.all([stat(bin).catch(() => null), stat(src).catch(() => null)]);
+ if (b?.isFile() && (!s || b.mtimeMs >= s.mtimeMs)) return bin;
+ if (!s) {
+ throw new Error("The speech tool is missing. Update Donkey to restore transcription.");
+ }
await mkdir(path.dirname(bin), { recursive: true });
await run(
"swiftc",
diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.ts
index 5aef4894..7e0f6069 100644
--- a/site/src/cut/server/util.ts
+++ b/site/src/cut/server/util.ts
@@ -1,5 +1,5 @@
import { spawn } from "node:child_process";
-import { stat } from "node:fs/promises";
+import { access, constants, stat } from "node:fs/promises";
import path from "node:path";
/** Does a file/dir exist? (stat, coerced to a boolean.) */
@@ -10,6 +10,24 @@ export async function exists(p: string) {
);
}
+/** First executable *file* named `name` on PATH, or null. Directories carry the
+ * execute bit too, so a like-named directory must not shadow the real CLI. */
+export async function findOnPath(name: string): Promise<string | null> {
+ for (const dir of (process.env.PATH ?? "").split(":")) {
+ if (!dir) continue;
+ const candidate = path.join(dir, name);
+ try {
+ const s = await stat(candidate); // follows symlinks
+ if (!s.isFile()) continue;
+ await access(candidate, constants.X_OK);
+ return candidate;
+ } catch {
+ // absent or not executable — keep looking
+ }
+ }
+ return null;
+}
+
/**
* First variant of `base` (stem, stem-1, stem-2, …) whose resolved path does
* not already exist. Used to avoid clobbering when copying/saving media.