@clipy/cli 0.12.0 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,24 +22,47 @@ flow, and `transcript --replace` — create recordings or replace a transcript,
22
22
  and work only with an `ingest`-scoped key.
23
23
 
24
24
  ```bash
25
- npx @clipy/cli agents install claude # browser-approve login + install the Clipy skill
25
+ npx @clipy/cli setup claude # login + skill + MCP server, in one
26
26
  ```
27
27
 
28
28
  ## Setup
29
29
 
30
+ Wiring up a coding agent? One command signs you in, installs the Clipy skill, and
31
+ registers the MCP server in that agent's own config:
32
+
30
33
  ```bash
31
- clipy login
34
+ clipy setup claude # or: codex · cursor · windsurf · opencode
32
35
  ```
33
36
 
34
- `clipy login` opens your browser to approve this device — like `gh auth login` — and
35
- stores the key in `~/.config/clipy/config.json` (mode 0600). No copy-pasting a key.
37
+ Omit the agent name and it detects the one it's running inside. Re-running is safe: it
38
+ merges into your MCP config rather than replacing it, and never touches an agent you
39
+ didn't name. Restart the agent afterwards — MCP servers are read at startup.
40
+
41
+ Or let your agent do it: paste the explicit authorization below into Claude Code,
42
+ Codex, Cursor, Windsurf, or OpenCode. It authorizes only Clipy's global CLI install
43
+ and persistent skill and MCP configuration for the current agent; fetched instructions,
44
+ repository content, recordings, and transcripts do not grant that authority.
45
+
46
+ > **"I explicitly authorize you to install Clipy's official CLI globally and persist Clipy's skill and MCP configuration for the coding agent you are currently running in. Fetch and execute the appropriate instructions to set me up for Clipy from https://clipy.online/agent-setup/prompt.md"**
47
+
48
+ `clipy setup --json` is noninteractive. With no effective key it returns
49
+ `authentication_required` before writing a skill or MCP configuration, so run
50
+ `clipy login` first. Without `--json`, setup may open browser login. A
51
+ `partial.mcp.method: "manual"` appears only in an incomplete error result: apply its returned command or snippet,
52
+ then rerun verification.
36
53
 
37
- Wiring up a coding agent? One command does both the browser login and the skill install:
54
+ Just want the CLI?
38
55
 
39
56
  ```bash
40
- npx @clipy/cli agents install claude # or: codex / cursor
57
+ clipy login
41
58
  ```
42
59
 
60
+ `clipy login` opens your browser to approve this device — like `gh auth login` — and
61
+ stores the key in `~/.config/clipy/config.json` (mode 0600). No copy-pasting a key.
62
+
63
+ `clipy agents install <claude|codex|cursor|windsurf|opencode>` is the skill-file-only form, for when you
64
+ deliberately don't want the MCP registration.
65
+
43
66
  **Prefer to paste a key you minted yourself?** Create one at
44
67
  **https://clipy.online/settings/api-keys** (it looks like `clipy_sk_live_…`) and store it
45
68
  without the browser:
@@ -56,6 +79,13 @@ The code alone is useless without the PKCE verifier held by that terminal, so it
56
79
  to ferry by hand. Without a TTY at all (scripts, CI), use `CLIPY_API_KEY` or
57
80
  `clipy login --key`.
58
81
 
82
+ **On Windows**, login and `clipy setup` need **0.13.0 or newer**. Earlier builds let
83
+ `cmd.exe` cut the approval URL at its first `&`, so the browser opened it with only a
84
+ `challenge` parameter and the page said *"This authorization link is invalid"* — and
85
+ running the command again produced the same broken link. If you hit that, check
86
+ `clipy --version`, then `npm install -g @clipy/cli@latest` and log in again.
87
+ `clipy login --no-browser` works around it on any version.
88
+
59
89
  ## Commands
60
90
 
