@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/cli.js CHANGED
@@ -239,7 +239,7 @@ var PotassiumClient = class {
239
239
  params: {
240
240
  protocolVersion: "2025-03-26",
241
241
  capabilities: {},
242
- clientInfo: { name: "@luaward/mcp", version: "0.2.4" }
242
+ clientInfo: { name: "@luaward/mcp", version: "0.2.6" }
243
243
  }
244
244
  })
245
245
  });
@@ -514,6 +514,105 @@ import { homedir as homedir2 } from "node:os";
514
514
  import { join as join2 } from "node:path";
515
515
  import { createInterface } from "node:readline";
516
516
  import { inflateSync } from "node:zlib";
517
+ var LUAU_RESERVED_KEYWORDS = /* @__PURE__ */ new Set([
518
+ "and",
519
+ "break",
520
+ "do",
521
+ "else",
522
+ "elseif",
523
+ "end",
524
+ "false",
525
+ "for",
526
+ "function",
527
+ "if",
528
+ "in",
529
+ "local",
530
+ "nil",
531
+ "not",
532
+ "or",
533
+ "repeat",
534
+ "return",
535
+ "then",
536
+ "true",
537
+ "until",
538
+ "while"
539
+ ]);
540
+ var LUAU_IDENT_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
541
+ function escapeLuauString(str) {
542
+ let out = '"';
543
+ for (let i = 0; i < str.length; i++) {
544
+ const code = str.charCodeAt(i);
545
+ if (code === 34) {
546
+ out += '\\"';
547
+ } else if (code === 92) {
548
+ out += "\\\\";
549
+ } else if (code === 10) {
550
+ out += "\\n";
551
+ } else if (code === 13) {
552
+ out += "\\r";
553
+ } else if (code === 9) {
554
+ out += "\\t";
555
+ } else if (code < 32 || code === 127) {
556
+ out += `\\${String(code).padStart(3, "0")}`;
557
+ } else {
558
+ out += str[i];
559
+ }
560
+ }
561
+ out += '"';
562
+ return out;
563
+ }
564
+ function toLuauLiteral(value) {
565
+ if (value === null || value === void 0) {
566
+ return "nil";
567
+ }
568
+ if (typeof value === "boolean") {
569
+ return value ? "true" : "false";
570
+ }
571
+ if (typeof value === "number") {
572
+ if (Number.isNaN(value)) return "0";
573
+ if (!Number.isFinite(value)) return value > 0 ? "math.huge" : "-math.huge";
574
+ return String(value);
575
+ }
576
+ if (typeof value === "string") {
577
+ return escapeLuauString(value);
578
+ }
579
+ if (Array.isArray(value)) {
580
+ if (value.length === 0) return "{}";
581
+ return `{ ${value.map((item) => toLuauLiteral(item)).join(", ")} }`;
582
+ }
583
+ if (typeof value === "object") {
584
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0);
585
+ if (entries.length === 0) return "{}";
586
+ const fields = entries.map(([k, v]) => {
587
+ const keyExpr = LUAU_IDENT_RE.test(k) && !LUAU_RESERVED_KEYWORDS.has(k) ? k : `[${escapeLuauString(k)}]`;
588
+ return `${keyExpr} = ${toLuauLiteral(v)}`;
589
+ });
590
+ return `{ ${fields.join(", ")} }`;
591
+ }
592
+ return "nil";
593
+ }
594
+ function buildStudioSpawnSpec(batchPath) {
595
+ const isBat = /\.(?:bat|cmd)$/i.test(batchPath);
596
+ if (isBat) {
597
+ return {
598
+ command: "cmd.exe",
599
+ args: ["/d", "/s", "/c", `"${batchPath}"`],
600
+ options: {
601
+ stdio: ["pipe", "pipe", "pipe"],
602
+ windowsVerbatimArguments: true,
603
+ windowsHide: true
604
+ }
605
+ };
606
+ }
607
+ return {
608
+ command: batchPath,
609
+ args: [],
610
+ options: {
611
+ stdio: ["pipe", "pipe", "pipe"],
612
+ windowsHide: true
613
+ }
614
+ };
615
+ }
517
616
  function discoverRobloxStudioMcpBatch(env = process.env) {
518
617
  if (env.ROBLOX_STUDIO_MCP_PATH?.trim()) {
519
618
  return env.ROBLOX_STUDIO_MCP_PATH.trim();
@@ -571,16 +670,19 @@ function parseStudioToolResponse(rpcRes) {
571
670
  var RobloxStudioMcpClient = class {
572
671
  batchPath;
573
672
  timeoutMs;
673
+ defaultDataModelType;
574
674
  customTransport;
575
675
  child = null;
576
676
  initPromise = null;
577
677
  pending = /* @__PURE__ */ new Map();
578
678
  rpcSeq = 9e3;
579
679
  cachedToolNames = null;
680
+ cachedToolSchemas = /* @__PURE__ */ new Map();
580
681
  exitHookInstalled = false;
581
682
  constructor(options = {}) {
582
683
  this.batchPath = options.batchPath || discoverRobloxStudioMcpBatch(options.env);
583
684
  this.timeoutMs = options.timeoutMs ?? 25e3;
685
+ this.defaultDataModelType = options.defaultDataModelType ?? "Edit";
584
686
  this.customTransport = options.transport;
585
687
  }
586
688
  dispose() {
@@ -610,14 +712,8 @@ var RobloxStudioMcpClient = class {
610
712
  `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.`
611
713
  );
612
714
  }
613
- const isBat = /\.(?:bat|cmd)$/i.test(this.batchPath);
614
- const child = isBat ? spawn("cmd.exe", ["/d", "/s", "/c", `"${this.batchPath}"`], {
615
- stdio: ["pipe", "pipe", "pipe"],
616
- windowsHide: true
617
- }) : spawn(this.batchPath, [], {
618
- stdio: ["pipe", "pipe", "pipe"],
619
- windowsHide: true
620
- });
715
+ const spec = buildStudioSpawnSpec(this.batchPath);
716
+ const child = spawn(spec.command, spec.args, spec.options);
621
717
  child.unref();
622
718
  this.child = child;
623
719
  if (!this.exitHookInstalled) {
@@ -658,7 +754,7 @@ var RobloxStudioMcpClient = class {
658
754
  await this.sendRawRpc("initialize", {
659
755
  protocolVersion: "2025-03-26",
660
756
  capabilities: {},
661
- clientInfo: { name: "@luaward/mcp", version: "0.2.4" }
757
+ clientInfo: { name: "@luaward/mcp", version: "0.2.6" }
662
758
  });
663
759
  if (this.child && !this.child.killed) {
664
760
  this.child.stdin.write(
@@ -701,6 +797,12 @@ var RobloxStudioMcpClient = class {
701
797
  const res = await this.sendRpc("tools/list", {});
702
798
  const tools = res?.result?.tools;
703
799
  if (Array.isArray(tools)) {
800
+ this.cachedToolSchemas.clear();
801
+ for (const t of tools) {
802
+ if (typeof t?.name === "string" && t.name && t.inputSchema && typeof t.inputSchema === "object") {
803
+ this.cachedToolSchemas.set(t.name, t.inputSchema);
804
+ }
805
+ }
704
806
  this.cachedToolNames = tools.map((t) => typeof t?.name === "string" ? t.name : "").filter(Boolean);
705
807
  return this.cachedToolNames;
706
808
  }
@@ -710,7 +812,8 @@ var RobloxStudioMcpClient = class {
710
812
  }
711
813
  async listStudios() {
712
814
  const tools = await this.listTools();
713
- const listToolName = tools.find((t) => t === "list_studios" || t === "get_studios" || t === "list_clients") ?? "list_studios";
815
+ const listPriority = ["list_roblox_studios", "list_studios", "get_studios", "list_clients"];
816
+ const listToolName = listPriority.find((candidate) => tools.includes(candidate)) ?? "list_roblox_studios";
714
817
  try {
715
818
  const rpcRes = await this.sendRpc("tools/call", { name: listToolName, arguments: {} });
716
819
  const parsed = parseStudioToolResponse(rpcRes);
@@ -725,19 +828,24 @@ var RobloxStudioMcpClient = class {
725
828
  if (item && typeof item === "object") {
726
829
  const obj = item;
727
830
  const sid = String(
728
- obj.studio_id ?? obj.studioId ?? obj.id ?? obj.session_id ?? obj.pid ?? ""
831
+ obj.id ?? obj.studio_id ?? obj.studioId ?? obj.session_id ?? obj.pid ?? ""
729
832
  ).trim();
730
833
  if (sid) {
834
+ const placeNameRaw = obj.place_name ?? obj.placeName ?? obj.local_file_name ?? obj.name;
731
835
  studios.push({
836
+ id: sid,
732
837
  studio_id: sid,
733
838
  place_id: obj.place_id ?? obj.placeId,
734
- place_name: typeof (obj.place_name ?? obj.placeName ?? obj.name) === "string" ? String(obj.place_name ?? obj.placeName ?? obj.name) : void 0,
839
+ game_id: obj.game_id ?? obj.gameId,
840
+ place_name: typeof placeNameRaw === "string" ? placeNameRaw : void 0,
841
+ local_file_name: typeof obj.local_file_name === "string" ? obj.local_file_name : void 0,
735
842
  user: typeof obj.user === "string" ? obj.user : void 0,
736
843
  raw: obj
737
844
  });
738
845
  }
739
846
  } else if (typeof item === "string" || typeof item === "number") {
740
- studios.push({ studio_id: String(item) });
847
+ const sid = String(item);
848
+ studios.push({ id: sid, studio_id: sid });
741
849
  }
742
850
  }
743
851
  return { ok: true, studios, rawText: parsed.text };
@@ -746,7 +854,7 @@ var RobloxStudioMcpClient = class {
746
854
  ...parsed.text.matchAll(/\b(?:studio_id|studioId|studio|id)[:=\s"']*([A-Za-z0-9_-]{2,64})\b/gi)
747
855
  ];
748
856
  for (const m of matches) {
749
- if (m[1]) studios.push({ studio_id: m[1] });
857
+ if (m[1]) studios.push({ id: m[1], studio_id: m[1] });
750
858
  }
751
859
  return { ok: true, studios, rawText: parsed.text };
752
860
  } catch (err) {
@@ -762,10 +870,11 @@ var RobloxStudioMcpClient = class {
762
870
  */
763
871
  async resolveStudioId(explicitStudioId) {
764
872
  if (explicitStudioId && explicitStudioId.trim()) {
873
+ const sid = explicitStudioId.trim();
765
874
  return {
766
875
  ok: true,
767
- studioId: explicitStudioId.trim(),
768
- studios: [{ studio_id: explicitStudioId.trim() }],
876
+ studioId: sid,
877
+ studios: [{ id: sid, studio_id: sid }],
769
878
  autoSelected: false
770
879
  };
771
880
  }
@@ -779,9 +888,10 @@ var RobloxStudioMcpClient = class {
779
888
  };
780
889
  }
781
890
  if (listed.studios.length === 1 && listed.studios[0]) {
891
+ const sid = listed.studios[0].id || listed.studios[0].studio_id;
782
892
  return {
783
893
  ok: true,
784
- studioId: listed.studios[0].studio_id,
894
+ studioId: sid,
785
895
  studios: listed.studios,
786
896
  autoSelected: true
787
897
  };
@@ -794,7 +904,7 @@ var RobloxStudioMcpClient = class {
794
904
  err: "No connected Roblox Studio instance found via %LOCALAPPDATA%\\Roblox\\mcp.bat. Open a place in Roblox Studio with MCP enabled first."
795
905
  };
796
906
  }
797
- const listStr = listed.studios.map((s) => `${s.studio_id}${s.place_name ? ` ("${s.place_name}")` : ""}`).join(", ");
907
+ const listStr = listed.studios.map((s) => `${s.id || s.studio_id}${s.place_name ? ` ("${s.place_name}")` : ""}`).join(", ");
798
908
  return {
799
909
  ok: false,
800
910
  studios: listed.studios,
@@ -806,7 +916,8 @@ var RobloxStudioMcpClient = class {
806
916
  const finalArgs = { ...args };
807
917
  let studioId = typeof finalArgs.studio_id === "string" ? finalArgs.studio_id.trim() : void 0;
808
918
  let autoSelected = false;
809
- if (!studioId && name !== "list_studios" && name !== "get_studios") {
919
+ const isListTool = name === "list_roblox_studios" || name === "list_studios" || name === "get_studios" || name === "list_clients";
920
+ if (!studioId && !isListTool) {
810
921
  const resolved = await this.resolveStudioId();
811
922
  if (!resolved.ok) {
812
923
  return { ok: false, text: resolved.err ?? "Failed to resolve studio_id", isError: true };
@@ -817,6 +928,12 @@ var RobloxStudioMcpClient = class {
817
928
  finalArgs.studio_id = studioId;
818
929
  }
819
930
  }
931
+ if (!isListTool && finalArgs.datamodel_type === void 0) {
932
+ const schemaProps = this.cachedToolSchemas.get(name)?.properties;
933
+ if (name === "execute_luau" || schemaProps && "datamodel_type" in schemaProps) {
934
+ finalArgs.datamodel_type = this.defaultDataModelType;
935
+ }
936
+ }
820
937
  try {
821
938
  const rpcRes = await this.sendRpc("tools/call", { name, arguments: finalArgs });
822
939
  const parsed = parseStudioToolResponse(rpcRes);
@@ -835,7 +952,7 @@ var RobloxStudioMcpClient = class {
835
952
  };
836
953
  }
837
954
  }
838
- async runStudioLuau(code, explicitStudioId) {
955
+ async runStudioLuau(code, explicitStudioId, datamodelType) {
839
956
  const resolved = await this.resolveStudioId(explicitStudioId);
840
957
  if (!resolved.ok) {
841
958
  return {
@@ -845,13 +962,30 @@ var RobloxStudioMcpClient = class {
845
962
  };
846
963
  }
847
964
  const tools = await this.listTools();
848
- const execTool = tools.find((t) => t === "run_code" || t === "execute_luau" || t === "run_script" || t === "eval") ?? "run_code";
849
- const res = await this.callTool(execTool, {
850
- command: code,
851
- code,
852
- source: code,
965
+ const execPriority = ["execute_luau", "run_code", "run_script", "eval"];
966
+ const execTool = execPriority.find((candidate) => tools.includes(candidate)) ?? "execute_luau";
967
+ const dmType = datamodelType ?? this.defaultDataModelType;
968
+ const schemaProps = this.cachedToolSchemas.get(execTool)?.properties;
969
+ const toolArgs = {
970
+ datamodel_type: dmType,
853
971
  ...resolved.studioId ? { studio_id: resolved.studioId } : {}
854
- });
972
+ };
973
+ if (execTool === "execute_luau") {
974
+ toolArgs.code = code;
975
+ if (schemaProps && "command" in schemaProps) {
976
+ toolArgs.command = code;
977
+ }
978
+ } else if (execTool === "run_code") {
979
+ toolArgs.command = code;
980
+ if (!schemaProps || "code" in schemaProps) {
981
+ toolArgs.code = code;
982
+ }
983
+ } else {
984
+ toolArgs.code = code;
985
+ toolArgs.command = code;
986
+ toolArgs.source = code;
987
+ }
988
+ const res = await this.callTool(execTool, toolArgs);
855
989
  return {
856
990
  ...res,
857
991
  studioId: resolved.studioId,
@@ -1245,6 +1379,10 @@ namespace Luaward {
1245
1379
  [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
1246
1380
  [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
1247
1381
  [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
1382
+ [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);
1383
+ [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
1384
+ [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
1385
+ [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
1248
1386
  [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
1249
1387
  [DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
1250
1388
  [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
@@ -1264,6 +1402,52 @@ namespace Luaward {
1264
1402
 
1265
1403
  public const uint GA_ROOT = 2;
1266
1404
  public const uint PW_RENDERFULLCONTENT = 0x00000002;
1405
+ public const byte VK_MENU = 0x12;
1406
+
1407
+ public static bool ForceForegroundWindow(IntPtr targetHwnd) {
1408
+ if (targetHwnd == IntPtr.Zero) return false;
1409
+ if (IsIconic(targetHwnd)) {
1410
+ ShowWindow(targetHwnd, 9);
1411
+ }
1412
+ SetForegroundWindow(targetHwnd);
1413
+ if (GetForegroundWindow() == targetHwnd) {
1414
+ return true;
1415
+ }
1416
+
1417
+ IntPtr fg = GetForegroundWindow();
1418
+ uint dummyPid = 0;
1419
+ uint curTid = GetCurrentThreadId();
1420
+ uint targetTid = GetWindowThreadProcessId(targetHwnd, out dummyPid);
1421
+ uint fgTid = fg != IntPtr.Zero ? GetWindowThreadProcessId(fg, out dummyPid) : 0;
1422
+
1423
+ bool attachedCurToFg = false;
1424
+ bool attachedCurToTarget = false;
1425
+ bool attachedFgToTarget = false;
1426
+ try {
1427
+ if (fgTid != 0 && fgTid != curTid) {
1428
+ attachedCurToFg = AttachThreadInput(curTid, fgTid, true);
1429
+ }
1430
+ if (targetTid != 0 && targetTid != curTid) {
1431
+ attachedCurToTarget = AttachThreadInput(curTid, targetTid, true);
1432
+ }
1433
+ if (fgTid != 0 && targetTid != 0 && fgTid != targetTid) {
1434
+ attachedFgToTarget = AttachThreadInput(fgTid, targetTid, true);
1435
+ }
1436
+
1437
+ // Briefly pulse Alt (VK_MENU) so Windows releases the Foreground Lock Timeout for background workers.
1438
+ keybd_event(VK_MENU, 0, 0, UIntPtr.Zero);
1439
+ keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
1440
+
1441
+ BringWindowToTop(targetHwnd);
1442
+ ShowWindow(targetHwnd, 5);
1443
+ SetForegroundWindow(targetHwnd);
1444
+ } finally {
1445
+ if (attachedFgToTarget) AttachThreadInput(fgTid, targetTid, false);
1446
+ if (attachedCurToTarget) AttachThreadInput(curTid, targetTid, false);
1447
+ if (attachedCurToFg) AttachThreadInput(curTid, fgTid, false);
1448
+ }
1449
+ return GetForegroundWindow() == targetHwnd;
1450
+ }
1267
1451
 
1268
1452
  public static bool IsWindowTopAtPoint(IntPtr targetHwnd, int x, int y) {
1269
1453
  if (targetHwnd == IntPtr.Zero) return false;
@@ -1582,20 +1766,37 @@ ${scriptBody}`;
1582
1766
  if (!filterStr) return all;
1583
1767
  return all.filter((w) => matchesWindowTarget(w, filterStr));
1584
1768
  }
1585
- async focusWindow(target) {
1769
+ async focusWindow(target, opts) {
1586
1770
  const wins = await this.listWindows(target);
1587
1771
  const win = wins[0];
1588
1772
  if (!win) return { ok: false, err: `No window matching "${target}" found` };
1589
- await this.runPsJson(
1590
- `
1591
- $h = [IntPtr]::new([Convert]::ToInt64("${win.hwnd}", 16))
1592
- if ([Luaward.Win32Desktop]::IsIconic($h)) { [void][Luaward.Win32Desktop]::ShowWindow($h, 9) }
1593
- [void][Luaward.Win32Desktop]::SetForegroundWindow($h)
1594
- @{ ok = $true } | ConvertTo-Json -Compress
1595
- `
1596
- );
1773
+ const res = await this.runPsJson(buildFocusWindowPsScript(win.hwnd, opts?.verifyPoint));
1597
1774
  const refreshed = (await this.listWindows(target))[0] ?? win;
1598
- return { ok: true, window: refreshed };
1775
+ const isForeground = Boolean(res.isForeground || refreshed.isForeground);
1776
+ const isTopAtPoint = Boolean(res.isTopAtPoint);
1777
+ const ok = isForeground || isTopAtPoint;
1778
+ return {
1779
+ ok,
1780
+ window: refreshed,
1781
+ isForeground,
1782
+ isTopAtPoint,
1783
+ fgProcess: res.fgProcess,
1784
+ ...ok ? {} : {
1785
+ err: `Could not bring "${refreshed.title}" (${refreshed.hwnd}) to foreground; current foreground process is "${res.fgProcess || "unknown"}"`
1786
+ }
1787
+ };
1788
+ }
1789
+ async isWindowTopAtPoint(hwnd, x, y) {
1790
+ const rx = Math.round(x);
1791
+ const ry = Math.round(y);
1792
+ return this.runPsJson(`
1793
+ $h = [IntPtr]::new([Convert]::ToInt64("${hwnd}", 16))
1794
+ $fg = [Luaward.Win32Desktop]::GetForegroundWindow()
1795
+ $isFg = ($fg -eq $h)
1796
+ $isTop = [Luaward.Win32Desktop]::IsWindowTopAtPoint($h, ${rx}, ${ry})
1797
+ $fgProc = (Get-ForegroundProcessName)
1798
+ @{ ok = $true; isTop = $isTop; isForeground = $isFg; fgProcess = $fgProc } | ConvertTo-Json -Compress
1799
+ `);
1599
1800
  }
1600
1801
  async resizeWindow(opts) {
1601
1802
  const wins = await this.listWindows(opts.target);
@@ -2086,6 +2287,21 @@ Walk-Ui $root 1
2086
2287
  if ($nodes.Count -eq 0) { "[]" } else { ConvertTo-Json -InputObject $nodes.ToArray() -Depth 5 -Compress }
2087
2288
  `;
2088
2289
  }
2290
+ function buildFocusWindowPsScript(hwnd, checkPoint) {
2291
+ const hasPoint = Boolean(checkPoint && Number.isFinite(checkPoint.x) && Number.isFinite(checkPoint.y));
2292
+ const checkX = hasPoint ? Math.round(checkPoint.x) : 0;
2293
+ const checkY = hasPoint ? Math.round(checkPoint.y) : 0;
2294
+ return `
2295
+ $h = [IntPtr]::new([Convert]::ToInt64("${hwnd}", 16))
2296
+ [void][Luaward.Win32Desktop]::ForceForegroundWindow($h)
2297
+ Start-Sleep -Milliseconds 40
2298
+ $fg = [Luaward.Win32Desktop]::GetForegroundWindow()
2299
+ $isFg = ($fg -eq $h)
2300
+ $isTop = ${hasPoint ? `[Luaward.Win32Desktop]::IsWindowTopAtPoint($h, ${checkX}, ${checkY})` : "$isFg"}
2301
+ $fgProc = (Get-ForegroundProcessName)
2302
+ @{ ok = ($isFg -or $isTop); isForeground = $isFg; isTopAtPoint = $isTop; fgProcess = $fgProc } | ConvertTo-Json -Compress
2303
+ `;
2304
+ }
2089
2305
  function buildScreenshotPsScript(opts) {
2090
2306
  const hasHwnd = Boolean(opts.hwnd?.startsWith("0x"));
2091
2307
  return `
@@ -2232,7 +2448,7 @@ function matchesWindowTarget(w, filter) {
2232
2448
  }
2233
2449
 
2234
2450
  // src/index.ts
2235
- var MCP_BRIDGE_VERSION = "0.2.4";
2451
+ var MCP_BRIDGE_VERSION = "0.2.6";
2236
2452
  var DEFAULT_MCP_URL = "https://luaward.com/mcp";
2237
2453
  var TOKEN_CREATE_URL = "https://dash.luaward.com/dashboard/ai";
2238
2454
  var TOKEN_SHAPE = /^lwm_[0-9a-f]{48}$/;
@@ -2330,6 +2546,145 @@ function extractProtocolVersion(parsed) {
2330
2546
  return void 0;
2331
2547
  }
2332
2548
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2549
+ var CLOUD_RESULT_PAGE_MAX_CHUNKS = 25;
2550
+ var CLOUD_RESULT_PAGE_LIMIT = 1e5;
2551
+ function stripExecPageEnvelope(rawText) {
2552
+ let body = rawText.replace(/^\[Auto-injected[^\n]*\]\r?\n/, "");
2553
+ body = body.replace(/^answer from the game \(untrusted\):\r?\n/, "");
2554
+ const consoleDoubleIdx = body.indexOf("\n\nconsole (from the game");
2555
+ if (consoleDoubleIdx !== -1) {
2556
+ body = body.slice(0, consoleDoubleIdx);
2557
+ } else {
2558
+ const consoleSingleIdx = body.indexOf("\nconsole (from the game");
2559
+ if (consoleSingleIdx !== -1) {
2560
+ body = body.slice(0, consoleSingleIdx);
2561
+ }
2562
+ }
2563
+ let agentTruncated = false;
2564
+ const cutMarkerMatch = /\r?\n\(the answer was cut to fit\)$/.exec(body);
2565
+ if (cutMarkerMatch) {
2566
+ agentTruncated = true;
2567
+ body = body.slice(0, cutMarkerMatch.index);
2568
+ }
2569
+ const continueMatch = /\r?\n\.\.\. \[(\d+)\.\.(\d+) of (\d+) chars; (\d+) more characters(?:; page with get_result\(cmd="([0-9a-f]{32})", offset=(\d+)\))?\]$/.exec(
2570
+ body
2571
+ );
2572
+ if (continueMatch) {
2573
+ body = body.slice(0, continueMatch.index);
2574
+ const offset = Number(continueMatch[1]);
2575
+ const end = Number(continueMatch[2]);
2576
+ const total = Number(continueMatch[3]);
2577
+ const remaining = Number(continueMatch[4]);
2578
+ const cmdId = continueMatch[5];
2579
+ const nextOffset = continueMatch[6] !== void 0 ? Number(continueMatch[6]) : end;
2580
+ return {
2581
+ body,
2582
+ hasMore: true,
2583
+ cmdId,
2584
+ offset,
2585
+ end,
2586
+ total,
2587
+ remaining,
2588
+ nextOffset,
2589
+ agentTruncated
2590
+ };
2591
+ }
2592
+ const endMatch = /\r?\n\.\.\. \[end of (\d+) chars \((\d+)\.\.(\d+)\)\]$/.exec(body);
2593
+ if (endMatch) {
2594
+ body = body.slice(0, endMatch.index);
2595
+ return {
2596
+ body,
2597
+ hasMore: false,
2598
+ total: Number(endMatch[1]),
2599
+ offset: Number(endMatch[2]),
2600
+ end: Number(endMatch[3]),
2601
+ agentTruncated
2602
+ };
2603
+ }
2604
+ return {
2605
+ body,
2606
+ hasMore: false,
2607
+ agentTruncated
2608
+ };
2609
+ }
2610
+ function extractJsonPayloadFromExec(rawText) {
2611
+ const cleaned = stripExecPageEnvelope(rawText).body.trim();
2612
+ if (!cleaned) return null;
2613
+ const candidates = [cleaned];
2614
+ if (cleaned.startsWith('"') && cleaned.endsWith('"')) {
2615
+ try {
2616
+ const unquoted = JSON.parse(cleaned);
2617
+ if (typeof unquoted === "string") candidates.unshift(unquoted.trim());
2618
+ } catch {
2619
+ }
2620
+ }
2621
+ const firstArr = cleaned.indexOf("[");
2622
+ const firstObj = cleaned.indexOf("{");
2623
+ let firstIdx = -1;
2624
+ let expectedClose = "";
2625
+ if (firstArr >= 0 && (firstObj < 0 || firstArr < firstObj)) {
2626
+ firstIdx = firstArr;
2627
+ expectedClose = "]";
2628
+ } else if (firstObj >= 0) {
2629
+ firstIdx = firstObj;
2630
+ expectedClose = "}";
2631
+ }
2632
+ if (firstIdx >= 0) {
2633
+ const lastIdx = cleaned.lastIndexOf(expectedClose);
2634
+ if (lastIdx > firstIdx) {
2635
+ candidates.push(cleaned.slice(firstIdx, lastIdx + 1));
2636
+ }
2637
+ }
2638
+ for (const c of candidates) {
2639
+ try {
2640
+ return JSON.parse(c);
2641
+ } catch {
2642
+ }
2643
+ }
2644
+ return null;
2645
+ }
2646
+ var KNOWN_STUDIO_SERVICES = /* @__PURE__ */ new Set([
2647
+ "ServerStorage",
2648
+ "ReplicatedStorage",
2649
+ "ServerScriptService",
2650
+ "StarterPlayer",
2651
+ "StarterGui",
2652
+ "StarterPack",
2653
+ "Workspace",
2654
+ "Lighting",
2655
+ "ReplicatedFirst"
2656
+ ]);
2657
+ function resolveStudioContainerPath(rawInput, defaultService = "ServerStorage", defaultFolder = "LuawardLiveScripts") {
2658
+ const raw = (rawInput ?? "").trim().replace(/^game\./, "");
2659
+ if (!raw) {
2660
+ return {
2661
+ service: defaultService,
2662
+ segments: [defaultFolder],
2663
+ displayPath: `${defaultService}.${defaultFolder}`
2664
+ };
2665
+ }
2666
+ const segs = raw.split(".").map((s) => s.trim()).filter(Boolean);
2667
+ if (segs.length === 0) {
2668
+ return {
2669
+ service: defaultService,
2670
+ segments: [defaultFolder],
2671
+ displayPath: `${defaultService}.${defaultFolder}`
2672
+ };
2673
+ }
2674
+ if (KNOWN_STUDIO_SERVICES.has(segs[0])) {
2675
+ const subSegs = segs.length > 1 ? segs.slice(1) : [defaultFolder];
2676
+ return {
2677
+ service: segs[0],
2678
+ segments: subSegs,
2679
+ displayPath: `${segs[0]}.${subSegs.join(".")}`
2680
+ };
2681
+ }
2682
+ return {
2683
+ service: defaultService,
2684
+ segments: segs,
2685
+ displayPath: `${defaultService}.${segs.join(".")}`
2686
+ };
2687
+ }
2333
2688
  var LOCAL_HYBRID_TOOLS = [
2334
2689
  {
2335
2690
  name: "editor_tabs",
@@ -2748,7 +3103,12 @@ var LOCAL_HYBRID_TOOLS = [
2748
3103
  properties: {
2749
3104
  root: {
2750
3105
  type: "string",
2751
- description: "Root service/path to mirror (default 'ReplicatedStorage')"
3106
+ description: "Root service or dotted path to mirror (e.g. 'ReplicatedStorage' or 'ReplicatedStorage.Remotes')"
3107
+ },
3108
+ roots: {
3109
+ type: "array",
3110
+ items: { type: "string" },
3111
+ description: "Optional list of root services to mirror when root is omitted (default ['ReplicatedStorage', 'Workspace'])"
2752
3112
  },
2753
3113
  filter: {
2754
3114
  type: "string",
@@ -2757,7 +3117,7 @@ var LOCAL_HYBRID_TOOLS = [
2757
3117
  kind: {
2758
3118
  type: "string",
2759
3119
  enum: ["network", "bindable", "all"],
2760
- description: "Remote kind filter (default 'all')"
3120
+ description: "Remote kind filter (default 'network' - prioritizes RemoteEvent/RemoteFunction/UnreliableRemoteEvent)"
2761
3121
  },
2762
3122
  max: {
2763
3123
  type: "integer",
@@ -2765,6 +3125,21 @@ var LOCAL_HYBRID_TOOLS = [
2765
3125
  maximum: 500,
2766
3126
  description: "Maximum remotes to mirror (default 200)"
2767
3127
  },
3128
+ max_depth: {
3129
+ type: "integer",
3130
+ minimum: 1,
3131
+ maximum: 12,
3132
+ description: "Maximum hierarchy depth (default 6)"
3133
+ },
3134
+ clear_existing: {
3135
+ type: "boolean",
3136
+ description: "Recreate existing remotes of the same class in Studio (default false)"
3137
+ },
3138
+ datamodel_type: {
3139
+ type: "string",
3140
+ enum: ["Edit", "Client", "Server"],
3141
+ description: "Roblox Studio DataModel context (default 'Edit'; use 'Client' or 'Server' during playtest)"
3142
+ },
2768
3143
  studio_id: {
2769
3144
  type: "string",
2770
3145
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
@@ -2795,26 +3170,49 @@ var LOCAL_HYBRID_TOOLS = [
2795
3170
  type: "string",
2796
3171
  description: "Live GUI root path or #n handle to mirror (default 'Players.LocalPlayer.PlayerGui')"
2797
3172
  },
3173
+ target_path: {
3174
+ type: "string",
3175
+ description: "Alias for target (live GUI path or #n handle to mirror)"
3176
+ },
2798
3177
  studio_root: {
2799
3178
  type: "string",
2800
- description: "Destination container in Roblox Studio (default 'StarterGui')"
3179
+ description: "Destination container name in Roblox Studio StarterGui (default 'LuawardMirroredGui')"
3180
+ },
3181
+ container_name: {
3182
+ type: "string",
3183
+ description: "Alias for studio_root container folder name inside StarterGui (default 'LuawardMirroredGui')"
2801
3184
  },
2802
3185
  depth: {
2803
3186
  type: "integer",
2804
3187
  minimum: 1,
2805
3188
  maximum: 12,
2806
- description: "Maximum hierarchy depth (default 6)"
3189
+ description: "Maximum hierarchy depth (default 10)"
2807
3190
  },
2808
3191
  max_instances: {
2809
3192
  type: "integer",
2810
3193
  minimum: 1,
2811
- maximum: 600,
3194
+ maximum: 1e3,
2812
3195
  description: "Maximum GUI instances to mirror (default 250)"
2813
3196
  },
3197
+ max_nodes: {
3198
+ type: "integer",
3199
+ minimum: 1,
3200
+ maximum: 1e3,
3201
+ description: "Alias for max_instances (default 250)"
3202
+ },
2814
3203
  only_visible: {
2815
3204
  type: "boolean",
2816
3205
  description: "Only mirror visible GUI elements (default false)"
2817
3206
  },
3207
+ include_core_gui: {
3208
+ type: "boolean",
3209
+ description: "Include non-RobloxGui ScreenGuis from CoreGui (default false)"
3210
+ },
3211
+ datamodel_type: {
3212
+ type: "string",
3213
+ enum: ["Edit", "Client", "Server"],
3214
+ description: "Roblox Studio DataModel context (default 'Edit')"
3215
+ },
2818
3216
  studio_id: {
2819
3217
  type: "string",
2820
3218
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
@@ -2837,18 +3235,34 @@ var LOCAL_HYBRID_TOOLS = [
2837
3235
  {
2838
3236
  name: "studio_diff",
2839
3237
  title: "Diff scripts, remotes, or GUI between Roblox Studio and live game",
2840
- 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.",
3238
+ 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.",
2841
3239
  inputSchema: {
2842
3240
  type: "object",
2843
3241
  properties: {
2844
3242
  scope: {
2845
3243
  type: "string",
2846
3244
  enum: ["scripts", "remotes", "gui", "all"],
2847
- description: "What to compare (default 'scripts')"
3245
+ description: "What to compare (default 'all')"
2848
3246
  },
2849
3247
  target: {
2850
3248
  type: "string",
2851
- description: "Optional root or specific script path to compare (default 'ReplicatedStorage')"
3249
+ description: "Optional root service to compare (e.g. 'ReplicatedStorage')"
3250
+ },
3251
+ roots: {
3252
+ type: "array",
3253
+ items: { type: "string" },
3254
+ description: "Optional list of root services to compare (default ['ReplicatedStorage', 'StarterGui', 'Workspace'])"
3255
+ },
3256
+ max_depth: {
3257
+ type: "integer",
3258
+ minimum: 1,
3259
+ maximum: 10,
3260
+ description: "Maximum hierarchy depth (default 5)"
3261
+ },
3262
+ datamodel_type: {
3263
+ type: "string",
3264
+ enum: ["Edit", "Client", "Server"],
3265
+ description: "Roblox Studio DataModel context (default 'Edit')"
2852
3266
  },
2853
3267
  studio_id: {
2854
3268
  type: "string",
@@ -2880,6 +3294,24 @@ var LOCAL_HYBRID_TOOLS = [
2880
3294
  type: "string",
2881
3295
  description: "Script path in Roblox Studio (e.g. 'StarterPlayer.StarterPlayerScripts.Main') or 'Selection' for currently selected script (default 'Selection')"
2882
3296
  },
3297
+ code: {
3298
+ type: "string",
3299
+ description: "Optional inline Luau code to run instead of reading from studio_path"
3300
+ },
3301
+ collect: {
3302
+ type: "boolean",
3303
+ description: "Use run_and_collect instead of exec (default true)"
3304
+ },
3305
+ wait_seconds: {
3306
+ type: "number",
3307
+ description: "Convenience settle time in seconds; mapped to run_and_collect settle_ms (0..15000 ms) when settle_ms is omitted"
3308
+ },
3309
+ timeout_ms: {
3310
+ type: "integer",
3311
+ minimum: 1e3,
3312
+ maximum: 85e3,
3313
+ description: "Maximum wait/runtime in milliseconds for run_and_collect (1000..85000, default 30000)"
3314
+ },
2883
3315
  clean_env: {
2884
3316
  type: "boolean",
2885
3317
  description: "Run in clean native Luau SAFEENV environment (default true)"
@@ -2898,6 +3330,11 @@ var LOCAL_HYBRID_TOOLS = [
2898
3330
  maximum: 15e3,
2899
3331
  description: "Settle window in ms after return (default 300)"
2900
3332
  },
3333
+ datamodel_type: {
3334
+ type: "string",
3335
+ enum: ["Edit", "Client", "Server"],
3336
+ description: "Roblox Studio DataModel context (default 'Edit')"
3337
+ },
2901
3338
  studio_id: {
2902
3339
  type: "string",
2903
3340
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
@@ -2920,13 +3357,25 @@ var LOCAL_HYBRID_TOOLS = [
2920
3357
  {
2921
3358
  name: "studio_publish",
2922
3359
  title: "Publish a Roblox Studio script to Luaward Cloud",
2923
- 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.",
3360
+ description: "Read a script's Luau source directly from Roblox Studio (%LOCALAPPDATA%\\Roblox\\mcp.bat) and create or deploy/protect it on Luaward Cloud.",
2924
3361
  inputSchema: {
2925
3362
  type: "object",
2926
3363
  properties: {
2927
3364
  script: {
2928
3365
  type: "string",
2929
- description: "Target Luaward Cloud script name or ID"
3366
+ description: "Target Luaward Cloud script name or ID to deploy to"
3367
+ },
3368
+ script_id: {
3369
+ type: "string",
3370
+ description: "Alias for script (target Luaward Cloud script ID to deploy to)"
3371
+ },
3372
+ name: {
3373
+ type: "string",
3374
+ description: "New Luaward Cloud script name when creating a new script"
3375
+ },
3376
+ project_id: {
3377
+ type: "string",
3378
+ description: "Optional project ID from list_projects when creating a new script"
2930
3379
  },
2931
3380
  studio_path: {
2932
3381
  type: "string",
@@ -2934,19 +3383,37 @@ var LOCAL_HYBRID_TOOLS = [
2934
3383
  },
2935
3384
  publish: {
2936
3385
  type: "boolean",
2937
- description: "Promote build to live automatically (default true; false for staged draft)"
3386
+ description: "Promote build to live automatically when deploying (default true; false for staged draft)"
3387
+ },
3388
+ draft: {
3389
+ type: "boolean",
3390
+ description: "Shorthand for publish=false when deploying (stage a draft build without updating live users)"
2938
3391
  },
2939
3392
  preset: {
2940
3393
  type: "string",
2941
3394
  enum: ["fast", "balanced", "max"],
2942
3395
  description: "Optional protection preset"
2943
3396
  },
3397
+ store_source: {
3398
+ type: "boolean",
3399
+ description: "Keep encrypted raw source on Luaward after compilation (requires 2FA)"
3400
+ },
3401
+ wait: {
3402
+ type: "integer",
3403
+ minimum: 0,
3404
+ maximum: 60,
3405
+ description: "Optional seconds to wait for the compiler build to finish (0..60, default 0)"
3406
+ },
3407
+ datamodel_type: {
3408
+ type: "string",
3409
+ enum: ["Edit", "Client", "Server"],
3410
+ description: "Roblox Studio DataModel context (default 'Edit')"
3411
+ },
2944
3412
  studio_id: {
2945
3413
  type: "string",
2946
3414
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
2947
3415
  }
2948
3416
  },
2949
- required: ["script"],
2950
3417
  additionalProperties: false
2951
3418
  },
2952
3419
  annotations: {
@@ -2975,7 +3442,11 @@ var LOCAL_HYBRID_TOOLS = [
2975
3442
  },
2976
3443
  studio_root: {
2977
3444
  type: "string",
2978
- description: "Optional destination container in Studio (e.g. 'ServerStorage.LiveImports'; omit to mirror into matching services)"
3445
+ description: "Destination container path in Studio (e.g. 'ServerStorage.LiveImports', 'ReplicatedStorage.Debug.LiveScripts', or plain folder name under ServerStorage; default 'ServerStorage.LuawardLiveScripts')"
3446
+ },
3447
+ container_name: {
3448
+ type: "string",
3449
+ description: "Alias for studio_root destination path or folder name (default 'ServerStorage.LuawardLiveScripts')"
2979
3450
  },
2980
3451
  max: {
2981
3452
  type: "integer",
@@ -2983,10 +3454,25 @@ var LOCAL_HYBRID_TOOLS = [
2983
3454
  maximum: 100,
2984
3455
  description: "Maximum scripts to import in one call (default 15)"
2985
3456
  },
3457
+ limit: {
3458
+ type: "integer",
3459
+ minimum: 1,
3460
+ maximum: 100,
3461
+ description: "Alias for max (default 15)"
3462
+ },
2986
3463
  disabled: {
2987
3464
  type: "boolean",
2988
3465
  description: "Set .Disabled = true on imported LocalScripts in Studio (default true)"
2989
3466
  },
3467
+ include_decompiled: {
3468
+ type: "boolean",
3469
+ description: "Decompile script source via decompile() in the live executor (default true)"
3470
+ },
3471
+ datamodel_type: {
3472
+ type: "string",
3473
+ enum: ["Edit", "Client", "Server"],
3474
+ description: "Roblox Studio DataModel context (default 'Edit')"
3475
+ },
2990
3476
  studio_id: {
2991
3477
  type: "string",
2992
3478
  description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
@@ -3033,6 +3519,18 @@ var LOCAL_HYBRID_TOOLS = [
3033
3519
  focus_first: {
3034
3520
  type: "boolean",
3035
3521
  description: "Focus each window before capturing (default false)"
3522
+ },
3523
+ include_images: {
3524
+ type: "boolean",
3525
+ description: "Include both PNG images side by side in the response (default true)"
3526
+ },
3527
+ base64_a: {
3528
+ type: "string",
3529
+ description: "Optional pre-captured PNG base64 string for image A instead of capturing target_a"
3530
+ },
3531
+ base64_b: {
3532
+ type: "string",
3533
+ description: "Optional pre-captured PNG base64 string for image B instead of capturing target_b"
3036
3534
  }
3037
3535
  },
3038
3536
  additionalProperties: false
@@ -3056,6 +3554,7 @@ var HybridMcpBridge = class {
3056
3554
  autoInjectPollMs;
3057
3555
  autoInjectMaxPolls;
3058
3556
  autoInjectCooldownMs;
3557
+ verifyDelayMs;
3059
3558
  fetchFn;
3060
3559
  stderr;
3061
3560
  cachedPairCommand;
@@ -3076,6 +3575,7 @@ var HybridMcpBridge = class {
3076
3575
  this.autoInjectPollMs = options.autoInjectPollMs ?? 400;
3077
3576
  this.autoInjectMaxPolls = options.autoInjectMaxPolls ?? 15;
3078
3577
  this.autoInjectCooldownMs = options.autoInjectCooldownMs ?? 3e4;
3578
+ this.verifyDelayMs = options.verifyDelayMs ?? 120;
3079
3579
  this.potassium = options.potassiumClient ?? new PotassiumClient({
3080
3580
  url: options.potassiumUrl ?? resolved.potassiumUrl,
3081
3581
  token: options.potassiumToken !== void 0 ? options.potassiumToken : resolved.potassiumToken,
@@ -3716,7 +4216,7 @@ ${lines.join("\n")}` }]
3716
4216
  };
3717
4217
  }
3718
4218
  const lookupCode = [
3719
- `local inst, err = lw.resolve(${JSON.stringify(target)})`,
4219
+ `local inst, err = lw.resolve(${toLuauLiteral(target)})`,
3720
4220
  "if not inst then error(err or 'target not found') end",
3721
4221
  "local pos, size = inst.AbsolutePosition, inst.AbsoluteSize",
3722
4222
  "if not (pos and size) then error(lw.path(inst) .. ' has no AbsolutePosition/AbsoluteSize') end",
@@ -3769,8 +4269,8 @@ ${lines.join("\n")}` }]
3769
4269
  const vpX = vpXMatch ? Number(vpXMatch[1]) : 0;
3770
4270
  const vpY = vpYMatch ? Number(vpYMatch[1]) : 0;
3771
4271
  const resolvedPath = pathMatch?.[1] ?? target;
3772
- const focusRes = await this.windows.focusWindow("roblox");
3773
- if (!focusRes.ok || !focusRes.window) {
4272
+ let focusRes = await this.windows.focusWindow("roblox");
4273
+ if (!focusRes.window) {
3774
4274
  return {
3775
4275
  content: [
3776
4276
  { type: "text", text: `os_click could not find Roblox window: ${focusRes.err ?? "not found"}` }
@@ -3783,6 +4283,40 @@ ${lines.join("\n")}` }]
3783
4283
  const scaleY = vpY > 0 && cr.height > 0 ? cr.height / vpY : 1;
3784
4284
  const screenX = Math.round(cr.screenLeft + clientX * scaleX);
3785
4285
  const screenY = Math.round(cr.screenTop + clientY * scaleY);
4286
+ const checkWindowReady = async (res) => {
4287
+ if (!res.ok || !res.window) {
4288
+ return { ready: false, fgProcess: res.fgProcess };
4289
+ }
4290
+ if (this.windows.isWindowTopAtPoint && res.isTopAtPoint === void 0) {
4291
+ const pt = await this.windows.isWindowTopAtPoint(res.window.hwnd, screenX, screenY);
4292
+ return { ready: pt.isTop || pt.isForeground, fgProcess: pt.fgProcess ?? res.fgProcess };
4293
+ }
4294
+ if (res.isTopAtPoint !== void 0 || res.isForeground !== void 0) {
4295
+ return {
4296
+ ready: Boolean(res.isTopAtPoint || res.isForeground),
4297
+ fgProcess: res.fgProcess
4298
+ };
4299
+ }
4300
+ return { ready: Boolean(res.window.isForeground), fgProcess: res.fgProcess };
4301
+ };
4302
+ let readiness = await checkWindowReady(focusRes);
4303
+ if (!readiness.ready) {
4304
+ focusRes = await this.windows.focusWindow("roblox", { verifyPoint: { x: screenX, y: screenY } });
4305
+ readiness = await checkWindowReady(focusRes);
4306
+ }
4307
+ if (!readiness.ready) {
4308
+ const fgDesc = readiness.fgProcess ? ` (current foreground process: "${readiness.fgProcess}")` : "";
4309
+ const errDetail = focusRes.err ? ` (${focusRes.err})` : "";
4310
+ return {
4311
+ content: [
4312
+ {
4313
+ type: "text",
4314
+ 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.`
4315
+ }
4316
+ ],
4317
+ isError: true
4318
+ };
4319
+ }
3786
4320
  const mouseAction = args.double_click === true ? "double_click" : args.button === "right" ? "right_click" : "click";
3787
4321
  const session = typeof args.session === "string" ? args.session : void 0;
3788
4322
  const shouldVerify = args.verify === true;
@@ -3845,6 +4379,9 @@ ${verifyText}`;
3845
4379
  return out.join("\n");
3846
4380
  }
3847
4381
  async verifyMouseActionInGame(beforeSnap, session) {
4382
+ if (this.verifyDelayMs > 0) {
4383
+ await sleep(this.verifyDelayMs);
4384
+ }
3848
4385
  const lines = ["Verification:"];
3849
4386
  try {
3850
4387
  const mouseCode = [
@@ -3877,7 +4414,7 @@ ${verifyText}`;
3877
4414
  }
3878
4415
  try {
3879
4416
  const snapRes = await this.callCloudTool("gui_snapshot", {
3880
- diff_from: "latest",
4417
+ diff_from: "last",
3881
4418
  ...session ? { session } : {}
3882
4419
  });
3883
4420
  if (snapRes.ok) {
@@ -3892,63 +4429,243 @@ ${diffSummary}`);
3892
4429
  }
3893
4430
  return lines.join("\n");
3894
4431
  }
3895
- extractJsonPayloadFromExec(rawText) {
3896
- const trimmed = rawText.trim();
3897
- if (!trimmed) return null;
3898
- const candidates = [trimmed];
3899
- if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
3900
- try {
3901
- const unquoted = JSON.parse(trimmed);
3902
- if (typeof unquoted === "string") candidates.unshift(unquoted);
3903
- } catch {
4432
+ async execWithFullOutput(args) {
4433
+ let firstRes = await this.callCloudTool("exec", args);
4434
+ if (this.autoInject && firstRes.isError && firstRes.text.includes("no game is connected")) {
4435
+ const inj = await this.tryZeroTouchAutoInject();
4436
+ if (inj.injected) {
4437
+ firstRes = await this.callCloudTool("exec", args);
4438
+ } else {
4439
+ firstRes = {
4440
+ ...firstRes,
4441
+ text: `${firstRes.text}
4442
+ [Zero-Touch Auto-Inject failed: ${inj.text}]`
4443
+ };
3904
4444
  }
3905
4445
  }
3906
- const firstBracket = trimmed.search(/[\[{]/);
3907
- const lastBracket = Math.max(trimmed.lastIndexOf("]"), trimmed.lastIndexOf("}"));
3908
- if (firstBracket >= 0 && lastBracket > firstBracket) {
3909
- candidates.push(trimmed.slice(firstBracket, lastBracket + 1));
4446
+ if (!firstRes.ok) {
4447
+ return {
4448
+ ok: false,
4449
+ text: firstRes.text,
4450
+ fullBody: "",
4451
+ pages: 1,
4452
+ truncated: false,
4453
+ isError: true
4454
+ };
3910
4455
  }
3911
- for (const c of candidates) {
3912
- try {
3913
- return JSON.parse(c);
3914
- } catch {
4456
+ const firstEnv = stripExecPageEnvelope(firstRes.text);
4457
+ let assembled = firstEnv.body;
4458
+ let pages = 1;
4459
+ let truncated = firstEnv.agentTruncated;
4460
+ let hasMore = firstEnv.hasMore;
4461
+ let nextCmd = firstEnv.cmdId;
4462
+ let nextOffset = firstEnv.nextOffset;
4463
+ const session = typeof args.session === "string" && args.session.trim() ? args.session.trim() : void 0;
4464
+ while (hasMore && nextCmd && nextOffset !== void 0 && pages < CLOUD_RESULT_PAGE_MAX_CHUNKS) {
4465
+ const pageRes = await this.callCloudTool("get_result", {
4466
+ cmd: nextCmd,
4467
+ offset: nextOffset,
4468
+ limit: CLOUD_RESULT_PAGE_LIMIT,
4469
+ ...session ? { session } : {}
4470
+ });
4471
+ if (!pageRes.ok) {
4472
+ return {
4473
+ ok: false,
4474
+ text: `get_result pagination failed at offset ${nextOffset} (cmd=${nextCmd}): ${pageRes.text}`,
4475
+ fullBody: assembled,
4476
+ pages,
4477
+ truncated: true,
4478
+ isError: true
4479
+ };
4480
+ }
4481
+ const env = stripExecPageEnvelope(pageRes.text);
4482
+ if (env.agentTruncated) truncated = true;
4483
+ if (env.body.length === 0) {
4484
+ truncated = true;
4485
+ break;
4486
+ }
4487
+ assembled += env.body;
4488
+ pages += 1;
4489
+ hasMore = env.hasMore;
4490
+ const next = env.nextOffset;
4491
+ if (env.cmdId) nextCmd = env.cmdId;
4492
+ if (hasMore && (next === void 0 || next <= nextOffset)) {
4493
+ truncated = true;
4494
+ break;
3915
4495
  }
4496
+ nextOffset = next;
3916
4497
  }
3917
- return null;
4498
+ if (hasMore) {
4499
+ truncated = true;
4500
+ }
4501
+ return {
4502
+ ok: true,
4503
+ text: firstRes.text,
4504
+ fullBody: assembled,
4505
+ pages,
4506
+ truncated,
4507
+ isError: false
4508
+ };
4509
+ }
4510
+ formatJsonParseError(toolName, sourceLabel, rawBody, pages = 1, truncated = false) {
4511
+ const excerpt = rawBody.trim().slice(0, 320);
4512
+ return {
4513
+ content: [
4514
+ {
4515
+ type: "text",
4516
+ text: `${toolName} failed to parse JSON from ${sourceLabel} (pages=${pages}, truncated=${truncated}, length=${rawBody.length}): ${excerpt || "(empty response)"}`
4517
+ }
4518
+ ],
4519
+ isError: true
4520
+ };
4521
+ }
4522
+ extractJsonPayloadFromExec(rawText) {
4523
+ return extractJsonPayloadFromExec(rawText);
4524
+ }
4525
+ parseStudioDataModelType(raw) {
4526
+ if (raw === "Client" || raw === "Server" || raw === "Edit") {
4527
+ return raw;
4528
+ }
4529
+ return "Edit";
3918
4530
  }
3919
4531
  async handleStudioMirrorRemotes(args) {
3920
- const roots = Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "Workspace"];
3921
- const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(12, args.max_depth)) : 6;
4532
+ const singleRoot = typeof args.root === "string" && args.root.trim() ? args.root.trim() : "";
4533
+ const roots = singleRoot ? [singleRoot] : Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "Workspace"];
4534
+ const filter = typeof args.filter === "string" ? args.filter.trim().toLowerCase() : "";
4535
+ const kind = args.kind === "all" || args.kind === "bindable" || args.kind === "network" ? args.kind : "network";
4536
+ const max = typeof args.max === "number" ? Math.max(1, Math.min(500, Math.floor(args.max))) : 200;
4537
+ const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(12, Math.floor(args.max_depth))) : 6;
3922
4538
  const clearExisting = args.clear_existing === true;
4539
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
3923
4540
  const session = typeof args.session === "string" ? args.session : void 0;
3924
4541
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4542
+ const remoteClassesMap = kind === "network" ? { RemoteEvent: true, RemoteFunction: true, UnreliableRemoteEvent: true } : kind === "bindable" ? { BindableEvent: true, BindableFunction: true } : {
4543
+ RemoteEvent: true,
4544
+ RemoteFunction: true,
4545
+ UnreliableRemoteEvent: true,
4546
+ BindableEvent: true,
4547
+ BindableFunction: true
4548
+ };
4549
+ const netPriorityMap = {
4550
+ RemoteEvent: true,
4551
+ RemoteFunction: true,
4552
+ UnreliableRemoteEvent: true
4553
+ };
4554
+ const lowPriorityFolders = {
4555
+ assets: true,
4556
+ models: true,
4557
+ characters: true,
4558
+ animations: true,
4559
+ sounds: true,
4560
+ meshes: true,
4561
+ effects: true,
4562
+ vfx: true,
4563
+ particles: true,
4564
+ clientguis: true,
4565
+ stories: true,
4566
+ dialogues: true
4567
+ };
3925
4568
  const liveScanCode = [
3926
4569
  "local HttpService = game:GetService('HttpService')",
3927
- `local roots = ${JSON.stringify(roots)}`,
3928
- `local maxDepth = ${maxDepth}`,
3929
- "local remoteClasses = { RemoteEvent = true, RemoteFunction = true, UnreliableRemoteEvent = true, BindableEvent = true, BindableFunction = true }",
3930
- "local items = {}",
3931
- "local function scan(inst, rootName, segs, depth)",
3932
- " if depth > maxDepth then return end",
3933
- " for _, child in ipairs(inst:GetChildren()) do",
3934
- " local nextSegs = {}",
3935
- " for i = 1, #segs do nextSegs[i] = segs[i] end",
3936
- " nextSegs[#nextSegs + 1] = child.Name",
3937
- " if remoteClasses[child.ClassName] then",
3938
- " items[#items + 1] = { root = rootName, className = child.ClassName, segments = nextSegs, path = rootName .. '.' .. table.concat(nextSegs, '.') }",
3939
- " end",
3940
- " if #child:GetChildren() > 0 then",
3941
- " scan(child, rootName, nextSegs, depth + 1)",
4570
+ `local roots = ${toLuauLiteral(roots)}`,
4571
+ `local filter = ${toLuauLiteral(filter)}`,
4572
+ `local maxItems = ${toLuauLiteral(max)}`,
4573
+ `local maxDepth = ${toLuauLiteral(maxDepth)}`,
4574
+ `local kindMode = ${toLuauLiteral(kind)}`,
4575
+ `local remoteClasses = ${toLuauLiteral(remoteClassesMap)}`,
4576
+ `local netPriorityClasses = ${toLuauLiteral(netPriorityMap)}`,
4577
+ `local lowPriorityFolders = ${toLuauLiteral(lowPriorityFolders)}`,
4578
+ "local netItems = {}",
4579
+ "local otherItems = {}",
4580
+ "local function resolveRoot(rPath)",
4581
+ " local segs = {}",
4582
+ " for seg in string.gmatch(rPath, '[^%.]+') do segs[#segs + 1] = seg end",
4583
+ " if #segs == 0 then return nil, nil, nil end",
4584
+ " local startIdx = (segs[1] == 'game') and 2 or 1",
4585
+ " local rootName = segs[startIdx]",
4586
+ " if not rootName then return nil, nil, nil end",
4587
+ " local ok, cur = pcall(function() return game:GetService(rootName) end)",
4588
+ " if not ok or not cur then return nil, nil, nil end",
4589
+ " local baseSegs = {}",
4590
+ " for i = startIdx + 1, #segs do",
4591
+ " cur = cur and cur:FindFirstChild(segs[i])",
4592
+ " baseSegs[#baseSegs + 1] = segs[i]",
4593
+ " end",
4594
+ " return cur, rootName, baseSegs",
4595
+ "end",
4596
+ "local normalQ = {}",
4597
+ "local lowQ = {}",
4598
+ "local nHead, lHead = 1, 1",
4599
+ "local visited = 0",
4600
+ "local maxVisited = 6000",
4601
+ "for _, rPath in ipairs(roots) do",
4602
+ " local inst, rootName, baseSegs = resolveRoot(rPath)",
4603
+ " if inst and rootName and baseSegs then",
4604
+ " normalQ[#normalQ + 1] = { inst = inst, rootName = rootName, segs = baseSegs, depth = 1 }",
4605
+ " end",
4606
+ "end",
4607
+ "local function nextNode()",
4608
+ " if nHead <= #normalQ then",
4609
+ " local n = normalQ[nHead]",
4610
+ " normalQ[nHead] = nil",
4611
+ " nHead = nHead + 1",
4612
+ " return n",
4613
+ " end",
4614
+ " if lHead <= #lowQ then",
4615
+ " local n = lowQ[lHead]",
4616
+ " lowQ[lHead] = nil",
4617
+ " lHead = lHead + 1",
4618
+ " return n",
4619
+ " end",
4620
+ " return nil",
4621
+ "end",
4622
+ "while visited < maxVisited do",
4623
+ " if kindMode == 'network' and #netItems >= maxItems then break end",
4624
+ " if kindMode == 'bindable' and #otherItems >= maxItems then break end",
4625
+ " if kindMode == 'all' and #netItems >= maxItems then break end",
4626
+ " local node = nextNode()",
4627
+ " if not node then break end",
4628
+ " if node.depth <= maxDepth then",
4629
+ " for _, child in ipairs(node.inst:GetChildren()) do",
4630
+ " visited = visited + 1",
4631
+ " if visited > maxVisited then break end",
4632
+ " local nextSegs = {}",
4633
+ " for i = 1, #node.segs do nextSegs[i] = node.segs[i] end",
4634
+ " nextSegs[#nextSegs + 1] = child.Name",
4635
+ " local fullPath = node.rootName .. '.' .. table.concat(nextSegs, '.')",
4636
+ " if remoteClasses[child.ClassName] then",
4637
+ " if filter == '' or string.find(string.lower(fullPath), filter, 1, true) then",
4638
+ " local rec = { root = node.rootName, className = child.ClassName, segments = nextSegs, path = fullPath }",
4639
+ " if netPriorityClasses[child.ClassName] then",
4640
+ " netItems[#netItems + 1] = rec",
4641
+ " else",
4642
+ " otherItems[#otherItems + 1] = rec",
4643
+ " end",
4644
+ " end",
4645
+ " end",
4646
+ " if kindMode == 'network' and #netItems >= maxItems then break end",
4647
+ " if kindMode == 'bindable' and #otherItems >= maxItems then break end",
4648
+ " if kindMode == 'all' and #netItems >= maxItems then break end",
4649
+ " if node.depth < maxDepth and #child:GetChildren() > 0 then",
4650
+ " local isLow = child:IsA('Model') or (lowPriorityFolders[string.lower(child.Name)] == true)",
4651
+ " local q = isLow and lowQ or normalQ",
4652
+ " q[#q + 1] = { inst = child, rootName = node.rootName, segs = nextSegs, depth = node.depth + 1 }",
4653
+ " end",
3942
4654
  " end",
3943
4655
  " end",
3944
4656
  "end",
3945
- "for _, rName in ipairs(roots) do",
3946
- " local ok, svc = pcall(function() return game:GetService(rName) end)",
3947
- " if ok and svc then scan(svc, rName, {}, 1) end",
4657
+ "local items = {}",
4658
+ "for _, rec in ipairs(netItems) do",
4659
+ " if #items >= maxItems then break end",
4660
+ " items[#items + 1] = rec",
4661
+ "end",
4662
+ "for _, rec in ipairs(otherItems) do",
4663
+ " if #items >= maxItems then break end",
4664
+ " items[#items + 1] = rec",
3948
4665
  "end",
3949
4666
  "return HttpService:JSONEncode(items)"
3950
4667
  ].join("\n");
3951
- const liveRes = await this.callCloudTool("exec", {
4668
+ const liveRes = await this.execWithFullOutput({
3952
4669
  code: liveScanCode,
3953
4670
  readonly: true,
3954
4671
  ...session ? { session } : {}
@@ -3959,11 +4676,21 @@ ${diffSummary}`);
3959
4676
  isError: true
3960
4677
  };
3961
4678
  }
3962
- const items = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
4679
+ const items = this.extractJsonPayloadFromExec(
4680
+ liveRes.fullBody
4681
+ );
4682
+ if (!Array.isArray(items)) {
4683
+ return this.formatJsonParseError(
4684
+ "studio_mirror_remotes",
4685
+ "live game remotes scan",
4686
+ liveRes.fullBody,
4687
+ liveRes.pages,
4688
+ liveRes.truncated
4689
+ );
4690
+ }
3963
4691
  const studioCode = [
3964
- "local HttpService = game:GetService('HttpService')",
3965
- `local items = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(items))})`,
3966
- `local clearExisting = ${clearExisting ? "true" : "false"}`,
4692
+ `local items = ${toLuauLiteral(items)}`,
4693
+ `local clearExisting = ${toLuauLiteral(clearExisting)}`,
3967
4694
  "local created, existing = 0, 0",
3968
4695
  "for _, item in ipairs(items) do",
3969
4696
  " local ok, rootInst = pcall(function() return game:GetService(item.root) end)",
@@ -4001,7 +4728,7 @@ ${diffSummary}`);
4001
4728
  "end",
4002
4729
  "return string.format('mirrored %d remotes (created=%d, existing=%d)', #items, created, existing)"
4003
4730
  ].join("\n");
4004
- const studioRes = await this.studio.runStudioLuau(studioCode, requestedStudioId);
4731
+ const studioRes = await this.studio.runStudioLuau(studioCode, requestedStudioId, datamodelType);
4005
4732
  if (!studioRes.ok) {
4006
4733
  return {
4007
4734
  content: [
@@ -4014,14 +4741,24 @@ ${diffSummary}`);
4014
4741
  };
4015
4742
  }
4016
4743
  const samplePaths = items.slice(0, 15).map((i) => ` - [${i.className}] ${i.path}`);
4744
+ const warnings = [];
4745
+ if (items.length >= max || liveRes.truncated) {
4746
+ warnings.push(
4747
+ `- Note: output reached limit (max=${max}${liveRes.truncated ? ", truncated" : ""}); pass filter/root or raise max to mirror more.`
4748
+ );
4749
+ }
4750
+ if (liveRes.pages > 1) {
4751
+ warnings.push(`- Pagination: reassembled ${liveRes.pages} pages from Cloud exec/get_result`);
4752
+ }
4017
4753
  return {
4018
4754
  content: [
4019
4755
  {
4020
4756
  type: "text",
4021
4757
  text: [
4022
- `studio_mirror_remotes complete (studio_id=${studioRes.studioId ?? "auto"}):`,
4023
- `- Live remotes discovered: ${items.length} across ${roots.join(", ")}`,
4758
+ `studio_mirror_remotes complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4759
+ `- Live remotes discovered: ${items.length} across ${roots.join(", ")} (kind=${kind}${filter ? `, filter="${filter}"` : ""}, max=${max})`,
4024
4760
  `- Studio result: ${studioRes.text}`,
4761
+ ...warnings,
4025
4762
  ...samplePaths.length > 0 ? ["- Sample mirrored paths:", ...samplePaths] : []
4026
4763
  ].join("\n")
4027
4764
  }
@@ -4029,25 +4766,39 @@ ${diffSummary}`);
4029
4766
  };
4030
4767
  }
4031
4768
  async handleStudioMirrorGui(args) {
4032
- const targetPath = typeof args.target_path === "string" ? args.target_path.trim() : "";
4033
- const containerName = typeof args.container_name === "string" && args.container_name.trim() ? args.container_name.trim() : "LuawardMirroredGui";
4034
- const maxNodes = typeof args.max_nodes === "number" ? Math.max(10, Math.min(1e3, args.max_nodes)) : 250;
4769
+ 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() : "";
4770
+ const targetPath = rawTarget === "Players.LocalPlayer.PlayerGui" || rawTarget === "PlayerGui" ? "" : rawTarget;
4771
+ 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";
4772
+ const containerName = rawContainer === "StarterGui" ? "LuawardMirroredGui" : rawContainer.replace(/^StarterGui\./, "") || "LuawardMirroredGui";
4773
+ const maxDepth = typeof args.depth === "number" ? Math.max(1, Math.min(12, Math.floor(args.depth))) : 10;
4774
+ const rawMaxNodes = typeof args.max_nodes === "number" ? args.max_nodes : typeof args.max_instances === "number" ? args.max_instances : 250;
4775
+ const maxNodes = Math.max(1, Math.min(1e3, Math.floor(rawMaxNodes)));
4776
+ const onlyVisible = args.only_visible === true;
4035
4777
  const includeCoreGui = args.include_core_gui === true;
4778
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4036
4779
  const session = typeof args.session === "string" ? args.session : void 0;
4037
4780
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4038
4781
  const liveGuiCode = [
4039
4782
  "local HttpService = game:GetService('HttpService')",
4040
4783
  "local Players = game:GetService('Players')",
4041
- `local targetPath = ${JSON.stringify(targetPath)}`,
4042
- `local maxNodes = ${maxNodes}`,
4043
- `local includeCore = ${includeCoreGui ? "true" : "false"}`,
4784
+ `local targetPath = ${toLuauLiteral(targetPath)}`,
4785
+ `local maxNodes = ${toLuauLiteral(maxNodes)}`,
4786
+ `local maxDepth = ${toLuauLiteral(maxDepth)}`,
4787
+ `local onlyVisible = ${toLuauLiteral(onlyVisible)}`,
4788
+ `local includeCore = ${toLuauLiteral(includeCoreGui)}`,
4044
4789
  "local nodes = {}",
4045
4790
  "local count = 0",
4791
+ "local capped = false",
4046
4792
  "local function serColor(c) return c and { c.R, c.G, c.B } or nil end",
4047
4793
  "local function serUDim2(u) return u and { u.X.Scale, u.X.Offset, u.Y.Scale, u.Y.Offset } or nil end",
4048
4794
  "local function serVec2(v) return v and { v.X, v.Y } or nil end",
4049
4795
  "local function serializeTree(inst, depth)",
4050
- " if count >= maxNodes or depth > 10 then return nil end",
4796
+ " if count >= maxNodes then capped = true; return nil end",
4797
+ " if depth > maxDepth then return nil end",
4798
+ " if onlyVisible then",
4799
+ " if inst:IsA('LayerCollector') and inst.Enabled == false then return nil end",
4800
+ " if inst:IsA('GuiObject') and inst.Visible == false then return nil end",
4801
+ " end",
4051
4802
  " count = count + 1",
4052
4803
  " local node = { className = inst.ClassName, name = inst.Name, children = {} }",
4053
4804
  " pcall(function()",
@@ -4072,7 +4823,7 @@ ${diffSummary}`);
4072
4823
  " end",
4073
4824
  " end)",
4074
4825
  " for _, child in ipairs(inst:GetChildren()) do",
4075
- " if count >= maxNodes then break end",
4826
+ " if count >= maxNodes then capped = true; break end",
4076
4827
  " local cNode = serializeTree(child, depth + 1)",
4077
4828
  " if cNode then node.children[#node.children + 1] = cNode end",
4078
4829
  " end",
@@ -4080,13 +4831,16 @@ ${diffSummary}`);
4080
4831
  "end",
4081
4832
  "if targetPath ~= '' and lw and lw.resolve then",
4082
4833
  " local inst = lw.resolve(targetPath)",
4083
- " if inst then nodes[#nodes + 1] = serializeTree(inst, 1) end",
4834
+ " if inst then",
4835
+ " local n = serializeTree(inst, 1)",
4836
+ " if n then nodes[#nodes + 1] = n end",
4837
+ " end",
4084
4838
  "else",
4085
4839
  " local lp = Players.LocalPlayer",
4086
4840
  " local pgui = lp and lp:FindFirstChildOfClass('PlayerGui')",
4087
4841
  " if pgui then",
4088
4842
  " for _, child in ipairs(pgui:GetChildren()) do",
4089
- " if count >= maxNodes then break end",
4843
+ " if count >= maxNodes then capped = true; break end",
4090
4844
  " local n = serializeTree(child, 1)",
4091
4845
  " if n then nodes[#nodes + 1] = n end",
4092
4846
  " end",
@@ -4095,7 +4849,7 @@ ${diffSummary}`);
4095
4849
  " local ok, cgui = pcall(function() return game:GetService('CoreGui') end)",
4096
4850
  " if ok and cgui then",
4097
4851
  " for _, child in ipairs(cgui:GetChildren()) do",
4098
- " if count >= maxNodes then break end",
4852
+ " if count >= maxNodes then capped = true; break end",
4099
4853
  " if child.Name ~= 'RobloxGui' then",
4100
4854
  " local n = serializeTree(child, 1)",
4101
4855
  " if n then nodes[#nodes + 1] = n end",
@@ -4104,9 +4858,9 @@ ${diffSummary}`);
4104
4858
  " end",
4105
4859
  " end",
4106
4860
  "end",
4107
- "return HttpService:JSONEncode({ count = count, trees = nodes })"
4861
+ "return HttpService:JSONEncode({ count = count, capped = capped, trees = nodes })"
4108
4862
  ].join("\n");
4109
- const liveRes = await this.callCloudTool("exec", {
4863
+ const liveRes = await this.execWithFullOutput({
4110
4864
  code: liveGuiCode,
4111
4865
  readonly: true,
4112
4866
  ...session ? { session } : {}
@@ -4117,15 +4871,20 @@ ${diffSummary}`);
4117
4871
  isError: true
4118
4872
  };
4119
4873
  }
4120
- const payload = this.extractJsonPayloadFromExec(liveRes.text) ?? {
4121
- count: 0,
4122
- trees: []
4123
- };
4874
+ const payload = this.extractJsonPayloadFromExec(liveRes.fullBody);
4875
+ if (!payload || typeof payload !== "object" || !Array.isArray(payload.trees)) {
4876
+ return this.formatJsonParseError(
4877
+ "studio_mirror_gui",
4878
+ "live GUI serialization",
4879
+ liveRes.fullBody,
4880
+ liveRes.pages,
4881
+ liveRes.truncated
4882
+ );
4883
+ }
4124
4884
  const studioBuildCode = [
4125
- "local HttpService = game:GetService('HttpService')",
4126
4885
  "local StarterGui = game:GetService('StarterGui')",
4127
- `local containerName = ${JSON.stringify(containerName)}`,
4128
- `local payload = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(payload))})`,
4886
+ `local containerName = ${toLuauLiteral(containerName)}`,
4887
+ `local payload = ${toLuauLiteral(payload)}`,
4129
4888
  "local folder = StarterGui:FindFirstChild(containerName)",
4130
4889
  "if folder then folder:Destroy() end",
4131
4890
  "folder = Instance.new('Folder')",
@@ -4168,7 +4927,7 @@ ${diffSummary}`);
4168
4927
  "for _, tree in ipairs(payload.trees or {}) do buildNode(tree, folder) end",
4169
4928
  "return string.format('mirrored %d GUI nodes into StarterGui.%s', created, containerName)"
4170
4929
  ].join("\n");
4171
- const studioRes = await this.studio.runStudioLuau(studioBuildCode, requestedStudioId);
4930
+ const studioRes = await this.studio.runStudioLuau(studioBuildCode, requestedStudioId, datamodelType);
4172
4931
  if (!studioRes.ok) {
4173
4932
  return {
4174
4933
  content: [
@@ -4180,32 +4939,44 @@ ${diffSummary}`);
4180
4939
  isError: true
4181
4940
  };
4182
4941
  }
4942
+ const notes = [];
4943
+ if (payload.capped || payload.count >= maxNodes || liveRes.truncated) {
4944
+ notes.push(
4945
+ `- Note: capture reached limit (max_nodes=${maxNodes}${liveRes.truncated ? ", truncated" : ""}); pass target/only_visible=true or raise max_nodes for deeper trees.`
4946
+ );
4947
+ }
4948
+ if (liveRes.pages > 1) {
4949
+ notes.push(`- Pagination: reassembled ${liveRes.pages} pages from Cloud exec/get_result`);
4950
+ }
4183
4951
  return {
4184
4952
  content: [
4185
4953
  {
4186
4954
  type: "text",
4187
4955
  text: [
4188
- `studio_mirror_gui complete (studio_id=${studioRes.studioId ?? "auto"}):`,
4956
+ `studio_mirror_gui complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4189
4957
  `- Live GUI nodes serialized: ${payload.count} (${payload.trees.length} root trees)`,
4190
4958
  `- Studio container: StarterGui.${containerName}`,
4191
- `- Studio result: ${studioRes.text}`
4959
+ `- Studio result: ${studioRes.text}`,
4960
+ ...notes
4192
4961
  ].join("\n")
4193
4962
  }
4194
4963
  ]
4195
4964
  };
4196
4965
  }
4197
4966
  async handleStudioDiff(args) {
4198
- const roots = Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "StarterGui", "Workspace"];
4967
+ const singleTarget = typeof args.target === "string" && args.target.trim() ? args.target.trim() : "";
4968
+ const roots = singleTarget ? [singleTarget] : Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "StarterGui", "Workspace"];
4199
4969
  const scope = typeof args.scope === "string" ? args.scope : "all";
4200
4970
  const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(10, args.max_depth)) : 5;
4971
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4201
4972
  const session = typeof args.session === "string" ? args.session : void 0;
4202
4973
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4203
4974
  const buildDiffScanCode = (isLive) => [
4204
4975
  "local HttpService = game:GetService('HttpService')",
4205
- `local roots = ${JSON.stringify(roots)}`,
4206
- `local scope = ${JSON.stringify(scope)}`,
4207
- `local maxDepth = ${maxDepth}`,
4208
- `local isLive = ${isLive ? "true" : "false"}`,
4976
+ `local roots = ${toLuauLiteral(roots)}`,
4977
+ `local scope = ${toLuauLiteral(scope)}`,
4978
+ `local maxDepth = ${toLuauLiteral(maxDepth)}`,
4979
+ `local isLive = ${toLuauLiteral(isLive)}`,
4209
4980
  "local entries = {}",
4210
4981
  "local count = 0",
4211
4982
  "local remoteClasses = { RemoteEvent = true, RemoteFunction = true, UnreliableRemoteEvent = true, BindableEvent = true, BindableFunction = true }",
@@ -4219,6 +4990,7 @@ ${diffSummary}`);
4219
4990
  "local function scan(inst, prefix, depth)",
4220
4991
  " if depth > maxDepth or count >= 1500 then return end",
4221
4992
  " for _, child in ipairs(inst:GetChildren()) do",
4993
+ " if count >= 1500 then break end",
4222
4994
  " local p = prefix .. '.' .. child.Name",
4223
4995
  " if matchesScope(child) then",
4224
4996
  " count = count + 1",
@@ -4240,12 +5012,12 @@ ${diffSummary}`);
4240
5012
  "return HttpService:JSONEncode(entries)"
4241
5013
  ].join("\n");
4242
5014
  const [liveRes, studioRes] = await Promise.all([
4243
- this.callCloudTool("exec", {
5015
+ this.execWithFullOutput({
4244
5016
  code: buildDiffScanCode(true),
4245
5017
  readonly: true,
4246
5018
  ...session ? { session } : {}
4247
5019
  }),
4248
- this.studio.runStudioLuau(buildDiffScanCode(false), requestedStudioId)
5020
+ this.studio.runStudioLuau(buildDiffScanCode(false), requestedStudioId, datamodelType)
4249
5021
  ]);
4250
5022
  if (!liveRes.ok) {
4251
5023
  return {
@@ -4259,8 +5031,20 @@ ${diffSummary}`);
4259
5031
  isError: true
4260
5032
  };
4261
5033
  }
4262
- const liveEntries = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
4263
- const studioEntries = this.extractJsonPayloadFromExec(studioRes.text) ?? [];
5034
+ const liveEntries = this.extractJsonPayloadFromExec(liveRes.fullBody);
5035
+ if (!Array.isArray(liveEntries)) {
5036
+ return this.formatJsonParseError(
5037
+ "studio_diff",
5038
+ "live game scan",
5039
+ liveRes.fullBody,
5040
+ liveRes.pages,
5041
+ liveRes.truncated
5042
+ );
5043
+ }
5044
+ const studioEntries = this.extractJsonPayloadFromExec(studioRes.text);
5045
+ if (!Array.isArray(studioEntries)) {
5046
+ return this.formatJsonParseError("studio_diff", "Roblox Studio scan", studioRes.text, 1, false);
5047
+ }
4264
5048
  const liveMap = /* @__PURE__ */ new Map();
4265
5049
  for (const e of liveEntries) liveMap.set(e.path, e.className);
4266
5050
  const studioMap = /* @__PURE__ */ new Map();
@@ -4285,7 +5069,8 @@ ${diffSummary}`);
4285
5069
  }
4286
5070
  }
4287
5071
  const lines = [
4288
- `studio_diff report (scope=${scope}, roots=${roots.join(", ")}, studio_id=${studioRes.studioId ?? "auto"}):`,
5072
+ `studio_diff report (scope=${scope}, roots=${roots.join(", ")}, studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
5073
+ `- Scanned counts: live=${liveEntries.length}, studio=${studioEntries.length}${liveRes.pages > 1 ? ` (live pages=${liveRes.pages})` : ""}`,
4289
5074
  `- Matched instances: ${matchedCount}`,
4290
5075
  `- Only in Live Game: ${onlyInLive.length}`,
4291
5076
  ...onlyInLive.slice(0, 20).map((x) => ` + [Live] ${x}`),
@@ -4296,6 +5081,11 @@ ${diffSummary}`);
4296
5081
  `- Class mismatches: ${classMismatches.length}`,
4297
5082
  ...classMismatches.slice(0, 10).map((x) => ` ! ${x}`)
4298
5083
  ];
5084
+ if (liveEntries.length >= 1500 || studioEntries.length >= 1500 || liveRes.truncated) {
5085
+ lines.push(
5086
+ "- Note: scan hit 1500-entry limit or truncation; pass target/roots or narrow scope/max_depth for complete coverage."
5087
+ );
5088
+ }
4299
5089
  return {
4300
5090
  content: [{ type: "text", text: lines.join("\n") }]
4301
5091
  };
@@ -4303,15 +5093,22 @@ ${diffSummary}`);
4303
5093
  buildStudioReadScriptSourceCode(studioPath) {
4304
5094
  return [
4305
5095
  "local HttpService = game:GetService('HttpService')",
4306
- `local pathStr = ${JSON.stringify(studioPath)}`,
4307
- "local segs = {}",
4308
- "for seg in string.gmatch(pathStr, '[^%.]+') do segs[#segs + 1] = seg end",
4309
- "if #segs == 0 then error('Empty studio_path') end",
4310
- "local startIdx = 1",
4311
- "if segs[1] == 'game' then startIdx = 2 end",
4312
- "local cur = game:GetService(segs[startIdx])",
4313
- "for i = startIdx + 1, #segs do",
4314
- " cur = cur and cur:FindFirstChild(segs[i])",
5096
+ `local pathStr = ${toLuauLiteral(studioPath)}`,
5097
+ "local cur = nil",
5098
+ "if pathStr == '' or pathStr == 'Selection' then",
5099
+ " local sel = game:GetService('Selection'):Get()",
5100
+ " cur = sel and sel[1] or nil",
5101
+ " if not cur then error('No script is currently selected in Roblox Studio Selection') end",
5102
+ "else",
5103
+ " local segs = {}",
5104
+ " for seg in string.gmatch(pathStr, '[^%.]+') do segs[#segs + 1] = seg end",
5105
+ " if #segs == 0 then error('Empty studio_path') end",
5106
+ " local startIdx = 1",
5107
+ " if segs[1] == 'game' then startIdx = 2 end",
5108
+ " cur = game:GetService(segs[startIdx])",
5109
+ " for i = startIdx + 1, #segs do",
5110
+ " cur = cur and cur:FindFirstChild(segs[i])",
5111
+ " end",
4315
5112
  "end",
4316
5113
  "if not cur then error('Studio instance not found: ' .. pathStr) end",
4317
5114
  "local ok, src = pcall(function() return cur.Source end)",
@@ -4320,24 +5117,20 @@ ${diffSummary}`);
4320
5117
  ].join("\n");
4321
5118
  }
4322
5119
  async handleStudioToLive(args) {
4323
- const studioPath = typeof args.studio_path === "string" ? args.studio_path.trim() : "";
4324
5120
  const directCode = typeof args.code === "string" ? args.code : "";
5121
+ const studioPath = typeof args.studio_path === "string" && args.studio_path.trim() ? args.studio_path.trim() : directCode.trim() ? "" : "Selection";
5122
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4325
5123
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4326
5124
  const session = typeof args.session === "string" ? args.session : void 0;
4327
5125
  const collect = args.collect !== false;
4328
- if (!studioPath && !directCode.trim()) {
4329
- return {
4330
- content: [{ type: "text", text: "studio_to_live requires either studio_path or code" }],
4331
- isError: true
4332
- };
4333
- }
4334
5126
  let codeToRun = directCode;
4335
5127
  let sourceLabel = "inline Studio snippet";
4336
5128
  let resolvedStudioId = requestedStudioId;
4337
5129
  if (studioPath) {
4338
5130
  const studioRes = await this.studio.runStudioLuau(
4339
5131
  this.buildStudioReadScriptSourceCode(studioPath),
4340
- requestedStudioId
5132
+ requestedStudioId,
5133
+ datamodelType
4341
5134
  );
4342
5135
  if (!studioRes.ok) {
4343
5136
  return {
@@ -4364,14 +5157,19 @@ ${diffSummary}`);
4364
5157
  };
4365
5158
  }
4366
5159
  codeToRun = parsed.source;
4367
- sourceLabel = `${parsed.path} [${parsed.className}] (${codeToRun.length} bytes, studio_id=${resolvedStudioId ?? "auto"})`;
5160
+ sourceLabel = `${parsed.path} [${parsed.className}] (${codeToRun.length} bytes, studio_id=${resolvedStudioId ?? "auto"}, datamodel_type=${datamodelType})`;
4368
5161
  }
4369
5162
  const cloudTool = collect ? "run_and_collect" : "exec";
5163
+ 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;
5164
+ 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;
4370
5165
  const cloudArgs = {
4371
5166
  code: codeToRun,
4372
5167
  ...collect ? {
4373
- wait_seconds: typeof args.wait_seconds === "number" ? args.wait_seconds : 1.5,
4374
- clean_env: typeof args.clean_env === "boolean" ? args.clean_env : true
5168
+ clean_env: typeof args.clean_env === "boolean" ? args.clean_env : true,
5169
+ ...resolvedTimeoutMs !== void 0 ? { timeout_ms: resolvedTimeoutMs } : {},
5170
+ ...resolvedSettleMs !== void 0 ? { settle_ms: resolvedSettleMs } : {},
5171
+ ...typeof args.track_resources === "boolean" ? { track_resources: args.track_resources } : {},
5172
+ ...typeof args.auto_cleanup === "boolean" ? { auto_cleanup: args.auto_cleanup } : {}
4375
5173
  } : {},
4376
5174
  ...session ? { session } : {}
4377
5175
  };
@@ -4388,17 +5186,13 @@ ${liveRes.text}`
4388
5186
  };
4389
5187
  }
4390
5188
  async handleStudioPublish(args) {
4391
- const studioPath = typeof args.studio_path === "string" ? args.studio_path.trim() : "";
4392
- if (!studioPath) {
4393
- return {
4394
- content: [{ type: "text", text: "studio_publish requires studio_path" }],
4395
- isError: true
4396
- };
4397
- }
5189
+ const studioPath = typeof args.studio_path === "string" && args.studio_path.trim() ? args.studio_path.trim() : "Selection";
5190
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4398
5191
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4399
5192
  const studioRes = await this.studio.runStudioLuau(
4400
5193
  this.buildStudioReadScriptSourceCode(studioPath),
4401
- requestedStudioId
5194
+ requestedStudioId,
5195
+ datamodelType
4402
5196
  );
4403
5197
  if (!studioRes.ok) {
4404
5198
  return {
@@ -4423,18 +5217,23 @@ ${liveRes.text}`
4423
5217
  isError: true
4424
5218
  };
4425
5219
  }
4426
- const scriptId = typeof args.script_id === "string" ? args.script_id.trim() : "";
4427
- if (scriptId) {
4428
- const deployRes = await this.callCloudTool("deploy_script", {
4429
- script_id: scriptId,
5220
+ 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() : "";
5221
+ if (scriptTarget) {
5222
+ const deployArgs = {
5223
+ script: scriptTarget,
4430
5224
  source: parsed.source,
4431
- ...typeof args.note === "string" ? { note: args.note } : {}
4432
- });
5225
+ ...typeof args.preset === "string" ? { preset: args.preset } : {},
5226
+ ...typeof args.publish === "boolean" ? { publish: args.publish } : {},
5227
+ ...typeof args.draft === "boolean" ? { draft: args.draft } : {},
5228
+ ...typeof args.store_source === "boolean" ? { store_source: args.store_source } : {},
5229
+ ...typeof args.wait === "number" && Number.isFinite(args.wait) ? { wait: Math.max(0, Math.min(60, Math.floor(args.wait))) } : {}
5230
+ };
5231
+ const deployRes = await this.callCloudTool("deploy_script", deployArgs);
4433
5232
  return {
4434
5233
  content: [
4435
5234
  {
4436
5235
  type: "text",
4437
- text: `studio_publish deployed ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}) to Luaward script ${scriptId}:
5236
+ text: `studio_publish deployed ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}) to Luaward script ${scriptTarget}:
4438
5237
  ${deployRes.text}`
4439
5238
  }
4440
5239
  ],
@@ -4442,16 +5241,20 @@ ${deployRes.text}`
4442
5241
  };
4443
5242
  }
4444
5243
  const scriptName = typeof args.name === "string" && args.name.trim() ? args.name.trim() : parsed.name || "StudioScript";
4445
- const createRes = await this.callCloudTool("create_script", {
5244
+ const createArgs = {
4446
5245
  name: scriptName,
4447
5246
  source: parsed.source,
4448
- ...typeof args.description === "string" ? { description: args.description } : {}
4449
- });
5247
+ ...typeof args.project_id === "string" && args.project_id.trim() ? { project_id: args.project_id.trim() } : {},
5248
+ ...typeof args.preset === "string" ? { preset: args.preset } : {},
5249
+ ...typeof args.store_source === "boolean" ? { store_source: args.store_source } : {},
5250
+ ...typeof args.wait === "number" && Number.isFinite(args.wait) ? { wait: Math.max(0, Math.min(60, Math.floor(args.wait))) } : {}
5251
+ };
5252
+ const createRes = await this.callCloudTool("create_script", createArgs);
4450
5253
  return {
4451
5254
  content: [
4452
5255
  {
4453
5256
  type: "text",
4454
- text: `studio_publish created Luaward script "${scriptName}" from ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}):
5257
+ text: `studio_publish created Luaward script "${scriptName}" from ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):
4455
5258
  ${createRes.text}`
4456
5259
  }
4457
5260
  ],
@@ -4459,40 +5262,59 @@ ${createRes.text}`
4459
5262
  };
4460
5263
  }
4461
5264
  async handleLiveScriptsToStudio(args) {
5265
+ const targets = Array.isArray(args.targets) && args.targets.length > 0 ? args.targets.map(String) : [];
4462
5266
  const filter = typeof args.filter === "string" ? args.filter.trim() : "";
4463
- const containerName = typeof args.container_name === "string" && args.container_name.trim() ? args.container_name.trim() : "LuawardLiveScripts";
4464
- const limit = typeof args.limit === "number" ? Math.max(1, Math.min(50, args.limit)) : 15;
5267
+ 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";
5268
+ const container = resolveStudioContainerPath(rawContainer, "ServerStorage", "LuawardLiveScripts");
5269
+ const rawLimit = typeof args.max === "number" ? args.max : typeof args.limit === "number" ? args.limit : 15;
5270
+ const limit = Math.max(1, Math.min(100, Math.floor(rawLimit)));
5271
+ const disabled = args.disabled !== false;
4465
5272
  const includeDecompiled = args.include_decompiled !== false;
5273
+ const datamodelType = this.parseStudioDataModelType(args.datamodel_type);
4466
5274
  const session = typeof args.session === "string" ? args.session : void 0;
4467
5275
  const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4468
5276
  const liveCollectCode = [
4469
5277
  "local HttpService = game:GetService('HttpService')",
4470
- `local filter = string.lower(${JSON.stringify(filter)})`,
4471
- `local limit = ${limit}`,
4472
- `local includeDecompiled = ${includeDecompiled ? "true" : "false"}`,
5278
+ `local targets = ${toLuauLiteral(targets)}`,
5279
+ `local filter = string.lower(${toLuauLiteral(filter)})`,
5280
+ `local limit = ${toLuauLiteral(limit)}`,
5281
+ `local includeDecompiled = ${toLuauLiteral(includeDecompiled)}`,
4473
5282
  "local roots = { game:GetService('ReplicatedStorage'), game:GetService('StarterPlayer'), game:GetService('Workspace'), game:GetService('Players').LocalPlayer }",
4474
5283
  "local results = {}",
4475
5284
  "local seen = {}",
5285
+ "local totalBytes = 0",
5286
+ "local maxTotalBytes = 600000",
4476
5287
  "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",
4477
- "for _, root in ipairs(roots) do",
4478
- " if root then",
4479
- " local ok, list = pcall(function() return root:GetDescendants() end)",
4480
- " if ok and type(list) == 'table' then",
4481
- " for _, inst in ipairs(list) do",
4482
- " if #results >= limit then break end",
4483
- " if not seen[inst] and (inst.ClassName == 'LocalScript' or inst.ClassName == 'ModuleScript') then",
4484
- " seen[inst] = true",
4485
- " local fullPath = inst:GetFullName()",
4486
- " if filter == '' or string.find(string.lower(fullPath), filter, 1, true) then",
4487
- " local src = '-- Live script: ' .. fullPath .. '\\n-- ClassName: ' .. inst.ClassName",
4488
- " if includeDecompiled and decompFn then",
4489
- " local okD, dec = pcall(decompFn, inst)",
4490
- " if okD and type(dec) == 'string' and #dec > 0 then",
4491
- " src = src .. '\\n\\n' .. dec:sub(1, 32000)",
4492
- " end",
4493
- " end",
4494
- " results[#results + 1] = { name = inst.Name, className = inst.ClassName, path = fullPath, source = src }",
4495
- " end",
5288
+ "local function collectOne(inst)",
5289
+ " if not inst or seen[inst] or #results >= limit then return end",
5290
+ " if inst.ClassName ~= 'LocalScript' and inst.ClassName ~= 'ModuleScript' then return end",
5291
+ " seen[inst] = true",
5292
+ " local fullPath = inst:GetFullName()",
5293
+ " if #targets == 0 and filter ~= '' and not string.find(string.lower(fullPath), filter, 1, true) then return end",
5294
+ " local src = '-- Live script: ' .. fullPath .. '\\n-- ClassName: ' .. inst.ClassName",
5295
+ " if includeDecompiled and decompFn then",
5296
+ " local okD, dec = pcall(decompFn, inst)",
5297
+ " if okD and type(dec) == 'string' and #dec > 0 then",
5298
+ " src = src .. '\\n\\n' .. dec:sub(1, 32000)",
5299
+ " end",
5300
+ " end",
5301
+ " if #results > 0 and (totalBytes + #src) > maxTotalBytes then return end",
5302
+ " totalBytes = totalBytes + #src",
5303
+ " results[#results + 1] = { name = inst.Name, className = inst.ClassName, path = fullPath, source = src }",
5304
+ "end",
5305
+ "if #targets > 0 and lw and lw.resolve then",
5306
+ " for _, tPath in ipairs(targets) do",
5307
+ " local inst = lw.resolve(tPath)",
5308
+ " if inst then collectOne(inst) end",
5309
+ " end",
5310
+ "else",
5311
+ " for _, root in ipairs(roots) do",
5312
+ " if root then",
5313
+ " local ok, list = pcall(function() return root:GetDescendants() end)",
5314
+ " if ok and type(list) == 'table' then",
5315
+ " for _, inst in ipairs(list) do",
5316
+ " if #results >= limit or totalBytes >= maxTotalBytes then break end",
5317
+ " collectOne(inst)",
4496
5318
  " end",
4497
5319
  " end",
4498
5320
  " end",
@@ -4500,7 +5322,7 @@ ${createRes.text}`
4500
5322
  "end",
4501
5323
  "return HttpService:JSONEncode(results)"
4502
5324
  ].join("\n");
4503
- const liveRes = await this.callCloudTool("exec", {
5325
+ const liveRes = await this.execWithFullOutput({
4504
5326
  code: liveCollectCode,
4505
5327
  readonly: true,
4506
5328
  ...session ? { session } : {}
@@ -4516,32 +5338,52 @@ ${createRes.text}`
4516
5338
  isError: true
4517
5339
  };
4518
5340
  }
4519
- const scripts = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
5341
+ const scripts = this.extractJsonPayloadFromExec(
5342
+ liveRes.fullBody
5343
+ );
5344
+ if (!Array.isArray(scripts)) {
5345
+ return this.formatJsonParseError(
5346
+ "live_scripts_to_studio",
5347
+ "live scripts collection",
5348
+ liveRes.fullBody,
5349
+ liveRes.pages,
5350
+ liveRes.truncated
5351
+ );
5352
+ }
4520
5353
  const studioImportCode = [
4521
- "local HttpService = game:GetService('HttpService')",
4522
- "local ServerStorage = game:GetService('ServerStorage')",
4523
- `local containerName = ${JSON.stringify(containerName)}`,
4524
- `local items = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(scripts))})`,
4525
- "local folder = ServerStorage:FindFirstChild(containerName)",
4526
- "if not folder then",
4527
- " folder = Instance.new('Folder')",
4528
- " folder.Name = containerName",
4529
- " folder.Parent = ServerStorage",
5354
+ `local targetService = ${toLuauLiteral(container.service)}`,
5355
+ `local targetSegments = ${toLuauLiteral(container.segments)}`,
5356
+ `local displayPath = ${toLuauLiteral(container.displayPath)}`,
5357
+ `local setDisabled = ${toLuauLiteral(disabled)}`,
5358
+ `local items = ${toLuauLiteral(scripts)}`,
5359
+ "local cur = game:GetService(targetService)",
5360
+ "for _, seg in ipairs(targetSegments) do",
5361
+ " local nextInst = cur:FindFirstChild(seg)",
5362
+ " if not nextInst then",
5363
+ " nextInst = Instance.new('Folder')",
5364
+ " nextInst.Name = seg",
5365
+ " nextInst.Parent = cur",
5366
+ " end",
5367
+ " cur = nextInst",
4530
5368
  "end",
5369
+ "local folder = cur",
4531
5370
  "local imported = 0",
4532
5371
  "for _, item in ipairs(items) do",
4533
5372
  " local ok, inst = pcall(Instance.new, item.className)",
4534
5373
  " if ok and inst then",
4535
5374
  " inst.Name = item.name .. '_' .. tostring(imported + 1)",
4536
5375
  " pcall(function() inst:SetAttribute('LivePath', item.path) end)",
5376
+ " if setDisabled and (item.className == 'LocalScript' or item.className == 'Script') then",
5377
+ " pcall(function() inst.Disabled = true end)",
5378
+ " end",
4537
5379
  " pcall(function() inst.Source = item.source end)",
4538
5380
  " inst.Parent = folder",
4539
5381
  " imported = imported + 1",
4540
5382
  " end",
4541
5383
  "end",
4542
- "return string.format('imported %d live scripts into ServerStorage.%s', imported, containerName)"
5384
+ "return string.format('imported %d live scripts into %s', imported, displayPath)"
4543
5385
  ].join("\n");
4544
- const studioRes = await this.studio.runStudioLuau(studioImportCode, requestedStudioId);
5386
+ const studioRes = await this.studio.runStudioLuau(studioImportCode, requestedStudioId, datamodelType);
4545
5387
  if (!studioRes.ok) {
4546
5388
  return {
4547
5389
  content: [
@@ -4553,16 +5395,26 @@ ${createRes.text}`
4553
5395
  isError: true
4554
5396
  };
4555
5397
  }
5398
+ const notes = [];
5399
+ if (liveRes.pages > 1) {
5400
+ notes.push(`- Pagination: reassembled ${liveRes.pages} pages from Cloud exec/get_result`);
5401
+ }
5402
+ if (scripts.length >= limit || liveRes.truncated) {
5403
+ notes.push(
5404
+ `- Note: collection reached limit (max=${limit}${liveRes.truncated ? ", truncated" : ""}); pass filter/targets or raise max to import more.`
5405
+ );
5406
+ }
4556
5407
  const listLines = scripts.slice(0, 15).map((s) => ` - [${s.className}] ${s.path} (${s.source.length} bytes)`);
4557
5408
  return {
4558
5409
  content: [
4559
5410
  {
4560
5411
  type: "text",
4561
5412
  text: [
4562
- `live_scripts_to_studio complete (studio_id=${studioRes.studioId ?? "auto"}):`,
5413
+ `live_scripts_to_studio complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4563
5414
  `- Scripts collected from live game: ${scripts.length}`,
4564
- `- Studio container: ServerStorage.${containerName}`,
5415
+ `- Studio container: ${container.displayPath}`,
4565
5416
  `- Studio result: ${studioRes.text}`,
5417
+ ...notes,
4566
5418
  ...listLines
4567
5419
  ].join("\n")
4568
5420
  }
@@ -4574,7 +5426,9 @@ ${createRes.text}`
4574
5426
  const targetB = typeof args.target_b === "string" && args.target_b.trim() ? args.target_b.trim() : "studio";
4575
5427
  const rawMethod = typeof args.method === "string" ? args.method : "auto";
4576
5428
  const method = rawMethod === "copy" || rawMethod === "screen" ? "copy" : rawMethod === "printwindow" || rawMethod === "print_window" ? "printwindow" : "auto";
4577
- const includeImages = args.include_images === true;
5429
+ const clientOnly = args.client_only !== false;
5430
+ const focusFirst = args.focus_first === true;
5431
+ const includeImages = args.include_images !== false;
4578
5432
  let base64A = typeof args.base64_a === "string" && args.base64_a.trim() ? args.base64_a.trim() : "";
4579
5433
  let base64B = typeof args.base64_b === "string" && args.base64_b.trim() ? args.base64_b.trim() : "";
4580
5434
  let labelA = base64A ? "base64_a" : targetA;
@@ -4582,7 +5436,12 @@ ${createRes.text}`
4582
5436
  let metaA;
4583
5437
  let metaB;
4584
5438
  if (!base64A) {
4585
- const shotA = await this.windows.captureScreenshot({ target: targetA, method, clientOnly: true });
5439
+ const shotA = await this.windows.captureScreenshot({
5440
+ target: targetA,
5441
+ method,
5442
+ clientOnly,
5443
+ focusFirst
5444
+ });
4586
5445
  if (!shotA.ok || !shotA.data) {
4587
5446
  return {
4588
5447
  content: [
@@ -4599,7 +5458,12 @@ ${createRes.text}`
4599
5458
  labelA = `${targetA} (${shotA.width}x${shotA.height}, method=${shotA.captureMethod ?? method})`;
4600
5459
  }
4601
5460
  if (!base64B) {
4602
- const shotB = await this.windows.captureScreenshot({ target: targetB, method, clientOnly: true });
5461
+ const shotB = await this.windows.captureScreenshot({
5462
+ target: targetB,
5463
+ method,
5464
+ clientOnly,
5465
+ focusFirst
5466
+ });
4603
5467
  if (!shotB.ok || !shotB.data) {
4604
5468
  return {
4605
5469
  content: [