@clipy/cli 0.15.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.
@@ -0,0 +1,277 @@
1
+ /**
2
+ * A minimal Chrome DevTools Protocol client for Chrome for Clipy.
3
+ *
4
+ * Playwright's connectOverCDP attaches to EVERY target in the browser before
5
+ * it returns, so one stuck tab (a hung renderer, an embedded view, another
6
+ * extension's page) blocks it indefinitely. Chrome for Clipy is long-lived and
7
+ * full of the person's own tabs, so the extension path talks to the browser
8
+ * endpoint directly and attaches only to the tabs it creates.
9
+ *
10
+ * Uses the global WebSocket where Node has one (22+) and otherwise a small
11
+ * RFC 6455 client over node:http, so the CLI keeps its Node 18 floor and its
12
+ * zero runtime dependencies.
13
+ */
14
+ import { request } from "node:http";
15
+ import { randomBytes } from "node:crypto";
16
+ function openWithGlobalWebSocket(url, onMessage, onClose, signal) {
17
+ const WS = globalThis.WebSocket;
18
+ const ws = new WS(url);
19
+ signal.addEventListener("abort", () => ws.close(), { once: true });
20
+ return new Promise((resolve, reject) => {
21
+ ws.onopen = () => resolve({ send: (t) => ws.send(t), close: () => ws.close() });
22
+ ws.onerror = () => reject(new Error(`could not open ${url}`));
23
+ ws.onmessage = (e) => onMessage(String(e.data));
24
+ ws.onclose = () => onClose("socket closed");
25
+ });
26
+ }
27
+ /** Client side of RFC 6455: masked text frames out; text, continuation,
28
+ * ping and close frames in. Enough for CDP, which sends JSON text frames. */
29
+ function openWithHttpUpgrade(url, onMessage, onClose, signal) {
30
+ const target = new URL(url);
31
+ return new Promise((resolve, reject) => {
32
+ // A stalled handshake must not keep the process alive after its timeout.
33
+ signal.addEventListener("abort", () => req.destroy(), { once: true });
34
+ const req = request({
35
+ host: target.hostname,
36
+ port: target.port,
37
+ path: target.pathname + target.search,
38
+ headers: {
39
+ Connection: "Upgrade",
40
+ Upgrade: "websocket",
41
+ "Sec-WebSocket-Version": "13",
42
+ "Sec-WebSocket-Key": randomBytes(16).toString("base64"),
43
+ },
44
+ });
45
+ req.on("error", reject);
46
+ req.on("response", (res) => reject(new Error(`websocket upgrade refused (${res.statusCode})`)));
47
+ req.on("upgrade", (_res, socket, head) => {
48
+ if (signal.aborted) {
49
+ socket.destroy();
50
+ return;
51
+ }
52
+ let buffer = head.length ? Buffer.from(head) : Buffer.alloc(0);
53
+ let fragments = [];
54
+ const writeFrame = (opcode, payload) => {
55
+ const mask = randomBytes(4);
56
+ const len = payload.length;
57
+ const header = len < 126
58
+ ? Buffer.from([0x80 | opcode, 0x80 | len])
59
+ : len < 65536
60
+ ? Buffer.from([0x80 | opcode, 0x80 | 126, len >> 8, len & 0xff])
61
+ : (() => {
62
+ const h = Buffer.alloc(10);
63
+ h[0] = 0x80 | opcode;
64
+ h[1] = 0x80 | 127;
65
+ h.writeBigUInt64BE(BigInt(len), 2);
66
+ return h;
67
+ })();
68
+ const masked = Buffer.alloc(len);
69
+ for (let i = 0; i < len; i++)
70
+ masked[i] = payload[i] ^ mask[i % 4];
71
+ socket.write(Buffer.concat([header, mask, masked]));
72
+ };
73
+ socket.on("data", (chunk) => {
74
+ buffer = Buffer.concat([buffer, chunk]);
75
+ for (;;) {
76
+ if (buffer.length < 2)
77
+ return;
78
+ const fin = (buffer[0] & 0x80) !== 0;
79
+ const opcode = buffer[0] & 0x0f;
80
+ let len = buffer[1] & 0x7f;
81
+ let offset = 2;
82
+ if (len === 126) {
83
+ if (buffer.length < 4)
84
+ return;
85
+ len = buffer.readUInt16BE(2);
86
+ offset = 4;
87
+ }
88
+ else if (len === 127) {
89
+ if (buffer.length < 10)
90
+ return;
91
+ len = Number(buffer.readBigUInt64BE(2));
92
+ offset = 10;
93
+ }
94
+ if (buffer.length < offset + len)
95
+ return;
96
+ const payload = buffer.subarray(offset, offset + len);
97
+ buffer = buffer.subarray(offset + len);
98
+ if (opcode === 0x8) {
99
+ socket.end();
100
+ return;
101
+ }
102
+ if (opcode === 0x9) {
103
+ writeFrame(0xa, Buffer.from(payload));
104
+ continue;
105
+ }
106
+ if (opcode === 0x1 || opcode === 0x0) {
107
+ fragments.push(Buffer.from(payload));
108
+ if (fin) {
109
+ onMessage(Buffer.concat(fragments).toString("utf8"));
110
+ fragments = [];
111
+ }
112
+ }
113
+ }
114
+ });
115
+ socket.on("close", () => onClose("socket closed"));
116
+ socket.on("error", () => onClose("socket error"));
117
+ resolve({
118
+ send: (text) => writeFrame(0x1, Buffer.from(text, "utf8")),
119
+ close: () => {
120
+ try {
121
+ writeFrame(0x8, Buffer.alloc(0));
122
+ }
123
+ catch {
124
+ // already gone
125
+ }
126
+ socket.end();
127
+ },
128
+ });
129
+ });
130
+ req.end();
131
+ });
132
+ }
133
+ export class CdpConnection {
134
+ transport;
135
+ nextId = 1;
136
+ pending = new Map();
137
+ closedReason = null;
138
+ constructor(transport) {
139
+ this.transport = transport;
140
+ }
141
+ static async connect(port, timeoutMs = 10_000) {
142
+ const version = (await (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(timeoutMs) })).json());
143
+ if (!version.webSocketDebuggerUrl)
144
+ throw new Error("Chrome for Clipy did not report a debugger endpoint");
145
+ const conn = new CdpConnection(null);
146
+ const onMessage = (text) => conn.dispatch(text);
147
+ const onClose = (reason) => conn.failAll(reason);
148
+ const open = typeof globalThis.WebSocket === "function"
149
+ ? openWithGlobalWebSocket
150
+ : openWithHttpUpgrade;
151
+ const abort = new AbortController();
152
+ try {
153
+ conn.transport = await withTimeout(open(version.webSocketDebuggerUrl, onMessage, onClose, abort.signal), timeoutMs, "connecting to Chrome for Clipy");
154
+ }
155
+ catch (error) {
156
+ abort.abort();
157
+ throw error;
158
+ }
159
+ return conn;
160
+ }
161
+ dispatch(text) {
162
+ let msg;
163
+ try {
164
+ msg = JSON.parse(text);
165
+ }
166
+ catch {
167
+ return;
168
+ }
169
+ if (typeof msg.id !== "number")
170
+ return;
171
+ const waiter = this.pending.get(msg.id);
172
+ if (!waiter)
173
+ return;
174
+ this.pending.delete(msg.id);
175
+ if (msg.error)
176
+ waiter.reject(new Error(msg.error.message ?? "CDP error"));
177
+ else
178
+ waiter.resolve(msg.result ?? {});
179
+ }
180
+ failAll(reason) {
181
+ this.closedReason = reason;
182
+ for (const waiter of this.pending.values())
183
+ waiter.reject(new Error(`Chrome for Clipy connection lost (${reason})`));
184
+ this.pending.clear();
185
+ }
186
+ send(method, params = {}, sessionId, timeoutMs = 30_000) {
187
+ if (this.closedReason || !this.transport) {
188
+ return Promise.reject(new Error(`Chrome for Clipy connection lost (${this.closedReason ?? "not open"})`));
189
+ }
190
+ const id = this.nextId++;
191
+ const result = new Promise((resolve, reject) => {
192
+ this.pending.set(id, { resolve: resolve, reject });
193
+ });
194
+ this.transport.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
195
+ return withTimeout(result, timeoutMs, method).finally(() => this.pending.delete(id));
196
+ }
197
+ close() {
198
+ this.transport?.close();
199
+ this.failAll("closed");
200
+ }
201
+ }
202
+ function withTimeout(promise, ms, what) {
203
+ let timer;
204
+ return Promise.race([
205
+ promise,
206
+ new Promise((_, reject) => {
207
+ timer = setTimeout(() => reject(new Error(`${what} timed out after ${Math.round(ms / 1000)}s`)), ms);
208
+ }),
209
+ ]).finally(() => clearTimeout(timer));
210
+ }
211
+ /** A tab this client created and attached to, and only that tab. */
212
+ export class CdpTab {
213
+ conn;
214
+ targetId;
215
+ sessionId;
216
+ constructor(conn, targetId, sessionId) {
217
+ this.conn = conn;
218
+ this.targetId = targetId;
219
+ this.sessionId = sessionId;
220
+ }
221
+ /** Opens `url` as a background tab (never activated) and attaches to it. */
222
+ static async openBackground(conn, url) {
223
+ const { targetId } = await conn.send("Target.createTarget", { url, background: true });
224
+ try {
225
+ const { sessionId } = await conn.send("Target.attachToTarget", { targetId, flatten: true });
226
+ return new CdpTab(conn, targetId, sessionId);
227
+ }
228
+ catch (error) {
229
+ await conn.send("Target.closeTarget", { targetId }).catch(() => { });
230
+ throw error;
231
+ }
232
+ }
233
+ /** Evaluates an expression in the page, awaiting a returned promise. A
234
+ * navigation can swap the document mid-call; that is retried, not failed. */
235
+ async evaluate(expression, timeoutMs = 30_000) {
236
+ for (let attempt = 1;; attempt++) {
237
+ try {
238
+ return await this.evaluateOnce(expression, timeoutMs);
239
+ }
240
+ catch (error) {
241
+ const message = error instanceof Error ? error.message : String(error);
242
+ if (attempt >= 4 || !/context was destroyed|Cannot find context|Inspected target navigated/i.test(message))
243
+ throw error;
244
+ await new Promise((r) => setTimeout(r, 250 * attempt));
245
+ }
246
+ }
247
+ }
248
+ async evaluateOnce(expression, timeoutMs) {
249
+ const res = await this.conn.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }, this.sessionId, timeoutMs);
250
+ if (res.exceptionDetails) {
251
+ throw new Error(res.exceptionDetails.exception?.description ?? res.exceptionDetails.text ?? "evaluation failed");
252
+ }
253
+ return res.result?.value;
254
+ }
255
+ /** Polls until `expression` is truthy; false if it never became so in time. */
256
+ async waitFor(expression, timeoutMs, intervalMs = 200) {
257
+ const deadline = Date.now() + timeoutMs;
258
+ for (;;) {
259
+ try {
260
+ if (await this.evaluate(`Boolean(${expression})`, 5_000))
261
+ return true;
262
+ }
263
+ catch {
264
+ // the document may be mid-navigation; keep polling
265
+ }
266
+ if (Date.now() >= deadline)
267
+ return false;
268
+ await new Promise((r) => setTimeout(r, intervalMs));
269
+ }
270
+ }
271
+ url() {
272
+ return this.evaluate("location.href", 5_000);
273
+ }
274
+ async close() {
275
+ await this.conn.send("Target.closeTarget", { targetId: this.targetId }, undefined, 5_000).catch(() => { });
276
+ }
277
+ }
@@ -13,9 +13,14 @@
13
13
  * Nothing is kept in a CLI process between commands: start, stop, abort and
