@clipy/cli 0.15.1 → 0.16.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/dist/index.js CHANGED
@@ -13,9 +13,9 @@
13
13
  * override the stored key. Read-only unless the key carries the "ingest" scope.
14
14
  */
15
15
  import { parseArgs } from "node:util";
16
- import { appendFileSync, closeSync, cpSync, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
16
+ import { appendFileSync, closeSync, copyFileSync, cpSync, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
17
17
  import { homedir, tmpdir } from "node:os";
18
- import { basename, dirname, join, resolve } from "node:path";
18
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
19
19
  import { createInterface } from "node:readline";
20
20
  import { spawn } from "node:child_process";
21
21
  import { createHash, randomUUID } from "node:crypto";
@@ -26,8 +26,9 @@ import { pathToFileURL } from "node:url";
26
26
  import { createServer } from "node:net";
27
27
  import { createServer as createHttpServer } from "node:http";
28
28
  import { CLIPY_SKILL_MD } from "./skill.js";
29
+ import { attachCdpDiagnostics } from "./cdpDiagnostics.js";
29
30
  import { SETUP_TARGETS, detectSetupTarget, isSetupTarget, registerMcpServer, renderSetupBox, shortPath, skillPathFor as setupSkillPathFor, } from "./setup.js";
30
- import { APP_NAME as CHROME_FOR_CLIPY_APP_NAME, appBundlePath as chromeForClipyAppPath, chromeStatus, DEFAULT_CDP_PORT, installApp as installChromeForClipyApp, startChrome as startChromeForClipy, startChromeForClipyCapture, markExtensionRecording, stopChrome as stopChromeForClipy, TAB_CAPTURE_TITLE_MARKER, } from "./chromeForClipy.js";
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";
31
32
  import { ExtensionRecordingEndedError, abortExtensionRecording, ExtensionAlreadyUploadedError, extensionReadiness, extensionRecordingStatus, extensionStoreUrl, openTabForPerson, sendExtensionMark, startExtensionRecording, stopExtensionRecording, } from "./chromeExtensionCapture.js";
32
33
  import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
33
34
  import { openUrl } from "./openUrl.js";
@@ -37,7 +38,8 @@ import { errorEnvelope } from "./context/errors.js";
37
38
  import { supportsWebp } from "./context/ffmpeg.js";
38
39
  import { renderProofFrames } from "./proofFrames.js";
39
40
  import { waitForAgentContext } from "./agentReadiness.js";
40
- import { BridgeUnavailableError, bridgeRequest, inspectBridge, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, probeSocketOpenable, probeBridgeHandshake, bridgeInfoFromFile, bridgeAppOutdated, MIN_BRIDGE_APP_VERSION, describeWindow, describeDisplay, } from "./macBridge.js";
41
+ import { BridgeUnavailableError, bridgeRequest, inspectBridge, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, probeSocketOpenable, probeBridgeHandshake, bridgeInfoFromFile, bridgeAppOutdated, MIN_BRIDGE_APP_VERSION, describeWindow, describeDisplay, resolveFromSources, } from "./macBridge.js";
42
+ import { defaultDisplay, describeCaps, ffmpegCaps, isWaylandSession, listLinuxSources, orphanedCaptureProcesses, parseDisplaySize, realRunner, startScreenRecorder, startVirtualDisplay, } from "./linuxScreen.js";
41
43
  // Exit quietly when stdout/stderr close early (e.g. `clipy list | head`).
42
44
  for (const stream of [process.stdout, process.stderr]) {
43
45
  stream.on("error", (e) => {
@@ -392,8 +394,9 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
392
394
  records the copy — real profile untouched, deleted after
393
395
 
394
396
  ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
395
- ${c.dim("--source mac-screen on record/session records the REAL screen via the")}
396
- ${c.dim("running Clipy Mac app (consent-gated, indicator always visible).")}
397
+ ${c.dim("--source screen on record/session records the REAL screen: on macOS via the")}
398
+ ${c.dim("running Clipy Mac app (consent-gated, indicator always visible; mac-screen is")}
399
+ ${c.dim("the same thing), on Linux with the CLI's own X11 recorder (ffmpeg x11grab).")}
397
400
  ${c.dim("On start it prints the resolved surface — recording window: \"<title>\" (id N).")}
398
401
  ${c.dim("CONFIRM that matches what you are driving: attested marks prove what YOU saw,")}
399
402
  ${c.dim("not what the camera saw. Clipy never fronts a window/tab for you.")}
@@ -402,8 +405,18 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
402
405
  --json gives each entry a "source" {kind,id,title}
403
406
  matching what session start/record report, so you
404
407
  can compare pick-vs-camera directly
405
- --window "<title|app|id>" Record that window's current screen area (e.g. --window Chrome)
408
+ --window "<title|app|id>" Record that window by itself (e.g. --window Chrome):
409
+ windows on top of it stay out, and it follows moves,
410
+ only when --json says windowCapture "window" (Linux:
411
+ covered parts are black without a compositor).
412
+ "area" (an older Clipy Mac app, or ffmpeg < 5.1)
413
+ records whatever is on top
406
414
  --display <id> Record a specific display
415
+ --x-display :N Linux: the X display to record (default $DISPLAY)
416
+ --virtual-display Linux: start a private X display (--width/--height,
417
+ default 1280x720) and record it. Launch apps there
418
+ with DISPLAY=:N; session run sets it for the command.
419
+ The user's screen, cursor and keyboard are untouched.
407
420
  --mic Opt IN to microphone capture (default: mic OFF —
408
421
  an agent recording for you is not the same consent
409
422
  as you clicking Record, so we never take the room)
@@ -419,6 +432,11 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
419
432
  Accepts the same auth flags as record
420
433
  (--storage-state/--cookie/--local-storage/--init-script)
421
434
  and --json (returns cdpUrl/cdpHttpUrl).
435
+ Browser evidence (console, failed requests,
436
+ GraphQL errors, WebSockets) is attached:
437
+ --diagnostics off|errors|all (default errors);
438
+ --network-detail also keeps headers and bodies
439
+ (cookies/authorization never leave the machine).
422
440
  --source chrome-for-clipy records ONE TAB (with
423
441
  tab audio) inside the persistent Chrome for
424
442
  Clipy instance (started automatically; sign in
@@ -475,7 +493,7 @@ ${c.bold("AGENTS")}
475
493
  first-run one. Use ${c.bold("setup")} unless you deliberately
476
494
  want just the skill file
477
495
  agents status | uninstall <t> Show / remove installed skills
478
- chrome <setup|start|stop|status|install-app> [--port <n>]
496
+ chrome <setup|start|stop|status|install-app> [--port <n>] [--foreground]
479
497
  "Chrome for Clipy": a dedicated, persistent
480
498
  automation browser with CDP exposed, picker-free
481
499
  tab capture (retitle a tab with the marker), and
@@ -1205,6 +1223,39 @@ async function doctorPlaywrightCheck() {
1205
1223
  data: { installMode: mode },
1206
1224
  };
1207
1225
  }
1226
+ /** Chrome for Clipy (`--source chrome-for-clipy` / `chrome-extension`) needs a
1227
+ * Chrome binary AND host tools that can prove a CDP listener is ours. Both
1228
+ * used to fail only at record time, the second as a misleading "not owned".
1229
+ * Optional for everyone else, so a gap is a warning, never a failure. */
1230
+ function doctorChromeCheck() {
1231
+ const sources = "--source chrome-for-clipy / chrome-extension";
1232
+ const binary = resolveChromeBinary(process.env, process.platform, homedir());
1233
+ if (!binary) {
1234
+ const override = process.env.CLIPY_CHROME_BINARY?.trim();
1235
+ return {
1236
+ name: "chrome",
1237
+ status: "warn",
1238
+ detail: override
1239
+ ? `CLIPY_CHROME_BINARY points at a missing file (${override}); ${sources} unavailable`
1240
+ : `Google Chrome not found; ${sources} unavailable`,
1241
+ hint: "install Google Chrome, or set CLIPY_CHROME_BINARY to its executable",
1242
+ data: { binary: null },
1243
+ };
1244
+ }
1245
+ const probe = chromeOwnershipProbeStatus();
1246
+ if (!probe.ok) {
1247
+ return {
1248
+ name: "chrome",
1249
+ status: "warn",
1250
+ detail: `found ${binary}, but ${probe.error}; ${sources} cannot start`,
1251
+ hint: process.platform === "win32"
1252
+ ? "Chrome for Clipy needs netstat and Windows PowerShell (Get-CimInstance) from System32"
1253
+ : "Chrome for Clipy needs lsof and ps on PATH",
1254
+ data: { binary, ownershipProbe: false },
1255
+ };
1256
+ }
1257
+ return { name: "chrome", status: "pass", detail: `Chrome for Clipy can run (${binary})`, data: { binary, ownershipProbe: true } };
1258
+ }
1208
1259
  // --- context prerequisites -------------------------------------------------
1209
1260
  // `clipy context import` needs yt-dlp (YouTube resolution) and ffmpeg/ffprobe
1210
1261
  // (probing + frame extraction), and both fail LATE — after the user has already
@@ -1414,14 +1465,82 @@ function doctorGlyph(status) {
1414
1465
  return c.dim("INFO");
1415
1466
  }
1416
1467
  }
1468
+ /**
1469
+ * `--source screen` on Linux: what this machine can record. Display capture
1470
+ * needs ffmpeg with x11grab; window capture also needs x11-utils (and
1471
+ * FFmpeg 5.1+ to capture by id); a private screen needs Xvfb. Warnings, never
1472
+ * failures: an agent on a box without them still has web and proof paths.
1473
+ */
1474
+ function doctorLinuxScreenChecks() {
1475
+ if (process.platform !== "linux")
1476
+ return [];
1477
+ const caps = ffmpegCaps(realRunner);
1478
+ const has = (cmd) => realRunner("sh", ["-c", `command -v ${cmd}`], process.env).status === 0;
1479
+ const data = {
1480
+ ffmpeg: caps.available,
1481
+ x11grab: caps.x11grab,
1482
+ windowIdCapture: caps.windowId,
1483
+ encoder: caps.encoder,
1484
+ display: process.env.DISPLAY ?? null,
1485
+ wayland: isWaylandSession(process.env),
1486
+ xwininfo: has("xwininfo"),
1487
+ xprop: has("xprop"),
1488
+ xvfb: has("Xvfb"),
1489
+ compositor: has("picom") || has("xcompmgr"),
1490
+ };
1491
+ const out = [];
1492
+ if (!caps.available || !caps.x11grab || !caps.encoder) {
1493
+ out.push({
1494
+ name: "screen",
1495
+ status: "warn",
1496
+ detail: `cannot record the screen: ${describeCaps(caps)}`,
1497
+ hint: "only needed for --source screen; install ffmpeg with x11grab and libx264 (Debian/Ubuntu: sudo apt install ffmpeg)",
1498
+ data,
1499
+ });
1500
+ return out;
1501
+ }
1502
+ const where = process.env.DISPLAY
1503
+ ? isWaylandSession(process.env)
1504
+ ? `Wayland session (the real screen needs the desktop's consent; use --virtual-display or --x-display)`
1505
+ : `X display ${process.env.DISPLAY}`
1506
+ : "no DISPLAY (use --virtual-display or --x-display :N)";
1507
+ out.push({ name: "screen", status: "pass", detail: `${describeCaps(caps)} · ${where}`, data });
1508
+ if (!data.xwininfo || !data.xprop) {
1509
+ out.push({
1510
+ name: "screen windows",
1511
+ status: "warn",
1512
+ detail: "cannot list windows, so --window is unavailable",
1513
+ hint: "install x11-utils (Debian/Ubuntu: sudo apt install x11-utils)",
1514
+ });
1515
+ }
1516
+ if (!data.xvfb) {
1517
+ out.push({
1518
+ name: "virtual display",
1519
+ status: "warn",
1520
+ detail: "Xvfb not found, so --virtual-display is unavailable",
1521
+ hint: "install xvfb (Debian/Ubuntu: sudo apt install xvfb); add picom or xcompmgr so covered windows record in full",
1522
+ });
1523
+ }
1524
+ else if (!data.compositor) {
1525
+ out.push({
1526
+ name: "virtual display",
1527
+ status: "pass",
1528
+ detail: "Xvfb available (no compositor: a covered window records black where it is covered)",
1529
+ hint: "install picom or xcompmgr for full window captures on a virtual display",
1530
+ });
1531
+ }
1532
+ return out;
1533
+ }
1417
1534
  async function cmdDoctor(ctx, json) {
1418
1535
  const checks = [
1419
1536
  await doctorApiCheck(ctx),
1420
1537
  await doctorAuthCheck(ctx),
1421
1538
  ...(await doctorBridgeChecks()),
1422
1539
  await doctorPlaywrightCheck(),
1540
+ doctorChromeCheck(),
1423
1541
  await doctorYtDlpCheck(),
1424
1542
  ...(await doctorFfmpegChecks()),
1543
+ ...doctorLinuxScreenChecks(),
1425
1544
  doctorInstallCheck(),
1426
1545
  ];
1427
1546
  const failed = checks.filter((chk) => chk.status === "fail").length;
@@ -1964,6 +2083,23 @@ async function uploadVideoToClipy(ctx, opts) {
1964
2083
  : {}),
1965
2084
  });
1966
2085
  uploadToken = ""; // completed — nothing to abort below
2086
+ // Browser evidence rides the same sidecar route the extension uses. It is
2087
+ // a bonus on top of a finished upload: a failure here is reported, never
2088
+ // allowed to fail the recording.
2089
+ if (opts.browserDiagnostics) {
2090
+ try {
2091
+ await ingestPostJson(ctx, "/api/videos/raw-upload/cursor", {
2092
+ recordingId,
2093
+ videoPublicId: publicId,
2094
+ browserDiagnostics: opts.browserDiagnostics,
2095
+ });
2096
+ const count = Array.isArray(opts.browserDiagnostics.events) ? opts.browserDiagnostics.events.length : 0;
2097
+ opts.log(`${c.dim(`attached browser evidence (${count} event${count === 1 ? "" : "s"})`)}`);
2098
+ }
2099
+ catch (err) {
2100
+ opts.log(`browser evidence was not attached: ${err.message}`);
2101
+ }
2102
+ }
1967
2103
  }
1968
2104
  catch (e) {
1969
2105
  // Best-effort: release the half-uploaded streaming session so it doesn't
@@ -2760,6 +2896,43 @@ function writeSessionState(file, state) {
2760
2896
  }
2761
2897
  renameSync(tmp, file);
2762
2898
  }
2899
+ /**
2900
+ * Move a file, copying when the destination is on another filesystem
2901
+ * (rename cannot cross devices, and /tmp is often a tmpfs). The source is
2902
+ * removed only once the copy is complete.
2903
+ */
2904
+ function moveFile(from, to) {
2905
+ // A kept capture is the user's screen: owner-only before it moves, so a
2906
+ // cross-device copy is never readable by others either.
2907
+ try {
2908
+ chmodSync(from, 0o600);
2909
+ }
2910
+ catch {
2911
+ // best-effort on platforms without POSIX modes
2912
+ }
2913
+ try {
2914
+ renameSync(from, to);
2915
+ }
2916
+ catch (e) {
2917
+ if (e.code !== "EXDEV")
2918
+ throw e;
2919
+ try {
2920
+ copyFileSync(from, to);
2921
+ }
2922
+ catch (copyErr) {
2923
+ // A partial copy would only take the space the caller needs next.
2924
+ rmSync(to, { force: true });
2925
+ throw copyErr;
2926
+ }
2927
+ rmSync(from, { force: true });
2928
+ }
2929
+ try {
2930
+ chmodSync(to, 0o600);
2931
+ }
2932
+ catch {
2933
+ // best-effort on platforms without POSIX modes
2934
+ }
2935
+ }
2763
2936
  function pidAlive(pid) {
2764
2937
  // kill(0, 0) signals our own process group and "succeeds".
2765
2938
  if (!Number.isInteger(pid) || pid <= 0)
@@ -2776,7 +2949,81 @@ function sessionIsActive(state) {
2776
2949
  return (["starting", "recording", "stopping", "uploading"].includes(state.state) &&
2777
2950
  pidAlive(state.pid));
2778
2951
  }
2779
- function cleanupSessionFiles(state, file) {
2952
+ /**
2953
+ * Clears a finished or stale session. Returns where a capture that was never
2954
+ * uploaded was kept, so the caller can tell the user.
2955
+ */
2956
+ function cleanupSessionFiles(state, file, opts = {}) {
2957
+ // A daemon killed outright cannot stop the ffmpeg recording its segments,
2958
+ // which would keep encoding the screen into a directory nobody reads. The
2959
+ // caller that just SIGKILLed it says so: the pid can outlive the signal
2960
+ // until it is reaped.
2961
+ const daemonGone = opts.daemonKilled || !pidAlive(state.pid);
2962
+ let keptPath = state.keptVideoPath;
2963
+ if (state.kind === "linux-screen" && state.tmpDir && daemonGone) {
2964
+ for (const pid of orphanedCaptureProcesses(state.tmpDir)) {
2965
+ try {
2966
+ process.kill(pid, "SIGTERM");
2967
+ }
2968
+ catch {
2969
+ // already gone
2970
+ }
2971
+ }
2972
+ // A daemon that died while uploading, or whose recovery move failed,
2973
+ // leaves the finished video in tmpDir as the only copy: move it out
2974
+ // before the directory goes, or keep it where it is.
2975
+ let kept = state.keptVideoPath;
2976
+ if (!kept && state.videoPath && (state.state === "uploading" || state.state === "failed")) {
2977
+ kept = state.videoPath;
2978
+ }
2979
+ if (kept && !existsSync(kept))
2980
+ kept = undefined;
2981
+ if (kept && isInside(kept, state.tmpDir)) {
2982
+ const out = join(sessionDir(), `kept-${randomUUID()}${extname(kept) || ".mp4"}`);
2983
+ try {
2984
+ moveFile(kept, out);
2985
+ kept = out;
2986
+ }
2987
+ catch {
2988
+ // stays in tmpDir, which is then kept below
2989
+ }
2990
+ }
2991
+ keptPath = kept;
2992
+ if (kept && isInside(kept, state.tmpDir)) {
2993
+ // Only the segments it was joined from can go.
2994
+ try {
2995
+ for (const name of readdirSync(state.tmpDir)) {
2996
+ if (name.startsWith("segment-"))
2997
+ rmSync(join(state.tmpDir, name), { force: true });
2998
+ }
2999
+ }
3000
+ catch {
3001
+ // best-effort
3002
+ }
3003
+ }
3004
+ else {
3005
+ // Its segments are unreachable once the state file goes. A failure that
3006
+ // left no finished video discards them too, as the daemon itself does.
3007
+ try {
3008
+ rmSync(state.tmpDir, { recursive: true, force: true });
3009
+ }
3010
+ catch {
3011
+ // best-effort
3012
+ }
3013
+ }
3014
+ }
3015
+ // Nor can it stop the Xvfb it started. Only stop a pid that is still that
3016
+ // Xvfb, so a reused pid is never touched.
3017
+ if (state.virtualDisplayPid && daemonGone) {
3018
+ try {
3019
+ if (readFileSync(`/proc/${state.virtualDisplayPid}/comm`, "utf8").trim() === "Xvfb") {
3020
+ process.kill(state.virtualDisplayPid, "SIGTERM");
3021
+ }
3022
+ }
3023
+ catch {
3024
+ // already gone, or not Linux
3025
+ }
3026
+ }
2780
3027
  for (const p of [state.marksPath, state.controlPath, file]) {
2781
3028
  try {
2782
3029
  rmSync(p, { force: true });
@@ -2785,6 +3032,23 @@ function cleanupSessionFiles(state, file) {
2785
3032
  // best-effort
2786
3033
  }
2787
3034
  }
3035
+ return keptPath;
3036
+ }
3037
+ /** A stale session's capture that was never uploaded is the user's to keep. */
3038
+ function reportKeptCapture(path) {
3039
+ if (path)
3040
+ process.stderr.write(`${c.yellow("!")} a session capture that was never uploaded was kept at: ${path}\n`);
3041
+ }
3042
+ /** A mark or chapter that found the daemon dead: say so, and where its capture went. */
3043
+ function dieSessionCleared(keptPath, json) {
3044
+ const message = "the session daemon is no longer running (crashed?) — session cleared. Start a new one.";
3045
+ if (json)
3046
+ printJson({ state: "cleared", error: message, ...(keptPath ? { keptVideoPath: keptPath } : {}) });
3047
+ die(keptPath ? `${message}\nThe capture was kept at: ${keptPath}` : message);
3048
+ }
3049
+ function isInside(path, dir) {
3050
+ const rel = relative(resolve(dir), resolve(path));
3051
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
2788
3052
  }
2789
3053
  /** Annotation for a mark Clipy itself evaluated against its own live page. */
2790
3054
  function verifiedMarkAnnotation(passed, expected, observed) {
@@ -2929,6 +3193,347 @@ async function evaluateAssertion(page, assert) {
2929
3193
  }
2930
3194
  return { passed, observed: observed.join("; "), expected: expected.join("; ") };
2931
3195
  }
3196
+ // --- Real-screen source naming ----------------------------------------------
3197
+ /**
3198
+ * `--source screen` is the real screen on every OS: the Clipy Mac app on
3199
+ * macOS and the CLI's own X11 recorder on Linux. `mac-screen` stays the
3200
+ * explicit Mac spelling. Windows has no screen path for agents yet, so it is
3201
+ * refused with the paths that do work there, never silently downgraded.
3202
+ */
3203
+ const WINDOWS_SCREEN_REFUSAL = "--source screen isn't available on Windows yet: the Clipy Windows app has no agent bridge. " +
3204
+ "Record a browser tab with --source chrome-for-clipy, a web page headlessly with --url, " +
3205
+ "or hand your own tool's screenshots or video to `clipy proof`.";
3206
+ function normalizeScreenSource(raw, platform = process.platform) {
3207
+ if (raw === "screen") {
3208
+ if (platform === "darwin")
3209
+ return "mac-screen";
3210
+ if (platform === "linux")
3211
+ return "linux-screen";
3212
+ die(WINDOWS_SCREEN_REFUSAL, 2);
3213
+ }
3214
+ if (raw === "linux-screen" && platform !== "linux")
3215
+ die("--source linux-screen records an X11 display and only runs on Linux", 2);
3216
+ // CLIPY_BRIDGE_FILE points the bridge client at an explicit app (tests and
3217
+ // remote setups use it off macOS), so only refuse when nothing could answer.
3218
+ if (raw === "mac-screen" && platform === "linux" && !process.env.CLIPY_BRIDGE_FILE?.trim()) {
3219
+ die("--source mac-screen records through the Clipy Mac app; on Linux use --source screen", 2);
3220
+ }
3221
+ return raw;
3222
+ }
3223
+ /** Both real-screen transports: they take --window/--display, not auth flags. */
3224
+ function isScreenSource(source) {
3225
+ return source === "mac-screen" || source === "linux-screen";
3226
+ }
3227
+ /**
3228
+ * Turn the flags into what to record. Fails before anything starts when the
3229
+ * request cannot be met (no display, Wayland, missing tools, no match), so an
3230
+ * agent never gets a session that looks live but captures nothing.
3231
+ */
3232
+ function planLinuxCapture(opts) {
3233
+ const caps = ffmpegCaps(realRunner);
3234
+ if (!caps.available)
3235
+ die("recording the screen on Linux needs ffmpeg (Debian/Ubuntu: `sudo apt install ffmpeg`)");
3236
+ if (!caps.x11grab)
3237
+ die("this ffmpeg was built without x11grab, so it cannot record an X display");
3238
+ if (!caps.encoder)
3239
+ die("this ffmpeg has neither libx264 nor libvpx, so it cannot encode a recording");
3240
+ if (opts.virtualDisplay) {
3241
+ if (opts.window || opts.display || opts.xDisplay) {
3242
+ die("--virtual-display records a new, empty display as a whole; it has no windows to pick yet. " +
3243
+ "To record one window, start your own display, launch the app, then use --x-display :N --window <id>.", 2);
3244
+ }
3245
+ let size;
3246
+ try {
3247
+ size = parseDisplaySize(`${opts.width}x${opts.height}`);
3248
+ }
3249
+ catch (e) {
3250
+ die(e.message, 2);
3251
+ }
3252
+ return {
3253
+ virtualDisplay: size,
3254
+ resolved: { kind: "display", title: `virtual display ${size.width}×${size.height}` },
3255
+ label: `a new ${size.width}×${size.height} virtual display`,
3256
+ };
3257
+ }
3258
+ const xDisplay = opts.xDisplay?.trim() || process.env.DISPLAY;
3259
+ if (!xDisplay) {
3260
+ die("no X display to record: run on a desktop session, name one with --x-display :N, " +
3261
+ "or pass --virtual-display to give the agent a screen of its own");
3262
+ }
3263
+ if (!opts.xDisplay && isWaylandSession(process.env)) {
3264
+ die("this is a Wayland session, which only lets an app read the screen through the desktop's own consent dialog. " +
3265
+ "Record a private screen with --virtual-display, name an X display with --x-display :N, or log in to an X11 session.");
3266
+ }
3267
+ const sources = listLinuxSources(xDisplay);
3268
+ if (sources.displays.length === 0)
3269
+ die(`could not read X display ${xDisplay} (is it running, and is DISPLAY/XAUTHORITY right?)`);
3270
+ if (opts.window && sources.windowsUnavailable)
3271
+ die(sources.windowsUnavailable);
3272
+ if (!opts.window && !opts.display) {
3273
+ const display = defaultDisplay(sources);
3274
+ return {
3275
+ xDisplay,
3276
+ target: { kind: "display", display },
3277
+ resolved: describeDisplay(display),
3278
+ label: display.name,
3279
+ };
3280
+ }
3281
+ let picked;
3282
+ try {
3283
+ picked = resolveFromSources(sources, { window: opts.window, display: opts.display });
3284
+ }
3285
+ catch (e) {
3286
+ die(e.message);
3287
+ }
3288
+ if (picked.source.type === "window") {
3289
+ const id = picked.source.id;
3290
+ const window = sources.windows.find((w) => w.id === id);
3291
+ if (!caps.windowId) {
3292
+ process.stderr.write(`${c.yellow("note:")} this ffmpeg cannot capture a window by id (needs FFmpeg 5.1+), so Clipy records the window's area of the screen and moves it with the window; windows on top of it will show.\n`);
3293
+ }
3294
+ return {
3295
+ xDisplay,
3296
+ target: { kind: "window", window },
3297
+ windowCapture: caps.windowId ? "window" : "area",
3298
+ resolved: picked.resolved,
3299
+ label: picked.label,
3300
+ };
3301
+ }
3302
+ const id = picked.source.type === "display" ? picked.source.id : -1;
3303
+ const display = sources.displays.find((d) => d.id === id);
3304
+ return { xDisplay, target: { kind: "display", display }, resolved: picked.resolved, label: picked.label };
3305
+ }
3306
+ /**
3307
+ * Stops a session daemon that did not reach `recording` in time, and clears
3308
+ * what it started (ffmpeg, Xvfb, its segments), so nothing is recorded or
3309
+ * uploaded behind a start that was reported as failed.
3310
+ */
3311
+ async function abandonStartingDaemon(file, pid) {
3312
+ try {
3313
+ process.kill(pid, "SIGTERM");
3314
+ }
3315
+ catch {
3316
+ // already gone
3317
+ }
3318
+ const grace = Date.now() + 3000;
3319
+ while (pidAlive(pid) && Date.now() < grace)
3320
+ await new Promise((r) => setTimeout(r, 150));
3321
+ if (pidAlive(pid)) {
3322
+ try {
3323
+ process.kill(pid, "SIGKILL");
3324
+ }
3325
+ catch {
3326
+ // already gone
3327
+ }
3328
+ }
3329
+ const s = readSessionState(file);
3330
+ if (s)
3331
+ cleanupSessionFiles(s, file, { daemonKilled: true });
3332
+ }
3333
+ async function cmdSessionStartLinux(ctx, opts) {
3334
+ const file = sessionFilePath(process.cwd());
3335
+ const existing = readSessionState(file);
3336
+ if (existing && sessionIsActive(existing)) {
3337
+ die(`a recording session is already active in this workspace (pid ${existing.pid}, started for ${existing.url}).\n` +
3338
+ `Finish it with \`clipy session stop\` or discard it with \`clipy session abort\`.`);
3339
+ }
3340
+ if (existing)
3341
+ reportKeptCapture(cleanupSessionFiles(existing, file));
3342
+ const key = requireKey(ctx);
3343
+ const plan = planLinuxCapture(opts);
3344
+ const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
3345
+ const id = randomUUID();
3346
+ const dir = sessionDir();
3347
+ mkdirSync(dir, { recursive: true });
3348
+ const state = {
3349
+ version: 1,
3350
+ kind: "linux-screen",
3351
+ xDisplay: plan.xDisplay,
3352
+ virtualDisplay: plan.virtualDisplay,
3353
+ screenTarget: plan.target,
3354
+ screenSource: plan.resolved,
3355
+ pid: 0,
3356
+ cwd: process.cwd(),
3357
+ url: `screen:${plan.label}`,
3358
+ name: opts.name,
3359
+ description: opts.description,
3360
+ recordingKind: opts.recordingKind,
3361
+ maxSec,
3362
+ width: opts.width,
3363
+ height: opts.height,
3364
+ state: "starting",
3365
+ marksPath: join(dir, `marks-${id}.jsonl`),
3366
+ controlPath: join(dir, `control-${id}.json`),
3367
+ logPath: join(dir, `daemon-${id}.log`),
3368
+ tmpDir: join(tmpdir(), `clipy-session-${id}`),
3369
+ };
3370
+ const logFd = openSync(state.logPath, "a");
3371
+ const child = spawn(process.execPath, [process.argv[1], "__session-daemon", file], {
3372
+ detached: true,
3373
+ stdio: ["ignore", logFd, logFd],
3374
+ env: { ...process.env, CLIPY_API_KEY: key, CLIPY_API_URL: ctx.apiUrl },
3375
+ });
3376
+ closeSync(logFd);
3377
+ if (!child.pid)
3378
+ die("failed to spawn the session daemon");
3379
+ state.pid = child.pid;
3380
+ writeSessionState(file, state);
3381
+ child.unref();
3382
+ // Recording only counts once frames are landing (the recorder checks), so
3383
+ // the agent's next command is inside a live capture.
3384
+ const deadline = Date.now() + 30_000;
3385
+ for (;;) {
3386
+ const s = readSessionState(file);
3387
+ if (s?.state === "recording")
3388
+ break;
3389
+ if (s?.state === "failed" || Date.now() >= deadline || (s && !pidAlive(s.pid))) {
3390
+ // A daemon still starting would otherwise go on to record, and upload,
3391
+ // after this command has reported failure; a failed one leaves its work
3392
+ // directory and state behind.
3393
+ await abandonStartingDaemon(file, child.pid);
3394
+ if (s?.state === "failed")
3395
+ die(`session failed to start: ${s.error ?? "unknown error"} (log: ${state.logPath})`);
3396
+ die(`session daemon did not start in time (log: ${state.logPath})`);
3397
+ }
3398
+ await new Promise((r) => setTimeout(r, 200));
3399
+ }
3400
+ const started = readSessionState(file);
3401
+ const xDisplay = started?.xDisplay ?? plan.xDisplay;
3402
+ if (opts.json) {
3403
+ printJson({
3404
+ state: "recording",
3405
+ captureMode: "linux-screen",
3406
+ xDisplay,
3407
+ virtualDisplay: Boolean(plan.virtualDisplay),
3408
+ maxSec,
3409
+ sessionFile: file,
3410
+ source: captureSourceResult(plan.resolved),
3411
+ ...(plan.windowCapture ? { windowCapture: plan.windowCapture } : {}),
3412
+ });
3413
+ return;
3414
+ }
3415
+ process.stdout.write(`${c.green("✓")} recording ${plan.label} on ${xDisplay} (max ${maxSec}s)\n`);
3416
+ if (plan.virtualDisplay) {
3417
+ process.stdout.write(`${c.bold("virtual display:")} ${xDisplay}: only what you launch there is recorded, and it never touches the user's screen.\n` +
3418
+ `${c.dim("launch apps on it with:")} DISPLAY=${xDisplay} <command> ${c.dim("(or use clipy session run, which sets DISPLAY)")}\n`);
3419
+ }
3420
+ else if (plan.target?.kind === "window") {
3421
+ process.stdout.write(plan.windowCapture === "area"
3422
+ ? `${c.bold("recording window:")} "${plan.resolved.title}" (id ${plan.resolved.id}), as the screen area it covers, so keep it in front: anything on top of it is recorded.\n`
3423
+ : `${c.bold("recording window:")} "${plan.resolved.title}" (id ${plan.resolved.id}), its own pixels. Under a compositor it records in full even when covered; without one, keep it unobscured, because covered parts record black.\n`);
3424
+ }
3425
+ process.stdout.write(`${c.dim("while it runs:")} clipy mark "what just happened"\n` +
3426
+ `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
3427
+ }
3428
+ /** One-shot `clipy record --source screen --for N` on Linux. */
3429
+ async function cmdRecordLinux(ctx, opts) {
3430
+ requireKey(ctx);
3431
+ if (maxPassRef(opts.notes) > 0) {
3432
+ die('pass-scoped --note values need --viewports; a screen recording is one take, so use "12: text"', 2);
3433
+ }
3434
+ const plan = planLinuxCapture(opts);
3435
+ const vd = plan.virtualDisplay ? await startVirtualDisplay(plan.virtualDisplay) : null;
3436
+ const xDisplay = vd?.display ?? plan.xDisplay;
3437
+ const auto = [];
3438
+ const workDir = join(tmpdir(), `clipy-record-${randomUUID()}`);
3439
+ // Set when an upload fails: the finished video is kept for the user to
3440
+ // retry, and only the intermediate segments are removed.
3441
+ let keptVideo = null;
3442
+ try {
3443
+ if (vd) {
3444
+ process.stderr.write(`${c.bold("virtual display:")} ${xDisplay}: launch apps there with DISPLAY=${xDisplay}; it closes when the recording ends.\n`);
3445
+ }
3446
+ const recorder = await startScreenRecorder({
3447
+ xDisplay,
3448
+ target: plan.target ?? { kind: "display", display: defaultDisplay(listLinuxSources(xDisplay)) },
3449
+ tmpDir: workDir,
3450
+ caps: ffmpegCaps(realRunner),
3451
+ });
3452
+ if (!opts.json)
3453
+ process.stderr.write(`${c.dim(`recording ${plan.label} for ${opts.forSec}s…`)}\n`);
3454
+ const until = recorder.startedAt + opts.forSec * 1000;
3455
+ while (Date.now() < until) {
3456
+ await new Promise((r) => setTimeout(r, 400));
3457
+ let note = null;
3458
+ try {
3459
+ note = recorder.tick();
3460
+ }
3461
+ catch (e) {
3462
+ auto.push({ startMs: Date.now() - recorder.startedAt, text: `[auto] screen capture stopped: ${e.message}` });
3463
+ break;
3464
+ }
3465
+ if (note)
3466
+ auto.push({ startMs: Date.now() - recorder.startedAt, text: note });
3467
+ if (recorder.ended())
3468
+ break;
3469
+ }
3470
+ const videoPath = await recorder.finish();
3471
+ const notes = [
3472
+ ...opts.notes.map((n) => ({ startMs: n.startMs ?? 0, text: n.text })),
3473
+ ...auto,
3474
+ ].sort((a, b) => a.startMs - b.startMs);
3475
+ let uploaded;
3476
+ try {
3477
+ uploaded = await uploadVideoToClipy(ctx, {
3478
+ videoPath,
3479
+ name: opts.name,
3480
+ description: opts.description,
3481
+ recordingKind: opts.recordingKind,
3482
+ narration: notes.length ? { notes } : undefined,
3483
+ log: (m) => {
3484
+ if (!opts.json)
3485
+ process.stderr.write(`${m}\n`);
3486
+ },
3487
+ });
3488
+ }
3489
+ catch (e) {
3490
+ keptVideo = videoPath;
3491
+ throw new Error(`${e.message}\nThe recording was kept at: ${videoPath}`);
3492
+ }
3493
+ return {
3494
+ publicId: uploaded.publicId,
3495
+ shareUrl: uploaded.shareUrl,
3496
+ contextUrl: uploaded.contextUrl,
3497
+ sizeBytes: uploaded.sizeBytes,
3498
+ source: captureSourceResult(plan.resolved),
3499
+ windowCapture: plan.windowCapture,
3500
+ };
3501
+ }
3502
+ finally {
3503
+ await vd?.stop();
3504
+ if (keptVideo) {
3505
+ for (const name of readdirSync(workDir)) {
3506
+ if (name.startsWith("segment-"))
3507
+ rmSync(join(workDir, name), { force: true });
3508
+ }
3509
+ }
3510
+ else {
3511
+ rmSync(workDir, { recursive: true, force: true });
3512
+ }
3513
+ }
3514
+ }
3515
+ /** `clipy sources` on Linux: the same shape the Mac app reports. */
3516
+ function printLinuxSources(sources, json) {
3517
+ if (json) {
3518
+ printJson({
3519
+ xDisplay: sources.xDisplay,
3520
+ displays: sources.displays.map((d) => ({ ...d, source: describeDisplay(d) })),
3521
+ windows: sources.windows.map((w) => ({ ...w, source: describeWindow(w) })),
3522
+ ...(sources.windowsUnavailable ? { windowsUnavailable: sources.windowsUnavailable } : {}),
3523
+ });
3524
+ return;
3525
+ }
3526
+ process.stdout.write(`${c.bold(`displays on ${sources.xDisplay}`)}\n`);
3527
+ for (const d of sources.displays)
3528
+ process.stdout.write(` ${d.id} ${d.name} ${d.width}×${d.height}\n`);
3529
+ process.stdout.write(`${c.bold("windows")}\n`);
3530
+ if (sources.windowsUnavailable)
3531
+ process.stdout.write(` ${c.dim(sources.windowsUnavailable)}\n`);
3532
+ for (const w of sources.windows)
3533
+ process.stdout.write(` ${w.id} ${windowLabel(w)} ${w.width}×${w.height}\n`);
3534
+ if (!sources.windowsUnavailable && sources.windows.length === 0)
3535
+ process.stdout.write(` ${c.dim("(none)")}\n`);
3536
+ }
2932
3537
  // --- Mac bridge flows (--source mac-screen): the desktop app records -------
2933
3538
  /** Resolves --window/--display to a bridge capture source (null = app default,
2934
3539
  * i.e. the full primary display). die()s with the candidate list on no/ambiguous
@@ -2979,6 +3584,37 @@ function echoedAudio(startResult) {
2979
3584
  * below this, the app silently ignores the field and records with ITS defaults.
2980
3585
  */
2981
3586
  const AUDIO_PROTOCOL_VERSION = 2;
3587
+ /**
3588
+ * From bridge protocol v3 the app says how it records a window: `window` (its
3589
+ * own pixels, the macOS default) or `area` (the fixed screen rectangle, which
3590
+ * records anything on top of it). An older app always records the area, so an
3591
+ * agent must not be told the window is isolated.
3592
+ */
3593
+ const WINDOW_CAPTURE_PROTOCOL_VERSION = 3;
3594
+ function warnWindowNotIsolated(emit, reason) {
3595
+ emit(c.yellow(`warning: ${reason}, so it records the window's screen area: windows on top of it, and ` +
3596
+ `anything else that enters the rectangle, are recorded too. Update the Clipy app ` +
3597
+ `(https://clipy.online/download) to record a window by itself.`));
3598
+ }
3599
+ /** Before `start`: an app too old to say how it records a window records the area. */
3600
+ function warnWindowCaptureUnknown(protocolVersion, target, emit) {
3601
+ if (target?.resolved.kind !== "window" || protocolVersion >= WINDOW_CAPTURE_PROTOCOL_VERSION)
3602
+ return false;
3603
+ warnWindowNotIsolated(emit, `this Clipy app speaks bridge protocol v${protocolVersion} (needs v${WINDOW_CAPTURE_PROTOCOL_VERSION})`);
3604
+ return true;
3605
+ }
3606
+ /** After `start`: what the app confirmed, and "area" when it confirmed nothing. */
3607
+ function appliedWindowCapture(target, startResult, emit, warned) {
3608
+ if (target?.resolved.kind !== "window")
3609
+ return undefined;
3610
+ const echoed = startResult.windowCapture;
3611
+ if (echoed === "window")
3612
+ return "window";
3613
+ if (!warned) {
3614
+ warnWindowNotIsolated(emit, echoed === "area" ? "the Clipy app is set to record a window with its screen area" : "the Clipy app did not confirm how it records the window");
3615
+ }
3616
+ return "area";
3617
+ }
2982
3618
  /**
2983
3619
  * Warn BEFORE `start` when the running app can't honour the audio request.
2984
3620
  * The timing is the entire point. The echo check below can only report what
@@ -3055,6 +3691,7 @@ async function cmdRecordMac(opts) {
3055
3691
  // Deliberately NOT `log`: a "your mic may be live" warning must survive
3056
3692
  // --json, and stderr never corrupts the JSON on stdout.
3057
3693
  const audioUncontrollable = warnAudioUncontrollable(info.protocolVersion, opts.audio, (m) => process.stderr.write(`${m}\n`));
3694
+ const windowWarned = warnWindowCaptureUnknown(info.protocolVersion, target, (m) => process.stderr.write(`${m}\n`));
3058
3695
  const notes = resolveNarrationNotes(opts.notes, [0]);
3059
3696
  const startResult = await bridgeRequest(info, "start", {
3060
3697
  // Explicit, never implicit: an absent field would fall through to the app's
@@ -3070,6 +3707,7 @@ async function cmdRecordMac(opts) {
3070
3707
  ...(target ? { source: target.source } : {}),
3071
3708
  });
3072
3709
  const appliedAudio = reportAudio(opts.audio, echoedAudio(startResult), log, audioUncontrollable);
3710
+ const windowCapture = appliedWindowCapture(target, startResult, (m) => process.stderr.write(`${m}\n`), windowWarned);
3073
3711
  log(`${c.dim(`recording for ${opts.forSec}s…`)}`);
3074
3712
  await new Promise((r) => setTimeout(r, opts.forSec * 1000));
3075
3713
  log(`${c.dim("stopping + uploading…")}`);
@@ -3083,6 +3721,7 @@ async function cmdRecordMac(opts) {
3083
3721
  // the surface — folding it in would muddy `source` and break its shape
3084
3722
  // parity with `clipy sources --json` entries.
3085
3723
  audio: appliedAudio,
3724
+ ...(windowCapture ? { windowCapture } : {}),
3086
3725
  };
3087
3726
  }
3088
3727
  function macSessionState(info, maxSec) {
@@ -3266,7 +3905,7 @@ async function cmdSessionStartExtension(opts) {
3266
3905
  `Finish it with \`clipy session stop\` or discard it with \`clipy session abort\`.`);
3267
3906
  }
3268
3907
  if (existing)
3269
- cleanupSessionFiles(existing, file);
3908
+ reportKeptCapture(cleanupSessionFiles(existing, file));
3270
3909
  const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
3271
3910
  let started;
3272
3911
  try {
@@ -3359,6 +3998,10 @@ async function cmdSessionStart(ctx, opts) {
3359
3998
  await cmdSessionStartExtension(opts);
3360
3999
  return;
3361
4000
  }
4001
+ if (opts.source === "linux-screen") {
4002
+ await cmdSessionStartLinux(ctx, opts);
4003
+ return;
4004
+ }
3362
4005
  if (opts.source === "mac-screen") {
3363
4006
  const file = sessionFilePath(process.cwd());
3364
4007
  const existing = readSessionState(file);
@@ -3375,6 +4018,7 @@ async function cmdSessionStart(ctx, opts) {
3375
4018
  }
3376
4019
  // Before the camera turns on, not after — see warnAudioUncontrollable().
3377
4020
  const audioUncontrollable = warnAudioUncontrollable(info.protocolVersion, opts.audio, (m) => process.stderr.write(`${m}\n`));
4021
+ const windowWarned = warnWindowCaptureUnknown(info.protocolVersion, target, (m) => process.stderr.write(`${m}\n`));
3378
4022
  const startResult = await bridgeRequest(info, "start", {
3379
4023
  // Explicit, never implicit — see reportAudio(): an absent field falls
3380
4024
  // through to the app's interactive defaults (mic ON) on older builds.
@@ -3387,6 +4031,7 @@ async function cmdSessionStart(ctx, opts) {
3387
4031
  });
3388
4032
  writeSessionState(file, macSessionState(info, maxSec));
3389
4033
  const appliedAudio = reportAudio(opts.audio, echoedAudio(startResult), (m) => process.stderr.write(`${m}\n`), audioUncontrollable);
4034
+ const windowCapture = appliedWindowCapture(target, startResult, (m) => process.stderr.write(`${m}\n`), windowWarned);
3390
4035
  if (opts.json) {
3391
4036
  printJson({
3392
4037
  state: "recording",
@@ -3398,6 +4043,7 @@ async function cmdSessionStart(ctx, opts) {
3398
4043
  target: target?.label,
3399
4044
  source: captureSourceResult(target?.resolved),
3400
4045
  audio: appliedAudio,
4046
+ ...(windowCapture ? { windowCapture } : {}),
3401
4047
  });
3402
4048
  return;
3403
4049
  }
@@ -3449,7 +4095,7 @@ async function cmdSessionStart(ctx, opts) {
3449
4095
  `Finish it with \`clipy session stop\` or discard it with \`clipy session abort\`.`);
3450
4096
  }
3451
4097
  if (existing)
3452
- cleanupSessionFiles(existing, file); // stale (daemon died) — clear
4098
+ reportKeptCapture(cleanupSessionFiles(existing, file)); // stale (daemon died) — clear
3453
4099
  // --profile-directory ⇒ copy the named profile into a scratch root HERE, in the
3454
4100
  // parent, so the user sees the loud disclosure (the daemon's stdout goes to a
3455
4101
  // log). The daemon launches against the scratch root and removes it at stop/abort;
@@ -3475,6 +4121,8 @@ async function cmdSessionStart(ctx, opts) {
3475
4121
  width: opts.width,
3476
4122
  height: opts.height,
3477
4123
  exposeCdp: opts.exposeCdp,
4124
+ diagnostics: opts.diagnostics,
4125
+ networkDetail: opts.networkDetail,
3478
4126
  storageStatePath: opts.auth.storageStatePath,
3479
4127
  initScriptPath: opts.auth.initScriptPath,
3480
4128
  cookieSpecs: opts.auth.cookieSpecs.length ? opts.auth.cookieSpecs : undefined,
@@ -3621,6 +4269,9 @@ async function cmdMark(text, json, opts) {
3621
4269
  }, json);
3622
4270
  return;
3623
4271
  }
4272
+ if (state.kind === "linux-screen" && hasAssert) {
4273
+ die("Clipy-evaluated assertions need a Clipy-owned page; use --observed/--verdict to attach evidence you collected yourself", 2);
4274
+ }
3624
4275
  if (state.kind === "mac") {
3625
4276
  // The Mac app records the real screen — there is no Clipy-owned page to probe,
3626
4277
  // so Clipy-EVALUATED assertions can't run here. Driver-attested marks CAN: the
@@ -3657,10 +4308,8 @@ async function cmdMark(text, json, opts) {
3657
4308
  process.stdout.write(`${glyph} mark @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${macText}\n`);
3658
4309
  return;
3659
4310
  }
3660
- if (!pidAlive(state.pid)) {
3661
- cleanupSessionFiles(state, file);
3662
- die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
3663
- }
4311
+ if (!pidAlive(state.pid))
4312
+ dieSessionCleared(cleanupSessionFiles(state, file), json);
3664
4313
  if (state.state !== "recording" || !state.recordStartEpochMs) {
3665
4314
  die(`session is ${state.state} — marks can only be added while recording`);
3666
4315
  }
@@ -3776,10 +4425,8 @@ async function cmdChapter(label, json) {
3776
4425
  process.stdout.write(`${c.green("✓")} chapter @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${label}\n`);
3777
4426
  return;
3778
4427
  }
3779
- if (!pidAlive(state.pid)) {
3780
- cleanupSessionFiles(state, file);
3781
- die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
3782
- }
4428
+ if (!pidAlive(state.pid))
4429
+ dieSessionCleared(cleanupSessionFiles(state, file), json);
3783
4430
  if (state.state !== "recording" || !state.recordStartEpochMs) {
3784
4431
  die(`session is ${state.state} — chapters can only be added while recording`);
3785
4432
  }
@@ -3887,10 +4534,11 @@ async function cmdSessionStop(json) {
3887
4534
  cleanupSessionFiles(state, file);
3888
4535
  return;
3889
4536
  }
3890
- cleanupSessionFiles(state, file);
4537
+ const keptPath = cleanupSessionFiles(state, file);
4538
+ const kept = keptPath ? `\nThe capture was kept at: ${keptPath}` : "";
3891
4539
  die(state.state === "failed"
3892
- ? `session failed: ${state.error ?? "unknown"} (log: ${state.logPath})`
3893
- : "the session daemon is no longer running (crashed?) — session cleared.");
4540
+ ? `session failed: ${state.error ?? "unknown"} (log: ${state.logPath})${kept}`
4541
+ : `the session daemon is no longer running (crashed?) — session cleared.${kept}`);
3894
4542
  }
3895
4543
  writeFileSync(state.controlPath, JSON.stringify({ action: "stop" }));
3896
4544
  if (!json)
@@ -3905,8 +4553,8 @@ async function cmdSessionStop(json) {
3905
4553
  return;
3906
4554
  }
3907
4555
  if (s?.state === "failed") {
3908
- const kept = s.keptVideoPath ? `\nThe capture was kept at: ${s.keptVideoPath}` : "";
3909
- cleanupSessionFiles(s, file);
4556
+ const keptPath = cleanupSessionFiles(s, file);
4557
+ const kept = keptPath ? `\nThe capture was kept at: ${keptPath}` : "";
3910
4558
  die(`session upload failed: ${s.error ?? "unknown"}${kept}`);
3911
4559
  }
3912
4560
  if (s?.state === "aborted") {
@@ -3914,8 +4562,9 @@ async function cmdSessionStop(json) {
3914
4562
  die("session was aborted");
3915
4563
  }
3916
4564
  if (s && !pidAlive(s.pid)) {
3917
- cleanupSessionFiles(s, file);
3918
- die(`the session daemon died mid-stop (log: ${state.logPath})`);
4565
+ const keptPath = cleanupSessionFiles(s, file);
4566
+ const kept = keptPath ? `\nThe capture was kept at: ${keptPath}` : "";
4567
+ die(`the session daemon died mid-stop (log: ${state.logPath})${kept}`);
3919
4568
  }
3920
4569
  if (Date.now() >= deadline) {
3921
4570
  die(`timed out waiting for the session to finish (log: ${state.logPath})`);
@@ -3961,13 +4610,16 @@ async function cmdSessionAbort(json) {
3961
4610
  process.exitCode = 1;
3962
4611
  return;
3963
4612
  }
3964
- if (failure && (await chromeStatus(homedir(), process.platform)).running) {
3965
- // Chrome for Clipy is up, so the recording may still be running: keep
3966
- // the session so a retry (or stop) can still reach it.
4613
+ const chrome = failure ? await chromeStatus(homedir(), process.platform) : null;
4614
+ if (failure && chrome && (chrome.running || chrome.error)) {
4615
+ // Chrome for Clipy is up (or its state cannot be verified), so the
4616
+ // recording may still be running: keep the session so a retry (or stop)
4617
+ // can still reach it.
4618
+ const reason = chrome.running ? failure : `${failure}; ${chrome.error}`;
3967
4619
  if (json)
3968
- printJson({ state: "recording", error: failure });
4620
+ printJson({ state: "recording", error: reason });
3969
4621
  else
3970
- process.stderr.write(`${c.yellow("!")} could not reach the extension to cancel (${failure}); the session is kept, retry \`clipy session abort\`\n`);
4622
+ process.stderr.write(`${c.yellow("!")} could not reach the extension to cancel (${reason}); the session is kept, retry \`clipy session abort\`\n`);
3971
4623
  process.exitCode = 1;
3972
4624
  return;
3973
4625
  }
@@ -3996,11 +4648,13 @@ async function cmdSessionAbort(json) {
3996
4648
  return;
3997
4649
  }
3998
4650
  if (!pidAlive(state.pid)) {
3999
- cleanupSessionFiles(state, file);
4000
- if (!json)
4651
+ const keptPath = cleanupSessionFiles(state, file);
4652
+ if (!json) {
4001
4653
  process.stdout.write(`${c.green("✓")} stale session cleared (daemon was not running)\n`);
4654
+ reportKeptCapture(keptPath);
4655
+ }
4002
4656
  else
4003
- printJson({ state: "cleared" });
4657
+ printJson(keptPath ? { state: "cleared", keptVideoPath: keptPath } : { state: "cleared" });
4004
4658
  return;
4005
4659
  }
4006
4660
  writeFileSync(state.controlPath, JSON.stringify({ action: "abort" }));
@@ -4055,21 +4709,23 @@ async function cmdSessionAbort(json) {
4055
4709
  }
4056
4710
  }
4057
4711
  }
4058
- if (final)
4059
- cleanupSessionFiles(final, file);
4712
+ const keptPath = final ? cleanupSessionFiles(final, file, { daemonKilled: wedged }) : undefined;
4713
+ if (!json)
4714
+ reportKeptCapture(keptPath);
4715
+ const kept = keptPath ? { keptVideoPath: keptPath } : {};
4060
4716
  if (wedged) {
4061
4717
  // Exit non-zero (and truthfully) — the daemon had to be force-killed, so we
4062
4718
  // can't promise a clean discard. Use process.exitCode (not process.exit) so
4063
4719
  // a caller like `session run` can still override with the child's code.
4064
4720
  if (json)
4065
- printJson({ state: "killed", pid: final?.pid ?? null });
4721
+ printJson({ state: "killed", pid: final?.pid ?? null, ...kept });
4066
4722
  else
4067
4723
  process.stderr.write(`${c.yellow("!")} the session daemon ignored abort for 30s and was force-killed (pid ${final?.pid}); nothing was uploaded\n`);
4068
4724
  process.exitCode = 1;
4069
4725
  return;
4070
4726
  }
4071
4727
  if (json)
4072
- printJson({ state: "aborted" });
4728
+ printJson({ state: "aborted", ...kept });
4073
4729
  else
4074
4730
  process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
4075
4731
  }
@@ -4195,6 +4851,9 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
4195
4851
  const started = readSessionState(file);
4196
4852
  const cdpHttpUrl = started?.cdpHttpUrl;
4197
4853
  const targetId = started?.extensionTargetId;
4854
+ // A Linux screen session: the driver's apps belong on the recorded display
4855
+ // (essential for a virtual one, which nothing else knows about).
4856
+ const xDisplay = started?.kind === "linux-screen" ? started.xDisplay : undefined;
4198
4857
  const [cmd, ...args] = childArgv;
4199
4858
  process.stderr.write(`${c.dim(`running: ${childArgv.join(" ")}`)}\n`);
4200
4859
  const child = spawn(cmd, args, {
@@ -4207,6 +4866,7 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
4207
4866
  CLIPY_SESSION: "1",
4208
4867
  CLIPY_SESSION_FILE: file,
4209
4868
  ...(cdpHttpUrl ? { CLIPY_CDP_URL: cdpHttpUrl } : {}),
4869
+ ...(xDisplay ? { DISPLAY: xDisplay, CLIPY_X_DISPLAY: xDisplay } : {}),
4210
4870
  // chrome-extension: the exact recorded tab, since other tabs in the
4211
4871
  // persistent profile can share its url.
4212
4872
  ...(targetId && started?.chromePort
@@ -4302,6 +4962,7 @@ async function runSessionDaemon(file) {
4302
4962
  const log = (m) => process.stderr.write(`[clipy-session] ${new Date().toISOString()} ${m}\n`);
4303
4963
  const autoMarks = [];
4304
4964
  let recordStart = 0;
4965
+ let browserEvidence = null;
4305
4966
  const autoMark = (text) => {
4306
4967
  if (autoMarks.length >= 50 || recordStart === 0)
4307
4968
  return;
@@ -4316,7 +4977,8 @@ async function runSessionDaemon(file) {
4316
4977
  };
4317
4978
  // A failed --fail-mode=abort assertion sets this; the main loop discards.
4318
4979
  let controlSignal = null;
4319
- mkdirSync(state.tmpDir, { recursive: true });
4980
+ // Owner-only: it holds the user's screen (or page) as it is recorded.
4981
+ mkdirSync(state.tmpDir, { recursive: true, mode: 0o700 });
4320
4982
  let browser = null;
4321
4983
  // Persistent (--user-data-dir) contexts have no separate browser, so track the
4322
4984
  // context too for the finally cleanup (an exception before stop must not leak
@@ -4324,9 +4986,12 @@ async function runSessionDaemon(file) {
4324
4986
  let ctxToClose = null;
4325
4987
  let controlServer = null;
4326
4988
  let discardCapture = null;
4989
+ // --source screen on Linux: the CLI's own X11 recorder, and the private
4990
+ // display it may have started. There is no page in this mode.
4991
+ let screenRecorder = null;
4992
+ let virtualDisplay = null;
4327
4993
  try {
4328
- const chromium = await loadChromium();
4329
- let page;
4994
+ let page = null;
4330
4995
  let cdpUrl;
4331
4996
  let cdpHttpUrl;
4332
4997
  // Mode-specific teardown, so the shared stop/abort paths below don't care
@@ -4337,7 +5002,44 @@ async function runSessionDaemon(file) {
4337
5002
  // below get installed), plus the context to install them on.
4338
5003
  let wantCdp = false;
4339
5004
  let bindingContext = null;
4340
- if (state.kind === "chrome-for-clipy") {
5005
+ if (state.kind === "linux-screen") {
5006
+ if (state.virtualDisplay) {
5007
+ virtualDisplay = await startVirtualDisplay(state.virtualDisplay);
5008
+ log(`virtual display ${virtualDisplay.display} started (Xvfb pid ${virtualDisplay.pid})`);
5009
+ save({ xDisplay: virtualDisplay.display, virtualDisplayPid: virtualDisplay.pid });
5010
+ }
5011
+ const xDisplay = state.xDisplay;
5012
+ if (!xDisplay)
5013
+ throw new Error("no X display to record");
5014
+ // A new virtual display has nothing on it yet, so its target is the
5015
+ // whole display; a real one was resolved by the parent.
5016
+ const target = state.screenTarget ?? { kind: "display", display: defaultDisplay(listLinuxSources(xDisplay)) };
5017
+ const recorder = await startScreenRecorder({
5018
+ xDisplay,
5019
+ target,
5020
+ tmpDir: state.tmpDir,
5021
+ caps: ffmpegCaps(realRunner),
5022
+ log,
5023
+ });
5024
+ screenRecorder = recorder;
5025
+ const vd = virtualDisplay;
5026
+ finishCapture = async () => {
5027
+ try {
5028
+ return await recorder.finish();
5029
+ }
5030
+ finally {
5031
+ await vd?.stop();
5032
+ virtualDisplay = null;
5033
+ }
5034
+ };
5035
+ discardCapture = async () => {
5036
+ await recorder.discard().catch(() => { });
5037
+ await vd?.stop();
5038
+ virtualDisplay = null;
5039
+ };
5040
+ }
5041
+ else if (state.kind === "chrome-for-clipy") {
5042
+ const chromium = await loadChromium();
4341
5043
  const port = state.chromePort ?? DEFAULT_CDP_PORT;
4342
5044
  log(`attaching to Chrome for Clipy on port ${port} for ${state.url}`);
4343
5045
  const cap = await startChromeForClipyCapture(chromium, {
@@ -4348,6 +5050,17 @@ async function runSessionDaemon(file) {
4348
5050
  tmpDir: state.tmpDir,
4349
5051
  targetUrl: state.url,
4350
5052
  log,
5053
+ // Attached before the first load, so its console, requests and
5054
+ // environment are kept (they land at t=0).
5055
+ onTargetPage: async (target) => {
5056
+ browserEvidence = attachCdpDiagnostics(target, {
5057
+ level: state.diagnostics ?? "errors",
5058
+ networkDetail: !!state.networkDetail,
5059
+ recordStart: () => recordStart,
5060
+ });
5061
+ // Bounded: evidence must never hold up the recording.
5062
+ await Promise.race([browserEvidence.ready, new Promise((r) => setTimeout(r, 3_000))]);
5063
+ },
4351
5064
  });
4352
5065
  // For a CDP-connected browser, close() disconnects and leaves Chrome for
4353
5066
  // Clipy running; it must never be killed by a session ending.
@@ -4374,6 +5087,7 @@ async function runSessionDaemon(file) {
4374
5087
  };
4375
5088
  }
4376
5089
  else {
5090
+ const chromium = await loadChromium();
4377
5091
  log(`launching chromium for ${state.url}`);
4378
5092
  // CDP is OPT-IN (--expose-cdp) and the env kill switch wins over the flag:
4379
5093
  // no debugging port is opened unless the user asked AND CLIPY_DISABLE_CDP
@@ -4424,9 +5138,10 @@ async function runSessionDaemon(file) {
4424
5138
  log(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
4425
5139
  }
4426
5140
  }
5141
+ const recordedPage = page;
4427
5142
  finishCapture = async () => {
4428
- const video = page.video();
4429
- await page.close();
5143
+ const video = recordedPage.video();
5144
+ await recordedPage.close();
4430
5145
  await context.close();
4431
5146
  if (!video)
4432
5147
  throw new Error("browser did not produce a video (recordVideo unavailable)");
@@ -4439,13 +5154,28 @@ async function runSessionDaemon(file) {
4439
5154
  return videoPath;
4440
5155
  };
4441
5156
  discardCapture = async () => {
4442
- await page.close().catch(() => { });
5157
+ await recordedPage.close().catch(() => { });
4443
5158
  await context.close().catch(() => { });
4444
5159
  };
4445
5160
  }
5161
+ // Browser evidence (console, requests, sockets) in the same v2 sidecar the
5162
+ // extension uploads, read from the browser rather than injected into the
5163
+ // page. Default: errors and failed requests; --network-detail adds
5164
+ // headers and bodies.
5165
+ // A screen capture has no page to read evidence from.
5166
+ if (page) {
5167
+ browserEvidence ??= attachCdpDiagnostics(page, {
5168
+ level: state.diagnostics ?? "errors",
5169
+ networkDetail: !!state.networkDetail,
5170
+ recordStart: () => recordStart,
5171
+ });
5172
+ // The first navigation comes later; EventSource listening must be in
5173
+ // place before it. Bounded so evidence never holds up the recording.
5174
+ await Promise.race([browserEvidence.ready, new Promise((r) => setTimeout(r, 3_000))]);
5175
+ }
4446
5176
  // Auto-marks: instrumentation ground truth alongside the agent's intent
4447
5177
  // marks. Type-tagged with [auto] so the transcript distinguishes them.
4448
- page.on("framenavigated", ((frame) => {
5178
+ page?.on("framenavigated", ((frame) => {
4449
5179
  try {
4450
5180
  if (frame.parentFrame() === null)
4451
5181
  autoMark(`[auto] navigated to ${frame.url()}`);
@@ -4454,7 +5184,7 @@ async function runSessionDaemon(file) {
4454
5184
  // never let instrumentation kill the recording
4455
5185
  }
4456
5186
  }));
4457
- page.on("console", ((msg) => {
5187
+ page?.on("console", ((msg) => {
4458
5188
  try {
4459
5189
  if (msg.type() === "error") {
4460
5190
  autoMark(`[auto] console error: ${msg.text().slice(0, 200)}`);
@@ -4490,6 +5220,9 @@ async function runSessionDaemon(file) {
4490
5220
  assertOutcome = { kind: "driver", passed, expected: "", observed: m.attest.observed };
4491
5221
  }
4492
5222
  else if (m.assert && typeof m.assert === "object") {
5223
+ if (!page) {
5224
+ throw new Error("Clipy-evaluated assertions need a Clipy-owned page; use --observed/--verdict to attach evidence you collected yourself");
5225
+ }
4493
5226
  // evaluateAssertion throws if the page is unresponsive — the HTTP path
4494
5227
  // turns that into a 5xx (the CLI then records a ⚠ UNVERIFIED file mark),
4495
5228
  // and the in-page path rejects to the driver.
@@ -4540,7 +5273,7 @@ async function runSessionDaemon(file) {
4540
5273
  // The bindings are exposed under *Impl names and re-declared with explicit
4541
5274
  // arity below, so an agent probing window.__clipyMark.length sees 2 (not the
4542
5275
  // 0 an exposeBinding wrapper reports).
4543
- if (wantCdp && bindingContext) {
5276
+ if (wantCdp && bindingContext && page) {
4544
5277
  const bindings = page;
4545
5278
  await bindings
4546
5279
  .exposeBinding("__clipyMarkImpl", async (source, ...args) => {
@@ -4587,7 +5320,7 @@ async function runSessionDaemon(file) {
4587
5320
  })
4588
5321
  .catch((e) => log(`in-page binding wrappers failed: ${e.message}`));
4589
5322
  if (state.kind === "chrome-for-clipy") {
4590
- await page.evaluate(() => {
5323
+ await bindings.evaluate(() => {
4591
5324
  const w = globalThis;
4592
5325
  w.__clipyMark = (text, opts) => w.__clipyMarkImpl(text, opts);
4593
5326
  w.__clipyChapter = (label) => w.__clipyChapterImpl(label);
@@ -4710,7 +5443,9 @@ async function runSessionDaemon(file) {
4710
5443
  controlServer = null;
4711
5444
  controlPort = 0;
4712
5445
  }
4713
- recordStart = Date.now();
5446
+ // A screen take's video starts when its ffmpeg did, a little before the
5447
+ // recorder reported frames; stamping marks from there keeps them in sync.
5448
+ recordStart = screenRecorder?.startedAt ?? Date.now();
4714
5449
  save({
4715
5450
  state: "recording",
4716
5451
  recordStartEpochMs: recordStart,
@@ -4721,7 +5456,7 @@ async function runSessionDaemon(file) {
4721
5456
  // chrome-for-clipy already navigated the target before capture started (the
4722
5457
  // marker-title selection requires a loaded page); re-navigating here would
4723
5458
  // just reload it on camera.
4724
- if (state.kind !== "chrome-for-clipy") {
5459
+ if (page && state.kind !== "chrome-for-clipy") {
4725
5460
  try {
4726
5461
  await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
4727
5462
  }
@@ -4732,7 +5467,33 @@ async function runSessionDaemon(file) {
4732
5467
  // Main loop: poll the control file; enforce the max-duration rail.
4733
5468
  let stopReason = "stop";
4734
5469
  for (;;) {
4735
- await page.waitForTimeout(400);
5470
+ if (page)
5471
+ await page.waitForTimeout(400);
5472
+ else
5473
+ await new Promise((r) => setTimeout(r, 400));
5474
+ if (screenRecorder) {
5475
+ // Resizes become segments, a closed window ends the take, and a
5476
+ // capture that keeps failing stops it: what was recorded uploads with
5477
+ // a note saying why, rather than the session running on with nothing
5478
+ // being captured.
5479
+ let note = null;
5480
+ try {
5481
+ note = screenRecorder.tick();
5482
+ }
5483
+ catch (e) {
5484
+ autoMark(`[auto] screen capture stopped: ${e.message}`);
5485
+ log(`screen capture failed: ${e.message}`);
5486
+ stopReason = "stop";
5487
+ break;
5488
+ }
5489
+ if (note)
5490
+ autoMark(note);
5491
+ if (screenRecorder.ended()) {
5492
+ log("recorded window is gone; stopping and uploading");
5493
+ stopReason = "stop";
5494
+ break;
5495
+ }
5496
+ }
4736
5497
  // A failed --fail-mode=abort assertion (set by the control handler) discards
4737
5498
  // the session just like a control-file abort.
4738
5499
  if (controlSignal === "abort") {
@@ -4777,6 +5538,16 @@ async function runSessionDaemon(file) {
4777
5538
  log(`max duration ${state.maxSec}s reached — auto-stopping and uploading`);
4778
5539
  }
4779
5540
  save({ state: "stopping" });
5541
+ // Last response bodies are read from the live page; let them land first.
5542
+ await Promise.race([browserEvidence?.settle(), new Promise((r) => setTimeout(r, 3_000))]).catch(() => { });
5543
+ // Snapshot before the page is torn down; uploaded after the recording.
5544
+ let diagnosticsSidecar = null;
5545
+ try {
5546
+ diagnosticsSidecar = (browserEvidence?.sidecar() ?? null);
5547
+ }
5548
+ catch (e) {
5549
+ log(`browser diagnostics unavailable: ${e.message}`);
5550
+ }
4780
5551
  const videoPath = await finishCapture();
4781
5552
  discardCapture = null;
4782
5553
  // Merge marks. The FILE is the mark of record: `clipy mark` writes there when
@@ -4882,23 +5653,28 @@ async function runSessionDaemon(file) {
4882
5653
  log(`mark limit: merged ${notes.length} marks — keeping the first 200 (dropped ${notes.length - 200})`);
4883
5654
  notes = notes.slice(0, 200);
4884
5655
  }
4885
- save({ state: "uploading" });
5656
+ save({ state: "uploading", videoPath });
4886
5657
  const uploaded = await uploadVideoToClipy(ctx, {
4887
5658
  videoPath,
4888
5659
  name: state.name,
4889
5660
  description: state.description,
4890
5661
  recordingKind: state.recordingKind,
4891
5662
  narration: notes.length ? { notes } : undefined,
5663
+ browserDiagnostics: diagnosticsSidecar,
4892
5664
  log: (m) => log(m.replace(/\x1b\[[0-9;]*m/g, "")),
4893
5665
  }).catch((e) => {
4894
5666
  // Keep the capture — losing the bytes is worse than leaving a file.
4895
- const kept = join(sessionDir(), `kept-${randomUUID()}.webm`);
5667
+ const kept = join(sessionDir(), `kept-${randomUUID()}${extname(videoPath) || ".webm"}`);
4896
5668
  try {
4897
- renameSync(videoPath, kept);
5669
+ moveFile(videoPath, kept);
4898
5670
  save({ keptVideoPath: kept });
5671
+ // The capture is safe outside it, so nothing in tmpDir is needed.
5672
+ rmSync(state.tmpDir, { recursive: true, force: true });
4899
5673
  }
4900
5674
  catch {
4901
- // original path stays in tmpDir (cleanup below is skipped on throw)
5675
+ // The move failed (a full disk, say): report the capture where it is.
5676
+ // Cleanup keeps a kept path that is still inside tmpDir.
5677
+ save({ keptVideoPath: videoPath });
4902
5678
  }
4903
5679
  throw e;
4904
5680
  });
@@ -4928,6 +5704,10 @@ async function runSessionDaemon(file) {
4928
5704
  await ctxToClose.close().catch(() => { });
4929
5705
  if (browser)
4930
5706
  await browser.close().catch(() => { });
5707
+ // A failure before the recorder took ownership of the display (or after
5708
+ // it) must not leave Xvfb running.
5709
+ if (virtualDisplay)
5710
+ await virtualDisplay.stop().catch(() => { });
4931
5711
  // Remove the copied-profile scratch root (a SIGKILL strands it → the 24h
4932
5712
  // sweep at the next record/session start catches that).
4933
5713
  if (state.profileScratchRoot) {
@@ -5093,18 +5873,18 @@ async function cmdSetup(ctx, targetRaw, json, withBrowser) {
5093
5873
  // ---------------------------------------------------------------------------
5094
5874
  // chrome: the dedicated "Chrome for Clipy" automation browser.
5095
5875
  // ---------------------------------------------------------------------------
5096
- async function cmdChrome(sub, json, portRaw) {
5876
+ async function cmdChrome(sub, json, portRaw, foreground = false) {
5097
5877
  const home = homedir();
5098
5878
  const port = portRaw ? Number(portRaw) : DEFAULT_CDP_PORT;
5099
5879
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
5100
- die("usage: clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--json]", 2);
5880
+ die("usage: clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--foreground] [--json]", 2);
5101
5881
  }
5102
5882
  switch (sub) {
5103
5883
  case "setup":
5104
5884
  await cmdChromeSetup(home, port, json);
5105
5885
  return;
5106
5886
  case "start": {
5107
- const result = await startChromeForClipy(home, process.env, process.platform, port);
5887
+ const result = await startChromeForClipy(home, process.env, process.platform, port, { foreground });
5108
5888
  if (!result.ok) {
5109
5889
  if (json)
5110
5890
  printJson({ ok: false, error: result.error });
@@ -5124,7 +5904,7 @@ async function cmdChrome(sub, json, portRaw) {
5124
5904
  return;
5125
5905
  }
5126
5906
  case "stop": {
5127
- const result = stopChromeForClipy(home);
5907
+ const result = await stopChromeForClipy(home);
5128
5908
  if (json)
5129
5909
  printJson({ ok: result.ok, stopped: result.stopped, ...(result.error ? { error: result.error } : {}) });
5130
5910
  else if (!result.ok)
@@ -5143,11 +5923,23 @@ async function cmdChrome(sub, json, portRaw) {
5143
5923
  }
5144
5924
  process.stdout.write(status.running
5145
5925
  ? `running (pid ${status.pid}), CDP ${status.cdpUrl} (${status.cdpReady ? (status.browser ?? "ready") : "not answering"})\n`
5146
- : "not running\n");
5147
- process.stdout.write(`profile: ${status.profileDir}\napp installed: ${status.appInstalled ? "yes" : "no"}\n`);
5926
+ : status.error ? `unknown: ${status.error}\n` : "not running\n");
5927
+ process.stdout.write(`profile: ${status.profileDir}\n`);
5928
+ if (process.platform === "darwin")
5929
+ process.stdout.write(`app installed: ${status.appInstalled ? "yes" : "no"}\n`);
5148
5930
  return;
5149
5931
  }
5150
5932
  case "install-app": {
5933
+ // The launcher bundle is a macOS Finder/Spotlight identity. Elsewhere
5934
+ // there is nothing to install, and `clipy chrome start` is the launcher.
5935
+ if (process.platform !== "darwin") {
5936
+ const note = "the launcher app is macOS-only; nothing to install here. Use `clipy chrome start`";
5937
+ if (json)
5938
+ printJson({ ok: true, skipped: true, reason: note });
5939
+ else
5940
+ process.stdout.write(`${note}\n`);
5941
+ return;
5942
+ }
5151
5943
  const result = installChromeForClipyApp(home, process.env, process.platform, port);
5152
5944
  if (!result.ok) {
5153
5945
  if (json)
@@ -5164,7 +5956,7 @@ async function cmdChrome(sub, json, portRaw) {
5164
5956
  return;
5165
5957
  }
5166
5958
  default:
5167
- die("usage: clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--json]", 2);
5959
+ die("usage: clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--foreground] [--json]", 2);
5168
5960
  }
5169
5961
  }
5170
5962
  const CHROME_SETUP_TIMEOUT_MS = 15 * 60_000;
@@ -5197,7 +5989,8 @@ async function cmdChromeSetup(home, port, json) {
5197
5989
  if (app.ok)
5198
5990
  say(`updated the "${CHROME_FOR_CLIPY_APP_NAME}" launcher at ${app.path}`);
5199
5991
  }
5200
- const started = await startChromeForClipy(home, process.env, process.platform, port);
5992
+ // The person installs the extension and signs in here, so the window comes forward.
5993
+ const started = await startChromeForClipy(home, process.env, process.platform, port, { foreground: true });
5201
5994
  if (!started.ok)
5202
5995
  fail(started.error);
5203
5996
  const openTab = (url) => openTabForPerson(port, url).catch(() => { });
@@ -5312,7 +6105,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
5312
6105
  // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
5313
6106
  // contract changes.
5314
6107
  // ---------------------------------------------------------------------------
5315
- const GUIDE_SCHEMA_VERSION = 16;
6108
+ const GUIDE_SCHEMA_VERSION = 17;
5316
6109
  /** The stable machine-readable failure taxonomy carried in `--json` error
5317
6110
  * envelopes. Codes are the contract; messages are not. Published through the
5318
6111
  * guide so an agent discovers the full recovery table without the skill. */
@@ -5398,16 +6191,16 @@ function cmdGuide(json) {
5398
6191
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
5399
6192
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
5400
6193
  cmdDoc("proof", "clipy proof (--frame <png|jpg|webp>… | --video <webm|mp4>) [--for <recording>] [--caption <text>…] [--hold sec] [--title t] [--type kind] [--note '3: text']… [--wait] [--json]", "Tool-neutral proof upload. --frame may be repeated to turn screenshots produced by any browser, computer-use, simulator, or test tool into one high-quality silent MP4; --caption must be omitted or repeated exactly once per frame and becomes timestamped agent narration. --hold controls each frame's duration (default 3s, 0.25–30; total cap 300s); --width/--height must be even integers from 320–3840 and default to 1280x720. Frame inputs are bounded to 50 MiB each and 250 MiB total. Screenshot stitching needs ffmpeg but does not need Playwright or a browser integration. --video uploads an already-recorded WebM or MP4 without re-encoding and needs no recording dependency. Exactly one source mode is required. --for <recording id|url> links the uploaded proof back to the recording it verifies (validated before upload; the link appears in the owner-only receipt on that recording's watch page and needs a key with both ingest and recordings:read). --json prints {id, shareUrl, contextUrl, sizeBytes, source, verifies?}; proof-video source reports only the detected container and never discloses the local path. Captions and notes are driver-attested narration, not Clipy-verified assertions.", ["--frame", "--caption", "--video", "--for", "--hold", "--width", "--height", "--title", "--description", "--type", "--note", "--wait", "--json"]),
5401
- cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch from a persistent Chromium user-data ROOT with its whole logged-in identity; web only, mutually exclusive with --storage-state; refused if <dir> is a profile subdir — pass the root — or, in direct mode, a live-locked root via SingletonLock/Socket), --profile-directory <name> (with --user-data-dir: pick a NAMED profile like 'Profile 12' from chrome://version; Playwright can't select a profile in place, so Clipy COPIES it into a temp recording root and launches the copy — loudly disclosed, the real profile is never opened or written, and the copy is deleted after upload; no need to quit Chrome, though it warns if Chrome is running since in-use DBs may copy inconsistently). Auth boundary: --storage-state only seeds what the file contains; for cross-origin auth produce it with `npx playwright open --save-storage=auth.json <login-host>`, or use --user-data-dir + --profile-directory to record your real profile, or --source mac-screen --window Chrome. With --source mac-screen: records the real screen via the Clipy Mac app (--type not yet applied on mac; auth flags rejected — the screen is already logged in); --window '<title|app|id>' records that window's initial screen area and --display <id> records one display (ids from clipy sources). --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--user-data-dir", "--profile-directory", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
5402
- cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen|chrome-for-clipy|chrome-extension] [--window w] [--display d] [--expose-cdp] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). With --source mac-screen, --window records that window's initial screen area and --display records one display. --source chrome-extension records ONE TAB through the Clipy extension inside Chrome for Clipy (needs a one-time clipy chrome setup): no daemon, the extension records and uploads; start returns cdpHttpUrl and the recorded tab's url (opened in the background, never focused), --name titles the recording, the tab's sound is left out unless --tab-audio (detected speech would replace the marks as the transcript), mark/chapter (plain or --observed/--verdict, not --assert-*) are kept by the CLI and sent at stop as the transcript, stop waits for the upload and returns the link. --source chrome-for-clipy records ONE TAB (tab video + tab audio, no picker or gesture) inside the persistent Chrome for Clipy instance: the instance is started automatically (sign in once via clipy chrome start and the profile stays signed in), the recorded tab opens at --url, its CDP endpoint is always published as cdpUrl/cdpHttpUrl so drivers attach to the very browser being recorded, and stopping the session leaves Chrome for Clipy running; auth-capture flags and --user-data-dir are rejected for this source. --expose-cdp (web sessions) opens a CDP endpoint (cdpUrl/cdpHttpUrl in the state file + session start/status output) so your own tools can drive the page while it records; OFF by default (any local process could attach), and CLIPY_DISABLE_CDP=1 forces it off. `session run [start flags] -- <command…>` starts a session, runs the command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp, plus CLIPY_TARGET_ID/CLIPY_PAGE_WS_URL for the recorded tab with --source chrome-extension), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code. It is the crash-safe wrapper, so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--user-data-dir/--profile-directory/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--tab-audio", "--expose-cdp", "--storage-state", "--user-data-dir", "--profile-directory", "--cookie", "--local-storage", "--init-script", "--json"]),
6194
+ cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch from a persistent Chromium user-data ROOT with its whole logged-in identity; web only, mutually exclusive with --storage-state; refused if <dir> is a profile subdir — pass the root — or, in direct mode, a live-locked root via SingletonLock/Socket), --profile-directory <name> (with --user-data-dir: pick a NAMED profile like 'Profile 12' from chrome://version; Playwright can't select a profile in place, so Clipy COPIES it into a temp recording root and launches the copy — loudly disclosed, the real profile is never opened or written, and the copy is deleted after upload; no need to quit Chrome, though it warns if Chrome is running since in-use DBs may copy inconsistently). Auth boundary: --storage-state only seeds what the file contains; for cross-origin auth produce it with `npx playwright open --save-storage=auth.json <login-host>`, or use --user-data-dir + --profile-directory to record your real profile, or --source mac-screen --window Chrome. With --source screen (or mac-screen on macOS): records the real screen, via the Clipy Mac app on macOS (--type not yet applied on mac) and with the CLI's own X11 recorder on Linux (silent; needs ffmpeg with x11grab). Auth flags are rejected, since the screen is already logged in; --window '<title|app|id>' records that window by itself (windows on top of it stay out, and it follows the window if it moves, only when --json reports windowCapture \"window\"; \"area\", from a Clipy Mac app older than bridge protocol v3 or on ffmpeg older than 5.1, records whatever is on top, and on Linux covered parts are black without a compositor) and --display <id> records one display (ids from clipy sources). Linux only: --x-display :N picks the X display (default $DISPLAY) and --virtual-display records a private X display sized by --width/--height. --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--user-data-dir", "--profile-directory", "--width", "--height", "--wait", "--source", "--window", "--display", "--x-display", "--virtual-display", "--json"]),
6195
+ cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|screen|chrome-for-clipy|chrome-extension] [--window w] [--display d] [--x-display :N] [--virtual-display] [--expose-cdp] [--diagnostics off|errors|all] [--network-detail] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). Web and chrome-for-clipy sessions attach browser evidence read from the browser itself (console output, uncaught errors, failed requests including GraphQL errors, WebSocket activity, environment) as the recording's browser diagnostics: --diagnostics errors (default) keeps warnings/errors and failures, all keeps every message and request, off keeps none; --network-detail also keeps request/response headers and text bodies (cookie and authorization headers never leave the machine; the server redacts the rest by field name and value pattern). With --source screen (mac-screen on macOS), --window records that window by itself (windows on top of it stay out only when --json reports windowCapture \"window\"; \"area\", from a Clipy Mac app older than bridge protocol v3 or on ffmpeg older than 5.1, records whatever is on top, and on Linux covered parts are black without a compositor) and --display records one display; on Linux --x-display :N picks the X display and --virtual-display records a private X display whose name is returned as xDisplay (session run exports it to the command as DISPLAY). --source chrome-extension records ONE TAB through the Clipy extension inside Chrome for Clipy (needs a one-time clipy chrome setup): no daemon, the extension records and uploads; start returns cdpHttpUrl and the recorded tab's url (opened in the background, never focused), --name titles the recording, the tab's sound is left out unless --tab-audio (detected speech would replace the marks as the transcript), mark/chapter (plain or --observed/--verdict, not --assert-*) are kept by the CLI and sent at stop as the transcript, stop waits for the upload and returns the link. --source chrome-for-clipy records ONE TAB (tab video + tab audio, no picker or gesture) inside the persistent Chrome for Clipy instance: the instance is started automatically (sign in once via clipy chrome start and the profile stays signed in), the recorded tab opens at --url, its CDP endpoint is always published as cdpUrl/cdpHttpUrl so drivers attach to the very browser being recorded, and stopping the session leaves Chrome for Clipy running; auth-capture flags and --user-data-dir are rejected for this source. --expose-cdp (web sessions) opens a CDP endpoint (cdpUrl/cdpHttpUrl in the state file + session start/status output) so your own tools can drive the page while it records; OFF by default (any local process could attach), and CLIPY_DISABLE_CDP=1 forces it off. `session run [start flags] -- <command…>` starts a session, runs the command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp, plus CLIPY_TARGET_ID/CLIPY_PAGE_WS_URL for the recorded tab with --source chrome-extension), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code. It is the crash-safe wrapper, so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--user-data-dir/--profile-directory/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--x-display", "--virtual-display", "--tab-audio", "--expose-cdp", "--diagnostics", "--network-detail", "--storage-state", "--user-data-dir", "--profile-directory", "--cookie", "--local-storage", "--init-script", "--json"]),
5403
6196
  cmdDoc("mark", "clipy mark \"<text>\" [--observed \"<values>\" --verdict pass|fail] [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>] [--json]", "Drop a live-timestamped note into the active session. A mark carries at most ONE evidence provenance, and the two are labeled + tallied separately so they can never be pooled. DRIVER-ATTESTED (--observed '<values>' --verdict pass|fail, both required together): you drove the browser and report what YOU observed — renders '<text> [≈ ASSERT driver-attested; observed=<values>]' (pass) / '<text> [≈ FAILED driver-attested; observed=<values>]' (fail) — a HEDGE glyph, never ✓/✗, so a skim distinguishes provenance by shape alone and works in EVERY session type including --source mac-screen. Honesty rule: driver-attested means Clipy vouches the agent SAID it, not that Clipy verified it — put real observed values there. Combining --observed/--verdict with --assert-* is a usage error. CLIPY-VERIFIED assertion marks (Clipy-owned page only) make the note evidence Clipy itself checked: --assert-selector checks a CSS selector matches (its trimmed textContent is recorded as 'observed'); --assert-text requires that element's text to contain a substring (needs --assert-selector); --assert-url matches the page URL against a glob (** = any, * = any non-slash, no * = substring). The daemon evaluates against its live page and annotates the mark: pass ⇒ '<text> [assert ✓ verified-by-clipy; <observed>]', fail ⇒ '<text> [ASSERT ✗ verified-by-clipy; expected …; observed …]' — a false claim cannot read as fact. --fail-mode warn (default) records the ✗; --fail-mode abort DISCARDS the whole session on a failed assertion (no upload) and the CLI exits non-zero. If any assertion was attempted, a leading 0ms [verification] note is prepended, reporting the provenances as SEPARATE segments: '[verification] N clipy-verified: P passed, F failed, K unverified · M driver-attested: P passed, F failed' (a segment is omitted when empty; with only clipy-verified marks the legacy 'N assertion(s): …' rendering is byte-identical). --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now (mutually exclusive). Assertions/backdating need a web session (rejected on --source mac-screen). Up to 200 marks per recording.", ["--observed", "--verdict", "--assert-selector", "--assert-text", "--assert-url", "--fail-mode", "--at", "--ago", "--json"]),
5404
6197
  cmdDoc("chapter", "clipy chapter \"<label>\" [--json]", "Mark a BEFORE/AFTER section boundary in the active recording (stored as '=== CHAPTER: <label> ==='). The PR-review shape: demo the base branch, run `clipy chapter \"AFTER — fix applied\"`, swap branches + restart the dev server, demo the fix — one video carrying both states. Works on web + --source mac-screen sessions.", ["--json"]),
5405
6198
  cmdDoc("doctor", "clipy doctor [--json]", "One-shot health check: API reachability (GET /api/health, with latency), API key + whoami round-trip, Mac agent bridge (exists/parses/pid/appVersion>=" + MIN_BRIDGE_APP_VERSION + "), Playwright resolvability (and the resolved path/node_modules dir), context/proof prerequisites (yt-dlp presence/path/version, ffmpeg + ffprobe presence/version, and whether that ffmpeg has libwebp), and install mode (npx/global/local) — each a pass/warn/fail with a fix hint; exits non-zero if any check fails. Read-only: it never installs anything, so a missing yt-dlp/ffmpeg reports WARN with the install command rather than silently downloading a binary. Run it first whenever an import, proof, or recording fails.", ["--json"]),
5406
6199
  cmdDoc("playwright-path", "clipy playwright-path [--json]", "Print the node_modules directory of the Playwright this CLI resolves, so your own --expose-cdp driver scripts can load the same copy: NODE_PATH=$(clipy playwright-path) node driver.js. Exits 1 (empty stdout) if Playwright is unresolvable. --json prints {path, nodeModulesDir, source}", ["--json"]),
5407
- cmdDoc("sources", "clipy sources [--json]", "List displays + windows the Clipy Mac app can capture — ids feed --window/--display. --json gives each entry a `source` {kind,id,title} in the SAME shape session start/record report for the resolved capture, so a caller can compare what it picked against what the camera reports without transforming either."),
6200
+ cmdDoc("sources", "clipy sources [--x-display :N] [--json]", "List displays + windows that --source screen can capture (the Clipy Mac app's on macOS; the X display's on Linux, where listing windows needs x11-utils) — ids feed --window/--display. --json gives each entry a `source` {kind,id,title} in the SAME shape session start/record report for the resolved capture, so a caller can compare what it picked against what the camera reports without transforming either."),
5408
6201
  cmdDoc("setup", "clipy setup [claude|codex|cursor|windsurf|opencode] [--with-browser] [--json]", "Wire Clipy into one coding agent in a single command: sign in if needed, install the bundled skill, and register the MCP server in that agent's own config (`claude`/`codex` through their own `mcp add`; `cursor`/`windsurf`/`opencode` by merging their JSON config, never replacing other servers). Omit the agent to auto-detect from the environment — ambiguous or unknown exits 2 rather than guessing. Re-running is safe. Successful --json output is {ok:true, target, skill:{installed,path}, mcp:{method,path,changed,alreadyPresent}, authenticated:true, restartRequired:true}. Failures use {ok:false,code,error,remediation,partial}; partial.mcp.method 'manual' means the caller must run partial.mcp.command or paste partial.mcp.snippet before setup is complete. The MCP server is read at agent startup, so the calling session will not see the tools until it restarts. --with-browser additionally provisions Chrome for Clipy, the agent-owned automation browser (see chrome): on macOS it installs the launcher app once, then it starts the instance. Its outcome is reported under a `browser` key ({ok, chrome:{appInstalled, appPath?, running, error?}}) and a browser failure never fails core setup.", ["--with-browser", "--json"]),
5409
6202
  cmdDoc("agents", "clipy agents <status|install|uninstall> <claude|codex|cursor|windsurf|opencode>", "Skill file only — does NOT register MCP. `clipy setup` is the one-command form; install triggers a browser login first when no key is configured (interactive terminals only)"),
5410
- cmdDoc("chrome", "clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--json]", "setup (one time, for --source chrome-extension): starts Chrome for Clipy, opens the Clipy extension's Web Store page and then clipy.online in that window, and waits up to 15 minutes until the extension reports it is installed and signed in; returns {ok:true, extension:{version,email}, chrome} and is a quick check on a ready machine. The two steps it waits for are the user's: an agent relays them and never performs them. Chrome for Clipy also launches with --allowlisted-extension-id (CLIPY_EXTENSION_ID overrides the store id), and an instance found running without the current flags is relaunched. Launch and manage 'Chrome for Clipy', a dedicated persistent automation browser: its own profile (sign in once, identity persists across launches), CDP on --port (default 9333) for any driver, --auto-select-tab-capture-source-by-title so a page's getDisplayMedia captures the tab whose title starts with the 'clipy-rec' marker without any picker or gesture UI, and background-throttling disabled so hidden tabs keep rendering. start is idempotent (re-reports the running instance); status returns {running,pid,port,cdpUrl,cdpReady,profileDir,appInstalled,captureTitleMarker}; install-app writes a named 'Chrome for Clipy.app' launcher into ~/Applications (macOS only). Drivers attach over raw CDP; no extension is needed.", ["--port", "--json"]),
6203
+ cmdDoc("chrome", "clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--foreground] [--json]", "setup (one time, for --source chrome-extension): starts Chrome for Clipy, opens the Clipy extension's Web Store page and then clipy.online in that window, and waits up to 15 minutes until the extension reports it is installed and signed in; returns {ok:true, extension:{version,email}, chrome} and is a quick check on a ready machine. The two steps it waits for are the user's: an agent relays them and never performs them. Chrome for Clipy also launches with --allowlisted-extension-id (CLIPY_EXTENSION_ID overrides the store id), and an instance found running without the current flags is relaunched. Launch and manage 'Chrome for Clipy', a dedicated persistent automation browser: its own profile (sign in once, identity persists across launches), CDP on --port (default 9333) for any driver, --auto-select-tab-capture-source-by-title so a page's getDisplayMedia captures the tab whose title starts with the 'clipy-rec' marker without any picker or gesture UI, and background-throttling disabled so hidden tabs keep rendering. start is idempotent (re-reports the running instance) and, on macOS, launches in the background without taking focus from the app the user is in (--foreground brings the window forward, e.g. to sign in; setup always does); status returns {running,pid,port,cdpUrl,cdpReady,profileDir,appInstalled,captureTitleMarker}; install-app writes a named 'Chrome for Clipy.app' launcher into ~/Applications (macOS only). Drivers attach over raw CDP; no extension is needed.", ["--port", "--foreground", "--json"]),
5411
6204
  cmdDoc("guide", "clipy guide --json", "This manifest"),
5412
6205
  cmdDoc("mcp", "clipy mcp", "Run the Clipy MCP server (wraps npx -y @clipy/mcp)"),
5413
6206
  ],
