@tmhs/screencast-mcp 0.48.0 → 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.
@@ -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,8 +96,18 @@ export function isRecorderProcess(pid, image) {
82
96
  return false;
83
97
  return tasklistHasImage(res.stdout, image);
84
98
  }
85
- export function isFfmpegProcess(pid) {
86
- return isRecorderProcess(pid, "ffmpeg.exe");
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));
87
111
  }
88
112
  export function classifyUnrequestedExit(opts) {
89
113
  const { code, backend, maxDurationSec, elapsedMs } = opts;
@@ -185,7 +209,7 @@ export function withRegistryLock(registry, fn, waitMs = LOCK_WAIT_MS) {
185
209
  const code = err.code;
186
210
  const busy = code === "EEXIST" || code === "EPERM" || code === "EACCES" || code === "EBUSY";
187
211
  if (!busy) {
188
- 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)}`);
189
213
  }
190
214
  if (code === "EEXIST") {
191
215
  let seen;
@@ -308,7 +332,7 @@ export class SessionStore {
308
332
  disk = withRegistryLock(this.path, read, this.lockWaitMs);
309
333
  }
310
334
  catch (err) {
311
- 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`);
312
336
  disk = read();
313
337
  }
314
338
  this.records = new Map(pruneRecords([...this.overlay(disk).values()]).map((r) => [r.id, r]));
@@ -370,7 +394,7 @@ export class SessionStore {
370
394
  return this.update(id, patch);
371
395
  }
372
396
  catch (err) {
373
- 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`);
374
398
  return undefined;
375
399
  }
376
400
  }
@@ -414,24 +438,16 @@ export class SessionStore {
414
438
  this.refresh();
415
439
  const reaped = [];
416
440
  const owners = new Map();
417
- const ownerAlive = (record) => {
418
- const pid = record.serverPid;
419
- if (pid === undefined || pid === process.pid || !isAlive(pid))
420
- return false;
421
- if (!owners.has(pid))
422
- owners.set(pid, processInfo(pid));
423
- return isSameServer(record, owners.get(pid) ?? null);
424
- };
425
441
  for (const record of this.records.values()) {
426
442
  if (!isLive(record.status))
427
443
  continue;
428
- if (isForeignLiveRecording(record, process.pid, ownerAlive(record))) {
444
+ if (isForeignLiveRecording(record, process.pid, ownerAlive(record, owners))) {
429
445
  continue;
430
446
  }
431
447
  const alive = isAlive(record.pid);
432
448
  const verdict = classifyOrphan(record, alive);
433
449
  if (verdict.reaped && record.pid !== null) {
434
- if (isRecorderProcess(record.pid, expectedImage(record)))
450
+ if (isOwnRecorder(record))
435
451
  killPid(record.pid);
436
452
  reaped.push(record.id);
437
453
  }
@@ -10,10 +10,10 @@ export function evenTimes(durationSec, count) {
10
10
  return Array.from({ length: count }, (_, i) => Math.round(((i + 0.5) * durationSec) / count * 1000) / 1000);
11
11
  }
12
12
  export function formatTimecode(sec) {
13
- const s = Math.max(0, sec);
14
- const h = Math.floor(s / 3600);
15
- const m = Math.floor((s % 3600) / 60);
16
- const rest = s % 60;
13
+ const tenths = Math.round(Math.max(0, sec) * 10);
14
+ const h = Math.floor(tenths / 36000);
15
+ const m = Math.floor((tenths % 36000) / 600);
16
+ const rest = (tenths % 600) / 10;
17
17
  if (h > 0)
18
18
  return `${h}:${String(m).padStart(2, "0")}:${String(Math.floor(rest)).padStart(2, "0")}`;
19
19
  return `${m}:${rest.toFixed(1).padStart(4, "0")}`;
@@ -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] : [];