@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/assets/chrome-for-clipy.icns +0 -0
- package/dist/cdpClient.js +277 -0
- package/dist/chromeExtensionCapture.js +373 -0
- package/dist/chromeForClipy.js +656 -0
- package/dist/index.js +815 -88
- package/dist/skill.js +58 -1
- package/package.json +6 -4
|
Binary file
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recording through the Clipy extension inside Chrome for Clipy, with no click.
|
|
3
|
+
*
|
|
4
|
+
* Chrome for Clipy launches with --allowlisted-extension-id=<Clipy extension>,
|
|
5
|
+
* which lets that extension call chrome.tabCapture without the toolbar click
|
|
6
|
+
* (activeTab) Chrome normally demands. The CLI reaches the extension through
|
|
7
|
+
* its agent page (chrome-extension://<id>/src/agent/agent.html): it opens the
|
|
8
|
+
* page over CDP and evaluates `clipyAgent.*`, each of which is one message to
|
|
9
|
+
* the service worker. The extension then records and uploads exactly as it
|
|
10
|
+
* does for a person, so the recording gets the extension's own pipeline
|
|
11
|
+
* (upload recovery, cursor and click evidence) rather than the CLI's.
|
|
12
|
+
*
|
|
13
|
+
* Nothing is kept in a CLI process between commands: start, stop, abort and
|
|
14
|
+
* status each reconnect, so `session start` can return and the agent can drive
|
|
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.
|
|
20
|
+
*/
|
|
21
|
+
import { randomUUID } from "node:crypto";
|
|
22
|
+
import { CdpConnection, CdpTab } from "./cdpClient.js";
|
|
23
|
+
import { clipyExtensionId, startChrome } from "./chromeForClipy.js";
|
|
24
|
+
const AGENT_PAGE_PATH = "src/agent/agent.html";
|
|
25
|
+
const AGENT_PROTOCOL = 1;
|
|
26
|
+
const BUSY_STATES = new Set(["starting", "countdown", "recording", "paused", "uploading"]);
|
|
27
|
+
export function extensionStoreUrl(env = process.env) {
|
|
28
|
+
return `https://chromewebstore.google.com/detail/${clipyExtensionId(env)}`;
|
|
29
|
+
}
|
|
30
|
+
export class ExtensionUnavailableError extends Error {
|
|
31
|
+
}
|
|
32
|
+
/** The extension gave a definite answer (failed upload, recording gone), so
|
|
33
|
+
* there is nothing left to retry and the session file can go. Any other error
|
|
34
|
+
* from stop is treated as transient and the file is kept. */
|
|
35
|
+
export class ExtensionRecordingEndedError extends Error {
|
|
36
|
+
}
|
|
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.`);
|
|
60
|
+
}
|
|
61
|
+
return { conn, agent };
|
|
62
|
+
}
|
|
63
|
+
async function withAgent(port, env, fn) {
|
|
64
|
+
const { conn, agent } = await connectAgent(port, env);
|
|
65
|
+
try {
|
|
66
|
+
return await fn({ conn, call: (expression, timeoutMs) => agent.evaluate(`globalThis.clipyAgent.${expression}`, timeoutMs) });
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
await agent.close();
|
|
70
|
+
conn.close();
|
|
71
|
+
}
|
|
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);
|
|
76
|
+
try {
|
|
77
|
+
const { targetId } = await conn.send("Target.createTarget", { url });
|
|
78
|
+
await conn.send("Target.activateTarget", { targetId }).catch(() => { });
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
conn.close();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** Read-only: is the extension installed, current enough, and signed in? */
|
|
85
|
+
export async function extensionReadiness(port, env) {
|
|
86
|
+
try {
|
|
87
|
+
return await withAgent(port, env, async ({ call }) => {
|
|
88
|
+
const res = await call("status(undefined, true)");
|
|
89
|
+
if (!res.ok || !res.agent) {
|
|
90
|
+
return { installed: true, version: null, signedIn: false, email: null, recorderState: null, error: res.error ?? "the extension did not answer" };
|
|
91
|
+
}
|
|
92
|
+
if (res.agent.protocol !== AGENT_PROTOCOL) {
|
|
93
|
+
return {
|
|
94
|
+
installed: true,
|
|
95
|
+
version: res.agent.version,
|
|
96
|
+
signedIn: Boolean(res.signedIn),
|
|
97
|
+
email: res.user?.email ?? null,
|
|
98
|
+
recorderState: res.state?.status ?? null,
|
|
99
|
+
error: `extension ${res.agent.version} speaks agent protocol ${res.agent.protocol}; this CLI needs ${AGENT_PROTOCOL}. Update the CLI or the extension.`,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
installed: true,
|
|
104
|
+
version: res.agent.version,
|
|
105
|
+
signedIn: Boolean(res.signedIn),
|
|
106
|
+
email: res.user?.email ?? null,
|
|
107
|
+
recorderState: res.state?.status ?? null,
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (error instanceof ExtensionUnavailableError) {
|
|
113
|
+
return { installed: false, version: null, signedIn: false, email: null, recorderState: null, error: error.message };
|
|
114
|
+
}
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function explainStartError(message) {
|
|
119
|
+
if (/not been invoked|activeTab|cannot be captured/i.test(message)) {
|
|
120
|
+
return (`Chrome refused tab capture without a click (${message}). Chrome for Clipy must run with ` +
|
|
121
|
+
`--allowlisted-extension-id; \`clipy chrome stop && clipy chrome start\` relaunches it with the flag. ` +
|
|
122
|
+
`If it still fails, this Chrome version may no longer honour the flag: use --source chrome-for-clipy instead.`);
|
|
123
|
+
}
|
|
124
|
+
return message;
|
|
125
|
+
}
|
|
126
|
+
/** CDP target ids and chrome.tabs ids are unrelated, so the target is named by
|
|
127
|
+
* a one-off title token the extension can see, then the title is restored. */
|
|
128
|
+
async function resolveTabId(target, call) {
|
|
129
|
+
const token = JSON.stringify(`clipy-agent-${randomUUID()}`);
|
|
130
|
+
try {
|
|
131
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
132
|
+
await target.evaluate(`(() => { globalThis.__clipyOriginalTitle ??= document.title; document.title = ${token}; })()`);
|
|
133
|
+
const tabId = (await call(`findTabByTitle(${token})`));
|
|
134
|
+
if (typeof tabId === "number")
|
|
135
|
+
return tabId;
|
|
136
|
+
await new Promise((r) => setTimeout(r, 250 * attempt));
|
|
137
|
+
}
|
|
138
|
+
throw new Error("could not identify the recording tab in Chrome for Clipy (does the page keep rewriting its title?)");
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
await target
|
|
142
|
+
.evaluate(`(() => { if (document.title === ${token}) document.title = globalThis.__clipyOriginalTitle ?? ""; delete globalThis.__clipyOriginalTitle; })()`)
|
|
143
|
+
.catch(() => { });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
export async function startExtensionRecording(opts) {
|
|
147
|
+
const started = await startChrome(opts.home, opts.env, opts.platform, opts.port);
|
|
148
|
+
if (!started.ok)
|
|
149
|
+
throw new Error(`Chrome for Clipy is not available: ${started.error}`);
|
|
150
|
+
const port = started.state.port;
|
|
151
|
+
return withAgent(port, opts.env, async ({ conn, call }) => {
|
|
152
|
+
const ready = await call("status(undefined, true)");
|
|
153
|
+
if (!ready.ok || !ready.agent)
|
|
154
|
+
throw new Error(ready.error ?? "the Clipy extension did not answer");
|
|
155
|
+
if (ready.agent.protocol !== AGENT_PROTOCOL) {
|
|
156
|
+
throw new Error(`extension ${ready.agent.version} speaks agent protocol ${ready.agent.protocol}; this CLI needs ${AGENT_PROTOCOL}`);
|
|
157
|
+
}
|
|
158
|
+
if (!ready.signedIn) {
|
|
159
|
+
throw new Error("the Clipy extension in Chrome for Clipy is signed out. Sign in at clipy.online in that window (or run `clipy chrome setup`).");
|
|
160
|
+
}
|
|
161
|
+
if (ready.state && BUSY_STATES.has(ready.state.status)) {
|
|
162
|
+
throw new Error(`the Clipy extension is already ${ready.state.status}; stop or abort that recording first`);
|
|
163
|
+
}
|
|
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);
|
|
179
|
+
try {
|
|
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))) {
|
|
182
|
+
opts.log("target page load timed out; recording its current state anyway");
|
|
183
|
+
}
|
|
184
|
+
const tabId = await resolveTabId(target, call);
|
|
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
|
+
}
|
|
207
|
+
if (!res.ok || !res.agent?.activeRecordingId) {
|
|
208
|
+
throw new Error(explainStartError(res.error ?? `recording did not start (state: ${res.state?.status ?? "unknown"})`));
|
|
209
|
+
}
|
|
210
|
+
opts.log(`extension ${res.agent.version} recording tab ${tabId} (${res.agent.activeRecordingId})`);
|
|
211
|
+
return {
|
|
212
|
+
recordingId: res.agent.activeRecordingId,
|
|
213
|
+
startedAtEpochMs: typeof res.state?.startedAt === "number" ? res.state.startedAt : Date.now(),
|
|
214
|
+
extensionVersion: res.agent.version,
|
|
215
|
+
features: res.agent.features ?? [],
|
|
216
|
+
cdpHttpUrl: `http://127.0.0.1:${port}`,
|
|
217
|
+
chromePid: started.state.pid,
|
|
218
|
+
port,
|
|
219
|
+
pageUrl: await target.url().catch(() => opts.targetUrl),
|
|
220
|
+
targetId: target.targetId,
|
|
221
|
+
warnings,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
catch (error) {
|
|
225
|
+
await target.close().catch(() => { });
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
});
|
|
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
|
+
}
|
|
302
|
+
/** Stop (or collect an auto-stopped) recording and wait for its upload. */
|
|
303
|
+
export async function stopExtensionRecording(opts) {
|
|
304
|
+
return withAgent(opts.port, opts.env, async ({ call }) => {
|
|
305
|
+
const id = JSON.stringify(opts.recordingId);
|
|
306
|
+
const narration = opts.notes?.length ? JSON.stringify({ notes: opts.notes }) : "undefined";
|
|
307
|
+
const stopped = await call(`stop(${id}, ${narration})`);
|
|
308
|
+
if (!stopped.ok) {
|
|
309
|
+
const message = stopped.error ?? "the extension refused to stop the recording";
|
|
310
|
+
throw /not active/.test(message) ? new ExtensionRecordingEndedError(message) : new Error(message);
|
|
311
|
+
}
|
|
312
|
+
const deadline = Date.now() + opts.timeoutMs;
|
|
313
|
+
let res = stopped;
|
|
314
|
+
for (;;) {
|
|
315
|
+
const result = res.agent?.result;
|
|
316
|
+
if (result?.status === "complete" && result.publicId && result.shareUrl) {
|
|
317
|
+
return { publicId: result.publicId, shareUrl: result.shareUrl };
|
|
318
|
+
}
|
|
319
|
+
if (result?.status === "error") {
|
|
320
|
+
throw new ExtensionRecordingEndedError(`the extension's upload failed: ${result.error ?? "unknown error"}`);
|
|
321
|
+
}
|
|
322
|
+
if (res.agent && res.agent.activeRecordingId !== opts.recordingId && !result) {
|
|
323
|
+
const reason = res.state?.status === "error" && res.state.message ? `: ${res.state.message}` : "";
|
|
324
|
+
throw new ExtensionRecordingEndedError(`the recording ended without an upload${reason}`);
|
|
325
|
+
}
|
|
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
|
+
}
|
|
332
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
333
|
+
res = await call(`status(${id})`);
|
|
334
|
+
}
|
|
335
|
+
});
|
|
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
|
+
}
|
|
351
|
+
/** Resolves once the extension has cancelled the recording or confirms it is
|
|
352
|
+
* no longer active; throws when the extension could not be asked. */
|
|
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 }) => {
|
|
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);
|
|
361
|
+
if (!res.ok && !/not active/.test(res.error ?? ""))
|
|
362
|
+
throw new Error(res.error ?? "cancel failed");
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
export async function extensionRecordingStatus(opts) {
|
|
366
|
+
return withAgent(opts.port, opts.env, async ({ call }) => {
|
|
367
|
+
const res = await call(`status(${JSON.stringify(opts.recordingId)})`);
|
|
368
|
+
if (!res.ok || !res.agent)
|
|
369
|
+
throw new Error(res.error ?? "the extension did not answer");
|
|
370
|
+
const active = res.agent.activeRecordingId === opts.recordingId;
|
|
371
|
+
return { state: active ? res.state?.status ?? "unknown" : res.agent.result ? "ended" : "gone", result: res.agent.result };
|
|
372
|
+
});
|
|
373
|
+
}
|