@tmhs/screencast-mcp 0.48.2 → 0.49.1

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 (47) hide show
  1. package/README.md +8 -7
  2. package/dist/resources.js +26 -0
  3. package/dist/server.js +2 -0
  4. package/dist/tools/backdrop.js +1 -11
  5. package/dist/tools/bugReport.js +5 -28
  6. package/dist/tools/burnSubtitles.js +2 -2
  7. package/dist/tools/callout.js +7 -49
  8. package/dist/tools/contactSheet.js +3 -24
  9. package/dist/tools/cursor.js +2 -22
  10. package/dist/tools/deleteRecording.js +119 -0
  11. package/dist/tools/denoise.js +2 -2
  12. package/dist/tools/findText.js +1 -3
  13. package/dist/tools/indexRecording.js +6 -6
  14. package/dist/tools/keystrokeOverlay.js +3 -44
  15. package/dist/tools/normalizeAudio.js +3 -4
  16. package/dist/tools/pipeline.js +16 -19
  17. package/dist/tools/redactRegion.js +7 -16
  18. package/dist/tools/reframe.js +3 -3
  19. package/dist/tools/sampleFrames.js +6 -2
  20. package/dist/tools/stepGuide.js +13 -10
  21. package/dist/tools/titleCard.js +1 -1
  22. package/dist/tools/waitForChange.js +28 -46
  23. package/dist/tools/zoom.js +3 -18
  24. package/dist/utils/audio.js +4 -0
  25. package/dist/utils/backdrop.js +12 -1
  26. package/dist/utils/bugReport.js +23 -0
  27. package/dist/utils/callout.js +48 -2
  28. package/dist/utils/captions.js +1 -0
  29. package/dist/utils/cursor.js +22 -1
  30. package/dist/utils/diff.js +6 -4
  31. package/dist/utils/frameQueue.js +50 -0
  32. package/dist/utils/images.js +4 -4
  33. package/dist/utils/keystrokes.js +44 -1
  34. package/dist/utils/media.js +27 -3
  35. package/dist/utils/ocrScan.js +35 -19
  36. package/dist/utils/paths.js +3 -0
  37. package/dist/utils/pool.js +29 -0
  38. package/dist/utils/produce.js +2 -0
  39. package/dist/utils/recordingFiles.js +32 -0
  40. package/dist/utils/replay.js +16 -23
  41. package/dist/utils/sessions.js +25 -0
  42. package/dist/utils/sheet.js +25 -2
  43. package/dist/utils/toolSpec.js +6 -0
  44. package/dist/utils/toolsets.js +1 -0
  45. package/dist/utils/waitLoop.js +50 -0
  46. package/dist/utils/zoom.js +18 -0
  47. package/package.json +1 -1
@@ -1,9 +1,11 @@
1
1
  import { fileURLToPath } from "node:url";
2
2
  import { ScreencastError } from "./errors.js";
3
3
  import { escapeFilterPath } from "./fonts.js";
4
- import { MOVE_SAMPLE_MS } from "./events.js";
4
+ import { MOVE_SAMPLE_MS, eventPaths, parseEventsJsonl } from "./events.js";
5
5
  import { mapTime, mapWindow } from "./timeline.js";
6
6
  import { resolveQuality } from "./targets.js";
7
+ import { z } from "zod";
8
+ import { existsSync, readFileSync } from "node:fs";
7
9
  export const CURSOR_SPRITE = { w: 114, h: 168, hotX: 9, hotY: 9, arrowH: 135 };
8
10
  export function cursorSpritePath() {
9
11
  return fileURLToPath(new URL("../../assets/cursor/arrow.png", import.meta.url));
@@ -315,3 +317,22 @@ export function buildCursorArgs(input, output, plan, style, frame, sprite, comma
315
317
  commands,
316
318
  };
317
319
  }
