@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,1103 @@
1
+ /**
2
+ * Local mode for the official CLI: `--local` on record, session, proof and
3
+ * context import, plus `clipy local setup|status` and `clipy models`.
4
+ *
5
+ * With --local nothing is uploaded and no Clipy account is needed. Instead of
6
+ * "upload, then the server transcribes and picks moments", the CLI runs the
7
+ * local pipeline (pipeline.ts): transcribe on this machine or with the user's
8
+ * own key, pick moments with rules (plus the user's model provider when one
9
+ * is set), extract frames with ffmpeg and write an AREC 1.4 folder. The last
10
+ * line printed is the absolute path of recording.arec (a JSON object with
11
+ * --json).
12
+ *
13
+ * Everything here takes its dependencies (`LocalEnv`) as an argument, so the
14
+ * tests drive it with fakes and never touch a screen, a model or the network.
15
+ */
16
+ import { existsSync, realpathSync } from "node:fs";
17
+ import { copyFile, mkdir, readdir, rename, rm, rmdir, stat } from "node:fs/promises";
18
+ import { homedir } from "node:os";
19
+ import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
20
+ import { createInterface } from "node:readline";
21
+ import { shareLine } from "./arec.js";
22
+ import { hasAudioStream } from "./media.js";
23
+ import { processRecording } from "./pipeline.js";
24
+ import { ensureSpeechEngine, realSpeechEngine, SPEECH_ENGINE_INSTALL_COMMAND, SPEECH_ENGINE_PACKAGE, SPEECH_ENGINE_SIZE, SPEECH_ENGINE_VERSION, SpeechEngineRequiredError, } from "./speechEngine.js";
25
+ export { SpeechEngineRequiredError } from "./speechEngine.js";
26
+ export class UsageError extends Error {
27
+ constructor(message) {
28
+ super(message);
29
+ this.name = "UsageError";
30
+ }
31
+ }
32
+ export const MODEL_PROVIDERS = ["openrouter", "openai", "gemini", "groq", "ollama", "lmstudio", "custom", "none"];
33
+ export const TRANSCRIBERS = [
34
+ "local-english",
35
+ "local-multilingual",
36
+ "openai",
37
+ "groq",
38
+ "deepgram",
39
+ "assemblyai",
40
+ "elevenlabs",
41
+ "gemini",
42
+ "none",
43
+ ];
44
+ export const LOCAL_MODELS = ["english-fast", "multilingual"];
45
+ /** Model presets that need no key, so `setup` can check them before saving. */
46
+ const KEYLESS_PRESETS = new Set(["ollama", "lmstudio", "custom"]);
47
+ /** Signals that stop a recording (or cancel the work after it) instead of killing the CLI mid-capture. */
48
+ export const STOP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
49
+ /** Reads one answer from the terminal; Ctrl-C or a closed stdin counts as no. */
50
+ function askTerminal(question) {
51
+ return new Promise((resolveAnswer) => {
52
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
53
+ let settled = false;
54
+ const done = (yes) => {
55
+ if (settled)
56
+ return;
57
+ settled = true;
58
+ rl.close();
59
+ resolveAnswer(yes);
60
+ };
61
+ rl.on("SIGINT", () => {
62
+ process.stderr.write("\n");
63
+ done(false);
64
+ });
65
+ rl.on("close", () => done(false));
66
+ rl.question(question, (answer) => done(/^(y|yes)?$/i.test(answer.trim())));
67
+ });
68
+ }
69
+ export function processIo() {
70
+ const canAsk = process.stdin.isTTY === true && process.stderr.isTTY === true;
71
+ return {
72
+ stdout: (t) => process.stdout.write(t),
73
+ stderr: (t) => process.stderr.write(t),
74
+ stdinIsTTY: process.stdin.isTTY === true,
75
+ ...(canAsk ? { confirm: askTerminal } : {}),
76
+ waitForStop(maxMs) {
77
+ return new Promise((resolveStop) => {
78
+ const stdin = process.stdin;
79
+ // A pipe or file on stdin that closes (an agent's shell ending, say)
80
+ // leaves nobody to press Enter: stop then instead of recording
81
+ // forever. With --max the take ends on its own, so stdin is ignored.
82
+ const stopOnEnd = maxMs === undefined && stdin.isTTY !== true;
83
+ let timer;
84
+ const done = (why) => {
85
+ if (timer)
86
+ clearTimeout(timer);
87
+ for (const sig of STOP_SIGNALS)
88
+ process.off(sig, onSignal);
89
+ stdin.off("data", onData);
90
+ stdin.off("end", onEnd);
91
+ stdin.pause();
92
+ resolveStop(why);
93
+ };
94
+ const onSignal = () => done("user");
95
+ const onEnd = () => done("user");
96
+ const onData = (chunk) => {
97
+ if (String(chunk).includes("\n") || String(chunk).includes("\r"))
98
+ done("user");
99
+ };
100
+ for (const sig of STOP_SIGNALS)
101
+ process.on(sig, onSignal);
102
+ stdin.on("data", onData);
103
+ if (stopOnEnd) {
104
+ if (stdin.readableEnded) {
105
+ done("user");
106
+ return;
107
+ }
108
+ stdin.on("end", onEnd);
109
+ }
110
+ stdin.resume();
111
+ if (maxMs !== undefined)
112
+ timer = setTimeout(() => done("max"), maxMs);
113
+ });
114
+ },
115
+ onInterrupt(onInterrupt) {
116
+ const handler = () => onInterrupt();
117
+ for (const sig of STOP_SIGNALS)
118
+ process.on(sig, handler);
119
+ return () => {
120
+ for (const sig of STOP_SIGNALS)
121
+ process.off(sig, handler);
122
+ };
123
+ },
124
+ };
125
+ }
126
+ /** The real environment: vendored packages, loaded on first use. */
127
+ export async function realLocalEnv(version, options = {}) {
128
+ const { realDeps } = await import("./deps.js");
129
+ let cache = null;
130
+ return {
131
+ deps: () => (cache ??= realDeps()),
132
+ io: processIo(),
133
+ now: () => new Date(),
134
+ version,
135
+ speech: realSpeechEngine(),
136
+ assumeYes: options.assumeYes === true,
137
+ };
138
+ }
139
+ // ---- Output folder and results ---------------------------------------------
140
+ /** `~/clipy/recordings/YYYY-MM-DD-HHMMSS`, local time. */
141
+ export function defaultOutDir(now, home = homedir()) {
142
+ const p = (n) => String(n).padStart(2, "0");
143
+ const stamp = `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`;
144
+ return join(home, "clipy", "recordings", stamp);
145
+ }
146
+ /** `--out` as given, or a fresh default folder (a suffix keeps two takes in one second apart). */
147
+ export function resolveOutDir(out, env) {
148
+ if (out && out.trim())
149
+ return resolve(out.trim());
150
+ const base = defaultOutDir(env.now(), env.home ?? homedir());
151
+ if (!existsSync(base))
152
+ return base;
153
+ for (let i = 2;; i++) {
154
+ const candidate = `${base}-${i}`;
155
+ if (!existsSync(candidate))
156
+ return candidate;
157
+ }
158
+ }
159
+ /** Recordings are private: take folders are readable by their owner only. */
160
+ export const TAKE_DIR_MODE = 0o700;
161
+ /** What a local take writes into its folder, so `--force` can clear exactly that. */
162
+ const TAKE_FILES = ["frames", "transcript.json", "moments.json", "frames.json", "metadata.json", "status.json"];
163
+ function isTakeFile(name) {
164
+ const base = name.endsWith(".tmp") ? name.slice(0, -4) : name;
165
+ return base.startsWith("recording.") || TAKE_FILES.includes(base);
166
+ }
167
+ /**
168
+ * Claims the folder a take writes to, before anything is recorded:
169
+ *
170
+ * - no `--out`: a fresh dated folder, created here. Creating it is the claim,
171
+ * so two takes started in the same second get `<stamp>` and `<stamp>-2`.
172
+ * - `--out` that is missing or empty: created (mode 0700) and used.
173
+ * - `--out` holding files: refused with a UsageError, unless `force`, which
174
+ * clears the previous take's files (and only those) first.
175
+ * - `claimed`: the folder was claimed earlier by this same take (a session
176
+ * claims it at start and writes it at stop), so it is used as it is.
177
+ * - `inputs`: files the take reads (an imported video, proof frames). An
178
+ * `--out` that contains one is refused, with or without `force`, so
179
+ * clearing or writing the take can never replace its own input.
180
+ */
181
+ export async function claimOutDir(out, env, opts = {}) {
182
+ if (out && out.trim()) {
183
+ const dir = resolve(out.trim());
184
+ for (const input of opts.inputs ?? []) {
185
+ if (isInside(realOrResolved(input), realOrResolved(dir))) {
186
+ throw new UsageError(`--out ${dir} contains the input ${resolve(input)}. Choose an --out folder that does not hold the files being imported.`);
187
+ }
188
+ }
189
+ if (opts.claimed) {
190
+ await mkdir(dir, { recursive: true, mode: TAKE_DIR_MODE });
191
+ return dir;
192
+ }
193
+ let entries = [];
194
+ try {
195
+ const info = await stat(dir);
196
+ if (!info.isDirectory())
197
+ throw new UsageError(`--out ${dir} is a file, not a folder`);
198
+ entries = await readdir(dir);
199
+ }
200
+ catch (error) {
201
+ if (error instanceof UsageError)
202
+ throw error;
203
+ if (error.code !== "ENOENT")
204
+ throw error;
205
+ }
206
+ if (entries.length > 0) {
207
+ if (!opts.force) {
208
+ throw new UsageError(`--out ${dir} is not empty. Choose a new or empty folder, or add --force to replace the take that is there.`);
209
+ }
210
+ for (const name of entries) {
211
+ if (isTakeFile(name))
212
+ await rm(join(dir, name), { recursive: true, force: true });
213
+ }
214
+ }
215
+ await mkdir(dir, { recursive: true, mode: TAKE_DIR_MODE });
216
+ return dir;
217
+ }
218
+ const base = defaultOutDir(env.now(), env.home ?? homedir());
219
+ await mkdir(dirname(base), { recursive: true });
220
+ for (let i = 1;; i++) {
221
+ const candidate = i === 1 ? base : `${base}-${i}`;
222
+ try {
223
+ // Not recursive: if another take created this folder first, EEXIST moves on.
224
+ await mkdir(candidate, { mode: TAKE_DIR_MODE });
225
+ return candidate;
226
+ }
227
+ catch (error) {
228
+ if (error.code !== "EEXIST")
229
+ throw error;
230
+ }
231
+ }
232
+ }
233
+ /** The real path when it exists (symlinks resolved), else the resolved path. */
234
+ function realOrResolved(path) {
235
+ try {
236
+ return realpathSync(path);
237
+ }
238
+ catch {
239
+ return resolve(path);
240
+ }
241
+ }
242
+ /** True when `path` is `dir` itself or anything below it. */
243
+ function isInside(path, dir) {
244
+ const rel = relative(dir, path);
245
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
246
+ }
247
+ /** Removes a claimed folder that is still empty (a take that failed before writing anything). */
248
+ export async function releaseOutDir(dir) {
249
+ try {
250
+ if ((await readdir(dir)).length === 0)
251
+ await rmdir(dir);
252
+ }
253
+ catch {
254
+ // best-effort
255
+ }
256
+ }
257
+ /**
258
+ * The checks that used to fail only after a capture had finished, run first:
259
+ * the config file and model provider (loadConfig resolves the provider and
260
+ * throws when a key is missing), ffmpeg, and the output folder. A capture that
261
+ * starts after this cannot be lost to any of them.
262
+ */
263
+ export async function prepareLocalTake(opts, env) {
264
+ const config = env.deps().loadConfig();
265
+ const ffmpeg = await ffmpegPath(env.deps);
266
+ if (!ffmpeg) {
267
+ throw new Error("ffmpeg was not found. Install ffmpeg (or set CLIPY_FFMPEG to its path) and try again; clipy local status shows what is missing.");
268
+ }
269
+ if (opts.speech)
270
+ await ensureEngineForTake(config, env, { json: opts.json === true, ffmpeg, file: opts.speechFile });
271
+ const dir = await claimOutDir(opts.out, env, { force: opts.force, claimed: opts.claimed, inputs: opts.inputs });
272
+ return { dir, config, ffmpeg };
273
+ }
274
+ /**
275
+ * On-device transcription with a downloaded model needs the speech engine:
276
+ * asked for (or refused) here, before anything is recorded. Without the model
277
+ * there is nothing to ask yet: the take records a transcript gap that says to
278
+ * run clipy models download, as before.
279
+ */
280
+ async function ensureEngineForTake(config, env, opts) {
281
+ if (!env.speech || config.transcription.kind !== "local")
282
+ return;
283
+ const model = config.transcription.model;
284
+ try {
285
+ if (!env.deps().modelStatus(model).installed)
286
+ return;
287
+ }
288
+ catch {
289
+ return;
290
+ }
291
+ if (env.speech.status().installed)
292
+ return;
293
+ // A file with no audio track is never transcribed (the pipeline records the
294
+ // gap), so it must not cost a download or a refusal. A probe that fails
295
+ // leaves the question to the take.
296
+ if (opts.file && !(await hasAudioStream(opts.ffmpeg, opts.file).catch(() => true)))
297
+ return;
298
+ const json = opts.json;
299
+ const controller = new AbortController();
300
+ const dispose = env.io.onInterrupt(() => controller.abort(new Error("Cancelled")));
301
+ try {
302
+ await ensureSpeechEngine(env.speech, env.io, { json, assumeYes: env.assumeYes, signal: controller.signal });
303
+ }
304
+ finally {
305
+ dispose();
306
+ }
307
+ }
308
+ /**
309
+ * A local take that failed after its capture finished. The capture is never
310
+ * deleted: `keptPath` is where it is now, and the message says so.
311
+ */
312
+ export class LocalTakeError extends Error {
313
+ keptPath;
314
+ reason;
315
+ constructor(reason, keptPath) {
316
+ super(keptPath ? `${reason}\nThe capture was kept at ${keptPath}` : reason);
317
+ this.name = "LocalTakeError";
318
+ this.reason = reason;
319
+ this.keptPath = keptPath;
320
+ }
321
+ }
322
+ /**
323
+ * After a failed take: the capture is either already in the folder
324
+ * (recording.mp4, placed before the failure) or still where the recorder left
325
+ * it, in which case it is moved into the folder as recording.<ext>.
326
+ */
327
+ export async function keepCapture(videoPath, dir, moved) {
328
+ if (!moved)
329
+ return null; // an imported or supplied file was never touched
330
+ // The source still existing means placing it never finished (placeVideo
331
+ // removes it only after recording.mp4 is complete), so the source is the
332
+ // intact capture: keep it, whatever else is in the folder.
333
+ if (!existsSync(videoPath)) {
334
+ const placed = join(dir, "recording.mp4");
335
+ return existsSync(placed) ? placed : null;
336
+ }
337
+ const target = join(dir, `recording${extname(videoPath) || ".mp4"}`);
338
+ try {
339
+ await mkdir(dir, { recursive: true, mode: TAKE_DIR_MODE });
340
+ try {
341
+ await rename(videoPath, target);
342
+ }
343
+ catch {
344
+ await copyFile(videoPath, target);
345
+ await rm(videoPath, { force: true });
346
+ }
347
+ return target;
348
+ }
349
+ catch {
350
+ return videoPath;
351
+ }
352
+ }
353
+ export function resultJson(result, extra = {}) {
354
+ return {
355
+ ok: true,
356
+ local: true,
357
+ arec: result.arecPath,
358
+ dir: result.dir,
359
+ video: join(result.dir, "recording.mp4"),
360
+ durationMs: result.durationMs,
361
+ moments: result.moments,
362
+ frames: result.frames,
363
+ planner: result.planner,
364
+ modelFallback: result.modelFallback,
365
+ transcript: { engine: result.transcriptEngine, segments: result.transcriptSegments },
366
+ warnings: result.warnings,
367
+ ...extra,
368
+ };
369
+ }
370
+ /** The end of every local take: the AREC path last on stdout, or one JSON object. */
371
+ export function printLocalResult(result, json, io, extra = {}) {
372
+ for (const warning of result.warnings)
373
+ io.stderr(`Warning: ${warning}\n`);
374
+ if (json) {
375
+ io.stdout(`${JSON.stringify(resultJson(result, extra))}\n`);
376
+ return;
377
+ }
378
+ io.stderr(`Done: ${result.frames} screenshot${result.frames === 1 ? "" : "s"}, ${result.transcriptSegments} transcript segment${result.transcriptSegments === 1 ? "" : "s"}. Nothing was uploaded. Give your AI agent the path below.\n${shareLine(join(result.dir, "recording.mp4"))}\n`);
379
+ io.stdout(`${result.arecPath}\n`);
380
+ }
381
+ /** A failed local command: one JSON object with --json, a message on stderr always. */
382
+ export function printLocalError(error, json, io) {
383
+ const message = error instanceof Error ? error.message : String(error);
384
+ if (json) {
385
+ const kept = error instanceof LocalTakeError && error.keptPath ? { error: error.reason, keptVideo: error.keptPath } : { error: message };
386
+ const code = error instanceof SpeechEngineRequiredError
387
+ ? { code: error.code, remediation: `run ${error.command} (downloads ${SPEECH_ENGINE_PACKAGE} ${SPEECH_ENGINE_VERSION} from npm, ${SPEECH_ENGINE_SIZE}), or re-run with --yes` }
388
+ : {};
389
+ io.stdout(`${JSON.stringify({ ok: false, local: true, ...kept, ...code })}\n`);
390
+ }
391
+ io.stderr(`clipy: ${message}\n`);
392
+ }
393
+ const STAGE_TEXT = {
394
+ transcribing: "Transcribing",
395
+ selecting: "Selecting moments",
396
+ extracting: "Extracting frames",
397
+ ready: "Ready",
398
+ failed: "Failed",
399
+ };
400
+ async function ffmpegPath(deps) {
401
+ if (process.env.CLIPY_FFMPEG)
402
+ return process.env.CLIPY_FFMPEG;
403
+ try {
404
+ return (await deps().checkCapture()).ffmpeg ?? undefined;
405
+ }
406
+ catch {
407
+ return undefined;
408
+ }
409
+ }
410
+ /**
411
+ * Runs the local pipeline on a finished video and returns the result (printing
412
+ * is up to the caller). A failure throws a LocalTakeError that says where the
413
+ * capture was kept: a capture is never deleted because processing failed.
414
+ */
415
+ export async function runLocalTake(req, env) {
416
+ let prepared = req.prepared;
417
+ if (!prepared) {
418
+ try {
419
+ // An import reads its video in place; a capture's video is a temp file moved in.
420
+ const inputs = req.moveVideo ? [] : [req.videoPath];
421
+ // A session's folder was claimed, and the engine settled, at `session start`.
422
+ const speech = !req.transcript && !req.outClaimed;
423
+ prepared = await prepareLocalTake({ out: req.out, force: req.force, claimed: req.outClaimed, inputs, speech, speechFile: req.videoPath, json: req.json }, env);
424
+ }
425
+ catch (error) {
426
+ if (error instanceof UsageError || !req.moveVideo)
427
+ throw error;
428
+ // A capture that reached here unprepared must still survive.
429
+ const kept = existsSync(req.videoPath) ? req.videoPath : null;
430
+ throw new LocalTakeError(error instanceof Error ? error.message : String(error), kept);
431
+ }
432
+ }
433
+ const { dir, config, ffmpeg } = prepared;
434
+ const quiet = req.quiet ?? req.json;
435
+ const onStatus = (s) => {
436
+ if (!quiet && s.stage !== "ready" && s.stage !== "failed")
437
+ env.io.stderr(`${STAGE_TEXT[s.stage]}...\n`);
438
+ };
439
+ const controller = new AbortController();
440
+ const dispose = env.io.onInterrupt(() => controller.abort(new Error("Cancelled")));
441
+ try {
442
+ return await processRecording({
443
+ dir,
444
+ videoPath: req.videoPath,
445
+ moveVideo: req.moveVideo,
446
+ interactions: req.interactions ?? null,
447
+ geometry: req.geometry,
448
+ durationMs: req.durationMs,
449
+ captureWarnings: req.captureWarnings,
450
+ deps: env.deps(),
451
+ config,
452
+ transcript: req.transcript ?? null,
453
+ narration: req.narration ?? [],
454
+ title: req.title,
455
+ description: req.description,
456
+ expectedResult: req.expectedResult,
457
+ recordingKind: req.recordingKind,
458
+ compiler: `clipy ${env.version} --local`,
459
+ origin: req.origin,
460
+ ffmpegPath: ffmpeg,
461
+ signal: controller.signal,
462
+ onStatus,
463
+ now: env.now,
464
+ });
465
+ }
466
+ catch (error) {
467
+ const reason = error instanceof Error ? error.message : String(error);
468
+ throw new LocalTakeError(reason, await keepCapture(req.videoPath, dir, req.moveVideo === true));
469
+ }
470
+ finally {
471
+ dispose();
472
+ }
473
+ }
474
+ /**
475
+ * Records the screen with the vendored capture package until Enter, Ctrl-C or
476
+ * --max, then builds the AREC. Returns the exit code.
477
+ */
478
+ export async function localCaptureRecord(opts, env) {
479
+ const { io } = env;
480
+ let display = null;
481
+ let prepared;
482
+ // Config, provider, ffmpeg and --out are checked before anything is
483
+ // recorded, so a mistake there never costs a take.
484
+ try {
485
+ // Only the microphone gives this recorder an audio track.
486
+ prepared = await prepareLocalTake({ out: opts.out, force: opts.force, speech: opts.mic, json: opts.json }, env);
487
+ }
488
+ catch (error) {
489
+ printLocalError(error, opts.json, io);
490
+ return error instanceof UsageError ? 2 : 1;
491
+ }
492
+ const { dir } = prepared;
493
+ let recording = false;
494
+ // A signal while Xvfb or the capture is starting must not kill the CLI
495
+ // (that would skip the capture package's cleanup): note it, and stop as
496
+ // soon as the capture is up.
497
+ let stopEarly = false;
498
+ let releaseEarly = io.onInterrupt(() => {
499
+ stopEarly = true;
500
+ });
501
+ try {
502
+ if (opts.virtualDisplay) {
503
+ display = await env.deps().startVirtualDisplay(opts.virtualDisplay);
504
+ const auth = display.xauthority ? ` XAUTHORITY=${display.xauthority}` : "";
505
+ io.stderr(`Virtual display ${display.display}: launch apps there with DISPLAY=${display.display}${auth}. It closes when the recording ends.\n`);
506
+ for (const warning of display.warnings ?? [])
507
+ io.stderr(`Warning: ${warning}\n`);
508
+ }
509
+ const session = await env.deps().startCapture({
510
+ source: opts.source,
511
+ outPath: join(dir, "recording.mp4"),
512
+ maxSeconds: opts.maxSeconds,
513
+ microphone: opts.mic,
514
+ xDisplay: display?.display,
515
+ });
516
+ recording = true;
517
+ releaseEarly();
518
+ releaseEarly = null;
519
+ io.stderr(`Recording${opts.maxSeconds ? ` (stops after ${opts.maxSeconds} s)` : ""}. Press Enter or Ctrl-C to stop. Nothing is uploaded.\n`);
520
+ if (opts.maxSeconds === undefined && io.stdinIsTTY === false) {
521
+ io.stderr("Warning: stdin is not a terminal and there is no --max, so the recording stops when stdin closes or on Ctrl-C, SIGTERM or SIGHUP. Add --max <sec> to bound it.\n");
522
+ }
523
+ if (!stopEarly)
524
+ await io.waitForStop(opts.maxSeconds !== undefined ? opts.maxSeconds * 1000 : undefined);
525
+ io.stderr("Stopping...\n");
526
+ // A second Ctrl-C or SIGTERM while the capture is being finalized must not
527
+ // kill the CLI and strand ffmpeg or the virtual display.
528
+ const holdSignals = io.onInterrupt(() => io.stderr("Still stopping; the take is being finalized.\n"));
529
+ let captured;
530
+ try {
531
+ captured = await session.stop();
532
+ for (const warning of captured.warnings)
533
+ io.stderr(`Warning: ${warning}\n`);
534
+ await display?.stop();
535
+ display = null;
536
+ }
537
+ finally {
538
+ holdSignals();
539
+ }
540
+ const result = await runLocalTake({
541
+ videoPath: captured.path,
542
+ moveVideo: true,
543
+ prepared,
544
+ title: opts.title ?? "Screen recording",
545
+ description: opts.description,
546
+ expectedResult: opts.expectedResult,
547
+ recordingKind: opts.recordingKind,
548
+ narration: opts.narration,
549
+ interactions: captured.interactions,
550
+ geometry: captured.geometry,
551
+ durationMs: captured.durationMs,
552
+ captureWarnings: captured.warnings,
553
+ origin: { kind: "capture", ...(opts.source ? { sourceName: opts.source } : opts.virtualDisplay ? { sourceName: "a virtual display" } : {}) },
554
+ json: opts.json,
555
+ }, env);
556
+ printLocalResult(result, opts.json, io, { source: { kind: "screen", ...(opts.source ? { id: opts.source } : {}) } });
557
+ return 0;
558
+ }
559
+ catch (error) {
560
+ const video = join(dir, "recording.mp4");
561
+ if (recording && !(error instanceof LocalTakeError) && existsSync(video)) {
562
+ // The capture failed to stop cleanly; whatever it wrote stays.
563
+ printLocalError(new LocalTakeError(error instanceof Error ? error.message : String(error), video), opts.json, io);
564
+ }
565
+ else {
566
+ printLocalError(error, opts.json, io);
567
+ }
568
+ return 1;
569
+ }
570
+ finally {
571
+ releaseEarly?.();
572
+ await display?.stop().catch(() => undefined);
573
+ // Belt and braces: nothing the capture package started outlives the take.
574
+ try {
575
+ env.deps().stopAllChildren?.();
576
+ }
577
+ catch {
578
+ // best-effort
579
+ }
580
+ if (!recording)
581
+ await releaseOutDir(dir);
582
+ }
583
+ }
584
+ /** `clipy sources --local`: what the capture package can record here. */
585
+ export async function localSources(json, env) {
586
+ try {
587
+ const sources = await env.deps().listSources();
588
+ if (json)
589
+ env.io.stdout(`${JSON.stringify({ ok: true, local: true, sources })}\n`);
590
+ else if (sources.length === 0)
591
+ env.io.stdout("No sources found. Run clipy local status.\n");
592
+ else {
593
+ for (const s of sources) {
594
+ env.io.stdout(`${s.id}\t${s.kind}\t${s.name}${s.width && s.height ? `\t${s.width}x${s.height}` : ""}\n`);
595
+ }
596
+ }
597
+ return 0;
598
+ }
599
+ catch (error) {
600
+ printLocalError(error, json, env.io);
601
+ return 1;
602
+ }
603
+ }
604
+ /** Throws a UsageError for a combination `clipy local setup` cannot save. */
605
+ export function validateSetupFlags(flags) {
606
+ const provider = flags.modelProvider;
607
+ if (provider !== undefined && !MODEL_PROVIDERS.includes(provider)) {
608
+ throw new UsageError(`Unknown model provider ${provider}. Choose one of: ${MODEL_PROVIDERS.join(", ")}.`);
609
+ }
610
+ if (provider === "custom" && (!flags.baseUrl || !flags.model)) {
611
+ throw new UsageError("--model-provider custom needs --base-url and --model");
612
+ }
613
+ if (provider === undefined && (flags.modelKey || flags.model || flags.baseUrl)) {
614
+ throw new UsageError("--model-key, --model and --base-url go with --model-provider");
615
+ }
616
+ const transcribe = flags.transcribe;
617
+ if (transcribe !== undefined && !TRANSCRIBERS.includes(transcribe)) {
618
+ throw new UsageError(`Unknown transcription engine ${transcribe}. Choose one of: ${TRANSCRIBERS.join(", ")}.`);
619
+ }
620
+ if (transcribe === undefined && flags.transcribeKey)
621
+ throw new UsageError("--transcribe-key goes with --transcribe");
622
+ if (transcribe && !["local-english", "local-multilingual", "none"].includes(transcribe) && !flags.transcribeKey) {
623
+ throw new UsageError(`--transcribe ${transcribe} needs --transcribe-key (use --transcribe-key - to read it from stdin), or leave the file alone and set CLIPY_TRANSCRIBE=${transcribe} and CLIPY_TRANSCRIBE_API_KEY in your environment`);
624
+ }
625
+ }
626
+ /** Shown when a key was typed on the command line, where shell history and `ps` can see it. */
627
+ export const LITERAL_KEY_NOTE = "Note: a key typed on the command line can stay in your shell history and show up in the process list. " +
628
+ "Next time set CLIPY_MODEL_API_KEY or CLIPY_TRANSCRIBE_API_KEY in your environment, or pass - to read the key from stdin.";
629
+ /**
630
+ * Resolves `--model-key -` and `--transcribe-key -`: the key is read from
631
+ * stdin (one line, trimmed) so it never appears in argv. `literal` lists the
632
+ * flags that carried a key on the command line, for LITERAL_KEY_NOTE.
633
+ */
634
+ export async function resolveKeyFlags(flags, readStdin) {
635
+ if (flags.modelKey === "-" && flags.transcribeKey === "-") {
636
+ throw new UsageError("only one of --model-key and --transcribe-key can read stdin; set the other with CLIPY_MODEL_API_KEY or CLIPY_TRANSCRIBE_API_KEY");
637
+ }
638
+ const out = { literal: [] };
639
+ for (const [field, flag] of [["modelKey", "--model-key"], ["transcribeKey", "--transcribe-key"]]) {
640
+ const value = flags[field];
641
+ if (value === undefined)
642
+ continue;
643
+ if (value === "-") {
644
+ const key = (await readStdin()).split(/\r?\n/)[0]?.trim() ?? "";
645
+ if (!key)
646
+ throw new UsageError(`${flag} - reads the key from stdin, but stdin was empty`);
647
+ out[field] = key;
648
+ }
649
+ else {
650
+ out[field] = value;
651
+ if (value.trim())
652
+ out.literal.push(flag);
653
+ }
654
+ }
655
+ return out;
656
+ }
657
+ /** The first line of stdin (a pipe, a file, or typed input ended with Enter). */
658
+ export function readStdinLine(stdin = process.stdin) {
659
+ return new Promise((resolveLine, reject) => {
660
+ let text = "";
661
+ const finish = () => {
662
+ stdin.off("data", onData);
663
+ stdin.off("end", finish);
664
+ stdin.off("error", onError);
665
+ stdin.pause();
666
+ resolveLine(text);
667
+ };
668
+ const onData = (chunk) => {
669
+ text += String(chunk);
670
+ if (/[\r\n]/.test(text))
671
+ finish();
672
+ };
673
+ const onError = (error) => {
674
+ stdin.off("data", onData);
675
+ stdin.off("end", finish);
676
+ reject(error);
677
+ };
678
+ if (stdin.readableEnded) {
679
+ resolveLine("");
680
+ return;
681
+ }
682
+ stdin.on("data", onData);
683
+ stdin.on("end", finish);
684
+ stdin.on("error", onError);
685
+ stdin.resume();
686
+ });
687
+ }
688
+ /** Maps `setup --transcribe` to the transcription entry saved in the config file. */
689
+ export function transcriptionFor(choice, key) {
690
+ switch (choice) {
691
+ case "local-english":
692
+ return { kind: "local", model: "english-fast" };
693
+ case "local-multilingual":
694
+ return { kind: "local", model: "multilingual" };
695
+ case "openai":
696
+ case "groq":
697
+ case "deepgram":
698
+ case "assemblyai":
699
+ case "elevenlabs":
700
+ case "gemini":
701
+ return { kind: choice, apiKey: key ?? "" };
702
+ default:
703
+ return { kind: "none" };
704
+ }
705
+ }
706
+ /** Maps `setup --model-provider` and its flags to the model entry saved in the config file. */
707
+ export function storedModelFor(preset, flags) {
708
+ if (preset === "none")
709
+ return null;
710
+ return {
711
+ preset,
712
+ ...(flags.key ? { apiKey: flags.key } : {}),
713
+ ...(flags.model ? { model: flags.model } : {}),
714
+ ...(flags.baseUrl ? { baseUrl: flags.baseUrl } : {}),
715
+ };
716
+ }
717
+ function safeHost(url) {
718
+ try {
719
+ return new URL(url).host;
720
+ }
721
+ catch {
722
+ return "a custom URL";
723
+ }
724
+ }
725
+ function isLocalUrl(url) {
726
+ try {
727
+ const host = new URL(url).hostname;
728
+ return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
729
+ }
730
+ catch {
731
+ return false;
732
+ }
733
+ }
734
+ export function describeTranscription(config) {
735
+ switch (config.kind) {
736
+ case "none":
737
+ return "off";
738
+ case "local":
739
+ return `local model ${config.model} (on this machine, the audio never leaves it)`;
740
+ case "openai-compatible":
741
+ return `${config.model} at ${safeHost(config.baseUrl)}${config.apiKey ? ", key set" : ", no key"}${isLocalUrl(config.baseUrl) ? " (on this machine)" : " (the audio is sent there)"}`;
742
+ default:
743
+ return `${config.kind}${config.model ? ` (${config.model})` : ""}${config.apiKey ? ", key set" : ", no key"} (the audio is sent there)`;
744
+ }
745
+ }
746
+ export function describeProvider(provider, preset) {
747
+ if (!provider)
748
+ return "rules only, no model provider (nothing leaves this machine)";
749
+ return `${preset ?? "custom"}: ${provider.model} at ${safeHost(provider.baseUrl)}${provider.apiKey ? ", key set" : ""}${isLocalUrl(provider.baseUrl) ? " (on this machine)" : " (the transcript is sent there)"}`;
750
+ }
751
+ /** `clipy local setup`: saves the provider and transcription choices. Never prints a key. */
752
+ export function cmdLocalSetup(flags, json, env) {
753
+ const { io } = env;
754
+ try {
755
+ validateSetupFlags(flags);
756
+ const deps = env.deps();
757
+ const patch = {};
758
+ const preset = flags.modelProvider;
759
+ if (preset) {
760
+ const f = { key: flags.modelKey, model: flags.model, baseUrl: flags.baseUrl };
761
+ // Check what can be checked before saving. A hosted preset given no key may
762
+ // still get one from CLIPY_MODEL_API_KEY, which loadConfig resolves below.
763
+ if (preset !== "none" && (f.key || KEYLESS_PRESETS.has(preset))) {
764
+ deps.presetProvider(preset, f.key, f.model, f.baseUrl);
765
+ }
766
+ patch.model = storedModelFor(preset, f);
767
+ }
768
+ if (flags.transcribe)
769
+ patch.transcription = transcriptionFor(flags.transcribe, flags.transcribeKey);
770
+ const changed = Object.keys(patch).length > 0;
771
+ if (changed)
772
+ deps.saveConfig(patch);
773
+ const config = deps.loadConfig();
774
+ const report = {
775
+ ok: true,
776
+ local: true,
777
+ saved: changed,
778
+ configPath: deps.configPath(),
779
+ momentSelection: describeProvider(config.model, config.modelPreset),
780
+ transcription: describeTranscription(config.transcription),
781
+ };
782
+ if (json) {
783
+ io.stdout(`${JSON.stringify(report)}\n`);
784
+ return 0;
785
+ }
786
+ if (changed)
787
+ io.stdout(`Saved to ${report.configPath}.\n`);
788
+ io.stdout(`Moment selection: ${report.momentSelection}\n`);
789
+ io.stdout(`Transcription: ${report.transcription}\n`);
790
+ if (!changed)
791
+ io.stderr("Nothing changed. Run clipy local setup --help for the options.\n");
792
+ return 0;
793
+ }
794
+ catch (error) {
795
+ printLocalError(error, json, io);
796
+ return error instanceof UsageError ? 2 : 1;
797
+ }
798
+ }
799
+ // ---- clipy models ------------------------------------------------------------
800
+ export function parseModelsArgs(positionals) {
801
+ if ((positionals[0] === "list" || positionals[0] === undefined) && positionals.length <= 1)
802
+ return { action: "list" };
803
+ if (positionals[0] === "download" && positionals.length === 2) {
804
+ if (!LOCAL_MODELS.includes(positionals[1])) {
805
+ throw new UsageError(`Unknown model ${positionals[1]}. Choose english-fast or multilingual.`);
806
+ }
807
+ return { action: "download", model: positionals[1] };
808
+ }
809
+ throw new UsageError("usage: clipy models list, or clipy models download <english-fast|multilingual>");
810
+ }
811
+ /** Model licences, used when the vendored model table does not carry them. */
812
+ export const MODEL_LICENSES = {
813
+ "english-fast": {
814
+ license: "CC-BY-4.0",
815
+ attribution: "NVIDIA Parakeet TDT-CTC 110M, licensed CC-BY-4.0",
816
+ },
817
+ multilingual: {
818
+ license: "MIT",
819
+ attribution: "OpenAI Whisper base, MIT licence",
820
+ },
821
+ };
822
+ export const MODEL_RUNTIME_NOTE = "Both models run with sherpa-onnx (Apache-2.0).";
823
+ function mb(bytes) {
824
+ return `${Math.round(bytes / 1_000_000)} MB`;
825
+ }
826
+ /** `clipy models list|download`: the on-device speech models local mode can use. */
827
+ export async function cmdModels(positionals, json, env) {
828
+ const { io } = env;
829
+ try {
830
+ const parsed = parseModelsArgs(positionals);
831
+ const deps = env.deps();
832
+ if (parsed.action === "list") {
833
+ const models = LOCAL_MODELS.map((model) => {
834
+ const info = deps.modelInfo(model);
835
+ return {
836
+ model,
837
+ ...info,
838
+ license: info.license ?? MODEL_LICENSES[model].license,
839
+ attribution: info.attribution ?? MODEL_LICENSES[model].attribution,
840
+ ...deps.modelStatus(model),
841
+ };
842
+ });
843
+ if (json) {
844
+ io.stdout(`${JSON.stringify({ ok: true, models, runtime: "sherpa-onnx (Apache-2.0)" })}\n`);
845
+ return 0;
846
+ }
847
+ for (const m of models) {
848
+ io.stdout(`${m.model}\t${m.installed ? "installed" : `not downloaded (${mb(m.sizeBytes)})`}\t${m.label}\t${m.license}\t${m.dir}\n`);
849
+ }
850
+ io.stderr(`${MODEL_RUNTIME_NOTE}\n`);
851
+ return 0;
852
+ }
853
+ const { model } = parsed;
854
+ let last = -1;
855
+ // Ctrl-C or SIGTERM aborts the download, and the partial files are removed.
856
+ const controller = new AbortController();
857
+ const dispose = io.onInterrupt(() => controller.abort(new Error("Download cancelled")));
858
+ let dir;
859
+ try {
860
+ dir = await deps.downloadModel(model, {
861
+ signal: controller.signal,
862
+ onProgress: (fraction) => {
863
+ const pct = Math.floor(fraction * 100);
864
+ if (pct >= last + 5 || pct === 100) {
865
+ last = pct;
866
+ if (!json)
867
+ io.stderr(`Downloading ${model}: ${pct}%\n`);
868
+ }
869
+ },
870
+ });
871
+ }
872
+ finally {
873
+ dispose();
874
+ }
875
+ const speechEngine = await offerSpeechEngine(json, env);
876
+ if (json)
877
+ io.stdout(`${JSON.stringify({ ok: true, model, dir, ...(speechEngine ? { speechEngine } : {}) })}\n`);
878
+ else
879
+ io.stdout(`${dir}\n`);
880
+ return 0;
881
+ }
882
+ catch (error) {
883
+ printLocalError(error, json, io);
884
+ return error instanceof UsageError ? 2 : 1;
885
+ }
886
+ }
887
+ /**
888
+ * After a model download, the engine that runs it: installed when accepted
889
+ * (a yes at the prompt, --yes or the env var), otherwise a note. Never fails
890
+ * the download. Returns what `--json` reports, or null when nothing changed.
891
+ */
892
+ async function offerSpeechEngine(json, env) {
893
+ if (!env.speech)
894
+ return null;
895
+ const status = env.speech.status();
896
+ if (status.installed)
897
+ return null;
898
+ const note = { installed: false, dir: status.dir, install: SPEECH_ENGINE_INSTALL_COMMAND };
899
+ try {
900
+ const controller = new AbortController();
901
+ const dispose = env.io.onInterrupt(() => controller.abort(new Error("Cancelled")));
902
+ try {
903
+ await ensureSpeechEngine(env.speech, env.io, { json, assumeYes: env.assumeYes, signal: controller.signal });
904
+ }
905
+ finally {
906
+ dispose();
907
+ }
908
+ return { installed: true, dir: status.dir };
909
+ }
910
+ catch (error) {
911
+ if (!(error instanceof SpeechEngineRequiredError)) {
912
+ env.io.stderr(`Warning: the speech engine was not installed: ${error instanceof Error ? error.message : String(error)}\n`);
913
+ }
914
+ else if (!json) {
915
+ env.io.stderr(`The model runs with the speech engine (${SPEECH_ENGINE_SIZE}), which is not installed yet: run ${SPEECH_ENGINE_INSTALL_COMMAND}, or answer yes when a take asks.\n`);
916
+ }
917
+ return note;
918
+ }
919
+ }
920
+ // ---- clipy speech -------------------------------------------------------------
921
+ /** `clipy speech status|install`: the on-device speech engine. Running install is the consent. */
922
+ export async function cmdSpeech(positionals, json, env) {
923
+ const { io } = env;
924
+ try {
925
+ const action = positionals[0] ?? "status";
926
+ if (positionals.length > 1 || (action !== "status" && action !== "install")) {
927
+ throw new UsageError("usage: clipy speech status, or clipy speech install");
928
+ }
929
+ const speech = env.speech ?? realSpeechEngine();
930
+ let status = speech.status();
931
+ let installedNow = false;
932
+ if (action === "install" && !status.installed) {
933
+ if (!json)
934
+ io.stderr(`Downloading the speech engine (${SPEECH_ENGINE_PACKAGE} ${SPEECH_ENGINE_VERSION}, ${SPEECH_ENGINE_SIZE}) into ${status.dir}...\n`);
935
+ const controller = new AbortController();
936
+ const dispose = io.onInterrupt(() => controller.abort(new Error("Cancelled")));
937
+ try {
938
+ status = await speech.install({ signal: controller.signal });
939
+ }
940
+ finally {
941
+ dispose();
942
+ }
943
+ installedNow = true;
944
+ }
945
+ if (json) {
946
+ io.stdout(`${JSON.stringify({ ok: true, ...speechReport(status), ...(action === "install" ? { installedNow } : {}) })}\n`);
947
+ return 0;
948
+ }
949
+ if (status.installed) {
950
+ io.stdout(`${status.entry}\n`);
951
+ io.stderr(`Speech engine ${installedNow ? "installed" : "ready"}: ${SPEECH_ENGINE_PACKAGE} ${status.source === "alongside" ? "(installed alongside the CLI)" : status.version}.\n`);
952
+ }
953
+ else {
954
+ io.stdout(`not installed (${status.dir})\n`);
955
+ io.stderr(`Run ${SPEECH_ENGINE_INSTALL_COMMAND} to download it (${SPEECH_ENGINE_SIZE}). A local take that needs it asks first.\n`);
956
+ }
957
+ return 0;
958
+ }
959
+ catch (error) {
960
+ printLocalError(error, json, io);
961
+ return error instanceof UsageError ? 2 : 1;
962
+ }
963
+ }
964
+ function speechReport(status) {
965
+ return {
966
+ installed: status.installed,
967
+ package: SPEECH_ENGINE_PACKAGE,
968
+ version: SPEECH_ENGINE_VERSION,
969
+ source: status.source,
970
+ entry: status.entry,
971
+ dir: status.dir,
972
+ ...(status.installed ? {} : { install: SPEECH_ENGINE_INSTALL_COMMAND }),
973
+ };
974
+ }
975
+ // ---- clipy local status and doctor ------------------------------------------
976
+ export const SPEECH_ENGINE_HINT = `run ${SPEECH_ENGINE_INSTALL_COMMAND} (${SPEECH_ENGINE_SIZE}; a local take that needs it asks first), or transcribe with your own key: set CLIPY_TRANSCRIBE=openai and CLIPY_TRANSCRIBE_API_KEY, or run clipy local setup --transcribe openai --transcribe-key - and paste the key`;
977
+ /**
978
+ * What local mode can do on this machine. Never a failure: local mode is
979
+ * optional, and an install that only uses the hosted product is healthy.
980
+ */
981
+ export async function localChecks(env, speechEngine) {
982
+ const checks = [];
983
+ let deps;
984
+ try {
985
+ deps = env.deps();
986
+ }
987
+ catch (error) {
988
+ return [{ name: "local mode", status: "warn", detail: `unavailable: ${error instanceof Error ? error.message : String(error)}` }];
989
+ }
990
+ let transcription = null;
991
+ try {
992
+ const config = deps.loadConfig();
993
+ transcription = config.transcription;
994
+ checks.push({
995
+ name: "local config",
996
+ status: "pass",
997
+ detail: `moments: ${describeProvider(config.model, config.modelPreset)} · transcription: ${describeTranscription(config.transcription)}`,
998
+ data: {
999
+ path: deps.configPath(),
1000
+ exists: existsSync(deps.configPath()),
1001
+ modelPreset: config.modelPreset,
1002
+ transcription: config.transcription.kind,
1003
+ },
1004
+ });
1005
+ }
1006
+ catch (error) {
1007
+ checks.push({
1008
+ name: "local config",
1009
+ status: "warn",
1010
+ detail: error instanceof Error ? error.message : String(error),
1011
+ hint: "fix or remove the file, or run clipy local setup",
1012
+ data: { path: safeConfigPath(deps) },
1013
+ });
1014
+ }
1015
+ const models = {};
1016
+ for (const model of LOCAL_MODELS) {
1017
+ try {
1018
+ models[model] = deps.modelStatus(model);
1019
+ }
1020
+ catch (error) {
1021
+ models[model] = { installed: false, error: error instanceof Error ? error.message : String(error) };
1022
+ }
1023
+ }
1024
+ const wanted = transcription?.kind === "local" ? transcription.model : null;
1025
+ const wantedInstalled = wanted ? models[wanted].installed === true : true;
1026
+ const installed = LOCAL_MODELS.filter((m) => models[m].installed);
1027
+ checks.push({
1028
+ name: "local models",
1029
+ status: wantedInstalled ? (installed.length > 0 ? "pass" : "info") : "warn",
1030
+ detail: installed.length > 0 ? `installed: ${installed.join(", ")}` : "no speech model downloaded",
1031
+ ...(wantedInstalled ? {} : { hint: `local transcription uses ${wanted}: clipy models download ${wanted}` }),
1032
+ data: models,
1033
+ });
1034
+ let engine = speechEngine ?? null;
1035
+ try {
1036
+ engine ??= (env.speech ?? realSpeechEngine()).status();
1037
+ }
1038
+ catch {
1039
+ engine = null;
1040
+ }
1041
+ const ready = engine?.installed === true;
1042
+ // Not an error: the engine is downloaded, after asking, the first time a take needs it.
1043
+ checks.push({
1044
+ name: "local speech",
1045
+ status: ready ? "pass" : "info",
1046
+ detail: ready
1047
+ ? `speech engine ready (${SPEECH_ENGINE_PACKAGE} ${engine?.source === "alongside" ? "installed alongside the CLI" : SPEECH_ENGINE_VERSION})`
1048
+ : "speech engine not installed (downloaded on first use, after asking)",
1049
+ ...(ready ? {} : { hint: SPEECH_ENGINE_HINT }),
1050
+ data: {
1051
+ sherpaOnnxNode: ready,
1052
+ installed: ready,
1053
+ version: SPEECH_ENGINE_VERSION,
1054
+ source: engine?.source ?? null,
1055
+ dir: engine?.dir ?? null,
1056
+ ...(ready ? {} : { install: SPEECH_ENGINE_INSTALL_COMMAND }),
1057
+ },
1058
+ });
1059
+ try {
1060
+ const capture = await deps.checkCapture();
1061
+ checks.push({
1062
+ name: "local capture",
1063
+ status: capture.ok ? "pass" : "warn",
1064
+ detail: capture.ok
1065
+ ? `ready (ffmpeg at ${capture.ffmpeg})`
1066
+ : `not ready: ${capture.problems.join("; ") || "unknown problem"}`,
1067
+ ...(capture.hints.length ? { hint: capture.hints.join("; ") } : {}),
1068
+ data: { ok: capture.ok, ffmpeg: capture.ffmpeg, problems: capture.problems },
1069
+ });
1070
+ }
1071
+ catch (error) {
1072
+ checks.push({ name: "local capture", status: "warn", detail: error instanceof Error ? error.message : String(error) });
1073
+ }
1074
+ return checks;
1075
+ }
1076
+ function safeConfigPath(deps) {
1077
+ try {
1078
+ return deps.configPath();
1079
+ }
1080
+ catch {
1081
+ return null;
1082
+ }
1083
+ }
1084
+ /** `clipy local status`: config, provider, transcription, models and capture, in one view. */
1085
+ export async function cmdLocalStatus(json, env, speechEngine) {
1086
+ const { io } = env;
1087
+ const checks = await localChecks(env, speechEngine);
1088
+ if (json) {
1089
+ io.stdout(`${JSON.stringify({ ok: true, local: true, checks })}\n`);
1090
+ return 0;
1091
+ }
1092
+ io.stdout("Local mode: record and build an AREC on this machine. No Clipy account, nothing uploaded.\n");
1093
+ for (const check of checks) {
1094
+ io.stdout(`${check.status.toUpperCase().padEnd(4)} ${check.name.padEnd(14)} ${check.detail}\n`);
1095
+ if (check.hint)
1096
+ io.stdout(` ${check.hint}\n`);
1097
+ }
1098
+ const config = checks.find((c) => c.name === "local config");
1099
+ const path = config?.data?.path;
1100
+ if (path)
1101
+ io.stdout(`config file: ${path}\n`);
1102
+ return 0;
1103
+ }