@tmhs/screencast-mcp 0.47.0 → 0.48.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.
package/dist/setup.js ADDED
@@ -0,0 +1,437 @@
1
+ import { spawn } from "node:child_process";
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ export const CLIENT_IDS = ["claude-desktop", "claude-code", "cursor", "vscode"];
7
+ export const SETUP_USAGE = `setup options:
8
+ --yes answer yes: install FFmpeg and write client configs without asking
9
+ --dry-run print the checks and the config changes; change nothing
10
+ --clients <list> detected (default) | none | a comma list of
11
+ ${CLIENT_IDS.join(", ")}
12
+ --no-install never offer to install FFmpeg
13
+ --force replace an existing, different "screencast" server entry
14
+ --test record a 3 s test clip and export a GIF
15
+
16
+ setup exits 0 when the doctor checks pass, 1 when something still needs fixing.
17
+ `;
18
+ export const PACKAGE = "@tmhs/screencast-mcp";
19
+ export const SERVER_NAME = "screencast";
20
+ const NPX = { command: "npx", args: ["-y", PACKAGE] };
21
+ export const WINGET_FFMPEG = ["install", "--id", "Gyan.FFmpeg", "-e", "--accept-source-agreements", "--accept-package-agreements"];
22
+ export function parseSetupArgs(argv) {
23
+ const options = { yes: false, dryRun: false, install: true, clients: "detected", force: false, test: false };
24
+ for (let i = 0; i < argv.length; i++) {
25
+ const raw = argv[i] ?? "";
26
+ const eq = raw.startsWith("--") ? raw.indexOf("=") : -1;
27
+ const flag = eq === -1 ? raw : raw.slice(0, eq);
28
+ switch (flag) {
29
+ case "--yes":
30
+ case "-y":
31
+ options.yes = true;
32
+ break;
33
+ case "--dry-run":
34
+ options.dryRun = true;
35
+ break;
36
+ case "--no-install":
37
+ options.install = false;
38
+ break;
39
+ case "--force":
40
+ options.force = true;
41
+ break;
42
+ case "--test":
43
+ options.test = true;
44
+ break;
45
+ case "--clients": {
46
+ let value;
47
+ if (eq !== -1)
48
+ value = raw.slice(eq + 1);
49
+ else
50
+ value = argv[++i];
51
+ if (value === undefined || value === "")
52
+ throw new Error("--clients needs a value.");
53
+ if (value === "detected" || value === "none") {
54
+ options.clients = value;
55
+ break;
56
+ }
57
+ const ids = value.split(",").map((s) => s.trim()).filter(Boolean);
58
+ const bad = ids.filter((id) => !CLIENT_IDS.includes(id));
59
+ if (bad.length > 0) {
60
+ throw new Error(`--clients: unknown client ${bad.map((b) => `"${b}"`).join(", ")}; use ${CLIENT_IDS.join(", ")}, detected, or none.`);
61
+ }
62
+ options.clients = ids;
63
+ break;
64
+ }
65
+ default:
66
+ throw new Error(`Unknown setup option "${raw}". Run screencast-mcp --help.`);
67
+ }
68
+ }
69
+ return options;
70
+ }
71
+ function appData(deps) {
72
+ return deps.env.APPDATA ?? join(deps.home, "AppData", "Roaming");
73
+ }
74
+ export function jsonClients(deps) {
75
+ const roaming = appData(deps);
76
+ return [
77
+ {
78
+ id: "claude-desktop",
79
+ name: "Claude Desktop",
80
+ path: join(roaming, "Claude", "claude_desktop_config.json"),
81
+ key: "mcpServers",
82
+ entry: NPX,
83
+ marker: join(roaming, "Claude"),
84
+ },
85
+ {
86
+ id: "cursor",
87
+ name: "Cursor",
88
+ path: join(deps.home, ".cursor", "mcp.json"),
89
+ key: "mcpServers",
90
+ entry: NPX,
91
+ marker: join(deps.home, ".cursor"),
92
+ },
93
+ {
94
+ id: "vscode",
95
+ name: "VS Code",
96
+ path: join(roaming, "Code", "User", "mcp.json"),
97
+ key: "servers",
98
+ entry: { type: "stdio", ...NPX },
99
+ marker: join(roaming, "Code", "User"),
100
+ },
101
+ ];
102
+ }
103
+ export function claudeCodeArgs(platform) {
104
+ const run = platform === "win32" ? ["cmd", "/c", "npx", "-y", PACKAGE] : ["npx", "-y", PACKAGE];
105
+ return ["mcp", "add", "--scope", "user", SERVER_NAME, "--", ...run];
106
+ }
107
+ const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
108
+ export function mergeServerConfig(existing, key, name, entry, force = false) {
109
+ let config = {};
110
+ if (existing !== null && existing.trim() !== "") {
111
+ let parsed;
112
+ try {
113
+ parsed = JSON.parse(existing.charCodeAt(0) === 0xfeff ? existing.slice(1) : existing);
114
+ }
115
+ catch (err) {
116
+ return { status: "invalid", reason: `not plain JSON (${err instanceof Error ? err.message : String(err)})` };
117
+ }
118
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
119
+ return { status: "invalid", reason: "the file is not a JSON object" };
120
+ }
121
+ config = parsed;
122
+ }
123
+ const servers = config[key] ?? {};
124
+ if (typeof servers !== "object" || servers === null || Array.isArray(servers)) {
125
+ return { status: "invalid", reason: `"${key}" is not an object` };
126
+ }
127
+ const current = servers[name];
128
+ if (current !== undefined) {
129
+ if (sameJson(current, entry))
130
+ return { status: "unchanged" };
131
+ if (!force)
132
+ return { status: "conflict", existing: current };
133
+ }
134
+ const next = { ...config, [key]: { ...servers, [name]: entry } };
135
+ return { status: "added", text: JSON.stringify(next, null, 2) + "\n" };
136
+ }
137
+ export function lineDiff(before, after) {
138
+ const a = before === "" ? [] : before.replace(/\n$/, "").split("\n");
139
+ const b = after === "" ? [] : after.replace(/\n$/, "").split("\n");
140
+ const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
141
+ for (let i = a.length - 1; i >= 0; i--) {
142
+ for (let j = b.length - 1; j >= 0; j--) {
143
+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
144
+ }
145
+ }
146
+ const out = [];
147
+ let i = 0;
148
+ let j = 0;
149
+ while (i < a.length || j < b.length) {
150
+ if (i < a.length && j < b.length && a[i] === b[j]) {
151
+ out.push(` ${a[i]}`);
152
+ i++;
153
+ j++;
154
+ }
155
+ else if (j < b.length && (i >= a.length || lcs[i][j + 1] >= lcs[i + 1][j])) {
156
+ out.push(`+ ${b[j]}`);
157
+ j++;
158
+ }
159
+ else {
160
+ out.push(`- ${a[i]}`);
161
+ i++;
162
+ }
163
+ }
164
+ return out.join("\n") + "\n";
165
+ }
166
+ export function backupPath(path, now) {
167
+ const p = (n) => String(n).padStart(2, "0");
168
+ const stamp = `${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`;
169
+ return `${path}.bak-${stamp}`;
170
+ }
171
+ export function checklist(report, env, platform) {
172
+ const lines = [];
173
+ const nodeMajor = Number((report.server?.node ?? process.version).replace(/^v/, "").split(".")[0]);
174
+ lines.push({ state: nodeMajor >= 22 ? "ok" : "fail", text: `Node.js ${report.server?.node ?? process.version}${nodeMajor >= 22 ? "" : " (needs 22+)"}` });
175
+ const ff = report.ffmpeg ?? {};
176
+ if (!ff.found)
177
+ lines.push({ state: "fail", text: "FFmpeg not found on PATH (or FFMPEG_PATH)" });
178
+ else if (ff.meetsFfmpeg8 === false)
179
+ lines.push({ state: "warn", text: `FFmpeg ${ff.version ?? "?"}: works, but transcribe and backend "wgc" need FFmpeg 8+` });
180
+ else
181
+ lines.push({ state: "ok", text: `FFmpeg ${ff.version ?? "?"}${ff.path ? ` (${ff.path})` : ""}` });
182
+ lines.push(report.ffprobe?.found ? { state: "ok", text: `ffprobe ${report.ffprobe.version ?? ""}`.trim() } : { state: "fail", text: "ffprobe not found" });
183
+ if (platform === "win32") {
184
+ lines.push({ state: report.devices?.gdigrab ? "ok" : "fail", text: report.devices?.gdigrab ? "Screen capture (gdigrab)" : "No gdigrab: this ffmpeg cannot capture the screen" });
185
+ lines.push({ state: report.wgc?.available ? "ok" : "info", text: report.wgc?.available ? "Windows Graphics Capture (backend wgc)" : 'Windows Graphics Capture unavailable (backend "wgc" needs FFmpeg 8)' });
186
+ lines.push(report.ocr?.available
187
+ ? { state: "ok", text: `Windows OCR${report.ocr.language ? ` (${report.ocr.language})` : ""}` }
188
+ : { state: "warn", text: "Windows OCR unavailable: find_text cannot read the screen (add an OCR language in Settings > Time & language > Language)" });
189
+ if (report.tts) {
190
+ lines.push(report.tts.available ? { state: "ok", text: "Windows speech (narrate)" } : { state: "warn", text: "No Windows voice: narrate cannot speak" });
191
+ }
192
+ }
193
+ else {
194
+ lines.push({ state: "warn", text: "Not Windows: capture and OCR are unavailable; the edit and watch tools work" });
195
+ }
196
+ const model = report.env?.SCREENCAST_WHISPER_MODEL ?? env.SCREENCAST_WHISPER_MODEL;
197
+ lines.push(model
198
+ ? { state: "ok", text: `Whisper model: ${model}` }
199
+ : { state: "info", text: "transcribe needs a Whisper model: download a ggml model and set SCREENCAST_WHISPER_MODEL to its path" });
200
+ return lines;
201
+ }
202
+ const MARK = { ok: "[ok] ", warn: "[warn]", fail: "[fail]", info: "[info]" };
203
+ async function configureJsonClient(client, opts, deps) {
204
+ const { fs } = deps;
205
+ const had = fs.exists(client.path);
206
+ let text = null;
207
+ if (had) {
208
+ try {
209
+ text = fs.readFile(client.path);
210
+ }
211
+ catch (err) {
212
+ deps.out(` ${client.name}: could not read ${client.path}: ${err instanceof Error ? err.message : String(err)}\n`);
213
+ return false;
214
+ }
215
+ }
216
+ const merged = mergeServerConfig(text, client.key, SERVER_NAME, client.entry, opts.force);
217
+ switch (merged.status) {
218
+ case "unchanged":
219
+ deps.out(` ${client.name}: already configured (${client.path})\n`);
220
+ return true;
221
+ case "invalid":
222
+ deps.out(` ${client.name}: left ${client.path} alone: ${merged.reason}. Add the server by hand (see docs/connect.html).\n`);
223
+ return false;
224
+ case "conflict":
225
+ deps.out(` ${client.name}: ${client.path} already has a different "${SERVER_NAME}" entry; kept it (pass --force to replace).\n`);
226
+ return false;
227
+ }
228
+ if (opts.dryRun) {
229
+ deps.out(` ${client.name}: would ${had ? "update" : "create"} ${client.path}:\n`);
230
+ deps.out(lineDiff(text ?? "", merged.text).replace(/^/gm, " "));
231
+ return true;
232
+ }
233
+ if (!opts.yes && !(await deps.confirm(`Add the screencast server to ${client.name} (${client.path})?`))) {
234
+ deps.out(` ${client.name}: skipped (run with --yes to write it, or --dry-run to see the change).\n`);
235
+ return false;
236
+ }
237
+ try {
238
+ let backup = null;
239
+ if (had) {
240
+ backup = backupPath(client.path, deps.now());
241
+ fs.copyFile(client.path, backup);
242
+ }
243
+ else {
244
+ fs.mkdir(dirname(client.path));
245
+ }
246
+ fs.writeFile(client.path, merged.text);
247
+ deps.out(` ${client.name}: ${had ? "updated" : "created"} ${client.path}${backup ? ` (backup: ${backup})` : ""}. Restart it to load the server.\n`);
248
+ return true;
249
+ }
250
+ catch (err) {
251
+ deps.out(` ${client.name}: could not write ${client.path}: ${err instanceof Error ? err.message : String(err)}\n`);
252
+ return false;
253
+ }
254
+ }
255
+ async function configureClaudeCode(opts, deps) {
256
+ const args = claudeCodeArgs(deps.platform);
257
+ const existing = await deps.exec("claude", ["mcp", "get", SERVER_NAME]);
258
+ if (existing.code === 0) {
259
+ deps.out(` Claude Code: already has a "${SERVER_NAME}" server (claude mcp get ${SERVER_NAME}).\n`);
260
+ return true;
261
+ }
262
+ if (opts.dryRun) {
263
+ deps.out(` Claude Code: would run: claude ${args.join(" ")}\n`);
264
+ return true;
265
+ }
266
+ if (!opts.yes && !(await deps.confirm("Add the screencast server to Claude Code (user scope)?"))) {
267
+ deps.out(` Claude Code: skipped. To add it yourself: claude ${args.join(" ")}\n`);
268
+ return false;
269
+ }
270
+ const res = await deps.exec("claude", args);
271
+ if (res.code !== 0) {
272
+ deps.out(` Claude Code: claude mcp add failed (${(res.stderr || res.stdout).trim() || `exit ${res.code}`}).\n`);
273
+ return false;
274
+ }
275
+ deps.out(" Claude Code: added (user scope). Check it with claude mcp list.\n");
276
+ return true;
277
+ }
278
+ async function detectedClients(deps) {
279
+ const found = [];
280
+ for (const c of jsonClients(deps))
281
+ if (deps.fs.exists(c.marker))
282
+ found.push(c.id);
283
+ const claude = await deps.exec("claude", ["--version"]).catch(() => ({ code: 1, stdout: "", stderr: "" }));
284
+ if (claude.code === 0)
285
+ found.push("claude-code");
286
+ return CLIENT_IDS.filter((id) => found.includes(id));
287
+ }
288
+ export async function runSetup(opts, deps) {
289
+ const say = deps.out;
290
+ say(`screencast-mcp setup${opts.dryRun ? " (dry run: nothing is installed or written)" : ""}\n\n`);
291
+ let report;
292
+ try {
293
+ report = await deps.doctor();
294
+ }
295
+ catch (err) {
296
+ deps.err(`screencast-mcp: the doctor checks failed to run: ${err instanceof Error ? err.message : String(err)}\n`);
297
+ return 1;
298
+ }
299
+ for (const line of checklist(report, deps.env, deps.platform))
300
+ say(`${MARK[line.state]} ${line.text}\n`);
301
+ const problems = report.problems ?? [];
302
+ if (problems.length > 0) {
303
+ say("\nWhat doctor says to fix:\n");
304
+ for (const p of problems)
305
+ say(` - ${p}\n`);
306
+ }
307
+ const ff = report.ffmpeg ?? {};
308
+ const needsFfmpeg = !ff.found || ff.meetsFfmpeg8 === false;
309
+ if (needsFfmpeg && opts.install && deps.platform === "win32") {
310
+ const line = `winget ${WINGET_FFMPEG.join(" ")}`;
311
+ say(`\nFFmpeg 8 ${ff.found ? "is not installed (found an older one)" : "is missing"}.\n`);
312
+ if (opts.dryRun) {
313
+ say(` would run: ${line}\n`);
314
+ }
315
+ else if (opts.yes || (await deps.confirm("Install FFmpeg 8 with winget now?"))) {
316
+ say(` running: ${line}\n`);
317
+ const res = await deps.exec("winget", WINGET_FFMPEG).catch((err) => ({
318
+ code: 1,
319
+ stdout: "",
320
+ stderr: err instanceof Error ? err.message : String(err),
321
+ }));
322
+ if (res.code === 0)
323
+ say(" FFmpeg installed. Open a new terminal so PATH picks it up, then run setup again.\n");
324
+ else
325
+ say(` winget failed (${(res.stderr || res.stdout).trim().split("\n").pop() || `exit ${res.code}`}). Install it yourself: ${line}\n`);
326
+ }
327
+ else {
328
+ say(` skipped. Install it yourself: ${line}\n`);
329
+ }
330
+ }
331
+ if (opts.clients !== "none") {
332
+ const ids = opts.clients === "detected" ? await detectedClients(deps) : opts.clients;
333
+ say("\nMCP clients:\n");
334
+ if (ids.length === 0) {
335
+ say(" none found (Claude Desktop, Claude Code, Cursor, VS Code). Name one with --clients, or see docs/connect.html.\n");
336
+ }
337
+ const byId = new Map(jsonClients(deps).map((c) => [c.id, c]));
338
+ for (const id of ids) {
339
+ const json = byId.get(id);
340
+ if (json)
341
+ await configureJsonClient(json, opts, deps);
342
+ else
343
+ await configureClaudeCode(opts, deps);
344
+ }
345
+ }
346
+ if (opts.test) {
347
+ say("\nTest clip:\n");
348
+ if (opts.dryRun) {
349
+ say(" would record 3 s of the screen and export a GIF.\n");
350
+ }
351
+ else {
352
+ try {
353
+ const gif = await deps.testClip();
354
+ say(` recorded 3 s and exported ${gif}\n`);
355
+ await deps.open(gif).catch(() => undefined);
356
+ }
357
+ catch (err) {
358
+ say(` the test clip failed: ${err instanceof Error ? err.message : String(err)}\n`);
359
+ return 1;
360
+ }
361
+ }
362
+ }
363
+ const ok = report.ok ?? problems.length === 0;
364
+ say(ok ? "\nAll checks passed.\n" : "\nSome checks need attention (above). Run setup again after fixing them.\n");
365
+ return ok ? 0 : 1;
366
+ }
367
+ function execReal(platform) {
368
+ return (cmd, args) => new Promise((resolveExec) => {
369
+ const child = spawn(cmd, args, { shell: platform === "win32", windowsHide: true });
370
+ let stdout = "";
371
+ let stderr = "";
372
+ child.stdout?.on("data", (d) => (stdout += d.toString()));
373
+ child.stderr?.on("data", (d) => (stderr += d.toString()));
374
+ child.on("error", (err) => resolveExec({ code: 127, stdout, stderr: err.message }));
375
+ child.on("close", (code) => resolveExec({ code: code ?? 1, stdout, stderr }));
376
+ });
377
+ }
378
+ const realFs = {
379
+ exists: (p) => existsSync(p),
380
+ readFile: (p) => readFileSync(p, "utf8"),
381
+ writeFile: (p, s) => writeFileSync(p, s),
382
+ mkdir: (p) => void mkdirSync(p, { recursive: true }),
383
+ copyFile: (a, b) => copyFileSync(a, b),
384
+ };
385
+ export function defaultSetupDeps(base) {
386
+ const platform = process.platform;
387
+ const exec = execReal(platform);
388
+ const withClient = async (fn) => {
389
+ const client = await base.connect();
390
+ try {
391
+ return await fn(client);
392
+ }
393
+ finally {
394
+ await client.close();
395
+ }
396
+ };
397
+ const must = async (c, name, args) => {
398
+ const res = await c.call(name, args);
399
+ if (res.isError)
400
+ throw new Error(`${name}: ${res.text}`);
401
+ return res.structured ?? {};
402
+ };
403
+ return {
404
+ out: base.io.out,
405
+ err: base.io.err,
406
+ env: process.env,
407
+ platform,
408
+ home: homedir(),
409
+ fs: realFs,
410
+ exec,
411
+ doctor: () => withClient(async (c) => (await must(c, "doctor", {}))),
412
+ confirm: async (question) => {
413
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
414
+ return false;
415
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
416
+ try {
417
+ return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim());
418
+ }
419
+ finally {
420
+ rl.close();
421
+ }
422
+ },
423
+ testClip: () => withClient(async (c) => {
424
+ const started = await must(c, "start_recording", { target: "full", fps: 15, maxDurationSec: 30 });
425
+ await new Promise((r) => setTimeout(r, 3000));
426
+ const stopped = await must(c, "stop_recording", { sessionId: String(started.sessionId) });
427
+ const gif = await must(c, "export_gif", { input: String(stopped.outputPath) });
428
+ return String(gif.outputPath);
429
+ }),
430
+ open: async (path) => {
431
+ if (platform !== "win32" || !process.stdout.isTTY)
432
+ return;
433
+ spawn("explorer.exe", [path], { detached: true, stdio: "ignore" }).unref();
434
+ },
435
+ now: () => new Date(),
436
+ };
437
+ }
@@ -13,9 +13,9 @@ const inputSchema = {
13
13
  input: z.string().min(1).describe("Path to the source video."),
14
14
  srt: z.string().min(1).describe("Its .srt (transcribe; words: true for word timing)."),
15
15
  remove: z
16
- .array(z.union([z.number().int().min(1).max(99999), z.string().min(1)]))
16
+ .array(z.union([z.number().int().min(0).max(99999), z.string().min(1)]))
17
17
  .optional()
18
- .describe("Cue numbers, or transcript text quoted exactly (must occur once)."),
18
+ .describe("Cue numbers as the .srt numbers them, or transcript text quoted exactly (must occur once)."),
19
19
  fillers: z.boolean().optional().describe("Also cut fillers (um, uh...) that have their own cue."),
20
20
  dryRun: z.boolean().optional().describe("Only report the cuts."),
21
21
  output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
@@ -40,7 +40,7 @@ export function register(server) {
40
40
  const duration = info.durationSec;
41
41
  if (duration === null || !info.videoCodec)
42
42
  throw new ScreencastError(`Not a readable video: ${args.input}`);
43
- const cues = normalizeCues(parseSrt(readFileSync(args.srt, "utf8")));
43
+ const cues = normalizeCues(parseSrt(readFileSync(args.srt, "utf8"), { index: true }));
44
44
  if (cues.length === 0)
45
45
  throw new ScreencastError(`No cues in ${args.srt}.`);
46
46
  const { cuts, skippedFillers } = planTranscriptCuts(cues, { remove: args.remove, fillers: args.fillers });
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
- import { join } from "node:path";
3
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
6
  import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
@@ -12,7 +12,7 @@ import { ocrStatus } from "../utils/capabilities.js";
12
12
  import { parseEventsJsonl } from "../utils/events.js";
13
13
  import { resolveWhisperModel, buildTranscribeArgs, parseSrt, normalizeCues } from "../utils/captions.js";
14
14
  import { subdir, tempPath } from "../utils/paths.js";
15
- import { DEFAULT_INDEX_FRAMES, DEFAULT_INDEX_THRESHOLD, INDEX_VERSION, MAX_INDEX_FRAMES, attach, cueTexts, eventTexts, fingerprintFile, findIndex, indexWritePath, keyframeTime, markerTexts, mergeSegments, planKeyframes, readIndex, resolveRecording, sameFingerprint, segmentsFrom, writeIndex, } from "../utils/recordingIndex.js";
15
+ import { DEFAULT_INDEX_FRAMES, DEFAULT_INDEX_THRESHOLD, INDEX_VERSION, MAX_INDEX_FRAMES, attach, canReuseIndex, cueTexts, defaultTranscriptPath, eventTexts, fingerprintFile, findIndex, indexMatchesVideo, indexWritePath, keyframeTime, legacyIndexSidecarPath, markerTexts, maskSegmentText, mergeSegments, planKeyframes, readIndex, resolveRecording, segmentsFrom, writeIndex, } from "../utils/recordingIndex.js";
16
16
  const OCR_BATCH = 8;
17
17
  const inputSchema = {
18
18
  input: z.string().optional().describe("Recording path."),
@@ -47,12 +47,16 @@ export function register(server) {
47
47
  const fingerprint = fingerprintFile(source.path);
48
48
  const report = progressReporter(extra);
49
49
  const notes = [];
50
- const existingPath = args.force ? null : findIndex(source.path, edits);
50
+ const existingPath = args.force ? null : findIndex(source.path, edits, fingerprint);
51
51
  const prior = existingPath ? readIndex(existingPath) : null;
52
- const cached = prior !== null &&
53
- sameFingerprint(prior.fingerprint, fingerprint) &&
54
- prior.sceneThreshold === threshold &&
55
- prior.maxFrames === maxFrames;
52
+ let ocrNow = null;
53
+ const ocrAvailable = async () => (ocrNow ??= process.platform === "win32" && (await ocrStatus()).available);
54
+ const cached = canReuseIndex(prior, {
55
+ fingerprint,
56
+ sceneThreshold: threshold,
57
+ maxFrames,
58
+ ocrAvailable: prior !== null && !prior.ocr ? await ocrAvailable() : false,
59
+ });
56
60
  let segments;
57
61
  let framesRead = 0;
58
62
  let ocr = false;
@@ -70,7 +74,7 @@ export function register(server) {
70
74
  report?.(0.1);
71
75
  const spans = segmentsFrom(planKeyframes(parseSceneScan(scan.stdout), duration, maxFrames), duration);
72
76
  const texts = spans.map(() => []);
73
- ocr = process.platform === "win32" && (await ocrStatus()).available;
77
+ ocr = await ocrAvailable();
74
78
  if (ocr) {
75
79
  for (let b = 0; b < spans.length; b += OCR_BATCH) {
76
80
  extra.signal.throwIfAborted();
@@ -94,13 +98,14 @@ export function register(server) {
94
98
  const read = spans.map((s, i) => ({ ...s, ocr: texts[i] ?? [] }));
95
99
  segments = ocr ? mergeSegments(read) : read;
96
100
  }
101
+ segments = maskSegmentText(segments);
97
102
  const events = source.eventsPath ? eventTexts(parseEventsJsonl(readFileSync(source.eventsPath, "utf8"))) : [];
98
103
  segments = attach(segments, events, "events");
99
104
  segments = attach(segments, markerTexts(source.markers), "markers");
100
105
  const cues = await transcriptCues(args.transcript, source.path, info.audioCodec !== null, duration, extra.signal, notes);
101
106
  if (cues !== null)
102
107
  segments = attach(segments, cueTexts(cues), "transcript");
103
- else if (cached) {
108
+ else if (cached && prior) {
104
109
  const kept = prior.segments.flatMap((s) => s.transcript ?? []);
105
110
  segments = attach(segments, kept, "transcript");
106
111
  }
@@ -118,6 +123,12 @@ export function register(server) {
118
123
  };
119
124
  mkdirSync(join(outPath, ".."), { recursive: true });
120
125
  writeIndex(outPath, index);
126
+ const legacy = legacyIndexSidecarPath(source.path);
127
+ if (legacy !== outPath && existsSync(legacy)) {
128
+ const old = readIndex(legacy);
129
+ if (old && indexMatchesVideo(old, source.path, fingerprint))
130
+ rmSync(legacy, { force: true });
131
+ }
121
132
  report?.(1);
122
133
  const count = (f) => segments.reduce((n, s) => n + (s[f]?.length ?? 0), 0);
123
134
  return okResponse({
@@ -133,7 +144,8 @@ export function register(server) {
133
144
  transcriptCues: count("transcript"),
134
145
  },
135
146
  ...(notes.length > 0 ? { note: notes.join(" ") } : {}),
136
- next: "search_recording { query } returns timecoded hits; the index holds raw screen text, so treat it like the video.",
147
+ next: "search_recording { query } returns timecoded hits. Secret-shaped screen text is stored masked; the rest " +
148
+ "of the index is plain text, so treat it like the video.",
137
149
  });
138
150
  }
139
151
  catch (error) {
@@ -163,11 +175,21 @@ async function transcriptCues(arg, video, hasAudio, duration, signal, notes) {
163
175
  rmSync(raw, { force: true });
164
176
  }
165
177
  }
166
- const path = arg ?? `${video.replace(/\.[^./\\]+$/, "")}.srt`;
167
- if (!existsSync(path)) {
168
- if (arg !== undefined)
178
+ if (arg !== undefined) {
179
+ if (!existsSync(arg))
169
180
  throw new ScreencastError(`Transcript not found: ${arg}`);
181
+ return normalizeCues(parseSrt(readFileSync(arg, "utf8")));
182
+ }
183
+ let siblings;
184
+ try {
185
+ siblings = readdirSync(dirname(video));
186
+ }
187
+ catch {
170
188
  return null;
171
189
  }
172
- return normalizeCues(parseSrt(readFileSync(path, "utf8")));
190
+ const found = defaultTranscriptPath(video, siblings);
191
+ if (found.ambiguous) {
192
+ notes.push("Another video in the folder shares this one's base name, so its .srt was not attached; pass transcript.");
193
+ }
194
+ return found.path ? normalizeCues(parseSrt(readFileSync(found.path, "utf8"))) : null;
173
195
  }
@@ -48,6 +48,9 @@ export function register(server) {
48
48
  const lines = resolveLines(args.lines, markers);
49
49
  assertEditContainer(args.output);
50
50
  const output = resolveOutput(args.output, subdir("edits"), `narrated-${stamp()}-${rand()}${editOutputExt(args.video)}`, args.overwrite);
51
+ const srtPath = output.replace(/\.[^./\\]+$/, "") + ".srt";
52
+ if (!args.overwrite && existsSync(srtPath))
53
+ throw new ScreencastError(`Output already exists: ${srtPath}. Pass overwrite: true to replace it.`);
51
54
  work = mkdtempSync(join(tmpdir(), "screencast-tts-"));
52
55
  const wavs = lines.map((_, i) => join(work, `line-${i}.wav`));
53
56
  const voice = await synthesize(lines.map((l, i) => ({ text: l.text, path: wavs[i] })), { voice: args.voice, rate: args.rate, signal: extra.signal });
@@ -59,7 +62,6 @@ export function register(server) {
59
62
  duck: args.duck,
60
63
  });
61
64
  await runEditJob(ffArgs, { output, durationSec: info.durationSec, extra });
62
- const srtPath = output.replace(/\.[^./\\]+$/, "") + ".srt";
63
65
  writeFileSync(srtPath, formatSrt(narrationCues(placed, info.durationSec)));
64
66
  const inputMarkers = readMarkers(args.video);
65
67
  if (inputMarkers.length > 0)
@@ -6,7 +6,7 @@ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
6
  import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
7
7
  import { requireFfmpeg, probeMedia, hasFilter, runCapture, runFfmpeg, scriptLongFilters } from "../utils/ffmpeg.js";
8
8
  import { jobTimeoutMs, runEditJob } from "../utils/jobs.js";
9
- import { planPipeline, probeArgs, MAX_PIPELINE_STEPS } from "../utils/pipeline.js";
9
+ import { planPipeline, probeArgs, sidecarCues, MAX_PIPELINE_STEPS } from "../utils/pipeline.js";
10
10
  import { calloutFonts, prepareCalloutAssets } from "../utils/calloutAssets.js";
11
11
  import { exportAnimation } from "../utils/animExport.js";
12
12
  import { calloutItemSchema, fontFileSchema } from "./callout.js";
@@ -110,7 +110,8 @@ const inputSchema = {
110
110
  .enum(RECIPES)
111
111
  .optional()
112
112
  .describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = " +
113
- "+ audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step."),
113
+ "+ audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step; " +
114
+ "trim, redact, crop and cursor go first (source pixels and time)."),
114
115
  quality: z.enum(["draft", "standard", "high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),
115
116
  dryRun: z.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),
116
117
  output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
@@ -162,6 +163,16 @@ export function register(server) {
162
163
  hasAudio,
163
164
  };
164
165
  const timeout = jobTimeoutMs(info.durationSec);
166
+ const last = steps.at(-1);
167
+ if (!last)
168
+ throw new ScreencastError("Provide at least one step.");
169
+ const ext = last.op === "export_gif" ? `.${last.format ?? "gif"}` : ".mp4";
170
+ const output = resolveOutput(args.output, subdir("edits"), `pipeline-${stamp()}-${rand()}${ext}`, args.overwrite);
171
+ const transcribes = last.op !== "export_gif" && steps.some((s) => s.op === "burn_subtitles" && s.transcribe);
172
+ const sidecar = output.replace(/\.[^./\\]+$/, "") + ".srt";
173
+ if (transcribes && !args.overwrite && existsSync(sidecar)) {
174
+ throw new ScreencastError(`Output already exists: ${sidecar}. Pass overwrite: true to replace it.`);
175
+ }
165
176
  for (const [i, s] of steps.entries()) {
166
177
  if (s.op !== "burn_subtitles")
167
178
  continue;
@@ -203,11 +214,6 @@ export function register(server) {
203
214
  const freezes = parseFreezes(scan.stderr, total);
204
215
  idle = useAudio ? intersect(freezes, parseSilences(scan.stderr, total)) : freezes;
205
216
  }
206
- const last = steps.at(-1);
207
- if (!last)
208
- throw new ScreencastError("Provide at least one step.");
209
- const ext = last.op === "export_gif" ? `.${last.format ?? "gif"}` : ".mp4";
210
- const output = resolveOutput(args.output, subdir("edits"), `pipeline-${stamp()}-${rand()}${ext}`, args.overwrite);
211
217
  const work = mkdtempSync(join(tmpdir(), "screencast-pipeline-"));
212
218
  try {
213
219
  const assets = {};
@@ -292,8 +298,8 @@ export function register(server) {
292
298
  const cues = existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
293
299
  subtitles[p.step] = cues.length > 0 ? join(work, `s${p.step}.srt`) : "";
294
300
  if (cues.length > 0) {
295
- transcript = formatSrt(cues);
296
- writeFileSync(subtitles[p.step], transcript);
301
+ transcript = { cues, opsBefore: p.ops.length };
302
+ writeFileSync(subtitles[p.step], formatSrt(cues));
297
303
  }
298
304
  else
299
305
  warnings.push(`Step ${p.step + 1}: no speech was recognised; no captions.`);
@@ -360,8 +366,11 @@ export function register(server) {
360
366
  let subtitlesPath;
361
367
  if (transcript) {
362
368
  try {
363
- subtitlesPath = output.replace(/\.[^./\\]+$/, "") + ".srt";
364
- writeFileSync(subtitlesPath, transcript);
369
+ const cues = sidecarCues(transcript.cues, plan.timeOps, transcript.opsBefore);
370
+ if (cues.length > 0) {
371
+ writeFileSync(sidecar, formatSrt(cues));
372
+ subtitlesPath = sidecar;
373
+ }
365
374
  }
366
375
  catch {
367
376
  subtitlesPath = undefined;