@clipy/cli 0.13.1 → 0.15.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
@@ -27,6 +27,8 @@ import { createServer } from "node:net";
27
27
  import { createServer as createHttpServer } from "node:http";
28
28
  import { CLIPY_SKILL_MD } from "./skill.js";
29
29
  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";
30
32
  import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
31
33
  import { openUrl } from "./openUrl.js";
32
34
  import { cmdContextImport } from "./context/importCmd.js";
@@ -34,6 +36,7 @@ import { cmdContextRead } from "./context/readCmd.js";
34
36
  import { errorEnvelope } from "./context/errors.js";
35
37
  import { supportsWebp } from "./context/ffmpeg.js";
36
38
  import { renderProofFrames } from "./proofFrames.js";
39
+ import { waitForAgentContext } from "./agentReadiness.js";
37
40
  import { BridgeUnavailableError, bridgeRequest, inspectBridge, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, probeSocketOpenable, probeBridgeHandshake, bridgeInfoFromFile, bridgeAppOutdated, MIN_BRIDGE_APP_VERSION, describeWindow, describeDisplay, } from "./macBridge.js";
38
41
  // Exit quietly when stdout/stderr close early (e.g. `clipy list | head`).
39
42
  for (const stream of [process.stdout, process.stderr]) {
@@ -151,12 +154,17 @@ function requireKey(ctx) {
151
154
  return ctx.apiKey;
152
155
  die(`no API key. Run ${c.bold("clipy login")} to approve this device in your browser, or set CLIPY_API_KEY.`);
153
156
  }
154
- async function api(ctx, path, accept = "application/json") {
157
+ async function api(ctx, path, accept = "application/json", deadlineSignal) {
155
158
  const key = requireKey(ctx);
156
159
  const controller = new AbortController();
160
+ const abortForDeadline = () => controller.abort();
161
+ if (deadlineSignal?.aborted)
162
+ controller.abort();
163
+ else
164
+ deadlineSignal?.addEventListener("abort", abortForDeadline, { once: true });
157
165
  const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
158
166
  try {
159
- return await fetch(`${ctx.apiUrl}${path}`, {
167
+ const response = await fetch(`${ctx.apiUrl}${path}`, {
160
168
  headers: {
161
169
  Authorization: `Bearer ${key}`,
162
170
  Accept: accept,
@@ -164,15 +172,24 @@ async function api(ctx, path, accept = "application/json") {
164
172
  },
165
173
  signal: controller.signal,
166
174
  });
175
+ const body = await response.arrayBuffer();
176
+ return new Response(body.byteLength > 0 ? body : null, {
177
+ status: response.status,
178
+ statusText: response.statusText,
179
+ headers: response.headers,
180
+ });
167
181
  }
168
182
  catch (e) {
169
183
  if (e.name === "AbortError") {
184
+ if (deadlineSignal?.aborted)
185
+ throw e;
170
186
  die(`request timed out after ${FETCH_TIMEOUT_MS / 1000}s (${path})`);
171
187
  }
172
188
  throw e;
173
189
  }
174
190
  finally {
175
191
  clearTimeout(timer);
192
+ deadlineSignal?.removeEventListener("abort", abortForDeadline);
176
193
  }
177
194
  }
178
195
  async function apiJson(ctx, path) {
@@ -401,7 +418,16 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
401
418
  process could attach — CLIPY_DISABLE_CDP=1 forces off).
402
419
  Accepts the same auth flags as record
403
420
  (--storage-state/--cookie/--local-storage/--init-script)
404
- and --json (returns cdpUrl/cdpHttpUrl)
421
+ and --json (returns cdpUrl/cdpHttpUrl).
422
+ --source chrome-for-clipy records ONE TAB (with
423
+ tab audio) inside the persistent Chrome for
424
+ Clipy instance (started automatically; sign in
425
+ once with clipy chrome start). CDP is always
426
+ published there, so drivers attach to the same
427
+ browser being recorded. --source chrome-extension
428
+ records the same way through the Clipy extension
429
+ installed there (no marks yet); run
430
+ clipy chrome setup once first
405
431
  session run [start flags] -- <command …>
406
432
  Start a session, run the command (inherited
407
433
  stdio), then GUARANTEE cleanup: exit 0 uploads,
@@ -431,17 +457,30 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
431
457
  session status Show the active session's state
432
458
 
433
459
  ${c.bold("AGENTS")}
434
- setup [claude|codex|cursor|windsurf|opencode]
460
+ setup [claude|codex|cursor|windsurf|opencode] [--with-browser]
435
461
  Wire Clipy into a coding agent in ONE command:
436
462
  sign in, install the skill, and register the MCP
437
463
  server in that agent's own config. Detects the
438
464
  agent it is running inside when you omit the name.
465
+ --with-browser also starts Chrome for Clipy (the
466
+ agent-owned automation browser) and installs its
467
+ launcher on macOS; a browser failure never fails
468
+ setup.
439
469
  ${c.dim("Published instructions: clipy.online/agent-setup/prompt.md")}
440
470
  agents install <claude|codex|cursor|windsurf|opencode>
441
471
  Skill only — no MCP, no login prompt beyond the
442
472
  first-run one. Use ${c.bold("setup")} unless you deliberately
443
473
  want just the skill file
444
474
  agents status | uninstall <t> Show / remove installed skills
475
+ chrome <setup|start|stop|status|install-app> [--port <n>]
476
+ "Chrome for Clipy": a dedicated, persistent
477
+ automation browser with CDP exposed, picker-free
478
+ tab capture (retitle a tab with the marker), and
479
+ background throttling disabled. Sign in once;
480
+ the profile persists. setup walks you through
481
+ installing the Clipy extension and signing in
482
+ there, then waits until it is ready. install-app
483
+ saves a named macOS launcher in ~/Applications
445
484
  doctor [--json] Health check: API key, Mac agent bridge,
446
485
  Playwright, and install mode — with fix hints
447
486
  guide --json Machine-readable manifest: every command,
@@ -808,7 +847,15 @@ async function cmdMoments(ctx, id, json) {
808
847
  async function cmdContext(ctx, id) {
809
848
  const publicId = normalizeId(id, ctx);
810
849
  const pid = encodeURIComponent(publicId);
811
- const res = await api(ctx, `/api/agent-context/${pid}`, "text/markdown, text/plain, application/json");
850
+ const waited = await waitForAgentContext((signal) => api(ctx, `/api/agent-context/${pid}`, "text/markdown, text/plain, application/json", signal), {
851
+ timeoutMs: 60_000,
852
+ now: Date.now,
853
+ sleep: (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
854
+ });
855
+ const res = waited.response;
856
+ if (waited.timedOut) {
857
+ process.stderr.write(`${c.yellow("!")} recording is still preparing; returning the latest available context\n`);
858
+ }
812
859
  const text = await res.text();
813
860
  if (!res.ok) {
814
861
  let msg = `Clipy API error ${res.status}`;
@@ -1485,8 +1532,11 @@ async function ingestPostChunk(ctx, recordingId, uploadToken, partNumber, bytes,
1485
1532
  for (let attempt = 1; attempt <= 4; attempt++) {
1486
1533
  // Copy the window into a standalone ArrayBuffer: it satisfies BlobPart
1487
1534
  // under strict lib settings (a subarray's .buffer is ArrayBufferLike) and
1488
- // makes the snapshot independent of the reused read buffer.
1489
- const part = bytes.slice().buffer;
1535
+ // makes the snapshot independent of the reused read buffer. Not
1536
+ // bytes.slice(): on a Node Buffer that is a view, so its .buffer is the
1537
+ // whole 4 MiB read buffer, and every part would carry stale bytes and
1538
+ // uninitialized memory past bytes.length.
1539
+ const part = new Uint8Array(bytes).buffer;
1490
1540
  const form = new FormData();
1491
1541
  form.append("recordingId", recordingId);
1492
1542
  form.append("uploadToken", uploadToken);
@@ -2708,6 +2758,9 @@ function writeSessionState(file, state) {
2708
2758
  renameSync(tmp, file);
2709
2759
  }
2710
2760
  function pidAlive(pid) {
2761
+ // kill(0, 0) signals our own process group and "succeeds".
2762
+ if (!Number.isInteger(pid) || pid <= 0)
2763
+ return false;
2711
2764
  try {
2712
2765
  process.kill(pid, 0);
2713
2766
  return true;
@@ -3078,7 +3131,126 @@ function cdpDriverSnippet(cdpHttpUrl) {
3078
3131
  c.dim(` resolve playwright for your script: NODE_PATH=$(clipy playwright-path) node driver.js`),
3079
3132
  ].join("\n");
3080
3133
  }
3134
+ function extensionSessionPort(state) {
3135
+ return state.chromePort ?? DEFAULT_CDP_PORT;
3136
+ }
3137
+ function extensionSessionId(state) {
3138
+ if (!state.extensionRecordingId) {
3139
+ die("session file is missing the extension recording id. Abort it with `clipy session abort` and restart");
3140
+ }
3141
+ return state.extensionRecordingId;
3142
+ }
3143
+ /** `--source chrome-extension`: the Clipy extension inside Chrome for Clipy
3144
+ * records and uploads the tab itself. No daemon; the session file only routes
3145
+ * stop/abort/status to the extension, like the Mac bridge path. */
3146
+ async function cmdSessionStartExtension(opts) {
3147
+ let target;
3148
+ try {
3149
+ target = new URL(opts.url);
3150
+ }
3151
+ catch {
3152
+ die(`invalid --url: ${opts.url}`, 2);
3153
+ }
3154
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
3155
+ die(`--url must be http(s), got ${target.protocol}`, 2);
3156
+ }
3157
+ if (opts.userDataDir) {
3158
+ die("--user-data-dir doesn't apply to --source chrome-extension; it records in the persistent Chrome for Clipy profile", 2);
3159
+ }
3160
+ if ((opts.name || opts.recordingKind) && !opts.json) {
3161
+ process.stderr.write(`${c.yellow("note: --name/--type are not applied to --source chrome-extension recordings yet")}\n`);
3162
+ }
3163
+ const file = sessionFilePath(process.cwd());
3164
+ const existing = readSessionState(file);
3165
+ if (existing && sessionIsActive(existing)) {
3166
+ die(`a recording session is already active in this workspace (started for ${existing.url}).\n` +
3167
+ `Finish it with \`clipy session stop\` or discard it with \`clipy session abort\`.`);
3168
+ }
3169
+ if (existing)
3170
+ cleanupSessionFiles(existing, file);
3171
+ const chromium = await loadChromium();
3172
+ const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
3173
+ let started;
3174
+ try {
3175
+ started = await startExtensionRecording(chromium, {
3176
+ home: homedir(),
3177
+ env: process.env,
3178
+ platform: process.platform,
3179
+ port: DEFAULT_CDP_PORT,
3180
+ targetUrl: target.href,
3181
+ maxSec,
3182
+ log: (m) => {
3183
+ if (!opts.json)
3184
+ process.stderr.write(`${c.dim(m)}\n`);
3185
+ },
3186
+ });
3187
+ }
3188
+ catch (error) {
3189
+ die(`could not start the extension recording: ${error instanceof Error ? error.message : String(error)}`);
3190
+ }
3191
+ // The extension is recording from here on: record the session before
3192
+ // anything else can fail, or nothing could stop or collect it.
3193
+ const dir = sessionDir();
3194
+ const session = {
3195
+ version: 1,
3196
+ kind: "chrome-extension",
3197
+ chromePort: started.port,
3198
+ extensionRecordingId: started.recordingId,
3199
+ // Chrome for Clipy's pid: the session is alive only while that browser is.
3200
+ pid: started.chromePid,
3201
+ cwd: process.cwd(),
3202
+ url: started.pageUrl || target.href,
3203
+ maxSec,
3204
+ width: 0,
3205
+ height: 0,
3206
+ state: "recording",
3207
+ recordStartEpochMs: started.startedAtEpochMs,
3208
+ cdpHttpUrl: started.cdpHttpUrl,
3209
+ marksPath: join(dir, "unused"),
3210
+ controlPath: join(dir, "unused"),
3211
+ logPath: join(dir, "unused"),
3212
+ tmpDir: join(dir, "unused"),
3213
+ };
3214
+ try {
3215
+ writeSessionState(file, session);
3216
+ markExtensionRecording(homedir(), {
3217
+ recordingId: started.recordingId,
3218
+ untilEpochMs: started.startedAtEpochMs + maxSec * 1000,
3219
+ });
3220
+ }
3221
+ catch (error) {
3222
+ await abortExtensionRecording(chromium, {
3223
+ port: started.port,
3224
+ env: process.env,
3225
+ recordingId: started.recordingId,
3226
+ }).catch(() => { });
3227
+ die(`could not save the session, so the recording was cancelled: ${error instanceof Error ? error.message : String(error)}`);
3228
+ }
3229
+ const cdpUrl = (await discoverCdpWsUrl(started.port).catch(() => null)) ?? undefined;
3230
+ if (cdpUrl)
3231
+ writeSessionState(file, { ...session, cdpUrl });
3232
+ if (opts.json) {
3233
+ printJson({
3234
+ state: "recording",
3235
+ captureMode: "chrome-extension",
3236
+ url: session.url,
3237
+ maxSec,
3238
+ sessionFile: file,
3239
+ extensionVersion: started.extensionVersion,
3240
+ cdpUrl: cdpUrl ?? null,
3241
+ cdpHttpUrl: started.cdpHttpUrl,
3242
+ });
3243
+ return;
3244
+ }
3245
+ 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.cdpHttpUrl} ${c.dim("(the tab whose url() is the one above)")}\n` +
3247
+ `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
3248
+ }
3081
3249
  async function cmdSessionStart(ctx, opts) {
3250
+ if (opts.source === "chrome-extension") {
3251
+ await cmdSessionStartExtension(opts);
3252
+ return;
3253
+ }
3082
3254
  if (opts.source === "mac-screen") {
3083
3255
  const file = sessionFilePath(process.cwd());
3084
3256
  const existing = readSessionState(file);
@@ -3143,11 +3315,24 @@ async function cmdSessionStart(ctx, opts) {
3143
3315
  if (target.protocol !== "http:" && target.protocol !== "https:") {
3144
3316
  die(`--url must be http(s), got ${target.protocol}`, 2);
3145
3317
  }
3318
+ const isChromeForClipy = opts.source === "chrome-for-clipy";
3319
+ let chromePort = DEFAULT_CDP_PORT;
3320
+ if (isChromeForClipy && opts.userDataDir) {
3321
+ die("--user-data-dir doesn't apply to --source chrome-for-clipy; it records the persistent Chrome for Clipy profile", 2);
3322
+ }
3146
3323
  validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/daemonizing
3147
3324
  if (opts.userDataDir)
3148
3325
  validateUserDataDir(opts.userDataDir, opts.profileDirectory);
3149
3326
  const key = requireKey(ctx);
3150
3327
  await loadChromium(); // fail fast with install instructions before daemonizing
3328
+ // Chrome for Clipy is started HERE, in the parent, so a missing Chrome or a
3329
+ // dead CDP port is a loud immediate error rather than a daemon-log mystery.
3330
+ if (isChromeForClipy) {
3331
+ const chromeUp = await startChromeForClipy(homedir(), process.env, process.platform, DEFAULT_CDP_PORT);
3332
+ if (!chromeUp.ok)
3333
+ die(`Chrome for Clipy failed to start: ${chromeUp.error}`);
3334
+ chromePort = chromeUp.state.port;
3335
+ }
3151
3336
  sweepStaleProfileCopies();
3152
3337
  const file = sessionFilePath(process.cwd());
3153
3338
  const existing = readSessionState(file);
@@ -3171,6 +3356,7 @@ async function cmdSessionStart(ctx, opts) {
3171
3356
  mkdirSync(dir, { recursive: true });
3172
3357
  const state = {
3173
3358
  version: 1,
3359
+ ...(isChromeForClipy ? { kind: "chrome-for-clipy", chromePort } : {}),
3174
3360
  pid: 0,
3175
3361
  cwd: process.cwd(),
3176
3362
  url: target.href,
@@ -3211,8 +3397,10 @@ async function cmdSessionStart(ctx, opts) {
3211
3397
  child.unref();
3212
3398
  // Wait for the daemon to actually start recording (first Chromium launch on
3213
3399
  // a cold cache can take a while) so the agent's next command lands inside a
3214
- // live recording, not a race.
3215
- const deadline = Date.now() + 60_000;
3400
+ // live recording, not a race. chrome-for-clipy needs more headroom: it fully
3401
+ // loads the target page BEFORE capture (marker selection needs a real page),
3402
+ // and a heavy page can spend 30s on `load` alone.
3403
+ const deadline = Date.now() + (isChromeForClipy ? 150_000 : 60_000);
3216
3404
  for (;;) {
3217
3405
  const s = readSessionState(file);
3218
3406
  if (s?.state === "recording")
@@ -3283,6 +3471,9 @@ async function cmdMark(text, json, opts) {
3283
3471
  const hasAssert = !!opts.assert;
3284
3472
  const attest = opts.attest;
3285
3473
  const backdated = opts.atSec != null || opts.agoSec != null;
3474
+ if (state.kind === "chrome-extension") {
3475
+ die("marks are not supported for --source chrome-extension recordings yet; use --source chrome-for-clipy when you need marks", 2);
3476
+ }
3286
3477
  if (state.kind === "mac") {
3287
3478
  // The Mac app records the real screen — there is no Clipy-owned page to probe,
3288
3479
  // so Clipy-EVALUATED assertions can't run here. Driver-attested marks CAN: the
@@ -3409,6 +3600,9 @@ async function cmdMark(text, json, opts) {
3409
3600
  async function cmdChapter(label, json) {
3410
3601
  const { file, state } = requireSession();
3411
3602
  const chapterText = `=== CHAPTER: ${label} ===`;
3603
+ if (state.kind === "chrome-extension") {
3604
+ die("chapters are not supported for --source chrome-extension recordings yet; use --source chrome-for-clipy when you need them", 2);
3605
+ }
3412
3606
  if (state.kind === "mac") {
3413
3607
  const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: chapterText }).catch((e) => {
3414
3608
  if (e instanceof BridgeUnavailableError) {
@@ -3460,6 +3654,38 @@ async function cmdChapter(label, json) {
3460
3654
  }
3461
3655
  async function cmdSessionStop(json) {
3462
3656
  const { file, state } = requireSession();
3657
+ if (state.kind === "chrome-extension") {
3658
+ if (!json)
3659
+ process.stderr.write(`${c.dim("stopping; the extension is uploading…")}\n`);
3660
+ const chromium = await loadChromium();
3661
+ let result;
3662
+ try {
3663
+ result = await stopExtensionRecording(chromium, {
3664
+ port: extensionSessionPort(state),
3665
+ env: process.env,
3666
+ recordingId: extensionSessionId(state),
3667
+ timeoutMs: 600_000,
3668
+ });
3669
+ }
3670
+ catch (error) {
3671
+ const message = error instanceof Error ? error.message : String(error);
3672
+ if (error instanceof ExtensionRecordingEndedError) {
3673
+ cleanupSessionFiles(state, file);
3674
+ markExtensionRecording(homedir(), null);
3675
+ die(`session stop failed: ${message}`);
3676
+ }
3677
+ die(`session stop could not finish (${message}). The session is kept: run \`clipy session stop\` again, or \`clipy session status\``);
3678
+ }
3679
+ cleanupSessionFiles(state, file);
3680
+ markExtensionRecording(homedir(), null);
3681
+ reportSessionResult({
3682
+ publicId: result.publicId,
3683
+ shareUrl: result.shareUrl,
3684
+ contextUrl: `${new URL(result.shareUrl).origin}/api/agent-context/${result.publicId}`,
3685
+ sizeBytes: 0,
3686
+ }, json);
3687
+ return;
3688
+ }
3463
3689
  if (state.kind === "mac") {
3464
3690
  if (!json)
3465
3691
  process.stderr.write(`${c.dim("stopping + uploading…")}\n`);
@@ -3551,6 +3777,41 @@ function reportSessionResult(result, json) {
3551
3777
  }
3552
3778
  async function cmdSessionAbort(json) {
3553
3779
  const { file, state } = requireSession();
3780
+ if (state.kind === "chrome-extension") {
3781
+ const chromium = await loadChromium();
3782
+ let failure = null;
3783
+ await abortExtensionRecording(chromium, {
3784
+ port: extensionSessionPort(state),
3785
+ env: process.env,
3786
+ recordingId: extensionSessionId(state),
3787
+ }).catch((error) => {
3788
+ failure = error instanceof Error ? error.message : String(error);
3789
+ });
3790
+ if (failure && (await chromeStatus(homedir(), process.platform)).running) {
3791
+ // Chrome for Clipy is up, so the recording may still be running: keep
3792
+ // the session so a retry (or stop) can still reach it.
3793
+ if (json)
3794
+ printJson({ state: "recording", error: failure });
3795
+ else
3796
+ process.stderr.write(`${c.yellow("!")} could not reach the extension to cancel (${failure}); the session is kept, retry \`clipy session abort\`\n`);
3797
+ process.exitCode = 1;
3798
+ return;
3799
+ }
3800
+ cleanupSessionFiles(state, file);
3801
+ markExtensionRecording(homedir(), null);
3802
+ if (failure) {
3803
+ if (json)
3804
+ printJson({ state: "cleared", error: failure });
3805
+ else
3806
+ process.stdout.write(`${c.green("✓")} Chrome for Clipy is not running, so nothing is recording; session cleared\n`);
3807
+ return;
3808
+ }
3809
+ if (json)
3810
+ printJson({ state: "aborted" });
3811
+ else
3812
+ process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
3813
+ return;
3814
+ }
3554
3815
  if (state.kind === "mac") {
3555
3816
  await bridgeRequest(bridgeInfoFromSession(state), "abort").catch(() => { });
3556
3817
  cleanupSessionFiles(state, file);
@@ -3648,6 +3909,39 @@ async function cmdSessionStatus(json) {
3648
3909
  process.stdout.write(`${c.dim("no session in this workspace")}\n`);
3649
3910
  return;
3650
3911
  }
3912
+ if (state.kind === "chrome-extension") {
3913
+ const elapsedSec = state.recordStartEpochMs ? Math.round((Date.now() - state.recordStartEpochMs) / 1000) : null;
3914
+ let live;
3915
+ try {
3916
+ const chromium = await loadChromium();
3917
+ live = await extensionRecordingStatus(chromium, {
3918
+ port: extensionSessionPort(state),
3919
+ env: process.env,
3920
+ recordingId: extensionSessionId(state),
3921
+ });
3922
+ }
3923
+ catch (error) {
3924
+ live = { state: "dead", result: { error: error instanceof Error ? error.message : String(error) } };
3925
+ }
3926
+ if (json) {
3927
+ printJson({
3928
+ state: live.state,
3929
+ url: state.url,
3930
+ elapsedSec,
3931
+ maxSec: state.maxSec,
3932
+ cdpUrl: state.cdpUrl ?? null,
3933
+ cdpHttpUrl: state.cdpHttpUrl ?? null,
3934
+ ...(live.result ? { result: live.result } : {}),
3935
+ });
3936
+ return;
3937
+ }
3938
+ process.stdout.write(`${c.bold(live.state)} — ${state.url}${elapsedSec != null ? ` — ${elapsedSec}s since start (max ${state.maxSec}s)` : ""}\n`);
3939
+ if (live.result?.shareUrl)
3940
+ process.stdout.write(`${c.dim("recording:")} ${live.result.shareUrl} ${c.dim("collect with: clipy session stop")}\n`);
3941
+ if (live.result?.error)
3942
+ process.stdout.write(`${c.dim("error:")} ${live.result.error}\n`);
3943
+ return;
3944
+ }
3651
3945
  if (state.kind === "mac" && state.state === "recording") {
3652
3946
  // The stored pid is the desktop APP's, which outlives the recording — ask
3653
3947
  // the bridge for the truth instead of inferring from process liveness.
@@ -3844,58 +4138,125 @@ async function runSessionDaemon(file) {
3844
4138
  // the Chromium).
3845
4139
  let ctxToClose = null;
3846
4140
  let controlServer = null;
4141
+ let discardCapture = null;
3847
4142
  try {
3848
4143
  const chromium = await loadChromium();
3849
- log(`launching chromium for ${state.url}`);
3850
- // CDP is OPT-IN (--expose-cdp) and the env kill switch wins over the flag:
3851
- // no debugging port is opened unless the user asked AND CLIPY_DISABLE_CDP
3852
- // isn't set. When enabled, Playwright still controls the browser over its
3853
- // own pipe; the extra --remote-debugging-port opens a parallel TCP endpoint
3854
- // an agent can attach to.
3855
- const wantCdp = !!state.exposeCdp && process.env.CLIPY_DISABLE_CDP !== "1";
3856
- if (state.exposeCdp && !wantCdp)
3857
- log("CDP disabled by CLIPY_DISABLE_CDP=1 — not opening a debugging port");
3858
- const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
3859
- // --user-data-dir ⇒ a persistent context (its own browser); else an ephemeral
3860
- // browser + context. The CDP debugging port (if any) rides the launch args.
3861
- const { context, browser: launchedBrowser } = await launchRecordingContext(chromium, {
3862
- userDataDir: state.userDataDir,
3863
- viewport: { width: state.width, height: state.height },
3864
- recordVideoDir: state.tmpDir,
3865
- args: [
3866
- "--no-sandbox",
3867
- "--disable-dev-shm-usage",
3868
- ...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
3869
- ],
3870
- storageStatePath: state.storageStatePath,
3871
- });
3872
- browser = launchedBrowser;
3873
- ctxToClose = context;
3874
- // Seed cookies/localStorage/init-script before the first navigation — re-parse
3875
- // the raw specs the parent CLI already validated. A bad spec here is caught by
3876
- // the outer try/catch and fails the session cleanly. (--storage-state was
3877
- // applied at launch; it and --user-data-dir are mutually exclusive.)
3878
- await applyAuthCapture(context, {
3879
- storageStatePath: state.storageStatePath,
3880
- initScriptPath: state.initScriptPath,
3881
- cookieSpecs: state.cookieSpecs ?? [],
3882
- localStorageSpecs: state.localStorageSpecs ?? [],
3883
- }, state.url);
3884
- // Persistent contexts open with a default page; ephemeral ones start empty.
3885
- const page = context.pages()[0] ?? (await context.newPage());
3886
- // Best-effort: publish the CDP URL so `session start`/`status` can hand it
3887
- // to the agent. The recording works fine even if discovery fails.
4144
+ let page;
3888
4145
  let cdpUrl;
3889
4146
  let cdpHttpUrl;
3890
- if (cdpPort) {
3891
- cdpUrl = (await discoverCdpWsUrl(cdpPort)) ?? undefined;
3892
- if (cdpUrl) {
3893
- cdpHttpUrl = `http://127.0.0.1:${cdpPort}`;
3894
- log(`CDP endpoint ready at ${cdpHttpUrl} (${cdpUrl})`);
3895
- }
3896
- else {
3897
- log(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
4147
+ // Mode-specific teardown, so the shared stop/abort paths below don't care
4148
+ // which capture engine is running. finishCapture returns the finished
4149
+ // capture's file path; discardCapture drops it.
4150
+ let finishCapture;
4151
+ // Whether a CDP driver can attach (and so whether the in-page mark bindings
4152
+ // below get installed), plus the context to install them on.
4153
+ let wantCdp = false;
4154
+ let bindingContext = null;
4155
+ if (state.kind === "chrome-for-clipy") {
4156
+ const port = state.chromePort ?? DEFAULT_CDP_PORT;
4157
+ log(`attaching to Chrome for Clipy on port ${port} for ${state.url}`);
4158
+ const cap = await startChromeForClipyCapture(chromium, {
4159
+ home: homedir(),
4160
+ env: process.env,
4161
+ platform: process.platform,
4162
+ port,
4163
+ tmpDir: state.tmpDir,
4164
+ targetUrl: state.url,
4165
+ log,
4166
+ });
4167
+ // For a CDP-connected browser, close() disconnects and leaves Chrome for
4168
+ // Clipy running; it must never be killed by a session ending.
4169
+ browser = cap.browser;
4170
+ page = cap.page;
4171
+ // The instance's CDP endpoint is inherently open, so publish it always so
4172
+ // drivers attach to the same browser the session is recording.
4173
+ cdpUrl = (await discoverCdpWsUrl(port)) ?? undefined;
4174
+ cdpHttpUrl = `http://127.0.0.1:${port}`;
4175
+ wantCdp = true;
4176
+ bindingContext = cap.browser.contexts()[0];
4177
+ finishCapture = async () => {
4178
+ const videoPath = await cap.stop();
4179
+ if (browser)
4180
+ await browser.close().catch(() => { });
4181
+ browser = null;
4182
+ return videoPath;
4183
+ };
4184
+ discardCapture = async () => {
4185
+ await cap.discard().catch(() => { });
4186
+ if (browser)
4187
+ await browser.close().catch(() => { });
4188
+ browser = null;
4189
+ };
4190
+ }
4191
+ else {
4192
+ log(`launching chromium for ${state.url}`);
4193
+ // CDP is OPT-IN (--expose-cdp) and the env kill switch wins over the flag:
4194
+ // no debugging port is opened unless the user asked AND CLIPY_DISABLE_CDP
4195
+ // isn't set. When enabled, Playwright still controls the browser over its
4196
+ // own pipe; the extra --remote-debugging-port opens a parallel TCP endpoint
4197
+ // an agent can attach to.
4198
+ wantCdp = !!state.exposeCdp && process.env.CLIPY_DISABLE_CDP !== "1";
4199
+ if (state.exposeCdp && !wantCdp)
4200
+ log("CDP disabled by CLIPY_DISABLE_CDP=1 — not opening a debugging port");
4201
+ const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
4202
+ // --user-data-dir ⇒ a persistent context (its own browser); else an ephemeral
4203
+ // browser + context. The CDP debugging port (if any) rides the launch args.
4204
+ const { context, browser: launchedBrowser } = await launchRecordingContext(chromium, {
4205
+ userDataDir: state.userDataDir,
4206
+ viewport: { width: state.width, height: state.height },
4207
+ recordVideoDir: state.tmpDir,
4208
+ args: [
4209
+ "--no-sandbox",
4210
+ "--disable-dev-shm-usage",
4211
+ ...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
4212
+ ],
4213
+ storageStatePath: state.storageStatePath,
4214
+ });
4215
+ browser = launchedBrowser;
4216
+ ctxToClose = context;
4217
+ bindingContext = context;
4218
+ // Seed cookies/localStorage/init-script before the first navigation — re-parse
4219
+ // the raw specs the parent CLI already validated. A bad spec here is caught by
4220
+ // the outer try/catch and fails the session cleanly. (--storage-state was
4221
+ // applied at launch; it and --user-data-dir are mutually exclusive.)
4222
+ await applyAuthCapture(context, {
4223
+ storageStatePath: state.storageStatePath,
4224
+ initScriptPath: state.initScriptPath,
4225
+ cookieSpecs: state.cookieSpecs ?? [],
4226
+ localStorageSpecs: state.localStorageSpecs ?? [],
4227
+ }, state.url);
4228
+ // Persistent contexts open with a default page; ephemeral ones start empty.
4229
+ page = context.pages()[0] ?? (await context.newPage());
4230
+ // Best-effort: publish the CDP URL so `session start`/`status` can hand it
4231
+ // to the agent. The recording works fine even if discovery fails.
4232
+ if (cdpPort) {
4233
+ cdpUrl = (await discoverCdpWsUrl(cdpPort)) ?? undefined;
4234
+ if (cdpUrl) {
4235
+ cdpHttpUrl = `http://127.0.0.1:${cdpPort}`;
4236
+ log(`CDP endpoint ready at ${cdpHttpUrl} (${cdpUrl})`);
4237
+ }
4238
+ else {
4239
+ log(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
4240
+ }
3898
4241
  }
4242
+ finishCapture = async () => {
4243
+ const video = page.video();
4244
+ await page.close();
4245
+ await context.close();
4246
+ if (!video)
4247
+ throw new Error("browser did not produce a video (recordVideo unavailable)");
4248
+ const videoPath = await video.path();
4249
+ // Persistent mode: context.close() already tore down Chromium; there is
4250
+ // no separate browser to close.
4251
+ if (browser)
4252
+ await browser.close().catch(() => { });
4253
+ browser = null;
4254
+ return videoPath;
4255
+ };
4256
+ discardCapture = async () => {
4257
+ await page.close().catch(() => { });
4258
+ await context.close().catch(() => { });
4259
+ };
3899
4260
  }
3900
4261
  // Auto-marks: instrumentation ground truth alongside the agent's intent
3901
4262
  // marks. Type-tagged with [auto] so the transcript distinguishes them.
@@ -3994,9 +4355,12 @@ async function runSessionDaemon(file) {
3994
4355
  // The bindings are exposed under *Impl names and re-declared with explicit
3995
4356
  // arity below, so an agent probing window.__clipyMark.length sees 2 (not the
3996
4357
  // 0 an exposeBinding wrapper reports).
3997
- if (wantCdp) {
3998
- await context
3999
- .exposeBinding("__clipyMarkImpl", async (_src, ...args) => {
4358
+ if (wantCdp && bindingContext) {
4359
+ const bindings = page;
4360
+ await bindings
4361
+ .exposeBinding("__clipyMarkImpl", async (source, ...args) => {
4362
+ if (source.page !== page || source.frame !== page.mainFrame())
4363
+ throw new Error("Only the recorded main frame can emit marks");
4000
4364
  if (recordStart === 0)
4001
4365
  return { skipped: true };
4002
4366
  const o = (args[1] ?? {});
@@ -4017,8 +4381,10 @@ async function runSessionDaemon(file) {
4017
4381
  return await applyMark({ text: String(args[0] ?? ""), assert });
4018
4382
  })
4019
4383
  .catch((e) => log(`__clipyMark binding failed: ${e.message}`));
4020
- await context
4021
- .exposeBinding("__clipyChapterImpl", (_src, ...args) => {
4384
+ await bindings
4385
+ .exposeBinding("__clipyChapterImpl", (source, ...args) => {
4386
+ if (source.page !== page || source.frame !== page.mainFrame())
4387
+ throw new Error("Only the recorded main frame can emit chapters");
4022
4388
  if (recordStart === 0)
4023
4389
  return;
4024
4390
  const label = String(args[0] ?? "").trim();
@@ -4029,12 +4395,19 @@ async function runSessionDaemon(file) {
4029
4395
  .catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
4030
4396
  // Declared-arity wrappers so window.__clipyMark.length === 2 / __clipyChapter
4031
4397
  // === 1 (they resolve the *Impl bindings lazily, at call time).
4032
- await context
4398
+ await bindings
4033
4399
  .addInitScript({
4034
4400
  content: "window.__clipyMark = (text, opts) => window.__clipyMarkImpl(text, opts);\n" +
4035
4401
  "window.__clipyChapter = (label) => window.__clipyChapterImpl(label);",
4036
4402
  })
4037
4403
  .catch((e) => log(`in-page binding wrappers failed: ${e.message}`));
4404
+ if (state.kind === "chrome-for-clipy") {
4405
+ await page.evaluate(() => {
4406
+ const w = globalThis;
4407
+ w.__clipyMark = (text, opts) => w.__clipyMarkImpl(text, opts);
4408
+ w.__clipyChapter = (label) => w.__clipyChapterImpl(label);
4409
+ });
4410
+ }
4038
4411
  }
4039
4412
  // Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
4040
4413
  // which owns the live page — evaluates assertions and stamps marks on its
@@ -4160,11 +4533,16 @@ async function runSessionDaemon(file) {
4160
4533
  cdpHttpUrl,
4161
4534
  ...(controlPort ? { controlPort, controlToken } : {}),
4162
4535
  });
4163
- try {
4164
- await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
4165
- }
4166
- catch {
4167
- log("page load timed out; recording current state anyway");
4536
+ // chrome-for-clipy already navigated the target before capture started (the
4537
+ // marker-title selection requires a loaded page); re-navigating here would
4538
+ // just reload it on camera.
4539
+ if (state.kind !== "chrome-for-clipy") {
4540
+ try {
4541
+ await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
4542
+ }
4543
+ catch {
4544
+ log("page load timed out; recording current state anyway");
4545
+ }
4168
4546
  }
4169
4547
  // Main loop: poll the control file; enforce the max-duration rail.
4170
4548
  let stopReason = "stop";
@@ -4199,8 +4577,8 @@ async function runSessionDaemon(file) {
4199
4577
  if (stopReason === "abort") {
4200
4578
  log("abort requested — discarding capture");
4201
4579
  save({ state: "aborted" });
4202
- await page.close().catch(() => { });
4203
- await context.close().catch(() => { });
4580
+ await discardCapture();
4581
+ discardCapture = null;
4204
4582
  try {
4205
4583
  rmSync(state.tmpDir, { recursive: true, force: true });
4206
4584
  }
@@ -4214,17 +4592,8 @@ async function runSessionDaemon(file) {
4214
4592
  log(`max duration ${state.maxSec}s reached — auto-stopping and uploading`);
4215
4593
  }
4216
4594
  save({ state: "stopping" });
4217
- const video = page.video();
4218
- await page.close();
4219
- await context.close();
4220
- if (!video)
4221
- throw new Error("browser did not produce a video (recordVideo unavailable)");
4222
- const videoPath = await video.path();
4223
- // Persistent mode: context.close() (above) already tore down Chromium; there
4224
- // is no separate browser to close.
4225
- if (browser)
4226
- await browser.close().catch(() => { });
4227
- browser = null;
4595
+ const videoPath = await finishCapture();
4596
+ discardCapture = null;
4228
4597
  // Merge marks. The FILE is the mark of record: `clipy mark` writes there when
4229
4598
  // its control call fails, and a timed-out ASSERTION is recorded ⚠-unverified.
4230
4599
  // That ⚠ is authoritative — if the daemon later evaluated the same mark, that
@@ -4365,6 +4734,8 @@ async function runSessionDaemon(file) {
4365
4734
  finally {
4366
4735
  if (controlServer)
4367
4736
  controlServer.close();
4737
+ if (discardCapture)
4738
+ await discardCapture().catch(() => { });
4368
4739
  // Persistent (--user-data-dir) contexts have no separate browser, so an
4369
4740
  // exception before the stop/abort path must close the context to avoid
4370
4741
  // leaking Chromium. Both closes are no-ops if the object is already closed.
@@ -4424,7 +4795,7 @@ function writeSkillFile(path) {
4424
4795
  // setup — skill + MCP + login in one command, for an agent following the
4425
4796
  // published setup instructions at clipy.online/agent-setup/prompt.md.
4426
4797
  // ---------------------------------------------------------------------------
4427
- async function cmdSetup(ctx, targetRaw, json) {
4798
+ async function cmdSetup(ctx, targetRaw, json, withBrowser) {
4428
4799
  const env = realSetupEnv();
4429
4800
  let target;
4430
4801
  if (targetRaw) {
@@ -4474,6 +4845,39 @@ async function cmdSetup(ctx, targetRaw, json) {
4474
4845
  catch (error) {
4475
4846
  failSetup(json, "skill_install_failed", `the MCP server was registered, but the skill could not be installed: ${error.message}`, `Fix permissions for ${skillPath}, then retry setup.`, { target, skill: { installed: false, path: skillPath }, mcp, authenticated: true });
4476
4847
  }
4848
+ let browser = null;
4849
+ if (withBrowser) {
4850
+ const chrome = { appInstalled: false, running: false };
4851
+ try {
4852
+ if (process.platform === "darwin") {
4853
+ const appPath = chromeForClipyAppPath(env.home);
4854
+ // Keep an existing launcher; `clipy chrome install-app` explicitly
4855
+ // refreshes its flags, executable path, and icon.
4856
+ if (existsSync(appPath)) {
4857
+ chrome.appInstalled = true;
4858
+ chrome.appPath = appPath;
4859
+ }
4860
+ else {
4861
+ const installed = installChromeForClipyApp(env.home, env.env, process.platform, DEFAULT_CDP_PORT);
4862
+ if (installed.ok) {
4863
+ chrome.appInstalled = true;
4864
+ chrome.appPath = installed.path;
4865
+ }
4866
+ else {
4867
+ chrome.error = installed.error;
4868
+ }
4869
+ }
4870
+ }
4871
+ const up = await startChromeForClipy(env.home, env.env, process.platform, DEFAULT_CDP_PORT);
4872
+ chrome.running = up.ok;
4873
+ if (!up.ok)
4874
+ chrome.error = chrome.error ?? up.error;
4875
+ }
4876
+ catch (error) {
4877
+ chrome.error = error instanceof Error ? error.message : String(error);
4878
+ }
4879
+ browser = { ok: chrome.running, chrome };
4880
+ }
4477
4881
  if (json) {
4478
4882
  printJson({
4479
4883
  ok: true,
@@ -4482,6 +4886,7 @@ async function cmdSetup(ctx, targetRaw, json) {
4482
4886
  mcp,
4483
4887
  authenticated: true,
4484
4888
  restartRequired: true,
4889
+ ...(browser ? { browser } : {}),
4485
4890
  docs: "https://clipy.online/agent-setup/prompt.md",
4486
4891
  });
4487
4892
  return;
@@ -4491,11 +4896,166 @@ async function cmdSetup(ctx, targetRaw, json) {
4491
4896
  `✓ Skill ${short(skillPath)}`,
4492
4897
  `✓ MCP ${mcp.path ? short(mcp.path) : (mcp.command ?? target)}${mcp.alreadyPresent && !mcp.changed ? " (already registered)" : ""}`,
4493
4898
  `✓ Signed in`,
4494
- "",
4495
- "→ Restart your agent to load the MCP server",
4496
4899
  ];
4900
+ if (browser) {
4901
+ rows.push(browser.chrome.running
4902
+ ? `✓ Chrome ${CHROME_FOR_CLIPY_APP_NAME} ${browser.chrome.appInstalled ? "installed and " : ""}running; sign in once to persist logins`
4903
+ : `✗ Chrome ${browser.chrome.error ?? `${CHROME_FOR_CLIPY_APP_NAME} did not start`}`);
4904
+ }
4905
+ rows.push("", "→ Restart your agent to load the MCP server");
4497
4906
  process.stdout.write(`${renderSetupBox("Clipy setup complete", rows)}\n`);
4498
4907
  }
4908
+ // ---------------------------------------------------------------------------
4909
+ // chrome: the dedicated "Chrome for Clipy" automation browser.
4910
+ // ---------------------------------------------------------------------------
4911
+ async function cmdChrome(sub, json, portRaw) {
4912
+ const home = homedir();
4913
+ const port = portRaw ? Number(portRaw) : DEFAULT_CDP_PORT;
4914
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
4915
+ die("usage: clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--json]", 2);
4916
+ }
4917
+ switch (sub) {
4918
+ case "setup":
4919
+ await cmdChromeSetup(home, port, json);
4920
+ return;
4921
+ case "start": {
4922
+ const result = await startChromeForClipy(home, process.env, process.platform, port);
4923
+ if (!result.ok) {
4924
+ if (json)
4925
+ printJson({ ok: false, error: result.error });
4926
+ else
4927
+ process.stderr.write(`error: ${result.error}\n`);
4928
+ process.exit(1);
4929
+ }
4930
+ const status = await chromeStatus(home, process.platform);
4931
+ if (json) {
4932
+ printJson({ ok: true, ...status, captureTitleMarker: TAB_CAPTURE_TITLE_MARKER });
4933
+ return;
4934
+ }
4935
+ process.stdout.write(`${CHROME_FOR_CLIPY_APP_NAME} running (pid ${status.pid})\n` +
4936
+ ` CDP: ${status.cdpUrl}\n` +
4937
+ ` Profile: ${status.profileDir}\n` +
4938
+ ` Capture: retitle a tab to start with "${TAB_CAPTURE_TITLE_MARKER}" and getDisplayMedia auto-selects it (no picker)\n`);
4939
+ return;
4940
+ }
4941
+ case "stop": {
4942
+ const result = stopChromeForClipy(home);
4943
+ if (json)
4944
+ printJson({ ok: result.ok, stopped: result.stopped, ...(result.error ? { error: result.error } : {}) });
4945
+ else if (!result.ok)
4946
+ process.stderr.write(`error: ${result.error}\n`);
4947
+ else
4948
+ process.stdout.write(result.stopped ? "stopped\n" : "not running\n");
4949
+ if (!result.ok)
4950
+ process.exit(1);
4951
+ return;
4952
+ }
4953
+ case "status": {
4954
+ const status = await chromeStatus(home, process.platform);
4955
+ if (json) {
4956
+ printJson({ ok: true, ...status, captureTitleMarker: TAB_CAPTURE_TITLE_MARKER });
4957
+ return;
4958
+ }
4959
+ process.stdout.write(status.running
4960
+ ? `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}\napp installed: ${status.appInstalled ? "yes" : "no"}\n`);
4963
+ return;
4964
+ }
4965
+ case "install-app": {
4966
+ const result = installChromeForClipyApp(home, process.env, process.platform, port);
4967
+ if (!result.ok) {
4968
+ if (json)
4969
+ printJson({ ok: false, error: result.error });
4970
+ else
4971
+ process.stderr.write(`error: ${result.error}\n`);
4972
+ process.exit(1);
4973
+ }
4974
+ if (json)
4975
+ printJson({ ok: true, path: result.path });
4976
+ else
4977
+ process.stdout.write(`Installed "${CHROME_FOR_CLIPY_APP_NAME}" at ${result.path}\n` +
4978
+ `Open it from Finder/Spotlight, or keep using clipy chrome start.\n`);
4979
+ return;
4980
+ }
4981
+ default:
4982
+ die("usage: clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--json]", 2);
4983
+ }
4984
+ }
4985
+ const CHROME_SETUP_TIMEOUT_MS = 15 * 60_000;
4986
+ /** One-time setup for `--source chrome-extension`. Two steps need the person
4987
+ * (Chrome does not allow scripting a Web Store install, and signing in is
4988
+ * theirs), so this opens the right page for each and waits until the
4989
+ * extension itself reports it is installed and signed in. Re-running it on a
4990
+ * ready instance is a quick check. */
4991
+ async function cmdChromeSetup(home, port, json) {
4992
+ const say = (m) => {
4993
+ if (!json)
4994
+ process.stdout.write(`${m}\n`);
4995
+ };
4996
+ const fail = (error) => {
4997
+ if (json)
4998
+ printJson({ ok: false, error });
4999
+ else
5000
+ process.stderr.write(`error: ${error}\n`);
5001
+ process.exit(1);
5002
+ };
5003
+ // Always rewritten: the launcher bakes in the launch flags, and one from an
5004
+ // older CLI would start Chrome without --allowlisted-extension-id.
5005
+ if (process.platform === "darwin") {
5006
+ const app = installChromeForClipyApp(home, process.env, process.platform, port);
5007
+ if (app.ok)
5008
+ say(`updated the "${CHROME_FOR_CLIPY_APP_NAME}" launcher at ${app.path}`);
5009
+ }
5010
+ const started = await startChromeForClipy(home, process.env, process.platform, port);
5011
+ if (!started.ok)
5012
+ fail(started.error);
5013
+ const chromium = (await loadChromium());
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
+ };
5025
+ const deadline = Date.now() + CHROME_SETUP_TIMEOUT_MS;
5026
+ let askedInstall = false;
5027
+ let askedSignIn = false;
5028
+ for (;;) {
5029
+ const ready = await extensionReadiness(chromium, port, process.env);
5030
+ if (ready.installed && ready.error)
5031
+ fail(ready.error);
5032
+ if (ready.installed && ready.signedIn) {
5033
+ const status = await chromeStatus(home, process.platform);
5034
+ if (json) {
5035
+ printJson({ ok: true, extension: { version: ready.version, email: ready.email }, chrome: status });
5036
+ }
5037
+ else {
5038
+ say(`${c.green("✓")} Chrome for Clipy is ready: extension ${ready.version}, signed in${ready.email ? ` as ${ready.email}` : ""}`);
5039
+ say(`${c.dim("record a tab with:")} clipy session start --source chrome-extension --url <url>`);
5040
+ }
5041
+ return;
5042
+ }
5043
+ if (!ready.installed && !askedInstall) {
5044
+ askedInstall = true;
5045
+ await openTab(extensionStoreUrl(process.env));
5046
+ say(`→ In the ${CHROME_FOR_CLIPY_APP_NAME} window, click "Add to Chrome" on the Clipy extension page. Waiting…`);
5047
+ }
5048
+ else if (ready.installed && !ready.signedIn && !askedSignIn) {
5049
+ askedSignIn = true;
5050
+ await openTab("https://clipy.online/?signin=1&signup_flow=extension");
5051
+ say(`→ Sign in to Clipy in the ${CHROME_FOR_CLIPY_APP_NAME} window. Waiting…`);
5052
+ }
5053
+ if (Date.now() >= deadline) {
5054
+ fail(ready.installed ? "timed out waiting for sign-in" : "timed out waiting for the Clipy extension to be installed");
5055
+ }
5056
+ await new Promise((r) => setTimeout(r, 3000));
5057
+ }
5058
+ }
4499
5059
  function failSetup(json, code, error, remediation, partial = null, exitCode = 1) {
4500
5060
  if (json) {
4501
5061
  printJson({ ok: false, code, error, remediation, partial });
@@ -4660,14 +5220,15 @@ function cmdGuide(json) {
4660
5220
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
4661
5221
  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"]),
4662
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; auth flags rejected — the screen is already logged in); --window '<title|app|id>' records that window's initial screen area and --display <id> records one display (ids from clipy sources). --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--user-data-dir", "--profile-directory", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
4663
- 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). With --source mac-screen, --window records that window's initial screen area and --display records one 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/--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", "--expose-cdp", "--storage-state", "--user-data-dir", "--profile-directory", "--cookie", "--local-storage", "--init-script", "--json"]),
5223
+ cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen|chrome-for-clipy|chrome-extension] [--window w] [--display d] [--expose-cdp] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). With --source mac-screen, --window records that window's initial screen area and --display records one display. --source chrome-extension records ONE TAB through the Clipy extension inside Chrome for Clipy (needs a one-time clipy chrome setup): no daemon, the extension records and uploads; start returns cdpHttpUrl, stop waits for the upload and returns the link; mark/chapter are refused on this source. --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), 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/--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", "--expose-cdp", "--storage-state", "--user-data-dir", "--profile-directory", "--cookie", "--local-storage", "--init-script", "--json"]),
4664
5224
  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"]),
4665
5225
  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"]),
4666
5226
  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"]),
4667
5227
  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"]),
4668
5228
  cmdDoc("sources", "clipy sources [--json]", "List displays + windows the Clipy Mac app can capture — ids feed --window/--display. --json gives each entry a `source` {kind,id,title} in the SAME shape session start/record report for the resolved capture, so a caller can compare what it picked against what the camera reports without transforming either."),
4669
- cmdDoc("setup", "clipy setup [claude|codex|cursor|windsurf|opencode] [--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.", ["--json"]),
5229
+ 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"]),
4670
5230
  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"]),
4671
5232
  cmdDoc("guide", "clipy guide --json", "This manifest"),
4672
5233
  cmdDoc("mcp", "clipy mcp", "Run the Clipy MCP server (wraps npx -y @clipy/mcp)"),
4673
5234
  ],
@@ -4775,6 +5336,8 @@ async function main() {
4775
5336
  key: { type: "string" },
4776
5337
  paste: { type: "boolean", default: false },
4777
5338
  "no-browser": { type: "boolean", default: false },
5339
+ "with-browser": { type: "boolean", default: false },
5340
+ port: { type: "string" },
4778
5341
  "api-url": { type: "string" },
4779
5342
  status: { type: "string" },
4780
5343
  page: { type: "string" },
@@ -5062,7 +5625,10 @@ async function main() {
5062
5625
  await cmdPlaywrightPath(json);
5063
5626
  return;
5064
5627
  case "setup":
5065
- await cmdSetup(ctx, rest[0], json);
5628
+ await cmdSetup(ctx, rest[0], json, values["with-browser"] === true);
5629
+ return;
5630
+ case "chrome":
5631
+ await cmdChrome(rest[0], json, values.port);
5066
5632
  return;
5067
5633
  case "agents":
5068
5634
  await cmdAgents(ctx, rest[0], rest[1], json);
@@ -5208,8 +5774,8 @@ async function main() {
5208
5774
  // start <url>) — `run` has no positional url, only --url.
5209
5775
  const buildStartOpts = (positionalUrl) => {
5210
5776
  const source = String(values.source ?? "web");
5211
- if (source !== "web" && source !== "mac-screen") {
5212
- die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
5777
+ if (source !== "web" && source !== "mac-screen" && source !== "chrome-for-clipy" && source !== "chrome-extension") {
5778
+ die("--source must be web (headless browser), mac-screen (the Clipy Mac app), chrome-for-clipy (the persistent automation browser), or chrome-extension (the Clipy extension inside Chrome for Clipy)", 2);
5213
5779
  }
5214
5780
  if ((values.window || values.display) && source !== "mac-screen") {
5215
5781
  die("--window/--display record the real screen — add --source mac-screen", 2);
@@ -5219,11 +5785,14 @@ async function main() {
5219
5785
  }
5220
5786
  if (source === "mac-screen" && authFlagsPresent)
5221
5787
  die(macAuthGuard, 2);
5788
+ if ((source === "chrome-for-clipy" || source === "chrome-extension") && authFlagsPresent) {
5789
+ 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
+ }
5222
5791
  if (source !== "mac-screen" && audioFlagsPresent)
5223
5792
  die(webAudioGuard, 2);
5224
5793
  const url = values.url?.trim() || positionalUrl;
5225
- if (!url && source === "web") {
5226
- die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen]", 2);
5794
+ if (!url && source !== "mac-screen") {
5795
+ die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen|chrome-for-clipy|chrome-extension]", 2);
5227
5796
  }
5228
5797
  return {
5229
5798
  url: url || "mac-screen",