The VS Code of video editing, built for agents.
TypeScript
Update dependencies and refactor CLI integration
konstantin-paulus059e1f6e765a
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 20c2302e..d708d36a 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -6,11 +6,8 @@"bin": {"dapi": "./dist/index.js"},- "exports": {- "./protocol": "./src/protocol.ts"- },"scripts": {- "build": "esbuild src/index.ts --bundle --platform=node --format=cjs --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --external:bufferutil --external:utf-8-validate --outfile=dist/index.js && chmod +x dist/index.js",+ "build": "esbuild src/index.ts --bundle --platform=node --format=cjs --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --outfile=dist/index.js && chmod +x dist/index.js","check": "tsc --noEmit","symlink:remove": "rm -f /opt/homebrew/bin/dapi","symlink:create": "npm run build && ln -sf \"$PWD/dist/index.js\" /opt/homebrew/bin/dapi"@@ -18,16 +15,15 @@"dependencies": {"@babel/core": "^7.29.7","@babel/preset-typescript": "^7.27.1",+ "@diffusionstudio/dapi": "*",+ "@modelcontextprotocol/sdk": "^1.30.0","babel-preset-solid": "^1.9.12","commander": "^14.0.3",- "esbuild": "^0.28.1",- "ws": "^8.18.3",- "@diffusionstudio/dapi": "*"+ "esbuild": "^0.28.1"},"devDependencies": {"@types/babel__core": "^7.20.5","@types/node": "^24.10.1",- "@types/ws": "^8.18.1","typescript": "~5.9.3"}}diff --git a/apps/cli/src/cli-client.ts b/apps/cli/src/cli-client.tsindex 0b1a5726..bd3189ff 100644--- a/apps/cli/src/cli-client.ts+++ b/apps/cli/src/cli-client.ts@@ -3,14 +3,12 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { connect } from "node:net";-import { randomBytes } from "node:crypto";-import type { AddressInfo } from "node:net";-import { WebSocketServer } from "ws";-import { SOCKET_PATH } from "@diffusionstudio/dapi/socket";-import { decodeReply } from "./protocol";+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { SOCKET_PATH, SocketTransport } from "@diffusionstudio/dapi/socket";+import { version } from "../../../package.json";-import type { ToolInput, ToolName, ToolResult } from "@diffusionstudio/dapi";-import type { CliHandshake, CliHandshakeReply, CliReply, CliRequest } from "./protocol";+import type { Socket } from "node:net";+import type { ToolInput, ToolName, ToolOutput } from "@diffusionstudio/dapi";const DEFAULT_TIMEOUT_MS = 60000;export const GENERATE_TIMEOUT_MS = 600000;@@ -19,131 +17,73 @@ export const EXPORT_TIMEOUT_MS = 3600000;export type CallOptions = { timeoutMs?: number };/**- * Calls one tool in the running app. Typed by the catalog: the input is what- * the tool's schema accepts, the result what its handler returns (bytes come- * back as bytes; the wire's base64 is decoded here).+ * Calls one tool in the running app over an MCP session on its socket.+ * Typed by the catalog: the input is what the tool's schema accepts, the+ * output its structured content. One session per call; a command makes one+ * or two, and the process exits when it settles.*/export async function call<N extends ToolName>(name: N,input: ToolInput<N>,options: CallOptions = {},-): Promise<ToolResult<N>> {- return (await transport({ path: name, input }, options.timeoutMs ?? DEFAULT_TIMEOUT_MS)) as ToolResult<N>;-}--/** Liveness: answered by the renderer's transport before any handler registers. */-export async function ping(): Promise<void> {- await transport({ path: "ping", input: undefined }, DEFAULT_TIMEOUT_MS);-}--// Asks the app (via the unix socket) to have the renderer dial our WebSocket-// server. Main replies once the connect info has been delivered, so a-// rejection here means the app is down or the renderer never became ready.-function requestConnection(handshake: CliHandshake, timeoutMs: number): Promise<void> {- return new Promise((resolve, reject) => {- const sock = connect(SOCKET_PATH);- let buf = "";- let settled = false;- const settle = (fn: () => void) => {- if (settled) return;- settled = true;- sock.destroy();- fn();- };-- sock.setEncoding("utf8");- sock.setTimeout(timeoutMs, () =>- settle(() => reject(new Error("Timed out waiting for the app to accept the connection"))),+): Promise<ToolOutput<N>> {+ return withClient(async (client) => {+ const result = await client.callTool(+ { name, arguments: input as Record<string, unknown> },+ undefined,+ { timeout: options.timeoutMs ?? DEFAULT_TIMEOUT_MS },);- sock.on("connect", () => sock.end(JSON.stringify(handshake)));- sock.on("data", (chunk) => {- buf += chunk;- });- sock.on("end", () => {- let reply: CliHandshakeReply;- try {- reply = JSON.parse(buf) as CliHandshakeReply;- } catch (e) {- settle(() => reject(e instanceof Error ? e : new Error(String(e))));- return;- }- if (reply.ok) settle(resolve);- else settle(() => reject(new Error(reply.error)));- });- sock.on("error", (err) => settle(() => reject(err)));+ if (result.isError) {+ const text = (result.content as Array<{ type: string; text?: string }>)+ .filter((block) => block.type === "text")+ .map((block) => block.text)+ .join("\n");+ throw new Error(text || `${name} failed`);+ }+ return result.structuredContent as ToolOutput<N>;});}-// Each call runs over its own short-lived WebSocket server that the renderer-// dials in to. No cancellation: the CLI process exits when the command settles.-async function transport(request: CliRequest, timeoutMs: number): Promise<unknown> {- const token = randomBytes(16).toString("hex");- // Frame batches can exceed ws's 100 MiB default, so disable the payload- // cap; the server only lives for one request.- const wss = new WebSocketServer({ host: "127.0.0.1", port: 0, maxPayload: 0 });+/** Liveness: a round-trip through the app's MCP server. */+export function ping(): Promise<void> {+ return withClient(async (client) => {+ await client.ping();+ });+}+async function withClient<T>(fn: (client: Client) => Promise<T>): Promise<T> {+ const socket = await openSocket();+ const client = new Client({ name: "dapi", version });try {- const reply = await new Promise<CliReply>((resolve, reject) => {- let settled = false;- const timer = setTimeout(() => {- settle(() => reject(new Error("Timed out waiting for response")));- }, timeoutMs);- const settle = (fn: () => void) => {- if (settled) return;- settled = true;- clearTimeout(timer);- fn();- };-- wss.on("error", (err) => settle(() => reject(err)));- wss.on("connection", (ws, req) => {- const url = new URL(req.url ?? "/", "ws://127.0.0.1");- if (url.searchParams.get("token") !== token) {- ws.terminate();- return;- }- ws.on("message", (raw) => {- try {- const parsed = decodeReply(raw.toString());- settle(() => resolve(parsed));- } catch (e) {- settle(() => reject(e instanceof Error ? e : new Error(String(e))));- }- });- ws.on("close", () => settle(() => reject(new Error("App disconnected before replying"))));- ws.on("error", (err) => settle(() => reject(err)));- ws.send(JSON.stringify(request));- });-- wss.once("listening", () => {- const { port } = wss.address() as AddressInfo;- requestConnection({ port, token }, timeoutMs).catch((err) =>- settle(() => reject(err instanceof Error ? err : new Error(String(err)))),- );- });- });-- if (reply.ok) return reply.data;- throw new Error(reply.error);+ await client.connect(new SocketTransport(socket));+ return await fn(client);} finally {- // Tear down explicitly so no lingering handles keep the Node event loop- // alive past `console.log(result)` and block the CLI from exiting.- for (const client of wss.clients) client.terminate();- wss.close();+ await client.close().catch(() => {});}}-/** The errno of a transport failure (ENOENT/ECONNREFUSED when the app is down), if any. */+// Connecting is where "the app is not running" shows up, as ENOENT (no+// socket file) or ECONNREFUSED (a stale one); see `errnoCode`.+function openSocket(): Promise<Socket> {+ return new Promise((resolve, reject) => {+ const socket = connect(SOCKET_PATH);+ socket.once("connect", () => {+ socket.off("error", reject);+ resolve(socket);+ });+ socket.once("error", reject);+ });+}++/** The errno of a connection failure (ENOENT/ECONNREFUSED when the app is down), if any. */export function errnoCode(e: unknown): string | undefined {return (e as NodeJS.ErrnoException | undefined)?.code;}-// Bridges the cold-start gap after launching the app. Main only delivers the-// handshake once the renderer has finished loading, and `ping` is answered by-// the renderer's transport, so a single round-trip proves the app is fully-// up. The retry loop only handles the brief window before the handshake-// socket itself binds (ENOENT/ECONNREFUSED).-export async function waitForCliSocket(timeoutMs = 30000): Promise<void> {+// Bridges the cold-start gap after launching the app: the socket appears+// once main is ready, and `ping` proves the server answers. The retry loop+// only handles the brief window before the socket binds.+export async function waitForApp(timeoutMs = 30000): Promise<void> {const start = Date.now();let lastError: unknown = null;while (Date.now() - start < timeoutMs) {@@ -157,7 +97,5 @@ export async function waitForCliSocket(timeoutMs = 30000): Promise<void> {await new Promise((r) => setTimeout(r, 200));}}- throw lastError instanceof Error- ? lastError- : new Error("Timed out waiting for the app to start");+ throw lastError instanceof Error ? lastError : new Error("Timed out waiting for the app to start");}diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.tsindex b5160bb3..4058434e 100644--- a/apps/cli/src/index.ts+++ b/apps/cli/src/index.ts@@ -4,19 +4,14 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { execFile } from "node:child_process";-import { randomUUID } from "node:crypto";-import { existsSync, mkdirSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { dirname, isAbsolute, join, resolve } from "node:path";+import { existsSync } from "node:fs";+import { isAbsolute, resolve } from "node:path";import { Command } from "commander";import { version } from "../../../package.json";import { parseTime, TIME_FPS } from "@diffusionstudio/jsx";-import { call, errnoCode, EXPORT_TIMEOUT_MS, GENERATE_TIMEOUT_MS, ping, waitForCliSocket } from "./cli-client";-import { listLocalFonts } from "./fonts";-import { buildIssueBody, createIssue } from "./report";-import { fetchVideo } from "./ytdlp";+import { call, errnoCode, EXPORT_TIMEOUT_MS, GENERATE_TIMEOUT_MS, ping, waitForApp } from "./cli-client";import { ISSUE_LOG_TAIL, MAX_FRAMES_PER_SHEET } from "@diffusionstudio/dapi";-import type { FrameQuality, LogEntry, LogLevel, TimecodedImage } from "@diffusionstudio/dapi";+import type { FrameQuality, ImageRef, LogEntry, LogLevel } from "@diffusionstudio/dapi";// Long-running commands (renders, AI generation) override the default 60s.const GENERATE = { timeoutMs: GENERATE_TIMEOUT_MS };@@ -104,10 +99,8 @@ async function mediaFrame(ref: string, opts: MediaFrameOptions): Promise<void> {const perSheet = parsePerSheet(opts.perSheet, opts.separate);const target = resolveAssetRef(ref);- const dir = opts.output ?? join(tmpdir(), `dapi-grab-${randomUUID().slice(0, 8)}`);- mkdirSync(dir, { recursive: true });try {- const images = await call("media_grab", {+ const { images } = await call("media_grab", {...target,times,count,@@ -118,8 +111,9 @@ async function mediaFrame(ref: string, opts: MediaFrameOptions): Promise<void> {combine: !opts.separate,perSheet,uncapped: opts.uncapped,+ output: resolveOutput(opts.output),});- writeImages(images, dir);+ printImages(images);} catch (e) {handleSocketError(e);}@@ -205,15 +199,15 @@ function parseTimeArg(value: string, flag: string, allowNegative = false): numbereturn seconds;}-// Frames and contact sheets arrive in the same shape: the app stamps each-// image with its timecode (`08s10f`, or `0f-08s10f` for a sheet), which is the-// filename too.-function writeImages(images: TimecodedImage[], dir: string): void {- for (const { timecode, png } of images) {- const path = join(dir, `${timecode}.png`);- writeFileSync(path, png);- console.log(JSON.stringify({ timecode, path }));- }+// The app wrote the PNGs (one per frame or contact sheet, named by+// timecode); print where each landed, one line per image.+function printImages(images: ImageRef[]): void {+ for (const image of images) console.log(JSON.stringify(image));+}++/** An output path as the app needs it: absolute, or absent for the app's default. */+function resolveOutput(path: string | undefined): string | undefined {+ return path === undefined ? undefined : resolve(process.cwd(), path);}function parsePerSheet(value: string | undefined, separate?: boolean): number | undefined {@@ -254,14 +248,11 @@ function parsePreviewWindow(opts: MediaPreviewOptions): { start?: number; end?:async function mediaFilmstrip(ref: string, opts: MediaPreviewOptions): Promise<void> {const { start, end, scale } = parsePreviewWindow(opts);const target = resolveAssetRef(ref);- const path = opts.output ?? join(tmpdir(), `${randomUUID()}.png`);- mkdirSync(dirname(resolve(path)), { recursive: true });const stop = startSpinner("Rendering filmstrip");try {- const { png, ...rest } = await call("media_filmstrip", { ...target, start, end, scale });+ const result = await call("media_filmstrip", { ...target, start, end, scale, output: resolveOutput(opts.output) });stop();- writeFileSync(path, png);- console.log(JSON.stringify({ path, ...rest }));+ console.log(JSON.stringify(result));} catch (e) {stop();handleSocketError(e);@@ -271,14 +262,11 @@ async function mediaFilmstrip(ref: string, opts: MediaPreviewOptions): Promise<vasync function mediaWaveform(ref: string, opts: MediaPreviewOptions): Promise<void> {const { start, end, scale } = parsePreviewWindow(opts);const target = resolveAssetRef(ref);- const path = opts.output ?? join(tmpdir(), `${randomUUID()}.png`);- mkdirSync(dirname(resolve(path)), { recursive: true });const stop = startSpinner("Rendering waveform");try {- const { png, ...rest } = await call("media_waveform", { ...target, start, end, scale });+ const result = await call("media_waveform", { ...target, start, end, scale, output: resolveOutput(opts.output) });stop();- writeFileSync(path, png);- console.log(JSON.stringify({ path, ...rest }));+ console.log(JSON.stringify(result));} catch (e) {stop();handleSocketError(e);@@ -292,11 +280,13 @@ async function captureNode(id: string, opts: CaptureOptions): Promise<void> {const frames = times.map((t) => Math.round(t * TIME_FPS));const perSheet = parsePerSheet(opts.perSheet, opts.separate);- const dir = opts.output ?? join(tmpdir(), `dapi-capture-${randomUUID().slice(0, 8)}`);- mkdirSync(dir, { recursive: true });try {- const images = await call("capture", { id, frames, combine: !opts.separate, perSheet }, GENERATE);- writeImages(images, dir);+ const { images } = await call(+ "capture",+ { id, frames, combine: !opts.separate, perSheet, output: resolveOutput(opts.output) },+ GENERATE,+ );+ printImages(images);} catch (e) {handleSocketError(e);}@@ -346,7 +336,7 @@ async function openProject(path: string | undefined, opts: OpenOptions): Promisetry {// A cold launch needs the renderer up before the app can answer; when// nothing was launched there is nothing to wait for, so fail fast.- if (launched) await waitForCliSocket();+ if (launched) await waitForApp();else await ping();if (path !== undefined) {@@ -369,8 +359,8 @@ async function context(): Promise<void> {async function whoami(): Promise<void> {try {- const result = await call("whoami", {});- console.log(JSON.stringify(result));+ const { user } = await call("whoami", {});+ console.log(JSON.stringify(user));} catch (e) {handleSocketError(e);}@@ -396,7 +386,7 @@ async function showLogs(opts: LogsOptions): Promise<void> {}try {- const entries = await call("logs", { tail, level: opts.level as LogLevel | undefined });+ const { entries } = await call("logs", { tail, level: opts.level as LogLevel | undefined });for (const entry of entries) console.log(formatLogEntry(entry));} catch (e) {handleSocketError(e);@@ -414,27 +404,10 @@ function formatLogEntry(entry: LogEntry): string {type ScreenshotOptions = { output?: string };// `diffusion-studio_2026-07-31_08-55-12.png`-function screenshotFilename(taken: Date, attempt: number): string {- const pad = (value: number) => String(value).padStart(2, "0");- const date = [taken.getFullYear(), pad(taken.getMonth() + 1), pad(taken.getDate())].join("-");- const time = [pad(taken.getHours()), pad(taken.getMinutes()), pad(taken.getSeconds())].join("-");- const slug = APP_NAME.toLowerCase().replace(/[^a-z0-9]+/g, "-");- return `${slug}_${date}_${time}${attempt > 1 ? `-${attempt}` : ""}.png`;-}-async function appScreenshot(opts: ScreenshotOptions): Promise<void> {- const dir = opts.output ?? tmpdir();- mkdirSync(dir, { recursive: true });try {- const { png, width, height } = await call("screenshot", {});- const taken = new Date();- let attempt = 1;- let path = join(dir, screenshotFilename(taken, attempt));- while (existsSync(path)) {- path = join(dir, screenshotFilename(taken, ++attempt));- }- writeFileSync(path, png);- console.log(JSON.stringify({ path, width, height }));+ const result = await call("screenshot", { output: resolveOutput(opts.output) });+ console.log(JSON.stringify(result));} catch (e) {handleSocketError(e);}@@ -443,56 +416,21 @@ async function appScreenshot(opts: ScreenshotOptions): Promise<void> {type IssueOptions = { body?: string; command?: string[]; logs?: string };async function reportIssue(title: string, opts: IssueOptions): Promise<void> {- const summary = title.trim();- if (!summary) {- console.error("A one-line title is required.");- process.exit(1);- }-- let tail = ISSUE_LOG_TAIL;+ let logs: number | undefined;if (opts.logs !== undefined) {const n = Number(opts.logs);if (!Number.isInteger(n) || n < 0) {console.error(`--logs must be a non-negative integer (got "${opts.logs}")`);process.exit(1);}- tail = n;+ logs = n;}-- // The app being broken (or down) is exactly what gets reported, so a failed- // log read is recorded in the report rather than failing the command.- let logs: string[] | undefined;- let appStatus = "not checked";- if (tail > 0) {- try {- logs = (await call("logs", { tail })).map(formatLogEntry);- appStatus = "running";- } catch (e) {- const code = errnoCode(e);- appStatus = code === "ENOENT" || code === "ECONNREFUSED"- ? "not running"- : `unreachable (${(e as Error).message})`;- }- }-- const body = buildIssueBody({- title: summary,- body: opts.body,- commands: opts.command,- logs,- appStatus,- version,- });-- let url: string;try {- url = await createIssue(summary, body);+ const result = await call("report", { title, body: opts.body, commands: opts.command, logs });+ console.log(JSON.stringify(result));} catch (e) {- console.error((e as Error).message);- process.exit(1);+ handleSocketError(e);}-- console.log(JSON.stringify({ url }));}function startSpinner(label: string): () => void {@@ -522,7 +460,7 @@ async function listModels(type: string | undefined): Promise<void> {process.exit(1);}try {- const models = await call("models", { type: type as "image" | "video" | "audio" | undefined });+ const { models } = await call("models", { type: type as "image" | "video" | "audio" | undefined });for (const model of models) console.log(JSON.stringify(model));} catch (e) {handleSocketError(e);@@ -531,7 +469,7 @@ async function listModels(type: string | undefined): Promise<void> {async function listVoices(): Promise<void> {try {- const voices = await call("voices", {});+ const { voices } = await call("voices", {});for (const voice of voices) console.log(JSON.stringify(voice));} catch (e) {handleSocketError(e);@@ -546,7 +484,7 @@ type ListFontsOptions = {namesOnly?: boolean;};-function listFonts(opts: ListFontsOptions): void {+async function listFonts(opts: ListFontsOptions): Promise<void> {let style: "normal" | "italic" | undefined;if (opts.style !== undefined) {if (opts.style !== "normal" && opts.style !== "italic") {@@ -567,34 +505,29 @@ function listFonts(opts: ListFontsOptions): void {}try {- const families = listLocalFonts({- familyPattern: opts.family,- weights: opts.weight,- style,- limit,- });+ const { families } = await call("fonts", { family: opts.family, weights: opts.weight, style, limit });if (opts.namesOnly) {for (const family of families) console.log(family.family);} else {for (const family of families) console.log(JSON.stringify(family));}} catch (e) {- console.error((e as Error).message);- process.exit(1);+ handleSocketError(e);}}type FetchCliOptions = { output?: string; format?: string; audio?: boolean };// `raw` is every operand after `url` — the yt-dlp passthrough placed after `--`.-// No spinner here: yt-dlp renders its own progress to the inherited stderr.async function fetch(url: string, opts: FetchCliOptions, raw: string[]): Promise<void> {+ const stop = startSpinner("Downloading");try {- const paths = await fetchVideo(url, { ...opts, raw });+ const { paths } = await call("fetch", { url, ...opts, raw, output: resolveOutput(opts.output) }, GENERATE);+ stop();for (const path of paths) console.log(JSON.stringify({ path }));} catch (e) {- console.error((e as Error).message);- process.exit(1);+ stop();+ handleSocketError(e);}}@@ -788,7 +721,7 @@ programprogram.command("fonts").description(- `List the local fonts available on this machine (macOS only; does not require the app). These family names are valid \`fontFamily\` values on <text>; each family lists its variants.`,+ `List the local fonts available on this machine (macOS only). These family names are valid \`fontFamily\` values on <text>; each family lists its variants.`,).option("-f, --family <pattern>", "filter to families whose name contains <pattern> (case-insensitive)").option("-w, --weight <weights...>", "filter to variants with the given CSS weight(s), e.g. -w 400 700")@@ -800,7 +733,7 @@ programprogram.command("fetch").description(- `Download a video with yt-dlp (installed separately; does not require the app). Writes files to disk only (a single URL can yield several, e.g. a playlist).`,+ `Download a video with yt-dlp (installed separately). Writes files to disk only (a single URL can yield several, e.g. a playlist).`,).argument("<url>", "video or page URL to download").option("-o, --output <path>", "output file path or directory (yt-dlp -o template; default: yt-dlp's default)")diff --git a/apps/cli/src/protocol.ts b/apps/cli/src/protocol.tsdeleted file mode 100644index eda36e18..00000000--- a/apps/cli/src/protocol.ts+++ /dev/null@@ -1,73 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--// The transport between the CLI and the app, and nothing else: the tool-// catalog and every request and result type live in @diffusionstudio/dapi.-// Free of Node built-ins so the renderer can import it; the socket path is-// in @diffusionstudio/dapi/socket.-//-// Each CLI command hosts a short-lived WebSocket server; main's only job is-// to relay the connect info to the renderer, which then dials the CLI-// directly. Main never sees request payloads.-export const CLI_WIRE = {- CONNECT: "cli:connect",-} as const;--// Sent by the CLI to main over the unix socket, relayed verbatim to the-// renderer. The token guards the loopback WebSocket server against other-// local processes racing to connect first.-export type CliHandshake = { port: number; token: string };--export type CliHandshakeReply = { ok: true } | { ok: false; error: string };--// One tRPC request/reply pair per WebSocket connection. `path` is the-// dot-joined procedure path in the renderer's router (e.g. "media.frame");-// procedure inputs and outputs are typed end-to-end via the AppRouter type,-// so the wire envelope stays untyped.-export type CliRequest = {- path: string;- input: unknown;-};--export type CliReply =- | { ok: true; data: unknown }- | { ok: false; error: string };--// Replies carry bytes (PNGs) inside JSON. A Uint8Array is written as-// `{ $bytes: <base64> }` and read back as a Uint8Array, so handlers and the-// CLI both see bytes and only this seam knows about base64. Chunked so a-// 100 MiB frame batch never builds a single giant argument list.-const BYTES_KEY = "$bytes";-const CHUNK = 0x8000;--export function encodeReply(reply: CliReply): string {- return JSON.stringify(reply, (_key, value) =>- value instanceof Uint8Array ? { [BYTES_KEY]: bytesToBase64(value) } : value,- );-}--export function decodeReply(text: string): CliReply {- return JSON.parse(text, (_key, value) =>- isBytesEnvelope(value) ? base64ToBytes(value[BYTES_KEY]) : value,- ) as CliReply;-}--function isBytesEnvelope(value: unknown): value is { [BYTES_KEY]: string } {- return typeof value === "object" && value !== null && typeof (value as Record<string, unknown>)[BYTES_KEY] === "string";-}--function bytesToBase64(bytes: Uint8Array): string {- let binary = "";- for (let i = 0; i < bytes.length; i += CHUNK) {- binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));- }- return btoa(binary);-}--function base64ToBytes(base64: string): Uint8Array {- const binary = atob(base64);- const bytes = new Uint8Array(binary.length);- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);- return bytes;-}diff --git a/apps/cli/src/ytdlp.ts b/apps/cli/src/ytdlp.tsdeleted file mode 100644index c184a2b4..00000000--- a/apps/cli/src/ytdlp.ts+++ /dev/null@@ -1,74 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { spawn, spawnSync } from "node:child_process";--// Resolve the binary once. YT_DLP_PATH mirrors DIFFUSION_APP_PATH: an escape-// hatch for pinned or non-PATH installs.-const BIN = process.env.YT_DLP_PATH ?? "yt-dlp";--// Fails with an actionable message before any download is attempted. ENOENT is-// the "not installed" case; a non-zero status means the binary is present but-// broken.-function assertInstalled(): void {- const probe = spawnSync(BIN, ["--version"], { encoding: "utf8" });- if (probe.error) {- if ((probe.error as NodeJS.ErrnoException).code === "ENOENT") {- throw new Error(- `yt-dlp not found. Install it (brew install yt-dlp, or pipx install yt-dlp) ` +- `or set YT_DLP_PATH to its location.`,- );- }- throw new Error(probe.error.message);- }- if (probe.status !== 0) {- throw new Error(probe.stderr?.trim() || "yt-dlp is present but not runnable.");- }-}--export type FetchOptions = {- output?: string;- format?: string;- audio?: boolean;- raw?: string[];-};--// Downloads the URL and resolves to the final file path(s) on disk. yt-dlp's-// own `after_move:filepath` reports what actually landed (post extraction /-// rename), so we never guess the name. --quiet silences stdout chatter while-// --progress forces the progress bar to stderr, keeping stdout to just the-// paths we capture.-export function fetchVideo(url: string, opts: FetchOptions = {}): Promise<string[]> {- assertInstalled();-- const args = ["--quiet", "--no-warnings", "--progress", "--print", "after_move:filepath"];- if (opts.output) args.push("-o", opts.output);- if (opts.format) {- args.push("-f", opts.format);- } else if (!opts.audio) {- // Default to mp4: prefer mp4/m4a streams, then remux the merged result so- // the landed file is a .mp4 even when only WebM/mkv sources were available.- // An explicit -f or --audio opts out.- args.push("-f", "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/bv*+ba/b", "--merge-output-format", "mp4");- }- if (opts.audio) args.push("-x");- if (opts.raw?.length) args.push(...opts.raw);- args.push(url);-- return new Promise((resolve, reject) => {- // stdout: resolved paths (captured); stderr: live progress (inherited).- const child = spawn(BIN, args, { stdio: ["ignore", "pipe", "inherit"] });- let out = "";- child.stdout.setEncoding("utf8");- child.stdout.on("data", (chunk) => (out += chunk));- child.on("error", reject);- child.on("close", (code) => {- if (code === 0) {- resolve(out.split("\n").map((line) => line.trim()).filter(Boolean));- } else {- reject(new Error(`yt-dlp exited with code ${code}.`));- }- });- });-}diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 56a49222..09d4b1e6 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -22,7 +22,8 @@"package": "npm run build && npm run build:web && npm run stage:cli && npm run stage:docs && npm run stage:skills && electron-forge package","make": "npm run build && npm run build:web && npm run stage:cli && npm run stage:docs && npm run stage:skills && electron-forge make","publish": "npm run build && npm run build:web && npm run stage:cli && npm run stage:docs && npm run stage:skills && electron-forge publish",- "make:icns": "sh scripts/make-icns.sh"+ "make:icns": "sh scripts/make-icns.sh",+ "test": "vitest run"},"devDependencies": {"@electron-forge/cli": "^7.11.1",@@ -32,19 +33,20 @@"@types/babel__core": "^7.20.5","@types/node": "^24.10.1","electron": "^43.1.1",- "typescript": "~5.9.3"+ "typescript": "~5.9.3",+ "vitest": "^4.0.0"},"dependencies": {"@babel/core": "^7.29.7","@babel/preset-typescript": "^7.27.1",- "@diffusionstudio/cli": "*",+ "@diffusionstudio/dapi": "*","@diffusionstudio/jsx": "*",+ "@modelcontextprotocol/sdk": "^1.30.0","babel-preset-solid": "^1.9.12","esbuild": "^0.28.1","nanoid": "^6.0.1","ts-morph": "^28.0.0","update-electron-app": "^3.0.0",- "yaml": "^2.9.0",- "@diffusionstudio/dapi": "*"+ "yaml": "^2.9.0"}}diff --git a/apps/desktop/scripts/stage-cli.mjs b/apps/desktop/scripts/stage-cli.mjsindex 90590cda..2183f24f 100644--- a/apps/desktop/scripts/stage-cli.mjs+++ b/apps/desktop/scripts/stage-cli.mjs@@ -17,10 +17,7 @@ const desktopDir = join(dirname(fileURLToPath(import.meta.url)), "..");const cliDir = join(desktopDir, "..", "cli");const stageDir = join(desktopDir, "cli");-// Must match the --external list in the apps/cli build script, minus ws's-// optional native addons (bufferutil, utf-8-validate): those are external-// only so the bundle doesn't choke on them, and ws falls back to its JS-// implementations when they are absent.+// Must match the --external list in the apps/cli build script.const EXTERNALS = ["esbuild", "@babel/core", "@babel/preset-typescript", "babel-preset-solid"];const cliPkg = JSON.parse(readFileSync(join(cliDir, "package.json"), "utf8"));diff --git a/apps/desktop/src/cli-server.ts b/apps/desktop/src/cli-server.tsdeleted file mode 100644index 457cb750..00000000--- a/apps/desktop/src/cli-server.ts+++ /dev/null@@ -1,161 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { existsSync, unlinkSync } from "node:fs";-import { createServer } from "node:net";-import type { Server, Socket } from "node:net";-import { app, BrowserWindow } from "electron";-import { CLI_WIRE } from "@diffusionstudio/cli/protocol";-import { SOCKET_PATH } from "@diffusionstudio/dapi/socket";-import type { CliHandshake, CliHandshakeReply } from "@diffusionstudio/cli/protocol";-import { mainBridge } from "./main-manager";-import { MAIN_CHANNELS } from "./main-channels";--let cliServer: Server | null = null;-let currentWindow: BrowserWindow | null = null;-let headless = false;-let windowLifecycleBound = false;--export function isHeadless(): boolean {- return headless;-}--function enableHeadless(): void {- if (headless) return;- headless = true;- if (currentWindow && !currentWindow.isDestroyed()) {- mainBridge.emit(currentWindow, MAIN_CHANNELS.HEADLESS_MODE, { active: true });- }-}--// Resolves once the current window has finished loading.-function waitForRendererReady(timeoutMs = 30000): Promise<void> {- if (!currentWindow || currentWindow.isDestroyed()) {- return Promise.reject(new Error("No window"));- }-- if (currentWindow.webContents.isCrashed()) {- return Promise.reject(new Error("Renderer crashed"));- }- if (!currentWindow.webContents.isLoading()) {- return Promise.resolve();- }-- return new Promise((resolve, reject) => {- const timer = setTimeout(() => {- console.warn(`[cli-server] renderer not ready after ${timeoutMs}ms`);- reject(new Error("App did not become ready in time"));- }, timeoutMs);-- const cleanup = () => {- clearTimeout(timer);- currentWindow?.webContents.off("did-finish-load", onLoad);- currentWindow?.webContents.off("did-fail-load", onFail);- };-- const onLoad = () => {- cleanup();- resolve();- };-- const onFail = () => {- cleanup();- reject(new Error(`Renderer failed to load`));- };-- currentWindow?.webContents.on("did-finish-load", onLoad);- currentWindow?.webContents.on("did-fail-load", onFail);- });-}--function bindWindowLifecycle(): void {- if (windowLifecycleBound) return;- windowLifecycleBound = true;- app.on("browser-window-created", (_event, window) => {- currentWindow = window;- window.on("closed", () => {- if (currentWindow === window) currentWindow = null;- });- });- // Catch any window that was created before the server started.- const windows = BrowserWindow.getAllWindows();- if (windows.length > 0) currentWindow = windows[windows.length - 1]!;-}--// Relays the CLI's connect info to the renderer, which dials the CLI's-// WebSocket server directly. The reply confirms delivery only; from there-// the request/response traffic bypasses main entirely.-async function deliverHandshake(handshake: CliHandshake, sock: Socket): Promise<void> {- let reply: CliHandshakeReply;- try {- await waitForRendererReady();- if (!currentWindow || currentWindow.isDestroyed()) {- throw new Error("No window");- }- currentWindow.webContents.send(CLI_WIRE.CONNECT, handshake);- reply = { ok: true };- } catch (err) {- reply = { ok: false, error: (err as Error).message };- }- if (!sock.destroyed) sock.end(JSON.stringify(reply));-}--export function startCliServer() {- cleanupStaleSocket();- bindWindowLifecycle();-- cliServer = createServer({ allowHalfOpen: true }, (sock: Socket) => {- enableHeadless();- let buf = "";- sock.setEncoding("utf8");- sock.setTimeout(60000, () => sock.destroy());- sock.on("data", (chunk) => {- buf += chunk;- });- sock.on("end", async () => {- sock.setTimeout(0);- let handshake: CliHandshake;- try {- handshake = JSON.parse(buf) as CliHandshake;- if (typeof handshake.port !== "number" || typeof handshake.token !== "string") {- throw new Error("Malformed handshake");- }- } catch {- sock.end(JSON.stringify({ ok: false, error: "Invalid handshake" }));- return;- }- await deliverHandshake(handshake, sock);- });- sock.on("error", () => {- // Client hung up; nothing to do.- });- });-- cliServer.on("error", (err) => {- console.error("CLI server error:", err);- });-- cliServer.listen(SOCKET_PATH);-}--export function stopCliServer() {- if (!cliServer) return;- cliServer.close();- cliServer = null;- cleanupStaleSocket();-}--/**- * Clean up a stale socket file (Unix). Safe because the single-instance lock- * guarantees no other instance of ours is running.- */-function cleanupStaleSocket() {- try {- if (process.platform !== "win32" && existsSync(SOCKET_PATH)) {- unlinkSync(SOCKET_PATH);- }- } catch {- // Best-effort.- }-}diff --git a/apps/desktop/src/dapi/handler.ts b/apps/desktop/src/dapi/handler.tsnew file mode 100644index 00000000..f94d9c72--- /dev/null+++ b/apps/desktop/src/dapi/handler.ts@@ -0,0 +1,22 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import type { LogEntry, ToolArgs, ToolResult } from "@diffusionstudio/dapi";++/** What a main-process handler gets besides its arguments. */+export type MainContext = {+ /** Fires when the caller cancels or goes away. */+ signal: AbortSignal;+ /** The app's console buffer, oldest first. */+ logs(): LogEntry[];+ /** The app's version. */+ version: string;+};++/** The tools that need the file system or a child process, not a window. */+export type MainToolName = "logs" | "fonts" | "fetch" | "report";++export type MainHandler<N extends MainToolName> = (args: ToolArgs<N>, ctx: MainContext) => Promise<ToolResult<N>>;++export type MainHandlers = { readonly [N in MainToolName]: MainHandler<N> };diff --git a/apps/desktop/src/dapi/handlers/fetch.ts b/apps/desktop/src/dapi/handlers/fetch.tsnew file mode 100644index 00000000..a809bf23--- /dev/null+++ b/apps/desktop/src/dapi/handlers/fetch.ts@@ -0,0 +1,81 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { spawn, spawnSync } from "node:child_process";+import { DapiError } from "@diffusionstudio/dapi";++import type { MainHandler } from "../handler";++// Resolve the binary once. YT_DLP_PATH is an escape hatch for pinned or+// non-PATH installs.+const BIN = process.env.YT_DLP_PATH ?? "yt-dlp";++// Fails with an actionable message before any download is attempted. ENOENT is+// the "not installed" case; a non-zero status means the binary is present but+// broken.+function assertInstalled(): void {+ const probe = spawnSync(BIN, ["--version"], { encoding: "utf8" });+ if (probe.error) {+ if ((probe.error as NodeJS.ErrnoException).code === "ENOENT") {+ throw new DapiError(+ "unsupported",+ "yt-dlp not found. Install it (brew install yt-dlp, or pipx install yt-dlp) or set YT_DLP_PATH to its location.",+ );+ }+ throw probe.error;+ }+ if (probe.status !== 0) {+ throw new DapiError("unsupported", probe.stderr?.trim() || "yt-dlp is present but not runnable.");+ }+}++// yt-dlp's own `after_move:filepath` reports what actually landed (post+// extraction / rename), so the name is never guessed. --quiet keeps stdout to+// those paths; stderr is kept only for the error line when it fails.+export const fetchVideo: MainHandler<"fetch"> = ({ url, output, format, audio, raw }, ctx) => {+ assertInstalled();++ const args = ["--quiet", "--no-warnings", "--print", "after_move:filepath"];+ if (output) args.push("-o", output);+ if (format) {+ args.push("-f", format);+ } else if (!audio) {+ // Default to mp4: prefer mp4/m4a streams, then remux the merged result so+ // the landed file is a .mp4 even when only WebM/mkv sources were available.+ // An explicit format or audio opts out.+ args.push("-f", "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/bv*+ba/b", "--merge-output-format", "mp4");+ }+ if (audio) args.push("-x");+ if (raw?.length) args.push(...raw);+ args.push(url);++ return new Promise((resolve, reject) => {+ const child = spawn(BIN, args, { stdio: ["ignore", "pipe", "pipe"] });+ let out = "";+ child.stdout.setEncoding("utf8");+ child.stdout.on("data", (chunk) => (out += chunk));++ let stderr = "";+ child.stderr.setEncoding("utf8");+ child.stderr.on("data", (chunk: string) => {+ stderr = (stderr + chunk).slice(-4096);+ });++ const onAbort = () => child.kill();+ ctx.signal.addEventListener("abort", onAbort, { once: true });++ child.on("error", reject);+ child.on("close", (code) => {+ ctx.signal.removeEventListener("abort", onAbort);+ if (ctx.signal.aborted) {+ reject(new DapiError("canceled", "Download canceled."));+ } else if (code === 0) {+ resolve({ paths: out.split("\n").map((line) => line.trim()).filter(Boolean) });+ } else {+ const detail = stderr.trim().split("\n").filter((l) => l.startsWith("ERROR")).pop();+ reject(new Error(detail ?? `yt-dlp exited with code ${code}.`));+ }+ });+ });+};diff --git a/apps/cli/src/fonts.ts b/apps/desktop/src/dapi/handlers/fonts.tssimilarity index 66%rename from apps/cli/src/fonts.tsrename to apps/desktop/src/dapi/handlers/fonts.tsindex d2de7964..56f54b5f 100644--- a/apps/cli/src/fonts.ts+++ b/apps/desktop/src/dapi/handlers/fonts.ts@@ -4,21 +4,14 @@import { spawnSync } from "node:child_process";import { platform } from "node:os";+import { DapiError } from "@diffusionstudio/dapi";-export type FontVariant = {- weight: string;- style: "normal" | "italic";- source: string;-};--export type FontFamily = {- family: string;- variants: FontVariant[];-};+import type { FontFamily } from "@diffusionstudio/dapi";+import type { MainHandler } from "../handler";// JXA script that walks every registered font family via NSFontManager and// emits each variant's CSS-style weight, italic flag, and CSS `local()` source.-// Embedded inline so the CLI binary is self-contained — runs via `osascript`.+// Runs via `osascript`.const LIST_FONTS_JXA = `ObjC.import("AppKit");@@ -63,16 +56,9 @@ function run() {}`;-export type ListLocalFontsOptions = {- familyPattern?: string;- weights?: string[];- style?: "normal" | "italic";- limit?: number;-};--export function listLocalFonts(options: ListLocalFontsOptions = {}): FontFamily[] {+function listLocalFonts(): FontFamily[] {if (platform() !== "darwin") {- throw new Error("fonts is only supported on macOS.");+ throw new DapiError("unsupported", "fonts is only supported on macOS.");}const result = spawnSync("osascript", ["-l", "JavaScript", "-e", LIST_FONTS_JXA], {encoding: "utf8",@@ -81,23 +67,24 @@ export function listLocalFonts(options: ListLocalFontsOptions = {}): FontFamily[if (result.status !== 0) {throw new Error(result.stderr.trim() || "Failed to enumerate fonts.");}+ return JSON.parse(result.stdout.trim()) as FontFamily[];+}- const all = JSON.parse(result.stdout.trim()) as FontFamily[];- const pattern = options.familyPattern?.toLowerCase();- const weights = options.weights && options.weights.length > 0 ? new Set(options.weights) : null;- const { style, limit } = options;+export const fonts: MainHandler<"fonts"> = async ({ family, weights, style, limit }) => {+ const pattern = family?.toLowerCase();+ const wanted = weights && weights.length > 0 ? new Set(weights) : null;- const out: FontFamily[] = [];- for (const family of all) {- if (pattern && !family.family.toLowerCase().includes(pattern)) continue;- const variants = family.variants.filter((v) => {- if (weights && !weights.has(v.weight)) return false;+ const families: FontFamily[] = [];+ for (const entry of listLocalFonts()) {+ if (pattern && !entry.family.toLowerCase().includes(pattern)) continue;+ const variants = entry.variants.filter((v) => {+ if (wanted && !wanted.has(v.weight)) return false;if (style && v.style !== style) return false;return true;});if (variants.length === 0) continue;- out.push({ family: family.family, variants });- if (limit !== undefined && out.length >= limit) break;+ families.push({ family: entry.family, variants });+ if (limit !== undefined && families.length >= limit) break;}- return out;-}+ return { families };+};diff --git a/apps/desktop/src/dapi/handlers/index.ts b/apps/desktop/src/dapi/handlers/index.tsnew file mode 100644index 00000000..0faa91ad--- /dev/null+++ b/apps/desktop/src/dapi/handlers/index.ts@@ -0,0 +1,13 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { logs } from "./logs";+import { fonts } from "./fonts";+import { fetchVideo } from "./fetch";+import { report } from "./report";++import type { MainHandlers } from "../handler";++/** Every tool main answers itself, keyed by its catalog name. */+export const mainHandlers: MainHandlers = { logs, fonts, fetch: fetchVideo, report };diff --git a/apps/desktop/src/dapi/handlers/logs.ts b/apps/desktop/src/dapi/handlers/logs.tsnew file mode 100644index 00000000..7b04e6af--- /dev/null+++ b/apps/desktop/src/dapi/handlers/logs.ts@@ -0,0 +1,27 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import type { LogEntry, LogLevel } from "@diffusionstudio/dapi";+import type { MainHandler } from "../handler";++const LEVEL_RANK: Record<LogLevel, number> = { debug: 0, info: 1, warning: 2, error: 3 };++export const logs: MainHandler<"logs"> = async ({ tail, level }, ctx) => {+ let entries = ctx.logs();+ if (level !== undefined) {+ const min = LEVEL_RANK[level];+ entries = entries.filter((e) => LEVEL_RANK[e.level] >= min);+ }+ if (tail !== undefined) entries = entries.slice(-tail);+ return { entries };+};++/** One log entry as a line: local time, level, message, source. */+export function formatLogEntry(entry: LogEntry): string {+ const pad = (n: number, w = 2) => String(n).padStart(w, "0");+ const d = new Date(entry.ts);+ const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`;+ const source = entry.source ? ` (${entry.source})` : "";+ return `${time} [${entry.level}] ${entry.message}${source}`;+}diff --git a/apps/cli/src/report.ts b/apps/desktop/src/dapi/handlers/report.tssimilarity index 58%rename from apps/cli/src/report.tsrename to apps/desktop/src/dapi/handlers/report.tsindex d618dec5..15876e06 100644--- a/apps/cli/src/report.ts+++ b/apps/desktop/src/dapi/handlers/report.ts@@ -4,50 +4,41 @@import { spawn } from "node:child_process";import { arch, platform, release } from "node:os";+import { DapiError, ISSUE_LOG_TAIL } from "@diffusionstudio/dapi";+import { formatLogEntry } from "./logs";++import type { MainHandler } from "../handler";const REPO = "diffusionstudio/editor";-export const GH_MISSING =+const GH_MISSING ="gh (GitHub CLI) is not installed, so the issue cannot be filed. Install it from https://cli.github.com, run `gh auth login`, then retry.";-export type IssueInput = {- title: string;- body?: string;- commands?: string[];- logs?: string[]; // already formatted log lines, oldest first- appStatus: string; // "running", "not running", "not checked", or why it was unreachable- version: string;-};-function fence(language: string, content: string): string {return `\`\`\`${language}\n${content}\n\`\`\``;}-function environmentTable(input: IssueInput): string {+function environmentTable(version: string): string {const rows: Array<[string, string]> = [- ["dapi", input.version],+ ["app", version],["platform", `${platform()} ${release()} (${arch()})`],- ["node", process.version],- ["app", input.appStatus],+ ["electron", process.versions.electron ?? "unknown"],];return ["| | |", "| --- | --- |", ...rows.map(([k, v]) => `| ${k} | ${v} |`)].join("\n");}-export function buildIssueBody(input: IssueInput): string {+function buildIssueBody(input: { body?: string; commands?: string[]; logs: string[]; version: string }): string {const sections: string[] = [];-if (input.body?.trim()) sections.push(input.body.trim());if (input.commands?.length) sections.push(`## Repro\n\n${fence("sh", input.commands.join("\n"))}`);- sections.push(`## Environment\n\n${environmentTable(input)}`);- if (input.logs?.length) sections.push(`## App logs\n\n${fence("", input.logs.join("\n"))}`);-+ sections.push(`## Environment\n\n${environmentTable(input.version)}`);+ if (input.logs.length) sections.push(`## App logs\n\n${fence("", input.logs.join("\n"))}`);return `${sections.join("\n\n")}\n`;}-// --repo is explicit because dapi runs from the user's project, not a checkout-// of the editor; the body goes over stdin so a long log tail can't blow the-// argv size limit.-export function createIssue(title: string, body: string): Promise<string> {+// --repo is explicit because the app is not a checkout of the editor; the body+// goes over stdin so a long log tail can't blow the argv size limit.+function createIssue(title: string, body: string): Promise<string> {return new Promise((resolve, reject) => {const gh = spawn("gh", ["issue", "create", "--repo", REPO, "--title", title, "--body-file", "-"]);@@ -57,7 +48,7 @@ export function createIssue(title: string, body: string): Promise<string> {gh.stderr.on("data", (chunk) => (stderr += chunk));gh.on("error", (e) => {- reject((e as NodeJS.ErrnoException).code === "ENOENT" ? new Error(GH_MISSING) : e);+ reject((e as NodeJS.ErrnoException).code === "ENOENT" ? new DapiError("unsupported", GH_MISSING) : e);});gh.on("close", (code) => {if (code !== 0) {@@ -73,7 +64,16 @@ export function createIssue(title: string, body: string): Promise<string> {resolve(url);});- gh.stdin.on("error", () => { }); // gh exiting early (auth failure) breaks the pipe+ gh.stdin.on("error", () => {}); // gh exiting early (auth failure) breaks the pipegh.stdin.end(body);});}++export const report: MainHandler<"report"> = async ({ title, body, commands, logs }, ctx) => {+ const summary = title.trim();+ if (!summary) throw new DapiError("invalid-input", "A one-line title is required.");+ const tail = logs ?? ISSUE_LOG_TAIL;+ const lines = tail > 0 ? ctx.logs().slice(-tail).map(formatLogEntry) : [];+ const url = await createIssue(summary, buildIssueBody({ body, commands, logs: lines, version: ctx.version }));+ return { url };+};diff --git a/apps/desktop/src/dapi/present.test.ts b/apps/desktop/src/dapi/present.test.tsnew file mode 100644index 00000000..1c75de82--- /dev/null+++ b/apps/desktop/src/dapi/present.test.ts@@ -0,0 +1,68 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import { present, toCallToolResult } from "./present";++const dir = mkdtempSync(join(tmpdir(), "dapi-present-"));+afterAll(() => rmSync(dir, { recursive: true, force: true }));++const png = (byte: number, size = 8) => new Uint8Array(size).fill(byte);++describe("present", () => {+ it("writes capture frames by timecode into the requested directory and returns their paths", async () => {+ const out = join(dir, "frames");+ const presented = await present("capture", { id: "intro", combine: true, output: out }, [+ { timecode: "0f", png: png(1) },+ { timecode: "1s", png: png(2) },+ ]);+ expect(presented.output).toEqual({ images: [{ timecode: "0f", path: join(out, "0f.png") }, { timecode: "1s", path: join(out, "1s.png") }] });+ expect(readFileSync(join(out, "1s.png"))).toEqual(Buffer.from(png(2)));+ });++ it("picks a fresh temp directory when none is given", async () => {+ const presented = await present("media_grab", { path: "/c.mp4", combine: true }, [{ timecode: "0f", png: png(3) }]);+ const { path } = (presented.output as { images: Array<{ path: string }> }).images[0]!;+ expect(path).toMatch(/dapi-grab-.*[\\/]0f\.png$/);+ rmSync(join(path, ".."), { recursive: true, force: true });+ });++ it("keeps a preview's other fields next to the path", async () => {+ const file = join(dir, "wave.png");+ const presented = await present("media_waveform", { path: "/c.mp4", output: file }, { png: png(4), silences: [{ start: 0, end: 1 }] });+ expect(presented.output).toEqual({ path: file, silences: [{ start: 0, end: 1 }] });+ });++ it("names screenshots by time and never overwrites one", async () => {+ const first = await present("screenshot", { output: dir }, { png: png(5), width: 10, height: 10 });+ const second = await present("screenshot", { output: dir }, { png: png(6), width: 10, height: 10 });+ const a = (first.output as { path: string }).path;+ const b = (second.output as { path: string }).path;+ expect(a).toMatch(/diffusion-studio_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.png$/);+ expect(b).not.toBe(a);+ });++ it("passes other results through untouched", async () => {+ expect(await present("check", { id: "x" }, { stats: {}, issues: [] })).toEqual({ output: { stats: {}, issues: [] }, images: [] });+ });+});++describe("toCallToolResult", () => {+ it("inlines a few small images and always carries the output as text and structure", () => {+ const result = toCallToolResult({ output: { images: [] }, images: [{ path: "/a.png", png: png(1) }] });+ expect(result.structuredContent).toEqual({ images: [] });+ expect(result.content[0]).toEqual({ type: "text", text: '{"images":[]}' });+ expect(result.content[1]).toMatchObject({ type: "image", mimeType: "image/png" });+ });++ it("sends paths only when there are many images or a large one", () => {+ const many = Array.from({ length: 5 }, (_, i) => ({ path: `/${i}.png`, png: png(i) }));+ expect(toCallToolResult({ output: {}, images: many }).content).toHaveLength(1);+ const large = [{ path: "/big.png", png: png(0, (1 << 20) + 1) }];+ expect(toCallToolResult({ output: {}, images: large }).content).toHaveLength(1);+ });+});diff --git a/apps/desktop/src/dapi/present.ts b/apps/desktop/src/dapi/present.tsnew file mode 100644index 00000000..67d90d1f--- /dev/null+++ b/apps/desktop/src/dapi/present.ts@@ -0,0 +1,110 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Turns what a handler returned into what a caller receives. Tools that+// render images hand back bytes; here they become files on disk, paths in+// the structured result, and — when the result is small — inline images the+// agent sees without opening anything.++import { existsSync } from "node:fs";+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { randomUUID } from "node:crypto";++import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";+import type { TimecodedImage, ToolArgs, ToolName, ToolOutput, ToolResult } from "@diffusionstudio/dapi";++/** A file the tool wrote, kept in memory only long enough to decide whether to inline it. */+export type WrittenImage = { path: string; png: Uint8Array };++export type Presented = { output: unknown; images: WrittenImage[] };++/** More than this, or any image larger than INLINE_MAX_BYTES, and the caller gets paths only. */+const INLINE_MAX_IMAGES = 4;+const INLINE_MAX_BYTES = 1 << 20;++const APP_SLUG = "diffusion-studio";++export async function present(name: ToolName, args: unknown, result: unknown): Promise<Presented> {+ switch (name) {+ case "capture":+ return presentImages(result as ToolResult<"capture">, (args as ToolArgs<"capture">).output, "capture");+ case "media_grab":+ return presentImages(result as ToolResult<"media_grab">, (args as ToolArgs<"media_grab">).output, "grab");+ case "media_filmstrip":+ return presentPreview(result as ToolResult<"media_filmstrip">, (args as ToolArgs<"media_filmstrip">).output, "filmstrip");+ case "media_waveform":+ return presentPreview(result as ToolResult<"media_waveform">, (args as ToolArgs<"media_waveform">).output, "waveform");+ case "screenshot":+ return presentScreenshot(result as ToolResult<"screenshot">, (args as ToolArgs<"screenshot">).output);+ default:+ return { output: result, images: [] };+ }+}++// Frames and contact sheets arrive in the same shape: each image is stamped+// with its timecode (`08s10f`, or `0f-08s10f` for a sheet), which is the+// filename too.+async function presentImages(images: TimecodedImage[], output: string | undefined, kind: string): Promise<Presented> {+ const dir = output ?? (await mkdtemp(join(tmpdir(), `dapi-${kind}-`)));+ await mkdir(dir, { recursive: true });+ const written: WrittenImage[] = [];+ const refs: ToolOutput<"capture">["images"] = [];+ for (const { timecode, png } of images) {+ const path = join(dir, `${timecode}.png`);+ await writeFile(path, png);+ written.push({ path, png });+ refs.push({ timecode, path });+ }+ return { output: { images: refs }, images: written };+}++async function presentPreview(+ result: { png: Uint8Array } & Record<string, unknown>,+ output: string | undefined,+ kind: string,+): Promise<Presented> {+ const { png, ...rest } = result;+ const path = output ?? join(tmpdir(), `dapi-${kind}-${randomUUID()}.png`);+ await mkdir(dirname(path), { recursive: true });+ await writeFile(path, png);+ return { output: { path, ...rest }, images: [{ path, png }] };+}++async function presentScreenshot(result: ToolResult<"screenshot">, output: string | undefined): Promise<Presented> {+ const dir = output ?? tmpdir();+ await mkdir(dir, { recursive: true });+ const taken = new Date();+ let attempt = 1;+ let path = join(dir, screenshotFilename(taken, attempt));+ while (existsSync(path)) path = join(dir, screenshotFilename(taken, ++attempt));+ await writeFile(path, result.png);+ const presented: ToolOutput<"screenshot"> = { path, width: result.width, height: result.height };+ return { output: presented, images: [{ path, png: result.png }] };+}++function screenshotFilename(taken: Date, attempt: number): string {+ const pad = (value: number) => String(value).padStart(2, "0");+ const date = [taken.getFullYear(), pad(taken.getMonth() + 1), pad(taken.getDate())].join("-");+ const time = [pad(taken.getHours()), pad(taken.getMinutes()), pad(taken.getSeconds())].join("-");+ return `${APP_SLUG}_${date}_${time}${attempt > 1 ? `-${attempt}` : ""}.png`;+}++/** The MCP result: the output as text and structured content, plus the images when they are few and small. */+export function toCallToolResult({ output, images }: Presented): CallToolResult {+ const content: CallToolResult["content"] = [{ type: "text", text: JSON.stringify(output) }];+ const inline = images.length <= INLINE_MAX_IMAGES && images.every((image) => image.png.byteLength <= INLINE_MAX_BYTES);+ if (inline) {+ for (const { png } of images) {+ content.push({ type: "image", data: Buffer.from(png).toString("base64"), mimeType: "image/png" });+ }+ }+ return { content, structuredContent: output as Record<string, unknown> };+}++/** A failure the agent reads as a sentence, not a protocol error. */+export function toErrorResult(error: unknown): CallToolResult {+ return { isError: true, content: [{ type: "text", text: (error as Error).message }] };+}diff --git a/apps/desktop/src/dapi/renderer-calls.ts b/apps/desktop/src/dapi/renderer-calls.tsnew file mode 100644index 00000000..e5be4f51--- /dev/null+++ b/apps/desktop/src/dapi/renderer-calls.ts@@ -0,0 +1,110 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { randomUUID } from "node:crypto";+import { app, BrowserWindow, ipcMain } from "electron";+import { DAPI_WIRE, DapiError } from "@diffusionstudio/dapi";++import type { DapiCall, DapiCancel, DapiReply } from "@diffusionstudio/dapi";++type InFlight = {+ resolve(data: unknown): void;+ reject(error: Error): void;+};++/**+ * Runs renderer tools from main: one `dapi:call` per request, answered by+ * `dapi:reply`, or `dapi:cancel` if the caller gives up. Calls wait for the+ * current window to finish loading; a window that reloads or dies fails the+ * calls it was answering.+ */+export class RendererCalls {+ private readonly inFlight = new Map<string, InFlight>();+ private window: BrowserWindow | null = null;++ start(): void {+ ipcMain.on(DAPI_WIRE.REPLY, (_event, reply: DapiReply) => {+ const call = this.inFlight.get(reply.id);+ if (!call) return;+ this.inFlight.delete(reply.id);+ if (reply.ok) call.resolve(reply.data);+ else call.reject(reply.error.code ? new DapiError(reply.error.code, reply.error.message) : new Error(reply.error.message));+ });++ app.on("browser-window-created", (_event, window) => this.track(window));+ const windows = BrowserWindow.getAllWindows();+ if (windows.length > 0) this.track(windows[windows.length - 1]!);+ }++ async call(tool: string, args: unknown, signal: AbortSignal): Promise<unknown> {+ const window = await this.ready();+ const id = randomUUID();+ return new Promise((resolve, reject) => {+ const onAbort = () => {+ this.inFlight.delete(id);+ if (!window.isDestroyed()) window.webContents.send(DAPI_WIRE.CANCEL, { id } satisfies DapiCancel);+ reject(new DapiError("canceled", "The call was canceled."));+ };+ signal.addEventListener("abort", onAbort, { once: true });+ this.inFlight.set(id, {+ resolve: (data) => {+ signal.removeEventListener("abort", onAbort);+ resolve(data);+ },+ reject: (error) => {+ signal.removeEventListener("abort", onAbort);+ reject(error);+ },+ });+ window.webContents.send(DAPI_WIRE.CALL, { id, tool, args } satisfies DapiCall);+ });+ }++ private track(window: BrowserWindow): void {+ this.window = window;+ const fail = (why: string) => () => this.failAll(why);+ window.webContents.on("did-start-loading", fail("The app reloaded before replying"));+ window.webContents.on("render-process-gone", fail("The app's renderer crashed"));+ window.on("closed", () => {+ if (this.window === window) this.window = null;+ this.failAll("The app window closed before replying");+ });+ }++ private failAll(message: string): void {+ const calls = [...this.inFlight.values()];+ this.inFlight.clear();+ for (const call of calls) call.reject(new Error(message));+ }++ // Resolves with the current window once it has finished loading.+ private ready(timeoutMs = 30000): Promise<BrowserWindow> {+ const window = this.window;+ if (!window || window.isDestroyed()) return Promise.reject(new Error("The app has no window"));+ if (window.webContents.isCrashed()) return Promise.reject(new Error("The app's renderer crashed"));+ if (!window.webContents.isLoading()) return Promise.resolve(window);++ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ cleanup();+ reject(new Error("The app did not become ready in time"));+ }, timeoutMs);+ const cleanup = () => {+ clearTimeout(timer);+ window.webContents.off("did-finish-load", onLoad);+ window.webContents.off("did-fail-load", onFail);+ };+ const onLoad = () => {+ cleanup();+ resolve(window);+ };+ const onFail = () => {+ cleanup();+ reject(new Error("The app failed to load"));+ };+ window.webContents.on("did-finish-load", onLoad);+ window.webContents.on("did-fail-load", onFail);+ });+ }+}diff --git a/apps/desktop/src/dapi/server.ts b/apps/desktop/src/dapi/server.tsnew file mode 100644index 00000000..5cd18734--- /dev/null+++ b/apps/desktop/src/dapi/server.ts@@ -0,0 +1,122 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { chmodSync, existsSync, unlinkSync } from "node:fs";+import { createServer } from "node:net";+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { tools } from "@diffusionstudio/dapi";+import { SOCKET_PATH, SocketTransport } from "@diffusionstudio/dapi/socket";+import { mainHandlers } from "./handlers";+import { present, toCallToolResult, toErrorResult } from "./present";+import { RendererCalls } from "./renderer-calls";++import type { Server, Socket } from "node:net";+import type { GenericTool, LogEntry, ToolName } from "@diffusionstudio/dapi";+import type { MainContext, MainToolName } from "./handler";++export type DapiServerDeps = {+ version: string;+ /** The app's console buffer, for `logs` and `report`. */+ logs(): LogEntry[];+ /** Called once, on the first connection: an agent is driving, so the UI may step back. */+ onFirstConnection(): void;+};++/**+ * The app's MCP server. Listens on the local socket; each connection gets its+ * own MCP session over the catalog. Main-process tools run here; renderer+ * tools are forwarded over IPC and their results presented (files written,+ * small images inlined) before they go back out.+ */+export class DapiServer {+ private readonly deps: DapiServerDeps;+ private readonly renderer = new RendererCalls();+ private readonly sessions = new Set<McpServer>();+ private server: Server | null = null;+ private connected = false;++ constructor(deps: DapiServerDeps) {+ this.deps = deps;+ for (const tool of tools) {+ if (tool.runsIn === "main" && !(tool.name in mainHandlers)) {+ throw new Error(`Main-process tool "${tool.name}" has no handler`);+ }+ }+ }++ start(): void {+ removeStaleSocket();+ this.renderer.start();+ this.server = createServer((socket) => void this.accept(socket));+ this.server.on("error", (error) => console.error("[dapi] server error:", error));+ this.server.listen(SOCKET_PATH, () => {+ // Linux shares /tmp between users; the socket file's mode is the auth.+ if (process.platform !== "win32") chmodSync(SOCKET_PATH, 0o600);+ });+ }++ stop(): void {+ for (const session of this.sessions) void session.close();+ this.sessions.clear();+ this.server?.close();+ this.server = null;+ removeStaleSocket();+ }++ private async accept(socket: Socket): Promise<void> {+ if (!this.connected) {+ this.connected = true;+ this.deps.onFirstConnection();+ }++ const session = new McpServer({ name: "diffusion-studio", version: this.deps.version });+ for (const tool of tools) this.register(session, tool);+ this.sessions.add(session);+ session.server.onclose = () => this.sessions.delete(session);+ try {+ await session.connect(new SocketTransport(socket));+ } catch (error) {+ console.error("[dapi] session failed to start:", error);+ this.sessions.delete(session);+ socket.destroy();+ }+ }++ private register(session: McpServer, tool: GenericTool): void {+ session.registerTool(+ tool.name,+ { title: tool.title, description: tool.description, inputSchema: tool.input, outputSchema: tool.output },+ async (args, extra) => {+ try {+ const result =+ tool.runsIn === "main"+ ? await this.runInMain(tool.name as MainToolName, args, extra.signal)+ : await this.renderer.call(tool.name, args, extra.signal);+ return toCallToolResult(await present(tool.name as ToolName, args, result));+ } catch (error) {+ return toErrorResult(error);+ }+ },+ );+ }++ private runInMain(name: MainToolName, args: unknown, signal: AbortSignal): Promise<unknown> {+ const ctx: MainContext = { signal, logs: this.deps.logs, version: this.deps.version };+ // Each handler takes its own parsed args; the map's union type cannot+ // express that pairing, so the call site widens.+ return (mainHandlers[name] as (args: unknown, ctx: MainContext) => Promise<unknown>)(args, ctx);+ }+}++/**+ * A socket file left by a previous run (Unix). Safe to remove because the+ * single-instance lock guarantees no other instance of ours is running.+ */+function removeStaleSocket(): void {+ try {+ if (process.platform !== "win32" && existsSync(SOCKET_PATH)) unlinkSync(SOCKET_PATH);+ } catch {+ // Best-effort.+ }+}diff --git a/apps/desktop/src/edit-types.ts b/apps/desktop/src/edit-types.tsnew file mode 100644index 00000000..1523cc57--- /dev/null+++ b/apps/desktop/src/edit-types.ts@@ -0,0 +1,140 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The shapes of a source edit and its outcome: the contract between the+// canvas (renderer) and the edit writer (main). Types only, with no Node+// imports, so the renderer's program can include it without Node's types.++import type { InspectValue, PropValue, SerializedAssetRef } from "@diffusionstudio/jsx";++export type { PropValue, SerializedAssetRef };++/**+ * A value an edit can carry: what a source spells as a literal, or a+ * `generate.*` declaration in its wire form, spelled as the call that+ * reproduces it (see `setProp`).+ */+export type EditValue = PropValue | SerializedAssetRef;++export interface SourceContext {+ /** Absolute path of the project folder. */+ dir: string;+ /** Called with the project-relative path of every file written. */+ onWrite?: (file: string) => void;+}++/**+ * Overwrites props of the element named by `source` (a `SOURCE_ATTR` value),+ * and — for a `<text>` — what it says. `text` is its literal content, which is+ * its children rather than a prop and so arrives on its own; an element that+ * only says something new comes with no props at all.+ */+export interface SourceSet {+ kind: "set";+ source: string;+ props: Record<string, EditValue>;+ text?: string;+}++/**+ * Adds `<tag {...props} />` under the element named by `parent`, in front of+ * the child named by `before` or last. `source` is the pending name the canvas+ * knows the new element by; the write answers with the real one in `ids`.+ * A parent may itself be pending when it was inserted earlier in the same+ * write. `text`, when present, is the element's literal text content+ * (`<text>Hello</text>`); without it the element is written self-closing.+ */+export interface SourceInsert {+ kind: "insert";+ source: string;+ parent: string;+ tag: string;+ props: Record<string, EditValue>;+ before?: string;+ text?: string;+}++/**+ * Moves the element named by `source` under the one named by `parent`, in+ * front of the child named by `before` or last. The element travels as it was+ * written — its own text, re-indented for where it lands — so a move is the+ * one edit that does not touch what an element says, only where it says it.+ * Both ends must be in one file: an element cannot move into another module's+ * JSX any more than a project could have put it there.+ */+export interface SourceMove {+ kind: "move";+ source: string;+ parent: string;+ before?: string;+}++/**+ * Removes the element named by `source` from the file, and with it everything+ * it contains: its children are its text, and go the way a move takes them+ * along. Addressed like a move — an unnamed element is a position, and cutting+ * text renumbers positions, so the element is found before anything is cut.+ */+export interface SourceRemove {+ kind: "remove";+ source: string;+}++/**+ * One iteration of a loop as the canvas rendered it: for every composition+ * element of the loop body, by its source, the props it came out with and (for+ * a `<text>`) its literal content — the values that were computed from the+ * item, spelled as literals. `pending` is the name the canvas already knows+ * that iteration's copy of the element by; the write answers with the real+ * one in `ids`. The first iteration keeps the body's own names, so it carries+ * none.+ */+export type SourceIteration = Record<string, { props: Record<string, EditValue>; text?: string; pending?: string }>;++/**+ * Replaces the `<For>`/`<Index>` around the element named by `source` with+ * one copy of its body per iteration, each spelling out what that iteration+ * rendered. Nothing that comes after this in the same write can address a+ * looped element (see `inLoop`): the loop is a recipe for elements, and a+ * change to one of them means writing them down first.+ */+export interface SourceUnroll {+ kind: "unroll";+ source: string;+ iterations: SourceIteration[];+}++/**+ * Overwrites the initializer of an `@inspect`-annotated top-level const (see+ * @diffusionstudio/jsx's inspect). Addressed by file and variable name — a+ * const's name is unique in its module, so no id is needed — and only written+ * when the declaration still carries the annotation and holds a literal: an+ * initializer someone rewrote into an expression is theirs again.+ */+export interface SourceVariable {+ kind: "variable";+ file: string;+ name: string;+ value: InspectValue;+}++export type SourceEdit = SourceSet | SourceInsert | SourceMove | SourceRemove | SourceUnroll | SourceVariable;++export interface WriteResult {+ /** Sources that could not be written, as `id` or `id (prop)`. */+ skipped: string[];+ /**+ * Elements that earned a name in this write, as `old source id -> new one`.+ * The canvas re-stamps its entities with these, so identity does not have to+ * wait for a recompile.+ */+ ids?: Record<string, string>;+ /**+ * The loops this write unrolled, by the `source` of the `SourceUnroll` that+ * asked. An unroll not listed here was declined, and the canvas takes its+ * loop back (see the edit writer).+ */+ unrolled?: string[];+ error?: string;+}diff --git a/apps/desktop/src/edit.ts b/apps/desktop/src/edit.tsindex b878d6de..f0f7dd70 100644--- a/apps/desktop/src/edit.ts+++ b/apps/desktop/src/edit.ts@@ -11,7 +11,7 @@ import { IndentationText, Project, SyntaxKind } from "ts-morph";import { ID_ATTR, INSPECT_TAG, formatSource, isCompositionTag, isLoopTag, isSerializedAssetRef, parseSource } from "@diffusionstudio/jsx";-import type { InspectValue, PropValue, SerializedAssetRef } from "@diffusionstudio/jsx";+import type { PropValue, SerializedAssetRef } from "@diffusionstudio/jsx";import type {ArrowFunction,FunctionExpression,@@ -24,136 +24,19 @@ import type {SourceFile,} from "ts-morph";-export type { PropValue, SerializedAssetRef };--/**- * A value an edit can carry: what a source spells as a literal, or a- * `generate.*` declaration in its wire form, spelled as the call that- * reproduces it (see `setProp`).- */-export type EditValue = PropValue | SerializedAssetRef;--export interface SourceContext {- /** Absolute path of the project folder. */- dir: string;- /** Called with the project-relative path of every file written. */- onWrite?: (file: string) => void;-}--/**- * Overwrites props of the element named by `source` (a `SOURCE_ATTR` value),- * and — for a `<text>` — what it says. `text` is its literal content, which is- * its children rather than a prop and so arrives on its own; an element that- * only says something new comes with no props at all.- */-export interface SourceSet {- kind: "set";- source: string;- props: Record<string, EditValue>;- text?: string;-}--/**- * Adds `<tag {...props} />` under the element named by `parent`, in front of- * the child named by `before` or last. `source` is the pending name the canvas- * knows the new element by; the write answers with the real one in `ids`.- * A parent may itself be pending when it was inserted earlier in the same- * write. `text`, when present, is the element's literal text content- * (`<text>Hello</text>`); without it the element is written self-closing.- */-export interface SourceInsert {- kind: "insert";- source: string;- parent: string;- tag: string;- props: Record<string, EditValue>;- before?: string;- text?: string;-}--/**- * Moves the element named by `source` under the one named by `parent`, in- * front of the child named by `before` or last. The element travels as it was- * written — its own text, re-indented for where it lands — so a move is the- * one edit that does not touch what an element says, only where it says it.- * Both ends must be in one file: an element cannot move into another module's- * JSX any more than a project could have put it there.- */-export interface SourceMove {- kind: "move";- source: string;- parent: string;- before?: string;-}--/**- * Removes the element named by `source` from the file, and with it everything- * it contains: its children are its text, and go the way a move takes them- * along. Addressed like a move — an unnamed element is a position, and cutting- * text renumbers positions, so the element is found before anything is cut.- */-export interface SourceRemove {- kind: "remove";- source: string;-}--/**- * One iteration of a loop as the canvas rendered it: for every composition- * element of the loop body, by its source, the props it came out with and (for- * a `<text>`) its literal content — the values that were computed from the- * item, spelled as literals. `pending` is the name the canvas already knows- * that iteration's copy of the element by; the write answers with the real- * one in `ids`. The first iteration keeps the body's own names, so it carries- * none.- */-export type SourceIteration = Record<string, { props: Record<string, EditValue>; text?: string; pending?: string }>;--/**- * Replaces the `<For>`/`<Index>` around the element named by `source` with- * one copy of its body per iteration, each spelling out what that iteration- * rendered. Nothing that comes after this in the same write can address a- * looped element (see `inLoop`): the loop is a recipe for elements, and a- * change to one of them means writing them down first.- */-export interface SourceUnroll {- kind: "unroll";- source: string;- iterations: SourceIteration[];-}--/**- * Overwrites the initializer of an `@inspect`-annotated top-level const (see- * @diffusionstudio/jsx's inspect). Addressed by file and variable name — a- * const's name is unique in its module, so no id is needed — and only written- * when the declaration still carries the annotation and holds a literal: an- * initializer someone rewrote into an expression is theirs again.- */-export interface SourceVariable {- kind: "variable";- file: string;- name: string;- value: InspectValue;-}--export type SourceEdit = SourceSet | SourceInsert | SourceMove | SourceRemove | SourceUnroll | SourceVariable;--export interface WriteResult {- /** Sources that could not be written, as `id` or `id (prop)`. */- skipped: string[];- /**- * Elements that earned a name in this write, as `old source id -> new one`.- * The canvas re-stamps its entities with these, so identity does not have to- * wait for a recompile.- */- ids?: Record<string, string>;- /**- * The loops this write unrolled, by the `source` of the `SourceUnroll` that- * asked. An unroll not listed here was declined, and the canvas takes its- * loop back (see the edit writer).- */- unrolled?: string[];- error?: string;-}+export type * from "./edit-types";+import type {+ EditValue,+ SourceContext,+ SourceEdit,+ SourceInsert,+ SourceIteration,+ SourceMove,+ SourceRemove,+ SourceUnroll,+ SourceVariable,+ WriteResult,+} from "./edit-types";/** The opening half of a JSX element — where its attributes live. */type JsxTag = JsxOpeningElement | JsxSelfClosingElement;diff --git a/apps/desktop/src/headless.ts b/apps/desktop/src/headless.tsnew file mode 100644index 00000000..b695807e--- /dev/null+++ b/apps/desktop/src/headless.ts@@ -0,0 +1,18 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// Whether an agent has connected since launch. Once one has, the UI steps+// back: file writes from tools are not echoed as edits, and the window may+// stay hidden. Set by the MCP server on its first connection; read wherever+// behaviour depends on who is driving.++let headless = false;++export function isHeadless(): boolean {+ return headless;+}++export function enableHeadless(): void {+ headless = true;+}diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex 9fd04403..fd88916d 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -7,10 +7,10 @@// through these via an envelope carrying the logical MAIN_CHANNELS name and// (for requests) a UUID for correlation.//-// CLI traffic uses a separate wire pair (CLI_WIRE in @diffusionstudio/cli/protocol);-// main forwards it opaquely without inspecting channel names.+// Tool calls from the MCP server use their own wire (DAPI_WIRE in+// @diffusionstudio/dapi), in the other direction: main asks, the renderer answers.import type { LogEntry, ScreenshotResult } from "@diffusionstudio/dapi";-import type { SourceEdit, WriteResult } from "./edit";+import type { SourceEdit, WriteResult } from "./edit-types";export const MAIN_WIRE = {REQUEST: "main:request",diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex bd79dd7c..23039413 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -8,7 +8,8 @@ import { mkdir, open, unlink } from "node:fs/promises";import { randomUUID } from "node:crypto";import type { FileHandle } from "node:fs/promises";import { updateElectronApp } from "update-electron-app";-import { startCliServer, stopCliServer, isHeadless } from "./cli-server";+import { DapiServer } from "./dapi/server";+import { enableHeadless, isHeadless } from "./headless";import { installCli, isCliInstalled } from "./cli-install";import { healSkillsLinks, installSkills, isSkillsInstalled } from "./skills-install";import { trackInstall } from "./analytics";@@ -97,6 +98,19 @@ const pendingDeepLinks = new Map<DeepLinkChannel, string>();const LOG_BUFFER_MAX = 2000;const logBuffer: LogEntry[] = [];+// The MCP server agents and the dapi CLI talk to. Started once the app is+// ready; the first connection switches the UI into headless mode.+const dapi = new DapiServer({+ version: app.getVersion(),+ logs: () => logBuffer,+ onFirstConnection() {+ enableHeadless();+ if (mainWindow && !mainWindow.isDestroyed()) {+ mainBridge.emit(mainWindow, MAIN_CHANNELS.HEADLESS_MODE, { active: true });+ }+ },+});+function pushLog(level: LogEntry["level"], message: string, source: string) {logBuffer.push({ ts: Date.now(), level, message, source });if (logBuffer.length > LOG_BUFFER_MAX) logBuffer.shift();@@ -361,7 +375,7 @@ if (app.requestSingleInstanceLock()) {const url = findProtocolUrl(process.argv);if (url) deliverDeepLink(url);- startCliServer();+ dapi.start();healSkillsLinks();trackInstall();createWindow(!isHiddenLaunch(process.argv));@@ -369,7 +383,7 @@ if (app.requestSingleInstanceLock()) {app.on("before-quit", () => {unwatchAll();- stopCliServer();+ dapi.stop();});app.on("window-all-closed", () => {diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 60e10afe..1793687d 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -4,16 +4,17 @@import { contextBridge, ipcRenderer, webUtils } from "electron";import { MAIN_WIRE } from "./main-channels";-import { CLI_WIRE } from "@diffusionstudio/cli/protocol";+import { DAPI_WIRE } from "@diffusionstudio/dapi";import type { IpcRendererEvent } from "electron";-const ALLOWED_RENDERER_TO_MAIN: ReadonlySet<string> = new Set([MAIN_WIRE.REQUEST]);+const ALLOWED_RENDERER_TO_MAIN: ReadonlySet<string> = new Set([MAIN_WIRE.REQUEST, DAPI_WIRE.REPLY]);const ALLOWED_MAIN_TO_RENDERER: ReadonlySet<string> = new Set([MAIN_WIRE.RESPONSE,MAIN_WIRE.EVENT,- CLI_WIRE.CONNECT,+ DAPI_WIRE.CALL,+ DAPI_WIRE.CANCEL,]);contextBridge.exposeInMainWorld("desktop", {diff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsindex 533fffb9..d7303b25 100644--- a/apps/desktop/src/projects.ts+++ b/apps/desktop/src/projects.ts@@ -14,7 +14,7 @@ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";import type { PluginItem, TransformOptions } from "@babel/core";import type { BuildOptions, Plugin } from "esbuild";-import { isHeadless } from "./cli-server";+import { isHeadless } from "./headless";import { mainBridge } from "./main-manager";import { MAIN_CHANNELS } from "./main-channels";import { applyEdits, editLabel, stampProject } from "./edit";diff --git a/apps/web/package.json b/apps/web/package.jsonindex a60ab03c..929f6a3d 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -15,7 +15,6 @@"dependencies": {"@diffusionstudio/api-contract": "^0.1.0","@diffusionstudio/assets": "*",- "@diffusionstudio/cli": "*","@diffusionstudio/encoder": "*","@diffusionstudio/jsx": "*","@diffusionstudio/koota-solid": "*",diff --git a/apps/web/src/context/render.ts b/apps/web/src/context/render.tsindex ab2eca7b..b7003a9d 100644--- a/apps/web/src/context/render.ts+++ b/apps/web/src/context/render.ts@@ -32,6 +32,8 @@ export type RenderOverlayState = {remaining?: { minutes: number; seconds: number };};+const PROGRESS_LOG_STEP = 2;+const [overlay, setOverlay] = createSignal<RenderOverlayState | null>(null);let cancelActive: (() => void) | undefined;@@ -78,6 +80,13 @@ export async function renderScene(cancelActive = undefined;setOverlay({ config, width, height, duration, progress: 0, remaining: undefined });+ let logged = -1;+ const logProgress = (percent: number) => {+ if (percent - logged < PROGRESS_LOG_STEP && percent < 100) return;+ logged = percent;+ console.info(`[export] ${percent}%`);+ };+engine.stop();let capture: Capture | undefined;@@ -94,6 +103,7 @@ export async function renderScene(comment: `Made with Diffusion Studio v${version}`,onProgress(p) {const percent = Math.round((p.progress / p.total) * 100);+ logProgress(percent);setOverlay((prev) =>prev? {diff --git a/apps/web/src/dapi/api.tsx b/apps/web/src/dapi/api.tsxindex 611f2246..f2d9c8ca 100644--- a/apps/web/src/dapi/api.tsx+++ b/apps/web/src/dapi/api.tsx@@ -14,12 +14,12 @@ import { openProjectFolder } from "@/projects";import { projectRoute } from "@/hooks/use-project-route";import { useFullscreenState } from "@/hooks/use-fullscreen-state";import { assert } from "@/utils/common";-import { cliBridge } from "./bridge";+import { toolBridge } from "./bridge";import { handlers } from "./handlers";import { editorSession, requireEditorSession, setEditorSession } from "./session";import type { JSX, Accessor } from "solid-js";-import type { ToolContext } from "./handler";+import type { ContextFactory } from "./bridge";type EditorApiContextValue = {isFullscreen: Accessor<boolean>;@@ -39,7 +39,7 @@ export function EditorApi() {const navigate = useNavigate();const auth = useAuth();- const context = (signal: AbortSignal): ToolContext => ({+ const context: ContextFactory = (signal) => ({session: editorSession,requireSession: requireEditorSession,signal,@@ -58,7 +58,7 @@ export function EditorApi() {},});- onCleanup(cliBridge.register(handlers, context));+ onCleanup(toolBridge.register(handlers, context));return null;}diff --git a/apps/web/src/dapi/bridge.ts b/apps/web/src/dapi/bridge.tsindex 2db5a591..c640bb56 100644--- a/apps/web/src/dapi/bridge.ts+++ b/apps/web/src/dapi/bridge.ts@@ -2,48 +2,31 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-import { parseToolArgs } from "@diffusionstudio/dapi";-import { CLI_WIRE, encodeReply } from "@diffusionstudio/cli/protocol";+import { DAPI_WIRE, isDapiError } from "@diffusionstudio/dapi";-import type { CliHandshake, CliReply, CliRequest } from "@diffusionstudio/cli/protocol";+import type { DapiCall, DapiCancel, DapiReply } from "@diffusionstudio/dapi";import type { Handlers, ServedToolName, ToolContext } from "./handler";-type Pending = { req: CliRequest; ws: WebSocket };-/** Builds the per-call context; the bridge supplies the abort signal. */export type ContextFactory = (signal: AbortSignal) => ToolContext;/**- * Answers tool calls from the CLI. Each CLI command hosts a short-lived- * WebSocket server; main relays only the connect info (CLI_WIRE.CONNECT) and- * we dial the CLI directly, so payloads never pass through main. One request- * and one reply per connection.- *- * The bridge is transport: it validates arguments against the catalog, runs- * the handler, and encodes the reply. Requests arriving before the handlers- * register (page bootstrap) are held and answered on registration.+ * Answers renderer tools for the MCP server in main. Main validated the+ * arguments against the catalog before sending them; this side runs the+ * handler and replies, honouring cancels. Calls that arrive before the+ * handlers register (page bootstrap) are held and answered on registration.*/-class CliBridge {+class ToolBridge {private handlers: Handlers | null = null;private context: ContextFactory | null = null;- private held: Pending[] = [];+ private held: DapiCall[] = [];+ private readonly inFlight = new Map<string, AbortController>();constructor() {- // Bind eagerly so CONNECT arrivals during page bootstrap are caught- // rather than silently dropped before the handlers register.- window.desktop?.on(CLI_WIRE.CONNECT, (payload) => {- const { port, token } = payload as CliHandshake;- const ws = new WebSocket(`ws://127.0.0.1:${port}/?token=${token}`);- ws.onmessage = (event) => {- try {- const req = JSON.parse(event.data as string) as CliRequest;- void this.dispatch({ req, ws });- } catch (err) {- console.error("[cli-bridge] malformed CLI request", err);- ws.close();- }- };- });+ // Bind eagerly so calls during page bootstrap are caught rather than+ // silently dropped before the handlers register.+ window.desktop?.on(DAPI_WIRE.CALL, (payload) => void this.dispatch(payload as DapiCall));+ window.desktop?.on(DAPI_WIRE.CANCEL, (payload) => this.inFlight.get((payload as DapiCancel).id)?.abort());}register(handlers: Handlers, context: ContextFactory): () => void {@@ -51,7 +34,7 @@ class CliBridge {this.context = context;const held = this.held;this.held = [];- for (const pending of held) void this.dispatch(pending);+ for (const call of held) void this.dispatch(call);return () => {if (this.handlers === handlers) {this.handlers = null;@@ -60,41 +43,31 @@ class CliBridge {};}- private async dispatch(pending: Pending): Promise<void> {- const { req, ws } = pending;- // Liveness, answered by the transport itself: `open` waits on it after- // launching the app, before any handler exists to answer anything else.- if (req.path === "ping") {- ws.send(encodeReply({ ok: true, data: undefined }));- return;- }+ private async dispatch(call: DapiCall): Promise<void> {if (!this.handlers || !this.context) {- this.held.push(pending);+ this.held.push(call);return;}const controller = new AbortController();- ws.addEventListener("close", () => controller.abort(), { once: true });+ this.inFlight.set(call.id, controller);- let reply: CliReply;+ let reply: DapiReply;try {- const name = req.path as ServedToolName;- const handler = this.handlers[name];- if (!handler) throw new Error(`Unknown tool "${req.path}"`);- const args = parseToolArgs(name, req.input);+ const handler = this.handlers[call.tool as ServedToolName];+ if (!handler) throw new Error(`The app has no handler for "${call.tool}"`);// Every handler takes its own parsed args; the map's union type cannot// express that pairing, so the call site widens.- const data = await (handler as (args: unknown, ctx: ToolContext) => Promise<unknown>)(args, this.context(controller.signal));- reply = { ok: true, data };- } catch (err) {- reply = { ok: false, error: (err as Error).message };- }- try {- ws.send(encodeReply(reply));- } catch (err) {- ws.send(encodeReply({ ok: false, error: `Failed to serialize reply for ${req.path}: ${(err as Error).message}` }));+ const run = handler as (args: unknown, ctx: ToolContext) => Promise<unknown>;+ reply = { id: call.id, ok: true, data: await run(call.args, this.context(controller.signal)) };+ } catch (error) {+ const message = (error as Error).message;+ reply = { id: call.id, ok: false, error: isDapiError(error) ? { code: error.code, message } : { message } };+ } finally {+ this.inFlight.delete(call.id);}+ if (!controller.signal.aborted) window.desktop?.send(DAPI_WIRE.REPLY, reply);}}-export const cliBridge = new CliBridge();+export const toolBridge = new ToolBridge();diff --git a/apps/web/src/dapi/handler.ts b/apps/web/src/dapi/handler.tsindex 1a7f67ab..22237088 100644--- a/apps/web/src/dapi/handler.ts+++ b/apps/web/src/dapi/handler.ts@@ -17,7 +17,7 @@ export type ToolContext = {session: Accessor<EditorSession | null>;/** The session, or a `no-project` error the caller can act on. */requireSession(): EditorSession;- /** Fires when the caller goes away before the reply. */+ /** Fires when the caller cancels or goes away before the reply. */signal: AbortSignal;/** What only the app shell can do: navigate, and know who is signed in. */app: {@@ -30,11 +30,7 @@ export type ToolContext = {export type ToolHandler<N extends ToolName> = (args: ToolArgs<N>, ctx: ToolContext) => Promise<ToolResult<N>>;-/**- * The tools the renderer answers. `logs` is a main-process tool in the- * catalog and is forwarded from here until main hosts the server itself;- * `fonts`, `fetch` and `report` have no renderer side at all.- */-export type ServedToolName = Exclude<ToolName, "fonts" | "fetch" | "report">;+/** The tools the renderer answers; the rest run in the main process. */+export type ServedToolName = Exclude<ToolName, "logs" | "fonts" | "fetch" | "report">;export type Handlers = { readonly [N in ServedToolName]: ToolHandler<N> };diff --git a/apps/web/src/dapi/handlers/context.ts b/apps/web/src/dapi/handlers/context.tsindex d75b349c..ff5d2bb2 100644--- a/apps/web/src/dapi/handlers/context.ts+++ b/apps/web/src/dapi/handlers/context.ts@@ -21,7 +21,7 @@ export const context: ToolHandler<"context"> = async (_, ctx) => {const rootDir = await getProjectsRoot();const open = ctx.session();- if (!open) return { rootDir, projectDir: null };+ if (!open) return { rootDir, projectDir: null, currentTime: null, fontFamilies: [], generations: [] };const { world, project } = open;const frameRate = world.get(FrameRate)?.value || 30;diff --git a/apps/web/src/dapi/handlers/index.ts b/apps/web/src/dapi/handlers/index.tsindex 2277306b..9aa95a0b 100644--- a/apps/web/src/dapi/handlers/index.ts+++ b/apps/web/src/dapi/handlers/index.ts@@ -10,7 +10,6 @@ import { exportScene } from "./export";import { models } from "./models";import { voices } from "./voices";import { whoami } from "./whoami";-import { logs } from "./logs";import { screenshot } from "./screenshot";import { mediaProbe } from "./media-probe";import { mediaGrab } from "./media-grab";@@ -31,7 +30,6 @@ export const handlers: Handlers = {models,voices,whoami,- logs,screenshot,media_probe: mediaProbe,media_grab: mediaGrab,diff --git a/apps/web/src/dapi/handlers/logs.ts b/apps/web/src/dapi/handlers/logs.tsdeleted file mode 100644index cdb909f8..00000000--- a/apps/web/src/dapi/handlers/logs.ts+++ /dev/null@@ -1,22 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { mainBridge } from "@/lib/ipc";-import { MAIN_CHANNELS } from "@desktop/main-channels";--import type { LogLevel } from "@diffusionstudio/dapi";-import type { ToolHandler } from "../handler";--const LEVEL_RANK: Record<LogLevel, number> = { debug: 0, info: 1, warning: 2, error: 3 };--// Main owns the buffer; this is a forward until main answers tools itself.-export const logs: ToolHandler<"logs"> = async ({ tail, level }) => {- let entries = await mainBridge.call(MAIN_CHANNELS.LOGS_GET, undefined);- if (level !== undefined) {- const min = LEVEL_RANK[level];- entries = entries.filter((e) => LEVEL_RANK[e.level] >= min);- }- if (tail !== undefined) entries = entries.slice(-tail);- return entries;-};diff --git a/apps/web/src/dapi/handlers/models.ts b/apps/web/src/dapi/handlers/models.tsindex b9d575b9..5209511a 100644--- a/apps/web/src/dapi/handlers/models.ts+++ b/apps/web/src/dapi/handlers/models.ts@@ -31,5 +31,5 @@ export const models: ToolHandler<"models"> = async ({ type }) => {if (!type || type === "audio") {for (const { id, name } of PROMPT_INPUT_AUDIO_MODEL_OPTIONS) out.push({ type: "audio", id, name });}- return out;+ return { models: out };};diff --git a/apps/web/src/dapi/handlers/voices.ts b/apps/web/src/dapi/handlers/voices.tsindex e589b0c0..65fd8982 100644--- a/apps/web/src/dapi/handlers/voices.ts+++ b/apps/web/src/dapi/handlers/voices.ts@@ -6,5 +6,6 @@ import { PROMPT_INPUT_VOICE_OPTIONS } from "@/components/genai/config";import type { ToolHandler } from "../handler";-export const voices: ToolHandler<"voices"> = async () =>- PROMPT_INPUT_VOICE_OPTIONS.map((v) => ({ id: v.value, label: v.label, description: v.description }));+export const voices: ToolHandler<"voices"> = async () => ({+ voices: PROMPT_INPUT_VOICE_OPTIONS.map((v) => ({ id: v.value, label: v.label, description: v.description })),+});diff --git a/apps/web/src/dapi/handlers/whoami.ts b/apps/web/src/dapi/handlers/whoami.tsindex 23022db5..a23daaa7 100644--- a/apps/web/src/dapi/handlers/whoami.ts+++ b/apps/web/src/dapi/handlers/whoami.ts@@ -4,4 +4,4 @@import type { ToolHandler } from "../handler";-export const whoami: ToolHandler<"whoami"> = async (_, ctx) => ctx.app.user();+export const whoami: ToolHandler<"whoami"> = async (_, ctx) => ({ user: ctx.app.user() });diff --git a/docs/mcp-server.md b/docs/mcp-server.mdindex d32644b3..94d0a1dd 100644--- a/docs/mcp-server.md+++ b/docs/mcp-server.md@@ -17,7 +17,7 @@ The point is not MCP for its own sake. The point is that the API gets one defini- One definition of the API: tool names, input schemas, descriptions and result shapes, owned by the app and served to clients at runtime.- Agents reach the app with a one-line registration and no PATH install.-- Long operations (export, generation, `listen`) report progress and can be cancelled, without client-side timeouts.+- Long operations (export, generation, `listen`) can be cancelled, and their progress is visible through `logs`.- The CLI binary stays useful for humans, scripts and CI, and no longer has to be built against a specific router type.- Keep the renderer handlers and their behaviour. This is a transport and surface change, not a rewrite of `capture`, `check`, `export` or the media handlers.@@ -141,14 +141,13 @@ for (const tool of catalog) {**Main-to-renderer calls.** The current bridge (`apps/desktop/src/main-manager.ts` and `MainBridge` in `apps/web/src/lib/ipc.ts`) carries requests from the renderer to main and events from main to the renderer. It has no request in the other direction, so this adds one, with three IPC messages:-- `dapi:call` from main: `{ callId, tool, input }`-- `dapi:progress` from renderer: `{ callId, progress, total?, message? }`-- `dapi:reply` from renderer: `{ callId, ok, data | error }`-- `dapi:cancel` from main: `{ callId }`+- `dapi:call` from main: `{ id, tool, args }`+- `dapi:reply` from renderer: `{ id, ok, data | error }`+- `dapi:cancel` from main: `{ id }`Main keeps a map of in-flight calls. Before sending it waits for the renderer to finish loading, which `waitForRendererReady` already does. In the renderer, `CliBridge` loses its WebSocket code and keeps its dispatch and hold-until-a-handler-registers logic, now fed by `dapi:call`. The renderer registers a plain `Record<toolName, handler>` instead of a tRPC router; each handler receives the already-validated input, an `AbortSignal`, and a `report(progress)` callback. tRPC and its `cli-rpc.ts` helpers go away.-**Progress and cancellation.** When the client passes a `progressToken`, main turns `dapi:progress` into `notifications/progress`. When the client sends `notifications/cancelled`, main sends `dapi:cancel` and the handler's `AbortSignal` fires. Client-side timeouts disappear; the client decides how long it is willing to wait. `export` reports encoded frames; `media_listen` and generation-backed work report whatever stage they are in; the others report nothing and that is fine.+**Progress and cancellation.** When the client sends `notifications/cancelled`, main sends `dapi:cancel` and the handler's `AbortSignal` fires. Progress needs no channel of its own: the export path logs its percentage to the console in 2% steps, the app buffers console output, and an agent waiting on an export polls `logs`. That works the same for an in-app export and a tool export, and keeps the call path to one request and one reply.**Results.** Every tool returns `structuredContent` matching its output schema, plus a text block with the same JSON so clients that ignore structured content still get it. Tools that produce images (`capture`, `media_grab`, `media_filmstrip`, `media_waveform`, `screenshot`) keep today's behaviour of writing PNGs to an output directory (an `output` input, defaulting to a fresh directory under the temp dir) and returning the paths. In addition, they inline `image` content blocks when the result is small: at most four images and none over about a megabyte. A contact sheet of a few positions therefore arrives in the agent's context immediately, while an uncapped hundred-frame grab arrives as a directory the agent reads selectively, which is the behaviour the current CLI was designed for.@@ -193,9 +192,9 @@ Removed from the CLI package: `cli-client.ts`, `cli-channels.ts`, the tRPC and `The CLI ships inside the app bundle, so there is no compatibility window to maintain between old CLIs and new apps. This can land as one feature branch in ordered steps, each of which builds and type-checks on its own.1. **Catalog.** Create `packages/dapi` with the tool catalog, `Time`, and `DapiError`, plus tests. Point the renderer handlers' request and result types at it. Delete `apps/cli/src/cli-channels.ts`; `apps/cli/src/protocol.ts` keeps only the handshake and envelope types of the current transport. No behaviour change. *Landed on `mcp-support`.*-2. **Renderer.** Replace the tRPC router in `api.tsx` with one handler per tool behind a uniform `(args, ctx)` signature, validated by the catalog schemas, with an `AbortSignal` per call. Handlers return bytes; the WebSocket transport carries them as tagged base64 until step 3 replaces it. The CLI drops tRPC for a typed `call(name, input)` over the same catalog, so it keeps working at every step and its import of `apps/web` is gone. Progress reporting waits for step 3, with the transport that carries it. *Landed on `mcp-support`.*-3. **Main.** Add `mcp-server.ts` with the socket transport, catalog registration, the in-flight map, result presentation, and the `logs`, `fonts`, `fetch` and `report` handlers. Delete `cli-server.ts`. Verify with the MCP Inspector against the socket.-4. **CLI.** Rewrite `apps/cli` as `mcp`, `open`, `call` and the wrappers. Drop tRPC and `ws`. Update `cli-install.ts` and the settings UI to offer MCP registration.+2. **Renderer.** Replace the tRPC router in `api.tsx` with one handler per tool behind a uniform `(args, ctx)` signature, validated by the catalog schemas, with an `AbortSignal` per call. Handlers return bytes; the WebSocket transport carries them as tagged base64 until step 3 replaces it. The CLI drops tRPC for a typed `call(name, input)` over the same catalog, so it keeps working at every step and its import of `apps/web` is gone. *Landed on `mcp-support`.*+3. **Main.** Add `dapi/server.ts` with catalog registration, `dapi/renderer-calls.ts` with the in-flight map, `dapi/present.ts` for files and inline images, and the `logs`, `fonts`, `fetch` and `report` handlers. The socket transport lives in `@diffusionstudio/dapi/socket`, shared with the CLI, which becomes an MCP client over it in this step so it keeps working. Delete `cli-server.ts`. *Landed on `mcp-support`; verified by an in-process client/server round trip, not yet against the running app.*+4. **CLI.** Add `dapi mcp` and `dapi call`, and generate the wrappers from the catalog. Update `cli-install.ts` and the settings UI to offer MCP registration.5. **Docs.** Update the skill and regenerate `reference/`. Update the installation reference the skill points to.6. **Cleanup.** Remove `CLI_WIRE`, the handshake types, and the `./protocol` and `./channels` exports from the CLI package.diff --git a/package-lock.json b/package-lock.jsonindex 23f685b9..296b1771 100644--- a/package-lock.json+++ b/package-lock.json@@ -25,10 +25,10 @@"@babel/core": "^7.29.7","@babel/preset-typescript": "^7.27.1","@diffusionstudio/dapi": "*",+ "@modelcontextprotocol/sdk": "^1.30.0","babel-preset-solid": "^1.9.12","commander": "^14.0.3",- "esbuild": "^0.28.1",- "ws": "^8.18.3"+ "esbuild": "^0.28.1"},"bin": {"dapi": "dist/index.js"@@ -36,7 +36,6 @@"devDependencies": {"@types/babel__core": "^7.20.5","@types/node": "^24.10.1",- "@types/ws": "^8.18.1","typescript": "~5.9.3"}},@@ -47,9 +46,9 @@"dependencies": {"@babel/core": "^7.29.7","@babel/preset-typescript": "^7.27.1",- "@diffusionstudio/cli": "*","@diffusionstudio/dapi": "*","@diffusionstudio/jsx": "*",+ "@modelcontextprotocol/sdk": "^1.30.0","babel-preset-solid": "^1.9.12","esbuild": "^0.28.1","nanoid": "^6.0.1",@@ -65,7 +64,8 @@"@types/babel__core": "^7.20.5","@types/node": "^24.10.1","electron": "^43.1.1",- "typescript": "~5.9.3"+ "typescript": "~5.9.3",+ "vitest": "^4.0.0"}},"apps/desktop/node_modules/nanoid": {@@ -93,7 +93,6 @@"dependencies": {"@diffusionstudio/api-contract": "^0.1.0","@diffusionstudio/assets": "*",- "@diffusionstudio/cli": "*","@diffusionstudio/dapi": "*","@diffusionstudio/encoder": "*","@diffusionstudio/jsx": "*",@@ -2007,6 +2006,18 @@"dev": true,"license": "MIT"},+ "node_modules/@hono/node-server": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.1.tgz",+ "integrity": "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg==",+ "license": "MIT",+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "hono": "^4"+ }+ },"node_modules/@humanfs/core": {"version": "0.19.2","resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",@@ -2473,6 +2484,85 @@"node": ">= 12.13.0"}},+ "node_modules/@modelcontextprotocol/sdk": {+ "version": "1.30.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz",+ "integrity": "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==",+ "license": "MIT",+ "dependencies": {+ "@hono/node-server": "^1.19.9 || ^2.0.5",+ "ajv": "^8.17.1",+ "ajv-formats": "^3.0.1",+ "content-type": "^1.0.5",+ "cors": "^2.8.5",+ "cross-spawn": "^7.0.5",+ "eventsource": "^3.0.2",+ "eventsource-parser": "^3.0.0",+ "express": "^5.2.1",+ "express-rate-limit": "^8.2.1",+ "hono": "^4.11.4",+ "jose": "^6.1.3",+ "json-schema-typed": "^8.0.2",+ "pkce-challenge": "^5.0.0",+ "raw-body": "^3.0.0",+ "zod": "^3.25 || ^4.0",+ "zod-to-json-schema": "^3.25.1"+ },+ "engines": {+ "node": ">=18"+ },+ "peerDependencies": {+ "@cfworker/json-schema": "^4.1.1",+ "zod": "^3.25 || ^4.0"+ },+ "peerDependenciesMeta": {+ "@cfworker/json-schema": {+ "optional": true+ },+ "zod": {+ "optional": false+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv": {+ "version": "8.20.0",+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",+ "license": "MIT",+ "dependencies": {+ "fast-deep-equal": "^3.1.3",+ "fast-uri": "^3.0.1",+ "json-schema-traverse": "^1.0.0",+ "require-from-string": "^2.0.2"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/epoberezkin"+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/ajv-formats": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",+ "license": "MIT",+ "dependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependencies": {+ "ajv": "^8.0.0"+ },+ "peerDependenciesMeta": {+ "ajv": {+ "optional": true+ }+ }+ },+ "node_modules/@modelcontextprotocol/sdk/node_modules/json-schema-traverse": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",+ "license": "MIT"+ },"node_modules/@nodelib/fs.scandir": {"version": "2.1.5","resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",@@ -4239,16 +4329,6 @@"dev": true,"license": "MIT"},- "node_modules/@types/ws": {- "version": "8.18.1",- "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",- "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",- "dev": true,- "license": "MIT",- "dependencies": {- "@types/node": "*"- }- },"node_modules/@types/yauzl": {"version": "2.10.3","resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",@@ -4858,6 +4938,64 @@"dev": true,"license": "ISC"},+ "node_modules/accepts": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",+ "license": "MIT",+ "dependencies": {+ "mime-types": "^3.0.0",+ "negotiator": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/accepts/node_modules/content-type": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/accepts/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/accepts/node_modules/negotiator": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz",+ "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^2.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/acorn": {"version": "8.17.0","resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz",@@ -5272,6 +5410,59 @@"dev": true,"license": "MIT"},+ "node_modules/body-parser": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",+ "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",+ "license": "MIT",+ "dependencies": {+ "bytes": "^3.1.2",+ "content-type": "^2.0.0",+ "debug": "^4.4.3",+ "http-errors": "^2.0.1",+ "iconv-lite": "^0.7.2",+ "on-finished": "^2.4.1",+ "qs": "^6.15.2",+ "raw-body": "^3.0.2",+ "type-is": "^2.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/body-parser/node_modules/content-type": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/body-parser/node_modules/iconv-lite": {+ "version": "0.7.3",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",+ "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/boolbase": {"version": "1.0.0","resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz",@@ -5405,6 +5596,15 @@"dev": true,"license": "MIT"},+ "node_modules/bytes": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/cacache": {"version": "16.1.3","resolved": "https://registry.npmjs.org/cacache/-/cacache-16.1.3.tgz",@@ -5547,7 +5747,6 @@"version": "1.0.2","resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz","integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",- "dev": true,"license": "MIT","dependencies": {"es-errors": "^1.3.0",@@ -5561,7 +5760,6 @@"version": "1.0.4","resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz","integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",- "dev": true,"license": "MIT","dependencies": {"call-bind-apply-helpers": "^1.0.2",@@ -5933,12 +6131,69 @@"dev": true,"license": "MIT"},+ "node_modules/content-disposition": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/content-type": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/convert-source-map": {"version": "2.0.0","resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz","integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==","license": "MIT"},+ "node_modules/cookie": {+ "version": "0.7.2",+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/cookie-signature": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",+ "license": "MIT",+ "engines": {+ "node": ">=6.6.0"+ }+ },+ "node_modules/cors": {+ "version": "2.8.6",+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",+ "license": "MIT",+ "dependencies": {+ "object-assign": "^4",+ "vary": "^1"+ },+ "engines": {+ "node": ">= 0.10"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/cross-dirname": {"version": "0.1.0","resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz",@@ -5950,7 +6205,6 @@"version": "7.0.6","resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz","integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",- "dev": true,"license": "MIT","dependencies": {"path-key": "^3.1.0",@@ -6211,6 +6465,15 @@"dev": true,"license": "MIT"},+ "node_modules/depd": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/deprecation": {"version": "2.3.1","resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz",@@ -6336,7 +6599,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz","integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",- "dev": true,"license": "MIT","dependencies": {"call-bind-apply-helpers": "^1.0.1",@@ -6354,6 +6616,12 @@"dev": true,"license": "MIT"},+ "node_modules/ee-first": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",+ "license": "MIT"+ },"node_modules/electron": {"version": "43.1.1","resolved": "https://registry.npmjs.org/electron/-/electron-43.1.1.tgz",@@ -6450,6 +6718,15 @@"license": "MIT","optional": true},+ "node_modules/encodeurl": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/encoding": {"version": "0.1.13","resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz",@@ -6542,7 +6819,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz","integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -6552,7 +6828,6 @@"version": "1.3.0","resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz","integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -6569,7 +6844,6 @@"version": "1.1.2","resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz","integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",- "dev": true,"license": "MIT","dependencies": {"es-errors": "^1.3.0"@@ -6636,6 +6910,12 @@"node": ">=6"}},+ "node_modules/escape-html": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",+ "license": "MIT"+ },"node_modules/escape-string-regexp": {"version": "4.0.0","resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz",@@ -6897,6 +7177,15 @@"url": "https://github.com/eta-dev/eta?sponsor=1"}},+ "node_modules/etag": {+ "version": "1.8.1",+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/eventemitter3": {"version": "5.0.4","resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",@@ -6914,6 +7203,27 @@"node": ">=0.8.x"}},+ "node_modules/eventsource": {+ "version": "3.0.7",+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",+ "license": "MIT",+ "dependencies": {+ "eventsource-parser": "^3.0.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/eventsource-parser": {+ "version": "3.1.1",+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },"node_modules/execa": {"version": "1.0.0","resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz",@@ -7030,6 +7340,84 @@"dev": true,"license": "Apache-2.0"},+ "node_modules/express": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",+ "license": "MIT",+ "dependencies": {+ "accepts": "^2.0.0",+ "body-parser": "^2.2.1",+ "content-disposition": "^1.0.0",+ "content-type": "^1.0.5",+ "cookie": "^0.7.1",+ "cookie-signature": "^1.2.1",+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "finalhandler": "^2.1.0",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.0",+ "merge-descriptors": "^2.0.0",+ "mime-types": "^3.0.0",+ "on-finished": "^2.4.1",+ "once": "^1.4.0",+ "parseurl": "^1.3.3",+ "proxy-addr": "^2.0.7",+ "qs": "^6.14.0",+ "range-parser": "^1.2.1",+ "router": "^2.2.0",+ "send": "^1.1.0",+ "serve-static": "^2.2.0",+ "statuses": "^2.0.1",+ "type-is": "^2.0.1",+ "vary": "^1.1.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/express-rate-limit": {+ "version": "8.7.0",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.0.tgz",+ "integrity": "sha512-hOwV7WOxXfjRpAM1DSJWZDXx3GhplwD8IfwuwvogD8i1Qnkgosw/H45s4ZnFAUHDAhPjlY9hLBvJhKmGMyY26g==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/express/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/external-editor": {"version": "3.1.0","resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz",@@ -7086,7 +7474,6 @@"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz","integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",- "dev": true,"license": "MIT"},"node_modules/fast-glob": {@@ -7137,7 +7524,6 @@"version": "3.1.3","resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.3.tgz","integrity": "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg==",- "dev": true,"funding": [{"type": "github",@@ -7224,9 +7610,30 @@"node": ">=8"}},- "node_modules/find-up": {- "version": "5.0.0",- "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz",+ "node_modules/finalhandler": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "on-finished": "^2.4.1",+ "parseurl": "^1.3.3",+ "statuses": "^2.0.1"+ },+ "engines": {+ "node": ">= 18.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/find-up": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz","integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==","dev": true,"license": "MIT",@@ -7297,6 +7704,24 @@"imul": "^1.0.0"}},+ "node_modules/forwarded": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/fresh": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/fs-extra": {"version": "10.1.0","resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",@@ -7377,7 +7802,6 @@"version": "1.1.2","resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz","integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",- "dev": true,"license": "MIT","funding": {"url": "https://github.com/sponsors/ljharb"@@ -7443,7 +7867,6 @@"version": "1.3.0","resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz","integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",- "dev": true,"license": "MIT","dependencies": {"call-bind-apply-helpers": "^1.0.2",@@ -7501,7 +7924,6 @@"version": "1.0.1","resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz","integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",- "dev": true,"license": "MIT","dependencies": {"dunder-proto": "^1.0.1",@@ -7638,7 +8060,6 @@"version": "1.2.0","resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz","integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -7707,7 +8128,6 @@"version": "1.1.0","resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz","integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -7720,7 +8140,6 @@"version": "2.0.4","resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz","integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",- "dev": true,"license": "MIT","dependencies": {"function-bind": "^1.1.2"@@ -7729,6 +8148,15 @@"node": ">= 0.4"}},+ "node_modules/hono": {+ "version": "4.13.5",+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.5.tgz",+ "integrity": "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw==",+ "license": "MIT",+ "engines": {+ "node": ">=16.9.0"+ }+ },"node_modules/hosted-git-info": {"version": "2.8.9","resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz",@@ -7762,6 +8190,26 @@"dev": true,"license": "BSD-2-Clause"},+ "node_modules/http-errors": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",+ "license": "MIT",+ "dependencies": {+ "depd": "~2.0.0",+ "inherits": "~2.0.4",+ "setprototypeof": "~1.2.0",+ "statuses": "~2.0.2",+ "toidentifier": "~1.0.1"+ },+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/http-proxy-agent": {"version": "5.0.0","resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-5.0.0.tgz",@@ -7959,7 +8407,6 @@"version": "2.0.4","resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz","integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",- "dev": true,"license": "ISC"},"node_modules/ini": {@@ -7993,12 +8440,20 @@"version": "10.2.0","resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz","integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",- "dev": true,"license": "MIT","engines": {"node": ">= 12"}},+ "node_modules/ipaddr.js": {+ "version": "1.9.1",+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/is-arrayish": {"version": "0.2.1","resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",@@ -8137,6 +8592,12 @@"node": ">=0.12.0"}},+ "node_modules/is-promise": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",+ "license": "MIT"+ },"node_modules/is-property": {"version": "1.0.2","resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",@@ -8224,7 +8685,6 @@"version": "2.0.0","resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz","integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",- "dev": true,"license": "ISC"},"node_modules/jest-worker": {@@ -8268,6 +8728,15 @@"jiti": "lib/jiti-cli.mjs"}},+ "node_modules/jose": {+ "version": "6.2.10",+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.10.tgz",+ "integrity": "sha512-iiW7J9qRFlGxvCOIBDBDxFePQSn7ZMAnrYGhrrOo6siO/MIqwfyilLR27pkfDgUk+raLuzADS8A3S/KLBisc0g==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/panva"+ }+ },"node_modules/js-tokens": {"version": "4.0.0","resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",@@ -8323,6 +8792,12 @@"dev": true,"license": "MIT"},+ "node_modules/json-schema-typed": {+ "version": "8.0.2",+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",+ "license": "BSD-2-Clause"+ },"node_modules/json-stable-stringify": {"version": "1.3.0","resolved": "https://registry.npmjs.org/json-stable-stringify/-/json-stable-stringify-1.3.0.tgz",@@ -9121,7 +9596,6 @@"version": "1.1.0","resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz","integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.4"@@ -9134,6 +9608,19 @@"dev": true,"license": "CC0-1.0"},+ "node_modules/media-typer": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz",+ "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/mediabunny": {"version": "1.50.6","resolved": "https://registry.npmjs.org/mediabunny/-/mediabunny-1.50.6.tgz",@@ -9183,6 +9670,18 @@"url": "https://github.com/sponsors/mesqueeb"}},+ "node_modules/merge-descriptors": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/merge-stream": {"version": "2.0.0","resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",@@ -9218,7 +9717,6 @@"version": "1.54.0","resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz","integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",- "dev": true,"license": "MIT","engines": {"node": ">= 0.6"@@ -9689,6 +10187,27 @@"url": "https://github.com/fb55/nth-check?sponsor=1"}},+ "node_modules/object-assign": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",+ "license": "MIT",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/object-inspect": {+ "version": "1.13.4",+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/object-keys": {"version": "1.1.1","resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",@@ -9713,11 +10232,22 @@"node": ">=12.20.0"}},+ "node_modules/on-finished": {+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",+ "license": "MIT",+ "dependencies": {+ "ee-first": "1.1.1"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/once": {"version": "1.4.0","resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz","integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",- "dev": true,"license": "ISC","dependencies": {"wrappy": "1"@@ -10009,6 +10539,15 @@"url": "https://github.com/inikulin/parse5?sponsor=1"}},+ "node_modules/parseurl": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/patch-package": {"version": "8.0.1","resolved": "https://registry.npmjs.org/patch-package/-/patch-package-8.0.1.tgz",@@ -10079,7 +10618,6 @@"version": "3.1.1","resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz","integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",- "dev": true,"license": "MIT","engines": {"node": ">=8"@@ -10092,6 +10630,16 @@"dev": true,"license": "MIT"},+ "node_modules/path-to-regexp": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/path-type": {"version": "2.0.0","resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz",@@ -10163,6 +10711,15 @@"node": ">=0.10.0"}},+ "node_modules/pkce-challenge": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",+ "license": "MIT",+ "engines": {+ "node": ">=16.20.0"+ }+ },"node_modules/plist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",@@ -10300,6 +10857,19 @@"node": ">=10"}},+ "node_modules/proxy-addr": {+ "version": "2.0.7",+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",+ "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==",+ "license": "MIT",+ "dependencies": {+ "forwarded": "0.2.0",+ "ipaddr.js": "1.9.1"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },"node_modules/pump": {"version": "3.0.4","resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",@@ -10321,6 +10891,22 @@"node": ">=6"}},+ "node_modules/qs": {+ "version": "6.16.0",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",+ "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",+ "license": "BSD-3-Clause",+ "dependencies": {+ "es-define-property": "^1.0.1",+ "side-channel": "^1.1.1"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/queue-microtask": {"version": "1.2.3","resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",@@ -10367,6 +10953,50 @@"murmur-32": "^0.1.0 || ^0.2.0"}},+ "node_modules/range-parser": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",+ "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.6"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/raw-body": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",+ "license": "MIT",+ "dependencies": {+ "bytes": "~3.1.2",+ "http-errors": "~2.0.1",+ "iconv-lite": "~0.7.0",+ "unpipe": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.10"+ }+ },+ "node_modules/raw-body/node_modules/iconv-lite": {+ "version": "0.7.3",+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",+ "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",+ "license": "MIT",+ "dependencies": {+ "safer-buffer": ">= 2.1.2 < 3.0.0"+ },+ "engines": {+ "node": ">=0.10.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/read-binary-file-arch": {"version": "1.0.6","resolved": "https://registry.npmjs.org/read-binary-file-arch/-/read-binary-file-arch-1.0.6.tgz",@@ -10525,7 +11155,6 @@"version": "2.0.2","resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz","integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",- "dev": true,"license": "MIT","engines": {"node": ">=0.10.0"@@ -10734,6 +11363,22 @@"fsevents": "~2.3.2"}},+ "node_modules/router": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.0",+ "depd": "^2.0.0",+ "is-promise": "^4.0.0",+ "parseurl": "^1.3.3",+ "path-to-regexp": "^8.0.0"+ },+ "engines": {+ "node": ">= 18"+ }+ },"node_modules/run-parallel": {"version": "1.2.0","resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",@@ -10783,7 +11428,6 @@"version": "2.1.2","resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz","integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",- "dev": true,"license": "MIT"},"node_modules/sax": {@@ -10874,6 +11518,48 @@"license": "MIT","optional": true},+ "node_modules/send": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "etag": "^1.8.1",+ "fresh": "^2.0.0",+ "http-errors": "^2.0.1",+ "mime-types": "^3.0.2",+ "ms": "^2.1.3",+ "on-finished": "^2.4.1",+ "range-parser": "^1.2.1",+ "statuses": "^2.0.2"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/send/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/serialize-error": {"version": "7.0.1","resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz",@@ -10926,6 +11612,25 @@"seroval": "^1.0"}},+ "node_modules/serve-static": {+ "version": "2.2.1",+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",+ "license": "MIT",+ "dependencies": {+ "encodeurl": "^2.0.0",+ "escape-html": "^1.0.3",+ "parseurl": "^1.3.3",+ "send": "^1.2.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/set-function-length": {"version": "1.2.2","resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",@@ -10944,11 +11649,16 @@"node": ">= 0.4"}},+ "node_modules/setprototypeof": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",+ "license": "ISC"+ },"node_modules/shebang-command": {"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz","integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",- "dev": true,"license": "MIT","dependencies": {"shebang-regex": "^3.0.0"@@ -10961,12 +11671,83 @@"version": "3.0.0","resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz","integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",- "dev": true,"license": "MIT","engines": {"node": ">=8"}},+ "node_modules/side-channel": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4",+ "side-channel-list": "^1.0.1",+ "side-channel-map": "^1.0.1",+ "side-channel-weakmap": "^1.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-list": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",+ "license": "MIT",+ "dependencies": {+ "es-errors": "^1.3.0",+ "object-inspect": "^1.13.4"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-map": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/side-channel-weakmap": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",+ "license": "MIT",+ "dependencies": {+ "call-bound": "^1.0.2",+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.5",+ "object-inspect": "^1.13.3",+ "side-channel-map": "^1.0.1"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/siginfo": {"version": "2.0.0","resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",@@ -11231,6 +12012,15 @@"integrity": "sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw==","license": "MIT"},+ "node_modules/statuses": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/std-env": {"version": "4.2.0","resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",@@ -11688,6 +12478,15 @@"node": ">=8.0"}},+ "node_modules/toidentifier": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",+ "license": "MIT",+ "engines": {+ "node": ">=0.6"+ }+ },"node_modules/tr46": {"version": "0.0.3","resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",@@ -11789,6 +12588,53 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/type-is": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",+ "license": "MIT",+ "dependencies": {+ "content-type": "^2.0.0",+ "media-typer": "^1.1.0",+ "mime-types": "^3.0.0"+ },+ "engines": {+ "node": ">= 18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/type-is/node_modules/content-type": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },+ "node_modules/type-is/node_modules/mime-types": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",+ "license": "MIT",+ "dependencies": {+ "mime-db": "^1.54.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/express"+ }+ },"node_modules/typed-binary": {"version": "4.3.3","resolved": "https://registry.npmjs.org/typed-binary/-/typed-binary-4.3.3.tgz",@@ -11897,6 +12743,15 @@"node": ">= 0.4.0"}},+ "node_modules/unpipe": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/unplugin": {"version": "3.3.0","resolved": "https://registry.npmjs.org/unplugin/-/unplugin-3.3.0.tgz",@@ -12083,6 +12938,15 @@"spdx-expression-parse": "^3.0.0"}},+ "node_modules/vary": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",+ "license": "MIT",+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/vite": {"version": "7.3.6","resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz",@@ -12497,7 +13361,6 @@"version": "2.0.2","resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz","integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",- "dev": true,"license": "ISC","dependencies": {"isexe": "^2.0.0"@@ -12587,30 +13450,8 @@"version": "1.0.2","resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz","integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",- "dev": true,"license": "ISC"},- "node_modules/ws": {- "version": "8.21.0",- "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",- "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",- "license": "MIT",- "engines": {- "node": ">=10.0.0"- },- "peerDependencies": {- "bufferutil": "^4.0.1",- "utf-8-validate": ">=5.0.2"- },- "peerDependenciesMeta": {- "bufferutil": {- "optional": true- },- "utf-8-validate": {- "optional": true- }- }- },"node_modules/xmlbuilder": {"version": "15.1.1","resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",@@ -12771,6 +13612,15 @@"url": "https://github.com/sponsors/colinhacks"}},+ "node_modules/zod-to-json-schema": {+ "version": "3.25.2",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25.28 || ^4"+ }+ },"packages/assets": {"name": "@diffusionstudio/assets","version": "0.1.0",@@ -12789,6 +13639,7 @@"license": "MPL-2.0","dependencies": {"@diffusionstudio/jsx": "*",+ "@modelcontextprotocol/sdk": "^1.30.0","zod": "^4.4.3"},"devDependencies": {diff --git a/packages/dapi/package.json b/packages/dapi/package.jsonindex 6a10c94e..b25e0166 100644--- a/packages/dapi/package.json+++ b/packages/dapi/package.json@@ -20,6 +20,7 @@],"dependencies": {"@diffusionstudio/jsx": "*",+ "@modelcontextprotocol/sdk": "^1.30.0","zod": "^4.4.3"},"devDependencies": {diff --git a/packages/dapi/src/catalog.test.ts b/packages/dapi/src/catalog.test.tsindex c0641573..844c286e 100644--- a/packages/dapi/src/catalog.test.ts+++ b/packages/dapi/src/catalog.test.ts@@ -26,10 +26,11 @@ describe("catalog", () => {}});- it("converts every schema to JSON Schema without throwing (bytes have no JSON form and pass as any)", () => {+ it("converts every input and output to JSON Schema, as MCP tools/list does", () => {for (const tool of catalog) {expect(() => z.toJSONSchema(tool.input, { io: "input" }), `${tool.name} input`).not.toThrow();- expect(() => z.toJSONSchema(tool.output, { unrepresentable: "any" }), `${tool.name} output`).not.toThrow();+ expect(() => z.toJSONSchema(tool.output), `${tool.name} output`).not.toThrow();+ expect(tool.output, `${tool.name} output must be an object for structured content`).toBeInstanceOf(z.ZodObject);}});diff --git a/packages/dapi/src/catalog.ts b/packages/dapi/src/catalog.tsindex 0db7d724..39c70d60 100644--- a/packages/dapi/src/catalog.ts+++ b/packages/dapi/src/catalog.ts@@ -3,7 +3,7 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import type { z } from "zod";-import type { Tool } from "./tool";+import type { GenericTool } from "./tool";import { open } from "./tools/open";import { context } from "./tools/context";@@ -60,7 +60,14 @@ export type ToolByName<N extends ToolName> = Extract<AnyTool, { name: N }>;export type ToolInput<N extends ToolName> = z.input<ToolByName<N>["input"]>;/** What a handler receives: parsed, defaults applied. */export type ToolArgs<N extends ToolName> = z.output<ToolByName<N>["input"]>;-export type ToolResult<N extends ToolName> = z.output<ToolByName<N>["output"]>;+/** What a caller receives: the tool's structured content. */+export type ToolOutput<N extends ToolName> = z.output<ToolByName<N>["output"]>;+/** What a handler returns; the output, unless the tool declares a `result`. */+export type ToolResult<N extends ToolName> = ToolByName<N> extends { result?: infer R }+ ? R extends z.ZodType+ ? z.output<R>+ : ToolOutput<N>+ : ToolOutput<N>;const byName = new Map<string, AnyTool>(catalog.map((tool) => [tool.name, tool]));@@ -72,5 +79,5 @@ export function isToolName(name: string): name is ToolName {return byName.has(name);}-/** The catalog as the generic `Tool` shape, for code that iterates it. */-export const tools: readonly Tool[] = catalog;+/** The catalog with each tool's specifics erased, for code that iterates it. */+export const tools: readonly GenericTool[] = catalog;diff --git a/packages/dapi/src/index.ts b/packages/dapi/src/index.tsindex da23f6c8..d6647796 100644--- a/packages/dapi/src/index.ts+++ b/packages/dapi/src/index.ts@@ -8,10 +8,10 @@import type { z } from "zod";export { defineTool } from "./tool";-export type { Tool, RunsIn } from "./tool";+export type { Tool, GenericTool, RunsIn } from "./tool";export { catalog, tools, toolByName, isToolName } from "./catalog";-export type { AnyTool, ToolName, ToolByName, ToolInput, ToolArgs, ToolResult } from "./catalog";+export type { AnyTool, ToolName, ToolByName, ToolInput, ToolArgs, ToolOutput, ToolResult } from "./catalog";export { Time, NonNegativeTime, TIME_FORMS } from "./time";export type { TimeInput } from "./time";@@ -20,13 +20,15 @@ export { DapiError, isDapiError } from "./errors";export type { DapiErrorCode } from "./errors";export { MAX_FRAMES_PER_SHEET, Bytes } from "./schemas";-export { parseToolArgs } from "./validate";++export { DAPI_WIRE } from "./ipc";+export type { DapiCall, DapiCancel, DapiReply } from "./ipc";export { FRAME_CAP } from "./tools/media-grab";export { ISSUE_LOG_TAIL } from "./tools/report";// Named request and result types, for handlers that spell out their// signature. Each is the parsed (output) side of the tool's schema.-import type { LogEntry as LogEntrySchema, LogLevel as LogLevelSchema, TimecodedImage as TimecodedImageSchema } from "./schemas";+import type { ImageRef as ImageRefSchema, LogEntry as LogEntrySchema, LogLevel as LogLevelSchema, TimecodedImage as TimecodedImageSchema } from "./schemas";import type { GenerationRow as GenerationRowType } from "./tools/context";import type { CheckIssue as CheckIssueSchema, CheckIssueCode as CheckIssueCodeSchema } from "./tools/check";import type { ExportFormat as ExportFormatSchema, ExportSettings as ExportSettingsSchema } from "./tools/export";@@ -35,11 +37,12 @@ import type { VoiceInfo as VoiceInfoSchema } from "./tools/voices";import type { FrameQuality as FrameQualitySchema } from "./tools/media-grab";import type { TranscriptSegment as TranscriptSegmentSchema, TranscriptWord as TranscriptWordSchema } from "./tools/media-transcribe";import type { FontFamily as FontFamilySchema } from "./tools/fonts";-import type { ToolArgs, ToolResult } from "./catalog";+import type { ToolArgs, ToolOutput, ToolResult } from "./catalog";export type LogLevel = z.output<typeof LogLevelSchema>;export type LogEntry = z.output<typeof LogEntrySchema>;export type TimecodedImage = z.output<typeof TimecodedImageSchema>;+export type ImageRef = z.output<typeof ImageRefSchema>;export type GenerationRow = GenerationRowType;export type CheckIssueCode = z.output<typeof CheckIssueCodeSchema>;export type CheckIssue = z.output<typeof CheckIssueSchema>;@@ -54,7 +57,7 @@ export type FontFamily = z.output<typeof FontFamilySchema>;export type OpenRequest = ToolArgs<"open">;export type OpenResult = ToolResult<"open">;-export type ContextResult = ToolResult<"context">;+export type ContextResult = ToolOutput<"context">;export type CaptureRequest = ToolArgs<"capture">;export type CaptureResult = ToolResult<"capture">;export type CheckRequest = ToolArgs<"check">;@@ -64,6 +67,7 @@ export type ExportResult = ToolResult<"export">;export type ModelsRequest = ToolArgs<"models">;export type LogsRequest = ToolArgs<"logs">;export type ScreenshotResult = ToolResult<"screenshot">;+export type ScreenshotOutput = ToolOutput<"screenshot">;export type MediaProbeRequest = ToolArgs<"media_probe">;export type MediaFrameRequest = ToolArgs<"media_grab">;export type MediaFrameResult = ToolResult<"media_grab">;diff --git a/packages/dapi/src/ipc.ts b/packages/dapi/src/ipc.tsnew file mode 100644index 00000000..db0eae92--- /dev/null+++ b/packages/dapi/src/ipc.ts@@ -0,0 +1,27 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++// The channel between the app's main process, which hosts the MCP server,+// and the renderer, which answers renderer tools. One call, one reply, and+// a cancel when the caller gives up. Arguments arrive validated: main parsed+// them against the catalog before forwarding.++import type { DapiErrorCode } from "./errors";++export const DAPI_WIRE = {+ /** main → renderer */+ CALL: "dapi:call",+ /** main → renderer */+ CANCEL: "dapi:cancel",+ /** renderer → main */+ REPLY: "dapi:reply",+} as const;++export type DapiCall = { id: string; tool: string; args: unknown };++export type DapiCancel = { id: string };++export type DapiReply =+ | { id: string; ok: true; data: unknown }+ | { id: string; ok: false; error: { code?: DapiErrorCode; message: string } };diff --git a/packages/dapi/src/schemas.ts b/packages/dapi/src/schemas.tsindex 7557a8c7..71f8a24a 100644--- a/packages/dapi/src/schemas.ts+++ b/packages/dapi/src/schemas.ts@@ -35,14 +35,25 @@ export const MAX_FRAMES_PER_SHEET = 12;export const Bytes = z.custom<Uint8Array>((value) => value instanceof Uint8Array, "expected bytes (a Uint8Array)");/**- * One image: a single frame stamped with its timecode, or a contact sheet- * stamped with the span it covers (`0f-08s10f`).+ * One rendered image as a handler returns it: a single frame stamped with its+ * timecode, or a contact sheet stamped with the span it covers (`0f-08s10f`).*/export const TimecodedImage = z.object({timecode: z.string(),png: Bytes,});+/** The same image once the server has written it to disk. */+export const ImageRef = z.object({+ timecode: z.string(),+ path: z.string().describe("absolute path of the PNG"),+});++export const outputDirField = z+ .string()+ .optional()+ .describe("absolute directory to write the PNGs into (default: a fresh directory under the system temp dir)");+/*** How frames are laid out: merged into contact sheets (the default) or one* image each. `perSheet` only means something for sheets; `checkSheetOptions`diff --git a/packages/dapi/src/socket.test.ts b/packages/dapi/src/socket.test.tsnew file mode 100644index 00000000..cdba741e--- /dev/null+++ b/packages/dapi/src/socket.test.ts@@ -0,0 +1,111 @@+/* This Source Code Form is subject to the terms of the Mozilla Public+ * License, v. 2.0. If a copy of the MPL was not distributed with this+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */++import { mkdtempSync, rmSync } from "node:fs";+import { connect, createServer } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";+import { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";+import { tools } from "./catalog";+import { SocketTransport } from "./socket";++import type { Server, Socket } from "node:net";++// A server over the real catalog with stub handlers, the way the app hosts+// it: one McpServer per accepted connection, MCP framed over the socket.+const dir = mkdtempSync(join(tmpdir(), "dapi-test-"));+const path = join(dir, "app.sock");+let server: Server;++beforeAll(async () => {+ server = createServer((socket) => {+ const session = new McpServer({ name: "test", version: "0.0.0" }, { capabilities: { logging: {} } });+ for (const tool of tools) {+ session.registerTool(+ tool.name,+ { description: tool.description, inputSchema: tool.input, outputSchema: tool.output },+ async (_args, extra) => {+ if (tool.name === "context") {+ // A notification right before the response, in the same write burst:+ // the transport must not let the response overtake its handling.+ await extra.sendNotification({ method: "notifications/message", params: { level: "info", data: "about to reply" } });+ const output = { rootDir: "/p", projectDir: null, currentTime: null, fontFamilies: [], generations: [] };+ return { content: [{ type: "text", text: JSON.stringify(output) }], structuredContent: output };+ }+ return { isError: true, content: [{ type: "text", text: `stub has no ${tool.name}` }] };+ },+ );+ }+ void session.connect(new SocketTransport(socket));+ });+ await new Promise<void>((resolve) => server.listen(path, resolve));+});++afterAll(async () => {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ rmSync(dir, { recursive: true, force: true });+});++async function open(): Promise<{ client: Client; socket: Socket }> {+ const socket = await new Promise<Socket>((resolve, reject) => {+ const s = connect(path);+ s.once("connect", () => resolve(s));+ s.once("error", reject);+ });+ const client = new Client({ name: "test-client", version: "0.0.0" });+ await client.connect(new SocketTransport(socket));+ return { client, socket };+}++describe("MCP over the socket", () => {+ it("lists the whole catalog with JSON Schema inputs", async () => {+ const { client } = await open();+ try {+ const { tools: listed } = await client.listTools();+ expect(listed.map((t) => t.name).sort()).toEqual(tools.map((t) => t.name).sort());+ const grab = listed.find((t) => t.name === "media_grab")!;+ expect(grab.inputSchema.type).toBe("object");+ expect(Object.keys(grab.inputSchema.properties ?? {})).toContain("times");+ expect(grab.outputSchema?.type).toBe("object");+ } finally {+ await client.close();+ }+ });++ it("returns structured content and rejects bad arguments with the field named", async () => {+ const { client } = await open();+ try {+ const messages: string[] = [];+ client.setNotificationHandler(LoggingMessageNotificationSchema, (n) => {+ messages.push(String(n.params.data));+ });+ const result = await client.callTool({ name: "context", arguments: {} });+ expect(result.structuredContent).toEqual({ rootDir: "/p", projectDir: null, currentTime: null, fontFamilies: [], generations: [] });+ expect(messages).toEqual(["about to reply"]);++ // Bad arguments come back as a result the agent can read, not a protocol error.+ const bad = await client.callTool({ name: "media_grab", arguments: { path: "/c.mp4", count: 0 } });+ expect(bad.isError).toBe(true);+ expect(JSON.stringify(bad.content)).toMatch(/count/);+ } finally {+ await client.close();+ }+ });++ it("serves several sessions at once", async () => {+ const a = await open();+ const b = await open();+ try {+ const [ra, rb] = await Promise.all([a.client.ping(), b.client.ping()]);+ expect(ra).toBeDefined();+ expect(rb).toBeDefined();+ } finally {+ await a.client.close();+ await b.client.close();+ }+ });+});diff --git a/packages/dapi/src/socket.ts b/packages/dapi/src/socket.tsindex d38ad1c9..a46fb457 100644--- a/packages/dapi/src/socket.ts+++ b/packages/dapi/src/socket.ts@@ -2,15 +2,94 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */+// The Node side of the protocol: where the app's socket lives and how MCP+// travels over it. Its own entry point (`@diffusionstudio/dapi/socket`) so+// the renderer can import the catalog without node:os or the MCP SDK.+import { platform, tmpdir } from "node:os";import { join } from "node:path";+import { ReadBuffer, serializeMessage } from "@modelcontextprotocol/sdk/shared/stdio.js";++import type { Socket } from "node:net";+import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";+import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";// One socket / named pipe per host. On macOS tmpdir is per-user; on Linux /tmp// is global but the socket file's owner-only mode 0600 keeps it isolated.-//-// Its own entry point (`@diffusionstudio/dapi/socket`) so the renderer can-// import the catalog without pulling in node:os / node:path.export const SOCKET_PATH =platform() === "win32"? "\\\\.\\pipe\\diffusion-studio": join(tmpdir(), "diffusion-studio.sock");++/**+ * MCP over a local socket, framed exactly like MCP over stdio: one JSON-RPC+ * message per line. The same class serves the app (one per accepted+ * connection) and the CLI (one per command); a stdio proxy needs neither,+ * since the bytes on the socket are already what a stdio client expects.+ */+export class SocketTransport implements Transport {+ onclose?: () => void;+ onerror?: (error: Error) => void;+ onmessage?: (message: JSONRPCMessage) => void;++ private readonly socket: Socket;+ private readonly buffer = new ReadBuffer();+ private started = false;+ private draining = false;++ constructor(socket: Socket) {+ this.socket = socket;+ }++ async start(): Promise<void> {+ if (this.started) throw new Error("SocketTransport already started");+ this.started = true;+ this.socket.on("data", (chunk: Buffer) => {+ this.buffer.append(chunk);+ void this.drain();+ });+ this.socket.on("error", (error) => this.onerror?.(error));+ this.socket.on("close", () => this.onclose?.());+ }++ send(message: JSONRPCMessage): Promise<void> {+ return new Promise((resolve, reject) => {+ if (this.socket.destroyed) {+ reject(new Error("Socket is closed"));+ return;+ }+ this.socket.write(serializeMessage(message), (error) => (error ? reject(error) : resolve()));+ });+ }++ async close(): Promise<void> {+ this.socket.end();+ this.socket.destroy();+ }++ // Messages are handed over one per turn of the event loop. The SDK runs+ // notification handlers on a microtask, so a notification and the response+ // that follows it in the same chunk must not be dispatched back to back:+ // the response would settle the request before the notification's handler+ // ran. A drain in progress picks up chunks appended meanwhile.+ private async drain(): Promise<void> {+ if (this.draining) return;+ this.draining = true;+ try {+ for (;;) {+ let message: JSONRPCMessage | null;+ try {+ message = this.buffer.readMessage();+ } catch (error) {+ this.onerror?.(error as Error);+ return;+ }+ if (!message) return;+ this.onmessage?.(message);+ await new Promise<void>((resolve) => setImmediate(resolve));+ }+ } finally {+ this.draining = false;+ }+ }+}diff --git a/packages/dapi/src/tool.ts b/packages/dapi/src/tool.tsindex 7c4f1818..6e2febdf 100644--- a/packages/dapi/src/tool.ts+++ b/packages/dapi/src/tool.ts@@ -14,7 +14,8 @@ export type RunsIn = "renderer" | "main";export interface Tool<Name extends string = string,Input extends z.ZodObject = z.ZodObject,- Output extends z.ZodType = z.ZodType,+ Output extends z.ZodObject = z.ZodObject,+ Result extends z.ZodType = Output,> {/** MCP tool name: `[a-z0-9_]`, unique across the catalog. */readonly name: Name;@@ -24,13 +25,26 @@ export interface Tool<readonly description: string;/** Always an object: MCP tool arguments are a JSON object by definition. */readonly input: Input;+ /** What the caller receives: a JSON object, the tool's structured content. */readonly output: Output;+ /**+ * What the handler returns, when that is not the output: image tools hand+ * back bytes, and the server presents them as files and inline images. Same+ * as `output` when omitted.+ */+ readonly result?: Result;readonly runsIn: RunsIn;}+/** A tool with its specifics erased, for code that iterates the catalog. */+export type GenericTool = Tool<string, z.ZodObject, z.ZodObject, z.ZodType>;+/** Identity with inference: keeps the literal name and the exact schema types. */-export function defineTool<const Name extends string, Input extends z.ZodObject, Output extends z.ZodType>(- tool: Tool<Name, Input, Output>,-): Tool<Name, Input, Output> {+export function defineTool<+ const Name extends string,+ Input extends z.ZodObject,+ Output extends z.ZodObject,+ Result extends z.ZodType = Output,+>(tool: Tool<Name, Input, Output, Result>): Tool<Name, Input, Output, Result> {return tool;}diff --git a/packages/dapi/src/tools/capture.ts b/packages/dapi/src/tools/capture.tsindex 56328380..8ceca5c3 100644--- a/packages/dapi/src/tools/capture.ts+++ b/packages/dapi/src/tools/capture.ts@@ -4,7 +4,7 @@import { z } from "zod";import { defineTool } from "../tool";-import { checkSheetOptions, SceneId, sheetFields, TimecodedImage } from "../schemas";+import { checkSheetOptions, ImageRef, outputDirField, SceneId, sheetFields, TimecodedImage } from "../schemas";export const capture = defineTool({name: "capture",@@ -19,8 +19,10 @@ export const capture = defineTool({.optional().describe("positions to capture as frame numbers relative to the export's first frame, the workarea's start (default: [0])"),...sheetFields,+ output: outputDirField,}).superRefine(checkSheetOptions),- output: z.array(TimecodedImage),+ output: z.object({ images: z.array(ImageRef) }),+ result: z.array(TimecodedImage),runsIn: "renderer",});diff --git a/packages/dapi/src/tools/context.ts b/packages/dapi/src/tools/context.tsindex 9c30c007..7bb408fc 100644--- a/packages/dapi/src/tools/context.ts+++ b/packages/dapi/src/tools/context.ts@@ -30,24 +30,18 @@ export const context = defineTool({description:"Report the current app context: the application root folder (always reported), the folder of the project the app has open (null when none is), where its playhead sits in seconds, the registered font families, and where its `generate.*` declarations stand. Poll it to wait for generations without blocking.",input: z.object({}),- output: z.union([- z.object({- rootDir: z.string().nullable().describe("folder projects live under; null until one has been chosen"),- projectDir: z.null(),- }),- z.object({- rootDir: z.string().nullable().describe("folder projects live under; null until one has been chosen"),- projectDir: z.string().describe("absolute path of the open project"),- currentTime: z- .number()- .nullable()- .describe("playhead in seconds, the unit the source places clips in; null when no scene is active"),- fontFamilies: z- .array(z.string())- .describe("families registered in the world drawing the project; the editor default is always among them"),- generations: z.array(GenerationRow),- }),- ]),+ output: z.object({+ rootDir: z.string().nullable().describe("folder projects live under; null until one has been chosen"),+ projectDir: z.string().nullable().describe("absolute path of the open project; null when none is open"),+ currentTime: z+ .number()+ .nullable()+ .describe("playhead in seconds, the unit the source places clips in; null when no scene is active or no project is open"),+ fontFamilies: z+ .array(z.string())+ .describe("families registered in the world drawing the project; the editor default is always among them"),+ generations: z.array(GenerationRow),+ }),runsIn: "renderer",});diff --git a/packages/dapi/src/tools/fonts.ts b/packages/dapi/src/tools/fonts.tsindex 4936dbfe..e6bdd994 100644--- a/packages/dapi/src/tools/fonts.ts+++ b/packages/dapi/src/tools/fonts.ts@@ -29,6 +29,6 @@ export const fonts = defineTool({style: FontStyle.optional().describe("filter to variants with the given style"),limit: z.int().min(1).optional().describe("return at most this many families"),}),- output: z.array(FontFamily),+ output: z.object({ families: z.array(FontFamily) }),runsIn: "main",});diff --git a/packages/dapi/src/tools/logs.ts b/packages/dapi/src/tools/logs.tsindex d959265b..6e63ed8a 100644--- a/packages/dapi/src/tools/logs.ts+++ b/packages/dapi/src/tools/logs.ts@@ -15,6 +15,6 @@ export const logs = defineTool({tail: z.int().min(1).optional().describe("return only the last n entries"),level: LogLevel.optional().describe("minimum level to include"),}),- output: z.array(LogEntry),+ output: z.object({ entries: z.array(LogEntry) }),runsIn: "main",});diff --git a/packages/dapi/src/tools/media-filmstrip.ts b/packages/dapi/src/tools/media-filmstrip.tsindex dd9cdd1c..20321daf 100644--- a/packages/dapi/src/tools/media-filmstrip.ts+++ b/packages/dapi/src/tools/media-filmstrip.ts@@ -9,6 +9,7 @@ import { AssetPath, Bytes, checkWindow, windowFields } from "../schemas";/** The window and scale that filmstrip and waveform share. */export const previewFields = {...windowFields,+ output: z.string().optional().describe("absolute path to write the PNG to (default: a fresh file under the system temp dir)"),scale: z.number().positive()@@ -22,6 +23,7 @@ export const mediaFilmstrip = defineTool({description:"Render a grid of thumbnails sampled across the timeline to a PNG (local render, no credits), each row stamped with an HH:MM:SS:FF ruler. A fast, token-efficient video track preview; narrow the window to zoom into a region of interest. Video only (use media_waveform for audio).",input: z.object({ path: AssetPath, ...previewFields }).superRefine(checkWindow),- output: z.looseObject({ png: Bytes }),+ output: z.looseObject({ path: z.string().describe("absolute path of the PNG") }),+ result: z.looseObject({ png: Bytes }),runsIn: "renderer",});diff --git a/packages/dapi/src/tools/media-grab.ts b/packages/dapi/src/tools/media-grab.tsindex 16df6aa2..5dcbb544 100644--- a/packages/dapi/src/tools/media-grab.ts+++ b/packages/dapi/src/tools/media-grab.ts@@ -4,7 +4,7 @@import { z } from "zod";import { defineTool } from "../tool";-import { AssetPath, checkSheetOptions, checkWindow, sheetFields, TimecodedImage, windowFields } from "../schemas";+import { AssetPath, checkSheetOptions, checkWindow, ImageRef, outputDirField, sheetFields, TimecodedImage, windowFields } from "../schemas";import { Time } from "../time";export const FrameQuality = z.enum(["small", "medium", "large", "fullres"]);@@ -46,6 +46,7 @@ export const mediaGrab = defineTool({.boolean().optional().describe(`lift the ${FRAME_CAP}-frame safety cap (grabbing many frames is slow and token-heavy)`),+ output: outputDirField,}).superRefine((value, ctx) => {if (value.times !== undefined && value.count !== undefined) {@@ -69,6 +70,7 @@ export const mediaGrab = defineTool({}checkSheetOptions(value, ctx);}),- output: z.array(TimecodedImage),+ output: z.object({ images: z.array(ImageRef) }),+ result: z.array(TimecodedImage),runsIn: "renderer",});diff --git a/packages/dapi/src/tools/media-waveform.ts b/packages/dapi/src/tools/media-waveform.tsindex d0691d5d..dd9f98ff 100644--- a/packages/dapi/src/tools/media-waveform.ts+++ b/packages/dapi/src/tools/media-waveform.ts@@ -7,6 +7,8 @@ import { defineTool } from "../tool";import { AssetPath, Bytes, checkWindow } from "../schemas";import { previewFields } from "./media-filmstrip";+const Silences = z.array(z.object({ start: z.number(), end: z.number() })).describe("seconds");+export const mediaWaveform = defineTool({name: "media_waveform",title: "Waveform preview",@@ -14,8 +16,9 @@ export const mediaWaveform = defineTool({"Render the audio track of a video or audio file as a waveform PNG (local render, no credits) with a timestamp ruler: loudness over time, with silent stretches highlighted in red. A fast, token-efficient audio track preview; the silent spans are also returned as second ranges.",input: z.object({ path: AssetPath, ...previewFields }).superRefine(checkWindow),output: z.looseObject({- png: Bytes,- silences: z.array(z.object({ start: z.number(), end: z.number() })).describe("seconds"),+ path: z.string().describe("absolute path of the PNG"),+ silences: Silences,}),+ result: z.looseObject({ png: Bytes, silences: Silences }),runsIn: "renderer",});diff --git a/packages/dapi/src/tools/models.ts b/packages/dapi/src/tools/models.tsindex f4dade8e..ca2cc8ce 100644--- a/packages/dapi/src/tools/models.ts+++ b/packages/dapi/src/tools/models.ts@@ -24,6 +24,6 @@ export const models = defineTool({input: z.object({type: ModelType.optional().describe("filter to one kind of model (default: all three)"),}),- output: z.array(ModelInfo),+ output: z.object({ models: z.array(ModelInfo) }),runsIn: "renderer",});diff --git a/packages/dapi/src/tools/screenshot.ts b/packages/dapi/src/tools/screenshot.tsindex 9f54bd58..7cc1fa33 100644--- a/packages/dapi/src/tools/screenshot.ts+++ b/packages/dapi/src/tools/screenshot.ts@@ -4,18 +4,19 @@import { z } from "zod";import { defineTool } from "../tool";-import { Bytes } from "../schemas";+import { Bytes, outputDirField } from "../schemas";export const screenshot = defineTool({name: "screenshot",title: "Window screenshot",description:"Capture the entire application window as a PNG — the full UI as the user sees it (panels, timeline, asset library, canvas viewport), at the window's current size. The tool for checking what the app itself looks like; to render a node or scene cleanly for composition checks use capture instead.",- input: z.object({}),+ input: z.object({ output: outputDirField }),output: z.object({- png: Bytes,+ path: z.string().describe("absolute path of the PNG"),width: z.number(),height: z.number(),}),+ result: z.object({ png: Bytes, width: z.number(), height: z.number() }),runsIn: "renderer",});diff --git a/packages/dapi/src/tools/tools.test.ts b/packages/dapi/src/tools/tools.test.tsindex 31aa8cb7..0879c0a6 100644--- a/packages/dapi/src/tools/tools.test.ts+++ b/packages/dapi/src/tools/tools.test.ts@@ -94,8 +94,10 @@ describe("logs and export", () => {});describe("context", () => {- it("accepts both the closed and the open report", () => {- expect(context.output.safeParse({ rootDir: "/p", projectDir: null }).success).toBe(true);+ it("reports the same shape with and without an open project", () => {+ expect(+ context.output.safeParse({ rootDir: "/p", projectDir: null, currentTime: null, fontFamilies: [], generations: [] }).success,+ ).toBe(true);expect(context.output.safeParse({rootDir: "/p",@@ -108,3 +110,11 @@ describe("context", () => {expect(context.output.safeParse({ rootDir: "/p", projectDir: "/p/a" }).success).toBe(false);});});++describe("image tools", () => {+ it("present bytes as paths: the result carries png, the output a path", () => {+ expect(capture.result!.safeParse([{ timecode: "0f", png: new Uint8Array(3) }]).success).toBe(true);+ expect(capture.output.safeParse({ images: [{ timecode: "0f", path: "/tmp/0f.png" }] }).success).toBe(true);+ expect(capture.output.safeParse({ images: [{ timecode: "0f", png: new Uint8Array(3) }] }).success).toBe(false);+ });+});diff --git a/packages/dapi/src/tools/voices.ts b/packages/dapi/src/tools/voices.tsindex 233cc66a..76d0f328 100644--- a/packages/dapi/src/tools/voices.ts+++ b/packages/dapi/src/tools/voices.ts@@ -16,6 +16,6 @@ export const voices = defineTool({title: "Speech voices",description: "List the speech voices available for `generate.voice` declarations in a project module.",input: z.object({}),- output: z.array(VoiceInfo),+ output: z.object({ voices: z.array(VoiceInfo) }),runsIn: "renderer",});diff --git a/packages/dapi/src/tools/whoami.ts b/packages/dapi/src/tools/whoami.tsindex f2d5cf0b..0aa6393a 100644--- a/packages/dapi/src/tools/whoami.ts+++ b/packages/dapi/src/tools/whoami.ts@@ -10,6 +10,8 @@ export const whoami = defineTool({title: "Signed-in account",description: "Report the authenticated account, or null if signed out.",input: z.object({}),- output: z.object({ id: z.string(), email: z.string().optional() }).nullable(),+ output: z.object({+ user: z.object({ id: z.string(), email: z.string().optional() }).nullable(),+ }),runsIn: "renderer",});diff --git a/packages/dapi/src/validate.test.ts b/packages/dapi/src/validate.test.tsdeleted file mode 100644index 6a14b389..00000000--- a/packages/dapi/src/validate.test.ts+++ /dev/null@@ -1,28 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import { describe, expect, it } from "vitest";-import { isDapiError } from "./errors";-import { parseToolArgs } from "./validate";--describe("parseToolArgs", () => {- it("returns parsed arguments with defaults applied", () => {- expect(parseToolArgs("capture", { id: "intro" })).toEqual({ id: "intro", combine: true });- });-- it("throws an invalid-input DapiError that names every bad field on one line", () => {- try {- parseToolArgs("media_grab", { path: "/c.mp4", times: ["abc"], count: 0 });- } catch (e) {- expect(isDapiError(e) && e.code).toBe("invalid-input");- const message = (e as Error).message;- expect(message).toMatch(/^Invalid arguments for media_grab: /);- expect(message).toMatch(/times\.0: expected a time/);- expect(message).toMatch(/count: /);- expect(message).not.toContain("\n");- return;- }- throw new Error("expected a throw");- });-});diff --git a/packages/dapi/src/validate.ts b/packages/dapi/src/validate.tsdeleted file mode 100644index 89c5e776..00000000--- a/packages/dapi/src/validate.ts+++ /dev/null@@ -1,25 +0,0 @@-/* This Source Code Form is subject to the terms of the Mozilla Public- * License, v. 2.0. If a copy of the MPL was not distributed with this- * file, You can obtain one at http://mozilla.org/MPL/2.0/. */--import type { z } from "zod";-import { toolByName } from "./catalog";-import type { ToolArgs, ToolName } from "./catalog";-import { DapiError } from "./errors";--/**- * Validates a tool's raw arguments against its schema. Every issue is- * reported on one line, keyed by the field it points at, so an agent can- * correct the call from the message alone.- */-export function parseToolArgs<N extends ToolName>(name: N, raw: unknown): ToolArgs<N> {- const result = toolByName(name).input.safeParse(raw);- if (result.success) return result.data as ToolArgs<N>;- throw new DapiError("invalid-input", `Invalid arguments for ${name}: ${formatIssues(result.error.issues)}`, {- cause: result.error,- });-}--function formatIssues(issues: readonly z.core.$ZodIssue[]): string {- return issues.map((issue) => `${issue.path.map(String).join(".") || "input"}: ${issue.message}`).join("; ");-}