320
+ export const cursorOptionsSchema = {
321
+ events: z.string().optional(),
322
+ size: z.number().min(0.25).max(8).optional(),
323
+ smoothing: z.number().min(0).max(1).optional(),
324
+ hideAfterSec: z.number().min(0).max(600).optional(),
325
+ clicks: z.boolean().optional(),
326
+ spotlight: z.boolean().optional(),
327
+ };
328
+ export function loadCursor(input, events, opts, endSec) {
329
+ const path = events ?? eventPaths(input).jsonl;
330
+ if (!existsSync(path)) {
331
+ throw new ScreencastError(`No event log for ${input} (looked for ${path}). Record with start_recording cursor: "events" ` +
332
+ "(no OS cursor in the video, events logged), or pass events: <path to .events.jsonl>.");
333
+ }
334
+ const plan = planCursor(parseEventsJsonl(readFileSync(path, "utf8")), opts, endSec);
335
+ if (plan.path.length === 0)
336
+ throw new ScreencastError(`The event log ${path} has no cursor positions to draw.`);
337
+ return plan;
338
+ }
@@ -1,5 +1,5 @@
1
1
  import { ScreencastError } from "./errors.js";
2
- import { targetInputArgs, SCREENSHOT_GRAB_FPS } from "./targets.js";
2
+ import { targetInputArgs } from "./targets.js";
3
3
  import { stillOutput } from "./paths.js";
4
4
  export const ANALYSIS_WIDTH = 320;
5
5
  export const SOURCE_PX_PER_ANALYSIS_PX = 4;
@@ -161,12 +161,14 @@ export function buildRawFrameArgs(input, size) {
161
161
  "-f", "rawvideo", "-",
162
162
  ];
163
163
  }
164
- export function buildRawGrabArgs(target, monitors, size) {
164
+ export function buildRawStreamArgs(target, monitors, size, fps) {
165
165
  return [
166
- "-v", "error", "-f", "gdigrab", "-framerate", String(SCREENSHOT_GRAB_FPS),
166
+ "-v", "error",
167
+ "-probesize", "32", "-analyzeduration", "0",
168
+ "-f", "gdigrab", "-framerate", String(Math.round(fps * 1000) / 1000),
167
169
  ...targetInputArgs(target, monitors),
168
- "-frames:v", "1",
169
170
  "-vf", `scale=${size.width}:${size.height}:flags=area,format=gray`,
171
+ "-flush_packets", "1",
170
172
  "-f", "rawvideo", "-",
171
173
  ];
172
174
  }
@@ -0,0 +1,50 @@
1
+ import { ScreencastError } from "./errors.js";
2
+ export class FrameQueue {
3
+ waiters = [];
4
+ error = null;
5
+ ended = false;
6
+ push(frame) {
7
+ const waiting = this.waiters;
8
+ this.waiters = [];
9
+ for (const w of waiting)
10
+ w.resolve(frame);
11
+ }
12
+ fail(error) {
13
+ if (this.error === null)
14
+ this.error = error;
15
+ this.rejectAll(this.error);
16
+ }
17
+ end() {
18
+ this.ended = true;
19
+ this.rejectAll(new ScreencastError("The screen capture ended unexpectedly."));
20
+ }
21
+ next(timeoutMs) {
22
+ if (this.error !== null)
23
+ return Promise.reject(this.error);
24
+ if (this.ended)
25
+ return Promise.reject(new ScreencastError("The screen capture ended unexpectedly."));
26
+ return new Promise((resolve, reject) => {
27
+ const timer = setTimeout(() => {
28
+ this.waiters = this.waiters.filter((w) => w !== waiter);
29
+ reject(new ScreencastError(`No frame from the screen capture within ${Math.round(timeoutMs / 1000)}s.`));
30
+ }, timeoutMs);
31
+ const waiter = {
32
+ resolve: (f) => {
33
+ clearTimeout(timer);
34
+ resolve(f);
35
+ },
36
+ reject: (e) => {
37
+ clearTimeout(timer);
38
+ reject(e);
39
+ },
40
+ };
41
+ this.waiters.push(waiter);
42
+ });
43
+ }
44
+ rejectAll(error) {
45
+ const waiting = this.waiters;
46
+ this.waiters = [];
47
+ for (const w of waiting)
48
+ w.reject(error);
49
+ }
50
+ }
@@ -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
  }
