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