@clipy/cli 0.1.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.
Files changed (3) hide show
  1. package/README.md +100 -0
  2. package/dist/index.js +737 -0
  3. package/package.json +46 -0
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # @clipy/cli
2
+
3
+ The [Clipy](https://clipy.online) command line. List, search, and read your screen
4
+ recordings — transcripts, AI summaries, key moments — from the terminal, download the
5
+ MP4s, or export subtitles. No browser needed.
6
+
7
+ [Clipy](https://clipy.online) is a free screen recorder ([Chrome extension and Mac app](https://clipy.online/download),
8
+ plus a [web recorder](https://clipy.online/screen-recorder)) that gives every
9
+ recording an instant share link, an AI transcript and summary, and
10
+ [agent-readable context](https://clipy.online/for-agents) — so both humans and AI
11
+ agents can act on what was recorded. This package is its terminal client.
12
+
13
+ It is **read-only**: it can never create, edit, or delete your recordings.
14
+
15
+ ```bash
16
+ npx @clipy/cli list # or: npm i -g @clipy/cli && clipy list
17
+ ```
18
+
19
+ ## Setup
20
+
21
+ 1. Create a free API key at **https://clipy.online/settings/api-keys** (it looks like
22
+ `clipy_sk_live_…`). Copy it — it's shown only once.
23
+ 2. Log in (stores the key in `~/.config/clipy/config.json`, mode 0600):
24
+
25
+ ```bash
26
+ clipy login
27
+ ```
28
+
29
+ Or skip the stored login entirely and set `CLIPY_API_KEY` in your environment.
30
+
31
+ ## Commands
32
+
33
+ ```text
34
+ clipy list [-n 20] [--page 2] [--status ready,processing] [--json]
35
+ clipy search <query> # full-text search titles + descriptions
36
+ clipy show <id|share-url> # metadata + share link
37
+ clipy transcript <id> [--srt|--vtt] # plaintext, or export subtitles
38
+ clipy summary <id> # TL;DR, key points, action items
39
+ clipy moments <id> # key moments: timestamps, captions, click coords
40
+ clipy context <id> # the full agent-context bundle as markdown
41
+ clipy download <id> [-o out.mp4] # download the MP4
42
+ clipy open <id> # open the share page in your browser
43
+ clipy wait <id> --for both # block until transcript/summary are ready
44
+ clipy mcp # run the Clipy MCP server (npx -y @clipy/mcp)
45
+ ```
46
+
47
+ Every recording-reading command accepts either the bare public id (`3kelcef8wo8h`) or the
48
+ full share URL (`https://clipy.online/video/3kelcef8wo8h`).
49
+
50
+ ## Scripting
51
+
52
+ `--json` prints the raw API response for `list`, `search`, `show`, `transcript`,
53
+ `summary`, `moments`, and `wait`:
54
+
55
+ ```bash
56
+ # Newest recording's id
57
+ clipy list -n 1 --json | jq -r '.recordings[0].id'
58
+
59
+ # Export subtitles for a recording
60
+ clipy transcript 3kelcef8wo8h --srt > recording.srt
61
+
62
+ # Record with anything, then block until Clipy finished transcribing
63
+ clipy wait 3kelcef8wo8h --for both && clipy summary 3kelcef8wo8h
64
+ ```
65
+
66
+ Exit codes: `0` ok · `1` error · `2` usage · `3` artifact not ready yet.
67
+
68
+ ## Configuration
69
+
70
+ | Setting | Flag | Env | Stored (via `clipy login`) |
71
+ | -------- | ----------- | --------------- | ------------------------------ |
72
+ | API key | `--key` | `CLIPY_API_KEY` | `~/.config/clipy/config.json` |
73
+ | API base | `--api-url` | `CLIPY_API_URL` | `~/.config/clipy/config.json` |
74
+
75
+ Precedence: flag → env → stored config.
76
+
77
+ ## For AI agents
78
+
79
+ If you're wiring Clipy into an MCP-capable agent (Claude Code, Cursor, Codex, …),
80
+ use the [`@clipy/mcp`](https://www.npmjs.com/package/@clipy/mcp) server instead — same
81
+ API, but with agent-native tools and inline key-moment frames
82
+ ([source](https://github.com/manovagyanik1/clipy-mcp) ·
83
+ [setup docs](https://clipy.online/docs/mcp)). `clipy mcp` is a shortcut that runs it.
84
+
85
+ Also: every **public** Clipy watch link is agent-readable without any install — append
86
+ `.md` to it (`https://clipy.online/video/<id>.md`) and it serves a markdown context
87
+ document with the summary, key moments, and transcript. Details at
88
+ [clipy.online/for-agents](https://clipy.online/for-agents).
89
+
90
+ ## Links
91
+
92
+ - Website: [clipy.online](https://clipy.online) · [free online screen recorder](https://clipy.online/screen-recorder)
93
+ - CLI docs: [clipy.online/docs/cli](https://clipy.online/docs/cli)
94
+ - MCP server: [`@clipy/mcp`](https://www.npmjs.com/package/@clipy/mcp) · [docs](https://clipy.online/docs/mcp) · [source](https://github.com/manovagyanik1/clipy-mcp)
95
+ - Free browser tools (converters, GIF makers, downloaders): [clipy.online/tools](https://clipy.online/tools)
96
+ - API keys: [clipy.online/settings/api-keys](https://clipy.online/settings/api-keys)
97
+
98
+ ## License
99
+
100
+ MIT © [Codersera](https://codersera.com)
package/dist/index.js ADDED
@@ -0,0 +1,737 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @clipy/cli — the Clipy command line.
4
+ *
5
+ * List, search, and read your Clipy screen recordings (transcripts, AI
6
+ * summaries, key moments) from the terminal, download the MP4s, or export
7
+ * subtitles — without opening a browser.
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.
13
+ */
14
+ import { parseArgs } from "node:util";
15
+ import { createWriteStream, mkdirSync, readFileSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { dirname, join, resolve } from "node:path";
18
+ import { createInterface } from "node:readline";
19
+ import { spawn } from "node:child_process";
20
+ import { Readable, Transform } from "node:stream";
21
+ import { pipeline } from "node:stream/promises";
22
+ import { createRequire } from "node:module";
23
+ // Exit quietly when stdout/stderr close early (e.g. `clipy list | head`).
24
+ for (const stream of [process.stdout, process.stderr]) {
25
+ stream.on("error", (e) => {
26
+ if (e.code === "EPIPE")
27
+ process.exit(0);
28
+ throw e;
29
+ });
30
+ }
31
+ const VERSION = (() => {
32
+ try {
33
+ return createRequire(import.meta.url)("../package.json").version;
34
+ }
35
+ catch {
36
+ return "0.0.0";
37
+ }
38
+ })();
39
+ // ---------------------------------------------------------------------------
40
+ // Terminal helpers
41
+ // ---------------------------------------------------------------------------
42
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
43
+ const c = {
44
+ bold: (s) => (useColor ? `\x1b[1m${s}\x1b[22m` : s),
45
+ dim: (s) => (useColor ? `\x1b[2m${s}\x1b[22m` : s),
46
+ green: (s) => (useColor ? `\x1b[32m${s}\x1b[39m` : s),
47
+ yellow: (s) => (useColor ? `\x1b[33m${s}\x1b[39m` : s),
48
+ red: (s) => (useColor ? `\x1b[31m${s}\x1b[39m` : s),
49
+ cyan: (s) => (useColor ? `\x1b[36m${s}\x1b[39m` : s),
50
+ };
51
+ function die(message, code = 1) {
52
+ process.stderr.write(`${c.red("error:")} ${message}\n`);
53
+ process.exit(code);
54
+ }
55
+ function statusGlyph(status) {
56
+ switch (status) {
57
+ case "ready":
58
+ return c.green("ready");
59
+ case "processing":
60
+ case "pending":
61
+ case "queued":
62
+ return c.yellow(status);
63
+ case "failed":
64
+ return c.red("failed");
65
+ case "none":
66
+ case null:
67
+ case undefined:
68
+ return c.dim("—");
69
+ default:
70
+ return String(status);
71
+ }
72
+ }
73
+ function fmtDuration(seconds) {
74
+ if (seconds == null || !Number.isFinite(seconds))
75
+ return "—";
76
+ const s = Math.round(seconds);
77
+ const h = Math.floor(s / 3600);
78
+ const m = Math.floor((s % 3600) / 60);
79
+ const sec = s % 60;
80
+ return h > 0
81
+ ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}`
82
+ : `${m}:${String(sec).padStart(2, "0")}`;
83
+ }
84
+ function fmtDate(iso) {
85
+ if (!iso)
86
+ return "—";
87
+ const d = new Date(iso);
88
+ if (Number.isNaN(d.getTime()))
89
+ return iso;
90
+ return d.toISOString().slice(0, 10);
91
+ }
92
+ /** Visible-width truncate with ellipsis (plain ASCII widths are fine here). */
93
+ function trunc(s, width) {
94
+ if (s.length <= width)
95
+ return s;
96
+ return `${s.slice(0, Math.max(0, width - 1))}…`;
97
+ }
98
+ // ---------------------------------------------------------------------------
99
+ // Config store (~/.config/clipy/config.json)
100
+ // ---------------------------------------------------------------------------
101
+ function configPath() {
102
+ const base = process.env.XDG_CONFIG_HOME && process.env.XDG_CONFIG_HOME.trim()
103
+ ? process.env.XDG_CONFIG_HOME
104
+ : join(homedir(), ".config");
105
+ return join(base, "clipy", "config.json");
106
+ }
107
+ function readConfig() {
108
+ try {
109
+ return JSON.parse(readFileSync(configPath(), "utf8"));
110
+ }
111
+ catch {
112
+ return {};
113
+ }
114
+ }
115
+ function writeConfig(cfg) {
116
+ const p = configPath();
117
+ mkdirSync(dirname(p), { recursive: true });
118
+ writeFileSync(p, `${JSON.stringify(cfg, null, 2)}\n`, { mode: 0o600 });
119
+ try {
120
+ chmodSync(p, 0o600);
121
+ }
122
+ catch {
123
+ // best-effort on platforms without POSIX modes
124
+ }
125
+ }
126
+ const FETCH_TIMEOUT_MS = 20_000;
127
+ function requireKey(ctx) {
128
+ if (ctx.apiKey)
129
+ return ctx.apiKey;
130
+ die(`no API key. Run ${c.bold("clipy login")} (create a key at ${ctx.apiUrl}/settings/api-keys), or set CLIPY_API_KEY.`);
131
+ }
132
+ async function api(ctx, path, accept = "application/json") {
133
+ const key = requireKey(ctx);
134
+ const controller = new AbortController();
135
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
136
+ try {
137
+ return await fetch(`${ctx.apiUrl}${path}`, {
138
+ headers: {
139
+ Authorization: `Bearer ${key}`,
140
+ Accept: accept,
141
+ "User-Agent": `clipy-cli/${VERSION}`,
142
+ },
143
+ signal: controller.signal,
144
+ });
145
+ }
146
+ catch (e) {
147
+ if (e.name === "AbortError") {
148
+ die(`request timed out after ${FETCH_TIMEOUT_MS / 1000}s (${path})`);
149
+ }
150
+ throw e;
151
+ }
152
+ finally {
153
+ clearTimeout(timer);
154
+ }
155
+ }
156
+ async function apiJson(ctx, path) {
157
+ const res = await api(ctx, path);
158
+ const text = await res.text();
159
+ let body = {};
160
+ try {
161
+ body = text ? JSON.parse(text) : {};
162
+ }
163
+ catch {
164
+ body = { raw: text };
165
+ }
166
+ if (!res.ok) {
167
+ const msg = (typeof body.error === "string" && body.error) || `Clipy API error ${res.status}`;
168
+ if (res.status === 401) {
169
+ die(`${msg}. Run ${c.bold("clipy login")} to set a new key.`);
170
+ }
171
+ die(msg);
172
+ }
173
+ return body;
174
+ }
175
+ // Accepts a bare public id OR a full Clipy watch/share URL and returns the id.
176
+ function normalizeId(input, ctx) {
177
+ const trimmed = input.trim().replace(/\/+$/, "");
178
+ const hosts = new Set(["clipy.online", "www.clipy.online"]);
179
+ try {
180
+ hosts.add(new URL(ctx.apiUrl).hostname.toLowerCase());
181
+ }
182
+ catch {
183
+ // ignore
184
+ }
185
+ try {
186
+ const u = new URL(trimmed);
187
+ if (hosts.has(u.hostname.toLowerCase())) {
188
+ const m = u.pathname.match(/\/(?:video|embed)\/([A-Za-z0-9_-]+)/);
189
+ if (m)
190
+ return m[1];
191
+ }
192
+ }
193
+ catch {
194
+ // not a URL — treat as a bare id
195
+ }
196
+ return trimmed;
197
+ }
198
+ // ---------------------------------------------------------------------------
199
+ // Output helpers
200
+ // ---------------------------------------------------------------------------
201
+ function printJson(data) {
202
+ process.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
203
+ }
204
+ function printRecordingsTable(recordings) {
205
+ if (recordings.length === 0) {
206
+ process.stdout.write(`${c.dim("no recordings")}\n`);
207
+ return;
208
+ }
209
+ const rows = recordings.map((r) => ({
210
+ id: r.id,
211
+ title: trunc(r.name || "Untitled", 40),
212
+ dur: fmtDuration(r.durationSeconds),
213
+ status: r.status,
214
+ transcript: r.transcriptStatus ?? "—",
215
+ created: fmtDate(r.createdAt),
216
+ }));
217
+ const w = {
218
+ id: Math.max(2, ...rows.map((r) => r.id.length)),
219
+ title: Math.max(5, ...rows.map((r) => r.title.length)),
220
+ dur: Math.max(3, ...rows.map((r) => r.dur.length)),
221
+ status: Math.max(6, ...rows.map((r) => r.status.length)),
222
+ transcript: Math.max(10, ...rows.map((r) => r.transcript.length)),
223
+ };
224
+ process.stdout.write(`${c.bold(`${"ID".padEnd(w.id)} ${"TITLE".padEnd(w.title)} ${"DUR".padEnd(w.dur)} ${"STATUS".padEnd(w.status)} ${"TRANSCRIPT".padEnd(w.transcript)} CREATED`)}\n`);
225
+ for (const r of rows) {
226
+ const statusColored = r.status === "ready" ? c.green(r.status.padEnd(w.status)) : c.yellow(r.status.padEnd(w.status));
227
+ process.stdout.write(`${c.cyan(r.id.padEnd(w.id))} ${r.title.padEnd(w.title)} ${r.dur.padEnd(w.dur)} ${statusColored} ${r.transcript.padEnd(w.transcript)} ${c.dim(r.created)}\n`);
228
+ }
229
+ }
230
+ function srtTime(seconds, sep) {
231
+ const ms = Math.max(0, Math.round(seconds * 1000));
232
+ const h = Math.floor(ms / 3_600_000);
233
+ const m = Math.floor((ms % 3_600_000) / 60_000);
234
+ const s = Math.floor((ms % 60_000) / 1000);
235
+ const rem = ms % 1000;
236
+ return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}${sep}${String(rem).padStart(3, "0")}`;
237
+ }
238
+ function toSrt(segments) {
239
+ return segments
240
+ .map((seg, i) => `${i + 1}\n${srtTime(seg.start, ",")} --> ${srtTime(seg.end, ",")}\n${seg.text}\n`)
241
+ .join("\n");
242
+ }
243
+ function toVtt(segments) {
244
+ const body = segments
245
+ .map((seg) => `${srtTime(seg.start, ".")} --> ${srtTime(seg.end, ".")}\n${seg.text}\n`)
246
+ .join("\n");
247
+ return `WEBVTT\n\n${body}`;
248
+ }
249
+ // ---------------------------------------------------------------------------
250
+ // Commands
251
+ // ---------------------------------------------------------------------------
252
+ const HELP = `${c.bold("clipy")} — the Clipy (https://clipy.online) command line, v${VERSION}
253
+
254
+ ${c.bold("USAGE")}
255
+ clipy <command> [arguments] [flags]
256
+
257
+ ${c.bold("AUTH")}
258
+ login [--key <clipy_sk_live_…>] Verify + store your API key (${c.dim("~/.config/clipy/config.json")})
259
+ logout Delete the stored key
260
+ whoami Check which key is active and that it works
261
+
262
+ ${c.bold("RECORDINGS")}
263
+ list [-n <N>] [--page <P>] [--status <s,…>] [--json]
264
+ List your recordings (newest first)
265
+ search <query> [--json] Full-text search titles + descriptions
266
+ show <id|url> [--json] One recording's metadata + share link
267
+ transcript <id> [--srt|--vtt|--json]
268
+ Print the transcript (plaintext by default)
269
+ summary <id> [--json] AI summary: TL;DR, key points, action items
270
+ moments <id> [--json] Key moments (timestamps + captions + click coords)
271
+ context <id> Full agent-context bundle as markdown
272
+ download <id> [-o <path>] Download the MP4
273
+ open <id> Open the share page in your browser
274
+ wait <id> [--for transcript|summary|both] [--timeout <sec>]
275
+ Block until processing artifacts are ready
276
+
277
+ ${c.bold("AGENTS")}
278
+ mcp Run the Clipy MCP server (wraps: npx -y @clipy/mcp)
279
+
280
+ ${c.bold("GLOBAL FLAGS")}
281
+ --key <key> API key for this invocation (else CLIPY_API_KEY, else stored login)
282
+ --api-url <url> API base (else CLIPY_API_URL, default https://clipy.online)
283
+ --json Machine-readable output (list/search/show/transcript/summary/moments/wait)
284
+ -v, --version Print version
285
+
286
+ ${c.bold("EXIT CODES")}
287
+ 0 ok · 1 error · 2 usage · 3 artifact not ready (transcript/summary/wait)
288
+
289
+ ${c.bold("SETUP")}
290
+ 1. Create a key at ${c.cyan("https://clipy.online/settings/api-keys")}
291
+ 2. ${c.bold("clipy login")}
292
+ 3. ${c.bold("clipy list")}
293
+
294
+ The CLI is read-only: it can never create, modify, or delete recordings.
295
+ `;
296
+ async function cmdLogin(ctx, keyFlag) {
297
+ let key = keyFlag?.trim() || "";
298
+ if (!key) {
299
+ key = await promptHidden(`Paste your Clipy API key (from ${ctx.apiUrl}/settings/api-keys): `);
300
+ }
301
+ if (!key.startsWith("clipy_sk_live_")) {
302
+ die("that doesn't look like a Clipy API key (expected it to start with clipy_sk_live_)");
303
+ }
304
+ // Verify before storing.
305
+ const probe = { ...ctx, apiKey: key };
306
+ await apiJson(probe, "/api/v1/recordings?limit=1");
307
+ const cfg = readConfig();
308
+ cfg.apiKey = key;
309
+ if (ctx.apiUrl !== "https://clipy.online")
310
+ cfg.apiUrl = ctx.apiUrl;
311
+ writeConfig(cfg);
312
+ process.stdout.write(`${c.green("✓")} key verified and saved to ${c.dim(configPath())}\n`);
313
+ }
314
+ function promptHidden(question) {
315
+ return new Promise((resolvePrompt) => {
316
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
317
+ const anyRl = rl;
318
+ process.stdout.write(question);
319
+ // Mute echoed input so the key isn't visible / in scrollback.
320
+ anyRl._writeToOutput = () => { };
321
+ rl.question("", (answer) => {
322
+ anyRl._writeToOutput = undefined;
323
+ process.stdout.write("\n");
324
+ rl.close();
325
+ resolvePrompt(answer.trim());
326
+ });
327
+ });
328
+ }
329
+ function cmdLogout() {
330
+ const cfg = readConfig();
331
+ if (!cfg.apiKey) {
332
+ process.stdout.write("no stored key — nothing to do\n");
333
+ return;
334
+ }
335
+ delete cfg.apiKey;
336
+ if (Object.keys(cfg).length === 0) {
337
+ try {
338
+ rmSync(configPath());
339
+ }
340
+ catch {
341
+ // ignore
342
+ }
343
+ }
344
+ else {
345
+ writeConfig(cfg);
346
+ }
347
+ process.stdout.write(`${c.green("✓")} stored key removed\n`);
348
+ }
349
+ async function cmdWhoami(ctx) {
350
+ const key = requireKey(ctx);
351
+ const source = process.env.CLIPY_API_KEY === key ? "env CLIPY_API_KEY" : readConfig().apiKey === key ? configPath() : "--key flag";
352
+ await apiJson(ctx, "/api/v1/recordings?limit=1");
353
+ process.stdout.write(`${c.green("✓")} key ${c.bold(`${key.slice(0, 22)}…`)} is valid (${c.dim(source)}) against ${ctx.apiUrl}\n`);
354
+ }
355
+ async function cmdList(ctx, opts) {
356
+ const params = new URLSearchParams();
357
+ params.set("limit", String(opts.n));
358
+ params.set("page", String(opts.page));
359
+ if (opts.q)
360
+ params.set("q", opts.q);
361
+ if (opts.status)
362
+ params.set("status", opts.status);
363
+ const body = await apiJson(ctx, `/api/v1/recordings?${params.toString()}`);
364
+ const recordings = (body.recordings ?? []);
365
+ if (opts.json) {
366
+ printJson(body);
367
+ return;
368
+ }
369
+ printRecordingsTable(recordings);
370
+ const pg = body.pagination;
371
+ if (pg && typeof pg.total === "number" && recordings.length < pg.total) {
372
+ process.stdout.write(c.dim(`page ${pg.page ?? opts.page}/${pg.totalPages ?? "?"} of ${pg.total} recordings — use --page/${"-n"} for more\n`));
373
+ }
374
+ }
375
+ async function cmdShow(ctx, id, json) {
376
+ const pid = encodeURIComponent(normalizeId(id, ctx));
377
+ const body = await apiJson(ctx, `/api/v1/recordings/${pid}`);
378
+ if (json) {
379
+ printJson(body);
380
+ return;
381
+ }
382
+ const r = body.recording;
383
+ if (!r)
384
+ die("unexpected response shape");
385
+ process.stdout.write(`${c.bold(r.name || "Untitled")}\n`);
386
+ if (r.description)
387
+ process.stdout.write(`${r.description}\n`);
388
+ process.stdout.write("\n");
389
+ const kv = [
390
+ ["id", c.cyan(r.id)],
391
+ ["status", statusGlyph(r.status)],
392
+ ["duration", fmtDuration(r.durationSeconds)],
393
+ ["source", r.sourcePlatform ?? "—"],
394
+ ["transcript", statusGlyph(r.transcriptStatus)],
395
+ ["summary", statusGlyph(r.summaryStatus)],
396
+ ["created", fmtDate(r.createdAt)],
397
+ ["share", c.cyan(r.webUrl)],
398
+ ["video", r.videoUrl ? c.dim(r.videoUrl) : "—"],
399
+ ];
400
+ const w = Math.max(...kv.map(([k]) => k.length));
401
+ for (const [k, v] of kv)
402
+ process.stdout.write(`${c.dim(k.padEnd(w))} ${v}\n`);
403
+ }
404
+ async function cmdTranscript(ctx, id, fmt) {
405
+ const pid = encodeURIComponent(normalizeId(id, ctx));
406
+ const body = await apiJson(ctx, `/api/v1/recordings/${pid}/transcript`);
407
+ const status = String(body.status ?? "unknown");
408
+ if (fmt === "json") {
409
+ printJson(body);
410
+ if (status !== "ready")
411
+ process.exit(3);
412
+ return;
413
+ }
414
+ if (status !== "ready") {
415
+ process.stderr.write(`transcript not ready (status: ${status}). Try ${c.bold(`clipy wait ${normalizeId(id, ctx)}`)}\n`);
416
+ process.exit(3);
417
+ }
418
+ // The ready payload nests under `transcript`; accept top-level too.
419
+ const t = (body.transcript ?? body);
420
+ if (fmt === "text") {
421
+ process.stdout.write(`${String(t.plaintext ?? "")}\n`);
422
+ return;
423
+ }
424
+ const segments = (t.segments ?? []);
425
+ if (!segments.length)
426
+ die("transcript has no segments to export");
427
+ process.stdout.write(fmt === "srt" ? toSrt(segments) : toVtt(segments));
428
+ }
429
+ async function cmdSummary(ctx, id, json) {
430
+ const pid = encodeURIComponent(normalizeId(id, ctx));
431
+ const body = await apiJson(ctx, `/api/v1/recordings/${pid}/summary`);
432
+ const status = String(body.status ?? "unknown");
433
+ if (json) {
434
+ printJson(body);
435
+ if (status !== "ready")
436
+ process.exit(3);
437
+ return;
438
+ }
439
+ if (status !== "ready") {
440
+ process.stderr.write(`summary not ready (status: ${status}). Try ${c.bold(`clipy wait ${normalizeId(id, ctx)} --for summary`)}\n`);
441
+ process.exit(3);
442
+ }
443
+ const s = body.summary;
444
+ if (!s)
445
+ die("summary missing from response");
446
+ process.stdout.write(`${c.bold("TL;DR")}\n${s.tldr ?? "—"}\n`);
447
+ if (s.keyPoints?.length) {
448
+ process.stdout.write(`\n${c.bold("Key points")}\n`);
449
+ for (const p of s.keyPoints)
450
+ process.stdout.write(` • ${p}\n`);
451
+ }
452
+ if (s.actionItems?.length) {
453
+ process.stdout.write(`\n${c.bold("Action items")}\n`);
454
+ for (const a of s.actionItems)
455
+ process.stdout.write(` ☐ ${a}\n`);
456
+ }
457
+ }
458
+ async function cmdMoments(ctx, id, json) {
459
+ const pid = encodeURIComponent(normalizeId(id, ctx));
460
+ const body = await apiJson(ctx, `/api/v1/recordings/${pid}/key-moments`);
461
+ if (json) {
462
+ printJson(body);
463
+ return;
464
+ }
465
+ const status = String(body.status ?? "unknown");
466
+ const moments = (body.moments ?? []);
467
+ if (!moments.length) {
468
+ process.stderr.write(`no key moments (status: ${status})\n`);
469
+ process.exit(status === "ready" ? 0 : 3);
470
+ }
471
+ for (const m of moments) {
472
+ const coord = m.x != null && m.y != null ? c.dim(` (click ${(m.x * 100).toFixed(0)}%,${(m.y * 100).toFixed(0)}%)`) : "";
473
+ process.stdout.write(`${c.cyan(m.timeLabel.padStart(7))} ${m.caption}${coord}\n`);
474
+ if (m.frameUrl)
475
+ process.stdout.write(`${" ".repeat(9)}${c.dim(m.frameUrl)}\n`);
476
+ }
477
+ }
478
+ async function cmdContext(ctx, id) {
479
+ const pid = encodeURIComponent(normalizeId(id, ctx));
480
+ const res = await api(ctx, `/api/agent-context/${pid}`, "text/markdown, text/plain, application/json");
481
+ const text = await res.text();
482
+ if (!res.ok) {
483
+ let msg = `Clipy API error ${res.status}`;
484
+ try {
485
+ const j = JSON.parse(text);
486
+ if (typeof j.error === "string")
487
+ msg = j.error;
488
+ }
489
+ catch {
490
+ // not json
491
+ }
492
+ die(msg);
493
+ }
494
+ process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
495
+ }
496
+ async function cmdDownload(ctx, id, outputPath) {
497
+ const pid = normalizeId(id, ctx);
498
+ const body = await apiJson(ctx, `/api/v1/recordings/${encodeURIComponent(pid)}`);
499
+ const rec = body.recording;
500
+ if (!rec?.videoUrl) {
501
+ die(`recording ${pid} has no downloadable video yet (status: ${rec?.status ?? "unknown"})`);
502
+ }
503
+ const dest = outputPath ? resolve(outputPath) : join(process.cwd(), `clipy-${pid}.mp4`);
504
+ const target = new URL(rec.videoUrl, ctx.apiUrl);
505
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
506
+ die(`refusing to download non-http(s) URL: ${target.protocol}`);
507
+ }
508
+ const controller = new AbortController();
509
+ const timer = setTimeout(() => controller.abort(), 600_000);
510
+ try {
511
+ const res = await fetch(target, { signal: controller.signal });
512
+ if (!res.ok || !res.body)
513
+ die(`failed to download video (HTTP ${res.status})`);
514
+ const total = Number(res.headers.get("content-length") || 0);
515
+ let done = 0;
516
+ const progress = new Transform({
517
+ transform(chunk, _enc, cb) {
518
+ done += chunk.length;
519
+ if (process.stderr.isTTY && total > 0) {
520
+ process.stderr.write(`\r${c.dim(`downloading… ${Math.round((done / total) * 100)}% (${fmtBytes(done)}/${fmtBytes(total)})`)}`);
521
+ }
522
+ cb(null, chunk);
523
+ },
524
+ });
525
+ await pipeline(Readable.fromWeb(res.body), progress, createWriteStream(dest));
526
+ if (process.stderr.isTTY && total > 0)
527
+ process.stderr.write("\r\x1b[2K");
528
+ }
529
+ finally {
530
+ clearTimeout(timer);
531
+ }
532
+ const bytes = statSync(dest).size;
533
+ process.stdout.write(`${c.green("✓")} saved ${c.bold(dest)} (${fmtBytes(bytes)})\n`);
534
+ }
535
+ function fmtBytes(n) {
536
+ if (n >= 1_073_741_824)
537
+ return `${(n / 1_073_741_824).toFixed(1)} GB`;
538
+ if (n >= 1_048_576)
539
+ return `${(n / 1_048_576).toFixed(1)} MB`;
540
+ if (n >= 1024)
541
+ return `${(n / 1024).toFixed(1)} KB`;
542
+ return `${n} B`;
543
+ }
544
+ async function cmdOpen(ctx, id) {
545
+ const pid = normalizeId(id, ctx);
546
+ const url = `${ctx.apiUrl}/video/${pid}`;
547
+ const platform = process.platform;
548
+ const opener = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
549
+ const args = platform === "win32" ? ["/c", "start", "", url] : [url];
550
+ try {
551
+ const child = spawn(opener, args, { detached: true, stdio: "ignore" });
552
+ child.unref();
553
+ process.stdout.write(`${c.green("✓")} opening ${c.cyan(url)}\n`);
554
+ }
555
+ catch {
556
+ process.stdout.write(`${url}\n`);
557
+ }
558
+ }
559
+ async function cmdWait(ctx, id, need, timeoutSec, json) {
560
+ const pid = encodeURIComponent(normalizeId(id, ctx));
561
+ const deadline = Date.now() + timeoutSec * 1000;
562
+ const terminal = new Set(["ready", "failed", "none"]);
563
+ const spin = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
564
+ let tick = 0;
565
+ for (;;) {
566
+ const transcript = await apiJson(ctx, `/api/v1/recordings/${pid}/transcript`);
567
+ const tStatus = String(transcript.status);
568
+ let summary = null;
569
+ let sStatus = "skipped";
570
+ if (need !== "transcript") {
571
+ summary = await apiJson(ctx, `/api/v1/recordings/${pid}/summary`);
572
+ sStatus = String(summary.status);
573
+ }
574
+ const transcriptDone = need === "summary" || terminal.has(tStatus);
575
+ const summaryDone = need === "transcript" || terminal.has(sStatus);
576
+ if (transcriptDone && summaryDone) {
577
+ if (process.stderr.isTTY)
578
+ process.stderr.write("\r\x1b[2K");
579
+ if (json) {
580
+ printJson({ id: normalizeId(id, ctx), transcript, ...(summary ? { summary } : {}) });
581
+ }
582
+ else {
583
+ process.stdout.write(`transcript: ${statusGlyph(tStatus)}${need !== "transcript" ? ` summary: ${statusGlyph(sStatus)}` : ""}\n`);
584
+ }
585
+ const failed = tStatus === "failed" || (need !== "transcript" && sStatus === "failed");
586
+ process.exit(failed ? 1 : 0);
587
+ }
588
+ if (Date.now() >= deadline) {
589
+ if (process.stderr.isTTY)
590
+ process.stderr.write("\r\x1b[2K");
591
+ process.stderr.write(`timed out after ${timeoutSec}s (transcript: ${tStatus}${need !== "transcript" ? `, summary: ${sStatus}` : ""})\n`);
592
+ process.exit(3);
593
+ }
594
+ if (process.stderr.isTTY) {
595
+ process.stderr.write(`\r${c.yellow(spin[tick++ % spin.length])} waiting… transcript: ${tStatus}${need !== "transcript" ? `, summary: ${sStatus}` : ""} `);
596
+ }
597
+ await new Promise((r) => setTimeout(r, 3000));
598
+ }
599
+ }
600
+ function cmdMcp() {
601
+ // `clipy mcp` IS the MCP server: it wraps `npx -y @clipy/mcp` with inherited
602
+ // stdio, so MCP clients can be configured with `clipy mcp` directly.
603
+ const npx = process.platform === "win32" ? "npx.cmd" : "npx";
604
+ const child = spawn(npx, ["-y", "@clipy/mcp"], { stdio: "inherit" });
605
+ child.on("exit", (code) => process.exit(code ?? 0));
606
+ child.on("error", (e) => die(`failed to launch @clipy/mcp via npx: ${e.message}`));
607
+ }
608
+ // ---------------------------------------------------------------------------
609
+ // Entry
610
+ // ---------------------------------------------------------------------------
611
+ async function main() {
612
+ const { values, positionals } = parseArgs({
613
+ args: process.argv.slice(2),
614
+ allowPositionals: true,
615
+ strict: false,
616
+ options: {
617
+ json: { type: "boolean", default: false },
618
+ key: { type: "string" },
619
+ "api-url": { type: "string" },
620
+ status: { type: "string" },
621
+ page: { type: "string" },
622
+ n: { type: "string", short: "n" },
623
+ limit: { type: "string" },
624
+ output: { type: "string", short: "o" },
625
+ srt: { type: "boolean", default: false },
626
+ vtt: { type: "boolean", default: false },
627
+ for: { type: "string" },
628
+ timeout: { type: "string" },
629
+ version: { type: "boolean", short: "v", default: false },
630
+ help: { type: "boolean", short: "h", default: false },
631
+ },
632
+ });
633
+ if (values.version) {
634
+ process.stdout.write(`${VERSION}\n`);
635
+ return;
636
+ }
637
+ const cfg = readConfig();
638
+ const ctx = {
639
+ apiUrl: (values["api-url"] ||
640
+ process.env.CLIPY_API_URL ||
641
+ cfg.apiUrl ||
642
+ "https://clipy.online").replace(/\/+$/, ""),
643
+ apiKey: values.key || process.env.CLIPY_API_KEY || cfg.apiKey || null,
644
+ };
645
+ const [command, ...rest] = positionals;
646
+ if (!command || values.help || command === "help") {
647
+ process.stdout.write(HELP);
648
+ if (!command && !values.help)
649
+ process.exitCode = 2;
650
+ return;
651
+ }
652
+ const json = Boolean(values.json);
653
+ const num = (v, dflt) => {
654
+ const n = parseInt(String(v ?? ""), 10);
655
+ return Number.isFinite(n) && n > 0 ? n : dflt;
656
+ };
657
+ switch (command) {
658
+ case "login":
659
+ await cmdLogin(ctx, values.key);
660
+ return;
661
+ case "logout":
662
+ cmdLogout();
663
+ return;
664
+ case "whoami":
665
+ await cmdWhoami(ctx);
666
+ return;
667
+ case "list":
668
+ await cmdList(ctx, {
669
+ n: num(values.n ?? values.limit, 20),
670
+ page: num(values.page, 1),
671
+ status: values.status,
672
+ json,
673
+ });
674
+ return;
675
+ case "search": {
676
+ const q = rest.join(" ").trim();
677
+ if (!q)
678
+ die("usage: clipy search <query>", 2);
679
+ await cmdList(ctx, { q, n: num(values.n ?? values.limit, 20), page: num(values.page, 1), status: values.status, json });
680
+ return;
681
+ }
682
+ case "show":
683
+ if (!rest[0])
684
+ die("usage: clipy show <id|url>", 2);
685
+ await cmdShow(ctx, rest[0], json);
686
+ return;
687
+ case "transcript": {
688
+ if (!rest[0])
689
+ die("usage: clipy transcript <id|url> [--srt|--vtt|--json]", 2);
690
+ const fmt = json ? "json" : values.srt ? "srt" : values.vtt ? "vtt" : "text";
691
+ await cmdTranscript(ctx, rest[0], fmt);
692
+ return;
693
+ }
694
+ case "summary":
695
+ if (!rest[0])
696
+ die("usage: clipy summary <id|url> [--json]", 2);
697
+ await cmdSummary(ctx, rest[0], json);
698
+ return;
699
+ case "moments":
700
+ case "key-moments":
701
+ if (!rest[0])
702
+ die("usage: clipy moments <id|url> [--json]", 2);
703
+ await cmdMoments(ctx, rest[0], json);
704
+ return;
705
+ case "context":
706
+ if (!rest[0])
707
+ die("usage: clipy context <id|url>", 2);
708
+ await cmdContext(ctx, rest[0]);
709
+ return;
710
+ case "download":
711
+ if (!rest[0])
712
+ die("usage: clipy download <id|url> [-o <path>]", 2);
713
+ await cmdDownload(ctx, rest[0], values.output);
714
+ return;
715
+ case "open":
716
+ if (!rest[0])
717
+ die("usage: clipy open <id|url>", 2);
718
+ await cmdOpen(ctx, rest[0]);
719
+ return;
720
+ case "wait": {
721
+ if (!rest[0])
722
+ die("usage: clipy wait <id|url> [--for transcript|summary|both] [--timeout <sec>]", 2);
723
+ const needRaw = String(values.for ?? "transcript");
724
+ if (!["transcript", "summary", "both"].includes(needRaw)) {
725
+ die("--for must be transcript, summary, or both", 2);
726
+ }
727
+ await cmdWait(ctx, rest[0], needRaw, num(values.timeout, 300), json);
728
+ return;
729
+ }
730
+ case "mcp":
731
+ cmdMcp();
732
+ return;
733
+ default:
734
+ die(`unknown command: ${command}\n\n${HELP}`, 2);
735
+ }
736
+ }
737
+ main().catch((e) => die(e.message));
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@clipy/cli",
3
+ "version": "0.1.0",
4
+ "description": "Command-line interface for Clipy — list, search, and read your screen recordings' transcripts, AI summaries, and key moments from the terminal.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "bin": {
11
+ "clipy": "dist/index.js"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md"
16
+ ],
17
+ "engines": {
18
+ "node": ">=18.17"
19
+ },
20
+ "keywords": [
21
+ "clipy",
22
+ "cli",
23
+ "screen-recording",
24
+ "transcript",
25
+ "srt",
26
+ "loom-alternative",
27
+ "ai-agent"
28
+ ],
29
+ "homepage": "https://clipy.online",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/manovagyanik1/clipy-cli.git"
33
+ },
34
+ "bugs": {
35
+ "url": "https://github.com/manovagyanik1/clipy-cli/issues"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc",
39
+ "prepublishOnly": "npm run build",
40
+ "start": "node dist/index.js"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^22.0.0",
44
+ "typescript": "^5.5.0"
45
+ }
46
+ }