@tmhs/screencast-mcp 0.49.1 → 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 (134) 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 -79
  16. package/dist/tools/bugReport.js +0 -243
  17. package/dist/tools/burnSubtitles.js +0 -56
  18. package/dist/tools/callout.js +0 -62
  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 -113
  24. package/dist/tools/convert.js +0 -46
  25. package/dist/tools/crop.js +0 -43
  26. package/dist/tools/cursor.js +0 -67
  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 -194
  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 -90
  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 -59
  47. package/dist/tools/overlay.js +0 -62
  48. package/dist/tools/pauseRecording.js +0 -44
  49. package/dist/tools/pipeline.js +0 -397
  50. package/dist/tools/readEvents.js +0 -98
  51. package/dist/tools/redactRegion.js +0 -62
  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 -249
  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 -142
  69. package/dist/tools/xfadeTransition.js +0 -58
  70. package/dist/tools/zoom.js +0 -134
  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 -117
  75. package/dist/utils/audioDevices.js +0 -107
  76. package/dist/utils/backdrop.js +0 -162
  77. package/dist/utils/bugReport.js +0 -195
  78. package/dist/utils/callout.js +0 -132
  79. package/dist/utils/calloutAssets.js +0 -42
  80. package/dist/utils/capabilities.js +0 -96
  81. package/dist/utils/captions.js +0 -104
  82. package/dist/utils/chapters.js +0 -227
  83. package/dist/utils/consent.js +0 -29
  84. package/dist/utils/cursor.js +0 -338
  85. package/dist/utils/diff.js +0 -186
  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/frameQueue.js +0 -50
  93. package/dist/utils/gpu.js +0 -219
  94. package/dist/utils/idle.js +0 -91
  95. package/dist/utils/images.js +0 -38
  96. package/dist/utils/jobs.js +0 -129
  97. package/dist/utils/keystrokes.js +0 -198
  98. package/dist/utils/lifecycle.js +0 -233
  99. package/dist/utils/logging.js +0 -75
  100. package/dist/utils/media.js +0 -584
  101. package/dist/utils/monitors.js +0 -124
  102. package/dist/utils/narrate.js +0 -233
  103. package/dist/utils/ocr.js +0 -222
  104. package/dist/utils/ocrScan.js +0 -93
  105. package/dist/utils/paths.js +0 -155
  106. package/dist/utils/pause.js +0 -190
  107. package/dist/utils/pipeline.js +0 -361
  108. package/dist/utils/player.js +0 -85
  109. package/dist/utils/pool.js +0 -29
  110. package/dist/utils/produce.js +0 -300
  111. package/dist/utils/recipes.js +0 -71
  112. package/dist/utils/recorder.js +0 -173
  113. package/dist/utils/recordingFiles.js +0 -32
  114. package/dist/utils/recordingIndex.js +0 -312
  115. package/dist/utils/replay.js +0 -283
  116. package/dist/utils/resolveTarget.js +0 -25
  117. package/dist/utils/retention.js +0 -48
  118. package/dist/utils/roots.js +0 -43
  119. package/dist/utils/sessions.js +0 -499
  120. package/dist/utils/sheet.js +0 -82
  121. package/dist/utils/stepGuide.js +0 -231
  122. package/dist/utils/steps.js +0 -88
  123. package/dist/utils/still.js +0 -38
  124. package/dist/utils/targetList.js +0 -64
  125. package/dist/utils/targets.js +0 -265
  126. package/dist/utils/timeline.js +0 -85
  127. package/dist/utils/toolSpec.js +0 -31
  128. package/dist/utils/toolsets.js +0 -134
  129. package/dist/utils/transcriptCut.js +0 -149
  130. package/dist/utils/validate.js +0 -23
  131. package/dist/utils/waitLoop.js +0 -50
  132. package/dist/utils/wgc.js +0 -84
  133. package/dist/utils/windows.js +0 -192
  134. package/dist/utils/zoom.js +0 -252
