@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,241 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/config/src/index.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ /**
4
+ * @clipy/local-config: the local edition's settings. Which model provider (if
5
+ * any) reads the transcript for spoken cues, and how recordings are
6
+ * transcribed.
7
+ *
8
+ * Settings come from a JSON file (see `configPath` and `StoredConfig`), and
9
+ * env vars override the file:
10
+ *
11
+ * | Env var | Overrides |
12
+ * |---|---|
13
+ * | `CLIPY_MODEL_PROVIDER` | `model.preset` (openrouter, openai, gemini, groq, ollama, lmstudio, custom) |
14
+ * | `CLIPY_MODEL_BASE_URL` | `model.baseUrl` |
15
+ * | `CLIPY_MODEL_API_KEY` | `model.apiKey` |
16
+ * | `CLIPY_MODEL` | `model.model` |
17
+ * | `CLIPY_TRANSCRIBE` | `transcription.kind` |
18
+ * | `CLIPY_TRANSCRIBE_API_KEY` | `transcription.apiKey` |
19
+ * | `CLIPY_TRANSCRIBE_MODEL` | `transcription.model` |
20
+ * | `CLIPY_TRANSCRIBE_BASE_URL` | `transcription.baseUrl` (OpenAI-compatible only) |
21
+ * | `CLIPY_LOCAL_CONFIG` | the file's path |
22
+ *
23
+ * A key saved in the file is only ever sent to the endpoint it was saved for.
24
+ * When an env var switches to another provider, the saved key and model are
25
+ * dropped; when it only moves the base URL, the saved key is dropped and the
26
+ * model name is kept.
27
+ *
28
+ * Nothing here prints or logs, and error messages never contain a key.
29
+ * Telemetry is always off in this edition.
30
+ */
31
+ import { randomBytes } from "node:crypto";
32
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
33
+ import { dirname } from "node:path";
34
+ import { PROVIDER_BASE_URLS } from "../moments/index.js";
35
+ import { ConfigError } from "./errors.js";
36
+ import { configPath, envValue } from "./paths.js";
37
+ import { presetProvider, TRANSCRIPTION_PRESETS } from "./presets.js";
38
+ import { describeIssues, LOCAL_TRANSCRIPTION_MODELS, MODEL_PRESETS, storedConfigSchema, TRANSCRIPTION_KINDS, } from "./schema.js";
39
+ export { ConfigError } from "./errors.js";
40
+ export { configPath } from "./paths.js";
41
+ export { DEFAULT_MODELS, presetProvider, TRANSCRIPTION_PRESETS } from "./presets.js";
42
+ export { LOCAL_TRANSCRIPTION_MODELS, MODEL_PRESETS, TRANSCRIPTION_KINDS, } from "./schema.js";
43
+ /** The default when nothing is configured: the local "English, fast" model, on every platform. */
44
+ export const DEFAULT_TRANSCRIPTION = { kind: "local", model: "english-fast" };
45
+ /** Character offset to "line L, column C", for a JSON error that must not quote the file. */
46
+ function lineAndColumn(text, offset) {
47
+ const before = text.slice(0, offset).split("\n");
48
+ return `line ${before.length}, column ${before[before.length - 1].length + 1}`;
49
+ }
50
+ /** The file as saved, validated. A missing file is an empty config. */
51
+ function readStored(path) {
52
+ let text;
53
+ try {
54
+ text = readFileSync(path, "utf8");
55
+ }
56
+ catch (error) {
57
+ const code = error.code;
58
+ if (code === "ENOENT")
59
+ return {};
60
+ throw new ConfigError(`Cannot read the config file ${path} (${code ?? "unknown error"}).`);
61
+ }
62
+ if (!text.trim())
63
+ return {};
64
+ let raw;
65
+ try {
66
+ raw = JSON.parse(text);
67
+ }
68
+ catch (error) {
69
+ // V8's message can quote part of the file, which may hold a key. Keep only the position.
70
+ const position = /position (\d+)/.exec(String(error.message))?.[1];
71
+ const where = position ? ` at ${lineAndColumn(text, Number(position))}` : "";
72
+ throw new ConfigError(`The config file ${path} is not valid JSON${where}.`);
73
+ }
74
+ const parsed = storedConfigSchema.safeParse(raw);
75
+ if (!parsed.success) {
76
+ throw new ConfigError(`The config file ${path} has an invalid setting: ${describeIssues(parsed.error)}.`);
77
+ }
78
+ return parsed.data;
79
+ }
80
+ function sameUrl(a, b) {
81
+ const norm = (u) => u?.trim().replace(/\/+$/, "");
82
+ return norm(a) === norm(b);
83
+ }
84
+ function oneOf(values, value, envName) {
85
+ if (values.includes(value))
86
+ return value;
87
+ throw new ConfigError(`${envName} must be one of ${values.join(", ")}.`);
88
+ }
89
+ function withPath(error, path) {
90
+ if (error instanceof ConfigError)
91
+ throw new ConfigError(`${error.message} (config file: ${path})`);
92
+ throw error;
93
+ }
94
+ function resolveModel(stored, env, path) {
95
+ const envPreset = envValue(env, "CLIPY_MODEL_PROVIDER");
96
+ const envBase = envValue(env, "CLIPY_MODEL_BASE_URL");
97
+ const envKey = envValue(env, "CLIPY_MODEL_API_KEY");
98
+ const envModel = envValue(env, "CLIPY_MODEL");
99
+ let draft = stored ? { ...stored } : {};
100
+ if (envPreset) {
101
+ const preset = oneOf(MODEL_PRESETS, envPreset, "CLIPY_MODEL_PROVIDER");
102
+ if (preset !== draft.preset)
103
+ draft = { preset };
104
+ }
105
+ if (envBase) {
106
+ // A different endpoint never inherits the saved key. The model name is kept.
107
+ const savedBase = draft.baseUrl ?? (draft.preset && draft.preset !== "custom" ? PROVIDER_BASE_URLS[draft.preset] : undefined);
108
+ if (!sameUrl(envBase, savedBase))
109
+ draft = { preset: draft.preset ?? "custom", model: draft.model };
110
+ draft.baseUrl = envBase;
111
+ }
112
+ // A key or model name alone picks the default provider, OpenRouter.
113
+ if (!draft.preset && (envKey || envModel))
114
+ draft = { preset: "openrouter" };
115
+ if (envKey)
116
+ draft.apiKey = envKey;
117
+ if (envModel)
118
+ draft.model = envModel;
119
+ if (!draft.preset)
120
+ return { model: null, modelPreset: null };
121
+ try {
122
+ return { model: presetProvider(draft.preset, draft.apiKey, draft.model, draft.baseUrl), modelPreset: draft.preset };
123
+ }
124
+ catch (error) {
125
+ return withPath(error, path);
126
+ }
127
+ }
128
+ /** Where an OpenAI-compatible transcription draft would send audio, if anywhere. */
129
+ function transcriptionBase(draft) {
130
+ if (draft.kind === "openai" || draft.kind === "groq")
131
+ return TRANSCRIPTION_PRESETS[draft.kind].baseUrl;
132
+ if (draft.kind === "openai-compatible")
133
+ return draft.baseUrl;
134
+ return undefined;
135
+ }
136
+ function resolveTranscription(stored, env, path) {
137
+ const envKind = envValue(env, "CLIPY_TRANSCRIBE");
138
+ const envKey = envValue(env, "CLIPY_TRANSCRIBE_API_KEY");
139
+ const envModel = envValue(env, "CLIPY_TRANSCRIBE_MODEL");
140
+ const envBase = envValue(env, "CLIPY_TRANSCRIBE_BASE_URL");
141
+ let draft = { ...(stored ?? DEFAULT_TRANSCRIPTION) };
142
+ if (envKind) {
143
+ const kind = oneOf(TRANSCRIPTION_KINDS, envKind, "CLIPY_TRANSCRIBE");
144
+ if (kind !== draft.kind)
145
+ draft = { kind };
146
+ }
147
+ if (envBase) {
148
+ if (envKind && !["openai", "groq", "openai-compatible"].includes(envKind)) {
149
+ throw new ConfigError(`CLIPY_TRANSCRIBE_BASE_URL only applies to OpenAI-compatible transcription, not ${envKind}.`);
150
+ }
151
+ // A different endpoint never inherits the saved key. The model name is kept.
152
+ const model = draft.model ?? defaultTranscriptionModel(draft.kind);
153
+ draft = sameUrl(envBase, transcriptionBase(draft))
154
+ ? { kind: "openai-compatible", baseUrl: envBase, apiKey: draft.apiKey, model }
155
+ : { kind: "openai-compatible", baseUrl: envBase, model: draft.model };
156
+ }
157
+ if (envKey)
158
+ draft.apiKey = envKey;
159
+ if (envModel)
160
+ draft.model = envModel;
161
+ const needKey = (who) => new ConfigError(`Transcription with ${who} needs an API key. Set CLIPY_TRANSCRIBE_API_KEY or "transcription.apiKey" (config file: ${path}).`);
162
+ switch (draft.kind) {
163
+ case "none":
164
+ return { kind: "none" };
165
+ case "local": {
166
+ const model = draft.model ?? "english-fast";
167
+ if (!LOCAL_TRANSCRIPTION_MODELS.includes(model)) {
168
+ throw new ConfigError(`The local transcription model must be one of ${LOCAL_TRANSCRIPTION_MODELS.join(", ")} (CLIPY_TRANSCRIBE_MODEL or "transcription.model", config file: ${path}).`);
169
+ }
170
+ return { kind: "local", model: model };
171
+ }
172
+ case "openai":
173
+ case "groq": {
174
+ if (!draft.apiKey)
175
+ throw needKey(draft.kind === "openai" ? "OpenAI" : "Groq");
176
+ const preset = TRANSCRIPTION_PRESETS[draft.kind];
177
+ return { kind: "openai-compatible", baseUrl: preset.baseUrl, apiKey: draft.apiKey, model: draft.model ?? preset.model };
178
+ }
179
+ case "openai-compatible": {
180
+ if (!draft.baseUrl) {
181
+ throw new ConfigError(`OpenAI-compatible transcription needs a base URL. Set CLIPY_TRANSCRIBE_BASE_URL or "transcription.baseUrl" (config file: ${path}).`);
182
+ }
183
+ if (!draft.model) {
184
+ throw new ConfigError(`OpenAI-compatible transcription needs a model name. Set CLIPY_TRANSCRIBE_MODEL or "transcription.model" (config file: ${path}).`);
185
+ }
186
+ return { kind: "openai-compatible", baseUrl: draft.baseUrl, apiKey: draft.apiKey ?? "", model: draft.model };
187
+ }
188
+ default: {
189
+ if (!draft.apiKey)
190
+ throw needKey(draft.kind);
191
+ return draft.model
192
+ ? { kind: draft.kind, apiKey: draft.apiKey, model: draft.model }
193
+ : { kind: draft.kind, apiKey: draft.apiKey };
194
+ }
195
+ }
196
+ }
197
+ function defaultTranscriptionModel(kind) {
198
+ return kind === "openai" || kind === "groq" ? TRANSCRIPTION_PRESETS[kind].model : undefined;
199
+ }
200
+ /**
201
+ * The user's settings: the file at `configPath(env)` with env vars on top. A
202
+ * missing file gives the defaults (rules only, local "English, fast"
203
+ * transcription). Throws a ConfigError, safe to print, when the file is
204
+ * malformed or a provider is missing something it needs.
205
+ */
206
+ export function loadConfig(env = process.env) {
207
+ const path = configPath(env);
208
+ const stored = readStored(path);
209
+ const { model, modelPreset } = resolveModel(stored.model, env, path);
210
+ return { model, modelPreset, transcription: resolveTranscription(stored.transcription, env, path), telemetry: false };
211
+ }
212
+ /**
213
+ * Update the settings file. Each top-level field in `patch` replaces the saved
214
+ * one whole (`model: null` clears the provider); fields left out, or
215
+ * undefined, are kept. Creates the directory if needed and writes the file
216
+ * with mode 0600, replacing it in one step so a crash never leaves half a
217
+ * file. Env vars are not written. Refuses to overwrite a malformed file.
218
+ */
219
+ export function saveConfig(patch, env = process.env) {
220
+ const path = configPath(env);
221
+ const next = { ...readStored(path), version: 1 };
222
+ for (const [key, value] of Object.entries(patch)) {
223
+ if (value !== undefined)
224
+ next[key] = value;
225
+ }
226
+ const parsed = storedConfigSchema.safeParse(next);
227
+ if (!parsed.success)
228
+ throw new ConfigError(`Cannot save settings: ${describeIssues(parsed.error)}.`);
229
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
230
+ const temp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
231
+ try {
232
+ writeFileSync(temp, `${JSON.stringify(parsed.data, null, 2)}\n`, { mode: 0o600 });
233
+ chmodSync(temp, 0o600);
234
+ renameSync(temp, path);
235
+ }
236
+ catch (error) {
237
+ rmSync(temp, { force: true });
238
+ const code = error.code;
239
+ throw new ConfigError(`Cannot write the config file ${path} (${code ?? "unknown error"}).`);
240
+ }
241
+ }
@@ -0,0 +1,37 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/config/src/paths.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ import { homedir } from "node:os";
4
+ import { posix, win32 } from "node:path";
5
+ /** Read an env var, treating an empty or blank value as unset. */
6
+ export function envValue(env, name) {
7
+ const value = env[name]?.trim();
8
+ return value ? value : undefined;
9
+ }
10
+ /**
11
+ * Where the settings file lives:
12
+ * - `CLIPY_LOCAL_CONFIG`, when set, wins everywhere.
13
+ * - macOS: `~/Library/Application Support/clipy-local/config.json`.
14
+ * - Windows: `%APPDATA%\clipy-local\config.json`.
15
+ * - Linux and others: `$XDG_CONFIG_HOME/clipy-local/config.json`, or
16
+ * `~/.config/clipy-local/config.json` when XDG_CONFIG_HOME is unset or not
17
+ * an absolute path (the XDG spec says to ignore relative values).
18
+ */
19
+ export function configPath(env = process.env, platform = process.platform) {
20
+ const override = envValue(env, "CLIPY_LOCAL_CONFIG");
21
+ if (override)
22
+ return override;
23
+ if (platform === "win32") {
24
+ const appData = envValue(env, "APPDATA");
25
+ if (appData)
26
+ return win32.join(appData, "clipy-local", "config.json");
27
+ const home = envValue(env, "USERPROFILE") ?? homedir();
28
+ return win32.join(home, "AppData", "Roaming", "clipy-local", "config.json");
29
+ }
30
+ const home = envValue(env, "HOME") ?? homedir();
31
+ if (platform === "darwin") {
32
+ return posix.join(home, "Library", "Application Support", "clipy-local", "config.json");
33
+ }
34
+ const xdg = envValue(env, "XDG_CONFIG_HOME");
35
+ const base = xdg && posix.isAbsolute(xdg) ? xdg : posix.join(home, ".config");
36
+ return posix.join(base, "clipy-local", "config.json");
37
+ }
@@ -0,0 +1,61 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/config/src/presets.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ import { DEFAULT_OPENROUTER_MODEL, PROVIDER_BASE_URLS } from "../moments/index.js";
4
+ import { ConfigError } from "./errors.js";
5
+ import { isHttpUrl } from "./schema.js";
6
+ /** Default model per preset. Ollama, LM Studio and custom have none: the user picks what they run. */
7
+ export const DEFAULT_MODELS = {
8
+ openrouter: DEFAULT_OPENROUTER_MODEL, // google/gemini-3.1-flash-lite, as the hosted planner uses
9
+ openai: "gpt-4.1-mini",
10
+ gemini: "gemini-2.5-flash",
11
+ groq: "llama-3.3-70b-versatile",
12
+ };
13
+ /** Presets that run on the user's machine and need no key. */
14
+ const LOCAL_PRESETS = new Set(["ollama", "lmstudio"]);
15
+ const PRESET_NAMES = {
16
+ openrouter: "OpenRouter",
17
+ openai: "OpenAI",
18
+ gemini: "Gemini",
19
+ groq: "Groq",
20
+ ollama: "Ollama",
21
+ lmstudio: "LM Studio",
22
+ custom: "A custom provider",
23
+ };
24
+ /** OpenAI-compatible transcription endpoints behind the `openai` and `groq` shorthands. */
25
+ export const TRANSCRIPTION_PRESETS = {
26
+ openai: { baseUrl: "https://api.openai.com/v1", model: "whisper-1" },
27
+ groq: { baseUrl: "https://api.groq.com/openai/v1", model: "whisper-large-v3-turbo" },
28
+ };
29
+ /**
30
+ * The ModelProvider for a preset. `baseUrl` replaces the preset's URL and is
31
+ * required for `custom`. Throws a ConfigError when something the preset needs
32
+ * is missing: a key for the hosted presets, a model name for Ollama, LM Studio
33
+ * and custom.
34
+ */
35
+ export function presetProvider(preset, apiKey, model, baseUrl) {
36
+ const name = PRESET_NAMES[preset];
37
+ if (!name)
38
+ throw new ConfigError(`Unknown model provider "${String(preset)}". Use one of ${Object.keys(PRESET_NAMES).join(", ")}.`);
39
+ const url = baseUrl?.trim() || (preset === "custom" ? undefined : PROVIDER_BASE_URLS[preset]);
40
+ if (!url) {
41
+ throw new ConfigError(`${name} needs a base URL. Set CLIPY_MODEL_BASE_URL or "model.baseUrl" in the config file.`);
42
+ }
43
+ if (!isHttpUrl(url)) {
44
+ throw new ConfigError(`The model base URL must be an http:// or https:// URL.`);
45
+ }
46
+ const key = apiKey?.trim() || undefined;
47
+ if (!key && preset !== "custom" && !LOCAL_PRESETS.has(preset)) {
48
+ throw new ConfigError(`${name} needs an API key. Set CLIPY_MODEL_API_KEY or "model.apiKey" in the config file.`);
49
+ }
50
+ const chosenModel = model?.trim() || DEFAULT_MODELS[preset];
51
+ if (!chosenModel) {
52
+ throw new ConfigError(`${name} needs a model name, for example the name of a model you have pulled or loaded. ` +
53
+ `Set CLIPY_MODEL or "model.model" in the config file.`);
54
+ }
55
+ const provider = { baseUrl: url, model: chosenModel };
56
+ if (key)
57
+ provider.apiKey = key;
58
+ if (preset === "openrouter")
59
+ provider.headers = { "HTTP-Referer": "https://clipy.online", "X-Title": "Clipy" };
60
+ return provider;
61
+ }
@@ -0,0 +1,66 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // GENERATED from oss/packages/config/src/schema.ts by cli/scripts/sync-local.mjs. Do not edit here.
3
+ import { z } from "zod";
4
+ export const MODEL_PRESETS = ["openrouter", "openai", "gemini", "groq", "ollama", "lmstudio", "custom"];
5
+ export const LOCAL_TRANSCRIPTION_MODELS = ["english-fast", "multilingual"];
6
+ /** Hosted transcription services that take only a key (and optionally a model). */
7
+ export const KEYED_TRANSCRIPTION_KINDS = ["deepgram", "assemblyai", "elevenlabs", "gemini"];
8
+ /** Every value `transcription.kind` and `CLIPY_TRANSCRIBE` accept. */
9
+ export const TRANSCRIPTION_KINDS = [
10
+ "none",
11
+ "local",
12
+ "openai",
13
+ "groq",
14
+ "openai-compatible",
15
+ ...KEYED_TRANSCRIPTION_KINDS,
16
+ ];
17
+ const HTTP_URL_MESSAGE = "must be an http:// or https:// URL";
18
+ export function isHttpUrl(value) {
19
+ try {
20
+ const url = new URL(value);
21
+ return url.protocol === "http:" || url.protocol === "https:";
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ const nonEmpty = z.string().trim().min(1, "must not be empty");
28
+ const httpUrl = z.string().trim().refine(isHttpUrl, HTTP_URL_MESSAGE);
29
+ const storedModelSchema = z.strictObject({
30
+ preset: z.enum(MODEL_PRESETS),
31
+ apiKey: nonEmpty.optional(),
32
+ model: nonEmpty.optional(),
33
+ baseUrl: httpUrl.optional(),
34
+ });
35
+ const storedTranscriptionSchema = z.discriminatedUnion("kind", [
36
+ z.strictObject({ kind: z.literal("none") }),
37
+ z.strictObject({ kind: z.literal("local"), model: z.enum(LOCAL_TRANSCRIPTION_MODELS).optional() }),
38
+ z.strictObject({ kind: z.enum(["openai", "groq"]), apiKey: nonEmpty, model: nonEmpty.optional() }),
39
+ z.strictObject({ kind: z.literal("openai-compatible"), baseUrl: httpUrl, apiKey: nonEmpty.optional(), model: nonEmpty }),
40
+ z.strictObject({ kind: z.enum(KEYED_TRANSCRIPTION_KINDS), apiKey: nonEmpty, model: nonEmpty.optional() }),
41
+ ]);
42
+ export const storedConfigSchema = z.looseObject({
43
+ version: z.literal(1).optional(),
44
+ model: storedModelSchema.nullable().optional(),
45
+ transcription: storedTranscriptionSchema.optional(),
46
+ });
47
+ /**
48
+ * One line per problem, naming the field. Zod issues here never carry the
49
+ * input value, so a key in the file cannot end up in the message.
50
+ */
51
+ export function describeIssues(error) {
52
+ return error.issues
53
+ .slice(0, 5)
54
+ .map((issue) => {
55
+ const path = issue.path.map(String);
56
+ let message = issue.message;
57
+ if (issue.code === "invalid_union" && "discriminator" in issue && typeof issue.discriminator === "string") {
58
+ if (path[path.length - 1] !== issue.discriminator)
59
+ path.push(issue.discriminator);
60
+ message = `must be one of ${TRANSCRIPTION_KINDS.join(", ")}`;
61
+ }
62
+ const field = path.length ? `"${path.join(".")}"` : "the file";
63
+ return path.length ? `${field}: ${message}` : `${field} must contain a JSON object`;
64
+ })
65
+ .join("; ");
66
+ }
@@ -0,0 +1,127 @@
1
+ const STROKE_VISIBLE_AFTER_END_MS = 6000;
2
+ const MAX_FRAME_FILTERS = 160;
3
+ export function activeDrawStrokesAt(track, tMs) {
4
+ if (!track || !Number.isFinite(tMs))
5
+ return [];
6
+ return track.strokes.flatMap((stroke) => {
7
+ if (tMs < stroke.start_ms || tMs > stroke.end_ms + STROKE_VISIBLE_AFTER_END_MS) {
8
+ return [];
9
+ }
10
+ const points = tMs < stroke.end_ms
11
+ ? stroke.points.filter((point) => point.time_ms <= tMs)
12
+ : stroke.points;
13
+ if (stroke.kind === 'pen' || stroke.kind === 'arrow' || stroke.kind === 'rect') {
14
+ return points.length >= 2 ? [{ ...stroke, points }] : [];
15
+ }
16
+ return stroke.start_ms <= tMs ? [stroke] : [];
17
+ });
18
+ }
19
+ export function buildDrawStrokeFrameFilters(strokes) {
20
+ const filters = [];
21
+ const activeStrokes = strokes.slice(0, 24);
22
+ for (let i = 0; i < activeStrokes.length; i += 1) {
23
+ const stroke = activeStrokes[i];
24
+ if (filters.length >= MAX_FRAME_FILTERS)
25
+ break;
26
+ const remainingStrokeSlots = activeStrokes.length - i;
27
+ const strokeBudget = Math.max(4, Math.floor((MAX_FRAME_FILTERS - filters.length) / remainingStrokeSlots));
28
+ const color = hexToFfmpegHex(stroke.color);
29
+ if (stroke.kind === 'pen') {
30
+ filters.push(...budgetedFilters(filters, lineDrawboxes(stroke.points, color, 7), strokeBudget));
31
+ }
32
+ else if (stroke.kind === 'arrow') {
33
+ const points = stroke.points.slice(0, 2);
34
+ filters.push(...budgetedFilters(filters, lineDrawboxes(points, color, 7), strokeBudget));
35
+ if (points.length === 2) {
36
+ filters.push(...budgetedFilters(filters, arrowHeadDrawboxes(points[0], points[1], color), strokeBudget));
37
+ }
38
+ }
39
+ else if (stroke.kind === 'rect') {
40
+ const a = stroke.points[0];
41
+ const b = stroke.points[1];
42
+ if (a && b) {
43
+ const x = Math.min(a.x, b.x);
44
+ const y = Math.min(a.y, b.y);
45
+ const w = Math.abs(a.x - b.x);
46
+ const h = Math.abs(a.y - b.y);
47
+ if (w > 0.002 && h > 0.002) {
48
+ appendFilter(filters, `drawbox=x='iw*${x.toFixed(5)}':y='ih*${y.toFixed(5)}':` +
49
+ `w='iw*${w.toFixed(5)}':h='ih*${h.toFixed(5)}':` +
50
+ `color=${color}@0.94:t=5`);
51
+ }
52
+ }
53
+ }
54
+ else if (stroke.kind === 'text') {
55
+ const p = stroke.points[0];
56
+ const text = stroke.text?.trim();
57
+ if (p && text) {
58
+ appendFilter(filters, `drawbox=x='iw*${p.x.toFixed(5)}-16':y='ih*${p.y.toFixed(5)}-16':` +
59
+ `w=32:h=32:color=${color}@0.96:t=4`);
60
+ }
61
+ }
62
+ else if (stroke.kind === 'step') {
63
+ const p = stroke.points[0];
64
+ if (p && typeof stroke.value === 'number') {
65
+ appendFilter(filters, `drawbox=x='iw*${p.x.toFixed(5)}-18':y='ih*${p.y.toFixed(5)}-18':` +
66
+ `w=36:h=36:color=${color}@0.96:t=fill`);
67
+ }
68
+ }
69
+ }
70
+ return filters.length > 0 ? `,${filters.join(',')}` : '';
71
+ }
72
+ function budgetedFilters(existing, next, strokeBudget) {
73
+ return next.slice(0, Math.max(0, Math.min(strokeBudget, MAX_FRAME_FILTERS - existing.length)));
74
+ }
75
+ function appendFilter(filters, filter) {
76
+ if (filters.length < MAX_FRAME_FILTERS) {
77
+ filters.push(filter);
78
+ }
79
+ }
80
+ function lineDrawboxes(points, color, thickness) {
81
+ const finitePoints = points
82
+ .filter((point) => Number.isFinite(point.x) && Number.isFinite(point.y))
83
+ .sort((a, b) => a.time_ms - b.time_ms);
84
+ const clean = decimatePoints(finitePoints, 80);
85
+ if (clean.length < 2)
86
+ return [];
87
+ return clean.map((point) => `drawbox=x='iw*${point.x.toFixed(5)}-${Math.round(thickness / 2)}':` +
88
+ `y='ih*${point.y.toFixed(5)}-${Math.round(thickness / 2)}':` +
89
+ `w=${thickness}:h=${thickness}:color=${color}@0.96:t=fill`);
90
+ }
91
+ function decimatePoints(points, maxPoints) {
92
+ if (points.length <= maxPoints)
93
+ return points;
94
+ if (maxPoints <= 1)
95
+ return points.slice(0, 1);
96
+ const out = [];
97
+ const last = points.length - 1;
98
+ for (let i = 0; i < maxPoints; i += 1) {
99
+ out.push(points[Math.round((i * last) / (maxPoints - 1))]);
100
+ }
101
+ return out;
102
+ }
103
+ function arrowHeadDrawboxes(from, to, color) {
104
+ const angle = Math.atan2(to.y - from.y, to.x - from.x);
105
+ const len = 0.035;
106
+ const left = {
107
+ ...to,
108
+ x: to.x - Math.cos(angle - Math.PI / 6) * len,
109
+ y: to.y - Math.sin(angle - Math.PI / 6) * len,
110
+ };
111
+ const right = {
112
+ ...to,
113
+ x: to.x - Math.cos(angle + Math.PI / 6) * len,
114
+ y: to.y - Math.sin(angle + Math.PI / 6) * len,
115
+ };
116
+ return [
117
+ ...lineDrawboxes([left, to], color, 7),
118
+ ...lineDrawboxes([right, to], color, 7),
119
+ ];
120
+ }
121
+ function hexToFfmpegHex(css) {
122
+ const normalized = css.trim();
123
+ if (/^#[0-9a-fA-F]{6}$/.test(normalized)) {
124
+ return `0x${normalized.slice(1)}`;
125
+ }
126
+ return '0xff5a36';
127
+ }