@tmhs/screencast-mcp 0.45.0 → 0.47.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 (56) hide show
  1. package/README.md +138 -82
  2. package/assets/cursor/arrow.png +0 -0
  3. package/dist/cli.js +360 -0
  4. package/dist/index.js +10 -2
  5. package/dist/prompts.js +16 -3
  6. package/dist/server.js +18 -0
  7. package/dist/tools/addMarker.js +6 -2
  8. package/dist/tools/bugReport.js +2 -2
  9. package/dist/tools/chapters.js +1 -1
  10. package/dist/tools/cursor.js +87 -0
  11. package/dist/tools/cutByTranscript.js +86 -0
  12. package/dist/tools/doctor.js +14 -1
  13. package/dist/tools/indexRecording.js +173 -0
  14. package/dist/tools/listVideoDevices.js +26 -0
  15. package/dist/tools/narrate.js +84 -0
  16. package/dist/tools/overlay.js +2 -0
  17. package/dist/tools/pauseRecording.js +44 -0
  18. package/dist/tools/pipeline.js +215 -19
  19. package/dist/tools/readEvents.js +1 -1
  20. package/dist/tools/resumeRecording.js +46 -0
  21. package/dist/tools/reviewRecording.js +1 -1
  22. package/dist/tools/searchRecording.js +73 -0
  23. package/dist/tools/startRecording.js +106 -67
  24. package/dist/tools/stepGuide.js +193 -0
  25. package/dist/tools/stopRecording.js +38 -3
  26. package/dist/tools/transcribe.js +4 -3
  27. package/dist/tools/zoom.js +1 -1
  28. package/dist/utils/audio.js +12 -4
  29. package/dist/utils/audioDevices.js +34 -4
  30. package/dist/utils/bugReport.js +1 -75
  31. package/dist/utils/captions.js +19 -6
  32. package/dist/utils/chapters.js +5 -0
  33. package/dist/utils/cursor.js +317 -0
  34. package/dist/utils/events.js +22 -4
  35. package/dist/utils/gpu.js +173 -0
  36. package/dist/utils/idle.js +10 -3
  37. package/dist/utils/keystrokes.js +2 -17
  38. package/dist/utils/lifecycle.js +85 -2
  39. package/dist/utils/media.js +4 -0
  40. package/dist/utils/monitors.js +5 -2
  41. package/dist/utils/narrate.js +224 -0
  42. package/dist/utils/pause.js +176 -0
  43. package/dist/utils/pipeline.js +154 -14
  44. package/dist/utils/recipes.js +67 -0
  45. package/dist/utils/recorder.js +163 -0
  46. package/dist/utils/recordingIndex.js +266 -0
  47. package/dist/utils/sessions.js +29 -5
  48. package/dist/utils/stepGuide.js +205 -0
  49. package/dist/utils/steps.js +88 -0
  50. package/dist/utils/targets.js +31 -7
  51. package/dist/utils/timeline.js +85 -0
  52. package/dist/utils/toolsets.js +17 -6
  53. package/dist/utils/transcriptCut.js +134 -0
  54. package/dist/utils/wgc.js +2 -2
  55. package/dist/wgcRecorder.js +1 -1
  56. package/package.json +3 -1
@@ -1,22 +1,43 @@
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
+ import { cursorOptionsSchema, loadCursor } from "./cursor.js";
19
+ import { cursorSpritePath } from "../utils/cursor.js";
18
20
  import { backdropOptionsSchema } from "./backdrop.js";
19
21
  import { keystrokeOptionsSchema, loadBadges, prepareKeystrokeAssets } from "./keystrokeOverlay.js";
22
+ import { MAX_ZOOM } from "../utils/zoom.js";
23
+ import { buildIdleScanArgs, intersect, parseFreezes, parseSilences, DEFAULT_MIN_IDLE_SEC } from "../utils/idle.js";
24
+ import { buildLoudnessMeasureArgs, buildNoiseFloorArgs, loudnessTarget, parseLoudnorm, parseNoiseFloor } from "../utils/audio.js";
25
+ import { buildTranscribeArgs, formatSrt, normalizeCues, parseSrt, resolveWhisperModel } from "../utils/captions.js";
26
+ import { eventPaths } from "../utils/events.js";
27
+ import { bundledFontPath } from "../utils/fonts.js";
28
+ import { retimeAss, retimeCues } from "../utils/timeline.js";
29
+ import { applyOverrides, recipeSteps, RECIPES } from "../utils/recipes.js";
30
+ function transcribeBlocker() {
31
+ if (!hasFilter("whisper"))
32
+ return "this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";
33
+ try {
34
+ resolveWhisperModel(undefined);
35
+ return null;
36
+ }
37
+ catch {
38
+ return "no whisper model (set SCREENCAST_WHISPER_MODEL).";
39
+ }
40
+ }
20
41
  const aspect = z.enum(["16:9", "9:16", "1:1", "4:5"]);
