@tmhs/screencast-mcp 0.44.2 → 0.45.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.
@@ -0,0 +1,131 @@
1
+ import { z } from "zod";
2
+ import { join } from "node:path";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
+ import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
7
+ import { requireFfmpeg, probeMedia } from "../utils/ffmpeg.js";
8
+ import { runEditJob } from "../utils/jobs.js";
9
+ import { eventPaths, parseEventsJsonl } from "../utils/events.js";
10
+ import { resolveTextFont } from "../utils/fonts.js";
11
+ import { planBadges, groupBadges, buildKeystrokeArgs, BADGE_POSITIONS, DEFAULT_LINGER_SEC, } from "../utils/keystrokes.js";
12
+ import { editOutputExt, assertEditContainer } from "../utils/media.js";
13
+ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
14
+ import { fontFileSchema } from "./callout.js";
15
+ export const keystrokeOptionsSchema = {
16
+ events: z.string().optional(),
17
+ clicks: z.boolean().optional(),
18
+ typing: z.boolean().optional(),
19
+ keys: z.enum(["shortcuts", "masked"]).optional(),
20
+ lingerSec: z.number().positive().max(10).optional(),
21
+ position: z.enum(BADGE_POSITIONS).optional(),
22
+ size: z.number().min(8).max(400).optional(),
23
+ color: z.string().optional(),
24
+ fontFile: z.string().min(1).optional(),
25
+ };
26
+ const o = keystrokeOptionsSchema;
27
+ export function loadBadges(input, events, opts) {
28
+ const path = events ?? eventPaths(input).jsonl;
29
+ if (!existsSync(path)) {
30
+ throw new ScreencastError(`No event log for ${input} (looked for ${path}). Record with start_recording events: true ` +
31
+ '(keys: "shortcuts" to name shortcuts), or pass events: <path to .events.jsonl>.');
32
+ }
33
+ const log = parseEventsJsonl(readFileSync(path, "utf8"));
34
+ return { badges: planBadges(log, opts), shortcutsLogged: log.filter((e) => e.type === "key").length, path };
35
+ }
36
+ export function prepareKeystrokeAssets(labels, workDir, tag = "", fontFile) {
37
+ const font = resolveTextFont(labels.join(" "), { weight: "bold", fontFile });
38
+ const textFiles = {};
39
+ labels.forEach((label, i) => {
40
+ if (workDir === null) {
41
+ textFiles[label] = `<badge ${i}>`;
42
+ return;
43
+ }
44
+ const f = join(workDir, `${tag}badge_${i}.txt`);
45
+ writeFileSync(f, label);
46
+ textFiles[label] = f;
47
+ });
48
+ return {
49
+ fontFile: font.fontFile,
50
+ textFiles,
51
+ ...(font.fallback && { fallbackFont: font.fontFile }),
52
+ warnings: font.warning ? [font.warning] : [],
53
+ };
54
+ }
55
+ const inputSchema = {
56
+ input: z.string().min(1).describe("Path to the recording."),
57
+ events: o.events.describe("Event log (default: the input's .events.jsonl)."),
58
+ clicks: o.clicks.describe("Show clicks (default true)."),
59
+ typing: o.typing.describe('Show typing as "Typing…" (default true).'),
60
+ keys: o.keys.describe("shortcuts (default): the chord (Ctrl + S); masked: modifiers only (Ctrl + …)."),
61
+ lingerSec: o.lingerSec.describe(`Seconds a badge stays up (default ${DEFAULT_LINGER_SEC}).`),
62
+ position: o.position.describe("Default bottom (centred)."),
63
+ size: o.size.describe("Font px (default 4.5% of the frame height)."),
64
+ color: o.color.describe("Text color (default white)."),
65
+ fontFile: fontFileSchema,
66
+ dryRun: z.boolean().optional().describe("Return the planned badges; write nothing."),
67
+ output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
68
+ overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
69
+ };
70
+ export function register(server) {
71
+ server.registerTool("keystroke_overlay", {
72
+ title: "Keystroke Overlay",
73
+ description: "Burn keycast-style badges for shortcuts, clicks, and typing from the recording's input event log " +
74
+ "(start_recording events: true). Never shows typed text: the log has none.",
75
+ inputSchema,
76
+ outputSchema: looseOutput({ badges: z.number().int() }),
77
+ annotations: WRITES_FILE,
78
+ }, async (args, extra) => {
79
+ try {
80
+ requireFfmpeg();
81
+ if (!existsSync(args.input))
82
+ throw new ScreencastError(`Input file not found: ${args.input}`);
83
+ const plan = { clicks: args.clicks, typing: args.typing, keys: args.keys, lingerSec: args.lingerSec };
84
+ const { badges, shortcutsLogged } = loadBadges(args.input, args.events, plan);
85
+ const note = shortcutsLogged === 0
86
+ ? 'The log names no shortcuts (recorded with keys: "masked"), so only clicks and typing can show.'
87
+ : undefined;
88
+ if (badges.length === 0) {
89
+ return okResponse({ badges: 0, note: "Nothing to show: the log has no clicks, shortcuts, or typing; nothing written." });
90
+ }
91
+ const groups = groupBadges(badges);
92
+ if (args.dryRun) {
93
+ const assets = prepareKeystrokeAssets(groups.map((g) => g.label), null, "", args.fontFile);
94
+ return okResponse({
95
+ dryRun: true,
96
+ badges: badges.length,
97
+ plan: badges,
98
+ ...(assets.fallbackFont && { fallbackFont: assets.fallbackFont }),
99
+ ...(assets.warnings.length > 0 && { warnings: assets.warnings }),
100
+ ...(note && { note }),
101
+ });
102
+ }
103
+ assertEditContainer(args.output);
104
+ const info = await probeMedia(args.input);
105
+ if (!info.height)
106
+ throw new ScreencastError(`Could not read the size of ${args.input}.`);
107
+ const output = resolveOutput(args.output, subdir("edits"), `keys-${stamp()}-${rand()}${editOutputExt(args.input)}`, args.overwrite);
108
+ const work = mkdtempSync(join(tmpdir(), "screencast-keys-"));
109
+ try {
110
+ const assets = prepareKeystrokeAssets(groups.map((g) => g.label), work, "", args.fontFile);
111
+ const style = { position: args.position, size: args.size, color: args.color };
112
+ const ffArgs = buildKeystrokeArgs(args.input, output, groups, assets, style, { height: info.height });
113
+ await runEditJob(ffArgs, { output, durationSec: info.durationSec, extra });
114
+ return okResponse({
115
+ outputPath: output,
116
+ badges: badges.length,
117
+ labels: groups.map((g) => g.label),
118
+ ...(assets.fallbackFont && { fallbackFont: assets.fallbackFont }),
119
+ ...(assets.warnings.length > 0 && { warnings: assets.warnings }),
120
+ ...(note && { note }),
121
+ });
122
+ }
123
+ finally {
124
+ rmSync(work, { recursive: true, force: true });
125
+ }
126
+ }
127
+ catch (error) {
128
+ return errorResponse(error);
129
+ }
130
+ });
131
+ }
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { join } from "node:path";
3
- import { existsSync, mkdtempSync, rmSync } from "node:fs";
3
+ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
6
6
  import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
