@clipy/cli 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -3
- package/dist/cdpClient.js +277 -0
- package/dist/cdpDiagnostics.js +644 -0
- package/dist/chromeExtensionCapture.js +197 -56
- package/dist/chromeForClipy.js +588 -111
- package/dist/index.js +1187 -125
- package/dist/linuxScreen.js +655 -0
- package/dist/macBridge.js +11 -1
- package/dist/processProbe.js +265 -0
- package/dist/skill.js +55 -21
- package/package.json +4 -4
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,9 +26,10 @@ 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 { ExtensionRecordingEndedError, abortExtensionRecording, extensionReadiness, extensionRecordingStatus, extensionStoreUrl, startExtensionRecording, stopExtensionRecording, } from "./chromeExtensionCapture.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";
|
|
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";
|
|
34
35
|
import { cmdContextImport } from "./context/importCmd.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
|
|
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
|
|
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
|
|
@@ -426,15 +444,18 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
|
|
|
426
444
|
published there, so drivers attach to the same
|
|
427
445
|
browser being recorded. --source chrome-extension
|
|
428
446
|
records the same way through the Clipy extension
|
|
429
|
-
installed there (
|
|
447
|
+
installed there (marks become its transcript); run
|
|
430
448
|
clipy chrome setup once first
|
|
431
449
|
session run [start flags] -- <command …>
|
|
432
450
|
Start a session, run the command (inherited
|
|
433
451
|
stdio), then GUARANTEE cleanup: exit 0 uploads,
|
|
434
452
|
any non-zero exit or signal discards and
|
|
435
453
|
propagates the code. Sets CLIPY_SESSION=1 (+
|
|
436
|
-
CLIPY_CDP_URL with --expose-cdp
|
|
437
|
-
|
|
454
|
+
CLIPY_CDP_URL with --expose-cdp; with
|
|
455
|
+
--source chrome-extension also
|
|
456
|
+
CLIPY_TARGET_ID and CLIPY_PAGE_WS_URL for the
|
|
457
|
+
recorded tab). Crash-safe
|
|
458
|
+
wrapper for driver scripts: no dead-air uploads.
|
|
438
459
|
mark "<what just happened>" Drop a live timestamped note; marks become the
|
|
439
460
|
recording's transcript. Attach evidence — one
|
|
440
461
|
provenance per mark, never pooled:
|
|
@@ -472,7 +493,7 @@ ${c.bold("AGENTS")}
|
|
|
472
493
|
first-run one. Use ${c.bold("setup")} unless you deliberately
|
|
473
494
|
want just the skill file
|
|
474
495
|
agents status | uninstall <t> Show / remove installed skills
|
|
475
|
-
chrome <setup|start|stop|status|install-app> [--port <n>]
|
|
496
|
+
chrome <setup|start|stop|status|install-app> [--port <n>] [--foreground]
|
|
476
497
|
"Chrome for Clipy": a dedicated, persistent
|
|
477
498
|
automation browser with CDP exposed, picker-free
|
|
478
499
|
tab capture (retitle a tab with the marker), and
|
|
@@ -1202,6 +1223,39 @@ async function doctorPlaywrightCheck() {
|
|
|
1202
1223
|
data: { installMode: mode },
|
|
1203
1224
|
};
|
|
1204
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
|
+
}
|
|
1205
1259
|
// --- context prerequisites -------------------------------------------------
|
|
1206
1260
|
// `clipy context import` needs yt-dlp (YouTube resolution) and ffmpeg/ffprobe
|
|
1207
1261
|
// (probing + frame extraction), and both fail LATE — after the user has already
|
|
@@ -1411,14 +1465,82 @@ function doctorGlyph(status) {
|
|
|
1411
1465
|
return c.dim("INFO");
|
|
1412
1466
|
}
|
|
1413
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
|
+
}
|
|
1414
1534
|
async function cmdDoctor(ctx, json) {
|
|
1415
1535
|
const checks = [
|
|
1416
1536
|
await doctorApiCheck(ctx),
|
|
1417
1537
|
await doctorAuthCheck(ctx),
|
|
1418
1538
|
...(await doctorBridgeChecks()),
|
|
1419
1539
|
await doctorPlaywrightCheck(),
|
|
1540
|
+
doctorChromeCheck(),
|
|
1420
1541
|
await doctorYtDlpCheck(),
|
|
1421
1542
|
...(await doctorFfmpegChecks()),
|
|
1543
|
+
...doctorLinuxScreenChecks(),
|
|
1422
1544
|
doctorInstallCheck(),
|
|
1423
1545
|
];
|
|
1424
1546
|
const failed = checks.filter((chk) => chk.status === "fail").length;
|
|
@@ -1961,6 +2083,23 @@ async function uploadVideoToClipy(ctx, opts) {
|
|
|
1961
2083
|
: {}),
|
|
1962
2084
|
});
|
|
1963
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
|
+
}
|
|
1964
2103
|
}
|
|
1965
2104
|
catch (e) {
|
|
1966
2105
|
// Best-effort: release the half-uploaded streaming session so it doesn't
|
|
@@ -2757,6 +2896,43 @@ function writeSessionState(file, state) {
|
|
|
2757
2896
|
}
|
|
2758
2897
|
renameSync(tmp, file);
|
|
2759
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
|
+
}
|
|
2760
2936
|
function pidAlive(pid) {
|
|
2761
2937
|
// kill(0, 0) signals our own process group and "succeeds".
|
|
2762
2938
|
if (!Number.isInteger(pid) || pid <= 0)
|
|
@@ -2773,7 +2949,81 @@ function sessionIsActive(state) {
|
|
|
2773
2949
|
return (["starting", "recording", "stopping", "uploading"].includes(state.state) &&
|
|
2774
2950
|
pidAlive(state.pid));
|
|
2775
2951
|
}
|
|
2776
|
-
|
|
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
|
+
}
|
|
2777
3027
|
for (const p of [state.marksPath, state.controlPath, file]) {
|
|
2778
3028
|
try {
|
|
2779
3029
|
rmSync(p, { force: true });
|
|
@@ -2782,6 +3032,23 @@ function cleanupSessionFiles(state, file) {
|
|
|
2782
3032
|
// best-effort
|
|
2783
3033
|
}
|
|
2784
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);
|
|
2785
3052
|
}
|
|
2786
3053
|
/** Annotation for a mark Clipy itself evaluated against its own live page. */
|
|
2787
3054
|
function verifiedMarkAnnotation(passed, expected, observed) {
|
|
@@ -2926,6 +3193,347 @@ async function evaluateAssertion(page, assert) {
|
|
|
2926
3193
|
}
|
|
2927
3194
|
return { passed, observed: observed.join("; "), expected: expected.join("; ") };
|
|
2928
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
|
+
}
|
|
2929
3537
|
// --- Mac bridge flows (--source mac-screen): the desktop app records -------
|
|
2930
3538
|
/** Resolves --window/--display to a bridge capture source (null = app default,
|
|
2931
3539
|
* i.e. the full primary display). die()s with the candidate list on no/ambiguous
|
|
@@ -2976,6 +3584,37 @@ function echoedAudio(startResult) {
|
|
|
2976
3584
|
* below this, the app silently ignores the field and records with ITS defaults.
|
|
2977
3585
|
*/
|
|
2978
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
|
+
}
|
|
2979
3618
|
/**
|
|
2980
3619
|
* Warn BEFORE `start` when the running app can't honour the audio request.
|
|
2981
3620
|
* The timing is the entire point. The echo check below can only report what
|
|
@@ -3052,6 +3691,7 @@ async function cmdRecordMac(opts) {
|
|
|
3052
3691
|
// Deliberately NOT `log`: a "your mic may be live" warning must survive
|
|
3053
3692
|
// --json, and stderr never corrupts the JSON on stdout.
|
|
3054
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`));
|
|
3055
3695
|
const notes = resolveNarrationNotes(opts.notes, [0]);
|
|
3056
3696
|
const startResult = await bridgeRequest(info, "start", {
|
|
3057
3697
|
// Explicit, never implicit: an absent field would fall through to the app's
|
|
@@ -3067,6 +3707,7 @@ async function cmdRecordMac(opts) {
|
|
|
3067
3707
|
...(target ? { source: target.source } : {}),
|
|
3068
3708
|
});
|
|
3069
3709
|
const appliedAudio = reportAudio(opts.audio, echoedAudio(startResult), log, audioUncontrollable);
|
|
3710
|
+
const windowCapture = appliedWindowCapture(target, startResult, (m) => process.stderr.write(`${m}\n`), windowWarned);
|
|
3070
3711
|
log(`${c.dim(`recording for ${opts.forSec}s…`)}`);
|
|
3071
3712
|
await new Promise((r) => setTimeout(r, opts.forSec * 1000));
|
|
3072
3713
|
log(`${c.dim("stopping + uploading…")}`);
|
|
@@ -3080,6 +3721,7 @@ async function cmdRecordMac(opts) {
|
|
|
3080
3721
|
// the surface — folding it in would muddy `source` and break its shape
|
|
3081
3722
|
// parity with `clipy sources --json` entries.
|
|
3082
3723
|
audio: appliedAudio,
|
|
3724
|
+
...(windowCapture ? { windowCapture } : {}),
|
|
3083
3725
|
};
|
|
3084
3726
|
}
|
|
3085
3727
|
function macSessionState(info, maxSec) {
|
|
@@ -3131,6 +3773,102 @@ function cdpDriverSnippet(cdpHttpUrl) {
|
|
|
3131
3773
|
c.dim(` resolve playwright for your script: NODE_PATH=$(clipy playwright-path) node driver.js`),
|
|
3132
3774
|
].join("\n");
|
|
3133
3775
|
}
|
|
3776
|
+
// Same limits the server enforces (lib/server/agentNarration.ts); an invalid
|
|
3777
|
+
// narration would fail the whole upload, so trim instead.
|
|
3778
|
+
const EXTENSION_MAX_NOTES = 200;
|
|
3779
|
+
const EXTENSION_MAX_NOTE_CHARS = 1_000;
|
|
3780
|
+
const EXTENSION_MAX_NOTE_START_MS = 24 * 60 * 60 * 1000;
|
|
3781
|
+
/** The session's marks as narration notes, plus the [verification] tally of
|
|
3782
|
+
* driver-attested marks stamped at the stop. */
|
|
3783
|
+
function extensionSessionNotes(state) {
|
|
3784
|
+
let lines = [];
|
|
3785
|
+
try {
|
|
3786
|
+
lines = readFileSync(state.marksPath, "utf8").split("\n").filter(Boolean);
|
|
3787
|
+
}
|
|
3788
|
+
catch {
|
|
3789
|
+
// no marks
|
|
3790
|
+
}
|
|
3791
|
+
const notes = [];
|
|
3792
|
+
for (const line of lines) {
|
|
3793
|
+
try {
|
|
3794
|
+
const m = JSON.parse(line);
|
|
3795
|
+
if (typeof m.tMs === "number" && typeof m.text === "string" && m.text.trim()) {
|
|
3796
|
+
notes.push({
|
|
3797
|
+
startMs: Math.min(EXTENSION_MAX_NOTE_START_MS, Math.max(0, Math.round(m.tMs))),
|
|
3798
|
+
text: m.text.trim().slice(0, EXTENSION_MAX_NOTE_CHARS),
|
|
3799
|
+
});
|
|
3800
|
+
}
|
|
3801
|
+
}
|
|
3802
|
+
catch {
|
|
3803
|
+
// skip a torn line
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
notes.sort((a, b) => a.startMs - b.startMs);
|
|
3807
|
+
const tally = verificationNote({
|
|
3808
|
+
clipyPassed: 0,
|
|
3809
|
+
clipyFailed: 0,
|
|
3810
|
+
clipyUnverified: 0,
|
|
3811
|
+
driverPassed: state.attestedPassed ?? 0,
|
|
3812
|
+
driverFailed: state.attestedFailed ?? 0,
|
|
3813
|
+
});
|
|
3814
|
+
const stopMs = state.recordStartEpochMs
|
|
3815
|
+
? Math.min(EXTENSION_MAX_NOTE_START_MS, Math.max(0, Date.now() - state.recordStartEpochMs))
|
|
3816
|
+
: 0;
|
|
3817
|
+
const kept = notes.slice(0, EXTENSION_MAX_NOTES - tally.length);
|
|
3818
|
+
return [...kept, ...tally.map((t) => ({ startMs: stopMs, text: t.text }))];
|
|
3819
|
+
}
|
|
3820
|
+
/** The server keeps 200 notes and stop adds one verification summary, so a
|
|
3821
|
+
* 200th mark would be dropped. Refuse it instead of reporting success. */
|
|
3822
|
+
function refuseExtensionMarkOverLimit(state, text) {
|
|
3823
|
+
if (text.length > EXTENSION_MAX_NOTE_CHARS) {
|
|
3824
|
+
die(`this mark is ${text.length} characters (including any --observed annotation); the limit is ${EXTENSION_MAX_NOTE_CHARS}. Shorten it or split it into several marks.`, 2);
|
|
3825
|
+
}
|
|
3826
|
+
let count = 0;
|
|
3827
|
+
try {
|
|
3828
|
+
count = readFileSync(state.marksPath, "utf8").split("\n").filter(Boolean).length;
|
|
3829
|
+
}
|
|
3830
|
+
catch {
|
|
3831
|
+
// no marks yet
|
|
3832
|
+
}
|
|
3833
|
+
if (count >= EXTENSION_MAX_NOTES - 1) {
|
|
3834
|
+
die(`mark limit reached: a recording keeps at most ${EXTENSION_MAX_NOTES - 1} marks. Stop this recording and start another to keep going.`);
|
|
3835
|
+
}
|
|
3836
|
+
}
|
|
3837
|
+
/** Sends the mark to the extension before the CLI records it locally. If the
|
|
3838
|
+
* extension cannot be reached the local copy still goes out at stop; if the
|
|
3839
|
+
* recording already ended on its own, the mark is refused rather than
|
|
3840
|
+
* reported as recorded. */
|
|
3841
|
+
async function forwardExtensionMark(state, tMs, text, summary) {
|
|
3842
|
+
if (!(state.extensionFeatures ?? []).includes("mark") || !state.extensionRecordingId)
|
|
3843
|
+
return;
|
|
3844
|
+
// Retried, then refused: a mark the extension never received would be lost
|
|
3845
|
+
// if the recording auto-stops before session stop sends the local copy.
|
|
3846
|
+
let sent = null;
|
|
3847
|
+
let lastError = "";
|
|
3848
|
+
for (let attempt = 1; attempt <= 3 && !sent; attempt++) {
|
|
3849
|
+
sent = await sendExtensionMark({
|
|
3850
|
+
port: extensionSessionPort(state),
|
|
3851
|
+
env: process.env,
|
|
3852
|
+
recordingId: state.extensionRecordingId,
|
|
3853
|
+
startMs: tMs,
|
|
3854
|
+
text,
|
|
3855
|
+
summary,
|
|
3856
|
+
}).catch((error) => {
|
|
3857
|
+
lastError = error instanceof Error ? error.message : String(error);
|
|
3858
|
+
return null;
|
|
3859
|
+
});
|
|
3860
|
+
if (!sent && attempt < 3)
|
|
3861
|
+
await new Promise((r) => setTimeout(r, 500 * attempt));
|
|
3862
|
+
}
|
|
3863
|
+
if (!sent) {
|
|
3864
|
+
die(`could not reach the Clipy extension to record this mark (${lastError}); it was not recorded. Check \`clipy session status\` and try again.`);
|
|
3865
|
+
}
|
|
3866
|
+
if (sent.ended) {
|
|
3867
|
+
die("the recording already ended (it reached --max and uploaded); this mark was not recorded. Run `clipy session stop` to collect it.");
|
|
3868
|
+
}
|
|
3869
|
+
if (!sent.ok)
|
|
3870
|
+
die(`the extension refused the mark: ${sent.error ?? "unknown error"}`);
|
|
3871
|
+
}
|
|
3134
3872
|
function extensionSessionPort(state) {
|
|
3135
3873
|
return state.chromePort ?? DEFAULT_CDP_PORT;
|
|
3136
3874
|
}
|
|
@@ -3157,8 +3895,8 @@ async function cmdSessionStartExtension(opts) {
|
|
|
3157
3895
|
if (opts.userDataDir) {
|
|
3158
3896
|
die("--user-data-dir doesn't apply to --source chrome-extension; it records in the persistent Chrome for Clipy profile", 2);
|
|
3159
3897
|
}
|
|
3160
|
-
if (
|
|
3161
|
-
process.stderr.write(`${c.yellow("note: --
|
|
3898
|
+
if (opts.recordingKind && !opts.json) {
|
|
3899
|
+
process.stderr.write(`${c.yellow("note: --type is not applied to --source chrome-extension recordings yet")}\n`);
|
|
3162
3900
|
}
|
|
3163
3901
|
const file = sessionFilePath(process.cwd());
|
|
3164
3902
|
const existing = readSessionState(file);
|
|
@@ -3167,18 +3905,19 @@ async function cmdSessionStartExtension(opts) {
|
|
|
3167
3905
|
`Finish it with \`clipy session stop\` or discard it with \`clipy session abort\`.`);
|
|
3168
3906
|
}
|
|
3169
3907
|
if (existing)
|
|
3170
|
-
cleanupSessionFiles(existing, file);
|
|
3171
|
-
const chromium = await loadChromium();
|
|
3908
|
+
reportKeptCapture(cleanupSessionFiles(existing, file));
|
|
3172
3909
|
const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
|
|
3173
3910
|
let started;
|
|
3174
3911
|
try {
|
|
3175
|
-
started = await startExtensionRecording(
|
|
3912
|
+
started = await startExtensionRecording({
|
|
3176
3913
|
home: homedir(),
|
|
3177
3914
|
env: process.env,
|
|
3178
3915
|
platform: process.platform,
|
|
3179
3916
|
port: DEFAULT_CDP_PORT,
|
|
3180
3917
|
targetUrl: target.href,
|
|
3181
3918
|
maxSec,
|
|
3919
|
+
name: opts.name,
|
|
3920
|
+
tabAudio: opts.tabAudio,
|
|
3182
3921
|
log: (m) => {
|
|
3183
3922
|
if (!opts.json)
|
|
3184
3923
|
process.stderr.write(`${c.dim(m)}\n`);
|
|
@@ -3188,6 +3927,9 @@ async function cmdSessionStartExtension(opts) {
|
|
|
3188
3927
|
catch (error) {
|
|
3189
3928
|
die(`could not start the extension recording: ${error instanceof Error ? error.message : String(error)}`);
|
|
3190
3929
|
}
|
|
3930
|
+
// Always on stderr, even with --json: a requested feature was dropped.
|
|
3931
|
+
for (const warning of started.warnings)
|
|
3932
|
+
process.stderr.write(`${c.yellow(`warning: ${warning}`)}\n`);
|
|
3191
3933
|
// The extension is recording from here on: record the session before
|
|
3192
3934
|
// anything else can fail, or nothing could stop or collect it.
|
|
3193
3935
|
const dir = sessionDir();
|
|
@@ -3196,6 +3938,8 @@ async function cmdSessionStartExtension(opts) {
|
|
|
3196
3938
|
kind: "chrome-extension",
|
|
3197
3939
|
chromePort: started.port,
|
|
3198
3940
|
extensionRecordingId: started.recordingId,
|
|
3941
|
+
extensionFeatures: started.features,
|
|
3942
|
+
extensionTargetId: started.targetId,
|
|
3199
3943
|
// Chrome for Clipy's pid: the session is alive only while that browser is.
|
|
3200
3944
|
pid: started.chromePid,
|
|
3201
3945
|
cwd: process.cwd(),
|
|
@@ -3206,7 +3950,7 @@ async function cmdSessionStartExtension(opts) {
|
|
|
3206
3950
|
state: "recording",
|
|
3207
3951
|
recordStartEpochMs: started.startedAtEpochMs,
|
|
3208
3952
|
cdpHttpUrl: started.cdpHttpUrl,
|
|
3209
|
-
marksPath: join(dir,
|
|
3953
|
+
marksPath: join(dir, `marks-${randomUUID()}.jsonl`),
|
|
3210
3954
|
controlPath: join(dir, "unused"),
|
|
3211
3955
|
logPath: join(dir, "unused"),
|
|
3212
3956
|
tmpDir: join(dir, "unused"),
|
|
@@ -3219,7 +3963,7 @@ async function cmdSessionStartExtension(opts) {
|
|
|
3219
3963
|
});
|
|
3220
3964
|
}
|
|
3221
3965
|
catch (error) {
|
|
3222
|
-
await abortExtensionRecording(
|
|
3966
|
+
await abortExtensionRecording({
|
|
3223
3967
|
port: started.port,
|
|
3224
3968
|
env: process.env,
|
|
3225
3969
|
recordingId: started.recordingId,
|
|
@@ -3239,11 +3983,14 @@ async function cmdSessionStartExtension(opts) {
|
|
|
3239
3983
|
extensionVersion: started.extensionVersion,
|
|
3240
3984
|
cdpUrl: cdpUrl ?? null,
|
|
3241
3985
|
cdpHttpUrl: started.cdpHttpUrl,
|
|
3986
|
+
// The recorded tab, exactly: other tabs can share its url.
|
|
3987
|
+
targetId: started.targetId,
|
|
3988
|
+
pageWsUrl: `ws://127.0.0.1:${started.port}/devtools/page/${started.targetId}`,
|
|
3242
3989
|
});
|
|
3243
3990
|
return;
|
|
3244
3991
|
}
|
|
3245
3992
|
process.stdout.write(`${c.green("✓")} the Clipy extension is recording ${c.bold(session.url)} in Chrome for Clipy (max ${maxSec}s)\n` +
|
|
3246
|
-
`${c.dim("drive that tab over CDP:")} ${started.
|
|
3993
|
+
`${c.dim("drive that tab over CDP:")} target ${started.targetId} ${c.dim(`(ws://127.0.0.1:${started.port}/devtools/page/${started.targetId})`)}\n` +
|
|
3247
3994
|
`${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
|
|
3248
3995
|
}
|
|
3249
3996
|
async function cmdSessionStart(ctx, opts) {
|
|
@@ -3251,6 +3998,10 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
3251
3998
|
await cmdSessionStartExtension(opts);
|
|
3252
3999
|
return;
|
|
3253
4000
|
}
|
|
4001
|
+
if (opts.source === "linux-screen") {
|
|
4002
|
+
await cmdSessionStartLinux(ctx, opts);
|
|
4003
|
+
return;
|
|
4004
|
+
}
|
|
3254
4005
|
if (opts.source === "mac-screen") {
|
|
3255
4006
|
const file = sessionFilePath(process.cwd());
|
|
3256
4007
|
const existing = readSessionState(file);
|
|
@@ -3267,6 +4018,7 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
3267
4018
|
}
|
|
3268
4019
|
// Before the camera turns on, not after — see warnAudioUncontrollable().
|
|
3269
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`));
|
|
3270
4022
|
const startResult = await bridgeRequest(info, "start", {
|
|
3271
4023
|
// Explicit, never implicit — see reportAudio(): an absent field falls
|
|
3272
4024
|
// through to the app's interactive defaults (mic ON) on older builds.
|
|
@@ -3279,6 +4031,7 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
3279
4031
|
});
|
|
3280
4032
|
writeSessionState(file, macSessionState(info, maxSec));
|
|
3281
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);
|
|
3282
4035
|
if (opts.json) {
|
|
3283
4036
|
printJson({
|
|
3284
4037
|
state: "recording",
|
|
@@ -3290,6 +4043,7 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
3290
4043
|
target: target?.label,
|
|
3291
4044
|
source: captureSourceResult(target?.resolved),
|
|
3292
4045
|
audio: appliedAudio,
|
|
4046
|
+
...(windowCapture ? { windowCapture } : {}),
|
|
3293
4047
|
});
|
|
3294
4048
|
return;
|
|
3295
4049
|
}
|
|
@@ -3341,7 +4095,7 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
3341
4095
|
`Finish it with \`clipy session stop\` or discard it with \`clipy session abort\`.`);
|
|
3342
4096
|
}
|
|
3343
4097
|
if (existing)
|
|
3344
|
-
cleanupSessionFiles(existing, file); // stale (daemon died) — clear
|
|
4098
|
+
reportKeptCapture(cleanupSessionFiles(existing, file)); // stale (daemon died) — clear
|
|
3345
4099
|
// --profile-directory ⇒ copy the named profile into a scratch root HERE, in the
|
|
3346
4100
|
// parent, so the user sees the loud disclosure (the daemon's stdout goes to a
|
|
3347
4101
|
// log). The daemon launches against the scratch root and removes it at stop/abort;
|
|
@@ -3367,6 +4121,8 @@ async function cmdSessionStart(ctx, opts) {
|
|
|
3367
4121
|
width: opts.width,
|
|
3368
4122
|
height: opts.height,
|
|
3369
4123
|
exposeCdp: opts.exposeCdp,
|
|
4124
|
+
diagnostics: opts.diagnostics,
|
|
4125
|
+
networkDetail: opts.networkDetail,
|
|
3370
4126
|
storageStatePath: opts.auth.storageStatePath,
|
|
3371
4127
|
initScriptPath: opts.auth.initScriptPath,
|
|
3372
4128
|
cookieSpecs: opts.auth.cookieSpecs.length ? opts.auth.cookieSpecs : undefined,
|
|
@@ -3472,7 +4228,49 @@ async function cmdMark(text, json, opts) {
|
|
|
3472
4228
|
const attest = opts.attest;
|
|
3473
4229
|
const backdated = opts.atSec != null || opts.agoSec != null;
|
|
3474
4230
|
if (state.kind === "chrome-extension") {
|
|
3475
|
-
|
|
4231
|
+
// The extension owns the page, not Clipy's daemon, so Clipy cannot evaluate
|
|
4232
|
+
// an assertion. Plain and driver-attested marks are kept here and sent with
|
|
4233
|
+
// the stop, where they become the recording's transcript.
|
|
4234
|
+
if (hasAssert) {
|
|
4235
|
+
die("Clipy-evaluated assertions need a Clipy-owned page: use --observed/--verdict to attach evidence you collected yourself", 2);
|
|
4236
|
+
}
|
|
4237
|
+
if (state.state !== "recording" || !state.recordStartEpochMs) {
|
|
4238
|
+
die(`session is ${state.state}; marks can only be added while recording`);
|
|
4239
|
+
}
|
|
4240
|
+
const nowMs = Math.max(0, Date.now() - state.recordStartEpochMs);
|
|
4241
|
+
const requestedMs = opts.atSec != null
|
|
4242
|
+
? Math.round(opts.atSec * 1000)
|
|
4243
|
+
: opts.agoSec != null
|
|
4244
|
+
? nowMs - Math.round(opts.agoSec * 1000)
|
|
4245
|
+
: nowMs;
|
|
4246
|
+
// A mark can only point inside the recording so far; the server would
|
|
4247
|
+
// reject a timestamp past 24h and fail the whole upload.
|
|
4248
|
+
const tMs = Math.min(nowMs, EXTENSION_MAX_NOTE_START_MS, Math.max(0, requestedMs));
|
|
4249
|
+
const markText = attest ? `${text.trim()} ${attestedMarkAnnotation(attest.verdict, attest.observed)}` : text.trim();
|
|
4250
|
+
refuseExtensionMarkOverLimit(state, markText);
|
|
4251
|
+
const passed = (state.attestedPassed ?? 0) + (attest?.verdict === "pass" ? 1 : 0);
|
|
4252
|
+
const failed = (state.attestedFailed ?? 0) + (attest && attest.verdict !== "pass" ? 1 : 0);
|
|
4253
|
+
// Sent with each verdict so a recording that auto-stops at --max still
|
|
4254
|
+
// ends with the tally; an explicit stop sends its own and this is unused.
|
|
4255
|
+
const summary = attest
|
|
4256
|
+
? verificationNote({ clipyPassed: 0, clipyFailed: 0, clipyUnverified: 0, driverPassed: passed, driverFailed: failed })[0]?.text
|
|
4257
|
+
: undefined;
|
|
4258
|
+
await forwardExtensionMark(state, tMs, markText, summary);
|
|
4259
|
+
appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: markText })}\n`, { mode: 0o600 });
|
|
4260
|
+
if (attest) {
|
|
4261
|
+
state.attestedPassed = passed;
|
|
4262
|
+
state.attestedFailed = failed;
|
|
4263
|
+
writeSessionState(file, state);
|
|
4264
|
+
}
|
|
4265
|
+
printMarkResult({
|
|
4266
|
+
tMs,
|
|
4267
|
+
text: markText,
|
|
4268
|
+
...(attest ? { assert: { passed: attest.verdict === "pass", observed: attest.observed, attested: true } } : {}),
|
|
4269
|
+
}, json);
|
|
4270
|
+
return;
|
|
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);
|
|
3476
4274
|
}
|
|
3477
4275
|
if (state.kind === "mac") {
|
|
3478
4276
|
// The Mac app records the real screen — there is no Clipy-owned page to probe,
|
|
@@ -3510,10 +4308,8 @@ async function cmdMark(text, json, opts) {
|
|
|
3510
4308
|
process.stdout.write(`${glyph} mark @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${macText}\n`);
|
|
3511
4309
|
return;
|
|
3512
4310
|
}
|
|
3513
|
-
if (!pidAlive(state.pid))
|
|
3514
|
-
cleanupSessionFiles(state, file);
|
|
3515
|
-
die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
|
|
3516
|
-
}
|
|
4311
|
+
if (!pidAlive(state.pid))
|
|
4312
|
+
dieSessionCleared(cleanupSessionFiles(state, file), json);
|
|
3517
4313
|
if (state.state !== "recording" || !state.recordStartEpochMs) {
|
|
3518
4314
|
die(`session is ${state.state} — marks can only be added while recording`);
|
|
3519
4315
|
}
|
|
@@ -3601,7 +4397,18 @@ async function cmdChapter(label, json) {
|
|
|
3601
4397
|
const { file, state } = requireSession();
|
|
3602
4398
|
const chapterText = `=== CHAPTER: ${label} ===`;
|
|
3603
4399
|
if (state.kind === "chrome-extension") {
|
|
3604
|
-
|
|
4400
|
+
if (state.state !== "recording" || !state.recordStartEpochMs) {
|
|
4401
|
+
die(`session is ${state.state}; chapters can only be added while recording`);
|
|
4402
|
+
}
|
|
4403
|
+
const tMs = Math.max(0, Date.now() - state.recordStartEpochMs);
|
|
4404
|
+
refuseExtensionMarkOverLimit(state, chapterText);
|
|
4405
|
+
await forwardExtensionMark(state, tMs, chapterText);
|
|
4406
|
+
appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: chapterText })}\n`, { mode: 0o600 });
|
|
4407
|
+
if (json)
|
|
4408
|
+
printJson({ tMs, label, text: chapterText });
|
|
4409
|
+
else
|
|
4410
|
+
process.stdout.write(`${c.green("✓")} chapter @ ${(tMs / 1000).toFixed(1)}s: ${label}\n`);
|
|
4411
|
+
return;
|
|
3605
4412
|
}
|
|
3606
4413
|
if (state.kind === "mac") {
|
|
3607
4414
|
const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: chapterText }).catch((e) => {
|
|
@@ -3618,10 +4425,8 @@ async function cmdChapter(label, json) {
|
|
|
3618
4425
|
process.stdout.write(`${c.green("✓")} chapter @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${label}\n`);
|
|
3619
4426
|
return;
|
|
3620
4427
|
}
|
|
3621
|
-
if (!pidAlive(state.pid))
|
|
3622
|
-
cleanupSessionFiles(state, file);
|
|
3623
|
-
die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
|
|
3624
|
-
}
|
|
4428
|
+
if (!pidAlive(state.pid))
|
|
4429
|
+
dieSessionCleared(cleanupSessionFiles(state, file), json);
|
|
3625
4430
|
if (state.state !== "recording" || !state.recordStartEpochMs) {
|
|
3626
4431
|
die(`session is ${state.state} — chapters can only be added while recording`);
|
|
3627
4432
|
}
|
|
@@ -3657,14 +4462,18 @@ async function cmdSessionStop(json) {
|
|
|
3657
4462
|
if (state.kind === "chrome-extension") {
|
|
3658
4463
|
if (!json)
|
|
3659
4464
|
process.stderr.write(`${c.dim("stopping; the extension is uploading…")}\n`);
|
|
3660
|
-
const
|
|
4465
|
+
const notes = extensionSessionNotes(state);
|
|
4466
|
+
if (notes.length && !(state.extensionFeatures ?? []).includes("narration")) {
|
|
4467
|
+
process.stderr.write(`${c.yellow(`warning: this Clipy extension build cannot receive marks; ${notes.length} mark(s) will not reach the recording. Update the extension.`)}\n`);
|
|
4468
|
+
}
|
|
3661
4469
|
let result;
|
|
3662
4470
|
try {
|
|
3663
|
-
result = await stopExtensionRecording(
|
|
4471
|
+
result = await stopExtensionRecording({
|
|
3664
4472
|
port: extensionSessionPort(state),
|
|
3665
4473
|
env: process.env,
|
|
3666
4474
|
recordingId: extensionSessionId(state),
|
|
3667
4475
|
timeoutMs: 600_000,
|
|
4476
|
+
notes,
|
|
3668
4477
|
});
|
|
3669
4478
|
}
|
|
3670
4479
|
catch (error) {
|
|
@@ -3725,10 +4534,11 @@ async function cmdSessionStop(json) {
|
|
|
3725
4534
|
cleanupSessionFiles(state, file);
|
|
3726
4535
|
return;
|
|
3727
4536
|
}
|
|
3728
|
-
cleanupSessionFiles(state, file);
|
|
4537
|
+
const keptPath = cleanupSessionFiles(state, file);
|
|
4538
|
+
const kept = keptPath ? `\nThe capture was kept at: ${keptPath}` : "";
|
|
3729
4539
|
die(state.state === "failed"
|
|
3730
|
-
? `session failed: ${state.error ?? "unknown"} (log: ${state.logPath})`
|
|
3731
|
-
:
|
|
4540
|
+
? `session failed: ${state.error ?? "unknown"} (log: ${state.logPath})${kept}`
|
|
4541
|
+
: `the session daemon is no longer running (crashed?) — session cleared.${kept}`);
|
|
3732
4542
|
}
|
|
3733
4543
|
writeFileSync(state.controlPath, JSON.stringify({ action: "stop" }));
|
|
3734
4544
|
if (!json)
|
|
@@ -3743,8 +4553,8 @@ async function cmdSessionStop(json) {
|
|
|
3743
4553
|
return;
|
|
3744
4554
|
}
|
|
3745
4555
|
if (s?.state === "failed") {
|
|
3746
|
-
const
|
|
3747
|
-
|
|
4556
|
+
const keptPath = cleanupSessionFiles(s, file);
|
|
4557
|
+
const kept = keptPath ? `\nThe capture was kept at: ${keptPath}` : "";
|
|
3748
4558
|
die(`session upload failed: ${s.error ?? "unknown"}${kept}`);
|
|
3749
4559
|
}
|
|
3750
4560
|
if (s?.state === "aborted") {
|
|
@@ -3752,8 +4562,9 @@ async function cmdSessionStop(json) {
|
|
|
3752
4562
|
die("session was aborted");
|
|
3753
4563
|
}
|
|
3754
4564
|
if (s && !pidAlive(s.pid)) {
|
|
3755
|
-
cleanupSessionFiles(s, file);
|
|
3756
|
-
|
|
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}`);
|
|
3757
4568
|
}
|
|
3758
4569
|
if (Date.now() >= deadline) {
|
|
3759
4570
|
die(`timed out waiting for the session to finish (log: ${state.logPath})`);
|
|
@@ -3778,22 +4589,37 @@ function reportSessionResult(result, json) {
|
|
|
3778
4589
|
async function cmdSessionAbort(json) {
|
|
3779
4590
|
const { file, state } = requireSession();
|
|
3780
4591
|
if (state.kind === "chrome-extension") {
|
|
3781
|
-
const chromium = await loadChromium();
|
|
3782
4592
|
let failure = null;
|
|
3783
|
-
|
|
4593
|
+
let uploaded = null;
|
|
4594
|
+
await abortExtensionRecording({
|
|
3784
4595
|
port: extensionSessionPort(state),
|
|
3785
4596
|
env: process.env,
|
|
3786
4597
|
recordingId: extensionSessionId(state),
|
|
3787
4598
|
}).catch((error) => {
|
|
3788
|
-
|
|
4599
|
+
if (error instanceof ExtensionAlreadyUploadedError)
|
|
4600
|
+
uploaded = error.message;
|
|
4601
|
+
else
|
|
4602
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
3789
4603
|
});
|
|
3790
|
-
if (
|
|
3791
|
-
//
|
|
3792
|
-
|
|
4604
|
+
if (uploaded) {
|
|
4605
|
+
// Too late to discard: keep the session so `session stop` can collect it.
|
|
4606
|
+
if (json)
|
|
4607
|
+
printJson({ state: "uploaded", error: uploaded });
|
|
4608
|
+
else
|
|
4609
|
+
process.stderr.write(`${c.yellow("!")} the recording was ${uploaded}; it cannot be discarded here. Run \`clipy session stop\` to collect it, or delete it from the library.\n`);
|
|
4610
|
+
process.exitCode = 1;
|
|
4611
|
+
return;
|
|
4612
|
+
}
|
|
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}`;
|
|
3793
4619
|
if (json)
|
|
3794
|
-
printJson({ state: "recording", error:
|
|
4620
|
+
printJson({ state: "recording", error: reason });
|
|
3795
4621
|
else
|
|
3796
|
-
process.stderr.write(`${c.yellow("!")} could not reach the extension to cancel (${
|
|
4622
|
+
process.stderr.write(`${c.yellow("!")} could not reach the extension to cancel (${reason}); the session is kept, retry \`clipy session abort\`\n`);
|
|
3797
4623
|
process.exitCode = 1;
|
|
3798
4624
|
return;
|
|
3799
4625
|
}
|
|
@@ -3822,11 +4648,13 @@ async function cmdSessionAbort(json) {
|
|
|
3822
4648
|
return;
|
|
3823
4649
|
}
|
|
3824
4650
|
if (!pidAlive(state.pid)) {
|
|
3825
|
-
cleanupSessionFiles(state, file);
|
|
3826
|
-
if (!json)
|
|
4651
|
+
const keptPath = cleanupSessionFiles(state, file);
|
|
4652
|
+
if (!json) {
|
|
3827
4653
|
process.stdout.write(`${c.green("✓")} stale session cleared (daemon was not running)\n`);
|
|
4654
|
+
reportKeptCapture(keptPath);
|
|
4655
|
+
}
|
|
3828
4656
|
else
|
|
3829
|
-
printJson({ state: "cleared" });
|
|
4657
|
+
printJson(keptPath ? { state: "cleared", keptVideoPath: keptPath } : { state: "cleared" });
|
|
3830
4658
|
return;
|
|
3831
4659
|
}
|
|
3832
4660
|
writeFileSync(state.controlPath, JSON.stringify({ action: "abort" }));
|
|
@@ -3881,21 +4709,23 @@ async function cmdSessionAbort(json) {
|
|
|
3881
4709
|
}
|
|
3882
4710
|
}
|
|
3883
4711
|
}
|
|
3884
|
-
|
|
3885
|
-
|
|
4712
|
+
const keptPath = final ? cleanupSessionFiles(final, file, { daemonKilled: wedged }) : undefined;
|
|
4713
|
+
if (!json)
|
|
4714
|
+
reportKeptCapture(keptPath);
|
|
4715
|
+
const kept = keptPath ? { keptVideoPath: keptPath } : {};
|
|
3886
4716
|
if (wedged) {
|
|
3887
4717
|
// Exit non-zero (and truthfully) — the daemon had to be force-killed, so we
|
|
3888
4718
|
// can't promise a clean discard. Use process.exitCode (not process.exit) so
|
|
3889
4719
|
// a caller like `session run` can still override with the child's code.
|
|
3890
4720
|
if (json)
|
|
3891
|
-
printJson({ state: "killed", pid: final?.pid ?? null });
|
|
4721
|
+
printJson({ state: "killed", pid: final?.pid ?? null, ...kept });
|
|
3892
4722
|
else
|
|
3893
4723
|
process.stderr.write(`${c.yellow("!")} the session daemon ignored abort for 30s and was force-killed (pid ${final?.pid}); nothing was uploaded\n`);
|
|
3894
4724
|
process.exitCode = 1;
|
|
3895
4725
|
return;
|
|
3896
4726
|
}
|
|
3897
4727
|
if (json)
|
|
3898
|
-
printJson({ state: "aborted" });
|
|
4728
|
+
printJson({ state: "aborted", ...kept });
|
|
3899
4729
|
else
|
|
3900
4730
|
process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
|
|
3901
4731
|
}
|
|
@@ -3913,8 +4743,7 @@ async function cmdSessionStatus(json) {
|
|
|
3913
4743
|
const elapsedSec = state.recordStartEpochMs ? Math.round((Date.now() - state.recordStartEpochMs) / 1000) : null;
|
|
3914
4744
|
let live;
|
|
3915
4745
|
try {
|
|
3916
|
-
|
|
3917
|
-
live = await extensionRecordingStatus(chromium, {
|
|
4746
|
+
live = await extensionRecordingStatus({
|
|
3918
4747
|
port: extensionSessionPort(state),
|
|
3919
4748
|
env: process.env,
|
|
3920
4749
|
recordingId: extensionSessionId(state),
|
|
@@ -3931,6 +4760,11 @@ async function cmdSessionStatus(json) {
|
|
|
3931
4760
|
maxSec: state.maxSec,
|
|
3932
4761
|
cdpUrl: state.cdpUrl ?? null,
|
|
3933
4762
|
cdpHttpUrl: state.cdpHttpUrl ?? null,
|
|
4763
|
+
// The recorded tab, exactly, for an agent resuming without the start output.
|
|
4764
|
+
targetId: state.extensionTargetId ?? null,
|
|
4765
|
+
pageWsUrl: state.extensionTargetId
|
|
4766
|
+
? `ws://127.0.0.1:${extensionSessionPort(state)}/devtools/page/${state.extensionTargetId}`
|
|
4767
|
+
: null,
|
|
3934
4768
|
...(live.result ? { result: live.result } : {}),
|
|
3935
4769
|
});
|
|
3936
4770
|
return;
|
|
@@ -4014,7 +4848,12 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
|
|
|
4014
4848
|
// child inherits our stdio and the deliverable is the wrapped run, not JSON.
|
|
4015
4849
|
await cmdSessionStart(ctx, { ...startOpts, json: false });
|
|
4016
4850
|
const file = sessionFilePath(process.cwd());
|
|
4017
|
-
const
|
|
4851
|
+
const started = readSessionState(file);
|
|
4852
|
+
const cdpHttpUrl = started?.cdpHttpUrl;
|
|
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;
|
|
4018
4857
|
const [cmd, ...args] = childArgv;
|
|
4019
4858
|
process.stderr.write(`${c.dim(`running: ${childArgv.join(" ")}`)}\n`);
|
|
4020
4859
|
const child = spawn(cmd, args, {
|
|
@@ -4027,6 +4866,12 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
|
|
|
4027
4866
|
CLIPY_SESSION: "1",
|
|
4028
4867
|
CLIPY_SESSION_FILE: file,
|
|
4029
4868
|
...(cdpHttpUrl ? { CLIPY_CDP_URL: cdpHttpUrl } : {}),
|
|
4869
|
+
...(xDisplay ? { DISPLAY: xDisplay, CLIPY_X_DISPLAY: xDisplay } : {}),
|
|
4870
|
+
// chrome-extension: the exact recorded tab, since other tabs in the
|
|
4871
|
+
// persistent profile can share its url.
|
|
4872
|
+
...(targetId && started?.chromePort
|
|
4873
|
+
? { CLIPY_TARGET_ID: targetId, CLIPY_PAGE_WS_URL: `ws://127.0.0.1:${started.chromePort}/devtools/page/${targetId}` }
|
|
4874
|
+
: {}),
|
|
4030
4875
|
},
|
|
4031
4876
|
});
|
|
4032
4877
|
// Forward Ctrl-C / termination to the child; its exit then drives the abort
|
|
@@ -4117,6 +4962,7 @@ async function runSessionDaemon(file) {
|
|
|
4117
4962
|
const log = (m) => process.stderr.write(`[clipy-session] ${new Date().toISOString()} ${m}\n`);
|
|
4118
4963
|
const autoMarks = [];
|
|
4119
4964
|
let recordStart = 0;
|
|
4965
|
+
let browserEvidence = null;
|
|
4120
4966
|
const autoMark = (text) => {
|
|
4121
4967
|
if (autoMarks.length >= 50 || recordStart === 0)
|
|
4122
4968
|
return;
|
|
@@ -4131,7 +4977,8 @@ async function runSessionDaemon(file) {
|
|
|
4131
4977
|
};
|
|
4132
4978
|
// A failed --fail-mode=abort assertion sets this; the main loop discards.
|
|
4133
4979
|
let controlSignal = null;
|
|
4134
|
-
|
|
4980
|
+
// Owner-only: it holds the user's screen (or page) as it is recorded.
|
|
4981
|
+
mkdirSync(state.tmpDir, { recursive: true, mode: 0o700 });
|
|
4135
4982
|
let browser = null;
|
|
4136
4983
|
// Persistent (--user-data-dir) contexts have no separate browser, so track the
|
|
4137
4984
|
// context too for the finally cleanup (an exception before stop must not leak
|
|
@@ -4139,9 +4986,12 @@ async function runSessionDaemon(file) {
|
|
|
4139
4986
|
let ctxToClose = null;
|
|
4140
4987
|
let controlServer = null;
|
|
4141
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;
|
|
4142
4993
|
try {
|
|
4143
|
-
|
|
4144
|
-
let page;
|
|
4994
|
+
let page = null;
|
|
4145
4995
|
let cdpUrl;
|
|
4146
4996
|
let cdpHttpUrl;
|
|
4147
4997
|
// Mode-specific teardown, so the shared stop/abort paths below don't care
|
|
@@ -4152,7 +5002,44 @@ async function runSessionDaemon(file) {
|
|
|
4152
5002
|
// below get installed), plus the context to install them on.
|
|
4153
5003
|
let wantCdp = false;
|
|
4154
5004
|
let bindingContext = null;
|
|
4155
|
-
if (state.kind === "
|
|
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();
|
|
4156
5043
|
const port = state.chromePort ?? DEFAULT_CDP_PORT;
|
|
4157
5044
|
log(`attaching to Chrome for Clipy on port ${port} for ${state.url}`);
|
|
4158
5045
|
const cap = await startChromeForClipyCapture(chromium, {
|
|
@@ -4163,6 +5050,17 @@ async function runSessionDaemon(file) {
|
|
|
4163
5050
|
tmpDir: state.tmpDir,
|
|
4164
5051
|
targetUrl: state.url,
|
|
4165
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
|
+
},
|
|
4166
5064
|
});
|
|
4167
5065
|
// For a CDP-connected browser, close() disconnects and leaves Chrome for
|
|
4168
5066
|
// Clipy running; it must never be killed by a session ending.
|
|
@@ -4189,6 +5087,7 @@ async function runSessionDaemon(file) {
|
|
|
4189
5087
|
};
|
|
4190
5088
|
}
|
|
4191
5089
|
else {
|
|
5090
|
+
const chromium = await loadChromium();
|
|
4192
5091
|
log(`launching chromium for ${state.url}`);
|
|
4193
5092
|
// CDP is OPT-IN (--expose-cdp) and the env kill switch wins over the flag:
|
|
4194
5093
|
// no debugging port is opened unless the user asked AND CLIPY_DISABLE_CDP
|
|
@@ -4239,9 +5138,10 @@ async function runSessionDaemon(file) {
|
|
|
4239
5138
|
log(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
|
|
4240
5139
|
}
|
|
4241
5140
|
}
|
|
5141
|
+
const recordedPage = page;
|
|
4242
5142
|
finishCapture = async () => {
|
|
4243
|
-
const video =
|
|
4244
|
-
await
|
|
5143
|
+
const video = recordedPage.video();
|
|
5144
|
+
await recordedPage.close();
|
|
4245
5145
|
await context.close();
|
|
4246
5146
|
if (!video)
|
|
4247
5147
|
throw new Error("browser did not produce a video (recordVideo unavailable)");
|
|
@@ -4254,13 +5154,28 @@ async function runSessionDaemon(file) {
|
|
|
4254
5154
|
return videoPath;
|
|
4255
5155
|
};
|
|
4256
5156
|
discardCapture = async () => {
|
|
4257
|
-
await
|
|
5157
|
+
await recordedPage.close().catch(() => { });
|
|
4258
5158
|
await context.close().catch(() => { });
|
|
4259
5159
|
};
|
|
4260
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
|
+
}
|
|
4261
5176
|
// Auto-marks: instrumentation ground truth alongside the agent's intent
|
|
4262
5177
|
// marks. Type-tagged with [auto] so the transcript distinguishes them.
|
|
4263
|
-
page
|
|
5178
|
+
page?.on("framenavigated", ((frame) => {
|
|
4264
5179
|
try {
|
|
4265
5180
|
if (frame.parentFrame() === null)
|
|
4266
5181
|
autoMark(`[auto] navigated to ${frame.url()}`);
|
|
@@ -4269,7 +5184,7 @@ async function runSessionDaemon(file) {
|
|
|
4269
5184
|
// never let instrumentation kill the recording
|
|
4270
5185
|
}
|
|
4271
5186
|
}));
|
|
4272
|
-
page
|
|
5187
|
+
page?.on("console", ((msg) => {
|
|
4273
5188
|
try {
|
|
4274
5189
|
if (msg.type() === "error") {
|
|
4275
5190
|
autoMark(`[auto] console error: ${msg.text().slice(0, 200)}`);
|
|
@@ -4305,6 +5220,9 @@ async function runSessionDaemon(file) {
|
|
|
4305
5220
|
assertOutcome = { kind: "driver", passed, expected: "", observed: m.attest.observed };
|
|
4306
5221
|
}
|
|
4307
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
|
+
}
|
|
4308
5226
|
// evaluateAssertion throws if the page is unresponsive — the HTTP path
|
|
4309
5227
|
// turns that into a 5xx (the CLI then records a ⚠ UNVERIFIED file mark),
|
|
4310
5228
|
// and the in-page path rejects to the driver.
|
|
@@ -4355,7 +5273,7 @@ async function runSessionDaemon(file) {
|
|
|
4355
5273
|
// The bindings are exposed under *Impl names and re-declared with explicit
|
|
4356
5274
|
// arity below, so an agent probing window.__clipyMark.length sees 2 (not the
|
|
4357
5275
|
// 0 an exposeBinding wrapper reports).
|
|
4358
|
-
if (wantCdp && bindingContext) {
|
|
5276
|
+
if (wantCdp && bindingContext && page) {
|
|
4359
5277
|
const bindings = page;
|
|
4360
5278
|
await bindings
|
|
4361
5279
|
.exposeBinding("__clipyMarkImpl", async (source, ...args) => {
|
|
@@ -4402,7 +5320,7 @@ async function runSessionDaemon(file) {
|
|
|
4402
5320
|
})
|
|
4403
5321
|
.catch((e) => log(`in-page binding wrappers failed: ${e.message}`));
|
|
4404
5322
|
if (state.kind === "chrome-for-clipy") {
|
|
4405
|
-
await
|
|
5323
|
+
await bindings.evaluate(() => {
|
|
4406
5324
|
const w = globalThis;
|
|
4407
5325
|
w.__clipyMark = (text, opts) => w.__clipyMarkImpl(text, opts);
|
|
4408
5326
|
w.__clipyChapter = (label) => w.__clipyChapterImpl(label);
|
|
@@ -4525,7 +5443,9 @@ async function runSessionDaemon(file) {
|
|
|
4525
5443
|
controlServer = null;
|
|
4526
5444
|
controlPort = 0;
|
|
4527
5445
|
}
|
|
4528
|
-
|
|
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();
|
|
4529
5449
|
save({
|
|
4530
5450
|
state: "recording",
|
|
4531
5451
|
recordStartEpochMs: recordStart,
|
|
@@ -4536,7 +5456,7 @@ async function runSessionDaemon(file) {
|
|
|
4536
5456
|
// chrome-for-clipy already navigated the target before capture started (the
|
|
4537
5457
|
// marker-title selection requires a loaded page); re-navigating here would
|
|
4538
5458
|
// just reload it on camera.
|
|
4539
|
-
if (state.kind !== "chrome-for-clipy") {
|
|
5459
|
+
if (page && state.kind !== "chrome-for-clipy") {
|
|
4540
5460
|
try {
|
|
4541
5461
|
await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
|
|
4542
5462
|
}
|
|
@@ -4547,7 +5467,33 @@ async function runSessionDaemon(file) {
|
|
|
4547
5467
|
// Main loop: poll the control file; enforce the max-duration rail.
|
|
4548
5468
|
let stopReason = "stop";
|
|
4549
5469
|
for (;;) {
|
|
4550
|
-
|
|
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
|
+
}
|
|
4551
5497
|
// A failed --fail-mode=abort assertion (set by the control handler) discards
|
|
4552
5498
|
// the session just like a control-file abort.
|
|
4553
5499
|
if (controlSignal === "abort") {
|
|
@@ -4592,6 +5538,16 @@ async function runSessionDaemon(file) {
|
|
|
4592
5538
|
log(`max duration ${state.maxSec}s reached — auto-stopping and uploading`);
|
|
4593
5539
|
}
|
|
4594
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
|
+
}
|
|
4595
5551
|
const videoPath = await finishCapture();
|
|
4596
5552
|
discardCapture = null;
|
|
4597
5553
|
// Merge marks. The FILE is the mark of record: `clipy mark` writes there when
|
|
@@ -4697,23 +5653,28 @@ async function runSessionDaemon(file) {
|
|
|
4697
5653
|
log(`mark limit: merged ${notes.length} marks — keeping the first 200 (dropped ${notes.length - 200})`);
|
|
4698
5654
|
notes = notes.slice(0, 200);
|
|
4699
5655
|
}
|
|
4700
|
-
save({ state: "uploading" });
|
|
5656
|
+
save({ state: "uploading", videoPath });
|
|
4701
5657
|
const uploaded = await uploadVideoToClipy(ctx, {
|
|
4702
5658
|
videoPath,
|
|
4703
5659
|
name: state.name,
|
|
4704
5660
|
description: state.description,
|
|
4705
5661
|
recordingKind: state.recordingKind,
|
|
4706
5662
|
narration: notes.length ? { notes } : undefined,
|
|
5663
|
+
browserDiagnostics: diagnosticsSidecar,
|
|
4707
5664
|
log: (m) => log(m.replace(/\x1b\[[0-9;]*m/g, "")),
|
|
4708
5665
|
}).catch((e) => {
|
|
4709
5666
|
// Keep the capture — losing the bytes is worse than leaving a file.
|
|
4710
|
-
const kept = join(sessionDir(), `kept-${randomUUID()}.webm`);
|
|
5667
|
+
const kept = join(sessionDir(), `kept-${randomUUID()}${extname(videoPath) || ".webm"}`);
|
|
4711
5668
|
try {
|
|
4712
|
-
|
|
5669
|
+
moveFile(videoPath, kept);
|
|
4713
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 });
|
|
4714
5673
|
}
|
|
4715
5674
|
catch {
|
|
4716
|
-
//
|
|
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 });
|
|
4717
5678
|
}
|
|
4718
5679
|
throw e;
|
|
4719
5680
|
});
|
|
@@ -4743,6 +5704,10 @@ async function runSessionDaemon(file) {
|
|
|
4743
5704
|
await ctxToClose.close().catch(() => { });
|
|
4744
5705
|
if (browser)
|
|
4745
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(() => { });
|
|
4746
5711
|
// Remove the copied-profile scratch root (a SIGKILL strands it → the 24h
|
|
4747
5712
|
// sweep at the next record/session start catches that).
|
|
4748
5713
|
if (state.profileScratchRoot) {
|
|
@@ -4908,18 +5873,18 @@ async function cmdSetup(ctx, targetRaw, json, withBrowser) {
|
|
|
4908
5873
|
// ---------------------------------------------------------------------------
|
|
4909
5874
|
// chrome: the dedicated "Chrome for Clipy" automation browser.
|
|
4910
5875
|
// ---------------------------------------------------------------------------
|
|
4911
|
-
async function cmdChrome(sub, json, portRaw) {
|
|
5876
|
+
async function cmdChrome(sub, json, portRaw, foreground = false) {
|
|
4912
5877
|
const home = homedir();
|
|
4913
5878
|
const port = portRaw ? Number(portRaw) : DEFAULT_CDP_PORT;
|
|
4914
5879
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
4915
|
-
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);
|
|
4916
5881
|
}
|
|
4917
5882
|
switch (sub) {
|
|
4918
5883
|
case "setup":
|
|
4919
5884
|
await cmdChromeSetup(home, port, json);
|
|
4920
5885
|
return;
|
|
4921
5886
|
case "start": {
|
|
4922
|
-
const result = await startChromeForClipy(home, process.env, process.platform, port);
|
|
5887
|
+
const result = await startChromeForClipy(home, process.env, process.platform, port, { foreground });
|
|
4923
5888
|
if (!result.ok) {
|
|
4924
5889
|
if (json)
|
|
4925
5890
|
printJson({ ok: false, error: result.error });
|
|
@@ -4939,7 +5904,7 @@ async function cmdChrome(sub, json, portRaw) {
|
|
|
4939
5904
|
return;
|
|
4940
5905
|
}
|
|
4941
5906
|
case "stop": {
|
|
4942
|
-
const result = stopChromeForClipy(home);
|
|
5907
|
+
const result = await stopChromeForClipy(home);
|
|
4943
5908
|
if (json)
|
|
4944
5909
|
printJson({ ok: result.ok, stopped: result.stopped, ...(result.error ? { error: result.error } : {}) });
|
|
4945
5910
|
else if (!result.ok)
|
|
@@ -4958,11 +5923,23 @@ async function cmdChrome(sub, json, portRaw) {
|
|
|
4958
5923
|
}
|
|
4959
5924
|
process.stdout.write(status.running
|
|
4960
5925
|
? `running (pid ${status.pid}), CDP ${status.cdpUrl} (${status.cdpReady ? (status.browser ?? "ready") : "not answering"})\n`
|
|
4961
|
-
: "not running\n");
|
|
4962
|
-
process.stdout.write(`profile: ${status.profileDir}\
|
|
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`);
|
|
4963
5930
|
return;
|
|
4964
5931
|
}
|
|
4965
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
|
+
}
|
|
4966
5943
|
const result = installChromeForClipyApp(home, process.env, process.platform, port);
|
|
4967
5944
|
if (!result.ok) {
|
|
4968
5945
|
if (json)
|
|
@@ -4979,7 +5956,7 @@ async function cmdChrome(sub, json, portRaw) {
|
|
|
4979
5956
|
return;
|
|
4980
5957
|
}
|
|
4981
5958
|
default:
|
|
4982
|
-
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);
|
|
4983
5960
|
}
|
|
4984
5961
|
}
|
|
4985
5962
|
const CHROME_SETUP_TIMEOUT_MS = 15 * 60_000;
|
|
@@ -4993,6 +5970,11 @@ async function cmdChromeSetup(home, port, json) {
|
|
|
4993
5970
|
if (!json)
|
|
4994
5971
|
process.stdout.write(`${m}\n`);
|
|
4995
5972
|
};
|
|
5973
|
+
// What the person must do. On stderr with --json, so an agent waiting on
|
|
5974
|
+
// setup can relay it while stdout stays one JSON object.
|
|
5975
|
+
const ask = (m) => {
|
|
5976
|
+
(json ? process.stderr : process.stdout).write(`${m}\n`);
|
|
5977
|
+
};
|
|
4996
5978
|
const fail = (error) => {
|
|
4997
5979
|
if (json)
|
|
4998
5980
|
printJson({ ok: false, error });
|
|
@@ -5007,26 +5989,16 @@ async function cmdChromeSetup(home, port, json) {
|
|
|
5007
5989
|
if (app.ok)
|
|
5008
5990
|
say(`updated the "${CHROME_FOR_CLIPY_APP_NAME}" launcher at ${app.path}`);
|
|
5009
5991
|
}
|
|
5010
|
-
|
|
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 });
|
|
5011
5994
|
if (!started.ok)
|
|
5012
5995
|
fail(started.error);
|
|
5013
|
-
const
|
|
5014
|
-
const openTab = async (url) => {
|
|
5015
|
-
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
|
|
5016
|
-
try {
|
|
5017
|
-
const page = await browser.contexts()[0]?.newPage();
|
|
5018
|
-
await page?.goto(url, { waitUntil: "load", timeout: 30_000 }).catch(() => { });
|
|
5019
|
-
await page?.bringToFront().catch(() => { });
|
|
5020
|
-
}
|
|
5021
|
-
finally {
|
|
5022
|
-
await browser.close().catch(() => { });
|
|
5023
|
-
}
|
|
5024
|
-
};
|
|
5996
|
+
const openTab = (url) => openTabForPerson(port, url).catch(() => { });
|
|
5025
5997
|
const deadline = Date.now() + CHROME_SETUP_TIMEOUT_MS;
|
|
5026
5998
|
let askedInstall = false;
|
|
5027
5999
|
let askedSignIn = false;
|
|
5028
6000
|
for (;;) {
|
|
5029
|
-
const ready = await extensionReadiness(
|
|
6001
|
+
const ready = await extensionReadiness(port, process.env);
|
|
5030
6002
|
if (ready.installed && ready.error)
|
|
5031
6003
|
fail(ready.error);
|
|
5032
6004
|
if (ready.installed && ready.signedIn) {
|
|
@@ -5043,12 +6015,12 @@ async function cmdChromeSetup(home, port, json) {
|
|
|
5043
6015
|
if (!ready.installed && !askedInstall) {
|
|
5044
6016
|
askedInstall = true;
|
|
5045
6017
|
await openTab(extensionStoreUrl(process.env));
|
|
5046
|
-
|
|
6018
|
+
ask(`→ In the ${CHROME_FOR_CLIPY_APP_NAME} window, click "Add to Chrome" on the Clipy extension page. Waiting…`);
|
|
5047
6019
|
}
|
|
5048
6020
|
else if (ready.installed && !ready.signedIn && !askedSignIn) {
|
|
5049
6021
|
askedSignIn = true;
|
|
5050
6022
|
await openTab("https://clipy.online/?signin=1&signup_flow=extension");
|
|
5051
|
-
|
|
6023
|
+
ask(`→ Sign in to Clipy in the ${CHROME_FOR_CLIPY_APP_NAME} window. Waiting…`);
|
|
5052
6024
|
}
|
|
5053
6025
|
if (Date.now() >= deadline) {
|
|
5054
6026
|
fail(ready.installed ? "timed out waiting for sign-in" : "timed out waiting for the Clipy extension to be installed");
|
|
@@ -5133,7 +6105,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
|
|
|
5133
6105
|
// command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
|
|
5134
6106
|
// contract changes.
|
|
5135
6107
|
// ---------------------------------------------------------------------------
|
|
5136
|
-
const GUIDE_SCHEMA_VERSION =
|
|
6108
|
+
const GUIDE_SCHEMA_VERSION = 17;
|
|
5137
6109
|
/** The stable machine-readable failure taxonomy carried in `--json` error
|
|
5138
6110
|
* envelopes. Codes are the contract; messages are not. Published through the
|
|
5139
6111
|
* guide so an agent discovers the full recovery table without the skill. */
|
|
@@ -5219,16 +6191,16 @@ function cmdGuide(json) {
|
|
|
5219
6191
|
cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
|
|
5220
6192
|
cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
|
|
5221
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"]),
|
|
5222
|
-
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;
|
|
5223
|
-
cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|
|
|
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"]),
|
|
5224
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"]),
|
|
5225
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"]),
|
|
5226
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"]),
|
|
5227
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"]),
|
|
5228
|
-
cmdDoc("sources", "clipy sources [--json]", "List displays + windows the Clipy Mac app
|
|
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."),
|
|
5229
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"]),
|
|
5230
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)"),
|
|
5231
|
-
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"]),
|
|
5232
6204
|
cmdDoc("guide", "clipy guide --json", "This manifest"),
|
|
5233
6205
|
cmdDoc("mcp", "clipy mcp", "Run the Clipy MCP server (wraps npx -y @clipy/mcp)"),
|
|
5234
6206
|
],
|
|
@@ -5240,8 +6212,9 @@ function cmdGuide(json) {
|
|
|
5240
6212
|
"Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
|
|
5241
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.",
|
|
5242
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.",
|
|
5243
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.",
|
|
5244
|
-
"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
|
|
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.",
|
|
5245
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.",
|
|
5246
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.",
|
|
5247
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).",
|
|
@@ -5338,6 +6311,7 @@ async function main() {
|
|
|
5338
6311
|
"no-browser": { type: "boolean", default: false },
|
|
5339
6312
|
"with-browser": { type: "boolean", default: false },
|
|
5340
6313
|
port: { type: "string" },
|
|
6314
|
+
foreground: { type: "boolean", default: false },
|
|
5341
6315
|
"api-url": { type: "string" },
|
|
5342
6316
|
status: { type: "string" },
|
|
5343
6317
|
page: { type: "string" },
|
|
@@ -5348,6 +6322,9 @@ async function main() {
|
|
|
5348
6322
|
"marks-only": { type: "boolean", default: false },
|
|
5349
6323
|
mic: { type: "boolean", default: false },
|
|
5350
6324
|
"no-system-audio": { type: "boolean", default: false },
|
|
6325
|
+
"tab-audio": { type: "boolean", default: false },
|
|
6326
|
+
diagnostics: { type: "string" },
|
|
6327
|
+
"network-detail": { type: "boolean", default: false },
|
|
5351
6328
|
vtt: { type: "boolean", default: false },
|
|
5352
6329
|
for: { type: "string" },
|
|
5353
6330
|
timeout: { type: "string" },
|
|
@@ -5376,6 +6353,8 @@ async function main() {
|
|
|
5376
6353
|
source: { type: "string" },
|
|
5377
6354
|
window: { type: "string" },
|
|
5378
6355
|
display: { type: "string" },
|
|
6356
|
+
"x-display": { type: "string" },
|
|
6357
|
+
"virtual-display": { type: "boolean", default: false },
|
|
5379
6358
|
type: { type: "string" },
|
|
5380
6359
|
"assert-selector": { type: "string" },
|
|
5381
6360
|
"assert-text": { type: "string" },
|
|
@@ -5468,7 +6447,19 @@ async function main() {
|
|
|
5468
6447
|
includeSystemAudio: !values["no-system-audio"],
|
|
5469
6448
|
includeMic: Boolean(values.mic),
|
|
5470
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
|
+
};
|
|
5471
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";
|
|
5472
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";
|
|
5473
6464
|
switch (command) {
|
|
5474
6465
|
case "login":
|
|
@@ -5628,7 +6619,7 @@ async function main() {
|
|
|
5628
6619
|
await cmdSetup(ctx, rest[0], json, values["with-browser"] === true);
|
|
5629
6620
|
return;
|
|
5630
6621
|
case "chrome":
|
|
5631
|
-
await cmdChrome(rest[0], json, values.port);
|
|
6622
|
+
await cmdChrome(rest[0], json, values.port, values.foreground === true);
|
|
5632
6623
|
return;
|
|
5633
6624
|
case "agents":
|
|
5634
6625
|
await cmdAgents(ctx, rest[0], rest[1], json);
|
|
@@ -5637,6 +6628,17 @@ async function main() {
|
|
|
5637
6628
|
cmdGuide(json);
|
|
5638
6629
|
return;
|
|
5639
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);
|
|
5640
6642
|
// Enumerate what the Mac app can capture, so --window/--display have ids.
|
|
5641
6643
|
try {
|
|
5642
6644
|
const sources = await listSources(readBridgeInfo());
|
|
@@ -5691,21 +6693,63 @@ async function main() {
|
|
|
5691
6693
|
return;
|
|
5692
6694
|
}
|
|
5693
6695
|
case "record": {
|
|
5694
|
-
const source = String(values.source ?? "web");
|
|
5695
|
-
if (source !== "web" && source
|
|
5696
|
-
die("--source must be web (headless browser) or
|
|
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);
|
|
5697
6699
|
}
|
|
5698
|
-
if ((values.window || values.display) && source
|
|
5699
|
-
die("--window/--display record the real screen
|
|
6700
|
+
if ((values.window || values.display) && !isScreenSource(source)) {
|
|
6701
|
+
die("--window/--display record the real screen: add --source screen", 2);
|
|
5700
6702
|
}
|
|
5701
6703
|
if (values.window && values.display) {
|
|
5702
6704
|
die("--window and --display are mutually exclusive — pick one capture source", 2);
|
|
5703
6705
|
}
|
|
5704
|
-
if (
|
|
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)
|
|
5705
6710
|
die(macAuthGuard, 2);
|
|
5706
|
-
if (source
|
|
6711
|
+
if (source === "linux-screen" && audioFlagsPresent)
|
|
6712
|
+
die(linuxAudioGuard, 2);
|
|
6713
|
+
if (source === "web" && audioFlagsPresent)
|
|
5707
6714
|
die(webAudioGuard, 2);
|
|
5708
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
|
+
}
|
|
5709
6753
|
if (source === "mac-screen") {
|
|
5710
6754
|
const noteFlags = values.note ?? [];
|
|
5711
6755
|
const forSec = num(values.for, 15);
|
|
@@ -5731,7 +6775,12 @@ async function main() {
|
|
|
5731
6775
|
await waitForArtifacts(ctx, result.publicId).catch(() => { });
|
|
5732
6776
|
}
|
|
5733
6777
|
if (json) {
|
|
5734
|
-
printJson({
|
|
6778
|
+
printJson({
|
|
6779
|
+
id: result.publicId,
|
|
6780
|
+
shareUrl: result.shareUrl,
|
|
6781
|
+
source: result.source,
|
|
6782
|
+
...(result.windowCapture ? { windowCapture: result.windowCapture } : {}),
|
|
6783
|
+
});
|
|
5735
6784
|
}
|
|
5736
6785
|
else {
|
|
5737
6786
|
process.stdout.write(`${c.green("✓")} recorded — ${c.bold(result.shareUrl)}\n`);
|
|
@@ -5773,29 +6822,39 @@ async function main() {
|
|
|
5773
6822
|
// cmdSessionStart opts. `positionalUrl` is rest[1] for `start` (session
|
|
5774
6823
|
// start <url>) — `run` has no positional url, only --url.
|
|
5775
6824
|
const buildStartOpts = (positionalUrl) => {
|
|
5776
|
-
const source = String(values.source ?? "web");
|
|
5777
|
-
if (source !== "web" && source
|
|
5778
|
-
die("--source must be web (headless browser),
|
|
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);
|
|
5779
6828
|
}
|
|
5780
|
-
if ((values.window || values.display) && source
|
|
5781
|
-
die("--window/--display record the real screen
|
|
6829
|
+
if ((values.window || values.display) && !isScreenSource(source)) {
|
|
6830
|
+
die("--window/--display record the real screen: add --source screen", 2);
|
|
5782
6831
|
}
|
|
5783
6832
|
if (values.window && values.display) {
|
|
5784
6833
|
die("--window and --display are mutually exclusive — pick one capture source", 2);
|
|
5785
6834
|
}
|
|
5786
|
-
if (
|
|
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)
|
|
5787
6839
|
die(macAuthGuard, 2);
|
|
6840
|
+
if (source === "linux-screen" && audioFlagsPresent)
|
|
6841
|
+
die(linuxAudioGuard, 2);
|
|
5788
6842
|
if ((source === "chrome-for-clipy" || source === "chrome-extension") && authFlagsPresent) {
|
|
5789
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);
|
|
5790
6844
|
}
|
|
5791
|
-
if (source
|
|
6845
|
+
if (!isScreenSource(source) && audioFlagsPresent)
|
|
5792
6846
|
die(webAudioGuard, 2);
|
|
6847
|
+
if (values["tab-audio"] && source !== "chrome-extension") {
|
|
6848
|
+
die("--tab-audio applies to --source chrome-extension only", 2);
|
|
6849
|
+
}
|
|
5793
6850
|
const url = values.url?.trim() || positionalUrl;
|
|
5794
|
-
if (!url && source
|
|
5795
|
-
die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|
|
|
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);
|
|
5796
6853
|
}
|
|
5797
6854
|
return {
|
|
5798
|
-
url: url ||
|
|
6855
|
+
url: url || source,
|
|
6856
|
+
xDisplay: values["x-display"]?.trim() || undefined,
|
|
6857
|
+
virtualDisplay: Boolean(values["virtual-display"]),
|
|
5799
6858
|
window: values.window?.trim() || undefined,
|
|
5800
6859
|
display: values.display?.trim() || undefined,
|
|
5801
6860
|
name: (values.title ?? values.name)?.trim() ||
|
|
@@ -5808,10 +6867,13 @@ async function main() {
|
|
|
5808
6867
|
json,
|
|
5809
6868
|
source: source,
|
|
5810
6869
|
exposeCdp: Boolean(values["expose-cdp"]),
|
|
6870
|
+
diagnostics: diagnosticsLevel(),
|
|
6871
|
+
networkDetail: Boolean(values["network-detail"]),
|
|
5811
6872
|
auth: authCapture(),
|
|
5812
6873
|
userDataDir: userDataDir(),
|
|
5813
6874
|
profileDirectory: profileDirectory(),
|
|
5814
6875
|
audio: audioChoice(),
|
|
6876
|
+
tabAudio: Boolean(values["tab-audio"]),
|
|
5815
6877
|
};
|
|
5816
6878
|
};
|
|
5817
6879
|
if (sub === "start") {
|