@tmhs/screencast-mcp 0.48.1 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +12 -9
  2. package/dist/cli.js +8 -7
  3. package/dist/context.js +33 -0
  4. package/dist/index.js +42 -27
  5. package/dist/resources.js +26 -0
  6. package/dist/server.js +2 -0
  7. package/dist/setup.js +7 -6
  8. package/dist/tools/addMarker.js +2 -2
  9. package/dist/tools/callout.js +6 -7
  10. package/dist/tools/contactSheet.js +3 -2
  11. package/dist/tools/deleteRecording.js +119 -0
  12. package/dist/tools/indexRecording.js +6 -6
  13. package/dist/tools/pauseRecording.js +3 -3
  14. package/dist/tools/redactRegion.js +6 -7
  15. package/dist/tools/sampleFrames.js +10 -6
  16. package/dist/tools/startRecording.js +11 -5
  17. package/dist/tools/stepGuide.js +12 -8
  18. package/dist/tools/stopRecording.js +7 -3
  19. package/dist/tools/waitForChange.js +13 -45
  20. package/dist/utils/audioDevices.js +2 -2
  21. package/dist/utils/callout.js +6 -2
  22. package/dist/utils/capabilities.js +2 -1
  23. package/dist/utils/consent.js +2 -2
  24. package/dist/utils/errors.js +4 -4
  25. package/dist/utils/ffmpeg.js +14 -1
  26. package/dist/utils/images.js +4 -4
  27. package/dist/utils/jobs.js +2 -9
  28. package/dist/utils/lifecycle.js +13 -31
  29. package/dist/utils/media.js +29 -8
  30. package/dist/utils/monitors.js +2 -2
  31. package/dist/utils/narrate.js +3 -3
  32. package/dist/utils/ocr.js +3 -3
  33. package/dist/utils/ocrScan.js +33 -19
  34. package/dist/utils/paths.js +3 -0
  35. package/dist/utils/pause.js +3 -3
  36. package/dist/utils/pool.js +29 -0
  37. package/dist/utils/recorder.js +7 -6
  38. package/dist/utils/recordingFiles.js +32 -0
  39. package/dist/utils/replay.js +21 -34
  40. package/dist/utils/retention.js +14 -14
  41. package/dist/utils/roots.js +2 -1
  42. package/dist/utils/sessions.js +58 -14
  43. package/dist/utils/targetList.js +2 -1
  44. package/dist/utils/toolSpec.js +6 -0
  45. package/dist/utils/toolsets.js +1 -0
  46. package/dist/utils/waitLoop.js +50 -0
  47. package/dist/utils/wgc.js +27 -0
  48. package/dist/utils/windows.js +2 -2
  49. package/dist/wgcRecorder.js +7 -10
  50. package/package.json +2 -2
@@ -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);
@@ -2,7 +2,7 @@ import { extname } from "node:path";
2
2
  import { ScreencastError } from "./errors.js";
3
3
  import { resolveQuality } from "./targets.js";
4
4
  import { validateColor, validateEvenDimension } from "./validate.js";
5
- import { stillOutput } from "./paths.js";
5
+ import { isStillImage, stillOutput } from "./paths.js";
6
6
  const DEFAULT_EDIT_QUALITY = "standard";
7
7
  function numberOrNull(v) {
8
8
  if (v === undefined)
@@ -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;
@@ -535,8 +542,22 @@ export function redactSteps(regions, opts, dims, input, tag) {
535
542
  });
536
543
  return { steps, out: `[${tag}out]` };
537
544
  }
538
- export function buildRedactArgs(input, output, regions, opts = {}, dims) {
539
- const { steps, out } = redactSteps(regions, opts, dims, "[0:v]", "");
545
+ export function stillEdit(input, output) {
546
+ if (!isStillImage(input)) {
547
+ assertEditContainer(output);
548
+ return { still: false, ext: editOutputExt(input) };
549
+ }
550
+ if (output && !isStillImage(output)) {
551
+ throw new ScreencastError("An image input writes an image: give the output a .png or .jpg extension.");
552
+ }
553
+ return { still: true, ext: /\.jpe?g$/i.test(input) ? extname(input).toLowerCase() : ".png" };
554
+ }
555
+ export function buildRedactArgs(input, output, regions, opts = {}, dims, still = false) {
556
+ const rs = still ? regions.map(({ start: _s, end: _e, ...r }) => r) : regions;
557
+ const { steps, out } = redactSteps(rs, opts, dims, "[0:v]", "");
558
+ if (still) {
559
+ return ["-y", "-i", input, "-filter_complex", steps.join(";"), "-map", out, "-frames:v", "1", ...stillOutput(output)];
560
+ }
540
561
  const [chain] = steps;
541
562
  if ((opts.style ?? "box") === "box" && chain !== undefined) {
542
563
  const vf = chain.slice("[0:v]".length, -out.length);
@@ -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 }));
@@ -5,27 +5,41 @@ import { probeMedia, runFfmpeg } from "./ffmpeg.js";
5
5
  import { jobTimeoutMs } from "./jobs.js";
