@clipy/cli 0.17.0 → 0.19.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 (61) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +265 -12
  3. package/dist/chromeForClipy.js +1 -1
  4. package/dist/context/importCmd.js +4 -1
  5. package/dist/context/readCmd.js +33 -21
  6. package/dist/context/ytdlp.js +108 -28
  7. package/dist/context-core/arec.js +66 -6
  8. package/dist/index.js +1180 -98
  9. package/dist/library.js +7 -3
  10. package/dist/local/arec.js +186 -0
  11. package/dist/local/commands.js +1103 -0
  12. package/dist/local/deps.js +42 -0
  13. package/dist/local/media.js +154 -0
  14. package/dist/local/pipeline.js +530 -0
  15. package/dist/local/ports.js +1 -0
  16. package/dist/local/speechEngine.js +260 -0
  17. package/dist/local/transcriptFile.js +54 -0
  18. package/dist/local/vendor/capture/capture.js +442 -0
  19. package/dist/local/vendor/capture/check.js +103 -0
  20. package/dist/local/vendor/capture/children.js +69 -0
  21. package/dist/local/vendor/capture/ffmpegArgs.js +108 -0
  22. package/dist/local/vendor/capture/index.js +36 -0
  23. package/dist/local/vendor/capture/proc.js +71 -0
  24. package/dist/local/vendor/capture/scripts.js +107 -0
  25. package/dist/local/vendor/capture/sidecar.js +199 -0
  26. package/dist/local/vendor/capture/sources.js +272 -0
  27. package/dist/local/vendor/capture/types.js +1 -0
  28. package/dist/local/vendor/capture/virtualDisplay.js +170 -0
  29. package/dist/local/vendor/capture/xauth.js +68 -0
  30. package/dist/local/vendor/config/errors.js +12 -0
  31. package/dist/local/vendor/config/index.js +241 -0
  32. package/dist/local/vendor/config/paths.js +37 -0
  33. package/dist/local/vendor/config/presets.js +61 -0
  34. package/dist/local/vendor/config/schema.js +66 -0
  35. package/dist/local/vendor/moments/generated/drawStrokes.js +127 -0
  36. package/dist/local/vendor/moments/generated/keyMomentsCursorContext.js +568 -0
  37. package/dist/local/vendor/moments/generated/keyMomentsFusion.js +406 -0
  38. package/dist/local/vendor/moments/generated/localMomentPlan.js +178 -0
  39. package/dist/local/vendor/moments/generated/types.js +1 -0
  40. package/dist/local/vendor/moments/index.js +147 -0
  41. package/dist/local/vendor/moments/llm.js +158 -0
  42. package/dist/local/vendor/transcribe/audio.js +251 -0
  43. package/dist/local/vendor/transcribe/chunking.js +250 -0
  44. package/dist/local/vendor/transcribe/index.js +89 -0
  45. package/dist/local/vendor/transcribe/local.js +221 -0
  46. package/dist/local/vendor/transcribe/localWorker.js +79 -0
  47. package/dist/local/vendor/transcribe/models.js +369 -0
  48. package/dist/local/vendor/transcribe/providers/assemblyai.js +61 -0
  49. package/dist/local/vendor/transcribe/providers/common.js +105 -0
  50. package/dist/local/vendor/transcribe/providers/deepgram.js +59 -0
  51. package/dist/local/vendor/transcribe/providers/elevenlabs.js +43 -0
  52. package/dist/local/vendor/transcribe/providers/gemini.js +102 -0
  53. package/dist/local/vendor/transcribe/providers/http.js +214 -0
  54. package/dist/local/vendor/transcribe/providers/openai.js +48 -0
  55. package/dist/local/vendor/transcribe/tar.js +53 -0
  56. package/dist/local/vendor/transcribe/types.js +1 -0
  57. package/dist/macBridge.js +78 -9
  58. package/dist/recheck.js +934 -0
  59. package/dist/recheckCmd.js +279 -0
  60. package/dist/skill.js +94 -3
  61. package/package.json +22 -11
