@luaward/mcp 0.2.4 → 0.2.6

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
@@ -233,7 +233,7 @@ var PotassiumClient = class {
233
233
  params: {
234
234
  protocolVersion: "2025-03-26",
235
235
  capabilities: {},
236
- clientInfo: { name: "@luaward/mcp", version: "0.2.4" }
236
+ clientInfo: { name: "@luaward/mcp", version: "0.2.6" }
237
237
  }
238
238
  })
239
239
  });
@@ -508,6 +508,105 @@ import { homedir as homedir2 } from "node:os";
508
508
  import { join as join2 } from "node:path";
509
509
  import { createInterface } from "node:readline";
510
510
  import { inflateSync } from "node:zlib";
511
+ var LUAU_RESERVED_KEYWORDS = /* @__PURE__ */ new Set([
512
+ "and",
513
+ "break",
514
+ "do",
515
+ "else",
516
+ "elseif",
517
+ "end",
518
+ "false",
519
+ "for",
520
+ "function",
521
+ "if",
522
+ "in",
523
+ "local",
524
+ "nil",
525
+ "not",
526
+ "or",
527
+ "repeat",
528
+ "return",
529
+ "then",
530
+ "true",
531
+ "until",
532
+ "while"
533
+ ]);
534
+ var LUAU_IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
535
+ function escapeLuauString(str) {
536
+ let out = '"';
537
+ for (let i = 0; i < str.length; i++) {
538
+ const code = str.charCodeAt(i);
539
+ if (code === 34) {
540
+ out += '\\"';
541
+ } else if (code === 92) {
542
+ out += "\\\\";
543
+ } else if (code === 10) {
544
+ out += "\\n";
545
+ } else if (code === 13) {
546
+ out += "\\r";
547
+ } else if (code === 9) {
548
+ out += "\\t";
549
+ } else if (code < 32 || code === 127) {
550
+ out += `\\${String(code).padStart(3, "0")}`;
551
+ } else {
552
+ out += str[i];
553
+ }
554
+ }
555
+ out += '"';
556
+ return out;
557
+ }
558
+ function toLuauLiteral(value) {
559
+ if (value === null || value === void 0) {
560
+ return "nil";
561
+ }
562
+ if (typeof value === "boolean") {
563
+ return value ? "true" : "false";
564
+ }
565
+ if (typeof value === "number") {
566
+ if (Number.isNaN(value)) return "0";
567
+ if (!Number.isFinite(value)) return value > 0 ? "math.huge" : "-math.huge";
568
+ return String(value);
569
+ }
570
+ if (typeof value === "string") {
571
+ return escapeLuauString(value);
572
+ }
573
+ if (Array.isArray(value)) {
574
+ if (value.length === 0) return "{}";
575
+ return `{ ${value.map((item) => toLuauLiteral(item)).join(", ")} }`;
576
+ }
577
+ if (typeof value === "object") {
578
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0);
579
+ if (entries.length === 0) return "{}";
580
+ const fields = entries.map(([k, v]) => {
581
+ const keyExpr = LUAU_IDENT_RE.test(k) && !LUAU_RESERVED_KEYWORDS.has(k) ? k : `[${escapeLuauString(k)}]`;
582
+ return `${keyExpr} = ${toLuauLiteral(v)}`;
583
+ });
584
+ return `{ ${fields.join(", ")} }`;
585
+ }
586
+ return "nil";
587
+ }
588
+ function buildStudioSpawnSpec(batchPath) {
589
+ const isBat = /\.(?:bat|cmd)$/i.test(batchPath);
590
+ if (isBat) {
591
+ return {
592
+ command: "cmd.exe",
593
+ args: ["/d", "/s", "/c", `"${batchPath}"`],
594
+ options: {
595
+ stdio: ["pipe", "pipe", "pipe"],
596
+ windowsVerbatimArguments: true,
597
+ windowsHide: true
598
+ }
599
+ };
600
+ }
601
+ return {
602
+ command: batchPath,
603
+ args: [],
604
+ options: {
605
+ stdio: ["pipe", "pipe", "pipe"],
606
+ windowsHide: true
607
+ }
608
+ };
609
+ }
511
610
  function discoverRobloxStudioMcpBatch(env = process.env) {
512
611
  if (env.ROBLOX_STUDIO_MCP_PATH?.trim()) {
513
612
  return env.ROBLOX_STUDIO_MCP_PATH.trim();
@@ -565,16 +664,19 @@ function parseStudioToolResponse(rpcRes) {
565
664
  var RobloxStudioMcpClient = class {
566
665
  batchPath;
567
666
  timeoutMs;
667
+ defaultDataModelType;
568
668
  customTransport;
569
669
  child = null;
570
670
  initPromise = null;
571
671
  pending = /* @__PURE__ */ new Map();
572
672
  rpcSeq = 9e3;
573
673
  cachedToolNames = null;
674
+ cachedToolSchemas = /* @__PURE__ */ new Map();
574
675
  exitHookInstalled = false;
575
676
  constructor(options = {}) {
576
677
  this.batchPath = options.batchPath || discoverRobloxStudioMcpBatch(options.env);
577
678
  this.timeoutMs = options.timeoutMs ?? 25e3;
679
+ this.defaultDataModelType = options.defaultDataModelType ?? "Edit";
578
680
  this.customTransport = options.transport;
579
681
  }
580
682
  dispose() {
@@ -604,14 +706,8 @@ var RobloxStudioMcpClient = class {
604
706
  `Roblox Studio MCP launcher not found at "${this.batchPath}". Ensure Roblox Studio is installed with MCP enabled (expected %LOCALAPPDATA%\\Roblox\\mcp.bat) or set ROBLOX_STUDIO_MCP_PATH.`
605
707
  );
606
708
  }
607
- const isBat = /\.(?:bat|cmd)$/i.test(this.batchPath);
608
- const child = isBat ? spawn("cmd.exe", ["/d", "/s", "/c", `"${this.batchPath}"`], {
609
- stdio: ["pipe", "pipe", "pipe"],
610
- windowsHide: true
611
- }) : spawn(this.batchPath, [], {
612
- stdio: ["pipe", "pipe", "pipe"],
613
- windowsHide: true
614
- });
709
+ const spec = buildStudioSpawnSpec(this.batchPath);
710
+ const child = spawn(spec.command, spec.args, spec.options);
615
711
  child.unref();
616
712
  this.child = child;
617
713
  if (!this.exitHookInstalled) {
@@ -652,7 +748,7 @@ var RobloxStudioMcpClient = class {
652
748
  await this.sendRawRpc("initialize", {
653
749
  protocolVersion: "2025-03-26",
654
750
  capabilities: {},
655
- clientInfo: { name: "@luaward/mcp", version: "0.2.4" }
751
+ clientInfo: { name: "@luaward/mcp", version: "0.2.6" }
656
752
  });
657
753
  if (this.child && !this.child.killed) {
658
754
  this.child.stdin.write(
@@ -695,6 +791,12 @@ var RobloxStudioMcpClient = class {
695
791
  const res = await this.sendRpc("tools/list", {});
696
792
  const tools = res?.result?.tools;
697
793
  if (Array.isArray(tools)) {
794
+ this.cachedToolSchemas.clear();
795
+ for (const t of tools) {
796
+ if (typeof t?.name === "string" && t.name && t.inputSchema && typeof t.inputSchema === "object") {
797
+ this.cachedToolSchemas.set(t.name, t.inputSchema);
798
+ }
799
+ }
698
800
  this.cachedToolNames = tools.map((t) => typeof t?.name === "string" ? t.name : "").filter(Boolean);
699
801
  return this.cachedToolNames;
700
802
  }
@@ -704,7 +806,8 @@ var RobloxStudioMcpClient = class {
704
806
  }
705
807
  async listStudios() {
706
808
  const tools = await this.listTools();
707
- const listToolName = tools.find((t) => t === "list_studios" || t === "get_studios" || t === "list_clients") ?? "list_studios";
809
+ const listPriority = ["list_roblox_studios", "list_studios", "get_studios", "list_clients"];
810
+ const listToolName = listPriority.find((candidate) => tools.includes(candidate)) ?? "list_roblox_studios";
708
811
  try {
709
812
  const rpcRes = await this.sendRpc("tools/call", { name: listToolName, arguments: {} });
710
813
  const parsed = parseStudioToolResponse(rpcRes);
@@ -719,19 +822,24 @@ var RobloxStudioMcpClient = class {
719
822
  if (item && typeof item === "object") {
720
823
  const obj = item;
721
824
  const sid = String(
722
- obj.studio_id ?? obj.studioId ?? obj.id ?? obj.session_id ?? obj.pid ?? ""
825
+ obj.id ?? obj.studio_id ?? obj.studioId ?? obj.session_id ?? obj.pid ?? ""
723
826
  ).trim();
724
827
  if (sid) {
828
+ const placeNameRaw = obj.place_name ?? obj.placeName ?? obj.local_file_name ?? obj.name;
725
829
  studios.push({
830
+ id: sid,
726
831
  studio_id: sid,
727
832
  place_id: obj.place_id ?? obj.placeId,
728
- place_name: typeof (obj.place_name ?? obj.placeName ?? obj.name) === "string" ? String(obj.place_name ?? obj.placeName ?? obj.name) : void 0,
833
+ game_id: obj.game_id ?? obj.gameId,
834
+ place_name: typeof placeNameRaw === "string" ? placeNameRaw : void 0,
835
+ local_file_name: typeof obj.local_file_name === "string" ? obj.local_file_name : void 0,
729
836
  user: typeof obj.user === "string" ? obj.user : void 0,
730
837
  raw: obj
731
838
  });
732
839
  }
733
840
  } else if (typeof item === "string" || typeof item === "number") {
734
- studios.push({ studio_id: String(item) });
841
+ const sid = String(item);
842
+ studios.push({ id: sid, studio_id: sid });
735
843
  }
736
844
  }
737
845
  return { ok: true, studios, rawText: parsed.text };
@@ -740,7 +848,7 @@ var RobloxStudioMcpClient = class {
740
848
  ...parsed.text.matchAll(/\b(?:studio_id|studioId|studio|id)[:=\s"']*([A-Za-z0-9_-]{2,64})\b/gi)
741
849
  ];
742
850
  for (const m of matches) {
743
- if (m[1]) studios.push({ studio_id: m[1] });
851
+ if (m[1]) studios.push({ id: m[1], studio_id: m[1] });
744
852
  }
745
853
  return { ok: true, studios, rawText: parsed.text };
746
854
  } catch (err) {
@@ -756,10 +864,11 @@ var RobloxStudioMcpClient = class {
756
864
  */
757
865
  async resolveStudioId(explicitStudioId) {
758
866
  if (explicitStudioId && explicitStudioId.trim()) {
867
+ const sid = explicitStudioId.trim();
759
868
  return {
760
869
  ok: true,
761
- studioId: explicitStudioId.trim(),
762
- studios: [{ studio_id: explicitStudioId.trim() }],
870
+ studioId: sid,
871
+ studios: [{ id: sid, studio_id: sid }],
763
872
  autoSelected: false
764
873
  };
765
874
  }
@@ -773,9 +882,10 @@ var RobloxStudioMcpClient = class {
773
882
  };
774
883
  }
775
884
  if (listed.studios.length === 1 && listed.studios[0]) {
885
+ const sid = listed.studios[0].id || listed.studios[0].studio_id;
776
886
  return {
777
887
  ok: true,
778
- studioId: listed.studios[0].studio_id,
888
+ studioId: sid,
779
889
  studios: listed.studios,
780
890
  autoSelected: true
781
891
  };
@@ -788,7 +898,7 @@ var RobloxStudioMcpClient = class {
788
898
  err: "No connected Roblox Studio instance found via %LOCALAPPDATA%\\Roblox\\mcp.bat. Open a place in Roblox Studio with MCP enabled first."
789
899
  };
790
900
  }
791
- const listStr = listed.studios.map((s) => `${s.studio_id}${s.place_name ? ` ("${s.place_name}")` : ""}`).join(", ");
901
+ const listStr = listed.studios.map((s) => `${s.id || s.studio_id}${s.place_name ? ` ("${s.place_name}")` : ""}`).join(", ");
792
902
  return {
793
903
  ok: false,
794
904
  studios: listed.studios,
@@ -800,7 +910,8 @@ var RobloxStudioMcpClient = class {
800
910
  const finalArgs = { ...args };
801
911
  let studioId = typeof finalArgs.studio_id === "string" ? finalArgs.studio_id.trim() : void 0;
802
912
  let autoSelected = false;
803
- if (!studioId && name !== "list_studios" && name !== "get_studios") {
913
+ const isListTool = name === "list_roblox_studios" || name === "list_studios" || name === "get_studios" || name === "list_clients";
914
+ if (!studioId && !isListTool) {
804
915
  const resolved = await this.resolveStudioId();
805
916
  if (!resolved.ok) {
806
917
  return { ok: false, text: resolved.err ?? "Failed to resolve studio_id", isError: true };
@@ -811,6 +922,12 @@ var RobloxStudioMcpClient = class {
811
922
  finalArgs.studio_id = studioId;
812
923
  }
813
924
  }
925
+ if (!isListTool && finalArgs.datamodel_type === void 0) {
926
+ const schemaProps = this.cachedToolSchemas.get(name)?.properties;
927
+ if (name === "execute_luau" || schemaProps && "datamodel_type" in schemaProps) {
928
+ finalArgs.datamodel_type = this.defaultDataModelType;
929
+ }
930
+ }
814
931
  try {
815
932
  const rpcRes = await this.sendRpc("tools/call", { name, arguments: finalArgs });
816
933
  const parsed = parseStudioToolResponse(rpcRes);
@@ -829,7 +946,7 @@ var RobloxStudioMcpClient = class {
829
946
  };
830
947
  }
831
948
  }
832
- async runStudioLuau(code, explicitStudioId) {
949
+ async runStudioLuau(code, explicitStudioId, datamodelType) {
833
950
  const resolved = await this.resolveStudioId(explicitStudioId);
834
951
  if (!resolved.ok) {
835
952
  return {
@@ -839,13 +956,30 @@ var RobloxStudioMcpClient = class {
839
956
  };
840
957
  }
841
958
  const tools = await this.listTools();
842
- const execTool = tools.find((t) => t === "run_code" || t === "execute_luau" || t === "run_script" || t === "eval") ?? "run_code";
843
- const res = await this.callTool(execTool, {
844
- command: code,
845
- code,
846
- source: code,
959
+ const execPriority = ["execute_luau", "run_code", "run_script", "eval"];
960
+ const execTool = execPriority.find((candidate) => tools.includes(candidate)) ?? "execute_luau";
961
+ const dmType = datamodelType ?? this.defaultDataModelType;
962
+ const schemaProps = this.cachedToolSchemas.get(execTool)?.properties;
963
+ const toolArgs = {
964
+ datamodel_type: dmType,
847
965
  ...resolved.studioId ? { studio_id: resolved.studioId } : {}
848
- });
966
+ };
967
+ if (execTool === "execute_luau") {
968
+ toolArgs.code = code;
969
+ if (schemaProps && "command" in schemaProps) {
970
+ toolArgs.command = code;
971
+ }
972
+ } else if (execTool === "run_code") {
973
+ toolArgs.command = code;
974
+ if (!schemaProps || "code" in schemaProps) {
975
+ toolArgs.code = code;
976
+ }
977
+ } else {
978
+ toolArgs.code = code;
979
+ toolArgs.command = code;
980
+ toolArgs.source = code;
981
+ }
982
+ const res = await this.callTool(execTool, toolArgs);
849
983
  return {
850
984
  ...res,
851
985
  studioId: resolved.studioId,
@@ -1239,6 +1373,10 @@ namespace Luaward {
1239
1373
  [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
1240
1374
  [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
1241
1375
  [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
1376
+ [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);
1377
+ [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
1378
+ [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
1379
+ [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
1242
1380
  [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
1243
1381
  [DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
1244
1382
  [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
@@ -1258,6 +1396,52 @@ namespace Luaward {
1258
1396
 
1259
1397
  public const uint GA_ROOT = 2;
1260
1398
  public const uint PW_RENDERFULLCONTENT = 0x00000002;
1399
+ public const byte VK_MENU = 0x12;
1400
+
1401
+ public static bool ForceForegroundWindow(IntPtr targetHwnd) {
1402
+ if (targetHwnd == IntPtr.Zero) return false;
1403
+ if (IsIconic(targetHwnd)) {
1404
+ ShowWindow(targetHwnd, 9);
1405
+ }
1406
+ SetForegroundWindow(targetHwnd);
1407
+ if (GetForegroundWindow() == targetHwnd) {
1408
+ return true;
1409
+ }
1410
+
1411
+ IntPtr fg = GetForegroundWindow();
1412
+ uint dummyPid = 0;
1413
+ uint curTid = GetCurrentThreadId();
1414
+ uint targetTid = GetWindowThreadProcessId(targetHwnd, out dummyPid);
1415
+ uint fgTid = fg != IntPtr.Zero ? GetWindowThreadProcessId(fg, out dummyPid) : 0;
1416
+
1417
+ bool attachedCurToFg = false;
1418
+ bool attachedCurToTarget = false;
1419
+ bool attachedFgToTarget = false;
1420
+ try {
1421
+ if (fgTid != 0 && fgTid != curTid) {
1422
+ attachedCurToFg = AttachThreadInput(curTid, fgTid, true);
1423
+ }
1424
+ if (targetTid != 0 && targetTid != curTid) {
1425
+ attachedCurToTarget = AttachThreadInput(curTid, targetTid, true);
1426
+ }
1427
+ if (fgTid != 0 && targetTid != 0 && fgTid != targetTid) {
1428
+ attachedFgToTarget = AttachThreadInput(fgTid, targetTid, true);
1429
+ }
1430
+
1431
+ // Briefly pulse Alt (VK_MENU) so Windows releases the Foreground Lock Timeout for background workers.
1432
+ keybd_event(VK_MENU, 0, 0, UIntPtr.Zero);
1433
+ keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
1434
+
1435
+ BringWindowToTop(targetHwnd);
1436
+ ShowWindow(targetHwnd, 5);
1437
+ SetForegroundWindow(targetHwnd);
1438
+ } finally {
1439
+ if (attachedFgToTarget) AttachThreadInput(fgTid, targetTid, false);
1440
+ if (attachedCurToTarget) AttachThreadInput(curTid, targetTid, false);
1441
+ if (attachedCurToFg) AttachThreadInput(curTid, fgTid, false);
1442
+ }
1443
+ return GetForegroundWindow() == targetHwnd;
1444
+ }
1261
1445
 
1262
1446
  public static bool IsWindowTopAtPoint(IntPtr targetHwnd, int x, int y) {
1263
1447
  if (targetHwnd == IntPtr.Zero) return false;
@@ -1576,20 +1760,37 @@ ${scriptBody}`;
1576
1760
  if (!filterStr) return all;
1577
1761
  return all.filter((w) => matchesWindowTarget(w, filterStr));
1578
1762
  }
1579
- async focusWindow(target) {
1763
+ async focusWindow(target, opts) {
1580
1764
  const wins = await this.listWindows(target);
1581
1765
  const win = wins[0];
1582
1766
  if (!win) return { ok: false, err: `No window matching "${target}" found` };
1583
- await this.runPsJson(
1584
- `
1585
- $h = [IntPtr]::new([Convert]::ToInt64("${win.hwnd}", 16))
1586
- if ([Luaward.Win32Desktop]::IsIconic($h)) { [void][Luaward.Win32Desktop]::ShowWindow($h, 9) }
1587
- [void][Luaward.Win32Desktop]::SetForegroundWindow($h)
1588
- @{ ok = $true } | ConvertTo-Json -Compress
1589
- `
1590
- );
1767
+ const res = await this.runPsJson(buildFocusWindowPsScript(win.hwnd, opts?.verifyPoint));
1591
1768
  const refreshed = (await this.listWindows(target))[0] ?? win;
1592
- return { ok: true, window: refreshed };
1769
+ const isForeground = Boolean(res.isForeground || refreshed.isForeground);
1770
+ const isTopAtPoint = Boolean(res.isTopAtPoint);
1771
+ const ok = isForeground || isTopAtPoint;
1772
+ return {
1773
+ ok,
1774
+ window: refreshed,
1775
+ isForeground,
1776
+ isTopAtPoint,
1777
+ fgProcess: res.fgProcess,
1778
+ ...ok ? {} : {
1779
+ err: `Could not bring "${refreshed.title}" (${refreshed.hwnd}) to foreground; current foreground process is "${res.fgProcess || "unknown"}"`
1780
+ }
1781
+ };
1782
+ }
1783
+ async isWindowTopAtPoint(hwnd, x, y) {
1784
+ const rx = Math.round(x);
1785
+ const ry = Math.round(y);
1786
+ return this.runPsJson(`
1787
+ $h = [IntPtr]::new([Convert]::ToInt64("${hwnd}", 16))
1788
+ $fg = [Luaward.Win32Desktop]::GetForegroundWindow()
1789
+ $isFg = ($fg -eq $h)
1790
+ $isTop = [Luaward.Win32Desktop]::IsWindowTopAtPoint($h, ${rx}, ${ry})
1791
+ $fgProc = (Get-ForegroundProcessName)
1792
+ @{ ok = $true; isTop = $isTop; isForeground = $isFg; fgProcess = $fgProc } | ConvertTo-Json -Compress
1793
+ `);
1593
1794
  }
1594
1795
  async resizeWindow(opts) {
1595
1796
  const wins = await this.listWindows(opts.target);
@@ -2080,6 +2281,21 @@ Walk-Ui $root 1
2080
2281
  if ($nodes.Count -eq 0) { "[]" } else { ConvertTo-Json -InputObject $nodes.ToArray() -Depth 5 -Compress }
2081
2282
  `;
2082
2283
  }
2284
+ function buildFocusWindowPsScript(hwnd, checkPoint) {
2285
+ const hasPoint = Boolean(checkPoint && Number.isFinite(checkPoint.x) && Number.isFinite(checkPoint.y));
2286
+ const checkX = hasPoint ? Math.round(checkPoint.x) : 0;
2287
+ const checkY = hasPoint ? Math.round(checkPoint.y) : 0;
2288
+ return `
2289
+ $h = [IntPtr]::new([Convert]::ToInt64("${hwnd}", 16))
2290
+ [void][Luaward.Win32Desktop]::ForceForegroundWindow($h)
2291
+ Start-Sleep -Milliseconds 40
2292
+ $fg = [Luaward.Win32Desktop]::GetForegroundWindow()
2293
+ $isFg = ($fg -eq $h)
2294
+ $isTop = ${hasPoint ? `[Luaward.Win32Desktop]::IsWindowTopAtPoint($h, ${checkX}, ${checkY})` : "$isFg"}
2295
+ $fgProc = (Get-ForegroundProcessName)
2296
+ @{ ok = ($isFg -or $isTop); isForeground = $isFg; isTopAtPoint = $isTop; fgProcess = $fgProc } | ConvertTo-Json -Compress
2297
+ `;
2298
+ }
2083
2299
  function buildScreenshotPsScript(opts) {
2084
2300
  const hasHwnd = Boolean(opts.hwnd?.startsWith("0x"));
2085
2301
  return `
@@ -2226,7 +2442,7 @@ function matchesWindowTarget(w, filter) {
2226
2442
  }
2227
2443
 
2228
2444
  // src/index.ts
2229
- var MCP_BRIDGE_VERSION = "0.2.4";
2445
+ var MCP_BRIDGE_VERSION = "0.2.6";
2230
2446
  var DEFAULT_MCP_URL = "https://luaward.com/mcp";
2231
2447
  var TOKEN_CREATE_URL = "https://dash.luaward.com/dashboard/ai";
2232
2448
  var TOKEN_SHAPE = /^lwm_[0-9a-f]{48}$/;
@@ -2324,6 +2540,145 @@ function extractProtocolVersion(parsed) {
2324
2540
  return void 0;
2325
2541
  }
2326
2542
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2543
+ var CLOUD_RESULT_PAGE_MAX_CHUNKS = 25;
2544
+ var CLOUD_RESULT_PAGE_LIMIT = 1e5;
2545
+ function stripExecPageEnvelope(rawText) {
2546
+ let body = rawText.replace(/^\[Auto-injected[^\n]*\]\r?\n/, "");
2547
+ body = body.replace(/^answer from the game \(untrusted\):\r?\n/, "");
2548
+ const consoleDoubleIdx = body.indexOf("\n\nconsole (from the game");
2549
+ if (consoleDoubleIdx !== -1) {
2550
+ body = body.slice(0, consoleDoubleIdx);
2551
+ } else {
2552
+ const consoleSingleIdx = body.indexOf("\nconsole (from the game");
2553
+ if (consoleSingleIdx !== -1) {
2554
+ body = body.slice(0, consoleSingleIdx);
2555
+ }
2556
+ }
2557
+ let agentTruncated = false;
2558
+ const cutMarkerMatch = /\r?\n\(the answer was cut to fit\)$/.exec(body);
2559
+ if (cutMarkerMatch) {
2560
+ agentTruncated = true;
2561
+ body = body.slice(0, cutMarkerMatch.index);
2562
+ }
2563
+ const continueMatch = /\r?\n\.\.\. \[(\d+)\.\.(\d+) of (\d+) chars; (\d+) more characters(?:; page with get_result\(cmd="([0-9a-f]{32})", offset=(\d+)\))?\]$/.exec(
2564
+ body
2565
+ );
2566
+ if (continueMatch) {
2567
+ body = body.slice(0, continueMatch.index);
2568
+ const offset = Number(continueMatch[1]);
2569
+ const end = Number(continueMatch[2]);
2570
+ const total = Number(continueMatch[3]);
2571
+ const remaining = Number(continueMatch[4]);
2572
+ const cmdId = continueMatch[5];
2573
+ const nextOffset = continueMatch[6] !== void 0 ? Number(continueMatch[6]) : end;
2574
+ return {
2575
+ body,
2576
+ hasMore: true,
2577
+ cmdId,
2578
+ offset,
2579
+ end,
2580
+ total,
2581
+ remaining,
2582
+ nextOffset,
2583
+ agentTruncated
2584
+ };
2585
+ }
2586
+ const endMatch = /\r?\n\.\.\. \[end of (\d+) chars \((\d+)\.\.(\d+)\)\]$/.exec(body);
2587
+ if (endMatch) {
2588
+ body = body.slice(0, endMatch.index);
2589
+ return {
2590
+ body,
2591
+ hasMore: false,
2592
+ total: Number(endMatch[1]),
2593
+ offset: Number(endMatch[2]),
2594
+ end: Number(endMatch[3]),
2595
+ agentTruncated
2596
+ };
2597
+ }
2598
+ return {
2599
+ body,
2600
+ hasMore: false,
2601
+ agentTruncated
2602
+ };
2603
+ }
2604
+ function extractJsonPayloadFromExec(rawText) {
2605
+ const cleaned = stripExecPageEnvelope(rawText).body.trim();
2606
+ if (!cleaned) return null;
2607
+ const candidates = [cleaned];
2608
+ if (cleaned.startsWith('"') && cleaned.endsWith('"')) {
2609
+ try {
2610
+ const unquoted = JSON.parse(cleaned);
2611
+ if (typeof unquoted === "string") candidates.unshift(unquoted.trim());
2612
+ } catch {
2613
+ }
2614
+ }
2615
+ const firstArr = cleaned.indexOf("[");
2616
+ const firstObj = cleaned.indexOf("{");
2617
+ let firstIdx = -1;
2618
+ let expectedClose = "";
2619
+ if (firstArr >= 0 && (firstObj < 0 || firstArr < firstObj)) {
2620
+ firstIdx = firstArr;
2621
+ expectedClose = "]";
2622
+ } else if (firstObj >= 0) {
2623
+ firstIdx = firstObj;
2624
+ expectedClose = "}";
2625
+ }
2626
+ if (firstIdx >= 0) {
2627
+ const lastIdx = cleaned.lastIndexOf(expectedClose);
2628
+ if (lastIdx > firstIdx) {
2629
+ candidates.push(cleaned.slice(firstIdx, lastIdx + 1));
2630
+ }
2631
+ }
2632
+ for (const c of candidates) {
2633
+ try {
2634
+ return JSON.parse(c);
2635
+ } catch {
2636
+ }
2637
+ }
2638
+ return null;
2639
+ }
2640
+ var KNOWN_STUDIO_SERVICES = /* @__PURE__ */ new Set([
2641
+ "ServerStorage",
2642
+ "ReplicatedStorage",
2643
+ "ServerScriptService",
2644
+ "StarterPlayer",
2645
+ "StarterGui",
2646
+ "StarterPack",
2647
+ "Workspace",
2648
+ "Lighting",
2649
+ "ReplicatedFirst"
2650
+ ]);
2651
+ function resolveStudioContainerPath(rawInput, defaultService = "ServerStorage", defaultFolder = "LuawardLiveScripts") {
2652
+ const raw = (rawInput ?? "").trim().replace(/^game\./, "");
2653
+ if (!raw) {
2654
+ return {
2655
+ service: defaultService,
2656
+ segments: [defaultFolder],
2657
+ displayPath: `${defaultService}.${defaultFolder}`
2658
+ };
2659
+ }
2660
+ const segs = raw.split(".").map((s) => s.trim()).filter(Boolean);
2661
+ if (segs.length === 0) {
2662
+ return {
2663
+ service: defaultService,
2664
+ segments: [defaultFolder],
2665
+ displayPath: `${defaultService}.${defaultFolder}`
2666
+ };
2667
+ }
2668
+ if (KNOWN_STUDIO_SERVICES.has(segs[0])) {
2669
+ const subSegs = segs.length > 1 ? segs.slice(1) : [defaultFolder];
2670
+ return {
2671
+ service: segs[0],
2672
+ segments: subSegs,
2673
+ displayPath: `${segs[0]}.${subSegs.join(".")}`
2674
+ };
2675
+ }
2676
+ return {
2677
+ service: defaultService,
2678
+ segments: segs,
2679
+ displayPath: `${defaultService}.${segs.join(".")}`
2680
+ };
2681
+ }
2327
2682
  var LOCAL_HYBRID_TOOLS = [
2328
2683
  {
2329
2684
  name: "editor_tabs",
@@ -2742,7 +3097,12 @@ var LOCAL_HYBRID_TOOLS = [
2742
3097
  properties: {
2743
3098
  root: {
2744
3099
  type: "string",
2745
- description: "Root service/path to mirror (default 'ReplicatedStorage')"
3100
+ description: "Root service or dotted path to mirror (e.g. 'ReplicatedStorage' or 'ReplicatedStorage.Remotes')"
3101
+ },
3102
+ roots: {
3103
+ type: "array",
3104
+ items: { type: "string" },
3105
+ description: "Optional list of root services to mirror when root is omitted (default ['ReplicatedStorage', 'Workspace'])"
2746
3106
  },
2747
3107
  filter: {
2748
3108
  type: "string",
@@ -2751,7 +3111,7 @@ var LOCAL_HYBRID_TOOLS = [
2751
3111
  kind: {
2752
3112
  type: "string",
2753
3113
  enum: ["network", "bindable", "all"],
2754
- description: "Remote kind filter (default 'all')"
3114
+ description: "Remote kind filter (default 'network' - prioritizes RemoteEvent/RemoteFunction/UnreliableRemoteEvent)"
2755
3115
  },
2756
3116
  max: {
2757
3117
  type: "integer",
@@ -2759,6 +3119,21 @@ var LOCAL_HYBRID_TOOLS = [
2759
3119
  maximum: 500,
2760
3120
  description: "Maximum remotes to mirror (default 200)"
2761
3121
  },
3122
+ max_depth: {
3123
+ type: "integer",
3124
+ minimum: 1,
3125
+ maximum: 12,
3126
+ description: "Maximum hierarchy depth (default 6)"
3127
+ },
3128
+ clear_existing: {
3129
+ type: "boolean",
3130
+ description: "Recreate existing remotes of the same class in Studio (default false)"
3131
+ },
3132
+ datamodel_type: {
3133
+ type: "string",
3134
+ enum: ["Edit", "Client", "Server"],
3135
+ description: "Roblox Studio DataModel context (default 'Edit'; use 'Client' or 'Server' during playtest)"
3136
+ },
2762
3137
  studio_id: {
2763
3138
  type: "string",
2764
3139
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
@@ -2789,26 +3164,49 @@ var LOCAL_HYBRID_TOOLS = [
2789
3164
  type: "string",
2790
3165
  description: "Live GUI root path or #n handle to mirror (default 'Players.LocalPlayer.PlayerGui')"
2791
3166
  },
3167
+ target_path: {
3168
+ type: "string",
3169
+ description: "Alias for target (live GUI path or #n handle to mirror)"
3170
+ },
2792
3171
  studio_root: {
2793
3172
  type: "string",
2794
- description: "Destination container in Roblox Studio (default 'StarterGui')"
3173
+ description: "Destination container name in Roblox Studio StarterGui (default 'LuawardMirroredGui')"
3174
+ },
3175
+ container_name: {
3176
+ type: "string",
3177
+ description: "Alias for studio_root container folder name inside StarterGui (default 'LuawardMirroredGui')"
2795
3178
  },
2796
3179
  depth: {
2797
3180
  type: "integer",
2798
3181
  minimum: 1,
2799
3182
  maximum: 12,
2800
- description: "Maximum hierarchy depth (default 6)"
3183
+ description: "Maximum hierarchy depth (default 10)"
2801
3184
  },
2802
3185
  max_instances: {
2803
3186
  type: "integer",
2804
3187
  minimum: 1,
2805
- maximum: 600,
3188
+ maximum: 1e3,
2806
3189
  description: "Maximum GUI instances to mirror (default 250)"
2807
3190
  },
3191
+ max_nodes: {
3192
+ type: "integer",
3193
+ minimum: 1,
3194
+ maximum: 1e3,
3195
+ description: "Alias for max_instances (default 250)"
3196
+ },
2808
3197
  only_visible: {
2809
3198
  type: "boolean",
2810
3199
  description: "Only mirror visible GUI elements (default false)"
2811
3200
  },
3201
+ include_core_gui: {
3202
+ type: "boolean",
3203
+ description: "Include non-RobloxGui ScreenGuis from CoreGui (default false)"
3204
+ },
3205
+ datamodel_type: {
3206
+ type: "string",
3207
+ enum: ["Edit", "Client", "Server"],
3208
+ description: "Roblox Studio DataModel context (default 'Edit')"
3209
+ },
2812
3210
  studio_id: {
2813
3211
  type: "string",
2814
3212
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
@@ -2831,18 +3229,34 @@ var LOCAL_HYBRID_TOOLS = [
2831
3229
  {
2832
3230
  name: "studio_diff",
2833
3231
  title: "Diff scripts, remotes, or GUI between Roblox Studio and live game",
2834
- description: "Compare scripts, remotes, or GUI hierarchy between Roblox Studio (%LOCALAPPDATA%\\Roblox\\mcp.bat) and the live connected Roblox game, reporting items only in live, only in Studio, modified items, and line diffs.",
3232
+ description: "Compare scripts, remotes, or GUI hierarchy between Roblox Studio (%LOCALAPPDATA%\\Roblox\\mcp.bat) and the live connected Roblox game, reporting items only in live, only in Studio, and class mismatches.",
2835
3233
  inputSchema: {
2836
3234
  type: "object",
2837
3235
  properties: {
2838
3236
  scope: {
2839
3237
  type: "string",
2840
3238
  enum: ["scripts", "remotes", "gui", "all"],
2841
- description: "What to compare (default 'scripts')"
3239
+ description: "What to compare (default 'all')"
2842
3240
  },
2843
3241
  target: {
2844
3242
  type: "string",
2845
- description: "Optional root or specific script path to compare (default 'ReplicatedStorage')"
3243
+ description: "Optional root service to compare (e.g. 'ReplicatedStorage')"
3244
+ },
3245
+ roots: {
3246
+ type: "array",
3247
+ items: { type: "string" },
3248
+ description: "Optional list of root services to compare (default ['ReplicatedStorage', 'StarterGui', 'Workspace'])"
3249
+ },
3250
+ max_depth: {
3251
+ type: "integer",
3252
+ minimum: 1,
3253
+ maximum: 10,
3254
+ description: "Maximum hierarchy depth (default 5)"
3255
+ },
3256
+ datamodel_type: {
3257
+ type: "string",
3258
+ enum: ["Edit", "Client", "Server"],
3259
+ description: "Roblox Studio DataModel context (default 'Edit')"
2846
3260
  },
2847
3261
  studio_id: {
2848
3262
  type: "string",
@@ -2874,6 +3288,24 @@ var LOCAL_HYBRID_TOOLS = [
2874
3288
  type: "string",
2875
3289
  description: "Script path in Roblox Studio (e.g. 'StarterPlayer.StarterPlayerScripts.Main') or 'Selection' for currently selected script (default 'Selection')"
2876
3290
  },
3291
+ code: {
3292
+ type: "string",
3293
+ description: "Optional inline Luau code to run instead of reading from studio_path"
3294
+ },
3295
+ collect: {
3296
+ type: "boolean",
3297
+ description: "Use run_and_collect instead of exec (default true)"
3298
+ },
3299
+ wait_seconds: {
3300
+ type: "number",
3301
+ description: "Convenience settle time in seconds; mapped to run_and_collect settle_ms (0..15000 ms) when settle_ms is omitted"
3302
+ },
3303
+ timeout_ms: {
3304
+ type: "integer",
3305
+ minimum: 1e3,
3306
+ maximum: 85e3,
3307
+ description: "Maximum wait/runtime in milliseconds for run_and_collect (1000..85000, default 30000)"
3308
+ },
2877
3309
  clean_env: {
2878
3310
  type: "boolean",
2879
3311
  description: "Run in clean native Luau SAFEENV environment (default true)"
@@ -2892,6 +3324,11 @@ var LOCAL_HYBRID_TOOLS = [
2892
3324
  maximum: 15e3,
2893
3325
  description: "Settle window in ms after return (default 300)"
2894
3326
  },
3327
+ datamodel_type: {
3328
+ type: "string",
3329
+ enum: ["Edit", "Client", "Server"],
3330
+ description: "Roblox Studio DataModel context (default 'Edit')"
3331
+ },
2895
3332
  studio_id: {
2896
3333
  type: "string",
2897
3334
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
@@ -2914,13 +3351,25 @@ var LOCAL_HYBRID_TOOLS = [
2914
3351
  {
2915
3352
  name: "studio_publish",
2916
3353
  title: "Publish a Roblox Studio script to Luaward Cloud",
2917
- description: "Read a script's Luau source directly from Roblox Studio (%LOCALAPPDATA%\\Roblox\\mcp.bat) and deploy/protect it on Luaward Cloud via deploy_script.",
3354
+ description: "Read a script's Luau source directly from Roblox Studio (%LOCALAPPDATA%\\Roblox\\mcp.bat) and create or deploy/protect it on Luaward Cloud.",
2918
3355
  inputSchema: {
2919
3356
  type: "object",
2920
3357
  properties: {
2921
3358
  script: {
2922
3359
  type: "string",
2923
- description: "Target Luaward Cloud script name or ID"
3360
+ description: "Target Luaward Cloud script name or ID to deploy to"
3361
+ },
3362
+ script_id: {
3363
+ type: "string",
3364
+ description: "Alias for script (target Luaward Cloud script ID to deploy to)"
3365
+ },
3366
+ name: {
3367
+ type: "string",
3368
+ description: "New Luaward Cloud script name when creating a new script"
3369
+ },
3370
+ project_id: {
3371
+ type: "string",
3372
+ description: "Optional project ID from list_projects when creating a new script"
2924
3373
  },
2925
3374
  studio_path: {
2926
3375
  type: "string",
@@ -2928,19 +3377,37 @@ var LOCAL_HYBRID_TOOLS = [
2928
3377
  },
2929
3378
  publish: {
2930
3379
  type: "boolean",
2931
- description: "Promote build to live automatically (default true; false for staged draft)"
3380
+ description: "Promote build to live automatically when deploying (default true; false for staged draft)"
3381
+ },
3382
+ draft: {
3383
+ type: "boolean",
3384
+ description: "Shorthand for publish=false when deploying (stage a draft build without updating live users)"
2932
3385
  },
2933
3386
  preset: {
2934
3387
  type: "string",
2935
3388
  enum: ["fast", "balanced", "max"],
2936
3389
  description: "Optional protection preset"
2937
3390
  },
3391
+ store_source: {
3392
+ type: "boolean",
3393
+ description: "Keep encrypted raw source on Luaward after compilation (requires 2FA)"
3394
+ },
3395
+ wait: {
3396
+ type: "integer",
3397
+ minimum: 0,
3398
+ maximum: 60,
3399
+ description: "Optional seconds to wait for the compiler build to finish (0..60, default 0)"
3400
+ },
3401
+ datamodel_type: {
3402
+ type: "string",
3403
+ enum: ["Edit", "Client", "Server"],
3404
+ description: "Roblox Studio DataModel context (default 'Edit')"
3405
+ },
2938
3406
  studio_id: {
2939
3407
  type: "string",
2940
3408
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
2941
3409
  }
2942
3410
  },
2943
- required: ["script"],
2944
3411
  additionalProperties: false
2945
3412
  },
2946
3413
  annotations: {
@@ -2969,7 +3436,11 @@ var LOCAL_HYBRID_TOOLS = [
2969
3436
  },
2970
3437
  studio_root: {
2971
3438
  type: "string",
2972
- description: "Optional destination container in Studio (e.g. 'ServerStorage.LiveImports'; omit to mirror into matching services)"
3439
+ description: "Destination container path in Studio (e.g. 'ServerStorage.LiveImports', 'ReplicatedStorage.Debug.LiveScripts', or plain folder name under ServerStorage; default 'ServerStorage.LuawardLiveScripts')"
3440
+ },
3441
+ container_name: {
3442
+ type: "string",
3443
+ description: "Alias for studio_root destination path or folder name (default 'ServerStorage.LuawardLiveScripts')"
2973
3444
  },
2974
3445
  max: {
2975
3446
  type: "integer",
@@ -2977,10 +3448,25 @@ var LOCAL_HYBRID_TOOLS = [
2977
3448
  maximum: 100,
2978
3449
  description: "Maximum scripts to import in one call (default 15)"
2979
3450
  },
3451
+ limit: {
3452
+ type: "integer",
3453
+ minimum: 1,
3454
+ maximum: 100,
3455
+ description: "Alias for max (default 15)"
3456
+ },
2980
3457
  disabled: {
2981
3458
  type: "boolean",
2982
3459
  description: "Set .Disabled = true on imported LocalScripts in Studio (default true)"
2983
3460
  },
3461
+ include_decompiled: {
3462
+ type: "boolean",
3463
+ description: "Decompile script source via decompile() in the live executor (default true)"
3464
+ },
3465
+ datamodel_type: {
3466
+ type: "string",
3467
+ enum: ["Edit", "Client", "Server"],
3468
+ description: "Roblox Studio DataModel context (default 'Edit')"
3469
+ },
2984
3470
  studio_id: {
2985
3471
  type: "string",
2986
3472
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
@@ -3027,6 +3513,18 @@ var LOCAL_HYBRID_TOOLS = [
3027
3513
  focus_first: {
3028
3514
  type: "boolean",
3029
3515
  description: "Focus each window before capturing (default false)"
3516
+ },
3517
+ include_images: {
3518
+ type: "boolean",
3519
+ description: "Include both PNG images side by side in the response (default true)"
3520
+ },
3521
+ base64_a: {
3522
+ type: "string",
3523
+ description: "Optional pre-captured PNG base64 string for image A instead of capturing target_a"
3524
+ },
3525
+ base64_b: {
3526
+ type: "string",
3527
+ description: "Optional pre-captured PNG base64 string for image B instead of capturing target_b"
3030
3528
  }
3031
3529
  },
3032
3530
  additionalProperties: false
@@ -3050,6 +3548,7 @@ var HybridMcpBridge = class {
3050
3548
  autoInjectPollMs;
3051
3549
  autoInjectMaxPolls;
3052
3550
  autoInjectCooldownMs;
3551
+ verifyDelayMs;
3053
3552
  fetchFn;
3054
3553
  stderr;
3055
3554
  cachedPairCommand;
@@ -3070,6 +3569,7 @@ var HybridMcpBridge = class {
3070
3569
  this.autoInjectPollMs = options.autoInjectPollMs ?? 400;
3071
3570
  this.autoInjectMaxPolls = options.autoInjectMaxPolls ?? 15;
3072
3571
  this.autoInjectCooldownMs = options.autoInjectCooldownMs ?? 3e4;
3572
+ this.verifyDelayMs = options.verifyDelayMs ?? 120;
3073
3573
  this.potassium = options.potassiumClient ?? new PotassiumClient({
3074
3574
  url: options.potassiumUrl ?? resolved.potassiumUrl,
3075
3575
  token: options.potassiumToken !== void 0 ? options.potassiumToken : resolved.potassiumToken,
@@ -3710,7 +4210,7 @@ ${lines.join("\n")}` }]
3710
4210
  };
3711
4211
  }
3712
4212
  const lookupCode = [
3713
- `local inst, err = lw.resolve(${JSON.stringify(target)})`,
4213
+ `local inst, err = lw.resolve(${toLuauLiteral(target)})`,
3714
4214
  "if not inst then error(err or 'target not found') end",
3715
4215
  "local pos, size = inst.AbsolutePosition, inst.AbsoluteSize",
3716
4216
  "if not (pos and size) then error(lw.path(inst) .. ' has no AbsolutePosition/AbsoluteSize') end",
@@ -3763,8 +4263,8 @@ ${lines.join("\n")}` }]
3763
4263
  const vpX = vpXMatch ? Number(vpXMatch[1]) : 0;
3764
4264
  const vpY = vpYMatch ? Number(vpYMatch[1]) : 0;
3765
4265
  const resolvedPath = pathMatch?.[1] ?? target;
3766
- const focusRes = await this.windows.focusWindow("roblox");
3767
- if (!focusRes.ok || !focusRes.window) {
4266
+ let focusRes = await this.windows.focusWindow("roblox");
4267
+ if (!focusRes.window) {
3768
4268
  return {
3769
4269
  content: [
3770
4270
  { type: "text", text: `os_click could not find Roblox window: ${focusRes.err ?? "not found"}` }
@@ -3777,6 +4277,40 @@ ${lines.join("\n")}` }]
3777
4277
  const scaleY = vpY > 0 && cr.height > 0 ? cr.height / vpY : 1;
3778
4278
  const screenX = Math.round(cr.screenLeft + clientX * scaleX);
3779
4279
  const screenY = Math.round(cr.screenTop + clientY * scaleY);
4280
+ const checkWindowReady = async (res) => {
4281
+ if (!res.ok || !res.window) {
4282
+ return { ready: false, fgProcess: res.fgProcess };
4283
+ }
4284
+ if (this.windows.isWindowTopAtPoint && res.isTopAtPoint === void 0) {
4285
+ const pt = await this.windows.isWindowTopAtPoint(res.window.hwnd, screenX, screenY);
4286
+ return { ready: pt.isTop || pt.isForeground, fgProcess: pt.fgProcess ?? res.fgProcess };
4287
+ }
4288
+ if (res.isTopAtPoint !== void 0 || res.isForeground !== void 0) {
4289
+ return {
4290
+ ready: Boolean(res.isTopAtPoint || res.isForeground),
4291
+ fgProcess: res.fgProcess
4292
+ };
4293
+ }
4294
+ return { ready: Boolean(res.window.isForeground), fgProcess: res.fgProcess };
4295
+ };
4296
+ let readiness = await checkWindowReady(focusRes);
4297
+ if (!readiness.ready) {
4298
+ focusRes = await this.windows.focusWindow("roblox", { verifyPoint: { x: screenX, y: screenY } });
4299
+ readiness = await checkWindowReady(focusRes);
4300
+ }
4301
+ if (!readiness.ready) {
4302
+ const fgDesc = readiness.fgProcess ? ` (current foreground process: "${readiness.fgProcess}")` : "";
4303
+ const errDetail = focusRes.err ? ` (${focusRes.err})` : "";
4304
+ return {
4305
+ content: [
4306
+ {
4307
+ type: "text",
4308
+ text: `os_click aborted: Roblox window did not reach foreground or is occluded at screen=(${screenX}, ${screenY})${fgDesc}${errDetail}; click cancelled to avoid hitting another window.`
4309
+ }
4310
+ ],
4311
+ isError: true
4312
+ };
4313
+ }
3780
4314
  const mouseAction = args.double_click === true ? "double_click" : args.button === "right" ? "right_click" : "click";
3781
4315
  const session = typeof args.session === "string" ? args.session : void 0;
3782
4316
  const shouldVerify = args.verify === true;
@@ -3839,6 +4373,9 @@ ${verifyText}`;
3839
4373
  return out.join("\n");
3840
4374
  }
3841
4375
  async verifyMouseActionInGame(beforeSnap, session) {
4376
+ if (this.verifyDelayMs > 0) {
4377
+ await sleep(this.verifyDelayMs);
4378
+ }
3842
4379
  const lines = ["Verification:"];
3843
4380
  try {
3844
4381
  const mouseCode = [
@@ -3871,7 +4408,7 @@ ${verifyText}`;
3871
4408
  }
3872
4409
  try {
3873
4410
  const snapRes = await this.callCloudTool("gui_snapshot", {
3874
- diff_from: "latest",
4411
+ diff_from: "last",
3875
4412
  ...session ? { session } : {}
3876
4413
  });
3877
4414
  if (snapRes.ok) {
@@ -3886,63 +4423,243 @@ ${diffSummary}`);
3886
4423
  }
3887
4424
  return lines.join("\n");
3888
4425
  }
3889
- extractJsonPayloadFromExec(rawText) {
3890
- const trimmed = rawText.trim();
3891
- if (!trimmed) return null;
3892
- const candidates = [trimmed];
3893
- if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
3894
- try {
3895
- const unquoted = JSON.parse(trimmed);
3896
- if (typeof unquoted === "string") candidates.unshift(unquoted);
3897
- } catch {
4426
+ async execWithFullOutput(args) {
4427
+ let firstRes = await this.callCloudTool("exec", args);
4428
+ if (this.autoInject && firstRes.isError && firstRes.text.includes("no game is connected")) {
4429
+ const inj = await this.tryZeroTouchAutoInject();
4430
+ if (inj.injected) {
4431
+ firstRes = await this.callCloudTool("exec", args);
4432
+ } else {
4433
+ firstRes = {
4434
+ ...firstRes,
4435
+ text: `${firstRes.text}
4436
+ [Zero-Touch Auto-Inject failed: ${inj.text}]`
4437
+ };
3898
4438
  }
3899
4439
  }
3900
- const firstBracket = trimmed.search(/[\[{]/);
3901
- const lastBracket = Math.max(trimmed.lastIndexOf("]"), trimmed.lastIndexOf("}"));
3902
- if (firstBracket >= 0 && lastBracket > firstBracket) {
3903
- candidates.push(trimmed.slice(firstBracket, lastBracket + 1));
4440
+ if (!firstRes.ok) {
4441
+ return {
4442
+ ok: false,
4443
+ text: firstRes.text,
4444
+ fullBody: "",
4445
+ pages: 1,
4446
+ truncated: false,
4447
+ isError: true
4448
+ };
3904
4449
  }
3905
- for (const c of candidates) {
3906
- try {
3907
- return JSON.parse(c);
3908
- } catch {
4450
+ const firstEnv = stripExecPageEnvelope(firstRes.text);
4451
+ let assembled = firstEnv.body;
4452
+ let pages = 1;
4453
+ let truncated = firstEnv.agentTruncated;
4454
+ let hasMore = firstEnv.hasMore;
4455
+ let nextCmd = firstEnv.cmdId;
4456
+ let nextOffset = firstEnv.nextOffset;
4457
+ const session = typeof args.session === "string" && args.session.trim() ? args.session.trim() : void 0;
4458
+ while (hasMore && nextCmd && nextOffset !== void 0 && pages < CLOUD_RESULT_PAGE_MAX_CHUNKS) {
4459
+ const pageRes = await this.callCloudTool("get_result", {
4460
+ cmd: nextCmd,
4461
+ offset: nextOffset,
4462
+ limit: CLOUD_RESULT_PAGE_LIMIT,
4463
+ ...session ? { session } : {}
4464
+ });
4465
+ if (!pageRes.ok) {
4466
+ return {
4467
+ ok: false,
4468
+ text: `get_result pagination failed at offset ${nextOffset} (cmd=${nextCmd}): ${pageRes.text}`,
4469
+ fullBody: assembled,
4470
+ pages,
4471
+ truncated: true,
4472
+ isError: true
4473
+ };
4474
+ }
4475
+ const env = stripExecPageEnvelope(pageRes.text);
4476
+ if (env.agentTruncated) truncated = true;
4477
+ if (env.body.length === 0) {
4478
+ truncated = true;
4479
+ break;
4480
+ }
4481
+ assembled += env.body;
4482
+ pages += 1;
4483
+ hasMore = env.hasMore;
4484
+ const next = env.nextOffset;
4485
+ if (env.cmdId) nextCmd = env.cmdId;
4486
+ if (hasMore && (next === void 0 || next <= nextOffset)) {
4487
+ truncated = true;
4488
+ break;
3909
4489
  }
4490
+ nextOffset = next;
3910
4491
  }
3911
- return null;
4492
+ if (hasMore) {
4493
+ truncated = true;
4494
+ }
4495
+ return {
4496
+ ok: true,
4497
+ text: firstRes.text,
4498
+ fullBody: assembled,
4499
+ pages,
4500
+ truncated,
4501
+ isError: false
4502
+ };
4503
+ }
4504
+ formatJsonParseError(toolName, sourceLabel, rawBody, pages = 1, truncated = false) {
4505
+ const excerpt = rawBody.trim().slice(0, 320);
4506
+ return {
4507
+ content: [
4508
+ {
4509
+ type: "text",
4510
+ text: `${toolName} failed to parse JSON from ${sourceLabel} (pages=${pages}, truncated=${truncated}, length=${rawBody.length}): ${excerpt || "(empty response)"}`
4511
+ }
4512
+ ],
4513
+ isError: true
4514
+ };
4515
+ }
4516
+ extractJsonPayloadFromExec(rawText) {
4517
+ return extractJsonPayloadFromExec(rawText);
4518
+ }
4519
+ parseStudioDataModelType(raw) {
4520
+ if (raw === "Client" || raw === "Server" || raw === "Edit") {
4521
+ return raw;
4522
+ }
4523
+ return "Edit";
3912
4524
  }
3913
4525
  async handleStudioMirrorRemotes(args) {
3914
- const roots = Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "Workspace"];
3915
- const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(12, args.max_depth)) : 6;
4526
+ const singleRoot = typeof args.root === "string" && args.root.trim() ? args.root.trim() : "";
4527
+ const roots = singleRoot ? [singleRoot] : Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "Workspace"];
4528
+ const filter = typeof args.filter === "string" ? args.filter.trim().toLowerCase() : "";
4529
+ const kind = args.kind === "all" || args.kind === "bindable" || args.kind === "network" ? args.kind : "network";
4530
+ const max = typeof args.max === "number" ? Math.max(1, Math.min(500, Math.floor(args.max))) : 200;
4531
+ const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(12, Math.floor(args.max_depth))) : 6;
3916
4532
  const clearExisting = args.clear_existing === true;
4533
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
3917
4534
  const session = typeof args.session === "string" ? args.session : void 0;
3918
4535
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4536
+ const remoteClassesMap = kind === "network" ? { RemoteEvent: true, RemoteFunction: true, UnreliableRemoteEvent: true } : kind === "bindable" ? { BindableEvent: true, BindableFunction: true } : {
4537
+ RemoteEvent: true,
4538
+ RemoteFunction: true,
4539
+ UnreliableRemoteEvent: true,
4540
+ BindableEvent: true,
4541
+ BindableFunction: true
4542
+ };
4543
+ const netPriorityMap = {
4544
+ RemoteEvent: true,
4545
+ RemoteFunction: true,
4546
+ UnreliableRemoteEvent: true
4547
+ };
4548
+ const lowPriorityFolders = {
4549
+ assets: true,
4550
+ models: true,
4551
+ characters: true,
4552
+ animations: true,
4553
+ sounds: true,
4554
+ meshes: true,
4555
+ effects: true,
4556
+ vfx: true,
4557
+ particles: true,
4558
+ clientguis: true,
4559
+ stories: true,
4560
+ dialogues: true
4561
+ };
3919
4562
  const liveScanCode = [
3920
4563
  "local HttpService = game:GetService('HttpService')",
3921
- `local roots = ${JSON.stringify(roots)}`,
3922
- `local maxDepth = ${maxDepth}`,
3923
- "local remoteClasses = { RemoteEvent = true, RemoteFunction = true, UnreliableRemoteEvent = true, BindableEvent = true, BindableFunction = true }",
3924
- "local items = {}",
3925
- "local function scan(inst, rootName, segs, depth)",
3926
- " if depth > maxDepth then return end",
3927
- " for _, child in ipairs(inst:GetChildren()) do",
3928
- " local nextSegs = {}",
3929
- " for i = 1, #segs do nextSegs[i] = segs[i] end",
3930
- " nextSegs[#nextSegs + 1] = child.Name",
3931
- " if remoteClasses[child.ClassName] then",
3932
- " items[#items + 1] = { root = rootName, className = child.ClassName, segments = nextSegs, path = rootName .. '.' .. table.concat(nextSegs, '.') }",
3933
- " end",
3934
- " if #child:GetChildren() > 0 then",
3935
- " scan(child, rootName, nextSegs, depth + 1)",
4564
+ `local roots = ${toLuauLiteral(roots)}`,
4565
+ `local filter = ${toLuauLiteral(filter)}`,
4566
+ `local maxItems = ${toLuauLiteral(max)}`,
4567
+ `local maxDepth = ${toLuauLiteral(maxDepth)}`,
4568
+ `local kindMode = ${toLuauLiteral(kind)}`,
4569
+ `local remoteClasses = ${toLuauLiteral(remoteClassesMap)}`,
4570
+ `local netPriorityClasses = ${toLuauLiteral(netPriorityMap)}`,
4571
+ `local lowPriorityFolders = ${toLuauLiteral(lowPriorityFolders)}`,
4572
+ "local netItems = {}",
4573
+ "local otherItems = {}",
4574
+ "local function resolveRoot(rPath)",
4575
+ " local segs = {}",
4576
+ " for seg in string.gmatch(rPath, '[^%.]+') do segs[#segs + 1] = seg end",
4577
+ " if #segs == 0 then return nil, nil, nil end",
4578
+ " local startIdx = (segs[1] == 'game') and 2 or 1",
4579
+ " local rootName = segs[startIdx]",
4580
+ " if not rootName then return nil, nil, nil end",
4581
+ " local ok, cur = pcall(function() return game:GetService(rootName) end)",
4582
+ " if not ok or not cur then return nil, nil, nil end",
4583
+ " local baseSegs = {}",
4584
+ " for i = startIdx + 1, #segs do",
4585
+ " cur = cur and cur:FindFirstChild(segs[i])",
4586
+ " baseSegs[#baseSegs + 1] = segs[i]",
4587
+ " end",
4588
+ " return cur, rootName, baseSegs",
4589
+ "end",
4590
+ "local normalQ = {}",
4591
+ "local lowQ = {}",
4592
+ "local nHead, lHead = 1, 1",
4593
+ "local visited = 0",
4594
+ "local maxVisited = 6000",
4595
+ "for _, rPath in ipairs(roots) do",
4596
+ " local inst, rootName, baseSegs = resolveRoot(rPath)",
4597
+ " if inst and rootName and baseSegs then",
4598
+ " normalQ[#normalQ + 1] = { inst = inst, rootName = rootName, segs = baseSegs, depth = 1 }",
4599
+ " end",
4600
+ "end",
4601
+ "local function nextNode()",
4602
+ " if nHead <= #normalQ then",
4603
+ " local n = normalQ[nHead]",
4604
+ " normalQ[nHead] = nil",
4605
+ " nHead = nHead + 1",
4606
+ " return n",
4607
+ " end",
4608
+ " if lHead <= #lowQ then",
4609
+ " local n = lowQ[lHead]",
4610
+ " lowQ[lHead] = nil",
4611
+ " lHead = lHead + 1",
4612
+ " return n",
4613
+ " end",
4614
+ " return nil",
4615
+ "end",
4616
+ "while visited < maxVisited do",
4617
+ " if kindMode == 'network' and #netItems >= maxItems then break end",
4618
+ " if kindMode == 'bindable' and #otherItems >= maxItems then break end",
4619
+ " if kindMode == 'all' and #netItems >= maxItems then break end",
4620
+ " local node = nextNode()",
4621
+ " if not node then break end",
4622
+ " if node.depth <= maxDepth then",
4623
+ " for _, child in ipairs(node.inst:GetChildren()) do",
4624
+ " visited = visited + 1",
4625
+ " if visited > maxVisited then break end",
4626
+ " local nextSegs = {}",
4627
+ " for i = 1, #node.segs do nextSegs[i] = node.segs[i] end",
4628
+ " nextSegs[#nextSegs + 1] = child.Name",
4629
+ " local fullPath = node.rootName .. '.' .. table.concat(nextSegs, '.')",
4630
+ " if remoteClasses[child.ClassName] then",
4631
+ " if filter == '' or string.find(string.lower(fullPath), filter, 1, true) then",
4632
+ " local rec = { root = node.rootName, className = child.ClassName, segments = nextSegs, path = fullPath }",
4633
+ " if netPriorityClasses[child.ClassName] then",
4634
+ " netItems[#netItems + 1] = rec",
4635
+ " else",
4636
+ " otherItems[#otherItems + 1] = rec",
4637
+ " end",
4638
+ " end",
4639
+ " end",
4640
+ " if kindMode == 'network' and #netItems >= maxItems then break end",
4641
+ " if kindMode == 'bindable' and #otherItems >= maxItems then break end",
4642
+ " if kindMode == 'all' and #netItems >= maxItems then break end",
4643
+ " if node.depth < maxDepth and #child:GetChildren() > 0 then",
4644
+ " local isLow = child:IsA('Model') or (lowPriorityFolders[string.lower(child.Name)] == true)",
4645
+ " local q = isLow and lowQ or normalQ",
4646
+ " q[#q + 1] = { inst = child, rootName = node.rootName, segs = nextSegs, depth = node.depth + 1 }",
4647
+ " end",
3936
4648
  " end",
3937
4649
  " end",
3938
4650
  "end",
3939
- "for _, rName in ipairs(roots) do",
3940
- " local ok, svc = pcall(function() return game:GetService(rName) end)",
3941
- " if ok and svc then scan(svc, rName, {}, 1) end",
4651
+ "local items = {}",
4652
+ "for _, rec in ipairs(netItems) do",
4653
+ " if #items >= maxItems then break end",
4654
+ " items[#items + 1] = rec",
4655
+ "end",
4656
+ "for _, rec in ipairs(otherItems) do",
4657
+ " if #items >= maxItems then break end",
4658
+ " items[#items + 1] = rec",
3942
4659
  "end",
3943
4660
  "return HttpService:JSONEncode(items)"
3944
4661
  ].join("\n");
3945
- const liveRes = await this.callCloudTool("exec", {
4662
+ const liveRes = await this.execWithFullOutput({
3946
4663
  code: liveScanCode,
3947
4664
  readonly: true,
3948
4665
  ...session ? { session } : {}
@@ -3953,11 +4670,21 @@ ${diffSummary}`);
3953
4670
  isError: true
3954
4671
  };
3955
4672
  }
3956
- const items = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
4673
+ const items = this.extractJsonPayloadFromExec(
4674
+ liveRes.fullBody
4675
+ );
4676
+ if (!Array.isArray(items)) {
4677
+ return this.formatJsonParseError(
4678
+ "studio_mirror_remotes",
4679
+ "live game remotes scan",
4680
+ liveRes.fullBody,
4681
+ liveRes.pages,
4682
+ liveRes.truncated
4683
+ );
4684
+ }
3957
4685
  const studioCode = [
3958
- "local HttpService = game:GetService('HttpService')",
3959
- `local items = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(items))})`,
3960
- `local clearExisting = ${clearExisting ? "true" : "false"}`,
4686
+ `local items = ${toLuauLiteral(items)}`,
4687
+ `local clearExisting = ${toLuauLiteral(clearExisting)}`,
3961
4688
  "local created, existing = 0, 0",
3962
4689
  "for _, item in ipairs(items) do",
3963
4690
  " local ok, rootInst = pcall(function() return game:GetService(item.root) end)",
@@ -3995,7 +4722,7 @@ ${diffSummary}`);
3995
4722
  "end",
3996
4723
  "return string.format('mirrored %d remotes (created=%d, existing=%d)', #items, created, existing)"
3997
4724
  ].join("\n");
3998
- const studioRes = await this.studio.runStudioLuau(studioCode, requestedStudioId);
4725
+ const studioRes = await this.studio.runStudioLuau(studioCode, requestedStudioId, datamodelType);
3999
4726
  if (!studioRes.ok) {
4000
4727
  return {
4001
4728
  content: [
@@ -4008,14 +4735,24 @@ ${diffSummary}`);
4008
4735
  };
4009
4736
  }
4010
4737
  const samplePaths = items.slice(0, 15).map((i) => ` - [${i.className}] ${i.path}`);
4738
+ const warnings = [];
4739
+ if (items.length >= max || liveRes.truncated) {
4740
+ warnings.push(
4741
+ `- Note: output reached limit (max=${max}${liveRes.truncated ? ", truncated" : ""}); pass filter/root or raise max to mirror more.`
4742
+ );
4743
+ }
4744
+ if (liveRes.pages > 1) {
4745
+ warnings.push(`- Pagination: reassembled ${liveRes.pages} pages from Cloud exec/get_result`);
4746
+ }
4011
4747
  return {
4012
4748
  content: [
4013
4749
  {
4014
4750
  type: "text",
4015
4751
  text: [
4016
- `studio_mirror_remotes complete (studio_id=${studioRes.studioId ?? "auto"}):`,
4017
- `- Live remotes discovered: ${items.length} across ${roots.join(", ")}`,
4752
+ `studio_mirror_remotes complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4753
+ `- Live remotes discovered: ${items.length} across ${roots.join(", ")} (kind=${kind}${filter ? `, filter="${filter}"` : ""}, max=${max})`,
4018
4754
  `- Studio result: ${studioRes.text}`,
4755
+ ...warnings,
4019
4756
  ...samplePaths.length > 0 ? ["- Sample mirrored paths:", ...samplePaths] : []
4020
4757
  ].join("\n")
4021
4758
  }
@@ -4023,25 +4760,39 @@ ${diffSummary}`);
4023
4760
  };
4024
4761
  }
4025
4762
  async handleStudioMirrorGui(args) {
4026
- const targetPath = typeof args.target_path === "string" ? args.target_path.trim() : "";
4027
- const containerName = typeof args.container_name === "string" && args.container_name.trim() ? args.container_name.trim() : "LuawardMirroredGui";
4028
- const maxNodes = typeof args.max_nodes === "number" ? Math.max(10, Math.min(1e3, args.max_nodes)) : 250;
4763
+ const rawTarget = typeof args.target_path === "string" && args.target_path.trim() ? args.target_path.trim() : typeof args.target === "string" && args.target.trim() ? args.target.trim() : "";
4764
+ const targetPath = rawTarget === "Players.LocalPlayer.PlayerGui" || rawTarget === "PlayerGui" ? "" : rawTarget;
4765
+ const rawContainer = typeof args.container_name === "string" && args.container_name.trim() ? args.container_name.trim() : typeof args.studio_root === "string" && args.studio_root.trim() ? args.studio_root.trim() : "LuawardMirroredGui";
4766
+ const containerName = rawContainer === "StarterGui" ? "LuawardMirroredGui" : rawContainer.replace(/^StarterGui\./, "") || "LuawardMirroredGui";
4767
+ const maxDepth = typeof args.depth === "number" ? Math.max(1, Math.min(12, Math.floor(args.depth))) : 10;
4768
+ const rawMaxNodes = typeof args.max_nodes === "number" ? args.max_nodes : typeof args.max_instances === "number" ? args.max_instances : 250;
4769
+ const maxNodes = Math.max(1, Math.min(1e3, Math.floor(rawMaxNodes)));
4770
+ const onlyVisible = args.only_visible === true;
4029
4771
  const includeCoreGui = args.include_core_gui === true;
4772
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4030
4773
  const session = typeof args.session === "string" ? args.session : void 0;
4031
4774
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4032
4775
  const liveGuiCode = [
4033
4776
  "local HttpService = game:GetService('HttpService')",
4034
4777
  "local Players = game:GetService('Players')",
4035
- `local targetPath = ${JSON.stringify(targetPath)}`,
4036
- `local maxNodes = ${maxNodes}`,
4037
- `local includeCore = ${includeCoreGui ? "true" : "false"}`,
4778
+ `local targetPath = ${toLuauLiteral(targetPath)}`,
4779
+ `local maxNodes = ${toLuauLiteral(maxNodes)}`,
4780
+ `local maxDepth = ${toLuauLiteral(maxDepth)}`,
4781
+ `local onlyVisible = ${toLuauLiteral(onlyVisible)}`,
4782
+ `local includeCore = ${toLuauLiteral(includeCoreGui)}`,
4038
4783
  "local nodes = {}",
4039
4784
  "local count = 0",
4785
+ "local capped = false",
4040
4786
  "local function serColor(c) return c and { c.R, c.G, c.B } or nil end",
4041
4787
  "local function serUDim2(u) return u and { u.X.Scale, u.X.Offset, u.Y.Scale, u.Y.Offset } or nil end",
4042
4788
  "local function serVec2(v) return v and { v.X, v.Y } or nil end",
4043
4789
  "local function serializeTree(inst, depth)",
4044
- " if count >= maxNodes or depth > 10 then return nil end",
4790
+ " if count >= maxNodes then capped = true; return nil end",
4791
+ " if depth > maxDepth then return nil end",
4792
+ " if onlyVisible then",
4793
+ " if inst:IsA('LayerCollector') and inst.Enabled == false then return nil end",
4794
+ " if inst:IsA('GuiObject') and inst.Visible == false then return nil end",
4795
+ " end",
4045
4796
  " count = count + 1",
4046
4797
  " local node = { className = inst.ClassName, name = inst.Name, children = {} }",
4047
4798
  " pcall(function()",
@@ -4066,7 +4817,7 @@ ${diffSummary}`);
4066
4817
  " end",
4067
4818
  " end)",
4068
4819
  " for _, child in ipairs(inst:GetChildren()) do",
4069
- " if count >= maxNodes then break end",
4820
+ " if count >= maxNodes then capped = true; break end",
4070
4821
  " local cNode = serializeTree(child, depth + 1)",
4071
4822
  " if cNode then node.children[#node.children + 1] = cNode end",
4072
4823
  " end",
@@ -4074,13 +4825,16 @@ ${diffSummary}`);
4074
4825
  "end",
4075
4826
  "if targetPath ~= '' and lw and lw.resolve then",
4076
4827
  " local inst = lw.resolve(targetPath)",
4077
- " if inst then nodes[#nodes + 1] = serializeTree(inst, 1) end",
4828
+ " if inst then",
4829
+ " local n = serializeTree(inst, 1)",
4830
+ " if n then nodes[#nodes + 1] = n end",
4831
+ " end",
4078
4832
  "else",
4079
4833
  " local lp = Players.LocalPlayer",
4080
4834
  " local pgui = lp and lp:FindFirstChildOfClass('PlayerGui')",
4081
4835
  " if pgui then",
4082
4836
  " for _, child in ipairs(pgui:GetChildren()) do",
4083
- " if count >= maxNodes then break end",
4837
+ " if count >= maxNodes then capped = true; break end",
4084
4838
  " local n = serializeTree(child, 1)",
4085
4839
  " if n then nodes[#nodes + 1] = n end",
4086
4840
  " end",
@@ -4089,7 +4843,7 @@ ${diffSummary}`);
4089
4843
  " local ok, cgui = pcall(function() return game:GetService('CoreGui') end)",
4090
4844
  " if ok and cgui then",
4091
4845
  " for _, child in ipairs(cgui:GetChildren()) do",
4092
- " if count >= maxNodes then break end",
4846
+ " if count >= maxNodes then capped = true; break end",
4093
4847
  " if child.Name ~= 'RobloxGui' then",
4094
4848
  " local n = serializeTree(child, 1)",
4095
4849
  " if n then nodes[#nodes + 1] = n end",
@@ -4098,9 +4852,9 @@ ${diffSummary}`);
4098
4852
  " end",
4099
4853
  " end",
4100
4854
  "end",
4101
- "return HttpService:JSONEncode({ count = count, trees = nodes })"
4855
+ "return HttpService:JSONEncode({ count = count, capped = capped, trees = nodes })"
4102
4856
  ].join("\n");
4103
- const liveRes = await this.callCloudTool("exec", {
4857
+ const liveRes = await this.execWithFullOutput({
4104
4858
  code: liveGuiCode,
4105
4859
  readonly: true,
4106
4860
  ...session ? { session } : {}
@@ -4111,15 +4865,20 @@ ${diffSummary}`);
4111
4865
  isError: true
4112
4866
  };
4113
4867
  }
4114
- const payload = this.extractJsonPayloadFromExec(liveRes.text) ?? {
4115
- count: 0,
4116
- trees: []
4117
- };
4868
+ const payload = this.extractJsonPayloadFromExec(liveRes.fullBody);
4869
+ if (!payload || typeof payload !== "object" || !Array.isArray(payload.trees)) {
4870
+ return this.formatJsonParseError(
4871
+ "studio_mirror_gui",
4872
+ "live GUI serialization",
4873
+ liveRes.fullBody,
4874
+ liveRes.pages,
4875
+ liveRes.truncated
4876
+ );
4877
+ }
4118
4878
  const studioBuildCode = [
4119
- "local HttpService = game:GetService('HttpService')",
4120
4879
  "local StarterGui = game:GetService('StarterGui')",
4121
- `local containerName = ${JSON.stringify(containerName)}`,
4122
- `local payload = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(payload))})`,
4880
+ `local containerName = ${toLuauLiteral(containerName)}`,
4881
+ `local payload = ${toLuauLiteral(payload)}`,
4123
4882
  "local folder = StarterGui:FindFirstChild(containerName)",
4124
4883
  "if folder then folder:Destroy() end",
4125
4884
  "folder = Instance.new('Folder')",
@@ -4162,7 +4921,7 @@ ${diffSummary}`);
4162
4921
  "for _, tree in ipairs(payload.trees or {}) do buildNode(tree, folder) end",
4163
4922
  "return string.format('mirrored %d GUI nodes into StarterGui.%s', created, containerName)"
4164
4923
  ].join("\n");
4165
- const studioRes = await this.studio.runStudioLuau(studioBuildCode, requestedStudioId);
4924
+ const studioRes = await this.studio.runStudioLuau(studioBuildCode, requestedStudioId, datamodelType);
4166
4925
  if (!studioRes.ok) {
4167
4926
  return {
4168
4927
  content: [
@@ -4174,32 +4933,44 @@ ${diffSummary}`);
4174
4933
  isError: true
4175
4934
  };
4176
4935
  }
4936
+ const notes = [];
4937
+ if (payload.capped || payload.count >= maxNodes || liveRes.truncated) {
4938
+ notes.push(
4939
+ `- Note: capture reached limit (max_nodes=${maxNodes}${liveRes.truncated ? ", truncated" : ""}); pass target/only_visible=true or raise max_nodes for deeper trees.`
4940
+ );
4941
+ }
4942
+ if (liveRes.pages > 1) {
4943
+ notes.push(`- Pagination: reassembled ${liveRes.pages} pages from Cloud exec/get_result`);
4944
+ }
4177
4945
  return {
4178
4946
  content: [
4179
4947
  {
4180
4948
  type: "text",
4181
4949
  text: [
4182
- `studio_mirror_gui complete (studio_id=${studioRes.studioId ?? "auto"}):`,
4950
+ `studio_mirror_gui complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4183
4951
  `- Live GUI nodes serialized: ${payload.count} (${payload.trees.length} root trees)`,
4184
4952
  `- Studio container: StarterGui.${containerName}`,
4185
- `- Studio result: ${studioRes.text}`
4953
+ `- Studio result: ${studioRes.text}`,
4954
+ ...notes
4186
4955
  ].join("\n")
4187
4956
  }
4188
4957
  ]
4189
4958
  };
4190
4959
  }
4191
4960
  async handleStudioDiff(args) {
4192
- const roots = Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "StarterGui", "Workspace"];
4961
+ const singleTarget = typeof args.target === "string" && args.target.trim() ? args.target.trim() : "";
4962
+ const roots = singleTarget ? [singleTarget] : Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "StarterGui", "Workspace"];
4193
4963
  const scope = typeof args.scope === "string" ? args.scope : "all";
4194
4964
  const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(10, args.max_depth)) : 5;
4965
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4195
4966
  const session = typeof args.session === "string" ? args.session : void 0;
4196
4967
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4197
4968
  const buildDiffScanCode = (isLive) => [
4198
4969
  "local HttpService = game:GetService('HttpService')",
4199
- `local roots = ${JSON.stringify(roots)}`,
4200
- `local scope = ${JSON.stringify(scope)}`,
4201
- `local maxDepth = ${maxDepth}`,
4202
- `local isLive = ${isLive ? "true" : "false"}`,
4970
+ `local roots = ${toLuauLiteral(roots)}`,
4971
+ `local scope = ${toLuauLiteral(scope)}`,
4972
+ `local maxDepth = ${toLuauLiteral(maxDepth)}`,
4973
+ `local isLive = ${toLuauLiteral(isLive)}`,
4203
4974
  "local entries = {}",
4204
4975
  "local count = 0",
4205
4976
  "local remoteClasses = { RemoteEvent = true, RemoteFunction = true, UnreliableRemoteEvent = true, BindableEvent = true, BindableFunction = true }",
@@ -4213,6 +4984,7 @@ ${diffSummary}`);
4213
4984
  "local function scan(inst, prefix, depth)",
4214
4985
  " if depth > maxDepth or count >= 1500 then return end",
4215
4986
  " for _, child in ipairs(inst:GetChildren()) do",
4987
+ " if count >= 1500 then break end",
4216
4988
  " local p = prefix .. '.' .. child.Name",
4217
4989
  " if matchesScope(child) then",
4218
4990
  " count = count + 1",
@@ -4234,12 +5006,12 @@ ${diffSummary}`);
4234
5006
  "return HttpService:JSONEncode(entries)"
4235
5007
  ].join("\n");
4236
5008
  const [liveRes, studioRes] = await Promise.all([
4237
- this.callCloudTool("exec", {
5009
+ this.execWithFullOutput({
4238
5010
  code: buildDiffScanCode(true),
4239
5011
  readonly: true,
4240
5012
  ...session ? { session } : {}
4241
5013
  }),
4242
- this.studio.runStudioLuau(buildDiffScanCode(false), requestedStudioId)
5014
+ this.studio.runStudioLuau(buildDiffScanCode(false), requestedStudioId, datamodelType)
4243
5015
  ]);
4244
5016
  if (!liveRes.ok) {
4245
5017
  return {
@@ -4253,8 +5025,20 @@ ${diffSummary}`);
4253
5025
  isError: true
4254
5026
  };
4255
5027
  }
4256
- const liveEntries = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
4257
- const studioEntries = this.extractJsonPayloadFromExec(studioRes.text) ?? [];
5028
+ const liveEntries = this.extractJsonPayloadFromExec(liveRes.fullBody);
5029
+ if (!Array.isArray(liveEntries)) {
5030
+ return this.formatJsonParseError(
5031
+ "studio_diff",
5032
+ "live game scan",
5033
+ liveRes.fullBody,
5034
+ liveRes.pages,
5035
+ liveRes.truncated
5036
+ );
5037
+ }
5038
+ const studioEntries = this.extractJsonPayloadFromExec(studioRes.text);
5039
+ if (!Array.isArray(studioEntries)) {
5040
+ return this.formatJsonParseError("studio_diff", "Roblox Studio scan", studioRes.text, 1, false);
5041
+ }
4258
5042
  const liveMap = /* @__PURE__ */ new Map();
4259
5043
  for (const e of liveEntries) liveMap.set(e.path, e.className);
4260
5044
  const studioMap = /* @__PURE__ */ new Map();
@@ -4279,7 +5063,8 @@ ${diffSummary}`);
4279
5063
  }
4280
5064
  }
4281
5065
  const lines = [
4282
- `studio_diff report (scope=${scope}, roots=${roots.join(", ")}, studio_id=${studioRes.studioId ?? "auto"}):`,
5066
+ `studio_diff report (scope=${scope}, roots=${roots.join(", ")}, studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
5067
+ `- Scanned counts: live=${liveEntries.length}, studio=${studioEntries.length}${liveRes.pages > 1 ? ` (live pages=${liveRes.pages})` : ""}`,
4283
5068
  `- Matched instances: ${matchedCount}`,
4284
5069
  `- Only in Live Game: ${onlyInLive.length}`,
4285
5070
  ...onlyInLive.slice(0, 20).map((x) => ` + [Live] ${x}`),
@@ -4290,6 +5075,11 @@ ${diffSummary}`);
4290
5075
  `- Class mismatches: ${classMismatches.length}`,
4291
5076
  ...classMismatches.slice(0, 10).map((x) => ` ! ${x}`)
4292
5077
  ];
5078
+ if (liveEntries.length >= 1500 || studioEntries.length >= 1500 || liveRes.truncated) {
5079
+ lines.push(
5080
+ "- Note: scan hit 1500-entry limit or truncation; pass target/roots or narrow scope/max_depth for complete coverage."
5081
+ );
5082
+ }
4293
5083
  return {
4294
5084
  content: [{ type: "text", text: lines.join("\n") }]
4295
5085
  };
@@ -4297,15 +5087,22 @@ ${diffSummary}`);
4297
5087
  buildStudioReadScriptSourceCode(studioPath) {
4298
5088
  return [
4299
5089
  "local HttpService = game:GetService('HttpService')",
4300
- `local pathStr = ${JSON.stringify(studioPath)}`,
4301
- "local segs = {}",
4302
- "for seg in string.gmatch(pathStr, '[^%.]+') do segs[#segs + 1] = seg end",
4303
- "if #segs == 0 then error('Empty studio_path') end",
4304
- "local startIdx = 1",
4305
- "if segs[1] == 'game' then startIdx = 2 end",
4306
- "local cur = game:GetService(segs[startIdx])",
4307
- "for i = startIdx + 1, #segs do",
4308
- " cur = cur and cur:FindFirstChild(segs[i])",
5090
+ `local pathStr = ${toLuauLiteral(studioPath)}`,
5091
+ "local cur = nil",
5092
+ "if pathStr == '' or pathStr == 'Selection' then",
5093
+ " local sel = game:GetService('Selection'):Get()",
5094
+ " cur = sel and sel[1] or nil",
5095
+ " if not cur then error('No script is currently selected in Roblox Studio Selection') end",
5096
+ "else",
5097
+ " local segs = {}",
5098
+ " for seg in string.gmatch(pathStr, '[^%.]+') do segs[#segs + 1] = seg end",
5099
+ " if #segs == 0 then error('Empty studio_path') end",
5100
+ " local startIdx = 1",
5101
+ " if segs[1] == 'game' then startIdx = 2 end",
5102
+ " cur = game:GetService(segs[startIdx])",
5103
+ " for i = startIdx + 1, #segs do",
5104
+ " cur = cur and cur:FindFirstChild(segs[i])",
5105
+ " end",
4309
5106
  "end",
4310
5107
  "if not cur then error('Studio instance not found: ' .. pathStr) end",
4311
5108
  "local ok, src = pcall(function() return cur.Source end)",
@@ -4314,24 +5111,20 @@ ${diffSummary}`);
4314
5111
  ].join("\n");
4315
5112
  }
4316
5113
  async handleStudioToLive(args) {
4317
- const studioPath = typeof args.studio_path === "string" ? args.studio_path.trim() : "";
4318
5114
  const directCode = typeof args.code === "string" ? args.code : "";
5115
+ const studioPath = typeof args.studio_path === "string" && args.studio_path.trim() ? args.studio_path.trim() : directCode.trim() ? "" : "Selection";
5116
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4319
5117
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4320
5118
  const session = typeof args.session === "string" ? args.session : void 0;
4321
5119
  const collect = args.collect !== false;
4322
- if (!studioPath && !directCode.trim()) {
4323
- return {
4324
- content: [{ type: "text", text: "studio_to_live requires either studio_path or code" }],
4325
- isError: true
4326
- };
4327
- }
4328
5120
  let codeToRun = directCode;
4329
5121
  let sourceLabel = "inline Studio snippet";
4330
5122
  let resolvedStudioId = requestedStudioId;
4331
5123
  if (studioPath) {
4332
5124
  const studioRes = await this.studio.runStudioLuau(
4333
5125
  this.buildStudioReadScriptSourceCode(studioPath),
4334
- requestedStudioId
5126
+ requestedStudioId,
5127
+ datamodelType
4335
5128
  );
4336
5129
  if (!studioRes.ok) {
4337
5130
  return {
@@ -4358,14 +5151,19 @@ ${diffSummary}`);
4358
5151
  };
4359
5152
  }
4360
5153
  codeToRun = parsed.source;
4361
- sourceLabel = `${parsed.path} [${parsed.className}] (${codeToRun.length} bytes, studio_id=${resolvedStudioId ?? "auto"})`;
5154
+ sourceLabel = `${parsed.path} [${parsed.className}] (${codeToRun.length} bytes, studio_id=${resolvedStudioId ?? "auto"}, datamodel_type=${datamodelType})`;
4362
5155
  }
4363
5156
  const cloudTool = collect ? "run_and_collect" : "exec";
5157
+ const resolvedSettleMs = typeof args.settle_ms === "number" && Number.isFinite(args.settle_ms) ? Math.max(0, Math.min(15e3, Math.round(args.settle_ms))) : typeof args.wait_seconds === "number" && Number.isFinite(args.wait_seconds) ? Math.max(0, Math.min(15e3, Math.round(args.wait_seconds * 1e3))) : void 0;
5158
+ const resolvedTimeoutMs = typeof args.timeout_ms === "number" && Number.isFinite(args.timeout_ms) ? Math.max(1e3, Math.min(85e3, Math.round(args.timeout_ms))) : void 0;
4364
5159
  const cloudArgs = {
4365
5160
  code: codeToRun,
4366
5161
  ...collect ? {
4367
- wait_seconds: typeof args.wait_seconds === "number" ? args.wait_seconds : 1.5,
4368
- clean_env: typeof args.clean_env === "boolean" ? args.clean_env : true
5162
+ clean_env: typeof args.clean_env === "boolean" ? args.clean_env : true,
5163
+ ...resolvedTimeoutMs !== void 0 ? { timeout_ms: resolvedTimeoutMs } : {},
5164
+ ...resolvedSettleMs !== void 0 ? { settle_ms: resolvedSettleMs } : {},
5165
+ ...typeof args.track_resources === "boolean" ? { track_resources: args.track_resources } : {},
5166
+ ...typeof args.auto_cleanup === "boolean" ? { auto_cleanup: args.auto_cleanup } : {}
4369
5167
  } : {},
4370
5168
  ...session ? { session } : {}
4371
5169
  };
@@ -4382,17 +5180,13 @@ ${liveRes.text}`
4382
5180
  };
4383
5181
  }
4384
5182
  async handleStudioPublish(args) {
4385
- const studioPath = typeof args.studio_path === "string" ? args.studio_path.trim() : "";
4386
- if (!studioPath) {
4387
- return {
4388
- content: [{ type: "text", text: "studio_publish requires studio_path" }],
4389
- isError: true
4390
- };
4391
- }
5183
+ const studioPath = typeof args.studio_path === "string" && args.studio_path.trim() ? args.studio_path.trim() : "Selection";
5184
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4392
5185
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4393
5186
  const studioRes = await this.studio.runStudioLuau(
4394
5187
  this.buildStudioReadScriptSourceCode(studioPath),
4395
- requestedStudioId
5188
+ requestedStudioId,
5189
+ datamodelType
4396
5190
  );
4397
5191
  if (!studioRes.ok) {
4398
5192
  return {
@@ -4417,18 +5211,23 @@ ${liveRes.text}`
4417
5211
  isError: true
4418
5212
  };
4419
5213
  }
4420
- const scriptId = typeof args.script_id === "string" ? args.script_id.trim() : "";
4421
- if (scriptId) {
4422
- const deployRes = await this.callCloudTool("deploy_script", {
4423
- script_id: scriptId,
5214
+ const scriptTarget = typeof args.script_id === "string" && args.script_id.trim() ? args.script_id.trim() : typeof args.script === "string" && args.script.trim() ? args.script.trim() : "";
5215
+ if (scriptTarget) {
5216
+ const deployArgs = {
5217
+ script: scriptTarget,
4424
5218
  source: parsed.source,
4425
- ...typeof args.note === "string" ? { note: args.note } : {}
4426
- });
5219
+ ...typeof args.preset === "string" ? { preset: args.preset } : {},
5220
+ ...typeof args.publish === "boolean" ? { publish: args.publish } : {},
5221
+ ...typeof args.draft === "boolean" ? { draft: args.draft } : {},
5222
+ ...typeof args.store_source === "boolean" ? { store_source: args.store_source } : {},
5223
+ ...typeof args.wait === "number" && Number.isFinite(args.wait) ? { wait: Math.max(0, Math.min(60, Math.floor(args.wait))) } : {}
5224
+ };
5225
+ const deployRes = await this.callCloudTool("deploy_script", deployArgs);
4427
5226
  return {
4428
5227
  content: [
4429
5228
  {
4430
5229
  type: "text",
4431
- text: `studio_publish deployed ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}) to Luaward script ${scriptId}:
5230
+ text: `studio_publish deployed ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}) to Luaward script ${scriptTarget}:
4432
5231
  ${deployRes.text}`
4433
5232
  }
4434
5233
  ],
@@ -4436,16 +5235,20 @@ ${deployRes.text}`
4436
5235
  };
4437
5236
  }
4438
5237
  const scriptName = typeof args.name === "string" && args.name.trim() ? args.name.trim() : parsed.name || "StudioScript";
4439
- const createRes = await this.callCloudTool("create_script", {
5238
+ const createArgs = {
4440
5239
  name: scriptName,
4441
5240
  source: parsed.source,
4442
- ...typeof args.description === "string" ? { description: args.description } : {}
4443
- });
5241
+ ...typeof args.project_id === "string" && args.project_id.trim() ? { project_id: args.project_id.trim() } : {},
5242
+ ...typeof args.preset === "string" ? { preset: args.preset } : {},
5243
+ ...typeof args.store_source === "boolean" ? { store_source: args.store_source } : {},
5244
+ ...typeof args.wait === "number" && Number.isFinite(args.wait) ? { wait: Math.max(0, Math.min(60, Math.floor(args.wait))) } : {}
5245
+ };
5246
+ const createRes = await this.callCloudTool("create_script", createArgs);
4444
5247
  return {
4445
5248
  content: [
4446
5249
  {
4447
5250
  type: "text",
4448
- text: `studio_publish created Luaward script "${scriptName}" from ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}):
5251
+ text: `studio_publish created Luaward script "${scriptName}" from ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):
4449
5252
  ${createRes.text}`
4450
5253
  }
4451
5254
  ],
@@ -4453,40 +5256,59 @@ ${createRes.text}`
4453
5256
  };
4454
5257
  }
4455
5258
  async handleLiveScriptsToStudio(args) {
5259
+ const targets = Array.isArray(args.targets) && args.targets.length > 0 ? args.targets.map(String) : [];
4456
5260
  const filter = typeof args.filter === "string" ? args.filter.trim() : "";
4457
- const containerName = typeof args.container_name === "string" && args.container_name.trim() ? args.container_name.trim() : "LuawardLiveScripts";
4458
- const limit = typeof args.limit === "number" ? Math.max(1, Math.min(50, args.limit)) : 15;
5261
+ const rawContainer = typeof args.studio_root === "string" && args.studio_root.trim() ? args.studio_root.trim() : typeof args.container_name === "string" && args.container_name.trim() ? args.container_name.trim() : "LuawardLiveScripts";
5262
+ const container = resolveStudioContainerPath(rawContainer, "ServerStorage", "LuawardLiveScripts");
5263
+ const rawLimit = typeof args.max === "number" ? args.max : typeof args.limit === "number" ? args.limit : 15;
5264
+ const limit = Math.max(1, Math.min(100, Math.floor(rawLimit)));
5265
+ const disabled = args.disabled !== false;
4459
5266
  const includeDecompiled = args.include_decompiled !== false;
5267
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4460
5268
  const session = typeof args.session === "string" ? args.session : void 0;
4461
5269
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4462
5270
  const liveCollectCode = [
4463
5271
  "local HttpService = game:GetService('HttpService')",
4464
- `local filter = string.lower(${JSON.stringify(filter)})`,
4465
- `local limit = ${limit}`,
4466
- `local includeDecompiled = ${includeDecompiled ? "true" : "false"}`,
5272
+ `local targets = ${toLuauLiteral(targets)}`,
5273
+ `local filter = string.lower(${toLuauLiteral(filter)})`,
5274
+ `local limit = ${toLuauLiteral(limit)}`,
5275
+ `local includeDecompiled = ${toLuauLiteral(includeDecompiled)}`,
4467
5276
  "local roots = { game:GetService('ReplicatedStorage'), game:GetService('StarterPlayer'), game:GetService('Workspace'), game:GetService('Players').LocalPlayer }",
4468
5277
  "local results = {}",
4469
5278
  "local seen = {}",
5279
+ "local totalBytes = 0",
5280
+ "local maxTotalBytes = 600000",
4470
5281
  "local decompFn = (type(decompile) == 'function' and decompile) or (type(getscriptbytecode) == 'function' and function(s) local ok, b = pcall(getscriptbytecode, s); return ok and b and ('-- bytecode (' .. tostring(#b) .. ' bytes)') or nil end) or nil",
4471
- "for _, root in ipairs(roots) do",
4472
- " if root then",
4473
- " local ok, list = pcall(function() return root:GetDescendants() end)",
4474
- " if ok and type(list) == 'table' then",
4475
- " for _, inst in ipairs(list) do",
4476
- " if #results >= limit then break end",
4477
- " if not seen[inst] and (inst.ClassName == 'LocalScript' or inst.ClassName == 'ModuleScript') then",
4478
- " seen[inst] = true",
4479
- " local fullPath = inst:GetFullName()",
4480
- " if filter == '' or string.find(string.lower(fullPath), filter, 1, true) then",
4481
- " local src = '-- Live script: ' .. fullPath .. '\\n-- ClassName: ' .. inst.ClassName",
4482
- " if includeDecompiled and decompFn then",
4483
- " local okD, dec = pcall(decompFn, inst)",
4484
- " if okD and type(dec) == 'string' and #dec > 0 then",
4485
- " src = src .. '\\n\\n' .. dec:sub(1, 32000)",
4486
- " end",
4487
- " end",
4488
- " results[#results + 1] = { name = inst.Name, className = inst.ClassName, path = fullPath, source = src }",
4489
- " end",
5282
+ "local function collectOne(inst)",
5283
+ " if not inst or seen[inst] or #results >= limit then return end",
5284
+ " if inst.ClassName ~= 'LocalScript' and inst.ClassName ~= 'ModuleScript' then return end",
5285
+ " seen[inst] = true",
5286
+ " local fullPath = inst:GetFullName()",
5287
+ " if #targets == 0 and filter ~= '' and not string.find(string.lower(fullPath), filter, 1, true) then return end",
5288
+ " local src = '-- Live script: ' .. fullPath .. '\\n-- ClassName: ' .. inst.ClassName",
5289
+ " if includeDecompiled and decompFn then",
5290
+ " local okD, dec = pcall(decompFn, inst)",
5291
+ " if okD and type(dec) == 'string' and #dec > 0 then",
5292
+ " src = src .. '\\n\\n' .. dec:sub(1, 32000)",
5293
+ " end",
5294
+ " end",
5295
+ " if #results > 0 and (totalBytes + #src) > maxTotalBytes then return end",
5296
+ " totalBytes = totalBytes + #src",
5297
+ " results[#results + 1] = { name = inst.Name, className = inst.ClassName, path = fullPath, source = src }",
5298
+ "end",
5299
+ "if #targets > 0 and lw and lw.resolve then",
5300
+ " for _, tPath in ipairs(targets) do",
5301
+ " local inst = lw.resolve(tPath)",
5302
+ " if inst then collectOne(inst) end",
5303
+ " end",
5304
+ "else",
5305
+ " for _, root in ipairs(roots) do",
5306
+ " if root then",
5307
+ " local ok, list = pcall(function() return root:GetDescendants() end)",
5308
+ " if ok and type(list) == 'table' then",
5309
+ " for _, inst in ipairs(list) do",
5310
+ " if #results >= limit or totalBytes >= maxTotalBytes then break end",
5311
+ " collectOne(inst)",
4490
5312
  " end",
4491
5313
  " end",
4492
5314
  " end",
@@ -4494,7 +5316,7 @@ ${createRes.text}`
4494
5316
  "end",
4495
5317
  "return HttpService:JSONEncode(results)"
4496
5318
  ].join("\n");
4497
- const liveRes = await this.callCloudTool("exec", {
5319
+ const liveRes = await this.execWithFullOutput({
4498
5320
  code: liveCollectCode,
4499
5321
  readonly: true,
4500
5322
  ...session ? { session } : {}
@@ -4510,32 +5332,52 @@ ${createRes.text}`
4510
5332
  isError: true
4511
5333
  };
4512
5334
  }
4513
- const scripts = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
5335
+ const scripts = this.extractJsonPayloadFromExec(
5336
+ liveRes.fullBody
5337
+ );
5338
+ if (!Array.isArray(scripts)) {
5339
+ return this.formatJsonParseError(
5340
+ "live_scripts_to_studio",
5341
+ "live scripts collection",
5342
+ liveRes.fullBody,
5343
+ liveRes.pages,
5344
+ liveRes.truncated
5345
+ );
5346
+ }
4514
5347
  const studioImportCode = [
4515
- "local HttpService = game:GetService('HttpService')",
4516
- "local ServerStorage = game:GetService('ServerStorage')",
4517
- `local containerName = ${JSON.stringify(containerName)}`,
4518
- `local items = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(scripts))})`,
4519
- "local folder = ServerStorage:FindFirstChild(containerName)",
4520
- "if not folder then",
4521
- " folder = Instance.new('Folder')",
4522
- " folder.Name = containerName",
4523
- " folder.Parent = ServerStorage",
5348
+ `local targetService = ${toLuauLiteral(container.service)}`,
5349
+ `local targetSegments = ${toLuauLiteral(container.segments)}`,
5350
+ `local displayPath = ${toLuauLiteral(container.displayPath)}`,
5351
+ `local setDisabled = ${toLuauLiteral(disabled)}`,
5352
+ `local items = ${toLuauLiteral(scripts)}`,
5353
+ "local cur = game:GetService(targetService)",
5354
+ "for _, seg in ipairs(targetSegments) do",
5355
+ " local nextInst = cur:FindFirstChild(seg)",
5356
+ " if not nextInst then",
5357
+ " nextInst = Instance.new('Folder')",
5358
+ " nextInst.Name = seg",
5359
+ " nextInst.Parent = cur",
5360
+ " end",
5361
+ " cur = nextInst",
4524
5362
  "end",
5363
+ "local folder = cur",
4525
5364
  "local imported = 0",
4526
5365
  "for _, item in ipairs(items) do",
4527
5366
  " local ok, inst = pcall(Instance.new, item.className)",
4528
5367
  " if ok and inst then",
4529
5368
  " inst.Name = item.name .. '_' .. tostring(imported + 1)",
4530
5369
  " pcall(function() inst:SetAttribute('LivePath', item.path) end)",
5370
+ " if setDisabled and (item.className == 'LocalScript' or item.className == 'Script') then",
5371
+ " pcall(function() inst.Disabled = true end)",
5372
+ " end",
4531
5373
  " pcall(function() inst.Source = item.source end)",
4532
5374
  " inst.Parent = folder",
4533
5375
  " imported = imported + 1",
4534
5376
  " end",
4535
5377
  "end",
4536
- "return string.format('imported %d live scripts into ServerStorage.%s', imported, containerName)"
5378
+ "return string.format('imported %d live scripts into %s', imported, displayPath)"
4537
5379
  ].join("\n");
4538
- const studioRes = await this.studio.runStudioLuau(studioImportCode, requestedStudioId);
5380
+ const studioRes = await this.studio.runStudioLuau(studioImportCode, requestedStudioId, datamodelType);
4539
5381
  if (!studioRes.ok) {
4540
5382
  return {
4541
5383
  content: [
@@ -4547,16 +5389,26 @@ ${createRes.text}`
4547
5389
  isError: true
4548
5390
  };
4549
5391
  }
5392
+ const notes = [];
5393
+ if (liveRes.pages > 1) {
5394
+ notes.push(`- Pagination: reassembled ${liveRes.pages} pages from Cloud exec/get_result`);
5395
+ }
5396
+ if (scripts.length >= limit || liveRes.truncated) {
5397
+ notes.push(
5398
+ `- Note: collection reached limit (max=${limit}${liveRes.truncated ? ", truncated" : ""}); pass filter/targets or raise max to import more.`
5399
+ );
5400
+ }
4550
5401
  const listLines = scripts.slice(0, 15).map((s) => ` - [${s.className}] ${s.path} (${s.source.length} bytes)`);
4551
5402
  return {
4552
5403
  content: [
4553
5404
  {
4554
5405
  type: "text",
4555
5406
  text: [
4556
- `live_scripts_to_studio complete (studio_id=${studioRes.studioId ?? "auto"}):`,
5407
+ `live_scripts_to_studio complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4557
5408
  `- Scripts collected from live game: ${scripts.length}`,
4558
- `- Studio container: ServerStorage.${containerName}`,
5409
+ `- Studio container: ${container.displayPath}`,
4559
5410
  `- Studio result: ${studioRes.text}`,
5411
+ ...notes,
4560
5412
  ...listLines
4561
5413
  ].join("\n")
4562
5414
  }
@@ -4568,7 +5420,9 @@ ${createRes.text}`
4568
5420
  const targetB = typeof args.target_b === "string" && args.target_b.trim() ? args.target_b.trim() : "studio";
4569
5421
  const rawMethod = typeof args.method === "string" ? args.method : "auto";
4570
5422
  const method = rawMethod === "copy" || rawMethod === "screen" ? "copy" : rawMethod === "printwindow" || rawMethod === "print_window" ? "printwindow" : "auto";
4571
- const includeImages = args.include_images === true;
5423
+ const clientOnly = args.client_only !== false;
5424
+ const focusFirst = args.focus_first === true;
5425
+ const includeImages = args.include_images !== false;
4572
5426
  let base64A = typeof args.base64_a === "string" && args.base64_a.trim() ? args.base64_a.trim() : "";
4573
5427
  let base64B = typeof args.base64_b === "string" && args.base64_b.trim() ? args.base64_b.trim() : "";
4574
5428
  let labelA = base64A ? "base64_a" : targetA;
@@ -4576,7 +5430,12 @@ ${createRes.text}`
4576
5430
  let metaA;
4577
5431
  let metaB;
4578
5432
  if (!base64A) {
4579
- const shotA = await this.windows.captureScreenshot({ target: targetA, method, clientOnly: true });
5433
+ const shotA = await this.windows.captureScreenshot({
5434
+ target: targetA,
5435
+ method,
5436
+ clientOnly,
5437
+ focusFirst
5438
+ });
4580
5439
  if (!shotA.ok || !shotA.data) {
4581
5440
  return {
4582
5441
  content: [
@@ -4593,7 +5452,12 @@ ${createRes.text}`
4593
5452
  labelA = `${targetA} (${shotA.width}x${shotA.height}, method=${shotA.captureMethod ?? method})`;
4594
5453
  }
4595
5454
  if (!base64B) {
4596
- const shotB = await this.windows.captureScreenshot({ target: targetB, method, clientOnly: true });
5455
+ const shotB = await this.windows.captureScreenshot({
5456
+ target: targetB,
5457
+ method,
5458
+ clientOnly,
5459
+ focusFirst
5460
+ });
4597
5461
  if (!shotB.ok || !shotB.data) {
4598
5462
  return {
4599
5463
  content: [
@@ -4938,9 +5802,12 @@ export {
4938
5802
  SCRATCH_TAB_NAME,
4939
5803
  TOKEN_CREATE_URL,
4940
5804
  TOKEN_SHAPE,
5805
+ WIN32_CSHARP_PRELUDE,
5806
+ buildFocusWindowPsScript,
4941
5807
  buildListWindowsPsScript,
4942
5808
  buildRobloxDeepLink,
4943
5809
  buildScreenshotPsScript,
5810
+ buildStudioSpawnSpec,
4944
5811
  buildUiTreePsScript,
4945
5812
  buildUipiWarning,
4946
5813
  comparePngBase64,
@@ -4949,6 +5816,7 @@ export {
4949
5816
  discoverPotassiumToken,
4950
5817
  discoverRobloxStudioMcpBatch,
4951
5818
  encodePowerShellCommand,
5819
+ extractJsonPayloadFromExec,
4952
5820
  findPotassiumBinary,
4953
5821
  findRobloxPlayerBinary,
4954
5822
  forwardJsonRpcLine,
@@ -4957,7 +5825,10 @@ export {
4957
5825
  matchesWindowTarget,
4958
5826
  resolveBridgeConfig,
4959
5827
  resolveStoredToken,
5828
+ resolveStudioContainerPath,
4960
5829
  resolveVirtualKeyCode,
4961
- startStdioBridge
5830
+ startStdioBridge,
5831
+ stripExecPageEnvelope,
5832
+ toLuauLiteral
4962
5833
  };
4963
5834
  //# sourceMappingURL=index.js.map