@clipy/cli 0.3.0 → 0.4.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Codersera
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @clipy/cli
2
2
 
3
+ > This repository is the public mirror of **`@clipy/cli`**. The package is developed in
4
+ > the Clipy monorepo and synced here with each npm release — browse the source or file
5
+ > issues here.
6
+
3
7
  [![npm version](https://img.shields.io/npm/v/%40clipy%2Fcli)](https://www.npmjs.com/package/@clipy/cli)
4
8
  [![license: MIT](https://img.shields.io/npm/l/%40clipy%2Fcli)](https://github.com/manovagyanik1/clipy-cli/blob/main/LICENSE)
5
9
  [![node >= 18](https://img.shields.io/node/v/%40clipy%2Fcli)](https://www.npmjs.com/package/@clipy/cli)
@@ -14,25 +18,44 @@ recording an instant share link, an AI transcript and summary, and
14
18
  [agent-readable context](https://clipy.online/for-agents) — so both humans and AI
15
19
  agents can act on what was recorded. This package is its terminal client.
16
20
 
17
- Every command except [`record`](#record) is **read-only** — those can never create,
18
- edit, or delete your recordings. `record` is the one that creates a recording, and
19
- only with an `ingest`-scoped key.
21
+ The read commands are **read-only** with any key. The write commands —
22
+ [`record`](#record), the `session`/`mark` flow, and `transcript --replace` — create
23
+ recordings or replace a transcript, and work only with an `ingest`-scoped key.
20
24
 
21
25
  ```bash
22
- npx @clipy/cli list # or: npm i -g @clipy/cli && clipy list
26
+ npx @clipy/cli agents install claude # browser-approve login + install the Clipy skill
23
27
  ```
24
28
 
25
29
  ## Setup
26
30
 
27
- 1. Create a free API key at **https://clipy.online/settings/api-keys** (it looks like
28
- `clipy_sk_live_…`). Copy it — it's shown only once.
29
- 2. Log in (stores the key in `~/.config/clipy/config.json`, mode 0600):
30
-
31
31
  ```bash
32
32
  clipy login
33
33
  ```
34
34
 
35
- Or skip the stored login entirely and set `CLIPY_API_KEY` in your environment.
35
+ `clipy login` opens your browser to approve this device — like `gh auth login` — and
36
+ stores the key in `~/.config/clipy/config.json` (mode 0600). No copy-pasting a key.
37
+
38
+ Wiring up a coding agent? One command does both the browser login and the skill install:
39
+
40
+ ```bash
41
+ npx @clipy/cli agents install claude # or: codex / cursor
42
+ ```
43
+
44
+ **Prefer to paste a key you minted yourself?** Create one at
45
+ **https://clipy.online/settings/api-keys** (it looks like `clipy_sk_live_…`) and store it
46
+ without the browser:
47
+
48
+ ```bash
49
+ clipy login --key clipy_sk_live_… # or: clipy login --paste to be prompted
50
+ ```
51
+
52
+ **On SSH or a display-less Linux box**, `clipy login` automatically switches to a
53
+ copy-code flow (also available anywhere as `clipy login --no-browser`): it prints the
54
+ approval URL for you to open on **any** device — your laptop, your phone — and after you
55
+ click Approve the page shows a one-time code to paste back into the waiting terminal.
56
+ The code alone is useless without the PKCE verifier held by that terminal, so it's safe
57
+ to ferry by hand. Without a TTY at all (scripts, CI), use `CLIPY_API_KEY` or
58
+ `clipy login --key`.
36
59
 
37
60
  ## Commands
38
61
 
@@ -110,6 +133,28 @@ Safety rails are built in: the session **auto-stops and uploads** at `--max <sec
110
133
  abort` discards everything; a crashed daemon is detected and cleared on the next command;
111
134
  corrupt captures are refused before upload, and a failed upload keeps the local file.
112
135
 
136
+ ## Record the real screen — a window, a display (Mac)
137
+
138
+ `--source mac-screen` on `record` / `session start` records through the **running Clipy
139
+ Mac app** (ScreenCaptureKit — real screen, real logged-in browser, not a headless page).
140
+ First use shows a consent dialog in the app; the recording indicator is always visible.
141
+
142
+ By default it captures the primary display. Target one window instead:
143
+
144
+ ```bash
145
+ clipy sources # list displays + windows with ids
146
+ clipy session start --source mac-screen --window "Chrome" --title "Fix walkthrough"
147
+ # … the agent drives the real, logged-in Chrome while Clipy records that window …
148
+ clipy mark "reproduced the bug"
149
+ clipy mark "fix applied — retesting"
150
+ clipy session stop # uploads, prints the share link
151
+ ```
152
+
153
+ `--window` takes a window id from `clipy sources`, or an app/title substring
154
+ (case-insensitive; ambiguous matches list the candidates instead of guessing).
155
+ `--display <id>` records a specific display. Both also work on one-shot
156
+ `clipy record --source mac-screen --for 30`.
157
+
113
158
  ## Scripting
114
159
 
115
160
  `--json` prints the raw API response for `list`, `search`, `show`, `transcript`,
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Browser-approve login for `clipy login` — the `gh auth login` shape.
3
+ *
4
+ * Flow (the wire contract, frozen against the server):
5
+ * 1. Generate a PKCE `verifier` (32 random bytes, base64url), its S256
6
+ * `challenge` = base64url(sha256(verifier)), and a random `state`.
7
+ * 2. Bind a loopback HTTP listener on 127.0.0.1 with an ephemeral port.
8
+ * 3. Open the browser at {apiUrl}/cli/authorize?challenge&state&port&name&scopes
9
+ * (and always print the URL so a headless open still has a fallback).
10
+ * 4. The browser redirects to http://127.0.0.1:<port>/callback?code&state on
11
+ * approve, or ?error=access_denied&state on deny. `state` is checked
12
+ * strictly — a mismatch is treated as an attack and fails.
13
+ * 5. POST {apiUrl}/api/cli-auth/exchange {code, verifier} → {apiKey, scopes,
14
+ * email}. Retries once on a network error or 5xx only; a consumed-code 400
15
+ * is single-use server-side and is never retried.
16
+ *
17
+ * Node stdlib only (http, crypto, os, child_process) — the CLI ships zero deps.
18
+ * Storing + verifying the returned key is the caller's job (index.ts), so this
19
+ * module has no dependency on the config store.
20
+ */
21
+ import { createServer } from "node:http";
22
+ import { createHash, randomBytes } from "node:crypto";
23
+ import { hostname } from "node:os";
24
+ import { spawn } from "node:child_process";
25
+ /**
26
+ * True when the loopback redirect can't work and the copy-code flow should be
27
+ * used instead: an SSH session (the browser runs on a different machine than
28
+ * the listener), or Linux with no display server to open a browser on.
29
+ */
30
+ export function shouldUseManualLogin(env = process.env) {
31
+ if (env.SSH_CONNECTION || env.SSH_TTY || env.SSH_CLIENT)
32
+ return true;
33
+ if (process.platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY)
34
+ return true;
35
+ return false;
36
+ }
37
+ const DEFAULT_SCOPES = ["recordings:read", "ingest"];
38
+ const DEFAULT_TIMEOUT_MS = 180_000;
39
+ const EXCHANGE_TIMEOUT_MS = 20_000;
40
+ function base64url(buf) {
41
+ return buf.toString("base64url");
42
+ }
43
+ /** Spawn the OS browser opener, always printing the URL as a fallback. */
44
+ function openBrowser(url, log) {
45
+ log("If the browser didn't open, visit:");
46
+ log(` ${url}`);
47
+ if (process.env.CLIPY_LOGIN_NO_BROWSER)
48
+ return;
49
+ let cmd;
50
+ let args;
51
+ if (process.platform === "darwin") {
52
+ cmd = "open";
53
+ args = [url];
54
+ }
55
+ else if (process.platform === "win32") {
56
+ cmd = "cmd";
57
+ args = ["/c", "start", "", url];
58
+ }
59
+ else {
60
+ cmd = "xdg-open";
61
+ args = [url];
62
+ }
63
+ try {
64
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
65
+ child.on("error", () => { }); // opener missing — the printed URL is the fallback
66
+ child.unref();
67
+ }
68
+ catch {
69
+ // ignore — the URL is already printed
70
+ }
71
+ }
72
+ export async function browserLogin(opts) {
73
+ const apiUrl = opts.apiUrl.replace(/\/+$/, "");
74
+ const scopes = opts.scopes && opts.scopes.length ? opts.scopes : DEFAULT_SCOPES;
75
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
76
+ const log = opts.log ?? (() => { });
77
+ const verifier = base64url(randomBytes(32)); // 43-char base64url PKCE verifier
78
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
79
+ const state = base64url(randomBytes(16));
80
+ const clientName = `Clipy CLI — ${hostname()}`.slice(0, 120);
81
+ const buildAuthorizeUrl = (port) => {
82
+ const url = new URL(`${apiUrl}/cli/authorize`);
83
+ url.searchParams.set("challenge", challenge);
84
+ url.searchParams.set("state", state);
85
+ if (port === null) {
86
+ url.searchParams.set("mode", "manual");
87
+ }
88
+ else {
89
+ url.searchParams.set("port", String(port));
90
+ }
91
+ url.searchParams.set("name", clientName);
92
+ url.searchParams.set("scopes", scopes.join(","));
93
+ return url.toString();
94
+ };
95
+ const opener = opts.open ?? ((u) => openBrowser(u, log));
96
+ if (opts.manual) {
97
+ // Copy-code flow: the approval page shows the one-time code; the user
98
+ // pastes it here. PKCE still binds the exchange to THIS process — a
99
+ // shoulder-surfed code is useless without the verifier.
100
+ if (!opts.promptCode)
101
+ throw new Error("manual login requires a code prompt");
102
+ const manualUrl = buildAuthorizeUrl(null);
103
+ if (opts.open) {
104
+ await opts.open(manualUrl); // tests drive the approval themselves
105
+ }
106
+ else {
107
+ log("Open this URL on any device, sign in, and approve:");
108
+ log(` ${manualUrl}`);
109
+ }
110
+ const code = (await opts.promptCode()).trim();
111
+ if (!code)
112
+ throw new Error("no approval code entered");
113
+ return exchangeCode(apiUrl, code, verifier);
114
+ }
115
+ const { code } = await waitForCallback({
116
+ state,
117
+ timeoutMs,
118
+ log,
119
+ open: async (port) => {
120
+ await opener(buildAuthorizeUrl(port));
121
+ },
122
+ });
123
+ return exchangeCode(apiUrl, code, verifier);
124
+ }
125
+ /** Bind the loopback listener, open the browser, and resolve with the code. */
126
+ function waitForCallback(args) {
127
+ const { state, timeoutMs, log, open } = args;
128
+ return new Promise((resolve, reject) => {
129
+ let settled = false;
130
+ const server = createServer(handleRequest);
131
+ const finish = (fn) => {
132
+ if (settled)
133
+ return;
134
+ settled = true;
135
+ clearTimeout(timer);
136
+ process.removeListener("SIGINT", onSigint);
137
+ server.close();
138
+ fn();
139
+ };
140
+ const timer = setTimeout(() => {
141
+ finish(() => reject(new Error(`timed out after ${Math.round(timeoutMs / 1000)}s waiting for browser approval`)));
142
+ }, timeoutMs);
143
+ const onSigint = () => finish(() => reject(new Error("login cancelled")));
144
+ process.once("SIGINT", onSigint);
145
+ function handleRequest(req, res) {
146
+ let url;
147
+ try {
148
+ url = new URL(req.url ?? "/", "http://127.0.0.1");
149
+ }
150
+ catch {
151
+ res.writeHead(400).end();
152
+ return;
153
+ }
154
+ if (url.pathname !== "/callback") {
155
+ // Stray request (favicon probes, scanners) — 404 and keep waiting.
156
+ res.writeHead(404, { "Content-Type": "text/plain" }).end("Not found");
157
+ return;
158
+ }
159
+ if (settled) {
160
+ // Double callback — first one already won; just render a friendly page.
161
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(pageSuccess());
162
+ return;
163
+ }
164
+ if (url.searchParams.get("state") !== state) {
165
+ // State mismatch = possible CSRF/injection. Fail the whole flow.
166
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }).end(pageError());
167
+ finish(() => reject(new Error("state mismatch on the login callback — aborting for safety")));
168
+ return;
169
+ }
170
+ const error = url.searchParams.get("error");
171
+ if (error) {
172
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(pageDenied());
173
+ finish(() => reject(new Error(error === "access_denied"
174
+ ? "login was cancelled in the browser"
175
+ : `login failed: ${error}`)));
176
+ return;
177
+ }
178
+ const code = url.searchParams.get("code");
179
+ if (!code) {
180
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" }).end(pageError());
181
+ finish(() => reject(new Error("login callback was missing the authorization code")));
182
+ return;
183
+ }
184
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }).end(pageSuccess());
185
+ finish(() => resolve({ code }));
186
+ }
187
+ server.on("error", (e) => {
188
+ finish(() => reject(new Error(`could not start the local login listener (${e.code ?? e.message})`)));
189
+ });
190
+ server.listen(0, "127.0.0.1", () => {
191
+ const addr = server.address();
192
+ if (!addr || typeof addr === "string") {
193
+ finish(() => reject(new Error("could not determine the local login listener port")));
194
+ return;
195
+ }
196
+ Promise.resolve(open(addr.port)).catch((e) => {
197
+ // A failed opener isn't fatal — the URL was printed. Keep waiting.
198
+ log(`could not open the browser automatically (${e.message}) — open the URL above`);
199
+ });
200
+ });
201
+ });
202
+ }
203
+ /** POST the code + PKCE verifier for the API key. One retry on network/5xx. */
204
+ async function exchangeCode(apiUrl, code, verifier) {
205
+ let lastError = null;
206
+ for (let attempt = 1; attempt <= 2; attempt++) {
207
+ const controller = new AbortController();
208
+ const timer = setTimeout(() => controller.abort(), EXCHANGE_TIMEOUT_MS);
209
+ let res;
210
+ try {
211
+ res = await fetch(`${apiUrl}/api/cli-auth/exchange`, {
212
+ method: "POST",
213
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
214
+ body: JSON.stringify({ code, verifier }),
215
+ signal: controller.signal,
216
+ });
217
+ }
218
+ catch (e) {
219
+ // Network error / abort → retry once, then give up.
220
+ lastError = new Error(e.name === "AbortError" ? "the key exchange timed out" : e.message);
221
+ if (attempt === 1)
222
+ continue;
223
+ throw lastError;
224
+ }
225
+ finally {
226
+ clearTimeout(timer);
227
+ }
228
+ // 5xx is transient → retry once. 4xx (consumed-code 400, rate-limit 429)
229
+ // is terminal — the code is single-use, so retrying can only ever 400.
230
+ if (res.status >= 500 && attempt === 1) {
231
+ lastError = new Error(`the key exchange failed (HTTP ${res.status})`);
232
+ continue;
233
+ }
234
+ const text = await res.text();
235
+ let body = {};
236
+ try {
237
+ body = text ? JSON.parse(text) : {};
238
+ }
239
+ catch {
240
+ body = {};
241
+ }
242
+ if (!res.ok) {
243
+ const msg = typeof body.error === "string" && body.error
244
+ ? body.error
245
+ : `the key exchange failed (HTTP ${res.status})`;
246
+ throw new Error(msg);
247
+ }
248
+ const apiKey = typeof body.apiKey === "string" ? body.apiKey : "";
249
+ if (!apiKey)
250
+ throw new Error("the login response did not include an API key");
251
+ return { apiKey, scopes: normalizeScopes(body.scopes), email: typeof body.email === "string" ? body.email : "" };
252
+ }
253
+ throw lastError ?? new Error("the key exchange failed");
254
+ }
255
+ function normalizeScopes(v) {
256
+ if (Array.isArray(v))
257
+ return v.filter((s) => typeof s === "string");
258
+ if (typeof v === "string")
259
+ return v.split(",").map((s) => s.trim()).filter(Boolean);
260
+ return [];
261
+ }
262
+ // --- Loopback response pages (served to the browser, then it can be closed) ---
263
+ function htmlPage(title, glyph, accent, heading, sub) {
264
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title><style>
265
+ :root{color-scheme:light dark}
266
+ *{box-sizing:border-box}
267
+ body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:#0b0b0f;color:#e8e8ea;font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
268
+ .card{max-width:26rem;margin:1.5rem;padding:2.5rem 2rem;text-align:center;background:#15151b;border:1px solid #26262f;border-radius:14px}
269
+ .mark{width:48px;height:48px;margin:0 auto 1.25rem;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.6rem;background:${accent}22;color:${accent}}
270
+ h1{margin:0 0 .5rem;font-size:1.35rem}
271
+ p{margin:0;color:#a1a1aa}
272
+ </style></head><body><div class="card"><div class="mark">${glyph}</div><h1>${heading}</h1><p>${sub}</p></div></body></html>`;
273
+ }
274
+ function pageSuccess() {
275
+ return htmlPage("Clipy — logged in", "✓", "#ff7a45", "You're logged in", "Return to your terminal — you can close this tab.");
276
+ }
277
+ function pageDenied() {
278
+ return htmlPage("Clipy — login cancelled", "×", "#a1a1aa", "Login cancelled", "You can close this tab and run the command again.");
279
+ }
280
+ function pageError() {
281
+ return htmlPage("Clipy — login error", "!", "#f87171", "Something went wrong", "This login request was invalid. Return to your terminal and try again.");
282
+ }
package/dist/index.js CHANGED
@@ -6,10 +6,11 @@
6
6
  * summaries, key moments) from the terminal, download the MP4s, or export
7
7
  * subtitles — without opening a browser.
8
8
  *
9
- * Auth: a personal API key (`clipy_sk_live_…`), minted at
10
- * https://clipy.online/settings/api-keys. `clipy login` stores it in
11
- * ~/.config/clipy/config.json (0600); CLIPY_API_KEY / --key override it.
12
- * Read-only: the CLI can never create, modify, or delete recordings.
9
+ * Auth: a personal API key (`clipy_sk_live_…`). `clipy login` opens your
10
+ * browser to approve this device (like `gh auth login`) and stores the key in
11
+ * ~/.config/clipy/config.json (0600); `--key`/`--paste` store a key you pasted
12
+ * from https://clipy.online/settings/api-keys instead. CLIPY_API_KEY / --key
13
+ * override the stored key. Read-only unless the key carries the "ingest" scope.
13
14
  */
14
15
  import { parseArgs } from "node:util";
15
16
  import { appendFileSync, closeSync, createWriteStream, mkdirSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
@@ -22,6 +23,8 @@ import { Readable, Transform } from "node:stream";
22
23
  import { pipeline } from "node:stream/promises";
23
24
  import { createRequire } from "node:module";
24
25
  import { CLIPY_SKILL_MD } from "./skill.js";
26
+ import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
27
+ import { BridgeUnavailableError, bridgeRequest, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, } from "./macBridge.js";
25
28
  // Exit quietly when stdout/stderr close early (e.g. `clipy list | head`).
26
29
  for (const stream of [process.stdout, process.stderr]) {
27
30
  stream.on("error", (e) => {
@@ -129,7 +132,7 @@ const FETCH_TIMEOUT_MS = 20_000;
129
132
  function requireKey(ctx) {
130
133
  if (ctx.apiKey)
131
134
  return ctx.apiKey;
132
- die(`no API key. Run ${c.bold("clipy login")} (create a key at ${ctx.apiUrl}/settings/api-keys), or set CLIPY_API_KEY.`);
135
+ die(`no API key. Run ${c.bold("clipy login")} to approve this device in your browser, or set CLIPY_API_KEY.`);
133
136
  }
134
137
  async function api(ctx, path, accept = "application/json") {
135
138
  const key = requireKey(ctx);
@@ -260,7 +263,10 @@ ${c.bold("USAGE")}
260
263
  clipy <command> [arguments] [flags]
261
264
 
262
265
  ${c.bold("AUTH")}
263
- login [--key <clipy_sk_live_…>] Verify + store your API key (${c.dim("~/.config/clipy/config.json")})
266
+ login Approve this device in your browser (like ${c.dim("gh auth login")})
267
+ login --no-browser Copy-code flow for SSH/headless: open the URL anywhere, paste the code back
268
+ login --key <clipy_sk_live_…> Skip the browser: store a key you pasted
269
+ login --paste Prompt for a pasted key instead of the browser
264
270
  logout Delete the stored key
265
271
  whoami Check which key is active and that it works
266
272
 
@@ -295,6 +301,12 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
295
301
  --wait Block until the transcript is ready before printing
296
302
 
297
303
  ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
304
+ ${c.dim("--source mac-screen on record/session records the REAL screen via the")}
305
+ ${c.dim("running Clipy Mac app (consent-gated, indicator always visible).")}
306
+ ${c.dim("Target one window or display instead of the whole screen:")}
307
+ sources List capturable displays + windows (ids for --window/--display)
308
+ --window "<title|app|id>" Record just that window (e.g. --window Chrome)
309
+ --display <id> Record a specific display
298
310
  session start --url <app> [--max <sec>] [--title <t>]
299
311
  Start recording in a background daemon and
300
312
  return immediately (auto-stops + uploads at
@@ -327,30 +339,103 @@ ${c.bold("EXIT CODES")}
327
339
  0 ok · 1 error · 2 usage · 3 artifact not ready (transcript/summary/wait)
328
340
 
329
341
  ${c.bold("SETUP")}
330
- 1. Create a key at ${c.cyan("https://clipy.online/settings/api-keys")}
331
- 2. ${c.bold("clipy login")}
332
- 3. ${c.bold("clipy list")}
342
+ 1. ${c.bold("clipy login")} approve this device in your browser
343
+ 2. ${c.bold("clipy list")} (or: ${c.bold("clipy agents install claude")} to wire up a coding agent)
333
344
 
334
- Every command except ${c.bold("record")} and ${c.bold("session")}/${c.bold("mark")} is read-only. Only those
335
- create recordings, and only with a key that carries the "ingest" permission.
345
+ Write commands — ${c.bold("record")}, ${c.bold("session")}/${c.bold("mark")}, and ${c.bold("transcript --replace")} — need a key
346
+ with the "ingest" permission. Everything else is read-only.
336
347
  `;
337
- async function cmdLogin(ctx, keyFlag) {
338
- let key = keyFlag?.trim() || "";
348
+ async function cmdLogin(ctx, opts) {
349
+ const keyFlag = opts.key?.trim() || "";
350
+ // A pasted key, an explicit --paste, or a non-interactive stdout all take the
351
+ // paste path — without a terminal we can't run either interactive flow.
352
+ if (keyFlag || opts.paste || !process.stdout.isTTY) {
353
+ await loginWithPaste(ctx, keyFlag);
354
+ return;
355
+ }
356
+ // --no-browser, SSH sessions, and display-less Linux take the copy-code
357
+ // flow: this machine can't receive the loopback redirect (or can't open a
358
+ // browser at all), so the approval page shows a code to paste back here.
359
+ await loginWithBrowser(ctx, opts.noBrowser || shouldUseManualLogin());
360
+ }
361
+ /** Browser-approve flow (the default): open clipy.online, approve, store. */
362
+ async function loginWithBrowser(ctx, manual) {
363
+ process.stderr.write(`${c.dim(manual ? "approve this device from a browser on any machine…" : "opening your browser to approve this device…")}\n`);
364
+ let result;
365
+ try {
366
+ result = await browserLogin({
367
+ apiUrl: ctx.apiUrl,
368
+ log: (m) => process.stderr.write(`${m}\n`),
369
+ manual,
370
+ promptCode: manual
371
+ ? () => promptVisible("Paste the approval code shown in the browser: ")
372
+ : undefined,
373
+ });
374
+ }
375
+ catch (e) {
376
+ die(`${e.message}\n` +
377
+ `You can log in with a pasted key instead: ${c.bold("clipy login --key <clipy_sk_live_…>")} ` +
378
+ `(create one at ${ctx.apiUrl}/settings/api-keys).`);
379
+ }
380
+ // Browser-minted keys are stored BEFORE the verify round-trip: the secret
381
+ // was just delivered once and is unrecoverable — a transient network blip
382
+ // on the verify call must not lose it.
383
+ await storeAndVerifyKey(ctx, result.apiKey, { scopes: result.scopes, email: result.email }, { storeFirst: true });
384
+ }
385
+ /** Paste flow (fallback): take a key from --key or a hidden prompt, store it. */
386
+ async function loginWithPaste(ctx, keyFlag) {
387
+ let key = keyFlag;
339
388
  if (!key) {
340
389
  key = await promptHidden(`Paste your Clipy API key (from ${ctx.apiUrl}/settings/api-keys): `);
341
390
  }
342
391
  if (!key.startsWith("clipy_sk_live_")) {
343
392
  die("that doesn't look like a Clipy API key (expected it to start with clipy_sk_live_)");
344
393
  }
345
- // Verify before storing.
346
- const probe = { ...ctx, apiKey: key };
347
- await apiJson(probe, "/api/v1/recordings?limit=1");
348
- const cfg = readConfig();
349
- cfg.apiKey = key;
350
- if (ctx.apiUrl !== "https://clipy.online")
351
- cfg.apiUrl = ctx.apiUrl;
352
- writeConfig(cfg);
353
- process.stdout.write(`${c.green("✓")} key verified and saved to ${c.dim(configPath())}\n`);
394
+ // Pasted keys still verify first — the user has the secret in hand, and
395
+ // catching a typo'd/revoked key before storing it is the better failure.
396
+ await storeAndVerifyKey(ctx, key, {}, { storeFirst: false });
397
+ }
398
+ /** Store a key (0600) + verify it against the API, order per `storeFirst`. */
399
+ async function storeAndVerifyKey(ctx, key, meta, opts) {
400
+ const store = () => {
401
+ const cfg = readConfig();
402
+ cfg.apiKey = key;
403
+ if (ctx.apiUrl !== "https://clipy.online")
404
+ cfg.apiUrl = ctx.apiUrl;
405
+ writeConfig(cfg);
406
+ };
407
+ if (opts.storeFirst) {
408
+ store();
409
+ try {
410
+ await apiJson({ ...ctx, apiKey: key }, "/api/v1/recordings?limit=1");
411
+ }
412
+ catch (e) {
413
+ process.stderr.write(`${c.yellow("!")} key saved to ${configPath()}, but verifying it failed (${e.message}).\n` +
414
+ ` Check with: ${c.bold("clipy whoami")}\n`);
415
+ return;
416
+ }
417
+ }
418
+ else {
419
+ await apiJson({ ...ctx, apiKey: key }, "/api/v1/recordings?limit=1");
420
+ store();
421
+ }
422
+ const bits = [];
423
+ if (meta.email)
424
+ bits.push(meta.email);
425
+ if (meta.scopes?.length)
426
+ bits.push(`scopes: ${meta.scopes.join(", ")}`);
427
+ const detail = bits.length ? ` ${c.dim(`(${bits.join(" · ")})`)}` : "";
428
+ process.stdout.write(`${c.green("✓")} logged in${detail} — key saved to ${c.dim(configPath())}\n`);
429
+ }
430
+ /** Plain visible readline prompt (for one-time codes the user just copied). */
431
+ function promptVisible(question) {
432
+ return new Promise((resolvePrompt) => {
433
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
434
+ rl.question(question, (answer) => {
435
+ rl.close();
436
+ resolvePrompt(answer.trim());
437
+ });
438
+ });
354
439
  }
355
440
  function promptHidden(question) {
356
441
  return new Promise((resolvePrompt) => {
@@ -911,7 +996,9 @@ async function uploadWebmToClipy(ctx, opts) {
911
996
  return {
912
997
  publicId,
913
998
  shareUrl: `${ctx.apiUrl}/video/${publicId}`,
914
- contextUrl: `${ctx.apiUrl}/api/agent-context/${publicId}`,
999
+ // The friendly content-negotiated form: markdown to agents, a rendered
1000
+ // page to browsers. Same document as /api/agent-context/<id>.
1001
+ contextUrl: `${ctx.apiUrl}/video/${publicId}.md`,
915
1002
  sizeBytes,
916
1003
  };
917
1004
  }
@@ -1107,7 +1194,105 @@ function cleanupSessionFiles(state, file) {
1107
1194
  }
1108
1195
  }
1109
1196
  }
1197
+ // --- Mac bridge flows (--source mac-screen): the desktop app records -------
1198
+ /** Resolves --window/--display to a bridge capture source (null = app default,
1199
+ * i.e. the full primary display). die()s with the candidate list on no/ambiguous
1200
+ * match so the agent can correct itself. */
1201
+ async function resolveBridgeTarget(info, opts) {
1202
+ if (!opts.window && !opts.display)
1203
+ return null;
1204
+ try {
1205
+ return await resolveCaptureSource(info, opts);
1206
+ }
1207
+ catch (e) {
1208
+ die(e.message);
1209
+ }
1210
+ }
1211
+ /** One-shot real-screen recording through the running Clipy app. */
1212
+ async function cmdRecordMac(opts) {
1213
+ const info = readBridgeInfo();
1214
+ const log = (m) => {
1215
+ if (!opts.json)
1216
+ process.stderr.write(`${m}\n`);
1217
+ };
1218
+ const target = await resolveBridgeTarget(info, opts);
1219
+ log(`${c.dim(`asking the Clipy app (v${info.appVersion}) to record ${target?.label ?? "the screen"}…`)}`);
1220
+ await bridgeRequest(info, "start", {
1221
+ // The recording is stopped by us after forSec; maxSec is the safety net
1222
+ // in case this CLI process dies mid-wait.
1223
+ maxSec: Math.min(opts.forSec + 60, 1800),
1224
+ title: opts.name,
1225
+ description: opts.description,
1226
+ notes: opts.notes.map((n) => ({ startMs: n.startMs, text: n.text })),
1227
+ ...(target ? { source: target.source } : {}),
1228
+ });
1229
+ log(`${c.dim(`recording for ${opts.forSec}s…`)}`);
1230
+ await new Promise((r) => setTimeout(r, opts.forSec * 1000));
1231
+ log(`${c.dim("stopping + uploading…")}`);
1232
+ const result = await bridgeRequest(info, "stop");
1233
+ return {
1234
+ publicId: String(result.publicId ?? ""),
1235
+ shareUrl: String(result.shareUrl ?? ""),
1236
+ };
1237
+ }
1238
+ function macSessionState(info, maxSec) {
1239
+ const dir = sessionDir();
1240
+ return {
1241
+ version: 1,
1242
+ kind: "mac",
1243
+ bridge: { socketPath: info.socketPath, token: info.token, pid: info.pid },
1244
+ pid: info.pid,
1245
+ cwd: process.cwd(),
1246
+ url: "mac-screen",
1247
+ maxSec,
1248
+ width: 0,
1249
+ height: 0,
1250
+ state: "recording",
1251
+ recordStartEpochMs: Date.now(),
1252
+ marksPath: join(dir, "unused"),
1253
+ controlPath: join(dir, "unused"),
1254
+ logPath: join(dir, "unused"),
1255
+ tmpDir: join(dir, "unused"),
1256
+ };
1257
+ }
1258
+ function bridgeInfoFromSession(state) {
1259
+ if (!state.bridge) {
1260
+ die("session file is missing bridge info — abort it with `clipy session abort` and restart");
1261
+ }
1262
+ return {
1263
+ socketPath: state.bridge.socketPath,
1264
+ token: state.bridge.token,
1265
+ pid: state.bridge.pid,
1266
+ appVersion: "",
1267
+ protocolVersion: 1,
1268
+ };
1269
+ }
1110
1270
  async function cmdSessionStart(ctx, opts) {
1271
+ if (opts.source === "mac-screen") {
1272
+ const file = sessionFilePath(process.cwd());
1273
+ const existing = readSessionState(file);
1274
+ if (existing && existing.kind !== "mac" && sessionIsActive(existing)) {
1275
+ die("a web recording session is already active here — finish or abort it first");
1276
+ }
1277
+ const info = readBridgeInfo();
1278
+ const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
1279
+ const target = await resolveBridgeTarget(info, opts);
1280
+ await bridgeRequest(info, "start", {
1281
+ maxSec,
1282
+ title: opts.name,
1283
+ description: opts.description,
1284
+ ...(target ? { source: target.source } : {}),
1285
+ });
1286
+ writeSessionState(file, macSessionState(info, maxSec));
1287
+ if (opts.json) {
1288
+ printJson({ state: "recording", source: "mac-screen", maxSec, target: target?.label });
1289
+ return;
1290
+ }
1291
+ process.stdout.write(`${c.green("✓")} the Clipy app is recording ${target ? target.label : "your screen"} (max ${maxSec}s)\n`);
1292
+ process.stdout.write(`${c.dim("while it runs:")} clipy mark "what just happened"\n` +
1293
+ `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
1294
+ return;
1295
+ }
1111
1296
  let target;
1112
1297
  try {
1113
1298
  target = new URL(opts.url);
@@ -1196,8 +1381,23 @@ function requireSession() {
1196
1381
  }
1197
1382
  return { file, state };
1198
1383
  }
1199
- function cmdMark(text, json) {
1384
+ async function cmdMark(text, json) {
1200
1385
  const { file, state } = requireSession();
1386
+ if (state.kind === "mac") {
1387
+ const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text }).catch((e) => {
1388
+ if (e instanceof BridgeUnavailableError) {
1389
+ cleanupSessionFiles(state, file);
1390
+ die("the Clipy app is no longer running — session cleared. Start a new one.");
1391
+ }
1392
+ die(e.message);
1393
+ });
1394
+ if (json) {
1395
+ printJson(result);
1396
+ return;
1397
+ }
1398
+ process.stdout.write(`${c.green("✓")} mark @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${text.trim()}\n`);
1399
+ return;
1400
+ }
1201
1401
  if (!pidAlive(state.pid)) {
1202
1402
  cleanupSessionFiles(state, file);
1203
1403
  die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
@@ -1216,6 +1416,23 @@ function cmdMark(text, json) {
1216
1416
  }
1217
1417
  async function cmdSessionStop(json) {
1218
1418
  const { file, state } = requireSession();
1419
+ if (state.kind === "mac") {
1420
+ if (!json)
1421
+ process.stderr.write(`${c.dim("stopping + uploading…")}\n`);
1422
+ const result = await bridgeRequest(bridgeInfoFromSession(state), "stop").catch((e) => {
1423
+ cleanupSessionFiles(state, file);
1424
+ die(e.message);
1425
+ });
1426
+ cleanupSessionFiles(state, file);
1427
+ const publicId = String(result.publicId ?? "");
1428
+ reportSessionResult({
1429
+ publicId,
1430
+ shareUrl: String(result.shareUrl ?? ""),
1431
+ contextUrl: `https://clipy.online/api/agent-context/${publicId}`,
1432
+ sizeBytes: 0,
1433
+ }, json);
1434
+ return;
1435
+ }
1219
1436
  if (!pidAlive(state.pid)) {
1220
1437
  // Daemon already gone: it may have finished (auto-stop at max duration)
1221
1438
  // or crashed. Report whatever terminal state it left behind.
@@ -1276,6 +1493,15 @@ function reportSessionResult(result, json) {
1276
1493
  }
1277
1494
  async function cmdSessionAbort(json) {
1278
1495
  const { file, state } = requireSession();
1496
+ if (state.kind === "mac") {
1497
+ await bridgeRequest(bridgeInfoFromSession(state), "abort").catch(() => { });
1498
+ cleanupSessionFiles(state, file);
1499
+ if (json)
1500
+ printJson({ state: "aborted" });
1501
+ else
1502
+ process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
1503
+ return;
1504
+ }
1279
1505
  if (!pidAlive(state.pid)) {
1280
1506
  cleanupSessionFiles(state, file);
1281
1507
  if (!json)
@@ -1302,7 +1528,7 @@ async function cmdSessionAbort(json) {
1302
1528
  else
1303
1529
  process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
1304
1530
  }
1305
- function cmdSessionStatus(json) {
1531
+ async function cmdSessionStatus(json) {
1306
1532
  const file = sessionFilePath(process.cwd());
1307
1533
  const state = readSessionState(file);
1308
1534
  if (!state) {
@@ -1312,6 +1538,41 @@ function cmdSessionStatus(json) {
1312
1538
  process.stdout.write(`${c.dim("no session in this workspace")}\n`);
1313
1539
  return;
1314
1540
  }
1541
+ if (state.kind === "mac" && state.state === "recording") {
1542
+ // The stored pid is the desktop APP's, which outlives the recording — ask
1543
+ // the bridge for the truth instead of inferring from process liveness.
1544
+ try {
1545
+ const status = await bridgeRequest(bridgeInfoFromSession(state), "status");
1546
+ const session = status.agentSession;
1547
+ if (!session) {
1548
+ if (json)
1549
+ printJson({ state: "ended", url: state.url });
1550
+ else
1551
+ process.stdout.write(`${c.bold("ended")} — the app finished this recording (auto-stop or Stop in the app).\n` +
1552
+ `${c.dim("clear the session file with:")} clipy session abort\n`);
1553
+ return;
1554
+ }
1555
+ if (json) {
1556
+ printJson({
1557
+ state: "recording",
1558
+ url: state.url,
1559
+ elapsedSec: session.elapsedSec ?? null,
1560
+ maxSec: session.maxSec ?? state.maxSec,
1561
+ marks: session.marks ?? null,
1562
+ });
1563
+ return;
1564
+ }
1565
+ process.stdout.write(`${c.bold("recording")} — ${state.url} — ${session.elapsedSec ?? "?"}s elapsed (max ${session.maxSec ?? state.maxSec}s, ${session.marks ?? 0} marks)\n`);
1566
+ return;
1567
+ }
1568
+ catch {
1569
+ if (json)
1570
+ printJson({ state: "dead", url: state.url });
1571
+ else
1572
+ process.stdout.write(`${c.bold("dead")} — the Clipy app is not answering. ${c.dim("clear with:")} clipy session abort\n`);
1573
+ return;
1574
+ }
1575
+ }
1315
1576
  const alive = pidAlive(state.pid);
1316
1577
  const elapsed = state.recordStartEpochMs && state.state === "recording"
1317
1578
  ? Math.round((Date.now() - state.recordStartEpochMs) / 1000)
@@ -1517,7 +1778,7 @@ function skillPathFor(target) {
1517
1778
  return join(home, ".cursor", "skills", "clipy", "SKILL.md");
1518
1779
  }
1519
1780
  }
1520
- function cmdAgents(sub, targetRaw, json) {
1781
+ async function cmdAgents(ctx, sub, targetRaw, json) {
1521
1782
  if (sub === "status" || sub === undefined) {
1522
1783
  const status = AGENT_TARGETS.map((t) => {
1523
1784
  const p = skillPathFor(t);
@@ -1546,6 +1807,16 @@ function cmdAgents(sub, targetRaw, json) {
1546
1807
  }
1547
1808
  const path = skillPathFor(target);
1548
1809
  if (sub === "install") {
1810
+ // First-run onboarding: with no API key configured, sign in first so the
1811
+ // installed skill can actually read + make recordings. Interactive
1812
+ // terminals only — without a TTY (CI) set CLIPY_API_KEY instead. SSH and
1813
+ // display-less Linux auto-route to the copy-code flow. An already-
1814
+ // configured key is left untouched. loginWithBrowser die()s (with the
1815
+ // paste fallback) if it fails.
1816
+ if (!ctx.apiKey && process.stdout.isTTY && !json) {
1817
+ process.stdout.write(`${c.dim("No Clipy API key found — signing you in first…")}\n`);
1818
+ await loginWithBrowser(ctx, shouldUseManualLogin());
1819
+ }
1549
1820
  mkdirSync(dirname(path), { recursive: true });
1550
1821
  writeFileSync(path, CLIPY_SKILL_MD);
1551
1822
  if (json) {
@@ -1614,7 +1885,7 @@ function cmdGuide(json) {
1614
1885
  { code: 3, meaning: "artifact not ready yet (transcript/summary/wait)" },
1615
1886
  ],
1616
1887
  commands: [
1617
- cmdDoc("login", "clipy login [--key <key>]", "Verify + store an API key"),
1888
+ cmdDoc("login", "clipy login [--no-browser] [--key <key>] [--paste]", "Approve this device in the browser (default). --no-browser (auto-detected on SSH and display-less Linux) prints the approval URL to open on any device and prompts for the code it shows. --key/--paste store a pasted key (also the automatic path when stdout is not a TTY)", ["--no-browser", "--key <key>", "--paste"]),
1618
1889
  cmdDoc("logout", "clipy logout", "Delete the stored key"),
1619
1890
  cmdDoc("whoami", "clipy whoami", "Check the active key"),
1620
1891
  cmdDoc("list", "clipy list [-n N] [--page P] [--status s,…] [--json]", "List recordings, newest first"),
@@ -1627,15 +1898,17 @@ function cmdGuide(json) {
1627
1898
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
1628
1899
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
1629
1900
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
1630
- cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--note '12: text']… [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript", ["--for", "--viewports", "--title", "--description", "--note", "--width", "--height", "--wait"]),
1631
- cmdDoc("session", "clipy session <start|stop|abort|status> [--url <url>] [--max sec]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s)"),
1901
+ cmdDoc("record", "clipy record --url <url> [--for sec] [--viewports list] [--title t] [--note '12: text']… [--wait] [--json]", "Headless one-shot capture of a web app; notes become the transcript. With --source mac-screen: records the real screen via the Clipy Mac app; --window '<title|app|id>' or --display <id> target one window/display (ids from clipy sources)", ["--for", "--viewports", "--title", "--description", "--note", "--width", "--height", "--wait", "--source", "--window", "--display"]),
1902
+ cmdDoc("session", "clipy session <start|stop|abort|status> [--url <url>] [--max sec] [--source web|mac-screen] [--window w] [--display d]", "Background recording session; auto-stops + uploads at --max (default 600s, cap 1800s). --window/--display (with --source mac-screen) record one window/display"),
1632
1903
  cmdDoc("mark", "clipy mark \"<text>\"", "Drop a live-timestamped note into the active session"),
1633
- cmdDoc("agents", "clipy agents <status|install|uninstall> <claude|codex|cursor>", "Install the bundled Clipy skill for a coding agent"),
1904
+ cmdDoc("sources", "clipy sources [--json]", "List displays + windows the Clipy Mac app can capture — ids feed --window/--display"),
1905
+ cmdDoc("agents", "clipy agents <status|install|uninstall> <claude|codex|cursor>", "Install the bundled Clipy skill for a coding agent; install triggers a browser login first when no key is configured (interactive terminals only)"),
1634
1906
  cmdDoc("guide", "clipy guide --json", "This manifest"),
1635
1907
  cmdDoc("mcp", "clipy mcp", "Run the Clipy MCP server (wraps npx -y @clipy/mcp)"),
1636
1908
  ],
1637
1909
  notes: [
1638
1910
  "Read commands accept a bare public id or the full https://clipy.online/video/<id> URL.",
1911
+ "login opens a browser to approve this device (loopback redirect to 127.0.0.1); use --key/--paste or a piped key on headless boxes.",
1639
1912
  "record/session/mark/transcript --replace are the only write commands; they need a key with the 'ingest' permission.",
1640
1913
  "Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
1641
1914
  "Public recordings have an unauthenticated context document at https://clipy.online/video/<id>.md.",
@@ -1697,6 +1970,8 @@ async function main() {
1697
1970
  options: {
1698
1971
  json: { type: "boolean", default: false },
1699
1972
  key: { type: "string" },
1973
+ paste: { type: "boolean", default: false },
1974
+ "no-browser": { type: "boolean", default: false },
1700
1975
  "api-url": { type: "string" },
1701
1976
  status: { type: "string" },
1702
1977
  page: { type: "string" },
@@ -1715,6 +1990,9 @@ async function main() {
1715
1990
  viewports: { type: "string" },
1716
1991
  max: { type: "string" },
1717
1992
  replace: { type: "string" },
1993
+ source: { type: "string" },
1994
+ window: { type: "string" },
1995
+ display: { type: "string" },
1718
1996
  width: { type: "string" },
1719
1997
  height: { type: "string" },
1720
1998
  wait: { type: "boolean", default: false },
@@ -1748,7 +2026,11 @@ async function main() {
1748
2026
  };
1749
2027
  switch (command) {
1750
2028
  case "login":
1751
- await cmdLogin(ctx, values.key);
2029
+ await cmdLogin(ctx, {
2030
+ key: values.key,
2031
+ paste: Boolean(values.paste),
2032
+ noBrowser: Boolean(values["no-browser"]),
2033
+ });
1752
2034
  return;
1753
2035
  case "logout":
1754
2036
  cmdLogout();
@@ -1827,15 +2109,83 @@ async function main() {
1827
2109
  cmdMcp();
1828
2110
  return;
1829
2111
  case "agents":
1830
- cmdAgents(rest[0], rest[1], json);
2112
+ await cmdAgents(ctx, rest[0], rest[1], json);
1831
2113
  return;
1832
2114
  case "guide":
1833
2115
  cmdGuide(json);
1834
2116
  return;
2117
+ case "sources": {
2118
+ // Enumerate what the Mac app can capture, so --window/--display have ids.
2119
+ try {
2120
+ const sources = await listSources(readBridgeInfo());
2121
+ if (json) {
2122
+ printJson(sources);
2123
+ return;
2124
+ }
2125
+ process.stdout.write(`${c.bold("DISPLAYS")}\n`);
2126
+ for (const d of sources.displays) {
2127
+ process.stdout.write(` ${d.id}\t${d.name || "display"}\t${c.dim(`${d.width}×${d.height}`)}\n`);
2128
+ }
2129
+ process.stdout.write(`${c.bold("WINDOWS")}\n`);
2130
+ for (const w of sources.windows) {
2131
+ process.stdout.write(` ${w.id}\t${windowLabel(w)}\t${c.dim(`${w.width}×${w.height}`)}\n`);
2132
+ }
2133
+ process.stdout.write(`${c.dim('record one with: clipy record --source mac-screen --window "<title or id>"')}\n`);
2134
+ }
2135
+ catch (e) {
2136
+ die(e.message);
2137
+ }
2138
+ return;
2139
+ }
1835
2140
  case "record": {
2141
+ const source = String(values.source ?? "web");
2142
+ if (source !== "web" && source !== "mac-screen") {
2143
+ die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
2144
+ }
2145
+ if ((values.window || values.display) && source !== "mac-screen") {
2146
+ die("--window/--display record the real screen — add --source mac-screen", 2);
2147
+ }
2148
+ if (values.window && values.display) {
2149
+ die("--window and --display are mutually exclusive — pick one capture source", 2);
2150
+ }
2151
+ if (source === "mac-screen") {
2152
+ const noteFlags = values.note ?? [];
2153
+ const forSec = num(values.for, 15);
2154
+ // The app-side safety watchdog caps a bridge recording at 1800s; a
2155
+ // longer --for would auto-stop at the cap while we kept waiting.
2156
+ if (forSec > 1740) {
2157
+ die("--for is capped at 1740s for --source mac-screen (the app auto-stops at 1800s)", 2);
2158
+ }
2159
+ try {
2160
+ const result = await cmdRecordMac({
2161
+ forSec,
2162
+ name: (values.title ?? values.name)?.trim() ||
2163
+ undefined,
2164
+ description: values.description?.trim() || undefined,
2165
+ window: values.window?.trim() || undefined,
2166
+ display: values.display?.trim() || undefined,
2167
+ notes: noteFlags.map(parseNoteFlag),
2168
+ json,
2169
+ });
2170
+ if (values.wait && result.publicId) {
2171
+ await waitForArtifacts(ctx, result.publicId).catch(() => { });
2172
+ }
2173
+ if (json) {
2174
+ printJson({ id: result.publicId, shareUrl: result.shareUrl });
2175
+ }
2176
+ else {
2177
+ process.stdout.write(`${c.green("✓")} recorded — ${c.bold(result.shareUrl)}\n`);
2178
+ process.stdout.write(`${c.dim("next:")} clipy context ${result.publicId} · clipy wait ${result.publicId}\n`);
2179
+ }
2180
+ }
2181
+ catch (e) {
2182
+ die(e.message);
2183
+ }
2184
+ return;
2185
+ }
1836
2186
  const url = values.url?.trim() || rest[0];
1837
2187
  if (!url) {
1838
- die("usage: clipy record --url <http(s) url> [--for <sec>] [--name <title>] [--viewports <list>] [--wait]", 2);
2188
+ die("usage: clipy record --url <http(s) url> [--for <sec>] [--name <title>] [--viewports <list>] [--source web|mac-screen] [--wait]", 2);
1839
2189
  }
1840
2190
  const noteFlags = values.note ?? [];
1841
2191
  await cmdRecord(ctx, {
@@ -1856,12 +2206,24 @@ async function main() {
1856
2206
  case "session": {
1857
2207
  const sub = rest[0];
1858
2208
  if (sub === "start") {
2209
+ const source = String(values.source ?? "web");
2210
+ if (source !== "web" && source !== "mac-screen") {
2211
+ die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
2212
+ }
2213
+ if ((values.window || values.display) && source !== "mac-screen") {
2214
+ die("--window/--display record the real screen — add --source mac-screen", 2);
2215
+ }
2216
+ if (values.window && values.display) {
2217
+ die("--window and --display are mutually exclusive — pick one capture source", 2);
2218
+ }
1859
2219
  const url = values.url?.trim() || rest[1];
1860
- if (!url) {
1861
- die("usage: clipy session start --url <http(s) url> [--max <sec>] [--name <title>]", 2);
2220
+ if (!url && source === "web") {
2221
+ die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen]", 2);
1862
2222
  }
1863
2223
  await cmdSessionStart(ctx, {
1864
- url,
2224
+ url: url || "mac-screen",
2225
+ window: values.window?.trim() || undefined,
2226
+ display: values.display?.trim() || undefined,
1865
2227
  name: (values.title ?? values.name)?.trim() ||
1866
2228
  undefined,
1867
2229
  description: values.description?.trim() || undefined,
@@ -1869,6 +2231,7 @@ async function main() {
1869
2231
  width: num(values.width, 1280),
1870
2232
  height: num(values.height, 720),
1871
2233
  json,
2234
+ source,
1872
2235
  });
1873
2236
  return;
1874
2237
  }
@@ -1881,7 +2244,7 @@ async function main() {
1881
2244
  return;
1882
2245
  }
1883
2246
  if (sub === "status" || sub === undefined) {
1884
- cmdSessionStatus(json);
2247
+ await cmdSessionStatus(json);
1885
2248
  return;
1886
2249
  }
1887
2250
  die("usage: clipy session <start|stop|abort|status>", 2);
@@ -1891,7 +2254,7 @@ async function main() {
1891
2254
  const text = rest.join(" ").trim();
1892
2255
  if (!text)
1893
2256
  die('usage: clipy mark "<what just happened>"', 2);
1894
- cmdMark(text, json);
2257
+ await cmdMark(text, json);
1895
2258
  return;
1896
2259
  }
1897
2260
  case "__session-daemon": {
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Mac bridge client — drives real screen recordings through the running
3
+ * Clipy desktop app over its Unix-socket agent bridge (agent_bridge.rs).
4
+ *
5
+ * Discovery: ~/Library/Application Support/Clipy/agent-bridge.json, written
6
+ * by the app on launch: {socketPath, token, pid, appVersion, protocolVersion}.
7
+ * The file and socket are 0600, and every request carries the per-launch
8
+ * token. Protocol: one JSON request line per connection, one JSON response
9
+ * line back.
10
+ */
11
+ import { readFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { createConnection } from "node:net";
15
+ export class BridgeUnavailableError extends Error {
16
+ }
17
+ const REQUEST_TIMEOUT_MS = 15_000;
18
+ /** stop waits for the streaming upload to hand back the share link. */
19
+ const STOP_TIMEOUT_MS = 200_000;
20
+ export function bridgeFilePath() {
21
+ if (process.env.CLIPY_BRIDGE_FILE?.trim())
22
+ return process.env.CLIPY_BRIDGE_FILE;
23
+ return join(homedir(), "Library", "Application Support", "Clipy", "agent-bridge.json");
24
+ }
25
+ function pidAlive(pid) {
26
+ try {
27
+ process.kill(pid, 0);
28
+ return true;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ /** Reads + validates the discovery file; throws BridgeUnavailableError with a
35
+ * friendly one-liner when the app isn't installed or running. */
36
+ export function readBridgeInfo() {
37
+ if (process.platform !== "darwin" && !process.env.CLIPY_BRIDGE_FILE) {
38
+ throw new BridgeUnavailableError("--source mac-screen records through the Clipy Mac app, which only runs on macOS.");
39
+ }
40
+ let raw;
41
+ try {
42
+ raw = readFileSync(bridgeFilePath(), "utf8");
43
+ }
44
+ catch {
45
+ throw new BridgeUnavailableError("the Clipy app is not running (no agent bridge found). Open Clipy, or install it from https://clipy.online/download");
46
+ }
47
+ let info;
48
+ try {
49
+ info = JSON.parse(raw);
50
+ }
51
+ catch {
52
+ throw new BridgeUnavailableError("agent bridge file is corrupt — restart the Clipy app");
53
+ }
54
+ if (!info.socketPath || !info.token || typeof info.pid !== "number") {
55
+ throw new BridgeUnavailableError("agent bridge file is incomplete — restart the Clipy app");
56
+ }
57
+ if (!pidAlive(info.pid)) {
58
+ throw new BridgeUnavailableError("the Clipy app is not running (stale agent bridge). Open Clipy and try again.");
59
+ }
60
+ return info;
61
+ }
62
+ /** Enumerate capturable displays + windows from the running app. */
63
+ export async function listSources(info) {
64
+ const data = await bridgeRequest(info, "sources");
65
+ const displays = Array.isArray(data.displays) ? data.displays : [];
66
+ const windows = Array.isArray(data.windows) ? data.windows : [];
67
+ return { displays, windows };
68
+ }
69
+ export function windowLabel(w) {
70
+ return w.title ? `${w.app_name} — ${w.title}` : w.app_name;
71
+ }
72
+ /**
73
+ * Resolves --window/--display flags to a CaptureSource. A numeric value is
74
+ * treated as an id from `clipy sources`; anything else is a case-insensitive
75
+ * substring match on "app_name title" (windows) or name (displays). Ambiguity
76
+ * throws with the candidate list — ids are unstable across app launches, so
77
+ * silent guessing would record the wrong thing.
78
+ */
79
+ export async function resolveCaptureSource(info, opts) {
80
+ if (opts.window && opts.display) {
81
+ throw new Error("--window and --display are mutually exclusive — pick one capture source");
82
+ }
83
+ const sources = await listSources(info);
84
+ if (opts.window) {
85
+ const q = opts.window.trim();
86
+ let matches;
87
+ if (/^\d+$/.test(q)) {
88
+ matches = sources.windows.filter((w) => w.id === Number(q));
89
+ }
90
+ else {
91
+ const needle = q.toLowerCase();
92
+ matches = sources.windows.filter((w) => `${w.app_name} ${w.title}`.toLowerCase().includes(needle));
93
+ // Several windows of several apps can match a loose substring; an exact
94
+ // app-name match ("Chrome") is almost always what the caller meant.
95
+ if (matches.length > 1) {
96
+ const exactApp = matches.filter((w) => w.app_name.toLowerCase() === needle);
97
+ if (exactApp.length >= 1)
98
+ matches = exactApp;
99
+ }
100
+ }
101
+ if (matches.length === 0) {
102
+ const available = sources.windows.map((w) => ` ${w.id} ${windowLabel(w)}`).join("\n");
103
+ throw new Error(`no window matches "${q}". Available windows (clipy sources):\n${available || " (none)"}`);
104
+ }
105
+ if (matches.length > 1) {
106
+ const list = matches.map((w) => ` ${w.id} ${windowLabel(w)}`).join("\n");
107
+ throw new Error(`"${q}" matches ${matches.length} windows — use the id instead:\n${list}`);
108
+ }
109
+ return { source: { type: "window", id: matches[0].id }, label: windowLabel(matches[0]) };
110
+ }
111
+ if (opts.display) {
112
+ const q = opts.display.trim();
113
+ const matches = /^\d+$/.test(q)
114
+ ? sources.displays.filter((d) => d.id === Number(q))
115
+ : sources.displays.filter((d) => d.name.toLowerCase().includes(q.toLowerCase()));
116
+ if (matches.length === 0) {
117
+ const available = sources.displays.map((d) => ` ${d.id} ${d.name}`).join("\n");
118
+ throw new Error(`no display matches "${q}". Available displays:\n${available || " (none)"}`);
119
+ }
120
+ if (matches.length > 1) {
121
+ const list = matches.map((d) => ` ${d.id} ${d.name}`).join("\n");
122
+ throw new Error(`"${q}" matches ${matches.length} displays — use the id instead:\n${list}`);
123
+ }
124
+ return {
125
+ source: { type: "display", id: matches[0].id },
126
+ label: matches[0].name || `display ${matches[0].id}`,
127
+ };
128
+ }
129
+ throw new Error("resolveCaptureSource called without --window or --display");
130
+ }
131
+ /** One request line in, one response line out. */
132
+ export function bridgeRequest(info, cmd, args = {}) {
133
+ const timeoutMs = cmd === "stop" ? STOP_TIMEOUT_MS : REQUEST_TIMEOUT_MS;
134
+ return new Promise((resolvePromise, reject) => {
135
+ const socket = createConnection({ path: info.socketPath });
136
+ let buffer = "";
137
+ let settled = false;
138
+ const timer = setTimeout(() => {
139
+ if (!settled) {
140
+ settled = true;
141
+ socket.destroy();
142
+ reject(new Error(cmd === "stop"
143
+ ? "the Clipy app did not finish the upload in time — check the app; the recording may still complete in the background"
144
+ : `the Clipy app did not answer (${cmd}) — is it responding?`));
145
+ }
146
+ }, timeoutMs);
147
+ socket.on("error", (e) => {
148
+ if (settled)
149
+ return;
150
+ settled = true;
151
+ clearTimeout(timer);
152
+ reject(e.code === "ENOENT" || e.code === "ECONNREFUSED"
153
+ ? new BridgeUnavailableError("the Clipy app is not running (agent bridge socket unavailable). Open Clipy and try again.")
154
+ : e);
155
+ });
156
+ socket.on("connect", () => {
157
+ socket.write(`${JSON.stringify({ token: info.token, cmd, ...args })}\n`);
158
+ });
159
+ socket.on("data", (chunk) => {
160
+ buffer += chunk.toString("utf8");
161
+ const newline = buffer.indexOf("\n");
162
+ if (newline === -1)
163
+ return;
164
+ if (settled)
165
+ return;
166
+ settled = true;
167
+ clearTimeout(timer);
168
+ socket.end();
169
+ try {
170
+ const parsed = JSON.parse(buffer.slice(0, newline));
171
+ if (parsed.ok) {
172
+ resolvePromise(parsed.data ?? {});
173
+ }
174
+ else {
175
+ reject(new Error(parsed.error?.message ?? "bridge error"));
176
+ }
177
+ }
178
+ catch {
179
+ reject(new Error("unparseable response from the Clipy app bridge"));
180
+ }
181
+ });
182
+ socket.on("close", () => {
183
+ if (!settled) {
184
+ settled = true;
185
+ clearTimeout(timer);
186
+ reject(new Error("the Clipy app closed the bridge connection unexpectedly"));
187
+ }
188
+ });
189
+ });
190
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipy/cli",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Command-line interface for Clipy — list, search, and read your screen recordings' transcripts, AI summaries, and key moments from the terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -37,7 +37,8 @@
37
37
  "scripts": {
38
38
  "build": "tsc",
39
39
  "prepublishOnly": "npm run build",
40
- "start": "node dist/index.js"
40
+ "start": "node dist/index.js",
41
+ "test:auth": "npm run build && node scripts/mock-auth-server.test.mjs"
41
42
  },
42
43
  "devDependencies": {
43
44
  "@types/node": "^22.0.0",