@clipy/cli 0.8.6 → 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.
@@ -0,0 +1,609 @@
1
+ /**
2
+ * `clipy context import <youtube-url|local-file>` — compiles a local Clipy
3
+ * context bundle (AREC v0.2-draft) and optionally syncs it to the library.
4
+ *
5
+ * Syncing is a TWO-PHASE protocol, and the split is deliberate: the server is
6
+ * the classification brain. Phase 1 uploads the transcript bundle and the
7
+ * server answers with a verdict — what kind of video this is, whether the
8
+ * transcript stands alone, and if not, exactly which timestamps to look at.
9
+ * Phase 2 fetches only those frames and uploads them. The CLI never decides a
10
+ * profile locally, so a local-only run (no --sync) stays honestly
11
+ * transcript-only and makes no claim about sufficiency.
12
+ */
13
+ import { createHash } from "node:crypto";
14
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { basename, join, resolve } from "node:path";
17
+ import { buildManifest, buildNormalizedTranscript, classifyTranscript, parseSrt, parseVtt, parseYoutubeJson3, renderArecMarkdown, slugHash, } from "../context-core/index.js";
18
+ import { fetchCaptions, fetchVideoMeta, resolveYtDlp } from "./ytdlp.js";
19
+ import { probeVideo } from "./probe.js";
20
+ import { extractFrames } from "./frames.js";
21
+ import { borrowLocalVideo, borrowYoutubeVideo } from "./videoFetch.js";
22
+ const YOUTUBE_HOSTS = new Set([
23
+ "youtube.com",
24
+ "www.youtube.com",
25
+ "m.youtube.com",
26
+ "music.youtube.com",
27
+ "youtu.be",
28
+ "www.youtu.be",
29
+ ]);
30
+ function classifyInput(raw) {
31
+ const trimmed = raw.trim();
32
+ let parsed = null;
33
+ try {
34
+ parsed = new URL(trimmed);
35
+ }
36
+ catch {
37
+ parsed = null;
38
+ }
39
+ if (parsed && (parsed.protocol === "http:" || parsed.protocol === "https:")) {
40
+ const host = parsed.hostname.toLowerCase();
41
+ if (YOUTUBE_HOSTS.has(host))
42
+ return { kind: "youtube", url: trimmed };
43
+ return { kind: "url", url: trimmed };
44
+ }
45
+ const path = resolve(trimmed);
46
+ if (existsSync(path) && statSync(path).isFile())
47
+ return { kind: "local", path };
48
+ throw new Error(`could not read "${raw}" — pass a YouTube URL or the path to a local video file.`);
49
+ }
50
+ function sha256File(path) {
51
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
52
+ }
53
+ function parseTranscriptFile(path) {
54
+ const text = readFileSync(path, "utf8");
55
+ const lower = path.toLowerCase();
56
+ if (lower.endsWith(".vtt"))
57
+ return parseVtt(text);
58
+ if (lower.endsWith(".srt"))
59
+ return parseSrt(text);
60
+ let parsed;
61
+ try {
62
+ parsed = JSON.parse(text);
63
+ }
64
+ catch {
65
+ throw new Error(`--transcript ${path} is neither .vtt/.srt nor valid JSON. Supported: WebVTT, SubRip, or Clipy transcript JSON ({"segments":[{"startMs","endMs","text"}]}).`);
66
+ }
67
+ // json3 (YouTube) and Clipy transcript JSON both land here.
68
+ const json3 = parseYoutubeJson3(parsed);
69
+ if (json3.length > 0)
70
+ return json3;
71
+ const raw = parsed.segments;
72
+ if (!Array.isArray(raw)) {
73
+ throw new Error(`--transcript ${path} has no usable segments.`);
74
+ }
75
+ const segments = [];
76
+ for (const item of raw) {
77
+ if (!item || typeof item !== "object")
78
+ continue;
79
+ const startMs = Number(item.startMs);
80
+ const endMs = Number(item.endMs);
81
+ const value = item.text;
82
+ if (!Number.isFinite(startMs) || typeof value !== "string")
83
+ continue;
84
+ segments.push({ startMs, endMs: Number.isFinite(endMs) ? endMs : startMs, text: value });
85
+ }
86
+ if (segments.length === 0)
87
+ throw new Error(`--transcript ${path} has no usable segments.`);
88
+ return segments;
89
+ }
90
+ function notify(message) {
91
+ process.stderr.write(`${message}\n`);
92
+ }
93
+ /** M:SS / H:MM:SS, matching how a user would scrub to the moment. */
94
+ function fmtClock(ms) {
95
+ const total = Math.max(0, Math.round(ms / 1000));
96
+ const h = Math.floor(total / 3600);
97
+ const m = Math.floor((total % 3600) / 60);
98
+ const ss = String(total % 60).padStart(2, "0");
99
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
100
+ }
101
+ /**
102
+ * The exact command to run again. Printed with every partial success, because
103
+ * "re-run it" is only actionable if the user does not have to reconstruct the
104
+ * flags they used ten minutes ago.
105
+ */
106
+ function rerunCommand(target, opts) {
107
+ const quote = (v) => (/[\s"']/.test(v) ? JSON.stringify(v) : v);
108
+ const parts = ["clipy", "context", "import", quote(target)];
109
+ if (opts.transcriptPath)
110
+ parts.push("--transcript", quote(opts.transcriptPath));
111
+ if (opts.outputDir)
112
+ parts.push("--output", quote(opts.outputDir));
113
+ if (opts.language)
114
+ parts.push("--language", quote(opts.language));
115
+ if (opts.folder)
116
+ parts.push("--folder", quote(opts.folder));
117
+ for (const tag of opts.tags)
118
+ parts.push("--tag", quote(tag));
119
+ parts.push("--sync");
120
+ return parts.join(" ");
121
+ }
122
+ async function compileYoutube(url, opts) {
123
+ const bin = await resolveYtDlp(notify);
124
+ notify("Fetching video info…");
125
+ const meta = await fetchVideoMeta(bin, url);
126
+ notify(`Found: "${meta.title}" (${fmtClock(meta.durationMs)})`);
127
+ const langPref = opts.language ?? meta.language ?? "en";
128
+ notify(`Downloading captions (${langPref})…`);
129
+ const captions = await fetchCaptions(bin, url, meta, langPref);
130
+ if (!captions) {
131
+ const available = [...new Set([...meta.subtitleLangs, ...meta.autoCaptionLangs])];
132
+ if (available.length > 0) {
133
+ throw new Error(`this video has no captions in "${langPref}". Re-run with --language <code> (e.g. --language ${available.includes("en") ? "en" : available[0]}).`);
134
+ }
135
+ throw new Error("this video has no captions (neither creator-provided nor auto-generated).\n" +
136
+ " Supply your own with --transcript <file.vtt|file.srt|transcript.json>.\n" +
137
+ " Local speech-to-text for caption-less videos lands in a future release.");
138
+ }
139
+ const raw = captions.format === "json3"
140
+ ? parseYoutubeJson3(JSON.parse(captions.text))
141
+ : parseVtt(captions.text);
142
+ const transcript = buildNormalizedTranscript(raw, {
143
+ language: captions.language,
144
+ source: captions.source,
145
+ durationMs: meta.durationMs || undefined,
146
+ });
147
+ notify(`Got ${transcript.segments.length} caption segments (${captions.source === "creator_captions" ? "creator-provided" : "auto-generated"}, ${captions.language}).`);
148
+ const source = {
149
+ kind: "youtube",
150
+ ...(meta.id ? { canonicalUrl: `https://www.youtube.com/watch?v=${meta.id}`, providerId: meta.id } : {}),
151
+ };
152
+ return finish({
153
+ title: opts.title ?? meta.title,
154
+ source,
155
+ durationMs: meta.durationMs,
156
+ transcript,
157
+ fingerprint: `youtube:${meta.id || url}`,
158
+ media: { kind: "youtube", url, ytDlpBin: bin, durationMs: meta.durationMs },
159
+ opts,
160
+ });
161
+ }
162
+ async function compileLocal(path, opts) {
163
+ if (!opts.transcriptPath) {
164
+ throw new Error(`local files need a transcript: pass --transcript <file.vtt|file.srt|transcript.json>.\n` +
165
+ " Local speech-to-text lands in a future release.");
166
+ }
167
+ const transcriptPath = resolve(opts.transcriptPath);
168
+ if (!existsSync(transcriptPath))
169
+ throw new Error(`--transcript ${transcriptPath} does not exist.`);
170
+ notify(`Probing ${basename(path)} with ffprobe…`);
171
+ const probe = await probeVideo(path);
172
+ const contentHash = sha256File(path);
173
+ notify(`Reading the transcript from ${basename(transcriptPath)}…`);
174
+ const segments = parseTranscriptFile(transcriptPath);
175
+ notify(`Got ${segments.length} transcript segments (${fmtClock(probe.durationMs)} of video).`);
176
+ const transcript = buildNormalizedTranscript(segments, {
177
+ ...(opts.language ? { language: opts.language } : {}),
178
+ source: "user_file",
179
+ durationMs: probe.durationMs || undefined,
180
+ });
181
+ return finish({
182
+ title: opts.title ?? basename(path),
183
+ // basename only — the bundle and the upload must never carry the user's
184
+ // directory layout, and `path` here is already absolute.
185
+ source: { kind: "local", contentHash, fileName: basename(path) },
186
+ durationMs: probe.durationMs,
187
+ transcript,
188
+ fingerprint: `local:${contentHash}`,
189
+ media: { kind: "local", path },
190
+ opts,
191
+ });
192
+ }
193
+ function finish(input) {
194
+ const sufficiency = classifyTranscript(input.transcript);
195
+ const manifest = buildManifest({
196
+ title: input.title,
197
+ source: input.source,
198
+ durationMs: input.durationMs,
199
+ profile: "transcript",
200
+ transcript: input.transcript,
201
+ compiler: { name: "@clipy/cli", version: input.opts.cliVersion },
202
+ sufficiency,
203
+ createdAt: new Date().toISOString(),
204
+ });
205
+ return {
206
+ manifest,
207
+ transcript: input.transcript,
208
+ markdown: renderArecMarkdown(manifest, input.transcript),
209
+ fingerprint: input.fingerprint,
210
+ media: input.media,
211
+ };
212
+ }
213
+ /**
214
+ * Rebuilds a compiled bundle around the server's verdict and the frames we
215
+ * fetched for it. recording.md is a pure function of the manifest plus the
216
+ * transcript, so re-rendering is the whole update.
217
+ */
218
+ function withVisualEvidence(compiled, classification, frames) {
219
+ const manifest = {
220
+ ...compiled.manifest,
221
+ profile: frames.length > 0 ? "visual" : compiled.manifest.profile,
222
+ serverClassification: classification,
223
+ ...(frames.length > 0 ? { frames } : {}),
224
+ };
225
+ return {
226
+ ...compiled,
227
+ manifest,
228
+ markdown: renderArecMarkdown(manifest, compiled.transcript),
229
+ };
230
+ }
231
+ /** A frame is captioned by the planned moment it was cut for. Timestamps can
232
+ * drift by a keyframe, so match on proximity; a caption from a different
233
+ * moment would be worse than none. */
234
+ const CAPTION_MATCH_TOLERANCE_MS = 2_000;
235
+ function captionForFrame(moments, timestampMs) {
236
+ let best;
237
+ let bestDelta = Number.POSITIVE_INFINITY;
238
+ for (const m of moments ?? []) {
239
+ const delta = Math.abs(m.tMs - timestampMs);
240
+ if (delta < bestDelta) {
241
+ best = m;
242
+ bestDelta = delta;
243
+ }
244
+ }
245
+ return best && bestDelta <= CAPTION_MATCH_TOLERANCE_MS ? best.caption : undefined;
246
+ }
247
+ /** Writes into a temp sibling then renames, so a failure never leaves a half bundle. */
248
+ function writeBundle(dir, compiled, frames = []) {
249
+ mkdirSync(dir, { recursive: true });
250
+ const bundlePath = join(dir, `clipy-context-${slugHash(compiled.fingerprint)}`);
251
+ const contents = {
252
+ "recording.md": compiled.markdown,
253
+ // createdAt changes every run; compare on everything else so a rerun over an
254
+ // unchanged source is genuinely idempotent.
255
+ "manifest.json": `${JSON.stringify(compiled.manifest, null, 2)}\n`,
256
+ "transcript.json": `${JSON.stringify(compiled.transcript, null, 2)}\n`,
257
+ };
258
+ let rewritten = false;
259
+ if (existsSync(bundlePath)) {
260
+ const entries = readdirSync(bundlePath);
261
+ if (!entries.includes("manifest.json")) {
262
+ throw new Error(`${bundlePath} exists but is not a Clipy context bundle — refusing to overwrite it. Use --output <dir> to write elsewhere.`);
263
+ }
264
+ rewritten = !sameBundle(bundlePath, contents);
265
+ if (!rewritten && frames.length === 0)
266
+ return { path: bundlePath, rewritten: false };
267
+ }
268
+ const staging = mkdtempSync(join(dir, ".clipy-context-tmp-"));
269
+ try {
270
+ for (const [name, body] of Object.entries(contents))
271
+ writeFileSync(join(staging, name), body);
272
+ if (frames.length > 0) {
273
+ mkdirSync(join(staging, "frames"), { recursive: true });
274
+ for (const frame of frames)
275
+ copyFileSync(frame.path, join(staging, "frames", frame.file));
276
+ }
277
+ rmSync(bundlePath, { recursive: true, force: true });
278
+ renameSync(staging, bundlePath);
279
+ }
280
+ finally {
281
+ rmSync(staging, { recursive: true, force: true });
282
+ }
283
+ return { path: bundlePath, rewritten };
284
+ }
285
+ function sameBundle(bundlePath, contents) {
286
+ try {
287
+ // recording.md is a pure function of the manifest and the transcript, and it
288
+ // embeds the compile timestamp — comparing it byte-wise would make every
289
+ // rerun look like a content change.
290
+ const a = JSON.parse(readFileSync(join(bundlePath, "manifest.json"), "utf8"));
291
+ const b = JSON.parse(contents["manifest.json"]);
292
+ delete a.createdAt;
293
+ delete b.createdAt;
294
+ if (JSON.stringify(a) !== JSON.stringify(b))
295
+ return false;
296
+ if (readFileSync(join(bundlePath, "transcript.json"), "utf8") !== contents["transcript.json"])
297
+ return false;
298
+ if (!existsSync(join(bundlePath, "recording.md")))
299
+ return false;
300
+ return true;
301
+ }
302
+ catch {
303
+ return false;
304
+ }
305
+ }
306
+ /** One place for the auth/UA/timeout shape both phases share. */
307
+ async function apiPost(opts, path, payload) {
308
+ const controller = new AbortController();
309
+ const timer = setTimeout(() => controller.abort(), 120_000);
310
+ let res;
311
+ try {
312
+ res = await fetch(`${opts.apiUrl}${path}`, {
313
+ method: "POST",
314
+ headers: {
315
+ Authorization: `Bearer ${opts.apiKey}`,
316
+ "Content-Type": "application/json",
317
+ Accept: "application/json",
318
+ "User-Agent": `clipy-cli/${opts.cliVersion}`,
319
+ },
320
+ body: JSON.stringify(payload),
321
+ signal: controller.signal,
322
+ });
323
+ }
324
+ finally {
325
+ clearTimeout(timer);
326
+ }
327
+ const text = await res.text();
328
+ let body = {};
329
+ try {
330
+ body = text ? JSON.parse(text) : {};
331
+ }
332
+ catch {
333
+ body = {};
334
+ }
335
+ return { ok: res.ok, status: res.status, body };
336
+ }
337
+ /** The server's verdict is untrusted input like anything else off the wire:
338
+ * every field is checked, and timestamps are clamped to the video. */
339
+ function parseClassification(raw, durationMs) {
340
+ if (!raw || typeof raw !== "object")
341
+ return null;
342
+ const c = raw;
343
+ const videoType = typeof c.videoType === "string" ? c.videoType.slice(0, 80) : "";
344
+ if (!videoType)
345
+ return null;
346
+ const confidence = Number(c.videoTypeConfidence);
347
+ const rawMoments = Array.isArray(c.moments) ? c.moments : [];
348
+ const moments = rawMoments
349
+ .flatMap((m) => {
350
+ if (!m || typeof m !== "object")
351
+ return [];
352
+ const tMs = Number(m.tMs);
353
+ const caption = m.caption;
354
+ if (!Number.isFinite(tMs) || typeof caption !== "string" || !caption.trim())
355
+ return [];
356
+ return [{ tMs, caption: caption.trim().slice(0, 300) }];
357
+ })
358
+ .slice(0, 60);
359
+ const rawTimestamps = Array.isArray(c.frameTimestampsMs) ? c.frameTimestampsMs : [];
360
+ const frameTimestampsMs = rawTimestamps
361
+ .map((t) => Number(t))
362
+ .filter((t) => Number.isFinite(t) && t >= 0 && (durationMs <= 0 || t <= durationMs))
363
+ // A server bug (or a compromised response) must not turn into an unbounded
364
+ // ffmpeg fan-out on the user's machine.
365
+ .slice(0, 60);
366
+ return {
367
+ videoType,
368
+ videoTypeConfidence: Number.isFinite(confidence) ? Math.min(1, Math.max(0, confidence)) : 0,
369
+ needsVisual: c.needsVisual === true,
370
+ ...(typeof c.visualReason === "string" && c.visualReason.trim()
371
+ ? { visualReason: c.visualReason.trim().slice(0, 300) }
372
+ : {}),
373
+ frameTimestampsMs,
374
+ ...(moments.length ? { moments } : {}),
375
+ ...(typeof c.model === "string" && c.model.trim() ? { model: c.model.trim().slice(0, 80) } : {}),
376
+ };
377
+ }
378
+ async function sync(compiled, opts, bundlePath) {
379
+ if (!opts.apiKey) {
380
+ throw new Error(`--sync needs an API key. Run \`clipy login\` (or set CLIPY_API_KEY), then re-run.\n` +
381
+ ` Nothing was lost: the local bundle is already written to ${bundlePath}.`);
382
+ }
383
+ const payload = {
384
+ idempotencyKey: slugHash(`${compiled.fingerprint}|${compiled.manifest.source.contentHash ?? ""}|${compiled.manifest.compiler.version}`),
385
+ manifest: compiled.manifest,
386
+ arecMarkdown: compiled.markdown,
387
+ transcript: compiled.transcript,
388
+ ...(opts.tags.length ? { tags: opts.tags } : {}),
389
+ ...(opts.folder ? { folderName: opts.folder } : {}),
390
+ };
391
+ notify(`Uploading the transcript to Clipy (${compiled.transcript.segments.length} segments, no video)…`);
392
+ const { ok, status, body } = await apiPost(opts, "/api/v1/context-documents", payload);
393
+ if (!ok) {
394
+ // Every one of these fails in PHASE 1, before anything reached the library
395
+ // — so the local bundle is the user's intact fallback, and saying so is the
396
+ // difference between "it broke" and "here is what you still have".
397
+ const detail = typeof body.error === "string" ? body.error : `HTTP ${status}`;
398
+ const intact = `Your local bundle is complete and unaffected: ${bundlePath}`;
399
+ if (status === 401) {
400
+ throw new Error(`sync failed while uploading the transcript: ${detail}\n` +
401
+ ` Run \`clipy login\` to set a new key, then re-run.\n ${intact}`);
402
+ }
403
+ if (status === 409) {
404
+ throw new Error(`sync failed while uploading the transcript: ${detail}\n` +
405
+ ` That idempotency key already points at different content — this source changed since the last import.\n` +
406
+ ` Delete the old document in your library, or import from a fresh copy.\n ${intact}`);
407
+ }
408
+ if (status === 429) {
409
+ throw new Error(`sync failed while uploading the transcript: ${detail}\n` +
410
+ ` You have hit today's ingest quota (it resets at 00:00 UTC). Re-run then.\n ${intact}`);
411
+ }
412
+ throw new Error(`sync failed while uploading the transcript: ${detail}\n ${intact}`);
413
+ }
414
+ return {
415
+ documentId: typeof body.id === "string" ? body.id : "",
416
+ publicId: typeof body.publicId === "string" ? body.publicId : "",
417
+ created: body.created !== false,
418
+ folderName: typeof body.folderName === "string" ? body.folderName : null,
419
+ classification: parseClassification(body.classification, compiled.manifest.durationMs),
420
+ };
421
+ }
422
+ /** Phase 2. Frames go up as base64 in one request; the server dedupes on the
423
+ * sha256 we computed here, so a retried import re-uploads nothing new. */
424
+ async function uploadFrames(documentId, frames, opts) {
425
+ const payload = {
426
+ frames: frames.map((f) => ({
427
+ timestampMs: f.timestampMs,
428
+ mimeType: f.mimeType,
429
+ base64: readFileSync(f.path).toString("base64"),
430
+ sha256: f.sha256,
431
+ ...(f.width ? { width: f.width } : {}),
432
+ ...(f.height ? { height: f.height } : {}),
433
+ })),
434
+ };
435
+ const { ok, status, body } = await apiPost(opts, `/api/v1/context-documents/${encodeURIComponent(documentId)}/frames`, payload);
436
+ if (!ok) {
437
+ const detail = typeof body.error === "string" ? body.error : `HTTP ${status}`;
438
+ throw new Error(`uploading the frames failed: ${detail}`);
439
+ }
440
+ return {
441
+ added: Number(body.added) || 0,
442
+ total: Number(body.total) || 0,
443
+ };
444
+ }
445
+ /**
446
+ * Phase 2, end to end: get the media, cut the frames the server asked for,
447
+ * upload them, and always let go of the borrowed video.
448
+ *
449
+ * Every failure here is non-fatal. The transcript bundle is already written and
450
+ * already synced, so a missing ffmpeg or an undownloadable video costs the user
451
+ * the pictures, not the import.
452
+ */
453
+ async function collectFrames(compiled, timestampsMs, opts) {
454
+ let borrowed = null;
455
+ const workDir = mkdtempSync(join(tmpdir(), "clipy-frames-out-"));
456
+ try {
457
+ borrowed =
458
+ compiled.media.kind === "local"
459
+ ? borrowLocalVideo(compiled.media.path)
460
+ : await borrowYoutubeVideo({
461
+ ytDlpBin: compiled.media.ytDlpBin,
462
+ url: compiled.media.url,
463
+ durationMs: compiled.media.durationMs,
464
+ notify,
465
+ });
466
+ const frames = await extractFrames({
467
+ videoPath: borrowed.path,
468
+ timestampsMs,
469
+ outDir: workDir,
470
+ notify,
471
+ });
472
+ notify(`Extracted ${frames.length} of ${timestampsMs.length} frames.`);
473
+ return { frames, workDir, failure: null };
474
+ }
475
+ catch (e) {
476
+ rmSync(workDir, { recursive: true, force: true });
477
+ return { frames: [], workDir: null, failure: e.message };
478
+ }
479
+ finally {
480
+ borrowed?.release();
481
+ }
482
+ }
483
+ export async function cmdContextImport(target, opts) {
484
+ const input = classifyInput(target);
485
+ if (input.kind === "url") {
486
+ throw new Error("direct media URLs are not supported yet — pass a YouTube URL or download the file first and import it locally.");
487
+ }
488
+ let compiled = input.kind === "youtube" ? await compileYoutube(input.url, opts) : await compileLocal(input.path, opts);
489
+ const outputDir = resolve(opts.outputDir ?? process.cwd());
490
+ let { path: bundlePath, rewritten } = writeBundle(outputDir, compiled);
491
+ const report = compiled.manifest.sufficiency;
492
+ let synced = null;
493
+ let uploadedFrames = [];
494
+ let frameUpload = null;
495
+ if (opts.sync) {
496
+ // Phase 1: the transcript bundle goes up, the verdict comes back.
497
+ synced = await sync(compiled, opts, bundlePath);
498
+ const classification = synced.classification;
499
+ notify(`Synced ✓ — ${synced.publicId} (private${synced.folderName ? `, filed in ${synced.folderName}` : ""}).`);
500
+ if (classification) {
501
+ const wanted = classification.frameTimestampsMs.length;
502
+ const needs = classification.needsVisual && wanted > 0;
503
+ // Three outcomes, not two: the server gates on whether the video needs
504
+ // pixels at all, THEN indexes it. A yes with nothing to point at is its
505
+ // own case — saying "the transcript stands on its own" there would
506
+ // contradict the verdict we were just given.
507
+ notify(`Classified: ${classification.videoType} (${classification.videoTypeConfidence.toFixed(2)}) — ${needs
508
+ ? `${wanted} visual moment${wanted === 1 ? "" : "s"} identified`
509
+ : classification.needsVisual
510
+ ? "this video leans on its visuals, but no specific moment could be pinpointed — staying transcript-only"
511
+ : "no visual moments; the transcript stands on its own"}`);
512
+ if (needs && !opts.frames) {
513
+ notify(`Frames skipped on purpose (--no-frames): no media was downloaded and the bundle stays transcript-only.\n` +
514
+ ` The document is already in your library; to add the ${wanted} frame${wanted === 1 ? "" : "s"} later, run:\n` +
515
+ ` ${rerunCommand(target, opts)}`);
516
+ }
517
+ else if (needs) {
518
+ // Phase 2: fetch only the moments the server named.
519
+ const { frames, workDir, failure } = await collectFrames(compiled, classification.frameTimestampsMs, opts);
520
+ if (failure) {
521
+ // Phase 1 already succeeded — this is a PARTIAL success, and saying
522
+ // "failed" here would send the user hunting for a document that is
523
+ // sitting in their library right now.
524
+ notify(`Frames could not be extracted, but your import is NOT lost.\n` +
525
+ ` Created: ${synced.publicId} — transcript, summary text and the ${classification.videoType} classification are all in your library.\n` +
526
+ ` Missing: ${classification.frameTimestampsMs.length} frame${classification.frameTimestampsMs.length === 1 ? "" : "s"} of visual evidence.\n` +
527
+ ` Why: ${failure.split("\n").join("\n ")}\n` +
528
+ ` To finish it once that is sorted, re-run:\n ${rerunCommand(target, opts)}`);
529
+ }
530
+ try {
531
+ if (frames.length > 0 && synced.documentId) {
532
+ notify(`Uploading ${frames.length} frame${frames.length === 1 ? "" : "s"}…`);
533
+ try {
534
+ frameUpload = await uploadFrames(synced.documentId, frames, opts);
535
+ uploadedFrames = frames;
536
+ notify(`Frames attached ✓ — ${frameUpload.added} new (${frameUpload.total} on the document).`);
537
+ }
538
+ catch (e) {
539
+ // Same partial-success rule as a failed extraction: the document
540
+ // exists, only the pictures are missing.
541
+ notify(`The frames were cut but ${e.message}\n` +
542
+ ` Your import is NOT lost: ${synced.publicId} is in your library with its transcript and classification.\n` +
543
+ ` The frames are also in the local bundle, so nothing was re-downloaded for nothing.\n` +
544
+ ` To retry just the upload, re-run:\n ${rerunCommand(target, opts)}`);
545
+ uploadedFrames = frames;
546
+ }
547
+ }
548
+ else if (frames.length > 0) {
549
+ notify("frames were extracted but the server returned no document id, so they were not uploaded.");
550
+ }
551
+ // Regenerate the LOCAL bundle around the verdict + the frames.
552
+ compiled = withVisualEvidence(compiled, classification, uploadedFrames.map((f) => {
553
+ const caption = captionForFrame(classification.moments, f.timestampMs);
554
+ return {
555
+ timestampMs: f.timestampMs,
556
+ file: f.file,
557
+ sha256: f.sha256,
558
+ ...(f.width ? { width: f.width } : {}),
559
+ ...(f.height ? { height: f.height } : {}),
560
+ ...(caption ? { caption } : {}),
561
+ };
562
+ }));
563
+ ({ path: bundlePath } = writeBundle(outputDir, compiled, uploadedFrames));
564
+ }
565
+ finally {
566
+ if (workDir)
567
+ rmSync(workDir, { recursive: true, force: true });
568
+ }
569
+ }
570
+ // Even with no frames, the verdict itself belongs in the bundle.
571
+ if (uploadedFrames.length === 0) {
572
+ compiled = withVisualEvidence(compiled, classification, []);
573
+ ({ path: bundlePath } = writeBundle(outputDir, compiled));
574
+ }
575
+ }
576
+ }
577
+ if (opts.json) {
578
+ process.stdout.write(`${JSON.stringify({
579
+ bundlePath,
580
+ profile: compiled.manifest.profile,
581
+ recommendedProfile: report?.recommendedProfile ?? null,
582
+ overallScore: report?.overallScore ?? null,
583
+ gapCount: report?.gaps.length ?? 0,
584
+ ...(synced ? { synced: true, publicId: synced.publicId } : opts.sync ? { synced: false } : {}),
585
+ classification: synced?.classification ?? null,
586
+ frames: uploadedFrames.length,
587
+ ...(frameUpload ? { framesAdded: frameUpload.added, framesTotal: frameUpload.total } : {}),
588
+ }, null, 2)}\n`);
589
+ return;
590
+ }
591
+ process.stdout.write(`bundle: ${bundlePath}${rewritten ? " (rewritten — source content changed)" : ""}\n`);
592
+ if (synced?.classification) {
593
+ process.stdout.write(`classified: ${synced.classification.videoType} (${synced.classification.videoTypeConfidence.toFixed(2)}) · ${synced.classification.frameTimestampsMs.length} visual moment${synced.classification.frameTimestampsMs.length === 1 ? "" : "s"}\n`);
594
+ }
595
+ process.stdout.write(`transcript: ${compiled.transcript.segments.length} segments from ${compiled.manifest.transcript.source}\n`);
596
+ if (report) {
597
+ process.stdout.write(`sufficiency: ${report.overallScore.toFixed(2)} · recommended profile ${report.recommendedProfile} · ${report.gaps.length} visual gap${report.gaps.length === 1 ? "" : "s"}\n`);
598
+ if (report.recommendedProfile === "visual" && !opts.sync) {
599
+ process.stdout.write(`note: this video leans on visuals at ${report.gaps.length} timestamps. Re-run with --sync to have the server classify it and pull the frames that matter.\n`);
600
+ }
601
+ }
602
+ if (uploadedFrames.length > 0) {
603
+ process.stdout.write(`frames: ${uploadedFrames.length} extracted into ${bundlePath}/frames${frameUpload ? ` · ${frameUpload.added} new on the server (${frameUpload.total} total)` : ""}\n`);
604
+ }
605
+ if (synced) {
606
+ process.stdout.write(`synced: ${synced.publicId} (private — only you can read it${synced.folderName ? `, filed in ${synced.folderName}` : ""})\n`);
607
+ }
608
+ process.stdout.write(`next: clipy context read ${bundlePath}\n`);
609
+ }
@@ -0,0 +1,53 @@
1
+ /** ffprobe wrapper for local-file imports. */
2
+ import { spawn } from "node:child_process";
3
+ const INSTALL_HINT = "ffprobe was not found. Install ffmpeg (macOS: brew install ffmpeg · Debian/Ubuntu: sudo apt install ffmpeg · Windows: winget install Gyan.FFmpeg) and try again.";
4
+ function run(args, timeoutMs) {
5
+ return new Promise((resolveRun, reject) => {
6
+ const child = spawn("ffprobe", args, { stdio: ["ignore", "pipe", "pipe"] });
7
+ let stdout = "";
8
+ let stderr = "";
9
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
10
+ child.stdout.on("data", (d) => {
11
+ stdout += d.toString("utf8");
12
+ });
13
+ child.stderr.on("data", (d) => {
14
+ if (stderr.length < 8192)
15
+ stderr += d.toString("utf8");
16
+ });
17
+ child.on("error", (e) => {
18
+ clearTimeout(timer);
19
+ reject(e.code === "ENOENT" ? new Error(INSTALL_HINT) : e);
20
+ });
21
+ child.on("close", (code) => {
22
+ clearTimeout(timer);
23
+ resolveRun({ code, stdout, stderr });
24
+ });
25
+ });
26
+ }
27
+ export async function probeVideo(path) {
28
+ const res = await run(["-v", "error", "-print_format", "json", "-show_format", "-show_streams", path], 60_000);
29
+ if (res.code !== 0) {
30
+ throw new Error(`ffprobe could not read ${path}: ${res.stderr.trim().split("\n").pop() ?? `exit ${res.code}`}`);
31
+ }
32
+ let parsed;
33
+ try {
34
+ parsed = JSON.parse(res.stdout);
35
+ }
36
+ catch {
37
+ throw new Error(`ffprobe returned unparseable output for ${path}`);
38
+ }
39
+ const streams = Array.isArray(parsed.streams) ? parsed.streams : [];
40
+ const video = streams.find((s) => s.codec_type === "video");
41
+ if (!video) {
42
+ throw new Error(`${path} has no video stream — Clipy context imports need a video file.`);
43
+ }
44
+ const format = (parsed.format ?? {});
45
+ const seconds = Number(format.duration ?? video.duration);
46
+ const width = Number(video.width);
47
+ const height = Number(video.height);
48
+ return {
49
+ durationMs: Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : 0,
50
+ ...(Number.isFinite(width) && width > 0 ? { width } : {}),
51
+ ...(Number.isFinite(height) && height > 0 ? { height } : {}),
52
+ };
53
+ }