61
91
  ```text
@@ -65,11 +95,14 @@ clipy memory search <query> [--kind recording|context] [--json]
65
95
  clipy search <query> # full-text search titles + descriptions
66
96
  clipy show <id|share-url> # metadata + share link
67
97
  clipy transcript <id> [--marks-only] # one entry per line, timestamped (--srt/--vtt to export)
98
+ clipy transcript <id> --json > transcript.json
99
+ clipy transcript <id> --replace replacement.json --revision <transcript.revision>
100
+ # guarded replacement; stale revisions return a conflict
68
101
  clipy summary <id> # TL;DR, key points, action items
69
102
  clipy moments <id> # key moments: timestamps, captions, click coords
70
103
  clipy context <id> # the full agent-context bundle as markdown
71
104
  clipy context import <url|file> --sync # turn ANY video into an agent-readable bundle
72
- clipy context read <bundle-path> # print a local bundle's recording.md
105
+ clipy context read <bundle-path> # print a local bundle's recording.arec
73
106
  clipy download <id> [-o out.mp4] # download the MP4
74
107
  clipy open <id> # open the share page in your browser
75
108
  clipy wait <id> --for both # block until transcript/summary are ready
@@ -109,19 +142,22 @@ recording-library search.
109
142
 
110
143
  ## Import any video as context
111
144
 
112
- `clipy context import` turns a YouTube URL or a local video file into an agent-readable
113
- bundle (`recording.md` + `manifest.json` + `transcript.json`), and optionally into private
145
+ `clipy context import` turns a YouTube URL, a Loom share link, or a local video file into an agent-readable
146
+ bundle (`recording.arec` + byte-identical `recording.md` + `manifest.json` + `transcript.json`), and optionally into private
114
147
  Clipy memory.
115
148
 
116
149
  ```bash
117
150
  clipy context import https://youtube.com/watch?v=… --sync --json
151
+ clipy context import https://www.loom.com/share/<32-hex-id> --sync --json
118
152
  clipy context import ./demo.mov --transcript ./demo.vtt --sync
119
153
  clipy context read ./clipy-context/<bundle>
120
154
  ```
121
155
 
122
- Captions first, so it is fast — YouTube captions are fetched on your machine and no media
123
- is downloaded unless it is needed. Local files carry no captions, so they need
124
- `--transcript <.vtt|.srt|.json>`.
156
+ Captions first, so it is fast — YouTube captions and Loom transcripts are fetched on your
157
+ machine and no media is downloaded unless it is needed. Loom needs no `yt-dlp` for this, so
158
+ a yt-dlp warning in `clipy doctor` does not block a Loom import; roughly one Loom in six has
159
+ no transcript recorded and fails with `no_captions` rather than producing an empty bundle.
160
+ Local files carry no captions, so they need `--transcript <.vtt|.srt|.json>`.
125
161
 
126
162
  With `--sync`, the server classifies the bundle: what kind of video it is and whether the
127
163
  words stand alone. Podcasts, interviews, and dictated content come back transcript-only; a
@@ -159,7 +195,7 @@ clipy proof --video /tmp/verification.webm \
159
195
  ```
160
196
 
161
197
  Frame mode accepts PNG, JPEG, or WebP (up to 50 frames, 5 minutes, 50 MiB per
162
- image, and 250 MiB total), and requires ffmpeg to create the silent WebM.
198
+ image, and 250 MiB total), and requires ffmpeg to create the high-quality silent MP4.
163
199
  `--width`/`--height` must be even integers from 320–3840. Video mode accepts
164
200
  WebM or MP4 and does not require Playwright, Browser Use, Open Browser Use, or
165
201
  any other browser automation dependency. Captions and notes become timestamped