@@ -14,6 +14,9 @@ import { zoomKeyframeSchema } from "./zoom.js";
14
14
  import { redactRegionSchema } from "./redactRegion.js";
15
15
  import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
16
16
  import { PLATFORMS } from "../utils/produce.js";
17
+ import { buildChapters, ffmetadata, markerPoints, markersOrChapters, retimeMarkers, writeMarkers } from "../utils/chapters.js";
18
+ import { backdropOptionsSchema } from "./backdrop.js";
19
+ import { keystrokeOptionsSchema, loadBadges, prepareKeystrokeAssets } from "./keystrokeOverlay.js";
17
20
  const aspect = z.enum(["16:9", "9:16", "1:1", "4:5"]);
18
21
  const fit = z.enum(["pad", "crop"]).optional();
19
22
  const step = z.discriminatedUnion("op", [
@@ -42,6 +45,8 @@ const step = z.discriminatedUnion("op", [
42
45
  z.object({ op: z.literal("callout"), items: z.array(calloutItemSchema).min(1).max(50), fontFile: fontFileSchema }),
43
46
  z.object({ op: z.literal("reframe"), aspect, fit }),
44
47
  z.object({ op: z.literal("zoom"), keyframes: z.array(zoomKeyframeSchema).min(1).max(100), transitionSec: z.number().positive().max(5).optional() }),
48
+ z.object({ op: z.literal("backdrop"), ...backdropOptionsSchema }),
49
+ z.object({ op: z.literal("keystroke_overlay"), ...keystrokeOptionsSchema }),
45
50
  z.object({ op: z.literal("export_preset"), platform: z.enum(PLATFORMS), fit }),
46
51
  z.object({
47
52
  op: z.literal("export_gif"),
@@ -63,11 +68,15 @@ const inputSchema = {
63
68
  dryRun: z.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),
64
69
  output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
65
70
  overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
71
+ chapters: z
72
+ .boolean()
73
+ .optional()
74
+ .describe("Keep the input's markers as chapters, re-timed through trims and speed."),
66
75
  };
67
76
  export function register(server) {
68
77
  server.registerTool("pipeline", {
69
78
  title: "Edit Pipeline",
70
- description: "Run several edits (trim, crop, scale, speed, redact, callout, reframe, zoom, then optionally " +
79
+ description: "Run several edits (trim, crop, scale, speed, redact, callout, keystroke_overlay, reframe, zoom, backdrop, then optionally " +
71
80
  "export_preset or export_gif) in one ffmpeg pass: one re-encode, no intermediate files. Prefer it " +
72
81
  "over chaining edit tools.",
73
82
  inputSchema,
@@ -109,8 +118,42 @@ export function register(server) {
109
118
  fallbackFonts.push(...a.fallbackFonts.map((f) => ({ step: i, ...f })));
110
119
  warnings.push(...a.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
111
120
  }
121
+ const keystrokes = {};
122
+ for (const [i, s] of steps.entries()) {
123
+ if (s.op === "backdrop" && s.image && !existsSync(s.image)) {
124
+ throw new ScreencastError(`step ${i + 1}: background image not found: ${s.image}`);
125
+ }
126
+ if (s.op !== "keystroke_overlay")
127
+ continue;
128
+ const { badges } = loadBadges(args.input, s.events, s);
129
+ const labels = [...new Set(badges.map((b) => b.label))];
130
+ const k = prepareKeystrokeAssets(labels, args.dryRun ? null : work, `s${i}_`, s.fontFile);
131
+ keystrokes[i] = { badges, fontFile: k.fontFile, textFiles: k.textFiles };
132
+ warnings.push(...k.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
133
+ }
112
134
  const target = last.op === "export_gif" ? (args.dryRun ? "<temporary stage1.mp4>" : join(work, "stage1.mp4")) : output;
113
- const plan = planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard");
135
+ let plan = planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", { keystrokes });
136
+ let chapterList = [];
137
+ let retimed = [];
138
+ if (args.chapters) {
139
+ const found = plan.gif ? null : await markersOrChapters(args.input, extra.signal);
140
+ if (!found)
141
+ warnings.push("chapters: a GIF/WebP cannot hold chapters; none written.");
142
+ else if (found.markers.length === 0)
143
+ warnings.push("chapters: the input has no markers (add_marker) or chapters; none written.");
144
+ else {
145
+ retimed = retimeMarkers(found.markers, plan.timeOps);
146
+ chapterList = plan.durationSec ? buildChapters(markerPoints(retimed), plan.durationSec) : [];
147
+ if (chapterList.length === 0)
148
+ warnings.push("chapters: no marker falls inside the result; none written.");
149
+ else {
150
+ const file = args.dryRun ? "<chapters.txt>" : join(work, "chapters.txt");
151
+ if (!args.dryRun)
152
+ writeFileSync(file, ffmetadata(chapterList));
153
+ plan = planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", { chaptersFile: file, keystrokes });
154
+ }
155
+ }
156
+ }
114
157
  const result = {
115
158
  steps: plan.summary,
116
159
  processes: plan.gif ? 2 : 1,
@@ -119,6 +162,7 @@ export function register(server) {
119
162
  durationSec: plan.durationSec,
120
163
  ...(fallbackFonts.length > 0 && { fallbackFonts }),
121
164
  ...(warnings.length > 0 && { warnings }),
165
+ ...(chapterList.length > 0 && { chapters: chapterList }),
122
166
  };
123
167
  if (args.dryRun)
124
168
  return okResponse({ dryRun: true, ...result, ffmpegArgs: plan.args });
@@ -127,7 +171,15 @@ export function register(server) {
127
171
  const anim = await exportAnimation(target, output, plan.gif, extra);
128
172
  return okResponse({ outputPath: output, ...result, animation: anim });
129
173
  }
130
- return okResponse({ outputPath: output, ...result });
174
+ let markersPath;
175
+ if (chapterList.length > 0) {
176
+ try {
177
+ markersPath = writeMarkers(output, retimed.filter((m) => m.t < (plan.durationSec ?? Infinity)));
178
+ }
179
+ catch {
180
+ }
181
+ }
182
+ return okResponse({ outputPath: output, ...result, ...(markersPath && { markersPath }) });
131
183
  }
132
184
  finally {
133
185
  rmSync(work, { recursive: true, force: true });
@@ -8,6 +8,7 @@ import { jobTimeoutMs } from "../utils/jobs.js";
8
8
  import { tempPath } from "../utils/paths.js";
9
9
  import { buildPlayerFramesArgs, clientSupportsApps, parsePlayerFrameLog, pickPlayerFrames, playerFramePlan, splitJpegs, DEFAULT_PLAYER_FRAMES, DEFAULT_PLAYER_WIDTH, MAX_PLAYER_FRAMES, MCP_APP_MIME, PLAYER_TOOL_META, PLAYER_URI, } from "../utils/player.js";
10
10
  import { getStore } from "../context.js";
11
+ import { markersOrChapters, readMarkers } from "../utils/chapters.js";
11
12
  const uiAsset = (name) => readFileSync(fileURLToPath(new URL(`../../assets/ui/${name}`, import.meta.url)), "utf8");
12
13
  export function playerHtml() {
13
14
  const js = uiAsset("player.js");
@@ -28,6 +29,9 @@ function resolveInput(args) {
28
29
  return args.input;
29
30
  throw new ScreencastError("Pass input or sessionId.");
30
31
  }
32
+ function markersField(markers) {
33
+ return markers && markers.length > 0 ? { markers: markers.map(({ t, label }) => ({ t, label })) } : {};
34
+ }
31
35
  export function register(server) {
32
36
  server.registerResource("review-player", PLAYER_URI, {
33
37
  title: "Recording review player",
@@ -68,6 +72,7 @@ export function register(server) {
68
72
  height: info.height,
69
73
  fps: info.fps,
70
74
  hasAudio: info.audioCodec !== null,
75
+ ...markersField(args.sessionId ? getStore().get(args.sessionId)?.markers ?? readMarkers(input) : readMarkers(input)),
71
76
  note: "Clients with MCP Apps show an inline review player for this result. Without it, " +
72
77
  "look with contact_sheet or sample_frames, then trim and redact with pipeline.",
73
78
  });
@@ -116,6 +121,12 @@ export function register(server) {
116
121
  return frame && jpeg ? [{ frame, jpeg }] : [];
117
122
  });
118
123
  const t0 = firstFrame.timeSec;
124
+ let markers = [];
125
+ try {
126
+ markers = (await markersOrChapters(args.input, extra.signal)).markers.map(({ t, label }) => ({ t, label }));
127
+ }
128
+ catch {
129
+ }
119
130
  const frameTimes = keep.map(({ frame }) => Math.round((frame.timeSec - t0) * 1000) / 1000);
120
131
  const sceneFrames = keep.flatMap(({ frame }, k) => (frame.scene ? [k] : []));
121
132
  return {
@@ -131,6 +142,7 @@ export function register(server) {
131
142
  frameTimes,
132
143
  intervalSec: plan.intervalSec,
133
144
  sceneFrames,
145
+ markers,
134
146
  }),
135
147
  },
136
148
  ...keep.map(({ jpeg }) => ({ type: "image", data: jpeg.toString("base64"), mimeType: "image/jpeg" })),
@@ -0,0 +1,90 @@
1
+ import { z } from "zod";
2
+ import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
3
+ import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
4
+ import { requireFfmpeg } from "../utils/ffmpeg.js";
5
+ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
6
+ import { eventPaths, prepareEventPaths } from "../utils/events.js";
7
+ import { logMessage } from "../utils/logging.js";
8
+ import { MAX_REPLAY_SEC, replayDiskBytes, saveReplay } from "../utils/replay.js";
9
+ import { getStore } from "../context.js";
10
+ const inputSchema = {
11
+ sessionId: z.string().min(1).describe("Session id of a replay buffer."),
12
+ lastSec: z
13
+ .number()
14
+ .positive()
15
+ .max(MAX_REPLAY_SEC)
16
+ .optional()
17
+ .describe("Seconds back from now (default and max: the buffer length)."),
18
+ output: z.string().optional().describe("Output .mp4 path (default under SCREENCAST_HOME/recordings)."),
19
+ overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
20
+ reencode: z
21
+ .boolean()
22
+ .optional()
23
+ .describe("Frame-exact re-encode. Default: instant stream copy that may hide up to 2 s of earlier frames."),
24
+ };
25
+ export function register(server) {
26
+ server.registerTool("save_replay", {
27
+ title: "Save Replay",
28
+ description: "Save the last N seconds of a replay buffer (start_recording replayBufferSec) to an mp4; the buffer keeps running.",
29
+ inputSchema,
30
+ outputSchema: looseOutput({
31
+ sessionId: z.string(),
32
+ outputPath: z.string(),
33
+ durationSec: z.number(),
34
+ }),
35
+ annotations: WRITES_FILE,
36
+ }, async (args, extra) => {
37
+ try {
38
+ const record = getStore().get(args.sessionId);
39
+ if (!record)
40
+ throw new ScreencastError(`No session with id "${args.sessionId}".`);
41
+ if (!record.replay) {
42
+ throw new ScreencastError(`Session "${args.sessionId}" is not a replay buffer.`, "Start one with start_recording { replayBufferSec: 60 }; for an ordinary recording use stop_recording and trim.");
43
+ }
44
+ const { ffmpeg, ffprobe } = requireFfmpeg();
45
+ const buf = record.replay;
46
+ const lastSec = Math.min(args.lastSec ?? buf.bufferSec, buf.bufferSec);
47
+ const output = resolveOutput(args.output, subdir("recordings"), `replay-${stamp()}-${rand()}.mp4`, args.overwrite);
48
+ if (buf.events)
49
+ prepareEventPaths(eventPaths(output), args.overwrite);
50
+ const started = Date.now();
51
+ const result = await saveReplay(buf, {
52
+ ffmpeg,
53
+ ffprobe,
54
+ lastSec,
55
+ output,
56
+ reencode: args.reencode,
57
+ quality: record.quality,
58
+ live: record.status === "recording",
59
+ signal: extra.signal,
60
+ });
61
+ const elapsedMs = Date.now() - started;
62
+ logMessage("info", `Saved ${result.durationSec}s of replay ${record.id} to ${output}.`, {
63
+ sessionId: record.id,
64
+ outputPath: output,
65
+ durationSec: result.durationSec,
66
+ });
67
+ const short = result.durationSec + 0.25 < lastSec;
68
+ return okResponse({
69
+ sessionId: record.id,
70
+ ...result,
71
+ requestedSec: args.lastSec ?? null,
72
+ bufferSec: buf.bufferSec,
73
+ bufferRunning: record.status === "recording",
74
+ bufferDiskBytes: replayDiskBytes(buf),
75
+ elapsedMs,
76
+ note: (args.lastSec !== undefined && args.lastSec > buf.bufferSec
77
+ ? `Capped at the buffer length (${buf.bufferSec}s). `
78
+ : "") +
79
+ (short ? "The buffer held less footage than requested (it started recently). " : "") +
80
+ (result.includesLive ? "" : "The clip ends at the last completed segment, up to 2 s before now. ") +
81
+ (record.status === "recording"
82
+ ? "The buffer keeps running; stop_recording discards it unless save: true."
83
+ : "This buffer is no longer recording; stop_recording discards it."),
84
+ });
85
+ }
86
+ catch (error) {
87
+ return errorResponse(error);
88
+ }
89
+ });
90
+ }
@@ -14,7 +14,8 @@ import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
14
14
  import { getStore } from "../context.js";
15
15
  import { classifyUnrequestedExit, killPid, serverIdentity } from "../utils/sessions.js";
16
16
  import { rmSync } from "node:fs";
17
- import { basename } from "node:path";
17
+ import { basename, join } from "node:path";
18
+ import { MAX_REPLAY_SEC, MIN_REPLAY_SEC, discardReplay, planReplayBuffer, prepareReplayDir, segmentOutputArgs, } from "../utils/replay.js";
18
19
  import { DEFAULT_KEY_MODE, eventPaths, parseCaptureStart, prepareEventPaths, startEventLogger, stopEventLogger, summarizeEvents, trackFinalizer, writeEventsFile, } from "../utils/events.js";
19
20
  const inputSchema = {
20
21
  target: z
@@ -77,6 +78,13 @@ const inputSchema = {
77
78
  .optional()
78
79
  .describe("gdigrab (default): the screen rectangle. wgc (window: targets, FFmpeg 8+): the window's own " +
79
80
  "surface, even when covered or moved; client area only, no audio."),
81
+ replayBufferSec: z
82
+ .number()
83
+ .int()
84
+ .min(MIN_REPLAY_SEC)
85
+ .max(MAX_REPLAY_SEC)
86
+ .optional()
87
+ .describe("Instant replay: keep only the last N s (bounded disk) for save_replay. gdigrab only."),
80
88
  };
81
89
  export function register(server) {
82
90
  server.registerTool("start_recording", {
@@ -108,6 +116,10 @@ export function register(server) {
108
116
  throw new ScreencastError('backend "wgc" needs FFmpeg 8 or newer (the gfxcapture filter). Use gdigrab, or update ffmpeg.');
109
117
  }
110
118
  }
119
+ if (args.replayBufferSec !== undefined && backend === "wgc") {
120
+ throw new ScreencastError('replayBufferSec is not supported with backend "wgc" yet; use gdigrab.');
121
+ }
122
+ const replay = args.replayBufferSec !== undefined ? planReplayBuffer(args.replayBufferSec) : null;
111
123
  const fps = args.fps ?? DEFAULT_FPS;
112
124
  const quality = args.quality ?? DEFAULT_QUALITY;
113
125
  const maxDurationSec = resolveMaxDuration(args.maxDurationSec);
@@ -115,12 +127,13 @@ export function register(server) {
115
127
  const audio = args.audio?.source === "system"
116
128
  ? { device: await resolveLoopbackDevice(args.audio.device) }
117
129
  : undefined;
118
- await confirmCapture(server, `Record ${describeTarget(args.target, window)} ` +
130
+ await confirmCapture(server, (replay ? `Keep a rolling ${replay.bufferSec} s replay buffer of ` : "Record ") +
131
+ `${describeTarget(args.target, window)} ` +
119
132
  (maxDurationSec > 0 ? `for up to ${maxDurationSec} s` : "with no time limit") +
120
133
  (audio ? `, with system audio (${audio.device})` : ", without audio") +
121
134
  (args.events ? ", logging mouse clicks and typing" : "") +
122
- `, saved to ${output}?`, extra.signal);
123
- const ffArgs = buildCaptureArgs(target, {
135
+ (replay ? ", kept only until save_replay or stop_recording { save: true } writes it out?" : `, saved to ${output}?`), extra.signal);
136
+ const captureArgs = buildCaptureArgs(target, {
124
137
  fps,
125
138
  quality,
126
139
  output,
@@ -128,9 +141,12 @@ export function register(server) {
128
141
  audio,
129
142
  maxDurationSec,
130
143
  });
144
+ const ffArgs = replay ? segmentOutputArgs(captureArgs, replay) : captureArgs;
145
+ if (replay)
146
+ prepareReplayDir(replay);
131
147
  const keyMode = args.keys ?? DEFAULT_KEY_MODE;
132
- const evPaths = args.events ? eventPaths(output) : null;
133
- if (evPaths)
148
+ const evPaths = args.events ? (replay ? { raw: join(replay.dir, "events.raw"), jsonl: "" } : eventPaths(output)) : null;
149
+ if (evPaths && !replay)
134
150
  prepareEventPaths(evPaths, args.overwrite);
135
151
  let frame = args.events
136
152
  ? captureFrame(target, monitors)
@@ -182,6 +198,8 @@ export function register(server) {
182
198
  await stopEventLogger(logger);
183
199
  if (evPaths)
184
200
  rmSync(evPaths.raw, { force: true });
201
+ if (replay)
202
+ discardReplay(replay);
185
203
  const tail = stderrTail.trim().split("\n").slice(-6).join("\n");
186
204
  throw new ScreencastError(`Recording failed to start (${backend === "wgc" ? "window capture" : "ffmpeg"} exited immediately):\n${tail}`);
187
205
  }
@@ -199,9 +217,20 @@ export function register(server) {
199
217
  ...serverIdentity(),
200
218
  status: "recording",
201
219
  startedAt: new Date().toISOString(),
220
+ videoStartMs: parseCaptureStart(stderrHead) ?? spawnedAt,
202
221
  ...(maxDurationSec > 0 ? { maxDurationSec } : {}),
203
222
  ...(window ? { matchedWindow: window.matchedTitle } : {}),
204
- ...(evPaths ? { events: { path: evPaths.jsonl, keys: keyMode } } : {}),
223
+ ...(evPaths && !replay ? { events: { path: evPaths.jsonl, keys: keyMode } } : {}),
224
+ ...(replay
225
+ ? {
226
+ replay: {
227
+ ...replay,
228
+ ...(evPaths && frame
229
+ ? { events: { raw: evPaths.raw, keys: keyMode, startMs: parseCaptureStart(stderrHead) ?? spawnedAt, frame } }
230
+ : {}),
231
+ },
232
+ }
233
+ : {}),
205
234
  backend,
206
235
  processImage: backend === "wgc" ? basename(process.execPath).toLowerCase() : "ffmpeg.exe",
207
236
  };
@@ -218,9 +247,15 @@ export function register(server) {
218
247
  await stopEventLogger(logger);
219
248
  if (evPaths)
220
249
  rmSync(evPaths.raw, { force: true });
250
+ if (replay)
251
+ discardReplay(replay);
221
252
  throw new ScreencastError(`Recording stopped: the session registry could not be written (${err.message}).`);
222
253
  }
223
- if (logger && evPaths && frame) {
254
+ if (logger && replay) {
255
+ const exited = new Promise((resolve) => child.once("exit", () => resolve()));
256
+ trackFinalizer(id, exited.then(() => stopEventLogger(logger)));
257
+ }
258
+ else if (logger && evPaths && frame) {
224
259
  const exited = new Promise((resolve) => child.once("exit", () => resolve()));
225
260
  trackFinalizer(id, exited.then(async () => {
226
261
  await stopEventLogger(logger);
@@ -268,8 +303,14 @@ export function register(server) {
268
303
  audioDevice: audio?.device ?? null,
269
304
  maxDurationSec: maxDurationSec > 0 ? maxDurationSec : null,
270
305
  ...(window ? windowMatchReport(window) : {}),
271
- ...(evPaths ? { eventsPath: evPaths.jsonl, keys: keyMode } : {}),
272
- note: "Call stop_recording with this sessionId to finalize the file." +
306
+ ...(evPaths && !replay ? { eventsPath: evPaths.jsonl, keys: keyMode } : {}),
307
+ ...(replay
308
+ ? { replay: { bufferSec: replay.bufferSec, segmentSec: replay.segmentSec, dir: replay.dir, events: !!evPaths } }
309
+ : {}),
310
+ note: (replay
311
+ ? `Replay buffer running: save_replay keeps the last seconds (up to ${replay.bufferSec}s) without stopping it; ` +
312
+ "stop_recording discards the buffer unless save: true (then it writes outputPath)."
313
+ : "Call stop_recording with this sessionId to finalize the file.") +
273
314
  (maxDurationSec > 0
274
315
  ? ` It stops on its own after ${maxDurationSec}s (maxDurationSec).`
275
316
  : ""),
@@ -5,8 +5,21 @@ import { STOPS_SESSION, looseOutput } from "../utils/toolSpec.js";
5
5
  import { requireFfmpeg } from "../utils/ffmpeg.js";
6
6
  import { probeDuration, stopSession } from "../utils/lifecycle.js";
7
7
  import { getStore } from "../context.js";
8
+ import { finishReplay } from "../utils/replay.js";
9
+ function replayReport(r) {
10
+ return {
11
+ saved: r.saved,
12
+ discarded: r.discarded,
13
+ ...(r.save ? { durationSec: r.save.durationSec, eventsPath: r.save.eventsPath } : {}),
14
+ ...(r.error ? { error: r.error, note: "The buffer was kept; call stop_recording with save: true again, or save_replay." } : {}),
15
+ };
16
+ }
8
17
  const inputSchema = {
9
18
  sessionId: z.string().min(1).describe("Session id returned by start_recording."),
19
+ save: z
20
+ .boolean()
21
+ .optional()
22
+ .describe("Replay buffer: write it all to outputPath first (default: discard)."),
10
23
  };
11
24
  export function register(server) {
12
25
  server.registerTool("stop_recording", {
@@ -28,7 +41,16 @@ export function register(server) {
28
41
  throw new ScreencastError(`No session with id "${args.sessionId}".`);
29
42
  }
30
43
  if (record.status !== "recording") {
44
+ const replay = record.replay && existsSync(record.replay.dir)
45
+ ? await finishReplay(record.replay, {
46
+ save: args.save ?? false,
47
+ output: record.outputPath,
48
+ quality: record.quality,
49
+ tools: requireFfmpeg,
50
+ })
51
+ : undefined;
31
52
  return okResponse({
53
+ ...(replay ? { replay: replayReport(replay) } : {}),
32
54
  sessionId: record.id,
33
55
  status: record.status,
34
56
  outputPath: record.outputPath,
@@ -42,9 +64,10 @@ export function register(server) {
42
64
  });
43
65
  }
44
66
  const { ffprobe } = requireFfmpeg();
45
- const { record: updated, graceful, durationSec } = await stopSession(store, record, {
67
+ const { record: updated, graceful, durationSec, replay } = await stopSession(store, record, {
46
68
  reason: "stopped",
47
69
  probe: (path) => probeDuration(ffprobe, path),
70
+ saveReplay: args.save,
48
71
  });
49
72
  return okResponse({
50
73
  sessionId: record.id,
@@ -52,6 +75,7 @@ export function register(server) {
52
75
  outputPath: record.outputPath,
53
76
  durationSec: durationSec ?? null,
54
77
  finalizedGracefully: graceful,
78
+ ...(replay ? { replay: replayReport(replay) } : {}),
55
79
  ...(updated?.events
56
80
  ? { eventsPath: updated.events.path, events: updated.events.summary ?? {}, ...(updated.events.error ? { eventsError: updated.events.error } : {}) }
57
81
  : {}),