@clipy/cli 0.18.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 (56) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +210 -9
  3. package/dist/context/importCmd.js +1 -1
  4. package/dist/context/ytdlp.js +1 -1
  5. package/dist/context-core/arec.js +1 -1
  6. package/dist/index.js +1042 -88
  7. package/dist/local/arec.js +186 -0
  8. package/dist/local/commands.js +1103 -0
  9. package/dist/local/deps.js +42 -0
  10. package/dist/local/media.js +154 -0
  11. package/dist/local/pipeline.js +530 -0
  12. package/dist/local/ports.js +1 -0
  13. package/dist/local/speechEngine.js +260 -0
  14. package/dist/local/transcriptFile.js +54 -0
  15. package/dist/local/vendor/capture/capture.js +442 -0
  16. package/dist/local/vendor/capture/check.js +103 -0
  17. package/dist/local/vendor/capture/children.js +69 -0
  18. package/dist/local/vendor/capture/ffmpegArgs.js +108 -0
  19. package/dist/local/vendor/capture/index.js +36 -0
  20. package/dist/local/vendor/capture/proc.js +71 -0
  21. package/dist/local/vendor/capture/scripts.js +107 -0
  22. package/dist/local/vendor/capture/sidecar.js +199 -0
  23. package/dist/local/vendor/capture/sources.js +272 -0
  24. package/dist/local/vendor/capture/types.js +1 -0
  25. package/dist/local/vendor/capture/virtualDisplay.js +170 -0
  26. package/dist/local/vendor/capture/xauth.js +68 -0
  27. package/dist/local/vendor/config/errors.js +12 -0
  28. package/dist/local/vendor/config/index.js +241 -0
  29. package/dist/local/vendor/config/paths.js +37 -0
  30. package/dist/local/vendor/config/presets.js +61 -0
  31. package/dist/local/vendor/config/schema.js +66 -0
  32. package/dist/local/vendor/moments/generated/drawStrokes.js +127 -0
  33. package/dist/local/vendor/moments/generated/keyMomentsCursorContext.js +568 -0
  34. package/dist/local/vendor/moments/generated/keyMomentsFusion.js +406 -0
  35. package/dist/local/vendor/moments/generated/localMomentPlan.js +178 -0
  36. package/dist/local/vendor/moments/generated/types.js +1 -0
  37. package/dist/local/vendor/moments/index.js +147 -0
  38. package/dist/local/vendor/moments/llm.js +158 -0
  39. package/dist/local/vendor/transcribe/audio.js +251 -0
  40. package/dist/local/vendor/transcribe/chunking.js +250 -0
  41. package/dist/local/vendor/transcribe/index.js +89 -0
  42. package/dist/local/vendor/transcribe/local.js +221 -0
  43. package/dist/local/vendor/transcribe/localWorker.js +79 -0
  44. package/dist/local/vendor/transcribe/models.js +369 -0
  45. package/dist/local/vendor/transcribe/providers/assemblyai.js +61 -0
  46. package/dist/local/vendor/transcribe/providers/common.js +105 -0
  47. package/dist/local/vendor/transcribe/providers/deepgram.js +59 -0
  48. package/dist/local/vendor/transcribe/providers/elevenlabs.js +43 -0
  49. package/dist/local/vendor/transcribe/providers/gemini.js +102 -0
  50. package/dist/local/vendor/transcribe/providers/http.js +214 -0
  51. package/dist/local/vendor/transcribe/providers/openai.js +48 -0
  52. package/dist/local/vendor/transcribe/tar.js +53 -0
  53. package/dist/local/vendor/transcribe/types.js +1 -0
  54. package/dist/macBridge.js +78 -9
  55. package/dist/skill.js +46 -1
  56. package/package.json +19 -9
