@luaward/mcp 0.2.5 → 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.5" }
242
+ clientInfo: { name: "@luaward/mcp", version: "0.2.6" }
243
243
  }
244
244
  })
245
245
  });
@@ -754,7 +754,7 @@ var RobloxStudioMcpClient = class {
754
754
  await this.sendRawRpc("initialize", {
755
755
  protocolVersion: "2025-03-26",
756
756
  capabilities: {},
757
- clientInfo: { name: "@luaward/mcp", version: "0.2.5" }
757
+ clientInfo: { name: "@luaward/mcp", version: "0.2.6" }
758
758
  });
759
759
  if (this.child && !this.child.killed) {
760
760
  this.child.stdin.write(
@@ -1379,6 +1379,10 @@ namespace Luaward {
1379
1379
  [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
1380
1380
  [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
1381
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();
1382
1386
  [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
1383
1387
  [DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
1384
1388
  [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
@@ -1398,6 +1402,52 @@ namespace Luaward {
1398
1402
 
1399
1403
  public const uint GA_ROOT = 2;
1400
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
+ }
1401
1451
 
1402
1452
  public static bool IsWindowTopAtPoint(IntPtr targetHwnd, int x, int y) {
1403
1453
  if (targetHwnd == IntPtr.Zero) return false;
@@ -1716,20 +1766,37 @@ ${scriptBody}`;
1716
1766
  if (!filterStr) return all;
1717
1767
  return all.filter((w) => matchesWindowTarget(w, filterStr));
1718
1768
  }
1719
- async focusWindow(target) {
1769
+ async focusWindow(target, opts) {
1720
1770
  const wins = await this.listWindows(target);
1721
1771
  const win = wins[0];
1722
1772
  if (!win) return { ok: false, err: `No window matching "${target}" found` };
1723
- await this.runPsJson(
1724
- `
1725
- $h = [IntPtr]::new([Convert]::ToInt64("${win.hwnd}", 16))
1726
- if ([Luaward.Win32Desktop]::IsIconic($h)) { [void][Luaward.Win32Desktop]::ShowWindow($h, 9) }
1727
- [void][Luaward.Win32Desktop]::SetForegroundWindow($h)
1728
- @{ ok = $true } | ConvertTo-Json -Compress
1729
- `
1730
- );
1773
+ const res = await this.runPsJson(buildFocusWindowPsScript(win.hwnd, opts?.verifyPoint));
1731
1774
  const refreshed = (await this.listWindows(target))[0] ?? win;
1732
- 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
+ `);
1733
1800
  }
1734
1801
  async resizeWindow(opts) {
1735
1802
  const wins = await this.listWindows(opts.target);
@@ -2220,6 +2287,21 @@ Walk-Ui $root 1
2220
2287
  if ($nodes.Count -eq 0) { "[]" } else { ConvertTo-Json -InputObject $nodes.ToArray() -Depth 5 -Compress }
2221
2288
  `;
2222
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
+ }
2223
2305
  function buildScreenshotPsScript(opts) {
2224
2306
  const hasHwnd = Boolean(opts.hwnd?.startsWith("0x"));
2225
2307
  return `
@@ -2366,7 +2448,7 @@ function matchesWindowTarget(w, filter) {
2366
2448
  }
2367
2449
 
2368
2450
  // src/index.ts
2369
- var MCP_BRIDGE_VERSION = "0.2.5";
2451
+ var MCP_BRIDGE_VERSION = "0.2.6";
2370
2452
  var DEFAULT_MCP_URL = "https://luaward.com/mcp";
2371
2453
  var TOKEN_CREATE_URL = "https://dash.luaward.com/dashboard/ai";
2372
2454
  var TOKEN_SHAPE = /^lwm_[0-9a-f]{48}$/;
@@ -2464,6 +2546,145 @@ function extractProtocolVersion(parsed) {
2464
2546
  return void 0;
2465
2547
  }
2466
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
+ }
2467
2688
  var LOCAL_HYBRID_TOOLS = [
2468
2689
  {
2469
2690
  name: "editor_tabs",
@@ -2896,7 +3117,7 @@ var LOCAL_HYBRID_TOOLS = [
2896
3117
  kind: {
2897
3118
  type: "string",
2898
3119
  enum: ["network", "bindable", "all"],
2899
- description: "Remote kind filter (default 'all')"
3120
+ description: "Remote kind filter (default 'network' - prioritizes RemoteEvent/RemoteFunction/UnreliableRemoteEvent)"
2900
3121
  },
2901
3122
  max: {
2902
3123
  type: "integer",
@@ -3083,7 +3304,13 @@ var LOCAL_HYBRID_TOOLS = [
3083
3304
  },
3084
3305
  wait_seconds: {
3085
3306
  type: "number",
3086
- description: "Wait time in seconds for run_and_collect (default 1.5)"
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)"
3087
3314
  },
3088
3315
  clean_env: {
3089
3316
  type: "boolean",
@@ -3140,19 +3367,15 @@ var LOCAL_HYBRID_TOOLS = [
3140
3367
  },
3141
3368
  script_id: {
3142
3369
  type: "string",
3143
- description: "Target Luaward Cloud script ID to deploy to"
3370
+ description: "Alias for script (target Luaward Cloud script ID to deploy to)"
3144
3371
  },
3145
3372
  name: {
3146
3373
  type: "string",
3147
3374
  description: "New Luaward Cloud script name when creating a new script"
3148
3375
  },
3149
- description: {
3376
+ project_id: {
3150
3377
  type: "string",
3151
- description: "Optional description when creating a new Luaward script"
3152
- },
3153
- note: {
3154
- type: "string",
3155
- description: "Optional build note when deploying to an existing Luaward script"
3378
+ description: "Optional project ID from list_projects when creating a new script"
3156
3379
  },
3157
3380
  studio_path: {
3158
3381
  type: "string",
@@ -3160,13 +3383,27 @@ var LOCAL_HYBRID_TOOLS = [
3160
3383
  },
3161
3384
  publish: {
3162
3385
  type: "boolean",
3163
- 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)"
3164
3391
  },
3165
3392
  preset: {
3166
3393
  type: "string",
3167
3394
  enum: ["fast", "balanced", "max"],
3168
3395
  description: "Optional protection preset"
3169
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
+ },
3170
3407
  datamodel_type: {
3171
3408
  type: "string",
3172
3409
  enum: ["Edit", "Client", "Server"],
@@ -3205,11 +3442,11 @@ var LOCAL_HYBRID_TOOLS = [
3205
3442
  },
3206
3443
  studio_root: {
3207
3444
  type: "string",
3208
- description: "Optional destination container in Studio ServerStorage (default 'LuawardLiveScripts')"
3445
+ description: "Destination container path in Studio (e.g. 'ServerStorage.LiveImports', 'ReplicatedStorage.Debug.LiveScripts', or plain folder name under ServerStorage; default 'ServerStorage.LuawardLiveScripts')"
3209
3446
  },
3210
3447
  container_name: {
3211
3448
  type: "string",
3212
- description: "Alias for studio_root destination folder name in ServerStorage (default 'LuawardLiveScripts')"
3449
+ description: "Alias for studio_root destination path or folder name (default 'ServerStorage.LuawardLiveScripts')"
3213
3450
  },
3214
3451
  max: {
3215
3452
  type: "integer",
@@ -3282,6 +3519,18 @@ var LOCAL_HYBRID_TOOLS = [
3282
3519
  focus_first: {
3283
3520
  type: "boolean",
3284
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"
3285
3534
  }
3286
3535
  },
3287
3536
  additionalProperties: false
@@ -3305,6 +3554,7 @@ var HybridMcpBridge = class {
3305
3554
  autoInjectPollMs;
3306
3555
  autoInjectMaxPolls;
3307
3556
  autoInjectCooldownMs;
3557
+ verifyDelayMs;
3308
3558
  fetchFn;
3309
3559
  stderr;
3310
3560
  cachedPairCommand;
@@ -3325,6 +3575,7 @@ var HybridMcpBridge = class {
3325
3575
  this.autoInjectPollMs = options.autoInjectPollMs ?? 400;
3326
3576
  this.autoInjectMaxPolls = options.autoInjectMaxPolls ?? 15;
3327
3577
  this.autoInjectCooldownMs = options.autoInjectCooldownMs ?? 3e4;
3578
+ this.verifyDelayMs = options.verifyDelayMs ?? 120;
3328
3579
  this.potassium = options.potassiumClient ?? new PotassiumClient({
3329
3580
  url: options.potassiumUrl ?? resolved.potassiumUrl,
3330
3581
  token: options.potassiumToken !== void 0 ? options.potassiumToken : resolved.potassiumToken,
@@ -4018,8 +4269,8 @@ ${lines.join("\n")}` }]
4018
4269
  const vpX = vpXMatch ? Number(vpXMatch[1]) : 0;
4019
4270
  const vpY = vpYMatch ? Number(vpYMatch[1]) : 0;
4020
4271
  const resolvedPath = pathMatch?.[1] ?? target;
4021
- const focusRes = await this.windows.focusWindow("roblox");
4022
- if (!focusRes.ok || !focusRes.window) {
4272
+ let focusRes = await this.windows.focusWindow("roblox");
4273
+ if (!focusRes.window) {
4023
4274
  return {
4024
4275
  content: [
4025
4276
  { type: "text", text: `os_click could not find Roblox window: ${focusRes.err ?? "not found"}` }
@@ -4032,6 +4283,40 @@ ${lines.join("\n")}` }]
4032
4283
  const scaleY = vpY > 0 && cr.height > 0 ? cr.height / vpY : 1;
4033
4284
  const screenX = Math.round(cr.screenLeft + clientX * scaleX);
4034
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
+ }
4035
4320
  const mouseAction = args.double_click === true ? "double_click" : args.button === "right" ? "right_click" : "click";
4036
4321
  const session = typeof args.session === "string" ? args.session : void 0;
4037
4322
  const shouldVerify = args.verify === true;
@@ -4094,6 +4379,9 @@ ${verifyText}`;
4094
4379
  return out.join("\n");
4095
4380
  }
4096
4381
  async verifyMouseActionInGame(beforeSnap, session) {
4382
+ if (this.verifyDelayMs > 0) {
4383
+ await sleep(this.verifyDelayMs);
4384
+ }
4097
4385
  const lines = ["Verification:"];
4098
4386
  try {
4099
4387
  const mouseCode = [
@@ -4126,7 +4414,7 @@ ${verifyText}`;
4126
4414
  }
4127
4415
  try {
4128
4416
  const snapRes = await this.callCloudTool("gui_snapshot", {
4129
- diff_from: "latest",
4417
+ diff_from: "last",
4130
4418
  ...session ? { session } : {}
4131
4419
  });
4132
4420
  if (snapRes.ok) {
@@ -4141,29 +4429,98 @@ ${diffSummary}`);
4141
4429
  }
4142
4430
  return lines.join("\n");
4143
4431
  }
4144
- extractJsonPayloadFromExec(rawText) {
4145
- const trimmed = rawText.trim();
4146
- if (!trimmed) return null;
4147
- const candidates = [trimmed];
4148
- if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
4149
- try {
4150
- const unquoted = JSON.parse(trimmed);
4151
- if (typeof unquoted === "string") candidates.unshift(unquoted);
4152
- } 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
+ };
4153
4444
  }
4154
4445
  }
4155
- const firstBracket = trimmed.search(/[\[{]/);
4156
- const lastBracket = Math.max(trimmed.lastIndexOf("]"), trimmed.lastIndexOf("}"));
4157
- if (firstBracket >= 0 && lastBracket > firstBracket) {
4158
- 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
+ };
4159
4455
  }
4160
- for (const c of candidates) {
4161
- try {
4162
- return JSON.parse(c);
4163
- } 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
+ };
4164
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;
4495
+ }
4496
+ nextOffset = next;
4165
4497
  }
4166
- 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);
4167
4524
  }
4168
4525
  parseStudioDataModelType(raw) {
4169
4526
  if (raw === "Client" || raw === "Server" || raw === "Edit") {
@@ -4175,7 +4532,7 @@ ${diffSummary}`);
4175
4532
  const singleRoot = typeof args.root === "string" && args.root.trim() ? args.root.trim() : "";
4176
4533
  const roots = singleRoot ? [singleRoot] : Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "Workspace"];
4177
4534
  const filter = typeof args.filter === "string" ? args.filter.trim().toLowerCase() : "";
4178
- const kind = args.kind === "network" || args.kind === "bindable" ? args.kind : "all";
4535
+ const kind = args.kind === "all" || args.kind === "bindable" || args.kind === "network" ? args.kind : "network";
4179
4536
  const max = typeof args.max === "number" ? Math.max(1, Math.min(500, Math.floor(args.max))) : 200;
4180
4537
  const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(12, Math.floor(args.max_depth))) : 6;
4181
4538
  const clearExisting = args.clear_existing === true;
@@ -4189,14 +4546,37 @@ ${diffSummary}`);
4189
4546
  BindableEvent: true,
4190
4547
  BindableFunction: true
4191
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
+ };
4192
4568
  const liveScanCode = [
4193
4569
  "local HttpService = game:GetService('HttpService')",
4194
4570
  `local roots = ${toLuauLiteral(roots)}`,
4195
4571
  `local filter = ${toLuauLiteral(filter)}`,
4196
4572
  `local maxItems = ${toLuauLiteral(max)}`,
4197
4573
  `local maxDepth = ${toLuauLiteral(maxDepth)}`,
4574
+ `local kindMode = ${toLuauLiteral(kind)}`,
4198
4575
  `local remoteClasses = ${toLuauLiteral(remoteClassesMap)}`,
4199
- "local items = {}",
4576
+ `local netPriorityClasses = ${toLuauLiteral(netPriorityMap)}`,
4577
+ `local lowPriorityFolders = ${toLuauLiteral(lowPriorityFolders)}`,
4578
+ "local netItems = {}",
4579
+ "local otherItems = {}",
4200
4580
  "local function resolveRoot(rPath)",
4201
4581
  " local segs = {}",
4202
4582
  " for seg in string.gmatch(rPath, '[^%.]+') do segs[#segs + 1] = seg end",
@@ -4213,31 +4593,79 @@ ${diffSummary}`);
4213
4593
  " end",
4214
4594
  " return cur, rootName, baseSegs",
4215
4595
  "end",
4216
- "local function scan(inst, rootName, segs, depth)",
4217
- " if depth > maxDepth or #items >= maxItems then return end",
4218
- " for _, child in ipairs(inst:GetChildren()) do",
4219
- " if #items >= maxItems then break end",
4220
- " local nextSegs = {}",
4221
- " for i = 1, #segs do nextSegs[i] = segs[i] end",
4222
- " nextSegs[#nextSegs + 1] = child.Name",
4223
- " local fullPath = rootName .. '.' .. table.concat(nextSegs, '.')",
4224
- " if remoteClasses[child.ClassName] then",
4225
- " if filter == '' or string.find(string.lower(fullPath), filter, 1, true) then",
4226
- " items[#items + 1] = { root = rootName, className = child.ClassName, segments = nextSegs, path = fullPath }",
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 }",
4227
4653
  " end",
4228
- " end",
4229
- " if #child:GetChildren() > 0 and #items < maxItems then",
4230
- " scan(child, rootName, nextSegs, depth + 1)",
4231
4654
  " end",
4232
4655
  " end",
4233
4656
  "end",
4234
- "for _, rPath in ipairs(roots) do",
4235
- " local inst, rootName, baseSegs = resolveRoot(rPath)",
4236
- " if inst and rootName and baseSegs then scan(inst, rootName, baseSegs, 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",
4237
4665
  "end",
4238
4666
  "return HttpService:JSONEncode(items)"
4239
4667
  ].join("\n");
4240
- const liveRes = await this.callCloudTool("exec", {
4668
+ const liveRes = await this.execWithFullOutput({
4241
4669
  code: liveScanCode,
4242
4670
  readonly: true,
4243
4671
  ...session ? { session } : {}
@@ -4248,7 +4676,18 @@ ${diffSummary}`);
4248
4676
  isError: true
4249
4677
  };
4250
4678
  }
4251
- 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
+ }
4252
4691
  const studioCode = [
4253
4692
  `local items = ${toLuauLiteral(items)}`,
4254
4693
  `local clearExisting = ${toLuauLiteral(clearExisting)}`,
@@ -4302,6 +4741,15 @@ ${diffSummary}`);
4302
4741
  };
4303
4742
  }
4304
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
+ }
4305
4753
  return {
4306
4754
  content: [
4307
4755
  {
@@ -4310,6 +4758,7 @@ ${diffSummary}`);
4310
4758
  `studio_mirror_remotes complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4311
4759
  `- Live remotes discovered: ${items.length} across ${roots.join(", ")} (kind=${kind}${filter ? `, filter="${filter}"` : ""}, max=${max})`,
4312
4760
  `- Studio result: ${studioRes.text}`,
4761
+ ...warnings,
4313
4762
  ...samplePaths.length > 0 ? ["- Sample mirrored paths:", ...samplePaths] : []
4314
4763
  ].join("\n")
4315
4764
  }
@@ -4339,11 +4788,13 @@ ${diffSummary}`);
4339
4788
  `local includeCore = ${toLuauLiteral(includeCoreGui)}`,
4340
4789
  "local nodes = {}",
4341
4790
  "local count = 0",
4791
+ "local capped = false",
4342
4792
  "local function serColor(c) return c and { c.R, c.G, c.B } or nil end",
4343
4793
  "local function serUDim2(u) return u and { u.X.Scale, u.X.Offset, u.Y.Scale, u.Y.Offset } or nil end",
4344
4794
  "local function serVec2(v) return v and { v.X, v.Y } or nil end",
4345
4795
  "local function serializeTree(inst, depth)",
4346
- " if count >= maxNodes or depth > maxDepth then return nil end",
4796
+ " if count >= maxNodes then capped = true; return nil end",
4797
+ " if depth > maxDepth then return nil end",
4347
4798
  " if onlyVisible then",
4348
4799
  " if inst:IsA('LayerCollector') and inst.Enabled == false then return nil end",
4349
4800
  " if inst:IsA('GuiObject') and inst.Visible == false then return nil end",
@@ -4372,7 +4823,7 @@ ${diffSummary}`);
4372
4823
  " end",
4373
4824
  " end)",
4374
4825
  " for _, child in ipairs(inst:GetChildren()) do",
4375
- " if count >= maxNodes then break end",
4826
+ " if count >= maxNodes then capped = true; break end",
4376
4827
  " local cNode = serializeTree(child, depth + 1)",
4377
4828
  " if cNode then node.children[#node.children + 1] = cNode end",
4378
4829
  " end",
@@ -4389,7 +4840,7 @@ ${diffSummary}`);
4389
4840
  " local pgui = lp and lp:FindFirstChildOfClass('PlayerGui')",
4390
4841
  " if pgui then",
4391
4842
  " for _, child in ipairs(pgui:GetChildren()) do",
4392
- " if count >= maxNodes then break end",
4843
+ " if count >= maxNodes then capped = true; break end",
4393
4844
  " local n = serializeTree(child, 1)",
4394
4845
  " if n then nodes[#nodes + 1] = n end",
4395
4846
  " end",
@@ -4398,7 +4849,7 @@ ${diffSummary}`);
4398
4849
  " local ok, cgui = pcall(function() return game:GetService('CoreGui') end)",
4399
4850
  " if ok and cgui then",
4400
4851
  " for _, child in ipairs(cgui:GetChildren()) do",
4401
- " if count >= maxNodes then break end",
4852
+ " if count >= maxNodes then capped = true; break end",
4402
4853
  " if child.Name ~= 'RobloxGui' then",
4403
4854
  " local n = serializeTree(child, 1)",
4404
4855
  " if n then nodes[#nodes + 1] = n end",
@@ -4407,9 +4858,9 @@ ${diffSummary}`);
4407
4858
  " end",
4408
4859
  " end",
4409
4860
  "end",
4410
- "return HttpService:JSONEncode({ count = count, trees = nodes })"
4861
+ "return HttpService:JSONEncode({ count = count, capped = capped, trees = nodes })"
4411
4862
  ].join("\n");
4412
- const liveRes = await this.callCloudTool("exec", {
4863
+ const liveRes = await this.execWithFullOutput({
4413
4864
  code: liveGuiCode,
4414
4865
  readonly: true,
4415
4866
  ...session ? { session } : {}
@@ -4420,10 +4871,16 @@ ${diffSummary}`);
4420
4871
  isError: true
4421
4872
  };
4422
4873
  }
4423
- const payload = this.extractJsonPayloadFromExec(liveRes.text) ?? {
4424
- count: 0,
4425
- trees: []
4426
- };
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
+ }
4427
4884
  const studioBuildCode = [
4428
4885
  "local StarterGui = game:GetService('StarterGui')",
4429
4886
  `local containerName = ${toLuauLiteral(containerName)}`,
@@ -4482,6 +4939,15 @@ ${diffSummary}`);
4482
4939
  isError: true
4483
4940
  };
4484
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
+ }
4485
4951
  return {
4486
4952
  content: [
4487
4953
  {
@@ -4490,7 +4956,8 @@ ${diffSummary}`);
4490
4956
  `studio_mirror_gui complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4491
4957
  `- Live GUI nodes serialized: ${payload.count} (${payload.trees.length} root trees)`,
4492
4958
  `- Studio container: StarterGui.${containerName}`,
4493
- `- Studio result: ${studioRes.text}`
4959
+ `- Studio result: ${studioRes.text}`,
4960
+ ...notes
4494
4961
  ].join("\n")
4495
4962
  }
4496
4963
  ]
@@ -4523,6 +4990,7 @@ ${diffSummary}`);
4523
4990
  "local function scan(inst, prefix, depth)",
4524
4991
  " if depth > maxDepth or count >= 1500 then return end",
4525
4992
  " for _, child in ipairs(inst:GetChildren()) do",
4993
+ " if count >= 1500 then break end",
4526
4994
  " local p = prefix .. '.' .. child.Name",
4527
4995
  " if matchesScope(child) then",
4528
4996
  " count = count + 1",
@@ -4544,7 +5012,7 @@ ${diffSummary}`);
4544
5012
  "return HttpService:JSONEncode(entries)"
4545
5013
  ].join("\n");
4546
5014
  const [liveRes, studioRes] = await Promise.all([
4547
- this.callCloudTool("exec", {
5015
+ this.execWithFullOutput({
4548
5016
  code: buildDiffScanCode(true),
4549
5017
  readonly: true,
4550
5018
  ...session ? { session } : {}
@@ -4563,8 +5031,20 @@ ${diffSummary}`);
4563
5031
  isError: true
4564
5032
  };
4565
5033
  }
4566
- const liveEntries = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
4567
- 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
+ }
4568
5048
  const liveMap = /* @__PURE__ */ new Map();
4569
5049
  for (const e of liveEntries) liveMap.set(e.path, e.className);
4570
5050
  const studioMap = /* @__PURE__ */ new Map();
@@ -4590,6 +5070,7 @@ ${diffSummary}`);
4590
5070
  }
4591
5071
  const lines = [
4592
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})` : ""}`,
4593
5074
  `- Matched instances: ${matchedCount}`,
4594
5075
  `- Only in Live Game: ${onlyInLive.length}`,
4595
5076
  ...onlyInLive.slice(0, 20).map((x) => ` + [Live] ${x}`),
@@ -4600,6 +5081,11 @@ ${diffSummary}`);
4600
5081
  `- Class mismatches: ${classMismatches.length}`,