@@ -1,9 +1,13 @@
1
1
  import { ScreencastError } from "./errors.js";
2
- import { escapeFilterPath } from "./fonts.js";
2
+ import { escapeFilterPath, resolveTextFont } from "./fonts.js";
3
3
  import { sumExpr } from "./expr.js";
4
4
  import { resolveQuality } from "./targets.js";
5
5
  import { validateColor } from "./validate.js";
6
6
  import { mapWindow } from "./timeline.js";
7
+ import { z } from "zod";
8
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { eventPaths, parseEventsJsonl } from "./events.js";
7
11
  export const BADGE_POSITIONS = ["bottom", "bottom-left", "bottom-right", "top", "top-left", "top-right"];
8
12
  export const DEFAULT_LINGER_SEC = 1.2;
9
13
  export const DOUBLE_CLICK_SEC = 0.5;
@@ -153,3 +157,42 @@ export function buildKeystrokeArgs(input, output, groups, assets, style, frame,
153
157
  output,
154
158
  ];
155
159
  }
160
+ export const keystrokeOptionsSchema = {
161
+ events: z.string().optional(),
162
+ clicks: z.boolean().optional(),
163
+ typing: z.boolean().optional(),
164
+ keys: z.enum(["shortcuts", "masked"]).optional(),
165
+ lingerSec: z.number().positive().max(10).optional(),
166
+ position: z.enum(BADGE_POSITIONS).optional(),
167
+ size: z.number().min(8).max(400).optional(),
168
+ color: z.string().optional(),
169
+ fontFile: z.string().min(1).optional(),
170
+ };
171
+ export function loadBadges(input, events, opts) {
172
+ const path = events ?? eventPaths(input).jsonl;
173
+ if (!existsSync(path)) {
174
+ throw new ScreencastError(`No event log for ${input} (looked for ${path}). Record with start_recording events: true ` +
175
+ '(keys: "shortcuts" to name shortcuts), or pass events: <path to .events.jsonl>.');
176
+ }
177
+ const log = parseEventsJsonl(readFileSync(path, "utf8"));
178
+ return { badges: planBadges(log, opts), shortcutsLogged: log.filter((e) => e.type === "key").length, path };
179
+ }
180
+ export function prepareKeystrokeAssets(labels, workDir, tag = "", fontFile) {
181
+ const font = resolveTextFont(labels.join(" "), { weight: "bold", fontFile });
182
+ const textFiles = {};
183
+ labels.forEach((label, i) => {
184
+ if (workDir === null) {
185
+ textFiles[label] = `<badge ${i}>`;
186
+ return;
187
+ }
188
+ const f = join(workDir, `${tag}badge_${i}.txt`);
189
+ writeFileSync(f, label);
190
+ textFiles[label] = f;
191
+ });
192
+ return {
193
+ fontFile: font.fontFile,
194
+ textFiles,
195
+ ...(font.fallback && { fallbackFont: font.fontFile }),
196
+ warnings: font.warning ? [font.warning] : [],
197
+ };
198
+ }
@@ -2,7 +2,8 @@ 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
+ import { z } from "zod";
6
7
  const DEFAULT_EDIT_QUALITY = "standard";
7
8
  function numberOrNull(v) {
8
9
  if (v === undefined)
@@ -463,6 +464,7 @@ export function buildClipArgs(input, output, seg, quality = DEFAULT_EDIT_QUALITY
463
464
  output,
464
465
  ];
465
466
  }
