@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
@@ -0,0 +1,119 @@
1
+ import { z } from "zod";
2
+ import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { errorMessage, errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
5
+ import { DELETES_FILE, looseOutput } from "../utils/toolSpec.js";
6
+ import { getStore } from "../context.js";
7
+ import { isLive } from "../utils/sessions.js";
8
+ import { samePath } from "../utils/recordingIndex.js";
9
+ import { assertDeleteAllowed, recordingSidecars } from "../utils/recordingFiles.js";
10
+ import { subdir } from "../utils/paths.js";
11
+ import { CONFIRM_TIMEOUT_MS, confirmCaptureEnabled, CONFIRM_CAPTURE_ENV } from "../utils/consent.js";
12
+ const inputSchema = {
13
+ sessionId: z.string().min(1).optional().describe("Session id of the recording to delete."),
14
+ input: z.string().min(1).optional().describe("Or the recording's path."),
15
+ };
16
+ function sizeOf(path) {
17
+ try {
18
+ const st = statSync(path);
19
+ if (!st.isDirectory())
20
+ return st.size;
21
+ return readdirSync(path).reduce((n, name) => n + sizeOf(resolve(path, name)), 0);
22
+ }
23
+ catch {
24
+ return 0;
25
+ }
26
+ }
27
+ async function confirmDelete(server, message, signal) {
28
+ if (!server.server.getClientCapabilities()?.elicitation?.form) {
29
+ if (confirmCaptureEnabled()) {
30
+ throw new ScreencastError(`Not deleted: ${CONFIRM_CAPTURE_ENV} requires the user to confirm, but this client does not support MCP elicitation.`);
31
+ }
32
+ return false;
33
+ }
34
+ let action;
35
+ try {
36
+ ({ action } = await server.server.elicitInput({ message, requestedSchema: { type: "object", properties: {} } }, { signal, timeout: CONFIRM_TIMEOUT_MS }));
37
+ }
38
+ catch (err) {
39
+ throw new ScreencastError(`Not deleted: the confirmation request failed (${errorMessage(err)}).`);
40
+ }
41
+ if (action !== "accept")
42
+ throw new ScreencastError(`Not deleted: ${action === "decline" ? "declined" : "cancelled"} by the user.`);
43
+ return true;
44
+ }
45
+ export function register(server) {
46
+ server.registerTool("delete_recording", {
47
+ title: "Delete Recording",
48
+ description: "Delete a finished recording with its sidecars (event log, webcam, transcript, index, markers, pause parts) " +
49
+ "and registry entries; reports bytes freed. Asks the user first when the client supports it. Edits made from it are kept.",
50
+ inputSchema,
51
+ outputSchema: looseOutput({
52
+ outputPath: z.string(),
53
+ deleted: z.array(z.string()),
54
+ bytesFreed: z.number(),
55
+ sessionsRemoved: z.array(z.string()),
56
+ }),
57
+ annotations: DELETES_FILE,
58
+ }, async (args, extra) => {
59
+ try {
60
+ if (!!args.sessionId === !!args.input)
61
+ throw new ScreencastError("Give exactly one of sessionId or input.");
62
+ const store = getStore();
63
+ let video;
64
+ if (args.sessionId) {
65
+ const record = store.get(args.sessionId);
66
+ if (!record)
67
+ throw new ScreencastError(`No session with id "${args.sessionId}".`);
68
+ video = record.outputPath;
69
+ }
70
+ else {
71
+ video = resolve(args.input);
72
+ }
73
+ assertDeleteAllowed(video);
74
+ const sessions = store.list().filter((r) => samePath(r.outputPath, video));
75
+ const live = sessions.find((r) => isLive(r.status));
76
+ if (live)
77
+ throw new ScreencastError(`Recording ${live.id} is still ${live.status}; stop it first.`);
78
+ let siblings = [];
79
+ try {
80
+ siblings = readdirSync(dirname(video));
81
+ }
82
+ catch {
83
+ }
84
+ const side = recordingSidecars(video, siblings, subdir("edits"));
85
+ const targets = [video, ...side.files, ...side.dirs].filter((p) => existsSync(p));
86
+ if (targets.length === 0 && sessions.length === 0)
87
+ throw new ScreencastError(`Nothing to delete: ${video} does not exist.`);
88
+ const asked = await confirmDelete(server, `Delete ${video} and ${targets.length - (existsSync(video) ? 1 : 0)} sidecar file(s)? This cannot be undone.`, extra.signal);
89
+ let bytesFreed = 0;
90
+ const deleted = [];
91
+ const failed = [];
92
+ for (const p of targets) {
93
+ const size = sizeOf(p);
94
+ try {
95
+ rmSync(p, { recursive: true, force: true });
96
+ deleted.push(p);
97
+ bytesFreed += size;
98
+ }
99
+ catch (err) {
100
+ failed.push(`${p}: ${errorMessage(err)}`);
101
+ }
102
+ }
103
+ const removedIds = existsSync(video) ? [] : sessions.map((r) => r.id);
104
+ if (removedIds.length > 0)
105
+ store.remove(removedIds);
106
+ return okResponse({
107
+ outputPath: video,
108
+ deleted,
109
+ bytesFreed,
110
+ sessionsRemoved: removedIds,
111
+ confirmedByUser: asked,
112
+ ...(failed.length > 0 ? { failed, note: "Some files could not be deleted (in use?); the registry entry was kept if the recording remains." } : {}),
113
+ });
114
+ }
115
+ catch (error) {
116
+ return errorResponse(error);
117
+ }
118
+ });
119
+ }
@@ -13,6 +13,7 @@ import { parseEventsJsonl } from "../utils/events.js";
13
13
  import { resolveWhisperModel, buildTranscribeArgs, parseSrt, normalizeCues } from "../utils/captions.js";
14
14
  import { subdir, tempPath } from "../utils/paths.js";
15
15
  import { DEFAULT_INDEX_FRAMES, DEFAULT_INDEX_THRESHOLD, INDEX_VERSION, MAX_INDEX_FRAMES, attach, canReuseIndex, cueTexts, defaultTranscriptPath, eventTexts, fingerprintFile, findIndex, indexMatchesVideo, indexWritePath, keyframeTime, legacyIndexSidecarPath, markerTexts, maskSegmentText, mergeSegments, planKeyframes, readIndex, resolveRecording, segmentsFrom, writeIndex, } from "../utils/recordingIndex.js";
16
+ import { mapPool } from "../utils/pool.js";
16
17
  const OCR_BATCH = 8;
17
18
  const inputSchema = {
18
19
  input: z.string().optional().describe("Recording path."),
@@ -79,14 +80,13 @@ export function register(server) {
79
80
  for (let b = 0; b < spans.length; b += OCR_BATCH) {
80
81
  extra.signal.throwIfAborted();
81
82
  const batch = spans.slice(b, b + OCR_BATCH);
82
- const frames = [];
83
- for (const [i, span] of batch.entries()) {
83
+ const grabbed = await mapPool(batch, async (span, i) => {
84
84
  const out = join(work, `key_${b + i}.png`);
85
85
  await runFfmpeg(buildSampleAtTimestampArgs(source.path, keyframeTime(span), out), 60_000, { signal: extra.signal });
86
- if (existsSync(out))
87
- frames.push({ at: b + i, path: out });
88
- }
89
- const read = frames.length > 0 ? await readFrames(frames.map((f) => f.path), work, extra.signal) : [];
86
+ return { at: b + i, path: out };
87
+ });
88
+ const frames = grabbed.filter((f) => existsSync(f.path));
89
+ const read = frames.length > 0 ? await readFrames(frames.map((f) => f.path), work, extra.signal, { sameSize: true }) : [];
90
90
  read.forEach((f, i) => (texts[frames[i].at] = f.lines.map((l) => l.text)));
91
91
  framesRead += read.length;
92
92
  report?.(0.1 + (0.85 * Math.min(spans.length, b + OCR_BATCH)) / spans.length);
@@ -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",
@@ -4,7 +4,7 @@ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
4
  import { OUTPUT_PATH, WRITES_FILE } from "../utils/toolSpec.js";
5
5
  import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
6
6
  import { runEditJob } from "../utils/jobs.js";
7
- import { buildRedactArgs, editOutputExt, assertEditContainer } from "../utils/media.js";
7
+ import { buildRedactArgs, stillEdit } from "../utils/media.js";
8
8
  import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
9
9
  export const redactRegionSchema = z.object({
10
10
  x: z.number().int().nonnegative(),
@@ -15,7 +15,7 @@ export const redactRegionSchema = z.object({
15
15
  end: z.number().positive().optional(),
16
16
  });
17
17
  const inputSchema = {
18
- input: z.string().min(1).describe("Path to the source video."),
18
+ input: z.string().min(1).describe("Path to the source video or image (png/jpg; time ranges are ignored for an image)."),
19
19
  regions: z
20
20
  .array(redactRegionSchema)
21
21
  .min(1)
@@ -37,7 +37,7 @@ const inputSchema = {
37
37
  export function register(server) {
38
38
  server.registerTool("redact_region", {
39
39
  title: "Redact Regions",
40
- description: "Cover given rectangles in a video (e.g. secrets on screen). Not automatic detection: find " +
40
+ description: "Cover given rectangles in a video or screenshot (e.g. secrets on screen). Not automatic detection: find " +
41
41
  "them with find_text redact: true. Off-frame regions are rejected.",
42
42
  inputSchema,
43
43
  outputSchema: OUTPUT_PATH,
@@ -49,15 +49,14 @@ export function register(server) {
49
49
  throw new ScreencastError(`Input file not found: ${args.input}`);
50
50
  }
51
51
  const { width, height, durationSec } = await probeMedia(args.input);
52
- assertEditContainer(args.output);
53
- const ext = editOutputExt(args.input);
52
+ const { still, ext } = stillEdit(args.input, args.output);
54
53
  const output = resolveOutput(args.output, subdir("edits"), `redact-${stamp()}-${rand()}${ext}`, args.overwrite);
55
54
  const ffArgs = buildRedactArgs(args.input, output, args.regions, {
56
55
  style: args.style,
57
56
  pad: args.pad,
58
57
  color: args.color,
59
- }, { width, height });
60
- await runEditJob(ffArgs, { output, durationSec, extra });
58
+ }, { width, height }, still);
59
+ await runEditJob(ffArgs, { output, durationSec: still ? null : durationSec, extra });
61
60
  return okResponse({
62
61
  outputPath: output,
63
62
  regions: args.regions.length,
@@ -5,9 +5,10 @@ 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
+ import { mapPool } from "../utils/pool.js";
11
12
  const inputSchema = {
12
13
  input: z.string().min(1).describe("Path to the source video file."),
13
14
  mode: z
@@ -117,24 +118,27 @@ export function register(server) {
117
118
  if (plan) {
118
119
  const isPng = (f) => f.endsWith(".png");
119
120
  const before = new Set(readdirSync(dir).filter(isPng));
120
- const pattern = sequencePattern(dir, "frame_%05d.png");
121
+ const prefix = pickFramePrefix(before, `${stamp()}-${rand()}`);
122
+ const pattern = sequencePattern(dir, `${prefix}%05d.png`);
121
123
  await runFfmpeg(buildSampleByFpsArgs(args.input, plan.fps, pattern, maxFrames, args.dedupe === true), jobTimeoutMs(durationSec), { signal: extra.signal });
122
124
  frames = readdirSync(dir)
123
- .filter(isPng)
124
- .filter((f) => !before.has(f))
125
+ .filter((f) => isPng(f) && f.startsWith(prefix) && !before.has(f))
125
126
  .sort()
126
127
  .map((f) => join(dir, f));
127
128
  }
128
129
  else {
129
130
  const ts = mode === "scenes" ? sceneTimes : args.timestamps;
130
- for (const [i, t] of ts.entries()) {
131
+ const outs = await mapPool(ts, async (t, i) => {
131
132
  const out = join(dir, `frame_${String(i).padStart(3, "0")}_${t}s.png`);
132
133
  rmSync(out, { force: true });
133
134
  await runFfmpeg(buildSampleAtTimestampArgs(args.input, t, out), 60_000, { signal: extra.signal });
135
+ return out;
136
+ });
137
+ for (const [i, out] of outs.entries()) {
134
138
  if (existsSync(out))
135
139
  frames.push(out);
136
140
  else
137
- skipped.push(t);
141
+ skipped.push(ts[i]);
138
142
  }
139
143
  }
140
144
  const inline = args.returnImages === false
@@ -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
  }
@@ -15,6 +15,7 @@ import { DEFAULT_SECRET_PATTERN } from "../utils/bugReport.js";
15
15
  import { resolveOutputDir, subdir, stamp, rand } from "../utils/paths.js";
16
16
  import { GUIDE_FILES, HTML_IMAGE_LADDER, HTML_MAX_BYTES, MAX_GUIDE_STEPS, assignSections, base64Bytes, buildHtmlImageArgs, buildGuideHtml, buildGuideMarkdown, buildStepFrameArgs, buildStepShotArgs, caption, guideSteps, htmlImageName, labelAt, nextHtmlRung, shotFilter, } from "../utils/stepGuide.js";
17
17
  import { resolveSource } from "./bugReport.js";
18
+ import { mapPool } from "../utils/pool.js";
18
19
  const OCR_BATCH = 10;
19
20
  const HTML_SAMPLE = 5;
20
21
  const inputSchema = {
@@ -84,18 +85,17 @@ export function register(server) {
84
85
  const total = shots.length * (useOcr ? 3 : 2) || 1;
85
86
  let done = 0;
86
87
  const tick = () => progress?.(++done / total);
87
- const frames = [];
88
- for (const { s } of shots) {
88
+ const frames = await mapPool(shots, async ({ s }) => {
89
89
  const out = join(work, `frame-${String(s.n).padStart(3, "0")}.png`);
90
90
  await runFfmpeg(buildStepFrameArgs(source.path, s.shotT, out), 60_000, { signal: extra.signal });
91
- frames.push(out);
92
91
  tick();
93
- }
92
+ return out;
93
+ });
94
94
  const read = frames.map(() => null);
95
95
  if (useOcr) {
96
96
  for (let b = 0; b < frames.length; b += OCR_BATCH) {
97
97
  extra.signal.throwIfAborted();
98
- const batch = await readFrames(frames.slice(b, b + OCR_BATCH), work, extra.signal);
98
+ const batch = await readFrames(frames.slice(b, b + OCR_BATCH), work, extra.signal, { sameSize: true });
99
99
  batch.forEach((f, k) => {
100
100
  read[b + k] = f;
101
101
  tick();
@@ -121,18 +121,22 @@ export function register(server) {
121
121
  }
122
122
  mkdirSync(imageDir, { recursive: true });
123
123
  let redactions = 0;
124
- for (const [k, { i }] of shots.entries()) {
124
+ const frameSize = { width: info.width, height: info.height };
125
+ const rendered = await mapPool(shots, async ({ i }, k) => {
125
126
  const step = steps[i];
126
127
  const file = GUIDE_FILES.image(step.n);
127
128
  const ring = step.x !== undefined && step.y !== undefined ? { x: step.x, y: step.y } : undefined;
128
- const filter = shotFilter({ width: info.width, height: info.height }, { click: ring, boxes: boxes[k] });
129
+ const filter = shotFilter(frameSize, { click: ring, boxes: boxes[k] });
129
130
  const out = join(imageDir, file);
130
131
  await runFfmpeg(buildStepShotArgs(frames[k], filter, out), 60_000, { signal: extra.signal });
132
+ tick();
133
+ return { step, file, out };
134
+ });
135
+ for (const [k, { step, file, out }] of rendered.entries()) {
131
136
  if (wantMd)
132
137
  written.push(out);
133
138
  step.image = file;
134
139
  redactions += boxes[k].length;
135
- tick();
136
140
  }
137
141
  const stepsNote = all.length === 0 ? "The event log has no clicks, shortcuts, typing, or scrolls." : undefined;
138
142
  const data = {
@@ -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({
@@ -4,7 +4,8 @@ import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
4
4
  import { requireFfmpeg, runFfmpeg, runFfmpegBuffer } from "../utils/ffmpeg.js";
5
5
  import { resolveCaptureTarget } from "../utils/resolveTarget.js";
6
6
  import { buildScreenshotArgs } from "../utils/targets.js";
7
- import { detectionSize, targetSize, diffFrames, buildRawGrabArgs, SettleTracker, targetDiffOptions, DEFAULT_PIXEL_THRESHOLD, } from "../utils/diff.js";
7
+ import { detectionSize, targetSize, buildRawGrabArgs, targetDiffOptions, DEFAULT_PIXEL_THRESHOLD, } from "../utils/diff.js";
8
+ import { waitLoop } from "../utils/waitLoop.js";
8
9
  import { windowMatchReport } from "../utils/windows.js";
9
10
  import { confirmCapture, describeTarget } from "../utils/consent.js";
10
11
  import { subdir, stamp, rand } from "../utils/paths.js";
@@ -55,7 +56,6 @@ const inputSchema = {
55
56
  .optional()
56
57
  .describe("Keep the final screenshot on disk and return its path (default false)."),
57
58
  };
58
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
59
59
  export function register(server) {
60
60
  server.registerTool("wait_for_change", {
61
61
  title: "Wait for Screen Change",
@@ -83,49 +83,17 @@ export function register(server) {
83
83
  const size = detectionSize(area.width, area.height);
84
84
  const grab = () => runFfmpegBuffer(buildRawGrabArgs(target, monitors, size), 15_000, { signal: extra.signal });
85
85
  const opts = targetDiffOptions(area, size, args.pixelThreshold);
86
- const started = Date.now();
87
- const baseline = await grab();
88
- const settle = new SettleTracker(baseline, size.width, size.height, opts);
89
- let lastChangeAt = started;
90
- let everChanged = false;
91
- let regions = [];
92
- let outcome = "timeout";
93
- while (Date.now() - started < timeoutMs) {
94
- if (extra.signal.aborted) {
95
- outcome = "cancelled";
96
- break;
97
- }
98
- await sleep(interval);
99
- const current = await grab().catch((error) => {
100
- if (extra.signal.aborted)
101
- return null;
102
- throw error;
103
- });
104
- if (!current) {
105
- outcome = "cancelled";
106
- break;
107
- }
108
- if (mode === "change") {
109
- const d = diffFrames(baseline, current, size.width, size.height, opts);
110
- if (d.regions.length > 0) {
111
- regions = d.regions;
112
- outcome = "changed";
113
- break;
114
- }
115
- }
116
- else {
117
- const changed = settle.push(current);
118
- if (changed.length > 0) {
119
- everChanged = true;
120
- lastChangeAt = Date.now();
121
- regions = changed;
122
- }
123
- else if (Date.now() - lastChangeAt >= settleMs) {
124
- outcome = "settled";
125
- break;
126
- }
127
- }
128
- }
86
+ const { outcome, regions, everChanged, startedAt: started } = await waitLoop({
87
+ grab,
88
+ mode,
89
+ width: size.width,
90
+ height: size.height,
91
+ diff: opts,
92
+ timeoutMs,
93
+ settleMs,
94
+ intervalMs: interval,
95
+ signal: extra.signal,
96
+ });
129
97
  const result = {
130
98
  outcome,
131
99
  mode,
@@ -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);
@@ -73,8 +73,12 @@ export function calloutSteps(items, assets, input, firstInput, tag) {
73
73
  });
74
74
  return { steps, out: cur, extraInputs };
75
75
  }
76
- export function buildCalloutArgs(input, output, items, assets, quality = "standard") {
77
- const { steps, out, extraInputs } = calloutSteps(items, assets, "[0:v]", 1, "");
76
+ export function buildCalloutArgs(input, output, items, assets, quality = "standard", still = false) {
77
+ const drawn = still ? items.map(({ from: _f, to: _t, ...c }) => c) : items;
78
+ const { steps, out, extraInputs } = calloutSteps(drawn, assets, "[0:v]", 1, "");
79
+ if (still) {
80
+ return ["-y", "-i", input, ...extraInputs, "-filter_complex", steps.join(";"), "-map", out, "-frames:v", "1", ...stillOutput(output)];
81
+ }
78
82
  return [
79
83
  "-y", "-i", input, ...extraInputs,
80
84
  "-filter_complex", steps.join(";"),
@@ -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);
@@ -2,6 +2,7 @@ import { readFileSync, rmSync } from "node:fs";
2
2
  import { ScreencastError } from "./errors.js";
3
3
  import { runFfmpeg } from "./ffmpeg.js";
4
4
  import { tempPath, stillOutput } from "./paths.js";
5
+ import { mapPool } from "./pool.js";
5
6
  export const DEFAULT_MAX_IMAGE_WIDTH = 1280;
6
7
  export const DEFAULT_MAX_INLINE_IMAGES = 8;
7
8
  export const MAX_INLINE_IMAGES = 20;
@@ -23,16 +24,15 @@ export function clampInlineCount(requested) {
23
24
  }
24
25
  export async function encodeInlineImages(paths, maxWidth = DEFAULT_MAX_IMAGE_WIDTH, maxCount = DEFAULT_MAX_INLINE_IMAGES) {
25
26
  const chosen = paths.slice(0, maxCount);
26
- const images = [];
27
- for (const path of chosen) {
27
+ const images = await mapPool(chosen, async (path) => {
28
28
  const tmp = tempPath(".jpg");
29
29
  try {
30
30
  await runFfmpeg(buildPreviewArgs(path, tmp, maxWidth), 30_000);
31
- images.push({ type: "image", data: readFileSync(tmp).toString("base64"), mimeType: "image/jpeg" });
31
+ return { type: "image", data: readFileSync(tmp).toString("base64"), mimeType: "image/jpeg" };
32
32
  }
33
33
  finally {
34
34
  rmSync(tmp, { force: true });
35
35
  }
36
- }
36
+ });
37
37
  return { images, omitted: paths.length - chosen.length };
38
38
  }