@clipy/cli 0.3.1 → 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,7 +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";
25
- import { BridgeUnavailableError, bridgeRequest, readBridgeInfo, } from "./macBridge.js";
26
+ import { browserLogin, shouldUseManualLogin } from "./browserLogin.js";
27
+ import { BridgeUnavailableError, bridgeRequest, listSources, readBridgeInfo, resolveCaptureSource, windowLabel, } from "./macBridge.js";
26
28
  // Exit quietly when stdout/stderr close early (e.g. `clipy list | head`).
27
29
  for (const stream of [process.stdout, process.stderr]) {
28
30
  stream.on("error", (e) => {
@@ -130,7 +132,7 @@ const FETCH_TIMEOUT_MS = 20_000;
130
132
  function requireKey(ctx) {
131
133
  if (ctx.apiKey)
132
134
  return ctx.apiKey;
133
- 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.`);
134
136
  }
135
137
  async function api(ctx, path, accept = "application/json") {
136
138
  const key = requireKey(ctx);
@@ -261,7 +263,10 @@ ${c.bold("USAGE")}
261
263
  clipy <command> [arguments] [flags]
262
264
 
263
265
  ${c.bold("AUTH")}
264
- 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
265
270
  logout Delete the stored key
266
271
  whoami Check which key is active and that it works
267
272
 
@@ -298,6 +303,10 @@ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")
298
303
  ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
299
304
  ${c.dim("--source mac-screen on record/session records the REAL screen via the")}
300
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
301
310
  session start --url <app> [--max <sec>] [--title <t>]
302
311
  Start recording in a background daemon and
303
312
  return immediately (auto-stops + uploads at
@@ -330,30 +339,103 @@ ${c.bold("EXIT CODES")}
330
339
  0 ok · 1 error · 2 usage · 3 artifact not ready (transcript/summary/wait)
331
340
 
332
341
  ${c.bold("SETUP")}
333
- 1. Create a key at ${c.cyan("https://clipy.online/settings/api-keys")}
334
- 2. ${c.bold("clipy login")}
335
- 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)
336
344
 
337
- Every command except ${c.bold("record")} and ${c.bold("session")}/${c.bold("mark")} is read-only. Only those
338
- 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.
339
347
  `;
340
- async function cmdLogin(ctx, keyFlag) {
341
- 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;
342
388
  if (!key) {
343
389
  key = await promptHidden(`Paste your Clipy API key (from ${ctx.apiUrl}/settings/api-keys): `);
344
390
  }
345
391
  if (!key.startsWith("clipy_sk_live_")) {
346
392
  die("that doesn't look like a Clipy API key (expected it to start with clipy_sk_live_)");
347
393
  }
348
- // Verify before storing.
349
- const probe = { ...ctx, apiKey: key };
350
- await apiJson(probe, "/api/v1/recordings?limit=1");
351
- const cfg = readConfig();
352
- cfg.apiKey = key;
353
- if (ctx.apiUrl !== "https://clipy.online")
354
- cfg.apiUrl = ctx.apiUrl;
355
- writeConfig(cfg);
356
- 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
+ });
357
439
  }
358
440
  function promptHidden(question) {
359
441
  return new Promise((resolvePrompt) => {
@@ -914,7 +996,9 @@ async function uploadWebmToClipy(ctx, opts) {
914
996
  return {
915
997
  publicId,
916
998
  shareUrl: `${ctx.apiUrl}/video/${publicId}`,
917
- 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`,
918
1002
  sizeBytes,
919
1003
  };
920
1004
  }
@@ -1111,6 +1195,19 @@ function cleanupSessionFiles(state, file) {
1111
1195
  }
1112
1196
  }
1113
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
+ }
1114
1211
  /** One-shot real-screen recording through the running Clipy app. */
1115
1212
  async function cmdRecordMac(opts) {
1116
1213
  const info = readBridgeInfo();
@@ -1118,7 +1215,8 @@ async function cmdRecordMac(opts) {
1118
1215
  if (!opts.json)
1119
1216
  process.stderr.write(`${m}\n`);
1120
1217
  };
1121
- log(`${c.dim(`asking the Clipy app (v${info.appVersion}) to record the screen…`)}`);
1218
+ const target = await resolveBridgeTarget(info, opts);
1219
+ log(`${c.dim(`asking the Clipy app (v${info.appVersion}) to record ${target?.label ?? "the screen"}…`)}`);
1122
1220
  await bridgeRequest(info, "start", {
1123
1221
  // The recording is stopped by us after forSec; maxSec is the safety net
1124
1222
  // in case this CLI process dies mid-wait.
@@ -1126,6 +1224,7 @@ async function cmdRecordMac(opts) {
1126
1224
  title: opts.name,
1127
1225
  description: opts.description,
1128
1226
  notes: opts.notes.map((n) => ({ startMs: n.startMs, text: n.text })),
1227
+ ...(target ? { source: target.source } : {}),
1129
1228
  });
1130
1229
  log(`${c.dim(`recording for ${opts.forSec}s…`)}`);
1131
1230
  await new Promise((r) => setTimeout(r, opts.forSec * 1000));
@@ -1177,17 +1276,19 @@ async function cmdSessionStart(ctx, opts) {
1177
1276
  }
1178
1277
  const info = readBridgeInfo();
1179
1278
  const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
1279
+ const target = await resolveBridgeTarget(info, opts);
1180
1280
  await bridgeRequest(info, "start", {
1181
1281
  maxSec,
1182
1282
  title: opts.name,
1183
1283
  description: opts.description,
1284
+ ...(target ? { source: target.source } : {}),
1184
1285
  });
1185
1286
  writeSessionState(file, macSessionState(info, maxSec));
1186
1287
  if (opts.json) {
1187
- printJson({ state: "recording", source: "mac-screen", maxSec });
1288
+ printJson({ state: "recording", source: "mac-screen", maxSec, target: target?.label });
1188
1289
  return;
1189
1290
  }
1190
- process.stdout.write(`${c.green("✓")} the Clipy app is recording your screen (max ${maxSec}s)\n`);
1291
+ process.stdout.write(`${c.green("✓")} the Clipy app is recording ${target ? target.label : "your screen"} (max ${maxSec}s)\n`);
1191
1292
  process.stdout.write(`${c.dim("while it runs:")} clipy mark "what just happened"\n` +
1192
1293
  `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
1193
1294
  return;
@@ -1427,7 +1528,7 @@ async function cmdSessionAbort(json) {
1427
1528
  else
1428
1529
  process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
1429
1530
  }
1430
- function cmdSessionStatus(json) {
1531
+ async function cmdSessionStatus(json) {
1431
1532
  const file = sessionFilePath(process.cwd());
1432
1533
  const state = readSessionState(file);
1433
1534
  if (!state) {
@@ -1437,6 +1538,41 @@ function cmdSessionStatus(json) {
1437
1538
  process.stdout.write(`${c.dim("no session in this workspace")}\n`);
1438
1539
  return;
1439
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
+ }
1440
1576
  const alive = pidAlive(state.pid);
1441
1577
  const elapsed = state.recordStartEpochMs && state.state === "recording"
1442
1578
  ? Math.round((Date.now() - state.recordStartEpochMs) / 1000)
@@ -1642,7 +1778,7 @@ function skillPathFor(target) {
1642
1778
  return join(home, ".cursor", "skills", "clipy", "SKILL.md");
1643
1779
  }
1644
1780
  }
1645
- function cmdAgents(sub, targetRaw, json) {
1781
+ async function cmdAgents(ctx, sub, targetRaw, json) {
1646
1782
  if (sub === "status" || sub === undefined) {
1647
1783
  const status = AGENT_TARGETS.map((t) => {
1648
1784
  const p = skillPathFor(t);
@@ -1671,6 +1807,16 @@ function cmdAgents(sub, targetRaw, json) {
1671
1807
  }
1672
1808
  const path = skillPathFor(target);
1673
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
+ }
1674
1820
  mkdirSync(dirname(path), { recursive: true });
1675
1821
  writeFileSync(path, CLIPY_SKILL_MD);
1676
1822
  if (json) {
@@ -1739,7 +1885,7 @@ function cmdGuide(json) {
1739
1885
  { code: 3, meaning: "artifact not ready yet (transcript/summary/wait)" },
1740
1886
  ],
1741
1887
  commands: [
1742
- 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"]),
1743
1889
  cmdDoc("logout", "clipy logout", "Delete the stored key"),
1744
1890
  cmdDoc("whoami", "clipy whoami", "Check the active key"),
1745
1891
  cmdDoc("list", "clipy list [-n N] [--page P] [--status s,…] [--json]", "List recordings, newest first"),
@@ -1752,15 +1898,17 @@ function cmdGuide(json) {
1752
1898
  cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
1753
1899
  cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
1754
1900
  cmdDoc("wait", "clipy wait <id> [--for transcript|summary|both] [--timeout sec]", "Block until artifacts are ready"),
1755
- 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"]),
1756
- 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"),
1757
1903
  cmdDoc("mark", "clipy mark \"<text>\"", "Drop a live-timestamped note into the active session"),
1758
- 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)"),
1759
1906
  cmdDoc("guide", "clipy guide --json", "This manifest"),
1760
1907
  cmdDoc("mcp", "clipy mcp", "Run the Clipy MCP server (wraps npx -y @clipy/mcp)"),
1761
1908
  ],
1762
1909
  notes: [
1763
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.",
1764
1912
  "record/session/mark/transcript --replace are the only write commands; they need a key with the 'ingest' permission.",
1765
1913
  "Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
1766
1914
  "Public recordings have an unauthenticated context document at https://clipy.online/video/<id>.md.",
@@ -1822,6 +1970,8 @@ async function main() {
1822
1970
  options: {
1823
1971
  json: { type: "boolean", default: false },
1824
1972
  key: { type: "string" },
1973
+ paste: { type: "boolean", default: false },
1974
+ "no-browser": { type: "boolean", default: false },
1825
1975
  "api-url": { type: "string" },
1826
1976
  status: { type: "string" },
1827
1977
  page: { type: "string" },
@@ -1841,6 +1991,8 @@ async function main() {
1841
1991
  max: { type: "string" },
1842
1992
  replace: { type: "string" },
1843
1993
  source: { type: "string" },
1994
+ window: { type: "string" },
1995
+ display: { type: "string" },
1844
1996
  width: { type: "string" },
1845
1997
  height: { type: "string" },
1846
1998
  wait: { type: "boolean", default: false },
@@ -1874,7 +2026,11 @@ async function main() {
1874
2026
  };
1875
2027
  switch (command) {
1876
2028
  case "login":
1877
- 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
+ });
1878
2034
  return;
1879
2035
  case "logout":
1880
2036
  cmdLogout();
@@ -1953,24 +2109,61 @@ async function main() {
1953
2109
  cmdMcp();
1954
2110
  return;
1955
2111
  case "agents":
1956
- cmdAgents(rest[0], rest[1], json);
2112
+ await cmdAgents(ctx, rest[0], rest[1], json);
1957
2113
  return;
1958
2114
  case "guide":
1959
2115
  cmdGuide(json);
1960
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
+ }
1961
2140
  case "record": {
1962
2141
  const source = String(values.source ?? "web");
1963
2142
  if (source !== "web" && source !== "mac-screen") {
1964
2143
  die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
1965
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
+ }
1966
2151
  if (source === "mac-screen") {
1967
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
+ }
1968
2159
  try {
1969
2160
  const result = await cmdRecordMac({
1970
- forSec: num(values.for, 15),
2161
+ forSec,
1971
2162
  name: (values.title ?? values.name)?.trim() ||
1972
2163
  undefined,
1973
2164
  description: values.description?.trim() || undefined,
2165
+ window: values.window?.trim() || undefined,
2166
+ display: values.display?.trim() || undefined,
1974
2167
  notes: noteFlags.map(parseNoteFlag),
1975
2168
  json,
1976
2169
  });
@@ -2017,12 +2210,20 @@ async function main() {
2017
2210
  if (source !== "web" && source !== "mac-screen") {
2018
2211
  die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
2019
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
+ }
2020
2219
  const url = values.url?.trim() || rest[1];
2021
2220
  if (!url && source === "web") {
2022
2221
  die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen]", 2);
2023
2222
  }
2024
2223
  await cmdSessionStart(ctx, {
2025
2224
  url: url || "mac-screen",
2225
+ window: values.window?.trim() || undefined,
2226
+ display: values.display?.trim() || undefined,
2026
2227
  name: (values.title ?? values.name)?.trim() ||
2027
2228
  undefined,
2028
2229
  description: values.description?.trim() || undefined,
@@ -2043,7 +2244,7 @@ async function main() {
2043
2244
  return;
2044
2245
  }
2045
2246
  if (sub === "status" || sub === undefined) {
2046
- cmdSessionStatus(json);
2247
+ await cmdSessionStatus(json);
2047
2248
  return;
2048
2249
  }
2049
2250
  die("usage: clipy session <start|stop|abort|status>", 2);
package/dist/macBridge.js CHANGED
@@ -59,6 +59,75 @@ export function readBridgeInfo() {
59
59
  }
60
60
  return info;
61
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
+ }
62
131
  /** One request line in, one response line out. */
63
132
  export function bridgeRequest(info, cmd, args = {}) {
64
133
  const timeoutMs = cmd === "stop" ? STOP_TIMEOUT_MS : REQUEST_TIMEOUT_MS;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clipy/cli",
3
- "version": "0.3.1",
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",