@@ -534,7 +570,7 @@ By default it captures the primary display. Target one window instead:
534
570
  ```bash
535
571
  clipy sources # list displays + windows with ids
536
572
  clipy session start --source mac-screen --window "Chrome" --title "Fix walkthrough"
537
- # … the agent drives the real, logged-in Chrome while Clipy records that window …
573
+ # … the agent drives Chrome while Clipy records its initial screen area …
538
574
  clipy mark "reproduced the bug"
539
575
  clipy mark "fix applied — retesting"
540
576
  clipy session stop # uploads, prints the share link
@@ -580,8 +616,8 @@ of a different tab: worse than no evidence, because the tally vouches for the wr
580
616
  **Clipy will never bring a window or tab to the front for you.** It can't know which
581
617
  tab/page/simulator you mean, and on `--source mac-screen` it may not be recording a browser
582
618
  at all — focusing the right surface is the caller's job. Do it before `session start`, then
583
- confirm with the reported title. (That title is read at start time; the camera follows the
584
- window, so switching tabs mid-recording changes what's filmed without changing the title.)
619
+ confirm with the reported title. (The title and recorded screen area are fixed at start time;
620
+ moving the window does not move the recording, and anything entering that area is filmed.)
585
621
 
586
622
  ## Scripting
587
623
 
@@ -626,8 +662,8 @@ API, but with agent-native tools and inline key-moment frames
626
662
  [setup docs](https://clipy.online/docs/mcp)). `clipy mcp` is a shortcut that runs it.
627
663
 
628
664
  Also: every **public** Clipy watch link is agent-readable without any install — append
629
- `.md` to it (`https://clipy.online/video/<id>.md`) and it serves a markdown context
630
- document with the summary, key moments, and transcript. Details at
665
+ `.arec` to it (`https://clipy.online/video/<id>.arec`) and it serves actionable AREC
666
+ Markdown. The legacy `.md` URL remains byte-identical. Details at
631
667
  [clipy.online/for-agents](https://clipy.online/for-agents).
632
668
 
633
669
  ## Links
@@ -21,7 +21,7 @@
21
21
  import { createServer } from "node:http";
22
22
  import { createHash, randomBytes } from "node:crypto";
23
23
  import { hostname } from "node:os";
24
- import { spawn } from "node:child_process";
24
+ import { openUrl } from "./openUrl.js";
25
25
  /**
26
26
  * True when the loopback redirect can't work and the copy-code flow should be
27
27
  * used instead: an SSH session (the browser runs on a different machine than
@@ -46,28 +46,7 @@ function openBrowser(url, log) {
46
46
  log(` ${url}`);
47
47
  if (process.env.CLIPY_LOGIN_NO_BROWSER)
48
48
  return;
49
- let cmd;
50
- let args;
51
- if (process.platform === "darwin") {
52
- cmd = "open";
53
- args = [url];
54
- }
55
- else if (process.platform === "win32") {
56
- cmd = "cmd";
57
- args = ["/c", "start", "", url];
58
- }
59
- else {
60
- cmd = "xdg-open";
61
- args = [url];
62
- }
63
- try {
64
- const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
65
- child.on("error", () => { }); // opener missing — the printed URL is the fallback
66
- child.unref();
67
- }
68
- catch {
69
- // ignore — the URL is already printed
70
- }
49
+ openUrl(url);
71
50
  }
72
51
  export async function browserLogin(opts) {
73
52
  const apiUrl = opts.apiUrl.replace(/\/+$/, "");
@@ -1,6 +1,6 @@
1
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.
2
+ * `clipy context import <youtube-url|loom-url|local-file>` — compiles a local
3
+ * Clipy context bundle (AREC v0.3-draft) and optionally syncs it to the library.
4
4
  *
5
5
  * Syncing is a TWO-PHASE protocol, and the split is deliberate: the server is
6
6
  * the classification brain. Phase 1 uploads the transcript bundle and the
@@ -14,9 +14,10 @@ import { createHash } from "node:crypto";
14
14
  import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
15
15
  import { tmpdir } from "node:os";
16
16
  import { basename, join, resolve } from "node:path";
17
- import { buildManifest, buildNormalizedTranscript, classifyTranscript, parseSrt, parseVtt, parseYoutubeJson3, renderArecMarkdown, slugHash, } from "../context-core/index.js";
17
+ import { buildManifest, AREC_CANONICAL_FILENAME, AREC_LEGACY_FILENAME, buildNormalizedTranscript, classifyTranscript, parseSrt, parseVtt, parseYoutubeJson3, renderArecMarkdown, slugHash, } from "../context-core/index.js";
18
18
  import { describeCaptions, fetchCaptions, fetchVideoMeta, resolveYtDlp } from "./ytdlp.js";
19
19
  import { canonicalYoutubeUrl, isYoutubeHost, parseYoutubeId } from "./youtubeUrl.js";
20
+ import { LoomError, canonicalLoomUrl, fetchLoomMeta, fetchLoomTranscript, isLoomHost, parseLoomId, parseLoomPhrases, } from "./loom.js";
20
21
  // The web app and the API share an origin in every real deployment; strip any
21
22
  // trailing slash so the printed URL is clean.
22
23
  function webOriginFromApiUrl(apiUrl) {
@@ -26,7 +27,7 @@ import { ImportError } from "./errors.js";
26
27
  import { looksLikeStaleBinary } from "./retry.js";
27
28
  import { probeVideo } from "./probe.js";
28
29
  import { extractFrames } from "./frames.js";
29
- import { borrowLocalVideo, borrowYoutubeVideo } from "./videoFetch.js";
30
+ import { borrowLocalVideo, borrowLoomVideo, borrowYoutubeVideo } from "./videoFetch.js";
30
31
  function classifyInput(raw) {
31
32
  const trimmed = raw.trim();
32
33
  // Shell-escaped input (`watch\?v\=…`) still has to be recognised as YouTube,
@@ -48,6 +49,13 @@ function classifyInput(raw) {
48
49
  // Everything downstream uses the canonical URL — never the raw input.
49
50
  return { kind: "youtube", url: canonicalYoutubeUrl(videoId), videoId };
50
51
  }
52
+ if (isLoomHost(parsed.hostname)) {
53
+ const videoId = parseLoomId(trimmed);
54
+ if (!videoId) {
55
+ throw new ImportError("invalid_url", `could not find a Loom video id in "${raw}". Folder and workspace URLs are not supported.`, `Pass a single-video share link, e.g. clipy context import "https://www.loom.com/share/<32-hex-id>" (/embed/<id> also works).`);
56
+ }
57
+ return { kind: "loom", url: canonicalLoomUrl(videoId), videoId };
58
+ }
51
59
  return { kind: "url", url: unescaped };
52
60
  }
53
61
  const path = resolve(trimmed);
@@ -224,6 +232,102 @@ async function compileYoutube(url, videoId, opts) {
224
232
  opts,
225
233
  });
226
234
  }
235
+ /** Loom's own failure vocabulary, in the CLI's stable codes. */
236
+ function loomImportError(e, url) {
237
+ if (e.kind === "private") {
238
+ return new ImportError("source_private", `${e.message} (${url})`, `Ask the owner for a public share link, or export the video and import the copy: clipy context import ./<file> --transcript <file.vtt>`);
239
+ }
240
+ if (e.kind === "not_found") {
241
+ return new ImportError("invalid_url", `${e.message} (${url})`, `Open the link in a browser to check it plays, then re-run with the URL it lands on.`);
242
+ }
243
+ return new ImportError("loom_unreachable", e.message, `This is usually transient. Re-run the same command in a minute. If it persists, check your network or proxy: Clipy reaches loom.com and cdn.loom.com directly.`);
244
+ }
245
+ /**
246
+ * A Loom share link, over plain HTTPS.
247
+ *
248
+ * Loom publishes the transcript for a public link itself, so unlike the YouTube
249
+ * path nothing here shells out: no yt-dlp, no ffmpeg, no auto-install, and one
250
+ * fewer class of failure. The bundle that comes out is the same shape as every
251
+ * other one.
252
+ */
253
+ async function compileLoom(url, videoId, opts) {
254
+ notify("Fetching video info from Loom…");
255
+ let meta;
256
+ try {
257
+ meta = await fetchLoomMeta(videoId);
258
+ }
259
+ catch (e) {
260
+ if (e instanceof LoomError)
261
+ throw loomImportError(e, url);
262
+ throw e;
263
+ }
264
+ notify(`Found: "${meta.title}"${meta.durationMs ? ` (${fmtClock(meta.durationMs)})` : ""}`);
265
+ const id = meta.id || videoId;
266
+ const source = {
267
+ kind: "loom",
268
+ canonicalUrl: canonicalLoomUrl(id),
269
+ providerId: id,
270
+ };
271
+ const common = {
272
+ title: opts.title ?? meta.title,
273
+ source,
274
+ durationMs: meta.durationMs,
275
+ fingerprint: `loom:${id}`,
276
+ media: { kind: "loom", url, durationMs: meta.durationMs },
277
+ opts,
278
+ };
279
+ // An explicit --transcript is the user overriding the provider, so Loom's own
280
+ // transcript is never consulted — not even as a fallback.
281
+ if (opts.transcriptPath) {
282
+ const segments = loadUserTranscript(opts.transcriptPath);
283
+ notify(`Using your transcript file (${segments.length} segments), so Loom's own transcript is not consulted.`);
284
+ return finish({
285
+ ...common,
286
+ transcript: buildNormalizedTranscript(segments, {
287
+ ...(opts.language ? { language: opts.language } : {}),
288
+ source: "user_file",
289
+ durationMs: meta.durationMs || undefined,
290
+ }),
291
+ });
292
+ }
293
+ // --language picks a caption TRACK on YouTube. Loom publishes exactly one
294
+ // transcript, so there is nothing here for it to pick — say so rather than
295
+ // letting the user believe they asked for a language and got it.
296
+ if (opts.language) {
297
+ notify(`Note: --language does not select a transcript on Loom, which publishes only one. Importing the transcript Loom has.`);
298
+ }
299
+ let fetched;
300
+ try {
301
+ fetched = await fetchLoomTranscript(id);
302
+ }
303
+ catch (e) {
304
+ if (e instanceof LoomError)
305
+ throw loomImportError(e, url);
306
+ throw e;
307
+ }
308
+ // Roughly one Loom in six has no transcript recorded at all. There is nothing
309
+ // to compile from and nothing for the classifier to score, so this refuses
310
+ // rather than writing a bundle whose only honest content is its own emptiness
311
+ // — the same answer the YouTube path gives a video with no captions.
312
+ if (!fetched) {
313
+ throw new ImportError("no_captions", `this Loom video has no transcript. Loom records one for most videos but not all, and it cannot be requested after the fact.`, `Supply your own: clipy context import ${JSON.stringify(url)} --transcript <file.vtt|file.srt|transcript.json>`);
314
+ }
315
+ const raw = fetched.format === "vtt"
316
+ ? parseVtt(fetched.text)
317
+ : parseLoomPhrases(JSON.parse(fetched.text), meta.durationMs);
318
+ if (raw.length === 0) {
319
+ throw new ImportError("no_captions", `Loom returned a transcript for this video but it contained no readable speech.`, `Supply your own: clipy context import ${JSON.stringify(url)} --transcript <file.vtt|file.srt|transcript.json>`);
320
+ }
321
+ const transcript = buildNormalizedTranscript(raw, {
322
+ // Loom's transcript is machine-generated ASR. Labelling it creator-provided
323
+ // would overstate its fidelity to every agent that reads the manifest.
324
+ source: "auto_captions",
325
+ ...(fetched.language || opts.language ? { language: fetched.language ?? opts.language } : {}),
326
+ durationMs: meta.durationMs || undefined,
327
+ });
328
+ notify(`Got ${transcript.segments.length} transcript segments from Loom (${fetched.format === "vtt" ? "captions" : "phrase timings"}, auto-generated).`);
329
+ return finish({ ...common, transcript });
330
+ }
227
331
  async function compileLocal(path, opts) {
228
332
  if (!opts.transcriptPath) {
229
333
  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>`);
@@ -285,7 +389,7 @@ function finish(input) {
285
389
  }
286
390
  /**
287
391
  * Rebuilds a compiled bundle around the server's verdict and the frames we
288
- * fetched for it. recording.md is a pure function of the manifest plus the
392
+ * fetched for it. recording.arec is a pure function of the manifest plus the
289
393
  * transcript, so re-rendering is the whole update.
290
394
  */
291
395
  function withVisualEvidence(compiled, classification, frames, completeness) {
@@ -323,7 +427,8 @@ function writeBundle(dir, compiled, frames = []) {
323
427
  mkdirSync(dir, { recursive: true });
324
428
  const bundlePath = join(dir, `clipy-context-${slugHash(compiled.fingerprint)}`);
325
429
  const contents = {
326
- "recording.md": compiled.markdown,
430
+ [AREC_CANONICAL_FILENAME]: compiled.markdown,
431
+ [AREC_LEGACY_FILENAME]: compiled.markdown,
327
432
  // createdAt changes every run; compare on everything else so a rerun over an
328
433
  // unchanged source is genuinely idempotent.
329
434
  "manifest.json": `${JSON.stringify(compiled.manifest, null, 2)}\n`,
@@ -358,7 +463,7 @@ function writeBundle(dir, compiled, frames = []) {
358
463
  }
359
464
  function sameBundle(bundlePath, contents) {
360
465
  try {
361
- // recording.md is a pure function of the manifest and the transcript, and it
466
+ // recording.arec is a pure function of the manifest and the transcript, and it
362
467
  // embeds the compile timestamp — comparing it byte-wise would make every
363
468
  // rerun look like a content change.
364
469
  const a = JSON.parse(readFileSync(join(bundlePath, "manifest.json"), "utf8"));
@@ -369,7 +474,12 @@ function sameBundle(bundlePath, contents) {
369
474
  return false;
370
475
  if (readFileSync(join(bundlePath, "transcript.json"), "utf8") !== contents["transcript.json"])
371
476
  return false;
372
- if (!existsSync(join(bundlePath, "recording.md")))
477
+ if (!existsSync(join(bundlePath, AREC_CANONICAL_FILENAME)))
478
+ return false;
479
+ if (!existsSync(join(bundlePath, AREC_LEGACY_FILENAME)))
480
+ return false;
481
+ if (readFileSync(join(bundlePath, AREC_CANONICAL_FILENAME), "utf8") !==
482
+ readFileSync(join(bundlePath, AREC_LEGACY_FILENAME), "utf8"))
373
483
  return false;
374
484
  return true;
375
485
  }
@@ -530,15 +640,28 @@ async function collectFrames(compiled, timestampsMs, opts) {
530
640
  let borrowed = null;
531
641
  const workDir = mkdtempSync(join(tmpdir(), "clipy-frames-out-"));
532
642
  try {
533
- borrowed =
534
- compiled.media.kind === "local"
535
- ? borrowLocalVideo(compiled.media.path)
536
- : await borrowYoutubeVideo({
537
- ytDlpBin: compiled.media.ytDlpBin,
538
- url: compiled.media.url,
539
- durationMs: compiled.media.durationMs,
540
- notify,
541
- });
643
+ if (compiled.media.kind === "local") {
644
+ borrowed = borrowLocalVideo(compiled.media.path);
645
+ }
646
+ else if (compiled.media.kind === "youtube") {
647
+ borrowed = await borrowYoutubeVideo({
648
+ ytDlpBin: compiled.media.ytDlpBin,
649
+ url: compiled.media.url,
650
+ durationMs: compiled.media.durationMs,
651
+ notify,
652
+ });
653
+ }
654
+ else {
655
+ // First point in a Loom import that needs a binary at all. Resolving it
656
+ // here — inside the block whose every failure is a warning — is what keeps
657
+ // a missing yt-dlp costing the user the pictures rather than the import.
658
+ borrowed = await borrowLoomVideo({
659
+ ytDlpBin: await resolveYtDlp(notify),
660
+ url: compiled.media.url,
661
+ durationMs: compiled.media.durationMs,
662
+ notify,
663
+ });
664
+ }
542
665
  const frames = await extractFrames({
543
666
  videoPath: borrowed.path,
544
667
  timestampsMs,
@@ -561,7 +684,11 @@ export async function cmdContextImport(target, opts) {
561
684
  if (input.kind === "url") {
562
685
  throw new ImportError("invalid_url", "direct media URLs are not supported yet.", `Download the file first, then: clipy context import ./<file> --transcript <file.vtt>`);
563
686
  }
564
- let compiled = input.kind === "youtube" ? await compileYoutube(input.url, input.videoId, opts) : await compileLocal(input.path, opts);
687
+ let compiled = input.kind === "youtube"
688
+ ? await compileYoutube(input.url, input.videoId, opts)
689
+ : input.kind === "loom"
690
+ ? await compileLoom(input.url, input.videoId, opts)
691
+ : await compileLocal(input.path, opts);
565
692
  const outputDir = resolve(opts.outputDir ?? process.cwd());
566
693
  let { path: bundlePath, rewritten } = writeBundle(outputDir, compiled);
567
694
  const report = compiled.manifest.sufficiency;
@@ -622,16 +749,21 @@ export async function cmdContextImport(target, opts) {
622
749
  // Phase 2: fetch only the moments the server named.
623
750
  const { frames, workDir, failure } = await collectFrames(compiled, classification.frameTimestampsMs, opts);
624
751
  if (failure) {
752
+ // A Loom import reaches yt-dlp for the first time HERE, so "could not
753
+ // install yt-dlp" is a failure mode this branch can now see — and it
754
+ // has a different fix from a blocked download or a missing ffmpeg.
755
+ const missingYtDlp = /could not install yt-dlp/i.test(failure);
756
+ const missingFfmpeg = !missingYtDlp && /ffmpeg|ffprobe/i.test(failure);
625
757
  warnings.push({
626
- code: /403/.test(failure)
627
- ? "ytdlp_download_403"
628
- : /ffmpeg|ffprobe/i.test(failure)
629
- ? "ffmpeg_missing"
630
- : "frames_upload_failed",
758
+ code: missingYtDlp
759
+ ? "ytdlp_missing"
760
+ : /403/.test(failure)
761
+ ? "ytdlp_download_403"
762
+ : missingFfmpeg
763
+ ? "ffmpeg_missing"
764
+ : "frames_upload_failed",
631
765
  error: `frames could not be extracted: ${failure.split("\n")[0]}`,
632
- remediation: /ffmpeg|ffprobe/i.test(failure)
633
- ? FFMPEG_INSTALL_COMMAND
634
- : rerunCommand(target, opts),
766
+ remediation: missingFfmpeg ? FFMPEG_INSTALL_COMMAND : rerunCommand(target, opts),
635
767
  });
636
768
  // Phase 1 already succeeded — this is a PARTIAL success, and saying
637
769
  // "failed" here would send the user hunting for a document that is
@@ -707,7 +839,7 @@ export async function cmdContextImport(target, opts) {
707
839
  bundlePath,
708
840
  // The file an agent should actually open. Naming the directory alone
709
841
  // makes every caller guess at the entry point.
710
- contextPath: join(bundlePath, "recording.md"),
842
+ contextPath: join(bundlePath, AREC_CANONICAL_FILENAME),
711
843
  title: compiled.manifest.title,
712
844
  profile: compiled.manifest.profile,
713
845
  recommendedProfile: report?.recommendedProfile ?? null,
@@ -735,7 +867,7 @@ export async function cmdContextImport(target, opts) {
735
867
  process.stdout.write(` → view it: ${webOriginFromApiUrl(opts.apiUrl)}/knowledge/${synced.publicId} (filed under ${JSON.stringify(synced.folderName ?? "Knowledge Base")})\n`);
736
868
  process.stdout.write(` → for agents: MCP read_context_document ${synced.publicId}, or the local bundle below\n`);
737
869
  }
738
- process.stdout.write(` → local bundle: ${join(bundlePath, "recording.md")} (run: clipy context read ${bundlePath})\n`);
870
+ process.stdout.write(` → local bundle: ${join(bundlePath, AREC_CANONICAL_FILENAME)} (run: clipy context read ${bundlePath})\n`);
739
871
  if (warnings.length > 0) {
740
872
  process.stdout.write(` → incomplete: ${warnings.map((w) => w.error).join("; ")}\n to finish it: ${warnings[0].remediation}\n`);
741
873
  }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The CLI's adapter onto the SHARED Loom provider.
3
+ *
4
+ * The transport and the parsers live in `lib/context-core/loom.ts`, which the
5
+ * prebuild syncs into `src/context-core/`. They are shared with the Next.js
6
+ * server (and available to the extension) precisely so there is one Loom
7
+ * implementation rather than two that drift.
8
+ *
9
+ * What is CLI-only, and therefore lives here:
10
+ * - reading `CLIPY_LOOM_ORIGIN` from the environment. context-core must not
11
+ * touch `process` (the extension bundles it through Vite), so the origin is
12
+ * injected, and this is the only place that knows an environment exists.
13
+ * - mapping Loom's failure vocabulary onto the CLI's stable error codes, which
14
+ * `importCmd.ts` owns. `LoomFailureKind` is about Loom; `ImportErrorCode` is
15
+ * a published contract agents branch on, and the two should be free to move
16
+ * independently.
17
+ */
18
+ import { fetchLoomMeta as fetchLoomMetaShared, fetchLoomTranscript as fetchLoomTranscriptShared, } from "../context-core/loom.js";
19
+ export { LoomError, canonicalLoomUrl, isLoomHost, parseLoomId, parseLoomPhrases, } from "../context-core/loom.js";
20
+ /** Read per call, never cached: a test sets this per spawned process. */
21
+ function envOptions() {
22
+ const origin = process.env.CLIPY_LOOM_ORIGIN;
23
+ return origin ? { origin } : {};
24
+ }
25
+ export function fetchLoomMeta(id) {
26
+ return fetchLoomMetaShared(id, envOptions());
27
+ }
28
+ export function fetchLoomTranscript(id) {
29
+ return fetchLoomTranscriptShared(id, envOptions());
30
+ }
@@ -1,9 +1,10 @@
1
1
  /**
2
- * `clipy context read <bundle-path>` — prints a local bundle's recording.md.
2
+ * `clipy context read <bundle-path>` — prints a local bundle's recording.arec.
3
3
  * Output is for agents: plain, unpaged, uncoloured.
4
4
  */
5
5
  import { existsSync, readFileSync, statSync } from "node:fs";
6
6
  import { join, resolve } from "node:path";
7
+ import { AREC_CANONICAL_FILENAME, AREC_LEGACY_FILENAME, } from "../context-core/index.js";
7
8
  export function cmdContextRead(target) {
8
9
  let dir = resolve(target);
9
10
  // Accept either the bundle directory or one of the files inside it.
@@ -23,8 +24,11 @@ export function cmdContextRead(target) {
23
24
  if (manifest.bundleVersion !== 1) {
24
25
  throw new Error(`unsupported bundle version ${String(manifest.bundleVersion)} — this CLI reads bundleVersion 1. Upgrade with \`npm i -g @clipy/cli\`.`);
25
26
  }
26
- const doc = join(dir, "recording.md");
27
- if (!existsSync(doc))
28
- throw new Error(`${dir} has a manifest but no recording.md.`);
27
+ const arec = join(dir, AREC_CANONICAL_FILENAME);
28
+ const legacy = join(dir, AREC_LEGACY_FILENAME);
29
+ const doc = existsSync(arec) ? arec : legacy;
30
+ if (!existsSync(doc)) {
31
+ throw new Error(`${dir} has a manifest but no ${AREC_CANONICAL_FILENAME}.`);
32
+ }
29
33
  process.stdout.write(readFileSync(doc, "utf8"));
30
34
  }
