@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
@@ -4,16 +4,18 @@ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
4
  import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
5
5
  import { requireFfmpeg, wgcAvailable } from "../utils/ffmpeg.js";
6
6
  import { fileURLToPath } from "node:url";
7
- import { buildCaptureArgs, captureFrame, resolveQuality, DEFAULT_FPS, DEFAULT_QUALITY, DEFAULT_MAX_RECORDING_SEC, MAX_RECORDING_CAP_SEC, resolveMaxDuration, captureKeyframeArgs, } from "../utils/targets.js";
7
+ import { buildCaptureArgs, captureFrame, DEFAULT_FPS, DEFAULT_QUALITY, DEFAULT_MAX_RECORDING_SEC, MAX_RECORDING_CAP_SEC, resolveMaxDuration, captureKeyframeArgs, } from "../utils/targets.js";
8
8
  import { resolveCaptureTarget } from "../utils/resolveTarget.js";
9
9
  import { windowMatchReport } from "../utils/windows.js";
10
- import { resolveLoopbackDevice } from "../utils/audioDevices.js";
10
+ import { resolveLoopbackDevice, resolveVideoDevice } from "../utils/audioDevices.js";
11
11
  import { confirmCapture, describeTarget } from "../utils/consent.js";
12
- import { logMessage, StderrWatch } from "../utils/logging.js";
13
12
  import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
14
13
  import { getStore } from "../context.js";
15
- import { classifyUnrequestedExit, killPid, serverIdentity } from "../utils/sessions.js";
16
- import { rmSync } from "node:fs";
14
+ import { killPid, serverIdentity } from "../utils/sessions.js";
15
+ import { mkdirSync, rmSync } from "node:fs";
16
+ import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, } from "../utils/gpu.js";
17
+ import { attachExitHandler, captureStartMs, settleCapture, tailLines, watchStderr, } from "../utils/recorder.js";
18
+ import { DEFAULT_WEBCAM_SIZE, eventClock, partsDir, sessionEnded, webcamOutputPath, webcamPartPath, } from "../utils/pause.js";
17
19
  import { basename, join } from "node:path";
18
20
  import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, segmentOutputArgs, } from "../utils/replay.js";
19
21
  import { DEFAULT_KEY_MODE, eventPaths, parseCaptureStart, prepareEventPaths, startEventLogger, stopEventLogger, summarizeEvents, trackFinalizer, writeEventsFile, } from "../utils/events.js";
@@ -73,11 +75,28 @@ const inputSchema = {
73
75
  .optional()
74
76
  .describe("With events: masked (default) logs typing only as 0.5 s-grid bursts, never keys; shortcuts " +
75
77
  "also names Ctrl/Alt/Win chords. Typed text is never logged."),
78
+ cursor: z
79
+ .enum(["os", "events"])
80
+ .optional()
81
+ .describe('events: leave the OS cursor out and log it (implies events) for the cursor tool to redraw.'),
76
82
  backend: z
77
- .enum(["gdigrab", "wgc"])
83
+ .enum(["gdigrab", "wgc", "ddagrab"])
78
84
  .optional()
79
85
  .describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own " +
80
- "surface, even when covered or moved; client area only, no audio."),
86
+ "surface, even when covered or moved; client area only, no audio. ddagrab: one display on the GPU, low CPU."),
87
+ encoder: z
88
+ .enum(["auto", "x264", "nvenc", "qsv", "amf"])
89
+ .optional()
90
+ .describe("auto = first working GPU encoder, else x264 (default with ddagrab; else x264)."),
91
+ webcam: z
92
+ .object({
93
+ device: z.string().optional().describe("list_video_devices name (default: first)."),
94
+ corner: z.enum(["top_left", "top_right", "bottom_left", "bottom_right"]).optional(),
95
+ size: z.number().min(0.1).max(0.5).optional().describe("Share of width (0.25)."),
96
+ shape: z.enum(["rect", "circle"]).optional(),
97
+ })
98
+ .optional()
99
+ .describe("Also record a camera to <output>.webcam.mp4, aligned for overlay."),
81
100
  replayBufferSec: z
82
101
  .number()
