@tmhs/screencast-mcp 0.48.1 → 0.48.2

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.
package/README.md CHANGED
@@ -42,6 +42,8 @@ The fastest path: `npx -y @tmhs/screencast-mcp setup` checks FFmpeg 8, OCR, and
42
42
 
43
43
  **You need** Windows 10 or 11, [Node.js](https://nodejs.org) 22+, and **FFmpeg 8 or newer** on `PATH` (`winget install Gyan.FFmpeg`, the full build). Older builds run most tools, but `transcribe` (the `whisper` filter) and `backend: "wgc"` (`gfxcapture`) need FFmpeg 8, and essentials or distro builds can lack them (Ubuntu LTS `apt install ffmpeg` gives 6.x). Capture is Windows-only; the watch, edit, and produce tools work anywhere ffmpeg runs. After connecting, ask the agent to run `doctor`: it reports the ffmpeg version, the filters and devices it has, OCR, and anything missing.
44
44
 
45
+ **Windows on ARM64** is in progress (#246): CI runs a non-blocking `windows-11-arm` job. gyan.dev ships no arm64 FFmpeg, so use BtbN's `winarm64-gpl` FFmpeg 8 build; it has `gdigrab`, `gfxcapture` and `drawtext` but no `whisper` or libvpx, so `transcribe` and `.webm` output need another build. `doctor` reports `arch` and what is missing.
46
+
45
47
  **Add it to your client:**
46
48
 
47
49
  | Client | How |
@@ -192,7 +194,7 @@ Every capture tool takes one `target` string: `full`, `monitor:<index>`, `window
192
194
  | `SCREENCAST_MAX_RECORDING_SEC` | `3600` | Default recording cap (`0` disables it) |
193
195
  | `SCREENCAST_JOB_TIMEOUT_MS` | scales with length | Override the edit job timeout |
194
196
  | `SCREENCAST_WHISPER_MODEL` | none | whisper.cpp model for `transcribe` |
195
- | `SCREENCAST_RETENTION_DAYS` | off | Delete screenshots, frames, and leftover raw event logs older than this many days at startup (never recordings or edits) |
197
+ | `SCREENCAST_RETENTION_DAYS` | off | Delete screenshots, frames, leftover raw event logs, and `index_recording` indexes older than this many days at startup (never recordings or edits; an index is rebuilt by running `index_recording` again) |
196
198
  | `SCREENCAST_PS_TIMEOUT_MS` | 20000 (OCR 60000) | Limit for the PowerShell helpers that list monitors and windows and run OCR |
197
199
  | `SCREENCAST_CONFIRM_CAPTURE` | off | Set to `1` to ask the user to confirm every live capture through MCP elicitation; clients without elicitation are refused |
198
200
  | `SCREENCAST_TOOLSETS` | `all` | Comma-separated toolsets to expose; the rest are not loaded, which shrinks the tool list the agent pays for on every turn (`core` is always on) |
@@ -226,7 +228,7 @@ Every capture tool takes one `target` string: `full`, `monitor:<index>`, `window
226
228
 
227
229
  - **No network requests, no telemetry.** The server runs ffmpeg, ffprobe, and PowerShell locally and talks to your client over stdio. OCR (`find_text`) and speech (`narrate`) use the engines built into Windows.
228
230
  - **What a tool returns goes to your model provider.** Inline frames, OCR text, and event summaries reach your agent like any tool result; files on disk stay on disk unless a tool returns them or you share them.
229
- - **Everything is stored under `SCREENCAST_HOME`** (`recordings/`, `screenshots/`, `frames/`, `edits/`, `sessions.json`) unless a call names another path. `find_text`, `wait_for_change`, and `screen_diff` delete their captures after the call by default.
231
+ - **Everything is stored under `SCREENCAST_HOME`** (`recordings/`, `screenshots/`, `frames/`, `edits/`, `sessions.json`) unless a call names another path. `find_text` and `wait_for_change` delete their captures after the call by default (`keep: true` keeps them); `screen_diff` compares existing images and captures nothing.
230
232
  - **The event log never records typed text.** Only with `start_recording` `events: true` (or `cursor: "events"`), and only while that recording runs: clicks, scrolls, and cursor positions system-wide, and typing as bursts on a 0.5 s grid with no key names (`keys: "shortcuts"` also names Ctrl/Alt/Win chords). There is no microphone capture; system audio only with `audio.source` = `system`.
231
233
  - **Deleting data.** Delete files under `SCREENCAST_HOME`, or set `SCREENCAST_RETENTION_DAYS`; recordings and edits are never deleted automatically.
232
234
 
package/dist/cli.js CHANGED
@@ -8,6 +8,7 @@ import { createServer } from "./server.js";
8
8
  import { MAX_RECORDING_CAP_SEC } from "./utils/targets.js";
9
9
  import { DEFAULT_ERROR_PATTERN, DEFAULT_SECRET_PATTERN, MAX_ERROR_LINES, maskSecrets } from "./utils/bugReport.js";
10
10
  import { defaultSetupDeps, parseSetupArgs, runSetup, SETUP_USAGE } from "./setup.js";
11
+ import { errorMessage } from "./utils/errors.js";
11
12
  const VERSION = createRequire(import.meta.url)("../package.json").version;
12
13
  export class CliUsageError extends Error {
13
14
  }
@@ -174,7 +175,7 @@ export function parseCliArgs(argv, env = process.env) {
174
175
  return { kind: "setup", options: parseSetupArgs(rest) };
175
176
  }
176
177
  catch (err) {
177
- throw new CliUsageError(err instanceof Error ? err.message : String(err));
178
+ throw new CliUsageError(errorMessage(err));
178
179
  }
179
180
  }
180
181
  default:
@@ -241,7 +242,7 @@ export function parseToolArgs(raw, readFile = (p) => readFileSync(p, "utf8")) {
241
242
  value = JSON.parse(text);
242
243
  }
243
244
  catch (err) {
244
- throw new CliUsageError(`Tool arguments are not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
245
+ throw new CliUsageError(`Tool arguments are not valid JSON: ${errorMessage(err)}`);
245
246
  }
246
247
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
247
248
  throw new CliUsageError("Tool arguments must be a JSON object.");
@@ -354,7 +355,7 @@ export async function runRecord(opts, io = defaultIo, deps = defaultRecordDeps)
354
355
  io.err(`screencast-mcp: recording ${opts.target} to ${String(started.outputPath)}\n`);
355
356
  }
356
357
  catch (err) {
357
- warn(`recording did not start, running the command without it: ${err instanceof Error ? err.message : String(err)}`);
358
+ warn(`recording did not start, running the command without it: ${errorMessage(err)}`);
358
359
  }
359
360
  const began = deps.now();
360
361
  evidence.exitCode = await deps.run(opts.command);
@@ -372,7 +373,7 @@ export async function runRecord(opts, io = defaultIo, deps = defaultRecordDeps)
372
373
  warn(early);
373
374
  }
374
375
  catch (err) {
375
- warn(`stop_recording failed: ${err instanceof Error ? err.message : String(err)}`);
376
+ warn(`stop_recording failed: ${errorMessage(err)}`);
376
377
  }
377
378
  }
378
379
  const failed = evidence.exitCode !== 0;
@@ -390,7 +391,7 @@ export async function runRecord(opts, io = defaultIo, deps = defaultRecordDeps)
390
391
  evidence.gif = String(gif.outputPath);
391
392
  }
392
393
  catch (err) {
393
- warn(`export_gif failed: ${err instanceof Error ? err.message : String(err)}`);
394
+ warn(`export_gif failed: ${errorMessage(err)}`);
394
395
  }
395
396
  }
396
397
  if (opts.contactSheet) {
@@ -404,7 +405,7 @@ export async function runRecord(opts, io = defaultIo, deps = defaultRecordDeps)
404
405
  evidence.contactSheet = String(sheet.outputPath);
405
406
  }
406
407
  catch (err) {
407
- warn(`contact_sheet failed: ${err instanceof Error ? err.message : String(err)}`);
408
+ warn(`contact_sheet failed: ${errorMessage(err)}`);
408
409
  }
409
410
  }
410
411
  }
@@ -453,7 +454,7 @@ async function ocrErrors(client, recording, durationSec, lastSec, outDir, warn)
453
454
  return errorLines(matches);
454
455
  }
455
456
  catch (err) {
456
- warn(`OCR of error lines failed: ${err instanceof Error ? err.message : String(err)}`);
457
+ warn(`OCR of error lines failed: ${errorMessage(err)}`);
457
458
  return null;
458
459
  }
459
460
  finally {
package/dist/context.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { SessionStore } from "./utils/sessions.js";
2
2
  import { registryPath } from "./utils/paths.js";
3
+ import { ScreencastError } from "./utils/errors.js";
3
4
  let store = null;
4
5
  export function getStore() {
5
6
  if (!store) {
@@ -15,3 +16,35 @@ export function markShuttingDown() {
15
16
  export function isShuttingDown() {
16
17
  return shuttingDown;
17
18
  }
19
+ let startsInFlight = 0;
20
+ let onStartsIdle = [];
21
+ export function beginStart() {
22
+ if (shuttingDown)
23
+ throw new ScreencastError("The server is shutting down; the recording was not started.");
24
+ startsInFlight++;
25
+ let released = false;
26
+ return () => {
27
+ if (released)
28
+ return;
29
+ released = true;
30
+ startsInFlight--;
31
+ if (startsInFlight === 0) {
32
+ const waiters = onStartsIdle;
33
+ onStartsIdle = [];
34
+ for (const w of waiters)
35
+ w();
36
+ }
37
+ };
38
+ }
39
+ export function startsSettled(timeoutMs) {
40
+ if (startsInFlight === 0)
41
+ return Promise.resolve(true);
42
+ return new Promise((resolve) => {
43
+ const timer = setTimeout(() => resolve(false), timeoutMs);
44
+ timer.unref?.();
45
+ onStartsIdle.push(() => {
46
+ clearTimeout(timer);
47
+ resolve(true);
48
+ });
49
+ });
50
+ }
package/dist/index.js CHANGED
@@ -1,15 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { isCliInvocation, runCli } from "./cli.js";
4
- import { getStore, isShuttingDown, markShuttingDown } from "./context.js";
5
- import { requireFfmpeg } from "./utils/ffmpeg.js";
4
+ import { getStore, isShuttingDown, markShuttingDown, startsSettled } from "./context.js";
5
+ import { probeDuration, requireFfmpeg } from "./utils/ffmpeg.js";
6
6
  import { abortEditJobs } from "./utils/jobs.js";
7
- import { probeDuration, stopAll } from "./utils/lifecycle.js";
7
+ import { stopAll } from "./utils/lifecycle.js";
8
8
  import { createServer } from "./server.js";
9
9
  import { pruneCaptures, retentionDays, RETENTION_ENV } from "./utils/retention.js";
10
10
  import { cleanupReplayDirs } from "./utils/replay.js";
11
- const server = createServer();
11
+ import { errorMessage } from "./utils/errors.js";
12
+ const START_SETTLE_MS = 10_000;
12
13
  async function main() {
14
+ const server = createServer();
15
+ installServerHandlers();
13
16
  try {
14
17
  const reaped = getStore().reapOrphans();
15
18
  if (reaped.length > 0) {
@@ -17,7 +20,7 @@ async function main() {
17
20
  }
18
21
  }
19
22
  catch (err) {
20
- process.stderr.write(`Orphan reaping skipped: ${err instanceof Error ? err.message : String(err)}\n`);
23
+ process.stderr.write(`Orphan reaping skipped: ${errorMessage(err)}\n`);
21
24
  }
22
25
  try {
23
26
  const live = getStore()
@@ -28,17 +31,20 @@ async function main() {
28
31
  process.stderr.write(`Removed ${removed} leftover replay buffer(s).\n`);
29
32
  }
30
33
  catch (err) {
31
- process.stderr.write(`Replay buffer cleanup skipped: ${err instanceof Error ? err.message : String(err)}\n`);
34
+ process.stderr.write(`Replay buffer cleanup skipped: ${errorMessage(err)}\n`);
32
35
  }
36
+ const transport = new StdioServerTransport();
37
+ await server.connect(transport);
33
38
  const days = retentionDays();
34
39
  if (days !== null) {
35
- const pruned = pruneCaptures(days);
36
- if (pruned.removed > 0) {
37
- process.stderr.write(`Deleted ${pruned.removed} capture file(s) older than ${days} day(s) (${RETENTION_ENV}).\n`);
38
- }
40
+ pruneCaptures(days).then((pruned) => {
41
+ if (pruned.removed > 0) {
42
+ process.stderr.write(`Deleted ${pruned.removed} capture file(s) older than ${days} day(s) (${RETENTION_ENV}).\n`);
43
+ }
44
+ }, (err) => {
45
+ process.stderr.write(`Retention prune failed: ${errorMessage(err)}\n`);
46
+ });
39
47
  }
40
- const transport = new StdioServerTransport();
41
- await server.connect(transport);
42
48
  process.stdin.on("end", () => void shutdown("client disconnected"));
43
49
  process.stdin.on("close", () => void shutdown("client disconnected"));
44
50
  server.server.onclose = () => void shutdown("transport closed");
@@ -46,24 +52,29 @@ async function main() {
46
52
  process.on(sig, () => void shutdown(sig));
47
53
  }
48
54
  }
49
- process.stdout.on("error", (err) => {
50
- if (err.code !== "EPIPE")
51
- process.stderr.write(`stdout error: ${err.message}\n`);
52
- void shutdown("client pipe closed");
53
- });
54
- process.on("uncaughtException", (err) => {
55
- process.stderr.write(`Uncaught exception: ${err.stack ?? err.message}\n`);
56
- void shutdown("uncaught exception", 1);
57
- });
58
- process.on("unhandledRejection", (reason) => {
59
- process.stderr.write(`Unhandled rejection: ${reason instanceof Error ? (reason.stack ?? reason.message) : String(reason)}\n`);
60
- });
55
+ function installServerHandlers() {
56
+ process.stdout.on("error", (err) => {
57
+ if (err.code !== "EPIPE")
58
+ process.stderr.write(`stdout error: ${err.message}\n`);
59
+ void shutdown("client pipe closed");
60
+ });
61
+ process.on("uncaughtException", (err) => {
62
+ process.stderr.write(`Uncaught exception: ${err.stack ?? err.message}\n`);
63
+ void shutdown("uncaught exception", 1);
64
+ });
65
+ process.on("unhandledRejection", (reason) => {
66
+ process.stderr.write(`Unhandled rejection: ${reason instanceof Error ? (reason.stack ?? reason.message) : String(reason)}\n`);
67
+ });
68
+ }
61
69
  async function shutdown(reason, exitCode = 0) {
62
70
  if (isShuttingDown())
63
71
  return;
64
72
  markShuttingDown();
65
73
  const edits = abortEditJobs();
66
74
  try {
75
+ if (!(await startsSettled(START_SETTLE_MS))) {
76
+ process.stderr.write(`Shutdown (${reason}): a start_recording call did not finish within ${START_SETTLE_MS / 1000}s.\n`);
77
+ }
67
78
  const store = getStore();
68
79
  if (store.activeIds().length > 0) {
69
80
  let ffprobe = null;
@@ -72,12 +83,12 @@ async function shutdown(reason, exitCode = 0) {
72
83
  }
73
84
  catch {
74
85
  }
75
- const stopped = await stopAll(store, (path) => ffprobe ? probeDuration(ffprobe, path) : Promise.resolve(null));
86
+ const stopped = await stopAll(store, (path) => ffprobe ? probeDuration(path, { ffprobe }) : Promise.resolve(null));
76
87
  process.stderr.write(`Shutdown (${reason}): stopped ${stopped.length} recording(s).\n`);
77
88
  }
78
89
  }
79
90
  catch (err) {
80
- process.stderr.write(`Shutdown cleanup failed: ${err instanceof Error ? err.message : String(err)}\n`);
91
+ process.stderr.write(`Shutdown cleanup failed: ${errorMessage(err)}\n`);
81
92
  }
82
93
  const cancelled = await edits;
83
94
  if (cancelled > 0)
@@ -85,11 +96,15 @@ async function shutdown(reason, exitCode = 0) {
85
96
  process.exit(exitCode);
86
97
  }
87
98
  const fatal = (error) => {
88
- process.stderr.write(`Fatal error: ${error instanceof Error ? error.message : String(error)}\n`);
99
+ process.stderr.write(`Fatal error: ${errorMessage(error)}\n`);
89
100
  process.exit(1);
90
101
  };
91
102
  const argv = process.argv.slice(2);
92
103
  if (isCliInvocation(argv)) {
104
+ process.stdout.on("error", (err) => {
105
+ if (err.code !== "EPIPE")
106
+ process.stderr.write(`stdout error: ${err.message}\n`);
107
+ });
93
108
  runCli(argv).then((code) => process.exit(code), fatal);
94
109
  }
95
110
  else {
package/dist/setup.js CHANGED
@@ -3,6 +3,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
6
+ import { errorMessage } from "./utils/errors.js";
6
7
  export const CLIENT_IDS = ["claude-desktop", "claude-code", "cursor", "vscode"];
7
8
  export const SETUP_USAGE = `setup options:
8
9
  --yes answer yes: install FFmpeg and write client configs without asking
@@ -113,7 +114,7 @@ export function mergeServerConfig(existing, key, name, entry, force = false) {
113
114
  parsed = JSON.parse(existing.charCodeAt(0) === 0xfeff ? existing.slice(1) : existing);
114
115
  }
115
116
  catch (err) {
116
- return { status: "invalid", reason: `not plain JSON (${err instanceof Error ? err.message : String(err)})` };
117
+ return { status: "invalid", reason: `not plain JSON (${errorMessage(err)})` };
117
118
  }
118
119
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
119
120
  return { status: "invalid", reason: "the file is not a JSON object" };
@@ -209,7 +210,7 @@ async function configureJsonClient(client, opts, deps) {
209
210
  text = fs.readFile(client.path);
210
211
  }
211
212
  catch (err) {
212
- deps.out(` ${client.name}: could not read ${client.path}: ${err instanceof Error ? err.message : String(err)}\n`);
213
+ deps.out(` ${client.name}: could not read ${client.path}: ${errorMessage(err)}\n`);
213
214
  return false;
214
215
  }
215
216
  }
@@ -248,7 +249,7 @@ async function configureJsonClient(client, opts, deps) {
248
249
  return true;
249
250
  }
250
251
  catch (err) {
251
- deps.out(` ${client.name}: could not write ${client.path}: ${err instanceof Error ? err.message : String(err)}\n`);
252
+ deps.out(` ${client.name}: could not write ${client.path}: ${errorMessage(err)}\n`);
252
253
  return false;
253
254
  }
254
255
  }
@@ -293,7 +294,7 @@ export async function runSetup(opts, deps) {
293
294
  report = await deps.doctor();
294
295
  }
295
296
  catch (err) {
296
- deps.err(`screencast-mcp: the doctor checks failed to run: ${err instanceof Error ? err.message : String(err)}\n`);
297
+ deps.err(`screencast-mcp: the doctor checks failed to run: ${errorMessage(err)}\n`);
297
298
  return 1;
298
299
  }
299
300
  for (const line of checklist(report, deps.env, deps.platform))
@@ -317,7 +318,7 @@ export async function runSetup(opts, deps) {
317
318
  const res = await deps.exec("winget", WINGET_FFMPEG).catch((err) => ({
318
319
  code: 1,
319
320
  stdout: "",
320
- stderr: err instanceof Error ? err.message : String(err),
321
+ stderr: errorMessage(err),
321
322
  }));
322
323
  if (res.code === 0)
323
324
  say(" FFmpeg installed. Open a new terminal so PATH picks it up, then run setup again.\n");
@@ -355,7 +356,7 @@ export async function runSetup(opts, deps) {
355
356
  await deps.open(gif).catch(() => undefined);
356
357
  }
357
358
  catch (err) {
358
- say(` the test clip failed: ${err instanceof Error ? err.message : String(err)}\n`);
359
+ say(` the test clip failed: ${errorMessage(err)}\n`);
359
360
  return 1;
360
361
  }
361
362
  }
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { existsSync } from "node:fs";
3
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
3
+ import { errorMessage, errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
4
  import { looseOutput } from "../utils/toolSpec.js";
5
5
  import { assertOutputAllowed } from "../utils/paths.js";
6
6
  import { cleanLabel, insertMarker, markerTimeSec, markersPath, readMarkers, writeMarkers, MAX_LABEL, } from "../utils/chapters.js";
@@ -61,7 +61,7 @@ export function register(server) {
61
61
  sidecar = writeMarkers(record.outputPath, markers, args.sessionId);
62
62
  }
63
63
  catch (err) {
64
- warning = `Saved in the session, but the sidecar ${sidecar} could not be written: ${err.message}`;
64
+ warning = `Saved in the session, but the sidecar ${sidecar} could not be written: ${errorMessage(err)}`;
65
65
  }
66
66
  return okResponse({
67
67
  sessionId: args.sessionId,
@@ -1,8 +1,8 @@
1
1
  import { z } from "zod";
2
2
  import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
3
3
  import { STOPS_SESSION, looseOutput } from "../utils/toolSpec.js";
4
- import { requireFfmpeg } from "../utils/ffmpeg.js";
5
- import { pauseSession, probeDuration } from "../utils/lifecycle.js";
4
+ import { probeDuration, requireFfmpeg } from "../utils/ffmpeg.js";
5
+ import { pauseSession } from "../utils/lifecycle.js";
6
6
  import { recordedSec } from "../utils/pause.js";
7
7
  import { getStore } from "../context.js";
8
8
  const r3 = (n) => Math.round(n * 1000) / 1000;
@@ -28,7 +28,7 @@ export function register(server) {
28
28
  });
29
29
  }
30
30
  const { ffprobe } = requireFfmpeg();
31
- const res = await pauseSession(store, record, { probe: (p) => probeDuration(ffprobe, p) });
31
+ const res = await pauseSession(store, record, { probe: (p) => probeDuration(p, { ffprobe }) });
32
32
  return okResponse({
33
33
  sessionId: record.id,
34
34
  status: "paused",
@@ -5,7 +5,7 @@ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
5
5
  import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
6
6
  import { requireFfmpeg, runFfmpeg, runCapture, probeMedia } from "../utils/ffmpeg.js";
7
7
  import { jobTimeoutMs } from "../utils/jobs.js";
8
- import { buildSampleByFpsArgs, buildSampleAtTimestampArgs, planFpsSampling, buildSceneScanArgs, parseSceneScan, pickSceneFrames, DEFAULT_SCENE_THRESHOLD, DEFAULT_MAX_FRAMES, MAX_FRAMES_CEILING, } from "../utils/media.js";
8
+ import { buildSampleByFpsArgs, pickFramePrefix, buildSampleAtTimestampArgs, planFpsSampling, buildSceneScanArgs, parseSceneScan, pickSceneFrames, DEFAULT_SCENE_THRESHOLD, DEFAULT_MAX_FRAMES, MAX_FRAMES_CEILING, } from "../utils/media.js";
9
9
  import { subdir, stamp, rand, sequencePattern, resolveOutputDir } from "../utils/paths.js";
10
10
  import { encodeInlineImages, clampInlineCount, DEFAULT_MAX_IMAGE_WIDTH, DEFAULT_MAX_INLINE_IMAGES, MAX_INLINE_IMAGES, } from "../utils/images.js";
11
11
  const inputSchema = {
@@ -117,11 +117,11 @@ export function register(server) {
117
117
  if (plan) {
118
118
  const isPng = (f) => f.endsWith(".png");
119
119
  const before = new Set(readdirSync(dir).filter(isPng));
120
- const pattern = sequencePattern(dir, "frame_%05d.png");
120
+ const prefix = pickFramePrefix(before, `${stamp()}-${rand()}`);
121
+ const pattern = sequencePattern(dir, `${prefix}%05d.png`);
121
122
  await runFfmpeg(buildSampleByFpsArgs(args.input, plan.fps, pattern, maxFrames, args.dedupe === true), jobTimeoutMs(durationSec), { signal: extra.signal });
122
123
  frames = readdirSync(dir)
123
- .filter(isPng)
124
- .filter((f) => !before.has(f))
124
+ .filter((f) => isPng(f) && f.startsWith(prefix) && !before.has(f))
125
125
  .sort()
126
126
  .map((f) => join(dir, f));
127
127
  }
@@ -1,6 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { z } from "zod";
3
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
3
+ import { errorMessage, 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";
@@ -10,7 +10,7 @@ import { windowMatchReport } from "../utils/windows.js";
10
10
  import { resolveLoopbackDevice, resolveVideoDevice } from "../utils/audioDevices.js";
11
11
  import { confirmCapture, describeTarget } from "../utils/consent.js";
12
12
  import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
13
- import { getStore } from "../context.js";
13
+ import { beginStart, getStore } from "../context.js";
14
14
  import { killPid, serverIdentity } from "../utils/sessions.js";
15
15
  import { mkdirSync, rmSync } from "node:fs";
16
16
  import { buildDdaInputArgs, ddagrabWorks, encoderArgs, getDxgiOutputs, planDdaSource, resolveEncoder, startWithEncoderFallback, } from "../utils/gpu.js";
@@ -132,7 +132,9 @@ export function register(server) {
132
132
  }),
133
133
  annotations: WRITES_FILE,
134
134
  }, async (args, extra) => {
135
+ let release = () => { };
135
136
  try {
137
+ release = beginStart();
136
138
  const { ffmpeg } = requireFfmpeg();
137
139
  const hideCursor = args.cursor === "events";
138
140
  if (hideCursor)
@@ -268,6 +270,7 @@ export function register(server) {
268
270
  fps,
269
271
  quality,
270
272
  pid: child.pid ?? null,
273
+ pidSpawnedAt: spawnedAt,
271
274
  ...serverIdentity(),
272
275
  status: "recording",
273
276
  startedAt: new Date().toISOString(),
@@ -330,7 +333,7 @@ export function register(server) {
330
333
  discardReplay(replay);
331
334
  if (webcamRaw)
332
335
  rmSync(partsDir(output), { recursive: true, force: true });
333
- throw new ScreencastError(`Recording stopped: the session registry could not be written (${err.message}).`);
336
+ throw new ScreencastError(`Recording stopped: the session registry could not be written (${errorMessage(err)}).`);
334
337
  }
335
338
  if (logger && replay) {
336
339
  const exited = new Promise((resolve) => child.once("exit", () => resolve()));
@@ -348,11 +351,11 @@ export function register(server) {
348
351
  }
349
352
  catch (err) {
350
353
  store.tryUpdate(id, {
351
- events: { path: evPaths.jsonl, keys: keyMode, error: err.message },
354
+ events: { path: evPaths.jsonl, keys: keyMode, error: errorMessage(err) },
352
355
  });
353
356
  }
354
357
  }).catch((err) => {
355
- process.stderr.write(`Event log for ${id} failed: ${err instanceof Error ? err.message : String(err)}\n`);
358
+ process.stderr.write(`Event log for ${id} failed: ${errorMessage(err)}\n`);
356
359
  }));
357
360
  }
358
361
  attachExitHandler(store, id, child, { backend, maxDurationSec, spawnedAt, watch });
@@ -388,5 +391,8 @@ export function register(server) {
388
391
  catch (error) {
389
392
  return errorResponse(error);
390
393
  }
394
+ finally {
395
+ release();
396
+ }
391
397
  });
392
398
  }
@@ -2,9 +2,10 @@ 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 { probeMedia, requireFfmpeg } from "../utils/ffmpeg.js";
6
- import { probeDuration, stopSession } from "../utils/lifecycle.js";
5
+ import { probeDuration, probeMedia, requireFfmpeg } from "../utils/ffmpeg.js";
6
+ import { stopSession } from "../utils/lifecycle.js";
7
7
  import { getStore } from "../context.js";
8
+ import { foreignStopRefusal, ownerAlive } from "../utils/sessions.js";
8
9
  import { finishReplay } from "../utils/replay.js";
9
10
  import { webcamPlacement } from "../utils/pause.js";
10
11
  function replayReport(r) {
@@ -95,10 +96,13 @@ export function register(server) {
95
96
  : "Session was not active; returning its recorded final state.",
96
97
  });
97
98
  }
99
+ const refusal = foreignStopRefusal(record, process.pid, ownerAlive(record));
100
+ if (refusal)
101
+ throw new ScreencastError(refusal);
98
102
  const { ffprobe } = requireFfmpeg();
99
103
  const { record: updated, graceful, durationSec, replay, segments } = await stopSession(store, record, {
100
104
  reason: "stopped",
101
- probe: (path) => probeDuration(ffprobe, path),
105
+ probe: (path) => probeDuration(path, { ffprobe }),
102
106
  saveReplay: args.save,
103
107
  });
104
108
  return okResponse({
@@ -1,4 +1,4 @@
1
- import { ScreencastError } from "./errors.js";
1
+ import { errorMessage, ScreencastError } from "./errors.js";
2
2
  import { requireFfmpeg, runCapture } from "./ffmpeg.js";
3
3
  export const LOOPBACK_HINTS = [
4
4
  "virtual-audio-capturer",
@@ -89,7 +89,7 @@ async function enumerateDshow() {
89
89
  res = await runCapture(ffmpeg, ["-hide_banner", "-list_devices", "true", "-f", "dshow", "-i", "dummy"], ENUM_TIMEOUT_MS, { closeStdin: true });
90
90
  }
91
91
  catch (err) {
92
- throw new ScreencastError(`Could not enumerate audio devices (${err.message}).`, ENUM_FAILED_HINT);
92
+ throw new ScreencastError(`Could not enumerate audio devices (${errorMessage(err)}).`, ENUM_FAILED_HINT);
93
93
  }
94
94
  cachedDevices = parseDshowAudioDevices(res.stderr);
95
95
  cachedVideo = parseDshowVideoDevices(res.stderr);
@@ -1,6 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { isAbsolute } from "node:path";
3
3
  import { runPowerShell, psTimeoutMs } from "./monitors.js";
4
+ import { errorMessage } from "./errors.js";
4
5
  export const FFMPEG_FEATURE_MAJOR = 8;
5
6
  export function parseFfmpegVersion(text) {
6
7
  const version = /^ff(?:mpeg|probe) version (\S+)/m.exec(text)?.[1] ?? null;
@@ -62,7 +63,7 @@ export async function ocrStatus() {
62
63
  return { available: raw.available === true, language: raw.language ?? null, languages };
63
64
  }
64
65
  catch (err) {
65
- return { available: false, language: null, languages: [], error: err.message };
66
+ return { available: false, language: null, languages: [], error: errorMessage(err) };
66
67
  }
67
68
  }
68
69
  export const ENV_SETTINGS = [
@@ -1,4 +1,4 @@
1
- import { ScreencastError } from "./errors.js";
1
+ import { errorMessage, ScreencastError } from "./errors.js";
2
2
  export const CONFIRM_CAPTURE_ENV = "SCREENCAST_CONFIRM_CAPTURE";
3
3
  export const CONFIRM_TIMEOUT_MS = 5 * 60 * 1000;
4
4
  export function confirmCaptureEnabled(env = process.env) {
@@ -21,7 +21,7 @@ export async function confirmCapture(server, request, signal) {
21
21
  ({ action } = await server.server.elicitInput({ message: request, requestedSchema: { type: "object", properties: {} } }, { signal, timeout: CONFIRM_TIMEOUT_MS }));
22
22
  }
23
23
  catch (err) {
24
- throw new ScreencastError(`Capture blocked: the confirmation request failed (${err instanceof Error ? err.message : String(err)}). Nothing was captured.`);
24
+ throw new ScreencastError(`Capture blocked: the confirmation request failed (${errorMessage(err)}). Nothing was captured.`);
25
25
  }
26
26
  if (action !== "accept") {
27
27
  throw new ScreencastError(`Capture ${action === "decline" ? "declined" : "cancelled"} by the user. Nothing was captured.`);
@@ -6,6 +6,9 @@ export class ScreencastError extends Error {
6
6
  this.hint = hint;
7
7
  }
8
8
  }
9
+ export function errorMessage(error) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
9
12
  export function okResponse(value, images = []) {
10
13
  const text = typeof value === "string" ? value : JSON.stringify(value, null, 2);
11
14
  const result = { content: [{ type: "text", text }, ...images] };
@@ -19,11 +22,8 @@ export function errorResponse(error) {
19
22
  if (error instanceof ScreencastError) {
20
23
  message = error.hint ? `${error.message}\n\n${error.hint}` : error.message;
21
24
  }
22
- else if (error instanceof Error) {
23
- message = error.message;
24
- }
25
25
  else {
26
- message = String(error);
26
+ message = errorMessage(error);
27
27
  }
28
28
  return { content: [{ type: "text", text: message }], isError: true };
29
29
  }
@@ -1,5 +1,5 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { ScreencastError } from "./errors.js";
@@ -262,6 +262,19 @@ export async function runFfmpeg(args, timeoutMs, opts = {}) {
262
262
  scripted.cleanup();
263
263
  }
264
264
  }
265
+ export async function probeDuration(path, opts = {}) {
266
+ if (!existsSync(path))
267
+ return null;
268
+ try {
269
+ const res = await runCapture(opts.ffprobe ?? requireFfmpeg().ffprobe, buildProbeArgs(path), 30_000);
270
+ if (res.code !== 0)
271
+ return null;
272
+ return parseMediaInfo(JSON.parse(res.stdout)).durationSec;
273
+ }
274
+ catch {
275
+ return null;
276
+ }
277
+ }
265
278
  export async function probeMedia(input) {
266
279
  const { ffprobe } = requireFfmpeg();
267
280
  const res = await runCapture(ffprobe, buildProbeArgs(input), 30_000);
@@ -1,7 +1,7 @@
1
1
  import { basename, dirname, extname, join } from "node:path";
2
2
  import { renameSync, rmSync } from "node:fs";
3
3
  import { ScreencastError } from "./errors.js";
4
- import { probeMedia, runFfmpeg } from "./ffmpeg.js";
4
+ import { runFfmpeg } from "./ffmpeg.js";
5
5
  export const JOB_TIMEOUT_ENV = "SCREENCAST_JOB_TIMEOUT_MS";
6
6
  export const BASE_TIMEOUT_MS = 10 * 60_000;
7
7
  export const UNKNOWN_DURATION_TIMEOUT_MS = 30 * 60_000;
@@ -126,11 +126,4 @@ export async function abortEditJobs(graceMs = 3_000) {
126
126
  }
127
127
  return jobs.length;
128
128
  }
129
- export async function probeDuration(input) {
130
- try {
131
- return (await probeMedia(input)).durationSec;
132
- }
133
- catch {
134
- return null;
135
- }
136
- }
129
+ export { probeDuration } from "./ffmpeg.js";
@@ -1,13 +1,12 @@
1
- import { existsSync, rmSync, writeFileSync } from "node:fs";
2
- import { requireFfmpeg, runCapture } from "./ffmpeg.js";
1
+ import { rmSync, writeFileSync } from "node:fs";
2
+ import { probeDuration, requireFfmpeg } from "./ffmpeg.js";
3
3
  import { finishReplay } from "./replay.js";
4
4
  import { whenFinalized } from "./events.js";
5
- import { buildProbeArgs, parseMediaInfo } from "./media.js";
6
- import { ScreencastError } from "./errors.js";
5
+ import { errorMessage, ScreencastError } from "./errors.js";
7
6
  import { wgcStopFile } from "./wgc.js";
8
7
  import { encoderArgs } from "./gpu.js";
9
8
  import { clearPausing, endSession, finishSegments, markPausing, pauseBlocker, recordedSec, segmentDurationSec, webcamOutputPath, } from "./pause.js";
10
- import { expectedImage, isAlive, isRecorderProcess, killPid, } from "./sessions.js";
9
+ import { isAlive, isOwnRecorder, killPid, } from "./sessions.js";
11
10
  async function waitForPidExit(pid, ms) {
12
11
  const deadline = Date.now() + ms;
13
12
  while (Date.now() < deadline && isAlive(pid)) {
@@ -25,19 +24,6 @@ export function waitForExit(child, ms) {
25
24
  });
26
25
  });
27
26
  }
28
- export async function probeDuration(ffprobe, path) {
29
- if (!existsSync(path))
30
- return null;
31
- try {
32
- const res = await runCapture(ffprobe, buildProbeArgs(path), 30_000);
33
- if (res.code !== 0)
34
- return null;
35
- return parseMediaInfo(JSON.parse(res.stdout)).durationSec;
36
- }
37
- catch {
38
- return null;
39
- }
40
- }
41
27
  async function quitChild(child, pid, gracefulMs) {
42
28
  if (!child.stdin || !child.stdin.writable)
43
29
  return false;
@@ -57,7 +43,7 @@ export async function finalParts(record, ffprobe) {
57
43
  return [];
58
44
  const parts = [...seg.parts];
59
45
  if (seg.current) {
60
- const probed = await probeDuration(ffprobe, seg.current.path);
46
+ const probed = await probeDuration(seg.current.path, { ffprobe });
61
47
  const endMs = record.stoppedAt ? Date.parse(record.stoppedAt) : Date.now();
62
48
  const durationSec = segmentDurationSec(seg.current.path, probed, seg.current.startMs, endMs) ?? 0;
63
49
  parts.push({ ...seg.current, durationSec });
@@ -158,7 +144,7 @@ export async function stopAll(store, probe, capMs = 10_000) {
158
144
  await stopSession(store, record, { reason: "shutdown", probe, gracefulMs: Math.min(8000, capMs) });
159
145
  }
160
146
  catch (err) {
161
- process.stderr.write(`Stopping ${id} on shutdown failed: ${err instanceof Error ? err.message : String(err)}\n`);
147
+ process.stderr.write(`Stopping ${id} on shutdown failed: ${errorMessage(err)}\n`);
162
148
  }
163
149
  });
164
150
  let timer;
@@ -186,17 +172,14 @@ async function runStop(store, record, opts) {
186
172
  try {
187
173
  let graceful = false;
188
174
  const child = store.getChild(record.id);
175
+ const stillRunning = (pid) => new ScreencastError(`Could not stop recording ${record.id}: its process (pid ${pid}) is still running.`);
189
176
  if (child && child.stdin && child.stdin.writable) {
190
- child.stdin.write("q\n");
191
- child.stdin.end();
192
- graceful = await waitForExit(child, opts.gracefulMs ?? 8000);
193
- if (!graceful && record.pid !== null) {
194
- killPid(record.pid);
195
- await waitForPidExit(record.pid, 2000);
196
- }
177
+ graceful = await quitChild(child, record.pid, opts.gracefulMs ?? 8000);
178
+ if (!graceful && record.pid !== null && isAlive(record.pid))
179
+ throw stillRunning(record.pid);
197
180
  }
198
181
  else if (record.pid !== null && isAlive(record.pid)) {
199
- if (isRecorderProcess(record.pid, expectedImage(record))) {
182
+ if (isOwnRecorder(record)) {
200
183
  if (stopFile) {
201
184
  writeFileSync(stopFile, "");
202
185
  await waitForPidExit(record.pid, opts.gracefulMs ?? 8000);
@@ -206,9 +189,8 @@ async function runStop(store, record, opts) {
206
189
  killPid(record.pid);
207
190
  await waitForPidExit(record.pid, 2000);
208
191
  }
209
- if (isAlive(record.pid)) {
210
- throw new ScreencastError(`Could not stop recording ${record.id}: its process (pid ${record.pid}) is still running.`);
211
- }
192
+ if (isAlive(record.pid))
193
+ throw stillRunning(record.pid);
212
194
  }
213
195
  }
214
196
  store.detachChild(record.id, child);
@@ -82,6 +82,12 @@ export function planFpsSampling(durationSec, fps, maxFrames) {
82
82
  const clampedFps = Math.max(1e-4, Math.floor((maxFrames / durationSec) * 10_000) / 10_000);
83
83
  return { fps: clampedFps, requestedFrames: requested, clamped: true };
84
84
  }
85
+ export function pickFramePrefix(existing, unique) {
86
+ for (const f of existing)
87
+ if (/^frame_\d+\.png$/i.test(f))
88
+ return `frame_${unique}_`;
89
+ return "frame_";
90
+ }
85
91
  export function buildSampleByFpsArgs(input, fps, outputPattern, maxFrames = DEFAULT_MAX_FRAMES, dedupe = false, range) {
86
92
  validatePositive(fps, "fps");
87
93
  const vf = dedupe ? `fps=${fps},mpdecimate` : `fps=${fps}`;
@@ -184,16 +190,17 @@ export function buildTrimArgs(input, output, opts) {
184
190
  args.push(...resolveQuality(DEFAULT_EDIT_QUALITY), "-c:a", "aac", output);
185
191
  return args;
186
192
  }
193
+ export function concatListContent(files) {
194
+ return files.map((p) => `file '${p.replace(/'/g, "'\\''")}'`).join("\n") + "\n";
195
+ }
187
196
  export function buildConcatListContent(inputs) {
188
197
  if (inputs.length < 2) {
189
198
  throw new ScreencastError("concat requires at least two input files.");
190
199
  }
191
- return (inputs
192
- .map((p) => `file '${p.replace(/'/g, "'\\''")}'`)
193
- .join("\n") + "\n");
200
+ return concatListContent(inputs);
194
201
  }
195
- export function buildConcatArgs(listFile, output) {
196
- return ["-y", "-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", output];
202
+ export function buildConcatArgs(listFile, output, opts = {}) {
203
+ return ["-y", ...(opts.quiet ? ["-v", "error"] : []), "-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", output];
197
204
  }
198
205
  export function hasHiddenFrames(info) {
199
206
  const { videoFrames: n, videoDurationSec: d, fps } = info;
@@ -3,7 +3,7 @@ import { randomBytes } from "node:crypto";
3
3
  import { rmSync, writeFileSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
- import { ScreencastError } from "./errors.js";
6
+ import { errorMessage, ScreencastError } from "./errors.js";
7
7
  export function parseMonitors(raw) {
8
8
  const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];
9
9
  const screens = arr.map((s) => ({
@@ -102,7 +102,7 @@ async function queryMonitors() {
102
102
  return parseMonitors(JSON.parse(stdout));
103
103
  }
104
104
  catch (err) {
105
- throw new ScreencastError(`Could not parse monitor geometry: ${err.message}`);
105
+ throw new ScreencastError(`Could not parse monitor geometry: ${errorMessage(err)}`);
106
106
  }
107
107
  }
108
108
  export function getMonitors(now = Date.now()) {
@@ -1,4 +1,4 @@
1
- import { ScreencastError } from "./errors.js";
1
+ import { errorMessage, ScreencastError } from "./errors.js";
2
2
  import { runPowerShell, psTimeoutMs } from "./monitors.js";
3
3
  import { audioCodecFor } from "./audio.js";
4
4
  import { isAudioOnlyPath } from "./media.js";
@@ -157,7 +157,7 @@ async function runTts(request, timeoutMs, signal) {
157
157
  return JSON.parse(stdout);
158
158
  }
159
159
  catch (err) {
160
- throw new ScreencastError(`Could not parse the speech engine's output: ${err.message}`);
160
+ throw new ScreencastError(`Could not parse the speech engine's output: ${errorMessage(err)}`);
161
161
  }
162
162
  }
163
163
  export async function listVoices(signal) {
@@ -174,7 +174,7 @@ export async function ttsStatus() {
174
174
  return { available: voices.length > 0, voices, ...(voices.length ? {} : { error: "No speech voices are installed." }) };
175
175
  }
176
176
  catch (err) {
177
- return { available: false, voices: [], error: err.message };
177
+ return { available: false, voices: [], error: errorMessage(err) };
178
178
  }
179
179
  }
180
180
  export async function synthesize(items, opts) {
package/dist/utils/ocr.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { runInNewContext } from "node:vm";
2
- import { ScreencastError } from "./errors.js";
2
+ import { errorMessage, ScreencastError } from "./errors.js";
3
3
  import { runPowerShell, psTimeoutMs } from "./monitors.js";
4
4
  export const OCR_SCALES = [2, 4];
5
5
  export const OCR_MAX_DIMENSION = 10_000;
@@ -21,7 +21,7 @@ export async function recognize(paths, scales) {
21
21
  raw = JSON.parse(stdout);
22
22
  }
23
23
  catch (err) {
24
- throw new ScreencastError(`Could not parse OCR output: ${err.message}`);
24
+ throw new ScreencastError(`Could not parse OCR output: ${errorMessage(err)}`);
25
25
  }
26
26
  const passes = Array.isArray(raw) ? raw : [raw];
27
27
  return passes.map((p, i) => parseOcrPass(p, scales[i] ?? 1));
@@ -102,7 +102,7 @@ export function regexRanges(texts, query, budgetMs = REGEX_BUDGET_MS) {
102
102
  new RegExp(query, "gi");
103
103
  }
104
104
  catch (err) {
105
- throw new ScreencastError(`Invalid regex: ${err.message}`);
105
+ throw new ScreencastError(`Invalid regex: ${errorMessage(err)}`);
106
106
  }
107
107
  try {
108
108
  return JSON.parse(runInNewContext(REGEX_SCAN, { texts, query }, { timeout: budgetMs }));
@@ -3,7 +3,7 @@ import { basename, dirname, extname, join } from "node:path";
3
3
  import { ScreencastError } from "./errors.js";
4
4
  import { runCapture } from "./ffmpeg.js";
5
5
  import { jobTimeoutMs } from "./jobs.js";
6
- import { concatList, buildReplayJoinArgs } from "./replay.js";
6
+ import { buildConcatArgs, concatListContent } from "./media.js";
7
7
  export const DEFAULT_WEBCAM_SIZE = 0.25;
8
8
  export function partsDir(output) {
9
9
  return `${output}.parts`;
@@ -148,8 +148,8 @@ export async function finishSegments(output, parts, opts) {
148
148
  mkdirSync(dir, { recursive: true });
149
149
  const list = join(dir, "segments.txt");
150
150
  const tmp = join(dir, `joined${extname(output) || ".mp4"}`);
151
- writeFileSync(list, concatList(video.map((p) => p.path)));
152
- const res = await runCapture(opts.ffmpeg, buildReplayJoinArgs(list, tmp), jobTimeoutMs(total));
151
+ writeFileSync(list, concatListContent(video.map((p) => p.path)));
152
+ const res = await runCapture(opts.ffmpeg, buildConcatArgs(list, tmp, { quiet: true }), jobTimeoutMs(total));
153
153
  if (res.code === 0 && existsSync(tmp)) {
154
154
  renameSync(tmp, output);
155
155
  result.joined = true;
@@ -1,11 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { mkdirSync, rmSync } from "node:fs";
3
- import { ScreencastError } from "./errors.js";
3
+ import { errorMessage, ScreencastError } from "./errors.js";
4
4
  import { logMessage, StderrWatch } from "./logging.js";
5
5
  import { parseCaptureStart, whenFinalized } from "./events.js";
6
6
  import { buildCaptureArgs } from "./targets.js";
7
- import { requireFfmpeg } from "./ffmpeg.js";
8
- import { joinSegments, probeDuration, withSessionOp } from "./lifecycle.js";
7
+ import { probeDuration, requireFfmpeg } from "./ffmpeg.js";
8
+ import { joinSegments, withSessionOp } from "./lifecycle.js";
9
9
  import { endSession, isPausing, partPath, partsDir, recordedSec, remainingCapSec, resumeBlocker, webcamPartPath, } from "./pause.js";
10
10
  import { classifyUnrequestedExit, killPid } from "./sessions.js";
11
11
  export function watchStderr(child, sessionId) {
@@ -86,7 +86,7 @@ export function attachExitHandler(store, id, child, opts) {
86
86
  });
87
87
  if (cur.segments && (cur.segments.parts.length > 0 || cur.webcam)) {
88
88
  void finalizeSegments(store, cur).catch((err) => {
89
- process.stderr.write(`Joining ${id}'s segments failed: ${err instanceof Error ? err.message : String(err)}\n`);
89
+ process.stderr.write(`Joining ${id}'s segments failed: ${errorMessage(err)}\n`);
90
90
  });
91
91
  }
92
92
  });
@@ -95,7 +95,7 @@ async function finalizeSegments(store, record) {
95
95
  const tools = requireFfmpeg();
96
96
  await whenFinalized(record.id);
97
97
  const { patch, error } = await joinSegments(record, tools);
98
- const durationSec = await probeDuration(tools.ffprobe, record.outputPath);
98
+ const durationSec = await probeDuration(record.outputPath, { ffprobe: tools.ffprobe });
99
99
  store.tryUpdate(record.id, { ...patch, durationSec: durationSec ?? undefined, ...(error ? { error } : {}) });
100
100
  }
101
101
  export function resumeSession(store, record, ffmpeg) {
@@ -151,6 +151,7 @@ async function runResume(store, record, ffmpeg) {
151
151
  updated = store.update(record.id, {
152
152
  status: "recording",
153
153
  pid: child.pid ?? null,
154
+ pidSpawnedAt: spawnedAt,
154
155
  videoStartMs: startMs - done * 1000,
155
156
  segments: {
156
157
  parts: seg.parts,
@@ -160,7 +161,7 @@ async function runResume(store, record, ffmpeg) {
160
161
  }
161
162
  catch (err) {
162
163
  abandon();
163
- throw new ScreencastError(`Resume stopped: the session registry could not be written (${err.message}).`);
164
+ throw new ScreencastError(`Resume stopped: the session registry could not be written (${errorMessage(err)}).`);
164
165
  }
165
166
  if (!updated) {
166
167
  abandon();
@@ -1,9 +1,9 @@
1
1
  import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { ScreencastError } from "./errors.js";
3
+ import { errorMessage, ScreencastError } from "./errors.js";
4
4
  import { runCapture } from "./ffmpeg.js";
5
5
  import { jobTimeoutMs } from "./jobs.js";
6
- import { buildProbeArgs, parseMediaInfo } from "./media.js";
6
+ import { buildConcatArgs, buildProbeArgs, concatListContent, parseMediaInfo } from "./media.js";
7
7
  import { homeRoot, rand, sequencePattern, stamp } from "./paths.js";
8
8
  import { resolveQuality } from "./targets.js";
9
9
  import { convertEvents, eventPaths, formatEventsJsonl, readRawEventLog, selectEvents, summarizeEvents, } from "./events.js";
@@ -86,12 +86,6 @@ export function liveSegmentFile(entries, wrap) {
86
86
  const index = last ? (last.index + 1) % wrap : 0;
87
87
  return `seg${String(index).padStart(5, "0")}.ts`;
88
88
  }
89
- export function concatList(files) {
90
- return files.map((p) => `file '${p.replace(/'/g, "'\\''")}'`).join("\n") + "\n";
91
- }
92
- export function buildReplayJoinArgs(listFile, output) {
93
- return ["-y", "-v", "error", "-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", output];
94
- }
95
89
  export function buildReplayCutArgs(input, output, opts) {
96
90
  const codec = opts.reencode
97
91
  ? [...resolveQuality(opts.quality ?? "standard"), ...(opts.audio ? ["-c:a", "aac", "-b:a", "160k"] : [])]
@@ -167,10 +161,10 @@ export async function saveReplay(buf, opts) {
167
161
  throw new ScreencastError("The replay buffer has no footage yet: the first segment is still being written. Try again in a couple of seconds.");
168
162
  }
169
163
  const listFile = join(snap, "join.txt");
170
- writeFileSync(listFile, concatList(files));
164
+ writeFileSync(listFile, concatListContent(files));
171
165
  const joined = join(snap, "joined.mp4");
172
166
  const timeout = jobTimeoutMs(opts.lastSec + 2 * buf.segmentSec);
173
- const join1 = await runCapture(opts.ffmpeg, buildReplayJoinArgs(listFile, joined), timeout, { signal: opts.signal });
167
+ const join1 = await runCapture(opts.ffmpeg, buildConcatArgs(listFile, joined, { quiet: true }), timeout, { signal: opts.signal });
174
168
  if (join1.code !== 0) {
175
169
  throw new ScreencastError(`Joining the replay segments failed:\n${join1.stderr.trim().split("\n").slice(-4).join("\n")}`);
176
170
  }
@@ -291,6 +285,6 @@ export async function finishReplay(buf, opts) {
291
285
  return { saved: true, discarded: discardReplay(buf), save };
292
286
  }
293
287
  catch (err) {
294
- return { saved: false, discarded: false, error: err instanceof Error ? err.message : String(err) };
288
+ return { saved: false, discarded: false, error: errorMessage(err) };
295
289
  }
296
290
  }
@@ -1,4 +1,4 @@
1
- import { readdirSync, rmdirSync, statSync, unlinkSync } from "node:fs";
1
+ import { readdir, rmdir, stat, unlink } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { homeRoot } from "./paths.js";
4
4
  export const RETENTION_ENV = "SCREENCAST_RETENTION_DAYS";
@@ -7,13 +7,13 @@ export function retentionDays(env = process.env) {
7
7
  return Number.isFinite(n) && n > 0 ? n : null;
8
8
  }
9
9
  const INDEX_FILE = /\.index\.json(\.\d+\.tmp)?$/;
10
- export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
10
+ export async function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
11
11
  const cutoff = now - days * 86_400_000;
12
12
  const result = { removed: 0, bytes: 0 };
13
- const prune = (dir, keep, recurse) => {
13
+ const prune = async (dir, keep, recurse) => {
14
14
  let names;
15
15
  try {
16
- names = readdirSync(dir);
16
+ names = await readdir(dir);
17
17
  }
18
18
  catch {
19
19
  return;
@@ -21,16 +21,16 @@ export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
21
21
  for (const name of names) {
22
22
  const path = join(dir, name);
23
23
  try {
24
- const st = statSync(path);
24
+ const st = await stat(path);
25
25
  if (st.isDirectory()) {
26
26
  if (!recurse)
27
27
  continue;
28
- prune(path, keep, true);
29
- if (readdirSync(path).length === 0 && st.mtimeMs < cutoff)
30
- rmdirSync(path);
28
+ await prune(path, keep, true);
29
+ if ((await readdir(path)).length === 0 && st.mtimeMs < cutoff)
30
+ await rmdir(path);
31
31
  }
32
32
  else if (!keep(name) && st.mtimeMs < cutoff) {
33
- unlinkSync(path);
33
+ await unlink(path);
34
34
  result.removed++;
35
35
  result.bytes += st.size;
36
36
  }
@@ -39,10 +39,10 @@ export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
39
39
  }
40
40
  }
41
41
  };
42
- prune(join(root, "screenshots"), () => false, true);
43
- prune(join(root, "frames"), () => false, true);
44
- prune(join(root, "recordings"), (name) => !/\.events\.raw(\.stop)?$/.test(name) && !INDEX_FILE.test(name), false);
45
- prune(join(root, "edits"), (name) => !INDEX_FILE.test(name), false);
46
- prune(join(root, "edits", "indexes"), (name) => !INDEX_FILE.test(name), false);
42
+ await prune(join(root, "screenshots"), () => false, true);
43
+ await prune(join(root, "frames"), () => false, true);
44
+ await prune(join(root, "recordings"), (name) => !/\.events\.raw(\.stop)?$/.test(name) && !INDEX_FILE.test(name), false);
45
+ await prune(join(root, "edits"), (name) => !INDEX_FILE.test(name), false);
46
+ await prune(join(root, "edits", "indexes"), (name) => !INDEX_FILE.test(name), false);
47
47
  return result;
48
48
  }
@@ -1,6 +1,7 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  import { RootsListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { setClientRoots } from "./paths.js";
4
+ import { errorMessage } from "./errors.js";
4
5
  export function rootDirs(roots) {
5
6
  const dirs = [];
6
7
  for (const { uri } of roots) {
@@ -30,7 +31,7 @@ export function trackClientRoots(server) {
30
31
  catch (err) {
31
32
  if (initial)
32
33
  setClientRoots([]);
33
- process.stderr.write(`roots/list failed: ${err instanceof Error ? err.message : String(err)}\n`);
34
+ process.stderr.write(`roots/list failed: ${errorMessage(err)}\n`);
34
35
  }
35
36
  };
36
37
  const previous = low.oninitialized;
@@ -1,7 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { readFileSync, writeFileSync, renameSync, existsSync, copyFileSync, openSync, closeSync, unlinkSync, statSync, linkSync, } from "node:fs";
3
3
  import { basename } from "node:path";
4
- import { ScreencastError } from "./errors.js";
4
+ import { errorMessage, ScreencastError } from "./errors.js";
5
5
  import { WGC_WINDOW_CLOSED_EXIT } from "./wgc.js";
6
6
  export const MAX_FINISHED_RECORDS = 100;
7
7
  export function isLive(status) {
@@ -23,6 +23,20 @@ export function isForeignLiveRecording(record, currentServerPid, ownerAlive) {
23
23
  record.serverPid !== currentServerPid &&
24
24
  ownerAlive);
25
25
  }
26
+ export function foreignStopRefusal(record, currentServerPid, ownerIsAlive) {
27
+ if (record.backend === "wgc" || !isForeignLiveRecording(record, currentServerPid, ownerIsAlive))
28
+ return null;
29
+ return (`Recording ${record.id} belongs to another running screencast-mcp instance (pid ${record.serverPid}). ` +
30
+ "Stop it from the client connected to that instance; closing that instance also finalizes it.");
31
+ }
32
+ export function ownerAlive(record, cache = new Map()) {
33
+ const pid = record.serverPid;
34
+ if (pid === undefined || pid === process.pid || !isAlive(pid))
35
+ return false;
36
+ if (!cache.has(pid))
37
+ cache.set(pid, processInfo(pid));
38
+ return isSameServer(record, cache.get(pid) ?? null);
39
+ }
26
40
  export function serverIdentity() {
27
41
  return {
28
42
  serverPid: process.pid,
@@ -82,6 +96,19 @@ export function isRecorderProcess(pid, image) {
82
96
  return false;
83
97
  return tasklistHasImage(res.stdout, image);
84
98
  }
99
+ export function isSameRecorder(record, running) {
100
+ if (!running)
101
+ return true;
102
+ if (running.image.toLowerCase() !== expectedImage(record).toLowerCase())
103
+ return false;
104
+ const ref = record.pidSpawnedAt;
105
+ return !(typeof ref === "number" && Number.isFinite(ref) && running.startMs > ref + OWNER_START_SLACK_MS);
106
+ }
107
+ export function isOwnRecorder(record) {
108
+ if (record.pid === null || !isRecorderProcess(record.pid, expectedImage(record)))
109
+ return false;
110
+ return record.pidSpawnedAt === undefined || isSameRecorder(record, processInfo(record.pid));
111
+ }
85
112
  export function classifyUnrequestedExit(opts) {
86
113
  const { code, backend, maxDurationSec, elapsedMs } = opts;
87
114
  if (backend === "wgc" && code === WGC_WINDOW_CLOSED_EXIT)
@@ -182,7 +209,7 @@ export function withRegistryLock(registry, fn, waitMs = LOCK_WAIT_MS) {
182
209
  const code = err.code;
183
210
  const busy = code === "EEXIST" || code === "EPERM" || code === "EACCES" || code === "EBUSY";
184
211
  if (!busy) {
185
- throw new ScreencastError(`Could not lock the session registry (${lock}): ${err.message}`);
212
+ throw new ScreencastError(`Could not lock the session registry (${lock}): ${errorMessage(err)}`);
186
213
  }
187
214
  if (code === "EEXIST") {
188
215
  let seen;
@@ -305,7 +332,7 @@ export class SessionStore {
305
332
  disk = withRegistryLock(this.path, read, this.lockWaitMs);
306
333
  }
307
334
  catch (err) {
308
- process.stderr.write(`${err.message} Reading the session registry without the lock.\n`);
335
+ process.stderr.write(`${errorMessage(err)} Reading the session registry without the lock.\n`);
309
336
  disk = read();
310
337
  }
311
338
  this.records = new Map(pruneRecords([...this.overlay(disk).values()]).map((r) => [r.id, r]));
@@ -367,7 +394,7 @@ export class SessionStore {
367
394
  return this.update(id, patch);
368
395
  }
369
396
  catch (err) {
370
- process.stderr.write(`Could not save session ${id}: ${err instanceof Error ? err.message : String(err)}\n`);
397
+ process.stderr.write(`Could not save session ${id}: ${errorMessage(err)}\n`);
371
398
  return undefined;
372
399
  }
373
400
  }
@@ -411,24 +438,16 @@ export class SessionStore {
411
438
  this.refresh();
412
439
  const reaped = [];
413
440
  const owners = new Map();
414
- const ownerAlive = (record) => {
415
- const pid = record.serverPid;
416
- if (pid === undefined || pid === process.pid || !isAlive(pid))
417
- return false;
418
- if (!owners.has(pid))
419
- owners.set(pid, processInfo(pid));
420
- return isSameServer(record, owners.get(pid) ?? null);
421
- };
422
441
  for (const record of this.records.values()) {
423
442
  if (!isLive(record.status))
424
443
  continue;
425
- if (isForeignLiveRecording(record, process.pid, ownerAlive(record))) {
444
+ if (isForeignLiveRecording(record, process.pid, ownerAlive(record, owners))) {
426
445
  continue;
427
446
  }
428
447
  const alive = isAlive(record.pid);
429
448
  const verdict = classifyOrphan(record, alive);
430
449
  if (verdict.reaped && record.pid !== null) {
431
- if (isRecorderProcess(record.pid, expectedImage(record)))
450
+ if (isOwnRecorder(record))
432
451
  killPid(record.pid);
433
452
  reaped.push(record.id);
434
453
  }
@@ -1,5 +1,6 @@
1
1
  import { virtualDesktopBounds } from "./targets.js";
2
2
  import { parseWindowSelector, selectWindow } from "./windows.js";
3
+ import { errorMessage } from "./errors.js";
3
4
  function windowTarget(w) {
4
5
  return w.hwnd !== undefined ? `window:hwnd=${w.hwnd}` : `window:${w.title}`;
5
6
  }
@@ -13,7 +14,7 @@ function resolves(query, w, allowCloaked) {
13
14
  return { ok: true };
14
15
  }
15
16
  catch (err) {
16
- return { ok: false, reason: firstSentence(err.message) };
17
+ return { ok: false, reason: firstSentence(errorMessage(err)) };
17
18
  }
18
19
  }
19
20
  export function buildTargetList(monitors, query, opts) {
package/dist/utils/wgc.js CHANGED
@@ -20,6 +20,33 @@ export function parseRawSize(stderr) {
20
20
  export function yuv420FrameBytes(width, height) {
21
21
  return (width * height * 3) / 2;
22
22
  }
23
+ export class FrameAssembler {
24
+ parts = [];
25
+ length = 0;
26
+ frameBytes = 0;
27
+ push(chunk) {
28
+ if (!chunk.length)
29
+ return;
30
+ this.parts.push(chunk);
31
+ this.length += chunk.length;
32
+ }
33
+ get buffered() {
34
+ return this.length;
35
+ }
36
+ take() {
37
+ const fb = this.frameBytes;
38
+ if (fb <= 0 || this.length < fb)
39
+ return null;
40
+ const frames = Math.floor(this.length / fb);
41
+ const all = this.parts.length === 1 && this.parts[0] ? this.parts[0] : Buffer.concat(this.parts, this.length);
42
+ const end = frames * fb;
43
+ const frame = all.subarray(end - fb, end);
44
+ const rest = this.length - end;
45
+ this.parts = rest ? [Buffer.from(all.subarray(end))] : [];
46
+ this.length = rest;
47
+ return frame;
48
+ }
49
+ }
23
50
  export function buildWgcEncodeArgs(width, height, cfg) {
24
51
  return [
25
52
  "-hide_banner", "-nostats", "-loglevel", "error", "-y",
@@ -1,4 +1,4 @@
1
- import { ScreencastError } from "./errors.js";
1
+ import { errorMessage, ScreencastError } from "./errors.js";
2
2
  import { runPowerShell } from "./monitors.js";
3
3
  export const MAX_CANDIDATES = 5;
4
4
  export function parseWindowSelector(wanted) {
@@ -180,7 +180,7 @@ export async function getRawWindows() {
180
180
  parsed = JSON.parse(stdout);
181
181
  }
182
182
  catch (err) {
183
- throw new ScreencastError(`Could not parse window geometry: ${err.message}`);
183
+ throw new ScreencastError(`Could not parse window geometry: ${errorMessage(err)}`);
184
184
  }
185
185
  const obj = parsed;
186
186
  const windows = Array.isArray(obj.windows) ? obj.windows : obj.windows ? [obj.windows] : [];
@@ -1,6 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { existsSync, rmSync } from "node:fs";
3
- import { buildWgcEncodeArgs, buildWgcGrabArgs, framesDue, parseRawSize, nudgeScript, startBanner, yuv420FrameBytes, wgcStopFile, WGC_WINDOW_CLOSED_EXIT, } from "./utils/wgc.js";
3
+ import { buildWgcEncodeArgs, buildWgcGrabArgs, FrameAssembler, framesDue, parseRawSize, nudgeScript, startBanner, yuv420FrameBytes, wgcStopFile, WGC_WINDOW_CLOSED_EXIT, } from "./utils/wgc.js";
4
4
  const FIRST_FRAME_TIMEOUT_MS = 10_000;
5
5
  const MAX_QUEUED_FRAMES = 4;
6
6
  const cfg = JSON.parse(process.argv[2] ?? "{}");
@@ -13,7 +13,7 @@ const nudge = spawn("powershell", ["-NoProfile", "-NonInteractive", "-Command",
13
13
  let grabErr = "";
14
14
  let size = null;
15
15
  let frameBytes = 0;
16
- let carry = Buffer.alloc(0);
16
+ const frames = new FrameAssembler();
17
17
  let latest = null;
18
18
  let encoder = null;
19
19
  let startedAt = 0;
@@ -41,13 +41,9 @@ function exitWith(code) {
41
41
  function drain() {
42
42
  if (!size || finishing)
43
43
  return;
44
- let off = 0;
45
- while (carry.length - off >= frameBytes) {
46
- latest = Buffer.from(carry.subarray(off, off + frameBytes));
47
- off += frameBytes;
48
- }
49
- if (off)
50
- carry = Buffer.from(carry.subarray(off));
44
+ const frame = frames.take();
45
+ if (frame)
46
+ latest = frame;
51
47
  if (latest && !encoder)
52
48
  begin();
53
49
  }
@@ -58,11 +54,12 @@ grab.stderr.on("data", (d) => {
58
54
  size = parseRawSize(grabErr);
59
55
  if (size) {
60
56
  frameBytes = yuv420FrameBytes(size.width, size.height);
57
+ frames.frameBytes = frameBytes;
61
58
  drain();
62
59
  }
63
60
  });
64
61
  grab.stdout.on("data", (chunk) => {
65
- carry = carry.length ? Buffer.concat([carry, chunk]) : chunk;
62
+ frames.push(chunk);
66
63
  drain();
67
64
  });
68
65
  function begin() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tmhs/screencast-mcp",
3
- "version": "0.48.1",
3
+ "version": "0.48.2",
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",
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "scripts": {
21
21
  "build": "tsc",
22
- "typecheck": "tsc --noEmit && tsc -p src/__tests__",
22
+ "typecheck": "tsc --noEmit && tsc -p src/__tests__ && tsc -p evals/tsconfig.json",
23
23
  "lint": "eslint .",
24
24
  "dev": "tsx watch src/index.ts",
25
25
  "start": "node dist/index.js",