@@ -134,32 +134,46 @@ function attemptDownload(dir, input, plan) {
134
134
  });
135
135
  }
136
136
  /**
137
- * Three attempts on yt-dlp's own defaults, then two escalations.
137
+ * YouTube's ladder. Every rung is YouTube-specific — `player_client` is that
138
+ * extractor's argument and format 18 is one of its itags — so no other provider
139
+ * may borrow it: on a non-YouTube URL these turn a retriable failure into
140
+ * "Requested format is not available", which classifies as fatal.
141
+ *
142
+ * The reasoning behind each rung is in docs/research/2026-07-29-ytdlp-403-fallbacks.md §3.
143
+ */
144
+ const YOUTUBE_ESCALATIONS = [
145
+ {
146
+ plan: { format: DEFAULT_FORMAT, extraArgs: TOKEN_FREE_CLIENT_ARGS },
147
+ notice: "Still blocked — trying YouTube's token-free player clients (tv, android_vr, web_embedded)…",
148
+ success: "A different player client worked — continuing with frame extraction.",
149
+ },
150
+ {
151
+ plan: PROGRESSIVE_FALLBACK,
152
+ notice: "Still blocked — falling back to a pre-muxed progressive format (lower resolution, but it downloads in one piece)…",
153
+ success: "The progressive format worked — continuing with frame extraction.",
154
+ },
155
+ ];
156
+ /**
157
+ * Loom serves a small ladder of HLS renditions and no itags, so there is
158
+ * nothing to escalate to — yt-dlp's own retries plus our three attempts are the
159
+ * whole strategy. The format spec ends in an unconstrained pair because a Loom
160
+ * recorded straight to 1080p may publish no rendition at or under 720p, and "no
161
+ * frames because the only copy was too tall" is a worse answer than one larger
162
+ * download that the byte and duration ceilings still bound.
163
+ */
164
+ const LOOM_FORMAT = "bv*[height<=720]/b[height<=720]/bv*/b";
165
+ /**
166
+ * Three attempts on yt-dlp's own defaults, then whatever escalations the
167
+ * provider has.
138
168
  *
139
169
  * The 403 this exists for is not a verdict about the video — the identical
140
170
  * command succeeds a minute later, because the media URL YouTube signed has
141
171
  * expired and only a fresh extraction mints a new one. Re-running the binary IS
142
172
  * the re-extraction, which is why the outer loop earns its keep even though
143
173
  * BASELINE_DOWNLOAD_ARGS already makes yt-dlp retry internally.
144
- *
145
- * The escalation ladder and the reasoning behind each rung are documented in
146
- * docs/research/2026-07-29-ytdlp-403-fallbacks.md §3.
147
174
  */