21
42
  const fit = z.enum(["pad", "crop"]).optional();
22
43
  const step = z.discriminatedUnion("op", [
@@ -44,9 +65,29 @@ const step = z.discriminatedUnion("op", [
44
65
  }),
45
66
  z.object({ op: z.literal("callout"), items: z.array(calloutItemSchema).min(1).max(50), fontFile: fontFileSchema }),
46
67
  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() }),
68
+ z.object({
69
+ op: z.literal("zoom"),
70
+ keyframes: z.array(zoomKeyframeSchema).min(1).max(100).optional(),
71
+ follow: z.literal("clicks").optional(),
72
+ maxZoom: z.number().min(1).max(MAX_ZOOM).optional(),
73
+ holdSec: z.number().positive().max(30).optional(),
74
+ transitionSec: z.number().positive().max(5).optional(),
75
+ }),
76
+ z.object({ op: z.literal("cut_idle"), minIdleSec: z.number().positive().optional(), keepSec: z.number().min(0).optional() }),
77
+ z.object({
78
+ op: z.literal("audio"),
79
+ normalize: z.union([z.enum(["youtube", "podcast", "broadcast"]), z.number().min(-70).max(-5)]).optional(),
80
+ denoise: z.enum(["light", "medium", "strong"]).optional(),
81
+ }),
82
+ z.object({
83
+ op: z.literal("burn_subtitles"),
84
+ subtitles: z.string().optional(),
85
+ transcribe: z.boolean().optional(),
86
+ style: z.enum(["clean", "social"]).optional(),
87
+ }),
48
88
  z.object({ op: z.literal("backdrop"), ...backdropOptionsSchema }),
49
89
  z.object({ op: z.literal("keystroke_overlay"), ...keystrokeOptionsSchema }),
90
+ z.object({ op: z.literal("cursor"), ...cursorOptionsSchema }),
50
91
  z.object({ op: z.literal("export_preset"), platform: z.enum(PLATFORMS), fit }),
