@tmhs/screencast-mcp 0.44.2 → 0.46.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 (44) hide show
  1. package/README.md +58 -11
  2. package/assets/ui/player.html +9 -0
  3. package/assets/ui/player.js +20 -0
  4. package/dist/index.js +12 -0
  5. package/dist/prompts.js +34 -4
  6. package/dist/server.js +20 -0
  7. package/dist/tools/addMarker.js +89 -0
  8. package/dist/tools/backdrop.js +89 -0
  9. package/dist/tools/bugReport.js +266 -0
  10. package/dist/tools/chapters.js +156 -0
  11. package/dist/tools/contactSheet.js +19 -17
  12. package/dist/tools/cutByTranscript.js +86 -0
  13. package/dist/tools/findText.js +14 -64
  14. package/dist/tools/indexRecording.js +173 -0
  15. package/dist/tools/keystrokeOverlay.js +131 -0
  16. package/dist/tools/pipeline.js +251 -18
  17. package/dist/tools/reviewRecording.js +12 -0
  18. package/dist/tools/saveReplay.js +90 -0
  19. package/dist/tools/searchRecording.js +73 -0
  20. package/dist/tools/startRecording.js +51 -10
  21. package/dist/tools/stepGuide.js +193 -0
  22. package/dist/tools/stopRecording.js +25 -1
  23. package/dist/tools/transcribe.js +4 -3
  24. package/dist/tools/zoom.js +1 -1
  25. package/dist/utils/audio.js +12 -4
  26. package/dist/utils/backdrop.js +151 -0
  27. package/dist/utils/bugReport.js +172 -0
  28. package/dist/utils/captions.js +19 -6
  29. package/dist/utils/chapters.js +227 -0
  30. package/dist/utils/idle.js +10 -3
  31. package/dist/utils/keystrokes.js +155 -0
  32. package/dist/utils/lifecycle.js +11 -2
  33. package/dist/utils/media.js +5 -2
  34. package/dist/utils/ocrScan.js +77 -0
  35. package/dist/utils/pipeline.js +169 -15
  36. package/dist/utils/recipes.js +67 -0
  37. package/dist/utils/recordingIndex.js +266 -0
  38. package/dist/utils/replay.js +278 -0
  39. package/dist/utils/stepGuide.js +205 -0
  40. package/dist/utils/steps.js +88 -0
  41. package/dist/utils/timeline.js +85 -0
  42. package/dist/utils/toolsets.js +32 -6
  43. package/dist/utils/transcriptCut.js +134 -0
  44. package/package.json +1 -1
