@tmhs/screencast-mcp 0.45.0 → 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.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  **An MCP server that lets an agent record the screen, _watch_ the footage, and make minimal ffmpeg edits — over stdio, on Windows.**
6
6
 
7
- Capture the desktop, a monitor, a window, or a region; sample a recording into frames the agent can actually look at; trim, crop, redact, annotate, zoom toward clicks, and export for GitHub or social. No cloud service, no telemetry: ffmpeg and ffprobe behind 49 typed tools.
7
+ Capture the desktop, a monitor, a window, or a region; sample a recording into frames the agent can actually look at; trim, crop, redact, annotate, zoom toward clicks, and export for GitHub or social. No cloud service, no telemetry: ffmpeg and ffprobe behind 53 typed tools.
8
8
 
9
9
  **For developers who want their coding agent to see and prove UI changes on Windows**: bug repros, UI verification, and demo clips the agent records, checks, and edits itself. Capture is Windows-only; the watch and edit tools work on any OS with ffmpeg. Free for non-commercial use ([CC BY-NC-ND 4.0](#license)); [why not OBS, Playwright, or a screenshot MCP?](#why-not-just)
10
10
 
@@ -79,7 +79,7 @@ What it can do beyond record-and-look:
79
79
  - **Zoom toward clicks.** Record with `events: true` and `zoom` glides in on each click and rings it, Screen Studio style.
80
80
  - **Review before sharing.** In clients with MCP Apps, `review_recording` opens an inline player where a person trims and draws redaction boxes.
81
81
  - **Find and cover secrets.** `find_text` reads the screen with Windows OCR and returns rectangles for `redact_region`.
82
- - **One call, one encode.** `pipeline` runs trim, crop, redact, callouts, and an export as a single ffmpeg pass.
82
+ - **One call, one encode.** `pipeline` runs trim, crop, redact, callouts, and an export as a single ffmpeg pass; `recipe: "tutorial"` turns a raw recording into a cut, zoomed, normalized, captioned mp4.
83
83
  - **Record a covered window.** `backend: "wgc"` records a window's own surface through Windows Graphics Capture.
84
84
 
85
85
  ### Why not just...
@@ -92,7 +92,7 @@ What it can do beyond record-and-look:
92
92
 
93
93
  ## Tools
94
94
 
95
- 49 tools in six groups. The manifest in [`mcp-tools.json`](mcp-tools.json) is the canonical surface; tests keep it, this README, and the docs site in sync with `src/tools/`.
95
+ 53 tools in six groups. The manifest in [`mcp-tools.json`](mcp-tools.json) is the canonical surface; tests keep it, this README, and the docs site in sync with `src/tools/`.
96
96
 
97
97
  ### Capture
98
98
 
@@ -121,6 +121,8 @@ What it can do beyond record-and-look:
121
121
  | `screen_diff` | Compare two screenshots/frames: SSIM score, share changed, and **bounding boxes of what changed**, with the changes outlined in an inline image. Verify a UI change happened, and only where expected. |
122
122
  | `wait_for_change` | Watch a target and return when it **changes** (a dialog opened) or **settles** (a build or page finished), instead of guessing a sleep. Reports elapsed time, changed regions, and the final state inline. |
123
123
  | `find_text` | **Read text** on screen or in a frame with the OCR engine built into Windows (no install): every line and match with its bounding box. Locate a button by its label, check what the screen says, or find secrets (`regex: "sk-|ghp_"`) and get `redact_region` rectangles with `redact: true`; `scanEverySec` checks a whole video, with a time window per match. Best-effort; review before relying on it. |
124
+ | `index_recording` | **Text timeline** of a recording (path or `sessionId`): cuts it at scene changes (with fill keyframes so no stretch over 10 s goes unread), OCRs one keyframe per segment, and attaches input events, markers, and transcript cues (an `.srt`, the `<video>.srt` sidecar, or `transcript: "whisper"`). Writes `<video>.index.json` next to the video (or under `SCREENCAST_HOME/edits/indexes` when that folder is outside the allowed output dirs); a re-run on an unchanged file reuses the OCR. The index holds the raw screen text, so treat it like the video. |
125
+ | `search_recording` | **Find a moment as text** in an indexed recording: "when did Save failed appear?" returns timecoded hits (segment `start`/`end` plus the exact time of a matching cue, marker, or event), best first, with secrets masked in the snippets. Plain queries tolerate OCR misreads; `regex: true` for patterns. No images unless `images: N` asks for small thumbnails of the top hits. |
124
126
  | `get_media_info` | ffprobe wrapper: duration, resolution, fps, codecs, container format, and size. |
125
127
 
126
128
  ### Minimal edit
@@ -147,11 +149,12 @@ These tools re-encode (a filter rewrites pixels, so stream copy does not apply).
147
149
  | `extract_audio` | Write the audio track to its own file (`mp3`, `aac`, `wav`, or `copy`). |
148
150
  | `normalize_audio` | **Loudness to a delivery target** (two-pass EBU R128 `loudnorm`): `youtube` −14 LUFS, `podcast` −16, `broadcast` −23, or any LUFS value. Video is copied; reports loudness before and after. |
149
151
  | `denoise` | Reduce **steady** background noise (fan, hum, hiss) with `afftdn`, tuned to the file's measured noise floor. Video is copied. |
150
- | `transcribe` | **Speech to an SRT file, locally**, with FFmpeg 8's `whisper` filter (needs a whisper.cpp model: pass `model` or set `SCREENCAST_WHISPER_MODEL`). Cues are renumbered and de-overlapped. |
152
+ | `transcribe` | **Speech to an SRT file, locally**, with FFmpeg 8's `whisper` filter (needs a whisper.cpp model: pass `model` or set `SCREENCAST_WHISPER_MODEL`). Cues are renumbered and de-overlapped; `words: true` gives one word per cue (whisper `max_len=1`) for `cut_by_transcript`. |
151
153
  | `burn_subtitles` | Burn an SRT/ASS into the video in the bundled font: `clean` (outlined line) or `social` (big bold text on a dark box, for muted autoplay). |
152
154
  | `chapters` | **Chapters without a re-encode**: from markers (the default), the strongest scene changes, transcript sections (an SRT split at pauses), or an explicit list, written into an mp4/mkv/mov copy as real chapters (FFMETADATA, stream copy; they show in VLC and MPC) and returned as YouTube chapter text, with any YouTube rule it breaks (first at 0:00, three or more, 10 s each). `subtitles` muxes an SRT as a soft, toggleable track (`mov_text` in mp4) instead of burning it in; `textOnly` writes nothing. |
153
155
  | `clip` | Extract one or more frame-accurate sub-segments, each to its own file. For a single segment, `trim` (default `exact: true`) does the same. |
154
156
  | `cut_idle` | **Remove dead air**: cut stretches where the screen is frozen and (when there is audio) silent, keeping a short pad at each edge. `dryRun` reports first; speech over a still screen is kept unless `useAudio: false`. |
157
+ | `cut_by_transcript` | **Edit by the transcript**: cut the lines you quote (`remove: ["exact words"]`, or cue numbers) and, with `fillers: true`, um/uh/erm, in one select/aselect pass that keeps audio and video in sync. Writes a re-timed `.srt` next to the video so `burn_subtitles` still lines up. Timing is as fine as the SRT: `transcribe { words: true }` gives one word per cue; with sentence cues a partial quote is placed by estimate (`exact: false`) and fillers inside a sentence are left in. `dryRun` returns the edited text first. |
155
158
 
156
159
  ### Redact
157
160
 
@@ -177,8 +180,9 @@ The production layer turns raw clips into a finished piece. Tools that combine c
177
180
  | `keystroke_overlay` | **Keycast-style badges** ("Ctrl + Shift + P", "Double click", "Typing…") burned in from the input event log, one at a time, each lingering `lingerSec` (default 1.2). Repeats merge (`Ctrl + Z ×3`); `position`, `size`, `clicks`, `typing`. It can only show what the log holds: never typed text, and shortcuts only from `keys: "shortcuts"` recordings; `keys: "masked"` here shows a chord's modifiers only. |
178
181
  | `backdrop` | **Frame a clip or screenshot** (Screen Studio / CleanShot style): padding, a gradient, solid, or wallpaper `image` background, rounded corners, and a soft drop shadow, optionally on a `16:9`/`9:16`/`1:1`/`4:5` canvas. Presets in the project palette: `desktop` (default, dark slate), `rec` (record red), `amber` (amber to red), `light`. A PNG/JPG input writes a framed still. |
179
182
  | `export_preset` | Encode a platform-ready file (`youtube`, `instagram_reel`, `tiktok`, `x`, `square`, `steam_trailer`, `vertical_reel`): reframes, caps fps, and encodes H.264 at the platform bitrate with faststart. `steam_trailer` is 1080p H.264 High at a padded 5.5 Mbps CBR (above Steam's 5 Mbps floor) with 48 kHz audio at -14 LUFS; `vertical_reel` centres the footage over a blurred copy of itself with audio at -14 LUFS. |
180
- | `pipeline` | **Several edits in one ffmpeg process**: `steps` of `trim`, `crop`, `scale`, `speed`, `redact`, `callout`, `keystroke_overlay`, `reframe`, `zoom` (keyframes), `backdrop`, ending optionally in `export_preset` or `export_gif`, each with its tool's options. One re-encode, no intermediate files, and a recipe you can save and re-run on the next recording; `dryRun` returns the planned command; `chapters: true` keeps the input's markers as chapters, re-timed through trims and speed changes. |
183
+ | `pipeline` | **Several edits in one ffmpeg process**: `steps` of `trim`, `crop`, `scale`, `speed`, `cut_idle`, `redact`, `callout`, `keystroke_overlay`, `reframe`, `zoom` (keyframes, or `follow: "clicks"` from the event log), `backdrop`, `audio` (`normalize`, `denoise`), `burn_subtitles` (a file, or `transcribe: true`), ending optionally in `export_preset` or `export_gif`, each with its tool's options. Or name a `recipe`: `pr_demo` (cut idle, click zoom, GIF under 10 MB), `tutorial` (plus denoise/normalize and captions, 1080p mp4) or `social_reel` (9:16, big captions); it expands to steps that `dryRun` shows and your own `steps` override. One re-encode, no intermediate files, and a recipe you can save and re-run on the next recording; `dryRun` returns the planned command; `chapters: true` keeps the input's markers as chapters, re-timed through trims and speed changes. |
181
184
  | `bug_report` | **A paste-ready repro package in one call**: from a recording path or `sessionId`, writes a folder with a trimmed clip (the last 30 s by default) and a GIF under 10 MB, a timecoded contact sheet, numbered steps rebuilt from the input event log, OCR'd error and dialog text, environment details (OS, displays and DPI, window, ffmpeg), and a `report.md` for `gh issue create --body-file` (plus `report.json`). Before anything is encoded, a whole-clip OCR secret scan boxes out API keys, tokens, and `password:` values in every output and masks them in the quoted text; it needs Windows OCR (`redact: false` skips it). |
185
+ | `step_guide` | **A step-by-step how-to from a recording** (Steps Recorder for the agent era): from a path or `sessionId` with an input event log, writes `guide.md` with an `images/` folder and/or one self-contained `guide.html`. Each click, shortcut, typing burst, and scroll becomes a numbered step with the frame just before it, the click ringed, and a caption ("Click **Save**") from OCR of the text under the click; markers become section headings. OCR also boxes secrets out of the screenshots and masks them in captions (`ocr: false` skips both; it needs Windows OCR). Typed text is never logged, so it never appears. Returns the steps so the agent can rewrite captions. |
182
186
 
183
187
  ### Targets
184
188
 
@@ -223,9 +227,9 @@ Edit and produce tools write to a `<name>.partial.<ext>` file next to the output
223
227
  | Toolset | Tools |
224
228
  | --- | --- |
225
229
  | `capture` | `start_recording`, `stop_recording`, `save_replay`, `list_sessions`, `get_session`, `read_events`, `add_marker`, `screenshot`, `list_targets`, `list_audio_devices` |
226
- | `watch` | `sample_frames`, `contact_sheet`, `screen_diff`, `wait_for_change`, `find_text`, `review_recording`, `player_frames` |
227
- | `edit` | `pipeline`, `trim`, `clip`, `concat`, `convert`, `export_gif`, `crop`, `scale`, `speed`, `compress`, `redact_region`, `cut_idle` |
228
- | `produce` | `callout`, `keystroke_overlay`, `backdrop`, `overlay`, `zoom`, `reframe`, `title_card`, `xfade_transition`, `assemble_highlights`, `export_preset`, `burn_subtitles`, `chapters`, `bug_report` |
230
+ | `watch` | `sample_frames`, `contact_sheet`, `screen_diff`, `wait_for_change`, `find_text`, `index_recording`, `search_recording`, `review_recording`, `player_frames` |
231
+ | `edit` | `pipeline`, `trim`, `clip`, `concat`, `convert`, `export_gif`, `crop`, `scale`, `speed`, `compress`, `redact_region`, `cut_idle`, `cut_by_transcript` |
232
+ | `produce` | `callout`, `keystroke_overlay`, `backdrop`, `overlay`, `zoom`, `reframe`, `title_card`, `xfade_transition`, `assemble_highlights`, `export_preset`, `burn_subtitles`, `chapters`, `bug_report`, `step_guide` |
229
233
  | `audio` | `extract_audio`, `normalize_audio`, `denoise`, `transcribe`, `music_bed` |
230
234
  | `core` (always) | `doctor`, `get_media_info` |
231
235
 
@@ -287,6 +291,14 @@ bug_report { "sessionId": "rec-…", "title": "Save fails on a read-only folder"
287
291
  gh issue create --title "Save fails on a read-only folder" --body-file …/report.md
288
292
  ```
289
293
 
294
+ Documenting a task as a how-to (record with `events: true`; `add_marker` between phases gives section headings):
295
+
296
+ ```jsonc
297
+ step_guide { "sessionId": "rec-…", "title": "Export a report as PDF" }
298
+ // -> { "outputDir": "…/edits/step-guide-…", "markdownPath": "…/guide.md", "htmlPath": "…/guide.html",
299
+ // "steps": [{ "n": 1, "caption": "Click File", "section": "Open the report", "image": "step-01.png" }, …] }
300
+ ```
301
+
290
302
  Inline images are downscaled JPEGs (`maxImageWidth`, default 1280) and capped per call (`maxInlineImages`, default 8, max 20); the full-resolution PNGs stay on disk. Pass `returnImage: false` / `returnImages: false` to get paths only.
291
303
 
292
304
  `sample_frames` writes at most `maxFrames` frames per call (default 100, max 1000). In `fps` mode it probes the video first; if the rate would exceed the cap, it samples at a lower rate so the frames still span the whole video, and the result's `capNote` says what it did.
@@ -299,6 +311,7 @@ Beyond tools, the server offers **prompts**: ready-made workflows that clients s
299
311
  | --- | --- |
300
312
  | `bug-repro-clip` | Record, find the bug moment, check for secrets, trim, annotate, and export a GIF for an issue. |
301
313
  | `file-bug-report` | Record a repro with input events, package it with `bug_report` (redacted clip, GIF, steps, error text, `report.md`), review it, and file it with `gh issue create` once you confirm. |
314
+ | `document-steps` | Record a task with input events and markers, turn it into a step-by-step guide with `step_guide`, and tidy the captions. |
302
315
  | `demo-gif` | Record a feature walkthrough and export a GIF small enough for a README or PR. |
303
316
  | `verify-ui-change` | Screenshot before, make the change, wait for the screen to settle, diff, and confirm the text. |
304
317
  | `review-recording` | Summarize what happens in a recording, with timestamps. |
package/dist/prompts.js CHANGED
@@ -19,10 +19,9 @@ Report the final file path, what the clip shows, and anything you redacted. (To
19
19
  Report the folder path, the steps, the error text found, and what was redacted.`,
20
20
  demoGif: (target, maxMB) => `Make a demo GIF of ${target} for a README or PR, under ${maxMB} MB.
21
21
 
22
- 1. start_recording { target: "${target}" }, walk through the feature (or ask me to), then stop_recording.
22
+ 1. start_recording { target: "${target}", events: true }, walk through the feature (or ask me to), then stop_recording.
23
23
  2. contact_sheet { input: <recording>, mode: "scenes" } to see the whole run at a glance and pick the best stretch.
24
- 3. trim to that stretch (skip any audio steps: a GIF has no sound).
25
- 4. export_gif { input: <clip>, maxBytes: ${Math.round(Number(maxMB) * 1_000_000) || 10_000_000} }. If it does not fit, try format: "webp" or a shorter clip.
24
+ 3. pipeline { input: <recording>, recipe: "pr_demo", steps: [{ op: "trim", ... that stretch }, { op: "export_gif", maxBytes: ${Math.round(Number(maxMB) * 1_000_000) || 10_000_000} }] }: one pass that cuts idle time, zooms toward the clicks, and writes the GIF (dryRun first to see the steps). If it does not fit, try format: "webp" or a shorter stretch.
26
25
  Report the file path, its size, and the settings export_gif chose.`,
27
26
  verifyUiChange: (target, expectation) => `Verify a UI change in ${target}. Expected: ${expectation || "(describe what should change)"}.
28
27
 
@@ -39,6 +38,12 @@ Say whether the change happened, whether anything changed that should not have,
39
38
  3. sample_frames { input: "${path}", mode: "scenes" } to look closely at each change.
40
39
  4. If there is on-screen text worth quoting, find_text on the relevant frame.
41
40
  Give a timestamped summary of the main steps and anything that looks wrong.`,
41
+ documentSteps: (target, task) => `Document ${task ? `how to ${task}` : "what I do next"} as a step-by-step guide.
42
+
43
+ 1. start_recording { target: "${target}", events: true } so every click and shortcut is logged, then do the task (or ask me to). Between phases, add_marker { sessionId: <id>, label: <phase name> } so the guide gets section headings. Then stop_recording.
44
+ 2. step_guide { sessionId: <session id>, title: <what the guide teaches> }. It writes guide.md (with an images folder) and a self-contained guide.html: one screenshot per step, the click ringed, captioned from the text under it, secrets boxed out. Typed text is never logged; say what to type in the captions yourself.
45
+ 3. Read the returned steps and rewrite any vague caption ("Click the marked spot") in guide.md, using the screenshot to name the control.
46
+ Report the guide paths, the steps, and anything you would check before sharing it.`,
42
47
  };
43
48
  export function registerPrompts(server) {
44
49
  server.registerPrompt("bug-repro-clip", {
@@ -79,4 +84,12 @@ export function registerPrompts(server) {
79
84
  description: "Summarize what happens in a recording, with timestamps, using a contact sheet and scene frames.",
80
85
  argsSchema: { path: z.string().describe("Path to the recording.") },
81
86
  }, ({ path }) => message(PROMPT_TEXT.reviewRecording(path)));
87
+ server.registerPrompt("document-steps", {
88
+ title: "Document what I just did",
89
+ description: "Record a task with input events and markers, then turn it into a step-by-step guide with step_guide.",
90
+ argsSchema: {
91
+ target: z.string().optional().describe("What to record (default: full)."),
92
+ task: z.string().optional().describe("The task the guide teaches."),
93
+ },
94
+ }, ({ target, task }) => message(PROMPT_TEXT.documentSteps(target || "full", task ?? "")));
82
95
  }
package/dist/server.js CHANGED
@@ -16,6 +16,8 @@ import { register as registerContactSheet } from "./tools/contactSheet.js";
16
16
  import { register as registerScreenDiff } from "./tools/screenDiff.js";
17
17
  import { register as registerWaitForChange } from "./tools/waitForChange.js";
18
18
  import { register as registerFindText } from "./tools/findText.js";
19
+ import { register as registerIndexRecording } from "./tools/indexRecording.js";
20
+ import { register as registerSearchRecording } from "./tools/searchRecording.js";
19
21
  import { register as registerGetMediaInfo } from "./tools/getMediaInfo.js";
20
22
  import { register as registerTrim } from "./tools/trim.js";
21
23
  import { register as registerConcat } from "./tools/concat.js";
@@ -36,6 +38,7 @@ import { register as registerTranscribe } from "./tools/transcribe.js";
36
38
  import { register as registerBurnSubtitles } from "./tools/burnSubtitles.js";
37
39
  import { register as registerClip } from "./tools/clip.js";
38
40
  import { register as registerCutIdle } from "./tools/cutIdle.js";
41
+ import { register as registerCutByTranscript } from "./tools/cutByTranscript.js";
39
42
  import { register as registerRedactRegion } from "./tools/redactRegion.js";
40
43
  import { register as registerListAudioDevices } from "./tools/listAudioDevices.js";
41
44
  import { register as registerListTargets } from "./tools/listTargets.js";
@@ -49,6 +52,7 @@ import { register as registerZoom } from "./tools/zoom.js";
49
52
  import { register as registerPipeline } from "./tools/pipeline.js";
50
53
  import { register as registerExportPreset } from "./tools/exportPreset.js";
51
54
  import { register as registerBugReport } from "./tools/bugReport.js";
55
+ import { register as registerStepGuide } from "./tools/stepGuide.js";
52
56
  import { registerResources } from "./resources.js";
53
57
  import { registerPrompts } from "./prompts.js";
54
58
  import { attachLogging } from "./utils/logging.js";
@@ -80,6 +84,8 @@ export function createServer(options = {}) {
80
84
  registerScreenDiff(server);
81
85
  registerWaitForChange(server);
82
86
  registerFindText(server);
87
+ registerIndexRecording(server);
88
+ registerSearchRecording(server);
83
89
  registerGetMediaInfo(server);
84
90
  registerTrim(server);
85
91
  registerConcat(server);
@@ -101,6 +107,7 @@ export function createServer(options = {}) {
101
107
  registerChapters(server);
102
108
  registerClip(server);
103
109
  registerCutIdle(server);
110
+ registerCutByTranscript(server);
104
111
  registerRedactRegion(server);
105
112
  registerListAudioDevices(server);
106
113
  registerListTargets(server);
@@ -114,6 +121,7 @@ export function createServer(options = {}) {
114
121
  registerPipeline(server);
115
122
  registerExportPreset(server);
116
123
  registerBugReport(server);
124
+ registerStepGuide(server);
117
125
  applyToolsets(tools, selection);
118
126
  registerResources(server);
119
127
  registerPrompts(server);
@@ -44,7 +44,7 @@ const inputSchema = {
44
44
  overwrite: z.boolean().optional().describe("Replace a report already in outputDir."),
45
45
  };
46
46
  const r3 = (n) => Math.round(n * 1000) / 1000;
47
- async function resolveSource(args) {
47
+ export async function resolveSource(args) {
48
48
  if (args.sessionId !== undefined) {
49
49
  const record = getStore().get(args.sessionId);
50
50
  if (!record)
@@ -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
+ }
@@ -0,0 +1,173 @@
1
+ import { z } from "zod";
2
+ import { join } from "node:path";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } 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, runFfmpeg, runCapture, probeMedia, hasFilter } from "../utils/ffmpeg.js";
8
+ import { jobTimeoutMs, progressReporter } from "../utils/jobs.js";
9
+ import { buildSceneScanArgs, parseSceneScan, buildSampleAtTimestampArgs } from "../utils/media.js";
10
+ import { readFrames } from "../utils/ocrScan.js";
11
+ import { ocrStatus } from "../utils/capabilities.js";
12
+ import { parseEventsJsonl } from "../utils/events.js";
13
+ import { resolveWhisperModel, buildTranscribeArgs, parseSrt, normalizeCues } from "../utils/captions.js";
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";
16
+ const OCR_BATCH = 8;
17
+ const inputSchema = {
18
+ input: z.string().optional().describe("Recording path."),
19
+ sessionId: z.string().optional().describe("Or a stopped session id."),
20
+ sceneThreshold: z.number().gt(0).lt(1).optional().describe(`Change starting a segment (default ${DEFAULT_INDEX_THRESHOLD}).`),
21
+ maxFrames: z.number().int().min(1).max(MAX_INDEX_FRAMES).optional().describe(`Keyframes to OCR (default ${DEFAULT_INDEX_FRAMES}).`),
22
+ transcript: z.string().optional().describe("An .srt, or 'whisper' to transcribe. Default: <video>.srt if any."),
23
+ force: z.boolean().optional().describe("Re-OCR despite a matching cached index."),
24
+ };
25
+ export function register(server) {
26
+ server.registerTool("index_recording", {
27
+ title: "Index Recording",
28
+ description: "Build a recording's text timeline (<video>.index.json: OCR per scene, events, markers, transcript) " +
29
+ "for search_recording.",
30
+ inputSchema,
31
+ outputSchema: looseOutput({ indexPath: z.string(), segments: z.number() }),
32
+ annotations: WRITES_FILE,
33
+ }, async (args, extra) => {
34
+ const work = mkdtempSync(join(tmpdir(), "screencast-index-"));
35
+ try {
36
+ const { ffmpeg } = requireFfmpeg();
37
+ const source = await resolveRecording(args);
38
+ const info = await probeMedia(source.path);
39
+ const duration = info.videoDurationSec ?? info.durationSec;
40
+ if (!info.width || duration === null || !(duration > 0)) {
41
+ throw new ScreencastError(`Could not read the video size and duration of ${source.path}.`);
42
+ }
43
+ const threshold = args.sceneThreshold ?? DEFAULT_INDEX_THRESHOLD;
44
+ const maxFrames = args.maxFrames ?? DEFAULT_INDEX_FRAMES;
45
+ const edits = subdir("edits");
46
+ const outPath = indexWritePath(source.path, edits);
47
+ const fingerprint = fingerprintFile(source.path);
48
+ const report = progressReporter(extra);
49
+ const notes = [];
50
+ const existingPath = args.force ? null : findIndex(source.path, edits);
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;
56
+ let segments;
57
+ let framesRead = 0;
58
+ let ocr = false;
59
+ if (cached) {
60
+ segments = prior.segments;
61
+ framesRead = prior.framesRead;
62
+ ocr = prior.ocr;
63
+ }
64
+ else {
65
+ const scan = await runCapture(ffmpeg, buildSceneScanArgs(source.path, threshold), jobTimeoutMs(duration), {
66
+ signal: extra.signal,
67
+ });
68
+ if (scan.code !== 0)
69
+ throw new ScreencastError(`Scene scan failed (exit ${scan.code}): ${scan.stderr.trim().slice(-400)}`);
70
+ report?.(0.1);
71
+ const spans = segmentsFrom(planKeyframes(parseSceneScan(scan.stdout), duration, maxFrames), duration);
72
+ const texts = spans.map(() => []);
73
+ ocr = process.platform === "win32" && (await ocrStatus()).available;
74
+ if (ocr) {
75
+ for (let b = 0; b < spans.length; b += OCR_BATCH) {
76
+ extra.signal.throwIfAborted();
77
+ const batch = spans.slice(b, b + OCR_BATCH);
78
+ const frames = [];
79
+ for (const [i, span] of batch.entries()) {
80
+ const out = join(work, `key_${b + i}.png`);
81
+ await runFfmpeg(buildSampleAtTimestampArgs(source.path, keyframeTime(span), out), 60_000, { signal: extra.signal });
82
+ if (existsSync(out))
83
+ frames.push({ at: b + i, path: out });
84
+ }
85
+ const read = frames.length > 0 ? await readFrames(frames.map((f) => f.path), work, extra.signal) : [];
86
+ read.forEach((f, i) => (texts[frames[i].at] = f.lines.map((l) => l.text)));
87
+ framesRead += read.length;
88
+ report?.(0.1 + (0.85 * Math.min(spans.length, b + OCR_BATCH)) / spans.length);
89
+ }
90
+ }
91
+ else {
92
+ notes.push("Windows OCR is not available, so the index holds no screen text; install an OCR language (doctor).");
93
+ }
94
+ const read = spans.map((s, i) => ({ ...s, ocr: texts[i] ?? [] }));
95
+ segments = ocr ? mergeSegments(read) : read;
96
+ }
97
+ const events = source.eventsPath ? eventTexts(parseEventsJsonl(readFileSync(source.eventsPath, "utf8"))) : [];
98
+ segments = attach(segments, events, "events");
99
+ segments = attach(segments, markerTexts(source.markers), "markers");
100
+ const cues = await transcriptCues(args.transcript, source.path, info.audioCodec !== null, duration, extra.signal, notes);
101
+ if (cues !== null)
102
+ segments = attach(segments, cueTexts(cues), "transcript");
103
+ else if (cached) {
104
+ const kept = prior.segments.flatMap((s) => s.transcript ?? []);
105
+ segments = attach(segments, kept, "transcript");
106
+ }
107
+ const index = {
108
+ version: INDEX_VERSION,
109
+ video: source.path,
110
+ fingerprint,
111
+ durationSec: duration,
112
+ createdAt: new Date().toISOString(),
113
+ sceneThreshold: threshold,
114
+ maxFrames,
115
+ framesRead,
116
+ ocr,
117
+ segments,
118
+ };
119
+ mkdirSync(join(outPath, ".."), { recursive: true });
120
+ writeIndex(outPath, index);
121
+ report?.(1);
122
+ const count = (f) => segments.reduce((n, s) => n + (s[f]?.length ?? 0), 0);
123
+ return okResponse({
124
+ indexPath: outPath,
125
+ segments: segments.length,
126
+ cached,
127
+ framesRead,
128
+ durationSec: duration,
129
+ sources: {
130
+ screenLines: segments.reduce((n, s) => n + s.ocr.length, 0),
131
+ events: count("events"),
132
+ markers: count("markers"),
133
+ transcriptCues: count("transcript"),
134
+ },
135
+ ...(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.",
137
+ });
138
+ }
139
+ catch (error) {
140
+ return errorResponse(error);
141
+ }
142
+ finally {
143
+ rmSync(work, { recursive: true, force: true });
144
+ }
145
+ });
146
+ }
147
+ async function transcriptCues(arg, video, hasAudio, duration, signal, notes) {
148
+ if (arg === "whisper") {
149
+ if (!hasAudio) {
150
+ notes.push("The recording has no audio, so there is no transcript.");
151
+ return null;
152
+ }
153
+ if (!hasFilter("whisper")) {
154
+ throw new ScreencastError("This ffmpeg has no whisper filter.", "transcript: 'whisper' needs FFmpeg 8 built with whisper.cpp; or pass an .srt.");
155
+ }
156
+ const model = resolveWhisperModel(undefined);
157
+ const raw = tempPath(".srt");
158
+ try {
159
+ await runFfmpeg(buildTranscribeArgs(video, model, raw), jobTimeoutMs(duration), { signal });
160
+ return existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
161
+ }
162
+ finally {
163
+ rmSync(raw, { force: true });
164
+ }
165
+ }
166
+ const path = arg ?? `${video.replace(/\.[^./\\]+$/, "")}.srt`;
167
+ if (!existsSync(path)) {
168
+ if (arg !== undefined)
169
+ throw new ScreencastError(`Transcript not found: ${arg}`);
170
+ return null;
171
+ }
172
+ return normalizeCues(parseSrt(readFileSync(path, "utf8")));
173
+ }