51
92
  z.object({
52
93
  op: z.literal("export_gif"),
@@ -60,10 +101,16 @@ const inputSchema = {
60
101
  input: z.string().min(1).describe("Path to the source video."),
61
102
  steps: z
62
103
  .array(step)
63
- .min(1)
64
104
  .max(MAX_PIPELINE_STEPS)
105
+ .optional()
65
106
  .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)."),
107
+ "and pixels are relative to the video as it is at that step (after earlier trims, speed, crops). " +
108
+ "zoom follow:\"clicks\" plans from the event log; burn_subtitles takes subtitles or transcribe:true."),
109
+ recipe: z
110
+ .enum(RECIPES)
111
+ .optional()
112
+ .describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = " +
113
+ "+ audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step."),
67
114
  quality: z.enum(["draft", "standard", "high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),
68
115
  dryRun: z.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),
69
116
  output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
@@ -76,19 +123,35 @@ const inputSchema = {
76
123
  export function register(server) {
77
124
  server.registerTool("pipeline", {
78
125
  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.",
126
+ description: "Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, cursor, reframe, zoom, backdrop, " +
127
+ "audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no " +
128
+ "intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",
82
129
  inputSchema,
83
130
  outputSchema: looseOutput({ processes: z.number().int(), steps: z.array(z.string()) }),
84
131
  annotations: WRITES_FILE,
85
132
  }, async (args, extra) => {
86
133
  try {
87
- requireFfmpeg();
134
+ const { ffmpeg } = requireFfmpeg();
88
135
  if (!existsSync(args.input))
89
136
  throw new ScreencastError(`Input file not found: ${args.input}`);
90
- const steps = args.steps;
91
137
  const info = await probeMedia(args.input);
138
+ const hasAudio = info.audioCodec !== null;
139
+ const warnings = [];
140
+ let steps = (args.steps ?? []);
141
+ if (args.recipe) {
142
+ const logged = readClicks(eventPaths(args.input).jsonl);
143
+ const r = recipeSteps(args.recipe, {
144
+ hasAudio,
145
+ hasClicks: !!logged && logged.length > 0,
146
+ transcribeBlocker: hasAudio ? transcribeBlocker() : null,
147
+ });
148
+ steps = applyOverrides(r.steps, steps);
149
+ warnings.push(...r.notes);
150
+ }
151
+ if (steps.length === 0)
152
+ throw new ScreencastError("Give steps, a recipe, or both.");
153
+ if (steps.length > MAX_PIPELINE_STEPS)
154
+ throw new ScreencastError(`At most ${MAX_PIPELINE_STEPS} steps.`);
92
155
  if (!info.width || !info.height)
93
156
  throw new ScreencastError(`Could not read the size of ${args.input}.`);
94
157
  const src = {
@@ -96,8 +159,50 @@ export function register(server) {
96
159
  height: info.height,
97
160
  fps: info.fps ?? 30,
98
161
  durationSec: info.durationSec,
99
- hasAudio: info.audioCodec !== null,
162
+ hasAudio,
100
163
  };
164
+ const timeout = jobTimeoutMs(info.durationSec);
165
+ for (const [i, s] of steps.entries()) {
166
+ if (s.op !== "burn_subtitles")
167
+ continue;
168
+ if (!hasFilter("subtitles")) {
169
+ throw new ScreencastError("This ffmpeg has no subtitles filter (it needs libass).", "Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");
170
+ }
171
+ if (s.subtitles && !existsSync(s.subtitles))
172
+ throw new ScreencastError(`step ${i + 1}: subtitles file not found: ${s.subtitles}`);
173
+ if (s.transcribe) {
174
+ if (!hasFilter("whisper"))
175
+ throw new ScreencastError(`step ${i + 1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);
176
+ resolveWhisperModel(undefined);
177
+ }
178
+ }
179
+ const clicks = {};
180
+ for (const [i, s] of steps.entries()) {
181
+ if (s.op !== "zoom" || s.follow !== "clicks")
182
+ continue;
183
+ const path = eventPaths(args.input).jsonl;
184
+ const logged = readClicks(path);
185
+ if (!logged)
186
+ throw new ScreencastError(`step ${i + 1}: no event log at ${path}; record with start_recording events: true.`);
187
+ clicks[i] = logged;
188
+ }
189
+ let idle;
190
+ const idleAt = steps.findIndex((s) => s.op === "cut_idle");
191
+ const idleStep = steps[idleAt];
192
+ if (idleStep?.op === "cut_idle") {
193
+ const total = info.durationSec;
194
+ if (total === null)
195
+ throw new ScreencastError(`Could not read the duration of ${args.input}.`);
196
+ const speedUp = steps.slice(0, idleAt).reduce((f, x) => (x.op === "speed" ? f * x.factor : f), 1);
197
+ const useAudio = hasAudio;
198
+ const scan = await runCapture(ffmpeg, buildIdleScanArgs(args.input, (idleStep.minIdleSec ?? DEFAULT_MIN_IDLE_SEC) * speedUp, useAudio), timeout, {
199
+ signal: extra.signal,
200
+ });
201
+ if (scan.code !== 0)
202
+ throw new ScreencastError(`Idle scan failed (exit ${scan.code}): ${scan.stderr.trim().slice(-400)}`);
203
+ const freezes = parseFreezes(scan.stderr, total);
204
+ idle = useAudio ? intersect(freezes, parseSilences(scan.stderr, total)) : freezes;
205
+ }
101
206
  const last = steps.at(-1);
102
207
  if (!last)
103
208
  throw new ScreencastError("Provide at least one step.");
@@ -107,7 +212,6 @@ export function register(server) {
107
212
  try {
108
213
  const assets = {};
109
214
  const fallbackFonts = [];
110
- const warnings = [];
111
215
  for (const [i, s] of steps.entries()) {
112
216
  if (s.op !== "callout")
113
217
  continue;
@@ -131,8 +235,86 @@ export function register(server) {
131
235
  keystrokes[i] = { badges, fontFile: k.fontFile, textFiles: k.textFiles };
132
236
  warnings.push(...k.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
133
237
  }
238
+ const cursor = {};
239
+ for (const [i, s] of steps.entries()) {
240
+ if (s.op !== "cursor")
241
+ continue;
242
+ cursor[i] = {
243
+ plan: loadCursor(args.input, s.events, s, info.durationSec),
244
+ sprite: cursorSpritePath(),
245
+ commandsFile: args.dryRun ? `<cursor ${i}.cmd>` : join(work, `s${i}_cursor.cmd`),
246
+ };
247
+ }
134
248
  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 });
249
+ const audioM = {};
250
+ const subtitles = {};
251
+ const fontsDir = dirname(bundledFontPath("regular"));
252
+ const planWith = (chaptersFile) => planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", {
253
+ keystrokes, cursor, idle, clicks, audio: audioM, subtitles, fontsDir, chaptersFile,
254
+ });
255
+ let plan = planWith();
256
+ let transcript;
257
+ for (let n = 0; !args.dryRun && plan.pending.length > 0; n++) {
258
+ const p = plan.pending[0];
259
+ if (n > steps.length * 3)
260
+ throw new ScreencastError(`Internal: step ${p.step + 1} ${p.kind} did not resolve.`);
261
+ const s = steps[p.step];
262
+ const capture = async (base) => {
263
+ const sc = scriptLongFilters(probeArgs(base, p));
264
+ try {
265
+ const r = await runCapture(ffmpeg, sc.args, timeout, { signal: extra.signal });
266
+ if (r.code !== 0)
267
+ throw new ScreencastError(`step ${p.step + 1} ${p.kind} scan failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);
268
+ return r;
269
+ }
270
+ finally {
271
+ sc.cleanup();
272
+ }
273
+ };
274
+ if (p.kind === "noisefloor") {
275
+ audioM[p.step] = { ...audioM[p.step], floorDb: parseNoiseFloor((await capture(buildNoiseFloorArgs(args.input))).stdout) };
276
+ }
277
+ else if (p.kind === "loudness" && s.op === "audio") {
278
+ const r = await capture(buildLoudnessMeasureArgs(args.input, loudnessTarget(s.normalize)));
279
+ try {
280
+ audioM[p.step] = { ...audioM[p.step], loudness: parseLoudnorm(r.stderr) };
281
+ }
282
+ catch {
283
+ warnings.push(`Step ${p.step + 1}: the audio is silent; not normalized.`);
284
+ audioM[p.step] = { ...audioM[p.step], silent: true };
285
+ }
286
+ }
287
+ else if (p.kind === "transcribe" && s.op === "burn_subtitles") {
288
+ const raw = join(work, `s${p.step}_raw.srt`);
289
+ await runFfmpeg(probeArgs(buildTranscribeArgs(args.input, resolveWhisperModel(undefined), raw), p), timeout, {
290
+ signal: extra.signal,
291
+ });
292
+ const cues = existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
293
+ subtitles[p.step] = cues.length > 0 ? join(work, `s${p.step}.srt`) : "";
294
+ if (cues.length > 0) {
295
+ transcript = formatSrt(cues);
296
+ writeFileSync(subtitles[p.step], transcript);
297
+ }
298
+ else
299
+ warnings.push(`Step ${p.step + 1}: no speech was recognised; no captions.`);
300
+ }
301
+ else if (p.kind === "subtitles" && s.op === "burn_subtitles" && s.subtitles) {
302
+ if (p.ops.length === 0)
303
+ subtitles[p.step] = s.subtitles;
304
+ else {
305
+ const text = readFileSync(s.subtitles, "utf8");
306
+ const ass = /\.(ass|ssa)$/i.test(s.subtitles);
307
+ const moved = ass ? retimeAss(text, p.ops) : formatSrt(retimeCues(normalizeCues(parseSrt(text)), p.ops));
308
+ const file = join(work, `s${p.step}${ass ? ".ass" : ".srt"}`);
309
+ writeFileSync(file, moved);
310
+ subtitles[p.step] = ass || moved.trim() ? file : "";
311
+ }
312
+ }
313
+ else {
314
+ throw new ScreencastError(`Internal: step ${p.step + 1} cannot resolve ${p.kind}.`);
315
+ }
316
+ plan = planWith();
317
+ }
136
318
  let chapterList = [];
137
319
  let retimed = [];
138
320
  if (args.chapters) {
@@ -150,12 +332,14 @@ export function register(server) {
150
332
  const file = args.dryRun ? "<chapters.txt>" : join(work, "chapters.txt");
151
333
  if (!args.dryRun)
152
334
  writeFileSync(file, ffmetadata(chapterList));
153
- plan = planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", { chaptersFile: file, keystrokes });
335
+ plan = planWith(file);
154
336
  }
155
337
  }
156
338
  }
157
339
  const result = {
340
+ ...(args.recipe && { recipe: args.recipe, expandedSteps: steps }),
158
341
  steps: plan.summary,
342
+ ...(args.dryRun && plan.pending.length > 0 && { measuredOnRun: plan.pending.map((p) => `step ${p.step + 1}: ${p.kind}`) }),
159
343
  processes: plan.gif ? 2 : 1,
160
344
  width: plan.width,
161
345
  height: plan.height,
@@ -166,11 +350,23 @@ export function register(server) {
166
350
  };
167
351
  if (args.dryRun)
168
352
  return okResponse({ dryRun: true, ...result, ffmpegArgs: plan.args });
353
+ for (const f of plan.files)
354
+ writeFileSync(f.path, f.content);
169
355
  await runEditJob(plan.args, { output: target, durationSec: plan.durationSec, inputDurationSec: info.durationSec, extra });
170
356
  if (plan.gif) {
171
357
  const anim = await exportAnimation(target, output, plan.gif, extra);
172
358
  return okResponse({ outputPath: output, ...result, animation: anim });
173
359
  }
360
+ let subtitlesPath;
361
+ if (transcript) {
362
+ try {
363
+ subtitlesPath = output.replace(/\.[^./\\]+$/, "") + ".srt";
364
+ writeFileSync(subtitlesPath, transcript);
365
+ }
366
+ catch {
367
+ subtitlesPath = undefined;
368
+ }
369
+ }
174
370
  let markersPath;
175
371
  if (chapterList.length > 0) {
176
372
  try {
@@ -179,7 +375,7 @@ export function register(server) {
179
375
  catch {
180
376
  }
181
377
  }
182
- return okResponse({ outputPath: output, ...result, ...(markersPath && { markersPath }) });
378
+ return okResponse({ outputPath: output, ...result, ...(markersPath && { markersPath }), ...(subtitlesPath && { subtitlesPath }) });
183
379
  }
184
380
  finally {
185
381
  rmSync(work, { recursive: true, force: true });
@@ -53,7 +53,7 @@ export function register(server) {
53
53
  throw new ScreencastError(`Session "${args.sessionId}" was recorded without an event log. ` +
54
54
  "Start the recording with events: true.");
55
55
  }
56
- if (record.status === "recording") {
56
+ if (record.status === "recording" || record.status === "paused") {
57
57
  throw new ScreencastError("The recording is still running; its event log is written when it stops.");
58
58
  }
59
59
  path = record.events.path;
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
3
+ import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
4
+ import { requireFfmpeg } from "../utils/ffmpeg.js";
5
+ import { resumeSession } from "../utils/recorder.js";
6
+ import { logMessage } from "../utils/logging.js";
7
+ import { recordedSec } from "../utils/pause.js";
8
+ import { getStore } from "../context.js";
9
+ const r3 = (n) => Math.round(n * 1000) / 1000;
10
+ export function register(server) {
11
+ server.registerTool("resume_recording", {
12
+ title: "Resume Recording",
13
+ description: "Resume a paused recording (same target and settings).",
14
+ inputSchema: { sessionId: z.string().min(1).describe("From start_recording.") },
15
+ outputSchema: looseOutput({ sessionId: z.string(), status: z.string(), recordedSec: z.number() }),
16
+ annotations: WRITES_FILE,
17
+ }, async (args) => {
18
+ try {
19
+ const store = getStore();
20
+ const record = store.get(args.sessionId);
21
+ if (!record)
22
+ throw new ScreencastError(`No session with id "${args.sessionId}".`);
23
+ if (record.status === "recording") {
24
+ return okResponse({
25
+ sessionId: record.id,
26
+ status: "recording",
27
+ recordedSec: r3(recordedSec(record.segments?.parts ?? [])),
28
+ note: "Already recording.",
29
+ });
30
+ }
31
+ const { ffmpeg } = requireFfmpeg();
32
+ const res = await resumeSession(store, record, ffmpeg);
33
+ logMessage("notice", `Recording ${record.id} resumed.`, { sessionId: record.id });
34
+ return okResponse({
35
+ sessionId: record.id,
36
+ status: "recording",
37
+ recordedSec: r3(res.recordedSec),
38
+ pid: res.record.pid,
39
+ ...(res.capSec > 0 ? { remainingSec: res.capSec } : {}),
40
+ });
41
+ }
42
+ catch (error) {
43
+ return errorResponse(error);
44
+ }
45
+ });
46
+ }
@@ -21,7 +21,7 @@ function resolveInput(args) {
21
21
  const record = getStore().get(args.sessionId);
22
22
  if (!record)
23
23
  throw new ScreencastError(`No session with id "${args.sessionId}".`);
24
- if (record.status === "recording")
24
+ if (record.status === "recording" || record.status === "paused")
25
25
  throw new ScreencastError("The recording is still running; stop it first.");
26
26
  return record.outputPath;
27
27
  }
@@ -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
+ }