@clipy/cli 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -30,13 +30,14 @@ import { attachCdpDiagnostics } from "./cdpDiagnostics.js";
30
30
  import { SETUP_TARGETS, detectSetupTarget, isSetupTarget, registerMcpServer, renderSetupBox, shortPath, skillPathFor as setupSkillPathFor, } from "./setup.js";
31
31
  import { APP_NAME as CHROME_FOR_CLIPY_APP_NAME, appBundlePath as chromeForClipyAppPath, chromeStatus, DEFAULT_CDP_PORT, installApp as installChromeForClipyApp, startChrome as startChromeForClipy, startChromeForClipyCapture, markExtensionRecording, ownershipProbeStatus as chromeOwnershipProbeStatus, resolveChromeBinary, stopChrome as stopChromeForClipy, TAB_CAPTURE_TITLE_MARKER, } from "./chromeForClipy.js";
32
32
  import { ExtensionRecordingEndedError, abortExtensionRecording, ExtensionAlreadyUploadedError, extensionReadiness, extensionRecordingStatus, extensionStoreUrl, openTabForPerson, sendExtensionMark, startExtensionRecording, stopExtensionRecording, } from "./chromeExtensionCapture.js";
33
- import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
33
+ import { browserLogin, LOGIN_SCOPES, shouldUseManualLogin } from "./browserLogin.js";
34
34
  import { openUrl } from "./openUrl.js";
35
35
  import { cmdContextImport } from "./context/importCmd.js";
36
36
  import { cmdContextRead } from "./context/readCmd.js";
37
37
  import { errorEnvelope } from "./context/errors.js";
38
38
  import { supportsWebp } from "./context/ffmpeg.js";
39
39
  import { renderProofFrames } from "./proofFrames.js";
40
+ import { cmdAnalytics, cmdComment, cmdComments, cmdDelete, cmdDiagnostics, cmdFolders, cmdInteractions, cmdOrganize, cmdShare, cmdUpdate, failure, } from "./library.js";
40
41
  import { waitForAgentContext } from "./agentReadiness.js";
41
42
  import { BridgeUnavailableError, bridgeRequest, inspectBridge, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, probeSocketOpenable, probeBridgeHandshake, bridgeInfoFromFile, bridgeAppOutdated, MIN_BRIDGE_APP_VERSION, describeWindow, describeDisplay, resolveFromSources, } from "./macBridge.js";
42
43
  import { defaultDisplay, describeCaps, ffmpegCaps, isWaylandSession, listLinuxSources, orphanedCaptureProcesses, parseDisplaySize, realRunner, startScreenRecorder, startVirtualDisplay, } from "./linuxScreen.js";
@@ -239,6 +240,19 @@ function normalizeId(input, ctx) {
239
240
  // ---------------------------------------------------------------------------
240
241
  // Output helpers
241
242
  // ---------------------------------------------------------------------------
243
+ /** The helpers library.ts commands need, bound to this invocation. */
244
+ function libraryDeps(ctx, json) {
245
+ return {
246
+ apiUrl: ctx.apiUrl,
247
+ apiKey: ctx.apiKey,
248
+ version: VERSION,
249
+ json,
250
+ normalizeId: (input) => normalizeId(input, ctx),
251
+ die,
252
+ printJson,
253
+ color: c,
254
+ };
255
+ }
242
256
  function printJson(data) {
243
257
  process.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
244
258
  }
@@ -303,6 +317,7 @@ ${c.bold("AUTH")}
303
317
  login --no-browser Copy-code flow for SSH/headless: open the URL anywhere, paste the code back
304
318
  login --key <clipy_sk_live_…> Skip the browser: store a key you pasted
305
319
  login --paste Prompt for a pasted key instead of the browser
320
+ login --allow-delete Also allow \`clipy delete\` (permanent; off by default)
306
321
  logout Delete the stored key
307
322
  whoami Check which key is active and that it works
308
323
 
@@ -345,6 +360,43 @@ ${c.bold("RECORDINGS")}
345
360
  open <id> Open the share page in your browser
346
361
  wait <id> [--for transcript|summary|both] [--timeout <sec>]
347
362
  Block until processing artifacts are ready
363
+ upload <file> [--title <t>] [--type kind] [--access mode] [--note '12: text']…
364
+ Upload an existing WebM, MP4 or MOV file to
365
+ your library (needs "ingest"). --wait, --json
366
+
367
+ ${c.bold("MANAGE")} ${c.dim("(needs recordings:write; comments needs comments:read, comment comments:write, analytics analytics:read)")}
368
+ update <id> [--title <t>] [--description <d> | --clear-description]
369
+ Rename a recording or edit its description
370
+ share <id> [public|restricted|private]
371
+ Show or change who can open the share link
372
+ organize <id> [--folder <name|id> | --no-folder] [--tag <t>]… [--untag <t>]…
373
+ File into a folder and add or remove tags
374
+ folders [--create <name>] List folders (with ids), or create one
375
+ comments <id> [--json] The comment thread, with timestamps
376
+ comment <id> "<text>" [--at <sec> | --reply-to <comment-id>]
377
+ Comment at a moment, or reply, as you
378
+ analytics <id> [--range <days>] Lifetime views, unique viewers, completion,
379
+ who watched (detail is Pro); --range sets
380
+ the days in the daily series
381
+ delete <id> --yes Permanently delete a recording. Needs a key
382
+ from \`clipy login --allow-delete\`
383
+
384
+ ${c.bold("BUG EVIDENCE")} ${c.dim("(captured by the Chrome extension's bug capture, or browsers Clipy drives)")}
385
+ diagnostics <id> [--errors] [--console] [--network] [--json]
386
+ Console logs, uncaught errors, network
387
+ requests and the browser/OS/viewport of a
388
+ recording. Alias: logs
389
+ --errors Only what went wrong: console errors, exceptions, failed
390
+ requests (combine with --console or --network to narrow)
391
+ --levels <l,…> Console levels: debug, info, log, warn, error
392
+ --status <s> Network status: 5xx, 4xx, 404, failed
393
+ --method/--host Narrow network requests
394
+ --bodies <b> Request/response bodies: none, errors, all
395
+ --limit/--after Page through long captures (max 500 per page)
396
+ interactions <id> [--types click,dwell,…] [--from-ms N] [--to-ms N]
397
+ Clicks, scrolls, typing and pauses with
398
+ the element labels and frame evidence;
399
+ page with --cursor <nextCursor>
348
400
 
349
401
  ${c.bold("PROOF")} ${c.dim("(tool-neutral evidence; needs an ingest-scoped API key)")}
350
402
  proof --frame <png|jpg|webp> [--frame <image> ...]
@@ -555,10 +607,10 @@ async function cmdLogin(ctx, opts) {
555
607
  // --no-browser, SSH sessions, and display-less Linux take the copy-code
556
608
  // flow: this machine can't receive the loopback redirect (or can't open a
557
609
  // browser at all), so the approval page shows a code to paste back here.
558
- await loginWithBrowser(ctx, opts.noBrowser || shouldUseManualLogin());
610
+ await loginWithBrowser(ctx, opts.noBrowser || shouldUseManualLogin(), opts.allowDelete ? [...LOGIN_SCOPES, "recordings:delete"] : undefined);
559
611
  }
560
612
  /** Browser-approve flow (the default): open clipy.online, approve, store. */
561
- async function loginWithBrowser(ctx, manual) {
613
+ async function loginWithBrowser(ctx, manual, scopes) {
562
614
  process.stderr.write(`${c.dim(manual ? "approve this device from a browser on any machine…" : "opening your browser to approve this device…")}\n`);
563
615
  let result;
564
616
  try {
@@ -566,6 +618,7 @@ async function loginWithBrowser(ctx, manual) {
566
618
  apiUrl: ctx.apiUrl,
567
619
  log: (m) => process.stderr.write(`${m}\n`),
568
620
  manual,
621
+ scopes,
569
622
  promptCode: manual
570
623
  ? () => promptVisible("Paste the approval code shown in the browser: ")
571
624
  : undefined,
@@ -1630,14 +1683,15 @@ async function ingestPostJson(ctx, path, payload) {
1630
1683
  }
1631
1684
  if (!res.ok) {
1632
1685
  const msg = (typeof body.error === "string" && body.error) || `Clipy API error ${res.status}`;
1686
+ const code = typeof body.code === "string" ? body.code : undefined;
1633
1687
  if (res.status === 401) {
1634
- throw ingestError(`${msg}. Run \`clipy login\` with an ingest-scoped key.`, res.status);
1688
+ throw ingestError(`${msg}. Run \`clipy login\` with an ingest-scoped key.`, res.status, code);
1635
1689
  }
