@tmhs/screencast-mcp 0.46.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.
@@ -0,0 +1,163 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdirSync, rmSync } from "node:fs";
3
+ import { ScreencastError } from "./errors.js";
4
+ import { logMessage, StderrWatch } from "./logging.js";
5
+ import { parseCaptureStart, whenFinalized } from "./events.js";
6
+ import { buildCaptureArgs } from "./targets.js";
7
+ import { requireFfmpeg } from "./ffmpeg.js";
8
+ import { joinSegments, probeDuration } from "./lifecycle.js";
9
+ import { endSession, isPausing, partPath, partsDir, recordedSec, remainingCapSec, resumeBlocker, webcamPartPath, } from "./pause.js";
10
+ import { classifyUnrequestedExit, killPid } from "./sessions.js";
11
+ export function watchStderr(child, sessionId) {
12
+ let head = "";
13
+ let tail = "";
14
+ let outputAt = null;
15
+ const watch = new StderrWatch(() => ({ sessionId }));
16
+ child.stderr?.on("data", (d) => {
17
+ const text = d.toString();
18
+ tail = (tail + text).slice(-2000);
19
+ if (head.length < 8000)
20
+ head += text;
21
+ if (outputAt === null && /Output #0/.test(head))
22
+ outputAt = Date.now();
23
+ watch.feed(text);
24
+ });
25
+ child.on("error", (err) => {
26
+ tail += `\n${err.message}`;
27
+ });
28
+ return { head: () => head, tail: () => tail, outputAt: () => outputAt };
29
+ }
30
+ export function tailLines(watch, n = 6) {
31
+ return watch.tail().trim().split("\n").slice(-n).join("\n");
32
+ }
33
+ export function settleCapture(child, watch, backend) {
34
+ return new Promise((resolve) => {
35
+ const timer = setTimeout(() => resolve("running"), backend === "wgc" ? 15_000 : backend === "ddagrab" ? 2000 : 1200);
36
+ if (backend === "wgc") {
37
+ child.stderr?.on("data", () => {
38
+ if (parseCaptureStart(watch.head()) !== null) {
39
+ clearTimeout(timer);
40
+ resolve("running");
41
+ }
42
+ });
43
+ }
44
+ child.on("error", () => {
45
+ clearTimeout(timer);
46
+ resolve("exited");
47
+ });
48
+ child.on("exit", () => {
49
+ clearTimeout(timer);
50
+ resolve("exited");
51
+ });
52
+ });
53
+ }
54
+ export function captureStartMs(watch, backend, spawnedAt) {
55
+ const banner = parseCaptureStart(watch.head());
56
+ if (banner !== null)
57
+ return banner;
58
+ return backend === "ddagrab" ? (watch.outputAt() ?? spawnedAt) : spawnedAt;
59
+ }
60
+ export function attachExitHandler(store, id, child, opts) {
61
+ child.on("exit", (code) => {
62
+ store.detachChild(id);
63
+ if (!isPausing(id))
64
+ endSession(id);
65
+ const cur = store.get(id);
66
+ if (!cur || cur.status !== "recording" || store.isStopping(id))
67
+ return;
68
+ const verdict = classifyUnrequestedExit({
69
+ code,
70
+ backend: opts.backend,
71
+ maxDurationSec: opts.maxDurationSec,
72
+ elapsedMs: Date.now() - opts.spawnedAt,
73
+ });
74
+ logMessage(verdict.status === "failed" ? "error" : "notice", verdict.status === "failed"
75
+ ? `Recording ${id} failed: the recorder exited with code ${code}.`
76
+ : `Recording ${id} ended on its own (${verdict.endReason}).`, { sessionId: id, ...verdict });
77
+ store.tryUpdate(id, {
78
+ ...verdict,
79
+ stoppedAt: new Date().toISOString(),
80
+ ...(verdict.status === "failed"
81
+ ? { error: `${opts.backend === "wgc" ? "The window recorder" : "ffmpeg"} exited with code ${code}:\n${tailLines(opts.watch)}` }
82
+ : {}),
83
+ });
84
+ if (cur.segments && (cur.segments.parts.length > 0 || cur.webcam)) {
85
+ void finalizeSegments(store, cur).catch((err) => {
86
+ process.stderr.write(`Joining ${id}'s segments failed: ${err instanceof Error ? err.message : String(err)}\n`);
87
+ });
88
+ }
89
+ });
90
+ }
91
+ async function finalizeSegments(store, record) {
92
+ const tools = requireFfmpeg();
93
+ await whenFinalized(record.id);
94
+ const { patch, error } = await joinSegments(record, tools);
95
+ const durationSec = await probeDuration(tools.ffprobe, record.outputPath);
96
+ store.tryUpdate(record.id, { ...patch, durationSec: durationSec ?? undefined, ...(error ? { error } : {}) });
97
+ }
98
+ export async function resumeSession(store, record, ffmpeg) {
99
+ const blocker = resumeBlocker(record, store.ownsPaused(record.id));
100
+ if (blocker)
101
+ throw new ScreencastError(`Cannot resume ${record.id}: ${blocker}.`);
102
+ const seg = record.segments;
103
+ const capture = record.capture;
104
+ const backend = record.backend ?? "gdigrab";
105
+ const done = recordedSec(seg.parts);
106
+ const capSec = remainingCapSec(record.maxDurationSec, done);
107
+ const index = seg.parts.length;
108
+ const path = partPath(record.outputPath, index);
109
+ const webcamPath = capture.webcam ? webcamPartPath(record.outputPath, index) : undefined;
110
+ if (index > 0 || webcamPath)
111
+ mkdirSync(partsDir(record.outputPath), { recursive: true });
112
+ const args = buildCaptureArgs(capture.target, {
113
+ ...capture.opts,
114
+ output: path,
115
+ maxDurationSec: capSec,
116
+ ...(capture.webcam && webcamPath ? { webcam: { ...capture.webcam, output: webcamPath } } : {}),
117
+ });
118
+ const spawnedAt = Date.now();
119
+ const child = spawn(ffmpeg, args, { stdio: ["pipe", "ignore", "pipe"], windowsHide: true });
120
+ const watch = watchStderr(child, record.id);
121
+ const cleanup = () => {
122
+ if (index > 0)
123
+ rmSync(path, { force: true });
124
+ if (webcamPath)
125
+ rmSync(webcamPath, { force: true });
126
+ };
127
+ if ((await settleCapture(child, watch, backend)) === "exited") {
128
+ cleanup();
129
+ throw new ScreencastError(`Resume failed (ffmpeg exited immediately); the recording stays paused:\n${tailLines(watch)}`);
130
+ }
131
+ const startMs = captureStartMs(watch, backend, spawnedAt);
132
+ const camStart = webcamPath ? parseCaptureStart(watch.head(), capture.opts.audio ? 2 : 1) : null;
133
+ store.attachChild(record.id, child);
134
+ let updated;
135
+ try {
136
+ updated = store.update(record.id, {
137
+ status: "recording",
138
+ pid: child.pid ?? null,
139
+ videoStartMs: startMs - done * 1000,
140
+ segments: {
141
+ parts: seg.parts,
142
+ current: { path, startMs, ...(webcamPath ? { webcamPath, ...(camStart !== null ? { webcamStartMs: camStart } : {}) } : {}) },
143
+ },
144
+ });
145
+ }
146
+ catch (err) {
147
+ store.detachChild(record.id);
148
+ if (child.pid !== undefined)
149
+ killPid(child.pid);
150
+ cleanup();
151
+ throw new ScreencastError(`Resume stopped: the session registry could not be written (${err.message}).`);
152
+ }
153
+ if (!updated) {
154
+ store.detachChild(record.id);
155
+ if (child.pid !== undefined)
156
+ killPid(child.pid);
157
+ cleanup();
158
+ throw new ScreencastError(`No session with id "${record.id}".`);
159
+ }
160
+ store.clearPaused(record.id);
161
+ attachExitHandler(store, record.id, child, { backend, maxDurationSec: capSec, spawnedAt, watch });
162
+ return { record: updated, recordedSec: done, capSec };
163
+ }
@@ -249,7 +249,7 @@ export async function resolveRecording(args) {
249
249
  const record = getStore().get(args.sessionId);
250
250
  if (!record)
251
251
  throw new ScreencastError(`No session with id "${args.sessionId}".`);
252
- if (record.status === "recording")
252
+ if (record.status === "recording" || record.status === "paused")
253
253
  throw new ScreencastError("The recording is still running; stop_recording it first.");
254
254
  await whenFinalized(record.id);
255
255
  if (!existsSync(record.outputPath))
@@ -4,7 +4,12 @@ import { basename } from "node:path";
4
4
  import { ScreencastError } from "./errors.js";
5
5
  import { WGC_WINDOW_CLOSED_EXIT } from "./wgc.js";
6
6
  export const MAX_FINISHED_RECORDS = 100;
7
+ export function isLive(status) {
8
+ return status === "recording" || status === "paused";
9
+ }
7
10
  export function classifyOrphan(record, alive) {
11
+ if (record.status === "paused")
12
+ return { status: "stopped", reaped: false };
8
13
  if (record.status !== "recording") {
9
14
  return { status: record.status, reaped: false };
10
15
  }
@@ -13,7 +18,7 @@ export function classifyOrphan(record, alive) {
13
18
  : { status: "stopped", reaped: false };
14
19
  }
15
20
  export function isForeignLiveRecording(record, currentServerPid, ownerAlive) {
16
- return (record.status === "recording" &&
21
+ return (isLive(record.status) &&
17
22
  record.serverPid !== undefined &&
18
23
  record.serverPid !== currentServerPid &&
19
24
  ownerAlive);
@@ -105,9 +110,9 @@ export function killPid(pid) {
105
110
  }
106
111
  }
107
112
  export function pruneRecords(records) {
108
- const active = records.filter((r) => r.status === "recording");
113
+ const active = records.filter((r) => isLive(r.status));
109
114
  const finished = records
110
- .filter((r) => r.status !== "recording")
115
+ .filter((r) => !isLive(r.status))
111
116
  .sort((a, b) => (a.startedAt < b.startedAt ? 1 : -1))
112
117
  .slice(0, MAX_FINISHED_RECORDS);
113
118
  return [...active, ...finished];
@@ -379,7 +384,20 @@ export class SessionStore {
379
384
  this.children.delete(id);
380
385
  }
381
386
  activeIds() {
382
- return [...this.children.keys()].filter((id) => this.records.get(id)?.status === "recording");
387
+ return [
388
+ ...[...this.children.keys()].filter((id) => this.records.get(id)?.status === "recording"),
389
+ ...[...this.paused].filter((id) => this.records.get(id)?.status === "paused" && !this.children.has(id)),
390
+ ];
391
+ }
392
+ paused = new Set();
393
+ markPaused(id) {
394
+ this.paused.add(id);
395
+ }
396
+ ownsPaused(id) {
397
+ return this.paused.has(id);
398
+ }
399
+ clearPaused(id) {
400
+ this.paused.delete(id);
383
401
  }
384
402
  markStopping(id) {
385
403
  this.stopping.add(id);
@@ -403,7 +421,7 @@ export class SessionStore {
403
421
  return isSameServer(record, owners.get(pid) ?? null);
404
422
  };
405
423
  for (const record of this.records.values()) {
406
- if (record.status !== "recording")
424
+ if (!isLive(record.status))
407
425
  continue;
408
426
  if (isForeignLiveRecording(record, process.pid, ownerAlive(record))) {
409
427
  continue;
@@ -421,6 +439,12 @@ export class SessionStore {
421
439
  ...(verdict.status === "orphaned"
422
440
  ? { error: "Reaped on server restart (recording was interrupted)." }
423
441
  : {}),
442
+ ...(record.status === "paused"
443
+ ? {
444
+ endReason: "shutdown",
445
+ error: `The server exited while this recording was paused; its parts were not joined (${record.segments?.parts.map((p) => p.path).join(", ") ?? record.outputPath}).`,
446
+ }
447
+ : {}),
424
448
  };
425
449
  this.records.set(record.id, { ...record, ...patch });
426
450
  this.pending.set(record.id, { ...this.pending.get(record.id), ...patch });
@@ -150,6 +150,11 @@ export function targetInputArgs(target, monitors, opts = {}) {
150
150
  }
151
151
  }
152
152
  }
153
+ export function buildWebcamInputArgs(device) {
154
+ if (device.trim().length === 0)
155
+ throw new ScreencastError("webcam device must not be empty.");
156
+ return ["-f", "dshow", "-use_wallclock_as_timestamps", "1", "-rtbufsize", "256M", "-i", `video=${device}`];
157
+ }
153
158
  export const DEFAULT_MAX_RECORDING_SEC = 3600;
154
159
  export function resolveMaxDuration(explicit, env = process.env) {
155
160
  if (explicit !== undefined)
@@ -180,26 +185,45 @@ function validateFps(fps) {
180
185
  export function captureKeyframeArgs(fps) {
181
186
  return ["-g", String(Math.max(1, Math.round(fps * 2)))];
182
187
  }
188
+ const FRAGMENTED_MP4 = ["-movflags", "+frag_keyframe+empty_moov+default_base_moof"];
183
189
  export function buildCaptureArgs(target, opts) {
184
190
  const fps = validateFps(opts.fps ?? DEFAULT_FPS);
185
191
  const quality = opts.quality ?? DEFAULT_QUALITY;
186
192
  const monitors = opts.monitors ?? [];
187
193
  const cap = validateMaxDuration(opts.maxDurationSec ?? 0);
194
+ const capArgs = cap > 0 ? ["-t", String(cap)] : [];
195
+ const cam = opts.webcam;
196
+ const camInput = opts.audio ? 2 : 1;
188
197
  return [
189
198
  "-y",
190
- "-f", "gdigrab",
191
- "-framerate", String(fps),
192
- ...targetInputArgs(target, monitors, { evenSize: true }),
199
+ ...(opts.videoInput ?? [
200
+ "-f", "gdigrab",
201
+ "-framerate", String(fps),
202
+ ...(opts.drawMouse === false ? ["-draw_mouse", "0"] : []),
203
+ ...targetInputArgs(target, monitors, { evenSize: true }),
204
+ ]),
193
205
  ...buildAudioInputArgs(opts.audio),
194
- ...(target.kind === "full" && monitors.length === 0
206
+ ...(cam ? buildWebcamInputArgs(cam.device) : []),
207
+ ...(cam ? ["-map", "0:v", ...(opts.audio ? ["-map", "1:a"] : [])] : []),
208
+ ...(!opts.videoInput && target.kind === "full" && monitors.length === 0
195
209
  ? ["-vf", "crop=trunc(iw/2)*2:trunc(ih/2)*2"]
196
210
  : []),
197
- ...resolveQuality(quality),
211
+ ...(opts.videoCodec ?? resolveQuality(quality)),
198
212
  ...captureKeyframeArgs(fps),
199
213
  ...(opts.audio ? ["-c:a", "aac", "-b:a", "160k"] : []),
200
- "-movflags", "+frag_keyframe+empty_moov+default_base_moof",
201
- ...(cap > 0 ? ["-t", String(cap)] : []),
214
+ ...FRAGMENTED_MP4,
215
+ ...capArgs,
202
216
  opts.output,
217
+ ...(cam
218
+ ? [
219
+ "-map", `${camInput}:v`,
220
+ ...(cam.codec ?? resolveQuality(quality)),
221
+ ...captureKeyframeArgs(fps),
222
+ ...FRAGMENTED_MP4,
223
+ ...capArgs,
224
+ cam.output,
225
+ ]
226
+ : []),
203
227
  ];
204
228
  }
205
229
  export const SCREENSHOT_GRAB_FPS = 30;
@@ -3,6 +3,8 @@ export const TOOLSETS = {
3
3
  capture: [
4
4
  "start_recording",
5
5
  "stop_recording",
6
+ "pause_recording",
7
+ "resume_recording",
6
8
  "save_replay",
7
9
  "list_sessions",
8
10
  "get_session",
@@ -11,6 +13,7 @@ export const TOOLSETS = {
11
13
  "screenshot",
12
14
  "list_targets",
13
15
  "list_audio_devices",
16
+ "list_video_devices",
14
17
  ],
15
18
  watch: [
16
19
  "sample_frames",
@@ -41,6 +44,7 @@ export const TOOLSETS = {
41
44
  produce: [
42
45
  "callout",
43
46
  "keystroke_overlay",
47
+ "cursor",
44
48
  "backdrop",
45
49
  "overlay",
46
50
  "zoom",
@@ -54,7 +58,7 @@ export const TOOLSETS = {
54
58
  "bug_report",
55
59
  "step_guide",
56
60
  ],
57
- audio: ["extract_audio", "normalize_audio", "denoise", "transcribe", "music_bed"],
61
+ audio: ["extract_audio", "normalize_audio", "denoise", "transcribe", "music_bed", "narrate"],
58
62
  };
59
63
  export const SELECTABLE_TOOLSETS = Object.keys(TOOLSETS).filter((t) => t !== "core");
60
64
  export function toolsetOf(tool) {
@@ -87,6 +91,7 @@ export function serverInstructions(selection) {
87
91
  lines.push("Capture: screenshot for a still; start_recording -> (do the task) -> stop_recording for video " +
88
92
  "(events: true also logs clicks for read_events and zoom). For flaky failures, start_recording " +
89
93
  "{ replayBufferSec } keeps a rolling buffer and save_replay writes the last seconds after the fact. " +
94
+ "pause_recording/resume_recording skip setup; backend ddagrab uses the GPU. " +
90
95
  "Never start a recording the user did not ask for.");
91
96
  }
92
97
  if (on.has("watch")) {
@@ -101,7 +106,7 @@ export function serverInstructions(selection) {
101
106
  "segment, clip = several files; export_gif for size-bounded GIF/WebP, compress for a smaller mp4.");
102
107
  }
103
108
  if (on.has("produce")) {
104
- lines.push("Produce: callout, zoom, keystroke_overlay, backdrop, overlay, title_card, xfade_transition, assemble_highlights, burn_subtitles, export_preset.");
109
+ lines.push("Produce: callout, zoom, keystroke_overlay, cursor, backdrop, overlay, title_card, xfade_transition, assemble_highlights, burn_subtitles, export_preset.");
105
110
  }
106
111
  if (on.has("produce")) {
107
112
  lines.push("Bug reports: bug_report turns a recording (path or sessionId) into one redacted folder: clip, GIF, " +
@@ -116,7 +121,7 @@ export function serverInstructions(selection) {
116
121
  lines.push(`Markers: ${marks.filter(Boolean).join(" ")}`);
117
122
  }
118
123
  if (on.has("audio")) {
119
- lines.push("Audio: extract_audio, normalize_audio, denoise, music_bed; transcribe makes an SRT for burn_subtitles (words: true for word timing, then cut_by_transcript cuts by quoting it).");
124
+ lines.push("Audio: extract_audio, normalize_audio, denoise, music_bed, narrate (offline voiceover); transcribe makes an SRT for burn_subtitles (words: true for word timing, then cut_by_transcript cuts by quoting it).");
120
125
  }
121
126
  lines.push("Outputs go under SCREENCAST_HOME unless a call names a path; times are seconds and positions video pixels. " +
122
127
  "Screen content can include secrets: redact (find_text redact: true -> redact_region) before sharing. " +
package/dist/utils/wgc.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { ScreencastError } from "./errors.js";
2
- export function buildWgcGrabArgs(hwnd, fps) {
2
+ export function buildWgcGrabArgs(hwnd, fps, cursor = true) {
3
3
  if (!Number.isSafeInteger(hwnd) || hwnd <= 0)
4
4
  throw new ScreencastError("Invalid window handle.");
5
5
  return [
6
6
  "-hide_banner", "-nostats", "-loglevel", "info",
7
7
  "-f", "lavfi",
8
- "-i", `gfxcapture=hwnd=${hwnd}:max_framerate=${fps},hwdownload,format=bgra,crop=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p`,
8
+ "-i", `gfxcapture=hwnd=${hwnd}:max_framerate=${fps}${cursor ? "" : ":capture_cursor=0"},hwdownload,format=bgra,crop=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p`,
9
9
  "-flush_packets", "1",
10
10
  "-f", "rawvideo", "-",
11
11
  ];
@@ -5,7 +5,7 @@ const FIRST_FRAME_TIMEOUT_MS = 10_000;
5
5
  const MAX_QUEUED_FRAMES = 4;
6
6
  const cfg = JSON.parse(process.argv[2] ?? "{}");
7
7
  const log = (s) => process.stderr.write(s.endsWith("\n") ? s : `${s}\n`);
8
- const grab = spawn(cfg.ffmpeg, buildWgcGrabArgs(cfg.hwnd, cfg.fps), { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
8
+ const grab = spawn(cfg.ffmpeg, buildWgcGrabArgs(cfg.hwnd, cfg.fps, cfg.cursor !== false), { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
9
9
  const nudge = spawn("powershell", ["-NoProfile", "-NonInteractive", "-Command", nudgeScript(cfg.hwnd, 200, process.pid)], {
10
10
  stdio: "ignore",
11
11
  windowsHide: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tmhs/screencast-mcp",
3
- "version": "0.46.0",
3
+ "version": "0.47.0",
4
4
  "description": "Let AI agents record the Windows screen, watch it as frames, and edit it with ffmpeg",
5
5
  "mcpName": "io.github.TMHSDigital/screencast-mcp",
6
6
  "type": "module",
@@ -27,6 +27,8 @@
27
27
  "test:watch": "vitest",
28
28
  "eval": "tsx evals/run.ts",
29
29
  "typecheck:evals": "tsc -p evals/tsconfig.json",
30
+ "docs": "tsc && node scripts/build-tool-docs.mjs",
31
+ "docs:check": "tsc && node scripts/build-tool-docs.mjs --check",
30
32
  "prepublishOnly": "npm run build"
31
33
  },
32
34
  "author": "TMHSDigital",