@clipy/cli 0.9.1 → 0.9.3
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 +202 -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 +102 -0
- 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,45 @@ 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
|
+
// The web app and the API share an origin in every real deployment; strip any
|
|
21
|
+
// trailing slash so the printed URL is clean.
|
|
22
|
+
function webOriginFromApiUrl(apiUrl) {
|
|
23
|
+
return apiUrl.replace(/\/+$/, "");
|
|
24
|
+
}
|
|
25
|
+
import { ImportError } from "./errors.js";
|
|
26
|
+
import { looksLikeStaleBinary } from "./retry.js";
|
|
19
27
|
import { probeVideo } from "./probe.js";
|
|
20
28
|
import { extractFrames } from "./frames.js";
|
|
21
29
|
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
30
|
function classifyInput(raw) {
|
|
31
31
|
const trimmed = raw.trim();
|
|
32
|
+
// Shell-escaped input (`watch\?v\=…`) still has to be recognised as YouTube,
|
|
33
|
+
// so host detection runs on the de-escaped string.
|
|
34
|
+
const unescaped = trimmed.replace(/\\/g, "");
|
|
32
35
|
let parsed = null;
|
|
33
36
|
try {
|
|
34
|
-
parsed = new URL(
|
|
37
|
+
parsed = new URL(unescaped);
|
|
35
38
|
}
|
|
36
39
|
catch {
|
|
37
40
|
parsed = null;
|
|
38
41
|
}
|
|
39
42
|
if (parsed && (parsed.protocol === "http:" || parsed.protocol === "https:")) {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
43
|
+
if (isYoutubeHost(parsed.hostname)) {
|
|
44
|
+
const videoId = parseYoutubeId(trimmed);
|
|
45
|
+
if (!videoId) {
|
|
46
|
+
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).`);
|
|
47
|
+
}
|
|
48
|
+
// Everything downstream uses the canonical URL — never the raw input.
|
|
49
|
+
return { kind: "youtube", url: canonicalYoutubeUrl(videoId), videoId };
|
|
50
|
+
}
|
|
51
|
+
return { kind: "url", url: unescaped };
|
|
44
52
|
}
|
|
45
53
|
const path = resolve(trimmed);
|
|
46
54
|
if (existsSync(path) && statSync(path).isFile())
|
|
47
55
|
return { kind: "local", path };
|
|
48
|
-
throw new
|
|
56
|
+
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
57
|
}
|
|
50
58
|
function sha256File(path) {
|
|
51
59
|
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
@@ -62,7 +70,7 @@ function parseTranscriptFile(path) {
|
|
|
62
70
|
parsed = JSON.parse(text);
|
|
63
71
|
}
|
|
64
72
|
catch {
|
|
65
|
-
throw new
|
|
73
|
+
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
74
|
}
|
|
67
75
|
// json3 (YouTube) and Clipy transcript JSON both land here.
|
|
68
76
|
const json3 = parseYoutubeJson3(parsed);
|
|
@@ -70,7 +78,7 @@ function parseTranscriptFile(path) {
|
|
|
70
78
|
return json3;
|
|
71
79
|
const raw = parsed.segments;
|
|
72
80
|
if (!Array.isArray(raw)) {
|
|
73
|
-
throw new
|
|
81
|
+
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
82
|
}
|
|
75
83
|
const segments = [];
|
|
76
84
|
for (const item of raw) {
|
|
@@ -83,10 +91,26 @@ function parseTranscriptFile(path) {
|
|
|
83
91
|
continue;
|
|
84
92
|
segments.push({ startMs, endMs: Number.isFinite(endMs) ? endMs : startMs, text: value });
|
|
85
93
|
}
|
|
86
|
-
if (segments.length === 0)
|
|
87
|
-
throw new
|
|
94
|
+
if (segments.length === 0) {
|
|
95
|
+
throw new ImportError("transcript_unreadable", `--transcript ${path} has no usable segments.`, `Supply WebVTT (.vtt), SubRip (.srt), or Clipy transcript JSON ({"segments":[{"startMs","endMs","text"}]}).`);
|
|
96
|
+
}
|
|
88
97
|
return segments;
|
|
89
98
|
}
|
|
99
|
+
/** Platform-correct, runnable verbatim — an agent should be able to paste it. */
|
|
100
|
+
const FFMPEG_INSTALL_COMMAND = process.platform === "darwin"
|
|
101
|
+
? "brew install ffmpeg"
|
|
102
|
+
: process.platform === "win32"
|
|
103
|
+
? "winget install Gyan.FFmpeg"
|
|
104
|
+
: "sudo apt install ffmpeg";
|
|
105
|
+
/** Resolves + parses `--transcript`, shared by every input kind. */
|
|
106
|
+
function loadUserTranscript(transcriptPath) {
|
|
107
|
+
const resolved = resolve(transcriptPath);
|
|
108
|
+
if (!existsSync(resolved)) {
|
|
109
|
+
throw new ImportError("transcript_unreadable", `--transcript ${resolved} does not exist.`, `Check the path, or drop --transcript to use the provider's captions.`);
|
|
110
|
+
}
|
|
111
|
+
notify(`Reading the transcript from ${basename(resolved)}…`);
|
|
112
|
+
return parseTranscriptFile(resolved);
|
|
113
|
+
}
|
|
90
114
|
function notify(message) {
|
|
91
115
|
process.stderr.write(`${message}\n`);
|
|
92
116
|
}
|
|
@@ -119,22 +143,67 @@ function rerunCommand(target, opts) {
|
|
|
119
143
|
parts.push("--sync");
|
|
120
144
|
return parts.join(" ");
|
|
121
145
|
}
|
|
122
|
-
async function compileYoutube(url, opts) {
|
|
146
|
+
async function compileYoutube(url, videoId, opts) {
|
|
123
147
|
const bin = await resolveYtDlp(notify);
|
|
124
148
|
notify("Fetching video info…");
|
|
125
149
|
const meta = await fetchVideoMeta(bin, url);
|
|
150
|
+
// A zero duration is how YouTube's placeholder/consent stubs come back. They
|
|
151
|
+
// are not real videos, and compiling one produces an empty bundle attributed
|
|
152
|
+
// to a URL the user did ask for — worse than a refusal.
|
|
153
|
+
if (!meta.durationMs) {
|
|
154
|
+
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>`);
|
|
155
|
+
}
|
|
126
156
|
notify(`Found: "${meta.title}" (${fmtClock(meta.durationMs)})`);
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
const
|
|
157
|
+
// providerId comes from the URL we parsed, not from yt-dlp's echo, so the
|
|
158
|
+
// manifest points at the video the user named even if metadata is partial.
|
|
159
|
+
const id = meta.id || videoId;
|
|
160
|
+
const source = {
|
|
161
|
+
kind: "youtube",
|
|
162
|
+
canonicalUrl: canonicalYoutubeUrl(id),
|
|
163
|
+
providerId: id,
|
|
164
|
+
};
|
|
165
|
+
// An explicit --transcript is the user overriding the provider, so YouTube's
|
|
166
|
+
// captions are never consulted — not even as a fallback.
|
|
167
|
+
if (opts.transcriptPath) {
|
|
168
|
+
const segments = loadUserTranscript(opts.transcriptPath);
|
|
169
|
+
notify(`Using your transcript file (${segments.length} segments) — skipping YouTube captions.`);
|
|
170
|
+
const transcript = buildNormalizedTranscript(segments, {
|
|
171
|
+
...(opts.language ? { language: opts.language } : {}),
|
|
172
|
+
source: "user_file",
|
|
173
|
+
durationMs: meta.durationMs || undefined,
|
|
174
|
+
});
|
|
175
|
+
return finish({
|
|
176
|
+
title: opts.title ?? meta.title,
|
|
177
|
+
source,
|
|
178
|
+
durationMs: meta.durationMs,
|
|
179
|
+
transcript,
|
|
180
|
+
fingerprint: `youtube:${id}`,
|
|
181
|
+
media: { kind: "youtube", url, ytDlpBin: bin, durationMs: meta.durationMs },
|
|
182
|
+
opts,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
let downloadFailure = null;
|
|
186
|
+
const captions = await fetchCaptions(bin, url, meta, {
|
|
187
|
+
...(opts.language ? { language: opts.language } : {}),
|
|
188
|
+
notify,
|
|
189
|
+
onFailure: (reason) => {
|
|
190
|
+
downloadFailure = reason;
|
|
191
|
+
},
|
|
192
|
+
});
|
|
130
193
|
if (!captions) {
|
|
194
|
+
// A listed track that refused to download is a different problem with a
|
|
195
|
+
// different fix, so it must not be reported as an absent track.
|
|
196
|
+
if (downloadFailure) {
|
|
197
|
+
const stale = looksLikeStaleBinary(downloadFailure);
|
|
198
|
+
throw new ImportError("no_captions", `the captions are listed but could not be downloaded: ${downloadFailure}`, stale
|
|
199
|
+
? `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`
|
|
200
|
+
: `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>`);
|
|
201
|
+
}
|
|
131
202
|
const available = [...new Set([...meta.subtitleLangs, ...meta.autoCaptionLangs])];
|
|
132
203
|
if (available.length > 0) {
|
|
133
|
-
throw new
|
|
204
|
+
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
205
|
}
|
|
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.");
|
|
206
|
+
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
207
|
}
|
|
139
208
|
const raw = captions.format === "json3"
|
|
140
209
|
? parseYoutubeJson3(JSON.parse(captions.text))
|
|
@@ -144,34 +213,38 @@ async function compileYoutube(url, opts) {
|
|
|
144
213
|
source: captions.source,
|
|
145
214
|
durationMs: meta.durationMs || undefined,
|
|
146
215
|
});
|
|
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
|
-
};
|
|
216
|
+
notify(`Got ${transcript.segments.length} caption segments (${describeCaptions(captions)}).`);
|
|
152
217
|
return finish({
|
|
153
218
|
title: opts.title ?? meta.title,
|
|
154
219
|
source,
|
|
155
220
|
durationMs: meta.durationMs,
|
|
156
221
|
transcript,
|
|
157
|
-
fingerprint: `youtube:${
|
|
222
|
+
fingerprint: `youtube:${id}`,
|
|
158
223
|
media: { kind: "youtube", url, ytDlpBin: bin, durationMs: meta.durationMs },
|
|
159
224
|
opts,
|
|
160
225
|
});
|
|
161
226
|
}
|
|
162
227
|
async function compileLocal(path, opts) {
|
|
163
228
|
if (!opts.transcriptPath) {
|
|
164
|
-
throw new
|
|
165
|
-
" Local speech-to-text lands in a future release.");
|
|
229
|
+
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
230
|
}
|
|
167
|
-
const transcriptPath = resolve(opts.transcriptPath);
|
|
168
|
-
if (!existsSync(transcriptPath))
|
|
169
|
-
throw new Error(`--transcript ${transcriptPath} does not exist.`);
|
|
170
231
|
notify(`Probing ${basename(path)} with ffprobe…`);
|
|
171
|
-
|
|
232
|
+
let probe;
|
|
233
|
+
try {
|
|
234
|
+
probe = await probeVideo(path);
|
|
235
|
+
}
|
|
236
|
+
catch (e) {
|
|
237
|
+
const message = e.message;
|
|
238
|
+
if (/ffprobe was not found/i.test(message)) {
|
|
239
|
+
throw new ImportError("ffmpeg_missing", message, FFMPEG_INSTALL_COMMAND);
|
|
240
|
+
}
|
|
241
|
+
if (/no video stream/i.test(message)) {
|
|
242
|
+
throw new ImportError("no_video_stream", message, `Supply a file with a video track, or import the audio transcript-only with --no-frames.`);
|
|
243
|
+
}
|
|
244
|
+
throw new ImportError("source_unreadable", message, `Check the file plays, then re-run.`);
|
|
245
|
+
}
|
|
172
246
|
const contentHash = sha256File(path);
|
|
173
|
-
|
|
174
|
-
const segments = parseTranscriptFile(transcriptPath);
|
|
247
|
+
const segments = loadUserTranscript(opts.transcriptPath);
|
|
175
248
|
notify(`Got ${segments.length} transcript segments (${fmtClock(probe.durationMs)} of video).`);
|
|
176
249
|
const transcript = buildNormalizedTranscript(segments, {
|
|
177
250
|
...(opts.language ? { language: opts.language } : {}),
|
|
@@ -215,12 +288,13 @@ function finish(input) {
|
|
|
215
288
|
* fetched for it. recording.md is a pure function of the manifest plus the
|
|
216
289
|
* transcript, so re-rendering is the whole update.
|
|
217
290
|
*/
|
|
218
|
-
function withVisualEvidence(compiled, classification, frames) {
|
|
291
|
+
function withVisualEvidence(compiled, classification, frames, completeness) {
|
|
219
292
|
const manifest = {
|
|
220
293
|
...compiled.manifest,
|
|
221
294
|
profile: frames.length > 0 ? "visual" : compiled.manifest.profile,
|
|
222
295
|
serverClassification: classification,
|
|
223
296
|
...(frames.length > 0 ? { frames } : {}),
|
|
297
|
+
...(completeness ? { completeness } : {}),
|
|
224
298
|
};
|
|
225
299
|
return {
|
|
226
300
|
...compiled,
|
|
@@ -321,6 +395,9 @@ async function apiPost(opts, path, payload) {
|
|
|
321
395
|
signal: controller.signal,
|
|
322
396
|
});
|
|
323
397
|
}
|
|
398
|
+
catch (e) {
|
|
399
|
+
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>`);
|
|
400
|
+
}
|
|
324
401
|
finally {
|
|
325
402
|
clearTimeout(timer);
|
|
326
403
|
}
|
|
@@ -377,8 +454,7 @@ function parseClassification(raw, durationMs) {
|
|
|
377
454
|
}
|
|
378
455
|
async function sync(compiled, opts, bundlePath) {
|
|
379
456
|
if (!opts.apiKey) {
|
|
380
|
-
throw new
|
|
381
|
-
` Nothing was lost: the local bundle is already written to ${bundlePath}.`);
|
|
457
|
+
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
458
|
}
|
|
383
459
|
const payload = {
|
|
384
460
|
idempotencyKey: slugHash(`${compiled.fingerprint}|${compiled.manifest.source.contentHash ?? ""}|${compiled.manifest.compiler.version}`),
|
|
@@ -395,21 +471,20 @@ async function sync(compiled, opts, bundlePath) {
|
|
|
395
471
|
// — so the local bundle is the user's intact fallback, and saying so is the
|
|
396
472
|
// difference between "it broke" and "here is what you still have".
|
|
397
473
|
const detail = typeof body.error === "string" ? body.error : `HTTP ${status}`;
|
|
398
|
-
const
|
|
474
|
+
const partial = { bundlePath };
|
|
399
475
|
if (status === 401) {
|
|
400
|
-
throw new
|
|
401
|
-
|
|
476
|
+
throw new ImportError("auth_required", `sync failed: ${detail}. Your local bundle is complete and unaffected: ${bundlePath}`, "clipy login", partial);
|
|
477
|
+
}
|
|
478
|
+
if (status === 403) {
|
|
479
|
+
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
480
|
}
|
|
403
481
|
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}`);
|
|
482
|
+
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
483
|
}
|
|
408
484
|
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}`);
|
|
485
|
+
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
486
|
}
|
|
412
|
-
throw new
|
|
487
|
+
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
488
|
}
|
|
414
489
|
return {
|
|
415
490
|
documentId: typeof body.id === "string" ? body.id : "",
|
|
@@ -483,15 +558,41 @@ async function collectFrames(compiled, timestampsMs, opts) {
|
|
|
483
558
|
export async function cmdContextImport(target, opts) {
|
|
484
559
|
const input = classifyInput(target);
|
|
485
560
|
if (input.kind === "url") {
|
|
486
|
-
throw new
|
|
561
|
+
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
562
|
}
|
|
488
|
-
let compiled = input.kind === "youtube" ? await compileYoutube(input.url, opts) : await compileLocal(input.path, opts);
|
|
563
|
+
let compiled = input.kind === "youtube" ? await compileYoutube(input.url, input.videoId, opts) : await compileLocal(input.path, opts);
|
|
489
564
|
const outputDir = resolve(opts.outputDir ?? process.cwd());
|
|
490
565
|
let { path: bundlePath, rewritten } = writeBundle(outputDir, compiled);
|
|
491
566
|
const report = compiled.manifest.sufficiency;
|
|
492
567
|
let synced = null;
|
|
493
568
|
let uploadedFrames = [];
|
|
494
569
|
let frameUpload = null;
|
|
570
|
+
// Everything that went wrong WITHOUT costing the user the import. These ride
|
|
571
|
+
// out on a successful (exit 0) result — an agent must not read a missing
|
|
572
|
+
// frame as a failed import.
|
|
573
|
+
const warnings = [];
|
|
574
|
+
/**
|
|
575
|
+
* The bundle outlives the run, and the warning envelope does not — so the
|
|
576
|
+
* verdict has to be written INTO the document. "Transcript-only because the
|
|
577
|
+
* words were enough" and "transcript-only because the frames failed" look
|
|
578
|
+
* identical on disk otherwise.
|
|
579
|
+
*/
|
|
580
|
+
const completenessOf = (classification,
|
|
581
|
+
/** Frames that reached the DOCUMENT — not merely the local bundle. A failed
|
|
582
|
+
* upload leaves the images on disk but the document still can't show them. */
|
|
583
|
+
attachedFrames = 0) => {
|
|
584
|
+
const planned = classification.needsVisual ? classification.frameTimestampsMs.length : 0;
|
|
585
|
+
const missing = Math.max(0, planned - attachedFrames);
|
|
586
|
+
if (missing === 0)
|
|
587
|
+
return { status: "complete" };
|
|
588
|
+
const cause = warnings[0];
|
|
589
|
+
return {
|
|
590
|
+
status: "incomplete",
|
|
591
|
+
missingFrames: missing,
|
|
592
|
+
...(cause ? { reasonCode: cause.code, reason: cause.error } : {}),
|
|
593
|
+
rerunCommand: rerunCommand(target, opts),
|
|
594
|
+
};
|
|
595
|
+
};
|
|
495
596
|
if (opts.sync) {
|
|
496
597
|
// Phase 1: the transcript bundle goes up, the verdict comes back.
|
|
497
598
|
synced = await sync(compiled, opts, bundlePath);
|
|
@@ -518,6 +619,17 @@ export async function cmdContextImport(target, opts) {
|
|
|
518
619
|
// Phase 2: fetch only the moments the server named.
|
|
519
620
|
const { frames, workDir, failure } = await collectFrames(compiled, classification.frameTimestampsMs, opts);
|
|
520
621
|
if (failure) {
|
|
622
|
+
warnings.push({
|
|
623
|
+
code: /403/.test(failure)
|
|
624
|
+
? "ytdlp_download_403"
|
|
625
|
+
: /ffmpeg|ffprobe/i.test(failure)
|
|
626
|
+
? "ffmpeg_missing"
|
|
627
|
+
: "frames_upload_failed",
|
|
628
|
+
error: `frames could not be extracted: ${failure.split("\n")[0]}`,
|
|
629
|
+
remediation: /ffmpeg|ffprobe/i.test(failure)
|
|
630
|
+
? FFMPEG_INSTALL_COMMAND
|
|
631
|
+
: rerunCommand(target, opts),
|
|
632
|
+
});
|
|
521
633
|
// Phase 1 already succeeded — this is a PARTIAL success, and saying
|
|
522
634
|
// "failed" here would send the user hunting for a document that is
|
|
523
635
|
// sitting in their library right now.
|
|
@@ -536,6 +648,11 @@ export async function cmdContextImport(target, opts) {
|
|
|
536
648
|
notify(`Frames attached ✓ — ${frameUpload.added} new (${frameUpload.total} on the document).`);
|
|
537
649
|
}
|
|
538
650
|
catch (e) {
|
|
651
|
+
warnings.push({
|
|
652
|
+
code: "frames_upload_failed",
|
|
653
|
+
error: `the frames were cut but ${e.message}`,
|
|
654
|
+
remediation: rerunCommand(target, opts),
|
|
655
|
+
});
|
|
539
656
|
// Same partial-success rule as a failed extraction: the document
|
|
540
657
|
// exists, only the pictures are missing.
|
|
541
658
|
notify(`The frames were cut but ${e.message}\n` +
|
|
@@ -546,6 +663,11 @@ export async function cmdContextImport(target, opts) {
|
|
|
546
663
|
}
|
|
547
664
|
}
|
|
548
665
|
else if (frames.length > 0) {
|
|
666
|
+
warnings.push({
|
|
667
|
+
code: "frames_upload_failed",
|
|
668
|
+
error: "frames were extracted but the server returned no document id, so they were not uploaded.",
|
|
669
|
+
remediation: rerunCommand(target, opts),
|
|
670
|
+
});
|
|
549
671
|
notify("frames were extracted but the server returned no document id, so they were not uploaded.");
|
|
550
672
|
}
|
|
551
673
|
// Regenerate the LOCAL bundle around the verdict + the frames.
|
|
@@ -559,7 +681,9 @@ export async function cmdContextImport(target, opts) {
|
|
|
559
681
|
...(f.height ? { height: f.height } : {}),
|
|
560
682
|
...(caption ? { caption } : {}),
|
|
561
683
|
};
|
|
562
|
-
})
|
|
684
|
+
}),
|
|
685
|
+
// frameUpload is set only when the server accepted them.
|
|
686
|
+
completenessOf(classification, frameUpload ? uploadedFrames.length : 0));
|
|
563
687
|
({ path: bundlePath } = writeBundle(outputDir, compiled, uploadedFrames));
|
|
564
688
|
}
|
|
565
689
|
finally {
|
|
@@ -569,25 +693,46 @@ export async function cmdContextImport(target, opts) {
|
|
|
569
693
|
}
|
|
570
694
|
// Even with no frames, the verdict itself belongs in the bundle.
|
|
571
695
|
if (uploadedFrames.length === 0) {
|
|
572
|
-
compiled = withVisualEvidence(compiled, classification, []);
|
|
696
|
+
compiled = withVisualEvidence(compiled, classification, [], completenessOf(classification));
|
|
573
697
|
({ path: bundlePath } = writeBundle(outputDir, compiled));
|
|
574
698
|
}
|
|
575
699
|
}
|
|
576
700
|
}
|
|
577
701
|
if (opts.json) {
|
|
578
702
|
process.stdout.write(`${JSON.stringify({
|
|
703
|
+
ok: true,
|
|
579
704
|
bundlePath,
|
|
705
|
+
// The file an agent should actually open. Naming the directory alone
|
|
706
|
+
// makes every caller guess at the entry point.
|
|
707
|
+
contextPath: join(bundlePath, "recording.md"),
|
|
708
|
+
title: compiled.manifest.title,
|
|
580
709
|
profile: compiled.manifest.profile,
|
|
581
710
|
recommendedProfile: report?.recommendedProfile ?? null,
|
|
582
711
|
overallScore: report?.overallScore ?? null,
|
|
583
712
|
gapCount: report?.gaps.length ?? 0,
|
|
584
713
|
...(synced ? { synced: true, publicId: synced.publicId } : opts.sync ? { synced: false } : {}),
|
|
714
|
+
...(synced?.folderName ? { folderName: synced.folderName } : {}),
|
|
585
715
|
classification: synced?.classification ?? null,
|
|
586
716
|
frames: uploadedFrames.length,
|
|
587
717
|
...(frameUpload ? { framesAdded: frameUpload.added, framesTotal: frameUpload.total } : {}),
|
|
718
|
+
warnings,
|
|
588
719
|
}, null, 2)}\n`);
|
|
589
720
|
return;
|
|
590
721
|
}
|
|
722
|
+
// The headline. A user who ran one command should not have to assemble "did
|
|
723
|
+
// it work, and where is it" out of four key-value lines.
|
|
724
|
+
process.stdout.write(`\nYour agent-ready context for ${JSON.stringify(compiled.manifest.title)} is ready.\n`);
|
|
725
|
+
if (synced) {
|
|
726
|
+
// Server copy first — once synced it is the canonical, durable one; the
|
|
727
|
+
// local bundle is the offline/working copy.
|
|
728
|
+
process.stdout.write(` → view it: ${webOriginFromApiUrl(opts.apiUrl)}/knowledge/${synced.publicId} (filed under ${JSON.stringify(synced.folderName ?? "Knowledge Base")})\n`);
|
|
729
|
+
process.stdout.write(` → for agents: MCP read_context_document ${synced.publicId}, or the local bundle below\n`);
|
|
730
|
+
}
|
|
731
|
+
process.stdout.write(` → local bundle: ${join(bundlePath, "recording.md")} (run: clipy context read ${bundlePath})\n`);
|
|
732
|
+
if (warnings.length > 0) {
|
|
733
|
+
process.stdout.write(` → incomplete: ${warnings.map((w) => w.error).join("; ")}\n to finish it: ${warnings[0].remediation}\n`);
|
|
734
|
+
}
|
|
735
|
+
process.stdout.write("\n");
|
|
591
736
|
process.stdout.write(`bundle: ${bundlePath}${rewritten ? " (rewritten — source content changed)" : ""}\n`);
|
|
592
737
|
if (synced?.classification) {
|
|
593
738
|
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 +750,4 @@ export async function cmdContextImport(target, opts) {
|
|
|
605
750
|
if (synced) {
|
|
606
751
|
process.stdout.write(`synced: ${synced.publicId} (private — only you can read it${synced.folderName ? `, filed in ${synced.folderName}` : ""})\n`);
|
|
607
752
|
}
|
|
608
|
-
process.stdout.write(`next: clipy context read ${bundlePath}\n`);
|
|
609
753
|
}
|
|
@@ -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]";
|