@tmhs/screencast-mcp 0.49.0 → 0.50.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 (133) hide show
  1. package/README.md +13 -8
  2. package/dist/index.js +550 -106
  3. package/dist/wgcRecorder.js +15 -139
  4. package/package.json +8 -4
  5. package/assets/.gitkeep +0 -0
  6. package/assets/icon.png +0 -0
  7. package/dist/cli.js +0 -516
  8. package/dist/context.js +0 -50
  9. package/dist/prompts.js +0 -95
  10. package/dist/resources.js +0 -93
  11. package/dist/server.js +0 -174
  12. package/dist/setup.js +0 -438
  13. package/dist/tools/addMarker.js +0 -93
  14. package/dist/tools/assembleHighlights.js +0 -69
  15. package/dist/tools/backdrop.js +0 -89
  16. package/dist/tools/bugReport.js +0 -266
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -103
  19. package/dist/tools/chapters.js +0 -156
  20. package/dist/tools/clip.js +0 -52
  21. package/dist/tools/compress.js +0 -51
  22. package/dist/tools/concat.js +0 -67
  23. package/dist/tools/contactSheet.js +0 -135
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -87
  27. package/dist/tools/cutByTranscript.js +0 -86
  28. package/dist/tools/cutIdle.js +0 -84
  29. package/dist/tools/deleteRecording.js +0 -119
  30. package/dist/tools/denoise.js +0 -60
  31. package/dist/tools/doctor.js +0 -146
  32. package/dist/tools/exportGif.js +0 -57
  33. package/dist/tools/exportPreset.js +0 -48
  34. package/dist/tools/extractAudio.js +0 -65
  35. package/dist/tools/findText.js +0 -196
  36. package/dist/tools/getMediaInfo.js +0 -36
  37. package/dist/tools/getSession.js +0 -40
  38. package/dist/tools/indexRecording.js +0 -195
  39. package/dist/tools/keystrokeOverlay.js +0 -131
  40. package/dist/tools/listAudioDevices.js +0 -35
  41. package/dist/tools/listSessions.js +0 -28
  42. package/dist/tools/listTargets.js +0 -76
  43. package/dist/tools/listVideoDevices.js +0 -26
  44. package/dist/tools/musicBed.js +0 -55
  45. package/dist/tools/narrate.js +0 -86
  46. package/dist/tools/normalizeAudio.js +0 -60
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -400
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -70
  52. package/dist/tools/reframe.js +0 -46
  53. package/dist/tools/resumeRecording.js +0 -46
  54. package/dist/tools/reviewRecording.js +0 -163
  55. package/dist/tools/sampleFrames.js +0 -200
  56. package/dist/tools/saveReplay.js +0 -90
  57. package/dist/tools/scale.js +0 -44
  58. package/dist/tools/screenDiff.js +0 -86
  59. package/dist/tools/screenshot.js +0 -76
  60. package/dist/tools/searchRecording.js +0 -79
  61. package/dist/tools/speed.js +0 -46
  62. package/dist/tools/startRecording.js +0 -398
  63. package/dist/tools/stepGuide.js +0 -250
  64. package/dist/tools/stopRecording.js +0 -132
  65. package/dist/tools/titleCard.js +0 -67
  66. package/dist/tools/transcribe.js +0 -66
  67. package/dist/tools/trim.js +0 -57
  68. package/dist/tools/waitForChange.js +0 -128
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -149
  71. package/dist/utils/anim.js +0 -54
  72. package/dist/utils/animExport.js +0 -56
  73. package/dist/utils/argPaths.js +0 -39
  74. package/dist/utils/audio.js +0 -113
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -151
  77. package/dist/utils/bugReport.js +0 -172
  78. package/dist/utils/callout.js +0 -90
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -103
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -317
  85. package/dist/utils/diff.js +0 -184
  86. package/dist/utils/errors.js +0 -29
  87. package/dist/utils/events.js +0 -403
  88. package/dist/utils/expr.js +0 -11
  89. package/dist/utils/ffmpeg.js +0 -285
  90. package/dist/utils/fontCoverage.js +0 -177
  91. package/dist/utils/fonts.js +0 -154
  92. package/dist/utils/gpu.js +0 -219
  93. package/dist/utils/idle.js +0 -91
  94. package/dist/utils/images.js +0 -38
  95. package/dist/utils/jobs.js +0 -129
  96. package/dist/utils/keystrokes.js +0 -155
  97. package/dist/utils/lifecycle.js +0 -233
  98. package/dist/utils/logging.js +0 -75
  99. package/dist/utils/media.js +0 -574
  100. package/dist/utils/monitors.js +0 -124
  101. package/dist/utils/narrate.js +0 -233
  102. package/dist/utils/ocr.js +0 -222
  103. package/dist/utils/ocrScan.js +0 -91
  104. package/dist/utils/paths.js +0 -155
  105. package/dist/utils/pause.js +0 -190
  106. package/dist/utils/pipeline.js +0 -361
  107. package/dist/utils/player.js +0 -85
  108. package/dist/utils/pool.js +0 -29
  109. package/dist/utils/produce.js +0 -298
  110. package/dist/utils/recipes.js +0 -71
  111. package/dist/utils/recorder.js +0 -173
  112. package/dist/utils/recordingFiles.js +0 -32
  113. package/dist/utils/recordingIndex.js +0 -312
  114. package/dist/utils/replay.js +0 -283
  115. package/dist/utils/resolveTarget.js +0 -25
  116. package/dist/utils/retention.js +0 -48
  117. package/dist/utils/roots.js +0 -43
  118. package/dist/utils/sessions.js +0 -499
  119. package/dist/utils/sheet.js +0 -59
  120. package/dist/utils/stepGuide.js +0 -231
  121. package/dist/utils/steps.js +0 -88
  122. package/dist/utils/still.js +0 -38
  123. package/dist/utils/targetList.js +0 -64
  124. package/dist/utils/targets.js +0 -265
  125. package/dist/utils/timeline.js +0 -85
  126. package/dist/utils/toolSpec.js +0 -31
  127. package/dist/utils/toolsets.js +0 -134
  128. package/dist/utils/transcriptCut.js +0 -149
  129. package/dist/utils/validate.js +0 -23
  130. package/dist/utils/waitLoop.js +0 -50
  131. package/dist/utils/wgc.js +0 -84
  132. package/dist/utils/windows.js +0 -192
  133. package/dist/utils/zoom.js +0 -234
