@tmhs/screencast-mcp 0.49.1 → 0.50.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 (134) hide show
  1. package/README.md +13 -8
  2. package/dist/index.js +550 -106
  3. package/dist/wgcRecorder.js +15 -139
  4. package/package.json +8 -4
  5. package/assets/.gitkeep +0 -0
  6. package/assets/icon.png +0 -0
  7. package/dist/cli.js +0 -516
  8. package/dist/context.js +0 -50
  9. package/dist/prompts.js +0 -95
  10. package/dist/resources.js +0 -93
  11. package/dist/server.js +0 -174
  12. package/dist/setup.js +0 -438
  13. package/dist/tools/addMarker.js +0 -93
  14. package/dist/tools/assembleHighlights.js +0 -69
  15. package/dist/tools/backdrop.js +0 -79
  16. package/dist/tools/bugReport.js +0 -243
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -62
  19. package/dist/tools/chapters.js +0 -156
  20. package/dist/tools/clip.js +0 -52
  21. package/dist/tools/compress.js +0 -51
  22. package/dist/tools/concat.js +0 -67
  23. package/dist/tools/contactSheet.js +0 -113
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -67
  27. package/dist/tools/cutByTranscript.js +0 -86
  28. package/dist/tools/cutIdle.js +0 -84
  29. package/dist/tools/deleteRecording.js +0 -119
  30. package/dist/tools/denoise.js +0 -60
  31. package/dist/tools/doctor.js +0 -146
  32. package/dist/tools/exportGif.js +0 -57
  33. package/dist/tools/exportPreset.js +0 -48
  34. package/dist/tools/extractAudio.js +0 -65
  35. package/dist/tools/findText.js +0 -194
  36. package/dist/tools/getMediaInfo.js +0 -36
  37. package/dist/tools/getSession.js +0 -40
  38. package/dist/tools/indexRecording.js +0 -195
  39. package/dist/tools/keystrokeOverlay.js +0 -90
  40. package/dist/tools/listAudioDevices.js +0 -35
  41. package/dist/tools/listSessions.js +0 -28
  42. package/dist/tools/listTargets.js +0 -76
  43. package/dist/tools/listVideoDevices.js +0 -26
  44. package/dist/tools/musicBed.js +0 -55
  45. package/dist/tools/narrate.js +0 -86
  46. package/dist/tools/normalizeAudio.js +0 -59
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -397
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -62
  52. package/dist/tools/reframe.js +0 -46
  53. package/dist/tools/resumeRecording.js +0 -46
  54. package/dist/tools/reviewRecording.js +0 -163
  55. package/dist/tools/sampleFrames.js +0 -200
  56. package/dist/tools/saveReplay.js +0 -90
  57. package/dist/tools/scale.js +0 -44
  58. package/dist/tools/screenDiff.js +0 -86
  59. package/dist/tools/screenshot.js +0 -76
  60. package/dist/tools/searchRecording.js +0 -79
  61. package/dist/tools/speed.js +0 -46
  62. package/dist/tools/startRecording.js +0 -398
  63. package/dist/tools/stepGuide.js +0 -249
  64. package/dist/tools/stopRecording.js +0 -132
  65. package/dist/tools/titleCard.js +0 -67
  66. package/dist/tools/transcribe.js +0 -66
  67. package/dist/tools/trim.js +0 -57
  68. package/dist/tools/waitForChange.js +0 -142
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -134
  71. package/dist/utils/anim.js +0 -54
  72. package/dist/utils/animExport.js +0 -56
  73. package/dist/utils/argPaths.js +0 -39
  74. package/dist/utils/audio.js +0 -117
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -162
  77. package/dist/utils/bugReport.js +0 -195
  78. package/dist/utils/callout.js +0 -132
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -104
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -338
  85. package/dist/utils/diff.js +0 -186
  86. package/dist/utils/errors.js +0 -29
  87. package/dist/utils/events.js +0 -403
  88. package/dist/utils/expr.js +0 -11
  89. package/dist/utils/ffmpeg.js +0 -285
  90. package/dist/utils/fontCoverage.js +0 -177
  91. package/dist/utils/fonts.js +0 -154
  92. package/dist/utils/frameQueue.js +0 -50
  93. package/dist/utils/gpu.js +0 -219
  94. package/dist/utils/idle.js +0 -91
  95. package/dist/utils/images.js +0 -38
  96. package/dist/utils/jobs.js +0 -129
  97. package/dist/utils/keystrokes.js +0 -198
  98. package/dist/utils/lifecycle.js +0 -233
  99. package/dist/utils/logging.js +0 -75
  100. package/dist/utils/media.js +0 -584
  101. package/dist/utils/monitors.js +0 -124
  102. package/dist/utils/narrate.js +0 -233
  103. package/dist/utils/ocr.js +0 -222
  104. package/dist/utils/ocrScan.js +0 -93
  105. package/dist/utils/paths.js +0 -155
  106. package/dist/utils/pause.js +0 -190
  107. package/dist/utils/pipeline.js +0 -361
  108. package/dist/utils/player.js +0 -85
  109. package/dist/utils/pool.js +0 -29
  110. package/dist/utils/produce.js +0 -300
  111. package/dist/utils/recipes.js +0 -71
  112. package/dist/utils/recorder.js +0 -173
  113. package/dist/utils/recordingFiles.js +0 -32
  114. package/dist/utils/recordingIndex.js +0 -312
  115. package/dist/utils/replay.js +0 -283
  116. package/dist/utils/resolveTarget.js +0 -25
  117. package/dist/utils/retention.js +0 -48
  118. package/dist/utils/roots.js +0 -43
  119. package/dist/utils/sessions.js +0 -499
  120. package/dist/utils/sheet.js +0 -82
  121. package/dist/utils/stepGuide.js +0 -231
  122. package/dist/utils/steps.js +0 -88
  123. package/dist/utils/still.js +0 -38
  124. package/dist/utils/targetList.js +0 -64
  125. package/dist/utils/targets.js +0 -265
  126. package/dist/utils/timeline.js +0 -85
  127. package/dist/utils/toolSpec.js +0 -31
  128. package/dist/utils/toolsets.js +0 -134
  129. package/dist/utils/transcriptCut.js +0 -149
  130. package/dist/utils/validate.js +0 -23
  131. package/dist/utils/waitLoop.js +0 -50
  132. package/dist/utils/wgc.js +0 -84
  133. package/dist/utils/windows.js +0 -192
  134. package/dist/utils/zoom.js +0 -252
