@clipy/cli 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@
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, createWriteStream, mkdirSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
16
+ import { appendFileSync, closeSync, createWriteStream, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
17
17
  import { homedir, tmpdir } from "node:os";
18
18
  import { dirname, join, resolve } from "node:path";
19
19
  import { createInterface } from "node:readline";
@@ -24,6 +24,7 @@ import { pipeline } from "node:stream/promises";
24
24
  import { createRequire } from "node:module";
25
25
  import { pathToFileURL } from "node:url";
26
26
  import { createServer } from "node:net";
27
+ import { createServer as createHttpServer } from "node:http";
27
28
  import { CLIPY_SKILL_MD } from "./skill.js";
28
29
  import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
29
30
  import { BridgeUnavailableError, bridgeRequest, inspectBridge, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, probeSocketOpenable, probeBridgeHandshake, bridgeInfoFromFile, bridgeAppOutdated, MIN_BRIDGE_APP_VERSION, } from "./macBridge.js";
@@ -306,6 +307,13 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
306
307
  notes become the transcript
307
308
  --width/--height Viewport + video size (default 1280×720)
308
309
  --wait Block until the transcript is ready before printing
310
+ --json Print {id, shareUrl, contextUrl, sizeBytes}
311
+ ${c.dim("auth (headless web capture only) — seed a logged-in session BEFORE the")}
312
+ ${c.dim("first navigation, so an app's route guard sees it (never on --source mac-screen):")}
313
+ --storage-state <f> Playwright storageState JSON (cookies + localStorage)
314
+ --cookie "n=v[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]" (repeatable)
315
+ --local-storage "k=v" Seed a localStorage pair for the target origin (repeatable)
316
+ --init-script <f> Run a JS file before every page load
309
317
 
310
318
  ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
311
319
  ${c.dim("--source mac-screen on record/session records the REAL screen via the")}
@@ -321,9 +329,27 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
321
329
  the recording kind (see record). --expose-cdp
322
330
  opens a CDP endpoint so your tools can drive the
323
331
  page as it records (off by default; any local
324
- process could attach — CLIPY_DISABLE_CDP=1 forces off)
325
- mark "<what just happened>" Drop a live timestamped note; marks become
326
- the recording's transcript chapters
332
+ process could attach — CLIPY_DISABLE_CDP=1 forces off).
333
+ Accepts the same auth flags as record
334
+ (--storage-state/--cookie/--local-storage/--init-script)
335
+ and --json (returns cdpUrl/cdpHttpUrl)
336
+ session run [start flags] -- <command …>
337
+ Start a session, run the command (inherited
338
+ stdio), then GUARANTEE cleanup: exit 0 uploads,
339
+ any non-zero exit or signal discards and
340
+ propagates the code. Sets CLIPY_SESSION=1 (+
341
+ CLIPY_CDP_URL with --expose-cdp). Crash-safe
342
+ wrapper for driver scripts — no dead-air uploads.
343
+ mark "<what just happened>" Drop a live timestamped note; marks become the
344
+ recording's transcript. Verify what you claim:
345
+ --assert-selector <css> assert an element exists (observed text recorded)
346
+ --assert-text <substr> require that element's text to contain <substr>
347
+ --assert-url <glob> assert the page URL matches (**/* wildcards)
348
+ --fail-mode warn|abort warn (default) annotates ASSERT ✗; abort
349
+ discards the whole session on a failed assertion
350
+ --at <sec> | --ago <sec> backdate the mark (absolute / N seconds ago)
351
+ chapter "<label>" Split the recording into BEFORE/AFTER sections
352
+ (demo base → chapter "AFTER" → demo the fix)
327
353
  session stop Finish: close browser, upload, print link
328
354
  session abort Discard the session — nothing is uploaded
329
355
  session status Show the active session's state
@@ -337,6 +363,9 @@ ${c.bold("AGENTS")}
337
363
  Playwright, and install mode — with fix hints
338
364
  guide --json Machine-readable manifest: every command,
339
365
  flag, env var, and exit code
366
+ playwright-path [--json] Print the node_modules dir of the Playwright
367
+ this CLI resolves, for your own driver scripts:
368
+ ${c.dim("NODE_PATH=$(clipy playwright-path) node driver.js")}
340
369
  transcript <id> --replace <file> Replace a transcript with agent-authored
341
370
  JSON ({segments} or {plaintext}); regenerates
342
371
  the summary ${c.dim("(needs the \"ingest\" permission)")}
@@ -345,7 +374,9 @@ ${c.bold("AGENTS")}
345
374
  ${c.bold("GLOBAL FLAGS")}
346
375
  --key <key> API key for this invocation (else CLIPY_API_KEY, else stored login)
347
376
  --api-url <url> API base (else CLIPY_API_URL, default https://clipy.online)
348
- --json Machine-readable output (list/search/show/transcript/summary/moments/wait)
377
+ --json Machine-readable output. Supported on: list, search, show,
378
+ transcript, summary, moments, wait, record, session
379
+ start/stop/status, mark, chapter, doctor, playwright-path
349
380
  -v, --version Print version
350
381
 
351
382
  ${c.bold("EXIT CODES")}
@@ -937,7 +968,17 @@ async function doctorBridgeChecks() {
937
968
  async function doctorPlaywrightCheck() {
938
969
  const res = await resolvePlaywright();
939
970
  if (res.ok) {
940
- return { name: "playwright", status: "pass", detail: `resolved via ${res.source}`, data: { source: res.source } };
971
+ // "PASS" here only means Clipy can load Playwright — NOT that the user's own
972
+ // --expose-cdp driver script will, since it resolves from a different cwd.
973
+ // Report where we found it, and always hand back the NODE_PATH escape hatch.
974
+ const nodeModulesDir = res.path ? nodeModulesDirOf(res.path) : null;
975
+ return {
976
+ name: "playwright",
977
+ status: "pass",
978
+ detail: `resolved via ${res.source}${res.path ? ` (${res.path})` : ""}`,
979
+ hint: "your own scripts (e.g. --expose-cdp drivers) resolve Playwright independently — from another directory `require('playwright')` can fail; run them with NODE_PATH=$(clipy playwright-path) or install Playwright there",
980
+ data: { source: res.source, path: res.path ?? null, nodeModulesDir },
981
+ };
941
982
  }
942
983
  const { mode } = detectInstallMode();
943
984
  return {
@@ -1149,8 +1190,18 @@ async function resolvePlaywright() {
1149
1190
  for (const mod of ["playwright", "playwright-core"]) {
1150
1191
  try {
1151
1192
  const chromium = chromiumFrom(await import(mod));
1152
- if (chromium)
1153
- return { ok: true, chromium, source: `import('${mod}')` };
1193
+ if (chromium) {
1194
+ // A bare import doesn't tell us WHERE it loaded from; ask the resolver
1195
+ // for the absolute entry path so doctor/playwright-path can report it.
1196
+ let path;
1197
+ try {
1198
+ path = createRequire(import.meta.url).resolve(mod);
1199
+ }
1200
+ catch {
1201
+ // resolved as a module but not to a concrete file path — leave unknown
1202
+ }
1203
+ return { ok: true, chromium, source: `import('${mod}')`, path };
1204
+ }
1154
1205
  }
1155
1206
  catch {
1156
1207
  // try the next strategy
@@ -1165,7 +1216,7 @@ async function resolvePlaywright() {
1165
1216
  const resolved = requireFromCwd.resolve(mod);
1166
1217
  const chromium = chromiumFrom(await import(pathToFileURL(resolved).href));
1167
1218
  if (chromium)
1168
- return { ok: true, chromium, source: `${mod} at ${dirname(resolved)}` };
1219
+ return { ok: true, chromium, source: `${mod} at ${dirname(resolved)}`, path: resolved };
1169
1220
  }
1170
1221
  catch {
1171
1222
  // fall through to the miss
@@ -1181,7 +1232,18 @@ async function resolvePlaywright() {
1181
1232
  * npx runs from an isolated `_npx` cache; a global bin lives outside cwd; a
1182
1233
  * project-local install sits under cwd/node_modules. */
1183
1234
  function detectInstallMode() {
1184
- const argv1 = process.argv[1] ? resolve(process.argv[1]) : "";
1235
+ const raw = process.argv[1] ? resolve(process.argv[1]) : "";
1236
+ // nvm/npm global bins are SYMLINKS (…/bin/clipy → …/lib/node_modules/@clipy/cli/dist/index.js).
1237
+ // Match against the REAL path or every global install misreports as
1238
+ // "unknown (running from source?)"; fall back to the raw path on a broken link.
1239
+ let argv1 = raw;
1240
+ try {
1241
+ if (raw)
1242
+ argv1 = realpathSync(raw);
1243
+ }
1244
+ catch {
1245
+ // dangling/permission-denied symlink — keep the raw path
1246
+ }
1185
1247
  const norm = argv1.replace(/\\/g, "/");
1186
1248
  const cwd = resolve(process.cwd()).replace(/\\/g, "/");
1187
1249
  let mode = "unknown";
@@ -1193,6 +1255,17 @@ function detectInstallMode() {
1193
1255
  mode = "global";
1194
1256
  return { mode, argv1 };
1195
1257
  }
1258
+ /** From a resolved package entry file, the node_modules DIRECTORY that contains
1259
+ * it — the substring up to and including the last "node_modules" segment — so
1260
+ * `NODE_PATH=$(clipy playwright-path) node driver.js` can require playwright.
1261
+ * Returns null when the entry isn't under a node_modules dir (linked/monorepo). */
1262
+ function nodeModulesDirOf(entryPath) {
1263
+ // \\→/ is a 1:1 char swap, so the index is valid against the original string.
1264
+ const idx = entryPath.replace(/\\/g, "/").lastIndexOf("/node_modules");
1265
+ if (idx < 0)
1266
+ return null;
1267
+ return entryPath.slice(0, idx + "/node_modules".length);
1268
+ }
1196
1269
  /** One-line install hint keyed to the install mode (the `doctor` ↳ line). For
1197
1270
  * npx we LEAD with the cwd-local install — the only guaranteed-working fix,
1198
1271
  * since the resolver's cwd-local strategy loads it and the npx cache can't see
@@ -1235,6 +1308,34 @@ async function loadChromium() {
1235
1308
  return res.chromium;
1236
1309
  die(playwrightMissingMessage(detectInstallMode().mode));
1237
1310
  }
1311
+ /** `clipy playwright-path` — print the node_modules DIRECTORY holding the
1312
+ * Playwright this CLI resolves, so a user's own driver script can find the same
1313
+ * copy: `NODE_PATH=$(clipy playwright-path) node driver.js`. Exits non-zero
1314
+ * (empty stdout) if Playwright is unresolvable, so the command substitution
1315
+ * fails loudly rather than handing NODE_PATH a bogus value. */
1316
+ async function cmdPlaywrightPath(json) {
1317
+ const res = await resolvePlaywright();
1318
+ if (!res.ok) {
1319
+ if (json) {
1320
+ printJson({ path: null, nodeModulesDir: null, source: null });
1321
+ process.exitCode = 1;
1322
+ return;
1323
+ }
1324
+ die(`${res.error}\n${playwrightInstallHint(detectInstallMode().mode)}`, 1);
1325
+ }
1326
+ const nodeModulesDir = res.path ? nodeModulesDirOf(res.path) : null;
1327
+ if (json) {
1328
+ printJson({ path: res.path ?? null, nodeModulesDir, source: res.source });
1329
+ if (!nodeModulesDir)
1330
+ process.exitCode = 1;
1331
+ return;
1332
+ }
1333
+ if (!nodeModulesDir) {
1334
+ die(`Playwright resolved${res.path ? ` at ${res.path}` : ""} but not from a node_modules directory — ` +
1335
+ `NODE_PATH can't point at it; install Playwright in your script's project instead`, 1);
1336
+ }
1337
+ process.stdout.write(`${nodeModulesDir}\n`);
1338
+ }
1238
1339
  /** Named viewport presets for `--viewports` (agent demos across screen sizes). */
1239
1340
  const VIEWPORT_ALIASES = {
1240
1341
  mobile: { width: 390, height: 844 },
@@ -1510,6 +1611,143 @@ async function waitForFirstPaint(page, size, log) {
1510
1611
  log(c.dim(`waited ${(waited / 1000).toFixed(1)}s for first meaningful paint`));
1511
1612
  return waited;
1512
1613
  }
1614
+ /** Parse one `--cookie` value into a Playwright cookie. Grammar:
1615
+ * `name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]`. The first
1616
+ * `;`-segment is name=value (split on the first `=`); later segments are
1617
+ * case-insensitive attributes. Without a Domain we url-scope the cookie to the
1618
+ * target; with one we domain-scope it. Throws on a malformed spec so the parent
1619
+ * can turn it into a die(2). */
1620
+ function parseCookieSpec(spec, targetUrl) {
1621
+ const segments = spec.split(";").map((s) => s.trim()).filter(Boolean);
1622
+ if (segments.length === 0)
1623
+ throw new Error(`--cookie "${spec}" is empty`);
1624
+ const eq = segments[0].indexOf("=");
1625
+ if (eq < 1)
1626
+ throw new Error(`--cookie "${spec}" must start with name=value`);
1627
+ const name = segments[0].slice(0, eq).trim();
1628
+ const value = segments[0].slice(eq + 1).trim();
1629
+ if (!name)
1630
+ throw new Error(`--cookie "${spec}" has an empty name`);
1631
+ let domain;
1632
+ let path;
1633
+ let secure = false;
1634
+ let httpOnly = false;
1635
+ let sameSite;
1636
+ for (const seg of segments.slice(1)) {
1637
+ const aEq = seg.indexOf("=");
1638
+ const attr = (aEq >= 0 ? seg.slice(0, aEq) : seg).trim().toLowerCase();
1639
+ const aVal = aEq >= 0 ? seg.slice(aEq + 1).trim() : "";
1640
+ switch (attr) {
1641
+ case "domain":
1642
+ domain = aVal;
1643
+ break;
1644
+ case "path":
1645
+ path = aVal;
1646
+ break;
1647
+ case "secure":
1648
+ secure = true;
1649
+ break;
1650
+ case "httponly":
1651
+ httpOnly = true;
1652
+ break;
1653
+ case "samesite": {
1654
+ const s = aVal.toLowerCase();
1655
+ sameSite = s === "strict" ? "Strict" : s === "none" ? "None" : "Lax";
1656
+ break;
1657
+ }
1658
+ default:
1659
+ throw new Error(`--cookie "${spec}": unknown attribute "${attr}" (accepted: Domain, Path, Secure, HttpOnly, SameSite)`);
1660
+ }
1661
+ }
1662
+ if (domain) {
1663
+ return { name, value, domain, path: path || "/", secure, httpOnly, ...(sameSite ? { sameSite } : {}) };
1664
+ }
1665
+ return { name, value, url: targetUrl };
1666
+ }
1667
+ /** Parse one `--local-storage` value ("key=value"; value may be empty). */
1668
+ function parseLocalStorageSpec(spec) {
1669
+ const eq = spec.indexOf("=");
1670
+ if (eq < 1)
1671
+ throw new Error(`--local-storage "${spec}" must be key=value`);
1672
+ return [spec.slice(0, eq), spec.slice(eq + 1)];
1673
+ }
1674
+ /** The single init script that seeds localStorage. Each pair is origin-guarded
1675
+ * so it never leaks into an unexpected origin the page might navigate to, and
1676
+ * runs before page scripts so route guards see the storage on first paint. */
1677
+ function localStorageInitScript(pairs, origin) {
1678
+ return pairs
1679
+ .map(([k, v]) => `if (location.origin === ${JSON.stringify(origin)}) localStorage.setItem(${JSON.stringify(k)}, ${JSON.stringify(v)});`)
1680
+ .join("\n");
1681
+ }
1682
+ /** Validate the auth-capture flags in the PARENT process — before launching a
1683
+ * browser or daemonizing — so an agent gets an instant, precise usage error
1684
+ * instead of a cryptic daemon-log failure. NEVER prints the storage-state
1685
+ * contents: it holds live credentials; only a shape warning is emitted. */
1686
+ function validateAuthCapture(auth, targetUrl) {
1687
+ if (auth.storageStatePath) {
1688
+ let raw;
1689
+ try {
1690
+ raw = readFileSync(auth.storageStatePath, "utf8");
1691
+ }
1692
+ catch {
1693
+ die(`--storage-state file not found or unreadable: ${auth.storageStatePath}`, 2);
1694
+ }
1695
+ let parsed;
1696
+ try {
1697
+ parsed = JSON.parse(raw);
1698
+ }
1699
+ catch {
1700
+ die(`--storage-state is not valid JSON: ${auth.storageStatePath}`, 2);
1701
+ }
1702
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1703
+ die(`--storage-state must be a Playwright storageState JSON object: ${auth.storageStatePath}`, 2);
1704
+ }
1705
+ if (!("cookies" in parsed) && !("origins" in parsed)) {
1706
+ process.stderr.write(`${c.yellow("warning:")} --storage-state has neither "cookies" nor "origins" — it may not be a Playwright storageState file\n`);
1707
+ }
1708
+ }
1709
+ if (auth.initScriptPath) {
1710
+ try {
1711
+ statSync(auth.initScriptPath);
1712
+ }
1713
+ catch {
1714
+ die(`--init-script file not found: ${auth.initScriptPath}`, 2);
1715
+ }
1716
+ }
1717
+ // Parse the cookie / local-storage specs now purely to surface grammar errors
1718
+ // up front; the values are re-parsed where they're applied.
1719
+ for (const spec of auth.cookieSpecs) {
1720
+ try {
1721
+ parseCookieSpec(spec, targetUrl);
1722
+ }
1723
+ catch (e) {
1724
+ die(e.message, 2);
1725
+ }
1726
+ }
1727
+ for (const spec of auth.localStorageSpecs) {
1728
+ try {
1729
+ parseLocalStorageSpec(spec);
1730
+ }
1731
+ catch (e) {
1732
+ die(e.message, 2);
1733
+ }
1734
+ }
1735
+ }
1736
+ /** Apply cookies, seeded localStorage, and the user init script to a freshly
1737
+ * created context, in that order, BEFORE newPage()/goto. --storage-state is
1738
+ * applied by the caller at newContext() time (Playwright takes the file path
1739
+ * directly), not here. Re-parses the raw specs the parent already validated. */
1740
+ async function applyAuthCapture(context, auth, targetUrl) {
1741
+ const cookies = auth.cookieSpecs.map((s) => parseCookieSpec(s, targetUrl));
1742
+ if (cookies.length)
1743
+ await context.addCookies(cookies);
1744
+ const pairs = auth.localStorageSpecs.map(parseLocalStorageSpec);
1745
+ if (pairs.length) {
1746
+ await context.addInitScript({ content: localStorageInitScript(pairs, new URL(targetUrl).origin) });
1747
+ }
1748
+ if (auth.initScriptPath)
1749
+ await context.addInitScript({ path: auth.initScriptPath });
1750
+ }
1513
1751
  async function cmdRecord(ctx, opts) {
1514
1752
  // Validate the target URL up front — a headless browser will happily hang on
1515
1753
  // a typo'd or non-http(s) URL otherwise.
@@ -1523,6 +1761,7 @@ async function cmdRecord(ctx, opts) {
1523
1761
  if (target.protocol !== "http:" && target.protocol !== "https:") {
1524
1762
  die(`--url must be http(s), got ${target.protocol}`, 2);
1525
1763
  }
1764
+ validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/browser
1526
1765
  requireKey(ctx); // fail fast before we spin up a browser
1527
1766
  const chromium = await loadChromium();
1528
1767
  const tmpDir = join(tmpdir(), `clipy-record-${randomUUID()}`);
@@ -1569,7 +1808,11 @@ async function cmdRecord(ctx, opts) {
1569
1808
  const context = await browser.newContext({
1570
1809
  viewport: { width: frame.width, height: frame.height },
1571
1810
  recordVideo: { dir: tmpDir, size: frame },
1811
+ // Playwright takes the storageState file path directly (cookies + origins).
1812
+ ...(opts.auth.storageStatePath ? { storageState: opts.auth.storageStatePath } : {}),
1572
1813
  });
1814
+ // Seed cookies/localStorage/init-script before the first navigation.
1815
+ await applyAuthCapture(context, opts.auth, target.href);
1573
1816
  const page = await context.newPage();
1574
1817
  // captureStart is set AFTER the first meaningful paint (below), so notes
1575
1818
  // and pass marks aren't anchored to the blank t=0 a compiling app shows.
@@ -1735,6 +1978,113 @@ function cleanupSessionFiles(state, file) {
1735
1978
  }
1736
1979
  }
1737
1980
  }
1981
+ /** Compile a URL glob to a RegExp: `**` → `.*`, a lone `*` → `[^/]*`, every
1982
+ * other regex metachar escaped. A glob with NO `*` is treated as a bare
1983
+ * substring match (the common "is this path in the URL" case). */
1984
+ function urlGlobMatches(glob, url) {
1985
+ if (!glob.includes("*"))
1986
+ return url.includes(glob);
1987
+ // Escape regex metachars, then restore the glob wildcards. \x00 is a private
1988
+ // placeholder so `**` isn't clobbered while we expand single `*`.
1989
+ const escaped = glob
1990
+ .replace(/[.+?^${}()|[\]\\]/g, "\\$&")
1991
+ .replace(/\*\*/g, "\x00")
1992
+ .replace(/\*/g, "[^/]*")
1993
+ .replace(/\x00/g, ".*");
1994
+ try {
1995
+ return new RegExp(`^${escaped}$`).test(url);
1996
+ }
1997
+ catch {
1998
+ return url.includes(glob.replace(/\*/g, ""));
1999
+ }
2000
+ }
2001
+ /** POST to the web daemon's local control endpoint with the bearer token.
2002
+ * Throws on connection failure / non-2xx (the caller decides whether to fall
2003
+ * back to the marks file or die). */
2004
+ async function postToControl(state, path, body, timeoutMs) {
2005
+ const controller = new AbortController();
2006
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
2007
+ try {
2008
+ const res = await fetch(`http://127.0.0.1:${state.controlPort}${path}`, {
2009
+ method: "POST",
2010
+ headers: {
2011
+ Authorization: `Bearer ${state.controlToken}`,
2012
+ "Content-Type": "application/json",
2013
+ },
2014
+ body: JSON.stringify(body ?? {}),
2015
+ signal: controller.signal,
2016
+ });
2017
+ const text = await res.text();
2018
+ let parsed = {};
2019
+ try {
2020
+ parsed = text ? JSON.parse(text) : {};
2021
+ }
2022
+ catch {
2023
+ parsed = { raw: text };
2024
+ }
2025
+ if (!res.ok) {
2026
+ throw new Error(typeof parsed.error === "string" ? parsed.error : `control endpoint error ${res.status}`);
2027
+ }
2028
+ return parsed;
2029
+ }
2030
+ catch (e) {
2031
+ if (e.name === "AbortError")
2032
+ throw new Error(`control endpoint timed out after ${timeoutMs / 1000}s`);
2033
+ throw e;
2034
+ }
2035
+ finally {
2036
+ clearTimeout(timer);
2037
+ }
2038
+ }
2039
+ /** Evaluate an assertion against the daemon's live page. Wraps the single
2040
+ * page.evaluate in a 5s race so an unresponsive page throws (a caught error the
2041
+ * caller turns into a 5xx) instead of hanging the daemon. A selector that
2042
+ * simply doesn't match is a normal FAIL, not an error. */
2043
+ async function evaluateAssertion(page, assert) {
2044
+ const expected = [];
2045
+ const observed = [];
2046
+ let passed = true;
2047
+ if (assert.urlGlob) {
2048
+ const url = page.url();
2049
+ expected.push(`url~"${assert.urlGlob}"`);
2050
+ observed.push(`url=${url}`);
2051
+ if (!urlGlobMatches(assert.urlGlob, url))
2052
+ passed = false;
2053
+ }
2054
+ if (assert.selector) {
2055
+ const sel = assert.selector;
2056
+ // Runs in the browser; typed locally so the CLI needs no DOM lib to build.
2057
+ const lookup = page.evaluate((s) => {
2058
+ const doc = globalThis.document;
2059
+ const el = doc?.querySelector(s);
2060
+ if (!el)
2061
+ return { match: false };
2062
+ const raw = (el.textContent ?? "").trim().replace(/\s+/g, " ");
2063
+ return { match: true, text: raw.slice(0, 200) };
2064
+ }, sel);
2065
+ const result = await Promise.race([
2066
+ lookup,
2067
+ new Promise((_, reject) => setTimeout(() => reject(new Error("page did not respond within 5s")), 5000)),
2068
+ ]);
2069
+ if (!result.match) {
2070
+ passed = false;
2071
+ expected.push(assert.expectText ? `${sel} containing "${assert.expectText}"` : `${sel} present`);
2072
+ observed.push(`${sel}=no match`);
2073
+ }
2074
+ else {
2075
+ observed.push(`${sel}=${result.text ? `"${result.text}"` : "(empty)"}`);
2076
+ if (assert.expectText != null && assert.expectText !== "") {
2077
+ expected.push(`"${assert.expectText}"`);
2078
+ if (!result.text.includes(assert.expectText))
2079
+ passed = false;
2080
+ }
2081
+ else {
2082
+ expected.push(`${sel} present`);
2083
+ }
2084
+ }
2085
+ }
2086
+ return { passed, observed: observed.join("; "), expected: expected.join("; ") };
2087
+ }
1738
2088
  // --- Mac bridge flows (--source mac-screen): the desktop app records -------
1739
2089
  /** Resolves --window/--display to a bridge capture source (null = app default,
1740
2090
  * i.e. the full primary display). die()s with the candidate list on no/ambiguous
@@ -1824,6 +2174,23 @@ function bridgeInfoFromSession(state) {
1824
2174
  protocolVersion: 1,
1825
2175
  };
1826
2176
  }
2177
+ /** The ready-to-run Playwright snippet printed after `session start --expose-cdp`.
2178
+ * Encodes the four gotchas that otherwise cost an agent a debugging round:
2179
+ * use connectOverCDP; the recorded page is contexts()[0].pages()[0] (a fresh
2180
+ * context/page is NOT the one being recorded); viewportSize() is null over CDP;
2181
+ * and a resize needs a CDP Emulation.setDeviceMetricsOverride, not setViewportSize. */
2182
+ function cdpDriverSnippet(cdpHttpUrl) {
2183
+ return [
2184
+ `${c.dim("drive the recorded page with your own Playwright:")}`,
2185
+ c.dim(` const { chromium } = require('playwright');`),
2186
+ c.dim(` const browser = await chromium.connectOverCDP(${JSON.stringify(cdpHttpUrl)});`),
2187
+ c.dim(` const page = browser.contexts()[0].pages()[0]; // the page being recorded (a NEW context/page is not captured)`),
2188
+ c.dim(` await page.goto('https://…'); // navigate / click / fill as usual`),
2189
+ c.dim(` const cdp = await browser.newCDPSession(page); // page.viewportSize() is null over CDP —`),
2190
+ c.dim(` await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 720, deviceScaleFactor: 1, mobile: false });`),
2191
+ c.dim(` resolve playwright for your script: NODE_PATH=$(clipy playwright-path) node driver.js`),
2192
+ ].join("\n");
2193
+ }
1827
2194
  async function cmdSessionStart(ctx, opts) {
1828
2195
  if (opts.source === "mac-screen") {
1829
2196
  const file = sessionFilePath(process.cwd());
@@ -1866,6 +2233,7 @@ async function cmdSessionStart(ctx, opts) {
1866
2233
  if (target.protocol !== "http:" && target.protocol !== "https:") {
1867
2234
  die(`--url must be http(s), got ${target.protocol}`, 2);
1868
2235
  }
2236
+ validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/daemonizing
1869
2237
  const key = requireKey(ctx);
1870
2238
  await loadChromium(); // fail fast with install instructions before daemonizing
1871
2239
  const file = sessionFilePath(process.cwd());
@@ -1892,6 +2260,10 @@ async function cmdSessionStart(ctx, opts) {
1892
2260
  width: opts.width,
1893
2261
  height: opts.height,
1894
2262
  exposeCdp: opts.exposeCdp,
2263
+ storageStatePath: opts.auth.storageStatePath,
2264
+ initScriptPath: opts.auth.initScriptPath,
2265
+ cookieSpecs: opts.auth.cookieSpecs.length ? opts.auth.cookieSpecs : undefined,
2266
+ localStorageSpecs: opts.auth.localStorageSpecs.length ? opts.auth.localStorageSpecs : undefined,
1895
2267
  state: "starting",
1896
2268
  marksPath: join(dir, `marks-${id}.jsonl`),
1897
2269
  controlPath: join(dir, `control-${id}.json`),
@@ -1944,8 +2316,8 @@ async function cmdSessionStart(ctx, opts) {
1944
2316
  }
1945
2317
  process.stdout.write(`${c.green("✓")} recording ${c.bold(target.href)} (max ${maxSec}s)\n`);
1946
2318
  if (started?.cdpHttpUrl) {
1947
- process.stdout.write(`${c.yellow("⚠ CDP exposed:")} any local process can attach to and control this browser while the session runs.\n` +
1948
- `${c.dim(`drive the browser: connect your tools to ${started.cdpHttpUrl}`)}\n`);
2319
+ process.stdout.write(`${c.yellow("⚠ CDP exposed:")} any local process can attach to and control this browser while the session runs.\n`);
2320
+ process.stdout.write(`${cdpDriverSnippet(started.cdpHttpUrl)}\n`);
1949
2321
  }
1950
2322
  else if (opts.exposeCdp) {
1951
2323
  // Asked for it, but it isn't up — either env-disabled or discovery failed.
@@ -1964,9 +2336,33 @@ function requireSession() {
1964
2336
  }
1965
2337
  return { file, state };
1966
2338
  }
1967
- async function cmdMark(text, json) {
2339
+ /** Print a /mark or /chapter control response (or a file-fallback shape). A
2340
+ * failed assertion prints a red ✗; everything else a green ✓. The mark text is
2341
+ * already annotated daemon-side, so it carries the ✓/✗ + observed inline. */
2342
+ function printMarkResult(res, json) {
2343
+ if (json) {
2344
+ printJson(res);
2345
+ return;
2346
+ }
2347
+ const sec = (Number(res.tMs ?? 0) / 1000).toFixed(1);
2348
+ const assert = res.assert;
2349
+ const glyph = assert && assert.passed === false ? c.red("✗") : c.green("✓");
2350
+ process.stdout.write(`${glyph} mark @ ${sec}s — ${String(res.text ?? "")}\n`);
2351
+ }
2352
+ async function cmdMark(text, json, opts) {
1968
2353
  const { file, state } = requireSession();
2354
+ const hasAssert = !!opts.assert;
2355
+ const backdated = opts.atSec != null || opts.agoSec != null;
1969
2356
  if (state.kind === "mac") {
2357
+ // The Mac app records the real screen — there is no page to probe, and the
2358
+ // bridge stamps every mark on its own clock, so assertions and backdating
2359
+ // are web-session features.
2360
+ if (hasAssert) {
2361
+ die("assertions need a web session — the Mac app records the real screen; there is no page to probe", 2);
2362
+ }
2363
+ if (backdated) {
2364
+ die("--at/--ago need a web session — the Mac bridge stamps each mark on its own clock", 2);
2365
+ }
1970
2366
  const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text }).catch((e) => {
1971
2367
  if (e instanceof BridgeUnavailableError) {
1972
2368
  cleanupSessionFiles(state, file);
@@ -1988,14 +2384,102 @@ async function cmdMark(text, json) {
1988
2384
  if (state.state !== "recording" || !state.recordStartEpochMs) {
1989
2385
  die(`session is ${state.state} — marks can only be added while recording`);
1990
2386
  }
2387
+ // --at is an absolute recording-clock time; --ago is N seconds before now,
2388
+ // both computed against the SAME recordStartEpochMs the daemon saved. Absent ⇒
2389
+ // let the daemon stamp its live clock (undefined atMs).
2390
+ const atMs = backdated
2391
+ ? opts.atSec != null
2392
+ ? Math.max(0, Math.round(opts.atSec * 1000))
2393
+ : Math.max(0, Date.now() - state.recordStartEpochMs - Math.round((opts.agoSec ?? 0) * 1000))
2394
+ : undefined;
2395
+ if (state.controlPort && state.controlToken) {
2396
+ let res;
2397
+ try {
2398
+ res = await postToControl(state, "/mark", {
2399
+ text: text.trim(),
2400
+ ...(atMs != null ? { atMs } : {}),
2401
+ ...(hasAssert ? { assert: opts.assert } : {}),
2402
+ }, 5000);
2403
+ }
2404
+ catch (e) {
2405
+ // Assertions REQUIRE the live page — there's no honest file fallback for a
2406
+ // verification the daemon couldn't run. Plain marks fall back to the file.
2407
+ if (hasAssert) {
2408
+ die(`the session daemon isn't answering — assertions need the live page (${e.message})`);
2409
+ }
2410
+ const tMs = atMs != null ? atMs : Math.max(0, Date.now() - state.recordStartEpochMs);
2411
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`, { mode: 0o600 });
2412
+ printMarkResult({ tMs, text: text.trim() }, json);
2413
+ return;
2414
+ }
2415
+ if (res.aborted) {
2416
+ // A failed assertion with --fail-mode abort discarded the session. Show
2417
+ // the ✗ mark, then die loudly so the agent can't mistake this for success.
2418
+ printMarkResult(res, json);
2419
+ die("session ABORTED by a failed assertion (--fail-mode abort) — nothing was uploaded. Fix the condition, then start a new session.");
2420
+ }
2421
+ printMarkResult(res, json);
2422
+ return;
2423
+ }
2424
+ // No control endpoint (session started by a pre-0.6 CLI): assertions can't run.
2425
+ if (hasAssert) {
2426
+ die("this session has no control endpoint (started by an older clipy) — stop it and run `clipy session start` again to use assertion marks");
2427
+ }
2428
+ const tMs = atMs != null ? atMs : Math.max(0, Date.now() - state.recordStartEpochMs);
2429
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`, { mode: 0o600 });
2430
+ printMarkResult({ tMs, text: text.trim() }, json);
2431
+ }
2432
+ /** `clipy chapter "<label>"` — a chapter is a specially-formatted mark
2433
+ * (=== CHAPTER: <label> ===) that splits one recording into BEFORE/AFTER
2434
+ * sections (demo base branch → chapter "AFTER" → swap branch → demo the fix). */
2435
+ async function cmdChapter(label, json) {
2436
+ const { file, state } = requireSession();
2437
+ const chapterText = `=== CHAPTER: ${label} ===`;
2438
+ if (state.kind === "mac") {
2439
+ const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: chapterText }).catch((e) => {
2440
+ if (e instanceof BridgeUnavailableError) {
2441
+ cleanupSessionFiles(state, file);
2442
+ die("the Clipy app is no longer running — session cleared. Start a new one.");
2443
+ }
2444
+ die(e.message);
2445
+ });
2446
+ if (json) {
2447
+ printJson({ tMs: Number(result.atSeconds ?? 0) * 1000, label, text: chapterText });
2448
+ return;
2449
+ }
2450
+ process.stdout.write(`${c.green("✓")} chapter @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${label}\n`);
2451
+ return;
2452
+ }
2453
+ if (!pidAlive(state.pid)) {
2454
+ cleanupSessionFiles(state, file);
2455
+ die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
2456
+ }
2457
+ if (state.state !== "recording" || !state.recordStartEpochMs) {
2458
+ die(`session is ${state.state} — chapters can only be added while recording`);
2459
+ }
2460
+ if (state.controlPort && state.controlToken) {
2461
+ try {
2462
+ const res = await postToControl(state, "/chapter", { label }, 5000);
2463
+ if (json) {
2464
+ printJson({ tMs: Number(res.tMs ?? 0), label, text: chapterText });
2465
+ }
2466
+ else {
2467
+ process.stdout.write(`${c.green("✓")} chapter @ ${(Number(res.tMs ?? 0) / 1000).toFixed(1)}s — ${label}\n`);
2468
+ }
2469
+ return;
2470
+ }
2471
+ catch {
2472
+ // Chapters aren't assertions — fall back to the marks file on failure.
2473
+ }
2474
+ }
1991
2475
  const tMs = Math.max(0, Date.now() - state.recordStartEpochMs);
1992
- appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`);
2476
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: chapterText })}\n`, { mode: 0o600 });
1993
2477
  if (json) {
1994
- printJson({ tMs, text: text.trim() });
1995
- return;
2478
+ printJson({ tMs, label, text: chapterText });
2479
+ }
2480
+ else {
2481
+ process.stdout.write(`${c.green("✓")} chapter @ ${(tMs / 1000).toFixed(1)}s — ${label}\n`);
1996
2482
  }
1997
- const sec = (tMs / 1000).toFixed(1);
1998
- process.stdout.write(`${c.green("✓")} mark @ ${sec}s — ${text.trim()}\n`);
1999
2483
  }
2000
2484
  async function cmdSessionStop(json) {
2001
2485
  const { file, state } = requireSession();
@@ -2104,8 +2588,60 @@ async function cmdSessionAbort(json) {
2104
2588
  await new Promise((r) => setTimeout(r, 300));
2105
2589
  }
2106
2590
  const final = readSessionState(file);
2591
+ const alive = final ? pidAlive(final.pid) : false;
2592
+ // The daemon is still alive AND mid-upload of a stop/max capture — the abort
2593
+ // arrived after it committed to finishing. Killing it would strand a partial
2594
+ // server-side upload, so let it finish; the user can collect it with
2595
+ // `session stop`. Leave the state file in place for that.
2596
+ if (final && alive && (final.state === "stopping" || final.state === "uploading")) {
2597
+ if (json) {
2598
+ printJson({ state: "finishing" });
2599
+ }
2600
+ else {
2601
+ process.stderr.write(`${c.yellow("!")} the recording is already being uploaded (abort came too late) — it will finish; run ${c.bold("clipy session stop")} to collect the link\n`);
2602
+ }
2603
+ process.exitCode = 1;
2604
+ return;
2605
+ }
2606
+ // Still recording after the full wait ⇒ the abort didn't take (wedged Chromium
2607
+ // / hung page). Don't quietly delete the state file out from under a process
2608
+ // that may still be recording — escalate: SIGTERM, a short grace, then SIGKILL,
2609
+ // and only THEN clean up. This is what makes `session run`'s "guaranteed
2610
+ // cleanup" honest.
2611
+ const wedged = final ? alive && (final.state === "starting" || final.state === "recording") : false;
2612
+ if (wedged && final) {
2613
+ try {
2614
+ process.kill(final.pid, "SIGTERM");
2615
+ }
2616
+ catch {
2617
+ // already gone
2618
+ }
2619
+ const graceDeadline = Date.now() + 3000;
2620
+ while (pidAlive(final.pid) && Date.now() < graceDeadline) {
2621
+ await new Promise((r) => setTimeout(r, 150));
2622
+ }
2623
+ if (pidAlive(final.pid)) {
2624
+ try {
2625
+ process.kill(final.pid, "SIGKILL");
2626
+ }
2627
+ catch {
2628
+ // already gone
2629
+ }
2630
+ }
2631
+ }
2107
2632
  if (final)
2108
2633
  cleanupSessionFiles(final, file);
2634
+ if (wedged) {
2635
+ // Exit non-zero (and truthfully) — the daemon had to be force-killed, so we
2636
+ // can't promise a clean discard. Use process.exitCode (not process.exit) so
2637
+ // a caller like `session run` can still override with the child's code.
2638
+ if (json)
2639
+ printJson({ state: "killed", pid: final?.pid ?? null });
2640
+ else
2641
+ process.stderr.write(`${c.yellow("!")} the session daemon ignored abort for 30s and was force-killed (pid ${final?.pid}); nothing was uploaded\n`);
2642
+ process.exitCode = 1;
2643
+ return;
2644
+ }
2109
2645
  if (json)
2110
2646
  printJson({ state: "aborted" });
2111
2647
  else
@@ -2175,9 +2711,71 @@ async function cmdSessionStatus(json) {
2175
2711
  process.stdout.write(`${c.bold(state.state)}${alive ? "" : c.red(" (daemon dead)")} — ${state.url}` +
2176
2712
  `${elapsed != null ? ` — ${elapsed}s elapsed (max ${state.maxSec}s)` : ""}\n`);
2177
2713
  if (state.cdpHttpUrl && state.state === "recording" && alive) {
2178
- process.stdout.write(`${c.dim(`drive the browser: connect your tools to ${state.cdpHttpUrl}`)}\n`);
2714
+ process.stdout.write(`${c.dim(`drive the recorded page: connectOverCDP(${state.cdpHttpUrl}) → browser.contexts()[0].pages()[0] · resize via CDP Emulation.setDeviceMetricsOverride · resolve playwright with NODE_PATH=$(clipy playwright-path)`)}\n`);
2179
2715
  }
2180
2716
  }
2717
+ /**
2718
+ * `clipy session run [start-flags] -- <command …>` — the crash-safe wrapper.
2719
+ * Starts a session, runs the command with inherited stdio, and GUARANTEES
2720
+ * cleanup: exit 0 uploads (session stop), any non-zero exit / signal discards
2721
+ * (session abort) and propagates the child's code. This is the fleet answer to
2722
+ * a crashed driver recording dead air to its max ceiling.
2723
+ */
2724
+ async function cmdSessionRun(ctx, startOpts, childArgv) {
2725
+ if (childArgv.length === 0) {
2726
+ die("usage: clipy session run [start flags] -- <command …> (everything after -- is the command to run)", 2);
2727
+ }
2728
+ // Start the session and block until it's recording. Force human output — the
2729
+ // child inherits our stdio and the deliverable is the wrapped run, not JSON.
2730
+ await cmdSessionStart(ctx, { ...startOpts, json: false });
2731
+ const file = sessionFilePath(process.cwd());
2732
+ const cdpHttpUrl = readSessionState(file)?.cdpHttpUrl;
2733
+ const [cmd, ...args] = childArgv;
2734
+ process.stderr.write(`${c.dim(`running: ${childArgv.join(" ")}`)}\n`);
2735
+ const child = spawn(cmd, args, {
2736
+ stdio: "inherit",
2737
+ env: {
2738
+ ...process.env,
2739
+ // Signals to the child that it's being recorded, and where to drive.
2740
+ CLIPY_SESSION: "1",
2741
+ ...(cdpHttpUrl ? { CLIPY_CDP_URL: cdpHttpUrl } : {}),
2742
+ },
2743
+ });
2744
+ // Forward Ctrl-C / termination to the child; its exit then drives the abort
2745
+ // path below (so we never double-abort or race the child).
2746
+ let forwarded = false;
2747
+ const forward = (sig) => {
2748
+ forwarded = true;
2749
+ try {
2750
+ child.kill(sig);
2751
+ }
2752
+ catch {
2753
+ // child already gone
2754
+ }
2755
+ };
2756
+ const onSigint = () => forward("SIGINT");
2757
+ const onSigterm = () => forward("SIGTERM");
2758
+ process.on("SIGINT", onSigint);
2759
+ process.on("SIGTERM", onSigterm);
2760
+ const outcome = await new Promise((res) => {
2761
+ child.on("error", (e) => {
2762
+ // Couldn't even spawn the command — don't leave the session recording.
2763
+ void cmdSessionAbort(false)
2764
+ .catch(() => { })
2765
+ .finally(() => die(`failed to run command "${cmd}": ${e.message}`));
2766
+ });
2767
+ child.on("exit", (code, signal) => res({ code, signal }));
2768
+ });
2769
+ process.off("SIGINT", onSigint);
2770
+ process.off("SIGTERM", onSigterm);
2771
+ if (outcome.code === 0 && !outcome.signal && !forwarded) {
2772
+ await cmdSessionStop(false); // clean exit → upload + print the share link
2773
+ return;
2774
+ }
2775
+ process.stderr.write(`${c.yellow(`command ${outcome.signal ? `terminated by ${outcome.signal}` : `exited ${outcome.code}`} — discarding the recording`)}\n`);
2776
+ await cmdSessionAbort(false);
2777
+ process.exit(outcome.code ?? 1); // propagate the child's failure
2778
+ }
2181
2779
  /** Reserve a free localhost TCP port for Chromium's CDP endpoint. Binding to
2182
2780
  * :0 then closing hands us a concrete port to pass to --remote-debugging-port,
2183
2781
  * which we can then poll — passing 0 directly leaves the chosen port only in
@@ -2236,8 +2834,26 @@ async function runSessionDaemon(file) {
2236
2834
  return;
2237
2835
  autoMarks.push({ startMs: Math.max(0, Date.now() - recordStart), text });
2238
2836
  };
2837
+ // Marks that arrive over the control endpoint (`clipy mark`/`chapter`) or the
2838
+ // in-page __clipyMark/__clipyChapter bindings. Kept in memory (like autoMarks)
2839
+ // and merged at stop. A hard 200 cap here is the server limit; storeDaemonMark
2840
+ // refuses past it so `clipy mark` gets an error rather than a silent drop.
2841
+ const daemonMarks = [];
2842
+ const storeDaemonMark = (note) => {
2843
+ if (daemonMarks.length >= 200)
2844
+ return false;
2845
+ daemonMarks.push(note);
2846
+ return true;
2847
+ };
2848
+ // Assertion tallies → the leading [verification] note at stop.
2849
+ let assertRan = 0;
2850
+ let assertPassed = 0;
2851
+ let assertFailed = 0;
2852
+ // A failed --fail-mode=abort assertion sets this; the main loop discards.
2853
+ let controlSignal = null;
2239
2854
  mkdirSync(state.tmpDir, { recursive: true });
2240
2855
  let browser = null;
2856
+ let controlServer = null;
2241
2857
  try {
2242
2858
  const chromium = await loadChromium();
2243
2859
  log(`launching chromium for ${state.url}`);
@@ -2261,7 +2877,40 @@ async function runSessionDaemon(file) {
2261
2877
  const context = await browser.newContext({
2262
2878
  viewport: { width: state.width, height: state.height },
2263
2879
  recordVideo: { dir: state.tmpDir, size: { width: state.width, height: state.height } },
2880
+ // Playwright takes the storageState file path directly (cookies + origins).
2881
+ ...(state.storageStatePath ? { storageState: state.storageStatePath } : {}),
2264
2882
  });
2883
+ // Seed cookies/localStorage/init-script before the first navigation — re-parse
2884
+ // the raw specs the parent CLI already validated. A bad spec here is caught by
2885
+ // the outer try/catch and fails the session cleanly.
2886
+ await applyAuthCapture(context, {
2887
+ storageStatePath: state.storageStatePath,
2888
+ initScriptPath: state.initScriptPath,
2889
+ cookieSpecs: state.cookieSpecs ?? [],
2890
+ localStorageSpecs: state.localStorageSpecs ?? [],
2891
+ }, state.url);
2892
+ // In-page mark/chapter bindings — only under --expose-cdp, and only alongside
2893
+ // the debugging port a driver already uses. A page.evaluate(() =>
2894
+ // window.__clipyMark("…")) emits a mark with ZERO spawn latency (no `clipy
2895
+ // mark` process). Same 200-cap store as the HTTP path. NOTE: while CDP is
2896
+ // exposed, the page's own scripts can call these too — that's within the
2897
+ // existing --expose-cdp trust model (any local process can already drive the
2898
+ // browser), and it's documented in the README's --expose-cdp section.
2899
+ if (wantCdp) {
2900
+ const inPageMark = (label) => {
2901
+ if (recordStart === 0)
2902
+ return;
2903
+ const text = label.trim();
2904
+ if (text)
2905
+ storeDaemonMark({ startMs: Math.max(0, Date.now() - recordStart), text });
2906
+ };
2907
+ await context
2908
+ .exposeBinding("__clipyMark", (_src, ...args) => inPageMark(String(args[0] ?? "")))
2909
+ .catch((e) => log(`__clipyMark binding failed: ${e.message}`));
2910
+ await context
2911
+ .exposeBinding("__clipyChapter", (_src, ...args) => inPageMark(`=== CHAPTER: ${String(args[0] ?? "").trim()} ===`))
2912
+ .catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
2913
+ }
2265
2914
  const page = await context.newPage();
2266
2915
  // Best-effort: publish the CDP URL so `session start`/`status` can hand it
2267
2916
  // to the agent. The recording works fine even if discovery fails.
@@ -2298,8 +2947,156 @@ async function runSessionDaemon(file) {
2298
2947
  // ignore
2299
2948
  }
2300
2949
  }));
2950
+ // Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
2951
+ // which owns the live page — evaluates assertions and stamps marks on its
2952
+ // own clock. 127.0.0.1 only, bearer-token auth (random UUID). If it can't
2953
+ // bind, the recording still runs and marks fall back to the marks file.
2954
+ const controlToken = randomUUID();
2955
+ let controlPort = 0;
2956
+ /** POST /mark → tMs (atMs override or live clock), optional assertion run
2957
+ * against the page, stored (annotated) mark, and the response the CLI shows. */
2958
+ const handleMark = async (body) => {
2959
+ const text = typeof body.text === "string" ? body.text.trim() : "";
2960
+ if (!text)
2961
+ throw new Error("mark text is required");
2962
+ const tMs = typeof body.atMs === "number" && Number.isFinite(body.atMs)
2963
+ ? Math.max(0, Math.round(body.atMs))
2964
+ : Math.max(0, Date.now() - recordStart);
2965
+ let annotated = text;
2966
+ let assertOut;
2967
+ let aborted = false;
2968
+ const assertSpec = body.assert;
2969
+ if (assertSpec && typeof assertSpec === "object") {
2970
+ // evaluateAssertion throws if the page is unresponsive — surfaced as a
2971
+ // 5xx so the CLI die()s rather than recording an unverified claim.
2972
+ const ev = await evaluateAssertion(page, assertSpec);
2973
+ assertRan++;
2974
+ if (ev.passed)
2975
+ assertPassed++;
2976
+ else
2977
+ assertFailed++;
2978
+ annotated = ev.passed
2979
+ ? `${text} [assert ✓ ${ev.observed}]`
2980
+ : `${text} [ASSERT ✗ expected ${ev.expected}; observed ${ev.observed}]`;
2981
+ assertOut = { passed: ev.passed, observed: ev.observed };
2982
+ if (!ev.passed && assertSpec.failMode === "abort")
2983
+ aborted = true;
2984
+ }
2985
+ if (!storeDaemonMark({ startMs: tMs, text: annotated })) {
2986
+ throw new Error("mark limit reached (200 marks per recording)");
2987
+ }
2988
+ if (aborted)
2989
+ controlSignal = "abort";
2990
+ return {
2991
+ tMs,
2992
+ text: annotated,
2993
+ ...(assertOut ? { assert: assertOut } : {}),
2994
+ ...(aborted ? { aborted: true } : {}),
2995
+ };
2996
+ };
2997
+ /** POST /chapter → a =={ CHAPTER }== mark at the live clock. */
2998
+ const handleChapter = (body) => {
2999
+ const label = typeof body.label === "string" ? body.label.trim() : "";
3000
+ if (!label)
3001
+ throw new Error("chapter label is required");
3002
+ const tMs = Math.max(0, Date.now() - recordStart);
3003
+ if (!storeDaemonMark({ startMs: tMs, text: `=== CHAPTER: ${label} ===` })) {
3004
+ throw new Error("mark limit reached (200 marks per recording)");
3005
+ }
3006
+ return { tMs };
3007
+ };
3008
+ const BODY_CAP = 1_000_000;
3009
+ controlServer = createHttpServer((req, res) => {
3010
+ const respond = (status, obj) => {
3011
+ res.writeHead(status, { "Content-Type": "application/json" });
3012
+ res.end(JSON.stringify(obj));
3013
+ };
3014
+ if (req.headers.authorization !== `Bearer ${controlToken}`) {
3015
+ respond(401, { error: "unauthorized" });
3016
+ return;
3017
+ }
3018
+ if (req.method !== "POST") {
3019
+ respond(405, { error: "method not allowed" });
3020
+ return;
3021
+ }
3022
+ // Only JSON — a wrong content-type is almost always a confused client.
3023
+ if (!String(req.headers["content-type"] ?? "").toLowerCase().includes("application/json")) {
3024
+ respond(415, { error: "content-type must be application/json" });
3025
+ return;
3026
+ }
3027
+ // Reject an over-cap body: first by its declared Content-Length (before
3028
+ // reading a byte), then again if the stream itself exceeds the cap. Send an
3029
+ // explicit 413 and DRAIN the rest (req.resume) so a mid-upload client reads
3030
+ // the status instead of hitting the opaque socket error a bare destroy gave.
3031
+ const declared = Number(req.headers["content-length"] ?? "");
3032
+ if (Number.isFinite(declared) && declared > BODY_CAP) {
3033
+ respond(413, { error: "request body too large (1MB cap)" });
3034
+ req.resume();
3035
+ return;
3036
+ }
3037
+ let raw = "";
3038
+ let tooLarge = false;
3039
+ req.on("data", (chunk) => {
3040
+ if (tooLarge)
3041
+ return; // keep consuming (draining) but stop accumulating
3042
+ raw += chunk;
3043
+ if (raw.length > BODY_CAP) {
3044
+ tooLarge = true;
3045
+ respond(413, { error: "request body too large (1MB cap)" });
3046
+ }
3047
+ });
3048
+ req.on("end", () => {
3049
+ if (tooLarge)
3050
+ return;
3051
+ void (async () => {
3052
+ let body;
3053
+ try {
3054
+ body = raw ? JSON.parse(raw) : {};
3055
+ }
3056
+ catch {
3057
+ respond(400, { error: "invalid JSON body" });
3058
+ return;
3059
+ }
3060
+ try {
3061
+ if (req.url === "/mark")
3062
+ respond(200, await handleMark(body));
3063
+ else if (req.url === "/chapter")
3064
+ respond(200, handleChapter(body));
3065
+ else
3066
+ respond(404, { error: "not found" });
3067
+ }
3068
+ catch (e) {
3069
+ respond(500, { error: e.message });
3070
+ }
3071
+ })();
3072
+ });
3073
+ });
3074
+ // Tight timeouts (Node defaults are minutes) so a wedged local client can't
3075
+ // pin daemon sockets open. headersTimeout must be ≤ requestTimeout.
3076
+ controlServer.requestTimeout = 10_000;
3077
+ controlServer.headersTimeout = 10_000;
3078
+ try {
3079
+ await new Promise((resolveBind, rejectBind) => {
3080
+ controlServer.on("error", rejectBind);
3081
+ controlServer.listen(0, "127.0.0.1", () => resolveBind());
3082
+ });
3083
+ const addr = controlServer.address();
3084
+ controlPort = typeof addr === "object" && addr ? addr.port : 0;
3085
+ log(`control endpoint listening on 127.0.0.1:${controlPort}`);
3086
+ }
3087
+ catch (e) {
3088
+ log(`control endpoint failed to bind (${e.message}) — marks will use the file fallback`);
3089
+ controlServer = null;
3090
+ controlPort = 0;
3091
+ }
2301
3092
  recordStart = Date.now();
2302
- save({ state: "recording", recordStartEpochMs: recordStart, cdpUrl, cdpHttpUrl });
3093
+ save({
3094
+ state: "recording",
3095
+ recordStartEpochMs: recordStart,
3096
+ cdpUrl,
3097
+ cdpHttpUrl,
3098
+ ...(controlPort ? { controlPort, controlToken } : {}),
3099
+ });
2303
3100
  try {
2304
3101
  await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
2305
3102
  }
@@ -2310,6 +3107,12 @@ async function runSessionDaemon(file) {
2310
3107
  let stopReason = "stop";
2311
3108
  for (;;) {
2312
3109
  await page.waitForTimeout(400);
3110
+ // A failed --fail-mode=abort assertion (set by the control handler) discards
3111
+ // the session just like a control-file abort.
3112
+ if (controlSignal === "abort") {
3113
+ stopReason = "abort";
3114
+ break;
3115
+ }
2313
3116
  let control = null;
2314
3117
  try {
2315
3118
  control = JSON.parse(readFileSync(state.controlPath, "utf8"));
@@ -2356,23 +3159,41 @@ async function runSessionDaemon(file) {
2356
3159
  const videoPath = await video.path();
2357
3160
  await browser.close().catch(() => { });
2358
3161
  browser = null;
2359
- // Merge the agent's marks (written live by `clipy mark` with its own
2360
- // clock) with the [auto] instrumentation marks.
2361
- const agentMarks = [];
3162
+ // Merge marks from three sources: the file (fallback path, written by
3163
+ // `clipy mark` when the control endpoint was unreachable), the daemon-side
3164
+ // marks (control endpoint + in-page bindings, already assertion-annotated),
3165
+ // and the [auto] instrumentation marks.
3166
+ const fileMarks = [];
2362
3167
  try {
2363
3168
  for (const line of readFileSync(state.marksPath, "utf8").split("\n")) {
2364
3169
  if (!line.trim())
2365
3170
  continue;
2366
3171
  const m = JSON.parse(line);
2367
3172
  if (typeof m.tMs === "number" && typeof m.text === "string" && m.text.trim()) {
2368
- agentMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
3173
+ fileMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
2369
3174
  }
2370
3175
  }
2371
3176
  }
2372
3177
  catch {
2373
3178
  // no marks file — fine
2374
3179
  }
2375
- const notes = [...agentMarks, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
3180
+ let notes = [...fileMarks, ...daemonMarks, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
3181
+ // If any assertions ran, prepend a 0ms verification summary so it LEADS the
3182
+ // transcript and the .md context (a stable sort keeps it ahead of other 0ms
3183
+ // marks). This is the "recordings are evidence" headline.
3184
+ if (assertRan > 0) {
3185
+ notes.unshift({
3186
+ startMs: 0,
3187
+ text: `[verification] ${assertRan} assertion(s): ${assertPassed} passed, ${assertFailed} failed`,
3188
+ });
3189
+ notes.sort((a, b) => a.startMs - b.startMs);
3190
+ }
3191
+ // Server limit: cap the merged set at 200 marks (the verification note sorts
3192
+ // to 0ms so it always survives the slice).
3193
+ if (notes.length > 200) {
3194
+ log(`mark limit: merged ${notes.length} marks — keeping the first 200 (dropped ${notes.length - 200})`);
3195
+ notes = notes.slice(0, 200);
3196
+ }
2376
3197
  save({ state: "uploading" });
2377
3198
  const uploaded = await uploadWebmToClipy(ctx, {
2378
3199
  videoPath,
@@ -2408,6 +3229,8 @@ async function runSessionDaemon(file) {
2408
3229
  process.exitCode = 1;
2409
3230
  }
2410
3231
  finally {
3232
+ if (controlServer)
3233
+ controlServer.close();
2411
3234
  if (browser)
2412
3235
  await browser.close().catch(() => { });
2413
3236
  }
@@ -2501,7 +3324,7 @@ async function cmdAgents(ctx, sub, targetRaw, json) {
2501
3324
  // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
2502
3325
  // contract changes.
2503
3326
  // ---------------------------------------------------------------------------
2504
- const GUIDE_SCHEMA_VERSION = 3;
3327
+ const GUIDE_SCHEMA_VERSION = 5;
2505
3328
  function cmdGuide(json) {
2506
3329
  if (!json) {
2507
3330
  process.stdout.write(HELP);
@@ -2551,10 +3374,12 @@ function cmdGuide(json) {
2551
3374
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
2552
3375
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
2553
3376
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
2554
- cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--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. With --source mac-screen: records the real screen via the Clipy Mac app (--type not yet applied on mac); --window '<title|app|id>' or --display <id> target one window/display (ids from clipy sources)", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--width", "--height", "--wait", "--source", "--window", "--display"]),
2555
- cmdDoc("session", "clipy session <start|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen] [--window w] [--display d] [--expose-cdp]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). --window/--display (with --source mac-screen) record one window/display. --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", ["--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp"]),
2556
- cmdDoc("mark", "clipy mark \"<text>\"", "Drop a live-timestamped note into the active session"),
2557
- cmdDoc("doctor", "clipy doctor [--json]", "One-shot health check: API key + whoami round-trip, Mac agent bridge (exists/parses/pid/appVersion>=" + MIN_BRIDGE_APP_VERSION + "), Playwright resolvability (and where it resolved from), and install mode (npx/global/local) — each a pass/warn/fail with a fix hint; exits non-zero if any check fails"),
3377
+ 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>. With --source mac-screen: records the real screen via the Clipy Mac app (--type not yet applied on mac; auth flags rejected — the screen is already logged in); --window '<title|app|id>' or --display <id> target one window/display (ids from clipy sources). --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
3378
+ cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen] [--window w] [--display d] [--expose-cdp] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). --window/--display (with --source mac-screen) record one window/display. --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), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code — the crash-safe wrapper so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--expose-cdp", "--storage-state", "--cookie", "--local-storage", "--init-script", "--json"]),
3379
+ cmdDoc("mark", "clipy mark \"<text>\" [--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. ASSERTION MARKS make the note evidence instead of a claim: --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 ✓ <observed>]', fail ⇒ '<text> [ASSERT ✗ 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 assertions ran, a leading 0ms '[verification] N assertion(s): P passed, F failed' note is prepended. --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.", ["--assert-selector", "--assert-text", "--assert-url", "--fail-mode", "--at", "--ago", "--json"]),
3380
+ 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"]),
3381
+ cmdDoc("doctor", "clipy doctor [--json]", "One-shot health check: 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), and install mode (npx/global/local) — each a pass/warn/fail with a fix hint; exits non-zero if any check fails", ["--json"]),
3382
+ 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"]),
2558
3383
  cmdDoc("sources", "clipy sources [--json]", "List displays + windows the Clipy Mac app can capture — ids feed --window/--display"),
2559
3384
  cmdDoc("agents", "clipy agents <status|install|uninstall> <claude|codex|cursor>", "Install the bundled Clipy skill for a coding agent; install triggers a browser login first when no key is configured (interactive terminals only)"),
2560
3385
  cmdDoc("guide", "clipy guide --json", "This manifest"),
@@ -2567,7 +3392,13 @@ function cmdGuide(json) {
2567
3392
  "Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
2568
3393
  "--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.",
2569
3394
  "--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.",
3395
+ "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.",
3396
+ "clipy chapter \"<label>\" splits one recording into BEFORE/AFTER sections for PR-review-style demos: record the base branch, `clipy chapter \"AFTER — fix applied\"`, swap branches + restart, record the fix. One video carries both states.",
3397
+ "clipy session run [start flags] -- <command…> is the crash-safe wrapper: it starts a session, runs your driver command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp), and guarantees cleanup — exit 0 uploads, any non-zero exit or signal discards and propagates the code. Use it so a crashing driver never records dead air to the max ceiling.",
3398
+ "clipy mark --at <sec> stamps at an absolute recording time; --ago <sec> stamps N seconds before now — a `clipy mark` spawn lands ~100-300ms late, so backdate to align a mark with the state it describes. When driving over --expose-cdp, call window.__clipyMark(\"text\") / window.__clipyChapter(\"label\") IN-PAGE (page.evaluate) to emit marks/chapters with zero spawn latency; while CDP is exposed the page's own scripts can call these too (within the existing --expose-cdp trust model).",
2570
3399
  "session --expose-cdp (web, opt-in) publishes a CDP endpoint (cdpHttpUrl) in `session start`/`session status` output and the 0600 session state file; connect with playwright.connectOverCDP() to drive the recorded page. Off by default (any local process could attach); CLIPY_DISABLE_CDP=1 forces it off.",
3400
+ "Driving an --expose-cdp session: connect with playwright.connectOverCDP(cdpHttpUrl); the recorded page is browser.contexts()[0].pages()[0] (a fresh context/page you open is NOT captured); page.viewportSize() is null over a CDP attach; resize with a CDP session's Emulation.setDeviceMetricsOverride, not setViewportSize. Your own driver script resolves Playwright from its own cwd — run it as NODE_PATH=$(clipy playwright-path) node driver.js if require('playwright') can't find it.",
3401
+ "Auth for headless web capture (record + session start): --storage-state <playwright storageState JSON> is passed straight to Playwright's newContext; --cookie / --local-storage / --init-script are applied to the context BEFORE the first navigation, so a logged-in SPA's route guard sees the state on first paint (seeding it after navigating loses that race). --cookie without a Domain is url-scoped to the target; with a Domain it is domain-scoped. --local-storage pairs are origin-guarded to the target. All four are web-only and are rejected on --source mac-screen, which records the real, already-signed-in screen. The storage-state file may hold live credentials; the CLI never prints its contents and the session state file that carries these specs is chmod 0600.",
2571
3402
  "clipy record gates its capture clock on the first non-blank frame (up to a 10s cap, then starts anyway) so notes aren't anchored to a still-compiling t=0.",
2572
3403
  "Run `clipy doctor` first when record/session or --source mac-screen fails — it names the exact missing piece (key, bridge socket/handshake/version, Playwright, install mode).",
2573
3404
  "Public recordings have an unauthenticated context document at https://clipy.online/video/<id>.md.",
@@ -2621,9 +3452,24 @@ async function cmdTranscriptReplace(ctx, id, file) {
2621
3452
  // ---------------------------------------------------------------------------
2622
3453
  // Entry
2623
3454
  // ---------------------------------------------------------------------------
3455
+ /** Parse a --at/--ago seconds value (fractional allowed, must be ≥ 0). */
3456
+ function parseSeconds(v, flag) {
3457
+ const n = Number(v);
3458
+ if (!Number.isFinite(n) || n < 0)
3459
+ die(`${flag} must be a non-negative number of seconds`, 2);
3460
+ return n;
3461
+ }
2624
3462
  async function main() {
3463
+ // Split on the first `--` ourselves so `session run … -- <cmd> [--child-flags]`
3464
+ // never feeds the child's own flags to parseArgs (strict:false would otherwise
3465
+ // fold them into `values`). Everything after `--` is the child command verbatim;
3466
+ // for every other command childArgv is simply unused.
3467
+ const rawArgv = process.argv.slice(2);
3468
+ const ddIndex = rawArgv.indexOf("--");
3469
+ const childArgv = ddIndex >= 0 ? rawArgv.slice(ddIndex + 1) : [];
3470
+ const parseArgv = ddIndex >= 0 ? rawArgv.slice(0, ddIndex) : rawArgv;
2625
3471
  const { values, positionals } = parseArgs({
2626
- args: process.argv.slice(2),
3472
+ args: parseArgv,
2627
3473
  allowPositionals: true,
2628
3474
  strict: false,
2629
3475
  options: {
@@ -2653,7 +3499,17 @@ async function main() {
2653
3499
  window: { type: "string" },
2654
3500
  display: { type: "string" },
2655
3501
  type: { type: "string" },
3502
+ "assert-selector": { type: "string" },
3503
+ "assert-text": { type: "string" },
3504
+ "assert-url": { type: "string" },
3505
+ "fail-mode": { type: "string" },
3506
+ at: { type: "string" },
3507
+ ago: { type: "string" },
2656
3508
  "expose-cdp": { type: "boolean", default: false },
3509
+ "storage-state": { type: "string" },
3510
+ "init-script": { type: "string" },
3511
+ cookie: { type: "string", multiple: true },
3512
+ "local-storage": { type: "string", multiple: true },
2657
3513
  width: { type: "string" },
2658
3514
  height: { type: "string" },
2659
3515
  wait: { type: "boolean", default: false },
@@ -2685,6 +3541,21 @@ async function main() {
2685
3541
  const n = parseInt(String(v ?? ""), 10);
2686
3542
  return Number.isFinite(n) && n > 0 ? n : dflt;
2687
3543
  };
3544
+ // Auth-capture flags seed a logged-in session into headless web capture; they
3545
+ // don't apply to --source mac-screen (which records the real, already-signed-in
3546
+ // screen). Resolve the file paths to absolute so the detached daemon — spawned
3547
+ // without an explicit cwd — reads the same files the parent validated.
3548
+ const authFlagsPresent = Boolean(values["storage-state"] ||
3549
+ values["init-script"] ||
3550
+ values.cookie?.length ||
3551
+ values["local-storage"]?.length);
3552
+ const authCapture = () => ({
3553
+ storageStatePath: values["storage-state"] ? resolve(String(values["storage-state"])) : undefined,
3554
+ initScriptPath: values["init-script"] ? resolve(String(values["init-script"])) : undefined,
3555
+ cookieSpecs: values.cookie ?? [],
3556
+ localStorageSpecs: values["local-storage"] ?? [],
3557
+ });
3558
+ const macAuthGuard = "auth state applies to headless web capture — --source mac-screen records the real, already-logged-in screen";
2688
3559
  switch (command) {
2689
3560
  case "login":
2690
3561
  await cmdLogin(ctx, {
@@ -2772,6 +3643,9 @@ async function main() {
2772
3643
  case "doctor":
2773
3644
  await cmdDoctor(ctx, json);
2774
3645
  return;
3646
+ case "playwright-path":
3647
+ await cmdPlaywrightPath(json);
3648
+ return;
2775
3649
  case "agents":
2776
3650
  await cmdAgents(ctx, rest[0], rest[1], json);
2777
3651
  return;
@@ -2812,6 +3686,8 @@ async function main() {
2812
3686
  if (values.window && values.display) {
2813
3687
  die("--window and --display are mutually exclusive — pick one capture source", 2);
2814
3688
  }
3689
+ if (source === "mac-screen" && authFlagsPresent)
3690
+ die(macAuthGuard, 2);
2815
3691
  const recordingKind = values.type ? requireRecordingKind(String(values.type)) : undefined;
2816
3692
  if (source === "mac-screen") {
2817
3693
  const noteFlags = values.note ?? [];
@@ -2867,12 +3743,16 @@ async function main() {
2867
3743
  height: num(values.height, 720),
2868
3744
  wait: Boolean(values.wait),
2869
3745
  json,
3746
+ auth: authCapture(),
2870
3747
  });
2871
3748
  return;
2872
3749
  }
2873
3750
  case "session": {
2874
3751
  const sub = rest[0];
2875
- if (sub === "start") {
3752
+ // Shared by `start` and `run`: validate the capture flags and build the
3753
+ // cmdSessionStart opts. `positionalUrl` is rest[1] for `start` (session
3754
+ // start <url>) — `run` has no positional url, only --url.
3755
+ const buildStartOpts = (positionalUrl) => {
2876
3756
  const source = String(values.source ?? "web");
2877
3757
  if (source !== "web" && source !== "mac-screen") {
2878
3758
  die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
@@ -2883,11 +3763,13 @@ async function main() {
2883
3763
  if (values.window && values.display) {
2884
3764
  die("--window and --display are mutually exclusive — pick one capture source", 2);
2885
3765
  }
2886
- const url = values.url?.trim() || rest[1];
3766
+ if (source === "mac-screen" && authFlagsPresent)
3767
+ die(macAuthGuard, 2);
3768
+ const url = values.url?.trim() || positionalUrl;
2887
3769
  if (!url && source === "web") {
2888
3770
  die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen]", 2);
2889
3771
  }
2890
- await cmdSessionStart(ctx, {
3772
+ return {
2891
3773
  url: url || "mac-screen",
2892
3774
  window: values.window?.trim() || undefined,
2893
3775
  display: values.display?.trim() || undefined,
@@ -2899,9 +3781,18 @@ async function main() {
2899
3781
  width: num(values.width, 1280),
2900
3782
  height: num(values.height, 720),
2901
3783
  json,
2902
- source,
3784
+ source: source,
2903
3785
  exposeCdp: Boolean(values["expose-cdp"]),
2904
- });
3786
+ auth: authCapture(),
3787
+ };
3788
+ };
3789
+ if (sub === "start") {
3790
+ await cmdSessionStart(ctx, buildStartOpts(rest[1]));
3791
+ return;
3792
+ }
3793
+ if (sub === "run") {
3794
+ // Everything after `--` is the command; start flags come before it.
3795
+ await cmdSessionRun(ctx, buildStartOpts(undefined), childArgv);
2905
3796
  return;
2906
3797
  }
2907
3798
  if (sub === "stop") {
@@ -2916,14 +3807,47 @@ async function main() {
2916
3807
  await cmdSessionStatus(json);
2917
3808
  return;
2918
3809
  }
2919
- die("usage: clipy session <start|stop|abort|status>", 2);
3810
+ die("usage: clipy session <start|run|stop|abort|status>", 2);
2920
3811
  return;
2921
3812
  }
2922
3813
  case "mark": {
2923
3814
  const text = rest.join(" ").trim();
2924
- if (!text)
2925
- die('usage: clipy mark "<what just happened>"', 2);
2926
- await cmdMark(text, json);
3815
+ if (!text) {
3816
+ die('usage: clipy mark "<what just happened>" [--assert-selector <css> [--assert-text <substr>]] [--assert-url <glob>] [--fail-mode warn|abort] [--at <sec>|--ago <sec>]', 2);
3817
+ }
3818
+ const selector = values["assert-selector"]?.trim() || undefined;
3819
+ const expectText = values["assert-text"]; // exact, not trimmed
3820
+ const urlGlob = values["assert-url"]?.trim() || undefined;
3821
+ if (expectText != null && !selector) {
3822
+ die("--assert-text needs --assert-selector (the substring is checked against that element's text)", 2);
3823
+ }
3824
+ const failModeRaw = values["fail-mode"]?.trim().toLowerCase();
3825
+ if (failModeRaw && failModeRaw !== "warn" && failModeRaw !== "abort") {
3826
+ die("--fail-mode must be warn or abort", 2);
3827
+ }
3828
+ const hasAssert = Boolean(selector || (expectText != null && expectText !== "") || urlGlob);
3829
+ if (failModeRaw && !hasAssert) {
3830
+ die("--fail-mode only applies with an assertion (--assert-selector / --assert-text / --assert-url)", 2);
3831
+ }
3832
+ if (values.at != null && values.ago != null)
3833
+ die("--at and --ago are mutually exclusive", 2);
3834
+ const atSec = values.at != null ? parseSeconds(String(values.at), "--at") : undefined;
3835
+ const agoSec = values.ago != null ? parseSeconds(String(values.ago), "--ago") : undefined;
3836
+ await cmdMark(text, json, {
3837
+ atSec,
3838
+ agoSec,
3839
+ assert: hasAssert
3840
+ ? { selector, expectText, urlGlob, failMode: failModeRaw || "warn" }
3841
+ : undefined,
3842
+ });
3843
+ return;
3844
+ }
3845
+ case "chapter": {
3846
+ const label = rest.join(" ").trim();
3847
+ if (!label) {
3848
+ die('usage: clipy chapter "<label>" e.g. clipy chapter "AFTER — fix applied"', 2);
3849
+ }
3850
+ await cmdChapter(label, json);
2927
3851
  return;
2928
3852
  }
2929
3853
  case "__session-daemon": {