@@ -1,163 +0,0 @@
1
- import { z } from "zod";
2
- import { existsSync, readFileSync, rmSync } from "node:fs";
3
- import { fileURLToPath } from "node:url";
4
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
5
- import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
6
- import { requireFfmpeg, probeMedia, runFfmpegBuffer } from "../utils/ffmpeg.js";
7
- import { jobTimeoutMs } from "../utils/jobs.js";
8
- import { tempPath } from "../utils/paths.js";
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
- import { getStore } from "../context.js";
11
- import { markersOrChapters, readMarkers } from "../utils/chapters.js";
12
- const uiAsset = (name) => readFileSync(fileURLToPath(new URL(`../../assets/ui/${name}`, import.meta.url)), "utf8");
13
- export function playerHtml() {
14
- const js = uiAsset("player.js");
15
- if (/<\/script/i.test(js))
16
- throw new ScreencastError("player.js must not contain a closing script tag.");
17
- return uiAsset("player.html").replace('<script src="player.js"></script>', () => `<script>\n${js}</script>`);
18
- }
19
- function resolveInput(args) {
20
- if (args.sessionId) {
21
- const record = getStore().get(args.sessionId);
22
- if (!record)
23
- throw new ScreencastError(`No session with id "${args.sessionId}".`);
24
- if (record.status === "recording" || record.status === "paused")
25
- throw new ScreencastError("The recording is still running; stop it first.");
26
- return record.outputPath;
27
- }
28
- if (args.input)
29
- return args.input;
30
- throw new ScreencastError("Pass input or sessionId.");
31
- }
32
- function markersField(markers) {
33
- return markers && markers.length > 0 ? { markers: markers.map(({ t, label }) => ({ t, label })) } : {};
34
- }
35
- export function register(server) {
36
- server.registerResource("review-player", PLAYER_URI, {
37
- title: "Recording review player",
38
- description: "Interactive player: scrub, trim, and draw redaction boxes on a recording.",
39
- mimeType: MCP_APP_MIME,
40
- }, async () => ({
41
- contents: [{ uri: PLAYER_URI, mimeType: MCP_APP_MIME, text: playerHtml(), _meta: { ui: { prefersBorder: true } } }],
42
- }));
43
- server.registerTool("review_recording", {
44
- title: "Review Recording",
45
- description: "Open a recording for a person to review: in MCP Apps clients an inline player to scrub, trim, " +
46
- "and redact, then export; elsewhere just the video's details.",
47
- inputSchema: {
48
- input: z.string().optional().describe("Path to the video."),
49
- sessionId: z.string().optional().describe("Or the session id of a stopped recording."),
50
- },
51
- outputSchema: looseOutput({
52
- input: z.string(),
53
- durationSec: z.number().nullable(),
54
- width: z.number().nullable(),
55
- height: z.number().nullable(),
56
- fps: z.number().nullable(),
57
- hasAudio: z.boolean(),
58
- }),
59
- annotations: READ_ONLY,
60
- _meta: PLAYER_TOOL_META,
61
- }, async (args) => {
62
- try {
63
- requireFfmpeg();
64
- const input = resolveInput(args);
65
- if (!existsSync(input))
66
- throw new ScreencastError(`Input file not found: ${input}`);
67
- const info = await probeMedia(input);
68
- return okResponse({
69
- input,
70
- durationSec: info.durationSec,
71
- width: info.width,
72
- height: info.height,
73
- fps: info.fps,
74
- hasAudio: info.audioCodec !== null,
75
- ...markersField(args.sessionId ? getStore().get(args.sessionId)?.markers ?? readMarkers(input) : readMarkers(input)),
76
- note: "Clients with MCP Apps show an inline review player for this result. Without it, " +
77
- "look with contact_sheet or sample_frames, then trim and redact with pipeline.",
78
- });
79
- }
80
- catch (error) {
81
- return errorResponse(error);
82
- }
83
- });
84
- const playerFrames = server.registerTool("player_frames", {
85
- title: "Player Frames",
86
- description: "Preview frames for the review player: JPEGs on an even grid over the video plus frames at " +
87
- "scene changes, with their real times. Used by the inline player; agents should use " +
88
- "sample_frames or contact_sheet instead.",
89
- inputSchema: {
90
- input: z.string().min(1).describe("Path to the video."),
91
- maxFrames: z.number().int().min(1).max(MAX_PLAYER_FRAMES).optional().describe(`Frames on the even grid (default ${DEFAULT_PLAYER_FRAMES}); scene-change frames come on top, up to as many again.`),
92
- width: z.number().int().min(64).max(1280).optional().describe(`Frame width (default ${DEFAULT_PLAYER_WIDTH}).`),
93
- },
94
- annotations: READ_ONLY,
95
- _meta: { ui: { visibility: ["app"] } },
96
- }, async (args, extra) => {
97
- try {
98
- requireFfmpeg();
99
- if (!existsSync(args.input))
100
- throw new ScreencastError(`Input file not found: ${args.input}`);
101
- const info = await probeMedia(args.input);
102
- const durationSec = info.durationSec ?? 0;
103
- const plan = playerFramePlan(durationSec, args.maxFrames ?? DEFAULT_PLAYER_FRAMES);
104
- const log = tempPath(".txt");
105
- let jpegs;
106
- let frames;
107
- try {
108
- const raw = await runFfmpegBuffer(buildPlayerFramesArgs(args.input, plan, args.width ?? DEFAULT_PLAYER_WIDTH, log), jobTimeoutMs(durationSec), { signal: extra.signal });
109
- jpegs = splitJpegs(raw);
110
- frames = parsePlayerFrameLog(existsSync(log) ? readFileSync(log, "utf8") : "").slice(0, jpegs.length);
111
- }
112
- finally {
113
- rmSync(log, { force: true });
114
- }
115
- const [firstFrame] = frames;
116
- if (!firstFrame)
117
- throw new ScreencastError("ffmpeg returned no preview frames.");
118
- const keep = pickPlayerFrames(frames, plan.count).flatMap((i) => {
119
- const frame = frames[i];
120
- const jpeg = jpegs[i];
121
- return frame && jpeg ? [{ frame, jpeg }] : [];
122
- });
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
- }
130
- const frameTimes = keep.map(({ frame }) => Math.round((frame.timeSec - t0) * 1000) / 1000);
131
- const sceneFrames = keep.flatMap(({ frame }, k) => (frame.scene ? [k] : []));
132
- return {
133
- content: [
134
- {
135
- type: "text",
136
- text: JSON.stringify({
137
- input: args.input,
138
- durationSec,
139
- width: info.width,
140
- height: info.height,
141
- hasAudio: info.audioCodec !== null,
142
- frameTimes,
143
- intervalSec: plan.intervalSec,
144
- sceneFrames,
145
- markers,
146
- }),
147
- },
148
- ...keep.map(({ jpeg }) => ({ type: "image", data: jpeg.toString("base64"), mimeType: "image/jpeg" })),
149
- ],
150
- };
151
- }
152
- catch (error) {
153
- return errorResponse(error);
154
- }
155
- });
156
- playerFrames.disable();
157
- const previous = server.server.oninitialized;
158
- server.server.oninitialized = () => {
159
- previous?.();
160
- if (clientSupportsApps(server.server.getClientCapabilities()))
161
- playerFrames.enable();
162
- };
163
- }
@@ -1,200 +0,0 @@
1
- import { z } from "zod";
2
- import { join } from "node:path";
3
- import { mkdirSync, readdirSync, existsSync, rmSync } from "node:fs";
4
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
5
- import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
6
- import { requireFfmpeg, runFfmpeg, runCapture, probeMedia } from "../utils/ffmpeg.js";
7
- import { jobTimeoutMs } from "../utils/jobs.js";
8
- import { buildSampleByFpsArgs, pickFramePrefix, buildSampleAtTimestampArgs, planFpsSampling, buildSceneScanArgs, parseSceneScan, pickSceneFrames, DEFAULT_SCENE_THRESHOLD, DEFAULT_MAX_FRAMES, MAX_FRAMES_CEILING, } from "../utils/media.js";
9
- import { subdir, stamp, rand, sequencePattern, resolveOutputDir } from "../utils/paths.js";
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";
12
- const inputSchema = {
13
- input: z.string().min(1).describe("Path to the source video file."),
14
- mode: z
15
- .enum(["fps", "timestamps", "scenes"])
16
- .optional()
17
- .describe("scenes: only frames where the screen changed (strongest first), usually the cheapest review. " +
18
- "Default: fps or timestamps, whichever is given."),
19
- fps: z
20
- .number()
21
- .positive()
22
- .optional()
23
- .describe("Frames per second (mode fps)."),
24
- timestamps: z
25
- .array(z.number().nonnegative())
26
- .optional()
27
- .describe("Seconds to grab a frame at (mode timestamps)."),
28
- sceneThreshold: z
29
- .number()
30
- .gt(0)
31
- .lt(1)
32
- .optional()
33
- .describe(`Mode scenes: change needed to count, 0-1 (default ${DEFAULT_SCENE_THRESHOLD}).`),
34
- dedupe: z
35
- .boolean()
36
- .optional()
37
- .describe("Mode fps: drop near-duplicate frames (default false)."),
38
- outputDir: z
39
- .string()
40
- .optional()
41
- .describe("Optional folder for the frames (a relative path resolves under SCREENCAST_HOME/frames). Defaults to SCREENCAST_HOME/frames/<id>."),
42
- maxFrames: z
43
- .number()
44
- .int()
45
- .min(1)
46
- .max(MAX_FRAMES_CEILING)
47
- .optional()
48
- .describe(`Frame cap (default ${DEFAULT_MAX_FRAMES}); fps is lowered to fit while still spanning the video.`),
49
- returnImages: z
50
- .boolean()
51
- .optional()
52
- .describe("Return the first maxInlineImages frames inline (default true)."),
53
- maxInlineImages: z
54
- .number()
55
- .int()
56
- .min(0)
57
- .max(MAX_INLINE_IMAGES)
58
- .optional()
59
- .describe(`Frames to embed inline (default ${DEFAULT_MAX_INLINE_IMAGES}); all are listed by path.`),
60
- maxImageWidth: z
61
- .number()
62
- .int()
63
- .min(16)
64
- .optional()
65
- .describe(`Max inline image width (default ${DEFAULT_MAX_IMAGE_WIDTH}).`),
66
- };
67
- export function register(server) {
68
- server.registerTool("sample_frames", {
69
- title: "Sample Frames",
70
- description: "Sample PNG frames from a video (by fps, timestamps, or scene changes) and return the first " +
71
- "few inline so the model can see what happened.",
72
- inputSchema,
73
- outputSchema: looseOutput({
74
- frameDir: z.string(),
75
- frameCount: z.number().int(),
76
- frames: z.array(z.string()),
77
- mode: z.string(),
78
- }),
79
- annotations: READ_ONLY,
80
- }, async (args, extra) => {
81
- try {
82
- requireFfmpeg();
83
- if (!existsSync(args.input)) {
84
- throw new ScreencastError(`Input file not found: ${args.input}`);
85
- }
86
- const hasFps = args.fps !== undefined;
87
- const hasTs = args.timestamps !== undefined && args.timestamps.length > 0;
88
- const mode = args.mode ?? (hasTs ? "timestamps" : "fps");
89
- const valid = mode === "scenes" ? !hasFps && !hasTs
90
- : mode === "fps" ? hasFps && !hasTs
91
- : hasTs && !hasFps;
92
- if (!valid) {
93
- throw new ScreencastError("Use exactly one way to pick frames: fps (fixed rate), timestamps " +
94
- "(explicit offsets), or mode: 'scenes' (with neither fps nor timestamps).");
95
- }
96
- const maxFrames = args.maxFrames ?? DEFAULT_MAX_FRAMES;
97
- if (hasTs && args.timestamps.length > maxFrames) {
98
- throw new ScreencastError(`${args.timestamps.length} timestamps exceeds maxFrames (${maxFrames}). ` +
99
- `Pass fewer timestamps, or raise maxFrames (up to ${MAX_FRAMES_CEILING}).`);
100
- }
101
- const durationSec = mode === "timestamps" ? null : (await probeMedia(args.input)).durationSec;
102
- const plan = mode === "fps" ? planFpsSampling(durationSec, args.fps, maxFrames) : null;
103
- let scenes = null;
104
- let sceneTimes = [];
105
- if (mode === "scenes") {
106
- const { ffmpeg } = requireFfmpeg();
107
- const scan = await runCapture(ffmpeg, buildSceneScanArgs(args.input, args.sceneThreshold ?? DEFAULT_SCENE_THRESHOLD), jobTimeoutMs(durationSec), { signal: extra.signal });
108
- if (scan.code !== 0) {
109
- throw new ScreencastError(`Scene scan failed (exit ${scan.code}): ${scan.stderr.trim().slice(-400)}`);
110
- }
111
- scenes = parseSceneScan(scan.stdout);
112
- sceneTimes = pickSceneFrames(scenes, maxFrames);
113
- }
114
- const dir = resolveOutputDir(args.outputDir, subdir("frames")) ?? join(subdir("frames"), `sample-${stamp()}-${rand()}`);
115
- mkdirSync(dir, { recursive: true });
116
- let frames = [];
117
- const skipped = [];
118
- if (plan) {
119
- const isPng = (f) => f.endsWith(".png");
120
- const before = new Set(readdirSync(dir).filter(isPng));
121
- const prefix = pickFramePrefix(before, `${stamp()}-${rand()}`);
122
- const pattern = sequencePattern(dir, `${prefix}%05d.png`);
123
- await runFfmpeg(buildSampleByFpsArgs(args.input, plan.fps, pattern, maxFrames, args.dedupe === true), jobTimeoutMs(durationSec), { signal: extra.signal });
124
- frames = readdirSync(dir)
125
- .filter((f) => isPng(f) && f.startsWith(prefix) && !before.has(f))
126
- .sort()
127
- .map((f) => join(dir, f));
128
- }
129
- else {
130
- const ts = mode === "scenes" ? sceneTimes : args.timestamps;
131
- const outs = await mapPool(ts, async (t, i) => {
132
- const out = join(dir, `frame_${String(i).padStart(3, "0")}_${t}s.png`);
133
- rmSync(out, { force: true });
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()) {
138
- if (existsSync(out))
139
- frames.push(out);
140
- else
141
- skipped.push(ts[i]);
142
- }
143
- }
144
- const inline = args.returnImages === false
145
- ? { images: [], omitted: 0 }
146
- : await encodeInlineImages(frames, args.maxImageWidth ?? DEFAULT_MAX_IMAGE_WIDTH, clampInlineCount(args.maxInlineImages));
147
- return okResponse({
148
- frameDir: dir,
149
- frameCount: frames.length,
150
- frames,
151
- mode: plan
152
- ? `fps=${plan.fps}${args.dedupe ? " (deduped)" : ""}`
153
- : scenes
154
- ? `scenes (threshold ${args.sceneThreshold ?? DEFAULT_SCENE_THRESHOLD})`
155
- : `timestamps=[${args.timestamps.join(", ")}]`,
156
- ...(scenes
157
- ? {
158
- frameTimes: sceneTimes,
159
- sceneChangesFound: scenes.length,
160
- ...(scenes.length + 1 > maxFrames
161
- ? {
162
- capNote: `Found ${scenes.length} scene changes; kept the opening frame and the ` +
163
- `${maxFrames - 1} strongest (maxFrames ${maxFrames}). Raise sceneThreshold ` +
164
- "to keep only bigger changes, or raise maxFrames.",
165
- }
166
- : {}),
167
- }
168
- : {}),
169
- ...(plan?.clamped
170
- ? {
171
- requestedFps: args.fps,
172
- capNote: `fps=${args.fps} would write about ${plan.requestedFrames} frames, over ` +
173
- `maxFrames (${maxFrames}); sampled at fps=${plan.fps} instead so the ` +
174
- `frames still span the whole video. Raise maxFrames or use timestamps for more detail.`,
175
- }
176
- : {}),
177
- ...(plan && !plan.clamped && frames.length >= maxFrames
178
- ? { capNote: `Stopped at maxFrames (${maxFrames}); the video's length could not be probed in advance.` }
179
- : {}),
180
- inlineImages: inline.images.length,
181
- ...(inline.omitted > 0
182
- ? {
183
- inlineNote: `Embedded the first ${inline.images.length} of ${frames.length} frames inline; ` +
184
- `the other ${inline.omitted} are on disk at the listed paths.`,
185
- }
186
- : {}),
187
- ...(skipped.length > 0
188
- ? {
189
- skippedTimestamps: skipped,
190
- note: `No frame was written for ${skipped.length} timestamp(s) past the ` +
191
- `end of the video: [${skipped.join(", ")}].`,
192
- }
193
- : {}),
194
- }, inline.images);
195
- }
196
- catch (error) {
197
- return errorResponse(error);
198
- }
199
- });
200
- }
@@ -1,90 +0,0 @@
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
- }
@@ -1,44 +0,0 @@
1
- import { z } from "zod";
2
- import { existsSync } from "node:fs";
3
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
- import { OUTPUT_PATH, WRITES_FILE } from "../utils/toolSpec.js";
5
- import { requireFfmpeg } from "../utils/ffmpeg.js";
6
- import { runEditJob, probeDuration } from "../utils/jobs.js";
7
- import { buildScaleArgs, editOutputExt, assertEditContainer } from "../utils/media.js";
8
- import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
9
- const inputSchema = {
10
- input: z.string().min(1).describe("Path to the source video."),
11
- width: z.number().int().positive().optional().describe("Target width in px. Omit to derive from height (keeps aspect)."),
12
- height: z.number().int().positive().optional().describe("Target height in px. Omit to derive from width (keeps aspect)."),
13
- output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
14
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
15
- };
16
- export function register(server) {
17
- server.registerTool("scale", {
18
- title: "Scale Video",
19
- description: "Resize a video to a target width and/or height and re-encode. Provide one " +
20
- "side to keep the aspect ratio, or both to set an exact size.",
21
- inputSchema,
22
- outputSchema: OUTPUT_PATH,
23
- annotations: WRITES_FILE,
24
- }, async (args, extra) => {
25
- try {
26
- requireFfmpeg();
27
- if (!existsSync(args.input)) {
28
- throw new ScreencastError(`Input file not found: ${args.input}`);
29
- }
30
- assertEditContainer(args.output);
31
- const ext = editOutputExt(args.input);
32
- const output = resolveOutput(args.output, subdir("edits"), `scale-${stamp()}-${rand()}${ext}`, args.overwrite);
33
- const ffArgs = buildScaleArgs(args.input, output, {
34
- width: args.width,
35
- height: args.height,
36
- });
37
- await runEditJob(ffArgs, { output, durationSec: await probeDuration(args.input), extra });
38
- return okResponse({ outputPath: output });
39
- }
40
- catch (error) {
41
- return errorResponse(error);
42
- }
43
- });
44
- }
@@ -1,86 +0,0 @@
1
- import { z } from "zod";
2
- import { existsSync, rmSync } from "node:fs";
3
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
- import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
5
- import { requireFfmpeg, runCapture, runFfmpeg, runFfmpegBuffer, probeMedia } from "../utils/ffmpeg.js";
6
- import { detectionSize, diffFrames, buildRawFrameArgs, buildSsimArgs, buildHighlightArgs, parseSsim, DEFAULT_PIXEL_THRESHOLD, } from "../utils/diff.js";
7
- import { stamp, rand } from "../utils/paths.js";
8
- import { tmpdir } from "node:os";
9
- import { join } from "node:path";
10
- import { encodeInlineImages, DEFAULT_MAX_IMAGE_WIDTH } from "../utils/images.js";
11
- const inputSchema = {
12
- a: z.string().min(1).describe("Before image (or video: first frame)."),
13
- b: z.string().min(1).describe("After image (or video); scaled to a's size."),
14
- pixelThreshold: z
15
- .number()
16
- .min(0)
17
- .max(255)
18
- .optional()
19
- .describe(`Mean 0-255 difference for a ~32x32 cell to count as changed (default ${DEFAULT_PIXEL_THRESHOLD}).`),
20
- returnImage: z
21
- .boolean()
22
- .optional()
23
- .describe("Return b inline with changes outlined (default true)."),
24
- };
25
- export function register(server) {
26
- server.registerTool("screen_diff", {
27
- title: "Screen Diff",
28
- description: "Compare two screenshots or frames: SSIM score, changed share, and changed boxes in b's " +
29
- "pixels, to check a UI change happened only where expected.",
30
- inputSchema,
31
- outputSchema: looseOutput({
32
- identical: z.boolean(),
33
- ssim: z.number().nullable(),
34
- meanDiff: z.number(),
35
- changedFraction: z.number(),
36
- regions: z.array(z.unknown()),
37
- }),
38
- annotations: READ_ONLY,
39
- }, async (args, extra) => {
40
- try {
41
- requireFfmpeg();
42
- for (const f of [args.a, args.b]) {
43
- if (!existsSync(f))
44
- throw new ScreencastError(`Input file not found: ${f}`);
45
- }
46
- const [ia, ib] = await Promise.all([probeMedia(args.a), probeMedia(args.b)]);
47
- if (!ia.width || !ia.height)
48
- throw new ScreencastError(`Could not read the size of ${args.a}.`);
49
- const size = detectionSize(ia.width, ia.height);
50
- const [ra, rb, ssimRun] = await Promise.all([
51
- runFfmpegBuffer(buildRawFrameArgs(args.a, size), 30_000, { signal: extra.signal }),
52
- runFfmpegBuffer(buildRawFrameArgs(args.b, size), 30_000, { signal: extra.signal }),
53
- runCapture(requireFfmpeg().ffmpeg, buildSsimArgs(args.a, args.b, size), 30_000, { signal: extra.signal }),
54
- ]);
55
- const diff = diffFrames(ra, rb, size.width, size.height, {
56
- scaleX: (ib.width ?? ia.width) / size.width,
57
- scaleY: (ib.height ?? ia.height) / size.height,
58
- pixelThreshold: args.pixelThreshold,
59
- });
60
- const images = [];
61
- if (args.returnImage !== false) {
62
- const highlighted = join(tmpdir(), `screencast-diff-${stamp()}-${rand()}.png`);
63
- try {
64
- await runFfmpeg(buildHighlightArgs(args.b, diff.regions, highlighted), 30_000, { signal: extra.signal });
65
- images.push(...(await encodeInlineImages([highlighted], DEFAULT_MAX_IMAGE_WIDTH, 1)).images);
66
- }
67
- finally {
68
- rmSync(highlighted, { force: true });
69
- }
70
- }
71
- return okResponse({
72
- identical: diff.regions.length === 0,
73
- ssim: parseSsim(ssimRun.stderr),
74
- meanDiff: Number(diff.meanDiff.toFixed(4)),
75
- changedFraction: Number(diff.changedFraction.toFixed(4)),
76
- regions: diff.regions,
77
- ...(ib.width !== ia.width || ib.height !== ia.height
78
- ? { note: `b (${ib.width}x${ib.height}) was compared at a's size (${ia.width}x${ia.height}).` }
79
- : {}),
80
- }, images);
81
- }
82
- catch (error) {
83
- return errorResponse(error);
84
- }
85
- });
86
- }
@@ -1,76 +0,0 @@
1
- import { z } from "zod";
2
- import { errorResponse, okResponse } from "../utils/errors.js";
3
- import { WRITES_FILE, looseOutput } from "../utils/toolSpec.js";
4
- import { requireFfmpeg } from "../utils/ffmpeg.js";
5
- import { captureStill } from "../utils/still.js";
6
- import { resolveCaptureTarget } from "../utils/resolveTarget.js";
7
- import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
8
- import { encodeInlineImages, DEFAULT_MAX_IMAGE_WIDTH } from "../utils/images.js";
9
- import { windowMatchReport } from "../utils/windows.js";
10
- import { confirmCapture, describeTarget } from "../utils/consent.js";
11
- const inputSchema = {
12
- target: z
13
- .string()
14
- .describe("full | monitor:<i> (0 = primary) | window:<title> (or window:exe=<app.exe> / window:hwnd=<n>) | " +
15
- "region:<x>,<y>,<w>,<h>. Titles match exactly, else as a substring; topmost wins."),
16
- exactTitle: z
17
- .boolean()
18
- .optional()
19
- .describe("window: targets match the whole title only, never a substring (default false)."),
20
- backend: z
21
- .enum(["gdigrab", "wgc"])
22
- .optional()
23
- .describe("gdigrab (default, ~0.2 s): what is visible. wgc (window:, FFmpeg 8+, ~1-2 s): the window even if covered."),
24
- output: z
25
- .string()
26
- .optional()
27
- .describe("Optional output .png path. Defaults to a file under SCREENCAST_HOME/screenshots."),
28
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
29
- returnImage: z
30
- .boolean()
31
- .optional()
32
- .describe("Return the image inline (default true; the PNG on disk stays full size)."),
33
- maxImageWidth: z
34
- .number()
35
- .int()
36
- .min(16)
37
- .optional()
38
- .describe(`Max inline image width (default ${DEFAULT_MAX_IMAGE_WIDTH}).`),
39
- };
40
- export function register(server) {
41
- server.registerTool("screenshot", {
42
- title: "Take Screenshot",
43
- description: "Capture one PNG of the screen, a monitor, a window, or a region, returned inline and by path.",
44
- inputSchema,
45
- outputSchema: looseOutput({
46
- outputPath: z.string(),
47
- target: z.string(),
48
- backend: z.string(),
49
- inlineImages: z.number().int(),
50
- }),
51
- annotations: WRITES_FILE,
52
- }, async (args, extra) => {
53
- try {
54
- requireFfmpeg();
55
- const resolved = await resolveCaptureTarget(args.target, { exactTitle: args.exactTitle, backend: args.backend });
56
- const { window } = resolved;
57
- const output = resolveOutput(args.output, subdir("screenshots"), `shot-${stamp()}-${rand()}.png`, args.overwrite);
58
- const backend = args.backend ?? "gdigrab";
59
- await confirmCapture(server, `Take a screenshot of ${describeTarget(args.target, window)}, saved to ${output}?`, extra.signal);
60
- await captureStill(resolved, output, backend);
61
- const images = args.returnImage === false
62
- ? []
63
- : (await encodeInlineImages([output], args.maxImageWidth ?? DEFAULT_MAX_IMAGE_WIDTH, 1)).images;
64
- return okResponse({
65
- outputPath: output,
66
- target: args.target,
67
- backend,
68
- ...(window ? windowMatchReport(window) : {}),
69
- inlineImages: images.length,
70
- }, images);
71
- }
72
- catch (error) {
73
- return errorResponse(error);
74
- }
75
- });
76
- }