4601
5082
  ...classMismatches.slice(0, 10).map((x) => ` ! ${x}`)
4602
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
+ }
4603
5089
  return {
4604
5090
  content: [{ type: "text", text: lines.join("\n") }]
4605
5091
  };
@@ -4674,14 +5160,16 @@ ${diffSummary}`);
4674
5160
  sourceLabel = `${parsed.path} [${parsed.className}] (${codeToRun.length} bytes, studio_id=${resolvedStudioId ?? "auto"}, datamodel_type=${datamodelType})`;
4675
5161
  }
4676
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;
4677
5165
  const cloudArgs = {
4678
5166
  code: codeToRun,
4679
5167
  ...collect ? {
4680
- wait_seconds: typeof args.wait_seconds === "number" ? args.wait_seconds : 1.5,
4681
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 } : {},
4682
5171
  ...typeof args.track_resources === "boolean" ? { track_resources: args.track_resources } : {},
4683
- ...typeof args.auto_cleanup === "boolean" ? { auto_cleanup: args.auto_cleanup } : {},
4684
- ...typeof args.settle_ms === "number" ? { settle_ms: args.settle_ms } : {}
5172
+ ...typeof args.auto_cleanup === "boolean" ? { auto_cleanup: args.auto_cleanup } : {}
4685
5173
  } : {},
4686
5174
  ...session ? { session } : {}
4687
5175
  };
@@ -4731,15 +5219,16 @@ ${liveRes.text}`
4731
5219
  }