@@ -0,0 +1,266 @@
1
+ import { z } from "zod";
2
+ import { createRequire } from "node:module";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir, release, version as osVersion } from "node:os";
5
+ import { join } from "node:path";
6
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
7
+ import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
8
+ import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
9
+ import { runEditJob } from "../utils/jobs.js";
10
+ import { planPipeline } from "../utils/pipeline.js";
11
+ import { exportAnimation } from "../utils/animExport.js";
12
+ import { DEFAULT_MAX_BYTES } from "../utils/anim.js";
13
+ import { evenTimes, DEFAULT_SHEET_COUNT, DEFAULT_TILE_WIDTH } from "../utils/sheet.js";
14
+ import { scanVideoFrames, scanMatches } from "../utils/ocrScan.js";
15
+ import { eventPaths, parseEventsJsonl, whenFinalized } from "../utils/events.js";
16
+ import { ocrStatus, parseFfmpegVersion, versionText } from "../utils/capabilities.js";
17
+ import { getMonitors } from "../utils/monitors.js";
18
+ import { resolveOutputDir, subdir, stamp, rand } from "../utils/paths.js";
19
+ import { encodeInlineImages, DEFAULT_MAX_IMAGE_WIDTH } from "../utils/images.js";
20
+ import { getStore } from "../context.js";
21
+ import { redactRegionSchema } from "./redactRegion.js";
22
+ import { renderContactSheet } from "./contactSheet.js";
23
+ import { DEFAULT_SCAN_FRAMES, MAX_SCAN_FRAMES } from "./findText.js";
24
+ import { DEFAULT_CLIP_SEC, DEFAULT_ERROR_PATTERN, DEFAULT_SCAN_EVERY_SEC, DEFAULT_SECRET_PATTERN, MAX_CLIP_SEC, MAX_STEPS, REPORT_FILES, buildReportMarkdown, clipWindow, errorFindings, maskSecrets, mergeRedactions, reconstructSteps, } from "../utils/bugReport.js";
25
+ const { version: serverVersion } = createRequire(import.meta.url)("../../package.json");
26
+ const inputSchema = {
27
+ input: z.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),
28
+ sessionId: z.string().min(1).optional().describe("Or a stopped session's id."),
29
+ title: z.string().max(200).optional().describe("Issue title."),
30
+ actual: z.string().max(4000).optional().describe("What happened."),
31
+ expected: z.string().max(4000).optional().describe("What should happen."),
32
+ start: z.number().nonnegative().optional().describe("Clip start s (default: end - clipSec)."),
33
+ end: z.number().positive().optional().describe("Clip end s (default: recording end)."),
34
+ clipSec: z.number().positive().max(MAX_CLIP_SEC).optional().describe(`Clip length without start (default ${DEFAULT_CLIP_SEC}).`),
35
+ redact: z.boolean().optional().describe("Box out OCR-found secrets in every output (default true; needs Windows OCR)."),
36
+ secretPattern: z.string().optional().describe("Secret regex (default: API keys, tokens, password: values)."),
37
+ regions: z.array(redactRegionSchema).optional().describe("Extra boxes (video px; start/end on the clip clock)."),
38
+ errorPattern: z.string().optional().describe("Error-line regex."),
39
+ scanEverySec: z.number().positive().optional().describe(`OCR every N s (default ${DEFAULT_SCAN_EVERY_SEC}).`),
40
+ maxFrames: z.number().int().min(1).max(MAX_SCAN_FRAMES).optional().describe(`Scan frame cap (default ${DEFAULT_SCAN_FRAMES}).`),
41
+ gif: z.boolean().optional().describe("Also export a GIF (default true)."),
42
+ maxBytes: z.number().int().min(10_000).optional().describe(`GIF size budget (default ${DEFAULT_MAX_BYTES}).`),
43
+ outputDir: z.string().optional().describe("Package folder (default: a new one in SCREENCAST_HOME/edits)."),
44
+ overwrite: z.boolean().optional().describe("Replace a report already in outputDir."),
45
+ };
46
+ const r3 = (n) => Math.round(n * 1000) / 1000;
47
+ export async function resolveSource(args) {
48
+ if (args.sessionId !== undefined) {
49
+ const record = getStore().get(args.sessionId);
50
+ if (!record)
51
+ throw new ScreencastError(`No session with id "${args.sessionId}".`);
52
+ if (record.status === "recording") {
53
+ throw new ScreencastError("The recording is still running; stop_recording it first.");
54
+ }
55
+ await whenFinalized(record.id);
56
+ if (!existsSync(record.outputPath))
57
+ throw new ScreencastError(`The session's recording is missing: ${record.outputPath}`);
58
+ const events = record.events?.path;
59
+ return { path: record.outputPath, eventsPath: events && existsSync(events) ? events : null, record };
60
+ }
61
+ const path = args.input;
62
+ if (!existsSync(path))
63
+ throw new ScreencastError(`Input file not found: ${path}`);
64
+ const { jsonl } = eventPaths(path);
65
+ return { path, eventsPath: existsSync(jsonl) ? jsonl : null };
66
+ }
67
+ async function displayRows() {
68
+ if (process.platform !== "win32")
69
+ return null;
70
+ try {
71
+ const monitors = await getMonitors();
72
+ return monitors
73
+ .map((m) => `${m.width}x${m.height}${m.dpi ? ` @${Math.round((m.dpi / 96) * 100)}%` : ""}${m.primary ? " (primary)" : ""}`)
74
+ .join(", ");
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ export function register(server) {
81
+ server.registerTool("bug_report", {
82
+ title: "Bug Report Package",
83
+ description: "Package a recording as a paste-ready repro folder: secret-scanned, redacted clip and GIF, contact " +
84
+ "sheet, steps from the event log, OCR'd errors, environment, report.md for gh issue create --body-file.",
85
+ inputSchema,
86
+ outputSchema: looseOutput({
87
+ outputDir: z.string(),
88
+ reportPath: z.string(),
89
+ jsonPath: z.string(),
90
+ clipPath: z.string(),
91
+ }),
92
+ annotations: WRITES_FILE,
93
+ }, async (args, extra) => {
94
+ let createdDir = null;
95
+ const written = [];
96
+ try {
97
+ if ((args.input === undefined) === (args.sessionId === undefined)) {
98
+ throw new ScreencastError("Provide exactly one of: input (a recording path) or sessionId.");
99
+ }
100
+ const { ffmpeg } = requireFfmpeg();
101
+ const source = await resolveSource(args);
102
+ const info = await probeMedia(source.path);
103
+ if (!info.width || !info.height)
104
+ throw new ScreencastError(`Could not read the size of ${source.path}.`);
105
+ const duration = info.videoDurationSec ?? info.durationSec;
106
+ if (duration === null)
107
+ throw new ScreencastError(`Could not read the duration of ${source.path}.`);
108
+ const window = clipWindow(duration, args);
109
+ const clipLen = r3(window.end - window.start);
110
+ const redact = args.redact !== false;
111
+ const secretPattern = args.secretPattern ?? DEFAULT_SECRET_PATTERN;
112
+ maskSecrets(["x"], secretPattern);
113
+ if (args.errorPattern !== undefined)
114
+ maskSecrets(["x"], args.errorPattern);
115
+ const format = "gif";
116
+ const dir = resolveOutputDir(args.outputDir, subdir("edits")) ?? join(subdir("edits"), `bug-report-${stamp()}-${rand()}`);
117
+ const paths = {
118
+ markdown: join(dir, REPORT_FILES.markdown),
119
+ json: join(dir, REPORT_FILES.json),
120
+ clip: join(dir, REPORT_FILES.clip),
121
+ gif: join(dir, REPORT_FILES.gif(format)),
122
+ sheet: join(dir, REPORT_FILES.contactSheet),
123
+ };
124
+ const clash = Object.values(paths).filter((p) => existsSync(p));
125
+ if (clash.length > 0 && !args.overwrite) {
126
+ throw new ScreencastError(`The folder already holds a report: ${clash.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);
127
+ }
128
+ if (!existsSync(dir)) {
129
+ mkdirSync(dir, { recursive: true });
130
+ createdDir = dir;
131
+ }
132
+ const warnings = [];
133
+ const work = mkdtempSync(join(tmpdir(), "screencast-bug-"));
134
+ try {
135
+ let ocr = "unavailable";
136
+ let scan = null;
137
+ const status = await ocrStatus();
138
+ if (status.available) {
139
+ scan = await scanVideoFrames(source.path, {
140
+ everySec: args.scanEverySec ?? DEFAULT_SCAN_EVERY_SEC,
141
+ maxFrames: args.maxFrames ?? DEFAULT_SCAN_FRAMES,
142
+ range: { start: window.start, duration: clipLen },
143
+ }, work, extra.signal);
144
+ ocr = "read";
145
+ }
146
+ else if (redact) {
147
+ throw new ScreencastError(`The secret scan needs Windows OCR, which is unavailable here${status.error ? ` (${status.error})` : ""}.`, "Pass redact: false to package without it (then check the clip yourself before sharing), or run doctor.");
148
+ }
149
+ else {
150
+ warnings.push("Windows OCR is unavailable, so no error text was read.");
151
+ }
152
+ const found = scan && redact ? mergeRedactions(scanMatches(scan, secretPattern, true, "line").redactRegions) : [];
153
+ const regions = [...found, ...(args.regions ?? [])];
154
+ const errors = scan ? errorFindings(scan.frames, args.errorPattern ?? DEFAULT_ERROR_PATTERN, redact ? secretPattern : null) : [];
155
+ extra.signal.throwIfAborted();
156
+ const steps = [
157
+ { op: "trim", start: window.start, end: window.end },
158
+ ...(regions.length > 0 ? [{ op: "redact", regions, style: "box" }] : []),
159
+ ];
160
+ const plan = planPipeline(source.path, paths.clip, steps, {
161
+ width: info.width,
162
+ height: info.height,
163
+ fps: info.fps ?? 30,
164
+ durationSec: info.durationSec,
165
+ hasAudio: info.audioCodec !== null,
166
+ });
167
+ await runEditJob(plan.args, { output: paths.clip, durationSec: plan.durationSec, inputDurationSec: clipLen, extra });
168
+ written.push(paths.clip);
169
+ let anim = null;
170
+ if (args.gif !== false) {
171
+ anim = await exportAnimation(paths.clip, paths.gif, { format, maxBytes: args.maxBytes ?? DEFAULT_MAX_BYTES }, extra);
172
+ written.push(paths.gif);
173
+ if (anim.note)
174
+ warnings.push(anim.note);
175
+ }
176
+ await renderContactSheet(paths.clip, evenTimes(clipLen, DEFAULT_SHEET_COUNT), paths.sheet, { tileWidth: DEFAULT_TILE_WIDTH }, extra.signal);
177
+ written.push(paths.sheet);
178
+ const allSteps = source.eventsPath ? reconstructSteps(parseEventsJsonl(readFileSync(source.eventsPath, "utf8"))) : [];
179
+ const stepsNote = source.eventsPath
180
+ ? allSteps.length === 0
181
+ ? "The event log has no clicks, shortcuts, typing, or scrolls."
182
+ : undefined
183
+ : "The recording has no input event log (record with start_recording events: true).";
184
+ const ff = parseFfmpegVersion(versionText(ffmpeg) ?? "");
185
+ const displays = await displayRows();
186
+ const record = source.record;
187
+ const mask = (s) => (redact ? (maskSecrets([s], secretPattern)[0] ?? s) : s);
188
+ const environment = [
189
+ ["OS", `${osVersion()} (${release()}), ${process.arch}`],
190
+ ...(displays ? [["Displays", displays]] : []),
191
+ ...(record ? [["Recorded target", mask(record.target)]] : []),
192
+ ...(record?.matchedWindow ? [["Window", mask(record.matchedWindow)]] : []),
193
+ ...(record?.backend ? [["Capture backend", record.backend]] : []),
194
+ [
195
+ "Recording",
196
+ `${info.width}x${info.height}${info.fps ? ` @ ${Math.round(info.fps * 100) / 100} fps` : ""}, ` +
197
+ `${r3(duration)} s${info.videoCodec ? `, ${info.videoCodec}` : ""}`,
198
+ ],
199
+ ["ffmpeg", ff.version ?? "unknown"],
200
+ ["screencast-mcp", `${serverVersion} (Node ${process.version})`],
201
+ ];
202
+ const data = {
203
+ title: args.title?.trim() || "Bug report",
204
+ ...(args.expected ? { expected: args.expected } : {}),
205
+ ...(args.actual ? { actual: args.actual } : {}),
206
+ createdAt: new Date().toISOString(),
207
+ clip: { start: window.start, end: window.end, recordingDurationSec: r3(duration), width: info.width, height: info.height },
208
+ files: {
209
+ clip: REPORT_FILES.clip,
210
+ ...(anim ? { gif: REPORT_FILES.gif(format) } : {}),
211
+ contactSheet: REPORT_FILES.contactSheet,
212
+ },
213
+ ...(anim ? { gif: { format, sizeBytes: anim.sizeBytes, withinBudget: anim.withinBudget } } : {}),
214
+ steps: allSteps.slice(0, MAX_STEPS),
215
+ ...(allSteps.length > MAX_STEPS ? { stepsOmitted: allSteps.length - MAX_STEPS } : {}),
216
+ ...(stepsNote ? { stepsNote } : {}),
217
+ errors,
218
+ ocr,
219
+ redaction: {
220
+ scanned: scan !== null && redact,
221
+ ...(scan && redact ? { everySec: r3(scan.step), framesScanned: scan.frames.length } : {}),
222
+ found: found.length,
223
+ manual: args.regions?.length ?? 0,
224
+ },
225
+ environment,
226
+ };
227
+ writeFileSync(paths.markdown, buildReportMarkdown(data));
228
+ written.push(paths.markdown);
229
+ writeFileSync(paths.json, JSON.stringify({ ...data, steps: allSteps, redaction: { ...data.redaction, regions } }, null, 2) + "\n");
230
+ written.push(paths.json);
231
+ if (scan?.clamped) {
232
+ warnings.push(`The scan interval was widened to ${r3(scan.step)} s to fit maxFrames.`);
233
+ }
234
+ const { images } = await encodeInlineImages([paths.sheet], DEFAULT_MAX_IMAGE_WIDTH, 1);
235
+ return okResponse({
236
+ outputDir: dir,
237
+ reportPath: paths.markdown,
238
+ jsonPath: paths.json,
239
+ clipPath: paths.clip,
240
+ ...(anim ? { gifPath: paths.gif, gifSizeBytes: anim.sizeBytes, gifWithinBudget: anim.withinBudget } : {}),
241
+ contactSheetPath: paths.sheet,
242
+ clip: { start: window.start, end: window.end },
243
+ steps: allSteps.length,
244
+ errors: errors.map((e) => e.text),
245
+ ocr,
246
+ redaction: data.redaction,
247
+ ...(warnings.length > 0 ? { warnings } : {}),
248
+ next: `Review the clip and report.md, then: gh issue create --title ${JSON.stringify(data.title)} ` +
249
+ `--body-file ${JSON.stringify(paths.markdown)} and drag the GIF into the issue.`,
250
+ note: "Redaction is OCR-based and best-effort: look at the clip before posting it anywhere public.",
251
+ }, images);
252
+ }
253
+ finally {
254
+ rmSync(work, { recursive: true, force: true });
255
+ }
256
+ }
257
+ catch (error) {
258
+ if (createdDir)
259
+ rmSync(createdDir, { recursive: true, force: true });
260
+ else
261
+ for (const p of written)
262
+ rmSync(p, { force: true });
263
+ return errorResponse(error);
264
+ }
265
+ });
266
+ }
@@ -0,0 +1,156 @@
1
+ import { z } from "zod";
2
+ import { extname, join } from "node:path";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
+ import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
7
+ import { requireFfmpeg, probeMedia, runCapture } from "../utils/ffmpeg.js";
8
+ import { jobTimeoutMs, runEditJob } from "../utils/jobs.js";
9
+ import { buildSceneScanArgs, parseSceneScan, editOutputExt, DEFAULT_SCENE_THRESHOLD } from "../utils/media.js";
10
+ import { parseSrt } from "../utils/captions.js";
11
+ import { buildChapters, buildChaptersMuxArgs, ffmetadata, markerPoints, markersOrChapters, scenePoints, transcriptPoints, youtubeChapters, YOUTUBE_MIN_CHAPTER_SEC, } from "../utils/chapters.js";
12
+ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
13
+ import { getStore } from "../context.js";
14
+ const CONTAINERS = new Set([".mp4", ".mkv", ".mov"]);
15
+ const MAX_SCENE_CHAPTERS = 12;
16
+ const inputSchema = {
17
+ input: z.string().min(1).optional().describe("Path to the video."),
18
+ sessionId: z.string().min(1).optional().describe("Or a stopped recording's id."),
19
+ from: z
20
+ .enum(["markers", "scenes", "transcript"])
21
+ .optional()
22
+ .describe("markers (default; add_marker, else the file's chapters), scenes (screen changes), or transcript (SRT sections)."),
23
+ chapters: z
24
+ .array(z.object({ start: z.number().min(0), title: z.string().min(1).max(100) }))
25
+ .min(1)
26
+ .max(200)
27
+ .optional()
28
+ .describe("Or explicit { start, title } chapters."),
29
+ transcript: z.string().optional().describe("The .srt for from: transcript."),
30
+ minChapterSec: z
31
+ .number()
32
+ .min(0)
33
+ .optional()
34
+ .describe(`Shortest chapter (default 1; scenes ${YOUTUBE_MIN_CHAPTER_SEC}, transcript 30).`),
35
+ subtitles: z.string().optional().describe("Also mux this .srt/.vtt/.ass as a soft subtitle track."),
36
+ subtitleLanguage: z.string().regex(/^[a-z]{3}$/).optional().describe('ISO 639-2, e.g. "eng".'),
37
+ textOnly: z.boolean().optional().describe("Return chapters and YouTube text only; write no file."),
38
+ output: z.string().optional().describe("Optional .mp4/.mkv/.mov path. Defaults under SCREENCAST_HOME/edits."),
39
+ overwrite: z.boolean().optional().describe("Allow replacing an existing output file."),
40
+ };
41
+ export function register(server) {
42
+ server.registerTool("chapters", {
43
+ title: "Chapters",
44
+ description: "Write chapters (markers, scene changes, transcript, or a list) into an mp4/mkv/mov copy without " +
45
+ "re-encoding; returns YouTube chapter text. Can mux an SRT as soft subtitles.",
46
+ inputSchema,
47
+ outputSchema: looseOutput({
48
+ chapters: z.array(looseOutput({ start: z.number(), end: z.number(), title: z.string() })),
49
+ youtube: z.string(),
50
+ }),
51
+ annotations: WRITES_FILE,
52
+ }, async (args, extra) => {
53
+ try {
54
+ requireFfmpeg();
55
+ let input = args.input;
56
+ let sessionMarkers;
57
+ if (args.sessionId) {
58
+ const record = getStore().get(args.sessionId);
59
+ if (!record)
60
+ throw new ScreencastError(`No session with id "${args.sessionId}".`);
61
+ if (record.status === "recording")
62
+ throw new ScreencastError("The recording is still running; stop it first.");
63
+ input ??= record.outputPath;
64
+ sessionMarkers = record.markers;
65
+ }
66
+ if (!input)
67
+ throw new ScreencastError("Pass input or sessionId.");
68
+ if (!existsSync(input))
69
+ throw new ScreencastError(`Input file not found: ${input}`);
70
+ for (const f of [args.transcript, args.subtitles]) {
71
+ if (f !== undefined && !existsSync(f))
72
+ throw new ScreencastError(`File not found: ${f}`);
73
+ }
74
+ if (args.subtitles && !/\.(srt|vtt|ass|ssa)$/i.test(args.subtitles)) {
75
+ throw new ScreencastError("subtitles must be an .srt, .vtt, or .ass file.");
76
+ }
77
+ const info = await probeMedia(input);
78
+ const durationSec = info.durationSec;
79
+ if (!durationSec || durationSec <= 0)
80
+ throw new ScreencastError(`Could not read the duration of ${input}.`);
81
+ const from = args.chapters ? "list" : (args.from ?? "markers");
82
+ let points;
83
+ let minDefault = 1;
84
+ let source = from;
85
+ if (args.chapters) {
86
+ points = args.chapters;
87
+ }
88
+ else if (from === "scenes") {
89
+ minDefault = YOUTUBE_MIN_CHAPTER_SEC;
90
+ const { ffmpeg } = requireFfmpeg();
91
+ const scan = await runCapture(ffmpeg, buildSceneScanArgs(input, DEFAULT_SCENE_THRESHOLD), jobTimeoutMs(durationSec), { signal: extra.signal });
92
+ if (scan.code !== 0) {
93
+ throw new ScreencastError(`Scene scan failed (exit ${scan.code}): ${scan.stderr.trim().slice(-400)}`);
94
+ }
95
+ points = scenePoints(parseSceneScan(scan.stdout), args.minChapterSec ?? minDefault, MAX_SCENE_CHAPTERS);
96
+ }
97
+ else if (from === "transcript") {
98
+ if (!args.transcript)
99
+ throw new ScreencastError("from: transcript needs transcript (an .srt path).");
100
+ minDefault = 30;
101
+ points = transcriptPoints(parseSrt(readFileSync(args.transcript, "utf8")), { minChapterSec: args.minChapterSec ?? minDefault });
102
+ if (points.length === 0)
103
+ throw new ScreencastError(`No cues in ${args.transcript}.`);
104
+ }
105
+ else {
106
+ let markers = sessionMarkers ?? [];
107
+ if (markers.length === 0) {
108
+ const found = await markersOrChapters(input, extra.signal);
109
+ markers = found.markers;
110
+ if (found.from === "chapters")
111
+ source = "embedded chapters";
112
+ }
113
+ if (markers.length === 0) {
114
+ throw new ScreencastError(`No markers for ${input}.`, "Add some with add_marker, or use from: scenes / transcript, or pass chapters.");
115
+ }
116
+ points = markerPoints(markers);
117
+ }
118
+ const chapters = buildChapters(points, durationSec, { minChapterSec: args.minChapterSec ?? minDefault });
119
+ if (chapters.length === 0)
120
+ throw new ScreencastError("No chapter falls inside the video.");
121
+ const yt = youtubeChapters(chapters, durationSec);
122
+ const result = {
123
+ source,
124
+ chapters,
125
+ youtube: yt.text,
126
+ ...(yt.issues.length > 0 ? { youtubeIssues: yt.issues } : {}),
127
+ };
128
+ if (args.textOnly)
129
+ return okResponse(result);
130
+ const ext = (args.output ? extname(args.output).toLowerCase() : editOutputExt(input));
131
+ if (!CONTAINERS.has(ext)) {
132
+ throw new ScreencastError(`Chapters can be written to .mp4, .mkv, or .mov, not ${ext || "a file without an extension"}.`);
133
+ }
134
+ const output = resolveOutput(args.output, subdir("edits"), `chapters-${stamp()}-${rand()}${ext}`, args.overwrite);
135
+ const work = mkdtempSync(join(tmpdir(), "screencast-chapters-"));
136
+ try {
137
+ const meta = join(work, "chapters.txt");
138
+ writeFileSync(meta, ffmetadata(chapters));
139
+ await runEditJob(buildChaptersMuxArgs(input, meta, output, { container: ext, subtitles: args.subtitles, language: args.subtitleLanguage }), { output, durationSec, extra });
140
+ }
141
+ finally {
142
+ rmSync(work, { recursive: true, force: true });
143
+ }
144
+ return okResponse({
145
+ outputPath: output,
146
+ ...result,
147
+ ...(args.subtitles
148
+ ? { subtitleTrack: { file: args.subtitles, codec: ext === ".mkv" ? "copy" : "mov_text", ...(args.subtitleLanguage ? { language: args.subtitleLanguage } : {}) } }
149
+ : {}),
150
+ });
151
+ }
152
+ catch (error) {
153
+ return errorResponse(error);
154
+ }
155
+ });
156
+ }
@@ -55,6 +55,24 @@ const inputSchema = {
55
55
  .optional()
56
56
  .describe(`Max inline image width (default ${DEFAULT_MAX_IMAGE_WIDTH}).`),
57
57
  };
58
+ export async function renderContactSheet(input, times, output, opts, signal) {
59
+ const grid = sheetGrid(times.length, opts.columns);
60
+ const work = mkdtempSync(join(tmpdir(), "screencast-sheet-"));
61
+ try {
62
+ const font = bundledFontPath("bold");
63
+ for (const [i, t] of times.entries()) {
64
+ const labelFile = join(work, `label_${i}.txt`);
65
+ writeFileSync(labelFile, formatTimecode(t));
66
+ const tile = join(work, `tile_${String(i).padStart(3, "0")}.png`);
67
+ await runFfmpeg(buildTileArgs(input, t, tile, opts.tileWidth, font, labelFile), 60_000, { signal });
68
+ }
69
+ await runFfmpeg(buildSheetArgs(sequencePattern(work, "tile_%03d.png"), grid, output), 60_000, { signal });
70
+ }
71
+ finally {
72
+ rmSync(work, { recursive: true, force: true });
73
+ }
74
+ return grid;
75
+ }
58
76
  export function register(server) {
59
77
  server.registerTool("contact_sheet", {
60
78
  title: "Contact Sheet",
@@ -95,23 +113,7 @@ export function register(server) {
95
113
  else {
96
114
  times = evenTimes(durationSec, count);
97
115
  }
98
- const grid = sheetGrid(times.length, args.columns);
99
- const work = mkdtempSync(join(tmpdir(), "screencast-sheet-"));
100
- try {
101
- const font = bundledFontPath("bold");
102
- for (const [i, t] of times.entries()) {
103
- const labelFile = join(work, `label_${i}.txt`);
104
- writeFileSync(labelFile, formatTimecode(t));
105
- const tile = join(work, `tile_${String(i).padStart(3, "0")}.png`);
106
- await runFfmpeg(buildTileArgs(args.input, t, tile, tileWidth, font, labelFile), 60_000, {
107
- signal: extra.signal,
108
- });
109
- }
110
- await runFfmpeg(buildSheetArgs(sequencePattern(work, "tile_%03d.png"), grid, output), 60_000, { signal: extra.signal });
111
- }
112
- finally {
113
- rmSync(work, { recursive: true, force: true });
114
- }
116
+ const grid = await renderContactSheet(args.input, times, output, { tileWidth, columns: args.columns }, extra.signal);
115
117
  result = {
116
118
  outputPath: output,
117
119
  mode: args.mode ?? "even",
@@ -0,0 +1,86 @@
1
+ import { z } from "zod";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
+ import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
5
+ import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
6
+ import { runEditJob } from "../utils/jobs.js";
7
+ import { parseSrt, normalizeCues, formatSrt } from "../utils/captions.js";
8
+ import { buildCutIdleArgs, MAX_CUTS } from "../utils/idle.js";
9
+ import { planTranscriptCuts, retimeCues } from "../utils/transcriptCut.js";
10
+ import { editOutputExt, assertEditContainer } from "../utils/media.js";
11
+ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
12
+ const inputSchema = {
13
+ input: z.string().min(1).describe("Path to the source video."),
14
+ srt: z.string().min(1).describe("Its .srt (transcribe; words: true for word timing)."),
15
+ remove: z
16
+ .array(z.union([z.number().int().min(1).max(99999), z.string().min(1)]))
17
+ .optional()
18
+ .describe("Cue numbers, or transcript text quoted exactly (must occur once)."),
19
+ fillers: z.boolean().optional().describe("Also cut fillers (um, uh...) that have their own cue."),
20
+ dryRun: z.boolean().optional().describe("Only report the cuts."),
21
+ output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
22
+ overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
23
+ };
24
+ export function register(server) {
25
+ server.registerTool("cut_by_transcript", {
26
+ title: "Cut By Transcript",
27
+ description: "Edit a video by its transcript: cut quoted text, cue numbers, or fillers. Also writes the re-timed .srt.",
28
+ inputSchema,
29
+ outputSchema: looseOutput({ cuts: z.array(z.unknown()), removedSec: z.number() }),
30
+ annotations: WRITES_FILE,
31
+ }, async (args, extra) => {
32
+ try {
33
+ requireFfmpeg();
34
+ for (const f of [args.input, args.srt])
35
+ if (!existsSync(f))
36
+ throw new ScreencastError(`File not found: ${f}`);
37
+ if (!args.remove?.length && !args.fillers)
38
+ throw new ScreencastError("Nothing to cut: pass remove and/or fillers: true.");
39
+ const info = await probeMedia(args.input);
40
+ const duration = info.durationSec;
41
+ if (duration === null || !info.videoCodec)
42
+ throw new ScreencastError(`Not a readable video: ${args.input}`);
43
+ const cues = normalizeCues(parseSrt(readFileSync(args.srt, "utf8")));
44
+ if (cues.length === 0)
45
+ throw new ScreencastError(`No cues in ${args.srt}.`);
46
+ const { cuts, skippedFillers } = planTranscriptCuts(cues, { remove: args.remove, fillers: args.fillers });
47
+ if (cuts.length > MAX_CUTS)
48
+ throw new ScreencastError(`Too many cuts (${cuts.length}, max ${MAX_CUTS}); cut in batches.`);
49
+ const removedSec = Number(cuts.reduce((s, c) => s + Math.min(c.end, duration) - Math.min(c.start, duration), 0).toFixed(2));
50
+ const retimed = retimeCues(cues, cuts);
51
+ const notes = [
52
+ cuts.length === 0 && "Nothing matched; nothing to cut.",
53
+ skippedFillers > 0 && `${skippedFillers} filler(s) inside longer cues were kept; transcribe with words: true to cut them.`,
54
+ cuts.some((c) => !c.exact) && "Some edges were estimated inside a cue; transcribe with words: true for word timing.",
55
+ ].filter(Boolean);
56
+ const summary = {
57
+ cuts,
58
+ removedSec,
59
+ originalSec: Number(duration.toFixed(2)),
60
+ newDurationSec: Number((duration - removedSec).toFixed(2)),
61
+ ...(notes.length ? { note: notes.join(" ") } : {}),
62
+ };
63
+ if (args.dryRun || cuts.length === 0) {
64
+ const text = retimed.map((c) => c.text.replace(/\n/g, " ")).join(" ");
65
+ return okResponse({ ...summary, ...(cuts.length ? { dryRun: true } : {}), text: text.length > 4000 ? `${text.slice(0, 4000)}…` : text });
66
+ }
67
+ assertEditContainer(args.output);
68
+ const ext = editOutputExt(args.input);
69
+ const output = resolveOutput(args.output, subdir("edits"), `cut-transcript-${stamp()}-${rand()}${ext}`, args.overwrite);
70
+ const srtPath = output.replace(/\.[^.\\/]+$/, "") + ".srt";
71
+ if (!args.overwrite && existsSync(srtPath))
72
+ throw new ScreencastError(`Output already exists: ${srtPath}. Pass overwrite: true to replace it.`);
73
+ await runEditJob(buildCutIdleArgs(args.input, output, cuts, info.audioCodec !== null), {
74
+ output,
75
+ durationSec: duration - removedSec,
76
+ inputDurationSec: duration,
77
+ extra,
78
+ });
79
+ writeFileSync(srtPath, formatSrt(retimed));
80
+ return okResponse({ outputPath: output, srtPath, ...summary });
81
+ }
82
+ catch (error) {
83
+ return errorResponse(error);
84
+ }
85
+ });
86
+ }