@clipy/cli 0.14.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -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, ExtensionAlreadyUploadedError, extensionReadiness, extensionRecordingStatus, extensionStoreUrl, openTabForPerson, sendExtensionMark, 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";
@@ -416,14 +418,26 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
416
418
  process could attach — CLIPY_DISABLE_CDP=1 forces off).
417
419
  Accepts the same auth flags as record
418
420
  (--storage-state/--cookie/--local-storage/--init-script)
419
- 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 (marks become its transcript); run
430
+ clipy chrome setup once first
420
431
  session run [start flags] -- <command …>
421
432
  Start a session, run the command (inherited
422
433
  stdio), then GUARANTEE cleanup: exit 0 uploads,
423
434
  any non-zero exit or signal discards and
424
435
  propagates the code. Sets CLIPY_SESSION=1 (+
425
- CLIPY_CDP_URL with --expose-cdp). Crash-safe
426
- wrapper for driver scripts — no dead-air uploads.
436
+ CLIPY_CDP_URL with --expose-cdp; with
437
+ --source chrome-extension also
438
+ CLIPY_TARGET_ID and CLIPY_PAGE_WS_URL for the
439
+ recorded tab). Crash-safe
440
+ wrapper for driver scripts: no dead-air uploads.
427
441
  mark "<what just happened>" Drop a live timestamped note; marks become the
428
442
  recording's transcript. Attach evidence — one
429
443
  provenance per mark, never pooled:
@@ -446,17 +460,30 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
446
460
  session status Show the active session's state
447
461
 
448
462
  ${c.bold("AGENTS")}
449
- setup [claude|codex|cursor|windsurf|opencode]
463
+ setup [claude|codex|cursor|windsurf|opencode] [--with-browser]
450
464
  Wire Clipy into a coding agent in ONE command:
451
465
  sign in, install the skill, and register the MCP
452
466
  server in that agent's own config. Detects the
453
467
  agent it is running inside when you omit the name.
468
+ --with-browser also starts Chrome for Clipy (the
469
+ agent-owned automation browser) and installs its
470
+ launcher on macOS; a browser failure never fails
471
+ setup.
454
472
  ${c.dim("Published instructions: clipy.online/agent-setup/prompt.md")}
455
473
  agents install <claude|codex|cursor|windsurf|opencode>
456
474
  Skill only — no MCP, no login prompt beyond the
457
475
  first-run one. Use ${c.bold("setup")} unless you deliberately
458
476
  want just the skill file
459
477
  agents status | uninstall <t> Show / remove installed skills
478
+ chrome <setup|start|stop|status|install-app> [--port <n>]
479
+ "Chrome for Clipy": a dedicated, persistent
480
+ automation browser with CDP exposed, picker-free
481
+ tab capture (retitle a tab with the marker), and
482
+ background throttling disabled. Sign in once;
483
+ the profile persists. setup walks you through
484
+ installing the Clipy extension and signing in
485
+ there, then waits until it is ready. install-app
486
+ saves a named macOS launcher in ~/Applications
460
487
  doctor [--json] Health check: API key, Mac agent bridge,
461
488
  Playwright, and install mode — with fix hints
462
489
  guide --json Machine-readable manifest: every command,
@@ -2734,6 +2761,9 @@ function writeSessionState(file, state) {
2734
2761
  renameSync(tmp, file);
2735
2762
  }
