@clipy/cli 0.13.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/chrome-for-clipy.icns +0 -0
- package/dist/agentReadiness.js +43 -0
- package/dist/chromeExtensionCapture.js +232 -0
- package/dist/chromeForClipy.js +656 -0
- package/dist/index.js +659 -90
- package/dist/skill.js +64 -3
- package/package.json +6 -4
|
Binary file
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
function retryDelayMs(response) {
|
|
2
|
+
const seconds = Number(response.headers.get('retry-after'));
|
|
3
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds * 1_000 : 3_000;
|
|
4
|
+
}
|
|
5
|
+
async function fetchBeforeDeadline(fetchContext, remainingMs) {
|
|
6
|
+
if (remainingMs <= 0)
|
|
7
|
+
return null;
|
|
8
|
+
const controller = new AbortController();
|
|
9
|
+
const timer = setTimeout(() => controller.abort(), remainingMs);
|
|
10
|
+
try {
|
|
11
|
+
return await fetchContext(controller.signal);
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
if (controller.signal.aborted)
|
|
15
|
+
return null;
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
clearTimeout(timer);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export async function waitForAgentContext(fetchContext, options) {
|
|
23
|
+
const startedAt = options.now();
|
|
24
|
+
const initial = await fetchBeforeDeadline(fetchContext, options.timeoutMs);
|
|
25
|
+
if (!initial)
|
|
26
|
+
throw new Error('Agent context request exceeded the wait timeout');
|
|
27
|
+
let response = initial;
|
|
28
|
+
while (response.headers.get('x-clipy-agent-readiness') === 'preparing') {
|
|
29
|
+
const remainingMs = options.timeoutMs - (options.now() - startedAt);
|
|
30
|
+
if (remainingMs <= 0)
|
|
31
|
+
return { response, timedOut: true };
|
|
32
|
+
await options.sleep(Math.min(retryDelayMs(response), remainingMs));
|
|
33
|
+
if (options.now() - startedAt >= options.timeoutMs) {
|
|
34
|
+
return { response, timedOut: true };
|
|
35
|
+
}
|
|
36
|
+
const next = await fetchBeforeDeadline(fetchContext, options.timeoutMs - (options.now() - startedAt));
|
|
37
|
+
if (!next)
|
|
38
|
+
return { response, timedOut: true };
|
|
39
|
+
await response.body?.cancel().catch(() => { });
|
|
40
|
+
response = next;
|
|
41
|
+
}
|
|
42
|
+
return { response, timedOut: false };
|
|
43
|
+
}
|
|
@@ -0,0 +1,232 @@
|
|
|
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
|
+
import { randomUUID } from "node:crypto";
|
|
18
|
+
import { clipyExtensionId, startChrome, } from "./chromeForClipy.js";
|
|
19
|
+
const AGENT_PAGE_PATH = "src/agent/agent.html";
|
|
20
|
+
const AGENT_PROTOCOL = 1;
|
|
21
|
+
const BUSY_STATES = new Set(["starting", "countdown", "recording", "paused", "uploading"]);
|
|
22
|
+
export function extensionStoreUrl(env = process.env) {
|
|
23
|
+
return `https://chromewebstore.google.com/detail/${clipyExtensionId(env)}`;
|
|
24
|
+
}
|
|
25
|
+
export class ExtensionUnavailableError extends Error {
|
|
26
|
+
}
|
|
27
|
+
/** The extension gave a definite answer (failed upload, recording gone), so
|
|
28
|
+
* there is nothing left to retry and the session file can go. Any other error
|
|
29
|
+
* from stop is treated as transient and the file is kept. */
|
|
30
|
+
export class ExtensionRecordingEndedError extends Error {
|
|
31
|
+
}
|
|
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");
|
|
38
|
+
}
|
|
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.`);
|
|
46
|
+
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 });
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
await close();
|
|
55
|
+
throw missing();
|
|
56
|
+
}
|
|
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);
|
|
67
|
+
try {
|
|
68
|
+
return await fn(conn);
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
await conn.close();
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/** Read-only: is the extension installed, current enough, and signed in? */
|
|
75
|
+
export async function extensionReadiness(chromium, port, env) {
|
|
76
|
+
try {
|
|
77
|
+
return await withAgent(chromium, port, env, async ({ call }) => {
|
|
78
|
+
const res = await call("status(undefined, true)");
|
|
79
|
+
if (!res.ok || !res.agent) {
|
|
80
|
+
return { installed: true, version: null, signedIn: false, email: null, recorderState: null, error: res.error ?? "the extension did not answer" };
|
|
81
|
+
}
|
|
82
|
+
if (res.agent.protocol !== AGENT_PROTOCOL) {
|
|
83
|
+
return {
|
|
84
|
+
installed: true,
|
|
85
|
+
version: res.agent.version,
|
|
86
|
+
signedIn: Boolean(res.signedIn),
|
|
87
|
+
email: res.user?.email ?? null,
|
|
88
|
+
recorderState: res.state?.status ?? null,
|
|
89
|
+
error: `extension ${res.agent.version} speaks agent protocol ${res.agent.protocol}; this CLI needs ${AGENT_PROTOCOL}. Update the CLI or the extension.`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
installed: true,
|
|
94
|
+
version: res.agent.version,
|
|
95
|
+
signedIn: Boolean(res.signedIn),
|
|
96
|
+
email: res.user?.email ?? null,
|
|
97
|
+
recorderState: res.state?.status ?? null,
|
|
98
|
+
};
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error instanceof ExtensionUnavailableError) {
|
|
103
|
+
return { installed: false, version: null, signedIn: false, email: null, recorderState: null, error: error.message };
|
|
104
|
+
}
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function explainStartError(message) {
|
|
109
|
+
if (/not been invoked|activeTab|cannot be captured/i.test(message)) {
|
|
110
|
+
return (`Chrome refused tab capture without a click (${message}). Chrome for Clipy must run with ` +
|
|
111
|
+
`--allowlisted-extension-id; \`clipy chrome stop && clipy chrome start\` relaunches it with the flag. ` +
|
|
112
|
+
`If it still fails, this Chrome version may no longer honour the flag: use --source chrome-for-clipy instead.`);
|
|
113
|
+
}
|
|
114
|
+
return message;
|
|
115
|
+
}
|
|
116
|
+
/** CDP target ids and chrome.tabs ids are unrelated, so the target is named by
|
|
117
|
+
* a one-off title token the extension can see, then the title is restored. */
|
|
118
|
+
async function resolveTabId(target, call) {
|
|
119
|
+
const token = JSON.stringify(`clipy-agent-${randomUUID()}`);
|
|
120
|
+
try {
|
|
121
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
122
|
+
await target.evaluate(`(() => { globalThis.__clipyOriginalTitle ??= document.title; document.title = ${token}; })()`);
|
|
123
|
+
const tabId = (await call(`findTabByTitle(${token})`));
|
|
124
|
+
if (typeof tabId === "number")
|
|
125
|
+
return tabId;
|
|
126
|
+
await new Promise((r) => setTimeout(r, 250 * attempt));
|
|
127
|
+
}
|
|
128
|
+
throw new Error("could not identify the recording tab in Chrome for Clipy (does the page keep rewriting its title?)");
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
await target
|
|
132
|
+
.evaluate(`(() => { if (document.title === ${token}) document.title = globalThis.__clipyOriginalTitle ?? ""; delete globalThis.__clipyOriginalTitle; })()`)
|
|
133
|
+
.catch(() => { });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
export async function startExtensionRecording(chromium, opts) {
|
|
137
|
+
const started = await startChrome(opts.home, opts.env, opts.platform, opts.port);
|
|
138
|
+
if (!started.ok)
|
|
139
|
+
throw new Error(`Chrome for Clipy is not available: ${started.error}`);
|
|
140
|
+
const port = started.state.port;
|
|
141
|
+
return withAgent(chromium, port, opts.env, async ({ context, call }) => {
|
|
142
|
+
const ready = await call("status(undefined, true)");
|
|
143
|
+
if (!ready.ok || !ready.agent)
|
|
144
|
+
throw new Error(ready.error ?? "the Clipy extension did not answer");
|
|
145
|
+
if (ready.agent.protocol !== AGENT_PROTOCOL) {
|
|
146
|
+
throw new Error(`extension ${ready.agent.version} speaks agent protocol ${ready.agent.protocol}; this CLI needs ${AGENT_PROTOCOL}`);
|
|
147
|
+
}
|
|
148
|
+
if (!ready.signedIn) {
|
|
149
|
+
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`).");
|
|
150
|
+
}
|
|
151
|
+
if (ready.state && BUSY_STATES.has(ready.state.status)) {
|
|
152
|
+
throw new Error(`the Clipy extension is already ${ready.state.status}; stop or abort that recording first`);
|
|
153
|
+
}
|
|
154
|
+
const target = await context.newPage();
|
|
155
|
+
try {
|
|
156
|
+
try {
|
|
157
|
+
await target.goto(opts.targetUrl, { waitUntil: "load", timeout: 30_000 });
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
opts.log("target page load timed out; recording its current state anyway");
|
|
161
|
+
}
|
|
162
|
+
await target.bringToFront().catch(() => { });
|
|
163
|
+
const tabId = await resolveTabId(target, call);
|
|
164
|
+
const res = await call(`start(${tabId}, ${Math.round(opts.maxSec)})`);
|
|
165
|
+
if (!res.ok || !res.agent?.activeRecordingId) {
|
|
166
|
+
throw new Error(explainStartError(res.error ?? `recording did not start (state: ${res.state?.status ?? "unknown"})`));
|
|
167
|
+
}
|
|
168
|
+
opts.log(`extension ${res.agent.version} recording tab ${tabId} (${res.agent.activeRecordingId})`);
|
|
169
|
+
return {
|
|
170
|
+
recordingId: res.agent.activeRecordingId,
|
|
171
|
+
startedAtEpochMs: Date.now(),
|
|
172
|
+
extensionVersion: res.agent.version,
|
|
173
|
+
cdpHttpUrl: `http://127.0.0.1:${port}`,
|
|
174
|
+
chromePid: started.state.pid,
|
|
175
|
+
port,
|
|
176
|
+
pageUrl: target.url(),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
await target.close().catch(() => { });
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/** 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 }) => {
|
|
188
|
+
const id = JSON.stringify(opts.recordingId);
|
|
189
|
+
const stopped = await call(`stop(${id})`);
|
|
190
|
+
if (!stopped.ok) {
|
|
191
|
+
const message = stopped.error ?? "the extension refused to stop the recording";
|
|
192
|
+
throw /not active/.test(message) ? new ExtensionRecordingEndedError(message) : new Error(message);
|
|
193
|
+
}
|
|
194
|
+
const deadline = Date.now() + opts.timeoutMs;
|
|
195
|
+
let res = stopped;
|
|
196
|
+
for (;;) {
|
|
197
|
+
const result = res.agent?.result;
|
|
198
|
+
if (result?.status === "complete" && result.publicId && result.shareUrl) {
|
|
199
|
+
return { publicId: result.publicId, shareUrl: result.shareUrl };
|
|
200
|
+
}
|
|
201
|
+
if (result?.status === "error") {
|
|
202
|
+
throw new ExtensionRecordingEndedError(`the extension's upload failed: ${result.error ?? "unknown error"}`);
|
|
203
|
+
}
|
|
204
|
+
if (res.agent && res.agent.activeRecordingId !== opts.recordingId && !result) {
|
|
205
|
+
const reason = res.state?.status === "error" && res.state.message ? `: ${res.state.message}` : "";
|
|
206
|
+
throw new ExtensionRecordingEndedError(`the recording ended without an upload${reason}`);
|
|
207
|
+
}
|
|
208
|
+
if (Date.now() >= deadline)
|
|
209
|
+
throw new Error("timed out waiting for the extension to finish uploading");
|
|
210
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
211
|
+
res = await call(`status(${id})`);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
/** Resolves once the extension has cancelled the recording or confirms it is
|
|
216
|
+
* 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 }) => {
|
|
219
|
+
const res = await call(`cancel(${JSON.stringify(opts.recordingId)})`);
|
|
220
|
+
if (!res.ok && !/not active/.test(res.error ?? ""))
|
|
221
|
+
throw new Error(res.error ?? "cancel failed");
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
export async function extensionRecordingStatus(chromium, opts) {
|
|
225
|
+
return withAgent(chromium, opts.port, opts.env, async ({ call }) => {
|
|
226
|
+
const res = await call(`status(${JSON.stringify(opts.recordingId)})`);
|
|
227
|
+
if (!res.ok || !res.agent)
|
|
228
|
+
throw new Error(res.error ?? "the extension did not answer");
|
|
229
|
+
const active = res.agent.activeRecordingId === opts.recordingId;
|
|
230
|
+
return { state: active ? res.state?.status ?? "unknown" : res.agent.result ? "ended" : "gone", result: res.agent.result };
|
|
231
|
+
});
|
|
232
|
+
}
|