@@ -0,0 +1,260 @@
1
+ /**
2
+ * The on-device speech engine (sherpa-onnx-node, about 35 MB of native code)
3
+ * is not a dependency of @clipy/cli, so a plain install stays small. The first
4
+ * time a local take needs on-device transcription, the CLI asks before
5
+ * downloading it, then installs the exact pinned version with npm into a
6
+ * folder Clipy owns (next to the speech models in the user's cache folder),
7
+ * which works for any global npm or pnpm install without write access to it.
8
+ *
9
+ * Accepting up front, for agents and CI: `clipy speech install`, `--yes`, or
10
+ * CLIPY_INSTALL_SPEECH_ENGINE=1. Without one of those and without a terminal
11
+ * to ask in, the take stops before recording with `speech_engine_required`.
12
+ *
13
+ * A copy the CLI can resolve on its own (`npm i -g sherpa-onnx-node` next to
14
+ * a global npm install of the CLI) is used when the Clipy folder has none.
15
+ */
16
+ import { spawn } from "node:child_process";
17
+ import { existsSync, readdirSync, realpathSync } from "node:fs";
18
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
19
+ import { createRequire } from "node:module";
20
+ import { homedir } from "node:os";
21
+ import { dirname, join } from "node:path";
22
+ export const SPEECH_ENGINE_PACKAGE = "sherpa-onnx-node";
23
+ /** Exact version: the platform packages it pulls in (sherpa-onnx-darwin-arm64 and so on) follow it. */
24
+ export const SPEECH_ENGINE_VERSION = "2.0.1";
25
+ /** Installed size across platforms (23 to 40 MB, 34 MB on Apple silicon). */
26
+ export const SPEECH_ENGINE_SIZE = "about 35 MB";
27
+ export const SPEECH_ENGINE_INSTALL_COMMAND = "clipy speech install";
28
+ /** Set to 1 (or true, yes) to accept the download without a prompt. */
29
+ export const SPEECH_ENGINE_ACCEPT_ENV = "CLIPY_INSTALL_SPEECH_ENGINE";
30
+ /** Overrides the folder the engine is installed into. */
31
+ export const SPEECH_ENGINE_DIR_ENV = "CLIPY_SPEECH_ENGINE_DIR";
32
+ /** `<cache>/clipy-local/speech-engine`, beside the speech models. */
33
+ export function speechEngineRoot(env = process.env, platform = process.platform, home = homedir()) {
34
+ const override = env[SPEECH_ENGINE_DIR_ENV]?.trim();
35
+ if (override)
36
+ return override;
37
+ if (platform === "win32")
38
+ return join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "clipy-local", "speech-engine");
39
+ if (platform === "darwin")
40
+ return join(home, "Library", "Caches", "clipy-local", "speech-engine");
41
+ return join(env.XDG_CACHE_HOME || join(home, ".cache"), "clipy-local", "speech-engine");
42
+ }
43
+ export function speechEngineDir(root = speechEngineRoot()) {
44
+ return join(root, `${SPEECH_ENGINE_PACKAGE}-${SPEECH_ENGINE_VERSION}`);
45
+ }
46
+ /** The entry file of an install in `dir`, or null. Resolution stays inside `dir`. */
47
+ function entryIn(dir) {
48
+ if (!existsSync(join(dir, "node_modules", SPEECH_ENGINE_PACKAGE, "package.json")))
49
+ return null;
50
+ try {
51
+ return createRequire(join(dir, "package.json")).resolve(SPEECH_ENGINE_PACKAGE);
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ function entryAlongside() {
58
+ try {
59
+ return createRequire(import.meta.url).resolve(SPEECH_ENGINE_PACKAGE);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ export function speechEngineStatus(root = speechEngineRoot(), alongside = entryAlongside) {
66
+ const dir = speechEngineDir(root);
67
+ const base = { dir, version: SPEECH_ENGINE_VERSION };
68
+ const own = entryIn(dir);
69
+ if (own)
70
+ return { installed: true, entry: own, source: "clipy", ...base };
71
+ const other = alongside();
72
+ if (other)
73
+ return { installed: true, entry: other, source: "alongside", ...base };
74
+ return { installed: false, entry: null, source: null, ...base };
75
+ }
76
+ export class SpeechEngineInstallError extends Error {
77
+ constructor(message) {
78
+ super(message);
79
+ this.name = "SpeechEngineInstallError";
80
+ }
81
+ }
82
+ /**
83
+ * npm, run with this same Node: the npm that ships next to it, CLIPY_NPM
84
+ * (an executable or an npm-cli.js), or `npm` on the PATH.
85
+ */
86
+ export function npmCommand(env = process.env) {
87
+ const override = env.CLIPY_NPM?.trim();
88
+ if (override) {
89
+ return /\.[cm]?js$/.test(override) ? { cmd: process.execPath, args: [override], shell: false } : { cmd: override, args: [], shell: false };
90
+ }
91
+ let nodeDir = dirname(process.execPath);
92
+ try {
93
+ nodeDir = dirname(realpathSync(process.execPath));
94
+ }
95
+ catch {
96
+ // keep the unresolved folder
97
+ }
98
+ for (const cli of [join(nodeDir, "..", "lib", "node_modules", "npm", "bin", "npm-cli.js"), join(nodeDir, "node_modules", "npm", "bin", "npm-cli.js")]) {
99
+ if (existsSync(cli))
100
+ return { cmd: process.execPath, args: [cli], shell: false };
101
+ }
102
+ // npm.cmd only starts through a shell on Windows.
103
+ return process.platform === "win32" ? { cmd: "npm.cmd", args: [], shell: true } : { cmd: "npm", args: [], shell: false };
104
+ }
105
+ function run(command, args, cwd, env, signal) {
106
+ return new Promise((resolveRun, reject) => {
107
+ const all = [...command.args, ...args].map((a) => (command.shell ? `"${a}"` : a));
108
+ const child = spawn(command.cmd, all, { cwd, env, shell: command.shell, stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
109
+ let stderr = "";
110
+ child.stderr?.on("data", (d) => {
111
+ if (stderr.length < 64_000)
112
+ stderr += String(d);
113
+ });
114
+ const onAbort = () => child.kill("SIGTERM");
115
+ signal?.addEventListener("abort", onAbort, { once: true });
116
+ child.on("error", (error) => {
117
+ signal?.removeEventListener("abort", onAbort);
118
+ reject(error);
119
+ });
120
+ child.on("close", (code) => {
121
+ signal?.removeEventListener("abort", onAbort);
122
+ resolveRun({ code, stderr });
123
+ });
124
+ });
125
+ }
126
+ /** npm settings from a parent `npm exec`/`pnpm dlx` that would send the install elsewhere. */
127
+ function installEnv(env) {
128
+ const out = { ...env };
129
+ for (const key of Object.keys(out)) {
130
+ if (/^npm_config_(global|location|prefix)$/i.test(key))
131
+ delete out[key];
132
+ }
133
+ return out;
134
+ }
135
+ function firstLines(text, n = 3) {
136
+ return text
137
+ .split("\n")
138
+ .map((l) => l.trim())
139
+ .filter(Boolean)
140
+ .slice(0, n)
141
+ .join(" ");
142
+ }
143
+ /**
144
+ * Installs the pinned engine into a staging folder, checks that it loads on
145
+ * this machine, then renames it into place, so the folder is complete or absent.
146
+ */
147
+ export async function installSpeechEngine(options = {}) {
148
+ const env = options.env ?? process.env;
149
+ const root = options.root ?? speechEngineRoot(env);
150
+ const finalDir = speechEngineDir(root);
151
+ if (entryIn(finalDir))
152
+ return speechEngineStatus(root, options.alongside);
153
+ await mkdir(root, { recursive: true });
154
+ const staging = join(root, `.install-${process.pid}-${Date.now().toString(36)}`);
155
+ await rm(staging, { recursive: true, force: true });
156
+ await mkdir(staging, { recursive: true });
157
+ try {
158
+ await writeFile(join(staging, "package.json"), `${JSON.stringify({ name: "clipy-speech-engine", private: true, description: "Installed by the Clipy CLI for on-device transcription." }, null, 2)}\n`);
159
+ const npm = npmCommand(env);
160
+ const spec = `${SPEECH_ENGINE_PACKAGE}@${SPEECH_ENGINE_VERSION}`;
161
+ let result;
162
+ try {
163
+ result = await run(npm, ["install", spec, "--save-exact", "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund", "--no-update-notifier", "--loglevel=error", "--prefix", staging], staging, installEnv(env), options.signal);
164
+ }
165
+ catch (error) {
166
+ throw new SpeechEngineInstallError(`could not run npm to download the speech engine (${error.message}). Install Node.js with npm, or install it yourself with npm i -g ${spec}.`);
167
+ }
168
+ if (options.signal?.aborted)
169
+ throw new SpeechEngineInstallError("the speech engine download was cancelled");
170
+ if (result.code !== 0) {
171
+ throw new SpeechEngineInstallError(`npm could not download ${spec}: ${firstLines(result.stderr) || `exit code ${result.code}`}`);
172
+ }
173
+ const entry = entryIn(staging);
174
+ if (!entry)
175
+ throw new SpeechEngineInstallError(`npm finished but ${SPEECH_ENGINE_PACKAGE} is missing from ${staging}`);
176
+ // Load it in a child: the native part (sherpa-onnx-<platform>-<arch>) must
177
+ // be there and start on this machine, and a crash must not take the CLI down.
178
+ const check = await run({ cmd: process.execPath, args: [], shell: false }, ["-e", "require(process.argv[1])", entry], staging, env, options.signal);
179
+ if (check.code !== 0) {
180
+ throw new SpeechEngineInstallError(`the speech engine was downloaded but does not load on this machine (${process.platform}-${process.arch}): ${firstLines(check.stderr, 1) || `exit code ${check.code}`}`);
181
+ }
182
+ // Another CLI may have finished the same install meanwhile: keep its copy.
183
+ if (!entryIn(finalDir)) {
184
+ await rm(finalDir, { recursive: true, force: true });
185
+ await rename(staging, finalDir);
186
+ }
187
+ }
188
+ finally {
189
+ await rm(staging, { recursive: true, force: true }).catch(() => undefined);
190
+ }
191
+ await removeOtherVersions(root);
192
+ return speechEngineStatus(root, options.alongside);
193
+ }
194
+ /** Older pinned versions left by an earlier CLI. Best-effort. */
195
+ async function removeOtherVersions(root) {
196
+ const keep = `${SPEECH_ENGINE_PACKAGE}-${SPEECH_ENGINE_VERSION}`;
197
+ let names = [];
198
+ try {
199
+ names = readdirSync(root);
200
+ }
201
+ catch {
202
+ return;
203
+ }
204
+ for (const name of names) {
205
+ if (name.startsWith(`${SPEECH_ENGINE_PACKAGE}-`) && name !== keep)
206
+ await rm(join(root, name), { recursive: true, force: true }).catch(() => undefined);
207
+ }
208
+ }
209
+ export function realSpeechEngine(env = process.env) {
210
+ return {
211
+ status: () => speechEngineStatus(speechEngineRoot(env)),
212
+ install: (options = {}) => installSpeechEngine({ ...options, env }),
213
+ };
214
+ }
215
+ // ---- Consent ----------------------------------------------------------------
216
+ /** The take stops because the engine is missing and nobody agreed to download it. */
217
+ export class SpeechEngineRequiredError extends Error {
218
+ code = "speech_engine_required";
219
+ command = SPEECH_ENGINE_INSTALL_COMMAND;
220
+ declined;
221
+ constructor(declined) {
222
+ super(declined
223
+ ? `Stopped: on-device transcription needs the speech engine, and it was not downloaded. Run ${SPEECH_ENGINE_INSTALL_COMMAND} when you want it, or choose another transcription option with clipy local setup --transcribe.`
224
+ : `On-device transcription needs the speech engine (${SPEECH_ENGINE_PACKAGE} ${SPEECH_ENGINE_VERSION}, ${SPEECH_ENGINE_SIZE}), which is not installed. ` +
225
+ `Run ${SPEECH_ENGINE_INSTALL_COMMAND} (or add --yes, or set ${SPEECH_ENGINE_ACCEPT_ENV}=1) to download it, or choose another transcription option with clipy local setup --transcribe.`);
226
+ this.name = "SpeechEngineRequiredError";
227
+ this.declined = declined;
228
+ }
229
+ }
230
+ export function acceptedByEnv(env = process.env) {
231
+ return /^(1|true|yes|y)$/i.test(env[SPEECH_ENGINE_ACCEPT_ENV]?.trim() ?? "");
232
+ }
233
+ export function speechEnginePrompt(dir) {
234
+ return (`On-device transcription needs the speech engine: ${SPEECH_ENGINE_PACKAGE} ${SPEECH_ENGINE_VERSION} from npm, ${SPEECH_ENGINE_SIZE}. ` +
235
+ `It is downloaded once, into ${dir}. Download it now? [Y/n] `);
236
+ }
237
+ /**
238
+ * Makes sure the engine is there before a take that needs it: present, or
239
+ * accepted (`assumeYes`, the env var, or a yes at the prompt) and installed.
240
+ * Otherwise throws SpeechEngineRequiredError.
241
+ */
242
+ export async function ensureSpeechEngine(speech, io, options) {
243
+ const status = speech.status();
244
+ if (status.installed)
245
+ return "present";
246
+ let accepted = options.assumeYes === true || acceptedByEnv(options.env);
247
+ if (!accepted) {
248
+ if (options.json || !io.confirm)
249
+ throw new SpeechEngineRequiredError(false);
250
+ accepted = await io.confirm(speechEnginePrompt(status.dir));
251
+ if (!accepted)
252
+ throw new SpeechEngineRequiredError(true);
253
+ }
254
+ if (!options.json)
255
+ io.stderr(`Downloading the speech engine (${SPEECH_ENGINE_PACKAGE} ${SPEECH_ENGINE_VERSION}, ${SPEECH_ENGINE_SIZE})...\n`);
256
+ const installed = await speech.install({ signal: options.signal });
257
+ if (!options.json)
258
+ io.stderr(`Speech engine ready: ${installed.dir}\n`);
259
+ return "installed";
260
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Reads a transcript the user already has: WebVTT, SubRip, or JSON (an array
3
+ * of `{startMs, endMs, text}`, a `transcript.json` from a local folder, or a
4
+ * YouTube json3 caption file). Parsing reuses the hosted caption parsers.
5
+ */
6
+ import { readFile } from "node:fs/promises";
7
+ import { basename, extname } from "node:path";
8
+ import { normalizeSegments, parseSrt, parseVtt, parseYoutubeJson3 } from "../context-core/index.js";
9
+ function fromJson(value) {
10
+ const list = Array.isArray(value)
11
+ ? value
12
+ : value && typeof value === "object" && Array.isArray(value.segments)
13
+ ? value.segments
14
+ : null;
15
+ if (!list)
16
+ return parseYoutubeJson3(value);
17
+ const out = [];
18
+ for (const raw of list) {
19
+ if (!raw || typeof raw !== "object")
20
+ continue;
21
+ const r = raw;
22
+ const startMs = Number(r.startMs ?? r.start_ms);
23
+ const endMs = Number(r.endMs ?? r.end_ms ?? startMs);
24
+ const text = typeof r.text === "string" ? r.text : "";
25
+ if (Number.isFinite(startMs) && Number.isFinite(endMs) && text.trim())
26
+ out.push({ startMs, endMs, text });
27
+ }
28
+ return out;
29
+ }
30
+ export async function readTranscriptFile(path, durationMs) {
31
+ const text = await readFile(path, "utf8");
32
+ const ext = extname(path).toLowerCase();
33
+ let segments;
34
+ if (ext === ".vtt")
35
+ segments = parseVtt(text);
36
+ else if (ext === ".srt")
37
+ segments = parseSrt(text);
38
+ else if (ext === ".json") {
39
+ let parsed;
40
+ try {
41
+ parsed = JSON.parse(text);
42
+ }
43
+ catch {
44
+ throw new Error(`${basename(path)} is not valid JSON`);
45
+ }
46
+ segments = fromJson(parsed);
47
+ }
48
+ else {
49
+ throw new Error(`Unsupported transcript file ${basename(path)}: use .vtt, .srt or .json`);
50
+ }
51
+ if (segments.length === 0)
52
+ throw new Error(`No transcript segments found in ${basename(path)}`);
53
+ return { segments: normalizeSegments(segments, { durationMs }).segments, label: `caption file ${basename(path)}` };
54
+ }