2736
2763
  function pidAlive(pid) {
2764
+ // kill(0, 0) signals our own process group and "succeeds".
2765
+ if (!Number.isInteger(pid) || pid <= 0)
2766
+ return false;
2737
2767
  try {
2738
2768
  process.kill(pid, 0);
2739
2769
  return true;
@@ -3104,7 +3134,231 @@ function cdpDriverSnippet(cdpHttpUrl) {
3104
3134
  c.dim(` resolve playwright for your script: NODE_PATH=$(clipy playwright-path) node driver.js`),
3105
3135
  ].join("\n");
3106
3136
  }
3137
+ // Same limits the server enforces (lib/server/agentNarration.ts); an invalid
3138
+ // narration would fail the whole upload, so trim instead.
3139
+ const EXTENSION_MAX_NOTES = 200;
3140
+ const EXTENSION_MAX_NOTE_CHARS = 1_000;
3141
+ const EXTENSION_MAX_NOTE_START_MS = 24 * 60 * 60 * 1000;
3142
+ /** The session's marks as narration notes, plus the [verification] tally of
3143
+ * driver-attested marks stamped at the stop. */
3144
+ function extensionSessionNotes(state) {
3145
+ let lines = [];
3146
+ try {
3147
+ lines = readFileSync(state.marksPath, "utf8").split("\n").filter(Boolean);
3148
+ }
3149
+ catch {
3150
+ // no marks
3151
+ }
3152
+ const notes = [];
3153
+ for (const line of lines) {
3154
+ try {
3155
+ const m = JSON.parse(line);
3156
+ if (typeof m.tMs === "number" && typeof m.text === "string" && m.text.trim()) {
3157
+ notes.push({
3158
+ startMs: Math.min(EXTENSION_MAX_NOTE_START_MS, Math.max(0, Math.round(m.tMs))),
3159
+ text: m.text.trim().slice(0, EXTENSION_MAX_NOTE_CHARS),
3160
+ });
3161
+ }
3162
+ }
3163
+ catch {
3164
+ // skip a torn line
3165
+ }
3166
+ }
3167
+ notes.sort((a, b) => a.startMs - b.startMs);
3168
+ const tally = verificationNote({
3169
+ clipyPassed: 0,
3170
+ clipyFailed: 0,
3171
+ clipyUnverified: 0,
3172
+ driverPassed: state.attestedPassed ?? 0,
3173
+ driverFailed: state.attestedFailed ?? 0,
3174
+ });
3175
+ const stopMs = state.recordStartEpochMs
3176
+ ? Math.min(EXTENSION_MAX_NOTE_START_MS, Math.max(0, Date.now() - state.recordStartEpochMs))
3177
+ : 0;
3178
+ const kept = notes.slice(0, EXTENSION_MAX_NOTES - tally.length);
3179
+ return [...kept, ...tally.map((t) => ({ startMs: stopMs, text: t.text }))];
3180
+ }
3181
+ /** The server keeps 200 notes and stop adds one verification summary, so a
3182
+ * 200th mark would be dropped. Refuse it instead of reporting success. */
3183
+ function refuseExtensionMarkOverLimit(state, text) {
3184
+ if (text.length > EXTENSION_MAX_NOTE_CHARS) {
3185
+ die(`this mark is ${text.length} characters (including any --observed annotation); the limit is ${EXTENSION_MAX_NOTE_CHARS}. Shorten it or split it into several marks.`, 2);
3186
+ }
3187
+ let count = 0;
3188
+ try {
3189
+ count = readFileSync(state.marksPath, "utf8").split("\n").filter(Boolean).length;
3190
+ }
3191
+ catch {
3192
+ // no marks yet
3193
+ }
3194
+ if (count >= EXTENSION_MAX_NOTES - 1) {
3195
+ die(`mark limit reached: a recording keeps at most ${EXTENSION_MAX_NOTES - 1} marks. Stop this recording and start another to keep going.`);
3196
+ }
3197
+ }
3198
+ /** Sends the mark to the extension before the CLI records it locally. If the
3199
+ * extension cannot be reached the local copy still goes out at stop; if the
3200
+ * recording already ended on its own, the mark is refused rather than
3201
+ * reported as recorded. */
3202
+ async function forwardExtensionMark(state, tMs, text, summary) {
3203
+ if (!(state.extensionFeatures ?? []).includes("mark") || !state.extensionRecordingId)
3204
+ return;
3205
+ // Retried, then refused: a mark the extension never received would be lost
3206
+ // if the recording auto-stops before session stop sends the local copy.
3207
+ let sent = null;
3208
+ let lastError = "";
3209
+ for (let attempt = 1; attempt <= 3 && !sent; attempt++) {
3210
+ sent = await sendExtensionMark({
3211
+ port: extensionSessionPort(state),
3212
+ env: process.env,
3213
+ recordingId: state.extensionRecordingId,
3214
+ startMs: tMs,
3215
+ text,
3216
+ summary,
3217
+ }).catch((error) => {
3218
+ lastError = error instanceof Error ? error.message : String(error);
3219
+ return null;
3220
+ });
3221
+ if (!sent && attempt < 3)
3222
+ await new Promise((r) => setTimeout(r, 500 * attempt));
3223
+ }
3224
+ if (!sent) {
3225
+ die(`could not reach the Clipy extension to record this mark (${lastError}); it was not recorded. Check \`clipy session status\` and try again.`);
3226
+ }
3227
+ if (sent.ended) {
3228
+ die("the recording already ended (it reached --max and uploaded); this mark was not recorded. Run `clipy session stop` to collect it.");
3229
+ }
3230
+ if (!sent.ok)
3231
+ die(`the extension refused the mark: ${sent.error ?? "unknown error"}`);
3232
+ }
3233
+ function extensionSessionPort(state) {
3234
+ return state.chromePort ?? DEFAULT_CDP_PORT;
3235
+ }
3236
+ function extensionSessionId(state) {
3237
+ if (!state.extensionRecordingId) {
3238
+ die("session file is missing the extension recording id. Abort it with `clipy session abort` and restart");
3239
+ }
3240
+ return state.extensionRecordingId;
3241
+ }
3242
+ /** `--source chrome-extension`: the Clipy extension inside Chrome for Clipy
3243
+ * records and uploads the tab itself. No daemon; the session file only routes
3244
+ * stop/abort/status to the extension, like the Mac bridge path. */
3245
+ async function cmdSessionStartExtension(opts) {
3246
+ let target;
3247
+ try {
3248
+ target = new URL(opts.url);
3249
+ }
3250
+ catch {
3251
+ die(`invalid --url: ${opts.url}`, 2);
3252
+ }
3253
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
3254
+ die(`--url must be http(s), got ${target.protocol}`, 2);
3255
+ }
3256
+ if (opts.userDataDir) {
3257
+ die("--user-data-dir doesn't apply to --source chrome-extension; it records in the persistent Chrome for Clipy profile", 2);
3258
+ }
3259
+ if (opts.recordingKind && !opts.json) {
3260
+ process.stderr.write(`${c.yellow("note: --type is not applied to --source chrome-extension recordings yet")}\n`);
3261
+ }
3262
+ const file = sessionFilePath(process.cwd());
3263
+ const existing = readSessionState(file);
3264
+ if (existing && sessionIsActive(existing)) {
3265
+ die(`a recording session is already active in this workspace (started for ${existing.url}).\n` +
3266
+ `Finish it with \`clipy session stop\` or discard it with \`clipy session abort\`.`);
3267
+ }
3268
+ if (existing)
3269
+ cleanupSessionFiles(existing, file);
3270
+ const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
3271
+ let started;
3272
+ try {
3273
+ started = await startExtensionRecording({
3274
+ home: homedir(),
3275
+ env: process.env,
3276
+ platform: process.platform,
3277
+ port: DEFAULT_CDP_PORT,
3278
+ targetUrl: target.href,
3279
+ maxSec,
3280
+ name: opts.name,
3281
+ tabAudio: opts.tabAudio,
3282
+ log: (m) => {
3283
+ if (!opts.json)
3284
+ process.stderr.write(`${c.dim(m)}\n`);
3285
+ },
3286
+ });
3287
+ }
3288
+ catch (error) {
3289
+ die(`could not start the extension recording: ${error instanceof Error ? error.message : String(error)}`);
3290
+ }
3291
+ // Always on stderr, even with --json: a requested feature was dropped.
3292
+ for (const warning of started.warnings)
3293
+ process.stderr.write(`${c.yellow(`warning: ${warning}`)}\n`);
3294
+ // The extension is recording from here on: record the session before
3295
+ // anything else can fail, or nothing could stop or collect it.
3296
+ const dir = sessionDir();
3297
+ const session = {
3298
+ version: 1,
3299
+ kind: "chrome-extension",
3300
+ chromePort: started.port,
3301
+ extensionRecordingId: started.recordingId,
3302
+ extensionFeatures: started.features,
3303
+ extensionTargetId: started.targetId,
3304
+ // Chrome for Clipy's pid: the session is alive only while that browser is.
3305
+ pid: started.chromePid,
3306
+ cwd: process.cwd(),
3307
+ url: started.pageUrl || target.href,
3308
+ maxSec,
3309
+ width: 0,
3310
+ height: 0,
3311
+ state: "recording",
3312
+ recordStartEpochMs: started.startedAtEpochMs,
3313
+ cdpHttpUrl: started.cdpHttpUrl,
3314
+ marksPath: join(dir, `marks-${randomUUID()}.jsonl`),
3315
+ controlPath: join(dir, "unused"),
3316
+ logPath: join(dir, "unused"),
3317
+ tmpDir: join(dir, "unused"),
3318
+ };
3319
+ try {
3320
+ writeSessionState(file, session);
3321
+ markExtensionRecording(homedir(), {
3322
+ recordingId: started.recordingId,
3323
+ untilEpochMs: started.startedAtEpochMs + maxSec * 1000,
3324
+ });
3325
+ }
3326
+ catch (error) {
3327
+ await abortExtensionRecording({
3328
+ port: started.port,
3329
+ env: process.env,
3330
+ recordingId: started.recordingId,
3331
+ }).catch(() => { });
3332
+ die(`could not save the session, so the recording was cancelled: ${error instanceof Error ? error.message : String(error)}`);
3333
+ }
3334
+ const cdpUrl = (await discoverCdpWsUrl(started.port).catch(() => null)) ?? undefined;
3335
+ if (cdpUrl)
3336
+ writeSessionState(file, { ...session, cdpUrl });
3337
+ if (opts.json) {
3338
+ printJson({
3339
+ state: "recording",
3340
+ captureMode: "chrome-extension",
3341
+ url: session.url,
3342
+ maxSec,
3343
+ sessionFile: file,
3344
+ extensionVersion: started.extensionVersion,
3345
+ cdpUrl: cdpUrl ?? null,
3346
+ cdpHttpUrl: started.cdpHttpUrl,
3347
+ // The recorded tab, exactly: other tabs can share its url.
3348
+ targetId: started.targetId,
3349
+ pageWsUrl: `ws://127.0.0.1:${started.port}/devtools/page/${started.targetId}`,
3350
+ });
3351
+ return;
3352
+ }
3353
+ process.stdout.write(`${c.green("✓")} the Clipy extension is recording ${c.bold(session.url)} in Chrome for Clipy (max ${maxSec}s)\n` +
3354
+ `${c.dim("drive that tab over CDP:")} target ${started.targetId} ${c.dim(`(ws://127.0.0.1:${started.port}/devtools/page/${started.targetId})`)}\n` +
3355
+ `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
3356
+ }
3107
3357
  async function cmdSessionStart(ctx, opts) {
3358
+ if (opts.source === "chrome-extension") {
3359
+ await cmdSessionStartExtension(opts);
3360
+ return;
3361
+ }
3108
3362
  if (opts.source === "mac-screen") {
3109
3363
  const file = sessionFilePath(process.cwd());
3110
3364
  const existing = readSessionState(file);
@@ -3169,11 +3423,24 @@ async function cmdSessionStart(ctx, opts) {
3169
3423
  if (target.protocol !== "http:" && target.protocol !== "https:") {
3170
3424
  die(`--url must be http(s), got ${target.protocol}`, 2);
3171
3425
  }
3426
+ const isChromeForClipy = opts.source === "chrome-for-clipy";
3427
+ let chromePort = DEFAULT_CDP_PORT;
3428
+ if (isChromeForClipy && opts.userDataDir) {
3429
+ die("--user-data-dir doesn't apply to --source chrome-for-clipy; it records the persistent Chrome for Clipy profile", 2);
3430
+ }
3172
3431
  validateAuthCapture(opts.auth, target.href); // usage errors (exit 2) before auth/daemonizing
3173
3432
  if (opts.userDataDir)
3174
3433
  validateUserDataDir(opts.userDataDir, opts.profileDirectory);
3175
3434
  const key = requireKey(ctx);
3176
3435
  await loadChromium(); // fail fast with install instructions before daemonizing
3436
+ // Chrome for Clipy is started HERE, in the parent, so a missing Chrome or a
3437
+ // dead CDP port is a loud immediate error rather than a daemon-log mystery.
3438
+ if (isChromeForClipy) {
3439
+ const chromeUp = await startChromeForClipy(homedir(), process.env, process.platform, DEFAULT_CDP_PORT);
3440
+ if (!chromeUp.ok)
3441
+ die(`Chrome for Clipy failed to start: ${chromeUp.error}`);
3442
+ chromePort = chromeUp.state.port;
3443
+ }
3177
3444
  sweepStaleProfileCopies();
3178
3445
  const file = sessionFilePath(process.cwd());
3179
3446
  const existing = readSessionState(file);
@@ -3197,6 +3464,7 @@ async function cmdSessionStart(ctx, opts) {
3197
3464
  mkdirSync(dir, { recursive: true });
3198
3465
  const state = {
3199
3466
  version: 1,
3467
+ ...(isChromeForClipy ? { kind: "chrome-for-clipy", chromePort } : {}),
3200
3468
  pid: 0,
3201
3469
  cwd: process.cwd(),
3202
3470
  url: target.href,
@@ -3237,8 +3505,10 @@ async function cmdSessionStart(ctx, opts) {
3237
3505
  child.unref();
3238
3506
  // Wait for the daemon to actually start recording (first Chromium launch on
3239
3507
  // a cold cache can take a while) so the agent's next command lands inside a
3240
- // live recording, not a race.
3241
- const deadline = Date.now() + 60_000;
3508
+ // live recording, not a race. chrome-for-clipy needs more headroom: it fully
3509
+ // loads the target page BEFORE capture (marker selection needs a real page),
3510
+ // and a heavy page can spend 30s on `load` alone.
3511
+ const deadline = Date.now() + (isChromeForClipy ? 150_000 : 60_000);
3242
3512
  for (;;) {
3243
3513
  const s = readSessionState(file);
3244
3514
  if (s?.state === "recording")
@@ -3309,6 +3579,48 @@ async function cmdMark(text, json, opts) {
3309
3579
  const hasAssert = !!opts.assert;
3310
3580
  const attest = opts.attest;
3311
3581
  const backdated = opts.atSec != null || opts.agoSec != null;
3582
+ if (state.kind === "chrome-extension") {
3583
+ // The extension owns the page, not Clipy's daemon, so Clipy cannot evaluate
3584
+ // an assertion. Plain and driver-attested marks are kept here and sent with
3585
+ // the stop, where they become the recording's transcript.
3586
+ if (hasAssert) {
3587
+ die("Clipy-evaluated assertions need a Clipy-owned page: use --observed/--verdict to attach evidence you collected yourself", 2);
3588
+ }
3589
+ if (state.state !== "recording" || !state.recordStartEpochMs) {
3590
+ die(`session is ${state.state}; marks can only be added while recording`);
3591
+ }
3592
+ const nowMs = Math.max(0, Date.now() - state.recordStartEpochMs);
3593
+ const requestedMs = opts.atSec != null
3594
+ ? Math.round(opts.atSec * 1000)
3595
+ : opts.agoSec != null
3596
+ ? nowMs - Math.round(opts.agoSec * 1000)
3597
+ : nowMs;
3598
+ // A mark can only point inside the recording so far; the server would
3599
+ // reject a timestamp past 24h and fail the whole upload.
3600
+ const tMs = Math.min(nowMs, EXTENSION_MAX_NOTE_START_MS, Math.max(0, requestedMs));
3601
+ const markText = attest ? `${text.trim()} ${attestedMarkAnnotation(attest.verdict, attest.observed)}` : text.trim();
3602
+ refuseExtensionMarkOverLimit(state, markText);
3603
+ const passed = (state.attestedPassed ?? 0) + (attest?.verdict === "pass" ? 1 : 0);
3604
+ const failed = (state.attestedFailed ?? 0) + (attest && attest.verdict !== "pass" ? 1 : 0);
3605
+ // Sent with each verdict so a recording that auto-stops at --max still
3606
+ // ends with the tally; an explicit stop sends its own and this is unused.
3607
+ const summary = attest
3608
+ ? verificationNote({ clipyPassed: 0, clipyFailed: 0, clipyUnverified: 0, driverPassed: passed, driverFailed: failed })[0]?.text
3609
+ : undefined;
3610
+ await forwardExtensionMark(state, tMs, markText, summary);
3611
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: markText })}\n`, { mode: 0o600 });
3612
+ if (attest) {
3613
+ state.attestedPassed = passed;
3614
+ state.attestedFailed = failed;
3615
+ writeSessionState(file, state);
3616
+ }
3617
+ printMarkResult({
3618
+ tMs,
3619
+ text: markText,
3620
+ ...(attest ? { assert: { passed: attest.verdict === "pass", observed: attest.observed, attested: true } } : {}),
3621
+ }, json);
3622
+ return;
3623
+ }
3312
3624
  if (state.kind === "mac") {
3313
3625
  // The Mac app records the real screen — there is no Clipy-owned page to probe,
3314
3626
  // so Clipy-EVALUATED assertions can't run here. Driver-attested marks CAN: the
@@ -3435,6 +3747,20 @@ async function cmdMark(text, json, opts) {
3435
3747
  async function cmdChapter(label, json) {
3436
3748
  const { file, state } = requireSession();
3437
3749
  const chapterText = `=== CHAPTER: ${label} ===`;
3750
+ if (state.kind === "chrome-extension") {
3751
+ if (state.state !== "recording" || !state.recordStartEpochMs) {
3752
+ die(`session is ${state.state}; chapters can only be added while recording`);
3753
+ }
3754
+ const tMs = Math.max(0, Date.now() - state.recordStartEpochMs);
3755
+ refuseExtensionMarkOverLimit(state, chapterText);
3756
+ await forwardExtensionMark(state, tMs, chapterText);
3757
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: chapterText })}\n`, { mode: 0o600 });
3758
+ if (json)
3759
+ printJson({ tMs, label, text: chapterText });
3760
+ else
3761
+ process.stdout.write(`${c.green("✓")} chapter @ ${(tMs / 1000).toFixed(1)}s: ${label}\n`);
3762
+ return;
3763
+ }
3438
3764
  if (state.kind === "mac") {
3439
3765
  const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: chapterText }).catch((e) => {
3440
3766
  if (e instanceof BridgeUnavailableError) {
@@ -3486,6 +3812,42 @@ async function cmdChapter(label, json) {
3486
3812
  }
3487
3813
  async function cmdSessionStop(json) {
3488
3814
  const { file, state } = requireSession();
3815
+ if (state.kind === "chrome-extension") {
3816
+ if (!json)
3817
+ process.stderr.write(`${c.dim("stopping; the extension is uploading…")}\n`);
3818
+ const notes = extensionSessionNotes(state);
3819
+ if (notes.length && !(state.extensionFeatures ?? []).includes("narration")) {
3820
+ process.stderr.write(`${c.yellow(`warning: this Clipy extension build cannot receive marks; ${notes.length} mark(s) will not reach the recording. Update the extension.`)}\n`);
3821
+ }
3822
+ let result;
3823
+ try {
3824
+ result = await stopExtensionRecording({
3825
+ port: extensionSessionPort(state),
3826
+ env: process.env,
3827
+ recordingId: extensionSessionId(state),
3828
+ timeoutMs: 600_000,
3829
+ notes,
3830
+ });
3831
+ }
3832
+ catch (error) {
3833
+ const message = error instanceof Error ? error.message : String(error);
3834
+ if (error instanceof ExtensionRecordingEndedError) {
3835
+ cleanupSessionFiles(state, file);
3836
+ markExtensionRecording(homedir(), null);
3837
+ die(`session stop failed: ${message}`);
3838
+ }
3839
+ die(`session stop could not finish (${message}). The session is kept: run \`clipy session stop\` again, or \`clipy session status\``);
3840
+ }
3841
+ cleanupSessionFiles(state, file);
3842
+ markExtensionRecording(homedir(), null);
3843
+ reportSessionResult({
3844
+ publicId: result.publicId,
3845
+ shareUrl: result.shareUrl,
3846
+ contextUrl: `${new URL(result.shareUrl).origin}/api/agent-context/${result.publicId}`,
3847
+ sizeBytes: 0,
3848
+ }, json);
3849
+ return;
3850
+ }
3489
3851
  if (state.kind === "mac") {
3490
3852
  if (!json)
3491
3853
  process.stderr.write(`${c.dim("stopping + uploading…")}\n`);
@@ -3577,6 +3939,53 @@ function reportSessionResult(result, json) {
3577
3939
  }
3578
3940
  async function cmdSessionAbort(json) {
3579
3941
  const { file, state } = requireSession();
3942
+ if (state.kind === "chrome-extension") {
3943
+ let failure = null;
3944
+ let uploaded = null;
3945
+ await abortExtensionRecording({
3946
+ port: extensionSessionPort(state),
3947
+ env: process.env,
3948
+ recordingId: extensionSessionId(state),
3949
+ }).catch((error) => {
3950
+ if (error instanceof ExtensionAlreadyUploadedError)
3951
+ uploaded = error.message;
3952
+ else
3953
+ failure = error instanceof Error ? error.message : String(error);
3954
+ });
3955
+ if (uploaded) {
3956
+ // Too late to discard: keep the session so `session stop` can collect it.
3957
+ if (json)
3958
+ printJson({ state: "uploaded", error: uploaded });
3959
+ else
3960
+ process.stderr.write(`${c.yellow("!")} the recording was ${uploaded}; it cannot be discarded here. Run \`clipy session stop\` to collect it, or delete it from the library.\n`);
3961
+ process.exitCode = 1;
3962
+ return;
3963
+ }
3964
+ if (failure && (await chromeStatus(homedir(), process.platform)).running) {
3965
+ // Chrome for Clipy is up, so the recording may still be running: keep
3966
+ // the session so a retry (or stop) can still reach it.
3967
+ if (json)
3968
+ printJson({ state: "recording", error: failure });
3969
+ else
3970
+ process.stderr.write(`${c.yellow("!")} could not reach the extension to cancel (${failure}); the session is kept, retry \`clipy session abort\`\n`);
3971
+ process.exitCode = 1;
3972
+ return;
3973
+ }
3974
+ cleanupSessionFiles(state, file);
3975
+ markExtensionRecording(homedir(), null);
3976
+ if (failure) {
3977
+ if (json)
3978
+ printJson({ state: "cleared", error: failure });
3979
+ else
3980
+ process.stdout.write(`${c.green("✓")} Chrome for Clipy is not running, so nothing is recording; session cleared\n`);
3981
+ return;
3982
+ }
3983
+ if (json)
3984
+ printJson({ state: "aborted" });
3985
+ else
3986
+ process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
3987
+ return;
3988
+ }
3580
3989
  if (state.kind === "mac") {
3581
3990
  await bridgeRequest(bridgeInfoFromSession(state), "abort").catch(() => { });
3582
3991
  cleanupSessionFiles(state, file);
@@ -3674,6 +4083,43 @@ async function cmdSessionStatus(json) {
3674
4083
  process.stdout.write(`${c.dim("no session in this workspace")}\n`);
3675
4084
  return;
3676
4085
  }
4086
+ if (state.kind === "chrome-extension") {
4087
+ const elapsedSec = state.recordStartEpochMs ? Math.round((Date.now() - state.recordStartEpochMs) / 1000) : null;
4088
+ let live;
4089
+ try {
4090
+ live = await extensionRecordingStatus({
4091
+ port: extensionSessionPort(state),
4092
+ env: process.env,
4093
+ recordingId: extensionSessionId(state),
4094
+ });
4095
+ }
4096
+ catch (error) {
4097
+ live = { state: "dead", result: { error: error instanceof Error ? error.message : String(error) } };
4098
+ }
4099
+ if (json) {
4100
+ printJson({
4101
+ state: live.state,
4102
+ url: state.url,
4103
+ elapsedSec,
4104
+ maxSec: state.maxSec,
4105
+ cdpUrl: state.cdpUrl ?? null,
4106
+ cdpHttpUrl: state.cdpHttpUrl ?? null,
4107
+ // The recorded tab, exactly, for an agent resuming without the start output.
4108
+ targetId: state.extensionTargetId ?? null,
4109
+ pageWsUrl: state.extensionTargetId
4110
+ ? `ws://127.0.0.1:${extensionSessionPort(state)}/devtools/page/${state.extensionTargetId}`
4111
+ : null,
4112
+ ...(live.result ? { result: live.result } : {}),
4113
+ });
4114
+ return;
4115
+ }
4116
+ process.stdout.write(`${c.bold(live.state)} — ${state.url}${elapsedSec != null ? ` — ${elapsedSec}s since start (max ${state.maxSec}s)` : ""}\n`);
4117
+ if (live.result?.shareUrl)
4118
+ process.stdout.write(`${c.dim("recording:")} ${live.result.shareUrl} ${c.dim("collect with: clipy session stop")}\n`);
4119
+ if (live.result?.error)
4120
+ process.stdout.write(`${c.dim("error:")} ${live.result.error}\n`);
4121
+ return;
4122
+ }
3677
4123
  if (state.kind === "mac" && state.state === "recording") {
3678
4124
  // The stored pid is the desktop APP's, which outlives the recording — ask
3679
4125
  // the bridge for the truth instead of inferring from process liveness.
@@ -3746,7 +4192,9 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
3746
4192
  // child inherits our stdio and the deliverable is the wrapped run, not JSON.
3747
4193
  await cmdSessionStart(ctx, { ...startOpts, json: false });
3748
4194
  const file = sessionFilePath(process.cwd());
3749
- const cdpHttpUrl = readSessionState(file)?.cdpHttpUrl;
4195
+ const started = readSessionState(file);
4196
+ const cdpHttpUrl = started?.cdpHttpUrl;
4197
+ const targetId = started?.extensionTargetId;
3750
4198
  const [cmd, ...args] = childArgv;
3751
4199
  process.stderr.write(`${c.dim(`running: ${childArgv.join(" ")}`)}\n`);
3752
4200
  const child = spawn(cmd, args, {
@@ -3759,6 +4207,11 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
3759
4207
  CLIPY_SESSION: "1",
3760
4208
  CLIPY_SESSION_FILE: file,
3761
4209
  ...(cdpHttpUrl ? { CLIPY_CDP_URL: cdpHttpUrl } : {}),
4210
+ // chrome-extension: the exact recorded tab, since other tabs in the
4211
+ // persistent profile can share its url.
4212
+ ...(targetId && started?.chromePort
4213
+ ? { CLIPY_TARGET_ID: targetId, CLIPY_PAGE_WS_URL: `ws://127.0.0.1:${started.chromePort}/devtools/page/${targetId}` }
4214
+ : {}),
3762
4215
  },
3763
4216
  });
3764
4217
  // Forward Ctrl-C / termination to the child; its exit then drives the abort
@@ -3870,58 +4323,125 @@ async function runSessionDaemon(file) {
3870
4323
  // the Chromium).
3871
4324
  let ctxToClose = null;
3872
4325
  let controlServer = null;
4326
+ let discardCapture = null;
3873
4327
  try {
3874
4328
  const chromium = await loadChromium();
3875
- log(`launching chromium for ${state.url}`);
3876
- // CDP is OPT-IN (--expose-cdp) and the env kill switch wins over the flag:
3877
- // no debugging port is opened unless the user asked AND CLIPY_DISABLE_CDP
3878
- // isn't set. When enabled, Playwright still controls the browser over its
3879
- // own pipe; the extra --remote-debugging-port opens a parallel TCP endpoint
3880
- // an agent can attach to.
3881
- const wantCdp = !!state.exposeCdp && process.env.CLIPY_DISABLE_CDP !== "1";
3882
- if (state.exposeCdp && !wantCdp)
3883
- log("CDP disabled by CLIPY_DISABLE_CDP=1 — not opening a debugging port");
3884
- const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
3885
- // --user-data-dir ⇒ a persistent context (its own browser); else an ephemeral
3886
- // browser + context. The CDP debugging port (if any) rides the launch args.
3887
- const { context, browser: launchedBrowser } = await launchRecordingContext(chromium, {
3888
- userDataDir: state.userDataDir,
3889
- viewport: { width: state.width, height: state.height },
3890
- recordVideoDir: state.tmpDir,
3891
- args: [
3892
- "--no-sandbox",
3893
- "--disable-dev-shm-usage",
3894
- ...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
3895
- ],
3896
- storageStatePath: state.storageStatePath,
3897
- });
3898
- browser = launchedBrowser;
3899
- ctxToClose = context;
3900
- // Seed cookies/localStorage/init-script before the first navigation — re-parse
3901
- // the raw specs the parent CLI already validated. A bad spec here is caught by
3902
- // the outer try/catch and fails the session cleanly. (--storage-state was
3903
- // applied at launch; it and --user-data-dir are mutually exclusive.)
3904
- await applyAuthCapture(context, {
3905
- storageStatePath: state.storageStatePath,
3906
- initScriptPath: state.initScriptPath,
3907
- cookieSpecs: state.cookieSpecs ?? [],
3908
- localStorageSpecs: state.localStorageSpecs ?? [],
3909
- }, state.url);
3910
- // Persistent contexts open with a default page; ephemeral ones start empty.
3911
- const page = context.pages()[0] ?? (await context.newPage());
3912
- // Best-effort: publish the CDP URL so `session start`/`status` can hand it
3913
- // to the agent. The recording works fine even if discovery fails.
4329
+ let page;
3914
4330
  let cdpUrl;
3915
4331
  let cdpHttpUrl;
3916
- if (cdpPort) {
3917
- cdpUrl = (await discoverCdpWsUrl(cdpPort)) ?? undefined;
3918
- if (cdpUrl) {
3919
- cdpHttpUrl = `http://127.0.0.1:${cdpPort}`;
3920
- log(`CDP endpoint ready at ${cdpHttpUrl} (${cdpUrl})`);
3921
- }
3922
- else {
3923
- log(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
4332
+ // Mode-specific teardown, so the shared stop/abort paths below don't care
4333
+ // which capture engine is running. finishCapture returns the finished
4334
+ // capture's file path; discardCapture drops it.
4335
+ let finishCapture;
4336
+ // Whether a CDP driver can attach (and so whether the in-page mark bindings
4337
+ // below get installed), plus the context to install them on.
4338
+ let wantCdp = false;
4339
+ let bindingContext = null;
4340
+ if (state.kind === "chrome-for-clipy") {
4341
+ const port = state.chromePort ?? DEFAULT_CDP_PORT;
4342
+ log(`attaching to Chrome for Clipy on port ${port} for ${state.url}`);
4343
+ const cap = await startChromeForClipyCapture(chromium, {
4344
+ home: homedir(),
4345
+ env: process.env,
4346
+ platform: process.platform,
4347
+ port,
4348
+ tmpDir: state.tmpDir,
4349
+ targetUrl: state.url,
4350
+ log,
4351
+ });
4352
+ // For a CDP-connected browser, close() disconnects and leaves Chrome for
4353
+ // Clipy running; it must never be killed by a session ending.
4354
+ browser = cap.browser;
4355
+ page = cap.page;
4356
+ // The instance's CDP endpoint is inherently open, so publish it always so
4357
+ // drivers attach to the same browser the session is recording.
4358
+ cdpUrl = (await discoverCdpWsUrl(port)) ?? undefined;
4359
+ cdpHttpUrl = `http://127.0.0.1:${port}`;
4360
+ wantCdp = true;
4361
+ bindingContext = cap.browser.contexts()[0];
4362
+ finishCapture = async () => {
4363
+ const videoPath = await cap.stop();
4364
+ if (browser)
4365
+ await browser.close().catch(() => { });
4366
+ browser = null;
4367
+ return videoPath;
4368
+ };
4369
+ discardCapture = async () => {
4370
+ await cap.discard().catch(() => { });
4371
+ if (browser)
4372
+ await browser.close().catch(() => { });
4373
+ browser = null;
4374
+ };
4375
+ }
4376
+ else {
4377
+ log(`launching chromium for ${state.url}`);
4378
+ // CDP is OPT-IN (--expose-cdp) and the env kill switch wins over the flag:
4379
+ // no debugging port is opened unless the user asked AND CLIPY_DISABLE_CDP
4380
+ // isn't set. When enabled, Playwright still controls the browser over its
4381
+ // own pipe; the extra --remote-debugging-port opens a parallel TCP endpoint
4382
+ // an agent can attach to.
4383
+ wantCdp = !!state.exposeCdp && process.env.CLIPY_DISABLE_CDP !== "1";
4384
+ if (state.exposeCdp && !wantCdp)
4385
+ log("CDP disabled by CLIPY_DISABLE_CDP=1 — not opening a debugging port");
4386
+ const cdpPort = wantCdp ? await pickFreePort().catch(() => 0) : 0;
4387
+ // --user-data-dir ⇒ a persistent context (its own browser); else an ephemeral
4388
+ // browser + context. The CDP debugging port (if any) rides the launch args.
4389
+ const { context, browser: launchedBrowser } = await launchRecordingContext(chromium, {
4390
+ userDataDir: state.userDataDir,
4391
+ viewport: { width: state.width, height: state.height },
4392
+ recordVideoDir: state.tmpDir,
4393
+ args: [
4394
+ "--no-sandbox",
4395
+ "--disable-dev-shm-usage",
4396
+ ...(cdpPort ? [`--remote-debugging-port=${cdpPort}`] : []),
4397
+ ],
4398
+ storageStatePath: state.storageStatePath,
4399
+ });
4400
+ browser = launchedBrowser;
4401
+ ctxToClose = context;
4402
+ bindingContext = context;
4403
+ // Seed cookies/localStorage/init-script before the first navigation — re-parse
4404
+ // the raw specs the parent CLI already validated. A bad spec here is caught by
4405
+ // the outer try/catch and fails the session cleanly. (--storage-state was
4406
+ // applied at launch; it and --user-data-dir are mutually exclusive.)
4407
+ await applyAuthCapture(context, {
4408
+ storageStatePath: state.storageStatePath,
4409
+ initScriptPath: state.initScriptPath,
4410
+ cookieSpecs: state.cookieSpecs ?? [],
4411
+ localStorageSpecs: state.localStorageSpecs ?? [],
4412
+ }, state.url);
4413
+ // Persistent contexts open with a default page; ephemeral ones start empty.
4414
+ page = context.pages()[0] ?? (await context.newPage());
4415
+ // Best-effort: publish the CDP URL so `session start`/`status` can hand it
4416
+ // to the agent. The recording works fine even if discovery fails.
4417
+ if (cdpPort) {
4418
+ cdpUrl = (await discoverCdpWsUrl(cdpPort)) ?? undefined;
4419
+ if (cdpUrl) {
4420
+ cdpHttpUrl = `http://127.0.0.1:${cdpPort}`;
4421
+ log(`CDP endpoint ready at ${cdpHttpUrl} (${cdpUrl})`);
4422
+ }
4423
+ else {
4424
+ log(`CDP endpoint not reachable on port ${cdpPort} — browser drive unavailable`);
4425
+ }
3924
4426
  }
4427
+ finishCapture = async () => {
4428
+ const video = page.video();
4429
+ await page.close();
4430
+ await context.close();
4431
+ if (!video)
4432
+ throw new Error("browser did not produce a video (recordVideo unavailable)");
4433
+ const videoPath = await video.path();
4434
+ // Persistent mode: context.close() already tore down Chromium; there is
4435
+ // no separate browser to close.
4436
+ if (browser)
4437
+ await browser.close().catch(() => { });
4438
+ browser = null;
4439
+ return videoPath;
4440
+ };
4441
+ discardCapture = async () => {
4442
+ await page.close().catch(() => { });
4443
+ await context.close().catch(() => { });
4444
+ };
3925
4445
  }
3926
4446
  // Auto-marks: instrumentation ground truth alongside the agent's intent
3927
4447
  // marks. Type-tagged with [auto] so the transcript distinguishes them.
@@ -4020,9 +4540,12 @@ async function runSessionDaemon(file) {
4020
4540
  // The bindings are exposed under *Impl names and re-declared with explicit
4021
4541
  // arity below, so an agent probing window.__clipyMark.length sees 2 (not the
4022
4542
  // 0 an exposeBinding wrapper reports).
4023
- if (wantCdp) {
4024
- await context
4025
- .exposeBinding("__clipyMarkImpl", async (_src, ...args) => {
4543
+ if (wantCdp && bindingContext) {
4544
+ const bindings = page;
4545
+ await bindings
4546
+ .exposeBinding("__clipyMarkImpl", async (source, ...args) => {
4547
+ if (source.page !== page || source.frame !== page.mainFrame())
4548
+ throw new Error("Only the recorded main frame can emit marks");
4026
4549
  if (recordStart === 0)
4027
4550
  return { skipped: true };
4028
4551
  const o = (args[1] ?? {});
@@ -4043,8 +4566,10 @@ async function runSessionDaemon(file) {
4043
4566
  return await applyMark({ text: String(args[0] ?? ""), assert });
4044
4567
  })
4045
4568
  .catch((e) => log(`__clipyMark binding failed: ${e.message}`));
4046
- await context
4047
- .exposeBinding("__clipyChapterImpl", (_src, ...args) => {
4569
+ await bindings
4570
+ .exposeBinding("__clipyChapterImpl", (source, ...args) => {
4571
+ if (source.page !== page || source.frame !== page.mainFrame())
4572
+ throw new Error("Only the recorded main frame can emit chapters");
4048
4573
  if (recordStart === 0)
4049
4574
  return;
4050
4575
  const label = String(args[0] ?? "").trim();
@@ -4055,12 +4580,19 @@ async function runSessionDaemon(file) {
4055
4580
  .catch((e) => log(`__clipyChapter binding failed: ${e.message}`));
4056
4581
  // Declared-arity wrappers so window.__clipyMark.length === 2 / __clipyChapter
4057
4582
  // === 1 (they resolve the *Impl bindings lazily, at call time).
4058
- await context
4583
+ await bindings
4059
4584
  .addInitScript({
4060
4585
  content: "window.__clipyMark = (text, opts) => window.__clipyMarkImpl(text, opts);\n" +
4061
4586
  "window.__clipyChapter = (label) => window.__clipyChapterImpl(label);",
4062
4587
  })
4063
4588
  .catch((e) => log(`in-page binding wrappers failed: ${e.message}`));
4589
+ if (state.kind === "chrome-for-clipy") {
4590
+ await page.evaluate(() => {
4591
+ const w = globalThis;
4592
+ w.__clipyMark = (text, opts) => w.__clipyMarkImpl(text, opts);
4593
+ w.__clipyChapter = (label) => w.__clipyChapterImpl(label);
4594
+ });
4595
+ }
4064
4596
  }
4065
4597
  // Local control endpoint: `clipy mark`/`chapter` POST here so the daemon —
4066
4598
  // which owns the live page — evaluates assertions and stamps marks on its
@@ -4186,11 +4718,16 @@ async function runSessionDaemon(file) {
4186
4718
  cdpHttpUrl,
4187
4719
  ...(controlPort ? { controlPort, controlToken } : {}),
4188
4720
  });
4189
- try {
4190
- await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
4191
- }
4192
- catch {
4193
- log("page load timed out; recording current state anyway");
4721
+ // chrome-for-clipy already navigated the target before capture started (the
4722
+ // marker-title selection requires a loaded page); re-navigating here would
4723
+ // just reload it on camera.
4724
+ if (state.kind !== "chrome-for-clipy") {
4725
+ try {
4726
+ await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
4727
+ }
4728
+ catch {
4729
+ log("page load timed out; recording current state anyway");
4730
+ }
4194
4731
  }
4195
4732
  // Main loop: poll the control file; enforce the max-duration rail.
4196
4733
  let stopReason = "stop";
@@ -4225,8 +4762,8 @@ async function runSessionDaemon(file) {
4225
4762
  if (stopReason === "abort") {
4226
4763
  log("abort requested — discarding capture");
4227
4764
  save({ state: "aborted" });
4228
- await page.close().catch(() => { });
4229
- await context.close().catch(() => { });
4765
+ await discardCapture();
4766
+ discardCapture = null;
4230
4767
  try {
4231
4768
  rmSync(state.tmpDir, { recursive: true, force: true });
4232
4769
  }
@@ -4240,17 +4777,8 @@ async function runSessionDaemon(file) {
4240
4777
  log(`max duration ${state.maxSec}s reached — auto-stopping and uploading`);
4241
4778
  }
4242
4779
  save({ state: "stopping" });
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() (above) already tore down Chromium; there
4250
- // is no separate browser to close.
4251
- if (browser)
4252
- await browser.close().catch(() => { });
4253
- browser = null;
4780
+ const videoPath = await finishCapture();
4781
+ discardCapture = null;
4254
4782
  // Merge marks. The FILE is the mark of record: `clipy mark` writes there when
4255
4783
  // its control call fails, and a timed-out ASSERTION is recorded ⚠-unverified.
4256
4784
  // That ⚠ is authoritative — if the daemon later evaluated the same mark, that
@@ -4391,6 +4919,8 @@ async function runSessionDaemon(file) {
4391
4919
  finally {
4392
4920
  if (controlServer)
4393
4921
  controlServer.close();
4922
+ if (discardCapture)
4923
+ await discardCapture().catch(() => { });
4394
4924
  // Persistent (--user-data-dir) contexts have no separate browser, so an
4395
4925
  // exception before the stop/abort path must close the context to avoid
4396
4926
  // leaking Chromium. Both closes are no-ops if the object is already closed.
@@ -4450,7 +4980,7 @@ function writeSkillFile(path) {
4450
4980
  // setup — skill + MCP + login in one command, for an agent following the
4451
4981
  // published setup instructions at clipy.online/agent-setup/prompt.md.
4452
4982
  // ---------------------------------------------------------------------------
4453
- async function cmdSetup(ctx, targetRaw, json) {
4983
+ async function cmdSetup(ctx, targetRaw, json, withBrowser) {
4454
4984
  const env = realSetupEnv();
4455
4985
  let target;
4456
4986
  if (targetRaw) {
@@ -4500,6 +5030,39 @@ async function cmdSetup(ctx, targetRaw, json) {
4500
5030
  catch (error) {
4501
5031
  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 });
4502
5032
  }
5033
+ let browser = null;
5034
+ if (withBrowser) {
5035
+ const chrome = { appInstalled: false, running: false };
5036
+ try {
5037
+ if (process.platform === "darwin") {
5038
+ const appPath = chromeForClipyAppPath(env.home);
5039
+ // Keep an existing launcher; `clipy chrome install-app` explicitly
5040
+ // refreshes its flags, executable path, and icon.
5041
+ if (existsSync(appPath)) {
5042
+ chrome.appInstalled = true;
5043
+ chrome.appPath = appPath;
5044
+ }
5045
+ else {
5046
+ const installed = installChromeForClipyApp(env.home, env.env, process.platform, DEFAULT_CDP_PORT);
5047
+ if (installed.ok) {
5048
+ chrome.appInstalled = true;
5049
+ chrome.appPath = installed.path;
5050
+ }
5051
+ else {
5052
+ chrome.error = installed.error;
5053
+ }
5054
+ }
5055
+ }
5056
+ const up = await startChromeForClipy(env.home, env.env, process.platform, DEFAULT_CDP_PORT);
5057
+ chrome.running = up.ok;
5058
+ if (!up.ok)
5059
+ chrome.error = chrome.error ?? up.error;
5060
+ }
5061
+ catch (error) {
5062
+ chrome.error = error instanceof Error ? error.message : String(error);
5063
+ }
5064
+ browser = { ok: chrome.running, chrome };
5065
+ }
4503
5066
  if (json) {
4504
5067
  printJson({
4505
5068
  ok: true,
@@ -4508,6 +5071,7 @@ async function cmdSetup(ctx, targetRaw, json) {
4508
5071
  mcp,
4509
5072
  authenticated: true,
4510
5073
  restartRequired: true,
5074
+ ...(browser ? { browser } : {}),
4511
5075
  docs: "https://clipy.online/agent-setup/prompt.md",
4512
5076
  });
4513
5077
  return;
@@ -4517,11 +5081,160 @@ async function cmdSetup(ctx, targetRaw, json) {
4517
5081
  `✓ Skill ${short(skillPath)}`,
4518
5082
  `✓ MCP ${mcp.path ? short(mcp.path) : (mcp.command ?? target)}${mcp.alreadyPresent && !mcp.changed ? " (already registered)" : ""}`,
4519
5083
  `✓ Signed in`,
4520
- "",
4521
- "→ Restart your agent to load the MCP server",
4522
5084
  ];
5085
+ if (browser) {
5086
+ rows.push(browser.chrome.running
5087
+ ? `✓ Chrome ${CHROME_FOR_CLIPY_APP_NAME} ${browser.chrome.appInstalled ? "installed and " : ""}running; sign in once to persist logins`
5088
+ : `✗ Chrome ${browser.chrome.error ?? `${CHROME_FOR_CLIPY_APP_NAME} did not start`}`);
5089
+ }
5090
+ rows.push("", "→ Restart your agent to load the MCP server");
4523
5091
  process.stdout.write(`${renderSetupBox("Clipy setup complete", rows)}\n`);
4524
5092
  }
5093
+ // ---------------------------------------------------------------------------
5094
+ // chrome: the dedicated "Chrome for Clipy" automation browser.
5095
+ // ---------------------------------------------------------------------------
5096
+ async function cmdChrome(sub, json, portRaw) {
5097
+ const home = homedir();
5098
+ const port = portRaw ? Number(portRaw) : DEFAULT_CDP_PORT;
5099
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
5100
+ die("usage: clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--json]", 2);
5101
+ }
5102
+ switch (sub) {
5103
+ case "setup":
5104
+ await cmdChromeSetup(home, port, json);
5105
+ return;
5106
+ case "start": {
5107
+ const result = await startChromeForClipy(home, process.env, process.platform, port);
5108
+ if (!result.ok) {
5109
+ if (json)
5110
+ printJson({ ok: false, error: result.error });
5111
+ else
5112
+ process.stderr.write(`error: ${result.error}\n`);
5113
+ process.exit(1);
5114
+ }
5115
+ const status = await chromeStatus(home, process.platform);
5116
+ if (json) {
5117
+ printJson({ ok: true, ...status, captureTitleMarker: TAB_CAPTURE_TITLE_MARKER });
5118
+ return;
5119
+ }
5120
+ process.stdout.write(`${CHROME_FOR_CLIPY_APP_NAME} running (pid ${status.pid})\n` +
5121
+ ` CDP: ${status.cdpUrl}\n` +
5122
+ ` Profile: ${status.profileDir}\n` +
5123
+ ` Capture: retitle a tab to start with "${TAB_CAPTURE_TITLE_MARKER}" and getDisplayMedia auto-selects it (no picker)\n`);
5124
+ return;
5125
+ }
5126
+ case "stop": {
5127
+ const result = stopChromeForClipy(home);
5128
+ if (json)
5129
+ printJson({ ok: result.ok, stopped: result.stopped, ...(result.error ? { error: result.error } : {}) });
5130
+ else if (!result.ok)
5131
+ process.stderr.write(`error: ${result.error}\n`);
5132
+ else
5133
+ process.stdout.write(result.stopped ? "stopped\n" : "not running\n");
5134
+ if (!result.ok)
5135
+ process.exit(1);
5136
+ return;
5137
+ }
5138
+ case "status": {
5139
+ const status = await chromeStatus(home, process.platform);
5140
+ if (json) {
5141
+ printJson({ ok: true, ...status, captureTitleMarker: TAB_CAPTURE_TITLE_MARKER });
5142
+ return;
5143
+ }
5144
+ process.stdout.write(status.running
5145
+ ? `running (pid ${status.pid}), CDP ${status.cdpUrl} (${status.cdpReady ? (status.browser ?? "ready") : "not answering"})\n`
5146
+ : "not running\n");
5147
+ process.stdout.write(`profile: ${status.profileDir}\napp installed: ${status.appInstalled ? "yes" : "no"}\n`);
5148
+ return;
5149
+ }
5150
+ case "install-app": {
5151
+ const result = installChromeForClipyApp(home, process.env, process.platform, port);
5152
+ if (!result.ok) {
5153
+ if (json)
5154
+ printJson({ ok: false, error: result.error });
5155
+ else
5156
+ process.stderr.write(`error: ${result.error}\n`);
5157
+ process.exit(1);
5158
+ }
5159
+ if (json)
5160
+ printJson({ ok: true, path: result.path });
5161
+ else
5162
+ process.stdout.write(`Installed "${CHROME_FOR_CLIPY_APP_NAME}" at ${result.path}\n` +
5163
+ `Open it from Finder/Spotlight, or keep using clipy chrome start.\n`);
5164
+ return;
5165
+ }
5166
+ default:
5167
+ die("usage: clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--json]", 2);
5168
+ }
5169
+ }
5170
+ const CHROME_SETUP_TIMEOUT_MS = 15 * 60_000;
5171
+ /** One-time setup for `--source chrome-extension`. Two steps need the person
5172
+ * (Chrome does not allow scripting a Web Store install, and signing in is
5173
+ * theirs), so this opens the right page for each and waits until the
5174
+ * extension itself reports it is installed and signed in. Re-running it on a
5175
+ * ready instance is a quick check. */
5176
+ async function cmdChromeSetup(home, port, json) {
5177
+ const say = (m) => {
5178
+ if (!json)
5179
+ process.stdout.write(`${m}\n`);
5180
+ };
5181
+ // What the person must do. On stderr with --json, so an agent waiting on
5182
+ // setup can relay it while stdout stays one JSON object.
5183
+ const ask = (m) => {
5184
+ (json ? process.stderr : process.stdout).write(`${m}\n`);
5185
+ };
5186
+ const fail = (error) => {
5187
+ if (json)
5188
+ printJson({ ok: false, error });
5189
+ else
5190
+ process.stderr.write(`error: ${error}\n`);
5191
+ process.exit(1);
5192
+ };
5193
+ // Always rewritten: the launcher bakes in the launch flags, and one from an
5194
+ // older CLI would start Chrome without --allowlisted-extension-id.
5195
+ if (process.platform === "darwin") {
5196
+ const app = installChromeForClipyApp(home, process.env, process.platform, port);
5197
+ if (app.ok)
5198
+ say(`updated the "${CHROME_FOR_CLIPY_APP_NAME}" launcher at ${app.path}`);
5199
+ }
5200
+ const started = await startChromeForClipy(home, process.env, process.platform, port);
5201
+ if (!started.ok)
5202
+ fail(started.error);
5203
+ const openTab = (url) => openTabForPerson(port, url).catch(() => { });
5204
+ const deadline = Date.now() + CHROME_SETUP_TIMEOUT_MS;
5205
+ let askedInstall = false;
5206
+ let askedSignIn = false;
5207
+ for (;;) {
5208
+ const ready = await extensionReadiness(port, process.env);
5209
+ if (ready.installed && ready.error)
5210
+ fail(ready.error);
5211
+ if (ready.installed && ready.signedIn) {
5212
+ const status = await chromeStatus(home, process.platform);
5213
+ if (json) {
5214
+ printJson({ ok: true, extension: { version: ready.version, email: ready.email }, chrome: status });
5215
+ }
5216
+ else {
5217
+ say(`${c.green("✓")} Chrome for Clipy is ready: extension ${ready.version}, signed in${ready.email ? ` as ${ready.email}` : ""}`);
5218
+ say(`${c.dim("record a tab with:")} clipy session start --source chrome-extension --url <url>`);
5219
+ }
5220
+ return;
5221
+ }
5222
+ if (!ready.installed && !askedInstall) {
5223
+ askedInstall = true;
5224
+ await openTab(extensionStoreUrl(process.env));
5225
+ ask(`→ In the ${CHROME_FOR_CLIPY_APP_NAME} window, click "Add to Chrome" on the Clipy extension page. Waiting…`);
5226
+ }
5227
+ else if (ready.installed && !ready.signedIn && !askedSignIn) {
5228
+ askedSignIn = true;
5229
+ await openTab("https://clipy.online/?signin=1&signup_flow=extension");
5230
+ ask(`→ Sign in to Clipy in the ${CHROME_FOR_CLIPY_APP_NAME} window. Waiting…`);
5231
+ }
5232
+ if (Date.now() >= deadline) {
5233
+ fail(ready.installed ? "timed out waiting for sign-in" : "timed out waiting for the Clipy extension to be installed");
5234
+ }
5235
+ await new Promise((r) => setTimeout(r, 3000));
5236
+ }
5237
+ }
4525
5238
  function failSetup(json, code, error, remediation, partial = null, exitCode = 1) {
4526
5239
  if (json) {
4527
5240
  printJson({ ok: false, code, error, remediation, partial });
@@ -4686,14 +5399,15 @@ function cmdGuide(json) {
4686
5399
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
4687
5400
  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"]),
4688
5401
  cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--type kind] [--note '12: text']… [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. Notes are absolute ('12: text') or pass-scoped ('pass2: text' / 'pass2@5: text', anchored to a --viewports pass's real start; a malformed pass note is rejected). --type declares the recording kind (bug_report|feature_request|product_demo|walkthrough_tutorial|feedback_review|discussion_talk|other, plus aliases bug/feature/demo/walkthrough/feedback/discussion) so the AI summary reads it correctly. Auth (web capture only, applied before the first navigation so a logged-in SPA's route guard sees it): --storage-state <playwright storageState JSON path>, --cookie 'name=value[; Domain=d; Path=p; Secure; HttpOnly; SameSite=Lax]' (repeatable), --local-storage 'key=value' (repeatable, target origin only), --init-script <js file run before every page load>, --user-data-dir <dir> (launch from a persistent Chromium user-data ROOT with its whole logged-in identity; web only, mutually exclusive with --storage-state; refused if <dir> is a profile subdir — pass the root — or, in direct mode, a live-locked root via SingletonLock/Socket), --profile-directory <name> (with --user-data-dir: pick a NAMED profile like 'Profile 12' from chrome://version; Playwright can't select a profile in place, so Clipy COPIES it into a temp recording root and launches the copy — loudly disclosed, the real profile is never opened or written, and the copy is deleted after upload; no need to quit Chrome, though it warns if Chrome is running since in-use DBs may copy inconsistently). Auth boundary: --storage-state only seeds what the file contains; for cross-origin auth produce it with `npx playwright open --save-storage=auth.json <login-host>`, or use --user-data-dir + --profile-directory to record your real profile, or --source mac-screen --window Chrome. With --source mac-screen: records the real screen via the Clipy Mac app (--type not yet applied on mac; auth flags rejected — the screen is already logged in); --window '<title|app|id>' records that window's initial screen area and --display <id> records one display (ids from clipy sources). --json prints {id, shareUrl, contextUrl, sizeBytes}", ["--for", "--viewports", "--title", "--description", "--type", "--note", "--storage-state", "--cookie", "--local-storage", "--init-script", "--user-data-dir", "--profile-directory", "--width", "--height", "--wait", "--source", "--window", "--display", "--json"]),
4689
- 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"]),
5402
+ cmdDoc("session", "clipy session <start|run|stop|abort|status> [--url <url>] [--max sec] [--type kind] [--source web|mac-screen|chrome-for-clipy|chrome-extension] [--window w] [--display d] [--expose-cdp] [--storage-state f] [--cookie 'n=v']… [--local-storage 'k=v']… [--init-script f] [--json]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --type sets the recording kind (see record). With --source mac-screen, --window records that window's initial screen area and --display records one display. --source chrome-extension records ONE TAB through the Clipy extension inside Chrome for Clipy (needs a one-time clipy chrome setup): no daemon, the extension records and uploads; start returns cdpHttpUrl and the recorded tab's url (opened in the background, never focused), --name titles the recording, the tab's sound is left out unless --tab-audio (detected speech would replace the marks as the transcript), mark/chapter (plain or --observed/--verdict, not --assert-*) are kept by the CLI and sent at stop as the transcript, stop waits for the upload and returns the link. --source chrome-for-clipy records ONE TAB (tab video + tab audio, no picker or gesture) inside the persistent Chrome for Clipy instance: the instance is started automatically (sign in once via clipy chrome start and the profile stays signed in), the recorded tab opens at --url, its CDP endpoint is always published as cdpUrl/cdpHttpUrl so drivers attach to the very browser being recorded, and stopping the session leaves Chrome for Clipy running; auth-capture flags and --user-data-dir are rejected for this source. --expose-cdp (web sessions) opens a CDP endpoint (cdpUrl/cdpHttpUrl in the state file + session start/status output) so your own tools can drive the page while it records; OFF by default (any local process could attach), and CLIPY_DISABLE_CDP=1 forces it off. `session run [start flags] -- <command…>` starts a session, runs the command with inherited stdio (env CLIPY_SESSION=1, plus CLIPY_CDP_URL when --expose-cdp, plus CLIPY_TARGET_ID/CLIPY_PAGE_WS_URL for the recorded tab with --source chrome-extension), then GUARANTEES cleanup: exit 0 uploads, any non-zero exit or signal discards (session abort) and propagates the child's code. It is the crash-safe wrapper, so a dead driver never records dead air. Accepts the same auth flags as record (--storage-state/--user-data-dir/--profile-directory/--cookie/--local-storage/--init-script; web only, rejected on --source mac-screen). `session run` exports CLIPY_SESSION_FILE to the child so mark/chapter resolve the session from any cwd. --json is supported on start/stop/status (start returns cdpUrl/cdpHttpUrl)", ["run", "--url", "--max", "--type", "--source", "--window", "--display", "--tab-audio", "--expose-cdp", "--storage-state", "--user-data-dir", "--profile-directory", "--cookie", "--local-storage", "--init-script", "--json"]),
4690
5403
  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"]),
4691
5404
  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"]),
4692
5405
  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"]),
4693
5406
  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"]),
4694
5407
  cmdDoc("sources", "clipy sources [--json]", "List displays + windows the Clipy Mac app can capture — ids feed --window/--display. --json gives each entry a `source` {kind,id,title} in the SAME shape session start/record report for the resolved capture, so a caller can compare what it picked against what the camera reports without transforming either."),
4695
- 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"]),
5408
+ 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"]),
4696
5409
  cmdDoc("agents", "clipy agents <status|install|uninstall> <claude|codex|cursor|windsurf|opencode>", "Skill file only — does NOT register MCP. `clipy setup` is the one-command form; install triggers a browser login first when no key is configured (interactive terminals only)"),
5410
+ cmdDoc("chrome", "clipy chrome <setup|start|stop|status|install-app> [--port <n>] [--json]", "setup (one time, for --source chrome-extension): starts Chrome for Clipy, opens the Clipy extension's Web Store page and then clipy.online in that window, and waits up to 15 minutes until the extension reports it is installed and signed in; returns {ok:true, extension:{version,email}, chrome} and is a quick check on a ready machine. The two steps it waits for are the user's: an agent relays them and never performs them. Chrome for Clipy also launches with --allowlisted-extension-id (CLIPY_EXTENSION_ID overrides the store id), and an instance found running without the current flags is relaunched. Launch and manage 'Chrome for Clipy', a dedicated persistent automation browser: its own profile (sign in once, identity persists across launches), CDP on --port (default 9333) for any driver, --auto-select-tab-capture-source-by-title so a page's getDisplayMedia captures the tab whose title starts with the 'clipy-rec' marker without any picker or gesture UI, and background-throttling disabled so hidden tabs keep rendering. start is idempotent (re-reports the running instance); status returns {running,pid,port,cdpUrl,cdpReady,profileDir,appInstalled,captureTitleMarker}; install-app writes a named 'Chrome for Clipy.app' launcher into ~/Applications (macOS only). Drivers attach over raw CDP; no extension is needed.", ["--port", "--json"]),
4697
5411
  cmdDoc("guide", "clipy guide --json", "This manifest"),
4698
5412
  cmdDoc("mcp", "clipy mcp", "Run the Clipy MCP server (wraps npx -y @clipy/mcp)"),
4699
5413
  ],
@@ -4801,6 +5515,8 @@ async function main() {
4801
5515
  key: { type: "string" },
4802
5516
  paste: { type: "boolean", default: false },
4803
5517
  "no-browser": { type: "boolean", default: false },
5518
+ "with-browser": { type: "boolean", default: false },
5519
+ port: { type: "string" },
4804
5520
  "api-url": { type: "string" },
4805
5521
  status: { type: "string" },
4806
5522
  page: { type: "string" },
@@ -4811,6 +5527,7 @@ async function main() {
4811
5527
  "marks-only": { type: "boolean", default: false },
4812
5528
  mic: { type: "boolean", default: false },
4813
5529
  "no-system-audio": { type: "boolean", default: false },
5530
+ "tab-audio": { type: "boolean", default: false },
4814
5531
  vtt: { type: "boolean", default: false },
4815
5532
  for: { type: "string" },
4816
5533
  timeout: { type: "string" },
@@ -5088,7 +5805,10 @@ async function main() {
5088
5805
  await cmdPlaywrightPath(json);
5089
5806
  return;
5090
5807
  case "setup":
5091
- await cmdSetup(ctx, rest[0], json);
5808
+ await cmdSetup(ctx, rest[0], json, values["with-browser"] === true);
5809
+ return;
5810
+ case "chrome":
5811
+ await cmdChrome(rest[0], json, values.port);
5092
5812
  return;
5093
5813
  case "agents":
5094
5814
  await cmdAgents(ctx, rest[0], rest[1], json);
@@ -5234,8 +5954,8 @@ async function main() {
5234
5954
  // start <url>) — `run` has no positional url, only --url.
5235
5955
  const buildStartOpts = (positionalUrl) => {
5236
5956
  const source = String(values.source ?? "web");
5237
- if (source !== "web" && source !== "mac-screen") {
5238
- die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
5957
+ if (source !== "web" && source !== "mac-screen" && source !== "chrome-for-clipy" && source !== "chrome-extension") {
5958
+ die("--source must be web (headless browser), mac-screen (the Clipy Mac app), chrome-for-clipy (the persistent automation browser), or chrome-extension (the Clipy extension inside Chrome for Clipy)", 2);
5239
5959
  }
5240
5960
  if ((values.window || values.display) && source !== "mac-screen") {
5241
5961
  die("--window/--display record the real screen — add --source mac-screen", 2);
@@ -5245,11 +5965,17 @@ async function main() {
5245
5965
  }
5246
5966
  if (source === "mac-screen" && authFlagsPresent)
5247
5967
  die(macAuthGuard, 2);
5968
+ if ((source === "chrome-for-clipy" || source === "chrome-extension") && authFlagsPresent) {
5969
+ die(`auth-capture flags don't apply to --source ${source}; sign into the Chrome for Clipy profile once (clipy chrome setup) and it stays signed in`, 2);
5970
+ }
5248
5971
  if (source !== "mac-screen" && audioFlagsPresent)
5249
5972
  die(webAudioGuard, 2);
5973
+ if (values["tab-audio"] && source !== "chrome-extension") {
5974
+ die("--tab-audio applies to --source chrome-extension only", 2);
5975
+ }
5250
5976
  const url = values.url?.trim() || positionalUrl;
5251
- if (!url && source === "web") {
5252
- die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen]", 2);
5977
+ if (!url && source !== "mac-screen") {
5978
+ die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen|chrome-for-clipy|chrome-extension]", 2);
5253
5979
  }
5254
5980
  return {
5255
5981
  url: url || "mac-screen",
@@ -5269,6 +5995,7 @@ async function main() {
5269
5995
  userDataDir: userDataDir(),
5270
5996
  profileDirectory: profileDirectory(),
5271
5997
  audio: audioChoice(),
5998
+ tabAudio: Boolean(values["tab-audio"]),
5272
5999
  };
5273
6000
  };
5274
6001
  if (sub === "start") {