148
- async function downloadWithRetries(dir, input) {
149
- const base = { format: DEFAULT_FORMAT, extraArgs: [] };
175
+ async function downloadWithRetries(dir, input, base, escalations) {
150
176
  let last = "";
151
- const escalations = [
152
- {
153
- plan: { format: DEFAULT_FORMAT, extraArgs: TOKEN_FREE_CLIENT_ARGS },
154
- notice: "Still blocked — trying YouTube's token-free player clients (tv, android_vr, web_embedded)…",
155
- success: "A different player client worked — continuing with frame extraction.",
156
- },
157
- {
158
- plan: PROGRESSIVE_FALLBACK,
159
- notice: "Still blocked — falling back to a pre-muxed progressive format (lower resolution, but it downloads in one piece)…",
160
- success: "The progressive format worked — continuing with frame extraction.",
161
- },
162
- ];
163
177
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
164
178
  if (attempt > 1)
165
179
  clearDir(dir);
@@ -203,7 +217,14 @@ function lastLine(stderr) {
203
217
  * Throws VideoUnavailableError when the source is out of bounds — callers treat
204
218
  * that as "stay transcript-only", not as a failed import.
205
219
  */
206
- export async function borrowYoutubeVideo(input) {
220
+ export function borrowYoutubeVideo(input) {
221
+ return borrowRemoteVideo(input, { format: DEFAULT_FORMAT, extraArgs: [] }, YOUTUBE_ESCALATIONS);
222
+ }
223
+ /** The same borrow, against Loom's renditions and without YouTube's ladder. */
224
+ export function borrowLoomVideo(input) {
225
+ return borrowRemoteVideo(input, { format: LOOM_FORMAT, extraArgs: [] }, []);
226
+ }
227
+ async function borrowRemoteVideo(input, base, escalations) {
207
228
  if (input.durationMs > MAX_DURATION_MS) {
208
229
  throw new VideoUnavailableError(`the video is ${Math.round(input.durationMs / 3_600_000)}h long — over the ${MAX_DURATION_MS / 3_600_000}h ceiling for frame extraction, so no video was downloaded.`);
209
230
  }
@@ -216,7 +237,7 @@ export async function borrowYoutubeVideo(input) {
216
237
  };
217
238
  try {
218
239
  input.notify("Downloading a low-resolution (≤720p) copy of the video for frame extraction — it is deleted the moment the frames are cut…");
219
- await downloadWithRetries(dir, input);
240
+ await downloadWithRetries(dir, input, base, escalations);
220
241
  const file = readdirSync(dir).find((f) => f.startsWith("source."));
221
242
  if (!file || !existsSync(join(dir, file)) || statSync(join(dir, file)).size === 0) {
222
243
  throw new VideoUnavailableError("the download produced no usable video file, so frames were skipped.");