@@ -5419,8 +6212,9 @@ function cmdGuide(json) {
5419
6212
  "Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
5420
6213
  "--note is absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text'); pass-scoped notes anchor to the real start of a --viewports pass, so they don't drift when load time shifts the pass boundaries. A malformed pass note (e.g. 'pass2 text' with no colon) is a usage error, not silently demoted.",
5421
6214
  "--type declares what a recording IS (bug_report/feature_request/product_demo/walkthrough_tutorial/feedback_review/discussion_talk/other, plus short aliases) so the AI summary doesn't misread a demo as a bug report. Applied on web today; --source mac-screen support is pending a Clipy app update.",
6215
+ "REAL SCREEN ON LINUX: --source screen records the X display with ffmpeg (x11grab), no Clipy app needed. A --window is that window's own pixels: under a compositor (GNOME, KDE, picom, xcompmgr) a covered window still records in full and nothing on top of it appears; without one the covered part is black. On an ffmpeg older than 5.1 a window is recorded as the screen area it covers instead, so anything on top of it shows; --json reports which as windowCapture (\"window\" or \"area\"). A resize starts a new segment that is fitted into the first frame, a closed window ends and uploads the take, and every such event lands as an [auto] mark. --virtual-display gives the agent its own private X display (Xvfb), which never touches the user's screen, cursor or keyboard; use `clipy session run --source screen --virtual-display -- <cmd>` so the command gets DISPLAY. Wayland sessions refuse the real screen (it needs the desktop's consent dialog): use --virtual-display or --x-display. Linux screen recordings are silent. Windows: no real-screen path for agents yet; use chrome-for-clipy, --url, or clipy proof.",
5422
6216
  "AUDIO on --source mac-screen: agent screen recordings do NOT capture the microphone by default (system audio ON, mic OFF). An agent recording on your behalf is not the same consent as a human clicking Record — nobody asked for the room, or whatever call you are on, to be captured — and agent narration rides on marks, not speech. Opt in with --mic; opt out of system audio with --no-system-audio. Both are --source mac-screen only: headless web captures are silent, so passing them on the web path is a usage error (exit 2). The resolved config is printed (`audio: system on, mic off`) and returned as a sibling `audio` {includeSystemAudio, includeMic} in --json — sibling, not inside `source`, because audio is a property of the capture, not of the surface. IMPORTANT: the CLI reports the config the APP echoed back, and if the app does not echo one (a desktop build predating agent audio control) it WARNS that the app is using its own defaults and the microphone may be recording — update the Clipy app to make the setting take effect.",
5423
- "CONFIRM THE CAMERA on --source mac-screen. `session start` and `record` print the surface they resolved, read LIVE from the app at start time — `recording window: \"<title>\" (id 157)` — and `session start --json` / `record --json` carry it as `source: {kind, id, title}`, the SAME shape each entry's `source` takes in `clipy sources --json`, so a caller can compare its pick against the camera with a direct object comparison. Check it and abort on mismatch: driver-attested marks prove what the DRIVER observed and say nothing about what the camera saw, so driving a background tab of the recorded window yields a truthful 'N passed' tally over footage of something else — worse than no evidence, because the tally vouches for the wrong footage. Clipy will NEVER activate or foreground a window/tab: it cannot know which tab/page/simulator you mean (on mac-screen it may not be recording a browser at all), so focusing the right surface is the caller's job, done before session start. The reported title and screen area are fixed at START time; moving the window does not move the recording, and anything entering that area is filmed.",
6217
+ "CONFIRM THE CAMERA on --source mac-screen. `session start` and `record` print the surface they resolved, read LIVE from the app at start time — `recording window: \"<title>\" (id 157)` — and `session start --json` / `record --json` carry it as `source: {kind, id, title}`, the SAME shape each entry's `source` takes in `clipy sources --json`, so a caller can compare its pick against the camera with a direct object comparison. Check it and abort on mismatch: driver-attested marks prove what the DRIVER observed and say nothing about what the camera saw, so driving a background tab of the recorded window yields a truthful 'N passed' tally over footage of something else — worse than no evidence, because the tally vouches for the wrong footage. Clipy will NEVER activate or foreground a window/tab: it cannot know which tab/page/simulator you mean (on mac-screen it may not be recording a browser at all), so focusing the right surface is the caller's job, done before session start. The reported title is fixed at START time. The recording is that window's own pixels: it follows the window if it moves, and windows on top of it are not filmed.",
5424
6218
  "Clipy is a RECORDER, not a driver. When you drive the browser yourself (the usual agent case), the primary path is: record the real app (--source mac-screen --window '<app>', or your own driven browser) and attach evidence with driver-attested marks — `clipy mark \"<claim>\" --observed \"<values you read>\" --verdict pass|fail` — plus `clipy chapter` for before/after. Clipy holds the ledger; it does not drive. The owned-browser auth flags (--storage-state/--user-data-dir/--profile-directory/--cookie/--local-storage/--init-script) are the AGENTLESS/CI fallback for when nothing is driving and Clipy needs its own logged-in context. Provenance is never pooled: driver-attested marks render '[≈ ASSERT driver-attested; observed=…]' / '[≈ FAILED …]' (hedge glyph) and clipy-evaluated ones '[assert ✓ verified-by-clipy; …]' / '[ASSERT ✗ verified-by-clipy; …]' (✓/✗ are reserved for what Clipy itself checked), and the [verification] note counts them in separate segments. The honesty rule: driver-attested means Clipy vouches the agent SAID it, not that Clipy verified it.",
5425
6219
  "Assertion marks are the differentiator: assert what you claim. `clipy mark \"X\" --assert-selector '.status' --assert-text Active` records X only alongside the live-page truth — the daemon runs the check against its Playwright page and annotates the mark ✓/✗ with what it actually observed, so a false claim cannot pass as fact in the transcript. --fail-mode abort turns a failed assertion into a discarded session (nothing uploaded, non-zero exit). Assertions need a web session and the daemon's control endpoint (started by clipy 0.6+); they are rejected on --source mac-screen.",
5426
6220
  "A mark is NEVER dropped, and a late verdict never rewrites it. If the daemon can't be reached to evaluate an assertion (its event loop briefly starved during a dev-server recompile), `clipy mark` records the narration anyway tagged '[ASSERT ⚠ clipy could not evaluate — <reason>]', prints a loud ⚠, and exits 0 — an unverified claim is flagged, never promoted to a ✓. The tally's third bucket counts these: '[verification] N assertion(s): P passed, F failed, K unverified' (the ', K unverified' clause is omitted when K=0). That ⚠ is the MARK OF RECORD: if the daemon was only slow and evaluates the same claim later, that verdict judged a LATER page state, so it does NOT overwrite the ⚠ — it's recorded as a separate '[late check of \"…\" — evaluated Ns after the claim: …]' note at its own time and counts toward none of P/F/K. Plain non-asserted marks the daemon later processes are just deduped (exactly once).",
@@ -5517,6 +6311,7 @@ async function main() {
5517
6311
  "no-browser": { type: "boolean", default: false },
5518
6312
  "with-browser": { type: "boolean", default: false },
5519
6313
  port: { type: "string" },
6314
+ foreground: { type: "boolean", default: false },
5520
6315
  "api-url": { type: "string" },
5521
6316
  status: { type: "string" },
5522
6317
  page: { type: "string" },
@@ -5528,6 +6323,8 @@ async function main() {
5528
6323
  mic: { type: "boolean", default: false },
5529
6324
  "no-system-audio": { type: "boolean", default: false },
5530
6325
  "tab-audio": { type: "boolean", default: false },
6326
+ diagnostics: { type: "string" },
6327
+ "network-detail": { type: "boolean", default: false },
5531
6328
  vtt: { type: "boolean", default: false },
5532
6329
  for: { type: "string" },
5533
6330
  timeout: { type: "string" },
@@ -5556,6 +6353,8 @@ async function main() {
5556
6353
  source: { type: "string" },
5557
6354
  window: { type: "string" },
5558
6355
  display: { type: "string" },
6356
+ "x-display": { type: "string" },
6357
+ "virtual-display": { type: "boolean", default: false },
5559
6358
  type: { type: "string" },
5560
6359
  "assert-selector": { type: "string" },
5561
6360
  "assert-text": { type: "string" },
@@ -5648,7 +6447,19 @@ async function main() {
5648
6447
  includeSystemAudio: !values["no-system-audio"],
5649
6448
  includeMic: Boolean(values.mic),
5650
6449
  });
6450
+ // Browser evidence for sessions Clipy drives. `errors` (the default) keeps
6451
+ // console warnings/errors, uncaught errors and failed requests; `all` keeps
6452
+ // every console message and request; `off` records none.
6453
+ const diagnosticsLevel = () => {
6454
+ const raw = values.diagnostics;
6455
+ if (raw === undefined)
6456
+ return "errors";
6457
+ if (raw === "off" || raw === "errors" || raw === "all")
6458
+ return raw;
6459
+ die(`--diagnostics must be off, errors or all (got "${raw}")`, 2);
6460
+ };
5651
6461
  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
+ const linuxAudioGuard = "--mic/--no-system-audio: Linux screen recordings are silent for now (narrate with clipy mark); drop the audio flag";
5652
6463
  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";
5653
6464
  switch (command) {
5654
6465
  case "login":
@@ -5808,7 +6619,7 @@ async function main() {
5808
6619
  await cmdSetup(ctx, rest[0], json, values["with-browser"] === true);
5809
6620
  return;
5810
6621
  case "chrome":
5811
- await cmdChrome(rest[0], json, values.port);
6622
+ await cmdChrome(rest[0], json, values.port, values.foreground === true);
5812
6623
  return;
5813
6624
  case "agents":
5814
6625
  await cmdAgents(ctx, rest[0], rest[1], json);
@@ -5817,6 +6628,17 @@ async function main() {
5817
6628
  cmdGuide(json);
5818
6629
  return;
5819
6630
  case "sources": {
6631
+ // An explicit CLIPY_BRIDGE_FILE means "ask that Clipy app", on any OS.
6632
+ if (process.platform === "linux" && !process.env.CLIPY_BRIDGE_FILE?.trim()) {
6633
+ const xDisplay = values["x-display"]?.trim() || process.env.DISPLAY;
6634
+ if (!xDisplay) {
6635
+ die("no X display: run on a desktop session or name one with --x-display :N (a --virtual-display session prints its own)");
6636
+ }
6637
+ printLinuxSources(listLinuxSources(xDisplay), json);
6638
+ return;
6639
+ }
6640
+ if (process.platform === "win32" && !process.env.CLIPY_BRIDGE_FILE?.trim())
6641
+ die(WINDOWS_SCREEN_REFUSAL);
5820
6642
  // Enumerate what the Mac app can capture, so --window/--display have ids.
5821
6643
  try {
5822
6644
  const sources = await listSources(readBridgeInfo());
@@ -5871,21 +6693,63 @@ async function main() {
5871
6693
  return;
5872
6694
  }
5873
6695
  case "record": {
5874
- const source = String(values.source ?? "web");
5875
- if (source !== "web" && source !== "mac-screen") {
5876
- die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
6696
+ const source = normalizeScreenSource(String(values.source ?? "web"));
6697
+ if (source !== "web" && !isScreenSource(source)) {
6698
+ die("--source must be web (headless browser) or screen (the real screen: the Clipy Mac app on macOS, the CLI's own recorder on Linux)", 2);
5877
6699
  }
5878
- if ((values.window || values.display) && source !== "mac-screen") {
5879
- die("--window/--display record the real screen — add --source mac-screen", 2);
6700
+ if ((values.window || values.display) && !isScreenSource(source)) {
6701
+ die("--window/--display record the real screen: add --source screen", 2);
5880
6702
  }
5881
6703
  if (values.window && values.display) {
5882
6704
  die("--window and --display are mutually exclusive — pick one capture source", 2);
5883
6705
  }
5884
- if (source === "mac-screen" && authFlagsPresent)
6706
+ if ((values["x-display"] || values["virtual-display"]) && source !== "linux-screen") {
6707
+ die("--x-display/--virtual-display apply to --source screen on Linux", 2);
6708
+ }
6709
+ if (isScreenSource(source) && authFlagsPresent)
5885
6710
  die(macAuthGuard, 2);
5886
- if (source !== "mac-screen" && audioFlagsPresent)
6711
+ if (source === "linux-screen" && audioFlagsPresent)
6712
+ die(linuxAudioGuard, 2);
6713
+ if (source === "web" && audioFlagsPresent)
5887
6714
  die(webAudioGuard, 2);
5888
6715
  const recordingKind = values.type ? requireRecordingKind(String(values.type)) : undefined;
6716
+ if (source === "linux-screen") {
6717
+ const forSec = num(values.for, 15);
6718
+ if (forSec > SESSION_HARD_CAP_SEC)
6719
+ die(`--for is capped at ${SESSION_HARD_CAP_SEC}s`, 2);
6720
+ const result = await cmdRecordLinux(ctx, {
6721
+ forSec,
6722
+ name: (values.title ?? values.name)?.trim() ||
6723
+ undefined,
6724
+ description: values.description?.trim() || undefined,
6725
+ recordingKind,
6726
+ window: values.window?.trim() || undefined,
6727
+ display: values.display?.trim() || undefined,
6728
+ xDisplay: values["x-display"]?.trim() || undefined,
6729
+ virtualDisplay: Boolean(values["virtual-display"]),
6730
+ width: num(values.width, 1280),
6731
+ height: num(values.height, 720),
6732
+ notes: (values.note ?? []).map(parseNoteFlag),
6733
+ json,
6734
+ }).catch((e) => die(e.message));
6735
+ if (values.wait && result.publicId)
6736
+ await waitForArtifacts(ctx, result.publicId).catch(() => { });
6737
+ if (json) {
6738
+ printJson({
6739
+ id: result.publicId,
6740
+ shareUrl: result.shareUrl,
6741
+ contextUrl: result.contextUrl,
6742
+ sizeBytes: result.sizeBytes,
6743
+ source: result.source,
6744
+ ...(result.windowCapture ? { windowCapture: result.windowCapture } : {}),
6745
+ });
6746
+ }
6747
+ else {
6748
+ process.stdout.write(`${c.green("✓")} recorded: ${c.bold(result.shareUrl)}\n`);
6749
+ process.stdout.write(`${c.dim("next:")} clipy context ${result.publicId} · clipy wait ${result.publicId}\n`);
6750
+ }
6751
+ return;
6752
+ }
5889
6753
  if (source === "mac-screen") {
5890
6754
  const noteFlags = values.note ?? [];
5891
6755
  const forSec = num(values.for, 15);
@@ -5911,7 +6775,12 @@ async function main() {
5911
6775
  await waitForArtifacts(ctx, result.publicId).catch(() => { });
5912
6776
  }
5913
6777
  if (json) {
5914
- printJson({ id: result.publicId, shareUrl: result.shareUrl, source: result.source });
6778
+ printJson({
6779
+ id: result.publicId,
6780
+ shareUrl: result.shareUrl,
6781
+ source: result.source,
6782
+ ...(result.windowCapture ? { windowCapture: result.windowCapture } : {}),
6783
+ });
5915
6784
  }
5916
6785
  else {
5917
6786
  process.stdout.write(`${c.green("✓")} recorded — ${c.bold(result.shareUrl)}\n`);
@@ -5953,32 +6822,39 @@ async function main() {
5953
6822
  // cmdSessionStart opts. `positionalUrl` is rest[1] for `start` (session
5954
6823
  // start <url>) — `run` has no positional url, only --url.
5955
6824
  const buildStartOpts = (positionalUrl) => {
5956
- const source = String(values.source ?? "web");
5957
- if (source !== "web" && source !== "mac-screen" && source !== "chrome-for-clipy" && source !== "chrome-extension") {
5958
- die("--source must be web (headless browser), mac-screen (the Clipy Mac app), chrome-for-clipy (the persistent automation browser), or chrome-extension (the Clipy extension inside Chrome for Clipy)", 2);
6825
+ const source = normalizeScreenSource(String(values.source ?? "web"));
6826
+ if (source !== "web" && !isScreenSource(source) && source !== "chrome-for-clipy" && source !== "chrome-extension") {
6827
+ die("--source must be web (headless browser), screen (the real screen: the Clipy Mac app on macOS, the CLI's own recorder on Linux), chrome-for-clipy (the persistent automation browser), or chrome-extension (the Clipy extension inside Chrome for Clipy)", 2);
5959
6828
  }
5960
- if ((values.window || values.display) && source !== "mac-screen") {
5961
- die("--window/--display record the real screen — add --source mac-screen", 2);
6829
+ if ((values.window || values.display) && !isScreenSource(source)) {
6830
+ die("--window/--display record the real screen: add --source screen", 2);
5962
6831
  }
5963
6832
  if (values.window && values.display) {
5964
6833
  die("--window and --display are mutually exclusive — pick one capture source", 2);
5965
6834
  }
5966
- if (source === "mac-screen" && authFlagsPresent)
6835
+ if ((values["x-display"] || values["virtual-display"]) && source !== "linux-screen") {
6836
+ die("--x-display/--virtual-display apply to --source screen on Linux", 2);
6837
+ }
6838
+ if (isScreenSource(source) && authFlagsPresent)
5967
6839
  die(macAuthGuard, 2);
6840
+ if (source === "linux-screen" && audioFlagsPresent)
6841
+ die(linuxAudioGuard, 2);
5968
6842
  if ((source === "chrome-for-clipy" || source === "chrome-extension") && authFlagsPresent) {
5969
6843
  die(`auth-capture flags don't apply to --source ${source}; sign into the Chrome for Clipy profile once (clipy chrome setup) and it stays signed in`, 2);
5970
6844
  }
5971
- if (source !== "mac-screen" && audioFlagsPresent)
6845
+ if (!isScreenSource(source) && audioFlagsPresent)
5972
6846
  die(webAudioGuard, 2);
5973
6847
  if (values["tab-audio"] && source !== "chrome-extension") {
5974
6848
  die("--tab-audio applies to --source chrome-extension only", 2);
5975
6849
  }
5976
6850
  const url = values.url?.trim() || positionalUrl;
5977
- if (!url && source !== "mac-screen") {
5978
- die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen|chrome-for-clipy|chrome-extension]", 2);
6851
+ if (!url && !isScreenSource(source)) {
6852
+ die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|screen|chrome-for-clipy|chrome-extension]", 2);
5979
6853
  }
5980
6854
  return {
5981
- url: url || "mac-screen",
6855
+ url: url || source,
6856
+ xDisplay: values["x-display"]?.trim() || undefined,
6857
+ virtualDisplay: Boolean(values["virtual-display"]),
5982
6858
  window: values.window?.trim() || undefined,
5983
6859
  display: values.display?.trim() || undefined,
5984
6860
  name: (values.title ?? values.name)?.trim() ||
@@ -5991,6 +6867,8 @@ async function main() {
5991
6867
  json,
5992
6868
  source: source,
5993
6869
  exposeCdp: Boolean(values["expose-cdp"]),
6870
+ diagnostics: diagnosticsLevel(),
6871
+ networkDetail: Boolean(values["network-detail"]),
5994
6872
  auth: authCapture(),
5995
6873
  userDataDir: userDataDir(),
5996
6874
  profileDirectory: profileDirectory(),