6
6
  import { buildSampleByFpsArgs, planFpsSampling } from "./media.js";
7
7
  import { recognize, mergePasses, findMatches, redactionRects, passScales } from "./ocr.js";
8
- export async function readFrames(sources, work, signal) {
9
- const sized = await Promise.all(sources.map(async (source) => {
8
+ import { mapPool } from "./pool.js";
9
+ export function buildOcrPassArgs(source, scales, outputs) {
10
+ if (scales.length === 0 || scales.length !== outputs.length) {
11
+ throw new ScreencastError("Each OCR pass needs one output.");
12
+ }
13
+ const scale = (s) => `scale=iw*${s}:ih*${s}:flags=lanczos`;
14
+ const png = ["-compression_level", "0"];
15
+ if (scales.length === 1)
16
+ return ["-y", "-v", "error", "-i", source, "-vf", scale(scales[0]), ...png, outputs[0]];
17
+ const labels = scales.map((_s, i) => `[s${i}]`);
18
+ const graph = [`[0:v]split=${scales.length}${labels.join("")}`, ...scales.map((s, i) => `${labels[i]}${scale(s)}[o${i}]`)].join(";");
19
+ return [
20
+ "-y", "-v", "error", "-i", source, "-filter_complex", graph,
21
+ ...outputs.flatMap((out, i) => ["-map", `[o${i}]`, ...png, out]),
22
+ ];
23
+ }
24
+ export async function readFrames(sources, work, signal, opts = {}) {
25
+ const sizeOf = async (source) => {
10
26
  const { width, height } = await probeMedia(source);
11
27
  if (!width || !height)
12
28
  throw new ScreencastError("Could not read the image size.");
13
- return { source, width, height };
14
- }));
15
- const passes = [];
16
- const passScaleList = [];
17
- const owner = [];
18
- for (const [f, { source, width, height }] of sized.entries()) {
19
- for (const [i, scale] of passScales(width, height).entries()) {
20
- const out = join(work, `pass${f}-${i}.png`);
21
- await runFfmpeg(["-y", "-v", "error", "-i", source, "-vf", `scale=iw*${scale}:ih*${scale}:flags=lanczos`, out], 60_000, {
22
- signal,
23
- });
24
- passes.push(out);
25
- passScaleList.push(scale);
26
- owner.push(f);
27
- }
28
- }
29
+ return { width, height };
30
+ };
31
+ const shared = opts.sameSize && sources[0] ? await sizeOf(sources[0]) : null;
32
+ const sized = await mapPool(sources, async (source) => ({ source, ...(shared ?? (await sizeOf(source))) }));
33
+ const perFrame = await mapPool(sized, async ({ source, width, height }, f) => {
34
+ const scales = passScales(width, height);
35
+ const outs = scales.map((_s, i) => join(work, `pass${f}-${i}.png`));
36
+ await runFfmpeg(buildOcrPassArgs(source, scales, outs), 60_000, { signal });
37
+ return scales.map((scale, i) => ({ out: outs[i], scale, f }));
38
+ });
39
+ const flat = perFrame.flat();
40
+ const passes = flat.map((p) => p.out);
41
+ const passScaleList = flat.map((p) => p.scale);
42
+ const owner = flat.map((p) => p.f);
29
43
  const results = await recognize(passes, passScaleList);
30
44
  return sized.map(({ width, height }, f) => ({
31
45
  lines: mergePasses(results.filter((_r, i) => owner[i] === f)),
@@ -45,7 +59,7 @@ export async function scanVideoFrames(input, opts, work, signal) {
45
59
  const step = 1 / plan.fps;
46
60
  const timeAt = (i) => Math.round(i * step * 1000) / 1000;
47
61
  const end = length ?? timeAt(paths.length - 1) + step;
48
- const read = await readFrames(paths, work, signal);
62
+ const read = await readFrames(paths, work, signal, { sameSize: true });
49
63
  return {
50
64
  frames: read.map((frame, i) => ({ ...frame, t: timeAt(i), path: paths[i] ?? "" })),
51
65
  step,
@@ -30,6 +30,9 @@ export function sequencePattern(dir, name) {
30
30
  return join(dir.replace(/%/g, "%%"), name);
31
31
  }
32
32
  const STILL_IMAGE = /\.(png|jpe?g|bmp|tiff?)$/i;
33
+ export function isStillImage(path) {
34
+ return STILL_IMAGE.test(path);
35
+ }
33
36
  export function stillOutput(output) {
34
37
  return STILL_IMAGE.test(output) ? ["-update", "1", output] : [output];
35
38
  }
@@ -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;
@@ -0,0 +1,29 @@
1
+ import { availableParallelism } from "node:os";
2
+ export function frameConcurrency(cores = availableParallelism()) {
3
+ return Math.min(4, Math.max(2, Math.floor(cores / 4)));
4
+ }
5
+ export async function mapPool(items, fn, limit = frameConcurrency()) {
6
+ const results = new Array(items.length);
7
+ let next = 0;
8
+ let failed = false;
9
+ let error;
10
+ const worker = async () => {
11
+ while (!failed && next < items.length) {
12
+ const i = next++;
13
+ try {
14
+ results[i] = await fn(items[i], i);
15
+ }
16
+ catch (err) {
17
+ if (!failed) {
18
+ failed = true;
19
+ error = err;
20
+ }
21
+ }
22
+ }
23
+ };
24
+ const n = Math.max(1, Math.min(Math.floor(limit), items.length));
25
+ await Promise.all(Array.from({ length: n }, worker));
26
+ if (failed)
27
+ throw error;
28
+ return results;
29
+ }
@@ -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();
@@ -0,0 +1,32 @@
1
+ import { basename } from "node:path";
2
+ import { markersPath } from "./chapters.js";
3
+ import { eventPaths } from "./events.js";
4
+ import { partsDir, webcamOutputPath } from "./pause.js";
5
+ import { allowedOutputDirs, assertLocalPath, homeRoot, isWithin } from "./paths.js";
6
+ import { ScreencastError } from "./errors.js";
7
+ import { defaultTranscriptPath, fallbackIndexPath, indexSidecarPath } from "./recordingIndex.js";
8
+ import { wgcStopFile } from "./wgc.js";
9
+ export function recordingSidecars(video, siblings, editsDir) {
10
+ const events = eventPaths(video);
11
+ const transcript = defaultTranscriptPath(video, siblings);
12
+ const files = [
13
+ events.jsonl,
14
+ events.raw,
15
+ `${events.raw}.stop`,
16
+ webcamOutputPath(video),
17
+ indexSidecarPath(video),
18
+ fallbackIndexPath(video, editsDir),
19
+ markersPath(video),
20
+ wgcStopFile(video),
21
+ ...(transcript.path && !transcript.ambiguous ? [transcript.path] : []),
22
+ ];
23
+ return { files: [...new Set(files)].filter((f) => basename(f) !== basename(video)), dirs: [partsDir(video)] };
24
+ }
25
+ export function assertDeleteAllowed(path) {
26
+ assertLocalPath(path, "Recording");
27
+ const dirs = [homeRoot(), ...(allowedOutputDirs() ?? [])];
28
+ if (dirs.some((d) => isWithin(path, d)))
29
+ return;
30
+ throw new ScreencastError(`Recording ${path} is outside SCREENCAST_HOME and the allowed directories, so it is not deleted. ` +
31
+ "Add its folder to SCREENCAST_ALLOWED_DIRS or the client's workspace roots, or delete it yourself.");
32
+ }
@@ -1,9 +1,11 @@
1
- import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, writeFileSync } from "node:fs";
1
+ import { createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { stat, writeFile } from "node:fs/promises";
3
+ import { pipeline } from "node:stream/promises";
2
4
  import { join } from "node:path";
3
- import { ScreencastError } from "./errors.js";
5
+ import { errorMessage, ScreencastError } from "./errors.js";
4
6
  import { runCapture } from "./ffmpeg.js";
5
7
  import { jobTimeoutMs } from "./jobs.js";
6
- import { buildProbeArgs, parseMediaInfo } from "./media.js";
8
+ import { buildConcatArgs, buildProbeArgs, concatListContent, parseMediaInfo } from "./media.js";
7
9
  import { homeRoot, rand, sequencePattern, stamp } from "./paths.js";
8
10
  import { resolveQuality } from "./targets.js";
9
11
  import { convertEvents, eventPaths, formatEventsJsonl, readRawEventLog, selectEvents, summarizeEvents, } from "./events.js";
@@ -86,12 +88,6 @@ export function liveSegmentFile(entries, wrap) {
86
88
  const index = last ? (last.index + 1) % wrap : 0;
87
89
  return `seg${String(index).padStart(5, "0")}.ts`;
88
90
  }
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
91
  export function buildReplayCutArgs(input, output, opts) {
96
92
  const codec = opts.reencode
97
93
  ? [...resolveQuality(opts.quality ?? "standard"), ...(opts.audio ? ["-c:a", "aac", "-b:a", "160k"] : [])]
@@ -109,24 +105,14 @@ export function sliceEvents(events, from, to) {
109
105
  return selectEvents(events, { from, to }).map((e) => ({ ...e, t: round3(e.t - from) }));
110
106
  }
111
107
  const round3 = (n) => Math.round(n * 1000) / 1000;
112
- function copyShared(src, dst) {
113
- const fd = openSync(src, "r");
114
- try {
115
- const size = statSync(src).size;
116
- const buf = Buffer.alloc(size);
117
- let read = 0;
118
- while (read < size) {
119
- const n = readSync(fd, buf, read, size - read, read);
120
- if (n === 0)
121
- break;
122
- read += n;
123
- }
124
- writeFileSync(dst, buf.subarray(0, read));
125
- return read;
126
- }
127
- finally {
128
- closeSync(fd);
108
+ export async function copyShared(src, dst, signal) {
109
+ const size = (await stat(src)).size;
110
+ if (size === 0) {
111
+ await writeFile(dst, "");
112
+ return 0;
129
113
  }
114
+ await pipeline(createReadStream(src, { start: 0, end: size - 1 }), createWriteStream(dst), { signal });
115
+ return (await stat(dst)).size;
130
116
  }
131
117
  async function probeStart(ffprobe, path, signal) {
132
118
  const res = await runCapture(ffprobe, ["-v", "error", "-show_entries", "format=start_time", "-of", "csv=p=0", path], 15_000, { signal });
@@ -142,16 +128,17 @@ export async function saveReplay(buf, opts) {
142
128
  const picked = pickSegments(entries, opts.lastSec);
143
129
  const snap = mkdtempSync(join(buf.dir, "save-"));
144
130
  try {
145
- const files = picked.map((e, i) => {
131
+ const files = [];
132
+ for (const [i, e] of picked.entries()) {
146
133
  const dst = join(snap, `${String(i).padStart(5, "0")}.ts`);
147
- copyShared(join(buf.dir, e.file), dst);
148
- return dst;
149
- });
134
+ await copyShared(join(buf.dir, e.file), dst, opts.signal);
135
+ files.push(dst);
136
+ }
150
137
  let includesLive = false;
151
138
  if (opts.live !== false) {
152
139
  const src = join(buf.dir, liveSegmentFile(entries, buf.wrap));
153
140
  const dst = join(snap, "live.ts");
154
- if (existsSync(src) && copyShared(src, dst) > 0) {
141
+ if (existsSync(src) && (await copyShared(src, dst, opts.signal)) > 0) {
155
142
  const newest = files.at(-1);
156
143
  const [liveStart, lastStart] = await Promise.all([
157
144
  probeStart(opts.ffprobe, dst, opts.signal),
@@ -167,10 +154,10 @@ export async function saveReplay(buf, opts) {
167
154
  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
155
  }
169
156
  const listFile = join(snap, "join.txt");
170
- writeFileSync(listFile, concatList(files));
157
+ writeFileSync(listFile, concatListContent(files));
171
158
  const joined = join(snap, "joined.mp4");
172
159
  const timeout = jobTimeoutMs(opts.lastSec + 2 * buf.segmentSec);
173
- const join1 = await runCapture(opts.ffmpeg, buildReplayJoinArgs(listFile, joined), timeout, { signal: opts.signal });
160
+ const join1 = await runCapture(opts.ffmpeg, buildConcatArgs(listFile, joined, { quiet: true }), timeout, { signal: opts.signal });
174
161
  if (join1.code !== 0) {
175
162
  throw new ScreencastError(`Joining the replay segments failed:\n${join1.stderr.trim().split("\n").slice(-4).join("\n")}`);
176
163
  }
@@ -291,6 +278,6 @@ export async function finishReplay(buf, opts) {
291
278
  return { saved: true, discarded: discardReplay(buf), save };
292
279
  }
293
280
  catch (err) {
294
- return { saved: false, discarded: false, error: err instanceof Error ? err.message : String(err) };
281
+ return { saved: false, discarded: false, error: errorMessage(err) };
295
282
  }
296
283
  }
@@ -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;