@@ -0,0 +1,102 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/transcribe/src/providers/gemini.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * Google Gemini `generateContent` with the audio inline, asked for JSON
5
+ * segments. Gemini is a general model, not a speech recognizer, so its
6
+ * timestamps are approximate; pieces are kept short to keep them close, and
7
+ * every answer is validated before use.
8
+ */
9
+ import { z } from "zod";
10
+ import { joinUrl, ProviderError, requestJson } from "./http.js";
11
+ import { runInPieces } from "./common.js";
12
+ export const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
13
+ export const GEMINI_DEFAULT_MODEL = "gemini-3.5-flash-lite";
14
+ const PROMPT = "Transcribe all speech in this audio, verbatim, in the language spoken. " +
15
+ 'Answer with JSON only: {"language": "<ISO 639-1 code>", "segments": [{"start": <seconds>, "end": <seconds>, "text": "<words>"}]}. ' +
16
+ "Times are seconds from the start of this audio. Make one segment per sentence or per pause, at most 15 seconds each, in order. " +
17
+ 'If there is no speech, answer {"segments": []}.';
18
+ const RESPONSE_SCHEMA = {
19
+ type: "OBJECT",
20
+ properties: {
21
+ language: { type: "STRING" },
22
+ segments: {
23
+ type: "ARRAY",
24
+ items: {
25
+ type: "OBJECT",
26
+ properties: { start: { type: "NUMBER" }, end: { type: "NUMBER" }, text: { type: "STRING" } },
27
+ required: ["start", "end", "text"],
28
+ },
29
+ },
30
+ },
31
+ required: ["segments"],
32
+ };
33
+ /** Seconds as a number, or "SS", "MM:SS", "HH:MM:SS(.ms)" strings the model sometimes writes. */
34
+ const Seconds = z.preprocess((v) => {
35
+ if (typeof v !== "string")
36
+ return v;
37
+ const parts = v.trim().replace(/s$/, "").split(":").map(Number);
38
+ if (parts.length === 0 || parts.length > 3 || parts.some((p) => !Number.isFinite(p)))
39
+ return v;
40
+ return parts.reduce((acc, p) => acc * 60 + p, 0);
41
+ }, z.number().finite().nonnegative());
42
+ export const GeminiTranscript = z.object({
43
+ language: z.string().optional(),
44
+ segments: z.array(z.object({ start: Seconds, end: Seconds, text: z.string() })),
45
+ });
46
+ const Answer = z
47
+ .object({
48
+ candidates: z
49
+ .array(z.object({ content: z.object({ parts: z.array(z.object({ text: z.string().optional() }).passthrough()).optional() }).passthrough().optional() }).passthrough())
50
+ .optional(),
51
+ })
52
+ .passthrough();
53
+ /** Pull the JSON object out of a reply, tolerating a ```json fence. */
54
+ function parseReply(text) {
55
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text);
56
+ const body = (fenced ? fenced[1] : text).trim();
57
+ return JSON.parse(body);
58
+ }
59
+ export async function transcribeGemini(input, config, limits = {}) {
60
+ const provider = "gemini";
61
+ const model = config.model || GEMINI_DEFAULT_MODEL;
62
+ const url = joinUrl(config.baseUrl || GEMINI_BASE_URL, `models/${encodeURIComponent(model)}:generateContent`);
63
+ // Inline requests are capped at 20 MB; 5 minutes of WAV is about 13 MB once base64 encoded.
64
+ const maxSec = limits.maxSec ?? 300;
65
+ const targetSec = limits.targetSec ?? 240;
66
+ const { segments, language, gaps } = await runInPieces(input, { maxSec, targetSec }, async (wav, durSec) => {
67
+ const body = {
68
+ contents: [
69
+ {
70
+ role: "user",
71
+ parts: [{ inline_data: { mime_type: "audio/wav", data: wav.toString("base64") } }, { text: PROMPT }],
72
+ },
73
+ ],
74
+ generationConfig: { temperature: 0, responseMimeType: "application/json", responseSchema: RESPONSE_SCHEMA },
75
+ };
76
+ const raw = await requestJson(provider, url, { method: "POST", headers: { "x-goog-api-key": config.apiKey, "Content-Type": "application/json" }, body: JSON.stringify(body) }, input.signal);
77
+ const answer = Answer.safeParse(raw);
78
+ const text = answer.success ? (answer.data.candidates?.[0]?.content?.parts ?? []).map((p) => p.text ?? "").join("") : "";
79
+ if (!text.trim())
80
+ throw new ProviderError(provider, 200, "the answer had no transcript");
81
+ let json;
82
+ try {
83
+ json = parseReply(text);
84
+ }
85
+ catch {
86
+ throw new ProviderError(provider, 200, "the answer was not valid JSON");
87
+ }
88
+ const parsed = GeminiTranscript.safeParse(json);
89
+ if (!parsed.success)
90
+ throw new ProviderError(provider, 200, "the answer did not match the transcript format");
91
+ return {
92
+ language: parsed.data.language || undefined,
93
+ segments: parsed.data.segments
94
+ .filter((s) => s.text.trim() && s.start <= durSec + 1)
95
+ .map((s) => {
96
+ const start = Math.min(s.start, durSec);
97
+ return { start, end: Math.min(Math.max(s.end, start), durSec), text: s.text };
98
+ }),
99
+ };
100
+ });
101
+ return { segments, language, engine: `gemini:${model}`, gaps };
102
+ }
@@ -0,0 +1,214 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/transcribe/src/providers/http.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * Shared HTTP plumbing for the hosted providers. Errors name the provider and
5
+ * the HTTP status only: response bodies can echo transcript text, and request
6
+ * details carry the user's key, so neither is ever put in a message or log.
7
+ */
8
+ export class ProviderError extends Error {
9
+ provider;
10
+ status;
11
+ constructor(provider, status, detail) {
12
+ let msg;
13
+ if (status === undefined) {
14
+ msg = `${provider} transcription failed: ${detail ?? "the provider could not be reached"}`;
15
+ }
16
+ else {
17
+ msg = `${provider} transcription failed (HTTP ${status})`;
18
+ if (status === 401 || status === 403)
19
+ msg += ": check the API key";
20
+ else if (status === 413)
21
+ msg += ": the audio is too large for this provider";
22
+ else if (status === 429)
23
+ msg += ": rate limited, try again later";
24
+ else if (detail)
25
+ msg += `: ${detail}`;
26
+ }
27
+ super(msg);
28
+ this.name = "ProviderError";
29
+ this.provider = provider;
30
+ this.status = status;
31
+ }
32
+ }
33
+ export function joinUrl(base, path) {
34
+ return `${base.replace(/\/+$/, "")}/${path.replace(/^\/+/, "")}`;
35
+ }
36
+ /** Largest provider answer read into memory. A transcript of hours of speech is a few MB. */
37
+ export const MAX_RESPONSE_BYTES = 20 * 1024 * 1024;
38
+ /**
39
+ * A transfer is abandoned when nothing moves for this long: no upload slice
40
+ * sent, no answer chunk read.
41
+ */
42
+ export const PROVIDER_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
43
+ /**
44
+ * How long a provider may think after the whole upload has gone before its
45
+ * answer starts. Long, because a synchronous provider can take many minutes
46
+ * over a recording of a few hours.
47
+ */
48
+ export const PROVIDER_ANSWER_WAIT_MS = 20 * 60 * 1000;
49
+ /** Upload slice: progress is counted per slice handed to the connection. */
50
+ const UPLOAD_SLICE = 64 * 1024;
51
+ /** The request body as bytes plus the content type its encoding needs (FormData only). */
52
+ async function bodyBytes(url, init) {
53
+ const body = init.body;
54
+ if (body === undefined || body === null)
55
+ return null;
56
+ if (body instanceof Uint8Array)
57
+ return { bytes: body, contentType: null };
58
+ if (typeof body === "string")
59
+ return { bytes: Buffer.from(body, "utf8"), contentType: "text/plain;charset=UTF-8" };
60
+ const r = new Request(url, { method: init.method ?? "POST", body });
61
+ return { bytes: new Uint8Array(await r.arrayBuffer()), contentType: r.headers.get("content-type") };
62
+ }
63
+ async function send(provider, url, init, signal, timing) {
64
+ const idleMs = timing.idleMs ?? PROVIDER_IDLE_TIMEOUT_MS;
65
+ const answerWaitMs = timing.answerWaitMs ?? PROVIDER_ANSWER_WAIT_MS;
66
+ const clock = new AbortController();
67
+ let timer;
68
+ let waiting = false;
69
+ const arm = (ms, answerWait) => {
70
+ clearTimeout(timer);
71
+ waiting = answerWait;
72
+ timer = setTimeout(() => clock.abort(), ms);
73
+ };
74
+ const bump = () => arm(idleMs, false);
75
+ const done = () => clearTimeout(timer);
76
+ const combined = signal ? AbortSignal.any([signal, clock.signal]) : clock.signal;
77
+ const timeoutError = () => {
78
+ if (!clock.signal.aborted || signal?.aborted)
79
+ return null;
80
+ return new ProviderError(provider, undefined, waiting ? `no answer ${Math.round(answerWaitMs / 60_000)} min after the upload, gave up` : `no progress for ${Math.round(idleMs / 1000)} s, gave up`);
81
+ };
82
+ bump();
83
+ let res;
84
+ try {
85
+ const body = await bodyBytes(url, init);
86
+ let finalInit = { ...init, redirect: "error", signal: combined };
87
+ if (body) {
88
+ // Streamed in slices so a slow upload that is still moving is not cut
89
+ // off; once it has all gone, the provider gets the longer answer wait.
90
+ const headers = new Headers(init.headers);
91
+ if (body.contentType && !headers.has("content-type"))
92
+ headers.set("content-type", body.contentType);
93
+ headers.set("content-length", String(body.bytes.byteLength));
94
+ let offset = 0;
95
+ const stream = new ReadableStream({
96
+ pull(controller) {
97
+ if (offset >= body.bytes.byteLength) {
98
+ arm(answerWaitMs, true);
99
+ return controller.close();
100
+ }
101
+ bump();
102
+ controller.enqueue(body.bytes.subarray(offset, offset + UPLOAD_SLICE));
103
+ offset += UPLOAD_SLICE;
104
+ },
105
+ });
106
+ finalInit = { ...finalInit, headers, body: stream, duplex: "half" };
107
+ }
108
+ res = await fetch(url, finalInit);
109
+ bump();
110
+ }
111
+ catch (err) {
112
+ done();
113
+ const timedOut = timeoutError();
114
+ if (timedOut)
115
+ throw timedOut;
116
+ if (err.name === "AbortError" || signal?.aborted)
117
+ throw err;
118
+ const code = err.cause?.code;
119
+ throw new ProviderError(provider, undefined, code ? `network error (${code})` : "the provider could not be reached");
120
+ }
121
+ if (!res.ok) {
122
+ done();
123
+ // Drain without reading the body into any message.
124
+ await res.body?.cancel().catch(() => undefined);
125
+ throw new ProviderError(provider, res.status);
126
+ }
127
+ return { res, timeoutError, bump, done };
128
+ }
129
+ /**
130
+ * fetch that turns network failures and non-2xx answers into a ProviderError.
131
+ * Redirects are refused: requests carry the user's key in headers
132
+ * (xi-api-key, x-goog-api-key, Authorization), and a redirect must not take
133
+ * it to another host. Times out per `timing` until the answer starts; the
134
+ * caller owns reading the body.
135
+ */
136
+ export async function request(provider, url, init, signal, timing = {}) {
137
+ const sent = await send(provider, url, init, signal, timing);
138
+ sent.done();
139
+ return sent.res;
140
+ }
141
+ /**
142
+ * Read a response body as UTF-8, failing once it passes `maxBytes` (checked
143
+ * against Content-Length first, then while streaming) so a broken or hostile
144
+ * endpoint cannot fill memory. `onTooLarge` builds the error to throw.
145
+ */
146
+ export async function readCappedText(res, maxBytes, onTooLarge, onChunk) {
147
+ const declared = Number(res.headers.get("content-length"));
148
+ if (Number.isFinite(declared) && declared > maxBytes) {
149
+ await res.body?.cancel().catch(() => undefined);
150
+ throw onTooLarge();
151
+ }
152
+ if (!res.body)
153
+ return "";
154
+ const reader = res.body.getReader();
155
+ const chunks = [];
156
+ let total = 0;
157
+ for (;;) {
158
+ const { done, value } = await reader.read();
159
+ if (done)
160
+ break;
161
+ onChunk?.();
162
+ total += value.byteLength;
163
+ if (total > maxBytes) {
164
+ await reader.cancel().catch(() => undefined);
165
+ throw onTooLarge();
166
+ }
167
+ chunks.push(value);
168
+ }
169
+ return Buffer.concat(chunks, total).toString("utf8");
170
+ }
171
+ export async function requestJson(provider, url, init, signal, maxBytes = MAX_RESPONSE_BYTES, timing = {}) {
172
+ const { res, timeoutError, bump, done } = await send(provider, url, init, signal, timing);
173
+ let text;
174
+ try {
175
+ text = await readCappedText(res, maxBytes, () => new ProviderError(provider, undefined, `the answer was larger than ${Math.round(maxBytes / (1024 * 1024))} MB`), bump);
176
+ }
177
+ catch (err) {
178
+ const timedOut = timeoutError();
179
+ if (timedOut)
180
+ throw timedOut;
181
+ if (err instanceof ProviderError || err.name === "AbortError" || signal?.aborted)
182
+ throw err;
183
+ throw new ProviderError(provider, undefined, "the answer was cut off");
184
+ }
185
+ finally {
186
+ done();
187
+ }
188
+ try {
189
+ return JSON.parse(text);
190
+ }
191
+ catch {
192
+ throw new ProviderError(provider, res.status, "the answer was not valid JSON");
193
+ }
194
+ }
195
+ function cancelled() {
196
+ const err = new Error("Transcription was cancelled");
197
+ err.name = "AbortError";
198
+ return err;
199
+ }
200
+ export function sleep(ms, signal) {
201
+ return new Promise((resolve, reject) => {
202
+ if (signal?.aborted)
203
+ return reject(cancelled());
204
+ const onAbort = () => {
205
+ clearTimeout(t);
206
+ reject(cancelled());
207
+ };
208
+ const t = setTimeout(() => {
209
+ signal?.removeEventListener("abort", onAbort);
210
+ resolve();
211
+ }, ms);
212
+ signal?.addEventListener("abort", onAbort, { once: true });
213
+ });
214
+ }
@@ -0,0 +1,48 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/transcribe/src/providers/openai.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * Any OpenAI-compatible `/audio/transcriptions` endpoint: OpenAI (`whisper-1`),
5
+ * Groq (`whisper-large-v3-turbo`, `whisper-large-v3`), or a self-hosted server
6
+ * speaking the same API. Segment timestamps need `response_format=verbose_json`,
7
+ * which OpenAI's `gpt-4o-*-transcribe` models do not offer; they would come
8
+ * back as one segment per piece.
9
+ */
10
+ import { z } from "zod";
11
+ import { joinUrl, ProviderError, requestJson } from "./http.js";
12
+ import { maxSecForBytes, runInPieces, wholePieceSegment } from "./common.js";
13
+ /** OpenAI rejects uploads over 25 MB; stay under it with room for the form. */
14
+ export const OPENAI_MAX_UPLOAD_BYTES = 24 * 1024 * 1024;
15
+ const VerboseJson = z.object({
16
+ text: z.string().optional(),
17
+ language: z.string().optional(),
18
+ segments: z
19
+ .array(z.object({ start: z.number(), end: z.number(), text: z.string() }).passthrough())
20
+ .nullish(),
21
+ });
22
+ export async function transcribeOpenAICompatible(input, config, limits = {}) {
23
+ const provider = "openai-compatible";
24
+ const maxSec = maxSecForBytes(limits.maxUploadBytes ?? OPENAI_MAX_UPLOAD_BYTES);
25
+ const url = joinUrl(config.baseUrl, "audio/transcriptions");
26
+ const { segments, language, gaps } = await runInPieces(input, { maxSec, targetSec: Math.min(600, Math.floor(maxSec * 0.8)) }, async (wav, durSec) => {
27
+ const form = new FormData();
28
+ form.append("file", new Blob([new Uint8Array(wav)], { type: "audio/wav" }), "audio.wav");
29
+ form.append("model", config.model);
30
+ form.append("response_format", "verbose_json");
31
+ form.append("timestamp_granularities[]", "segment");
32
+ const headers = {};
33
+ if (config.apiKey)
34
+ headers.Authorization = `Bearer ${config.apiKey}`;
35
+ const raw = await requestJson(provider, url, { method: "POST", headers, body: form }, input.signal);
36
+ const parsed = VerboseJson.safeParse(raw);
37
+ if (!parsed.success)
38
+ throw new ProviderError(provider, 200, "unexpected answer shape");
39
+ const segs = parsed.data.segments;
40
+ return {
41
+ language: parsed.data.language,
42
+ segments: segs && segs.length > 0
43
+ ? segs.map((s) => ({ start: s.start, end: s.end, text: s.text }))
44
+ : wholePieceSegment(parsed.data.text ?? "", durSec),
45
+ };
46
+ });
47
+ return { segments, language, engine: `openai-compatible:${config.model}`, gaps };
48
+ }
@@ -0,0 +1,53 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/transcribe/src/tar.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * Just enough of tar to pull named files out of an archive held in memory
5
+ * (ustar, GNU long names and pax path records). Used for model archives that
6
+ * are only published as `.tar.bz2`.
7
+ */
8
+ function readString(buf, start, len) {
9
+ const raw = buf.subarray(start, start + len);
10
+ const nul = raw.indexOf(0);
11
+ return raw.subarray(0, nul === -1 ? raw.length : nul).toString("utf8");
12
+ }
13
+ function readOctal(buf, start, len) {
14
+ const s = readString(buf, start, len).trim();
15
+ return s ? parseInt(s, 8) : 0;
16
+ }
17
+ /** Every regular file in the archive, in order. */
18
+ export function* readTar(buf) {
19
+ let pos = 0;
20
+ let longName = null;
21
+ while (pos + 512 <= buf.length) {
22
+ const header = buf.subarray(pos, pos + 512);
23
+ if (header.every((b) => b === 0))
24
+ return;
25
+ const size = readOctal(header, 124, 12);
26
+ const type = String.fromCharCode(header[156] || 48);
27
+ const prefix = readString(header, 345, 155);
28
+ let name = readString(header, 0, 100);
29
+ if (prefix)
30
+ name = `${prefix}/${name}`;
31
+ const dataStart = pos + 512;
32
+ const data = buf.subarray(dataStart, dataStart + size);
33
+ pos = dataStart + Math.ceil(size / 512) * 512;
34
+ if (type === "L") {
35
+ longName = readString(data, 0, data.length);
36
+ continue;
37
+ }
38
+ if (type === "x") {
39
+ const m = /\d+ path=([^\n]*)\n/.exec(data.toString("utf8"));
40
+ if (m)
41
+ longName = m[1];
42
+ continue;
43
+ }
44
+ if (type === "g")
45
+ continue;
46
+ if (longName !== null) {
47
+ name = longName;
48
+ longName = null;
49
+ }
50
+ if (type === "0" || type === "\0" || type === "7")
51
+ yield { name: name.replace(/^\.\//, ""), data };
52
+ }
53
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/macBridge.js CHANGED
@@ -7,6 +7,11 @@
7
7
  * The file and socket are 0600, and every request carries the per-launch
8
8
  * token. Protocol: one JSON request line per connection, one JSON response
9
9
  * line back.
10
+ *
11
+ * Clipy Local (the open-source local edition) runs the same bridge and writes
12
+ * ~/Library/Application Support/Clipy Local/agent-bridge.json with
13
+ * `edition: "local"`. Only `--local` commands read that file, and they never
14
+ * read the official app's: the official app uploads, Clipy Local never does.
10
15
  */
11
16
  import { readFileSync, statSync } from "node:fs";
12
17
  import { homedir } from "node:os";
@@ -17,6 +22,9 @@ export class BridgeUnavailableError extends Error {
17
22
  const REQUEST_TIMEOUT_MS = 15_000;
18
23
  /** stop waits for the streaming upload to hand back the share link. */
19
24
  const STOP_TIMEOUT_MS = 200_000;
25
+ /** Clipy Local's stop waits up to 300 s for the take to be processed. */
26
+ const LOCAL_STOP_TIMEOUT_MS = 330_000;
27
+ export const LOCAL_APP_HINT = "Open Clipy Local (build it from the open-source Clipy repository), or record with the CLI's own recorder: clipy record --local --max 60";
20
28
  /** The oldest Clipy Mac app version that ships the agent bridge this CLI drives.
21
29
  * Older builds either don't write the discovery file at all or wrote it to a
22
30
  * path the CLI never read (the pre-0.1.41 bundle-id location), so `--source
@@ -24,11 +32,25 @@ const STOP_TIMEOUT_MS = 200_000;
24
32
  * stale/missing-bridge errors below. */
25
33
  export const MIN_BRIDGE_APP_VERSION = "0.1.41";
26
34
  const UPDATE_HINT = "your installed Clipy app may predate the agent bridge — update via https://clipy.online/download";
27
- export function bridgeFilePath() {
35
+ export function bridgeFilePath(edition = "cloud") {
36
+ if (edition === "local") {
37
+ if (process.env.CLIPY_LOCAL_BRIDGE_FILE?.trim())
38
+ return process.env.CLIPY_LOCAL_BRIDGE_FILE;
39
+ return join(homedir(), "Library", "Application Support", "Clipy Local", "agent-bridge.json");
40
+ }
28
41
  if (process.env.CLIPY_BRIDGE_FILE?.trim())
29
42
  return process.env.CLIPY_BRIDGE_FILE;
30
43
  return join(homedir(), "Library", "Application Support", "Clipy", "agent-bridge.json");
31
44
  }
45
+ /** Whether an app could answer for this edition here: macOS, or an explicit file. */
46
+ export function bridgeApplicable(edition, platform = process.platform) {
47
+ const override = edition === "local" ? process.env.CLIPY_LOCAL_BRIDGE_FILE : process.env.CLIPY_BRIDGE_FILE;
48
+ return platform === "darwin" || !!override?.trim();
49
+ }
50
+ /** How errors name the app on the other end of the socket. */
51
+ export function bridgeAppName(info) {
52
+ return info.edition === "local" ? "Clipy Local" : "the Clipy app";
53
+ }
32
54
  /** Numeric-dotted version compare: a<b → -1, a==b → 0, a>b → 1. Missing/short
33
55
  * parts count as 0 (so "0.1" == "0.1.0"). */
34
56
  export function compareVersions(a, b) {
@@ -63,7 +85,9 @@ function pidAlive(pid) {
63
85
  * diagnostic one-liner (file path, pid + liveness, appVersion, and an update
64
86
  * hint when the app looks too old) so an agent hitting a dead end can see what
65
87
  * was actually found and self-correct. */
66
- export function readBridgeInfo() {
88
+ export function readBridgeInfo(edition = "cloud") {
89
+ if (edition === "local")
90
+ return readLocalBridgeInfo();
67
91
  const path = bridgeFilePath();
68
92
  if (process.platform !== "darwin" && !process.env.CLIPY_BRIDGE_FILE) {
69
93
  throw new BridgeUnavailableError("--source mac-screen records through the Clipy Mac app, which only runs on macOS.");
@@ -104,7 +128,44 @@ export function readBridgeInfo() {
104
128
  `${info.appVersion ? `, appVersion ${info.appVersion}` : ""} — the Clipy app has quit. ` +
105
129
  `Open Clipy and try again.`);
106
130
  }
107
- return info;
131
+ if (info.edition === "local") {
132
+ // Clipy Local never writes this path; only a CLIPY_BRIDGE_FILE pointed at
133
+ // its file gets here. Its takes stay on this computer, so say --local.
134
+ throw new BridgeUnavailableError(`the agent bridge at ${path} is Clipy Local's, which keeps recordings on this computer and never uploads. Add --local.`);
135
+ }
136
+ return { ...info, edition: "cloud" };
137
+ }
138
+ /** readBridgeInfo for Clipy Local: its own discovery file, never the official app's. */
139
+ function readLocalBridgeInfo() {
140
+ const path = bridgeFilePath("local");
141
+ if (!bridgeApplicable("local")) {
142
+ throw new BridgeUnavailableError("--source mac-screen with --local records through Clipy Local, which runs on macOS. Record with the CLI's own recorder instead: clipy record --local --max 60");
143
+ }
144
+ let raw;
145
+ try {
146
+ raw = readFileSync(path, "utf8");
147
+ }
148
+ catch {
149
+ throw new BridgeUnavailableError(`Clipy Local is not running: no agent bridge file at ${path}. ${LOCAL_APP_HINT}.`);
150
+ }
151
+ let info;
152
+ try {
153
+ info = JSON.parse(raw);
154
+ }
155
+ catch {
156
+ throw new BridgeUnavailableError(`the agent bridge file at ${path} is corrupt (unparseable JSON). Restart Clipy Local.`);
157
+ }
158
+ if (!info.socketPath || !info.token || typeof info.pid !== "number") {
159
+ throw new BridgeUnavailableError(`the agent bridge file at ${path} is incomplete (missing socketPath, token or pid). Restart Clipy Local.`);
160
+ }
161
+ if (info.edition !== "local") {
162
+ // Never drive an app that uploads from a --local command.
163
+ throw new BridgeUnavailableError(`the agent bridge at ${path} is not Clipy Local's (edition ${info.edition ?? "cloud"}), and --local never records through an app that uploads. ${LOCAL_APP_HINT}.`);
164
+ }
165
+ if (!pidAlive(info.pid)) {
166
+ throw new BridgeUnavailableError(`Clipy Local has quit (pid ${info.pid} in ${path} is not running). ${LOCAL_APP_HINT}.`);
167
+ }
168
+ return { ...info, appVersion: typeof info.appVersion === "string" ? info.appVersion : "" };
108
169
  }
109
170
  /** Full BridgeInfo (INCLUDING the token) straight from the discovery file,
110
171
  * skipping the liveness/version gating readBridgeInfo does — for the doctor
@@ -344,7 +405,9 @@ export function resolveFromSources(sources, opts) {
344
405
  }
345
406
  /** One request line in, one response line out. */
346
407
  export function bridgeRequest(info, cmd, args = {}) {
347
- const timeoutMs = cmd === "stop" ? STOP_TIMEOUT_MS : REQUEST_TIMEOUT_MS;
408
+ const local = info.edition === "local";
409
+ const app = bridgeAppName(info);
410
+ const timeoutMs = cmd === "stop" ? (local ? LOCAL_STOP_TIMEOUT_MS : STOP_TIMEOUT_MS) : REQUEST_TIMEOUT_MS;
348
411
  return new Promise((resolvePromise, reject) => {
349
412
  const socket = createConnection({ path: info.socketPath });
350
413
  let buffer = "";
@@ -354,8 +417,12 @@ export function bridgeRequest(info, cmd, args = {}) {
354
417
  settled = true;
355
418
  socket.destroy();
356
419
  reject(new Error(cmd === "stop"
357
- ? "the Clipy app did not finish the upload in time — check the app; the recording may still complete in the background"
358
- : `the Clipy app did not answer (${cmd}) — is it responding?`));
420
+ ? local
421
+ ? "Clipy Local did not finish processing in time. Check the app; the take is still being processed and its recording.arec updates in place"
422
+ : "the Clipy app did not finish the upload in time — check the app; the recording may still complete in the background"
423
+ : local
424
+ ? `Clipy Local did not answer (${cmd}). Is it responding?`
425
+ : `the Clipy app did not answer (${cmd}) — is it responding?`));
359
426
  }
360
427
  }, timeoutMs);
361
428
  socket.on("error", (e) => {
@@ -364,7 +431,9 @@ export function bridgeRequest(info, cmd, args = {}) {
364
431
  settled = true;
365
432
  clearTimeout(timer);
366
433
  reject(e.code === "ENOENT" || e.code === "ECONNREFUSED"
367
- ? new BridgeUnavailableError("the Clipy app is not running (agent bridge socket unavailable). Open Clipy and try again.")
434
+ ? new BridgeUnavailableError(local
435
+ ? `Clipy Local is not running (agent bridge socket unavailable). ${LOCAL_APP_HINT}.`
436
+ : "the Clipy app is not running (agent bridge socket unavailable). Open Clipy and try again.")
368
437
  : e);
369
438
  });
370
439
  socket.on("connect", () => {
@@ -390,14 +459,14 @@ export function bridgeRequest(info, cmd, args = {}) {
390
459
  }
391
460
  }
392
461
  catch {
393
- reject(new Error("unparseable response from the Clipy app bridge"));
462
+ reject(new Error(`unparseable response from the ${local ? "Clipy Local" : "Clipy app"} bridge`));
394
463
  }
395
464
  });
396
465
  socket.on("close", () => {
397
466
  if (!settled) {
398
467
  settled = true;
399
468
  clearTimeout(timer);
400
- reject(new Error("the Clipy app closed the bridge connection unexpectedly"));
469
+ reject(new Error(`${app} closed the bridge connection unexpectedly`));
401
470
  }
402
471
  });
403
472
  });