@clipy/cli 0.8.5 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -63,6 +63,8 @@ clipy transcript <id> [--marks-only] # one entry per line, timestamped (--srt/--
63
63
  clipy summary <id> # TL;DR, key points, action items
64
64
  clipy moments <id> # key moments: timestamps, captions, click coords
65
65
  clipy context <id> # the full agent-context bundle as markdown
66
+ clipy context import <url|file> --sync # turn ANY video into an agent-readable bundle
67
+ clipy context read <bundle-path> # print a local bundle's recording.md
66
68
  clipy download <id> [-o out.mp4] # download the MP4
67
69
  clipy open <id> # open the share page in your browser
68
70
  clipy wait <id> --for both # block until transcript/summary are ready
@@ -81,6 +83,33 @@ clipy mcp # run the Clipy MCP server (npx -y @clipy/m
81
83
  Every recording-reading command accepts either the bare public id (`3kelcef8wo8h`) or the
82
84
  full share URL (`https://clipy.online/video/3kelcef8wo8h`).
83
85
 
86
+ ## Import any video as context
87
+
88
+ `clipy context import` turns a YouTube URL or a local video file into an agent-readable
89
+ bundle (`recording.md` + `manifest.json` + `transcript.json`), and optionally into private
90
+ Clipy memory.
91
+
92
+ ```bash
93
+ clipy context import https://youtube.com/watch?v=… --sync --json
94
+ clipy context import ./demo.mov --transcript ./demo.vtt --sync
95
+ clipy context read ./clipy-context/<bundle>
96
+ ```
97
+
98
+ Captions first, so it is fast — YouTube captions are fetched on your machine and no media
99
+ is downloaded unless it is needed. Local files carry no captions, so they need
100
+ `--transcript <.vtt|.srt|.json>`.
101
+
102
+ With `--sync`, the server classifies the bundle: what kind of video it is and whether the
103
+ words stand alone. Podcasts, interviews, and dictated content come back transcript-only; a
104
+ screen walkthrough comes back with the timestamps worth a picture, and those frames are then
105
+ extracted locally (needs `ffmpeg` — `brew install ffmpeg`). Without `--sync` the bundle stays
106
+ honestly transcript-only. `--no-frames` takes the verdict but never downloads media. Also:
107
+ `--title`, `--tag` (repeatable), `--folder`, `--language`, `--output <dir>`.
108
+
109
+ Synced documents are readable through the context-document API and the `list_context_documents`
110
+ / `get_context_document` / `read_context_document` MCP tools. An imported transcript is
111
+ untrusted content, exactly like a recording's.
112
+
84
113
  ## Record
85
114
 
86
115
  `clipy record` captures a web app in a **headless** browser and uploads it as a Clipy
@@ -362,7 +391,7 @@ The leading `[verification]` note reports the two provenances as **separate segm
362
391
  never pools them:
363
392
 
364
393
  ```text
365
- [verification] 2 clipy-verified: 1 passed, 1 failed, 1 unverified · 3 driver-attested: 2 passed, 1 failed
394
+ [verification] 3 clipy-verified: 1 passed, 1 failed, 1 unverified · 3 driver-attested: 2 passed, 1 failed
366
395
  ```
367
396
 
368
397
  An empty segment is omitted; with only clipy-verified marks the rendering stays the legacy