83
102
  .int()
@@ -86,6 +105,10 @@ const inputSchema = {
86
105
  .optional()
87
106
  .describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab only."),
88
107
  };
108
+ function webcamStart(watch, audio) {
109
+ const ms = parseCaptureStart(watch.head(), audio ? 2 : 1);
110
+ return ms !== null ? { webcamStartMs: ms } : {};
111
+ }
89
112
  export function register(server) {
90
113
  server.registerTool("start_recording", {
91
114
  title: "Start Recording",
@@ -102,6 +125,9 @@ export function register(server) {
102
125
  }, async (args, extra) => {
103
126
  try {
104
127
  const { ffmpeg } = requireFfmpeg();
128
+ const hideCursor = args.cursor === "events";
129
+ if (hideCursor)
130
+ args.events = true;
105
131
  const { target, monitors, window } = await resolveCaptureTarget(args.target, {
106
132
  exactTitle: args.exactTitle,
107
133
  backend: args.backend,
@@ -127,19 +153,43 @@ export function register(server) {
127
153
  const audio = args.audio?.source === "system"
128
154
  ? { device: await resolveLoopbackDevice(args.audio.device) }
129
155
  : undefined;
156
+ if (args.webcam && (backend === "wgc" || replay)) {
157
+ throw new ScreencastError("webcam works with backend gdigrab or ddagrab, without replayBufferSec.");
158
+ }
159
+ const webcamDevice = args.webcam ? await resolveVideoDevice(args.webcam.device) : undefined;
160
+ const dda = backend === "ddagrab" ? planDdaSource(captureFrame(target, monitors), await getDxgiOutputs()) : null;
130
161
  await confirmCapture(server, (replay ? `Keep a rolling ${replay.bufferSec} s replay buffer of ` : "Record ") +
131
162
  `${describeTarget(args.target, window)} ` +
132
163
  (maxDurationSec > 0 ? `for up to ${maxDurationSec} s` : "with no time limit") +
133
164
  (audio ? `, with system audio (${audio.device})` : ", without audio") +
165
+ (webcamDevice ? `, with the webcam (${webcamDevice})` : "") +
134
166
  (args.events ? ", logging mouse clicks and typing" : "") +
135
167
  (replay ? ", kept only until save_replay or stop_recording { save: true } writes it out?" : `, saved to ${output}?`), extra.signal);
136
- const captureArgs = buildCaptureArgs(target, {
168
+ const pick = await resolveEncoder(args.encoder ?? (backend === "ddagrab" ? "auto" : "x264"), backend === "ddagrab" ? "ddagrab" : "gdigrab", ffmpeg);
169
+ if (dda && !pick.gpuFrames && !(await ddagrabWorks(ffmpeg))) {
170
+ throw new ScreencastError("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).", 'Use backend "gdigrab".');
171
+ }
172
+ const hw = pick.encoder !== "x264";
173
+ const captureOpts = {
137
174
  fps,
138
175
  quality,
139
- output,
140
176
  monitors,
141
177
  audio,
178
+ drawMouse: !hideCursor,
179
+ ...(dda ? { videoInput: buildDdaInputArgs(dda, fps, { download: !pick.gpuFrames, drawMouse: !hideCursor }) } : {}),
180
+ ...(hw ? { videoCodec: encoderArgs(pick.encoder, quality, { gpuFrames: pick.gpuFrames }) } : {}),
181
+ };
182
+ const webcam = webcamDevice
183
+ ? { device: webcamDevice, ...(hw ? { codec: encoderArgs(pick.encoder, quality) } : {}) }
184
+ : undefined;
185
+ const webcamRaw = webcam ? webcamPartPath(output, 0) : undefined;
186
+ if (webcamRaw)
187
+ mkdirSync(partsDir(output), { recursive: true });
188
+ const captureArgs = buildCaptureArgs(target, {
189
+ ...captureOpts,
190
+ output,
142
191
  maxDurationSec,
192
+ ...(webcam && webcamRaw ? { webcam: { ...webcam, output: webcamRaw } } : {}),
143
193
  });
144
194
  const ffArgs = replay ? segmentOutputArgs(captureArgs, replay) : captureArgs;
145
195
  if (replay)
@@ -156,43 +206,15 @@ export function register(server) {
156
206
  const child = backend === "wgc"
157
207
  ? spawn(process.execPath, [
158
208
  fileURLToPath(new URL("../wgcRecorder.js", import.meta.url)),
159
- JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...resolveQuality(quality), ...captureKeyframeArgs(fps)], output, maxDurationSec }),
209
+ JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...encoderArgs(pick.encoder, quality), ...captureKeyframeArgs(fps)], output, maxDurationSec, cursor: !hideCursor }),
160
210
  ], { stdio: ["pipe", "ignore", "pipe"], windowsHide: true })
161
211
  : spawn(ffmpeg, ffArgs, {
162
212
  stdio: ["pipe", "ignore", "pipe"],
163
213
  windowsHide: true,
164
214
  });
165
- let stderrTail = "";
166
- let stderrHead = "";
167
215
  const id = `rec-${stamp()}-${rand(6)}`;
168
- const watch = new StderrWatch(() => ({ sessionId: id }));
169
- child.stderr?.on("data", (d) => {
170
- const text = d.toString();
171
- stderrTail = (stderrTail + text).slice(-2000);
172
- if (stderrHead.length < 8000)
173
- stderrHead += text;
174
- watch.feed(text);
175
- });
176
- const settled = await new Promise((resolve) => {
177
- const timer = setTimeout(() => resolve("running"), backend === "wgc" ? 15_000 : 1200);
178
- if (backend === "wgc") {
179
- child.stderr?.on("data", () => {
180
- if (parseCaptureStart(stderrHead) !== null) {
181
- clearTimeout(timer);
182
- resolve("running");
183
- }
184
- });
185
- }
186
- child.on("error", (err) => {
187
- clearTimeout(timer);
188
- stderrTail += `\n${err.message}`;
189
- resolve("exited");
190
- });
191
- child.on("exit", () => {
192
- clearTimeout(timer);
193
- resolve("exited");
194
- });
195
- });
216
+ const watch = watchStderr(child, id);
217
+ const settled = await settleCapture(child, watch, backend);
196
218
  if (settled === "exited") {
197
219
  if (logger)
198
220
  await stopEventLogger(logger);
@@ -200,11 +222,13 @@ export function register(server) {
200
222
  rmSync(evPaths.raw, { force: true });
201
223
  if (replay)
202
224
  discardReplay(replay);
203
- const tail = stderrTail.trim().split("\n").slice(-6).join("\n");
204
- throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tail}`);
225
+ if (webcamRaw)
226
+ rmSync(partsDir(output), { recursive: true, force: true });
227
+ throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tailLines(watch)}`);
205
228
  }
229
+ const startMs = captureStartMs(watch, backend, spawnedAt);
206
230
  if (backend === "wgc" && frame && window?.client) {
207
- const m = /wgc: (\d+)x(\d+)/.exec(stderrHead);
231
+ const m = /wgc: (\d+)x(\d+)/.exec(watch.head());
208
232
  frame = { x: window.client.x, y: window.client.y, w: m ? Number(m[1]) : frame.w, h: m ? Number(m[2]) : frame.h };
209
233
  }
210
234
  const record = {
@@ -217,7 +241,7 @@ export function register(server) {
217
241
  ...serverIdentity(),
218
242
  status: "recording",
219
243
  startedAt: new Date().toISOString(),
220
- videoStartMs: parseCaptureStart(stderrHead) ?? spawnedAt,
244
+ videoStartMs: startMs,
221
245
  ...(maxDurationSec > 0 ? { maxDurationSec } : {}),
222
246
  ...(window ? { matchedWindow: window.matchedTitle } : {}),
223
247
  ...(evPaths && !replay ? { events: { path: evPaths.jsonl, keys: keyMode } } : {}),
@@ -226,12 +250,37 @@ export function register(server) {
226
250
  replay: {
227
251
  ...replay,
228
252
  ...(evPaths && frame
229
- ? { events: { raw: evPaths.raw, keys: keyMode, startMs: parseCaptureStart(stderrHead) ?? spawnedAt, frame } }
253
+ ? { events: { raw: evPaths.raw, keys: keyMode, startMs, frame } }
230
254
  : {}),
231
255
  },
232
256
  }
233
257
  : {}),
234
258
  backend,
259
+ ...(pick.encoder !== "x264" ? { encoder: pick.encoder } : {}),
260
+ ...(backend !== "wgc" && !replay
261
+ ? {
262
+ capture: { target, opts: captureOpts, ...(webcam ? { webcam } : {}) },
263
+ segments: {
264
+ parts: [],
265
+ current: {
266
+ path: output,
267
+ startMs,
268
+ ...(webcamRaw ? { webcamPath: webcamRaw, ...webcamStart(watch, !!audio) } : {}),
269
+ },
270
+ },
271
+ }
272
+ : {}),
273
+ ...(webcamDevice
274
+ ? {
275
+ webcam: {
276
+ device: webcamDevice,
277
+ path: webcamOutputPath(output),
278
+ corner: args.webcam?.corner ?? "bottom_right",
279
+ size: args.webcam?.size ?? DEFAULT_WEBCAM_SIZE,
280
+ shape: args.webcam?.shape ?? "rect",
281
+ },
282
+ }
283
+ : {}),
235
284
  processImage: backend === "wgc" ? basename(process.execPath).toLowerCase() : "ffmpeg.exe",
236
285
  };
237
286
  const store = getStore();
@@ -249,6 +298,8 @@ export function register(server) {
249
298
  rmSync(evPaths.raw, { force: true });
250
299
  if (replay)
251
300
  discardReplay(replay);
301
+ if (webcamRaw)
302
+ rmSync(partsDir(output), { recursive: true, force: true });
252
303
  throw new ScreencastError(`Recording stopped: the session registry could not be written (${err.message}).`);
253
304
  }
254
305
  if (logger && replay) {
@@ -256,12 +307,11 @@ export function register(server) {
256
307
  trackFinalizer(id, exited.then(() => stopEventLogger(logger)));
257
308
  }
258
309
  else if (logger && evPaths && frame) {
259
- const exited = new Promise((resolve) => child.once("exit", () => resolve()));
260
- trackFinalizer(id, exited.then(async () => {
310
+ trackFinalizer(id, sessionEnded(id).then(async () => {
261
311
  await stopEventLogger(logger);
262
- const startMs = parseCaptureStart(stderrHead) ?? spawnedAt;
263
312
  try {
264
- const events = writeEventsFile(evPaths, { startMs, frame, endSec: (Date.now() - startMs) / 1000 });
313
+ const clock = eventClock(store.get(id)?.segments, startMs, Date.now());
314
+ const events = writeEventsFile(evPaths, { ...clock, frame });
265
315
  store.tryUpdate(id, {
266
316
  events: { path: evPaths.jsonl, keys: keyMode, count: events.length, summary: summarizeEvents(events) },
267
317
  });
@@ -275,23 +325,7 @@ export function register(server) {
275
325
  process.stderr.write(`Event log for ${id} failed: ${err instanceof Error ? err.message : String(err)}\n`);
276
326
  }));
277
327
  }
278
- child.on("exit", (code) => {
279
- store.detachChild(id);
280
- const cur = store.get(id);
281
- if (!cur || cur.status !== "recording" || store.isStopping(id))
282
- return;
283
- const verdict = classifyUnrequestedExit({ code, backend, maxDurationSec, elapsedMs: Date.now() - spawnedAt });
284
- logMessage(verdict.status === "failed" ? "error" : "notice", verdict.status === "failed"
285
- ? `Recording ${id} failed: the recorder exited with code ${code}.`
286
- : `Recording ${id} ended on its own (${verdict.endReason}).`, { sessionId: id, ...verdict });
287
- store.tryUpdate(id, {
288
- ...verdict,
289
- stoppedAt: new Date().toISOString(),
290
- ...(verdict.status === "failed"
291
- ? { error: `${backend === "wgc" ? "The window recorder" : "ffmpeg"} exited with code ${code}:\n${stderrTail.trim().split("\n").slice(-6).join("\n")}` }
292
- : {}),
293
- });
294
- });
328
+ attachExitHandler(store, id, child, { backend, maxDurationSec, spawnedAt, watch });
295
329
  return okResponse({
296
330
  sessionId: id,
297
331
  status: "recording",
@@ -302,6 +336,10 @@ export function register(server) {
302
336
  quality,
303
337
  audioDevice: audio?.device ?? null,
304
338
  maxDurationSec: maxDurationSec > 0 ? maxDurationSec : null,
339
+ encoder: pick.encoder,
340
+ ...(pick.note ? { encoderNote: pick.note } : {}),
341
+ ...(dda ? { gpuFrames: pick.gpuFrames } : {}),
342
+ ...(webcamDevice ? { webcam: { device: webcamDevice, path: webcamOutputPath(output) } } : {}),
305
343
  ...(window ? windowMatchReport(window) : {}),
306
344
  ...(evPaths && !replay ? { eventsPath: evPaths.jsonl, keys: keyMode } : {}),
307
345
  ...(replay
@@ -310,7 +348,8 @@ export function register(server) {
310
348
  note: (replay
311
349
  ? `Replay buffer running: save_replay keeps the last seconds (up to ${replay.bufferSec}s) without stopping it; ` +
312
350
  "stop_recording discards the buffer unless save: true (then it writes outputPath)."
313
- : "Call stop_recording with this sessionId to finalize the file.") +
351
+ : "Call stop_recording with this sessionId to finalize the file" +
352
+ (backend === "wgc" ? "." : " (pause_recording/resume_recording leave stretches out).")) +
314
353
  (maxDurationSec > 0
315
354
  ? ` It stops on its own after ${maxDurationSec}s (maxDurationSec).`
316
355
  : ""),
@@ -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
+ }
@@ -2,10 +2,11 @@ import { z } from "zod";
2
2
  import { existsSync } from "node:fs";
3
3
  import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
4
  import { STOPS_SESSION, looseOutput } from "../utils/toolSpec.js";
5
- import { requireFfmpeg } from "../utils/ffmpeg.js";
5
+ import { probeMedia, requireFfmpeg } from "../utils/ffmpeg.js";
6
6
  import { probeDuration, stopSession } from "../utils/lifecycle.js";
7
7
  import { getStore } from "../context.js";
8
8
  import { finishReplay } from "../utils/replay.js";
9
+ import { webcamPlacement } from "../utils/pause.js";
9
10
  function replayReport(r) {
10
11
  return {
11
12
  saved: r.saved,
@@ -14,6 +15,37 @@ function replayReport(r) {
14
15
  ...(r.error ? { error: r.error, note: "The buffer was kept; call stop_recording with save: true again, or save_replay." } : {}),
15
16
  };
16
17
  }
18
+ async function webcamReport(cam, output) {
19
+ if (cam.error || !existsSync(cam.path))
20
+ return { error: cam.error ?? `No webcam file was written (${cam.path}).` };
21
+ const size = async (p) => {
22
+ try {
23
+ const info = await probeMedia(p);
24
+ return info.width && info.height ? { width: info.width, height: info.height } : null;
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ };
30
+ const [screen, camSize] = await Promise.all([size(output), size(cam.path)]);
31
+ const circle = cam.shape === "circle";
32
+ const place = screen && camSize ? webcamPlacement(screen, circle ? { width: 1, height: 1 } : camSize, cam.corner, cam.size) : null;
33
+ return {
34
+ path: cam.path,
35
+ ...(place
36
+ ? {
37
+ overlay: {
38
+ input: output,
39
+ overlay: cam.path,
40
+ x: place.x,
41
+ y: place.y,
42
+ ...(circle ? { height: place.height, shape: "circle" } : { width: place.width }),
43
+ },
44
+ note: "Aligned with the recording: pass `overlay` to the overlay tool (any corner or size works).",
45
+ }
46
+ : {}),
47
+ };
48
+ }
17
49
  const inputSchema = {
18
50
  sessionId: z.string().min(1).describe("Session id returned by start_recording."),
19
51
  save: z
@@ -40,7 +72,7 @@ export function register(server) {
40
72
  if (!record) {
41
73
  throw new ScreencastError(`No session with id "${args.sessionId}".`);
42
74
  }
43
- if (record.status !== "recording") {
75
+ if (record.status !== "recording" && record.status !== "paused") {
44
76
  const replay = record.replay && existsSync(record.replay.dir)
45
77
  ? await finishReplay(record.replay, {
46
78
  save: args.save ?? false,
@@ -64,7 +96,7 @@ export function register(server) {
64
96
  });
65
97
  }
66
98
  const { ffprobe } = requireFfmpeg();
67
- const { record: updated, graceful, durationSec, replay } = await stopSession(store, record, {
99
+ const { record: updated, graceful, durationSec, replay, segments } = await stopSession(store, record, {
68
100
  reason: "stopped",
69
101
  probe: (path) => probeDuration(ffprobe, path),
70
102
  saveReplay: args.save,
@@ -76,6 +108,9 @@ export function register(server) {
76
108
  durationSec: durationSec ?? null,
77
109
  finalizedGracefully: graceful,
78
110
  ...(replay ? { replay: replayReport(replay) } : {}),
111
+ ...(segments && segments.count > 1 ? { segmentsJoined: segments.count } : {}),
112
+ ...(segments?.error ? { segmentsError: segments.error } : {}),
113
+ ...(updated?.webcam ? { webcam: await webcamReport(updated.webcam, record.outputPath) } : {}),
79
114
  ...(updated?.events
80
115
  ? { eventsPath: updated.events.path, events: updated.events.summary ?? {}, ...(updated.events.error ? { eventsError: updated.events.error } : {}) }
81
116
  : {}),
@@ -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"))
@@ -59,13 +59,18 @@ export function audioCodecFor(output) {
59
59
  return ["-c:a", "aac", "-b:a", "192k"];
60
60
  }
61
61
  }
62
- export function buildLoudnessApplyArgs(input, output, t, m) {
62
+ export function loudnormFilter(t, m) {
63
+ if (!m)
64
+ return `loudnorm=${filterTarget(t)}`;
63
65
  const measured = `measured_I=${m.input_i}:measured_TP=${m.input_tp}:measured_LRA=${m.input_lra}:` +
64
66
  `measured_thresh=${m.input_thresh}:offset=${m.target_offset}`;
67
+ return `loudnorm=${filterTarget(t)}:${measured}:linear=true`;
68
+ }
69
+ export function buildLoudnessApplyArgs(input, output, t, m) {
65
70
  return [
66
71
  "-y", "-hide_banner", "-i", input,
67
72
  ...keepVideoArgs(output),
68
- "-af", `loudnorm=${filterTarget(t)}:${measured}:linear=true:print_format=json`,
73
+ "-af", `${loudnormFilter(t, m)}:print_format=json`,
69
74
  "-ar", "48000",
70
75
  ...audioCodecFor(output),
71
76
  output,
@@ -91,14 +96,17 @@ export function noiseFloorSetting(floorDb) {
91
96
  return -50;
92
97
  return Math.max(-80, Math.min(-20, Math.round(floorDb + 5)));
93
98
  }
94
- export function buildDenoiseArgs(input, output, strength = "medium", noiseFloorDb = null) {
99
+ export function denoiseFilter(strength, noiseFloorDb) {
95
100
  const nr = DENOISE_NR[strength];
96
101
  if (nr === undefined)
97
102
  throw new ScreencastError(`Unknown denoise strength "${strength}".`);
103
+ return `afftdn=nr=${nr}:nf=${noiseFloorSetting(noiseFloorDb)}`;
104
+ }
105
+ export function buildDenoiseArgs(input, output, strength = "medium", noiseFloorDb = null) {
98
106
  return [
99
107
  "-y", "-i", input,
100
108
  ...keepVideoArgs(output),
101
- "-af", `afftdn=nr=${nr}:nf=${noiseFloorSetting(noiseFloorDb)}`,
109
+ "-af", denoiseFilter(strength, noiseFloorDb),
102
110
  ...audioCodecFor(output),
103
111
  output,
104
112
  ];