@tmhs/screencast-mcp 0.47.0 → 0.48.1

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 (41) hide show
  1. package/README.md +28 -247
  2. package/assets/fonts/Inter-Bold.ttf +0 -0
  3. package/assets/fonts/Inter-Regular.ttf +0 -0
  4. package/dist/cli.js +189 -34
  5. package/dist/server.js +13 -0
  6. package/dist/setup.js +437 -0
  7. package/dist/tools/assembleHighlights.js +2 -0
  8. package/dist/tools/cutByTranscript.js +3 -3
  9. package/dist/tools/exportPreset.js +2 -0
  10. package/dist/tools/indexRecording.js +37 -15
  11. package/dist/tools/narrate.js +3 -1
  12. package/dist/tools/pipeline.js +23 -11
  13. package/dist/tools/searchRecording.js +9 -3
  14. package/dist/tools/startRecording.js +72 -42
  15. package/dist/tools/stepGuide.js +57 -4
  16. package/dist/tools/titleCard.js +2 -0
  17. package/dist/tools/xfadeTransition.js +2 -0
  18. package/dist/utils/argPaths.js +39 -0
  19. package/dist/utils/audioDevices.js +0 -4
  20. package/dist/utils/captions.js +5 -3
  21. package/dist/utils/events.js +40 -8
  22. package/dist/utils/gpu.js +50 -4
  23. package/dist/utils/lifecycle.js +56 -16
  24. package/dist/utils/media.js +3 -2
  25. package/dist/utils/monitors.js +34 -3
  26. package/dist/utils/narrate.js +12 -3
  27. package/dist/utils/ocr.js +8 -3
  28. package/dist/utils/paths.js +41 -3
  29. package/dist/utils/pause.js +15 -1
  30. package/dist/utils/pipeline.js +5 -1
  31. package/dist/utils/recipes.js +7 -3
  32. package/dist/utils/recorder.js +20 -11
  33. package/dist/utils/recordingIndex.js +54 -8
  34. package/dist/utils/replay.js +20 -2
  35. package/dist/utils/retention.js +4 -1
  36. package/dist/utils/roots.js +1 -1
  37. package/dist/utils/sessions.js +3 -4
  38. package/dist/utils/sheet.js +4 -4
  39. package/dist/utils/stepGuide.js +26 -0
  40. package/dist/utils/transcriptCut.js +20 -5
  41. package/package.json +7 -5
@@ -6,7 +6,7 @@ import { buildProbeArgs, parseMediaInfo } from "./media.js";
6
6
  import { ScreencastError } from "./errors.js";
7
7
  import { wgcStopFile } from "./wgc.js";
8
8
  import { encoderArgs } from "./gpu.js";
9
- import { clearPausing, endSession, finishSegments, markPausing, pauseBlocker, recordedSec, webcamOutputPath, } from "./pause.js";
9
+ import { clearPausing, endSession, finishSegments, markPausing, pauseBlocker, recordedSec, segmentDurationSec, webcamOutputPath, } from "./pause.js";
10
10
  import { expectedImage, isAlive, isRecorderProcess, killPid, } from "./sessions.js";