4732
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() : "";
4733
5221
  if (scriptTarget) {
4734
- const deployRes = await this.callCloudTool("deploy_script", {
4735
- ...typeof args.script_id === "string" && args.script_id.trim() ? { script_id: args.script_id.trim() } : {},
4736
- ...typeof args.script === "string" && args.script.trim() ? { script: args.script.trim() } : {},
4737
- ...!args.script_id && !args.script ? { script: scriptTarget } : {},
5222
+ const deployArgs = {
5223
+ script: scriptTarget,
4738
5224
  source: parsed.source,
4739
- ...typeof args.note === "string" ? { note: args.note } : {},
5225
+ ...typeof args.preset === "string" ? { preset: args.preset } : {},
4740
5226
  ...typeof args.publish === "boolean" ? { publish: args.publish } : {},
4741
- ...typeof args.preset === "string" ? { preset: args.preset } : {}
4742
- });
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);
4743
5232
  return {
4744
5233
  content: [
4745
5234
  {
@@ -4752,11 +5241,15 @@ ${deployRes.text}`
4752
5241
  };
4753
5242
  }
4754
5243
  const scriptName = typeof args.name === "string" && args.name.trim() ? args.name.trim() : parsed.name || "StudioScript";
4755
- const createRes = await this.callCloudTool("create_script", {
5244
+ const createArgs = {
4756
5245
  name: scriptName,
4757
5246
  source: parsed.source,
4758
- ...typeof args.description === "string" ? { description: args.description } : {}
4759
- });
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);
4760
5253
  return {
4761
5254
  content: [
4762
5255
  {
@@ -4771,8 +5264,8 @@ ${createRes.text}`
4771
5264
  async handleLiveScriptsToStudio(args) {
4772
5265
  const targets = Array.isArray(args.targets) && args.targets.length > 0 ? args.targets.map(String) : [];
4773
5266
  const filter = typeof args.filter === "string" ? args.filter.trim() : "";
4774
- 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() : "LuawardLiveScripts";
4775
- const containerName = rawContainer.replace(/^ServerStorage\./, "") || "LuawardLiveScripts";
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");
4776
5269
  const rawLimit = typeof args.max === "number" ? args.max : typeof args.limit === "number" ? args.limit : 15;
4777
5270
  const limit = Math.max(1, Math.min(100, Math.floor(rawLimit)));
4778
5271
  const disabled = args.disabled !== false;
@@ -4789,6 +5282,8 @@ ${createRes.text}`
4789
5282
  "local roots = { game:GetService('ReplicatedStorage'), game:GetService('StarterPlayer'), game:GetService('Workspace'), game:GetService('Players').LocalPlayer }",
4790
5283
  "local results = {}",
4791
5284
  "local seen = {}",
5285
+ "local totalBytes = 0",
5286
+ "local maxTotalBytes = 600000",
4792
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",
4793
5288
  "local function collectOne(inst)",
4794
5289
  " if not inst or seen[inst] or #results >= limit then return end",
@@ -4803,6 +5298,8 @@ ${createRes.text}`
4803
5298
  " src = src .. '\\n\\n' .. dec:sub(1, 32000)",
4804
5299
  " end",
4805
5300
  " end",
5301
+ " if #results > 0 and (totalBytes + #src) > maxTotalBytes then return end",
5302
+ " totalBytes = totalBytes + #src",
4806
5303
  " results[#results + 1] = { name = inst.Name, className = inst.ClassName, path = fullPath, source = src }",
4807
5304
  "end",
4808
5305
  "if #targets > 0 and lw and lw.resolve then",
@@ -4816,7 +5313,7 @@ ${createRes.text}`
4816
5313
  " local ok, list = pcall(function() return root:GetDescendants() end)",
4817
5314
  " if ok and type(list) == 'table' then",
4818
5315
  " for _, inst in ipairs(list) do",
4819
- " if #results >= limit then break end",
5316
+ " if #results >= limit or totalBytes >= maxTotalBytes then break end",
4820
5317
  " collectOne(inst)",
4821
5318
  " end",
4822
5319
  " end",
@@ -4825,7 +5322,7 @@ ${createRes.text}`
4825
5322
  "end",
4826
5323
  "return HttpService:JSONEncode(results)"
4827
5324
  ].join("\n");
4828
- const liveRes = await this.callCloudTool("exec", {
5325
+ const liveRes = await this.execWithFullOutput({
4829
5326
  code: liveCollectCode,
4830
5327
  readonly: true,
4831
5328
  ...session ? { session } : {}
@@ -4841,18 +5338,35 @@ ${createRes.text}`
4841
5338
  isError: true
4842
5339
  };
4843
5340
  }
4844
- 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
+ }
4845
5353
  const studioImportCode = [
4846
- "local ServerStorage = game:GetService('ServerStorage')",
4847
- `local containerName = ${toLuauLiteral(containerName)}`,
5354
+ `local targetService = ${toLuauLiteral(container.service)}`,
5355
+ `local targetSegments = ${toLuauLiteral(container.segments)}`,
5356
+ `local displayPath = ${toLuauLiteral(container.displayPath)}`,
4848
5357
  `local setDisabled = ${toLuauLiteral(disabled)}`,
4849
5358
  `local items = ${toLuauLiteral(scripts)}`,
4850
- "local folder = ServerStorage:FindFirstChild(containerName)",
4851
- "if not folder then",
4852
- " folder = Instance.new('Folder')",
4853
- " folder.Name = containerName",
4854
- " folder.Parent = ServerStorage",
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",
4855
5368
  "end",
5369
+ "local folder = cur",
4856
5370
  "local imported = 0",
4857
5371
  "for _, item in ipairs(items) do",
4858
5372
  " local ok, inst = pcall(Instance.new, item.className)",
@@ -4867,7 +5381,7 @@ ${createRes.text}`
4867
5381
  " imported = imported + 1",
4868
5382
  " end",
4869
5383
  "end",
4870
- "return string.format('imported %d live scripts into ServerStorage.%s', imported, containerName)"
5384
+ "return string.format('imported %d live scripts into %s', imported, displayPath)"
4871
5385
  ].join("\n");
4872
5386
  const studioRes = await this.studio.runStudioLuau(studioImportCode, requestedStudioId, datamodelType);
4873
5387
  if (!studioRes.ok) {
@@ -4881,6 +5395,15 @@ ${createRes.text}`
4881
5395
  isError: true
4882
5396
  };
4883
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
+ }
4884
5407
  const listLines = scripts.slice(0, 15).map((s) => ` - [${s.className}] ${s.path} (${s.source.length} bytes)`);
4885
5408
  return {
4886
5409
  content: [
@@ -4889,8 +5412,9 @@ ${createRes.text}`
4889
5412
  text: [
4890
5413
  `live_scripts_to_studio complete (studio_id=${studioRes.studioId ?? "auto"}, datamodel_type=${datamodelType}):`,
4891
5414
  `- Scripts collected from live game: ${scripts.length}`,
4892
- `- Studio container: ServerStorage.${containerName}`,
5415
+ `- Studio container: ${container.displayPath}`,
4893
5416
  `- Studio result: ${studioRes.text}`,
5417
+ ...notes,
4894
5418
  ...listLines
4895
5419
  ].join("\n")
4896
5420
  }
@@ -4902,7 +5426,9 @@ ${createRes.text}`
4902
5426
  const targetB = typeof args.target_b === "string" && args.target_b.trim() ? args.target_b.trim() : "studio";
4903
5427
  const rawMethod = typeof args.method === "string" ? args.method : "auto";
4904
5428
  const method = rawMethod === "copy" || rawMethod === "screen" ? "copy" : rawMethod === "printwindow" || rawMethod === "print_window" ? "printwindow" : "auto";
4905
- 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;
4906
5432
  let base64A = typeof args.base64_a === "string" && args.base64_a.trim() ? args.base64_a.trim() : "";
4907
5433
  let base64B = typeof args.base64_b === "string" && args.base64_b.trim() ? args.base64_b.trim() : "";
4908
5434
  let labelA = base64A ? "base64_a" : targetA;
@@ -4910,7 +5436,12 @@ ${createRes.text}`
4910
5436
  let metaA;
4911
5437
  let metaB;
4912
5438
  if (!base64A) {
4913
- 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
+ });
4914
5445
  if (!shotA.ok || !shotA.data) {
4915
5446
  return {
4916
5447
  content: [
@@ -4927,7 +5458,12 @@ ${createRes.text}`
4927
5458
  labelA = `${targetA} (${shotA.width}x${shotA.height}, method=${shotA.captureMethod ?? method})`;
4928
5459
  }
4929
5460
  if (!base64B) {
4930
- 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
+ });
4931
5467
  if (!shotB.ok || !shotB.data) {
4932
5468
  return {
4933
5469
  content: [