@@ -1,398 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { z } from "zod";
3
- import { errorMessage, errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
- import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
5
- import { requireFfmpeg, wgcAvailable } from "../utils/ffmpeg.js";
6
- import { fileURLToPath } from "node:url";
7
- import { buildCaptureArgs, captureFrame, DEFAULT_FPS, DEFAULT_QUALITY, DEFAULT_MAX_RECORDING_SEC, MAX_RECORDING_CAP_SEC, resolveMaxDuration, captureKeyframeArgs, } from "../utils/targets.js";
8
- import { resolveCaptureTarget } from "../utils/resolveTarget.js";
9
- import { windowMatchReport } from "../utils/windows.js";
10
- import { resolveLoopbackDevice, resolveVideoDevice } from "../utils/audioDevices.js";
11
- import { confirmCapture, describeTarget } from "../utils/consent.js";
12
- import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
13
- import { beginStart, getStore } from "../context.js";
14
- import { killPid, serverIdentity } from "../utils/sessions.js";
15
- import { mkdirSync, rmSync } from "node:fs";
16
- import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, startWithEncoderFallback, } 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";
19
- import { basename, join } from "node:path";
20
- import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, replayEventRotateSec, resetReplaySegments, segmentOutputArgs, } from "../utils/replay.js";
21
- import { DEFAULT_KEY_MODE, eventPaths, parseCaptureStart, prepareEventPaths, startEventLogger, stopEventLogger, summarizeEvents, trackFinalizer, writeEventsFile, } from "../utils/events.js";
22
- const inputSchema = {
23
- target: z
24
- .string()
25
- .describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | " +
26
- "region:<x>,<y>,<w>,<h>. With gdigrab a window's rectangle is resolved once at start (visible, " +
27
- "on top); it does not follow the window."),
28
- exactTitle: z
29
- .boolean()
30
- .optional()
31
- .describe("window: targets match the whole title only, never a substring (default false)."),
32
- fps: z
33
- .number()
34
- .int()
35
- .min(1)
36
- .max(120)
37
- .optional()
38
- .describe(`Frames per second (default ${DEFAULT_FPS}).`),
39
- quality: z
40
- .enum(["draft", "standard", "high"])
41
- .optional()
42
- .describe(`Encoder preset (default ${DEFAULT_QUALITY}).`),
43
- audio: z
44
- .object({
45
- source: z
46
- .enum(["system", "none"])
47
- .describe("system = what the machine plays (needs a loopback device); none = video only."),
48
- device: z
49
- .string()
50
- .optional()
51
- .describe("dshow loopback device (from list_audio_devices); auto-detected if omitted."),
52
- })
53
- .optional()
54
- .describe("Audio (default none). No microphone capture."),
55
- output: z
56
- .string()
57
- .optional()
58
- .describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),
59
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
60
- maxDurationSec: z
61
- .number()
62
- .int()
63
- .min(0)
64
- .max(MAX_RECORDING_CAP_SEC)
65
- .optional()
66
- .describe(`Auto-stop after this many seconds (default ${DEFAULT_MAX_RECORDING_SEC} or ` +
67
- "SCREENCAST_MAX_RECORDING_SEC; max 7 days; 0 = no cap)."),
68
- events: z
69
- .boolean()
70
- .optional()
71
- .describe("Also log clicks, scroll, cursor, and typing (video-timed, video pixels) for read_events " +
72
- "(default false; ~1 s slower start)."),
73
- keys: z
74
- .enum(["masked", "shortcuts"])
75
- .optional()
76
- .describe("With events: masked (default) logs typing only as 0.5 s-grid bursts, never keys; shortcuts " +
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.'),
82
- backend: z
83
- .enum(["gdigrab", "wgc", "ddagrab"])
84
- .optional()
85
- .describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own " +
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."),
100
- replayBufferSec: z
101
- .number()
102
- .int()
103
- .min(MIN_REPLAY_SEC)
104
- .max(MAX_REPLAY_SEC)
105
- .optional()
106
- .describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab or ddagrab, not wgc."),
107
- };
108
- function frameSize(target, monitors) {
109
- try {
110
- const f = captureFrame(target, monitors);
111
- return { width: f.w, height: f.h };
112
- }
113
- catch {
114
- return undefined;
115
- }
116
- }
117
- function webcamStart(watch, audio) {
118
- const ms = parseCaptureStart(watch.head(), audio ? 2 : 1);
119
- return ms !== null ? { webcamStartMs: ms } : {};
120
- }
121
- export function register(server) {
122
- server.registerTool("start_recording", {
123
- title: "Start Recording",
124
- description: "Start a background screen recording. Returns a session id; finalize it with stop_recording. " +
125
- "Never auto-starts.",
126
- inputSchema,
127
- outputSchema: looseOutput({
128
- sessionId: z.string(),
129
- status: z.string(),
130
- backend: z.string(),
131
- outputPath: z.string(),
132
- }),
133
- annotations: WRITES_FILE,
134
- }, async (args, extra) => {
135
- let release = () => { };
136
- try {
137
- release = beginStart();
138
- const { ffmpeg } = requireFfmpeg();
139
- const hideCursor = args.cursor === "events";
140
- if (hideCursor)
141
- args.events = true;
142
- const { target, monitors, window } = await resolveCaptureTarget(args.target, {
143
- exactTitle: args.exactTitle,
144
- backend: args.backend,
145
- });
146
- const backend = args.backend ?? "gdigrab";
147
- if (backend === "wgc") {
148
- if (!window?.hwnd)
149
- throw new ScreencastError('backend "wgc" records one window: use a window: target.');
150
- if (args.audio?.source === "system")
151
- throw new ScreencastError('Audio is not supported with backend "wgc" yet; use gdigrab.');
152
- if (!wgcAvailable()) {
153
- throw new ScreencastError('backend "wgc" needs FFmpeg 8 or newer (the gfxcapture filter). Use gdigrab, or update ffmpeg.');
154
- }
155
- }
156
- if (args.replayBufferSec !== undefined && backend === "wgc") {
157
- throw new ScreencastError('replayBufferSec is not supported with backend "wgc" yet; use gdigrab or ddagrab.');
158
- }
159
- const replay = args.replayBufferSec !== undefined ? planReplayBuffer(args.replayBufferSec) : null;
160
- const fps = args.fps ?? DEFAULT_FPS;
161
- const quality = args.quality ?? DEFAULT_QUALITY;
162
- const maxDurationSec = resolveMaxDuration(args.maxDurationSec);
163
- const output = resolveOutput(args.output, subdir("recordings"), `rec-${stamp()}-${rand()}.mp4`, args.overwrite);
164
- const audio = args.audio?.source === "system"
165
- ? { device: await resolveLoopbackDevice(args.audio.device) }
166
- : undefined;
167
- if (args.webcam && (backend === "wgc" || replay)) {
168
- throw new ScreencastError("webcam works with backend gdigrab or ddagrab, without replayBufferSec.");
169
- }
170
- const webcamDevice = args.webcam ? await resolveVideoDevice(args.webcam.device) : undefined;
171
- const dda = backend === "ddagrab" ? planDdaSource(captureFrame(target, monitors), await getDxgiOutputs()) : null;
172
- await confirmCapture(server, (replay ? `Keep a rolling ${replay.bufferSec} s replay buffer of ` : "Record ") +
173
- `${describeTarget(args.target, window)} ` +
174
- (maxDurationSec > 0 ? `for up to ${maxDurationSec} s` : "with no time limit") +
175
- (audio ? `, with system audio (${audio.device})` : ", without audio") +
176
- (webcamDevice ? `, with the webcam (${webcamDevice})` : "") +
177
- (args.events ? ", logging mouse clicks and typing" : "") +
178
- (replay ? ", kept only until save_replay or stop_recording { save: true } writes it out?" : `, saved to ${output}?`), extra.signal);
179
- let pick = await resolveEncoder(args.encoder ?? (backend === "ddagrab" ? "auto" : "x264"), backend === "ddagrab" ? "ddagrab" : "gdigrab", ffmpeg, undefined, backend === "wgc" ? undefined : frameSize(target, monitors));
180
- const ddaUsable = async (p) => !dda || p.gpuFrames || (await ddagrabWorks(ffmpeg));
181
- if (!(await ddaUsable(pick))) {
182
- throw new ScreencastError("Desktop Duplication (ddagrab) does not capture on this machine (a remote session, or no D3D11 GPU).", 'Use backend "gdigrab".');
183
- }
184
- const webcamRaw = webcamDevice ? webcamPartPath(output, 0) : undefined;
185
- if (webcamRaw)
186
- mkdirSync(partsDir(output), { recursive: true });
187
- const plan = (p) => {
188
- const hw = p.encoder !== "x264";
189
- const captureOpts = {
190
- fps,
191
- quality,
192
- monitors,
193
- audio,
194
- drawMouse: !hideCursor,
195
- ...(dda ? { videoInput: buildDdaInputArgs(dda, fps, { download: !p.gpuFrames, drawMouse: !hideCursor }) } : {}),
196
- ...(hw ? { videoCodec: encoderArgs(p.encoder, quality, { gpuFrames: p.gpuFrames }) } : {}),
197
- };
198
- const webcam = webcamDevice
199
- ? { device: webcamDevice, ...(hw ? { codec: encoderArgs(p.encoder, quality) } : {}) }
200
- : undefined;
201
- const captureArgs = buildCaptureArgs(target, {
202
- ...captureOpts,
203
- output,
204
- maxDurationSec,
205
- ...(webcam && webcamRaw ? { webcam: { ...webcam, output: webcamRaw } } : {}),
206
- });
207
- return { captureOpts, webcam, ffArgs: replay ? segmentOutputArgs(captureArgs, replay) : captureArgs };
208
- };
209
- if (replay)
210
- prepareReplayDir(replay);
211
- const keyMode = args.keys ?? DEFAULT_KEY_MODE;
212
- const evPaths = args.events ? (replay ? { raw: join(replay.dir, "events.raw"), jsonl: "" } : eventPaths(output)) : null;
213
- if (evPaths && !replay)
214
- prepareEventPaths(evPaths, args.overwrite);
215
- let frame = args.events
216
- ? captureFrame(target, monitors)
217
- : null;
218
- const logger = evPaths
219
- ? await startEventLogger(evPaths.raw, keyMode, replay ? { rotateSec: replayEventRotateSec(replay.bufferSec) } : {})
220
- : null;
221
- const id = `rec-${stamp()}-${rand(6)}`;
222
- const launch = async (p) => {
223
- const settings = plan(p);
224
- const spawnedAt = Date.now();
225
- const child = backend === "wgc"
226
- ? spawn(process.execPath, [
227
- fileURLToPath(new URL("../wgcRecorder.js", import.meta.url)),
228
- JSON.stringify({ ffmpeg, hwnd: window.hwnd, fps, encode: [...encoderArgs(p.encoder, quality), ...captureKeyframeArgs(fps)], output, maxDurationSec, cursor: !hideCursor }),
229
- ], { stdio: ["pipe", "ignore", "pipe"], windowsHide: true })
230
- : spawn(ffmpeg, settings.ffArgs, {
231
- stdio: ["pipe", "ignore", "pipe"],
232
- windowsHide: true,
233
- });
234
- const watch = watchStderr(child, id);
235
- const settled = await settleCapture(child, watch, backend);
236
- return { ...settings, child, watch, spawnedAt, settled };
237
- };
238
- const started = await startWithEncoderFallback(pick, launch, {
239
- why: (r) => tailLines(r.watch, 3),
240
- canFallback: () => ddaUsable({ encoder: "x264", gpuFrames: false }),
241
- beforeRetry: () => {
242
- if (replay)
243
- resetReplaySegments(replay);
244
- },
245
- });
246
- const { run, failure: retried } = started;
247
- pick = started.pick;
248
- const { child, watch, spawnedAt, captureOpts, webcam } = run;
249
- if (run.settled === "exited") {
250
- if (logger)
251
- await stopEventLogger(logger);
252
- if (evPaths)
253
- rmSync(evPaths.raw, { force: true });
254
- if (replay)
255
- discardReplay(replay);
256
- if (webcamRaw)
257
- rmSync(partsDir(output), { recursive: true, force: true });
258
- throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tailLines(watch)}` +
259
- (retried ? `\n(Retried with libx264 after ${retried})` : ""));
260
- }
261
- const startMs = captureStartMs(watch, backend, spawnedAt);
262
- if (backend === "wgc" && frame && window?.client) {
263
- const m = /wgc: (\d+)x(\d+)/.exec(watch.head());
264
- frame = { x: window.client.x, y: window.client.y, w: m ? Number(m[1]) : frame.w, h: m ? Number(m[2]) : frame.h };
265
- }
266
- const record = {
267
- id,
268
- target: args.target,
269
- outputPath: output,
270
- fps,
271
- quality,
272
- pid: child.pid ?? null,
273
- pidSpawnedAt: spawnedAt,
274
- ...serverIdentity(),
275
- status: "recording",
276
- startedAt: new Date().toISOString(),
277
- videoStartMs: startMs,
278
- ...(maxDurationSec > 0 ? { maxDurationSec } : {}),
279
- ...(window ? { matchedWindow: window.matchedTitle } : {}),
280
- ...(evPaths && !replay ? { events: { path: evPaths.jsonl, keys: keyMode } } : {}),
281
- ...(replay
282
- ? {
283
- replay: {
284
- ...replay,
285
- ...(evPaths && frame
286
- ? { events: { raw: evPaths.raw, keys: keyMode, startMs, frame } }
287
- : {}),
288
- },
289
- }
290
- : {}),
291
- backend,
292
- ...(pick.encoder !== "x264" ? { encoder: pick.encoder } : {}),
293
- ...(backend !== "wgc" && !replay
294
- ? {
295
- capture: { target, opts: captureOpts, ...(webcam ? { webcam } : {}) },
296
- segments: {
297
- parts: [],
298
- current: {
299
- path: output,
300
- startMs,
301
- ...(webcamRaw ? { webcamPath: webcamRaw, ...webcamStart(watch, !!audio) } : {}),
302
- },
303
- },
304
- }
305
- : {}),
306
- ...(webcamDevice
307
- ? {
308
- webcam: {
309
- device: webcamDevice,
310
- path: webcamOutputPath(output),
311
- corner: args.webcam?.corner ?? "bottom_right",
312
- size: args.webcam?.size ?? DEFAULT_WEBCAM_SIZE,
313
- shape: args.webcam?.shape ?? "rect",
314
- },
315
- }
316
- : {}),
317
- processImage: backend === "wgc" ? basename(process.execPath).toLowerCase() : "ffmpeg.exe",
318
- };
319
- const store = getStore();
320
- store.attachChild(id, child);
321
- try {
322
- store.create(record);
323
- }
324
- catch (err) {
325
- store.detachChild(id);
326
- if (child.pid !== undefined)
327
- killPid(child.pid);
328
- if (logger)
329
- await stopEventLogger(logger);
330
- if (evPaths)
331
- rmSync(evPaths.raw, { force: true });
332
- if (replay)
333
- discardReplay(replay);
334
- if (webcamRaw)
335
- rmSync(partsDir(output), { recursive: true, force: true });
336
- throw new ScreencastError(`Recording stopped: the session registry could not be written (${errorMessage(err)}).`);
337
- }
338
- if (logger && replay) {
339
- const exited = new Promise((resolve) => child.once("exit", () => resolve()));
340
- trackFinalizer(id, exited.then(() => stopEventLogger(logger)));
341
- }
342
- else if (logger && evPaths && frame) {
343
- trackFinalizer(id, sessionEnded(id).then(async () => {
344
- await stopEventLogger(logger);
345
- try {
346
- const clock = eventClock(store.get(id)?.segments, startMs, Date.now());
347
- const events = writeEventsFile(evPaths, { ...clock, frame });
348
- store.tryUpdate(id, {
349
- events: { path: evPaths.jsonl, keys: keyMode, count: events.length, summary: summarizeEvents(events) },
350
- });
351
- }
352
- catch (err) {
353
- store.tryUpdate(id, {
354
- events: { path: evPaths.jsonl, keys: keyMode, error: errorMessage(err) },
355
- });
356
- }
357
- }).catch((err) => {
358
- process.stderr.write(`Event log for ${id} failed: ${errorMessage(err)}\n`);
359
- }));
360
- }
361
- attachExitHandler(store, id, child, { backend, maxDurationSec, spawnedAt, watch });
362
- return okResponse({
363
- sessionId: id,
364
- status: "recording",
365
- backend,
366
- outputPath: output,
367
- pid: record.pid,
368
- fps,
369
- quality,
370
- audioDevice: audio?.device ?? null,
371
- maxDurationSec: maxDurationSec > 0 ? maxDurationSec : null,
372
- encoder: pick.encoder,
373
- ...(pick.note ? { encoderNote: pick.note } : {}),
374
- ...(dda ? { gpuFrames: pick.gpuFrames } : {}),
375
- ...(webcamDevice ? { webcam: { device: webcamDevice, path: webcamOutputPath(output) } } : {}),
376
- ...(window ? windowMatchReport(window) : {}),
377
- ...(evPaths && !replay ? { eventsPath: evPaths.jsonl, keys: keyMode } : {}),
378
- ...(replay
379
- ? { replay: { bufferSec: replay.bufferSec, segmentSec: replay.segmentSec, dir: replay.dir, events: !!evPaths } }
380
- : {}),
381
- note: (replay
382
- ? `Replay buffer running: save_replay keeps the last seconds (up to ${replay.bufferSec}s) without stopping it; ` +
383
- "stop_recording discards the buffer unless save: true (then it writes outputPath)."
384
- : "Call stop_recording with this sessionId to finalize the file" +
385
- (backend === "wgc" ? "." : " (pause_recording/resume_recording leave stretches out).")) +
386
- (maxDurationSec > 0
387
- ? ` It stops on its own after ${maxDurationSec}s (maxDurationSec).`
388
- : ""),
389
- });
390
- }
391
- catch (error) {
392
- return errorResponse(error);
393
- }
394
- finally {
395
- release();
396
- }
397
- });
398
- }
@@ -1,249 +0,0 @@
1
- import { z } from "zod";
2
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, 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, resolveSource } from "../utils/bugReport.js";
15
- import { resolveOutputDir, subdir, stamp, rand } from "../utils/paths.js";
16
- import { GUIDE_FILES, HTML_IMAGE_LADDER, HTML_MAX_BYTES, MAX_GUIDE_STEPS, assignSections, base64Bytes, buildHtmlImageArgs, buildGuideHtml, buildGuideMarkdown, buildStepFrameArgs, buildStepShotArgs, caption, guideSteps, htmlImageName, labelAt, nextHtmlRung, shotFilter, } from "../utils/stepGuide.js";
17
- import { mapPool } from "../utils/pool.js";
18
- const OCR_BATCH = 10;
19
- const HTML_SAMPLE = 5;
20
- const inputSchema = {
21
- input: z.string().min(1).optional().describe("Recording path (uses its .events.jsonl)."),
22
- sessionId: z.string().min(1).optional().describe("Or a stopped session's id."),
23
- title: z.string().max(200).optional().describe("Guide title."),
24
- format: z.enum(["md", "html", "both"]).optional().describe("md + images/, self-contained html, or both (default)."),
25
- ocr: z.boolean().optional().describe("OCR shots for captions and secret boxes (default true; needs Windows OCR)."),
26
- outputDir: z.string().optional().describe("Guide folder (default: new in SCREENCAST_HOME/edits)."),
27
- overwrite: z.boolean().optional().describe("Replace a guide already in outputDir."),
28
- };
29
- export function register(server) {
30
- server.registerTool("step_guide", {
31
- title: "Step-by-Step Guide",
32
- description: "Turn a recording's event log into a numbered how-to: a ringed screenshot and caption per step, marker " +
33
- "headings; Markdown and/or one HTML file. Never includes typed text.",
34
- inputSchema,
35
- outputSchema: looseOutput({ outputDir: z.string() }),
36
- annotations: WRITES_FILE,
37
- }, async (args, extra) => {
38
- let createdDir = null;
39
- const written = [];
40
- try {
41
- if ((args.input === undefined) === (args.sessionId === undefined)) {
42
- throw new ScreencastError("Provide exactly one of: input (a recording path) or sessionId.");
43
- }
44
- requireFfmpeg();
45
- const source = await resolveSource(args);
46
- if (!source.eventsPath) {
47
- 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.");
48
- }
49
- const info = await probeMedia(source.path);
50
- if (!info.width || !info.height)
51
- throw new ScreencastError(`Could not read the size of ${source.path}.`);
52
- const duration = info.videoDurationSec ?? info.durationSec;
53
- if (duration === null)
54
- throw new ScreencastError(`Could not read the duration of ${source.path}.`);
55
- const fps = info.fps ?? 30;
56
- const format = args.format ?? "both";
57
- const wantMd = format !== "html";
58
- const wantHtml = format !== "md";
59
- const useOcr = args.ocr !== false;
60
- if (useOcr) {
61
- const status = await ocrStatus();
62
- if (!status.available) {
63
- 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.");
64
- }
65
- }
66
- const dir = resolveOutputDir(args.outputDir, subdir("edits")) ?? join(subdir("edits"), `step-guide-${stamp()}-${rand()}`);
67
- const paths = { markdown: join(dir, GUIDE_FILES.markdown), html: join(dir, GUIDE_FILES.html), images: join(dir, GUIDE_FILES.images) };
68
- const clash = [paths.markdown, paths.html].filter((p) => existsSync(p));
69
- if (clash.length > 0 && !args.overwrite) {
70
- throw new ScreencastError(`The folder already holds a guide: ${clash.join(", ")}. Pass overwrite: true to replace it, or choose another outputDir.`);
71
- }
72
- const all = inputSteps(parseEventsJsonl(readFileSync(source.eventsPath, "utf8")));
73
- const kept = all.slice(0, MAX_GUIDE_STEPS);
74
- const plain = guideSteps(kept, { durationSec: duration, fps });
75
- const shots = plain.map((s, i) => ({ i, s })).filter(({ s }) => s.shotT !== undefined);
76
- const warnings = [];
77
- if (!existsSync(dir)) {
78
- mkdirSync(dir, { recursive: true });
79
- createdDir = dir;
80
- }
81
- const work = mkdtempSync(join(tmpdir(), "screencast-guide-"));
82
- try {
83
- const progress = progressReporter(extra);
84
- const total = shots.length * (useOcr ? 3 : 2) || 1;
85
- let done = 0;
86
- const tick = () => progress?.(++done / total);
87
- const frames = await mapPool(shots, async ({ s }) => {
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
- tick();
91
- return out;
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, { sameSize: true });
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
- const frameSize = { width: info.width, height: info.height };
124
- const rendered = await mapPool(shots, async ({ i }, k) => {
125
- const step = steps[i];
126
- const file = GUIDE_FILES.image(step.n);
127
- const ring = step.x !== undefined && step.y !== undefined ? { x: step.x, y: step.y } : undefined;
128
- const filter = shotFilter(frameSize, { click: ring, boxes: boxes[k] });
129
- const out = join(imageDir, file);
130
- await runFfmpeg(buildStepShotArgs(frames[k], filter, out), 60_000, { signal: extra.signal });
131
- tick();
132
- return { step, file, out };
133
- });
134
- for (const [k, { step, file, out }] of rendered.entries()) {
135
- if (wantMd)
136
- written.push(out);
137
- step.image = file;
138
- redactions += boxes[k].length;
139
- }
140
- const stepsNote = all.length === 0 ? "The event log has no clicks, shortcuts, typing, or scrolls." : undefined;
141
- const data = {
142
- title: args.title?.trim() || "Step-by-step guide",
143
- createdAt: new Date().toISOString(),
144
- recording: { durationSec: Math.round(duration * 1000) / 1000, width: info.width, height: info.height },
145
- steps,
146
- ...(all.length > MAX_GUIDE_STEPS ? { stepsOmitted: all.length - MAX_GUIDE_STEPS } : {}),
147
- ...(stepsNote ? { stepsNote } : {}),
148
- ocr: useOcr ? "read" : "off",
149
- redactions,
150
- };
151
- if (wantMd) {
152
- writeFileSync(paths.markdown, buildGuideMarkdown(data));
153
- written.push(paths.markdown);
154
- }
155
- if (wantHtml) {
156
- const htmlDir = join(work, "html");
157
- mkdirSync(htmlDir, { recursive: true });
158
- const files = steps.flatMap((s) => (s.image ? [s.image] : []));
159
- const src = (file) => `data:image/jpeg;base64,${readFileSync(join(htmlDir, htmlImageName(file))).toString("base64")}`;
160
- const encode = async (file, rung) => {
161
- const out = join(htmlDir, htmlImageName(file));
162
- await runFfmpeg(buildHtmlImageArgs(join(imageDir, file), rung, out), 60_000, { signal: extra.signal });
163
- return base64Bytes(statSync(out).size);
164
- };
165
- const sample = files.length > HTML_SAMPLE ? files.filter((_, k) => k % Math.ceil(files.length / HTML_SAMPLE) === 0) : [];
166
- let start = 0;
167
- for (; sample.length > 0 && start < HTML_IMAGE_LADDER.length - 1; start++) {
168
- let bytes = 0;
169
- for (const f of sample)
170
- bytes += await encode(f, HTML_IMAGE_LADDER[start]);
171
- if ((bytes / sample.length) * files.length <= HTML_MAX_BYTES * 0.9)
172
- break;
173
- }
174
- let page = "";
175
- for (let r = start; r !== null;) {
176
- const rung = HTML_IMAGE_LADDER[r];
177
- let images = 0;
178
- for (const file of files)
179
- images += await encode(file, rung);
180
- page = images <= HTML_MAX_BYTES ? buildGuideHtml(data, src) : "";
181
- const bytes = page ? Buffer.byteLength(page) : images;
182
- if (bytes <= HTML_MAX_BYTES)
183
- break;
184
- const next = nextHtmlRung(r, bytes);
185
- if (next === null) {
186
- page ||= buildGuideHtml(data, src);
187
- warnings.push(`guide.html is ${(Buffer.byteLength(page) / 1e6).toFixed(1)} MB, over the ${HTML_MAX_BYTES / 1e6} MB budget even with ${rung.width} px JPEGs; ` +
188
- "use format: md for a guide this long.");
189
- }
190
- r = next;
191
- }
192
- writeFileSync(paths.html, page);
193
- written.push(paths.html);
194
- }
195
- if (args.overwrite) {
196
- if (!wantHtml)
197
- rmSync(paths.html, { force: true });
198
- if (!wantMd) {
199
- rmSync(paths.markdown, { force: true });
200
- if (existsSync(paths.images)) {
201
- for (const f of readdirSync(paths.images))
202
- if (/^step-\d+\.png$/.test(f))
203
- rmSync(join(paths.images, f), { force: true });
204
- try {
205
- rmdirSync(paths.images);
206
- }
207
- catch {
208
- }
209
- }
210
- }
211
- }
212
- if (data.stepsOmitted)
213
- warnings.push(`Only the first ${MAX_GUIDE_STEPS} steps were written; ${data.stepsOmitted} more were left out.`);
214
- if (stepsNote)
215
- warnings.push(stepsNote);
216
- return okResponse({
217
- outputDir: dir,
218
- ...(wantMd ? { markdownPath: paths.markdown, imagesDir: paths.images } : {}),
219
- ...(wantHtml ? { htmlPath: paths.html } : {}),
220
- steps: steps.map((s) => ({
221
- ...(s.n > 0 ? { n: s.n } : {}),
222
- t: s.t,
223
- action: s.action,
224
- caption: caption(s),
225
- ...(s.section ? { section: s.section } : {}),
226
- ...(s.image ? { image: s.image } : {}),
227
- })),
228
- ocr: data.ocr,
229
- redactions,
230
- ...(warnings.length > 0 ? { warnings } : {}),
231
- note: useOcr
232
- ? "Captions are OCR-based templates: rewrite them in guide.md as needed. The secret scan is best-effort: look at the screenshots before sharing."
233
- : "Not scanned for secrets: look at the screenshots before sharing.",
234
- });
235
- }
236
- finally {
237
- rmSync(work, { recursive: true, force: true });
238
- }
239
- }
240
- catch (error) {
241
- if (createdDir)
242
- rmSync(createdDir, { recursive: true, force: true });
243
- else
244
- for (const p of written)
245
- rmSync(p, { force: true });
246
- return errorResponse(error);
247
- }
248
- });
249
- }