467
+ export const REDACT_STYLES = ["box", "blur", "pixelate"];
466
468
  function normalizeRegions(regions, pad, dims) {
467
469
  return regions.map((r, i) => {
468
470
  const x0 = requireNonNegativeInt(r.x, `region[${i}] x`);
@@ -542,8 +544,22 @@ export function redactSteps(regions, opts, dims, input, tag) {
542
544
  });
543
545
  return { steps, out: `[${tag}out]` };
544
546
  }
545
- export function buildRedactArgs(input, output, regions, opts = {}, dims) {
546
- const { steps, out } = redactSteps(regions, opts, dims, "[0:v]", "");
547
+ export function stillEdit(input, output) {
548
+ if (!isStillImage(input)) {
549
+ assertEditContainer(output);
550
+ return { still: false, ext: editOutputExt(input) };
551
+ }
552
+ if (output && !isStillImage(output)) {
553
+ throw new ScreencastError("An image input writes an image: give the output a .png or .jpg extension.");
554
+ }
555
+ return { still: true, ext: /\.jpe?g$/i.test(input) ? extname(input).toLowerCase() : ".png" };
556
+ }
557
+ export function buildRedactArgs(input, output, regions, opts = {}, dims, still = false) {
558
+ const rs = still ? regions.map(({ start: _s, end: _e, ...r }) => r) : regions;
559
+ const { steps, out } = redactSteps(rs, opts, dims, "[0:v]", "");
560
+ if (still) {
561
+ return ["-y", "-i", input, "-filter_complex", steps.join(";"), "-map", out, "-frames:v", "1", ...stillOutput(output)];
562
+ }
547
563
  const [chain] = steps;
548
564
  if ((opts.style ?? "box") === "box" && chain !== undefined) {
549
565
  const vf = chain.slice("[0:v]".length, -out.length);
@@ -558,3 +574,11 @@ export function buildRedactArgs(input, output, regions, opts = {}, dims) {
558
574
  output,
559
575
  ];
560
576
  }
577
+ export const redactRegionSchema = z.object({
578
+ x: z.number().int().nonnegative(),
579
+ y: z.number().int().nonnegative(),
580
+ width: z.number().int().positive(),
581
+ height: z.number().int().positive(),
582
+ start: z.number().nonnegative().optional(),
583
+ end: z.number().positive().optional(),
584
+ });
@@ -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,
@@ -75,3 +89,5 @@ export function scanMatches(scan, query, regex, scope = "match") {
75
89
  }
76
90
  return { matches, redactRegions };
77
91
  }
92
+ export const DEFAULT_SCAN_FRAMES = 30;
93
+ export const MAX_SCAN_FRAMES = 120;
@@ -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
  }
@@ -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
+ }
@@ -215,6 +215,8 @@ export function buildMusicBedArgs(video, music, output, videoDuration, hasVideoA
215
215
  output,
216
216
  ];
217
217
  }