14
14
  * status each reconnect, so `session start` can return and the agent can drive
15
15
  * the tab with its own tools in between.
16
+ *
17
+ * Raw CDP (cdpClient.ts), not Playwright: this path attaches only to the two
18
+ * background tabs it opens, so a stuck tab elsewhere in the person's Chrome
19
+ * for Clipy cannot hang it, and it needs no Playwright install.
16
20
  */
17
21
  import { randomUUID } from "node:crypto";
18
- import { clipyExtensionId, startChrome, } from "./chromeForClipy.js";
22
+ import { CdpConnection, CdpTab } from "./cdpClient.js";
23
+ import { clipyExtensionId, startChrome } from "./chromeForClipy.js";
19
24
  const AGENT_PAGE_PATH = "src/agent/agent.html";
20
25
  const AGENT_PROTOCOL = 1;
21
26
  const BUSY_STATES = new Set(["starting", "countdown", "recording", "paused", "uploading"]);
@@ -29,52 +34,57 @@ export class ExtensionUnavailableError extends Error {
29
34
  * from stop is treated as transient and the file is kept. */
30
35
  export class ExtensionRecordingEndedError extends Error {
31
36
  }
32
- async function connectAgent(chromium, port, env) {
33
- const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
34
- const context = browser.contexts()[0];
35
- if (!context) {
36
- await browser.close().catch(() => { });
37
- throw new Error("Chrome for Clipy has no browser context to attach to");
37
+ /** The extension bounds capture setup (OFFSCREEN_PREPARE) at 120s, so a start
38
+ * can legitimately take that long; wait past it for the definite answer. */
39
+ const AGENT_START_TIMEOUT_MS = 150_000;
40
+ // A start that never got going leaves the extension idle; give its access
41
+ // check this long to begin before deciding nothing is coming.
42
+ const ORPHAN_IDLE_GRACE_MS = 15_000;
43
+ /** The agent page is opened in the background: a foreground tab would make
44
+ * the extension think the person left the recorded tab. */
45
+ async function connectAgent(port, env) {
46
+ const conn = await CdpConnection.connect(port);
47
+ let agent;
48
+ try {
49
+ agent = await CdpTab.openBackground(conn, `chrome-extension://${clipyExtensionId(env)}/${AGENT_PAGE_PATH}`);
50
+ }
51
+ catch (error) {
52
+ conn.close();
53
+ throw error;
54
+ }
55
+ if (!(await agent.waitFor("typeof globalThis.clipyAgent === 'object'", 10_000))) {
56
+ await agent.close();
57
+ conn.close();
58
+ throw new ExtensionUnavailableError(`the Clipy extension (with agent support) is not installed in Chrome for Clipy. ` +
59
+ `Run \`clipy chrome setup\`, or install it from ${extensionStoreUrl(env)} in that window.`);
38
60
  }
39
- const agent = await context.newPage();
40
- const close = async () => {
41
- await agent.close().catch(() => { });
42
- await browser.close().catch(() => { });
43
- };
44
- const missing = () => new ExtensionUnavailableError(`the Clipy extension (with agent support) is not installed in Chrome for Clipy. ` +
45
- `Run \`clipy chrome setup\`, or install it from ${extensionStoreUrl(env)} in that window.`);
61
+ return { conn, agent };
62
+ }
63
+ async function withAgent(port, env, fn) {
64
+ const { conn, agent } = await connectAgent(port, env);
46
65
  try {
47
- await agent.goto(`chrome-extension://${clipyExtensionId(env)}/${AGENT_PAGE_PATH}`, {
48
- waitUntil: "load",
49
- timeout: 15_000,
50
- });
51
- await agent.waitForFunction("typeof globalThis.clipyAgent === 'object'", undefined, { timeout: 10_000 });
66
+ return await fn({ conn, call: (expression, timeoutMs) => agent.evaluate(`globalThis.clipyAgent.${expression}`, timeoutMs) });
52
67
  }
53
- catch {
54
- await close();
55
- throw missing();
68
+ finally {
69
+ await agent.close();
70
+ conn.close();
56
71
  }
57
- return {
58
- browser,
59
- context,
60
- agent,
61
- call: (expression) => agent.evaluate(`globalThis.clipyAgent.${expression}`),
62
- close,
63
- };
64
- }
65
- async function withAgent(chromium, port, env, fn) {
66
- const conn = await connectAgent(chromium, port, env);
72
+ }
73
+ /** Opens a page in FRONT, for the steps a person has to do (install, sign in). */
74
+ export async function openTabForPerson(port, url) {
75
+ const conn = await CdpConnection.connect(port);
67
76
  try {
68
- return await fn(conn);
77
+ const { targetId } = await conn.send("Target.createTarget", { url });
78
+ await conn.send("Target.activateTarget", { targetId }).catch(() => { });
69
79
  }
70
80
  finally {
71
- await conn.close();
81
+ conn.close();
72
82
  }
73
83
  }
74
84
  /** Read-only: is the extension installed, current enough, and signed in? */
75
- export async function extensionReadiness(chromium, port, env) {
85
+ export async function extensionReadiness(port, env) {
76
86
  try {
77
- return await withAgent(chromium, port, env, async ({ call }) => {
87
+ return await withAgent(port, env, async ({ call }) => {
78
88
  const res = await call("status(undefined, true)");
79
89
  if (!res.ok || !res.agent) {
80
90
  return { installed: true, version: null, signedIn: false, email: null, recorderState: null, error: res.error ?? "the extension did not answer" };
@@ -133,12 +143,12 @@ async function resolveTabId(target, call) {
133
143
  .catch(() => { });
134
144
  }
135
145
  }
136
- export async function startExtensionRecording(chromium, opts) {
146
+ export async function startExtensionRecording(opts) {
137
147
  const started = await startChrome(opts.home, opts.env, opts.platform, opts.port);
138
148
  if (!started.ok)
139
149
  throw new Error(`Chrome for Clipy is not available: ${started.error}`);
140
150
  const port = started.state.port;
141
- return withAgent(chromium, port, opts.env, async ({ context, call }) => {
151
+ return withAgent(port, opts.env, async ({ conn, call }) => {
142
152
  const ready = await call("status(undefined, true)");
143
153
  if (!ready.ok || !ready.agent)
144
154
  throw new Error(ready.error ?? "the Clipy extension did not answer");
@@ -151,29 +161,64 @@ export async function startExtensionRecording(chromium, opts) {
151
161
  if (ready.state && BUSY_STATES.has(ready.state.status)) {
152
162
  throw new Error(`the Clipy extension is already ${ready.state.status}; stop or abort that recording first`);
153
163
  }
154
- const target = await context.newPage();
164
+ const features = ready.agent.features ?? [];
165
+ const warnings = [];
166
+ if (opts.name && !features.includes("name")) {
167
+ warnings.push(`extension ${ready.agent.version} ignores --name; the recording gets an automatic title. Update the Clipy extension.`);
168
+ }
169
+ if (!features.includes("tab-audio")) {
170
+ warnings.push(`extension ${ready.agent.version} always records the tab's sound; any speech in it will replace your marks as the transcript. Update the Clipy extension.`);
171
+ }
172
+ if (!features.includes("narration")) {
173
+ warnings.push(`extension ${ready.agent.version} cannot receive marks; clipy mark will not reach this recording. Update the Clipy extension.`);
174
+ }
175
+ // In the background too: the agent drives this tab over CDP while the
176
+ // person keeps using whatever is in front, and tab capture does not need
177
+ // the tab to be visible.
178
+ const target = await CdpTab.openBackground(conn, opts.targetUrl);
155
179
  try {
156
- try {
157
- await target.goto(opts.targetUrl, { waitUntil: "load", timeout: 30_000 });
158
- }
159
- catch {
180
+ // A new tab is a complete about:blank before the real page commits.
181
+ if (!(await target.waitFor("location.href !== 'about:blank' && document.readyState === 'complete'", 30_000))) {
160
182
  opts.log("target page load timed out; recording its current state anyway");
161
183
  }
162
- await target.bringToFront().catch(() => { });
163
184
  const tabId = await resolveTabId(target, call);
164
- const res = await call(`start(${tabId}, ${Math.round(opts.maxSec)})`);
185
+ const startToken = randomUUID();
186
+ let res;
187
+ try {
188
+ res = await call(`start(${tabId}, ${Math.round(opts.maxSec)}, ${JSON.stringify(opts.name ?? null)}, ${opts.tabAudio === true}, ${JSON.stringify(startToken)})`, AGENT_START_TIMEOUT_MS);
189
+ }
190
+ catch (error) {
191
+ // No answer from the extension: a start may still have gone through.
192
+ // Cancel it rather than leave an unowned recording to upload.
193
+ const orphan = await cancelOrphanedAgentStart(port, opts.env, opts.log, startToken);
194
+ const message = error instanceof Error ? error.message : String(error);
195
+ if (orphan.uploaded)
196
+ throw new Error(`${message}; the recording finished and uploaded anyway: ${orphan.uploaded}`);
197
+ if (orphan.unresolved) {
198
+ throw new Error(`${message}; recording ${orphan.unresolved.recordingId} may still be running in Chrome for Clipy and could not be cancelled ` +
199
+ `(${orphan.unresolved.error}). Stop it from the Clipy extension in that window.`);
200
+ }
201
+ if (orphan.unchecked) {
202
+ throw new Error(`${message}; could not check whether the recording started anyway (${orphan.unchecked}). ` +
203
+ "Look at the Clipy extension in Chrome for Clipy and stop it there if it is recording.");
204
+ }
205
+ throw error;
206
+ }
165
207
  if (!res.ok || !res.agent?.activeRecordingId) {
166
208
  throw new Error(explainStartError(res.error ?? `recording did not start (state: ${res.state?.status ?? "unknown"})`));
167
209
  }
168
210
  opts.log(`extension ${res.agent.version} recording tab ${tabId} (${res.agent.activeRecordingId})`);
169
211
  return {
170
212
  recordingId: res.agent.activeRecordingId,
171
- startedAtEpochMs: Date.now(),
213
+ startedAtEpochMs: typeof res.state?.startedAt === "number" ? res.state.startedAt : Date.now(),
172
214
  extensionVersion: res.agent.version,
215
+ features: res.agent.features ?? [],
173
216
  cdpHttpUrl: `http://127.0.0.1:${port}`,
174
217
  chromePid: started.state.pid,
175
218
  port,
176
- pageUrl: target.url(),
219
+ pageUrl: await target.url().catch(() => opts.targetUrl),
220
+ targetId: target.targetId,
221
+ warnings,
177
222
  };
178
223
  }
179
224
  catch (error) {
@@ -182,11 +227,84 @@ export async function startExtensionRecording(chromium, opts) {
182
227
  }
183
228
  });
184
229
  }
230
+ async function cancelOrphanedAgentStart(port, env, log, startToken) {
231
+ try {
232
+ return await withAgent(port, env, async ({ call }) => {
233
+ // Retried, then reported: a cancel that silently failed would leave a
234
+ // recording running with no session to stop or collect it.
235
+ const cancel = async (id) => {
236
+ let lastError = "";
237
+ for (let attempt = 1; attempt <= 3; attempt++) {
238
+ const res = await call(`cancel(${JSON.stringify(id)})`, 30_000).catch((error) => ({
239
+ ok: false,
240
+ error: error instanceof Error ? error.message : String(error),
241
+ }));
242
+ if (res.ok || /not active/.test(res.error ?? "")) {
243
+ log(`cancelled recording ${id}, which started after the CLI stopped waiting for it`);
244
+ return {};
245
+ }
246
+ if (/^already uploaded: /.test(res.error ?? ""))
247
+ return { uploaded: res.error.replace(/^already uploaded: /, "") };
248
+ lastError = res.error ?? "cancel failed";
249
+ if (attempt < 3)
250
+ await new Promise((r) => setTimeout(r, 500 * attempt));
251
+ }
252
+ return { unresolved: { recordingId: id, error: lastError } };
253
+ };
254
+ // Refuse the start outright if it has not passed the access check yet
255
+ // (that check has no timeout of its own).
256
+ const first = await call(`abandonStart(${JSON.stringify(startToken)})`, 10_000).catch(() => null);
257
+ const canAbandon = Boolean(first?.agent?.features?.includes("abandon-start"));
258
+ // While the extension is busy starting, keep watching through its whole
259
+ // setup window: a recording can still begin near the end of it.
260
+ const idleDeadline = Date.now() + ORPHAN_IDLE_GRACE_MS;
261
+ const hardDeadline = Date.now() + AGENT_START_TIMEOUT_MS;
262
+ let sawStart = false;
263
+ for (;;) {
264
+ const status = await call("status()", 10_000);
265
+ const mine = status.agent?.lastStart?.token === startToken ? status.agent.lastStart.recordingId : null;
266
+ if (mine) {
267
+ if (status.agent?.activeRecordingId === mine)
268
+ return await cancel(mine);
269
+ const result = (await call(`status(${JSON.stringify(mine)})`, 10_000)).agent?.result;
270
+ if (result?.status === "complete")
271
+ return { uploaded: result.shareUrl ?? result.publicId ?? mine };
272
+ // Still retrying the upload: cancelling drops the queued replay. An
273
+ // error result already means nothing was uploaded.
274
+ return result?.status === "recovering" ? await cancel(mine) : {};
275
+ }
276
+ // An extension without start tokens: any agent recording now live is ours.
277
+ if (!status.agent?.features?.includes("start-token")) {
278
+ const id = status.agent?.agentControlled ? status.agent.activeRecordingId : null;
279
+ if (id)
280
+ return await cancel(id);
281
+ }
282
+ // Our start is still in the extension's hands (possibly its access
283
+ // check): keep watching, since it may yet begin or be refused.
284
+ const pending = status.agent?.pendingStart === startToken;
285
+ const busy = pending || Boolean(status.state && BUSY_STATES.has(status.state.status));
286
+ if (canAbandon && !pending && !mine)
287
+ return {};
288
+ if (sawStart && !busy)
289
+ return {};
290
+ sawStart ||= busy;
291
+ const now = Date.now();
292
+ if (now >= hardDeadline || (!busy && now >= idleDeadline))
293
+ return {};
294
+ await new Promise((r) => setTimeout(r, 500));
295
+ }
296
+ });
297
+ }
298
+ catch (error) {
299
+ return { unchecked: error instanceof Error ? error.message : String(error) };
300
+ }
301
+ }
185
302
  /** Stop (or collect an auto-stopped) recording and wait for its upload. */
186
- export async function stopExtensionRecording(chromium, opts) {
187
- return withAgent(chromium, opts.port, opts.env, async ({ call }) => {
303
+ export async function stopExtensionRecording(opts) {
304
+ return withAgent(opts.port, opts.env, async ({ call }) => {
188
305
  const id = JSON.stringify(opts.recordingId);
189
- const stopped = await call(`stop(${id})`);
306
+ const narration = opts.notes?.length ? JSON.stringify({ notes: opts.notes }) : "undefined";
307
+ const stopped = await call(`stop(${id}, ${narration})`);
190
308
  if (!stopped.ok) {
191
309
  const message = stopped.error ?? "the extension refused to stop the recording";
192
310
  throw /not active/.test(message) ? new ExtensionRecordingEndedError(message) : new Error(message);
@@ -205,24 +323,47 @@ export async function stopExtensionRecording(chromium, opts) {
205
323
  const reason = res.state?.status === "error" && res.state.message ? `: ${res.state.message}` : "";
206
324
  throw new ExtensionRecordingEndedError(`the recording ended without an upload${reason}`);
207
325
  }
208
- if (Date.now() >= deadline)
209
- throw new Error("timed out waiting for the extension to finish uploading");
326
+ if (Date.now() >= deadline) {
327
+ // Plain Error, not ended: the session is kept so a later stop can collect it.
328
+ throw new Error(result?.status === "recovering"
329
+ ? "the extension is still retrying the upload; run `clipy session stop` again shortly to collect the link"
330
+ : "timed out waiting for the extension to finish uploading");
331
+ }
210
332
  await new Promise((r) => setTimeout(r, 1000));
211
333
  res = await call(`status(${id})`);
212
334
  }
213
335
  });
214
336
  }
337
+ /** Hands one mark to the extension as it happens, so a recording that stops
338
+ * on its own (--max) still uploads with it. Best effort: the CLI keeps its own
339
+ * copy and sends everything again at stop. */
340
+ export async function sendExtensionMark(opts) {
341
+ return withAgent(opts.port, opts.env, async ({ call }) => {
342
+ const args = [JSON.stringify(opts.recordingId), Math.round(opts.startMs), JSON.stringify(opts.text)];
343
+ if (opts.summary)
344
+ args.push(JSON.stringify(opts.summary));
345
+ const res = await call(`mark(${args.join(", ")})`);
346
+ // "not active": the recording already stopped on its own (--max) and
347
+ // uploaded, so nothing sent now can reach it.
348
+ return { ok: res.ok, ended: !res.ok && /not active/.test(res.error ?? ""), error: res.error };
349
+ });
350
+ }
215
351
  /** Resolves once the extension has cancelled the recording or confirms it is
216
352
  * no longer active; throws when the extension could not be asked. */
217
- export async function abortExtensionRecording(chromium, opts) {
218
- await withAgent(chromium, opts.port, opts.env, async ({ call }) => {
353
+ /** The recording reached the library before the abort; `session stop` collects it. */
354
+ export class ExtensionAlreadyUploadedError extends Error {
355
+ }
356
+ export async function abortExtensionRecording(opts) {
357
+ await withAgent(opts.port, opts.env, async ({ call }) => {
219
358
  const res = await call(`cancel(${JSON.stringify(opts.recordingId)})`);
359
+ if (!res.ok && /^already uploaded/.test(res.error ?? ""))
360
+ throw new ExtensionAlreadyUploadedError(res.error);
220
361
  if (!res.ok && !/not active/.test(res.error ?? ""))
221
362
  throw new Error(res.error ?? "cancel failed");
222
363
  });
223
364
  }
224
- export async function extensionRecordingStatus(chromium, opts) {
225
- return withAgent(chromium, opts.port, opts.env, async ({ call }) => {
365
+ export async function extensionRecordingStatus(opts) {
366
+ return withAgent(opts.port, opts.env, async ({ call }) => {
226
367
  const res = await call(`status(${JSON.stringify(opts.recordingId)})`);
227
368
  if (!res.ok || !res.agent)
228
369
  throw new Error(res.error ?? "the extension did not answer");
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@ 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
30
  import { APP_NAME as CHROME_FOR_CLIPY_APP_NAME, appBundlePath as chromeForClipyAppPath, chromeStatus, DEFAULT_CDP_PORT, installApp as installChromeForClipyApp, startChrome as startChromeForClipy, startChromeForClipyCapture, markExtensionRecording, stopChrome as stopChromeForClipy, TAB_CAPTURE_TITLE_MARKER, } from "./chromeForClipy.js";
31
- import { ExtensionRecordingEndedError, abortExtensionRecording, extensionReadiness, extensionRecordingStatus, extensionStoreUrl, startExtensionRecording, stopExtensionRecording, } from "./chromeExtensionCapture.js";
31
+ import { ExtensionRecordingEndedError, abortExtensionRecording, ExtensionAlreadyUploadedError, extensionReadiness, extensionRecordingStatus, extensionStoreUrl, openTabForPerson, sendExtensionMark, startExtensionRecording, stopExtensionRecording, } from "./chromeExtensionCapture.js";
32
32
  import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
33
33
  import { openUrl } from "./openUrl.js";
34
34
  import { cmdContextImport } from "./context/importCmd.js";
@@ -426,15 +426,18 @@ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session
426
426
  published there, so drivers attach to the same
427
427
  browser being recorded. --source chrome-extension
428
428
  records the same way through the Clipy extension
429
- installed there (no marks yet); run
429
+ installed there (marks become its transcript); run
430
430
  clipy chrome setup once first
431
431
  session run [start flags] -- <command …>
432
432
  Start a session, run the command (inherited
433
433
  stdio), then GUARANTEE cleanup: exit 0 uploads,
434
434
  any non-zero exit or signal discards and
435
435
  propagates the code. Sets CLIPY_SESSION=1 (+
436
- CLIPY_CDP_URL with --expose-cdp). Crash-safe
437
- 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.
438
441
  mark "<what just happened>" Drop a live timestamped note; marks become the
439
442
  recording's transcript. Attach evidence — one
440
443
  provenance per mark, never pooled:
@@ -3131,6 +3134,102 @@ function cdpDriverSnippet(cdpHttpUrl) {
3131
3134
  c.dim(` resolve playwright for your script: NODE_PATH=$(clipy playwright-path) node driver.js`),
3132
3135
  ].join("\n");
3133
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
+ }
3134
3233
  function extensionSessionPort(state) {
3135
3234
  return state.chromePort ?? DEFAULT_CDP_PORT;
3136
3235
  }
@@ -3157,8 +3256,8 @@ async function cmdSessionStartExtension(opts) {
3157
3256
  if (opts.userDataDir) {
3158
3257
  die("--user-data-dir doesn't apply to --source chrome-extension; it records in the persistent Chrome for Clipy profile", 2);
3159
3258
  }
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`);
3259
+ if (opts.recordingKind && !opts.json) {
3260
+ process.stderr.write(`${c.yellow("note: --type is not applied to --source chrome-extension recordings yet")}\n`);
3162
3261
  }
3163
3262
  const file = sessionFilePath(process.cwd());
3164
3263
  const existing = readSessionState(file);
@@ -3168,17 +3267,18 @@ async function cmdSessionStartExtension(opts) {
3168
3267
  }
3169
3268
  if (existing)
3170
3269
  cleanupSessionFiles(existing, file);
3171
- const chromium = await loadChromium();
3172
3270
  const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
3173
3271
  let started;
3174
3272
  try {
3175
- started = await startExtensionRecording(chromium, {
3273
+ started = await startExtensionRecording({
3176
3274
  home: homedir(),
3177
3275
  env: process.env,
3178
3276
  platform: process.platform,
3179
3277
  port: DEFAULT_CDP_PORT,
3180
3278
  targetUrl: target.href,
3181
3279
  maxSec,
3280
+ name: opts.name,
3281
+ tabAudio: opts.tabAudio,
3182
3282
  log: (m) => {
3183
3283
  if (!opts.json)
3184
3284
  process.stderr.write(`${c.dim(m)}\n`);
@@ -3188,6 +3288,9 @@ async function cmdSessionStartExtension(opts) {
3188
3288
  catch (error) {
3189
3289
  die(`could not start the extension recording: ${error instanceof Error ? error.message : String(error)}`);
3190
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`);
3191
3294
  // The extension is recording from here on: record the session before
3192
3295
  // anything else can fail, or nothing could stop or collect it.
3193
3296
  const dir = sessionDir();
@@ -3196,6 +3299,8 @@ async function cmdSessionStartExtension(opts) {
3196
3299
  kind: "chrome-extension",
3197
3300
  chromePort: started.port,
3198
3301
  extensionRecordingId: started.recordingId,
3302
+ extensionFeatures: started.features,
3303
+ extensionTargetId: started.targetId,
3199
3304
  // Chrome for Clipy's pid: the session is alive only while that browser is.
3200
3305
  pid: started.chromePid,
3201
3306
  cwd: process.cwd(),
@@ -3206,7 +3311,7 @@ async function cmdSessionStartExtension(opts) {
3206
3311
  state: "recording",
3207
3312
  recordStartEpochMs: started.startedAtEpochMs,
3208
3313
  cdpHttpUrl: started.cdpHttpUrl,
3209
- marksPath: join(dir, "unused"),
3314
+ marksPath: join(dir, `marks-${randomUUID()}.jsonl`),
3210
3315
  controlPath: join(dir, "unused"),
3211
3316
  logPath: join(dir, "unused"),
3212
3317
  tmpDir: join(dir, "unused"),
@@ -3219,7 +3324,7 @@ async function cmdSessionStartExtension(opts) {
3219
3324
  });
3220
3325
  }
3221
3326
  catch (error) {
3222
- await abortExtensionRecording(chromium, {
3327
+ await abortExtensionRecording({
3223
3328
  port: started.port,
3224
3329
  env: process.env,
3225
3330
  recordingId: started.recordingId,
@@ -3239,11 +3344,14 @@ async function cmdSessionStartExtension(opts) {
3239
3344
  extensionVersion: started.extensionVersion,
3240
3345
  cdpUrl: cdpUrl ?? null,
3241
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}`,
3242
3350
  });
3243
3351
  return;
3244
3352
  }
3245
3353
  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` +
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` +
3247
3355
  `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
3248
3356
  }
3249
3357
  async function cmdSessionStart(ctx, opts) {
@@ -3472,7 +3580,46 @@ async function cmdMark(text, json, opts) {
3472
3580
  const attest = opts.attest;
3473
3581
  const backdated = opts.atSec != null || opts.agoSec != null;
3474
3582
  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);
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;
3476
3623
  }
3477
3624
  if (state.kind === "mac") {
3478
3625
  // The Mac app records the real screen — there is no Clipy-owned page to probe,
@@ -3601,7 +3748,18 @@ async function cmdChapter(label, json) {
3601
3748
  const { file, state } = requireSession();
3602
3749
  const chapterText = `=== CHAPTER: ${label} ===`;
3603
3750
  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);
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;
3605
3763
  }
3606
3764
  if (state.kind === "mac") {
3607
3765
  const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text: chapterText }).catch((e) => {
@@ -3657,14 +3815,18 @@ async function cmdSessionStop(json) {
3657
3815
  if (state.kind === "chrome-extension") {
3658
3816
  if (!json)
3659
3817
  process.stderr.write(`${c.dim("stopping; the extension is uploading…")}\n`);
3660
- const chromium = await loadChromium();
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
+ }
3661
3822
  let result;
3662
3823
  try {
3663
- result = await stopExtensionRecording(chromium, {
3824
+ result = await stopExtensionRecording({
3664
3825
  port: extensionSessionPort(state),
3665
3826
  env: process.env,
3666
3827
  recordingId: extensionSessionId(state),
3667
3828
  timeoutMs: 600_000,
3829
+ notes,
3668
3830
  });
3669
3831
  }
3670
3832
  catch (error) {
@@ -3778,15 +3940,27 @@ function reportSessionResult(result, json) {
3778
3940
  async function cmdSessionAbort(json) {
3779
3941
  const { file, state } = requireSession();
3780
3942
  if (state.kind === "chrome-extension") {
3781
- const chromium = await loadChromium();
3782
3943
  let failure = null;
3783
- await abortExtensionRecording(chromium, {
3944
+ let uploaded = null;
3945
+ await abortExtensionRecording({
3784
3946
  port: extensionSessionPort(state),
3785
3947
  env: process.env,
3786
3948
  recordingId: extensionSessionId(state),
3787
3949
  }).catch((error) => {
3788
- failure = error instanceof Error ? error.message : String(error);
3950
+ if (error instanceof ExtensionAlreadyUploadedError)
3951
+ uploaded = error.message;
3952
+ else
3953
+ failure = error instanceof Error ? error.message : String(error);
3789
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
+ }
3790
3964
  if (failure && (await chromeStatus(homedir(), process.platform)).running) {
3791
3965
  // Chrome for Clipy is up, so the recording may still be running: keep
3792
3966
  // the session so a retry (or stop) can still reach it.
@@ -3913,8 +4087,7 @@ async function cmdSessionStatus(json) {
3913
4087
  const elapsedSec = state.recordStartEpochMs ? Math.round((Date.now() - state.recordStartEpochMs) / 1000) : null;
3914
4088
  let live;
3915
4089
  try {
3916
- const chromium = await loadChromium();
3917
- live = await extensionRecordingStatus(chromium, {
4090
+ live = await extensionRecordingStatus({
3918
4091
  port: extensionSessionPort(state),
3919
4092
  env: process.env,
3920
4093
  recordingId: extensionSessionId(state),
@@ -3931,6 +4104,11 @@ async function cmdSessionStatus(json) {
3931
4104
  maxSec: state.maxSec,
3932
4105
  cdpUrl: state.cdpUrl ?? null,
3933
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,
3934
4112
  ...(live.result ? { result: live.result } : {}),
3935
4113
  });
3936
4114
  return;
@@ -4014,7 +4192,9 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
4014
4192
  // child inherits our stdio and the deliverable is the wrapped run, not JSON.
4015
4193
  await cmdSessionStart(ctx, { ...startOpts, json: false });
4016
4194
  const file = sessionFilePath(process.cwd());
4017
- const cdpHttpUrl = readSessionState(file)?.cdpHttpUrl;
4195
+ const started = readSessionState(file);
4196
+ const cdpHttpUrl = started?.cdpHttpUrl;
4197
+ const targetId = started?.extensionTargetId;
4018
4198
  const [cmd, ...args] = childArgv;
4019
4199
  process.stderr.write(`${c.dim(`running: ${childArgv.join(" ")}`)}\n`);
4020
4200
  const child = spawn(cmd, args, {
@@ -4027,6 +4207,11 @@ async function cmdSessionRun(ctx, startOpts, childArgv) {
4027
4207
  CLIPY_SESSION: "1",
4028
4208
  CLIPY_SESSION_FILE: file,
4029
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
+ : {}),
4030
4215
  },
4031
4216
  });
4032
4217
  // Forward Ctrl-C / termination to the child; its exit then drives the abort
@@ -4993,6 +5178,11 @@ async function cmdChromeSetup(home, port, json) {
4993
5178
  if (!json)
4994
5179
  process.stdout.write(`${m}\n`);
4995
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
+ };
4996
5186
  const fail = (error) => {
4997
5187
  if (json)
4998
5188
  printJson({ ok: false, error });
@@ -5010,23 +5200,12 @@ async function cmdChromeSetup(home, port, json) {
5010
5200
  const started = await startChromeForClipy(home, process.env, process.platform, port);
5011
5201
  if (!started.ok)
5012
5202
  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
- };
5203
+ const openTab = (url) => openTabForPerson(port, url).catch(() => { });
5025
5204
  const deadline = Date.now() + CHROME_SETUP_TIMEOUT_MS;
5026
5205
  let askedInstall = false;
5027
5206
  let askedSignIn = false;
5028
5207
  for (;;) {
5029
- const ready = await extensionReadiness(chromium, port, process.env);
5208
+ const ready = await extensionReadiness(port, process.env);
5030
5209
  if (ready.installed && ready.error)
5031
5210
  fail(ready.error);
5032
5211
  if (ready.installed && ready.signedIn) {
@@ -5043,12 +5222,12 @@ async function cmdChromeSetup(home, port, json) {
5043
5222
  if (!ready.installed && !askedInstall) {
5044
5223
  askedInstall = true;
5045
5224
  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…`);
5225
+ ask(`→ In the ${CHROME_FOR_CLIPY_APP_NAME} window, click "Add to Chrome" on the Clipy extension page. Waiting…`);
5047
5226
  }
5048
5227
  else if (ready.installed && !ready.signedIn && !askedSignIn) {
5049
5228
  askedSignIn = true;
5050
5229
  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…`);
5230
+ ask(`→ Sign in to Clipy in the ${CHROME_FOR_CLIPY_APP_NAME} window. Waiting…`);
5052
5231
  }
5053
5232
  if (Date.now() >= deadline) {
5054
5233
  fail(ready.installed ? "timed out waiting for sign-in" : "timed out waiting for the Clipy extension to be installed");
@@ -5220,7 +5399,7 @@ function cmdGuide(json) {
5220
5399
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
5221
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"]),
5222
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"]),
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"]),
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"]),
5224
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"]),
5225
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"]),
5226
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"]),
@@ -5348,6 +5527,7 @@ async function main() {
5348
5527
  "marks-only": { type: "boolean", default: false },
5349
5528
  mic: { type: "boolean", default: false },
5350
5529
  "no-system-audio": { type: "boolean", default: false },
5530
+ "tab-audio": { type: "boolean", default: false },
5351
5531
  vtt: { type: "boolean", default: false },
5352
5532
  for: { type: "string" },
5353
5533
  timeout: { type: "string" },
@@ -5790,6 +5970,9 @@ async function main() {
5790
5970
  }
5791
5971
  if (source !== "mac-screen" && audioFlagsPresent)
5792
5972
  die(webAudioGuard, 2);
5973
+ if (values["tab-audio"] && source !== "chrome-extension") {
5974
+ die("--tab-audio applies to --source chrome-extension only", 2);
5975
+ }
5793
5976
  const url = values.url?.trim() || positionalUrl;
5794
5977
  if (!url && source !== "mac-screen") {
5795
5978
  die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen|chrome-for-clipy|chrome-extension]", 2);
@@ -5812,6 +5995,7 @@ async function main() {
5812
5995
  userDataDir: userDataDir(),
5813
5996
  profileDirectory: profileDirectory(),
5814
5997
  audio: audioChoice(),
5998
+ tabAudio: Boolean(values["tab-audio"]),
5815
5999
  };
5816
6000
  };
5817
6001
  if (sub === "start") {
package/dist/skill.js CHANGED
@@ -15,7 +15,7 @@ description: Read and create Clipy screen recordings, turn screenshots or tool-n
15
15
 
16
16
  # Clipy — recordings you can read AND make
17
17
 
18
- Written for @clipy/cli + @clipy/mcp 0.15.0 (the two versions move in lockstep). If
18
+ Written for @clipy/cli + @clipy/mcp 0.15.1 (the two versions move in lockstep). If
19
19
  \`clipy --version\` reports older, upgrade first: \`npm i -g @clipy/cli@latest\`.
20
20
 
21
21
  Clipy (clipy.online) is the screen recorder built to be agent-readable. Every
@@ -297,10 +297,11 @@ WHAT must be verified, and WHETHER the target depends on an existing login.
297
297
  (see the Chrome for Clipy section below). It records tab audio without
298
298
  a manual capture-picker step; it uses a dedicated browser the
299
299
  user signed into once, never their daily one.
300
- - **The user asks you to record yourself doing something in the browser,
301
- and does not need marks:** \`--source chrome-extension\` (see "Recording
302
- through the Clipy extension" below). Same dedicated browser; the Clipy
303
- extension records and uploads the tab.
300
+ - **The user asks you to record yourself doing something in the browser
301
+ (a walkthrough, an SOP, docs, a verification) while they keep working:**
302
+ \`--source chrome-extension\` (see "Recording through the Clipy
303
+ extension" below). Same dedicated browser; the Clipy extension records
304
+ the tab in the background and uploads it.
304
305
 
305
306
  Before capture, visibly confirm the resolved target: expected URL, expected
306
307
  signed-in/signed-out state, expected account/role when it is safe to display, and
@@ -524,21 +525,27 @@ process while CDP is open. Browser automation setup is opt-in. Install with
524
525
  \`clipy setup <agent> --with-browser\` or \`clipy chrome start\`, only when the
525
526
  user asked for browser automation.
526
527
 
527
- ### Recording through the Clipy extension (no marks)
528
+ ### Recording through the Clipy extension
528
529
 
529
530
  clipy chrome setup --json # one-time; quick check when already ready
530
- clipy session start --source chrome-extension --url <page> --json
531
- # drive the tab showing <page> over cdpHttpUrl with Playwright
531
+ clipy session start --source chrome-extension --url <page> --name "<title>" --json
532
+ # drive the tab whose CDP target id is the output's targetId (or attach to pageWsUrl)
533
+ clipy mark "Opened Settings > Billing" # one mark per meaningful step
532
534
  clipy session stop --json # returns shareUrl + contextUrl
533
535
 
534
- The Clipy extension inside Chrome for Clipy records the tab (video and tab
535
- audio) with no click, because Chrome for Clipy launches with
536
+ The Clipy extension inside Chrome for Clipy records the tab (picture only;
537
+ add \`--tab-audio\` for its sound, but detected speech then replaces your
538
+ marks as the transcript) with no click, because Chrome for Clipy launches with
536
539
  \`--allowlisted-extension-id\`. \`clipy chrome setup\` waits up to 15 minutes
537
540
  for the two steps only the user can do in the Chrome for Clipy window: click
538
541
  "Add to Chrome" on the extension page it opens, and sign in to Clipy. Relay
539
- those instructions and never try to do either yourself. \`clipy mark\` and
540
- \`clipy chapter\` are refused on this source; use \`--source chrome-for-clipy\`
541
- when you need them. Full agent instructions:
542
+ those instructions and never try to do either yourself. The recorded tab opens
543
+ in the background: never bring it to the front, drive it step by step over CDP,
544
+ and the user keeps working in other tabs or apps meanwhile. These recordings
545
+ are silent, so your marks become the transcript, the summary and the steps an
546
+ SOP or doc is written from: mark each step as you take it. \`--observed\` /
547
+ \`--verdict\` attested marks work; Clipy-evaluated \`--assert-*\` marks do not
548
+ (the extension, not Clipy, owns the page). Full agent instructions:
542
549
  https://clipy.online/docs/chrome-for-clipy.md
543
550
 
544
551
  ### Assert what you claim (two provenances, never pooled)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipy/cli",
3
- "version": "0.15.0",
3
+ "version": "0.15.1",
4
4
  "description": "Command-line interface for Clipy \u2014 list, search, and read your screen recordings' transcripts, AI summaries, and key moments from the terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -41,11 +41,11 @@
41
41
  "start": "node dist/index.js",
42
42
  "test:auth": "npm run build && node scripts/mock-auth-server.test.mjs && node scripts/doctor.test.mjs && node scripts/open-url.test.mjs",
43
43
  "test:proof": "npm run build && node scripts/proof-frames.test.mjs",
44
- "test:setup": "npm run build && node scripts/setup.test.mjs && node scripts/chrome-for-clipy.test.mjs && node scripts/capture-title.test.mjs",
44
+ "test:setup": "npm run build && node scripts/setup.test.mjs && node scripts/chrome-for-clipy.test.mjs && node scripts/capture-title.test.mjs && node scripts/cdp-client.test.mjs",
45
45
  "test:memory": "npm run build && node scripts/memory-search.test.mjs",
46
46
  "test:chrome-capture": "npm run build && node scripts/chrome-capture.test.mjs",
47
47
  "test:session": "npm run build && node scripts/auth-guard.test.mjs && node scripts/session-control.test.mjs",
48
- "test": "npm run test:auth && npm run test:session && node scripts/setup.test.mjs && node scripts/chrome-for-clipy.test.mjs && node scripts/capture-title.test.mjs && node scripts/transcript-replace.test.mjs && node scripts/proof-frames.test.mjs && node scripts/memory-search.test.mjs && node scripts/agent-readiness.test.mjs && node scripts/context-sync.test.mjs && node scripts/context-frames.test.mjs && node scripts/context-youtube-transcript.test.mjs && node scripts/context-youtube-url-lang.test.mjs && node scripts/context-loom-url.test.mjs && node scripts/context-loom-import.test.mjs && node scripts/context-retry.test.mjs && node scripts/context-json-envelope.test.mjs && node scripts/context-ytdlp-update.test.mjs",
48
+ "test": "npm run test:auth && npm run test:session && node scripts/setup.test.mjs && node scripts/chrome-for-clipy.test.mjs && node scripts/capture-title.test.mjs && node scripts/cdp-client.test.mjs && node scripts/transcript-replace.test.mjs && node scripts/proof-frames.test.mjs && node scripts/memory-search.test.mjs && node scripts/agent-readiness.test.mjs && node scripts/context-sync.test.mjs && node scripts/context-frames.test.mjs && node scripts/context-youtube-transcript.test.mjs && node scripts/context-youtube-url-lang.test.mjs && node scripts/context-loom-url.test.mjs && node scripts/context-loom-import.test.mjs && node scripts/context-retry.test.mjs && node scripts/context-json-envelope.test.mjs && node scripts/context-ytdlp-update.test.mjs",
49
49
  "prebuild": "node scripts/sync-context-core.mjs",
50
50
  "test:context": "npm run build && node scripts/agent-readiness.test.mjs && node scripts/context-sync.test.mjs && node scripts/context-frames.test.mjs && node scripts/context-youtube-transcript.test.mjs && node scripts/context-youtube-url-lang.test.mjs && node scripts/context-loom-url.test.mjs && node scripts/context-loom-import.test.mjs && node scripts/context-retry.test.mjs && node scripts/context-json-envelope.test.mjs && node scripts/context-ytdlp-update.test.mjs"
51
51
  },