@clipy/cli 0.9.0 → 0.9.2
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/dist/context/errors.js +38 -0
- package/dist/context/importCmd.js +194 -58
- package/dist/context/retry.js +130 -0
- package/dist/context/videoFetch.js +134 -58
- package/dist/context/youtubeUrl.js +68 -0
- package/dist/context/ytdlp.js +185 -38
- package/dist/context-core/arec.js +39 -0
- package/dist/index.js +235 -8
- package/dist/skill.js +103 -1
- package/package.json +3 -3
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export class ImportError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
remediation;
|
|
4
|
+
/** What survived, when something did. Non-null makes this a partial failure. */
|
|
5
|
+
partial;
|
|
6
|
+
constructor(code, message, remediation, partial = null) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "ImportError";
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.remediation = remediation;
|
|
11
|
+
this.partial = partial;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export function isImportError(e) {
|
|
15
|
+
return e instanceof Error && e.name === "ImportError";
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The one JSON object a failed `--json` run prints. Exactly one object per run,
|
|
19
|
+
* success or failure, so an agent can always `JSON.parse` stdout.
|
|
20
|
+
*/
|
|
21
|
+
export function errorEnvelope(e) {
|
|
22
|
+
if (isImportError(e)) {
|
|
23
|
+
return {
|
|
24
|
+
ok: false,
|
|
25
|
+
code: e.code,
|
|
26
|
+
error: e.message,
|
|
27
|
+
remediation: e.remediation,
|
|
28
|
+
partial: e.partial,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
ok: false,
|
|
33
|
+
code: "unknown",
|
|
34
|
+
error: e instanceof Error ? e.message : String(e),
|
|
35
|
+
remediation: "Re-run the command; if it fails again, report this output as a bug.",
|
|
36
|
+
partial: null,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -15,37 +15,40 @@ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdir
|
|
|
15
15
|
import { tmpdir } from "node:os";
|
|
16
16
|
import { basename, join, resolve } from "node:path";
|
|
17
17
|
import { buildManifest, buildNormalizedTranscript, classifyTranscript, parseSrt, parseVtt, parseYoutubeJson3, renderArecMarkdown, slugHash, } from "../context-core/index.js";
|
|
18
|
-
import { fetchCaptions, fetchVideoMeta, resolveYtDlp } from "./ytdlp.js";
|
|
18
|
+
import { describeCaptions, fetchCaptions, fetchVideoMeta, resolveYtDlp } from "./ytdlp.js";
|
|
19
|
+
import { canonicalYoutubeUrl, isYoutubeHost, parseYoutubeId } from "./youtubeUrl.js";
|
|
20
|
+
import { ImportError } from "./errors.js";
|
|
21
|
+
import { looksLikeStaleBinary } from "./retry.js";
|
|
19
22
|
import { probeVideo } from "./probe.js";
|
|
20
23
|
import { extractFrames } from "./frames.js";
|
|
21
24
|
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
25
|
function classifyInput(raw) {
|
|
31
26
|
const trimmed = raw.trim();
|
|
27
|
+
// Shell-escaped input (`watch\?v\=…`) still has to be recognised as YouTube,
|
|
28
|
+
// so host detection runs on the de-escaped string.
|
|
29
|
+
const unescaped = trimmed.replace(/\\/g, "");
|
|
32
30
|
let parsed = null;
|
|
33
31
|
try {
|
|
34
|
-
parsed = new URL(
|
|
32
|
+
parsed = new URL(unescaped);
|
|
35
33
|
}
|
|
36
34
|
catch {
|
|
37
35
|
parsed = null;
|
|
38
36
|
}
|
|
39
37
|
if (parsed && (parsed.protocol === "http:" || parsed.protocol === "https:")) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
38
|
+
if (isYoutubeHost(parsed.hostname)) {
|
|
39
|
+
const videoId = parseYoutubeId(trimmed);
|
|
40
|
+
if (!videoId) {
|
|
41
|
+
throw new ImportError("invalid_url", `could not find a video id in "${raw}". Channel, playlist and search URLs are not supported.`, `Pass a single-video URL, e.g. clipy context import "https://www.youtube.com/watch?v=<id>" (youtu.be/<id> and /shorts/<id> also work).`);
|
|
42
|
+
}
|
|
43
|
+
// Everything downstream uses the canonical URL — never the raw input.
|
|
44
|
+
return { kind: "youtube", url: canonicalYoutubeUrl(videoId), videoId };
|
|
45
|
+
}
|
|
46
|
+
return { kind: "url", url: unescaped };
|
|
44
47
|
}
|
|
45
48
|
const path = resolve(trimmed);
|
|
46
49
|
if (existsSync(path) && statSync(path).isFile())
|
|
47
50
|
return { kind: "local", path };
|
|
48
|
-
throw new
|
|
51
|
+
throw new ImportError("source_unreadable", `could not read "${raw}" — it is neither a YouTube URL nor a readable local file.`, `Check the path exists, or pass a YouTube URL: clipy context import "https://www.youtube.com/watch?v=<id>"`);
|
|
49
52
|
}
|
|
50
53
|
function sha256File(path) {
|
|
51
54
|
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
@@ -62,7 +65,7 @@ function parseTranscriptFile(path) {
|
|
|
62
65
|
parsed = JSON.parse(text);
|
|
63
66
|
}
|
|
64
67
|
catch {
|
|
65
|
-
throw new
|
|
68
|
+
throw new ImportError("transcript_unreadable", `--transcript ${path} is neither .vtt/.srt nor valid JSON.`, `Supply WebVTT (.vtt), SubRip (.srt), or Clipy transcript JSON ({"segments":[{"startMs","endMs","text"}]}).`);
|
|
66
69
|
}
|
|
67
70
|
// json3 (YouTube) and Clipy transcript JSON both land here.
|
|
68
71
|
const json3 = parseYoutubeJson3(parsed);
|
|
@@ -70,7 +73,7 @@ function parseTranscriptFile(path) {
|
|
|
70
73
|
return json3;
|
|
71
74
|
const raw = parsed.segments;
|
|
72
75
|
if (!Array.isArray(raw)) {
|
|
73
|
-
throw new
|
|
76
|
+
throw new ImportError("transcript_unreadable", `--transcript ${path} has no usable segments.`, `Supply WebVTT (.vtt), SubRip (.srt), or Clipy transcript JSON ({"segments":[{"startMs","endMs","text"}]}).`);
|
|
74
77
|
}
|
|
75
78
|
const segments = [];
|
|
76
79
|
for (const item of raw) {
|
|
@@ -83,10 +86,26 @@ function parseTranscriptFile(path) {
|
|
|
83
86
|
continue;
|
|
84
87
|
segments.push({ startMs, endMs: Number.isFinite(endMs) ? endMs : startMs, text: value });
|
|
85
88
|
}
|
|
86
|
-
if (segments.length === 0)
|
|
87
|
-
throw new
|
|
89
|
+
if (segments.length === 0) {
|
|
90
|
+
throw new ImportError("transcript_unreadable", `--transcript ${path} has no usable segments.`, `Supply WebVTT (.vtt), SubRip (.srt), or Clipy transcript JSON ({"segments":[{"startMs","endMs","text"}]}).`);
|
|
91
|
+
}
|
|
88
92
|
return segments;
|
|
89
93
|
}
|
|
94
|
+
/** Platform-correct, runnable verbatim — an agent should be able to paste it. */
|
|
95
|
+
const FFMPEG_INSTALL_COMMAND = process.platform === "darwin"
|
|
96
|
+
? "brew install ffmpeg"
|
|
97
|
+
: process.platform === "win32"
|
|
98
|
+
? "winget install Gyan.FFmpeg"
|
|
99
|
+
: "sudo apt install ffmpeg";
|
|
100
|
+
/** Resolves + parses `--transcript`, shared by every input kind. */
|
|
101
|
+
function loadUserTranscript(transcriptPath) {
|
|
102
|
+
const resolved = resolve(transcriptPath);
|
|
103
|
+
if (!existsSync(resolved)) {
|
|
104
|
+
throw new ImportError("transcript_unreadable", `--transcript ${resolved} does not exist.`, `Check the path, or drop --transcript to use the provider's captions.`);
|
|
105
|
+
}
|
|
106
|
+
notify(`Reading the transcript from ${basename(resolved)}…`);
|
|
107
|
+
return parseTranscriptFile(resolved);
|
|
108
|
+
}
|
|
90
109
|
function notify(message) {
|
|
91
110
|
process.stderr.write(`${message}\n`);
|
|
92
111
|
}
|
|
@@ -119,22 +138,67 @@ function rerunCommand(target, opts) {
|
|
|
119
138
|
parts.push("--sync");
|
|
120
139
|
return parts.join(" ");
|
|
121
140
|
}
|
|
122
|
-
async function compileYoutube(url, opts) {
|
|
141
|
+
async function compileYoutube(url, videoId, opts) {
|
|
123
142
|
const bin = await resolveYtDlp(notify);
|
|
124
143
|
notify("Fetching video info…");
|
|
125
144
|
const meta = await fetchVideoMeta(bin, url);
|
|
145
|
+
// A zero duration is how YouTube's placeholder/consent stubs come back. They
|
|
146
|
+
// are not real videos, and compiling one produces an empty bundle attributed
|
|
147
|
+
// to a URL the user did ask for — worse than a refusal.
|
|
148
|
+
if (!meta.durationMs) {
|
|
149
|
+
throw new ImportError("invalid_url", `could not read this video: ${url} returned no duration. That usually means it is private, region-blocked, age-gated, members-only, or an unfinished live stream.`, `Open the URL in a browser to check it plays, or import a local copy: clipy context import ./<file> --transcript <file.vtt>`);
|
|
150
|
+
}
|
|
126
151
|
notify(`Found: "${meta.title}" (${fmtClock(meta.durationMs)})`);
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const
|
|
152
|
+
// providerId comes from the URL we parsed, not from yt-dlp's echo, so the
|
|
153
|
+
// manifest points at the video the user named even if metadata is partial.
|
|
154
|
+
const id = meta.id || videoId;
|
|
155
|
+
const source = {
|
|
156
|
+
kind: "youtube",
|
|
157
|
+
canonicalUrl: canonicalYoutubeUrl(id),
|
|
158
|
+
providerId: id,
|
|
159
|
+
};
|
|
160
|
+
// An explicit --transcript is the user overriding the provider, so YouTube's
|
|
161
|
+
// captions are never consulted — not even as a fallback.
|
|
162
|
+
if (opts.transcriptPath) {
|
|
163
|
+
const segments = loadUserTranscript(opts.transcriptPath);
|
|
164
|
+
notify(`Using your transcript file (${segments.length} segments) — skipping YouTube captions.`);
|
|
165
|
+
const transcript = buildNormalizedTranscript(segments, {
|
|
166
|
+
...(opts.language ? { language: opts.language } : {}),
|
|
167
|
+
source: "user_file",
|
|
168
|
+
durationMs: meta.durationMs || undefined,
|
|
169
|
+
});
|
|
170
|
+
return finish({
|
|
171
|
+
title: opts.title ?? meta.title,
|
|
172
|
+
source,
|
|
173
|
+
durationMs: meta.durationMs,
|
|
174
|
+
transcript,
|
|
175
|
+
fingerprint: `youtube:${id}`,
|
|
176
|
+
media: { kind: "youtube", url, ytDlpBin: bin, durationMs: meta.durationMs },
|
|
177
|
+
opts,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
let downloadFailure = null;
|
|
181
|
+
const captions = await fetchCaptions(bin, url, meta, {
|
|
182
|
+
...(opts.language ? { language: opts.language } : {}),
|
|
183
|
+
notify,
|
|
184
|
+
onFailure: (reason) => {
|
|
185
|
+
downloadFailure = reason;
|
|
186
|
+
},
|
|
187
|
+
});
|
|
130
188
|
if (!captions) {
|
|
189
|
+
// A listed track that refused to download is a different problem with a
|
|
190
|
+
// different fix, so it must not be reported as an absent track.
|
|
191
|
+
if (downloadFailure) {
|
|
192
|
+
const stale = looksLikeStaleBinary(downloadFailure);
|
|
193
|
+
throw new ImportError("no_captions", `the captions are listed but could not be downloaded: ${downloadFailure}`, stale
|
|
194
|
+
? `This looks like an out-of-date yt-dlp (an extraction failure, not a block). Update it — the managed copy self-updates, or run: yt-dlp -U`
|
|
195
|
+
: `If this is HTTP 429, YouTube is rate-limiting this machine — wait a few minutes and re-run. Otherwise supply your own captions: clipy context import <url> --transcript <file.vtt>`);
|
|
196
|
+
}
|
|
131
197
|
const available = [...new Set([...meta.subtitleLangs, ...meta.autoCaptionLangs])];
|
|
132
198
|
if (available.length > 0) {
|
|
133
|
-
throw new
|
|
199
|
+
throw new ImportError("no_captions", `this video has no captions in "${opts.language ?? "any usable language"}". Available: ${available.slice(0, 20).join(", ")}${available.length > 20 ? `, … (${available.length} total)` : ""}.`, `Re-run picking one of those: clipy context import <url> --language ${available[0]}`);
|
|
134
200
|
}
|
|
135
|
-
throw new
|
|
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.");
|
|
201
|
+
throw new ImportError("no_captions", "this video has no captions at all (neither creator-provided nor auto-generated).", `Supply your own: clipy context import <url> --transcript <file.vtt|file.srt|transcript.json>`);
|
|
138
202
|
}
|
|
139
203
|
const raw = captions.format === "json3"
|
|
140
204
|
? parseYoutubeJson3(JSON.parse(captions.text))
|
|
@@ -144,34 +208,38 @@ async function compileYoutube(url, opts) {
|
|
|
144
208
|
source: captions.source,
|
|
145
209
|
durationMs: meta.durationMs || undefined,
|
|
146
210
|
});
|
|
147
|
-
notify(`Got ${transcript.segments.length} caption segments (${captions
|
|
148
|
-
const source = {
|
|
149
|
-
kind: "youtube",
|
|
150
|
-
...(meta.id ? { canonicalUrl: `https://www.youtube.com/watch?v=${meta.id}`, providerId: meta.id } : {}),
|
|
151
|
-
};
|
|
211
|
+
notify(`Got ${transcript.segments.length} caption segments (${describeCaptions(captions)}).`);
|
|
152
212
|
return finish({
|
|
153
213
|
title: opts.title ?? meta.title,
|
|
154
214
|
source,
|
|
155
215
|
durationMs: meta.durationMs,
|
|
156
216
|
transcript,
|
|
157
|
-
fingerprint: `youtube:${
|
|
217
|
+
fingerprint: `youtube:${id}`,
|
|
158
218
|
media: { kind: "youtube", url, ytDlpBin: bin, durationMs: meta.durationMs },
|
|
159
219
|
opts,
|
|
160
220
|
});
|
|
161
221
|
}
|
|
162
222
|
async function compileLocal(path, opts) {
|
|
163
223
|
if (!opts.transcriptPath) {
|
|
164
|
-
throw new
|
|
165
|
-
" Local speech-to-text lands in a future release.");
|
|
224
|
+
throw new ImportError("no_captions", "local files need a transcript — Clipy cannot transcribe them yet.", `Re-run with a caption file: clipy context import ${JSON.stringify(path)} --transcript <file.vtt|file.srt|transcript.json>`);
|
|
166
225
|
}
|
|
167
|
-
const transcriptPath = resolve(opts.transcriptPath);
|
|
168
|
-
if (!existsSync(transcriptPath))
|
|
169
|
-
throw new Error(`--transcript ${transcriptPath} does not exist.`);
|
|
170
226
|
notify(`Probing ${basename(path)} with ffprobe…`);
|
|
171
|
-
|
|
227
|
+
let probe;
|
|
228
|
+
try {
|
|
229
|
+
probe = await probeVideo(path);
|
|
230
|
+
}
|
|
231
|
+
catch (e) {
|
|
232
|
+
const message = e.message;
|
|
233
|
+
if (/ffprobe was not found/i.test(message)) {
|
|
234
|
+
throw new ImportError("ffmpeg_missing", message, FFMPEG_INSTALL_COMMAND);
|
|
235
|
+
}
|
|
236
|
+
if (/no video stream/i.test(message)) {
|
|
237
|
+
throw new ImportError("no_video_stream", message, `Supply a file with a video track, or import the audio transcript-only with --no-frames.`);
|
|
238
|
+
}
|
|
239
|
+
throw new ImportError("source_unreadable", message, `Check the file plays, then re-run.`);
|
|
240
|
+
}
|
|
172
241
|
const contentHash = sha256File(path);
|
|
173
|
-
|
|
174
|
-
const segments = parseTranscriptFile(transcriptPath);
|
|
242
|
+
const segments = loadUserTranscript(opts.transcriptPath);
|
|
175
243
|
notify(`Got ${segments.length} transcript segments (${fmtClock(probe.durationMs)} of video).`);
|
|
176
244
|
const transcript = buildNormalizedTranscript(segments, {
|
|
177
245
|
...(opts.language ? { language: opts.language } : {}),
|
|
@@ -215,12 +283,13 @@ function finish(input) {
|
|
|
215
283
|
* fetched for it. recording.md is a pure function of the manifest plus the
|
|
216
284
|
* transcript, so re-rendering is the whole update.
|
|
217
285
|
*/
|
|
218
|
-
function withVisualEvidence(compiled, classification, frames) {
|
|
286
|
+
function withVisualEvidence(compiled, classification, frames, completeness) {
|
|
219
287
|
const manifest = {
|
|
220
288
|
...compiled.manifest,
|
|
221
289
|
profile: frames.length > 0 ? "visual" : compiled.manifest.profile,
|
|
222
290
|
serverClassification: classification,
|
|
223
291
|
...(frames.length > 0 ? { frames } : {}),
|
|
292
|
+
...(completeness ? { completeness } : {}),
|
|
224
293
|
};
|
|
225
294
|
return {
|
|
226
295
|
...compiled,
|
|
@@ -321,6 +390,9 @@ async function apiPost(opts, path, payload) {
|
|
|
321
390
|
signal: controller.signal,
|
|
322
391
|
});
|
|
323
392
|
}
|
|
393
|
+
catch (e) {
|
|
394
|
+
throw new ImportError("server_unreachable", `could not reach the Clipy API at ${opts.apiUrl}: ${e.message}`, `Check your network, then re-run. Without --sync the local bundle is still written and readable with: clipy context read <bundle>`);
|
|
395
|
+
}
|
|
324
396
|
finally {
|
|
325
397
|
clearTimeout(timer);
|
|
326
398
|
}
|
|
@@ -377,8 +449,7 @@ function parseClassification(raw, durationMs) {
|
|
|
377
449
|
}
|
|
378
450
|
async function sync(compiled, opts, bundlePath) {
|
|
379
451
|
if (!opts.apiKey) {
|
|
380
|
-
throw new
|
|
381
|
-
` Nothing was lost: the local bundle is already written to ${bundlePath}.`);
|
|
452
|
+
throw new ImportError("auth_required", `--sync needs an API key, and none is configured. The local bundle is already written to ${bundlePath}.`, "clipy login", { bundlePath });
|
|
382
453
|
}
|
|
383
454
|
const payload = {
|
|
384
455
|
idempotencyKey: slugHash(`${compiled.fingerprint}|${compiled.manifest.source.contentHash ?? ""}|${compiled.manifest.compiler.version}`),
|
|
@@ -395,21 +466,20 @@ async function sync(compiled, opts, bundlePath) {
|
|
|
395
466
|
// — so the local bundle is the user's intact fallback, and saying so is the
|
|
396
467
|
// difference between "it broke" and "here is what you still have".
|
|
397
468
|
const detail = typeof body.error === "string" ? body.error : `HTTP ${status}`;
|
|
398
|
-
const
|
|
469
|
+
const partial = { bundlePath };
|
|
399
470
|
if (status === 401) {
|
|
400
|
-
throw new
|
|
401
|
-
|
|
471
|
+
throw new ImportError("auth_required", `sync failed: ${detail}. Your local bundle is complete and unaffected: ${bundlePath}`, "clipy login", partial);
|
|
472
|
+
}
|
|
473
|
+
if (status === 403) {
|
|
474
|
+
throw new ImportError("wrong_scope", `sync failed: ${detail}. The key is valid but lacks the ingest scope. Your local bundle is complete and unaffected: ${bundlePath}`, "Mint a key with the ingest scope at https://clipy.online/settings/api-keys, then re-run with it.", partial);
|
|
402
475
|
}
|
|
403
476
|
if (status === 409) {
|
|
404
|
-
throw new
|
|
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}`);
|
|
477
|
+
throw new ImportError("content_conflict", `sync failed: ${detail}. That idempotency key already points at different content — this source changed since the last import. Your local bundle is complete and unaffected: ${bundlePath}`, "Delete the old document in your library, or import from a fresh copy.", partial);
|
|
407
478
|
}
|
|
408
479
|
if (status === 429) {
|
|
409
|
-
throw new
|
|
410
|
-
` You have hit today's ingest quota (it resets at 00:00 UTC). Re-run then.\n ${intact}`);
|
|
480
|
+
throw new ImportError("quota_exceeded", `sync failed: ${detail}. You have hit today's ingest quota (it resets at 00:00 UTC). Your local bundle is complete and unaffected: ${bundlePath}`, "Re-run after 00:00 UTC. Do not retry in a loop — it only burns the limit.", partial);
|
|
411
481
|
}
|
|
412
|
-
throw new
|
|
482
|
+
throw new ImportError("server_unreachable", `sync failed while uploading the transcript: ${detail}. Your local bundle is complete and unaffected: ${bundlePath}`, `Re-run the same command. The bundle is readable meanwhile: clipy context read ${bundlePath}`, partial);
|
|
413
483
|
}
|
|
414
484
|
return {
|
|
415
485
|
documentId: typeof body.id === "string" ? body.id : "",
|
|
@@ -483,15 +553,41 @@ async function collectFrames(compiled, timestampsMs, opts) {
|
|
|
483
553
|
export async function cmdContextImport(target, opts) {
|
|
484
554
|
const input = classifyInput(target);
|
|
485
555
|
if (input.kind === "url") {
|
|
486
|
-
throw new
|
|
556
|
+
throw new ImportError("invalid_url", "direct media URLs are not supported yet.", `Download the file first, then: clipy context import ./<file> --transcript <file.vtt>`);
|
|
487
557
|
}
|
|
488
|
-
let compiled = input.kind === "youtube" ? await compileYoutube(input.url, opts) : await compileLocal(input.path, opts);
|
|
558
|
+
let compiled = input.kind === "youtube" ? await compileYoutube(input.url, input.videoId, opts) : await compileLocal(input.path, opts);
|
|
489
559
|
const outputDir = resolve(opts.outputDir ?? process.cwd());
|
|
490
560
|
let { path: bundlePath, rewritten } = writeBundle(outputDir, compiled);
|
|
491
561
|
const report = compiled.manifest.sufficiency;
|
|
492
562
|
let synced = null;
|
|
493
563
|
let uploadedFrames = [];
|
|
494
564
|
let frameUpload = null;
|
|
565
|
+
// Everything that went wrong WITHOUT costing the user the import. These ride
|
|
566
|
+
// out on a successful (exit 0) result — an agent must not read a missing
|
|
567
|
+
// frame as a failed import.
|
|
568
|
+
const warnings = [];
|
|
569
|
+
/**
|
|
570
|
+
* The bundle outlives the run, and the warning envelope does not — so the
|
|
571
|
+
* verdict has to be written INTO the document. "Transcript-only because the
|
|
572
|
+
* words were enough" and "transcript-only because the frames failed" look
|
|
573
|
+
* identical on disk otherwise.
|
|
574
|
+
*/
|
|
575
|
+
const completenessOf = (classification,
|
|
576
|
+
/** Frames that reached the DOCUMENT — not merely the local bundle. A failed
|
|
577
|
+
* upload leaves the images on disk but the document still can't show them. */
|
|
578
|
+
attachedFrames = 0) => {
|
|
579
|
+
const planned = classification.needsVisual ? classification.frameTimestampsMs.length : 0;
|
|
580
|
+
const missing = Math.max(0, planned - attachedFrames);
|
|
581
|
+
if (missing === 0)
|
|
582
|
+
return { status: "complete" };
|
|
583
|
+
const cause = warnings[0];
|
|
584
|
+
return {
|
|
585
|
+
status: "incomplete",
|
|
586
|
+
missingFrames: missing,
|
|
587
|
+
...(cause ? { reasonCode: cause.code, reason: cause.error } : {}),
|
|
588
|
+
rerunCommand: rerunCommand(target, opts),
|
|
589
|
+
};
|
|
590
|
+
};
|
|
495
591
|
if (opts.sync) {
|
|
496
592
|
// Phase 1: the transcript bundle goes up, the verdict comes back.
|
|
497
593
|
synced = await sync(compiled, opts, bundlePath);
|
|
@@ -518,6 +614,17 @@ export async function cmdContextImport(target, opts) {
|
|
|
518
614
|
// Phase 2: fetch only the moments the server named.
|
|
519
615
|
const { frames, workDir, failure } = await collectFrames(compiled, classification.frameTimestampsMs, opts);
|
|
520
616
|
if (failure) {
|
|
617
|
+
warnings.push({
|
|
618
|
+
code: /403/.test(failure)
|
|
619
|
+
? "ytdlp_download_403"
|
|
620
|
+
: /ffmpeg|ffprobe/i.test(failure)
|
|
621
|
+
? "ffmpeg_missing"
|
|
622
|
+
: "frames_upload_failed",
|
|
623
|
+
error: `frames could not be extracted: ${failure.split("\n")[0]}`,
|
|
624
|
+
remediation: /ffmpeg|ffprobe/i.test(failure)
|
|
625
|
+
? FFMPEG_INSTALL_COMMAND
|
|
626
|
+
: rerunCommand(target, opts),
|
|
627
|
+
});
|
|
521
628
|
// Phase 1 already succeeded — this is a PARTIAL success, and saying
|
|
522
629
|
// "failed" here would send the user hunting for a document that is
|
|
523
630
|
// sitting in their library right now.
|
|
@@ -536,6 +643,11 @@ export async function cmdContextImport(target, opts) {
|
|
|
536
643
|
notify(`Frames attached ✓ — ${frameUpload.added} new (${frameUpload.total} on the document).`);
|
|
537
644
|
}
|
|
538
645
|
catch (e) {
|
|
646
|
+
warnings.push({
|
|
647
|
+
code: "frames_upload_failed",
|
|
648
|
+
error: `the frames were cut but ${e.message}`,
|
|
649
|
+
remediation: rerunCommand(target, opts),
|
|
650
|
+
});
|
|
539
651
|
// Same partial-success rule as a failed extraction: the document
|
|
540
652
|
// exists, only the pictures are missing.
|
|
541
653
|
notify(`The frames were cut but ${e.message}\n` +
|
|
@@ -546,6 +658,11 @@ export async function cmdContextImport(target, opts) {
|
|
|
546
658
|
}
|
|
547
659
|
}
|
|
548
660
|
else if (frames.length > 0) {
|
|
661
|
+
warnings.push({
|
|
662
|
+
code: "frames_upload_failed",
|
|
663
|
+
error: "frames were extracted but the server returned no document id, so they were not uploaded.",
|
|
664
|
+
remediation: rerunCommand(target, opts),
|
|
665
|
+
});
|
|
549
666
|
notify("frames were extracted but the server returned no document id, so they were not uploaded.");
|
|
550
667
|
}
|
|
551
668
|
// Regenerate the LOCAL bundle around the verdict + the frames.
|
|
@@ -559,7 +676,9 @@ export async function cmdContextImport(target, opts) {
|
|
|
559
676
|
...(f.height ? { height: f.height } : {}),
|
|
560
677
|
...(caption ? { caption } : {}),
|
|
561
678
|
};
|
|
562
|
-
})
|
|
679
|
+
}),
|
|
680
|
+
// frameUpload is set only when the server accepted them.
|
|
681
|
+
completenessOf(classification, frameUpload ? uploadedFrames.length : 0));
|
|
563
682
|
({ path: bundlePath } = writeBundle(outputDir, compiled, uploadedFrames));
|
|
564
683
|
}
|
|
565
684
|
finally {
|
|
@@ -569,25 +688,43 @@ export async function cmdContextImport(target, opts) {
|
|
|
569
688
|
}
|
|
570
689
|
// Even with no frames, the verdict itself belongs in the bundle.
|
|
571
690
|
if (uploadedFrames.length === 0) {
|
|
572
|
-
compiled = withVisualEvidence(compiled, classification, []);
|
|
691
|
+
compiled = withVisualEvidence(compiled, classification, [], completenessOf(classification));
|
|
573
692
|
({ path: bundlePath } = writeBundle(outputDir, compiled));
|
|
574
693
|
}
|
|
575
694
|
}
|
|
576
695
|
}
|
|
577
696
|
if (opts.json) {
|
|
578
697
|
process.stdout.write(`${JSON.stringify({
|
|
698
|
+
ok: true,
|
|
579
699
|
bundlePath,
|
|
700
|
+
// The file an agent should actually open. Naming the directory alone
|
|
701
|
+
// makes every caller guess at the entry point.
|
|
702
|
+
contextPath: join(bundlePath, "recording.md"),
|
|
703
|
+
title: compiled.manifest.title,
|
|
580
704
|
profile: compiled.manifest.profile,
|
|
581
705
|
recommendedProfile: report?.recommendedProfile ?? null,
|
|
582
706
|
overallScore: report?.overallScore ?? null,
|
|
583
707
|
gapCount: report?.gaps.length ?? 0,
|
|
584
708
|
...(synced ? { synced: true, publicId: synced.publicId } : opts.sync ? { synced: false } : {}),
|
|
709
|
+
...(synced?.folderName ? { folderName: synced.folderName } : {}),
|
|
585
710
|
classification: synced?.classification ?? null,
|
|
586
711
|
frames: uploadedFrames.length,
|
|
587
712
|
...(frameUpload ? { framesAdded: frameUpload.added, framesTotal: frameUpload.total } : {}),
|
|
713
|
+
warnings,
|
|
588
714
|
}, null, 2)}\n`);
|
|
589
715
|
return;
|
|
590
716
|
}
|
|
717
|
+
// The headline. A user who ran one command should not have to assemble "did
|
|
718
|
+
// it work, and where is it" out of four key-value lines.
|
|
719
|
+
process.stdout.write(`\nYour agent-ready context for ${JSON.stringify(compiled.manifest.title)} is ready.\n`);
|
|
720
|
+
process.stdout.write(` → local bundle: ${join(bundlePath, "recording.md")} (point your agent here, or run: clipy context read ${bundlePath})\n`);
|
|
721
|
+
if (synced) {
|
|
722
|
+
process.stdout.write(` → in your Clipy library: filed under ${JSON.stringify(synced.folderName ?? "Knowledge Base")} — searchable, and readable by agents via MCP (read_context_document ${synced.publicId})\n`);
|
|
723
|
+
}
|
|
724
|
+
if (warnings.length > 0) {
|
|
725
|
+
process.stdout.write(` → incomplete: ${warnings.map((w) => w.error).join("; ")}\n to finish it: ${warnings[0].remediation}\n`);
|
|
726
|
+
}
|
|
727
|
+
process.stdout.write("\n");
|
|
591
728
|
process.stdout.write(`bundle: ${bundlePath}${rewritten ? " (rewritten — source content changed)" : ""}\n`);
|
|
592
729
|
if (synced?.classification) {
|
|
593
730
|
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`);
|
|
@@ -605,5 +742,4 @@ export async function cmdContextImport(target, opts) {
|
|
|
605
742
|
if (synced) {
|
|
606
743
|
process.stdout.write(`synced: ${synced.publicId} (private — only you can read it${synced.folderName ? `, filed in ${synced.folderName}` : ""})\n`);
|
|
607
744
|
}
|
|
608
|
-
process.stdout.write(`next: clipy context read ${bundlePath}\n`);
|
|
609
745
|
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which yt-dlp failures are worth trying again.
|
|
3
|
+
*
|
|
4
|
+
* YouTube hands out media URLs that expire, and it throttles bursts. Both show
|
|
5
|
+
* up as an HTTP 403 on a command that succeeds verbatim a few seconds later —
|
|
6
|
+
* so a single attempt turns a hiccup into "frames could not be extracted".
|
|
7
|
+
* Against that, a genuinely unavailable video must fail on the first try:
|
|
8
|
+
* retrying a private video three times just makes the user wait longer for the
|
|
9
|
+
* same answer.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* Failures no client change or retry can fix. Checked FIRST, ahead of the 403
|
|
13
|
+
* test, because YouTube sometimes wraps these in a 403 — and retrying a bot
|
|
14
|
+
* check or an age gate burns the user's IP reputation for nothing.
|
|
15
|
+
*/
|
|
16
|
+
const FATAL_MARKERS = [
|
|
17
|
+
/Sign in to confirm you.?re not a bot/i,
|
|
18
|
+
/Sign in to confirm your age/i,
|
|
19
|
+
/This video is unavailable/i,
|
|
20
|
+
/Video unavailable/i,
|
|
21
|
+
/Private video/i,
|
|
22
|
+
/members-only/i,
|
|
23
|
+
/age.?restricted/i,
|
|
24
|
+
];
|
|
25
|
+
const FORBIDDEN = /HTTP Error 403|\b403 Forbidden\b/i;
|
|
26
|
+
const TRANSIENT = [
|
|
27
|
+
/HTTP Error 5\d\d/i,
|
|
28
|
+
/HTTP Error 429/i,
|
|
29
|
+
/\btimed out\b/i,
|
|
30
|
+
/\btimeout\b/i,
|
|
31
|
+
/connection reset/i,
|
|
32
|
+
/ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENETUNREACH/,
|
|
33
|
+
/temporary failure/i,
|
|
34
|
+
/unable to connect/i,
|
|
35
|
+
/remote end closed connection/i,
|
|
36
|
+
];
|
|
37
|
+
/**
|
|
38
|
+
* Classifies yt-dlp's stderr. Only ever called on yt-dlp's OWN output — our
|
|
39
|
+
* local aborts (the size ceiling, our 20-minute cap) are fatal by construction
|
|
40
|
+
* and must not be routed through here, or a slow link would be retried for an
|
|
41
|
+
* hour.
|
|
42
|
+
*/
|
|
43
|
+
export function classifyFailure(stderr) {
|
|
44
|
+
if (FATAL_MARKERS.some((re) => re.test(stderr)))
|
|
45
|
+
return "fatal";
|
|
46
|
+
if (FORBIDDEN.test(stderr))
|
|
47
|
+
return "forbidden";
|
|
48
|
+
if (TRANSIENT.some((re) => re.test(stderr)))
|
|
49
|
+
return "transient";
|
|
50
|
+
return "fatal";
|
|
51
|
+
}
|
|
52
|
+
export function isRetriable(kind) {
|
|
53
|
+
return kind !== "fatal";
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A stale binary and a transient 403 look nothing alike once you know where to
|
|
57
|
+
* look: a 403 fails mid-transfer with formats already resolved, while an
|
|
58
|
+
* outdated yt-dlp fails during EXTRACTION — it cannot solve the signature
|
|
59
|
+
* challenge or is being forced onto SABR. Only the second is fixed by updating,
|
|
60
|
+
* so only the second should suggest it.
|
|
61
|
+
*/
|
|
62
|
+
const STALE_BINARY_MARKERS = [
|
|
63
|
+
/unable to extract/i,
|
|
64
|
+
/Only images are available/i,
|
|
65
|
+
/Signature extraction failed/i,
|
|
66
|
+
/n challenge/i,
|
|
67
|
+
/nsig extraction failed/i,
|
|
68
|
+
/forcing SABR/i,
|
|
69
|
+
/Requested format is not available/i,
|
|
70
|
+
/no video formats found/i,
|
|
71
|
+
];
|
|
72
|
+
export function looksLikeStaleBinary(stderr) {
|
|
73
|
+
return STALE_BINARY_MARKERS.some((re) => re.test(stderr));
|
|
74
|
+
}
|
|
75
|
+
/** How a retry is announced, so every caller says it the same way. */
|
|
76
|
+
export function retryNotice(stderr, kind, attempt, total) {
|
|
77
|
+
const what = kind === "forbidden"
|
|
78
|
+
? "Download blocked (HTTP 403)"
|
|
79
|
+
: `Download failed (${firstUsefulLine(stderr)})`;
|
|
80
|
+
return `${what} — retrying (${attempt}/${total})…`;
|
|
81
|
+
}
|
|
82
|
+
function firstUsefulLine(stderr) {
|
|
83
|
+
const line = stderr.trim().split("\n").filter(Boolean).pop() ?? "unknown error";
|
|
84
|
+
return line.replace(/^ERROR:\s*/i, "").slice(0, 120);
|
|
85
|
+
}
|
|
86
|
+
export function sleep(ms) {
|
|
87
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
88
|
+
}
|
|
89
|
+
/** Backoff between attempts 1→2 and 2→3. The observed recovery window for an
|
|
90
|
+
* expired media URL is "a minute later", so these are deliberately unhurried. */
|
|
91
|
+
export const RETRY_BACKOFF_MS = [3_000, 8_000];
|
|
92
|
+
export const MAX_ATTEMPTS = 3;
|
|
93
|
+
/**
|
|
94
|
+
* On every attempt. Letting yt-dlp retry a mid-transfer 403 in-process is far
|
|
95
|
+
* cheaper than re-running the binary, and pacing the extraction burst is what
|
|
96
|
+
* keeps a residential IP from reading as automation. Concurrency stays at 1 —
|
|
97
|
+
* we fetch one bounded rendition once, so there is nothing to win by raising it
|
|
98
|
+
* and a rate-limit to lose.
|
|
99
|
+
*/
|
|
100
|
+
export const BASELINE_DOWNLOAD_ARGS = [
|
|
101
|
+
"--retries", "5",
|
|
102
|
+
"--fragment-retries", "5",
|
|
103
|
+
"--extractor-retries", "3",
|
|
104
|
+
"--retry-sleep", "http:exp=1:30",
|
|
105
|
+
"--retry-sleep", "fragment:exp=1:30",
|
|
106
|
+
"--sleep-requests", "0.75",
|
|
107
|
+
"--concurrent-fragments", "1",
|
|
108
|
+
];
|
|
109
|
+
/**
|
|
110
|
+
* The client fallback, used only after the defaults have failed repeatedly.
|
|
111
|
+
*
|
|
112
|
+
* These three need no PO token and (for tv/android_vr) no JS runtime, unlike
|
|
113
|
+
* `android`, which is PO-token-gated and is NOT in yt-dlp's default set —
|
|
114
|
+
* falling back to it moves away from token-free clients rather than toward
|
|
115
|
+
* them. See docs/research/2026-07-29-ytdlp-403-fallbacks.md §2.
|
|
116
|
+
*/
|
|
117
|
+
export const TOKEN_FREE_CLIENT_ARGS = [
|
|
118
|
+
"--extractor-args",
|
|
119
|
+
"youtube:player_client=tv,android_vr,web_embedded",
|
|
120
|
+
];
|
|
121
|
+
/**
|
|
122
|
+
* Last resort: a pre-muxed progressive file is served as one conventional HTTP
|
|
123
|
+
* download, sidestepping both adaptive-fragment 403s and SABR. Format 18 is
|
|
124
|
+
* 360p — worse than our 720p target, and far better than no frames at all.
|
|
125
|
+
*/
|
|
126
|
+
export const PROGRESSIVE_FALLBACK = {
|
|
127
|
+
format: "b[height<=720]/18",
|
|
128
|
+
extraArgs: ["--extractor-args", "youtube:player_client=tv,android_vr"],
|
|
129
|
+
};
|
|
130
|
+
export const DEFAULT_FORMAT = "bv*[height<=720]/b[height<=720]";
|