@tmhs/screencast-mcp 0.47.0 → 0.48.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.
@@ -1,4 +1,8 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
2
6
  import { ScreencastError } from "./errors.js";
3
7
  export function parseMonitors(raw) {
4
8
  const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];
@@ -43,11 +47,37 @@ export function psTimeoutMs(fallback, env = process.env) {
43
47
  const override = Number(env[PS_TIMEOUT_ENV]);
44
48
  return Number.isInteger(override) && override > 0 ? override : fallback;
45
49
  }
50
+ export const MAX_COMMAND_LINE_CHARS = 32_767;
51
+ export function payloadPreamble(path) {
52
+ const b64 = Buffer.from(path, "utf8").toString("base64");
53
+ return `$Payload = [IO.File]::ReadAllText([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64}')), [Text.Encoding]::UTF8)\n`;
54
+ }
55
+ export function powerShellArgs(script, payloadPath) {
56
+ const full = PS_UTF8_PREAMBLE + (payloadPath === undefined ? "" : payloadPreamble(payloadPath)) + script;
57
+ return ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(full, "utf16le").toString("base64")];
58
+ }
59
+ export function commandLineLength(file, args) {
60
+ return [file, ...args].reduce((n, a) => n + a.length + 3, 0);
61
+ }
62
+ export async function withPayloadFile(payload, fn) {
63
+ const path = join(tmpdir(), `screencast-ps-${process.pid}-${randomBytes(6).toString("hex")}.json`);
64
+ writeFileSync(path, payload, { encoding: "utf8", mode: 0o600 });
65
+ try {
66
+ return await fn(path);
67
+ }
68
+ finally {
69
+ rmSync(path, { force: true });
70
+ }
71
+ }
46
72
  export function runPowerShell(script, what, opts = {}) {
47
- const encoded = Buffer.from(PS_UTF8_PREAMBLE + script, "utf16le").toString("base64");
73
+ if (opts.payload === undefined)
74
+ return execPowerShell(script, what, opts);
75
+ return withPayloadFile(opts.payload, (path) => execPowerShell(script, what, opts, path));
76
+ }
77
+ function execPowerShell(script, what, opts, payloadPath) {
48
78
  const timeout = opts.timeoutMs ?? psTimeoutMs(PS_TIMEOUT_MS);
49
79
  const file = opts.command?.file ?? "powershell";
50
- const args = opts.command?.args ?? ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded];
80
+ const args = opts.command?.args ?? powerShellArgs(script, payloadPath);
51
81
  return new Promise((resolve, reject) => {
52
82
  execFile(file, args, { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout, killSignal: "SIGKILL", signal: opts.signal }, (err, stdout, stderr) => {
53
83
  if (opts.signal?.aborted) {
@@ -57,7 +87,8 @@ export function runPowerShell(script, what, opts = {}) {
57
87
  reject(new ScreencastError(`Timed out reading ${what} after ${timeout / 1000} s (PowerShell did not answer).`, `Retry; if it keeps happening, restart the app being captured or raise ${PS_TIMEOUT_ENV}.`));
58
88
  }
59
89
  else if (err || !stdout) {
60
- reject(new ScreencastError(`Could not enumerate ${what}: ${stderr?.trim() || err?.message || "powershell failed"}`));
90
+ const label = opts.failure ?? `Could not enumerate ${what}`;
91
+ reject(new ScreencastError(`${label}: ${stderr?.trim() || err?.message || "powershell failed"}`));
61
92
  }
62
93
  else {
63
94
  resolve(stdout);
@@ -138,12 +138,21 @@ const asArray = (v) => (Array.isArray(v) ? v : v === undefined || v === null ? [
138
138
  export function parseVoices(raw) {
139
139
  return asArray(raw.voices).map((v) => ({ name: String(v.name ?? ""), language: String(v.language ?? ""), gender: String(v.gender ?? "") }));
140
140
  }
141
+ export function ttsCall(request) {
142
+ return { script: PS_TTS, payload: JSON.stringify(request) };
143
+ }
141
144
  async function runTts(request, timeoutMs, signal) {
142
145
  if (process.platform !== "win32") {
143
146
  throw new ScreencastError("narrate uses the speech engine built into Windows and runs on Windows only.");
144
147
  }
145
- const req = Buffer.from(JSON.stringify(request), "utf8").toString("base64");
146
- const stdout = await runPowerShell(PS_TTS.replace("__REQ__", req), "speech voices", { timeoutMs, signal });
148
+ const { script, payload } = ttsCall(request);
149
+ const list = "list" in request;
150
+ const stdout = await runPowerShell(script, list ? "speech voices" : "the speech engine", {
151
+ timeoutMs,
152
+ signal,
153
+ payload,
154
+ failure: list ? "Could not list speech voices" : "Could not synthesize speech",
155
+ });
147
156
  try {
148
157
  return JSON.parse(stdout);
149
158
  }
@@ -193,7 +202,7 @@ function Out($o) { ConvertTo-Json -InputObject $o -Depth 5 -Compress }
193
202
  try {
194
203
  Add-Type -AssemblyName System.Runtime.WindowsRuntime
195
204
  $null = [Windows.Media.SpeechSynthesis.SpeechSynthesizer, Windows.Media, ContentType = WindowsRuntime]
196
- $req = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__REQ__')) | ConvertFrom-Json
205
+ $req = $Payload | ConvertFrom-Json
197
206
  $all = @([Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices)
198
207
  $voices = @($all | ForEach-Object { [pscustomobject]@{ name = $_.DisplayName; language = $_.Language; gender = [string]$_.Gender } })
199
208
  if ($req.list) { Out ([pscustomobject]@{ voices = $voices }); return }
package/dist/utils/ocr.js CHANGED
@@ -3,13 +3,18 @@ import { ScreencastError } from "./errors.js";
3
3
  import { runPowerShell, psTimeoutMs } from "./monitors.js";
4
4
  export const OCR_SCALES = [2, 4];
5
5
  export const OCR_MAX_DIMENSION = 10_000;
6
+ export function ocrCall(paths) {
7
+ return { script: PS_OCR, payload: JSON.stringify(paths) };
8
+ }
6
9
  export async function recognize(paths, scales) {
7
10
  if (process.platform !== "win32") {
8
11
  throw new ScreencastError("find_text uses the Windows OCR engine and runs on Windows only.");
9
12
  }
10
- const list = Buffer.from(JSON.stringify(paths), "utf8").toString("base64");
11
- const stdout = await runPowerShell(PS_OCR.replace("__PATHS__", list), "text (OCR)", {
13
+ const { script, payload } = ocrCall(paths);
14
+ const stdout = await runPowerShell(script, "text (OCR)", {
12
15
  timeoutMs: psTimeoutMs(OCR_TIMEOUT_MS + Math.max(0, paths.length - 2) * OCR_PER_IMAGE_MS),
16
+ payload,
17
+ failure: "Could not run OCR",
13
18
  });
14
19
  let raw;
15
20
  try {
@@ -197,7 +202,7 @@ $null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsR
197
202
  $null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
198
203
  $asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation\`1' })[0]
199
204
  function Await($op, [Type]$t) { $task = $asTask.MakeGenericMethod($t).Invoke($null, @($op)); if (-not $task.Wait(${OCR_STEP_TIMEOUT_MS})) { throw "The OCR engine did not answer within ${OCR_STEP_TIMEOUT_MS / 1000} s." }; $task.Result }
200
- $paths = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PATHS__')) | ConvertFrom-Json
205
+ $paths = $Payload | ConvertFrom-Json
201
206
  $engine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
202
207
  $out = foreach ($p in $paths) {
203
208
  try {
@@ -81,7 +81,33 @@ export function isWithin(path, dir) {
81
81
  const rel = relative(realish(dir), realish(path));
82
82
  return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
83
83
  }
84
+ export function isNetworkPath(path) {
85
+ const p = path.trim();
86
+ if (!/^[\\/]{2}/.test(p))
87
+ return false;
88
+ return !/^[\\/]{2}\?[\\/][A-Za-z]:[\\/]/.test(p);
89
+ }
90
+ export function assertLocalPath(path, label = "Path") {
91
+ if (isNetworkPath(path)) {
92
+ throw new ScreencastError(`${label} ${path} is a network or device path; only local files are allowed. ` +
93
+ "Copy the file to a local folder first.");
94
+ }
95
+ }
96
+ export function assertInputAllowed(path, label = "Input") {
97
+ assertLocalPath(path, label);
98
+ const full = resolve(path);
99
+ if (clientRoots === "pending" && envAllowedDirs().length === 0 && !isWithin(full, homeRoot())) {
100
+ throw new ScreencastError(`${label} ${full} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. ` +
101
+ "Retry the call in a moment.");
102
+ }
103
+ const allowed = allowedOutputDirs();
104
+ if (allowed === null || allowed.some((dir) => isWithin(full, dir)))
105
+ return;
106
+ throw new ScreencastError(`${label} ${full} is outside the allowed directories: ${allowed.join(", ")}. ` +
107
+ `Move it under one of them, or add its folder to ${ALLOWED_DIRS_ENV} or the client's workspace roots.`);
108
+ }
84
109
  export function assertOutputAllowed(path) {
110
+ assertLocalPath(path, "Output");
85
111
  if (clientRoots === "pending" && envAllowedDirs().length === 0 && !isWithin(path, homeRoot())) {
86
112
  throw new ScreencastError(`Output ${path} is outside SCREENCAST_HOME and the client's workspace roots have not loaded yet. ` +
87
113
  "Retry the call in a moment, or omit the path to write under SCREENCAST_HOME.");
@@ -93,13 +119,24 @@ export function assertOutputAllowed(path) {
93
119
  `Write under one of them (a relative path lands in SCREENCAST_HOME), or add the folder to ` +
94
120
  `${ALLOWED_DIRS_ENV} or the client's workspace roots.`);
95
121
  }
122
+ export function assertOverwriteAllowed(path) {
123
+ if (allowedOutputDirs() !== null || isWithin(path, homeRoot()))
124
+ return;
125
+ throw new ScreencastError(`Refusing to replace ${path}: it is outside SCREENCAST_HOME and no allowed directories are set. ` +
126
+ `Add its folder to ${ALLOWED_DIRS_ENV} (or the client's workspace roots) to allow overwriting there, ` +
127
+ "or write to a new path.");
128
+ }
96
129
  export function resolveOutput(provided, defaultDir, defaultName, overwrite = false) {
97
130
  if (provided && provided.trim().length > 0) {
131
+ assertLocalPath(provided, "Output");
98
132
  const path = resolve(defaultDir, provided);
99
133
  assertOutputAllowed(path);
100
- if (!overwrite && existsSync(path)) {
101
- throw new ScreencastError(`Output already exists: ${path}. Pass overwrite: true to replace it, ` +
102
- `or choose a different path.`);
134
+ if (existsSync(path)) {
135
+ if (!overwrite) {
136
+ throw new ScreencastError(`Output already exists: ${path}. Pass overwrite: true to replace it, ` +
137
+ `or choose a different path.`);
138
+ }
139
+ assertOverwriteAllowed(path);
103
140
  }
104
141
  return path;
105
142
  }
@@ -108,6 +145,7 @@ export function resolveOutput(provided, defaultDir, defaultName, overwrite = fal
108
145
  export function resolveOutputDir(provided, defaultParent) {
109
146
  if (!provided || provided.trim().length === 0)
110
147
  return undefined;
148
+ assertLocalPath(provided, "Output directory");
111
149
  const dir = resolve(defaultParent, provided);
112
150
  assertOutputAllowed(dir);
113
151
  return dir;
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, extname, join } from "node:path";
3
3
  import { ScreencastError } from "./errors.js";
4
4
  import { runCapture } from "./ffmpeg.js";
@@ -18,6 +18,20 @@ export function webcamOutputPath(output) {
18
18
  const ext = extname(output);
19
19
  return join(dirname(output), `${basename(output, ext)}.webcam.mp4`);
20
20
  }
21
+ export function segmentDurationSec(path, probed, startMs, endMs) {
22
+ if (probed !== null && probed > 0)
23
+ return probed;
24
+ let size;
25
+ try {
26
+ size = statSync(path).size;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ if (size <= 0)
32
+ return null;
33
+ return Math.max(0.001, Math.round(endMs - startMs) / 1000);
34
+ }
21
35
  export function recordedSec(parts) {
22
36
  return parts.reduce((s, p) => s + p.durationSec, 0);
23
37
  }
@@ -9,7 +9,7 @@ import { groupBadges, keystrokeSteps, retimeBadges } from "./keystrokes.js";
9
9
  import { cutFilters, cutsFor, DEFAULT_KEEP_SEC, DEFAULT_MIN_IDLE_SEC } from "./idle.js";
10
10
  import { denoiseFilter, loudnessTarget, loudnormFilter } from "./audio.js";
11
11
  import { subtitlesFilter } from "./captions.js";
12
- import { mapSpans, mapTime } from "./timeline.js";
12
+ import { mapSpans, mapTime, retimeCues } from "./timeline.js";
13
13
  import { cursorSteps, transformCursor } from "./cursor.js";
14
14
  export const MAX_PIPELINE_STEPS = 30;
15
15
  const r3 = (v) => Math.round(v * 1000) / 1000;
@@ -21,6 +21,10 @@ export function probeArgs(args, p) {
21
21
  out.splice(out.indexOf("-i"), 0, ...p.seek);
22
22
  return out;
23
23
  }
24
+ export function sidecarCues(cues, timeOps, opsBefore) {
25
+ const later = timeOps.slice(opsBefore);
26
+ return later.length > 0 ? retimeCues(cues, later) : [...cues];
27
+ }
24
28
  export function planPipeline(input, output, steps, src, assets = {}, quality = "standard", opts = {}) {
25
29
  if (steps.length === 0)
26
30
  throw new ScreencastError("Give at least one step.");
@@ -41,13 +41,15 @@ export function recipeSteps(recipe, ctx) {
41
41
  }
42
42
  return { steps, notes };
43
43
  }
44
+ const SOURCE_OPS = new Set(["redact", "crop", "cursor"]);
44
45
  export function applyOverrides(base, overrides) {
45
46
  const out = [...base];
46
47
  const tail = out.at(-1) && EXPORTS.has(out.at(-1).op) ? out.pop() : null;
47
48
  let exportStep = tail;
48
49
  const recipeLen = out.length;
49
50
  const replaced = new Set();
50
- const first = [];
51
+ const trims = [];
52
+ const front = [];
51
53
  for (const o of overrides) {
52
54
  if (EXPORTS.has(o.op)) {
53
55
  exportStep = o;
@@ -55,7 +57,9 @@ export function applyOverrides(base, overrides) {
55
57
  }
56
58
  const i = out.findIndex((s, j) => j < recipeLen && !replaced.has(j) && s.op === o.op);
57
59
  if (i === -1 && o.op === "trim")
58
- first.push(o);
60
+ trims.push(o);
61
+ else if (i === -1 && SOURCE_OPS.has(o.op))
62
+ front.push(o);
59
63
  else if (i === -1)
60
64
  out.push(o);
61
65
  else {
@@ -63,5 +67,5 @@ export function applyOverrides(base, overrides) {
63
67
  replaced.add(i);
64
68
  }
65
69
  }
66
- return [...first, ...out, ...(exportStep ? [exportStep] : [])];
70
+ return [...trims, ...front, ...out, ...(exportStep ? [exportStep] : [])];
67
71
  }
@@ -5,7 +5,7 @@ import { logMessage, StderrWatch } from "./logging.js";
5
5
  import { parseCaptureStart, whenFinalized } from "./events.js";
6
6
  import { buildCaptureArgs } from "./targets.js";
7
7
  import { requireFfmpeg } from "./ffmpeg.js";
8
- import { joinSegments, probeDuration } from "./lifecycle.js";
8
+ import { joinSegments, probeDuration, withSessionOp } from "./lifecycle.js";
9
9
  import { endSession, isPausing, partPath, partsDir, recordedSec, remainingCapSec, resumeBlocker, webcamPartPath, } from "./pause.js";
10
10
  import { classifyUnrequestedExit, killPid } from "./sessions.js";
11
11
  export function watchStderr(child, sessionId) {
@@ -59,7 +59,10 @@ export function captureStartMs(watch, backend, spawnedAt) {
59
59
  }
60
60
  export function attachExitHandler(store, id, child, opts) {
61
61
  child.on("exit", (code) => {
62
- store.detachChild(id);
62
+ const attached = store.getChild(id);
63
+ if (attached && attached !== child)
64
+ return;
65
+ store.detachChild(id, child);
63
66
  if (!isPausing(id))
64
67
  endSession(id);
65
68
  const cur = store.get(id);
@@ -95,7 +98,10 @@ async function finalizeSegments(store, record) {
95
98
  const durationSec = await probeDuration(tools.ffprobe, record.outputPath);
96
99
  store.tryUpdate(record.id, { ...patch, durationSec: durationSec ?? undefined, ...(error ? { error } : {}) });
97
100
  }
98
- export async function resumeSession(store, record, ffmpeg) {
101
+ export function resumeSession(store, record, ffmpeg) {
102
+ return withSessionOp(store, record.id, "resume", () => runResume(store, store.get(record.id) ?? record, ffmpeg));
103
+ }
104
+ async function runResume(store, record, ffmpeg) {
99
105
  const blocker = resumeBlocker(record, store.ownsPaused(record.id));
100
106
  if (blocker)
101
107
  throw new ScreencastError(`Cannot resume ${record.id}: ${blocker}.`);
@@ -119,6 +125,9 @@ export async function resumeSession(store, record, ffmpeg) {
119
125
  const child = spawn(ffmpeg, args, { stdio: ["pipe", "ignore", "pipe"], windowsHide: true });
120
126
  const watch = watchStderr(child, record.id);
121
127
  const cleanup = () => {
128
+ const other = store.getChild(record.id);
129
+ if (other && other !== child)
130
+ return;
122
131
  if (index > 0)
123
132
  rmSync(path, { force: true });
124
133
  if (webcamPath)
@@ -131,6 +140,12 @@ export async function resumeSession(store, record, ffmpeg) {
131
140
  const startMs = captureStartMs(watch, backend, spawnedAt);
132
141
  const camStart = webcamPath ? parseCaptureStart(watch.head(), capture.opts.audio ? 2 : 1) : null;
133
142
  store.attachChild(record.id, child);
143
+ const abandon = () => {
144
+ store.detachChild(record.id, child);
145
+ if (child.pid !== undefined)
146
+ killPid(child.pid);
147
+ cleanup();
148
+ };
134
149
  let updated;
135
150
  try {
136
151
  updated = store.update(record.id, {
@@ -144,17 +159,11 @@ export async function resumeSession(store, record, ffmpeg) {
144
159
  });
145
160
  }
146
161
  catch (err) {
147
- store.detachChild(record.id);
148
- if (child.pid !== undefined)
149
- killPid(child.pid);
150
- cleanup();
162
+ abandon();
151
163
  throw new ScreencastError(`Resume stopped: the session registry could not be written (${err.message}).`);
152
164
  }
153
165
  if (!updated) {
154
- store.detachChild(record.id);
155
- if (child.pid !== undefined)
156
- killPid(child.pid);
157
- cleanup();
166
+ abandon();
158
167
  throw new ScreencastError(`No session with id "${record.id}".`);
159
168
  }
160
169
  store.clearPaused(record.id);
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { closeSync, existsSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from "node:fs";
3
- import { basename, join, resolve } from "node:path";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
4
  import { ScreencastError } from "./errors.js";
5
5
  import { pickSceneFrames } from "./media.js";
6
6
  import { normalizeForMatch, regexRanges, MAX_QUERY_LENGTH } from "./ocr.js";
@@ -20,8 +20,20 @@ export const MAX_SNIPPET = 200;
20
20
  export const MAX_MATCHES_PER_HIT = 5;
21
21
  const r3 = (v) => Math.round(v * 1000) / 1000;
22
22
  export function indexSidecarPath(video) {
23
+ return `${video}.index.json`;
24
+ }
25
+ export function legacyIndexSidecarPath(video) {
23
26
  return `${video.replace(/\.[^./\\]+$/, "")}.index.json`;
24
27
  }
28
+ export function samePath(a, b) {
29
+ const norm = (p) => (process.platform === "win32" ? resolve(p).toLowerCase() : resolve(p));
30
+ return norm(a) === norm(b);
31
+ }
32
+ export function indexMatchesVideo(index, video, fingerprint) {
33
+ if (typeof index.video === "string" && samePath(index.video, video))
34
+ return true;
35
+ return fingerprint !== undefined && !!index.fingerprint && sameFingerprint(index.fingerprint, fingerprint);
36
+ }
25
37
  export function fallbackIndexPath(video, editsDir) {
26
38
  const key = createHash("sha1").update(resolve(video).toLowerCase()).digest("hex").slice(0, 12);
27
39
  const name = basename(video).replace(/\.[^.]+$/, "");
@@ -37,12 +49,41 @@ export function indexWritePath(video, editsDir) {
37
49
  return fallbackIndexPath(video, editsDir);
38
50
  }
39
51
  }
40
- export function findIndex(video, editsDir) {
52
+ export function findIndex(video, editsDir, fingerprint) {
41
53
  for (const p of [indexSidecarPath(video), fallbackIndexPath(video, editsDir)])
42
54
  if (existsSync(p))
43
55
  return p;
56
+ const legacy = legacyIndexSidecarPath(video);
57
+ if (legacy !== indexSidecarPath(video) && existsSync(legacy)) {
58
+ const index = readIndex(legacy);
59
+ if (index && indexMatchesVideo(index, video, fingerprint))
60
+ return legacy;
61
+ }
44
62
  return null;
45
63
  }
64
+ export function canReuseIndex(prior, want) {
65
+ return (prior !== null &&
66
+ sameFingerprint(prior.fingerprint, want.fingerprint) &&
67
+ prior.sceneThreshold === want.sceneThreshold &&
68
+ prior.maxFrames === want.maxFrames &&
69
+ (prior.ocr || !want.ocrAvailable));
70
+ }
71
+ export function maskSegmentText(segments, pattern = DEFAULT_SECRET_PATTERN) {
72
+ return segments.map((s) => (s.ocr.length > 0 ? { ...s, ocr: maskSecrets(s.ocr, pattern) } : s));
73
+ }
74
+ const VIDEO_EXT = /\.(mp4|mkv|mov|webm|avi|m4v|wmv|flv|gif|ts|mpg|mpeg)$/i;
75
+ const stemOf = (name) => name.replace(/\.[^.]+$/, "").toLowerCase();
76
+ export function defaultTranscriptPath(video, siblings) {
77
+ const names = new Set(siblings.map((n) => n.toLowerCase()));
78
+ const own = basename(video);
79
+ if (names.has(`${own}.srt`.toLowerCase()))
80
+ return { path: `${video}.srt`, ambiguous: false };
81
+ const shortName = `${own.replace(/\.[^.]+$/, "")}.srt`;
82
+ if (!names.has(shortName.toLowerCase()))
83
+ return { path: null, ambiguous: false };
84
+ const rival = siblings.some((n) => n.toLowerCase() !== own.toLowerCase() && VIDEO_EXT.test(n) && stemOf(n) === stemOf(own));
85
+ return rival ? { path: null, ambiguous: true } : { path: join(dirname(video), shortName), ambiguous: false };
86
+ }
46
87
  export function planKeyframes(changes, durationSec, maxFrames, maxGap = MAX_SEGMENT_SEC) {
47
88
  const times = pickSceneFrames(changes.filter((c) => c.timeSec < durationSec), maxFrames).map(r3);
48
89
  while (times.length < maxFrames) {
@@ -188,7 +229,16 @@ export function searchIndex(index, query, opts = {}) {
188
229
  if (query.length > MAX_QUERY_LENGTH) {
189
230
  throw new ScreencastError(`The query is ${query.length} characters; at most ${MAX_QUERY_LENGTH} are allowed.`);
190
231
  }
191
- const items = itemsOf(index);
232
+ if (opts.video !== undefined && !indexMatchesVideo(index, opts.video, opts.fingerprint)) {
233
+ throw new ScreencastError(`The index found is for ${index.video}, not ${opts.video}.`, "Run index_recording on this recording.");
234
+ }
235
+ if (!opts.regex && !/[\p{L}\p{N}]/u.test(normalizeForMatch(query))) {
236
+ throw new ScreencastError("query needs at least one letter or digit.", "For punctuation, use regex: true.");
237
+ }
238
+ const pattern = opts.secretPattern === undefined ? DEFAULT_SECRET_PATTERN : opts.secretPattern;
239
+ const raw = itemsOf(index);
240
+ const masked = pattern ? maskSecrets(raw.map((i) => i.text), pattern) : raw.map((i) => i.text);
241
+ const items = raw.map((item, i) => ({ ...item, text: masked[i] ?? "" }));
192
242
  const matched = new Map();
193
243
  const add = (item, score) => {
194
244
  const entry = matched.get(item.seg) ?? { score: 0, matches: [] };
@@ -230,13 +280,9 @@ export function searchIndex(index, query, opts = {}) {
230
280
  .map(([seg, m]) => ({ seg, ...m }))
231
281
  .sort((a, b) => b.score - a.score || index.segments[a.seg].start - index.segments[b.seg].start);
232
282
  const chosen = ranked.slice(0, opts.limit ?? DEFAULT_SEARCH_LIMIT);
233
- const pattern = opts.secretPattern === undefined ? DEFAULT_SECRET_PATTERN : opts.secretPattern;
234
- const shown = chosen.flatMap((c) => c.matches.slice(0, MAX_MATCHES_PER_HIT));
235
- const masked = pattern ? maskSecrets(shown.map((m) => m.text), pattern) : shown.map((m) => m.text);
236
- let k = 0;
237
283
  const hits = chosen.map((c) => {
238
284
  const seg = index.segments[c.seg];
239
- const matches = c.matches.slice(0, MAX_MATCHES_PER_HIT).map((m) => ({ source: m.source, t: m.t, text: snippet(masked[k++] ?? "") }));
285
+ const matches = c.matches.slice(0, MAX_MATCHES_PER_HIT).map((m) => ({ source: m.source, t: m.t, text: snippet(m.text) }));
240
286
  return { start: seg.start, end: seg.end, t: Math.min(...c.matches.map((m) => m.t)), score: c.score, matches };
241
287
  });
242
288
  return { hits, total: matched.size };
@@ -6,7 +6,7 @@ import { jobTimeoutMs } from "./jobs.js";
6
6
  import { buildProbeArgs, parseMediaInfo } from "./media.js";
7
7
  import { homeRoot, rand, sequencePattern, stamp } from "./paths.js";
8
8
  import { resolveQuality } from "./targets.js";
9
- import { convertEvents, eventPaths, formatEventsJsonl, selectEvents, summarizeEvents, } from "./events.js";
9
+ import { convertEvents, eventPaths, formatEventsJsonl, readRawEventLog, selectEvents, summarizeEvents, } from "./events.js";
10
10
  export const REPLAY_SEGMENT_SEC = 2;
11
11
  export const REPLAY_SLACK_SEGMENTS = 3;
12
12
  export const MIN_REPLAY_SEC = 4;
@@ -15,6 +15,10 @@ const SEGMENT_PATTERN = "seg%05d.ts";
15
15
  const SEGMENT_NAME = /^seg(\d{5})\.ts$/;
16
16
  const LIST_NAME = "segments.csv";
17
17
  const DIR_NAME = /^buf-[\w-]+$/;
18
+ export const REPLAY_EVENT_SLACK_SEC = 60;
19
+ export function replayEventRotateSec(bufferSec) {
20
+ return bufferSec + REPLAY_EVENT_SLACK_SEC;
21
+ }
18
22
  export function replayRoot() {
19
23
  return join(homeRoot(), "replay");
20
24
  }
@@ -197,7 +201,8 @@ export async function saveReplay(buf, opts) {
197
201
  includesLive,
198
202
  };
199
203
  if (buf.events) {
200
- const raw = existsSync(buf.events.raw) ? readFileSync(buf.events.raw, "utf8") : "";
204
+ const sinceMs = buf.events.startMs + fromSec * 1000 - REPLAY_EVENT_SLACK_SEC * 1000;
205
+ const raw = readRawEventLog(buf.events.raw, sinceMs);
201
206
  const events = sliceEvents(convertEvents(raw, { startMs: buf.events.startMs, frame: buf.events.frame }), fromSec, toSec);
202
207
  const { jsonl } = eventPaths(opts.output);
203
208
  writeFileSync(jsonl, formatEventsJsonl(events));
@@ -213,6 +218,19 @@ export async function saveReplay(buf, opts) {
213
218
  export function prepareReplayDir(buf) {
214
219
  mkdirSync(buf.dir, { recursive: true });
215
220
  }
221
+ export function resetReplaySegments(buf) {
222
+ let names;
223
+ try {
224
+ names = readdirSync(buf.dir);
225
+ }
226
+ catch {
227
+ return;
228
+ }
229
+ for (const name of names) {
230
+ if (SEGMENT_NAME.test(name) || name === LIST_NAME)
231
+ rmSync(join(buf.dir, name), { force: true });
232
+ }
233
+ }
216
234
  export function discardReplay(buf) {
217
235
  try {
218
236
  rmSync(buf.dir, { recursive: true, force: true });
@@ -6,6 +6,7 @@ export function retentionDays(env = process.env) {
6
6
  const n = Number(env[RETENTION_ENV]);
7
7
  return Number.isFinite(n) && n > 0 ? n : null;
8
8
  }
9
+ const INDEX_FILE = /\.index\.json(\.\d+\.tmp)?$/;
9
10
  export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
10
11
  const cutoff = now - days * 86_400_000;
11
12
  const result = { removed: 0, bytes: 0 };
@@ -40,6 +41,8 @@ export function pruneCaptures(days, now = Date.now(), root = homeRoot()) {
40
41
  };
41
42
  prune(join(root, "screenshots"), () => false, true);
42
43
  prune(join(root, "frames"), () => false, true);
43
- prune(join(root, "recordings"), (name) => !/\.events\.raw(\.stop)?$/.test(name), false);
44
+ prune(join(root, "recordings"), (name) => !/\.events\.raw(\.stop)?$/.test(name) && !INDEX_FILE.test(name), false);
45
+ prune(join(root, "edits"), (name) => !INDEX_FILE.test(name), false);
46
+ prune(join(root, "edits", "indexes"), (name) => !INDEX_FILE.test(name), false);
44
47
  return result;
45
48
  }
@@ -29,7 +29,7 @@ export function trackClientRoots(server) {
29
29
  }
30
30
  catch (err) {
31
31
  if (initial)
32
- setClientRoots(null);
32
+ setClientRoots([]);
33
33
  process.stderr.write(`roots/list failed: ${err instanceof Error ? err.message : String(err)}\n`);
34
34
  }
35
35
  };
@@ -380,7 +380,9 @@ export class SessionStore {
380
380
  getChild(id) {
381
381
  return this.children.get(id);
382
382
  }
383
- detachChild(id) {
383
+ detachChild(id, child) {
384
+ if (child && this.children.get(id) !== child)
385
+ return;
384
386
  this.children.delete(id);
385
387
  }
386
388
  activeIds() {
@@ -103,6 +103,32 @@ export function shotFilter(size, opts) {
103
103
  export function buildStepFrameArgs(input, t, output) {
104
104
  return ["-y", "-v", "error", "-ss", String(t), "-i", input, "-frames:v", "1", output];
105
105
  }
106
+ export const HTML_MAX_BYTES = 10_000_000;
107
+ export const HTML_IMAGE_LADDER = [
108
+ { width: 1280, q: 4 },
109
+ { width: 960, q: 6 },
110
+ { width: 800, q: 8 },
111
+ { width: 640, q: 10 },
112
+ { width: 480, q: 14 },
113
+ { width: 360, q: 20 },
114
+ ];
115
+ export const htmlImageName = (file) => file.replace(/\.png$/i, ".jpg");
116
+ export function buildHtmlImageArgs(png, rung, output) {
117
+ return [
118
+ "-y", "-v", "error", "-i", png,
119
+ "-vf", `scale=w='min(iw,${rung.width})':h=-2:flags=lanczos,format=yuvj420p`,
120
+ "-frames:v", "1", "-q:v", String(rung.q), output,
121
+ ];
122
+ }
123
+ export const base64Bytes = (n) => 4 * Math.ceil(n / 3);
124
+ export function nextHtmlRung(at, bytes, budget = HTML_MAX_BYTES) {
125
+ const w = HTML_IMAGE_LADDER[at].width;
126
+ for (let k = at + 1; k < HTML_IMAGE_LADDER.length; k++) {
127
+ if (bytes * (HTML_IMAGE_LADDER[k].width / w) ** 2 <= budget)
128
+ return k;
129
+ }
130
+ return at + 1 < HTML_IMAGE_LADDER.length ? HTML_IMAGE_LADDER.length - 1 : null;
131
+ }
106
132
  export function buildStepShotArgs(frame, filter, output) {
107
133
  return ["-y", "-v", "error", "-i", frame, "-filter_complex", filter, "-map", "[out]", "-frames:v", "1", output];
108
134
  }
@@ -57,10 +57,10 @@ export function mergeCuts(cuts) {
57
57
  for (const c of sorted) {
58
58
  const prev = out[out.length - 1];
59
59
  if (prev && c.start <= prev.end + 0.01) {
60
- if (c.end > prev.end) {
60
+ if (c.end > prev.end)
61
61
  prev.end = c.end;
62
+ if (!prev.text.includes(c.text))
62
63
  prev.text = `${prev.text} ${c.text}`;
63
- }
64
64
  prev.exact &&= c.exact;
65
65
  }
66
66
  else
@@ -68,14 +68,29 @@ export function mergeCuts(cuts) {
68
68
  }
69
69
  return out;
70
70
  }
71
+ export function cueByNumber(cues, n) {
72
+ const numbers = cues.flatMap((c) => (c.index === undefined ? [] : [c.index]));
73
+ if (numbers.length === 0) {
74
+ const c = Number.isInteger(n) ? cues[n - 1] : undefined;
75
+ if (!c)
76
+ throw new ScreencastError(`No cue ${n}: the transcript has cues 1-${cues.length}.`);
77
+ return c;
78
+ }
79
+ const hits = cues.filter((c) => c.index === n);
80
+ if (hits.length > 1)
81
+ throw new ScreencastError(`The transcript numbers ${hits.length} cues ${n}; quote the text to cut instead.`);
82
+ if (hits.length === 0) {
83
+ throw new ScreencastError(`No cue ${n}: the transcript's cues are numbered ${Math.min(...numbers)}-${Math.max(...numbers)}` +
84
+ " (a cue with no duration, or wholly overlapped by the next, has no time to cut).");
85
+ }
86
+ return hits[0];
87
+ }
71
88
  export function planTranscriptCuts(cues, req) {
72
89
  const words = cueWords(cues);
73
90
  const cuts = [];
74
91
  for (const r of req.remove ?? []) {
75
92
  if (typeof r === "number") {
76
- const c = cues[r - 1];
77
- if (!Number.isInteger(r) || !c)
78
- throw new ScreencastError(`No cue ${r}: the transcript has cues 1-${cues.length}.`);
93
+ const c = cueByNumber(cues, r);
79
94
  cuts.push({ start: r3(c.start), end: r3(c.end), text: c.text.replace(/\s+/g, " "), exact: true });
80
95
  continue;
81
96
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tmhs/screencast-mcp",
3
- "version": "0.47.0",
3
+ "version": "0.48.0",
4
4
  "description": "Let AI agents record the Windows screen, watch it as frames, and edit it with ffmpeg",
5
5
  "mcpName": "io.github.TMHSDigital/screencast-mcp",
6
6
  "type": "module",
@@ -25,6 +25,7 @@
25
25
  "start": "node dist/index.js",
26
26
  "test": "vitest run",
27
27
  "test:watch": "vitest",
28
+ "test:coverage": "vitest run --coverage",
28
29
  "eval": "tsx evals/run.ts",
29
30
  "typecheck:evals": "tsc -p evals/tsconfig.json",
30
31
  "docs": "tsc && node scripts/build-tool-docs.mjs",
@@ -70,6 +71,7 @@
70
71
  "@eslint/js": "^10.0.1",
71
72
  "@types/jsdom": "^30.0.0",
72
73
  "@types/node": "^22.15.3",
74
+ "@vitest/coverage-v8": "^5.0.5",
73
75
  "eslint": "^10.5.0",
74
76
  "jsdom": "^30.1.3",
75
77
  "tsx": "^4.19.4",