@clipy/cli 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -12,14 +12,17 @@
12
12
  * Read-only: the CLI can never create, modify, or delete recordings.
13
13
  */
14
14
  import { parseArgs } from "node:util";
15
- import { createWriteStream, mkdirSync, readFileSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
16
- import { homedir } from "node:os";
15
+ import { appendFileSync, closeSync, createWriteStream, mkdirSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync, chmodSync } from "node:fs";
16
+ import { homedir, tmpdir } from "node:os";
17
17
  import { dirname, join, resolve } from "node:path";
18
18
  import { createInterface } from "node:readline";
19
19
  import { spawn } from "node:child_process";
20
+ import { createHash, randomUUID } from "node:crypto";
20
21
  import { Readable, Transform } from "node:stream";
21
22
  import { pipeline } from "node:stream/promises";
22
23
  import { createRequire } from "node:module";
24
+ import { CLIPY_SKILL_MD } from "./skill.js";
25
+ import { BridgeUnavailableError, bridgeRequest, readBridgeInfo, } from "./macBridge.js";
23
26
  // Exit quietly when stdout/stderr close early (e.g. `clipy list | head`).
24
27
  for (const stream of [process.stdout, process.stderr]) {
25
28
  stream.on("error", (e) => {
@@ -249,6 +252,9 @@ function toVtt(segments) {
249
252
  // ---------------------------------------------------------------------------
250
253
  // Commands
251
254
  // ---------------------------------------------------------------------------
255
+ // Session-mode safety rails (also shown in HELP, so declared before it).
256
+ const SESSION_DEFAULT_MAX_SEC = 600;
257
+ const SESSION_HARD_CAP_SEC = 1800;
252
258
  const HELP = `${c.bold("clipy")} — the Clipy (https://clipy.online) command line, v${VERSION}
253
259
 
254
260
  ${c.bold("USAGE")}
@@ -274,7 +280,44 @@ ${c.bold("RECORDINGS")}
274
280
  wait <id> [--for transcript|summary|both] [--timeout <sec>]
275
281
  Block until processing artifacts are ready
276
282
 
283
+ ${c.bold("RECORD")} ${c.dim("(needs an API key with the \"ingest\" permission)")}
284
+ record --url <http(s) url> [--for <sec>] [--title <t>] [--wait]
285
+ Capture a web app headlessly and upload it as
286
+ a Clipy recording. Prints the share link + the
287
+ agent-context URL. ${c.dim("Requires Playwright:")}
288
+ ${c.dim("npm i -g playwright && npx playwright install chromium")}
289
+ --for <sec> How long to record after load (default 15; per viewport)
290
+ --viewports <l> Record several sizes into ONE video, e.g.
291
+ mobile,tablet,desktop or 390x844,1440x900 (chapters marked)
292
+ --title/--description Recording metadata
293
+ --note "12: text" Timestamped narration note (repeatable) — for silent
294
+ captures the notes become the transcript
295
+ --width/--height Viewport + video size (default 1280×720)
296
+ --wait Block until the transcript is ready before printing
297
+
298
+ ${c.bold("SESSION")} ${c.dim("(agent works, Clipy records — one active session per directory)")}
299
+ ${c.dim("--source mac-screen on record/session records the REAL screen via the")}
300
+ ${c.dim("running Clipy Mac app (consent-gated, indicator always visible).")}
301
+ session start --url <app> [--max <sec>] [--title <t>]
302
+ Start recording in a background daemon and
303
+ return immediately (auto-stops + uploads at
304
+ --max, default ${SESSION_DEFAULT_MAX_SEC}s, cap ${SESSION_HARD_CAP_SEC}s)
305
+ mark "<what just happened>" Drop a live timestamped note; marks become
306
+ the recording's transcript chapters
307
+ session stop Finish: close browser, upload, print link
308
+ session abort Discard the session — nothing is uploaded
309
+ session status Show the active session's state
310
+
277
311
  ${c.bold("AGENTS")}
312
+ agents install <claude|codex|cursor>
313
+ Install the bundled Clipy skill for a coding
314
+ agent (teaches it to read + make recordings)
315
+ agents status | uninstall <t> Show / remove installed skills
316
+ guide --json Machine-readable manifest: every command,
317
+ flag, env var, and exit code
318
+ transcript <id> --replace <file> Replace a transcript with agent-authored
319
+ JSON ({segments} or {plaintext}); regenerates
320
+ the summary ${c.dim("(needs the \"ingest\" permission)")}
278
321
  mcp Run the Clipy MCP server (wraps: npx -y @clipy/mcp)
279
322
 
280
323
  ${c.bold("GLOBAL FLAGS")}
@@ -291,7 +334,8 @@ ${c.bold("SETUP")}
291
334
  2. ${c.bold("clipy login")}
292
335
  3. ${c.bold("clipy list")}
293
336
 
294
- The CLI is read-only: it can never create, modify, or delete recordings.
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.
295
339
  `;
296
340
  async function cmdLogin(ctx, keyFlag) {
297
341
  let key = keyFlag?.trim() || "";
@@ -606,6 +650,1168 @@ function cmdMcp() {
606
650
  child.on("error", (e) => die(`failed to launch @clipy/mcp via npx: ${e.message}`));
607
651
  }
608
652
  // ---------------------------------------------------------------------------
653
+ // record — the ONE write command. Drives a headless browser (Playwright),
654
+ // captures the page to WebM, and streams it through Clipy's raw-upload
655
+ // pipeline exactly like the web recorder does. Needs an API key with the
656
+ // `ingest` scope. Everything else in this CLI stays read-only.
657
+ // ---------------------------------------------------------------------------
658
+ /**
659
+ * POST JSON to an ingest endpoint with the API key. Retries transient failures
660
+ * (network error / 429 / 5xx) and THROWS on hard errors so the caller's
661
+ * try/finally can run its abort + cleanup (die() would process.exit and skip
662
+ * them). Auth/scope errors get a helpful message.
663
+ */
664
+ async function ingestPostJson(ctx, path, payload) {
665
+ const key = requireKey(ctx);
666
+ for (let attempt = 1; attempt <= 4; attempt++) {
667
+ const controller = new AbortController();
668
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
669
+ let res;
670
+ try {
671
+ res = await fetch(`${ctx.apiUrl}${path}`, {
672
+ method: "POST",
673
+ headers: {
674
+ Authorization: `Bearer ${key}`,
675
+ "Content-Type": "application/json",
676
+ Accept: "application/json",
677
+ "User-Agent": `clipy-cli/${VERSION}`,
678
+ },
679
+ body: JSON.stringify(payload),
680
+ signal: controller.signal,
681
+ });
682
+ }
683
+ catch (e) {
684
+ if (attempt < 4) {
685
+ await new Promise((r) => setTimeout(r, attempt * 1000));
686
+ continue;
687
+ }
688
+ throw new Error(e.name === "AbortError" ? `request timed out (${path})` : e.message);
689
+ }
690
+ finally {
691
+ clearTimeout(timer);
692
+ }
693
+ if ((res.status === 429 || res.status >= 500) && attempt < 4) {
694
+ await new Promise((r) => setTimeout(r, attempt * 1000));
695
+ continue;
696
+ }
697
+ const text = await res.text();
698
+ let body = {};
699
+ try {
700
+ body = text ? JSON.parse(text) : {};
701
+ }
702
+ catch {
703
+ body = { raw: text };
704
+ }
705
+ if (!res.ok) {
706
+ const msg = (typeof body.error === "string" && body.error) || `Clipy API error ${res.status}`;
707
+ if (res.status === 401) {
708
+ throw new Error(`${msg}. Run \`clipy login\` with an ingest-scoped key.`);
709
+ }
710
+ if (res.status === 403) {
711
+ throw new Error(`${msg}\nYour API key needs the "ingest" permission. Mint one at ` +
712
+ `${ctx.apiUrl}/settings/api-keys (check "Record & upload").`);
713
+ }
714
+ throw new Error(msg);
715
+ }
716
+ return body;
717
+ }
718
+ throw new Error(`request failed after retries (${path})`);
719
+ }
720
+ /** Upload one chunk as multipart/form-data, retrying transient 429/5xx. */
721
+ async function ingestPostChunk(ctx, recordingId, uploadToken, partNumber, bytes) {
722
+ const key = requireKey(ctx);
723
+ for (let attempt = 1; attempt <= 4; attempt++) {
724
+ // Copy the window into a standalone ArrayBuffer: it satisfies BlobPart
725
+ // under strict lib settings (a subarray's .buffer is ArrayBufferLike) and
726
+ // makes the snapshot independent of the reused read buffer.
727
+ const part = bytes.slice().buffer;
728
+ const form = new FormData();
729
+ form.append("recordingId", recordingId);
730
+ form.append("uploadToken", uploadToken);
731
+ form.append("partNumber", String(partNumber));
732
+ form.append("file", new Blob([part], { type: "video/webm" }), `part-${partNumber}.webm`);
733
+ const controller = new AbortController();
734
+ const timer = setTimeout(() => controller.abort(), 120_000);
735
+ let res;
736
+ try {
737
+ res = await fetch(`${ctx.apiUrl}/api/videos/raw-upload/chunk`, {
738
+ method: "POST",
739
+ headers: { Authorization: `Bearer ${key}`, "User-Agent": `clipy-cli/${VERSION}` },
740
+ body: form,
741
+ signal: controller.signal,
742
+ });
743
+ }
744
+ catch (e) {
745
+ if (attempt === 4)
746
+ throw e;
747
+ await new Promise((r) => setTimeout(r, attempt * 1000));
748
+ continue;
749
+ }
750
+ finally {
751
+ clearTimeout(timer);
752
+ }
753
+ if (res.ok)
754
+ return;
755
+ // 429 (too far ahead) / 5xx are transient — back off and retry.
756
+ if ((res.status === 429 || res.status >= 500) && attempt < 4) {
757
+ await new Promise((r) => setTimeout(r, attempt * 1000));
758
+ continue;
759
+ }
760
+ const text = await res.text().catch(() => "");
761
+ // Throw (not die) so cmdRecord's finally can abort + clean up.
762
+ throw new Error(`chunk ${partNumber} failed (HTTP ${res.status})${text ? `: ${text}` : ""}`);
763
+ }
764
+ }
765
+ async function loadChromium() {
766
+ for (const mod of ["playwright", "playwright-core"]) {
767
+ try {
768
+ const pw = (await import(mod));
769
+ if (pw.chromium)
770
+ return pw.chromium;
771
+ }
772
+ catch {
773
+ // try the next module
774
+ }
775
+ }
776
+ die(`clipy record needs Playwright (a headless browser). Install it once:\n` +
777
+ ` ${c.bold("npm install -g playwright")}\n` +
778
+ ` ${c.bold("npx playwright install chromium")}\n` +
779
+ `Then re-run your command. (Playwright is kept out of the base CLI so the ` +
780
+ `read-only commands stay a small, dependency-free install.)`);
781
+ }
782
+ /** Named viewport presets for `--viewports` (agent demos across screen sizes). */
783
+ const VIEWPORT_ALIASES = {
784
+ mobile: { width: 390, height: 844 },
785
+ tablet: { width: 768, height: 1024 },
786
+ desktop: { width: 1440, height: 900 },
787
+ };
788
+ function parseViewports(spec) {
789
+ const out = [];
790
+ for (const part of spec.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)) {
791
+ const alias = VIEWPORT_ALIASES[part];
792
+ if (alias) {
793
+ out.push({ ...alias, label: `${part} (${alias.width}×${alias.height})` });
794
+ continue;
795
+ }
796
+ const m = part.match(/^(\d{2,4})x(\d{2,4})$/);
797
+ if (!m) {
798
+ die(`invalid viewport "${part}" — use WIDTHxHEIGHT (e.g. 390x844) or ${Object.keys(VIEWPORT_ALIASES).join("/")}`, 2);
799
+ }
800
+ out.push({ width: parseInt(m[1], 10), height: parseInt(m[2], 10), label: `${m[1]}×${m[2]}` });
801
+ }
802
+ if (out.length === 0)
803
+ die("no viewports parsed from --viewports", 2);
804
+ if (out.length > 8)
805
+ die("--viewports supports at most 8 sizes per recording", 2);
806
+ return out;
807
+ }
808
+ /** Parses a `--note` flag value: "12: opened settings" or "12.5s: text" → note
809
+ * at 12s. A value with no timestamp prefix becomes a note at 0s. */
810
+ function parseNoteFlag(value) {
811
+ const m = value.match(/^\s*(\d+(?:\.\d+)?)s?\s*:\s*(.+)$/);
812
+ if (m)
813
+ return { startMs: Math.round(parseFloat(m[1]) * 1000), text: m[2].trim() };
814
+ return { startMs: 0, text: value.trim() };
815
+ }
816
+ /** WebM/Matroska files start with the EBML magic. Refuse to upload anything
817
+ * else — a crashed Chromium can leave a zero-byte or garbage file behind. */
818
+ function validateWebmFile(videoPath) {
819
+ const size = statSync(videoPath).size;
820
+ if (size === 0)
821
+ throw new Error("recording produced an empty file");
822
+ const fd = openSync(videoPath, "r");
823
+ try {
824
+ const head = Buffer.alloc(4);
825
+ readSync(fd, head, 0, 4, 0);
826
+ if (!(head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3)) {
827
+ throw new Error("recording file is not valid WebM (corrupt capture?)");
828
+ }
829
+ }
830
+ finally {
831
+ closeSync(fd);
832
+ }
833
+ return size;
834
+ }
835
+ /**
836
+ * Streams a captured WebM through Clipy's raw-upload pipeline
837
+ * (initiate → chunks → finalize → complete). Shared by `clipy record` and
838
+ * session mode. Aborts the server-side upload session on failure.
839
+ */
840
+ async function uploadWebmToClipy(ctx, opts) {
841
+ const sizeBytes = validateWebmFile(opts.videoPath);
842
+ opts.log(`${c.dim(`captured ${fmtBytes(sizeBytes)} — uploading…`)}`);
843
+ const recordingId = randomUUID();
844
+ let uploadToken = "";
845
+ let publicId = "";
846
+ try {
847
+ // 1) initiate → uploadToken + the video row (createVideoRow so the share
848
+ // link exists immediately). sourcePlatform 'web' is honest: this IS a
849
+ // web-content capture.
850
+ const init = await ingestPostJson(ctx, "/api/videos/raw-upload/initiate", {
851
+ recordingId,
852
+ createVideoRow: true,
853
+ sourcePlatform: "web",
854
+ sourceVersion: `cli/${VERSION}`,
855
+ });
856
+ uploadToken = String(init.uploadToken ?? "");
857
+ publicId = String(init.publicId ?? "");
858
+ if (!uploadToken)
859
+ throw new Error("initiate did not return an uploadToken");
860
+ // 2) stream the WebM in sequential 4 MiB parts read straight off disk (a
861
+ // long capture never has to sit fully in memory). Sequential keeps
862
+ // nextPartNumber advancing so we never trip the out-of-order guard.
863
+ const PART_SIZE = 4 * 1024 * 1024;
864
+ const totalParts = Math.max(1, Math.ceil(sizeBytes / PART_SIZE));
865
+ const fd = openSync(opts.videoPath, "r");
866
+ try {
867
+ const window = Buffer.allocUnsafe(PART_SIZE);
868
+ let partNumber = 1;
869
+ let offset = 0;
870
+ while (offset < sizeBytes) {
871
+ const bytesRead = readSync(fd, window, 0, PART_SIZE, offset);
872
+ if (bytesRead <= 0)
873
+ break;
874
+ // new Blob([...]) snapshots the bytes synchronously, so reusing `window`
875
+ // on the next iteration is safe (the chunk is fully sent before then).
876
+ await ingestPostChunk(ctx, recordingId, uploadToken, partNumber, window.subarray(0, bytesRead));
877
+ if (process.stderr.isTTY) {
878
+ process.stderr.write(`\r${c.dim(`uploading… part ${partNumber}/${totalParts}`)}`);
879
+ }
880
+ offset += bytesRead;
881
+ partNumber++;
882
+ }
883
+ }
884
+ finally {
885
+ closeSync(fd);
886
+ }
887
+ if (process.stderr.isTTY)
888
+ process.stderr.write("\r\x1b[2K");
889
+ // 3) finalize (seal bytes) then 4) complete (promote the row + enqueue
890
+ // transcode/transcribe/summarize). Narration rides `complete` and
891
+ // becomes the transcript server-side when the capture has no speech.
892
+ await ingestPostJson(ctx, "/api/videos/raw-upload/finalize", { recordingId, uploadToken });
893
+ await ingestPostJson(ctx, "/api/videos/raw-upload/complete", {
894
+ recordingId,
895
+ uploadToken,
896
+ name: opts.name,
897
+ description: opts.description,
898
+ sourcePlatform: "web",
899
+ sourceVersion: `cli/${VERSION}`,
900
+ ...(opts.narration && (opts.narration.text || opts.narration.notes?.length)
901
+ ? { narration: opts.narration }
902
+ : {}),
903
+ });
904
+ uploadToken = ""; // completed — nothing to abort below
905
+ }
906
+ catch (e) {
907
+ // Best-effort: release the half-uploaded streaming session so it doesn't
908
+ // sit as an orphan (the server also janitors orphans after 8 days).
909
+ if (uploadToken) {
910
+ await ingestPostJson(ctx, "/api/videos/raw-upload/abort", { recordingId, uploadToken }).catch(() => { });
911
+ }
912
+ throw e;
913
+ }
914
+ return {
915
+ publicId,
916
+ shareUrl: `${ctx.apiUrl}/video/${publicId}`,
917
+ contextUrl: `${ctx.apiUrl}/api/agent-context/${publicId}`,
918
+ sizeBytes,
919
+ };
920
+ }
921
+ async function cmdRecord(ctx, opts) {
922
+ // Validate the target URL up front — a headless browser will happily hang on
923
+ // a typo'd or non-http(s) URL otherwise.
924
+ let target;
925
+ try {
926
+ target = new URL(opts.url);
927
+ }
928
+ catch {
929
+ die(`invalid --url: ${opts.url}`, 2);
930
+ }
931
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
932
+ die(`--url must be http(s), got ${target.protocol}`, 2);
933
+ }
934
+ requireKey(ctx); // fail fast before we spin up a browser
935
+ const chromium = await loadChromium();
936
+ const tmpDir = join(tmpdir(), `clipy-record-${randomUUID()}`);
937
+ mkdirSync(tmpDir, { recursive: true });
938
+ const log = (m) => {
939
+ if (!opts.json)
940
+ process.stderr.write(`${m}\n`);
941
+ };
942
+ // Multi-viewport mode records every size sequentially into ONE video; the
943
+ // frame is sized to the largest viewport and smaller passes letterbox
944
+ // inside it. Each pass emits an auto note so the transcript chapters the
945
+ // passes ("Viewport mobile (390×844)" …).
946
+ const passes = opts.viewports ?? [
947
+ { width: opts.width, height: opts.height, label: `${opts.width}×${opts.height}` },
948
+ ];
949
+ const frame = {
950
+ width: Math.max(...passes.map((v) => v.width)),
951
+ height: Math.max(...passes.map((v) => v.height)),
952
+ };
953
+ let uploaded;
954
+ const autoNotes = [];
955
+ try {
956
+ // --- Capture -----------------------------------------------------------
957
+ let videoPath;
958
+ log(`${c.dim("launching headless chromium…")}`);
959
+ const browser = await chromium.launch({
960
+ headless: true,
961
+ // Cloud sandboxes / CI containers run as root where Chromium's own
962
+ // sandbox can't initialize; this is a user-driven capture of a URL they
963
+ // chose, so the browser sandbox isn't a trust boundary here.
964
+ args: ["--no-sandbox", "--disable-dev-shm-usage"],
965
+ });
966
+ try {
967
+ const context = await browser.newContext({
968
+ viewport: { width: frame.width, height: frame.height },
969
+ recordVideo: { dir: tmpDir, size: frame },
970
+ });
971
+ const page = await context.newPage();
972
+ const captureStart = Date.now();
973
+ for (const [i, vp] of passes.entries()) {
974
+ if (opts.viewports) {
975
+ await page.setViewportSize({ width: vp.width, height: vp.height }).catch(() => { });
976
+ autoNotes.push({
977
+ startMs: Date.now() - captureStart,
978
+ text: `[auto] Viewport pass ${i + 1}/${passes.length}: ${vp.label}`,
979
+ });
980
+ log(`${c.dim(`viewport ${vp.label}…`)}`);
981
+ }
982
+ log(`${c.dim(`opening ${target.href}…`)}`);
983
+ try {
984
+ await page.goto(target.href, { waitUntil: "load", timeout: 30_000 });
985
+ }
986
+ catch {
987
+ // A slow SPA may not fire 'load' — keep recording anyway; the agent
988
+ // asked to capture whatever is on screen for --for seconds.
989
+ log(c.yellow(`page load timed out; recording current state anyway`));
990
+ }
991
+ log(`${c.dim(`recording for ${opts.forSec}s…`)}`);
992
+ if (opts.viewports) {
993
+ // Slow scroll through the page so each size shows real layout, not
994
+ // just the fold. Scroll in ~6 steps across the pass duration.
995
+ const steps = 6;
996
+ const stepMs = (opts.forSec * 1000) / steps;
997
+ for (let s = 0; s < steps; s++) {
998
+ await page.waitForTimeout(stepMs);
999
+ await page.mouse.wheel(0, Math.round(vp.height * 0.7)).catch(() => { });
1000
+ }
1001
+ }
1002
+ else {
1003
+ await page.waitForTimeout(opts.forSec * 1000);
1004
+ }
1005
+ }
1006
+ const video = page.video();
1007
+ // Close the page then context so Playwright finalizes + flushes the WebM.
1008
+ await page.close();
1009
+ await context.close();
1010
+ if (!video)
1011
+ throw new Error("browser did not produce a video (recordVideo unavailable)");
1012
+ videoPath = await video.path();
1013
+ }
1014
+ finally {
1015
+ await browser.close().catch(() => { });
1016
+ }
1017
+ // --- Upload ------------------------------------------------------------
1018
+ const notes = [...autoNotes, ...opts.notes].sort((a, b) => a.startMs - b.startMs);
1019
+ uploaded = await uploadWebmToClipy(ctx, {
1020
+ videoPath,
1021
+ name: opts.name,
1022
+ description: opts.description,
1023
+ narration: notes.length ? { notes } : undefined,
1024
+ log,
1025
+ });
1026
+ }
1027
+ finally {
1028
+ try {
1029
+ rmSync(tmpDir, { recursive: true, force: true });
1030
+ }
1031
+ catch {
1032
+ // best-effort temp cleanup
1033
+ }
1034
+ }
1035
+ if (opts.wait && uploaded.publicId) {
1036
+ log(`${c.dim("waiting for transcript…")}`);
1037
+ await waitForArtifacts(ctx, uploaded.publicId).catch(() => {
1038
+ log(c.yellow("artifacts not ready yet — they'll finish in the background"));
1039
+ });
1040
+ }
1041
+ if (opts.json) {
1042
+ printJson({
1043
+ id: uploaded.publicId,
1044
+ shareUrl: uploaded.shareUrl,
1045
+ contextUrl: uploaded.contextUrl,
1046
+ sizeBytes: uploaded.sizeBytes,
1047
+ });
1048
+ return;
1049
+ }
1050
+ process.stdout.write(`${c.green("✓")} recorded — ${c.bold(uploaded.shareUrl)}\n`);
1051
+ process.stdout.write(`${c.dim("agent context:")} ${uploaded.contextUrl}\n`);
1052
+ process.stdout.write(`${c.dim("next:")} clipy context ${uploaded.publicId} · clipy transcript ${uploaded.publicId}\n`);
1053
+ }
1054
+ /** Poll until the transcript reaches a terminal state (or ~5 min elapse). */
1055
+ async function waitForArtifacts(ctx, publicId) {
1056
+ const pid = encodeURIComponent(publicId);
1057
+ const deadline = Date.now() + 300_000;
1058
+ const terminal = new Set(["ready", "failed", "none"]);
1059
+ for (;;) {
1060
+ const t = await apiJson(ctx, `/api/v1/recordings/${pid}/transcript`);
1061
+ if (terminal.has(String(t.status)))
1062
+ return;
1063
+ if (Date.now() >= deadline)
1064
+ return;
1065
+ await new Promise((r) => setTimeout(r, 3000));
1066
+ }
1067
+ }
1068
+ function sessionDir() {
1069
+ return join(dirname(configPath()), "sessions");
1070
+ }
1071
+ /** One session per workspace: the session file is keyed by cwd. */
1072
+ function sessionFilePath(cwd) {
1073
+ const digest = createHash("sha1").update(cwd).digest("hex").slice(0, 16);
1074
+ return join(sessionDir(), `session-${digest}.json`);
1075
+ }
1076
+ function readSessionState(file) {
1077
+ try {
1078
+ return JSON.parse(readFileSync(file, "utf8"));
1079
+ }
1080
+ catch {
1081
+ return null;
1082
+ }
1083
+ }
1084
+ function writeSessionState(file, state) {
1085
+ mkdirSync(dirname(file), { recursive: true });
1086
+ const tmp = `${file}.${process.pid}.tmp`;
1087
+ writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
1088
+ renameSync(tmp, file);
1089
+ }
1090
+ function pidAlive(pid) {
1091
+ try {
1092
+ process.kill(pid, 0);
1093
+ return true;
1094
+ }
1095
+ catch {
1096
+ return false;
1097
+ }
1098
+ }
1099
+ function sessionIsActive(state) {
1100
+ return (["starting", "recording", "stopping", "uploading"].includes(state.state) &&
1101
+ pidAlive(state.pid));
1102
+ }
1103
+ function cleanupSessionFiles(state, file) {
1104
+ for (const p of [state.marksPath, state.controlPath, file]) {
1105
+ try {
1106
+ rmSync(p, { force: true });
1107
+ }
1108
+ catch {
1109
+ // best-effort
1110
+ }
1111
+ }
1112
+ }
1113
+ // --- Mac bridge flows (--source mac-screen): the desktop app records -------
1114
+ /** One-shot real-screen recording through the running Clipy app. */
1115
+ async function cmdRecordMac(opts) {
1116
+ const info = readBridgeInfo();
1117
+ const log = (m) => {
1118
+ if (!opts.json)
1119
+ process.stderr.write(`${m}\n`);
1120
+ };
1121
+ log(`${c.dim(`asking the Clipy app (v${info.appVersion}) to record the screen…`)}`);
1122
+ await bridgeRequest(info, "start", {
1123
+ // The recording is stopped by us after forSec; maxSec is the safety net
1124
+ // in case this CLI process dies mid-wait.
1125
+ maxSec: Math.min(opts.forSec + 60, 1800),
1126
+ title: opts.name,
1127
+ description: opts.description,
1128
+ notes: opts.notes.map((n) => ({ startMs: n.startMs, text: n.text })),
1129
+ });
1130
+ log(`${c.dim(`recording for ${opts.forSec}s…`)}`);
1131
+ await new Promise((r) => setTimeout(r, opts.forSec * 1000));
1132
+ log(`${c.dim("stopping + uploading…")}`);
1133
+ const result = await bridgeRequest(info, "stop");
1134
+ return {
1135
+ publicId: String(result.publicId ?? ""),
1136
+ shareUrl: String(result.shareUrl ?? ""),
1137
+ };
1138
+ }
1139
+ function macSessionState(info, maxSec) {
1140
+ const dir = sessionDir();
1141
+ return {
1142
+ version: 1,
1143
+ kind: "mac",
1144
+ bridge: { socketPath: info.socketPath, token: info.token, pid: info.pid },
1145
+ pid: info.pid,
1146
+ cwd: process.cwd(),
1147
+ url: "mac-screen",
1148
+ maxSec,
1149
+ width: 0,
1150
+ height: 0,
1151
+ state: "recording",
1152
+ recordStartEpochMs: Date.now(),
1153
+ marksPath: join(dir, "unused"),
1154
+ controlPath: join(dir, "unused"),
1155
+ logPath: join(dir, "unused"),
1156
+ tmpDir: join(dir, "unused"),
1157
+ };
1158
+ }
1159
+ function bridgeInfoFromSession(state) {
1160
+ if (!state.bridge) {
1161
+ die("session file is missing bridge info — abort it with `clipy session abort` and restart");
1162
+ }
1163
+ return {
1164
+ socketPath: state.bridge.socketPath,
1165
+ token: state.bridge.token,
1166
+ pid: state.bridge.pid,
1167
+ appVersion: "",
1168
+ protocolVersion: 1,
1169
+ };
1170
+ }
1171
+ async function cmdSessionStart(ctx, opts) {
1172
+ if (opts.source === "mac-screen") {
1173
+ const file = sessionFilePath(process.cwd());
1174
+ const existing = readSessionState(file);
1175
+ if (existing && existing.kind !== "mac" && sessionIsActive(existing)) {
1176
+ die("a web recording session is already active here — finish or abort it first");
1177
+ }
1178
+ const info = readBridgeInfo();
1179
+ const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
1180
+ await bridgeRequest(info, "start", {
1181
+ maxSec,
1182
+ title: opts.name,
1183
+ description: opts.description,
1184
+ });
1185
+ writeSessionState(file, macSessionState(info, maxSec));
1186
+ if (opts.json) {
1187
+ printJson({ state: "recording", source: "mac-screen", maxSec });
1188
+ return;
1189
+ }
1190
+ process.stdout.write(`${c.green("✓")} the Clipy app is recording your screen (max ${maxSec}s)\n`);
1191
+ process.stdout.write(`${c.dim("while it runs:")} clipy mark "what just happened"\n` +
1192
+ `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
1193
+ return;
1194
+ }
1195
+ let target;
1196
+ try {
1197
+ target = new URL(opts.url);
1198
+ }
1199
+ catch {
1200
+ die(`invalid --url: ${opts.url}`, 2);
1201
+ }
1202
+ if (target.protocol !== "http:" && target.protocol !== "https:") {
1203
+ die(`--url must be http(s), got ${target.protocol}`, 2);
1204
+ }
1205
+ const key = requireKey(ctx);
1206
+ await loadChromium(); // fail fast with install instructions before daemonizing
1207
+ const file = sessionFilePath(process.cwd());
1208
+ const existing = readSessionState(file);
1209
+ if (existing && sessionIsActive(existing)) {
1210
+ die(`a recording session is already active in this workspace (pid ${existing.pid}, started for ${existing.url}).\n` +
1211
+ `Finish it with \`clipy session stop\` or discard it with \`clipy session abort\`.`);
1212
+ }
1213
+ if (existing)
1214
+ cleanupSessionFiles(existing, file); // stale (daemon died) — clear
1215
+ const maxSec = Math.min(Math.max(1, opts.maxSec), SESSION_HARD_CAP_SEC);
1216
+ const id = randomUUID();
1217
+ const dir = sessionDir();
1218
+ mkdirSync(dir, { recursive: true });
1219
+ const state = {
1220
+ version: 1,
1221
+ pid: 0,
1222
+ cwd: process.cwd(),
1223
+ url: target.href,
1224
+ name: opts.name,
1225
+ description: opts.description,
1226
+ maxSec,
1227
+ width: opts.width,
1228
+ height: opts.height,
1229
+ state: "starting",
1230
+ marksPath: join(dir, `marks-${id}.jsonl`),
1231
+ controlPath: join(dir, `control-${id}.json`),
1232
+ logPath: join(dir, `daemon-${id}.log`),
1233
+ tmpDir: join(tmpdir(), `clipy-session-${id}`),
1234
+ };
1235
+ const logFd = openSync(state.logPath, "a");
1236
+ const child = spawn(process.execPath, [process.argv[1], "__session-daemon", file], {
1237
+ detached: true,
1238
+ stdio: ["ignore", logFd, logFd],
1239
+ env: {
1240
+ ...process.env,
1241
+ CLIPY_API_KEY: key,
1242
+ CLIPY_API_URL: ctx.apiUrl,
1243
+ },
1244
+ });
1245
+ closeSync(logFd);
1246
+ if (!child.pid)
1247
+ die("failed to spawn the session daemon");
1248
+ state.pid = child.pid;
1249
+ writeSessionState(file, state);
1250
+ child.unref();
1251
+ // Wait for the daemon to actually start recording (first Chromium launch on
1252
+ // a cold cache can take a while) so the agent's next command lands inside a
1253
+ // live recording, not a race.
1254
+ const deadline = Date.now() + 60_000;
1255
+ for (;;) {
1256
+ const s = readSessionState(file);
1257
+ if (s?.state === "recording")
1258
+ break;
1259
+ if (s?.state === "failed") {
1260
+ die(`session failed to start: ${s.error ?? "unknown error"} (log: ${state.logPath})`);
1261
+ }
1262
+ if (Date.now() >= deadline || (s && !pidAlive(s.pid))) {
1263
+ die(`session daemon did not start in time (log: ${state.logPath})`);
1264
+ }
1265
+ await new Promise((r) => setTimeout(r, 300));
1266
+ }
1267
+ if (opts.json) {
1268
+ printJson({ state: "recording", url: target.href, maxSec, sessionFile: file });
1269
+ return;
1270
+ }
1271
+ process.stdout.write(`${c.green("✓")} recording ${c.bold(target.href)} (max ${maxSec}s)\n`);
1272
+ process.stdout.write(`${c.dim("while it runs:")} clipy mark "what just happened"\n` +
1273
+ `${c.dim("when finished:")} clipy session stop ${c.dim("· discard:")} clipy session abort\n`);
1274
+ }
1275
+ function requireSession() {
1276
+ const file = sessionFilePath(process.cwd());
1277
+ const state = readSessionState(file);
1278
+ if (!state) {
1279
+ die(`no recording session in this workspace. Start one with \`clipy session start --url <app>\`.`);
1280
+ }
1281
+ return { file, state };
1282
+ }
1283
+ async function cmdMark(text, json) {
1284
+ const { file, state } = requireSession();
1285
+ if (state.kind === "mac") {
1286
+ const result = await bridgeRequest(bridgeInfoFromSession(state), "mark", { text }).catch((e) => {
1287
+ if (e instanceof BridgeUnavailableError) {
1288
+ cleanupSessionFiles(state, file);
1289
+ die("the Clipy app is no longer running — session cleared. Start a new one.");
1290
+ }
1291
+ die(e.message);
1292
+ });
1293
+ if (json) {
1294
+ printJson(result);
1295
+ return;
1296
+ }
1297
+ process.stdout.write(`${c.green("✓")} mark @ ${Number(result.atSeconds ?? 0).toFixed(1)}s — ${text.trim()}\n`);
1298
+ return;
1299
+ }
1300
+ if (!pidAlive(state.pid)) {
1301
+ cleanupSessionFiles(state, file);
1302
+ die("the session daemon is no longer running (crashed?) — session cleared. Start a new one.");
1303
+ }
1304
+ if (state.state !== "recording" || !state.recordStartEpochMs) {
1305
+ die(`session is ${state.state} — marks can only be added while recording`);
1306
+ }
1307
+ const tMs = Math.max(0, Date.now() - state.recordStartEpochMs);
1308
+ appendFileSync(state.marksPath, `${JSON.stringify({ tMs, text: text.trim() })}\n`);
1309
+ if (json) {
1310
+ printJson({ tMs, text: text.trim() });
1311
+ return;
1312
+ }
1313
+ const sec = (tMs / 1000).toFixed(1);
1314
+ process.stdout.write(`${c.green("✓")} mark @ ${sec}s — ${text.trim()}\n`);
1315
+ }
1316
+ async function cmdSessionStop(json) {
1317
+ const { file, state } = requireSession();
1318
+ if (state.kind === "mac") {
1319
+ if (!json)
1320
+ process.stderr.write(`${c.dim("stopping + uploading…")}\n`);
1321
+ const result = await bridgeRequest(bridgeInfoFromSession(state), "stop").catch((e) => {
1322
+ cleanupSessionFiles(state, file);
1323
+ die(e.message);
1324
+ });
1325
+ cleanupSessionFiles(state, file);
1326
+ const publicId = String(result.publicId ?? "");
1327
+ reportSessionResult({
1328
+ publicId,
1329
+ shareUrl: String(result.shareUrl ?? ""),
1330
+ contextUrl: `https://clipy.online/api/agent-context/${publicId}`,
1331
+ sizeBytes: 0,
1332
+ }, json);
1333
+ return;
1334
+ }
1335
+ if (!pidAlive(state.pid)) {
1336
+ // Daemon already gone: it may have finished (auto-stop at max duration)
1337
+ // or crashed. Report whatever terminal state it left behind.
1338
+ if (state.state === "done" && state.result) {
1339
+ reportSessionResult(state.result, json);
1340
+ cleanupSessionFiles(state, file);
1341
+ return;
1342
+ }
1343
+ cleanupSessionFiles(state, file);
1344
+ die(state.state === "failed"
1345
+ ? `session failed: ${state.error ?? "unknown"} (log: ${state.logPath})`
1346
+ : "the session daemon is no longer running (crashed?) — session cleared.");
1347
+ }
1348
+ writeFileSync(state.controlPath, JSON.stringify({ action: "stop" }));
1349
+ if (!json)
1350
+ process.stderr.write(`${c.dim("stopping + uploading…")}\n`);
1351
+ // Stop = close browser + upload; give long recordings room to finish.
1352
+ const deadline = Date.now() + 600_000;
1353
+ for (;;) {
1354
+ const s = readSessionState(file);
1355
+ if (s?.state === "done" && s.result) {
1356
+ reportSessionResult(s.result, json);
1357
+ cleanupSessionFiles(s, file);
1358
+ return;
1359
+ }
1360
+ if (s?.state === "failed") {
1361
+ const kept = s.keptVideoPath ? `\nThe capture was kept at: ${s.keptVideoPath}` : "";
1362
+ cleanupSessionFiles(s, file);
1363
+ die(`session upload failed: ${s.error ?? "unknown"}${kept}`);
1364
+ }
1365
+ if (s?.state === "aborted") {
1366
+ cleanupSessionFiles(s, file);
1367
+ die("session was aborted");
1368
+ }
1369
+ if (s && !pidAlive(s.pid)) {
1370
+ cleanupSessionFiles(s, file);
1371
+ die(`the session daemon died mid-stop (log: ${state.logPath})`);
1372
+ }
1373
+ if (Date.now() >= deadline) {
1374
+ die(`timed out waiting for the session to finish (log: ${state.logPath})`);
1375
+ }
1376
+ await new Promise((r) => setTimeout(r, 500));
1377
+ }
1378
+ }
1379
+ function reportSessionResult(result, json) {
1380
+ if (json) {
1381
+ printJson({
1382
+ id: result.publicId,
1383
+ shareUrl: result.shareUrl,
1384
+ contextUrl: result.contextUrl,
1385
+ sizeBytes: result.sizeBytes,
1386
+ });
1387
+ return;
1388
+ }
1389
+ process.stdout.write(`${c.green("✓")} recorded — ${c.bold(result.shareUrl)}\n`);
1390
+ process.stdout.write(`${c.dim("agent context:")} ${result.contextUrl}\n`);
1391
+ process.stdout.write(`${c.dim("next:")} clipy context ${result.publicId} · clipy wait ${result.publicId}\n`);
1392
+ }
1393
+ async function cmdSessionAbort(json) {
1394
+ const { file, state } = requireSession();
1395
+ if (state.kind === "mac") {
1396
+ await bridgeRequest(bridgeInfoFromSession(state), "abort").catch(() => { });
1397
+ cleanupSessionFiles(state, file);
1398
+ if (json)
1399
+ printJson({ state: "aborted" });
1400
+ else
1401
+ process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
1402
+ return;
1403
+ }
1404
+ if (!pidAlive(state.pid)) {
1405
+ cleanupSessionFiles(state, file);
1406
+ if (!json)
1407
+ process.stdout.write(`${c.green("✓")} stale session cleared (daemon was not running)\n`);
1408
+ else
1409
+ printJson({ state: "cleared" });
1410
+ return;
1411
+ }
1412
+ writeFileSync(state.controlPath, JSON.stringify({ action: "abort" }));
1413
+ const deadline = Date.now() + 30_000;
1414
+ for (;;) {
1415
+ const s = readSessionState(file);
1416
+ if (!s || s.state === "aborted" || s.state === "failed" || !pidAlive(s.pid))
1417
+ break;
1418
+ if (Date.now() >= deadline)
1419
+ break;
1420
+ await new Promise((r) => setTimeout(r, 300));
1421
+ }
1422
+ const final = readSessionState(file);
1423
+ if (final)
1424
+ cleanupSessionFiles(final, file);
1425
+ if (json)
1426
+ printJson({ state: "aborted" });
1427
+ else
1428
+ process.stdout.write(`${c.green("✓")} session aborted — nothing was uploaded\n`);
1429
+ }
1430
+ function cmdSessionStatus(json) {
1431
+ const file = sessionFilePath(process.cwd());
1432
+ const state = readSessionState(file);
1433
+ if (!state) {
1434
+ if (json)
1435
+ printJson({ state: "none" });
1436
+ else
1437
+ process.stdout.write(`${c.dim("no session in this workspace")}\n`);
1438
+ return;
1439
+ }
1440
+ const alive = pidAlive(state.pid);
1441
+ const elapsed = state.recordStartEpochMs && state.state === "recording"
1442
+ ? Math.round((Date.now() - state.recordStartEpochMs) / 1000)
1443
+ : null;
1444
+ if (json) {
1445
+ printJson({
1446
+ state: alive || ["done", "failed", "aborted"].includes(state.state) ? state.state : "dead",
1447
+ url: state.url,
1448
+ elapsedSec: elapsed,
1449
+ maxSec: state.maxSec,
1450
+ pid: state.pid,
1451
+ });
1452
+ return;
1453
+ }
1454
+ process.stdout.write(`${c.bold(state.state)}${alive ? "" : c.red(" (daemon dead)")} — ${state.url}` +
1455
+ `${elapsed != null ? ` — ${elapsed}s elapsed (max ${state.maxSec}s)` : ""}\n`);
1456
+ }
1457
+ async function runSessionDaemon(file) {
1458
+ const state = readSessionState(file);
1459
+ if (!state) {
1460
+ process.stderr.write(`[clipy-session] session file missing: ${file}\n`);
1461
+ process.exit(1);
1462
+ }
1463
+ const ctx = {
1464
+ apiUrl: process.env.CLIPY_API_URL || "https://clipy.online",
1465
+ apiKey: process.env.CLIPY_API_KEY || null,
1466
+ };
1467
+ const save = (patch) => {
1468
+ Object.assign(state, patch);
1469
+ writeSessionState(file, state);
1470
+ };
1471
+ const log = (m) => process.stderr.write(`[clipy-session] ${new Date().toISOString()} ${m}\n`);
1472
+ const autoMarks = [];
1473
+ let recordStart = 0;
1474
+ const autoMark = (text) => {
1475
+ if (autoMarks.length >= 50 || recordStart === 0)
1476
+ return;
1477
+ autoMarks.push({ startMs: Math.max(0, Date.now() - recordStart), text });
1478
+ };
1479
+ mkdirSync(state.tmpDir, { recursive: true });
1480
+ let browser = null;
1481
+ try {
1482
+ const chromium = await loadChromium();
1483
+ log(`launching chromium for ${state.url}`);
1484
+ browser = await chromium.launch({
1485
+ headless: true,
1486
+ args: ["--no-sandbox", "--disable-dev-shm-usage"],
1487
+ });
1488
+ const context = await browser.newContext({
1489
+ viewport: { width: state.width, height: state.height },
1490
+ recordVideo: { dir: state.tmpDir, size: { width: state.width, height: state.height } },
1491
+ });
1492
+ const page = await context.newPage();
1493
+ // Auto-marks: instrumentation ground truth alongside the agent's intent
1494
+ // marks. Type-tagged with [auto] so the transcript distinguishes them.
1495
+ page.on("framenavigated", ((frame) => {
1496
+ try {
1497
+ if (frame.parentFrame() === null)
1498
+ autoMark(`[auto] navigated to ${frame.url()}`);
1499
+ }
1500
+ catch {
1501
+ // never let instrumentation kill the recording
1502
+ }
1503
+ }));
1504
+ page.on("console", ((msg) => {
1505
+ try {
1506
+ if (msg.type() === "error") {
1507
+ autoMark(`[auto] console error: ${msg.text().slice(0, 200)}`);
1508
+ }
1509
+ }
1510
+ catch {
1511
+ // ignore
1512
+ }
1513
+ }));
1514
+ recordStart = Date.now();
1515
+ save({ state: "recording", recordStartEpochMs: recordStart });
1516
+ try {
1517
+ await page.goto(state.url, { waitUntil: "load", timeout: 30_000 });
1518
+ }
1519
+ catch {
1520
+ log("page load timed out; recording current state anyway");
1521
+ }
1522
+ // Main loop: poll the control file; enforce the max-duration rail.
1523
+ let stopReason = "stop";
1524
+ for (;;) {
1525
+ await page.waitForTimeout(400);
1526
+ let control = null;
1527
+ try {
1528
+ control = JSON.parse(readFileSync(state.controlPath, "utf8"));
1529
+ }
1530
+ catch {
1531
+ control = null;
1532
+ }
1533
+ if (control?.action === "abort") {
1534
+ stopReason = "abort";
1535
+ break;
1536
+ }
1537
+ if (control?.action === "stop") {
1538
+ stopReason = "stop";
1539
+ break;
1540
+ }
1541
+ if (Date.now() - recordStart >= state.maxSec * 1000) {
1542
+ stopReason = "max";
1543
+ break;
1544
+ }
1545
+ }
1546
+ if (stopReason === "abort") {
1547
+ log("abort requested — discarding capture");
1548
+ save({ state: "aborted" });
1549
+ await page.close().catch(() => { });
1550
+ await context.close().catch(() => { });
1551
+ try {
1552
+ rmSync(state.tmpDir, { recursive: true, force: true });
1553
+ }
1554
+ catch {
1555
+ // best-effort
1556
+ }
1557
+ return;
1558
+ }
1559
+ if (stopReason === "max") {
1560
+ autoMark(`[auto] session auto-stopped at the ${state.maxSec}s max duration`);
1561
+ log(`max duration ${state.maxSec}s reached — auto-stopping and uploading`);
1562
+ }
1563
+ save({ state: "stopping" });
1564
+ const video = page.video();
1565
+ await page.close();
1566
+ await context.close();
1567
+ if (!video)
1568
+ throw new Error("browser did not produce a video (recordVideo unavailable)");
1569
+ const videoPath = await video.path();
1570
+ await browser.close().catch(() => { });
1571
+ browser = null;
1572
+ // Merge the agent's marks (written live by `clipy mark` with its own
1573
+ // clock) with the [auto] instrumentation marks.
1574
+ const agentMarks = [];
1575
+ try {
1576
+ for (const line of readFileSync(state.marksPath, "utf8").split("\n")) {
1577
+ if (!line.trim())
1578
+ continue;
1579
+ const m = JSON.parse(line);
1580
+ if (typeof m.tMs === "number" && typeof m.text === "string" && m.text.trim()) {
1581
+ agentMarks.push({ startMs: Math.max(0, Math.round(m.tMs)), text: m.text.trim() });
1582
+ }
1583
+ }
1584
+ }
1585
+ catch {
1586
+ // no marks file — fine
1587
+ }
1588
+ const notes = [...agentMarks, ...autoMarks].sort((a, b) => a.startMs - b.startMs);
1589
+ save({ state: "uploading" });
1590
+ const uploaded = await uploadWebmToClipy(ctx, {
1591
+ videoPath,
1592
+ name: state.name,
1593
+ description: state.description,
1594
+ narration: notes.length ? { notes } : undefined,
1595
+ log: (m) => log(m.replace(/\x1b\[[0-9;]*m/g, "")),
1596
+ }).catch((e) => {
1597
+ // Keep the capture — losing the bytes is worse than leaving a file.
1598
+ const kept = join(sessionDir(), `kept-${randomUUID()}.webm`);
1599
+ try {
1600
+ renameSync(videoPath, kept);
1601
+ save({ keptVideoPath: kept });
1602
+ }
1603
+ catch {
1604
+ // original path stays in tmpDir (cleanup below is skipped on throw)
1605
+ }
1606
+ throw e;
1607
+ });
1608
+ save({ state: "done", result: uploaded });
1609
+ log(`done — ${uploaded.shareUrl}`);
1610
+ try {
1611
+ rmSync(state.tmpDir, { recursive: true, force: true });
1612
+ }
1613
+ catch {
1614
+ // best-effort
1615
+ }
1616
+ }
1617
+ catch (e) {
1618
+ save({ state: "failed", error: e.message });
1619
+ log(`failed: ${e.message}`);
1620
+ process.exitCode = 1;
1621
+ }
1622
+ finally {
1623
+ if (browser)
1624
+ await browser.close().catch(() => { });
1625
+ }
1626
+ }
1627
+ // ---------------------------------------------------------------------------
1628
+ // agents — install the bundled Clipy skill for a coding agent, so one command
1629
+ // teaches Claude Code / Codex / Cursor how to read AND make recordings.
1630
+ // ---------------------------------------------------------------------------
1631
+ const AGENT_TARGETS = ["claude", "codex", "cursor"];
1632
+ function skillPathFor(target) {
1633
+ const home = homedir();
1634
+ switch (target) {
1635
+ case "claude":
1636
+ return join(home, ".claude", "skills", "clipy", "SKILL.md");
1637
+ case "codex": {
1638
+ const codexHome = process.env.CODEX_HOME?.trim() || join(home, ".codex");
1639
+ return join(codexHome, "skills", "clipy", "SKILL.md");
1640
+ }
1641
+ case "cursor":
1642
+ return join(home, ".cursor", "skills", "clipy", "SKILL.md");
1643
+ }
1644
+ }
1645
+ function cmdAgents(sub, targetRaw, json) {
1646
+ if (sub === "status" || sub === undefined) {
1647
+ const status = AGENT_TARGETS.map((t) => {
1648
+ const p = skillPathFor(t);
1649
+ let installed = false;
1650
+ try {
1651
+ installed = statSync(p).isFile();
1652
+ }
1653
+ catch {
1654
+ installed = false;
1655
+ }
1656
+ return { target: t, installed, path: p };
1657
+ });
1658
+ if (json) {
1659
+ printJson({ agents: status });
1660
+ return;
1661
+ }
1662
+ for (const s of status) {
1663
+ process.stdout.write(`${s.installed ? c.green("✓ installed") : c.dim("— not installed")} ${s.target.padEnd(7)} ${c.dim(s.path)}\n`);
1664
+ }
1665
+ process.stdout.write(`${c.dim("install with:")} clipy agents install <claude|codex|cursor>\n`);
1666
+ return;
1667
+ }
1668
+ const target = targetRaw;
1669
+ if (!target || !AGENT_TARGETS.includes(target)) {
1670
+ die(`usage: clipy agents <status|install|uninstall> <${AGENT_TARGETS.join("|")}>`, 2);
1671
+ }
1672
+ const path = skillPathFor(target);
1673
+ if (sub === "install") {
1674
+ mkdirSync(dirname(path), { recursive: true });
1675
+ writeFileSync(path, CLIPY_SKILL_MD);
1676
+ if (json) {
1677
+ printJson({ installed: true, target, path });
1678
+ return;
1679
+ }
1680
+ process.stdout.write(`${c.green("✓")} Clipy skill installed for ${c.bold(target)} at ${c.dim(path)}\n`);
1681
+ process.stdout.write(`${c.dim("It teaches the agent to read clipy.online links and to record with clipy record / session.")}\n`);
1682
+ return;
1683
+ }
1684
+ if (sub === "uninstall") {
1685
+ try {
1686
+ rmSync(dirname(path), { recursive: true, force: true });
1687
+ }
1688
+ catch {
1689
+ // best-effort
1690
+ }
1691
+ if (json) {
1692
+ printJson({ uninstalled: true, target, path });
1693
+ return;
1694
+ }
1695
+ process.stdout.write(`${c.green("✓")} Clipy skill removed for ${target}\n`);
1696
+ return;
1697
+ }
1698
+ die(`usage: clipy agents <status|install|uninstall> <${AGENT_TARGETS.join("|")}>`, 2);
1699
+ }
1700
+ // ---------------------------------------------------------------------------
1701
+ // guide — machine-readable capability manifest. `clipy guide --json` is the
1702
+ // single document an agent can fetch to learn env vars, exit codes, and every
1703
+ // command's shape without trial-and-error. Bump GUIDE_SCHEMA_VERSION when the
1704
+ // contract changes.
1705
+ // ---------------------------------------------------------------------------
1706
+ const GUIDE_SCHEMA_VERSION = 1;
1707
+ function cmdGuide(json) {
1708
+ if (!json) {
1709
+ process.stdout.write(HELP);
1710
+ process.stdout.write(`\n${c.dim("machine-readable form:")} clipy guide --json\n`);
1711
+ return;
1712
+ }
1713
+ const cmdDoc = (name, usage, description, flags = []) => ({
1714
+ name,
1715
+ usage,
1716
+ description,
1717
+ flags,
1718
+ });
1719
+ printJson({
1720
+ schemaVersion: GUIDE_SCHEMA_VERSION,
1721
+ binary: "clipy",
1722
+ version: VERSION,
1723
+ description: "Clipy (clipy.online) command line: read your screen recordings' transcripts/summaries/key moments, and record web apps headlessly (one-shot or live session with timestamped marks).",
1724
+ outputConvention: {
1725
+ jsonFlag: "--json",
1726
+ stdout: "primary results (JSON when --json is set)",
1727
+ stderr: "progress + human hints; never JSON",
1728
+ errors: "exit non-zero with a message on stderr prefixed 'error:'",
1729
+ },
1730
+ env: [
1731
+ { name: "CLIPY_API_KEY", description: "API key (clipy_sk_live_…) from clipy.online/settings/api-keys; write commands need the 'ingest' scope" },
1732
+ { name: "CLIPY_API_URL", description: "API base URL override (default https://clipy.online)" },
1733
+ { name: "NO_COLOR", description: "disable ANSI color" },
1734
+ ],
1735
+ exitCodes: [
1736
+ { code: 0, meaning: "success" },
1737
+ { code: 1, meaning: "error" },
1738
+ { code: 2, meaning: "usage error" },
1739
+ { code: 3, meaning: "artifact not ready yet (transcript/summary/wait)" },
1740
+ ],
1741
+ commands: [
1742
+ cmdDoc("login", "clipy login [--key <key>]", "Verify + store an API key"),
1743
+ cmdDoc("logout", "clipy logout", "Delete the stored key"),
1744
+ cmdDoc("whoami", "clipy whoami", "Check the active key"),
1745
+ cmdDoc("list", "clipy list [-n N] [--page P] [--status s,…] [--json]", "List recordings, newest first"),
1746
+ cmdDoc("search", "clipy search <query> [--json]", "Full-text search titles + descriptions"),
1747
+ cmdDoc("show", "clipy show <id|url> [--json]", "One recording's metadata + share link"),
1748
+ cmdDoc("transcript", "clipy transcript <id> [--srt|--vtt|--json] | clipy transcript <id> --replace <file.json|-> ", "Print the transcript, or REPLACE it (ingest scope; file holds {segments:[{start,end,text}]} or {plaintext}; regenerates the summary)", ["--srt", "--vtt", "--json", "--replace <file>"]),
1749
+ cmdDoc("summary", "clipy summary <id> [--json]", "AI summary: TL;DR, key points, action items"),
1750
+ cmdDoc("moments", "clipy moments <id> [--json]", "Key moments: timestamps, captions, click coords"),
1751
+ cmdDoc("context", "clipy context <id>", "Full agent-context bundle as markdown"),
1752
+ cmdDoc("download", "clipy download <id> [-o path]", "Download the MP4"),
1753
+ cmdDoc("open", "clipy open <id>", "Open the share page in a browser"),
1754
+ 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)"),
1757
+ 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"),
1759
+ cmdDoc("guide", "clipy guide --json", "This manifest"),
1760
+ cmdDoc("mcp", "clipy mcp", "Run the Clipy MCP server (wraps npx -y @clipy/mcp)"),
1761
+ ],
1762
+ notes: [
1763
+ "Read commands accept a bare public id or the full https://clipy.online/video/<id> URL.",
1764
+ "record/session/mark/transcript --replace are the only write commands; they need a key with the 'ingest' permission.",
1765
+ "Headless captures have no audio: --note flags and session marks become the transcript, labeled agent-narration.",
1766
+ "Public recordings have an unauthenticated context document at https://clipy.online/video/<id>.md.",
1767
+ ],
1768
+ });
1769
+ }
1770
+ /** transcript --replace: PUT agent-authored transcript content. */
1771
+ async function cmdTranscriptReplace(ctx, id, file) {
1772
+ const pid = encodeURIComponent(normalizeId(id, ctx));
1773
+ let raw;
1774
+ if (file === "-") {
1775
+ raw = readFileSync(0, "utf8");
1776
+ }
1777
+ else {
1778
+ raw = readFileSync(resolve(file), "utf8");
1779
+ }
1780
+ let payload;
1781
+ try {
1782
+ payload = JSON.parse(raw);
1783
+ }
1784
+ catch {
1785
+ die("replace file must be JSON: {segments:[{start,end,text}...]} or {plaintext:\"...\"}", 2);
1786
+ }
1787
+ const key = requireKey(ctx);
1788
+ const res = await fetch(`${ctx.apiUrl}/api/v1/recordings/${pid}/transcript`, {
1789
+ method: "PUT",
1790
+ headers: {
1791
+ Authorization: `Bearer ${key}`,
1792
+ "Content-Type": "application/json",
1793
+ "User-Agent": `clipy-cli/${VERSION}`,
1794
+ },
1795
+ body: JSON.stringify(payload),
1796
+ });
1797
+ const text = await res.text();
1798
+ let body = {};
1799
+ try {
1800
+ body = text ? JSON.parse(text) : {};
1801
+ }
1802
+ catch {
1803
+ body = { raw: text };
1804
+ }
1805
+ if (!res.ok) {
1806
+ const msg = (typeof body.error === "string" && body.error) || `Clipy API error ${res.status}`;
1807
+ if (res.status === 403) {
1808
+ die(`${msg}\nYour API key needs the "ingest" permission (clipy.online/settings/api-keys).`);
1809
+ }
1810
+ die(msg);
1811
+ }
1812
+ printJson(body);
1813
+ }
1814
+ // ---------------------------------------------------------------------------
609
1815
  // Entry
610
1816
  // ---------------------------------------------------------------------------
611
1817
  async function main() {
@@ -626,6 +1832,18 @@ async function main() {
626
1832
  vtt: { type: "boolean", default: false },
627
1833
  for: { type: "string" },
628
1834
  timeout: { type: "string" },
1835
+ url: { type: "string" },
1836
+ name: { type: "string" },
1837
+ title: { type: "string" },
1838
+ description: { type: "string" },
1839
+ note: { type: "string", multiple: true },
1840
+ viewports: { type: "string" },
1841
+ max: { type: "string" },
1842
+ replace: { type: "string" },
1843
+ source: { type: "string" },
1844
+ width: { type: "string" },
1845
+ height: { type: "string" },
1846
+ wait: { type: "boolean", default: false },
629
1847
  version: { type: "boolean", short: "v", default: false },
630
1848
  help: { type: "boolean", short: "h", default: false },
631
1849
  },
@@ -686,7 +1904,11 @@ async function main() {
686
1904
  return;
687
1905
  case "transcript": {
688
1906
  if (!rest[0])
689
- die("usage: clipy transcript <id|url> [--srt|--vtt|--json]", 2);
1907
+ die("usage: clipy transcript <id|url> [--srt|--vtt|--json] [--replace <file.json|->]", 2);
1908
+ if (values.replace) {
1909
+ await cmdTranscriptReplace(ctx, rest[0], String(values.replace));
1910
+ return;
1911
+ }
690
1912
  const fmt = json ? "json" : values.srt ? "srt" : values.vtt ? "vtt" : "text";
691
1913
  await cmdTranscript(ctx, rest[0], fmt);
692
1914
  return;
@@ -730,6 +1952,116 @@ async function main() {
730
1952
  case "mcp":
731
1953
  cmdMcp();
732
1954
  return;
1955
+ case "agents":
1956
+ cmdAgents(rest[0], rest[1], json);
1957
+ return;
1958
+ case "guide":
1959
+ cmdGuide(json);
1960
+ return;
1961
+ case "record": {
1962
+ const source = String(values.source ?? "web");
1963
+ if (source !== "web" && source !== "mac-screen") {
1964
+ die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
1965
+ }
1966
+ if (source === "mac-screen") {
1967
+ const noteFlags = values.note ?? [];
1968
+ try {
1969
+ const result = await cmdRecordMac({
1970
+ forSec: num(values.for, 15),
1971
+ name: (values.title ?? values.name)?.trim() ||
1972
+ undefined,
1973
+ description: values.description?.trim() || undefined,
1974
+ notes: noteFlags.map(parseNoteFlag),
1975
+ json,
1976
+ });
1977
+ if (values.wait && result.publicId) {
1978
+ await waitForArtifacts(ctx, result.publicId).catch(() => { });
1979
+ }
1980
+ if (json) {
1981
+ printJson({ id: result.publicId, shareUrl: result.shareUrl });
1982
+ }
1983
+ else {
1984
+ process.stdout.write(`${c.green("✓")} recorded — ${c.bold(result.shareUrl)}\n`);
1985
+ process.stdout.write(`${c.dim("next:")} clipy context ${result.publicId} · clipy wait ${result.publicId}\n`);
1986
+ }
1987
+ }
1988
+ catch (e) {
1989
+ die(e.message);
1990
+ }
1991
+ return;
1992
+ }
1993
+ const url = values.url?.trim() || rest[0];
1994
+ if (!url) {
1995
+ die("usage: clipy record --url <http(s) url> [--for <sec>] [--name <title>] [--viewports <list>] [--source web|mac-screen] [--wait]", 2);
1996
+ }
1997
+ const noteFlags = values.note ?? [];
1998
+ await cmdRecord(ctx, {
1999
+ url,
2000
+ forSec: num(values.for, 15),
2001
+ name: (values.title ?? values.name)?.trim() ||
2002
+ undefined,
2003
+ description: values.description?.trim() || undefined,
2004
+ notes: noteFlags.map(parseNoteFlag),
2005
+ viewports: values.viewports ? parseViewports(String(values.viewports)) : null,
2006
+ width: num(values.width, 1280),
2007
+ height: num(values.height, 720),
2008
+ wait: Boolean(values.wait),
2009
+ json,
2010
+ });
2011
+ return;
2012
+ }
2013
+ case "session": {
2014
+ const sub = rest[0];
2015
+ if (sub === "start") {
2016
+ const source = String(values.source ?? "web");
2017
+ if (source !== "web" && source !== "mac-screen") {
2018
+ die("--source must be web (headless browser) or mac-screen (the Clipy Mac app)", 2);
2019
+ }
2020
+ const url = values.url?.trim() || rest[1];
2021
+ if (!url && source === "web") {
2022
+ die("usage: clipy session start --url <http(s) url> [--max <sec>] [--source web|mac-screen]", 2);
2023
+ }
2024
+ await cmdSessionStart(ctx, {
2025
+ url: url || "mac-screen",
2026
+ name: (values.title ?? values.name)?.trim() ||
2027
+ undefined,
2028
+ description: values.description?.trim() || undefined,
2029
+ maxSec: num(values.max, SESSION_DEFAULT_MAX_SEC),
2030
+ width: num(values.width, 1280),
2031
+ height: num(values.height, 720),
2032
+ json,
2033
+ source,
2034
+ });
2035
+ return;
2036
+ }
2037
+ if (sub === "stop") {
2038
+ await cmdSessionStop(json);
2039
+ return;
2040
+ }
2041
+ if (sub === "abort") {
2042
+ await cmdSessionAbort(json);
2043
+ return;
2044
+ }
2045
+ if (sub === "status" || sub === undefined) {
2046
+ cmdSessionStatus(json);
2047
+ return;
2048
+ }
2049
+ die("usage: clipy session <start|stop|abort|status>", 2);
2050
+ return;
2051
+ }
2052
+ case "mark": {
2053
+ const text = rest.join(" ").trim();
2054
+ if (!text)
2055
+ die('usage: clipy mark "<what just happened>"', 2);
2056
+ await cmdMark(text, json);
2057
+ return;
2058
+ }
2059
+ case "__session-daemon": {
2060
+ if (!rest[0])
2061
+ die("internal: __session-daemon needs a session file", 2);
2062
+ await runSessionDaemon(rest[0]);
2063
+ return;
2064
+ }
733
2065
  default:
734
2066
  die(`unknown command: ${command}\n\n${HELP}`, 2);
735
2067
  }