218
+ export const ASPECTS = ["16:9", "9:16", "1:1", "4:5"];
219
+ export const REFRAME_FITS = ["pad", "crop"];
218
220
  export const ASPECT_DIMS = {
219
221
  "16:9": { w: 1920, h: 1080 },
220
222
  "9:16": { w: 1080, h: 1920 },
@@ -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,4 +1,6 @@
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
5
  import { errorMessage, ScreencastError } from "./errors.js";
4
6
  import { runCapture } from "./ffmpeg.js";
@@ -103,24 +105,14 @@ export function sliceEvents(events, from, to) {
103
105
  return selectEvents(events, { from, to }).map((e) => ({ ...e, t: round3(e.t - from) }));
104
106
  }
105
107
  const round3 = (n) => Math.round(n * 1000) / 1000;
106
- function copyShared(src, dst) {
107
- const fd = openSync(src, "r");
108
- try {
109
- const size = statSync(src).size;
110
- const buf = Buffer.alloc(size);
111
- let read = 0;
112
- while (read < size) {
113
- const n = readSync(fd, buf, read, size - read, read);
114
- if (n === 0)
115
- break;
116
- read += n;
117
- }
118
- writeFileSync(dst, buf.subarray(0, read));
119
- return read;
120
- }
121
- finally {
122
- 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;
123
113
  }
114
+ await pipeline(createReadStream(src, { start: 0, end: size - 1 }), createWriteStream(dst), { signal });
115
+ return (await stat(dst)).size;
124
116
  }
125
117
  async function probeStart(ffprobe, path, signal) {
126
118
  const res = await runCapture(ffprobe, ["-v", "error", "-show_entries", "format=start_time", "-of", "csv=p=0", path], 15_000, { signal });
@@ -136,16 +128,17 @@ export async function saveReplay(buf, opts) {
136
128
  const picked = pickSegments(entries, opts.lastSec);
137
129
  const snap = mkdtempSync(join(buf.dir, "save-"));
138
130
  try {
139
- const files = picked.map((e, i) => {
131
+ const files = [];
132
+ for (const [i, e] of picked.entries()) {
140
133
  const dst = join(snap, `${String(i).padStart(5, "0")}.ts`);
141
- copyShared(join(buf.dir, e.file), dst);
142
- return dst;
143
- });
134
+ await copyShared(join(buf.dir, e.file), dst, opts.signal);
135
+ files.push(dst);
136
+ }
144
137
  let includesLive = false;
145
138
  if (opts.live !== false) {
146
139
  const src = join(buf.dir, liveSegmentFile(entries, buf.wrap));
147
140
  const dst = join(snap, "live.ts");
148
- if (existsSync(src) && copyShared(src, dst) > 0) {
141
+ if (existsSync(src) && (await copyShared(src, dst, opts.signal)) > 0) {
149
142
  const newest = files.at(-1);
150
143
  const [liveStart, lastStart] = await Promise.all([
151
144
  probeStart(opts.ffprobe, dst, opts.signal),
@@ -259,6 +259,7 @@ export class SessionStore {
259
259
  lockWaitMs;
260
260
  records = new Map();
261
261
  pending = new Map();
262
+ removed = new Set();
262
263
  seen = null;
263
264
  children = new Map();
264
265
  stopping = new Set();
@@ -305,6 +306,8 @@ export class SessionStore {
305
306
  if (base)
306
307
  disk.set(id, { ...base, ...patch });
307
308
  }
309
+ for (const id of this.removed)
310
+ disk.delete(id);
308
311
  return disk;
309
312
  }
310
313
  refresh() {
@@ -346,6 +349,7 @@ export class SessionStore {
346
349
  this.seen = this.signature();
347
350
  this.records = new Map(pruned.map((r) => [r.id, r]));
348
351
  this.pending.clear();
352
+ this.removed.clear();
349
353
  }, this.lockWaitMs);
350
354
  for (const cb of this.listeners) {
351
355
  try {
@@ -367,6 +371,27 @@ export class SessionStore {
367
371
  throw err;
368
372
  }
369
373
  }
374
+ remove(ids) {
375
+ const before = ids.flatMap((id) => {
376
+ const r = this.records.get(id);
377
+ return r ? [r] : [];
378
+ });
379
+ for (const id of ids) {
380
+ this.removed.add(id);
381
+ this.pending.delete(id);
382
+ this.records.delete(id);
383
+ }
384
+ try {
385
+ this.persist();
386
+ }
387
+ catch (err) {
388
+ for (const id of ids)
389
+ this.removed.delete(id);
390
+ for (const r of before)
391
+ this.records.set(r.id, r);
392
+ throw err;
393
+ }
394
+ }
370
395
  get(id) {
371
396
  this.refresh();
372
397
  return this.records.get(id);
@@ -1,6 +1,11 @@
1
1
  import { ScreencastError } from "./errors.js";
2
- import { escapeFilterPath } from "./fonts.js";
3
- import { stillOutput } from "./paths.js";
2
+ import { escapeFilterPath, bundledFontPath } from "./fonts.js";
3
+ import { stillOutput, sequencePattern } from "./paths.js";
4
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { tmpdir } from "node:os";
7
+ import { mapPool } from "./pool.js";
8
+ import { runFfmpeg } from "./ffmpeg.js";
4
9
  export const DEFAULT_SHEET_COUNT = 12;
5
10
  export const MAX_SHEET_COUNT = 48;
6
11
  export const DEFAULT_TILE_WIDTH = 320;
@@ -57,3 +62,21 @@ export function buildPosterArgs(input, durationSec, output, width) {
57
62
  ...stillOutput(output),
58
63
  ];
59
64
  }
65
+ export async function renderContactSheet(input, times, output, opts, signal) {
66
+ const grid = sheetGrid(times.length, opts.columns);
67
+ const work = mkdtempSync(join(tmpdir(), "screencast-sheet-"));
68
+ try {
69
+ const font = bundledFontPath("bold");
70
+ await mapPool(times, async (t, i) => {
71
+ const labelFile = join(work, `label_${i}.txt`);
72
+ writeFileSync(labelFile, formatTimecode(t));
73
+ const tile = join(work, `tile_${String(i).padStart(3, "0")}.png`);
74
+ await runFfmpeg(buildTileArgs(input, t, tile, opts.tileWidth, font, labelFile), 60_000, { signal });
75
+ });
76
+ await runFfmpeg(buildSheetArgs(sequencePattern(work, "tile_%03d.png"), grid, output), 60_000, { signal });
77
+ }
78
+ finally {
79
+ rmSync(work, { recursive: true, force: true });
80
+ }
81
+ return grid;
82
+ }
@@ -17,6 +17,12 @@ export const STOPS_SESSION = {
17
17
  idempotentHint: true,
18
18
  openWorldHint: false,
19
19
  };
20
+ export const DELETES_FILE = {
21
+ readOnlyHint: false,
22
+ destructiveHint: true,
23
+ idempotentHint: true,
24
+ openWorldHint: false,
25
+ };
20
26
  export function looseOutput(shape) {
21
27
  return z.looseObject(shape);
22
28
  }
@@ -7,6 +7,7 @@ export const TOOLSETS = {
7
7
  "resume_recording",
8
8
  "save_replay",
9
9
  "list_sessions",
10
+ "delete_recording",
10
11
  "get_session",
11
12
  "read_events",
12
13
  "add_marker",
@@ -0,0 +1,50 @@
1
+ import { diffFrames, SettleTracker } from "./diff.js";
2
+ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
3
+ export async function waitLoop(o) {
4
+ const now = o.now ?? Date.now;
5
+ const sleep = o.sleep ?? defaultSleep;
6
+ const startedAt = now();
7
+ const baseline = await o.grab();
8
+ const settle = new SettleTracker(baseline, o.width, o.height, o.diff);
9
+ let lastChangeAt = startedAt;
10
+ let everChanged = false;
11
+ let regions = [];
12
+ let outcome = "timeout";
13
+ while (now() - startedAt < o.timeoutMs) {
14
+ if (o.signal.aborted) {
15
+ outcome = "cancelled";
16
+ break;
17
+ }
18
+ await sleep(o.intervalMs);
19
+ const current = await o.grab().catch((error) => {
20
+ if (o.signal.aborted)
21
+ return null;
22
+ throw error;
23
+ });
24
+ if (!current) {
25
+ outcome = "cancelled";
26
+ break;
27
+ }
28
+ if (o.mode === "change") {
29
+ const d = diffFrames(baseline, current, o.width, o.height, o.diff);
30
+ if (d.regions.length > 0) {
31
+ regions = d.regions;
32
+ outcome = "changed";
33
+ break;
34
+ }
35
+ }
36
+ else {
37
+ const changed = settle.push(current);
38
+ if (changed.length > 0) {
39
+ everChanged = true;
40
+ lastChangeAt = now();
41
+ regions = changed;
42
+ }
43
+ else if (now() - lastChangeAt >= o.settleMs) {
44
+ outcome = "settled";
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ return { outcome, regions, everChanged, startedAt };
50
+ }