11
11
  async function waitForPidExit(pid, ms) {
12
12
  const deadline = Date.now() + ms;
@@ -57,7 +57,9 @@ export async function finalParts(record, ffprobe) {
57
57
  return [];
58
58
  const parts = [...seg.parts];
59
59
  if (seg.current) {
60
- const durationSec = (await probeDuration(ffprobe, seg.current.path)) ?? 0;
60
+ const probed = await probeDuration(ffprobe, seg.current.path);
61
+ const endMs = record.stoppedAt ? Date.parse(record.stoppedAt) : Date.now();
62
+ const durationSec = segmentDurationSec(seg.current.path, probed, seg.current.startMs, endMs) ?? 0;
61
63
  parts.push({ ...seg.current, durationSec });
62
64
  }
63
65
  return parts;
@@ -82,7 +84,44 @@ export async function joinSegments(record, tools) {
82
84
  error: res.error,
83
85
  };
84
86
  }
85
- export async function pauseSession(store, record, opts) {
87
+ const sessionOps = new WeakMap();
88
+ export function sessionOpInFlight(store, id) {
89
+ return sessionOps.get(store)?.get(id)?.kind ?? null;
90
+ }
91
+ export function withSessionOp(store, id, kind, fn, opts = {}) {
92
+ let ops = sessionOps.get(store);
93
+ if (!ops)
94
+ sessionOps.set(store, (ops = new Map()));
95
+ const running = ops.get(id);
96
+ if (running?.kind === kind)
97
+ return running.promise;
98
+ if (running && !opts.queue) {
99
+ return Promise.reject(new ScreencastError(`Cannot ${kind} ${id}: a ${running.kind} of it is in progress.`, "Retry once it finishes (get_recording shows the session's status)."));
100
+ }
101
+ let start;
102
+ if (running) {
103
+ start = running.promise.then(() => fn(true), () => fn(true));
104
+ }
105
+ else {
106
+ try {
107
+ start = fn(false);
108
+ }
109
+ catch (err) {
110
+ start = Promise.reject(err);
111
+ }
112
+ }
113
+ const map = ops;
114
+ const op = start.finally(() => {
115
+ if (map.get(id)?.promise === op)
116
+ map.delete(id);
117
+ });
118
+ map.set(id, { kind, promise: op });
119
+ return op;
120
+ }
121
+ export function pauseSession(store, record, opts) {
122
+ return withSessionOp(store, record.id, "pause", () => runPause(store, store.get(record.id) ?? record, opts));
123
+ }
124
+ async function runPause(store, record, opts) {
86
125
  const child = store.getChild(record.id);
87
126
  const blocker = pauseBlocker(record, !!child);
88
127
  if (blocker)
@@ -90,10 +129,12 @@ export async function pauseSession(store, record, opts) {
90
129
  markPausing(record.id);
91
130
  store.markStopping(record.id);
92
131
  try {
132
+ const pausedAt = Date.now();
93
133
  const graceful = await quitChild(child, record.pid, opts.gracefulMs ?? 8000);
94
- store.detachChild(record.id);
134
+ store.detachChild(record.id, child);
95
135
  const cur = record.segments.current;
96
- const segmentSec = (await opts.probe(cur.path)) ?? 0;
136
+ const probed = await opts.probe(cur.path);
137
+ const segmentSec = segmentDurationSec(cur.path, probed, cur.startMs, pausedAt) ?? 0;
97
138
  const parts = record.segments.parts;
98
139
  const next = segmentSec > 0 ? [...parts, { ...cur, durationSec: segmentSec }] : parts;
99
140
  if (segmentSec <= 0 && cur.path !== record.outputPath)
@@ -128,17 +169,16 @@ export async function stopAll(store, probe, capMs = 10_000) {
128
169
  clearTimeout(timer);
129
170
  return ids;
130
171
  }
131
- const inFlight = new WeakMap();
132
172
  export function stopSession(store, record, opts) {
133
- let stops = inFlight.get(store);
134
- if (!stops)
135
- inFlight.set(store, (stops = new Map()));
136
- const running = stops.get(record.id);
137
- if (running)
138
- return running;
139
- const stop = runStop(store, record, opts).finally(() => stops.delete(record.id));
140
- stops.set(record.id, stop);
141
- return stop;
173
+ return withSessionOp(store, record.id, "stop", async (waited) => {
174
+ if (!waited)
175
+ return runStop(store, record, opts);
176
+ const cur = store.get(record.id) ?? record;
177
+ if (cur.status !== "recording" && cur.status !== "paused") {
178
+ return { record: cur, graceful: true, durationSec: cur.durationSec ?? null };
179
+ }
180
+ return runStop(store, cur, opts);
181
+ }, { queue: true });
142
182
  }
143
183
  async function runStop(store, record, opts) {
144
184
  store.markStopping(record.id);
@@ -171,7 +211,7 @@ async function runStop(store, record, opts) {
171
211
  }
172
212
  }
173
213
  }
174
- store.detachChild(record.id);
214
+ store.detachChild(record.id, child);
175
215
  if (record.status === "paused")
176
216
  graceful = true;
177
217
  endSession(record.id);
@@ -484,8 +484,9 @@ export const BLUR_PASSES = 3;
484
484
  export const MIN_PIXEL_BLOCK = 16;
485
485
  export function blurRadius(r) {
486
486
  const m = Math.min(r.w, r.h);
487
- const lr = Math.min(Math.floor(m / 2), Math.max(MIN_BLUR_RADIUS, Math.min(20, Math.floor(m / 4))));
488
- const cr = Math.min(lr, Math.floor(Math.ceil(m / 2) / 2));
487
+ const maxRadius = (side) => Math.max(0, Math.floor((side - 1) / 2));
488
+ const lr = Math.min(maxRadius(m), Math.max(MIN_BLUR_RADIUS, Math.min(20, Math.floor(m / 4))));
489
+ const cr = Math.min(lr, maxRadius(Math.ceil(m / 2)));
489
490
  return `lr=${lr}:lp=${BLUR_PASSES}:cr=${cr}:cp=${BLUR_PASSES}`;
490
491
  }
491
492
  export function pixelateFilter(r) {
@@ -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
  }