1636
1690
  if (res.status === 403) {
1637
1691
  throw ingestError(`${msg}\nYour API key needs the "ingest" permission. Mint one at ` +
1638
- `${ctx.apiUrl}/settings/api-keys (check "Record & upload").`, res.status);
1692
+ `${ctx.apiUrl}/settings/api-keys (check "Record & upload").`, res.status, code);
1639
1693
  }
1640
- throw ingestError(msg, res.status);
1694
+ throw ingestError(msg, res.status, code);
1641
1695
  }
1642
1696
  return body;
1643
1697
  }
@@ -1645,8 +1699,22 @@ async function ingestPostJson(ctx, path, payload) {
1645
1699
  }
1646
1700
  // Error with the HTTP status attached so callers can branch on it (e.g. the
1647
1701
  // best-effort read receipt treats owner-scope 404 as "not mine", not a failure).
1648
- function ingestError(message, status) {
1649
- return Object.assign(new Error(message), { status });
1702
+ function ingestError(message, status, code) {
1703
+ return Object.assign(new Error(message), { status, ...(code ? { code } : {}) });
1704
+ }
1705
+ /**
1706
+ * Whether a failed /complete may have committed unseen: no HTTP response at
1707
+ * all (network error, timeout), or a 502/504 from the gateway in front of the
1708
+ * app. Every answer the route itself gives (503 access_mode_pending, a 500
1709
+ * that marked the recording failed) is explicit and never a success.
1710
+ */
1711
+ /** /complete answers that mean the recording exists or is being committed. */
1712
+ const PENDING_COMPLETION_CODES = new Set(["access_mode_pending", "queue_pending", "claim_pending"]);
1713
+ function completionWasAmbiguous(error) {
1714
+ const { status, code } = error;
1715
+ if (typeof status !== "number")
1716
+ return true;
1717
+ return !code && (status === 502 || status === 504);
1650
1718
  }
1651
1719
  /** Upload one chunk as multipart/form-data, retrying transient 429/5xx. */
1652
1720
  async function ingestPostChunk(ctx, recordingId, uploadToken, partNumber, bytes, container = "webm") {
@@ -2022,13 +2090,12 @@ async function uploadVideoToClipy(ctx, opts) {
2022
2090
  let publicId = "";
2023
2091
  try {
2024
2092
  // 1) initiate → uploadToken + the video row (createVideoRow so the share
2025
- // link exists immediately). The existing CLI/raw-upload contract uses
2026
- // sourcePlatform "web"; sourceVersion carries `cli-proof/*` provenance
2027
- // until the backend grows provider-specific source metadata.
2093
+ // link exists immediately). Servers that predate "cli" store "web" and
2094
+ // the sourceVersion prefix (`cli/`, `cli-proof/`) still identifies us.
2028
2095
  const init = await ingestPostJson(ctx, "/api/videos/raw-upload/initiate", {
2029
2096
  recordingId,
2030
2097
  createVideoRow: true,
2031
- sourcePlatform: "web",
2098
+ sourcePlatform: "cli",
2032
2099
  sourceVersion,
2033
2100
  });
2034
2101
  uploadToken = String(init.uploadToken ?? "");
@@ -2075,8 +2142,10 @@ async function uploadVideoToClipy(ctx, opts) {
2075
2142
  uploadToken,
2076
2143
  name: opts.name,
2077
2144
  description: opts.description,
2078
- sourcePlatform: "web",
2145
+ sourcePlatform: "cli",
2079
2146
  sourceVersion,
2147
+ ...(opts.accessMode ? { accessMode: opts.accessMode } : {}),
2148
+ ...(opts.nameIsUserProvided && opts.name ? { nameIsUserProvided: true } : {}),
2080
2149
  ...(opts.recordingKind ? { recordingKind: opts.recordingKind } : {}),
2081
2150
  ...(opts.narration && (opts.narration.text || opts.narration.notes?.length)
2082
2151
  ? { narration: opts.narration }
@@ -2104,10 +2173,33 @@ async function uploadVideoToClipy(ctx, opts) {
2104
2173
  catch (e) {
2105
2174
  // Best-effort: release the half-uploaded streaming session so it doesn't
2106
2175
  // sit as an orphan (the server also janitors orphans after 8 days).
2176
+ // A /complete whose responses were all lost may still have committed;
2177
+ // the server then refuses the abort with 409 already_attached, which
2178
+ // proves the recording exists. Reporting failure would invite a duplicate.
2179
+ // An explicit answer from the route (503 access_mode_pending, queue_pending,
2180
+ // claim_pending) is not a success, but the recording exists: the error
2181
+ // names it so the caller never uploads the file again.
2182
+ // A coded pending answer already says the recording exists or is being
2183
+ // committed: name it directly, without depending on an abort that could
2184
+ // itself fail, and without aborting a commit still in flight.
2185
+ const pendingCode = e.code;
2186
+ if (publicId && pendingCode && PENDING_COMPLETION_CODES.has(pendingCode)) {
2187
+ throw Object.assign(e, { publicId });
2188
+ }
2189
+ let attached = false;
2107
2190
  if (uploadToken) {
2108
- await ingestPostJson(ctx, "/api/videos/raw-upload/abort", { recordingId, uploadToken }).catch(() => { });
2191
+ await ingestPostJson(ctx, "/api/videos/raw-upload/abort", { recordingId, uploadToken }).catch((abortError) => {
2192
+ attached = abortError.status === 409;
2193
+ });
2194
+ }
2195
+ if (publicId && attached) {
2196
+ if (!completionWasAmbiguous(e))
2197
+ throw Object.assign(e, { publicId });
2198
+ // otherwise fall through to the success result
2199
+ }
2200
+ else {
2201
+ throw e;
2109
2202
  }
2110
- throw e;
2111
2203
  }
2112
2204
  return {
2113
2205
  publicId,
@@ -2119,6 +2211,103 @@ async function uploadVideoToClipy(ctx, opts) {
2119
2211
  container,
2120
2212
  };
2121
2213
  }
2214
+ // ---------------------------------------------------------------------------
2215
+ // upload: put an existing video file into the library. The same pipeline as
2216
+ // `proof --video`, but titled after the file and meant for ordinary videos
2217
+ // (a screen recording made elsewhere, a demo, a bug repro from a teammate).
2218
+ // ---------------------------------------------------------------------------
2219
+ async function cmdUpload(ctx, file, opts) {
2220
+ const fail = (code, message, remediation, exitCode = 1, partial = null) => failure({ json: opts.json, die }, code, message, remediation, exitCode, partial);
2221
+ if (!ctx.apiKey) {
2222
+ fail("auth_required", "no API key", "Run `clipy login` to approve this device, or set CLIPY_API_KEY.");
2223
+ }
2224
+ const videoPath = resolve(file);
2225
+ if (!existsSync(videoPath)) {
2226
+ fail("source_unreadable", `no such file: ${videoPath}`, "Check the path; nothing was uploaded.");
2227
+ }
2228
+ let accessMode;
2229
+ if (opts.accessMode !== undefined) {
2230
+ if (!["public", "restricted", "private"].includes(opts.accessMode)) {
2231
+ fail("usage_error", "--access must be public, restricted or private", "Fix the arguments.", 2);
2232
+ }
2233
+ accessMode = opts.accessMode;
2234
+ }
2235
+ const log = (message) => {
2236
+ if (!opts.json)
2237
+ process.stderr.write(`${message}\n`);
2238
+ };
2239
+ const title = opts.name ?? basename(videoPath, extname(videoPath));
2240
+ let uploaded;
2241
+ try {
2242
+ const notes = resolveNarrationNotes(opts.notes, [0]).sort((a, b) => a.startMs - b.startMs);
2243
+ uploaded = await uploadVideoToClipy(ctx, {
2244
+ videoPath,
2245
+ name: title,
2246
+ nameIsUserProvided: opts.name !== undefined,
2247
+ description: opts.description,
2248
+ recordingKind: opts.recordingKind,
2249
+ narration: notes.length > 0 ? { notes } : undefined,
2250
+ accessMode,
2251
+ sourceVersion: `cli/${VERSION}`,
2252
+ log,
2253
+ });
2254
+ }
2255
+ catch (error) {
2256
+ const message = error.message;
2257
+ const status = error.status;
2258
+ if (status === undefined && /not valid WebM or MP4|empty file|not a file/i.test(message)) {
2259
+ fail("source_unreadable", message, "Upload a WebM, MP4 or MOV file; nothing was uploaded.");
2260
+ }
2261
+ const stranded = error.publicId;
2262
+ if (stranded) {
2263
+ const partial = { id: stranded, shareUrl: `${ctx.apiUrl}/video/${stranded}` };
2264
+ if (error.code === "access_mode_pending") {
2265
+ fail("sharing_not_applied", `uploaded as ${stranded}, but the ${accessMode ?? "requested"} sharing could not be applied, so it may still be readable at the account's default access`, `Do not upload again. Set the sharing on the existing recording: clipy share ${stranded} ${accessMode ?? "private"}`, 1, partial);
2266
+ }
2267
+ fail("upload_unconfirmed", `uploaded as ${stranded}, but the server did not confirm its completion: ${message}`, `Do not upload again; the recording exists. Check it with: clipy show ${stranded}`, 1, partial);
2268
+ }
2269
+ if (status === 401)
2270
+ fail("auth_required", message, "Run `clipy login` to set a new key, then retry.");
2271
+ if (status === 429 || (status === 403 && /pro|allowance|recordings or|minutes/i.test(message))) {
2272
+ fail("quota_exceeded", message, "Report the limit to the user and stop; retrying only burns it.");
2273
+ }
2274
+ if (status === 403) {
2275
+ fail("wrong_scope", message, 'The key needs "ingest": run `clipy login` again, or create one at /settings/api-keys.');
2276
+ }
2277
+ fail("unknown", message, "Re-run once; if it fails again, report this output as a bug.");
2278
+ }
2279
+ // The recording exists from here on. A failed wait is a warning on a
2280
+ // successful result, never a failure: a caller that saw a failure would
2281
+ // upload the same file again and create a duplicate.
2282
+ const warnings = [];
2283
+ if (opts.wait) {
2284
+ const waitError = await waitForArtifactsSafely(ctx, uploaded.publicId);
2285
+ if (waitError) {
2286
+ warnings.push({
2287
+ code: "wait_incomplete",
2288
+ error: `uploaded, but waiting for processing failed: ${waitError}`,
2289
+ remediation: `Do not upload again. Check progress with: clipy wait ${uploaded.publicId} --for both`,
2290
+ });
2291
+ }
2292
+ }
2293
+ if (opts.json) {
2294
+ printJson({
2295
+ ok: true,
2296
+ id: uploaded.publicId,
2297
+ shareUrl: uploaded.shareUrl,
2298
+ contextUrl: uploaded.contextUrl,
2299
+ sizeBytes: uploaded.sizeBytes,
2300
+ container: uploaded.container,
2301
+ warnings,
2302
+ });
2303
+ return;
2304
+ }
2305
+ process.stdout.write(`${c.green("✓")} uploaded: ${c.bold(uploaded.shareUrl)}\n`);
2306
+ process.stdout.write(`${c.dim("agent context:")} ${uploaded.contextUrl}\n`);
2307
+ for (const warning of warnings) {
2308
+ process.stderr.write(`${c.yellow("warning:")} ${warning.error}\n ${warning.remediation}\n`);
2309
+ }
2310
+ }
2122
2311
  /**
2123
2312
  * Creates a shareable proof recording from screenshots supplied by any agent
2124
2313
  * tool, or uploads a WebM/MP4 that tool already recorded. This path deliberately
@@ -2844,6 +3033,44 @@ async function cmdRecord(ctx, opts) {
2844
3033
  process.stdout.write(`${c.dim("next:")} clipy context ${uploaded.publicId} · clipy transcript ${uploaded.publicId}\n`);
2845
3034
  }
2846
3035
  /** Poll until the transcript reaches a terminal state (or ~5 min elapse). */
3036
+ /**
3037
+ * waitForArtifacts without the exits: returns null once the transcript is
3038
+ * terminal (or the five-minute deadline passes, as waitForArtifacts does) and
3039
+ * an error message instead of calling die(). For callers whose real work has
3040
+ * already succeeded and must not be reported as failed.
3041
+ */
3042
+ async function waitForArtifactsSafely(ctx, publicId) {
3043
+ const key = ctx.apiKey;
3044
+ if (!key)
3045
+ return "no API key";
3046
+ const url = `${ctx.apiUrl}/api/v1/recordings/${encodeURIComponent(publicId)}/transcript`;
3047
+ const deadline = Date.now() + 300_000;
3048
+ const terminal = new Set(["ready", "failed", "none"]);
3049
+ for (;;) {
3050
+ const controller = new AbortController();
3051
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
3052
+ try {
3053
+ const res = await fetch(url, {
3054
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json", "User-Agent": `clipy-cli/${VERSION}` },
3055
+ signal: controller.signal,
3056
+ });
3057
+ if (!res.ok)
3058
+ return `HTTP ${res.status}`;
3059
+ const body = (await res.json());
3060
+ if (terminal.has(String(body.status)))
3061
+ return null;
3062
+ }
3063
+ catch (e) {
3064
+ return e.name === "AbortError" ? "request timed out" : e.message;
3065
+ }
3066
+ finally {
3067
+ clearTimeout(timer);
3068
+ }
3069
+ if (Date.now() >= deadline)
3070
+ return null;
3071
+ await new Promise((r) => setTimeout(r, 3000));
3072
+ }
3073
+ }
2847
3074
  async function waitForArtifacts(ctx, publicId) {
2848
3075
  const pid = encodeURIComponent(publicId);
2849
3076
  const deadline = Date.now() + 300_000;
@@ -6105,7 +6332,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
6105
6332
  // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
6106
6333
  // contract changes.
6107
6334
  // ---------------------------------------------------------------------------
6108
- const GUIDE_SCHEMA_VERSION = 17;
6335
+ const GUIDE_SCHEMA_VERSION = 18;
6109
6336
  /** The stable machine-readable failure taxonomy carried in `--json` error
6110
6337
  * envelopes. Codes are the contract; messages are not. Published through the
6111
6338
  * guide so an agent discovers the full recovery table without the skill. */
@@ -6119,13 +6346,19 @@ const GUIDE_ERROR_CODES = [
6119
6346
  { code: "ffmpeg_missing", meaning: "ffmpeg/ffprobe is not installed or not on PATH", retryable: true, remediation: "brew install ffmpeg (macOS) / sudo apt install ffmpeg (Linux) / winget install Gyan.FFmpeg, then re-run the same command" },
6120
6347
  { code: "no_video_stream", meaning: "the file carries no decodable video track", retryable: false, remediation: "audio-only source — import transcript-only with --no-frames, or supply the real video file" },
6121
6348
  { code: "auth_required", meaning: "HTTP 401 — no API key, or the key is invalid/revoked", retryable: true, remediation: "run `clipy login` and WAIT for the user to approve the device in the browser it opens (`clipy login --no-browser` on headless hosts); retry only after login returns" },
6122
- { code: "wrong_scope", meaning: "HTTP 403 — the key is valid but lacks a required permission", retryable: false, remediation: "write paths need the 'ingest' scope — mint a key carrying it at /settings/api-keys; re-running with the same key cannot help" },
6349
+ { code: "wrong_scope", meaning: "HTTP 403 — the key is valid but lacks a required permission", retryable: false, remediation: "the error names the missing scope: recording/upload needs 'ingest', update/share/organize need 'recordings:write', comments needs 'comments:read', comment needs 'comments:write', analytics needs 'analytics:read', delete needs 'recordings:delete' (clipy login --allow-delete). Mint a key carrying it at /settings/api-keys; re-running with the same key cannot help" },
6123
6350
  { code: "quota_exceeded", meaning: "HTTP 429 — the account hit a plan or rate limit", retryable: false, remediation: "report the quota to the user and STOP; a retry loop only burns the limit. Any local bundle already produced remains readable" },
6124
6351
  { code: "frames_upload_failed", meaning: "the transcript synced but the frames did not", retryable: true, remediation: "PARTIAL SUCCESS, not a failure — the document exists and is readable. Re-run the SAME import command later to complete it; never re-import from scratch" },
6125
6352
  { code: "server_unreachable", meaning: "the Clipy API could not be reached", retryable: true, remediation: "check `clipy doctor --json`'s api check; a local (non --sync) bundle is still complete and readable with `clipy context read`" },
6126
6353
  { code: "transcript_unreadable", meaning: "the --transcript file could not be parsed", retryable: false, remediation: "confirm it is a real .vtt/.srt/Clipy transcript JSON and not empty or an HTML error page; ask the user for the right file rather than guessing another path" },
6127
6354
  { code: "source_unreadable", meaning: "the local video file could not be opened or probed", retryable: false, remediation: "verify the path exists and is readable (unmounted volume, still downloading, wrong container) — not retryable until the file is" },
6128
6355
  { code: "content_conflict", meaning: "a different video already occupies that document", retryable: false, remediation: "do NOT overwrite — show the user both and let them choose; re-running unchanged conflicts again" },
6356
+ { code: "usage_error", meaning: "the command's arguments are wrong or missing (exit 2)", retryable: false, remediation: "fix the arguments; this manifest lists every command's usage and flags" },
6357
+ { code: "not_found", meaning: "HTTP 404: no recording or folder with that id or name in this account", retryable: false, remediation: "look the id up with `clipy list --json` (or the folder with `clipy folders --json`); ids from another account never resolve" },
6358
+ { code: "invalid_request", meaning: "the API refused the request as sent (HTTP 400, 409 or 422)", retryable: false, remediation: "read `error`, change the request accordingly; re-running unchanged fails the same way" },
6359
+ { code: "confirmation_required", meaning: "a permanent action (clipy delete) was run without --yes (exit 2)", retryable: false, remediation: "only if the user asked for that exact recording to be deleted, re-run with --yes" },
6360
+ { code: "upload_unconfirmed", meaning: "the upload became a recording, but the server never confirmed its completion (still being committed or queued)", retryable: false, remediation: "do NOT upload again (that creates a duplicate); check the recording in partial.id with `clipy show <id>`" },
6361
+ { code: "sharing_not_applied", meaning: "the upload became a recording, but the requested public/restricted/private sharing could not be applied", retryable: false, remediation: "do NOT upload again (that creates a duplicate); run the `clipy share <id> <mode>` in the remediation, using partial.id" },
6129
6362
  { code: "unknown", meaning: "an unclassified failure", retryable: true, remediation: "re-run once; if it repeats, hand the user the whole envelope as a bug report rather than improvising a workaround" },
6130
6363
  ];
6131
6364
  function cmdGuide(json) {
@@ -6149,12 +6382,12 @@ function cmdGuide(json) {
6149
6382
  jsonFlag: "--json",
6150
6383
  stdout: "primary results (JSON when --json is set) — THE SOURCE OF TRUTH",
6151
6384
  stderr: "progress, warnings, and install disclosures; narration only, never part of the contract, never JSON. Do not parse it and do not infer success or failure from it.",
6152
- errors: "exit non-zero with a message on stderr prefixed 'error:'. Under --json, `context import` prints exactly ONE object on stdout either way: a failure is {ok:false, code, error, remediation, partial} — branch on `code` (stable, see errorCodes), never on `error` text; `remediation` is the next action, written to be run verbatim where possible; `partial` holds whatever survived (e.g. {bundlePath}) or null.",
6385
+ errors: "exit non-zero with a message on stderr prefixed 'error:'. Under --json, `context import` and the library commands (upload, update, share, organize, folders, comments, comment, analytics, delete, diagnostics, interactions) print exactly ONE object on stdout either way: a failure is {ok:false, code, error, remediation, partial} — branch on `code` (stable, see errorCodes), never on `error` text; `remediation` is the next action, written to be run verbatim where possible; `partial` holds whatever survived (e.g. {bundlePath}) or null.",
6153
6386
  success: "{ok:true, …} always carries a `warnings` array — empty when nothing went wrong. A PARTIAL success (transcript synced, frames missing) is ok:true with entries in `warnings`, each {code, error, remediation}, and exits 0. Read the warnings; do not read them as failure.",
6154
6387
  neverInventSuccess: "If no readable result was printed, the work did not happen. Never report an import, recording, or frame capture as done because the command appeared to run.",
6155
6388
  },
6156
6389
  env: [
6157
- { name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; write commands need the 'ingest' scope" },
6390
+ { name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; record/upload/proof need 'ingest', update/share/organize need 'recordings:write', comments needs 'comments:read', comment needs 'comments:write', analytics needs 'analytics:read', delete needs 'recordings:delete'" },
6158
6391
  { name: "CLIPY_API_URL", description: "API base URL override (default https://clipy.online)" },
6159
6392
  { name: "CLIPY_DISABLE_CDP", description: "set to 1 to force session --expose-cdp off (a hard kill switch that wins over the flag)" },
6160
6393
  { name: "CLIPY_SESSION_FILE", description: "path to a session state file that mark/chapter/session stop|abort|status resolve FIRST (before the cwd hash). `session run` exports it to the child so a driver can mark from any cwd." },
@@ -6174,7 +6407,7 @@ function cmdGuide(json) {
6174
6407
  tellTheUser: "Say plainly: imported and readable, frames pending, and which timestamps are affected (the classifier already names them in the bundle's sufficiency report).",
6175
6408
  },
6176
6409
  commands: [
6177
- cmdDoc("login", "clipy login [--no-browser] [--key <key>] [--paste]", "Approve this device in the browser (default). --no-browser (auto-detected on SSH and display-less Linux) prints the approval URL to open on any device and prompts for the code it shows. --key/--paste store a pasted key (also the automatic path when stdout is not a TTY)", ["--no-browser", "--key <key>", "--paste"]),
6410
+ cmdDoc("login", "clipy login [--no-browser] [--allow-delete] [--key <key>] [--paste]", "Approve this device in the browser (default). The approved key reads, organizes, comments and uploads; --allow-delete adds the permanent-delete permission. --no-browser (auto-detected on SSH and display-less Linux) prints the approval URL to open on any device and prompts for the code it shows. --key/--paste store a pasted key (also the automatic path when stdout is not a TTY)", ["--no-browser", "--key <key>", "--paste"]),
6178
6411
  cmdDoc("logout", "clipy logout", "Delete the stored key"),
6179
6412
  cmdDoc("whoami", "clipy whoami", "Check the active key"),
6180
6413
  cmdDoc("list", "clipy list [-n N] [--page P] [--status s,…] [--json]", "List recordings, newest first"),
@@ -6187,6 +6420,17 @@ function cmdGuide(json) {
6187
6420
  cmdDoc("context", "clipy context <id>", "Full agent-context bundle as markdown"),
6188
6421
  cmdDoc("context import", "clipy context import <youtube-url|loom-url|local-file> [--transcript <f>] [--output <dir>] [--language <code>] [--title <t>] [--tag <t>]… [--folder <name>] [--sync] [--json]", "Compile ANY video into a local Clipy context bundle — a directory holding recording.arec (the canonical agent-facing Markdown document), a byte-identical recording.md compatibility copy, manifest.json (provenance, versions, sufficiency report) and transcript.json. YouTube URLs resolve on YOUR machine via a Clipy-managed yt-dlp (auto-installed into ~/.clipy/bin on first use, with a disclosure); creator captions are preferred over auto-captions and NO media is downloaded. Loom share links (loom.com/share/<32-hex-id>) use Loom's own published transcript over plain HTTPS — no yt-dlp is needed and none is installed, so `clipy doctor`'s yt-dlp check does not gate a Loom import; roughly one Loom in six has no transcript recorded and fails with `no_captions` rather than emitting an empty bundle, and Loom's transcript is machine-generated so it is recorded as auto_captions. Local files need --transcript <.vtt|.srt|Clipy transcript JSON> and are probed with ffprobe. A deterministic classifier scores how well the transcript stands alone and lists the timestamps where it is blind — v1 emits the transcript profile only, so those gaps are the honest statement of what the bundle cannot show. Reruns over the same source are idempotent. --sync additionally uploads the DERIVED bundle (never source media) to your private library.", ["--transcript", "--output", "--language", "--title", "--tag", "--folder", "--sync", "--no-frames", "--json"]),
6189
6422
  cmdDoc("context read", "clipy context read <bundle-path>", "Print a local bundle's recording.arec to stdout — plain, unpaged, uncoloured, for an agent to read directly. It opens with a self-describing header (source, duration, classification, sufficiency, untrusted-content warning) before the [MM:SS] transcript sections, so the first screen tells you what the document is and where it is blind. For a SYNCED document read it over MCP instead: get_context_document for metadata+classification without the transcript, then read_context_document with startMs/endMs for just the span you need."),
6423
+ cmdDoc("upload", "clipy upload <file> [--title t] [--description d] [--type kind] [--access public|restricted|private] [--note '12: text']… [--wait] [--json]", "Upload an existing WebM/MP4/MOV file to the library through the same pipeline as recordings (needs 'ingest'; counts toward the recording allowance). JSON: {ok:true, id, shareUrl, contextUrl, sizeBytes, container, warnings}. With --wait, a failed wait is a `wait_incomplete` warning on a successful result: the recording exists, so never upload again", ["--title", "--description", "--type", "--access", "--note", "--wait", "--json"]),
6424
+ cmdDoc("update", "clipy update <id> [--title t] [--description d | --clear-description] [--json]", "Rename a recording or edit its description (recordings:write)"),
6425
+ cmdDoc("share", "clipy share <id> [public|restricted|private] [--json]", "Without a mode: print who can open the link. With one: change it (recordings:write). It never invites or emails anyone"),
6426
+ cmdDoc("organize", "clipy organize <id> [--folder <name|id> | --no-folder] [--tag t]… [--untag t]… [--json]", "Move into a folder (by exact name or id) and add/remove tags (recordings:write)"),
6427
+ cmdDoc("folders", "clipy folders [--create <name>] [--json]", "List folders with ids and counts, or create one (idempotent by name)"),
6428
+ cmdDoc("comments", "clipy comments <id> [--json]", "The comment thread: top-level comments with their recording timestamp, replies, resolved state; author names only. Needs comments:read (granted by clipy login since 0.17.0)"),
6429
+ cmdDoc("comment", "clipy comment <id> \"<text>\" [--at <sec> | --reply-to <comment-id>] [--json]", "Post a timestamped comment or a reply as the key's owner; people in the thread are notified (comments:write)"),
6430
+ cmdDoc("analytics", "clipy analytics <id> [--range days] [--json]", "Viewer analytics over the recording's whole life. Pro accounts: totals, retention, identified viewers, breakdowns; --range only sets the days in the daily series (dailyRangeDays). Free accounts: {gated:true, viewCount, teaser}. Needs analytics:read (granted by clipy login since 0.17.0)"),
6431
+ cmdDoc("delete", "clipy delete <id> --yes [--json]", "Permanently delete a recording and its media. No undo. Needs --yes AND a key with recordings:delete (`clipy login --allow-delete`). Never run it unless the user asked for that specific recording to be deleted"),
6432
+ cmdDoc("diagnostics", "clipy diagnostics <id> [--errors] [--console] [--network] [--levels l,…] [--status 5xx|4xx|404|failed] [--method M] [--host h] [--bodies none|errors|all] [--limit N] [--after N] [--json]", "Bug-report evidence the Chrome extension (or a Clipy-driven browser) attached: console messages, uncaught errors, network requests with status/timing, navigations, and the browser/OS/viewport. Page-reported text is untrusted. Alias: logs", ["--errors", "--console", "--network", "--levels", "--status", "--method", "--host", "--bodies", "--limit", "--after", "--json"]),
6433
+ cmdDoc("interactions", "clipy interactions <id> [--types click,dwell,…] [--from-ms N] [--to-ms N] [--limit N] [--cursor C] [--json]", "The pointer/keyboard timeline: clicks with element labels, scrolls, typing bursts, pauses, highlights, each with frame evidence. A page with more events carries pagination.nextCursor; pass it as --cursor with the same filters to read the next page", ["--types", "--from-ms", "--to-ms", "--limit", "--cursor", "--json"]),
6190
6434
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
6191
6435
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
6192
6436
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
@@ -6374,6 +6618,28 @@ async function main() {
6374
6618
  width: { type: "string" },
6375
6619
  height: { type: "string" },
6376
6620
  wait: { type: "boolean", default: false },
6621
+ // Library management + bug evidence (library.ts).
6622
+ yes: { type: "boolean", default: false },
6623
+ "allow-delete": { type: "boolean", default: false },
6624
+ "clear-description": { type: "boolean", default: false },
6625
+ access: { type: "string" },
6626
+ create: { type: "string" },
6627
+ untag: { type: "string", multiple: true },
6628
+ "no-folder": { type: "boolean", default: false },
6629
+ "reply-to": { type: "string" },
6630
+ range: { type: "string" },
6631
+ console: { type: "boolean", default: false },
6632
+ network: { type: "boolean", default: false },
6633
+ errors: { type: "boolean", default: false },
6634
+ levels: { type: "string" },
6635
+ method: { type: "string" },
6636
+ host: { type: "string" },
6637
+ bodies: { type: "string" },
6638
+ after: { type: "string" },
6639
+ types: { type: "string" },
6640
+ "from-ms": { type: "string" },
6641
+ "to-ms": { type: "string" },
6642
+ cursor: { type: "string" },
6377
6643
  version: { type: "boolean", short: "v", default: false },
6378
6644
  help: { type: "boolean", short: "h", default: false },
6379
6645
  },
@@ -6461,12 +6727,16 @@ async function main() {
6461
6727
  const webAudioGuard = "--mic/--no-system-audio apply to --source mac-screen only — headless web captures record no audio at all, so there is nothing to turn on or off";
6462
6728
  const linuxAudioGuard = "--mic/--no-system-audio: Linux screen recordings are silent for now (narrate with clipy mark); drop the audio flag";
6463
6729
  const macAuthGuard = "auth state (--storage-state/--user-data-dir/--cookie/--local-storage/--init-script) applies to headless web capture — --source mac-screen records the real, already-logged-in screen";
6730
+ // Usage errors for the library commands honour --json like their API
6731
+ // errors do: one {ok:false, code:"usage_error", …} object on stdout.
6732
+ const usageFail = (message) => failure({ json, die }, "usage_error", message, "Fix the arguments; `clipy guide --json` lists every command's flags.", 2);
6464
6733
  switch (command) {
6465
6734
  case "login":
6466
6735
  await cmdLogin(ctx, {
6467
6736
  key: values.key,
6468
6737
  paste: Boolean(values.paste),
6469
6738
  noBrowser: Boolean(values["no-browser"]),
6739
+ allowDelete: Boolean(values["allow-delete"]),
6470
6740
  });
6471
6741
  return;
6472
6742
  case "logout":
@@ -6586,6 +6856,142 @@ async function main() {
6586
6856
  await cmdContext(ctx, rest[0]);
6587
6857
  return;
6588
6858
  }
6859
+ case "upload": {
6860
+ const file = rest[0] ?? values.video;
6861
+ if (!file)
6862
+ usageFail('usage: clipy upload <file.mp4|webm|mov> [--title "<t>"] [--type kind] [--access public|restricted|private] [--wait] [--json]', 2);
6863
+ // Validated here, not by requireRecordingKind/parseNoteFlag, whose die()
6864
+ // would print prose and break the one-object --json contract.
6865
+ let uploadKind;
6866
+ if (values.type) {
6867
+ uploadKind = normalizeRecordingKind(String(values.type)) ?? undefined;
6868
+ if (!uploadKind) {
6869
+ usageFail(`--type "${String(values.type)}" is not a recording kind. Accepted: ${RECORDING_KINDS.join(", ")}`);
6870
+ }
6871
+ }
6872
+ const uploadNotes = values.note ?? [];
6873
+ const passNote = uploadNotes.find((note) => /^\s*pass\s*\d/i.test(note));
6874
+ if (passNote !== undefined) {
6875
+ usageFail(`--note "${passNote}": an uploaded file has no passes; use absolute times such as "12: text"`);
6876
+ }
6877
+ await cmdUpload(ctx, file, {
6878
+ name: (values.title ?? values.name)?.trim() || undefined,
6879
+ description: values.description?.trim() || undefined,
6880
+ recordingKind: uploadKind,
6881
+ notes: uploadNotes.map(parseNoteFlag),
6882
+ accessMode: values.access,
6883
+ wait: Boolean(values.wait),
6884
+ json,
6885
+ });
6886
+ return;
6887
+ }
6888
+ case "update":
6889
+ if (!rest[0])
6890
+ usageFail('usage: clipy update <id|url> [--title "<title>"] [--description "<text>" | --clear-description]', 2);
6891
+ await cmdUpdate(libraryDeps(ctx, json), rest[0], {
6892
+ title: values.title ?? values.name,
6893
+ description: values.description,
6894
+ clearDescription: Boolean(values["clear-description"]),
6895
+ });
6896
+ return;
6897
+ case "share":
6898
+ if (!rest[0])
6899
+ usageFail("usage: clipy share <id|url> [public|restricted|private]", 2);
6900
+ await cmdShare(libraryDeps(ctx, json), rest[0], rest[1] ?? values.access);
6901
+ return;
6902
+ case "organize":
6903
+ if (!rest[0])
6904
+ usageFail("usage: clipy organize <id|url> [--folder <name|id> | --no-folder] [--tag <t>]… [--untag <t>]…", 2);
6905
+ await cmdOrganize(libraryDeps(ctx, json), rest[0], {
6906
+ folder: values.folder,
6907
+ noFolder: Boolean(values["no-folder"]),
6908
+ addTags: values.tag ?? [],
6909
+ removeTags: values.untag ?? [],
6910
+ });
6911
+ return;
6912
+ case "folders":
6913
+ await cmdFolders(libraryDeps(ctx, json), { create: values.create });
6914
+ return;
6915
+ case "delete":
6916
+ if (!rest[0])
6917
+ usageFail("usage: clipy delete <id|url> --yes", 2);
6918
+ await cmdDelete(libraryDeps(ctx, json), rest[0], { yes: Boolean(values.yes) });
6919
+ return;
6920
+ case "comments":
6921
+ if (!rest[0])
6922
+ usageFail("usage: clipy comments <id|url> [--json]", 2);
6923
+ await cmdComments(libraryDeps(ctx, json), rest[0]);
6924
+ return;
6925
+ case "comment": {
6926
+ if (!rest[0])
6927
+ usageFail('usage: clipy comment <id|url> "<text>" [--at <seconds> | --reply-to <comment-id>]', 2);
6928
+ const at = values.at;
6929
+ await cmdComment(libraryDeps(ctx, json), rest[0], rest.slice(1).join(" "), {
6930
+ atSeconds: at === undefined
6931
+ ? undefined
6932
+ : Number.isFinite(Number(at)) && Number(at) >= 0
6933
+ ? Number(at)
6934
+ : usageFail("--at must be a non-negative number of seconds"),
6935
+ replyTo: values["reply-to"],
6936
+ });
6937
+ return;
6938
+ }
6939
+ case "analytics": {
6940
+ if (!rest[0])
6941
+ usageFail("usage: clipy analytics <id|url> [--range <days>] [--json]", 2);
6942
+ const range = values.range === undefined ? undefined : Number(values.range);
6943
+ if (range !== undefined && (!Number.isInteger(range) || range < 1 || range > 365)) {
6944
+ usageFail("--range must be a whole number of days from 1 to 365", 2);
6945
+ }
6946
+ await cmdAnalytics(libraryDeps(ctx, json), rest[0], { range });
6947
+ return;
6948
+ }
6949
+ case "diagnostics":
6950
+ case "logs": {
6951
+ if (!rest[0])
6952
+ usageFail("usage: clipy diagnostics <id|url> [--errors] [--console] [--network] [--levels warn,error] [--status 5xx|4xx|failed|404] [--method M] [--host h] [--json]", 2);
6953
+ const optInt = (v, flag) => {
6954
+ if (v === undefined)
6955
+ return undefined;
6956
+ const n = Number(v);
6957
+ if (!Number.isInteger(n) || n < 0)
6958
+ usageFail(`${flag} must be a whole number`, 2);
6959
+ return n;
6960
+ };
6961
+ await cmdDiagnostics(libraryDeps(ctx, json), rest[0], {
6962
+ console: Boolean(values.console),
6963
+ network: Boolean(values.network),
6964
+ errors: Boolean(values.errors),
6965
+ levels: values.levels,
6966
+ status: values.status,
6967
+ method: values.method,
6968
+ host: values.host,
6969
+ bodies: values.bodies,
6970
+ limit: optInt(values.limit, "--limit"),
6971
+ after: optInt(values.after, "--after"),
6972
+ });
6973
+ return;
6974
+ }
6975
+ case "interactions": {
6976
+ if (!rest[0])
6977
+ usageFail("usage: clipy interactions <id|url> [--types click,dwell,…] [--from-ms N] [--to-ms N] [--limit N] [--cursor C] [--json]", 2);
6978
+ const optMs = (v, flag) => {
6979
+ if (v === undefined)
6980
+ return undefined;
6981
+ const n = Number(v);
6982
+ if (!Number.isInteger(n) || n < 0)
6983
+ usageFail(`${flag} must be a whole number of milliseconds`, 2);
6984
+ return n;
6985
+ };
6986
+ await cmdInteractions(libraryDeps(ctx, json), rest[0], {
6987
+ types: values.types,
6988
+ fromMs: optMs(values["from-ms"], "--from-ms"),
6989
+ toMs: optMs(values["to-ms"], "--to-ms"),
6990
+ limit: optMs(values.limit, "--limit"),
6991
+ cursor: values.cursor || undefined,
6992
+ });
6993
+ return;
6994
+ }
6589
6995
  case "download":
6590
6996
  if (!rest[0])
6591
6997
  die("usage: clipy download <id|url> [-o <path>]", 2);