@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.
@@ -1,22 +1,41 @@
1
1
  import { z } from "zod";
2
- import { join } from "node:path";
3
- import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } 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";
7
- import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
8
- import { runEditJob } from "../utils/jobs.js";
9
- import { planPipeline, MAX_PIPELINE_STEPS } from "../utils/pipeline.js";
7
+ import { requireFfmpeg, probeMedia, hasFilter, runCapture, runFfmpeg, scriptLongFilters } from "../utils/ffmpeg.js";
8
+ import { jobTimeoutMs, runEditJob } from "../utils/jobs.js";
9
+ import { planPipeline, probeArgs, 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";
13
- import { zoomKeyframeSchema } from "./zoom.js";
13
+ import { readClicks, zoomKeyframeSchema } from "./zoom.js";
14
14
  import { redactRegionSchema } from "./redactRegion.js";
15
15
  import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
16
16
  import { PLATFORMS } from "../utils/produce.js";
17
17
  import { buildChapters, ffmetadata, markerPoints, markersOrChapters, retimeMarkers, writeMarkers } from "../utils/chapters.js";
18
18
  import { backdropOptionsSchema } from "./backdrop.js";
19
19
  import { keystrokeOptionsSchema, loadBadges, prepareKeystrokeAssets } from "./keystrokeOverlay.js";
20
+ import { MAX_ZOOM } from "../utils/zoom.js";
21
+ import { buildIdleScanArgs, intersect, parseFreezes, parseSilences, DEFAULT_MIN_IDLE_SEC } from "../utils/idle.js";
22
+ import { buildLoudnessMeasureArgs, buildNoiseFloorArgs, loudnessTarget, parseLoudnorm, parseNoiseFloor } from "../utils/audio.js";
23
+ import { buildTranscribeArgs, formatSrt, normalizeCues, parseSrt, resolveWhisperModel } from "../utils/captions.js";
24
+ import { eventPaths } from "../utils/events.js";
25
+ import { bundledFontPath } from "../utils/fonts.js";
26
+ import { retimeAss, retimeCues } from "../utils/timeline.js";
27
+ import { applyOverrides, recipeSteps, RECIPES } from "../utils/recipes.js";
28
+ function transcribeBlocker() {
29
+ if (!hasFilter("whisper"))
30
+ return "this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";
31
+ try {
32
+ resolveWhisperModel(undefined);
33
+ return null;
34
+ }
35
+ catch {
36
+ return "no whisper model (set SCREENCAST_WHISPER_MODEL).";
37
+ }
38
+ }
20
39
  const aspect = z.enum(["16:9", "9:16", "1:1", "4:5"]);
21
40
  const fit = z.enum(["pad", "crop"]).optional();
22
41
  const step = z.discriminatedUnion("op", [
@@ -44,7 +63,26 @@ const step = z.discriminatedUnion("op", [
44
63
  }),
45
64
  z.object({ op: z.literal("callout"), items: z.array(calloutItemSchema).min(1).max(50), fontFile: fontFileSchema }),
46
65
  z.object({ op: z.literal("reframe"), aspect, fit }),
47
- z.object({ op: z.literal("zoom"), keyframes: z.array(zoomKeyframeSchema).min(1).max(100), transitionSec: z.number().positive().max(5).optional() }),
66
+ z.object({
67
+ op: z.literal("zoom"),
68
+ keyframes: z.array(zoomKeyframeSchema).min(1).max(100).optional(),
69
+ follow: z.literal("clicks").optional(),
70
+ maxZoom: z.number().min(1).max(MAX_ZOOM).optional(),
71
+ holdSec: z.number().positive().max(30).optional(),
72
+ transitionSec: z.number().positive().max(5).optional(),
73
+ }),
74
+ z.object({ op: z.literal("cut_idle"), minIdleSec: z.number().positive().optional(), keepSec: z.number().min(0).optional() }),
75
+ z.object({
76
+ op: z.literal("audio"),
77
+ normalize: z.union([z.enum(["youtube", "podcast", "broadcast"]), z.number().min(-70).max(-5)]).optional(),
78
+ denoise: z.enum(["light", "medium", "strong"]).optional(),
79
+ }),
80
+ z.object({
81
+ op: z.literal("burn_subtitles"),
82
+ subtitles: z.string().optional(),
83
+ transcribe: z.boolean().optional(),
84
+ style: z.enum(["clean", "social"]).optional(),
85
+ }),
48
86
  z.object({ op: z.literal("backdrop"), ...backdropOptionsSchema }),
49
87
  z.object({ op: z.literal("keystroke_overlay"), ...keystrokeOptionsSchema }),
50
88
  z.object({ op: z.literal("export_preset"), platform: z.enum(PLATFORMS), fit }),
@@ -60,10 +98,16 @@ const inputSchema = {
60
98
  input: z.string().min(1).describe("Path to the source video."),
61
99
  steps: z
62
100
  .array(step)
63
- .min(1)
64
101
  .max(MAX_PIPELINE_STEPS)
102
+ .optional()
65
103
  .describe("Edits in order, each { op, ...its tool's options }; export_preset/export_gif only last. Times " +
66
- "and pixels are relative to the video as it is at that step (after earlier trims, speed, crops)."),
104
+ "and pixels are relative to the video as it is at that step (after earlier trims, speed, crops). " +
105
+ "zoom follow:\"clicks\" plans from the event log; burn_subtitles takes subtitles or transcribe:true."),
106
+ recipe: z
107
+ .enum(RECIPES)
108
+ .optional()
109
+ .describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = " +
110
+ "+ audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step."),
67
111
  quality: z.enum(["draft", "standard", "high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),
68
112
  dryRun: z.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),
69
113
  output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
@@ -76,19 +120,35 @@ const inputSchema = {
76
120
  export function register(server) {
77
121
  server.registerTool("pipeline", {
78
122
  title: "Edit Pipeline",
79
- description: "Run several edits (trim, crop, scale, speed, redact, callout, keystroke_overlay, reframe, zoom, backdrop, then optionally " +
80
- "export_preset or export_gif) in one ffmpeg pass: one re-encode, no intermediate files. Prefer it " +
81
- "over chaining edit tools.",
123
+ description: "Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, reframe, zoom, backdrop, " +
124
+ "audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no " +
125
+ "intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",
82
126
  inputSchema,
83
127
  outputSchema: looseOutput({ processes: z.number().int(), steps: z.array(z.string()) }),
84
128
  annotations: WRITES_FILE,
85
129
  }, async (args, extra) => {
86
130
  try {
87
- requireFfmpeg();
131
+ const { ffmpeg } = requireFfmpeg();
88
132
  if (!existsSync(args.input))
89
133
  throw new ScreencastError(`Input file not found: ${args.input}`);
90
- const steps = args.steps;
91
134
  const info = await probeMedia(args.input);
135
+ const hasAudio = info.audioCodec !== null;
136
+ const warnings = [];
137
+ let steps = (args.steps ?? []);
138
+ if (args.recipe) {
139
+ const logged = readClicks(eventPaths(args.input).jsonl);
140
+ const r = recipeSteps(args.recipe, {
141
+ hasAudio,
142
+ hasClicks: !!logged && logged.length > 0,
143
+ transcribeBlocker: hasAudio ? transcribeBlocker() : null,
144
+ });
145
+ steps = applyOverrides(r.steps, steps);
146
+ warnings.push(...r.notes);
147
+ }
148
+ if (steps.length === 0)
149
+ throw new ScreencastError("Give steps, a recipe, or both.");
150
+ if (steps.length > MAX_PIPELINE_STEPS)
151
+ throw new ScreencastError(`At most ${MAX_PIPELINE_STEPS} steps.`);
92
152
  if (!info.width || !info.height)
93
153
  throw new ScreencastError(`Could not read the size of ${args.input}.`);
94
154
  const src = {
@@ -96,8 +156,50 @@ export function register(server) {
96
156
  height: info.height,
97
157
  fps: info.fps ?? 30,
98
158
  durationSec: info.durationSec,
99
- hasAudio: info.audioCodec !== null,
159
+ hasAudio,
100
160
  };
161
+ const timeout = jobTimeoutMs(info.durationSec);
162
+ for (const [i, s] of steps.entries()) {
163
+ if (s.op !== "burn_subtitles")
164
+ continue;
165
+ if (!hasFilter("subtitles")) {
166
+ throw new ScreencastError("This ffmpeg has no subtitles filter (it needs libass).", "Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");
167
+ }
168
+ if (s.subtitles && !existsSync(s.subtitles))
169
+ throw new ScreencastError(`step ${i + 1}: subtitles file not found: ${s.subtitles}`);
170
+ if (s.transcribe) {
171
+ if (!hasFilter("whisper"))
172
+ throw new ScreencastError(`step ${i + 1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);
173
+ resolveWhisperModel(undefined);
174
+ }
175
+ }
176
+ const clicks = {};
177
+ for (const [i, s] of steps.entries()) {
178
+ if (s.op !== "zoom" || s.follow !== "clicks")
179
+ continue;
180
+ const path = eventPaths(args.input).jsonl;
181
+ const logged = readClicks(path);
182
+ if (!logged)
183
+ throw new ScreencastError(`step ${i + 1}: no event log at ${path}; record with start_recording events: true.`);
184
+ clicks[i] = logged;
185
+ }
186
+ let idle;
187
+ const idleAt = steps.findIndex((s) => s.op === "cut_idle");
188
+ const idleStep = steps[idleAt];
189
+ if (idleStep?.op === "cut_idle") {
190
+ const total = info.durationSec;
191
+ if (total === null)
192
+ throw new ScreencastError(`Could not read the duration of ${args.input}.`);
193
+ const speedUp = steps.slice(0, idleAt).reduce((f, x) => (x.op === "speed" ? f * x.factor : f), 1);
194
+ const useAudio = hasAudio;
195
+ const scan = await runCapture(ffmpeg, buildIdleScanArgs(args.input, (idleStep.minIdleSec ?? DEFAULT_MIN_IDLE_SEC) * speedUp, useAudio), timeout, {
196
+ signal: extra.signal,
197
+ });
198
+ if (scan.code !== 0)
199
+ throw new ScreencastError(`Idle scan failed (exit ${scan.code}): ${scan.stderr.trim().slice(-400)}`);
200
+ const freezes = parseFreezes(scan.stderr, total);
201
+ idle = useAudio ? intersect(freezes, parseSilences(scan.stderr, total)) : freezes;
202
+ }
101
203
  const last = steps.at(-1);
102
204
  if (!last)
103
205
  throw new ScreencastError("Provide at least one step.");
@@ -107,7 +209,6 @@ export function register(server) {
107
209
  try {
108
210
  const assets = {};
109
211
  const fallbackFonts = [];
110
- const warnings = [];
111
212
  for (const [i, s] of steps.entries()) {
112
213
  if (s.op !== "callout")
113
214
  continue;
@@ -132,7 +233,75 @@ export function register(server) {
132
233
  warnings.push(...k.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
133
234
  }
134
235
  const target = last.op === "export_gif" ? (args.dryRun ? "<temporary stage1.mp4>" : join(work, "stage1.mp4")) : output;
135
- let plan = planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", { keystrokes });
236
+ const audioM = {};
237
+ const subtitles = {};
238
+ const fontsDir = dirname(bundledFontPath("regular"));
239
+ const planWith = (chaptersFile) => planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", {
240
+ keystrokes, idle, clicks, audio: audioM, subtitles, fontsDir, chaptersFile,
241
+ });
242
+ let plan = planWith();
243
+ let transcript;
244
+ for (let n = 0; !args.dryRun && plan.pending.length > 0; n++) {
245
+ const p = plan.pending[0];
246
+ if (n > steps.length * 3)
247
+ throw new ScreencastError(`Internal: step ${p.step + 1} ${p.kind} did not resolve.`);
248
+ const s = steps[p.step];
249
+ const capture = async (base) => {
250
+ const sc = scriptLongFilters(probeArgs(base, p));
251
+ try {
252
+ const r = await runCapture(ffmpeg, sc.args, timeout, { signal: extra.signal });
253
+ if (r.code !== 0)
254
+ throw new ScreencastError(`step ${p.step + 1} ${p.kind} scan failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);
255
+ return r;
256
+ }
257
+ finally {
258
+ sc.cleanup();
259
+ }
260
+ };
261
+ if (p.kind === "noisefloor") {
262
+ audioM[p.step] = { ...audioM[p.step], floorDb: parseNoiseFloor((await capture(buildNoiseFloorArgs(args.input))).stdout) };
263
+ }
264
+ else if (p.kind === "loudness" && s.op === "audio") {
265
+ const r = await capture(buildLoudnessMeasureArgs(args.input, loudnessTarget(s.normalize)));
266
+ try {
267
+ audioM[p.step] = { ...audioM[p.step], loudness: parseLoudnorm(r.stderr) };
268
+ }
269
+ catch {
270
+ warnings.push(`Step ${p.step + 1}: the audio is silent; not normalized.`);
271
+ audioM[p.step] = { ...audioM[p.step], silent: true };
272
+ }
273
+ }
274
+ else if (p.kind === "transcribe" && s.op === "burn_subtitles") {
275
+ const raw = join(work, `s${p.step}_raw.srt`);
276
+ await runFfmpeg(probeArgs(buildTranscribeArgs(args.input, resolveWhisperModel(undefined), raw), p), timeout, {
277
+ signal: extra.signal,
278
+ });
279
+ const cues = existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
280
+ subtitles[p.step] = cues.length > 0 ? join(work, `s${p.step}.srt`) : "";
281
+ if (cues.length > 0) {
282
+ transcript = formatSrt(cues);
283
+ writeFileSync(subtitles[p.step], transcript);
284
+ }
285
+ else
286
+ warnings.push(`Step ${p.step + 1}: no speech was recognised; no captions.`);
287
+ }
288
+ else if (p.kind === "subtitles" && s.op === "burn_subtitles" && s.subtitles) {
289
+ if (p.ops.length === 0)
290
+ subtitles[p.step] = s.subtitles;
291
+ else {
292
+ const text = readFileSync(s.subtitles, "utf8");
293
+ const ass = /\.(ass|ssa)$/i.test(s.subtitles);
294
+ const moved = ass ? retimeAss(text, p.ops) : formatSrt(retimeCues(normalizeCues(parseSrt(text)), p.ops));
295
+ const file = join(work, `s${p.step}${ass ? ".ass" : ".srt"}`);
296
+ writeFileSync(file, moved);
297
+ subtitles[p.step] = ass || moved.trim() ? file : "";
298
+ }
299
+ }
300
+ else {
301
+ throw new ScreencastError(`Internal: step ${p.step + 1} cannot resolve ${p.kind}.`);
302
+ }
303
+ plan = planWith();
304
+ }
136
305
  let chapterList = [];
137
306
  let retimed = [];
138
307
  if (args.chapters) {
@@ -150,12 +319,14 @@ export function register(server) {
150
319
  const file = args.dryRun ? "<chapters.txt>" : join(work, "chapters.txt");
151
320
  if (!args.dryRun)
152
321
  writeFileSync(file, ffmetadata(chapterList));
153
- plan = planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", { chaptersFile: file, keystrokes });
322
+ plan = planWith(file);
154
323
  }
155
324
  }
156
325
  }
157
326
  const result = {
327
+ ...(args.recipe && { recipe: args.recipe, expandedSteps: steps }),
158
328
  steps: plan.summary,
329
+ ...(args.dryRun && plan.pending.length > 0 && { measuredOnRun: plan.pending.map((p) => `step ${p.step + 1}: ${p.kind}`) }),
159
330
  processes: plan.gif ? 2 : 1,
160
331
  width: plan.width,
161
332
  height: plan.height,
@@ -171,6 +342,16 @@ export function register(server) {
171
342
  const anim = await exportAnimation(target, output, plan.gif, extra);
172
343
  return okResponse({ outputPath: output, ...result, animation: anim });
173
344
  }
345
+ let subtitlesPath;
346
+ if (transcript) {
347
+ try {
348
+ subtitlesPath = output.replace(/\.[^./\\]+$/, "") + ".srt";
349
+ writeFileSync(subtitlesPath, transcript);
350
+ }
351
+ catch {
352
+ subtitlesPath = undefined;
353
+ }
354
+ }
174
355
  let markersPath;
175
356
  if (chapterList.length > 0) {
176
357
  try {
@@ -179,7 +360,7 @@ export function register(server) {
179
360
  catch {
180
361
  }
181
362
  }
182
- return okResponse({ outputPath: output, ...result, ...(markersPath && { markersPath }) });
363
+ return okResponse({ outputPath: output, ...result, ...(markersPath && { markersPath }), ...(subtitlesPath && { subtitlesPath }) });
183
364
  }
184
365
  finally {
185
366
  rmSync(work, { recursive: true, force: true });
@@ -0,0 +1,73 @@
1
+ import { z } from "zod";
2
+ import { join } from "node:path";
3
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
+ import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
7
+ import { requireFfmpeg, runFfmpeg } from "../utils/ffmpeg.js";
8
+ import { buildSampleAtTimestampArgs } from "../utils/media.js";
9
+ import { subdir } from "../utils/paths.js";
10
+ import { encodeInlineImages, clampInlineCount, MAX_INLINE_IMAGES } from "../utils/images.js";
11
+ import { DEFAULT_SEARCH_LIMIT, MAX_SEARCH_LIMIT, fingerprintFile, findIndex, keyframeTime, readIndex, resolveRecording, sameFingerprint, searchIndex, } from "../utils/recordingIndex.js";
12
+ const THUMB_WIDTH = 480;
13
+ const inputSchema = {
14
+ input: z.string().optional().describe("Recording path."),
15
+ sessionId: z.string().optional().describe("Or a stopped session id."),
16
+ query: z.string().min(1).describe("Text; tolerates OCR misreads."),
17
+ regex: z.boolean().optional().describe("query is a regex."),
18
+ limit: z.number().int().min(1).max(MAX_SEARCH_LIMIT).optional().describe(`Max hits (default ${DEFAULT_SEARCH_LIMIT}).`),
19
+ images: z.number().int().min(0).max(MAX_INLINE_IMAGES).optional().describe("Thumbnails of the top N hits (default 0)."),
20
+ };
21
+ export function register(server) {
22
+ server.registerTool("search_recording", {
23
+ title: "Search Recording",
24
+ description: "Search an index_recording timeline (screen text, events, markers, transcript): timecoded hits, " +
25
+ "best first, secrets masked. No frames unless asked.",
26
+ inputSchema,
27
+ outputSchema: looseOutput({ total: z.number(), hits: z.array(z.unknown()) }),
28
+ annotations: READ_ONLY,
29
+ }, async (args, extra) => {
30
+ try {
31
+ const source = await resolveRecording(args);
32
+ const indexPath = findIndex(source.path, subdir("edits"));
33
+ const index = indexPath ? readIndex(indexPath) : null;
34
+ if (!indexPath || !index) {
35
+ throw new ScreencastError(`No index for ${source.path}.`, "Run index_recording on it first.");
36
+ }
37
+ const stale = !sameFingerprint(index.fingerprint, fingerprintFile(source.path));
38
+ const { hits, total } = searchIndex(index, args.query, { regex: args.regex === true, limit: args.limit });
39
+ const want = Math.min(clampInlineCount(args.images ?? 0), hits.length);
40
+ let images = [];
41
+ if (want > 0) {
42
+ requireFfmpeg();
43
+ const work = mkdtempSync(join(tmpdir(), "screencast-search-"));
44
+ try {
45
+ const shots = [];
46
+ for (const [i, hit] of hits.slice(0, want).entries()) {
47
+ const at = hit.t === hit.start ? keyframeTime(hit) : hit.t;
48
+ const out = join(work, `hit_${i}.png`);
49
+ await runFfmpeg(buildSampleAtTimestampArgs(source.path, at, out), 60_000, { signal: extra.signal });
50
+ if (existsSync(out))
51
+ shots.push(out);
52
+ }
53
+ images = (await encodeInlineImages(shots, THUMB_WIDTH, want)).images;
54
+ }
55
+ finally {
56
+ rmSync(work, { recursive: true, force: true });
57
+ }
58
+ }
59
+ return okResponse({
60
+ indexPath,
61
+ query: args.query,
62
+ total,
63
+ hits,
64
+ ...(total > hits.length ? { more: total - hits.length } : {}),
65
+ ...(index.ocr ? {} : { note: "The index has no screen text (OCR was unavailable when it was built)." }),
66
+ ...(stale ? { stale: true, warning: "The recording changed since it was indexed; run index_recording again." } : {}),
67
+ }, images);
68
+ }
69
+ catch (error) {
70
+ return errorResponse(error);
71
+ }
72
+ });
73
+ }
@@ -0,0 +1,193 @@
1
+ import { z } from "zod";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
+ import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
7
+ import { requireFfmpeg, probeMedia, runFfmpeg } from "../utils/ffmpeg.js";
8
+ import { progressReporter } from "../utils/jobs.js";
9
+ import { parseEventsJsonl } from "../utils/events.js";
10
+ import { inputSteps } from "../utils/steps.js";
11
+ import { readMarkers } from "../utils/chapters.js";
12
+ import { ocrStatus } from "../utils/capabilities.js";
13
+ import { readFrames, scanMatches } from "../utils/ocrScan.js";
14
+ import { DEFAULT_SECRET_PATTERN } from "../utils/bugReport.js";
15
+ import { resolveOutputDir, subdir, stamp, rand } from "../utils/paths.js";
16
+ import { GUIDE_FILES, MAX_GUIDE_STEPS, assignSections, buildGuideHtml, buildGuideMarkdown, buildStepFrameArgs, buildStepShotArgs, caption, guideSteps, labelAt, shotFilter, } from "../utils/stepGuide.js";
17
+ import { resolveSource } from "./bugReport.js";
18
+ const OCR_BATCH = 10;
19
+ const inputSchema = {
20
+ input: z.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),
21
+ sessionId: z.string().min(1).optional().describe("Or a stopped session's id."),
22
+ title: z.string().max(200).optional().describe("Guide title."),
23
+ format: z.enum(["md", "html", "both"]).optional().describe("md + images/, self-contained html, or both (default)."),
24
+ ocr: z.boolean().optional().describe("OCR shots for captions and secret boxes (default true; needs Windows OCR)."),
25
+ outputDir: z.string().optional().describe("Guide folder (default: new in SCREENCAST_HOME/edits)."),
26
+ overwrite: z.boolean().optional().describe("Replace a guide already in outputDir."),
27
+ };
28
+ export function register(server) {
29
+ server.registerTool("step_guide", {
30
+ title: "Step-by-Step Guide",
31
+ description: "Turn a recording's event log into a numbered how-to: a ringed screenshot and caption per step, marker " +
32
+ "headings; Markdown and/or one HTML file. Never includes typed text.",
33
+ inputSchema,
34
+ outputSchema: looseOutput({ outputDir: z.string() }),
35
+ annotations: WRITES_FILE,
36
+ }, async (args, extra) => {
37
+ let createdDir = null;
38
+ const written = [];
39
+ try {
40
+ if ((args.input === undefined) === (args.sessionId === undefined)) {
41
+ throw new ScreencastError("Provide exactly one of: input (a recording path) or sessionId.");
42
+ }
43
+ requireFfmpeg();
44
+ const source = await resolveSource(args);
45
+ if (!source.eventsPath) {
46
+ throw new ScreencastError("The recording has no input event log, so there are no steps to write.", "Record with start_recording events: true, or pass a recording that has a .events.jsonl beside it.");
47
+ }
48
+ const info = await probeMedia(source.path);
49
+ if (!info.width || !info.height)
50
+ throw new ScreencastError(`Could not read the size of ${source.path}.`);
51
+ const duration = info.videoDurationSec ?? info.durationSec;
52
+ if (duration === null)
53
+ throw new ScreencastError(`Could not read the duration of ${source.path}.`);
54
+ const fps = info.fps ?? 30;
55
+ const format = args.format ?? "both";
56
+ const wantMd = format !== "html";
57
+ const wantHtml = format !== "md";
58
+ const useOcr = args.ocr !== false;
59
+ if (useOcr) {
60
+ const status = await ocrStatus();
61
+ if (!status.available) {
62
+ throw new ScreencastError(`Captions and the secret scan need Windows OCR, which is unavailable here${status.error ? ` (${status.error})` : ""}.`, "Pass ocr: false for a guide without them (then check the screenshots yourself before sharing), or run doctor.");
63
+ }
64
+ }
65
+ const dir = resolveOutputDir(args.outputDir, subdir("edits")) ?? join(subdir("edits"), `step-guide-${stamp()}-${rand()}`);
66
+ const paths = { markdown: join(dir, GUIDE_FILES.markdown), html: join(dir, GUIDE_FILES.html), images: join(dir, GUIDE_FILES.images) };
67
+ const clash = [paths.markdown, paths.html].filter((p) => existsSync(p));
68
+ if (clash.length > 0 && !args.overwrite) {
69
+ throw new ScreencastError(`The folder already holds a guide: ${clash.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);
70
+ }
71
+ const all = inputSteps(parseEventsJsonl(readFileSync(source.eventsPath, "utf8")));
72
+ const kept = all.slice(0, MAX_GUIDE_STEPS);
73
+ const plain = guideSteps(kept, { durationSec: duration, fps });
74
+ const shots = plain.map((s, i) => ({ i, s })).filter(({ s }) => s.shotT !== undefined);
75
+ const warnings = [];
76
+ if (!existsSync(dir)) {
77
+ mkdirSync(dir, { recursive: true });
78
+ createdDir = dir;
79
+ }
80
+ const work = mkdtempSync(join(tmpdir(), "screencast-guide-"));
81
+ try {
82
+ const progress = progressReporter(extra);
83
+ const total = shots.length * (useOcr ? 3 : 2) || 1;
84
+ let done = 0;
85
+ const tick = () => progress?.(++done / total);
86
+ const frames = [];
87
+ for (const { s } of shots) {
88
+ const out = join(work, `frame-${String(s.n).padStart(3, "0")}.png`);
89
+ await runFfmpeg(buildStepFrameArgs(source.path, s.shotT, out), 60_000, { signal: extra.signal });
90
+ frames.push(out);
91
+ tick();
92
+ }
93
+ const read = frames.map(() => null);
94
+ if (useOcr) {
95
+ for (let b = 0; b < frames.length; b += OCR_BATCH) {
96
+ extra.signal.throwIfAborted();
97
+ const batch = await readFrames(frames.slice(b, b + OCR_BATCH), work, extra.signal);
98
+ batch.forEach((f, k) => {
99
+ read[b + k] = f;
100
+ tick();
101
+ });
102
+ }
103
+ }
104
+ const labels = kept.map(() => null);
105
+ const boxes = shots.map(({ i, s }, k) => {
106
+ const frame = read[k];
107
+ if (!frame)
108
+ return [];
109
+ if (s.x !== undefined && s.y !== undefined)
110
+ labels[i] = labelAt(frame.lines, s.x, s.y);
111
+ return scanMatches({ frames: [{ ...frame, t: 0, path: "" }], step: 1, end: 1 }, DEFAULT_SECRET_PATTERN, true, "line")
112
+ .redactRegions;
113
+ });
114
+ const steps = assignSections(guideSteps(kept, { durationSec: duration, fps, labels }), readMarkers(source.path));
115
+ const imageDir = wantMd ? paths.images : join(work, "images");
116
+ if (wantMd && existsSync(imageDir) && args.overwrite) {
117
+ for (const f of readdirSync(imageDir))
118
+ if (/^step-\d+\.png$/.test(f))
119
+ rmSync(join(imageDir, f), { force: true });
120
+ }
121
+ mkdirSync(imageDir, { recursive: true });
122
+ let redactions = 0;
123
+ for (const [k, { i }] of shots.entries()) {
124
+ const step = steps[i];
125
+ const file = GUIDE_FILES.image(step.n);
126
+ const ring = step.x !== undefined && step.y !== undefined ? { x: step.x, y: step.y } : undefined;
127
+ const filter = shotFilter({ width: info.width, height: info.height }, { click: ring, boxes: boxes[k] });
128
+ const out = join(imageDir, file);
129
+ await runFfmpeg(buildStepShotArgs(frames[k], filter, out), 60_000, { signal: extra.signal });
130
+ if (wantMd)
131
+ written.push(out);
132
+ step.image = file;
133
+ redactions += boxes[k].length;
134
+ tick();
135
+ }
136
+ const stepsNote = all.length === 0 ? "The event log has no clicks, shortcuts, typing, or scrolls." : undefined;
137
+ const data = {
138
+ title: args.title?.trim() || "Step-by-step guide",
139
+ createdAt: new Date().toISOString(),
140
+ recording: { durationSec: Math.round(duration * 1000) / 1000, width: info.width, height: info.height },
141
+ steps,
142
+ ...(all.length > MAX_GUIDE_STEPS ? { stepsOmitted: all.length - MAX_GUIDE_STEPS } : {}),
143
+ ...(stepsNote ? { stepsNote } : {}),
144
+ ocr: useOcr ? "read" : "off",
145
+ redactions,
146
+ };
147
+ if (wantMd) {
148
+ writeFileSync(paths.markdown, buildGuideMarkdown(data));
149
+ written.push(paths.markdown);
150
+ }
151
+ if (wantHtml) {
152
+ const src = (file) => `data:image/png;base64,${readFileSync(join(imageDir, file)).toString("base64")}`;
153
+ writeFileSync(paths.html, buildGuideHtml(data, src));
154
+ written.push(paths.html);
155
+ }
156
+ if (data.stepsOmitted)
157
+ warnings.push(`Only the first ${MAX_GUIDE_STEPS} steps were written; ${data.stepsOmitted} more were left out.`);
158
+ if (stepsNote)
159
+ warnings.push(stepsNote);
160
+ return okResponse({
161
+ outputDir: dir,
162
+ ...(wantMd ? { markdownPath: paths.markdown, imagesDir: paths.images } : {}),
163
+ ...(wantHtml ? { htmlPath: paths.html } : {}),
164
+ steps: steps.map((s) => ({
165
+ ...(s.n > 0 ? { n: s.n } : {}),
166
+ t: s.t,
167
+ action: s.action,
168
+ caption: caption(s),
169
+ ...(s.section ? { section: s.section } : {}),
170
+ ...(s.image ? { image: s.image } : {}),
171
+ })),
172
+ ocr: data.ocr,
173
+ redactions,
174
+ ...(warnings.length > 0 ? { warnings } : {}),
175
+ note: useOcr
176
+ ? "Captions are OCR-based templates: rewrite them in guide.md as needed. The secret scan is best-effort: look at the screenshots before sharing."
177
+ : "Not scanned for secrets: look at the screenshots before sharing.",
178
+ });
179
+ }
180
+ finally {
181
+ rmSync(work, { recursive: true, force: true });
182
+ }
183
+ }
184
+ catch (error) {
185
+ if (createdDir)
186
+ rmSync(createdDir, { recursive: true, force: true });
187
+ else
188
+ for (const p of written)
189
+ rmSync(p, { force: true });
190
+ return errorResponse(error);
191
+ }
192
+ });
193
+ }
@@ -4,7 +4,7 @@ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
4
  import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
5
5
  import { requireFfmpeg, runFfmpeg, probeMedia, hasFilter } from "../utils/ffmpeg.js";
6
6
  import { jobTimeoutMs } from "../utils/jobs.js";
7
- import { resolveWhisperModel, buildTranscribeArgs, parseSrt, normalizeCues, formatSrt, WHISPER_MODEL_ENV, } from "../utils/captions.js";
7
+ import { resolveWhisperModel, buildTranscribeArgs, parseSrt, normalizeCues, mergePunctuation, formatSrt, WHISPER_MODEL_ENV, } from "../utils/captions.js";
8
8
  import { resolveOutput, subdir, stamp, rand, tempPath } from "../utils/paths.js";
9
9
  const inputSchema = {
10
10
  input: z.string().min(1).describe("Path to the video or audio to transcribe."),
@@ -13,6 +13,7 @@ const inputSchema = {
13
13
  .optional()
14
14
  .describe(`Path to a whisper.cpp model file (ggml-*.bin). Defaults to ${WHISPER_MODEL_ENV}.`),
15
15
  language: z.string().optional().describe("Spoken language code, e.g. 'en', or 'auto' (default)."),
16
+ words: z.boolean().optional().describe("One word per cue, for word timing (cut_by_transcript)."),
16
17
  output: z.string().optional().describe("Optional output .srt path. Defaults under SCREENCAST_HOME/edits."),
17
18
  overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
18
19
  };
@@ -41,10 +42,10 @@ export function register(server) {
41
42
  const output = resolveOutput(args.output, subdir("edits"), `captions-${stamp()}-${rand()}.srt`, args.overwrite);
42
43
  const raw = tempPath(".srt");
43
44
  try {
44
- await runFfmpeg(buildTranscribeArgs(args.input, model, raw, args.language ?? "auto"), jobTimeoutMs(info.durationSec), {
45
+ await runFfmpeg(buildTranscribeArgs(args.input, model, raw, args.language ?? "auto", args.words), jobTimeoutMs(info.durationSec), {
45
46
  signal: extra.signal,
46
47
  });
47
- const cues = existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
48
+ const cues = existsSync(raw) ? normalizeCues(mergePunctuation(parseSrt(readFileSync(raw, "utf8")))) : [];
48
49
  writeFileSync(output, formatSrt(cues));
49
50
  const text = cues.map((c) => c.text.replace(/\n/g, " ")).join(" ");
50
51
  return okResponse({
@@ -9,7 +9,7 @@ import { keyframesToViews, buildZoomArgs, createAutoZoomPlanner, planClickZoom,
9
9
  import { eventPaths, parseEventsJsonl } from "../utils/events.js";
10
10
  import { validateColor } from "../utils/validate.js";
11
11
  export const MAX_RINGS = 200;
12
- function readClicks(path) {
12
+ export function readClicks(path) {
13
13
  if (!existsSync(path))
14
14
  return null;
15
15
  return parseEventsJsonl(readFileSync(path, "utf8"))