Skip to content

The VS Code of video editing, built for agents.

TypeScript

Add `dapi fetch` command for downloading videos with yt-dlp

konstantin-paulus41cbb54c2dfc
diff --git a/apps/cli/reference/README.md b/apps/cli/reference/README.md
index 7731b31b..e6d9e4b9 100644
--- a/apps/cli/reference/README.md
+++ b/apps/cli/reference/README.md
@@ -6,7 +6,7 @@ Each feature command has its own file (linked below). The JSX code syntax consum
## Groups
-**Top-level:** [`open`](./open.md), [`whoami`](./whoami.md), [`context`](./context.md) (alias `ctx`), [`mount`](./mount.md), [`models`](./models.md), [`voices`](./voices.md), [`fonts`](./fonts.md).
+**Top-level:** [`open`](./open.md), [`whoami`](./whoami.md), [`context`](./context.md) (alias `ctx`), [`mount`](./mount.md), [`models`](./models.md), [`voices`](./voices.md), [`fonts`](./fonts.md), [`fetch`](./fetch.md).
| Group | Alias | Scope |
| ----- | ----- | ----- |
@@ -93,6 +93,10 @@ How the surface is divided:
- [`dapi fonts`](./fonts.md): list local fonts
+### Download
+
+- [`dapi fetch`](./fetch.md): download a video with yt-dlp (installed separately)
+
## Shared types
```ts
@@ -111,4 +115,4 @@ Time inputs take the `Time` format unless noted otherwise. Times in **outputs**
- **Unix-style names are canonical:** list/read is `ls`, delete is `rm`, duplicate is `cp`, move/reparent is `mv`, search is `grep`. The longer English forms (`list`, `remove`, `duplicate`, `move`) are aliases of the Unix forms, not the other way around. `get` is a universal alias for `ls`. Commands without a natural Unix equivalent (`tree`, `rename`, `patch`, `add`, `create`, `active`, `context`, `whoami`, `open`, `focus`, `set`) keep their descriptive names.
- **Stderr:** human-readable error messages.
- **Exit codes:** `0` on success, `1` on any error (missing file, app not running, invalid input, IPC error).
-- **App must be running:** every command except `open` and `fonts` talks to the open Diffusion Studio instance. If the app isn't running, the CLI prints an instruction to launch it and exits `1`.
+- **App must be running:** every command except `open`, `fonts`, and `fetch` talks to the open Diffusion Studio instance. If the app isn't running, the CLI prints an instruction to launch it and exits `1`.
diff --git a/apps/cli/reference/fetch.md b/apps/cli/reference/fetch.md
new file mode 100644
index 00000000..f07e3523
--- /dev/null
+++ b/apps/cli/reference/fetch.md
@@ -0,0 +1,38 @@
+# `dapi fetch <url>`
+
+Downloads a video with [yt-dlp](https://github.com/yt-dlp/yt-dlp). Does not require the app to be running. yt-dlp is not bundled: install it separately (`brew install yt-dlp`, or `pipx install yt-dlp`). If it is not on `PATH`, the command exits `1` with an install hint; set `YT_DLP_PATH` to point at a specific binary.
+
+This writes the file to disk only. To pull a downloaded file into the open project, add it afterwards: `dapi asset add <path>` (see [asset add](./asset/add.md)).
+
+## Arguments
+
+- `<url>`: the video or page URL to download.
+
+## Options
+
+- `-o, --output <path>`: output file path or directory (yt-dlp `-o` template). Default: yt-dlp's own default template in the current directory.
+- `-f, --format <selector>`: yt-dlp format selector, e.g. `"bv*+ba/b"`.
+- `-a, --audio`: extract audio only (yt-dlp `-x`).
+
+## Passthrough
+
+Forward raw yt-dlp flags after `--`; they are appended verbatim:
+
+```sh
+dapi fetch https://youtu.be/xyz -f "bv*+ba/b" -- --sponsorblock-remove all --limit-rate 2M
+```
+
+## Output
+
+JSON Lines, one per file written (a single URL can yield several, e.g. a playlist):
+
+```ts
+{ path: string } // absolute path of the file on disk, after any extraction / rename
+```
+
+Download progress is rendered by yt-dlp on stderr while the command runs.
+
+## Notes
+
+- The resolved path comes from yt-dlp's `after_move:filepath`, so it reflects the real name after audio extraction or renaming, not a guess.
+- Exit code is `0` on success; on failure the command surfaces yt-dlp's exit code and prints its stderr.
diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts
index 90b94d46..91c6b4ed 100644
--- a/apps/cli/src/index.ts
+++ b/apps/cli/src/index.ts
@@ -15,6 +15,7 @@ import { cliAPI, waitForCliSocket } from "./cli-client";
import { compileProject } from "./compile-project";
import { listLocalFonts } from "./fonts";
import { openFolder } from "./open-folder";
+import { fetchVideo } from "./ytdlp";
import type { EncoderConfigInput } from "./protocol";
const APP_NAME = "Diffusion Studio";
@@ -953,6 +954,20 @@ function listFonts(opts: ListFontsOptions): void {
}
}
+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> {
+ try {
+ const paths = await fetchVideo(url, { ...opts, raw });
+ for (const path of paths) console.log(JSON.stringify({ path }));
+ } catch (e) {
+ console.error((e as Error).message);
+ process.exit(1);
+ }
+}
+
const program = new Command();
// Appends the command's reference page to its help description.
@@ -1275,6 +1290,17 @@ program
.option("-n, --names-only", "output only family names (one per line, no variant detail)")
.action((opts: ListFontsOptions) => listFonts(opts));
+program
+ .command("fetch")
+ .description(`Download a video with yt-dlp (must be installed separately)${docs("fetch")}`)
+ .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)")
+ .option("-f, --format <selector>", `yt-dlp format selector, e.g. "bv*+ba/b"`)
+ .option("-a, --audio", "extract audio only (yt-dlp -x)")
+ .allowExcessArguments()
+ .addHelpText("after", `\nForward raw yt-dlp flags after --, e.g. dapi fetch <url> -- --sponsorblock-remove all`)
+ .action((url: string, opts: FetchCliOptions, cmd: Command) => fetch(url, opts, cmd.args.slice(1)));
+
// Explicit argv convention: the packaged wrapper runs this bundle on
// Electron in ELECTRON_RUN_AS_NODE mode, where commander would otherwise
// detect Electron and drop the script path from argv.
diff --git a/apps/cli/src/ytdlp.ts b/apps/cli/src/ytdlp.ts
new file mode 100644
index 00000000..fe4da8bd
--- /dev/null
+++ b/apps/cli/src/ytdlp.ts
@@ -0,0 +1,67 @@
+/* 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);
+ 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}.`));
+ }
+ });
+ });
+}