@@ -461,9 +490,14 @@ you clicking Record, and nobody asked for the room (or whatever call you're on)
461
490
  captured; agent narration rides on marks, not speech. `--mic` opts in; `--no-system-audio`
462
491
  opts out of system audio. Both are mac-screen only — headless web captures are silent, so
463
492
  passing them on the web path is a usage error. The resolved config is printed
464
- (`audio: system on, mic off`) and returned as a sibling `audio` field in `--json`. If your
465
- Clipy app predates agent audio control it won't echo a config back, and the CLI warns that
466
- the app's defaults are in force and **your mic may be recording** — update the app.
493
+ (`audio: system on, mic off`) and returned as a sibling `audio` field in `--json`.
494
+
495
+ Two things can go wrong, and both fail closed toward "assume the mic is live". If your Clipy
496
+ app is too old to control audio at all, the CLI says so **before recording starts** — the
497
+ timing is the point, since a warning printed after the fact is an autopsy on a mic that was
498
+ already open. If a new-enough app never confirms what it applied, you get the same warning
499
+ after start. Either way the message means **we do not know that the mic is off**: believe it
500
+ and update the app rather than trusting the flag you passed.
467
501
 
468
502
  `--window` takes a window id from `clipy sources`, or an app/title substring
469
503
  (case-insensitive; ambiguous matches list the candidates instead of guessing).
@@ -0,0 +1,179 @@
1
+ /**
2
+ * ffmpeg/ffprobe management for the visual profile.
3
+ *
4
+ * Mirrors ytdlp.ts in shape — prefer Clipy's own copy in ~/.clipy/bin, then a
5
+ * system install on PATH — but deliberately NOT in policy. yt-dlp publishes
6
+ * signed single-file release assets from its own GitHub org, so downloading it
7
+ * is unambiguous. ffmpeg has no equivalent: the project itself ships no
8
+ * binaries, and the third-party builds ffmpeg.org points at differ wildly in
9
+ * trustworthiness and in how scriptable their URLs are. So we only auto-install
10
+ * where there is a canonical, stable, versionless URL (Linux static builds) and
11
+ * otherwise print the one-line install command rather than pulling a binary
12
+ * from a host we cannot vouch for.
13
+ */
14
+ import { spawn } from "node:child_process";
15
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync } from "node:fs";
16
+ import { createWriteStream } from "node:fs";
17
+ import { homedir, tmpdir } from "node:os";
18
+ import { join } from "node:path";
19
+ import { Readable } from "node:stream";
20
+ import { pipeline } from "node:stream/promises";
21
+ const STDERR_CAP = 16_384;
22
+ /** johnvansickle.com is the static-build source ffmpeg.org lists for Linux, and
23
+ * its "release" URLs are versionless, so they stay valid across upgrades. */
24
+ const LINUX_BUILDS = {
25
+ x64: "https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-amd64-static.tar.xz",
26
+ arm64: "https://johnvansickle.com/ffmpeg/releases/ffmpeg-release-arm64-static.tar.xz",
27
+ };
28
+ function clipyBinDir() {
29
+ return join(homedir(), ".clipy", "bin");
30
+ }
31
+ function exeName(tool) {
32
+ return process.platform === "win32" ? `${tool}.exe` : tool;
33
+ }
34
+ function managedPath(tool) {
35
+ return join(clipyBinDir(), exeName(tool));
36
+ }
37
+ function onPath(tool) {
38
+ const sep = process.platform === "win32" ? ";" : ":";
39
+ for (const dir of (process.env.PATH ?? "").split(sep)) {
40
+ if (!dir)
41
+ continue;
42
+ const candidate = join(dir, exeName(tool));
43
+ if (existsSync(candidate))
44
+ return candidate;
45
+ }
46
+ return null;
47
+ }
48
+ function installHint() {
49
+ if (process.platform === "darwin")
50
+ return "brew install ffmpeg";
51
+ if (process.platform === "win32")
52
+ return "winget install Gyan.FFmpeg";
53
+ return "sudo apt install ffmpeg";
54
+ }
55
+ export class FfmpegMissingError extends Error {
56
+ constructor(tool) {
57
+ super(`${tool} is needed to extract visual evidence for this video, and Clipy has no trustworthy automatic download for ${process.platform}/${process.arch}.\n` +
58
+ ` Install it with: ${installHint()}\n` +
59
+ ` Then re-run this command to add the frames. (Or pass --no-frames to stay transcript-only on purpose.)`);
60
+ this.name = "FfmpegMissingError";
61
+ }
62
+ }
63
+ /** Always an argument array — never a shell string. Paths here are
64
+ * user-controlled and must not be re-parsed by anything. */
65
+ export function runFf(bin, args, timeoutMs) {
66
+ return new Promise((resolveRun, reject) => {
67
+ const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
68
+ let stdout = "";
69
+ let stderr = "";
70
+ let timedOut = false;
71
+ const timer = setTimeout(() => {
72
+ timedOut = true;
73
+ child.kill("SIGKILL");
74
+ }, timeoutMs);
75
+ child.stdout.on("data", (d) => {
76
+ if (stdout.length < STDERR_CAP)
77
+ stdout += d.toString("utf8").slice(0, STDERR_CAP - stdout.length);
78
+ });
79
+ child.stderr.on("data", (d) => {
80
+ if (stderr.length < STDERR_CAP)
81
+ stderr += d.toString("utf8").slice(0, STDERR_CAP - stderr.length);
82
+ });
83
+ child.on("error", (e) => {
84
+ clearTimeout(timer);
85
+ reject(e);
86
+ });
87
+ child.on("close", (code) => {
88
+ clearTimeout(timer);
89
+ if (timedOut) {
90
+ reject(new Error(`${bin} timed out after ${Math.round(timeoutMs / 1000)}s`));
91
+ return;
92
+ }
93
+ resolveRun({ code, stdout, stderr });
94
+ });
95
+ });
96
+ }
97
+ /** Unpacks the Linux static tarball, which nests both binaries one directory
98
+ * deep under a version-stamped name. */
99
+ async function installLinux(url, notify) {
100
+ notify(`ffmpeg is not installed. Downloading a static build into ${clipyBinDir()} (from ${url}) — Clipy keeps its own copy and never installs system-wide.`);
101
+ mkdirSync(clipyBinDir(), { recursive: true });
102
+ const work = mkdtempSync(join(tmpdir(), "clipy-ffmpeg-"));
103
+ try {
104
+ const archive = join(work, "ffmpeg.tar.xz");
105
+ let res;
106
+ try {
107
+ res = await fetch(url, { redirect: "follow" });
108
+ }
109
+ catch (e) {
110
+ throw new Error(`could not download ffmpeg from ${url}: ${e.message}. Install it with \`${installHint()}\` and re-run.`);
111
+ }
112
+ if (!res.ok || !res.body) {
113
+ throw new Error(`could not download ffmpeg from ${url} (HTTP ${res.status}). Install it with \`${installHint()}\` and re-run.`);
114
+ }
115
+ await pipeline(Readable.fromWeb(res.body), createWriteStream(archive));
116
+ const untar = await runFf("tar", ["-xJf", archive, "-C", work], 180_000);
117
+ if (untar.code !== 0)
118
+ throw new Error(`could not unpack the ffmpeg archive: ${untar.stderr.trim().slice(0, 200)}`);
119
+ const nested = readdirSync(work).find((entry) => entry.startsWith("ffmpeg-") && !entry.endsWith(".tar.xz"));
120
+ if (!nested)
121
+ throw new Error("the ffmpeg archive did not contain the expected directory");
122
+ for (const tool of ["ffmpeg", "ffprobe"]) {
123
+ const from = join(work, nested, tool);
124
+ if (!existsSync(from))
125
+ throw new Error(`the ffmpeg archive did not contain ${tool}`);
126
+ renameSync(from, managedPath(tool));
127
+ chmodSync(managedPath(tool), 0o755);
128
+ }
129
+ }
130
+ finally {
131
+ rmSync(work, { recursive: true, force: true });
132
+ }
133
+ }
134
+ const cache = new Map();
135
+ export async function resolveFf(tool, notify) {
136
+ const hit = cache.get(tool);
137
+ if (hit)
138
+ return hit;
139
+ const managed = managedPath(tool);
140
+ if (existsSync(managed)) {
141
+ cache.set(tool, managed);
142
+ return managed;
143
+ }
144
+ const found = onPath(tool);
145
+ if (found) {
146
+ cache.set(tool, found);
147
+ return found;
148
+ }
149
+ const linuxUrl = process.platform === "linux" ? LINUX_BUILDS[process.arch] : undefined;
150
+ if (!linuxUrl)
151
+ throw new FfmpegMissingError(tool);
152
+ await installLinux(linuxUrl, notify);
153
+ if (!existsSync(managed))
154
+ throw new FfmpegMissingError(tool);
155
+ notify(`Installed ffmpeg and ffprobe to ${clipyBinDir()} (one-time setup).`);
156
+ cache.set(tool, managed);
157
+ return managed;
158
+ }
159
+ let webpSupport = null;
160
+ /**
161
+ * Homebrew's default ffmpeg ships without libwebp, so the still format has to
162
+ * be probed rather than assumed. Probed once per process.
163
+ */
164
+ export async function supportsWebp(bin) {
165
+ if (webpSupport !== null)
166
+ return webpSupport;
167
+ try {
168
+ const res = await runFf(bin, ["-hide_banner", "-encoders"], 30_000);
169
+ webpSupport = res.code === 0 && /^\s*\S*V\S*\s+libwebp(_anim)?\s/m.test(res.stdout);
170
+ }
171
+ catch {
172
+ webpSupport = false;
173
+ }
174
+ return webpSupport;
175
+ }
176
+ /** Test seam: lets the suite assert both still formats without a second ffmpeg. */
177
+ export function __setWebpSupportForTests(value) {
178
+ webpSupport = value;
179
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Phase 2 of the visual pipeline: turn the server's frame timestamps into
3
+ * actual images on disk.
4
+ *
5
+ * One ffmpeg invocation per timestamp with `-ss` BEFORE `-i` so the decoder
6
+ * seeks rather than decoding the whole file up to that point — the difference
7
+ * between a second and several minutes on a long recording.
8
+ */
9
+ import { createHash } from "node:crypto";
10
+ import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { resolveFf, runFf, supportsWebp } from "./ffmpeg.js";
13
+ /** Frames are context for a reader, not masters — 1600px wide is plenty and
14
+ * keeps the base64 upload from ballooning. */
15
+ const MAX_WIDTH = 1600;
16
+ const PER_FRAME_TIMEOUT_MS = 60_000;
17
+ function pad(index) {
18
+ return String(index).padStart(6, "0");
19
+ }
20
+ /** M:SS, so a warning names the moment the way the user would scrub to it. */
21
+ function fmtClock(ms) {
22
+ const total = Math.max(0, Math.round(ms / 1000));
23
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
24
+ }
25
+ /** ffmpeg prints the encoded still's dimensions in its stream summary; parsing
26
+ * it is cheaper than a second ffprobe spawn per frame. */
27
+ function parseDimensions(stderr) {
28
+ const match = /Video:.*?[,\s](\d{2,5})x(\d{2,5})/.exec(stderr);
29
+ if (!match)
30
+ return {};
31
+ const width = Number(match[1]);
32
+ const height = Number(match[2]);
33
+ if (!Number.isFinite(width) || !Number.isFinite(height))
34
+ return {};
35
+ return { width, height };
36
+ }
37
+ export async function extractFrames(input) {
38
+ const notify = input.notify ?? (() => { });
39
+ if (input.timestampsMs.length === 0)
40
+ return [];
41
+ const bin = await resolveFf("ffmpeg", notify);
42
+ const webp = await supportsWebp(bin);
43
+ const ext = webp ? "webp" : "jpg";
44
+ const mimeType = webp ? "image/webp" : "image/jpeg";
45
+ if (!webp) {
46
+ notify("note: this ffmpeg build has no webp encoder — extracting frames as JPEG instead (slightly larger, same content).");
47
+ }
48
+ mkdirSync(input.outDir, { recursive: true });
49
+ // Sorted and de-duplicated: the server may hand back near-identical
50
+ // timestamps, and frame N should mean "the Nth moment in the video".
51
+ const timestamps = [...new Set(input.timestampsMs.filter((t) => Number.isFinite(t) && t >= 0))].sort((a, b) => a - b);
52
+ notify(`Extracting ${timestamps.length} frame${timestamps.length === 1 ? "" : "s"} with ffmpeg…`);
53
+ const frames = [];
54
+ for (let index = 0; index < timestamps.length; index += 1) {
55
+ const timestampMs = timestamps[index];
56
+ const file = `${pad(index)}.${ext}`;
57
+ const path = join(input.outDir, file);
58
+ try {
59
+ const res = await runFf(bin, [
60
+ "-hide_banner",
61
+ "-nostdin",
62
+ "-y",
63
+ "-ss",
64
+ (timestampMs / 1000).toFixed(3),
65
+ "-i",
66
+ input.videoPath,
67
+ "-frames:v",
68
+ "1",
69
+ "-vf",
70
+ `scale='min(${MAX_WIDTH},iw)':-2`,
71
+ "-q:v",
72
+ "3",
73
+ path,
74
+ ], PER_FRAME_TIMEOUT_MS);
75
+ // A timestamp past the end of the file exits 0 having written nothing, so
76
+ // the file's existence is the real success check, not the exit code.
77
+ if (res.code !== 0 || !existsSync(path) || statSync(path).size === 0) {
78
+ notify(`warning: no frame could be extracted at ${fmtClock(timestampMs)} (moment ${index + 1} of ${timestamps.length}) — skipping that one, the rest continue. ${res.stderr.trim().split("\n").pop() ?? ""}`.trim());
79
+ continue;
80
+ }
81
+ const bytes = readFileSync(path);
82
+ frames.push({
83
+ timestampMs,
84
+ path,
85
+ file,
86
+ ...parseDimensions(res.stderr),
87
+ sha256: createHash("sha256").update(bytes).digest("hex"),
88
+ byteSize: bytes.length,
89
+ mimeType,
90
+ });
91
+ }
92
+ catch (e) {
93
+ notify(`warning: no frame could be extracted at ${fmtClock(timestampMs)} (moment ${index + 1} of ${timestamps.length}) — skipping that one, the rest continue. ${e.message}`);
94
+ }
95
+ }
96
+ return frames;
97
+ }