@chrrxs/robloxstudio-mcp-inspector 3.4.4 → 3.5.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.
package/dist/index.js CHANGED
@@ -3834,8 +3834,8 @@ var SOCIAL_LINK_FIELDS = {
3834
3834
  roblox_group: "robloxGroupSocialLink",
3835
3835
  guilded: "guildedSocialLink"
3836
3836
  };
3837
- function trailingId(path12) {
3838
- return typeof path12 === "string" ? positiveSafeInteger(path12.split("/").pop()) ?? null : null;
3837
+ function trailingId(path13) {
3838
+ return typeof path13 === "string" ? positiveSafeInteger(path13.split("/").pop()) ?? null : null;
3839
3839
  }
3840
3840
  function optionalText(value) {
3841
3841
  return typeof value === "string" ? value : "";
@@ -4127,8 +4127,8 @@ var OpenCloudClient = class {
4127
4127
  };
4128
4128
  }
4129
4129
  async getMonetizationItem(kind, universeId, id) {
4130
- const path12 = `${MONETIZATION_APIS[kind].collectionPath(universeId)}/${id}/creator`;
4131
- return normalizeMonetizationItem(kind, universeId, await this.request(path12));
4130
+ const path13 = `${MONETIZATION_APIS[kind].collectionPath(universeId)}/${id}/creator`;
4131
+ return normalizeMonetizationItem(kind, universeId, await this.request(path13));
4132
4132
  }
4133
4133
  async createMonetizationItem(kind, universeId, item) {
4134
4134
  const response = await this.requestMultipart(MONETIZATION_APIS[kind].collectionPath(universeId), monetizationForm(item));
@@ -4136,8 +4136,8 @@ var OpenCloudClient = class {
4136
4136
  }
4137
4137
  /** Changes only the given fields. Roblox answers with an empty 204. */
4138
4138
  async updateMonetizationItem(kind, universeId, id, changes) {
4139
- const path12 = `${MONETIZATION_APIS[kind].collectionPath(universeId)}/${id}`;
4140
- await this.sendMultipart(path12, monetizationForm(changes), "PATCH", async (response) => {
4139
+ const path13 = `${MONETIZATION_APIS[kind].collectionPath(universeId)}/${id}`;
4140
+ await this.sendMultipart(path13, monetizationForm(changes), "PATCH", async (response) => {
4141
4141
  await response.arrayBuffer();
4142
4142
  });
4143
4143
  }
@@ -4153,8 +4153,8 @@ var OpenCloudClient = class {
4153
4153
  });
4154
4154
  }
4155
4155
  async getPlace(universeId, placeId) {
4156
- const path12 = `/cloud/v2/universes/${universeId}/places/${placeId}`;
4157
- return normalizePlace(universeId, placeId, await this.request(path12));
4156
+ const path13 = `/cloud/v2/universes/${universeId}/places/${placeId}`;
4157
+ return normalizePlace(universeId, placeId, await this.request(path13));
4158
4158
  }
4159
4159
  async updatePlace(universeId, placeId, changes) {
4160
4160
  const { body, updateMask } = placePatch(changes);
@@ -11699,6 +11699,53 @@ var TOOL_DEFINITIONS = [
11699
11699
  }
11700
11700
  }
11701
11701
  },
11702
+ {
11703
+ name: "capture_video",
11704
+ category: "read",
11705
+ description: "Use to record the viewport as video to review motion such as cutscenes or animations, not repeated screenshots.",
11706
+ inputSchema: {
11707
+ type: "object",
11708
+ properties: {
11709
+ action: {
11710
+ type: "string",
11711
+ enum: ["record", "start", "stop", "storyboard"],
11712
+ description: "record (default) waits duration_ms; start/stop wrap other calls."
11713
+ },
11714
+ duration_ms: {
11715
+ type: "number",
11716
+ description: "action=record length; default 5000, max 30000."
11717
+ },
11718
+ fps: {
11719
+ type: "number",
11720
+ description: "Frames per second, 1-60; default 30."
11721
+ },
11722
+ output_path: {
11723
+ type: "string",
11724
+ description: ".mp4 path; defaults to a kept temp file."
11725
+ },
11726
+ frames: {
11727
+ type: "number",
11728
+ description: "Storyboard image frames, 0-25; default 9."
11729
+ },
11730
+ input_path: {
11731
+ type: "string",
11732
+ description: "Video for action=storyboard: an earlier video.path."
11733
+ },
11734
+ start_ms: {
11735
+ type: "number",
11736
+ description: "Storyboard span start; default 0."
11737
+ },
11738
+ end_ms: {
11739
+ type: "number",
11740
+ description: "Storyboard span end; default the video end."
11741
+ },
11742
+ instance_id: {
11743
+ type: "string",
11744
+ description: "Studio process ID when ambiguous."
11745
+ }
11746
+ }
11747
+ }
11748
+ },
11702
11749
  // === Monetization ===
11703
11750
  {
11704
11751
  name: "manage_monetization",
@@ -13470,11 +13517,32 @@ function isHostCaptureDisabled(env = process.env) {
13470
13517
  const value = (env.ROBLOX_STUDIO_HOST_CAPTURE ?? "").trim().toLowerCase();
13471
13518
  return value === "0" || value === "false" || value === "off";
13472
13519
  }
13520
+ var WSL_WINDOWS_POWERSHELL = "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
13521
+ var detectedWslWindowsHost;
13522
+ function detectWslWindowsHost() {
13523
+ if (detectedWslWindowsHost !== void 0)
13524
+ return detectedWslWindowsHost;
13525
+ let release = "";
13526
+ try {
13527
+ release = fs4.readFileSync("/proc/sys/kernel/osrelease", "utf8");
13528
+ } catch {
13529
+ }
13530
+ detectedWslWindowsHost = /microsoft|wsl/i.test(release) && fs4.existsSync(WSL_WINDOWS_POWERSHELL);
13531
+ return detectedWslWindowsHost;
13532
+ }
13533
+ var hostEnvironment = { detectWslWindowsHost };
13534
+ function isWslWindowsHost(platform = process.platform) {
13535
+ return platform === "linux" && hostEnvironment.detectWslWindowsHost();
13536
+ }
13473
13537
  function isHostCaptureSupported(platform = process.platform) {
13474
- return platform === "win32" || platform === "darwin";
13538
+ return platform === "win32" || platform === "darwin" || isWslWindowsHost(platform);
13475
13539
  }
13476
13540
  function hostCaptureUnsupportedReason(platform = process.platform) {
13477
- return `host window capture is only implemented on Windows and macOS (this is ${platform})`;
13541
+ return `host window capture is only implemented on Windows, WSL with Windows interop, and macOS (this is ${platform})`;
13542
+ }
13543
+ function withWslEnv(env, entries) {
13544
+ const existing = (env.WSLENV ?? "").split(":").filter((entry) => entry.length > 0);
13545
+ return { ...env, WSLENV: [...existing, ...entries].join(":") };
13478
13546
  }
13479
13547
  async function prepareHostWindowCapture() {
13480
13548
  if (process.platform === "darwin" && !isHostCaptureDisabled())
@@ -13705,6 +13773,8 @@ function parseWindowsCaptureReport(value, expectedIdentity) {
13705
13773
  return { ok: true, width: value.width, height: value.height, stride: value.stride, title: value.title, identity };
13706
13774
  }
13707
13775
  function powershellPath() {
13776
+ if (isWslWindowsHost())
13777
+ return WSL_WINDOWS_POWERSHELL;
13708
13778
  const systemRoot = process.env.SystemRoot ?? process.env.windir;
13709
13779
  if (systemRoot) {
13710
13780
  const candidate = path9.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
@@ -13713,16 +13783,23 @@ function powershellPath() {
13713
13783
  }
13714
13784
  return "powershell.exe";
13715
13785
  }
13786
+ function windowsCaptureEnvironment(titleHint, outFile, expectedIdentity, wsl, env = process.env) {
13787
+ const captureEnv = {
13788
+ ...env,
13789
+ MCP_CAPTURE_TITLE_HINT: titleHint ?? "",
13790
+ MCP_CAPTURE_OUT: outFile,
13791
+ MCP_CAPTURE_EXPECTED_IDENTITY: expectedIdentity ? JSON.stringify(expectedIdentity) : ""
13792
+ };
13793
+ return wsl ? withWslEnv(captureEnv, ["MCP_CAPTURE_TITLE_HINT/w", "MCP_CAPTURE_OUT/pw", "MCP_CAPTURE_EXPECTED_IDENTITY/w"]) : captureEnv;
13794
+ }
13716
13795
  function runWindowsCapture(titleHint, outFile, expectedIdentity) {
13717
13796
  const { promise, resolve: resolve7, reject } = Promise.withResolvers();
13718
13797
  const encoded = Buffer.from(WINDOWS_CAPTURE_SCRIPT, "utf16le").toString("base64");
13798
+ const wsl = isWslWindowsHost();
13719
13799
  const child = spawn4(powershellPath(), ["-NoProfile", "-NonInteractive", "-NoLogo", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], {
13720
- env: {
13721
- ...process.env,
13722
- MCP_CAPTURE_TITLE_HINT: titleHint ?? "",
13723
- MCP_CAPTURE_OUT: outFile,
13724
- MCP_CAPTURE_EXPECTED_IDENTITY: expectedIdentity ? JSON.stringify(expectedIdentity) : ""
13725
- },
13800
+ env: windowsCaptureEnvironment(titleHint, outFile, expectedIdentity, wsl),
13801
+ // A Windows program started from WSL cannot use a Linux working directory.
13802
+ ...wsl ? { cwd: "/mnt/c/Windows" } : {},
13726
13803
  stdio: ["ignore", "pipe", "pipe"],
13727
13804
  windowsHide: true
13728
13805
  });
@@ -13809,6 +13886,424 @@ async function captureStudioWindow(titleHint, expectedIdentity) {
13809
13886
  }
13810
13887
  }
13811
13888
 
13889
+ // ../core/dist/video-recorder.js
13890
+ import { execFileSync as execFileSync3, spawn as spawn5 } from "child_process";
13891
+ import * as fs5 from "fs";
13892
+ import * as os5 from "os";
13893
+ import * as path10 from "path";
13894
+ var PROBE_TIMEOUT_MS = 15e3;
13895
+ var GRAB_TIMEOUT_MS = 15e3;
13896
+ var STOP_TIMEOUT_MS = 15e3;
13897
+ var STORYBOARD_TIMEOUT_MS = 6e4;
13898
+ var MAX_GRAB_BYTES = 16384 * 16384 * 4;
13899
+ var STORYBOARD_PADDING = 4;
13900
+ var ENCODER_PREFERENCE = ["libx264", "h264_mf", "mpeg4"];
13901
+ function ffmpegCommand(env = process.env, wsl = isWslWindowsHost()) {
13902
+ const configured = env.ROBLOX_STUDIO_FFMPEG?.trim();
13903
+ if (configured)
13904
+ return configured;
13905
+ return wsl ? "ffmpeg.exe" : "ffmpeg";
13906
+ }
13907
+ function videoRecordingUnsupportedReason(platform = process.platform) {
13908
+ if (platform === "win32" || isWslWindowsHost(platform))
13909
+ return void 0;
13910
+ return `video recording is only implemented on Windows and WSL with Windows interop (this is ${platform}); use capture_screenshot instead`;
13911
+ }
13912
+ function ffmpegPathArgument(filePath, wsl = isWslWindowsHost()) {
13913
+ if (!wsl || !path10.isAbsolute(filePath))
13914
+ return filePath;
13915
+ return execFileSync3("wslpath", ["-w", filePath], { encoding: "utf8" }).trim();
13916
+ }
13917
+ function locateWindowsFfmpeg() {
13918
+ try {
13919
+ const source = execFileSync3(WSL_WINDOWS_POWERSHELL, [
13920
+ "-NoProfile",
13921
+ "-NonInteractive",
13922
+ "-Command",
13923
+ "(Get-Command ffmpeg.exe -ErrorAction SilentlyContinue).Source"
13924
+ ], { encoding: "utf8", cwd: "/mnt/c/Windows", timeout: PROBE_TIMEOUT_MS }).trim();
13925
+ if (!source)
13926
+ return void 0;
13927
+ return execFileSync3("wslpath", ["-u", source], { encoding: "utf8" }).trim();
13928
+ } catch {
13929
+ return void 0;
13930
+ }
13931
+ }
13932
+ var DEFAULT_VIDEO_PREFIX = "studio-video-";
13933
+ var KEPT_DEFAULT_VIDEOS = 20;
13934
+ var DEFAULT_VIDEO_PRUNE_GRACE_MS = 10 * 6e4;
13935
+ function defaultVideoDirectory() {
13936
+ return path10.join(os5.tmpdir(), "robloxstudio-mcp", "videos");
13937
+ }
13938
+ function defaultVideoPath(date = /* @__PURE__ */ new Date()) {
13939
+ const stamp = date.toISOString().replace(/[:.]/g, "-");
13940
+ return path10.join(defaultVideoDirectory(), `${DEFAULT_VIDEO_PREFIX}${stamp}-${Math.random().toString(36).slice(2, 8)}.mp4`);
13941
+ }
13942
+ async function pruneDefaultVideos(directory = defaultVideoDirectory(), keep = KEPT_DEFAULT_VIDEOS, now = Date.now()) {
13943
+ let entries;
13944
+ try {
13945
+ entries = await fs5.promises.readdir(directory);
13946
+ } catch {
13947
+ return;
13948
+ }
13949
+ const videos = entries.filter((name) => name.startsWith(DEFAULT_VIDEO_PREFIX) && name.endsWith(".mp4")).sort();
13950
+ const settled = [];
13951
+ for (const name of videos) {
13952
+ try {
13953
+ const stats = await fs5.promises.stat(path10.join(directory, name));
13954
+ if (now - stats.mtimeMs >= DEFAULT_VIDEO_PRUNE_GRACE_MS)
13955
+ settled.push(name);
13956
+ } catch {
13957
+ }
13958
+ }
13959
+ const young = videos.length - settled.length;
13960
+ const excess = settled.length - Math.max(0, keep - young);
13961
+ for (const name of settled.slice(0, Math.max(0, excess))) {
13962
+ await fs5.promises.rm(path10.join(directory, name), { force: true }).catch(() => void 0);
13963
+ }
13964
+ }
13965
+ var FFMPEG_INSTALL_HINT = "Install FFmpeg 8.0 or newer (for example `winget install Gyan.FFmpeg`) and restart the MCP server, or point ROBLOX_STUDIO_FFMPEG at ffmpeg.exe.";
13966
+ function runFfmpeg(ffmpegPath, args, timeoutMs, maxStdoutBytes = 64 * 1024 * 1024) {
13967
+ const { promise, resolve: resolve7, reject } = Promise.withResolvers();
13968
+ const child = spawn5(ffmpegPath, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
13969
+ const chunks = [];
13970
+ let stdoutBytes = 0;
13971
+ let stderr = "";
13972
+ let settled = false;
13973
+ const finish = (fn) => {
13974
+ if (settled)
13975
+ return;
13976
+ settled = true;
13977
+ clearTimeout(timer);
13978
+ fn();
13979
+ };
13980
+ const timer = setTimeout(() => {
13981
+ child.kill();
13982
+ finish(() => reject(new Error(`ffmpeg timed out after ${timeoutMs}ms`)));
13983
+ }, timeoutMs);
13984
+ child.stdout.on("data", (chunk) => {
13985
+ stdoutBytes += chunk.length;
13986
+ if (stdoutBytes > maxStdoutBytes) {
13987
+ child.kill();
13988
+ finish(() => reject(new Error(`ffmpeg output exceeded ${maxStdoutBytes} bytes`)));
13989
+ return;
13990
+ }
13991
+ chunks.push(chunk);
13992
+ });
13993
+ child.stderr.setEncoding("utf8");
13994
+ child.stderr.on("data", (chunk) => {
13995
+ if (stderr.length < 64 * 1024)
13996
+ stderr += chunk;
13997
+ });
13998
+ child.on("error", (error) => {
13999
+ finish(() => reject(error.code === "ENOENT" ? new Error(`ffmpeg was not found (${ffmpegPath}). ${FFMPEG_INSTALL_HINT}`) : new Error(`could not start ffmpeg (${ffmpegPath}): ${error.message}`)));
14000
+ });
14001
+ child.on("close", (code) => {
14002
+ finish(() => resolve7({ code, stdout: Buffer.concat(chunks), stderr }));
14003
+ });
14004
+ return promise;
14005
+ }
14006
+ function stderrSummary(stderr) {
14007
+ const seen = /* @__PURE__ */ new Set();
14008
+ for (const raw of stderr.split(/\r?\n/)) {
14009
+ const line = raw.replace(/^(?:\[[^\]]*@\s*[0-9a-fA-Fx]+\]\s*)+/, "").trim();
14010
+ if (line.length > 0)
14011
+ seen.add(line);
14012
+ if (seen.size >= 3)
14013
+ break;
14014
+ }
14015
+ return [...seen].join(" | ").slice(0, 600);
14016
+ }
14017
+ function evenFloor(value) {
14018
+ return Math.max(2, value - value % 2);
14019
+ }
14020
+ function gfxcaptureCrop(crop, frameWidth, frameHeight) {
14021
+ const left = Math.max(0, Math.min(frameWidth - 2, Math.floor(crop.x)));
14022
+ const top = Math.max(0, Math.min(frameHeight - 2, Math.floor(crop.y)));
14023
+ const width = evenFloor(Math.min(Math.floor(crop.width), frameWidth - left));
14024
+ const height = evenFloor(Math.min(Math.floor(crop.height), frameHeight - top));
14025
+ return {
14026
+ left,
14027
+ top,
14028
+ right: Math.max(0, frameWidth - left - width),
14029
+ bottom: Math.max(0, frameHeight - top - height),
14030
+ width,
14031
+ height
14032
+ };
14033
+ }
14034
+ function encoderArgs(encoder) {
14035
+ if (encoder === "libx264")
14036
+ return ["-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p"];
14037
+ if (encoder === "h264_mf")
14038
+ return ["-c:v", "h264_mf", "-b:v", "12M", "-pix_fmt", "nv12"];
14039
+ return ["-c:v", "mpeg4", "-q:v", "3", "-pix_fmt", "yuv420p"];
14040
+ }
14041
+ function sourceGraph(source, windowId, fps, pixelFormat, crop) {
14042
+ if (source === "gdigrab") {
14043
+ const cropFilter = crop ? `crop=${crop.width}:${crop.height}:${crop.left}:${crop.top},` : "";
14044
+ const filter = `${cropFilter}format=${pixelFormat}[v]`;
14045
+ return [
14046
+ "-f",
14047
+ "gdigrab",
14048
+ "-framerate",
14049
+ String(fps),
14050
+ "-draw_mouse",
14051
+ "0",
14052
+ "-i",
14053
+ `hwnd=${windowId}`,
14054
+ "-filter_complex",
14055
+ `[0:v]${filter}`
14056
+ ];
14057
+ }
14058
+ const options = [`gfxcapture=hwnd=${windowId}`, "capture_cursor=0", `max_framerate=${fps}`];
14059
+ if (crop) {
14060
+ options.push(`crop_left=${crop.left}`, `crop_top=${crop.top}`, `crop_right=${crop.right}`, `crop_bottom=${crop.bottom}`);
14061
+ }
14062
+ const convert = pixelFormat === "bgra" ? "" : `,format=${pixelFormat}`;
14063
+ return ["-filter_complex", `${options.join(":")},hwdownload,format=bgra${convert}[v]`];
14064
+ }
14065
+ function recordingArgs(options) {
14066
+ const crop = gfxcaptureCrop(options.crop, options.frameWidth, options.frameHeight);
14067
+ return [
14068
+ "-hide_banner",
14069
+ "-nostats",
14070
+ "-loglevel",
14071
+ "error",
14072
+ "-y",
14073
+ ...sourceGraph(options.source, options.windowId, options.fps, "bgra", crop),
14074
+ "-map",
14075
+ "[v]",
14076
+ "-t",
14077
+ (options.maxDurationMs / 1e3).toFixed(3),
14078
+ // WGC delivers a frame only when the window changes; constant frame rate
14079
+ // repeats the last one so playback timing matches wall time.
14080
+ "-fps_mode",
14081
+ "cfr",
14082
+ "-r",
14083
+ String(options.fps),
14084
+ ...encoderArgs(options.encoder),
14085
+ "-movflags",
14086
+ "+faststart",
14087
+ options.outputPath
14088
+ ];
14089
+ }
14090
+ function grabFrameArgs(source, windowId) {
14091
+ return [
14092
+ // Info level prints the output frame size; errors are filtered from it on failure.
14093
+ "-hide_banner",
14094
+ "-nostats",
14095
+ "-loglevel",
14096
+ "info",
14097
+ ...sourceGraph(source, windowId, 30, "rgba"),
14098
+ "-map",
14099
+ "[v]",
14100
+ "-frames:v",
14101
+ "1",
14102
+ "-f",
14103
+ "rawvideo",
14104
+ "-"
14105
+ ];
14106
+ }
14107
+ function storyboardGrid(frames) {
14108
+ const columns = Math.max(1, Math.ceil(Math.sqrt(frames)));
14109
+ return { columns, rows: Math.max(1, Math.ceil(frames / columns)) };
14110
+ }
14111
+ function storyboardTimes(startSeconds, endSeconds, frames, durationSeconds) {
14112
+ const span = Math.max(0, endSeconds - startSeconds);
14113
+ const latest = Math.max(0, durationSeconds - 0.05);
14114
+ const times = [];
14115
+ for (let i = 0; i < frames; i++) {
14116
+ const t = startSeconds + (i + 0.5) * span / frames;
14117
+ times.push(Math.round(Math.min(latest, Math.max(0, t)) * 1e3) / 1e3);
14118
+ }
14119
+ return times;
14120
+ }
14121
+ function storyboardArgs(options, tileWidth, tileHeight, times) {
14122
+ const { columns, rows } = storyboardGrid(times.length);
14123
+ const inputs = [];
14124
+ let graph = "";
14125
+ times.forEach((t, i) => {
14126
+ inputs.push("-ss", t.toFixed(3), "-i", options.inputPath);
14127
+ graph += `[${i}:v]trim=end_frame=1,setpts=PTS-STARTPTS,scale=${tileWidth}:${tileHeight},setsar=1[f${i}];`;
14128
+ });
14129
+ graph += times.map((_, i) => `[f${i}]`).join("");
14130
+ graph += `concat=n=${times.length}:v=1:a=0,tile=${columns}x${rows}:padding=${STORYBOARD_PADDING}:color=black`;
14131
+ return [
14132
+ "-hide_banner",
14133
+ "-nostats",
14134
+ "-loglevel",
14135
+ "error",
14136
+ ...inputs,
14137
+ "-filter_complex",
14138
+ graph,
14139
+ "-frames:v",
14140
+ "1",
14141
+ "-q:v",
14142
+ "4",
14143
+ "-f",
14144
+ "image2pipe",
14145
+ "-c:v",
14146
+ "mjpeg",
14147
+ "-"
14148
+ ];
14149
+ }
14150
+ function parseMediaInfo(stderr) {
14151
+ const duration = /Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/.exec(stderr);
14152
+ const size = /Stream #\d+:\d+[^\n]*Video:[^\n]*?,\s*(\d{2,5})x(\d{2,5})/.exec(stderr);
14153
+ if (!duration || !size)
14154
+ return void 0;
14155
+ const durationSeconds = Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3]);
14156
+ return { durationSeconds, width: Number(size[1]), height: Number(size[2]) };
14157
+ }
14158
+ var FfmpegRecording = class {
14159
+ done;
14160
+ stopRequested = false;
14161
+ child;
14162
+ constructor(options, live) {
14163
+ const { promise, resolve: resolve7 } = Promise.withResolvers();
14164
+ this.done = promise;
14165
+ this.child = spawn5(options.ffmpegPath, recordingArgs(options), { stdio: ["pipe", "ignore", "pipe"], windowsHide: true });
14166
+ live.add(this);
14167
+ let stderr = "";
14168
+ this.child.stderr?.setEncoding("utf8");
14169
+ this.child.stderr?.on("data", (chunk) => {
14170
+ if (stderr.length < 64 * 1024)
14171
+ stderr += chunk;
14172
+ });
14173
+ this.child.stdin?.on("error", () => void 0);
14174
+ this.child.on("error", (error) => {
14175
+ live.delete(this);
14176
+ resolve7({
14177
+ ok: false,
14178
+ error: error.code === "ENOENT" ? `ffmpeg was not found (${options.ffmpegPath}). ${FFMPEG_INSTALL_HINT}` : `could not start ffmpeg: ${error.message}`
14179
+ });
14180
+ });
14181
+ this.child.on("close", (code) => {
14182
+ live.delete(this);
14183
+ if (code === 0) {
14184
+ resolve7({ ok: true, reason: this.stopRequested ? "stopped" : "duration_limit" });
14185
+ return;
14186
+ }
14187
+ const detail = stderrSummary(stderr);
14188
+ resolve7({ ok: false, error: `ffmpeg exited with code ${code}${detail ? `: ${detail}` : ""}` });
14189
+ });
14190
+ }
14191
+ async stop() {
14192
+ if (!this.stopRequested) {
14193
+ this.stopRequested = true;
14194
+ this.child.stdin?.end("q");
14195
+ }
14196
+ const timer = setTimeout(() => this.child.kill(), STOP_TIMEOUT_MS);
14197
+ try {
14198
+ const exit = await this.done;
14199
+ return exit;
14200
+ } finally {
14201
+ clearTimeout(timer);
14202
+ }
14203
+ }
14204
+ kill() {
14205
+ this.child.kill();
14206
+ }
14207
+ };
14208
+ function createFfmpegVideoBackend(env = process.env) {
14209
+ let probed;
14210
+ const live = /* @__PURE__ */ new Set();
14211
+ let exitHookInstalled = false;
14212
+ const installExitHook = () => {
14213
+ if (exitHookInstalled)
14214
+ return;
14215
+ exitHookInstalled = true;
14216
+ process.once("exit", () => {
14217
+ for (const recording of live)
14218
+ recording.kill();
14219
+ });
14220
+ };
14221
+ return {
14222
+ async probe() {
14223
+ if (probed)
14224
+ return { ok: true, ...probed };
14225
+ let ffmpegPath = ffmpegCommand(env);
14226
+ if (ffmpegPath === "ffmpeg.exe" && isWslWindowsHost()) {
14227
+ try {
14228
+ await runFfmpeg(ffmpegPath, ["-hide_banner", "-version"], PROBE_TIMEOUT_MS);
14229
+ } catch {
14230
+ ffmpegPath = locateWindowsFfmpeg() ?? ffmpegPath;
14231
+ }
14232
+ }
14233
+ try {
14234
+ const sources = [];
14235
+ const filter = await runFfmpeg(ffmpegPath, ["-hide_banner", "-h", "filter=gfxcapture"], PROBE_TIMEOUT_MS);
14236
+ if (filter.stdout.toString("utf8").includes("Filter gfxcapture"))
14237
+ sources.push("gfxcapture");
14238
+ const demuxer = await runFfmpeg(ffmpegPath, ["-hide_banner", "-h", "demuxer=gdigrab"], PROBE_TIMEOUT_MS);
14239
+ if (demuxer.stdout.toString("utf8").includes("Demuxer gdigrab"))
14240
+ sources.push("gdigrab");
14241
+ if (sources.length === 0) {
14242
+ return {
14243
+ ok: false,
14244
+ error: `ffmpeg (${ffmpegPath}) can capture neither through gfxcapture (Windows Graphics Capture) nor gdigrab. ${FFMPEG_INSTALL_HINT}`
14245
+ };
14246
+ }
14247
+ const encoders = (await runFfmpeg(ffmpegPath, ["-hide_banner", "-encoders"], PROBE_TIMEOUT_MS)).stdout.toString("utf8");
14248
+ const encoder = ENCODER_PREFERENCE.find((name) => new RegExp(`^\\s*V\\S*\\s+${name}\\s`, "m").test(encoders));
14249
+ if (!encoder) {
14250
+ return { ok: false, error: `ffmpeg (${ffmpegPath}) has none of the ${ENCODER_PREFERENCE.join(", ")} video encoders. ${FFMPEG_INSTALL_HINT}` };
14251
+ }
14252
+ probed = { ffmpegPath, encoder, sources };
14253
+ return { ok: true, ...probed };
14254
+ } catch (error) {
14255
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
14256
+ }
14257
+ },
14258
+ async grabWindowFrame(ffmpegPath, windowId, source) {
14259
+ const result = await runFfmpeg(ffmpegPath, grabFrameArgs(source, windowId), GRAB_TIMEOUT_MS, MAX_GRAB_BYTES);
14260
+ const output = /Output #0[\s\S]*?Video:\s*rawvideo[^\n]*?,\s*(\d+)x(\d+)/.exec(result.stderr);
14261
+ if (result.code !== 0 || !output) {
14262
+ const errors = result.stderr.split(/\r?\n/).filter((line) => /fail|error|invalid|cannot|unable/i.test(line)).join("\n");
14263
+ throw new Error(`could not capture the Studio window with ffmpeg ${source}: ${stderrSummary(errors) || `exit code ${result.code}`}`);
14264
+ }
14265
+ const width = Number(output[1]);
14266
+ const height = Number(output[2]);
14267
+ if (result.stdout.length !== width * height * 4) {
14268
+ throw new Error(`ffmpeg returned ${result.stdout.length} bytes for a ${width}x${height} frame`);
14269
+ }
14270
+ return { width, height, rgba: result.stdout };
14271
+ },
14272
+ start(options) {
14273
+ installExitHook();
14274
+ return new FfmpegRecording({ ...options, outputPath: ffmpegPathArgument(options.outputPath) }, live);
14275
+ },
14276
+ async mediaInfo(ffmpegPath, inputPath) {
14277
+ const result = await runFfmpeg(ffmpegPath, ["-hide_banner", "-i", ffmpegPathArgument(inputPath)], PROBE_TIMEOUT_MS);
14278
+ const info = parseMediaInfo(result.stderr);
14279
+ if (!info)
14280
+ throw new Error(`could not read video ${inputPath}: ${stderrSummary(result.stderr) || "no video stream"}`);
14281
+ return info;
14282
+ },
14283
+ async storyboard(options) {
14284
+ const { info } = options;
14285
+ const { columns, rows } = storyboardGrid(options.frames);
14286
+ const available = Math.floor((options.maxWidth - STORYBOARD_PADDING * (columns - 1)) / columns);
14287
+ const tileWidth = evenFloor(Math.min(info.width, available));
14288
+ const tileHeight = evenFloor(Math.round(info.height * tileWidth / info.width));
14289
+ const times = storyboardTimes(options.startSeconds, options.endSeconds, options.frames, info.durationSeconds);
14290
+ const input = { ...options, inputPath: ffmpegPathArgument(options.inputPath) };
14291
+ const result = await runFfmpeg(options.ffmpegPath, storyboardArgs(input, tileWidth, tileHeight, times), STORYBOARD_TIMEOUT_MS);
14292
+ if (result.code !== 0 || result.stdout.length === 0) {
14293
+ throw new Error(`could not build the storyboard: ${stderrSummary(result.stderr) || `exit code ${result.code}`}`);
14294
+ }
14295
+ return {
14296
+ jpeg: result.stdout,
14297
+ width: columns * tileWidth + (columns - 1) * STORYBOARD_PADDING,
14298
+ height: rows * tileHeight + (rows - 1) * STORYBOARD_PADDING,
14299
+ columns,
14300
+ rows,
14301
+ timesSeconds: times
14302
+ };
14303
+ }
14304
+ };
14305
+ }
14306
+
13812
14307
  // ../core/dist/micro-profiler/libmp-vendor.js
13813
14308
  var LibMP = (() => {
13814
14309
  var __create2 = Object.create;
@@ -17101,13 +17596,13 @@ var LibMP = (() => {
17101
17596
  }
17102
17597
  async ConvertToFile(session, format, outputName) {
17103
17598
  if (typeof process !== "undefined" && process.versions?.node) {
17104
- const fs7 = await import("fs");
17105
- const descriptor = fs7.openSync(outputName, "w");
17599
+ const fs8 = await import("fs");
17600
+ const descriptor = fs8.openSync(outputName, "w");
17106
17601
  try {
17107
17602
  return this._runtime._runTool(session, format, (chunk) => {
17108
17603
  let offset = 0;
17109
17604
  while (offset < chunk.byteLength) {
17110
- const written = fs7.writeSync(descriptor, chunk, offset, chunk.byteLength - offset);
17605
+ const written = fs8.writeSync(descriptor, chunk, offset, chunk.byteLength - offset);
17111
17606
  if (written <= 0)
17112
17607
  return false;
17113
17608
  offset += written;
@@ -17115,7 +17610,7 @@ var LibMP = (() => {
17115
17610
  return true;
17116
17611
  });
17117
17612
  } finally {
17118
- fs7.closeSync(descriptor);
17613
+ fs8.closeSync(descriptor);
17119
17614
  }
17120
17615
  }
17121
17616
  if (typeof document === "undefined" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function" || typeof Blob === "undefined")
@@ -17779,21 +18274,21 @@ var LibMP = (() => {
17779
18274
  static OpenFromExternalProvider(provider, options = {}) {
17780
18275
  return runtime._openFromExternalProvider(provider, options);
17781
18276
  }
17782
- static async OpenFromFile(path12, cacheSize = 0) {
17783
- const fs7 = await import("fs");
18277
+ static async OpenFromFile(path13, cacheSize = 0) {
18278
+ const fs8 = await import("fs");
17784
18279
  let descriptor = null;
17785
18280
  let fileSize = 0n;
17786
18281
  let openError = null;
17787
18282
  const provider = {
17788
18283
  open() {
17789
18284
  try {
17790
- descriptor = fs7.openSync(path12, "r");
17791
- fileSize = fs7.fstatSync(descriptor, { bigint: true }).size;
18285
+ descriptor = fs8.openSync(path13, "r");
18286
+ fileSize = fs8.fstatSync(descriptor, { bigint: true }).size;
17792
18287
  return true;
17793
18288
  } catch (error) {
17794
18289
  if (descriptor !== null) {
17795
18290
  try {
17796
- fs7.closeSync(descriptor);
18291
+ fs8.closeSync(descriptor);
17797
18292
  } catch {
17798
18293
  }
17799
18294
  }
@@ -17805,7 +18300,7 @@ var LibMP = (() => {
17805
18300
  },
17806
18301
  close() {
17807
18302
  if (descriptor !== null) {
17808
- fs7.closeSync(descriptor);
18303
+ fs8.closeSync(descriptor);
17809
18304
  descriptor = null;
17810
18305
  }
17811
18306
  fileSize = 0n;
@@ -17818,7 +18313,7 @@ var LibMP = (() => {
17818
18313
  }
17819
18314
  let bytesRead = 0;
17820
18315
  while (bytesRead < size) {
17821
- const count = fs7.readSync(descriptor, destination, bytesRead, size - bytesRead, offset + BigInt(bytesRead));
18316
+ const count = fs8.readSync(descriptor, destination, bytesRead, size - bytesRead, offset + BigInt(bytesRead));
17822
18317
  if (count === 0)
17823
18318
  break;
17824
18319
  bytesRead += count;
@@ -18513,9 +19008,9 @@ function breakdownFrame(session, frame, ranges, frameOffsetMs, usPerTickCpu, nam
18513
19008
  return row;
18514
19009
  };
18515
19010
  const hotPath = (threadRoots) => {
18516
- const path12 = [];
19011
+ const path13 = [];
18517
19012
  let candidates = threadRoots;
18518
- while (candidates.length > 0 && path12.length < SPIKE_HOT_PATH_DEPTH) {
19013
+ while (candidates.length > 0 && path13.length < SPIKE_HOT_PATH_DEPTH) {
18519
19014
  let best = candidates[0];
18520
19015
  for (const candidate of candidates) {
18521
19016
  if (candidate.busyUs > best.busyUs)
@@ -18523,10 +19018,10 @@ function breakdownFrame(session, frame, ranges, frameOffsetMs, usPerTickCpu, nam
18523
19018
  }
18524
19019
  if (best.busyUs <= 0)
18525
19020
  break;
18526
- path12.push(describeNode(best));
19021
+ path13.push(describeNode(best));
18527
19022
  candidates = best.children;
18528
19023
  }
18529
- return path12;
19024
+ return path13;
18530
19025
  };
18531
19026
  const topTimers = [...timerTotals.entries()].map(([timerId, totals]) => {
18532
19027
  const info = names.timer(timerId);
@@ -19317,9 +19812,9 @@ function analyzeMicroProfilerSession(session, options = {}) {
19317
19812
 
19318
19813
  // ../core/dist/micro-profiler/capture.js
19319
19814
  import { randomUUID as randomUUID5 } from "crypto";
19320
- import * as fs5 from "fs";
19321
- import * as os5 from "os";
19322
- import * as path10 from "path";
19815
+ import * as fs6 from "fs";
19816
+ import * as os6 from "os";
19817
+ import * as path11 from "path";
19323
19818
  import { setTimeout as sleep } from "timers/promises";
19324
19819
  var MICRO_PROFILER_ACTIONS = ["capture", "start", "stop", "analyze"];
19325
19820
  var MICRO_PROFILER_DEFAULT_DURATION_MS = 1e3;
@@ -19373,7 +19868,7 @@ function microProfilerAnalysisOptions(request) {
19373
19868
  };
19374
19869
  }
19375
19870
  function defaultCaptureDirectory() {
19376
- return path10.join(os5.tmpdir(), "robloxstudio-mcp", "micro-profiler");
19871
+ return path11.join(os6.tmpdir(), "robloxstudio-mcp", "micro-profiler");
19377
19872
  }
19378
19873
  function captureFileStamp(date) {
19379
19874
  return date.toISOString().replace(/[:.]/g, "-");
@@ -19382,7 +19877,7 @@ var DEFAULT_CAPTURE_PRUNE_GRACE_MS = 10 * 6e4;
19382
19877
  async function pruneDefaultCaptures(directory, keep = KEPT_DEFAULT_CAPTURES, graceMs = DEFAULT_CAPTURE_PRUNE_GRACE_MS, now = Date.now()) {
19383
19878
  let entries;
19384
19879
  try {
19385
- entries = await fs5.promises.readdir(directory);
19880
+ entries = await fs6.promises.readdir(directory);
19386
19881
  } catch {
19387
19882
  return;
19388
19883
  }
@@ -19390,33 +19885,33 @@ async function pruneDefaultCaptures(directory, keep = KEPT_DEFAULT_CAPTURES, gra
19390
19885
  const settled = [];
19391
19886
  for (const name of captures) {
19392
19887
  try {
19393
- const stats = await fs5.promises.stat(path10.join(directory, name));
19888
+ const stats = await fs6.promises.stat(path11.join(directory, name));
19394
19889
  if (now - stats.mtimeMs >= graceMs)
19395
19890
  settled.push(name);
19396
19891
  } catch {
19397
19892
  }
19398
19893
  }
19399
19894
  for (const name of settled.slice(0, Math.max(0, settled.length - keep))) {
19400
- await fs5.promises.rm(path10.join(directory, name), { force: true });
19401
- await fs5.promises.rm(path10.join(directory, `${name}${WINDOW_SIDECAR_SUFFIX}`), { force: true });
19895
+ await fs6.promises.rm(path11.join(directory, name), { force: true });
19896
+ await fs6.promises.rm(path11.join(directory, `${name}${WINDOW_SIDECAR_SUFFIX}`), { force: true });
19402
19897
  }
19403
19898
  }
19404
19899
  async function resolveCapturePath(outputPath, role, now = /* @__PURE__ */ new Date()) {
19405
19900
  if (outputPath !== void 0 && outputPath !== "")
19406
- return { path: path10.resolve(outputPath), generated: false };
19901
+ return { path: path11.resolve(outputPath), generated: false };
19407
19902
  const directory = defaultCaptureDirectory();
19408
- await fs5.promises.mkdir(directory, { recursive: true });
19903
+ await fs6.promises.mkdir(directory, { recursive: true });
19409
19904
  await pruneDefaultCaptures(directory, KEPT_DEFAULT_CAPTURES - 1);
19410
19905
  const safeRole = role.replace(/[^A-Za-z0-9-]/g, "_");
19411
19906
  const uniqueId = `${process.pid}-${randomUUID5().slice(0, 8)}`;
19412
19907
  return {
19413
- path: path10.join(directory, `micro-profiler-${captureFileStamp(now)}-${safeRole}-${uniqueId}${CAPTURE_EXTENSION}`),
19908
+ path: path11.join(directory, `micro-profiler-${captureFileStamp(now)}-${safeRole}-${uniqueId}${CAPTURE_EXTENSION}`),
19414
19909
  generated: true
19415
19910
  };
19416
19911
  }
19417
19912
  async function writeCaptureFile(target, bytes) {
19418
- await fs5.promises.mkdir(path10.dirname(target.path), { recursive: true });
19419
- await fs5.promises.writeFile(target.path, bytes, { flag: target.generated ? "wx" : "w" });
19913
+ await fs6.promises.mkdir(path11.dirname(target.path), { recursive: true });
19914
+ await fs6.promises.writeFile(target.path, bytes, { flag: target.generated ? "wx" : "w" });
19420
19915
  }
19421
19916
  function parseCaptureTransfer(value) {
19422
19917
  if (!value || typeof value !== "object" || Array.isArray(value))
@@ -19488,13 +19983,13 @@ async function writeWindowSidecar(capturePath, target, recording) {
19488
19983
  requested_duration_ms: finiteNumber(recording.requested_duration_ms),
19489
19984
  capture_wall_ms: finiteNumber(recording.capture_wall_ms)
19490
19985
  };
19491
- await fs5.promises.writeFile(`${capturePath}${WINDOW_SIDECAR_SUFFIX}`, `${JSON.stringify(sidecar, null, 2)}
19986
+ await fs6.promises.writeFile(`${capturePath}${WINDOW_SIDECAR_SUFFIX}`, `${JSON.stringify(sidecar, null, 2)}
19492
19987
  `, "utf8");
19493
19988
  }
19494
19989
  async function readWindowSidecar(capturePath) {
19495
19990
  let parsed;
19496
19991
  try {
19497
- parsed = JSON.parse(await fs5.promises.readFile(`${capturePath}${WINDOW_SIDECAR_SUFFIX}`, "utf8"));
19992
+ parsed = JSON.parse(await fs6.promises.readFile(`${capturePath}${WINDOW_SIDECAR_SUFFIX}`, "utf8"));
19498
19993
  } catch {
19499
19994
  return void 0;
19500
19995
  }
@@ -19753,13 +20248,34 @@ var ReferenceUploads = class {
19753
20248
  };
19754
20249
 
19755
20250
  // ../core/dist/tools/index.js
19756
- import * as fs6 from "fs";
19757
- import * as path11 from "path";
20251
+ import * as fs7 from "fs";
20252
+ import * as path12 from "path";
19758
20253
  var MAX_SCRIPT_EDITS = 100;
19759
20254
  function sameHostWindowIdentity(actual, expected) {
19760
20255
  return actual?.windowId === expected.windowId && actual.processId === expected.processId && actual.bundleIdentifier === expected.bundleIdentifier;
19761
20256
  }
19762
20257
  var HOST_VIEWPORT_RECT_TTL_MS = 6e4;
20258
+ var VIDEO_ACTIONS = ["record", "start", "stop", "storyboard"];
20259
+ var VIDEO_DEFAULT_DURATION_MS = 5e3;
20260
+ var VIDEO_MIN_DURATION_MS = 500;
20261
+ var VIDEO_MAX_DURATION_MS = 3e4;
20262
+ var VIDEO_START_MAX_DURATION_MS = 3e5;
20263
+ var VIDEO_DEFAULT_FPS = 30;
20264
+ var VIDEO_MAX_FPS = 60;
20265
+ var VIDEO_DEFAULT_STORYBOARD_FRAMES = 9;
20266
+ var VIDEO_MAX_STORYBOARD_FRAMES = 25;
20267
+ var VIDEO_STORYBOARD_MAX_WIDTH = 1536;
20268
+ var VIDEO_START_GRACE_MS = 750;
20269
+ function isVideoAction(value) {
20270
+ return typeof value === "string" && VIDEO_ACTIONS.includes(value);
20271
+ }
20272
+ function clampedInteger(value, name, min, max, fallback) {
20273
+ if (value === void 0)
20274
+ return fallback;
20275
+ if (typeof value !== "number" || !Number.isFinite(value))
20276
+ throw new Error(`${name} must be a number`);
20277
+ return Math.min(max, Math.max(min, Math.floor(value)));
20278
+ }
19763
20279
  var MAX_INLINE_IMAGE_BYTES = 6e6;
19764
20280
  var MAX_MATRIX_IMAGE_BYTES = 8e6;
19765
20281
  var DEFAULT_ASSET_AUDIO_PREVIEWS = 3;
@@ -19888,6 +20404,15 @@ function encodeImageFromRgbaResponse(response, format, quality) {
19888
20404
  function sleep2(ms) {
19889
20405
  return new Promise((resolve7) => setTimeout(resolve7, ms));
19890
20406
  }
20407
+ async function settledWithin(promise, ms) {
20408
+ const timeout = Promise.withResolvers();
20409
+ const timer = setTimeout(() => timeout.resolve(void 0), ms);
20410
+ try {
20411
+ return await Promise.race([promise, timeout.promise]);
20412
+ } finally {
20413
+ clearTimeout(timer);
20414
+ }
20415
+ }
19891
20416
  function errorMessage(error) {
19892
20417
  return error instanceof Error ? error.message : String(error);
19893
20418
  }
@@ -20038,9 +20563,9 @@ function compactSoundReference(sound) {
20038
20563
  name: stringField(sound, "name"),
20039
20564
  className: stringField(sound, "className")
20040
20565
  };
20041
- const path12 = stringField(sound, "path");
20042
- if (path12)
20043
- compact.path = path12;
20566
+ const path13 = stringField(sound, "path");
20567
+ if (path13)
20568
+ compact.path = path13;
20044
20569
  const assetId = robloxAssetIdFromContentId(sound.assetId ?? sound.soundId ?? sound.asset);
20045
20570
  if (assetId !== void 0)
20046
20571
  compact.assetId = assetId;
@@ -20103,8 +20628,8 @@ function loadMicroProfilerBaseline(source, sourcePath) {
20103
20628
  if (typeof sourcePath !== "string" || sourcePath === "") {
20104
20629
  throw new Error("baseline_path must be a non-empty string when provided");
20105
20630
  }
20106
- const resolved = path11.resolve(sourcePath);
20107
- const parsed = JSON.parse(fs6.readFileSync(resolved, "utf8"));
20631
+ const resolved = path12.resolve(sourcePath);
20632
+ const parsed = JSON.parse(fs7.readFileSync(resolved, "utf8"));
20108
20633
  const record = asRecord(parsed);
20109
20634
  if (!record)
20110
20635
  throw new Error(`baseline_path did not contain a JSON object: ${resolved}`);
@@ -20640,6 +21165,12 @@ var RobloxStudioTools = class {
20640
21165
  hostWindowCapture = captureStudioWindow;
20641
21166
  hostViewportRects = /* @__PURE__ */ new Map();
20642
21167
  viewportCaptureQueues = /* @__PURE__ */ new Map();
21168
+ // capture_video: the host recorder and the recordings started per Instance.
21169
+ videoRecorder = createFfmpegVideoBackend();
21170
+ videoRecordings = /* @__PURE__ */ new Map();
21171
+ videoStarting = /* @__PURE__ */ new Set();
21172
+ // How long start waits for the encoder to fail fast before reporting success.
21173
+ videoStartGraceMs = VIDEO_START_GRACE_MS;
20643
21174
  // generate_model reference images, shared by retries under one operation ID.
20644
21175
  referenceUploads = new ReferenceUploads();
20645
21176
  // Paces chunks of a client capture copied through the client broker.
@@ -21193,8 +21724,8 @@ var RobloxStudioTools = class {
21193
21724
  return void 0;
21194
21725
  }
21195
21726
  }
21196
- async getFileTree(path12 = "", instance_id) {
21197
- const response = await this._callSingle("/api/file-tree", { path: path12 }, void 0, instance_id);
21727
+ async getFileTree(path13 = "", instance_id) {
21728
+ const response = await this._callSingle("/api/file-tree", { path: path13 }, void 0, instance_id);
21198
21729
  return {
21199
21730
  content: [
21200
21731
  {
@@ -21317,9 +21848,9 @@ var RobloxStudioTools = class {
21317
21848
  ]
21318
21849
  };
21319
21850
  }
21320
- async getProjectStructure(path12, maxDepth, scriptsOnly, instance_id) {
21851
+ async getProjectStructure(path13, maxDepth, scriptsOnly, instance_id) {
21321
21852
  const response = await this._callSingle("/api/project-structure", {
21322
- path: path12,
21853
+ path: path13,
21323
21854
  maxDepth,
21324
21855
  scriptsOnly
21325
21856
  }, void 0, instance_id);
@@ -21517,7 +22048,7 @@ var RobloxStudioTools = class {
21517
22048
  };
21518
22049
  }
21519
22050
  async setSelection(paths, mode, instance_id) {
21520
- if (!Array.isArray(paths) || paths.some((path12) => typeof path12 !== "string" || path12.length === 0)) {
22051
+ if (!Array.isArray(paths) || paths.some((path13) => typeof path13 !== "string" || path13.length === 0)) {
21521
22052
  throw new Error("selection paths must contain only non-empty instance paths");
21522
22053
  }
21523
22054
  const selectionMode = mode ?? "set";
@@ -22254,9 +22785,9 @@ var RobloxStudioTools = class {
22254
22785
  const rawJson = mutable.raw_json;
22255
22786
  if (typeof rawJson === "string") {
22256
22787
  if (typeof outputPath === "string" && outputPath !== "") {
22257
- const resolvedOutputPath = path11.resolve(outputPath);
22258
- fs6.mkdirSync(path11.dirname(resolvedOutputPath), { recursive: true });
22259
- fs6.writeFileSync(resolvedOutputPath, rawJson, "utf8");
22788
+ const resolvedOutputPath = path12.resolve(outputPath);
22789
+ fs7.mkdirSync(path12.dirname(resolvedOutputPath), { recursive: true });
22790
+ fs7.writeFileSync(resolvedOutputPath, rawJson, "utf8");
22260
22791
  mutable.output_path = resolvedOutputPath;
22261
22792
  }
22262
22793
  delete mutable.raw_json;
@@ -22295,8 +22826,8 @@ var RobloxStudioTools = class {
22295
22826
  if (typeof inputPath !== "string" || inputPath === "") {
22296
22827
  throw new Error('input_path is required for action="analyze": a capture_path from an earlier capture, or a MicroProfiler .gprx dump');
22297
22828
  }
22298
- const resolvedInput = path11.resolve(inputPath);
22299
- const bytes2 = await fs6.promises.readFile(resolvedInput);
22829
+ const resolvedInput = path12.resolve(inputPath);
22830
+ const bytes2 = await fs7.promises.readFile(resolvedInput);
22300
22831
  const window = await readWindowSidecar(resolvedInput);
22301
22832
  const summary2 = await analyzeMicroProfilerCapture(bytes2, { ...analysisOptions, window });
22302
22833
  summary2.action = action;
@@ -22434,9 +22965,9 @@ var RobloxStudioTools = class {
22434
22965
  // harness that reads the file sees why there is no analysis.
22435
22966
  _microProfilerFailure(body, summaryOutputPath) {
22436
22967
  if (typeof summaryOutputPath === "string" && summaryOutputPath !== "") {
22437
- const resolvedSummaryPath = path11.resolve(summaryOutputPath);
22438
- fs6.mkdirSync(path11.dirname(resolvedSummaryPath), { recursive: true });
22439
- fs6.writeFileSync(resolvedSummaryPath, JSON.stringify(body, null, 2), "utf8");
22968
+ const resolvedSummaryPath = path12.resolve(summaryOutputPath);
22969
+ fs7.mkdirSync(path12.dirname(resolvedSummaryPath), { recursive: true });
22970
+ fs7.writeFileSync(resolvedSummaryPath, JSON.stringify(body, null, 2), "utf8");
22440
22971
  body.summary_output_path = resolvedSummaryPath;
22441
22972
  }
22442
22973
  return { content: [{ type: "text", text: JSON.stringify(body) }] };
@@ -22459,9 +22990,9 @@ var RobloxStudioTools = class {
22459
22990
  });
22460
22991
  }
22461
22992
  if (typeof options.summaryOutputPath === "string" && options.summaryOutputPath !== "") {
22462
- const resolvedSummaryPath = path11.resolve(options.summaryOutputPath);
22463
- fs6.mkdirSync(path11.dirname(resolvedSummaryPath), { recursive: true });
22464
- fs6.writeFileSync(resolvedSummaryPath, JSON.stringify(summary, null, 2), "utf8");
22993
+ const resolvedSummaryPath = path12.resolve(options.summaryOutputPath);
22994
+ fs7.mkdirSync(path12.dirname(resolvedSummaryPath), { recursive: true });
22995
+ fs7.writeFileSync(resolvedSummaryPath, JSON.stringify(summary, null, 2), "utf8");
22465
22996
  summary.summary_output_path = resolvedSummaryPath;
22466
22997
  }
22467
22998
  if (!options.includeComparisonIndex) {
@@ -22522,7 +23053,7 @@ var RobloxStudioTools = class {
22522
23053
  return record.placeId !== void 0 && instance.placeId === record.placeId;
22523
23054
  }
22524
23055
  if ((record.source === "baseplate" || record.source === "local_file") && record.localPlaceFile) {
22525
- const expectedName = path11.basename(record.localPlaceFile);
23056
+ const expectedName = path12.basename(record.localPlaceFile);
22526
23057
  return instance.placeName === expectedName || instance.dataModelName === expectedName;
22527
23058
  }
22528
23059
  return true;
@@ -24001,7 +24532,7 @@ var RobloxStudioTools = class {
24001
24532
  throw new Error(`File exceeds Roblox's ${limitBytes}-byte (${limit}) ${assetType} upload limit: ${filePath}`);
24002
24533
  }
24003
24534
  });
24004
- const fileName = path11.basename(filePath);
24535
+ const fileName = path12.basename(filePath);
24005
24536
  const resolvedCreator = resolveUploadCreator(userId, groupId);
24006
24537
  if (assetType === "Decal" && this.cookieClient.hasCookie()) {
24007
24538
  const result2 = await this.cookieClient.uploadImage({
@@ -24209,10 +24740,10 @@ var RobloxStudioTools = class {
24209
24740
  return { content: [{ type: "text", text: JSON.stringify({ error: "plugin returned no base64 payload", ...notice }) }] };
24210
24741
  }
24211
24742
  const bytes = Buffer.from(response.base64, "base64");
24212
- const resolved = path11.resolve(outputPath);
24743
+ const resolved = path12.resolve(outputPath);
24213
24744
  try {
24214
- fs6.mkdirSync(path11.dirname(resolved), { recursive: true });
24215
- fs6.writeFileSync(resolved, bytes);
24745
+ fs7.mkdirSync(path12.dirname(resolved), { recursive: true });
24746
+ fs7.writeFileSync(resolved, bytes);
24216
24747
  } catch (err2) {
24217
24748
  return { content: [{ type: "text", text: JSON.stringify({ error: `failed to write ${resolved}: ${err2.message}`, ...notice }) }] };
24218
24749
  }
@@ -24262,8 +24793,12 @@ var RobloxStudioTools = class {
24262
24793
  // Even native capture must wait while another call has fitted the simulator
24263
24794
  // or drawn markers. Otherwise it could observe temporary UI or dimensions.
24264
24795
  async _captureViewportImage(instanceId, targetRole, format, quality, maxBytes = MAX_INLINE_IMAGE_BYTES) {
24796
+ return await this._withViewportQueue(instanceId, () => this._captureViewportImageNow(instanceId, targetRole, format, quality, maxBytes));
24797
+ }
24798
+ // Serializes viewport readers and marker transactions per Studio process.
24799
+ async _withViewportQueue(instanceId, run2) {
24265
24800
  const previous = this.viewportCaptureQueues.get(instanceId) ?? Promise.resolve();
24266
- const capture = previous.then(() => this._captureViewportImageNow(instanceId, targetRole, format, quality, maxBytes));
24801
+ const capture = previous.then(run2);
24267
24802
  const settled = capture.then(() => void 0, () => void 0);
24268
24803
  this.viewportCaptureQueues.set(instanceId, settled);
24269
24804
  try {
@@ -24572,6 +25107,311 @@ var RobloxStudioTools = class {
24572
25107
  ]
24573
25108
  };
24574
25109
  }
25110
+ // capture_video records the viewport on the MCP host (see video-recorder.ts)
25111
+ // and answers with the MP4 path plus a storyboard image the agent can read.
25112
+ async captureVideo(request = {}, instance_id) {
25113
+ const action = request.action ?? "record";
25114
+ if (!isVideoAction(action)) {
25115
+ throw new Error(`action must be one of ${VIDEO_ACTIONS.join(", ")}`);
25116
+ }
25117
+ if (action === "storyboard")
25118
+ return await this._videoStoryboard(request);
25119
+ for (const key of ["input_path", "start_ms", "end_ms"]) {
25120
+ if (request[key] !== void 0)
25121
+ throw new Error(`${key} is only used with action="storyboard"`);
25122
+ }
25123
+ if (action === "stop") {
25124
+ const recording2 = this._activeVideoRecording(instance_id);
25125
+ const frames = clampedInteger(request.frames, "frames", 0, VIDEO_MAX_STORYBOARD_FRAMES, recording2.storyboardFrames);
25126
+ this.videoRecordings.delete(recording2.instanceId);
25127
+ const exit2 = recording2.exit ?? await recording2.process.stop();
25128
+ return await this._finishVideo(action, recording2, exit2, frames);
25129
+ }
25130
+ if (action === "start" && request.duration_ms !== void 0) {
25131
+ throw new Error(`duration_ms is only used with action="record"; action="start" records until action="stop" (at most ${VIDEO_START_MAX_DURATION_MS} ms)`);
25132
+ }
25133
+ const storyboardFrames = clampedInteger(request.frames, "frames", 0, VIDEO_MAX_STORYBOARD_FRAMES, VIDEO_DEFAULT_STORYBOARD_FRAMES);
25134
+ const fps = clampedInteger(request.fps, "fps", 1, VIDEO_MAX_FPS, VIDEO_DEFAULT_FPS);
25135
+ const durationMs = clampedInteger(request.duration_ms, "duration_ms", VIDEO_MIN_DURATION_MS, VIDEO_MAX_DURATION_MS, VIDEO_DEFAULT_DURATION_MS);
25136
+ const maxDurationMs = action === "record" ? durationMs + 1e4 : VIDEO_START_MAX_DURATION_MS;
25137
+ const outputPath = request.output_path;
25138
+ if (outputPath !== void 0 && (typeof outputPath !== "string" || !outputPath.toLowerCase().endsWith(".mp4"))) {
25139
+ throw new Error("output_path must be a path ending in .mp4");
25140
+ }
25141
+ const started = await this._startVideoRecording(instance_id, { fps, maxDurationMs, storyboardFrames, outputPath });
25142
+ if (!started.ok)
25143
+ return this._textResult({ action, error: started.error });
25144
+ const { recording, width, height } = started;
25145
+ if (action === "start") {
25146
+ return this._textResult({
25147
+ action,
25148
+ recording: true,
25149
+ target: recording.targetRole,
25150
+ video: { path: recording.outputPath, fps, width, height, encoder: recording.encoder, source: recording.source },
25151
+ max_duration_ms: maxDurationMs,
25152
+ message: `Recording the Studio viewport. Trigger the scene now (for example with execute_luau, eval_client_runtime, or simulated input), then call capture_video action="stop". It stops itself after ${maxDurationMs} ms.`
25153
+ });
25154
+ }
25155
+ const remaining = Math.max(0, recording.startedAt + durationMs - Date.now());
25156
+ await settledWithin(recording.process.done, remaining);
25157
+ if (this.videoRecordings.get(recording.instanceId) === recording)
25158
+ this.videoRecordings.delete(recording.instanceId);
25159
+ const exit = recording.exit ?? await recording.process.stop();
25160
+ return await this._finishVideo(action, recording, exit, storyboardFrames);
25161
+ }
25162
+ _activeVideoRecording(instance_id) {
25163
+ if (instance_id !== void 0) {
25164
+ const key = this.bridge.resolveConnectedInstanceId(instance_id) ?? instance_id;
25165
+ const recording = this.videoRecordings.get(key) ?? this.videoRecordings.get(instance_id);
25166
+ if (!recording) {
25167
+ throw new Error(`No capture_video recording is active for instance_id "${instance_id}". Start one with action="start".`);
25168
+ }
25169
+ return recording;
25170
+ }
25171
+ const recordings = [...this.videoRecordings.values()];
25172
+ if (recordings.length === 1)
25173
+ return recordings[0];
25174
+ if (recordings.length === 0)
25175
+ throw new Error('No capture_video recording is active. Start one with action="start".');
25176
+ throw new Error(`Several capture_video recordings are active (${recordings.map((r) => r.instanceId).join(", ")}); pass instance_id.`);
25177
+ }
25178
+ async _startVideoRecording(instance_id, options) {
25179
+ const unsupported = videoRecordingUnsupportedReason();
25180
+ if (unsupported)
25181
+ return { ok: false, error: unsupported };
25182
+ if (isHostCaptureDisabled()) {
25183
+ return { ok: false, error: "video recording reads the Studio window, and host window capture is disabled by ROBLOX_STUDIO_HOST_CAPTURE" };
25184
+ }
25185
+ const refresh = this.bridge.refreshTopologyForRouting();
25186
+ if (refresh)
25187
+ await refresh;
25188
+ const { instanceId, clientRole } = this._resolveRuntime(instance_id);
25189
+ const targetRole = clientRole ?? "edit";
25190
+ const existing = this.videoRecordings.get(instanceId);
25191
+ if (this.videoStarting.has(instanceId) || existing && existing.exit === void 0) {
25192
+ return {
25193
+ ok: false,
25194
+ error: `A capture_video recording is already running for this Studio${existing ? ` (${existing.outputPath})` : ""}. Call action="stop" first.`
25195
+ };
25196
+ }
25197
+ this.videoStarting.add(instanceId);
25198
+ try {
25199
+ const probe = await this.videoRecorder.probe();
25200
+ if (!probe.ok)
25201
+ return { ok: false, error: probe.error };
25202
+ const outputPath = path12.resolve(options.outputPath ?? defaultVideoPath());
25203
+ await fs7.promises.mkdir(path12.dirname(outputPath), { recursive: true });
25204
+ if (options.outputPath === void 0)
25205
+ await pruneDefaultVideos(path12.dirname(outputPath));
25206
+ const located = await this._withViewportQueue(instanceId, () => this._locateVideoViewport(instanceId, targetRole, probe.ffmpegPath, probe.sources));
25207
+ if (!located.success)
25208
+ return { ok: false, error: `Could not locate the Studio viewport: ${located.error}` };
25209
+ const encoderProcess = this.videoRecorder.start({
25210
+ ffmpegPath: probe.ffmpegPath,
25211
+ encoder: probe.encoder,
25212
+ source: located.source,
25213
+ windowId: located.windowId,
25214
+ crop: located.rect,
25215
+ frameWidth: located.frameWidth,
25216
+ frameHeight: located.frameHeight,
25217
+ fps: options.fps,
25218
+ maxDurationMs: options.maxDurationMs,
25219
+ outputPath
25220
+ });
25221
+ const recording = {
25222
+ instanceId,
25223
+ targetRole,
25224
+ outputPath,
25225
+ ffmpegPath: probe.ffmpegPath,
25226
+ encoder: probe.encoder,
25227
+ source: located.source,
25228
+ fps: options.fps,
25229
+ maxDurationMs: options.maxDurationMs,
25230
+ storyboardFrames: options.storyboardFrames,
25231
+ startedAt: Date.now(),
25232
+ process: encoderProcess
25233
+ };
25234
+ void encoderProcess.done.then((exit) => {
25235
+ recording.exit = exit;
25236
+ });
25237
+ this.videoRecordings.set(instanceId, recording);
25238
+ const early = await settledWithin(encoderProcess.done, this.videoStartGraceMs);
25239
+ if (early !== void 0) {
25240
+ if (this.videoRecordings.get(instanceId) === recording)
25241
+ this.videoRecordings.delete(instanceId);
25242
+ return {
25243
+ ok: false,
25244
+ error: early.ok ? "ffmpeg stopped right after starting; nothing was recorded" : `Could not record the Studio window: ${early.error}`
25245
+ };
25246
+ }
25247
+ return { ok: true, recording, width: located.rect.width - located.rect.width % 2, height: located.rect.height - located.rect.height % 2 };
25248
+ } finally {
25249
+ this.videoStarting.delete(instanceId);
25250
+ }
25251
+ }
25252
+ // Finds the Studio window and the viewport rect inside the frames the
25253
+ // recorder will see. The markers are drawn and grabbed through the same
25254
+ // capture source as the recording, so no DPI conversion is involved.
25255
+ async _locateVideoViewport(instanceId, targetRole, ffmpegPath, sources) {
25256
+ const window = await this.hostWindowCapture(this._hostCaptureTitleHint(instanceId));
25257
+ if (!window.ok)
25258
+ return { success: false, error: window.error };
25259
+ const windowId = window.capture.identity?.windowId;
25260
+ if (windowId === void 0)
25261
+ return { success: false, error: "the host window capture did not identify the Studio window" };
25262
+ let prepared;
25263
+ let result;
25264
+ try {
25265
+ prepared = await this._callViewportMarkers("prepare", targetRole, instanceId);
25266
+ if (prepared.error || !prepared.captureId) {
25267
+ result = { success: false, error: prepared.error ?? "the Studio plugin could not prepare viewport markers (update the plugin)" };
25268
+ } else if (prepared.viewportChanged) {
25269
+ result = {
25270
+ success: false,
25271
+ error: 'device emulation is not using Fit to Window scaling, so the viewport would move once markers are removed. Call set_device_simulator with scalingMode="FitToWindow" (or stopSimulation=true), then record again.'
25272
+ };
25273
+ } else {
25274
+ result = await this._locateVideoViewportWithMarkers(instanceId, targetRole, prepared.captureId, ffmpegPath, windowId, sources);
25275
+ }
25276
+ } catch (error) {
25277
+ result = { success: false, error: errorMessage(error) };
25278
+ } finally {
25279
+ if (prepared?.captureId) {
25280
+ try {
25281
+ const restored = await this._callViewportMarkers("finish", targetRole, instanceId, prepared.captureId);
25282
+ if (restored.error)
25283
+ result = { success: false, error: `could not restore the Studio viewport: ${restored.error}` };
25284
+ else if (restored.stale || !restored.success)
25285
+ result = { success: false, error: "the viewport marker transaction expired; retry" };
25286
+ } catch (error) {
25287
+ result = { success: false, error: `could not restore the Studio viewport: ${errorMessage(error)}` };
25288
+ }
25289
+ }
25290
+ }
25291
+ return result;
25292
+ }
25293
+ async _locateVideoViewportWithMarkers(instanceId, targetRole, captureId, ffmpegPath, windowId, sources) {
25294
+ const shown = await this._callViewportMarkers("show", targetRole, instanceId, captureId);
25295
+ if (shown.error || !shown.viewportWidth || !shown.viewportHeight) {
25296
+ return { success: false, error: `could not draw viewport markers: ${shown.error ?? "no viewport size reported"}` };
25297
+ }
25298
+ let frame;
25299
+ let source;
25300
+ const grabErrors = [];
25301
+ let hidden;
25302
+ try {
25303
+ for (const candidate of sources) {
25304
+ try {
25305
+ frame = await this.videoRecorder.grabWindowFrame(ffmpegPath, windowId, candidate);
25306
+ source = candidate;
25307
+ break;
25308
+ } catch (error) {
25309
+ grabErrors.push(errorMessage(error));
25310
+ }
25311
+ }
25312
+ } finally {
25313
+ hidden = await this._callViewportMarkers("hide", targetRole, instanceId, captureId);
25314
+ }
25315
+ if (hidden.error)
25316
+ return { success: false, error: `could not hide viewport markers: ${hidden.error}` };
25317
+ if (!frame || !source)
25318
+ return { success: false, error: grabErrors.join("; ") || "no capture source is available" };
25319
+ const located = findViewportRect(frame.rgba, frame.width, frame.height, {
25320
+ viewportWidth: shown.viewportWidth,
25321
+ viewportHeight: shown.viewportHeight,
25322
+ markerSize: shown.markerSize ?? 12
25323
+ });
25324
+ if ("error" in located)
25325
+ return { success: false, error: located.error };
25326
+ return { success: true, windowId, source, rect: located.rect, frameWidth: frame.width, frameHeight: frame.height };
25327
+ }
25328
+ async _finishVideo(action, recording, exit, frames) {
25329
+ const video = {
25330
+ path: recording.outputPath,
25331
+ fps: recording.fps,
25332
+ encoder: recording.encoder,
25333
+ source: recording.source
25334
+ };
25335
+ const body = { action, target: recording.targetRole, video };
25336
+ if (!exit.ok)
25337
+ return this._textResult({ ...body, error: `The recording failed: ${exit.error}` });
25338
+ let info;
25339
+ try {
25340
+ info = await this.videoRecorder.mediaInfo(recording.ffmpegPath, recording.outputPath);
25341
+ } catch (error) {
25342
+ return this._textResult({ ...body, error: errorMessage(error) });
25343
+ }
25344
+ const stats = await fs7.promises.stat(recording.outputPath).catch(() => void 0);
25345
+ Object.assign(video, {
25346
+ duration_ms: Math.round(info.durationSeconds * 1e3),
25347
+ width: info.width,
25348
+ height: info.height,
25349
+ ...stats ? { bytes: stats.size } : {}
25350
+ });
25351
+ if (action === "stop" && exit.reason === "duration_limit") {
25352
+ body.stopped_by = "max_duration";
25353
+ body.message = `The recording reached its ${recording.maxDurationMs} ms limit and stopped itself before action="stop".`;
25354
+ }
25355
+ return await this._videoResultWithStoryboard(body, recording.ffmpegPath, recording.outputPath, info, 0, info.durationSeconds, frames);
25356
+ }
25357
+ async _videoStoryboard(request) {
25358
+ const inputPath = request.input_path;
25359
+ if (typeof inputPath !== "string" || inputPath === "") {
25360
+ throw new Error('input_path is required for action="storyboard": a video.path from an earlier capture_video result');
25361
+ }
25362
+ const frames = clampedInteger(request.frames, "frames", 1, VIDEO_MAX_STORYBOARD_FRAMES, VIDEO_DEFAULT_STORYBOARD_FRAMES);
25363
+ const resolved = path12.resolve(inputPath);
25364
+ const ffmpegPath = ffmpegCommand();
25365
+ const info = await this.videoRecorder.mediaInfo(ffmpegPath, resolved);
25366
+ const durationMs = Math.round(info.durationSeconds * 1e3);
25367
+ const startMs = clampedInteger(request.start_ms, "start_ms", 0, durationMs, 0);
25368
+ const endMs = clampedInteger(request.end_ms, "end_ms", 0, durationMs, durationMs);
25369
+ if (endMs <= startMs) {
25370
+ throw new Error(`end_ms must be after start_ms within the ${durationMs} ms video`);
25371
+ }
25372
+ const body = {
25373
+ action: "storyboard",
25374
+ video: { path: resolved, duration_ms: durationMs, width: info.width, height: info.height },
25375
+ window_ms: { start: startMs, end: endMs }
25376
+ };
25377
+ return await this._videoResultWithStoryboard(body, ffmpegPath, resolved, info, startMs / 1e3, endMs / 1e3, frames);
25378
+ }
25379
+ async _videoResultWithStoryboard(body, ffmpegPath, inputPath, info, startSeconds, endSeconds, frames) {
25380
+ if (frames <= 0)
25381
+ return this._textResult(body);
25382
+ try {
25383
+ const sheet = await this.videoRecorder.storyboard({
25384
+ ffmpegPath,
25385
+ inputPath,
25386
+ info,
25387
+ startSeconds,
25388
+ endSeconds,
25389
+ frames,
25390
+ maxWidth: VIDEO_STORYBOARD_MAX_WIDTH
25391
+ });
25392
+ if (sheet.jpeg.length > MAX_INLINE_IMAGE_BYTES)
25393
+ throw new Error(`the storyboard is ${sheet.jpeg.length} bytes, over the inline image limit`);
25394
+ body.storyboard = {
25395
+ frames: sheet.timesSeconds.length,
25396
+ columns: sheet.columns,
25397
+ rows: sheet.rows,
25398
+ width: sheet.width,
25399
+ height: sheet.height,
25400
+ times_ms: sheet.timesSeconds.map((t) => Math.round(t * 1e3))
25401
+ };
25402
+ const guide = `The image is a ${sheet.columns}x${sheet.rows} storyboard read left to right, top to bottom; storyboard.times_ms gives each frame's time in the video. To inspect a span closely, call capture_video action="storyboard" with input_path, start_ms, and end_ms instead of recording again.`;
25403
+ body.message = typeof body.message === "string" ? `${body.message} ${guide}` : guide;
25404
+ return {
25405
+ content: [
25406
+ { type: "text", text: JSON.stringify(body) },
25407
+ { type: "image", data: sheet.jpeg.toString("base64"), mimeType: "image/jpeg" }
25408
+ ]
25409
+ };
25410
+ } catch (error) {
25411
+ body.storyboard_error = errorMessage(error);
25412
+ return this._textResult(body);
25413
+ }
25414
+ }
24575
25415
  };
24576
25416
 
24577
25417
  // ../core/dist/mcp-runtime.js
@@ -24604,6 +25444,12 @@ Tool descriptions explain selection. Input schemas explain arguments. This guide
24604
25444
  - Use action=view with a BasePart or Model path to frame it, or omit path to frame exactly one selected BasePart or Model. Empty, multiple, or unsupported selections require an explicit target or a changed selection. The original camera type is restored after framing, including on failure. The current viewing direction is preserved unless from or angleY overrides it. padding below 1 crops closer and above 1 pulls back.
24605
25445
  - For visual proof, change the instance, frame it with selection, then call capture_screenshot.
24606
25446
 
25447
+ ## Video recording
25448
+
25449
+ - Use capture_video instead of repeated capture_screenshot calls to review motion such as a cutscene, camera path, tween, or animation. action=record records for duration_ms (up to 30 s) and blocks. To record a moment you trigger with other tools, call action=start, trigger it (execute_luau, eval_client_runtime, or simulated input), then action=stop; a started recording stops itself after 5 minutes.
25450
+ - The result saves an MP4 at video.path and returns one storyboard image of evenly spaced frames, with each frame's time in storyboard.times_ms; frames sets how many (0 omits the image). Re-sample part of a saved video with action=storyboard, input_path, start_ms, and end_ms instead of recording again.
25451
+ - During a playtest the recording follows the client viewport, like capture_screenshot. It reads the Studio window on the MCP host through FFmpeg 8 or newer (Windows or WSL), so it keeps recording behind other windows but not while Studio is minimized. Studio draws about 15 fps in the background, so bring Studio to the front for smooth playback.
25452
+
24607
25453
  ## Script changes
24608
25454
 
24609
25455
  - Read the relevant source with get_script_source before changing it.
@@ -24757,6 +25603,7 @@ var TEXT_RESULT_TOOLS = /* @__PURE__ */ new Set(["get_roblox_docs"]);
24757
25603
  var SIDE_EFFECTING_READ_TOOLS = /* @__PURE__ */ new Set([
24758
25604
  "capture_micro_profiler",
24759
25605
  "capture_script_profiler",
25606
+ "capture_video",
24760
25607
  "export_rbxm",
24761
25608
  "selection"
24762
25609
  ]);
@@ -24977,6 +25824,9 @@ function serverInstructions(definitions) {
24977
25824
  if (has("capture_screenshot", "simulate_mouse_input")) {
24978
25825
  instructions.push("Capture a screenshot before sending mouse input so its pixel coordinates match the viewport.");
24979
25826
  }
25827
+ if (has("capture_video")) {
25828
+ instructions.push("Use capture_video, not repeated capture_screenshot calls, to review motion such as cutscenes, tweens, or animations.");
25829
+ }
24980
25830
  if (has("selection", "capture_screenshot")) {
24981
25831
  instructions.push("Use selection action=view before capture_screenshot when the viewport must frame a specific instance.");
24982
25832
  }
@@ -25026,10 +25876,10 @@ function createToolHttpHandler(options) {
25026
25876
  // ../core/dist/auth.js
25027
25877
  import { randomBytes, createHash as createHash4, timingSafeEqual } from "crypto";
25028
25878
  import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync4, linkSync as linkSync2, unlinkSync as unlinkSync2 } from "fs";
25029
- import { join as join9, dirname as dirname5 } from "path";
25879
+ import { join as join10, dirname as dirname5 } from "path";
25030
25880
  import { homedir as homedir3 } from "os";
25031
25881
  function authTokenFilePath() {
25032
- return join9(homedir3(), ".robloxstudio-mcp", "auth-token");
25882
+ return join10(homedir3(), ".robloxstudio-mcp", "auth-token");
25033
25883
  }
25034
25884
  var EMPTY_TOKEN_RETRY_MS = 25;
25035
25885
  var EMPTY_TOKEN_RETRIES = 20;
@@ -25127,6 +25977,7 @@ var TOOL_PROXY_ENDPOINTS = {
25127
25977
  generate_model: ["/api/generate-model"],
25128
25978
  preview_asset: ["/api/preview-asset"],
25129
25979
  capture_screenshot: ["/api/capture-studio", "/api/capture-screenshot", "/api/capture-begin", "/api/capture-read", "/api/capture-markers"],
25980
+ capture_video: ["/api/capture-markers"],
25130
25981
  simulate_mouse_input: ["/api/simulate-mouse-input"],
25131
25982
  simulate_keyboard_input: ["/api/simulate-keyboard-input"],
25132
25983
  get_memory_breakdown: ["/api/get-memory-breakdown"],
@@ -25349,6 +26200,16 @@ var TOOL_HANDLERS = {
25349
26200
  preview_asset: (tools, body) => tools.previewAsset(body.assetId, body.includeProperties, body.maxDepth, body.instance_id, body.includeAudio, body.maxAudioPreviews),
25350
26201
  upload_asset: (tools, body) => tools.uploadAsset(body.filePath, body.assetType, body.displayName, body.description, body.userId, body.groupId),
25351
26202
  capture_screenshot: (tools, body) => tools.captureScreenshot(body.instance_id, body.format, body.quality),
26203
+ capture_video: (tools, body) => tools.captureVideo({
26204
+ action: body.action,
26205
+ duration_ms: body.duration_ms,
26206
+ fps: body.fps,
26207
+ output_path: body.output_path,
26208
+ frames: body.frames,
26209
+ input_path: body.input_path,
26210
+ start_ms: body.start_ms,
26211
+ end_ms: body.end_ms
26212
+ }, body.instance_id),
25352
26213
  simulate_mouse_input: (tools, body) => tools.simulateMouseInput(body.action, body.x, body.y, body.button, body.wheel, body.target, body.instance_id),
25353
26214
  simulate_keyboard_input: (tools, body) => tools.simulateKeyboardInput(body.keyCode, body.action, body.duration, body.text, body.target, body.instance_id),
25354
26215
  get_memory_breakdown: (tools, body) => tools.getMemoryBreakdown(body.target, body.tags, body.instance_id),
@@ -25524,8 +26385,8 @@ function createHttpServer(tools, bridge, allowedTools, serverConfig, security) {
25524
26385
  });
25525
26386
  const authToken = security?.authToken;
25526
26387
  const authRequired = (requestPath) => {
25527
- const path12 = requestPath.toLowerCase().replace(/\/+$/, "");
25528
- return path12 === "/mcp" || path12.startsWith("/mcp/") || path12 === "/proxy" || path12 === "/topology" || path12 === "/request-status" || path12 === "/unregister-instance-id" || path12 === "/create-multiplayer-group" || path12 === "/remove-multiplayer-group";
26388
+ const path13 = requestPath.toLowerCase().replace(/\/+$/, "");
26389
+ return path13 === "/mcp" || path13.startsWith("/mcp/") || path13 === "/proxy" || path13 === "/topology" || path13 === "/request-status" || path13 === "/unregister-instance-id" || path13 === "/create-multiplayer-group" || path13 === "/remove-multiplayer-group";
25529
26390
  };
25530
26391
  app.use((req, res, next) => {
25531
26392
  if (!authToken || !authRequired(req.path)) {
@@ -26885,7 +27746,7 @@ var import_saxes = __toESM(require_saxes(), 1);
26885
27746
  import { existsSync as existsSync6, lstatSync as lstatSync2, mkdirSync as mkdirSync5, readFileSync as readFileSync9, renameSync, rmSync as rmSync5, rmdirSync, statSync as statSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync5 } from "fs";
26886
27747
  import { execSync } from "child_process";
26887
27748
  import { randomUUID as randomUUID8 } from "crypto";
26888
- import { basename as basename3, join as join10 } from "path";
27749
+ import { basename as basename3, join as join11 } from "path";
26889
27750
  import { homedir as homedir4 } from "os";
26890
27751
  import { isUtf8 } from "buffer";
26891
27752
  var DEFAULT_PLUGIN_PORT = 58741;
@@ -26937,15 +27798,15 @@ function getPluginsFolder() {
26937
27798
  if (process.env.MCP_PLUGINS_DIR)
26938
27799
  return process.env.MCP_PLUGINS_DIR;
26939
27800
  if (process.platform === "win32") {
26940
- return join10(process.env.LOCALAPPDATA || join10(homedir4(), "AppData", "Local"), "Roblox", "Plugins");
27801
+ return join11(process.env.LOCALAPPDATA || join11(homedir4(), "AppData", "Local"), "Roblox", "Plugins");
26941
27802
  }
26942
27803
  if (isWSL()) {
26943
27804
  const localAppData = getWindowsUserLocalAppData();
26944
27805
  if (localAppData)
26945
- return join10(localAppData.linuxPath, "Roblox", "Plugins");
27806
+ return join11(localAppData.linuxPath, "Roblox", "Plugins");
26946
27807
  console.warn("[install-plugin] WSL detected but could not resolve Windows %LOCALAPPDATA%. Falling back to ~/Documents/Roblox/Plugins/ - you will likely need to copy the rbxmx to /mnt/c/Users/<you>/AppData/Local/Roblox/Plugins/ manually. Set MCP_PLUGINS_DIR to skip detection.");
26947
27808
  }
26948
- return join10(homedir4(), "Documents", "Roblox", "Plugins");
27809
+ return join11(homedir4(), "Documents", "Roblox", "Plugins");
26949
27810
  }
26950
27811
  var STALE_TEST_PLUGINS_DIRECTORY = "RsmcpIsolatedPlugins";
26951
27812
  function pluginDirectorySettingPattern() {
@@ -26988,16 +27849,16 @@ function repairDefaultStudioPluginDirectorySetting(pluginsFolder, log) {
26988
27849
  let defaultPluginsFolder;
26989
27850
  let studioPluginsDirectory;
26990
27851
  if (process.platform === "win32") {
26991
- const localAppData = process.env.LOCALAPPDATA || join10(homedir4(), "AppData", "Local");
26992
- defaultPluginsFolder = join10(localAppData, "Roblox", "Plugins");
26993
- settingsPath = join10(localAppData, "Roblox", "GlobalSettings_13.xml");
27852
+ const localAppData = process.env.LOCALAPPDATA || join11(homedir4(), "AppData", "Local");
27853
+ defaultPluginsFolder = join11(localAppData, "Roblox", "Plugins");
27854
+ settingsPath = join11(localAppData, "Roblox", "GlobalSettings_13.xml");
26994
27855
  studioPluginsDirectory = defaultPluginsFolder.replaceAll("\\", "/");
26995
27856
  } else if (isWSL()) {
26996
27857
  const localAppData = getWindowsUserLocalAppData();
26997
27858
  if (!localAppData)
26998
27859
  return;
26999
- defaultPluginsFolder = join10(localAppData.linuxPath, "Roblox", "Plugins");
27000
- settingsPath = join10(localAppData.linuxPath, "Roblox", "GlobalSettings_13.xml");
27860
+ defaultPluginsFolder = join11(localAppData.linuxPath, "Roblox", "Plugins");
27861
+ settingsPath = join11(localAppData.linuxPath, "Roblox", "GlobalSettings_13.xml");
27001
27862
  studioPluginsDirectory = [
27002
27863
  localAppData.windowsPath.replace(/[\\/]+$/u, ""),
27003
27864
  "Roblox",
@@ -27013,7 +27874,7 @@ function repairDefaultStudioPluginDirectorySetting(pluginsFolder, log) {
27013
27874
  }
27014
27875
  }
27015
27876
  function handleVariantConflict({ pluginsFolder, otherAssetName, replace, log = console.log, warn = console.warn }) {
27016
- const otherDest = join10(pluginsFolder, otherAssetName);
27877
+ const otherDest = join11(pluginsFolder, otherAssetName);
27017
27878
  if (!existsSync6(otherDest))
27018
27879
  return;
27019
27880
  if (replace) {
@@ -27039,7 +27900,7 @@ function pluginInstallLockError(lockPath, reason) {
27039
27900
  return new Error(`${reason}: ${lockPath}. If no installer or lock recovery is running, remove that lock directory and retry.`);
27040
27901
  }
27041
27902
  function readPluginInstallLockOwner(lockPath) {
27042
- const ownerPath = join10(lockPath, "owner.json");
27903
+ const ownerPath = join11(lockPath, "owner.json");
27043
27904
  if (!lstatSync2(lockPath).isDirectory() || !lstatSync2(ownerPath).isFile()) {
27044
27905
  throw new Error("Lock and owner metadata must be a directory and regular file");
27045
27906
  }
@@ -27069,7 +27930,7 @@ function recoverPluginInstallLock(lockPath, warn) {
27069
27930
  throw pluginInstallLockError(lockPath, `Cannot safely read plugin installation lock owner (${error})`);
27070
27931
  }
27071
27932
  assertPluginInstallOwnerExited(lockPath, owner);
27072
- const claimPath = join10(lockPath, `recovery-${owner.token}`);
27933
+ const claimPath = join11(lockPath, `recovery-${owner.token}`);
27073
27934
  try {
27074
27935
  mkdirSync5(claimPath);
27075
27936
  } catch (error) {
@@ -27108,8 +27969,8 @@ function recoverPluginInstallLock(lockPath, warn) {
27108
27969
  }
27109
27970
  }
27110
27971
  function acquirePluginInstallLock(pluginsFolder, warn) {
27111
- const lockPath = join10(pluginsFolder, PLUGIN_INSTALL_LOCK_NAME);
27112
- const ownerPath = join10(lockPath, "owner.json");
27972
+ const lockPath = join11(pluginsFolder, PLUGIN_INSTALL_LOCK_NAME);
27973
+ const ownerPath = join11(lockPath, "owner.json");
27113
27974
  const owner = {
27114
27975
  pid: process.pid,
27115
27976
  token: randomUUID8(),
@@ -27255,12 +28116,12 @@ function installPluginAsset({ pluginsFolder, assetName, otherAssetName, source,
27255
28116
  const configured = configurePluginAssetForPort(source, rawPort);
27256
28117
  assertPluginAssetIdentity(configured, assetName, expectedVersion, expectedVariant);
27257
28118
  mkdirSync5(pluginsFolder, { recursive: true });
27258
- const destination = join10(pluginsFolder, assetName);
28119
+ const destination = join11(pluginsFolder, assetName);
27259
28120
  const releaseLock = acquirePluginInstallLock(pluginsFolder, warn);
27260
28121
  try {
27261
28122
  let installed = false;
27262
28123
  if (!installedFileMatches(configured, destination)) {
27263
- const staged = join10(pluginsFolder, `.${assetName}.${process.pid}.${randomUUID8()}.tmp`);
28124
+ const staged = join11(pluginsFolder, `.${assetName}.${process.pid}.${randomUUID8()}.tmp`);
27264
28125
  try {
27265
28126
  writeFileSync5(staged, configured, { flag: "wx" });
27266
28127
  renameSync(staged, destination);
@@ -27291,7 +28152,7 @@ function installPluginAsset({ pluginsFolder, assetName, otherAssetName, source,
27291
28152
 
27292
28153
  // ../core/dist/plugin-installer.js
27293
28154
  import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
27294
- import { dirname as dirname6, join as join11 } from "path";
28155
+ import { dirname as dirname6, join as join12 } from "path";
27295
28156
  import { fileURLToPath } from "url";
27296
28157
  import { get } from "https";
27297
28158
  var REPO = "chrrxs/robloxstudio-mcp";
@@ -27355,8 +28216,8 @@ function createPluginInstaller(moduleUrl, variant) {
27355
28216
  }
27356
28217
  function bundledAssetPath() {
27357
28218
  const candidates = [
27358
- join11(currentDir, "..", "studio-plugin", ASSET_NAME),
27359
- join11(currentDir, "..", "..", "..", "studio-plugin", ASSET_NAME)
28219
+ join12(currentDir, "..", "studio-plugin", ASSET_NAME),
28220
+ join12(currentDir, "..", "..", "..", "studio-plugin", ASSET_NAME)
27360
28221
  ];
27361
28222
  return candidates.find((candidate) => existsSync7(candidate)) ?? null;
27362
28223
  }
@@ -27366,7 +28227,7 @@ function createPluginInstaller(moduleUrl, variant) {
27366
28227
  return existsSync7(sourcePath) ? sourcePath : null;
27367
28228
  }
27368
28229
  function packageVersion() {
27369
- const pkg = JSON.parse(readFileSync10(join11(currentDir, "..", "package.json"), "utf8"));
28230
+ const pkg = JSON.parse(readFileSync10(join12(currentDir, "..", "package.json"), "utf8"));
27370
28231
  if (!pkg.version) {
27371
28232
  throw new Error("Package version not found");
27372
28233
  }