@@ -1,62 +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 { buildOverlayArgs, 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 base video."),
11
- overlay: z.string().min(1).describe("Overlay image or video path."),
12
- x: z.number().int().nonnegative().describe("Left, px."),
13
- y: z.number().int().nonnegative().describe("Top, px."),
14
- width: z.number().int().positive().optional().describe("Scale to this width (other side keeps aspect)."),
15
- height: z.number().int().positive().optional().describe("Scale to this height."),
16
- start: z.number().nonnegative().optional().describe("Show from this second."),
17
- end: z.number().positive().optional().describe("Hide after this second."),
18
- shape: z.enum(["rect", "circle"]).optional().describe("circle: centre square masked round (webcam)."),
19
- output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
20
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
21
- };
22
- export function register(server) {
23
- server.registerTool("overlay", {
24
- title: "Overlay Image or Video",
25
- description: "Composite an image or video (logo, watermark, picture-in-picture) onto a video at a pixel " +
26
- "position, optionally scaled and time-limited; keeps the base's audio and length.",
27
- inputSchema,
28
- outputSchema: OUTPUT_PATH,
29
- annotations: WRITES_FILE,
30
- }, async (args, extra) => {
31
- try {
32
- requireFfmpeg();
33
- if (!existsSync(args.input)) {
34
- throw new ScreencastError(`Input file not found: ${args.input}`);
35
- }
36
- if (!existsSync(args.overlay)) {
37
- throw new ScreencastError(`Overlay file not found: ${args.overlay}`);
38
- }
39
- assertEditContainer(args.output);
40
- const ext = editOutputExt(args.input);
41
- const output = resolveOutput(args.output, subdir("edits"), `overlay-${stamp()}-${rand()}${ext}`, args.overwrite);
42
- const scale = args.width !== undefined || args.height !== undefined
43
- ? { width: args.width, height: args.height }
44
- : undefined;
45
- const durationSec = await probeDuration(args.input);
46
- const ffArgs = buildOverlayArgs(args.input, args.overlay, output, {
47
- x: args.x,
48
- y: args.y,
49
- start: args.start,
50
- end: args.end,
51
- scale,
52
- shape: args.shape,
53
- durationSec,
54
- });
55
- await runEditJob(ffArgs, { output, durationSec, extra });
56
- return okResponse({ outputPath: output });
57
- }
58
- catch (error) {
59
- return errorResponse(error);
60
- }
61
- });
62
- }
@@ -1,44 +0,0 @@
1
- import { z } from "zod";
2
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
3
- import { STOPS_SESSION, looseOutput } from "../utils/toolSpec.js";
4
- import { probeDuration, requireFfmpeg } from "../utils/ffmpeg.js";
5
- import { pauseSession } from "../utils/lifecycle.js";
6
- import { recordedSec } from "../utils/pause.js";
7
- import { getStore } from "../context.js";
8
- const r3 = (n) => Math.round(n * 1000) / 1000;
9
- export function register(server) {
10
- server.registerTool("pause_recording", {
11
- title: "Pause Recording",
12
- description: "Pause a recording; until resume_recording nothing is captured, and the gap is left out of the file, events, and markers.",
13
- inputSchema: { sessionId: z.string().min(1).describe("From start_recording.") },
14
- outputSchema: looseOutput({ sessionId: z.string(), status: z.string(), recordedSec: z.number() }),
15
- annotations: STOPS_SESSION,
16
- }, async (args) => {
17
- try {
18
- const store = getStore();
19
- const record = store.get(args.sessionId);
20
- if (!record)
21
- throw new ScreencastError(`No session with id "${args.sessionId}".`);
22
- if (record.status === "paused") {
23
- return okResponse({
24
- sessionId: record.id,
25
- status: "paused",
26
- recordedSec: r3(recordedSec(record.segments?.parts ?? [])),
27
- note: "Already paused.",
28
- });
29
- }
30
- const { ffprobe } = requireFfmpeg();
31
- const res = await pauseSession(store, record, { probe: (p) => probeDuration(p, { ffprobe }) });
32
- return okResponse({
33
- sessionId: record.id,
34
- status: "paused",
35
- recordedSec: r3(res.recordedSec),
36
- segments: res.record?.segments?.parts.length ?? 0,
37
- note: "Nothing is captured until resume_recording; stop_recording joins what was recorded.",
38
- });
39
- }
40
- catch (error) {
41
- return errorResponse(error);
42
- }
43
- });
44
- }
@@ -1,397 +0,0 @@
1
- import { z } from "zod";
2
- import { dirname, 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, hasFilter, runCapture, runFfmpeg, scriptLongFilters } from "../utils/ffmpeg.js";
8
- import { jobTimeoutMs, runEditJob } from "../utils/jobs.js";
9
- import { planPipeline, probeArgs, sidecarCues, MAX_PIPELINE_STEPS } from "../utils/pipeline.js";
10
- import { calloutFonts, prepareCalloutAssets } from "../utils/calloutAssets.js";
11
- import { exportAnimation } from "../utils/animExport.js";
12
- import { assertEditContainer, redactRegionSchema, REDACT_STYLES } from "../utils/media.js";
13
- import { resolveOutput, subdir, stamp, rand } from "../utils/paths.js";
14
- import { PLATFORMS, ASPECTS, REFRAME_FITS } from "../utils/produce.js";
15
- import { buildChapters, ffmetadata, markerPoints, markersOrChapters, retimeMarkers, writeMarkers } from "../utils/chapters.js";
16
- import { cursorSpritePath, cursorOptionsSchema, loadCursor } from "../utils/cursor.js";
17
- import { MAX_ZOOM, readClicks, zoomKeyframeSchema } from "../utils/zoom.js";
18
- import { buildIdleScanArgs, intersect, parseFreezes, parseSilences, DEFAULT_MIN_IDLE_SEC } from "../utils/idle.js";
19
- import { buildLoudnessMeasureArgs, buildNoiseFloorArgs, loudnessTarget, parseLoudnorm, parseNoiseFloor, DENOISE_STRENGTHS, loudnessTargetSchema } from "../utils/audio.js";
20
- import { buildTranscribeArgs, formatSrt, normalizeCues, parseSrt, resolveWhisperModel, CAPTION_STYLE_NAMES } from "../utils/captions.js";
21
- import { eventPaths } from "../utils/events.js";
22
- import { bundledFontPath } from "../utils/fonts.js";
23
- import { retimeAss, retimeCues } from "../utils/timeline.js";
24
- import { applyOverrides, recipeSteps, RECIPES } from "../utils/recipes.js";
25
- import { calloutItemSchema, fontFileSchema } from "../utils/callout.js";
26
- import { backdropOptionsSchema } from "../utils/backdrop.js";
27
- import { keystrokeOptionsSchema, loadBadges, prepareKeystrokeAssets } from "../utils/keystrokes.js";
28
- function transcribeBlocker() {
29
- if (!hasFilter("whisper"))
30
- return "this ffmpeg has no whisper filter (FFmpeg 8 with whisper.cpp).";
31
- try {
32
- resolveWhisperModel(undefined);
33
- return null;
34
- }
35
- catch {
36
- return "no whisper model (set SCREENCAST_WHISPER_MODEL).";
37
- }
38
- }
39
- const aspect = z.enum(ASPECTS);
40
- const fit = z.enum(REFRAME_FITS).optional();
41
- const step = z.discriminatedUnion("op", [
42
- z.object({
43
- op: z.literal("trim"),
44
- start: z.number().nonnegative(),
45
- end: z.number().positive().optional(),
46
- duration: z.number().positive().optional(),
47
- }),
48
- z.object({
49
- op: z.literal("crop"),
50
- x: z.number().int().nonnegative(),
51
- y: z.number().int().nonnegative(),
52
- width: z.number().int().positive(),
53
- height: z.number().int().positive(),
54
- }),
55
- z.object({ op: z.literal("scale"), width: z.number().int().positive().optional(), height: z.number().int().positive().optional() }),
56
- z.object({ op: z.literal("speed"), factor: z.number().positive() }),
57
- z.object({
58
- op: z.literal("redact"),
59
- regions: z.array(redactRegionSchema).min(1),
60
- style: z.enum(REDACT_STYLES).optional(),
61
- pad: z.number().int().nonnegative().optional(),
62
- color: z.string().optional(),
63
- }),
64
- z.object({ op: z.literal("callout"), items: z.array(calloutItemSchema).min(1).max(50), fontFile: fontFileSchema }),
65
- z.object({ op: z.literal("reframe"), aspect, fit }),
66
- z.object({
67
- op: z.literal("zoom"),
68
- keyframes: z.array(zoomKeyframeSchema).min(1).max(100).optional(),
69
- follow: z.literal("clicks").optional(),
70
- maxZoom: z.number().min(1).max(MAX_ZOOM).optional(),
71
- holdSec: z.number().positive().max(30).optional(),
72
- transitionSec: z.number().positive().max(5).optional(),
73
- }),
74
- z.object({ op: z.literal("cut_idle"), minIdleSec: z.number().positive().optional(), keepSec: z.number().min(0).optional() }),
75
- z.object({
76
- op: z.literal("audio"),
77
- normalize: loudnessTargetSchema.optional(),
78
- denoise: z.enum(DENOISE_STRENGTHS).optional(),
79
- }),
80
- z.object({
81
- op: z.literal("burn_subtitles"),
82
- subtitles: z.string().min(1).optional(),
83
- transcribe: z.boolean().optional(),
84
- style: z.enum(CAPTION_STYLE_NAMES).optional(),
85
- }),
86
- z.object({ op: z.literal("backdrop"), ...backdropOptionsSchema }),
87
- z.object({ op: z.literal("keystroke_overlay"), ...keystrokeOptionsSchema }),
88
- z.object({ op: z.literal("cursor"), ...cursorOptionsSchema }),
89
- z.object({ op: z.literal("export_preset"), platform: z.enum(PLATFORMS), fit }),
90
- z.object({
91
- op: z.literal("export_gif"),
92
- format: z.enum(["gif", "webp"]).optional(),
93
- maxBytes: z.number().int().min(10_000).optional(),
94
- fps: z.number().positive().max(30).optional(),
95
- width: z.number().int().min(64).max(1920).optional(),
96
- }),
97
- ]);
98
- const inputSchema = {
99
- input: z.string().min(1).describe("Path to the source video."),
100
- steps: z
101
- .array(step)
102
- .max(MAX_PIPELINE_STEPS)
103
- .optional()
104
- .describe("Edits in order, each { op, ...its tool's options }; export_preset/export_gif only last. Times " +
105
- "and pixels are relative to the video as it is at that step (after earlier trims, speed, crops). " +
106
- "zoom follow:\"clicks\" plans from the event log; burn_subtitles takes subtitles or transcribe:true."),
107
- recipe: z
108
- .enum(RECIPES)
109
- .optional()
110
- .describe("Polish preset expanded to steps (see dryRun): pr_demo = cut_idle, click zoom, GIF <=10 MB; tutorial = " +
111
- "+ audio, captions, 1080p mp4; social_reel = 9:16, big captions. Given steps replace its same-op step; " +
112
- "trim, redact, crop and cursor go first (source pixels and time)."),
113
- quality: z.enum(["draft", "standard", "high"]).optional().describe("Encoder preset for an mp4 result (default standard)."),
114
- dryRun: z.boolean().optional().describe("Return the plan (ffmpeg command, output size) without running it."),
115
- output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
116
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
117
- chapters: z
118
- .boolean()
119
- .optional()
120
- .describe("Keep the input's markers as chapters, re-timed through trims and speed."),
121
- };
122
- export function register(server) {
123
- server.registerTool("pipeline", {
124
- title: "Edit Pipeline",
125
- description: "Run several edits (trim, crop, scale, speed, cut_idle, redact, callout, keystroke_overlay, cursor, reframe, zoom, backdrop, " +
126
- "audio, burn_subtitles, then optionally export_preset or export_gif) in one ffmpeg pass: one re-encode, no " +
127
- "intermediate files. Prefer it over chaining edit tools; a recipe does the usual polish in one call.",
128
- inputSchema,
129
- outputSchema: looseOutput({ processes: z.number().int(), steps: z.array(z.string()) }),
130
- annotations: WRITES_FILE,
131
- }, async (args, extra) => {
132
- try {
133
- const { ffmpeg } = requireFfmpeg();
134
- if (!existsSync(args.input))
135
- throw new ScreencastError(`Input file not found: ${args.input}`);
136
- const info = await probeMedia(args.input);
137
- const hasAudio = info.audioCodec !== null;
138
- const warnings = [];
139
- let steps = (args.steps ?? []);
140
- if (args.recipe) {
141
- const logged = readClicks(eventPaths(args.input).jsonl);
142
- const r = recipeSteps(args.recipe, {
143
- hasAudio,
144
- hasClicks: !!logged && logged.length > 0,
145
- transcribeBlocker: hasAudio ? transcribeBlocker() : null,
146
- });
147
- steps = applyOverrides(r.steps, steps);
148
- warnings.push(...r.notes);
149
- }
150
- if (steps.length === 0)
151
- throw new ScreencastError("Give steps, a recipe, or both.");
152
- if (steps.length > MAX_PIPELINE_STEPS)
153
- throw new ScreencastError(`At most ${MAX_PIPELINE_STEPS} steps.`);
154
- if (!info.width || !info.height)
155
- throw new ScreencastError(`Could not read the size of ${args.input}.`);
156
- const src = {
157
- width: info.width,
158
- height: info.height,
159
- fps: info.fps ?? 30,
160
- durationSec: info.durationSec,
161
- hasAudio,
162
- };
163
- const timeout = jobTimeoutMs(info.durationSec);
164
- const last = steps.at(-1);
165
- if (!last)
166
- throw new ScreencastError("Provide at least one step.");
167
- if (last.op !== "export_gif")
168
- assertEditContainer(args.output);
169
- const ext = last.op === "export_gif" ? `.${last.format ?? "gif"}` : ".mp4";
170
- const output = resolveOutput(args.output, subdir("edits"), `pipeline-${stamp()}-${rand()}${ext}`, args.overwrite);
171
- const transcribes = last.op !== "export_gif" && steps.some((s) => s.op === "burn_subtitles" && s.transcribe);
172
- const sidecar = output.replace(/\.[^./\\]+$/, "") + ".srt";
173
- if (transcribes && !args.overwrite && existsSync(sidecar)) {
174
- throw new ScreencastError(`Output already exists: ${sidecar}. Pass overwrite: true to replace it.`);
175
- }
176
- for (const [i, s] of steps.entries()) {
177
- if (s.op !== "burn_subtitles")
178
- continue;
179
- if (!hasFilter("subtitles")) {
180
- throw new ScreencastError("This ffmpeg has no subtitles filter (it needs libass).", "Install a full ffmpeg build, e.g. `winget install Gyan.FFmpeg`.");
181
- }
182
- if (s.subtitles && !existsSync(s.subtitles))
183
- throw new ScreencastError(`step ${i + 1}: subtitles file not found: ${s.subtitles}`);
184
- if (s.transcribe) {
185
- if (!hasFilter("whisper"))
186
- throw new ScreencastError(`step ${i + 1}: transcribe needs FFmpeg 8 built with whisper.cpp (no whisper filter here).`);
187
- resolveWhisperModel(undefined);
188
- }
189
- }
190
- const clicks = {};
191
- for (const [i, s] of steps.entries()) {
192
- if (s.op !== "zoom" || s.follow !== "clicks")
193
- continue;
194
- const path = eventPaths(args.input).jsonl;
195
- const logged = readClicks(path);
196
- if (!logged)
197
- throw new ScreencastError(`step ${i + 1}: no event log at ${path}; record with start_recording events: true.`);
198
- clicks[i] = logged;
199
- }
200
- let idle;
201
- const idleAt = steps.findIndex((s) => s.op === "cut_idle");
202
- const idleStep = steps[idleAt];
203
- if (idleStep?.op === "cut_idle") {
204
- const total = info.durationSec;
205
- if (total === null)
206
- throw new ScreencastError(`Could not read the duration of ${args.input}.`);
207
- const speedUp = steps.slice(0, idleAt).reduce((f, x) => (x.op === "speed" ? f * x.factor : f), 1);
208
- const useAudio = hasAudio;
209
- const scan = await runCapture(ffmpeg, buildIdleScanArgs(args.input, (idleStep.minIdleSec ?? DEFAULT_MIN_IDLE_SEC) * speedUp, useAudio), timeout, {
210
- signal: extra.signal,
211
- });
212
- if (scan.code !== 0)
213
- throw new ScreencastError(`Idle scan failed (exit ${scan.code}): ${scan.stderr.trim().slice(-400)}`);
214
- const freezes = parseFreezes(scan.stderr, total);
215
- idle = useAudio ? intersect(freezes, parseSilences(scan.stderr, total)) : freezes;
216
- }
217
- const work = mkdtempSync(join(tmpdir(), "screencast-pipeline-"));
218
- try {
219
- const assets = {};
220
- const fallbackFonts = [];
221
- for (const [i, s] of steps.entries()) {
222
- if (s.op !== "callout")
223
- continue;
224
- const a = args.dryRun
225
- ? { fontFile: "<font>", textFiles: s.items.map((c) => (c.type === "text" ? "<text>" : null)), arrowFiles: s.items.map((c) => (c.type === "arrow" ? "<arrow.png>" : null)), ...calloutFonts(s.items, s.fontFile) }
226
- : await prepareCalloutAssets(s.items, work, `s${i}_`, s.fontFile);
227
- assets[i] = a;
228
- fallbackFonts.push(...a.fallbackFonts.map((f) => ({ step: i, ...f })));
229
- warnings.push(...a.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
230
- }
231
- const keystrokes = {};
232
- for (const [i, s] of steps.entries()) {
233
- if (s.op === "backdrop" && s.image && !existsSync(s.image)) {
234
- throw new ScreencastError(`step ${i + 1}: background image not found: ${s.image}`);
235
- }
236
- if (s.op !== "keystroke_overlay")
237
- continue;
238
- const { badges } = loadBadges(args.input, s.events, s);
239
- const labels = [...new Set(badges.map((b) => b.label))];
240
- const k = prepareKeystrokeAssets(labels, args.dryRun ? null : work, `s${i}_`, s.fontFile);
241
- keystrokes[i] = { badges, fontFile: k.fontFile, textFiles: k.textFiles };
242
- warnings.push(...k.warnings.map((w) => `Step ${i}, ${w.charAt(0).toLowerCase()}${w.slice(1)}`));
243
- }
244
- const cursor = {};
245
- for (const [i, s] of steps.entries()) {
246
- if (s.op !== "cursor")
247
- continue;
248
- cursor[i] = {
249
- plan: loadCursor(args.input, s.events, s, info.durationSec),
250
- sprite: cursorSpritePath(),
251
- commandsFile: args.dryRun ? `<cursor ${i}.cmd>` : join(work, `s${i}_cursor.cmd`),
252
- };
253
- }
254
- const target = last.op === "export_gif" ? (args.dryRun ? "<temporary stage1.mp4>" : join(work, "stage1.mp4")) : output;
255
- const audioM = {};
256
- const subtitles = {};
257
- const fontsDir = dirname(bundledFontPath("regular"));
258
- const planWith = (chaptersFile) => planPipeline(args.input, target, steps, src, assets, args.quality ?? "standard", {
259
- keystrokes, cursor, idle, clicks, audio: audioM, subtitles, fontsDir, chaptersFile,
260
- });
261
- let plan = planWith();
262
- let transcript;
263
- for (let n = 0; !args.dryRun && plan.pending.length > 0; n++) {
264
- const p = plan.pending[0];
265
- if (n > steps.length * 3)
266
- throw new ScreencastError(`Internal: step ${p.step + 1} ${p.kind} did not resolve.`);
267
- const s = steps[p.step];
268
- const capture = async (base) => {
269
- const sc = scriptLongFilters(probeArgs(base, p));
270
- try {
271
- const r = await runCapture(ffmpeg, sc.args, timeout, { signal: extra.signal });
272
- if (r.code !== 0)
273
- throw new ScreencastError(`step ${p.step + 1} ${p.kind} scan failed (exit ${r.code}): ${r.stderr.trim().slice(-400)}`);
274
- return r;
275
- }
276
- finally {
277
- sc.cleanup();
278
- }
279
- };
280
- if (p.kind === "noisefloor") {
281
- audioM[p.step] = { ...audioM[p.step], floorDb: parseNoiseFloor((await capture(buildNoiseFloorArgs(args.input))).stdout) };
282
- }
283
- else if (p.kind === "loudness" && s.op === "audio") {
284
- const r = await capture(buildLoudnessMeasureArgs(args.input, loudnessTarget(s.normalize)));
285
- try {
286
- audioM[p.step] = { ...audioM[p.step], loudness: parseLoudnorm(r.stderr) };
287
- }
288
- catch {
289
- warnings.push(`Step ${p.step + 1}: the audio is silent; not normalized.`);
290
- audioM[p.step] = { ...audioM[p.step], silent: true };
291
- }
292
- }
293
- else if (p.kind === "transcribe" && s.op === "burn_subtitles") {
294
- const raw = join(work, `s${p.step}_raw.srt`);
295
- await runFfmpeg(probeArgs(buildTranscribeArgs(args.input, resolveWhisperModel(undefined), raw), p), timeout, {
296
- signal: extra.signal,
297
- });
298
- const cues = existsSync(raw) ? normalizeCues(parseSrt(readFileSync(raw, "utf8"))) : [];
299
- subtitles[p.step] = cues.length > 0 ? join(work, `s${p.step}.srt`) : "";
300
- if (cues.length > 0) {
301
- transcript = { cues, opsBefore: p.ops.length };
302
- writeFileSync(subtitles[p.step], formatSrt(cues));
303
- }
304
- else
305
- warnings.push(`Step ${p.step + 1}: no speech was recognised; no captions.`);
306
- }
307
- else if (p.kind === "subtitles" && s.op === "burn_subtitles" && s.subtitles) {
308
- if (p.ops.length === 0)
309
- subtitles[p.step] = s.subtitles;
310
- else {
311
- const text = readFileSync(s.subtitles, "utf8");
312
- const ass = /\.(ass|ssa)$/i.test(s.subtitles);
313
- const moved = ass ? retimeAss(text, p.ops) : formatSrt(retimeCues(normalizeCues(parseSrt(text)), p.ops));
314
- const file = join(work, `s${p.step}${ass ? ".ass" : ".srt"}`);
315
- writeFileSync(file, moved);
316
- subtitles[p.step] = ass || moved.trim() ? file : "";
317
- }
318
- }
319
- else {
320
- throw new ScreencastError(`Internal: step ${p.step + 1} cannot resolve ${p.kind}.`);
321
- }
322
- plan = planWith();
323
- }
324
- let chapterList = [];
325
- let retimed = [];
326
- if (args.chapters) {
327
- const found = plan.gif ? null : await markersOrChapters(args.input, extra.signal);
328
- if (!found)
329
- warnings.push("chapters: a GIF/WebP cannot hold chapters; none written.");
330
- else if (found.markers.length === 0)
331
- warnings.push("chapters: the input has no markers (add_marker) or chapters; none written.");
332
- else {
333
- retimed = retimeMarkers(found.markers, plan.timeOps);
334
- chapterList = plan.durationSec ? buildChapters(markerPoints(retimed), plan.durationSec) : [];
335
- if (chapterList.length === 0)
336
- warnings.push("chapters: no marker falls inside the result; none written.");
337
- else {
338
- const file = args.dryRun ? "<chapters.txt>" : join(work, "chapters.txt");
339
- if (!args.dryRun)
340
- writeFileSync(file, ffmetadata(chapterList));
341
- plan = planWith(file);
342
- }
343
- }
344
- }
345
- const result = {
346
- ...(args.recipe && { recipe: args.recipe, expandedSteps: steps }),
347
- steps: plan.summary,
348
- ...(args.dryRun && plan.pending.length > 0 && { measuredOnRun: plan.pending.map((p) => `step ${p.step + 1}: ${p.kind}`) }),
349
- processes: plan.gif ? 2 : 1,
350
- width: plan.width,
351
- height: plan.height,
352
- durationSec: plan.durationSec,
353
- ...(fallbackFonts.length > 0 && { fallbackFonts }),
354
- ...(warnings.length > 0 && { warnings }),
355
- ...(chapterList.length > 0 && { chapters: chapterList }),
356
- };
357
- if (args.dryRun)
358
- return okResponse({ dryRun: true, ...result, ffmpegArgs: plan.args });
359
- for (const f of plan.files)
360
- writeFileSync(f.path, f.content);
361
- await runEditJob(plan.args, { output: target, durationSec: plan.durationSec, inputDurationSec: info.durationSec, extra });
362
- if (plan.gif) {
363
- const anim = await exportAnimation(target, output, plan.gif, extra);
364
- return okResponse({ outputPath: output, ...result, animation: anim });
365
- }
366
- let subtitlesPath;
367
- if (transcript) {
368
- try {
369
- const cues = sidecarCues(transcript.cues, plan.timeOps, transcript.opsBefore);
370
- if (cues.length > 0) {
371
- writeFileSync(sidecar, formatSrt(cues));
372
- subtitlesPath = sidecar;
373
- }
374
- }
375
- catch {
376
- subtitlesPath = undefined;
377
- }
378
- }
379
- let markersPath;
380
- if (chapterList.length > 0) {
381
- try {
382
- markersPath = writeMarkers(output, retimed.filter((m) => m.t < (plan.durationSec ?? Infinity)));
383
- }
384
- catch {
385
- }
386
- }
387
- return okResponse({ outputPath: output, ...result, ...(markersPath && { markersPath }), ...(subtitlesPath && { subtitlesPath }) });
388
- }
389
- finally {
390
- rmSync(work, { recursive: true, force: true });
391
- }
392
- }
393
- catch (error) {
394
- return errorResponse(error);
395
- }
396
- });
397
- }
@@ -1,98 +0,0 @@
1
- import { z } from "zod";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { errorResponse, okResponse, ScreencastError } from "../utils/errors.js";
4
- import { READ_ONLY, looseOutput } from "../utils/toolSpec.js";
5
- import { EVENT_TYPES, eventPaths, parseEventsJsonl, selectEvents, summarizeEvents, eventGaps, } from "../utils/events.js";
6
- import { getStore } from "../context.js";
7
- export const DEFAULT_EVENT_LIMIT = 200;
8
- export const MAX_EVENT_LIMIT = 5000;
9
- const inputSchema = {
10
- sessionId: z.string().min(1).optional().describe("Session id of a recording started with events: true."),
11
- input: z
12
- .string()
13
- .optional()
14
- .describe("Or a recording path, or its .events.jsonl."),
15
- from: z.number().min(0).optional().describe("Earliest video second."),
16
- to: z.number().min(0).optional().describe("Latest video second."),
17
- types: z
18
- .array(z.enum(EVENT_TYPES))
19
- .optional()
20
- .describe("down/up (mouse buttons; clicks are down), move (sampled cursor), wheel, key (shortcut), " +
21
- "typing (burst), gap (events may be missing)."),
22
- inFrameOnly: z.boolean().optional().describe("Drop events whose cursor was outside the recorded area."),
23
- limit: z
24
- .number()
25
- .int()
26
- .min(1)
27
- .max(MAX_EVENT_LIMIT)
28
- .optional()
29
- .describe(`Most events to return (default ${DEFAULT_EVENT_LIMIT}).`),
30
- };
31
- export function register(server) {
32
- server.registerTool("read_events", {
33
- title: "Read Input Events",
34
- description: "Read the input events (clicks, scroll, cursor, shortcuts, typing bursts) of a recording made " +
35
- "with events: true, in video seconds and pixels; e.g. types: ['down'], then sample_frames there.",
36
- inputSchema,
37
- outputSchema: looseOutput({
38
- eventsPath: z.string(),
39
- total: z.number().int(),
40
- matched: z.number().int(),
41
- returned: z.number().int(),
42
- summary: z.record(z.string(), z.number()),
43
- }),
44
- annotations: READ_ONLY,
45
- }, async (args) => {
46
- try {
47
- let path;
48
- if (args.sessionId) {
49
- const record = getStore().get(args.sessionId);
50
- if (!record)
51
- throw new ScreencastError(`No session with id "${args.sessionId}".`);
52
- if (!record.events) {
53
- throw new ScreencastError(`Session "${args.sessionId}" was recorded without an event log. ` +
54
- "Start the recording with events: true.");
55
- }
56
- if (record.status === "recording" || record.status === "paused") {
57
- throw new ScreencastError("The recording is still running; its event log is written when it stops.");
58
- }
59
- path = record.events.path;
60
- }
61
- else if (args.input) {
62
- path = args.input.endsWith(".jsonl") ? args.input : eventPaths(args.input).jsonl;
63
- }
64
- else {
65
- throw new ScreencastError("Pass sessionId or input.");
66
- }
67
- if (!existsSync(path)) {
68
- throw new ScreencastError(`No event log at ${path}. Record with start_recording events: true.`);
69
- }
70
- const all = parseEventsJsonl(readFileSync(path, "utf8"));
71
- const matched = selectEvents(all, args);
72
- const limit = args.limit ?? DEFAULT_EVENT_LIMIT;
73
- const gaps = eventGaps(all);
74
- return okResponse({
75
- eventsPath: path,
76
- total: all.length,
77
- matched: matched.length,
78
- returned: Math.min(limit, matched.length),
79
- summary: summarizeEvents(all),
80
- ...(gaps.length > 0
81
- ? {
82
- truncated: true,
83
- gaps,
84
- warning: "The log is missing events in the gaps listed: Windows removed the input hook, input went to an " +
85
- "elevated window or the lock screen, or the helper stopped. Do not read silence there as no activity.",
86
- }
87
- : {}),
88
- events: matched.slice(0, limit),
89
- ...(matched.length > limit
90
- ? { note: `${matched.length - limit} more matched; narrow from/to or types, or raise limit.` }
91
- : {}),
92
- });
93
- }
94
- catch (error) {
95
- return errorResponse(error);
96
- }
97
- });
98
- }
@@ -1,62 +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, probeMedia } from "../utils/ffmpeg.js";
6
- import { runEditJob } from "../utils/jobs.js";
7
- import { buildRedactArgs, stillEdit, redactRegionSchema, REDACT_STYLES } 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 or image (png/jpg; time ranges are ignored for an image)."),
11
- regions: z
12
- .array(redactRegionSchema)
13
- .min(1)
14
- .describe("Pixel rectangles (x, y, width, height), each optionally limited to start..end seconds."),
15
- style: z
16
- .enum(REDACT_STYLES)
17
- .optional()
18
- .describe("box (default): irreversible fill; blur/pixelate are partially recoverable."),
19
- pad: z
20
- .number()
21
- .int()
22
- .nonnegative()
23
- .optional()
24
- .describe("Grow each region by this many px (default 0)."),
25
- color: z.string().optional().describe("Box fill color (default black)."),
26
- output: z.string().optional().describe("Optional output path. Defaults under SCREENCAST_HOME/edits."),
27
- overwrite: z.boolean().optional().describe("Allow replacing an existing file at the output path (default false)."),
28
- };
29
- export function register(server) {
30
- server.registerTool("redact_region", {
31
- title: "Redact Regions",
32
- description: "Cover given rectangles in a video or screenshot (e.g. secrets on screen). Not automatic detection: find " +
33
- "them with find_text redact: true. Off-frame regions are rejected.",
34
- inputSchema,
35
- outputSchema: OUTPUT_PATH,
36
- annotations: WRITES_FILE,
37
- }, async (args, extra) => {
38
- try {
39
- requireFfmpeg();
40
- if (!existsSync(args.input)) {
41
- throw new ScreencastError(`Input file not found: ${args.input}`);
42
- }
43
- const { width, height, durationSec } = await probeMedia(args.input);
44
- const { still, ext } = stillEdit(args.input, args.output);
45
- const output = resolveOutput(args.output, subdir("edits"), `redact-${stamp()}-${rand()}${ext}`, args.overwrite);
46
- const ffArgs = buildRedactArgs(args.input, output, args.regions, {
47
- style: args.style,
48
- pad: args.pad,
49
- color: args.color,
50
- }, { width, height }, still);
51
- await runEditJob(ffArgs, { output, durationSec: still ? null : durationSec, extra });
52
- return okResponse({
53
- outputPath: output,
54
- regions: args.regions.length,
55
- style: args.style ?? "box",
56
- });
57
- }
58
- catch (error) {
59
- return errorResponse(error);
60
- }
61
- });
62
- }