@luaward/mcp 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  // src/index.ts
2
- import { existsSync as existsSync3, readFileSync as readFileSync2 } from "node:fs";
3
- import { homedir as homedir3 } from "node:os";
4
- import { join as join3, resolve as resolve2 } from "node:path";
5
- import { createInterface as createInterface2 } from "node:readline";
2
+ import { existsSync as existsSync4, readFileSync as readFileSync2 } from "node:fs";
3
+ import { homedir as homedir4 } from "node:os";
4
+ import { join as join4, resolve as resolve2 } from "node:path";
5
+ import { createInterface as createInterface3 } from "node:readline";
6
6
 
7
7
  // src/potassium.ts
8
8
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
@@ -198,6 +198,7 @@ var PotassiumClient = class {
198
198
  fetchFn;
199
199
  sessionId = null;
200
200
  initialized = false;
201
+ lastInitNetworkError = null;
201
202
  rpcSeq = 1e3;
202
203
  constructor(options = {}) {
203
204
  this.url = (options.url || process.env.POTASSIUM_MCP_URL || DEFAULT_POTASSIUM_URL).trim();
@@ -220,6 +221,7 @@ var PotassiumClient = class {
220
221
  }
221
222
  async ensureInitialized() {
222
223
  if (this.initialized) return true;
224
+ this.lastInitNetworkError = null;
223
225
  try {
224
226
  const res = await this.fetchFn(this.url, {
225
227
  method: "POST",
@@ -231,7 +233,7 @@ var PotassiumClient = class {
231
233
  params: {
232
234
  protocolVersion: "2025-03-26",
233
235
  capabilities: {},
234
- clientInfo: { name: "@luaward/mcp", version: "0.2.1" }
236
+ clientInfo: { name: "@luaward/mcp", version: "0.2.3" }
235
237
  }
236
238
  })
237
239
  });
@@ -252,12 +254,20 @@ var PotassiumClient = class {
252
254
  } catch {
253
255
  }
254
256
  return true;
255
- } catch {
257
+ } catch (err) {
258
+ this.lastInitNetworkError = err instanceof Error ? err.message : String(err);
256
259
  return false;
257
260
  }
258
261
  }
259
262
  async callTool(name, args = {}) {
260
- await this.ensureInitialized();
263
+ const initOk = await this.ensureInitialized();
264
+ if (!initOk && this.lastInitNetworkError) {
265
+ return {
266
+ ok: false,
267
+ text: `Potassium local MCP (${this.url}) is not reachable: ${this.lastInitNetworkError}`,
268
+ isError: true
269
+ };
270
+ }
261
271
  try {
262
272
  const res = await this.fetchFn(this.url, {
263
273
  method: "POST",
@@ -491,12 +501,544 @@ var PotassiumClient = class {
491
501
  }
492
502
  };
493
503
 
494
- // src/windows.ts
495
- import { execFile, spawn } from "node:child_process";
496
- import { existsSync as existsSync2, readdirSync, statSync } from "node:fs";
504
+ // src/studio.ts
505
+ import { spawn } from "node:child_process";
506
+ import { existsSync as existsSync2 } from "node:fs";
497
507
  import { homedir as homedir2 } from "node:os";
498
508
  import { join as join2 } from "node:path";
499
509
  import { createInterface } from "node:readline";
510
+ import { inflateSync } from "node:zlib";
511
+ function discoverRobloxStudioMcpBatch(env = process.env) {
512
+ if (env.ROBLOX_STUDIO_MCP_PATH?.trim()) {
513
+ return env.ROBLOX_STUDIO_MCP_PATH.trim();
514
+ }
515
+ const home = homedir2();
516
+ const localAppData = env.LOCALAPPDATA || join2(home, "AppData", "Local");
517
+ const candidates = [
518
+ join2(localAppData, "Roblox", "mcp.bat"),
519
+ join2(localAppData, "RobloxStudio", "mcp.bat")
520
+ ];
521
+ for (const c of candidates) {
522
+ if (existsSync2(c)) return c;
523
+ }
524
+ return candidates[0];
525
+ }
526
+ function parseStudioToolResponse(rpcRes) {
527
+ if (!rpcRes) {
528
+ return { ok: false, text: "Empty response from Roblox Studio MCP", isError: true };
529
+ }
530
+ if (rpcRes.error && typeof rpcRes.error === "object") {
531
+ const err = rpcRes.error;
532
+ return {
533
+ ok: false,
534
+ text: err.message || `Roblox Studio MCP error (${String(err.code ?? "unknown")})`,
535
+ isError: true
536
+ };
537
+ }
538
+ const result = rpcRes.result;
539
+ if (!result || typeof result !== "object") {
540
+ return { ok: true, text: JSON.stringify(rpcRes.result ?? {}), structured: rpcRes.result };
541
+ }
542
+ const texts = [];
543
+ if (Array.isArray(result.content)) {
544
+ for (const item of result.content) {
545
+ if (item && typeof item.text === "string") {
546
+ texts.push(item.text);
547
+ }
548
+ }
549
+ }
550
+ const joined = texts.join("\n").trim();
551
+ let structured = result.structuredContent;
552
+ if (structured === void 0 && (joined.startsWith("{") || joined.startsWith("["))) {
553
+ try {
554
+ structured = JSON.parse(joined);
555
+ } catch {
556
+ }
557
+ }
558
+ return {
559
+ ok: !result.isError,
560
+ text: joined || (structured !== void 0 ? JSON.stringify(structured) : "ok"),
561
+ structured,
562
+ isError: Boolean(result.isError)
563
+ };
564
+ }
565
+ var RobloxStudioMcpClient = class {
566
+ batchPath;
567
+ timeoutMs;
568
+ customTransport;
569
+ child = null;
570
+ initPromise = null;
571
+ pending = /* @__PURE__ */ new Map();
572
+ rpcSeq = 9e3;
573
+ cachedToolNames = null;
574
+ exitHookInstalled = false;
575
+ constructor(options = {}) {
576
+ this.batchPath = options.batchPath || discoverRobloxStudioMcpBatch(options.env);
577
+ this.timeoutMs = options.timeoutMs ?? 25e3;
578
+ this.customTransport = options.transport;
579
+ }
580
+ dispose() {
581
+ const c = this.child;
582
+ this.child = null;
583
+ this.initPromise = null;
584
+ for (const [id, p] of this.pending) {
585
+ clearTimeout(p.timer);
586
+ p.reject(new Error("Roblox Studio MCP client disposed"));
587
+ this.pending.delete(id);
588
+ }
589
+ if (c && !c.killed) {
590
+ try {
591
+ c.stdin.end();
592
+ c.kill();
593
+ } catch {
594
+ }
595
+ }
596
+ }
597
+ async ensureStdioProcess() {
598
+ if (this.customTransport) return;
599
+ if (this.child && !this.child.killed && this.initPromise) {
600
+ return this.initPromise;
601
+ }
602
+ if (!existsSync2(this.batchPath)) {
603
+ throw new Error(
604
+ `Roblox Studio MCP launcher not found at "${this.batchPath}". Ensure Roblox Studio is installed with MCP enabled (expected %LOCALAPPDATA%\\Roblox\\mcp.bat) or set ROBLOX_STUDIO_MCP_PATH.`
605
+ );
606
+ }
607
+ const isBat = /\.(?:bat|cmd)$/i.test(this.batchPath);
608
+ const child = isBat ? spawn("cmd.exe", ["/d", "/s", "/c", `"${this.batchPath}"`], {
609
+ stdio: ["pipe", "pipe", "pipe"],
610
+ windowsHide: true
611
+ }) : spawn(this.batchPath, [], {
612
+ stdio: ["pipe", "pipe", "pipe"],
613
+ windowsHide: true
614
+ });
615
+ child.unref();
616
+ this.child = child;
617
+ if (!this.exitHookInstalled) {
618
+ this.exitHookInstalled = true;
619
+ process.once("exit", () => this.dispose());
620
+ }
621
+ const rl = createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY });
622
+ rl.on("line", (line) => {
623
+ const trimmed = line.trim();
624
+ if (!trimmed.startsWith("{")) return;
625
+ try {
626
+ const parsed = JSON.parse(trimmed);
627
+ if (parsed.id !== void 0 && parsed.id !== null) {
628
+ const key = String(parsed.id);
629
+ const waiter = this.pending.get(key);
630
+ if (waiter) {
631
+ this.pending.delete(key);
632
+ clearTimeout(waiter.timer);
633
+ waiter.resolve(parsed);
634
+ }
635
+ }
636
+ } catch {
637
+ }
638
+ });
639
+ child.once("exit", (code) => {
640
+ if (this.child === child) {
641
+ this.child = null;
642
+ this.initPromise = null;
643
+ }
644
+ const err = new Error(`Roblox Studio MCP process exited (code ${code ?? "null"})`);
645
+ for (const [id, waiter] of this.pending) {
646
+ clearTimeout(waiter.timer);
647
+ waiter.reject(err);
648
+ this.pending.delete(id);
649
+ }
650
+ });
651
+ this.initPromise = (async () => {
652
+ await this.sendRawRpc("initialize", {
653
+ protocolVersion: "2025-03-26",
654
+ capabilities: {},
655
+ clientInfo: { name: "@luaward/mcp", version: "0.2.3" }
656
+ });
657
+ if (this.child && !this.child.killed) {
658
+ this.child.stdin.write(
659
+ `${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized", params: {} })}
660
+ `
661
+ );
662
+ }
663
+ })();
664
+ return this.initPromise;
665
+ }
666
+ async sendRawRpc(method, params) {
667
+ if (this.customTransport) {
668
+ return this.customTransport(method, params);
669
+ }
670
+ const child = this.child;
671
+ if (!child || child.killed) {
672
+ throw new Error("Roblox Studio MCP process is not running");
673
+ }
674
+ const id = ++this.rpcSeq;
675
+ const key = String(id);
676
+ return new Promise((resolveRpc, rejectRpc) => {
677
+ const timer = setTimeout(() => {
678
+ this.pending.delete(key);
679
+ rejectRpc(new Error(`Roblox Studio MCP request "${method}" timed out after ${this.timeoutMs}ms`));
680
+ }, this.timeoutMs);
681
+ this.pending.set(key, { resolve: resolveRpc, reject: rejectRpc, timer });
682
+ child.stdin.write(
683
+ `${JSON.stringify({ jsonrpc: "2.0", id, method, ...params ? { params } : {} })}
684
+ `
685
+ );
686
+ });
687
+ }
688
+ async sendRpc(method, params) {
689
+ await this.ensureStdioProcess();
690
+ return this.sendRawRpc(method, params);
691
+ }
692
+ async listTools() {
693
+ if (this.cachedToolNames) return this.cachedToolNames;
694
+ try {
695
+ const res = await this.sendRpc("tools/list", {});
696
+ const tools = res?.result?.tools;
697
+ if (Array.isArray(tools)) {
698
+ this.cachedToolNames = tools.map((t) => typeof t?.name === "string" ? t.name : "").filter(Boolean);
699
+ return this.cachedToolNames;
700
+ }
701
+ } catch {
702
+ }
703
+ return [];
704
+ }
705
+ async listStudios() {
706
+ const tools = await this.listTools();
707
+ const listToolName = tools.find((t) => t === "list_studios" || t === "get_studios" || t === "list_clients") ?? "list_studios";
708
+ try {
709
+ const rpcRes = await this.sendRpc("tools/call", { name: listToolName, arguments: {} });
710
+ const parsed = parseStudioToolResponse(rpcRes);
711
+ if (!parsed.ok) {
712
+ return { ok: false, studios: [], rawText: parsed.text };
713
+ }
714
+ const studios = [];
715
+ const s = parsed.structured;
716
+ const arr = Array.isArray(s) ? s : s && typeof s === "object" ? Array.isArray(s.studios) ? s.studios : Array.isArray(s.clients) ? s.clients : Array.isArray(s.instances) ? s.instances : null : null;
717
+ if (arr) {
718
+ for (const item of arr) {
719
+ if (item && typeof item === "object") {
720
+ const obj = item;
721
+ const sid = String(
722
+ obj.studio_id ?? obj.studioId ?? obj.id ?? obj.session_id ?? obj.pid ?? ""
723
+ ).trim();
724
+ if (sid) {
725
+ studios.push({
726
+ studio_id: sid,
727
+ place_id: obj.place_id ?? obj.placeId,
728
+ place_name: typeof (obj.place_name ?? obj.placeName ?? obj.name) === "string" ? String(obj.place_name ?? obj.placeName ?? obj.name) : void 0,
729
+ user: typeof obj.user === "string" ? obj.user : void 0,
730
+ raw: obj
731
+ });
732
+ }
733
+ } else if (typeof item === "string" || typeof item === "number") {
734
+ studios.push({ studio_id: String(item) });
735
+ }
736
+ }
737
+ return { ok: true, studios, rawText: parsed.text };
738
+ }
739
+ const matches = [
740
+ ...parsed.text.matchAll(/\b(?:studio_id|studioId|studio|id)[:=\s"']*([A-Za-z0-9_-]{2,64})\b/gi)
741
+ ];
742
+ for (const m of matches) {
743
+ if (m[1]) studios.push({ studio_id: m[1] });
744
+ }
745
+ return { ok: true, studios, rawText: parsed.text };
746
+ } catch (err) {
747
+ return {
748
+ ok: false,
749
+ studios: [],
750
+ rawText: err instanceof Error ? err.message : String(err)
751
+ };
752
+ }
753
+ }
754
+ /**
755
+ * Automatically resolves `studio_id` when the caller omits it and exactly one Roblox Studio instance is connected.
756
+ */
757
+ async resolveStudioId(explicitStudioId) {
758
+ if (explicitStudioId && explicitStudioId.trim()) {
759
+ return {
760
+ ok: true,
761
+ studioId: explicitStudioId.trim(),
762
+ studios: [{ studio_id: explicitStudioId.trim() }],
763
+ autoSelected: false
764
+ };
765
+ }
766
+ const listed = await this.listStudios();
767
+ if (!listed.ok) {
768
+ return {
769
+ ok: false,
770
+ studios: [],
771
+ autoSelected: false,
772
+ err: `Could not query Roblox Studio MCP (${this.batchPath}): ${listed.rawText}`
773
+ };
774
+ }
775
+ if (listed.studios.length === 1 && listed.studios[0]) {
776
+ return {
777
+ ok: true,
778
+ studioId: listed.studios[0].studio_id,
779
+ studios: listed.studios,
780
+ autoSelected: true
781
+ };
782
+ }
783
+ if (listed.studios.length === 0) {
784
+ return {
785
+ ok: false,
786
+ studios: [],
787
+ autoSelected: false,
788
+ err: "No connected Roblox Studio instance found via %LOCALAPPDATA%\\Roblox\\mcp.bat. Open a place in Roblox Studio with MCP enabled first."
789
+ };
790
+ }
791
+ const listStr = listed.studios.map((s) => `${s.studio_id}${s.place_name ? ` ("${s.place_name}")` : ""}`).join(", ");
792
+ return {
793
+ ok: false,
794
+ studios: listed.studios,
795
+ autoSelected: false,
796
+ err: `Multiple Roblox Studio instances are open (${listStr}); pass studio_id explicitly.`
797
+ };
798
+ }
799
+ async callTool(name, args = {}) {
800
+ const finalArgs = { ...args };
801
+ let studioId = typeof finalArgs.studio_id === "string" ? finalArgs.studio_id.trim() : void 0;
802
+ let autoSelected = false;
803
+ if (!studioId && name !== "list_studios" && name !== "get_studios") {
804
+ const resolved = await this.resolveStudioId();
805
+ if (!resolved.ok) {
806
+ return { ok: false, text: resolved.err ?? "Failed to resolve studio_id", isError: true };
807
+ }
808
+ studioId = resolved.studioId;
809
+ autoSelected = resolved.autoSelected;
810
+ if (studioId) {
811
+ finalArgs.studio_id = studioId;
812
+ }
813
+ }
814
+ try {
815
+ const rpcRes = await this.sendRpc("tools/call", { name, arguments: finalArgs });
816
+ const parsed = parseStudioToolResponse(rpcRes);
817
+ return {
818
+ ...parsed,
819
+ studioId,
820
+ autoSelected
821
+ };
822
+ } catch (err) {
823
+ return {
824
+ ok: false,
825
+ text: err instanceof Error ? err.message : String(err),
826
+ studioId,
827
+ autoSelected,
828
+ isError: true
829
+ };
830
+ }
831
+ }
832
+ async runStudioLuau(code, explicitStudioId) {
833
+ const resolved = await this.resolveStudioId(explicitStudioId);
834
+ if (!resolved.ok) {
835
+ return {
836
+ ok: false,
837
+ text: resolved.err ?? "Could not resolve Roblox Studio instance",
838
+ isError: true
839
+ };
840
+ }
841
+ const tools = await this.listTools();
842
+ const execTool = tools.find((t) => t === "run_code" || t === "execute_luau" || t === "run_script" || t === "eval") ?? "run_code";
843
+ const res = await this.callTool(execTool, {
844
+ command: code,
845
+ code,
846
+ source: code,
847
+ ...resolved.studioId ? { studio_id: resolved.studioId } : {}
848
+ });
849
+ return {
850
+ ...res,
851
+ studioId: resolved.studioId,
852
+ autoSelected: resolved.autoSelected
853
+ };
854
+ }
855
+ };
856
+ function paethPredictor(a, b, c) {
857
+ const p = a + b - c;
858
+ const pa = Math.abs(p - a);
859
+ const pb = Math.abs(p - b);
860
+ const pc = Math.abs(p - c);
861
+ if (pa <= pb && pa <= pc) return a;
862
+ if (pb <= pc) return b;
863
+ return c;
864
+ }
865
+ function decodePngRgba(base64Data) {
866
+ try {
867
+ const buf = Buffer.from(base64Data, "base64");
868
+ if (buf.length < 33) return null;
869
+ if (buf[0] !== 137 || buf[1] !== 80 || buf[2] !== 78 || buf[3] !== 71) return null;
870
+ let offset = 8;
871
+ let width = 0;
872
+ let height = 0;
873
+ let bitDepth = 0;
874
+ let colorType = 0;
875
+ const idatChunks = [];
876
+ while (offset + 8 <= buf.length) {
877
+ const len = buf.readUInt32BE(offset);
878
+ const type = buf.toString("ascii", offset + 4, offset + 8);
879
+ const dataStart = offset + 8;
880
+ const dataEnd = dataStart + len;
881
+ if (dataEnd + 4 > buf.length) break;
882
+ if (type === "IHDR" && len >= 13) {
883
+ width = buf.readUInt32BE(dataStart);
884
+ height = buf.readUInt32BE(dataStart + 4);
885
+ bitDepth = buf[dataStart + 8] ?? 0;
886
+ colorType = buf[dataStart + 9] ?? 0;
887
+ } else if (type === "IDAT") {
888
+ idatChunks.push(buf.subarray(dataStart, dataEnd));
889
+ } else if (type === "IEND") {
890
+ break;
891
+ }
892
+ offset = dataEnd + 4;
893
+ }
894
+ if (width <= 0 || height <= 0 || bitDepth !== 8 || idatChunks.length === 0) return null;
895
+ const channels = colorType === 6 ? 4 : colorType === 2 ? 3 : colorType === 0 ? 1 : 0;
896
+ if (channels === 0) return null;
897
+ const compressed = Buffer.concat(idatChunks);
898
+ const raw = inflateSync(compressed);
899
+ const stride = width * channels;
900
+ if (raw.length < height * (stride + 1)) return null;
901
+ const unfiltered = new Uint8Array(height * stride);
902
+ for (let y = 0; y < height; y++) {
903
+ const filterType = raw[y * (stride + 1)] ?? 0;
904
+ const rowIn = y * (stride + 1) + 1;
905
+ const rowOut = y * stride;
906
+ const prevRowOut = (y - 1) * stride;
907
+ for (let x = 0; x < stride; x++) {
908
+ const rawByte = raw[rowIn + x] ?? 0;
909
+ const a = x >= channels ? unfiltered[rowOut + x - channels] ?? 0 : 0;
910
+ const b = y > 0 ? unfiltered[prevRowOut + x] ?? 0 : 0;
911
+ const c = y > 0 && x >= channels ? unfiltered[prevRowOut + x - channels] ?? 0 : 0;
912
+ let val = rawByte;
913
+ if (filterType === 1) val = rawByte + a & 255;
914
+ else if (filterType === 2) val = rawByte + b & 255;
915
+ else if (filterType === 3) val = rawByte + (a + b >> 1) & 255;
916
+ else if (filterType === 4) val = rawByte + paethPredictor(a, b, c) & 255;
917
+ unfiltered[rowOut + x] = val;
918
+ }
919
+ }
920
+ const rgba = new Uint8Array(width * height * 4);
921
+ for (let i = 0; i < width * height; i++) {
922
+ if (channels === 4) {
923
+ rgba[i * 4] = unfiltered[i * 4] ?? 0;
924
+ rgba[i * 4 + 1] = unfiltered[i * 4 + 1] ?? 0;
925
+ rgba[i * 4 + 2] = unfiltered[i * 4 + 2] ?? 0;
926
+ rgba[i * 4 + 3] = unfiltered[i * 4 + 3] ?? 255;
927
+ } else if (channels === 3) {
928
+ rgba[i * 4] = unfiltered[i * 3] ?? 0;
929
+ rgba[i * 4 + 1] = unfiltered[i * 3 + 1] ?? 0;
930
+ rgba[i * 4 + 2] = unfiltered[i * 3 + 2] ?? 0;
931
+ rgba[i * 4 + 3] = 255;
932
+ } else {
933
+ const g = unfiltered[i] ?? 0;
934
+ rgba[i * 4] = g;
935
+ rgba[i * 4 + 1] = g;
936
+ rgba[i * 4 + 2] = g;
937
+ rgba[i * 4 + 3] = 255;
938
+ }
939
+ }
940
+ return { width, height, rgba };
941
+ } catch {
942
+ return null;
943
+ }
944
+ }
945
+ function comparePngBase64(b64A, b64B, metaA, metaB) {
946
+ if (b64A === b64B) {
947
+ return {
948
+ widthA: metaA?.width,
949
+ heightA: metaA?.height,
950
+ widthB: metaB?.width,
951
+ heightB: metaB?.height,
952
+ sameDimensions: true,
953
+ similarityPct: 100,
954
+ diffPct: 0,
955
+ changedCells: [],
956
+ gridSummary: "Images are 100% byte-identical (0.0% diff across all 4x4 grid regions)."
957
+ };
958
+ }
959
+ const imgA = decodePngRgba(b64A);
960
+ const imgB = decodePngRgba(b64B);
961
+ if (!imgA || !imgB) {
962
+ const lenA = Buffer.byteLength(b64A, "base64");
963
+ const lenB = Buffer.byteLength(b64B, "base64");
964
+ const ratio = Math.max(lenA, lenB) > 0 ? Math.min(lenA, lenB) / Math.max(lenA, lenB) : 1;
965
+ const sim = Math.round(ratio * 1e3) / 10;
966
+ return {
967
+ widthA: metaA?.width,
968
+ heightA: metaA?.height,
969
+ widthB: metaB?.width,
970
+ heightB: metaB?.height,
971
+ sameDimensions: metaA?.width === metaB?.width && metaA?.height === metaB?.height,
972
+ similarityPct: sim,
973
+ diffPct: Math.round((100 - sim) * 10) / 10,
974
+ changedCells: [],
975
+ gridSummary: `Binary size comparison: A=${lenA} bytes, B=${lenB} bytes (~${sim}% size similarity).`
976
+ };
977
+ }
978
+ const gridRows = 4;
979
+ const gridCols = 4;
980
+ const samplesPerCell = 16;
981
+ const totalCols = gridCols * samplesPerCell;
982
+ const totalRows = gridRows * samplesPerCell;
983
+ let totalDiff = 0;
984
+ let totalSamples = 0;
985
+ const changedCells = [];
986
+ const cellLines = [];
987
+ const rowLabels = ["Top", "UpperMid", "LowerMid", "Bottom"];
988
+ const colLabels = ["Left", "CenterLeft", "CenterRight", "Right"];
989
+ for (let gr = 0; gr < gridRows; gr++) {
990
+ for (let gc = 0; gc < gridCols; gc++) {
991
+ let cellDiff = 0;
992
+ let cellCount = 0;
993
+ for (let sr = 0; sr < samplesPerCell; sr++) {
994
+ for (let sc = 0; sc < samplesPerCell; sc++) {
995
+ const u = (gc * samplesPerCell + sc + 0.5) / totalCols;
996
+ const v = (gr * samplesPerCell + sr + 0.5) / totalRows;
997
+ const ax = Math.min(imgA.width - 1, Math.floor(u * imgA.width));
998
+ const ay = Math.min(imgA.height - 1, Math.floor(v * imgA.height));
999
+ const bx = Math.min(imgB.width - 1, Math.floor(u * imgB.width));
1000
+ const by = Math.min(imgB.height - 1, Math.floor(v * imgB.height));
1001
+ const aIdx = (ay * imgA.width + ax) * 4;
1002
+ const bIdx = (by * imgB.width + bx) * 4;
1003
+ const dr = Math.abs((imgA.rgba[aIdx] ?? 0) - (imgB.rgba[bIdx] ?? 0));
1004
+ const dg = Math.abs((imgA.rgba[aIdx + 1] ?? 0) - (imgB.rgba[bIdx + 1] ?? 0));
1005
+ const db = Math.abs((imgA.rgba[aIdx + 2] ?? 0) - (imgB.rgba[bIdx + 2] ?? 0));
1006
+ const d = (dr + dg + db) / (255 * 3);
1007
+ cellDiff += d;
1008
+ cellCount++;
1009
+ totalDiff += d;
1010
+ totalSamples++;
1011
+ }
1012
+ }
1013
+ const cellPct = Math.round(cellDiff / Math.max(1, cellCount) * 1e3) / 10;
1014
+ const label = `${rowLabels[gr]}-${colLabels[gc]}`;
1015
+ if (cellPct >= 5) {
1016
+ changedCells.push(`${label} (${cellPct}% diff)`);
1017
+ }
1018
+ cellLines.push(`${label}:${cellPct}%`);
1019
+ }
1020
+ }
1021
+ const diffPct = Math.round(totalDiff / Math.max(1, totalSamples) * 1e3) / 10;
1022
+ const similarityPct = Math.max(0, Math.round((100 - diffPct) * 10) / 10);
1023
+ return {
1024
+ widthA: imgA.width,
1025
+ heightA: imgA.height,
1026
+ widthB: imgB.width,
1027
+ heightB: imgB.height,
1028
+ sameDimensions: imgA.width === imgB.width && imgA.height === imgB.height,
1029
+ similarityPct,
1030
+ diffPct,
1031
+ changedCells,
1032
+ gridSummary: `4x4 region diff: ${cellLines.join(", ")}`
1033
+ };
1034
+ }
1035
+
1036
+ // src/windows.ts
1037
+ import { execFile, spawn as spawn2 } from "node:child_process";
1038
+ import { existsSync as existsSync3, readdirSync, statSync } from "node:fs";
1039
+ import { homedir as homedir3 } from "node:os";
1040
+ import { join as join3 } from "node:path";
1041
+ import { createInterface as createInterface2 } from "node:readline";
500
1042
  import { promisify } from "node:util";
501
1043
  var execFileAsync = promisify(execFile);
502
1044
  function encodePowerShellCommand(script) {
@@ -520,25 +1062,25 @@ function buildRobloxDeepLink(params) {
520
1062
  return `roblox://experiences/start?${queryParts.join("&")}`;
521
1063
  }
522
1064
  function findRobloxPlayerBinary(env = process.env) {
523
- if (env.ROBLOX_PLAYER_PATH && existsSync2(env.ROBLOX_PLAYER_PATH)) {
1065
+ if (env.ROBLOX_PLAYER_PATH && existsSync3(env.ROBLOX_PLAYER_PATH)) {
524
1066
  return env.ROBLOX_PLAYER_PATH;
525
1067
  }
526
- const home = homedir2();
527
- const localAppData = env.LOCALAPPDATA || join2(home, "AppData", "Local");
1068
+ const home = homedir3();
1069
+ const localAppData = env.LOCALAPPDATA || join3(home, "AppData", "Local");
528
1070
  const roots = [
529
- join2(localAppData, "Roblox", "Versions"),
530
- join2(localAppData, "Bloxstrap", "Versions"),
531
- join2(localAppData, "Fishstrap", "Versions"),
1071
+ join3(localAppData, "Roblox", "Versions"),
1072
+ join3(localAppData, "Bloxstrap", "Versions"),
1073
+ join3(localAppData, "Fishstrap", "Versions"),
532
1074
  "C:\\Program Files (x86)\\Roblox\\Versions"
533
1075
  ];
534
1076
  let newestExe = null;
535
1077
  let newestMtime = -1;
536
1078
  for (const root of roots) {
537
- if (!existsSync2(root)) continue;
1079
+ if (!existsSync3(root)) continue;
538
1080
  try {
539
1081
  for (const entry of readdirSync(root)) {
540
- const exe = join2(root, entry, "RobloxPlayerBeta.exe");
541
- if (existsSync2(exe)) {
1082
+ const exe = join3(root, entry, "RobloxPlayerBeta.exe");
1083
+ if (existsSync3(exe)) {
542
1084
  const st = statSync(exe);
543
1085
  if (st.mtimeMs > newestMtime) {
544
1086
  newestMtime = st.mtimeMs;
@@ -552,21 +1094,21 @@ function findRobloxPlayerBinary(env = process.env) {
552
1094
  return newestExe;
553
1095
  }
554
1096
  function findPotassiumBinary(customPath, env = process.env) {
555
- if (customPath && existsSync2(customPath)) return customPath;
556
- if (env.POTASSIUM_PATH && existsSync2(env.POTASSIUM_PATH)) return env.POTASSIUM_PATH;
557
- const home = homedir2();
558
- const localAppData = env.LOCALAPPDATA || join2(home, "AppData", "Local");
559
- const appData = env.APPDATA || join2(home, "AppData", "Roaming");
1097
+ if (customPath && existsSync3(customPath)) return customPath;
1098
+ if (env.POTASSIUM_PATH && existsSync3(env.POTASSIUM_PATH)) return env.POTASSIUM_PATH;
1099
+ const home = homedir3();
1100
+ const localAppData = env.LOCALAPPDATA || join3(home, "AppData", "Local");
1101
+ const appData = env.APPDATA || join3(home, "AppData", "Roaming");
560
1102
  const candidates = [
561
- join2(localAppData, "Potassium", "Potassium.exe"),
562
- join2(appData, "Potassium", "Potassium.exe"),
563
- join2(home, "Desktop", "Potassium.exe"),
564
- join2(home, "Desktop", "Potassium", "Potassium.exe"),
565
- join2(home, "Downloads", "Potassium", "Potassium.exe"),
1103
+ join3(localAppData, "Potassium", "Potassium.exe"),
1104
+ join3(appData, "Potassium", "Potassium.exe"),
1105
+ join3(home, "Desktop", "Potassium.exe"),
1106
+ join3(home, "Desktop", "Potassium", "Potassium.exe"),
1107
+ join3(home, "Downloads", "Potassium", "Potassium.exe"),
566
1108
  "C:\\Potassium\\Potassium.exe"
567
1109
  ];
568
1110
  for (const c of candidates) {
569
- if (existsSync2(c)) return c;
1111
+ if (existsSync3(c)) return c;
570
1112
  }
571
1113
  return null;
572
1114
  }
@@ -710,8 +1252,35 @@ namespace Luaward {
710
1252
  [DllImport("user32.dll")] public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
711
1253
  [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint uCode, uint uMapType);
712
1254
  [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);
1255
+ [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT Point);
1256
+ [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr hwnd, uint gaFlags);
1257
+ [DllImport("user32.dll")] public static extern bool IsChild(IntPtr hWndParent, IntPtr hWnd);
713
1258
 
1259
+ public const uint GA_ROOT = 2;
714
1260
  public const uint PW_RENDERFULLCONTENT = 0x00000002;
1261
+
1262
+ public static bool IsWindowTopAtPoint(IntPtr targetHwnd, int x, int y) {
1263
+ if (targetHwnd == IntPtr.Zero) return false;
1264
+ POINT pt = new POINT { X = x, Y = y };
1265
+ IntPtr hit = WindowFromPoint(pt);
1266
+ if (hit == IntPtr.Zero) return false;
1267
+ if (hit == targetHwnd || IsChild(targetHwnd, hit)) return true;
1268
+ IntPtr root = GetAncestor(hit, GA_ROOT);
1269
+ return root == targetHwnd;
1270
+ }
1271
+
1272
+ public static bool IsWindowUnoccluded(IntPtr targetHwnd, int left, int top, int width, int height) {
1273
+ if (targetHwnd == IntPtr.Zero || width <= 0 || height <= 0) return false;
1274
+ int cx = left + (width / 2);
1275
+ int cy = top + (height / 2);
1276
+ int insetX = Math.Max(4, Math.Min(40, width / 6));
1277
+ int insetY = Math.Max(4, Math.Min(40, height / 6));
1278
+ return IsWindowTopAtPoint(targetHwnd, cx, cy)
1279
+ && IsWindowTopAtPoint(targetHwnd, left + insetX, top + insetY)
1280
+ && IsWindowTopAtPoint(targetHwnd, left + width - insetX, top + insetY)
1281
+ && IsWindowTopAtPoint(targetHwnd, left + insetX, top + height - insetY)
1282
+ && IsWindowTopAtPoint(targetHwnd, left + width - insetX, top + height - insetY);
1283
+ }
715
1284
  public const uint INPUT_MOUSE = 0;
716
1285
  public const uint INPUT_KEYBOARD = 1;
717
1286
  public const uint MOUSEEVENTF_MOVE = 0x0001;
@@ -865,7 +1434,7 @@ var PowerShellWindowsDriver = class {
865
1434
  return this.workerReady;
866
1435
  }
867
1436
  const encodedBootstrap = encodePowerShellCommand(PS_WORKER_BOOTSTRAP);
868
- const child = spawn(
1437
+ const child = spawn2(
869
1438
  "powershell.exe",
870
1439
  ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encodedBootstrap],
871
1440
  { stdio: ["pipe", "pipe", "pipe"], windowsHide: true }
@@ -880,7 +1449,7 @@ var PowerShellWindowsDriver = class {
880
1449
  child.stderr.on("data", (chunk) => {
881
1450
  stderrBuf = (stderrBuf + String(chunk)).slice(-2e3);
882
1451
  });
883
- const rl = createInterface({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY });
1452
+ const rl = createInterface2({ input: child.stdout, crlfDelay: Number.POSITIVE_INFINITY });
884
1453
  this.workerReady = new Promise((resolveReady, rejectReady) => {
885
1454
  let isReady = false;
886
1455
  const readyTimer = setTimeout(() => {
@@ -1145,6 +1714,11 @@ $h = [IntPtr]::new([Convert]::ToInt64("${win.hwnd}", 16))
1145
1714
  if (!pw) return { ok: false, text: "Potassium window not found for relative_to=potassium_window" };
1146
1715
  baseX = pw.rect.left;
1147
1716
  baseY = pw.rect.top;
1717
+ } else if (params.relativeTo === "studio_window") {
1718
+ const sw = (await this.listWindows("studio"))[0];
1719
+ if (!sw) return { ok: false, text: "Roblox Studio window not found for relative_to=studio_window" };
1720
+ baseX = sw.clientRect.width > 0 ? sw.clientRect.screenLeft : sw.rect.left;
1721
+ baseY = sw.clientRect.height > 0 ? sw.clientRect.screenTop : sw.rect.top;
1148
1722
  }
1149
1723
  const screenX = Math.round((params.x ?? 0) + baseX);
1150
1724
  const screenY = Math.round((params.y ?? 0) + baseY);
@@ -1345,7 +1919,7 @@ $sent += [int][Luaward.Win32Desktop]::SendKeyVk(${vk}, $true)
1345
1919
  async launchRoblox(params) {
1346
1920
  const deepLink = buildRobloxDeepLink(params);
1347
1921
  const bin = params.binaryPath || (params.directBinary ? findRobloxPlayerBinary() : null);
1348
- if (bin && existsSync2(bin)) {
1922
+ if (bin && existsSync3(bin)) {
1349
1923
  const b64Bin = Buffer.from(bin, "utf8").toString("base64");
1350
1924
  const b64Link2 = Buffer.from(deepLink, "utf8").toString("base64");
1351
1925
  const res = await this.runPsJson(`
@@ -1565,23 +2139,47 @@ function Capture-ViaPrintWindow {
1565
2139
  }
1566
2140
  }
1567
2141
 
1568
- $result = $null
1569
- if ($method -eq "printwindow" -and $hasHwnd) {
1570
- $result = Capture-ViaPrintWindow
1571
- } else {
2142
+ function Capture-ViaCopyFromScreen {
1572
2143
  $bmp = New-Object System.Drawing.Bitmap $w, $h
1573
2144
  $g = [System.Drawing.Graphics]::FromImage($bmp)
1574
2145
  try {
1575
2146
  $g.CopyFromScreen($left, $top, 0, 0, (New-Object System.Drawing.Size($w, $h)))
1576
2147
  $ms = New-Object System.IO.MemoryStream
1577
2148
  $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
1578
- $result = @{
2149
+ return @{
1579
2150
  ok = $true
1580
2151
  width = $w
1581
2152
  height = $h
1582
2153
  captureMethod = "copy"
1583
2154
  data = [Convert]::ToBase64String($ms.ToArray())
1584
2155
  }
2156
+ } finally {
2157
+ $g.Dispose()
2158
+ $bmp.Dispose()
2159
+ }
2160
+ }
2161
+
2162
+ $result = $null
2163
+ $hwndPtr = [IntPtr]::new([Convert]::ToInt64("${opts.hwnd || "0x0"}", 16))
2164
+ $isTop = $hasHwnd -and [Luaward.Win32Desktop]::IsWindowUnoccluded($hwndPtr, $left, $top, $w, $h)
2165
+ if ($hasHwnd -and ($method -eq "printwindow" -or ($method -eq "auto" -and (-not $isTop)))) {
2166
+ try {
2167
+ $result = Capture-ViaPrintWindow
2168
+ } catch {
2169
+ $pwErr = $_.Exception.Message
2170
+ if ($method -eq "auto") {
2171
+ try {
2172
+ $result = Capture-ViaCopyFromScreen
2173
+ } catch {
2174
+ $result = @{ ok = $false; err = "PrintWindow failed ($pwErr); CopyFromScreen fallback failed ($($_.Exception.Message))" }
2175
+ }
2176
+ } else {
2177
+ $result = @{ ok = $false; err = "PrintWindow failed: $pwErr" }
2178
+ }
2179
+ }
2180
+ } else {
2181
+ try {
2182
+ $result = Capture-ViaCopyFromScreen
1585
2183
  } catch {
1586
2184
  $copyErr = $_.Exception.Message
1587
2185
  if ($method -eq "auto" -and $hasHwnd) {
@@ -1593,19 +2191,32 @@ if ($method -eq "printwindow" -and $hasHwnd) {
1593
2191
  } else {
1594
2192
  $result = @{ ok = $false; err = "CopyFromScreen failed: $copyErr" }
1595
2193
  }
1596
- } finally {
1597
- $g.Dispose()
1598
- $bmp.Dispose()
1599
2194
  }
1600
2195
  }
1601
2196
  $result | ConvertTo-Json -Compress
1602
2197
  `;
1603
2198
  }
2199
+ function isRobloxStudioWindow(w) {
2200
+ const proc = w.processName.toLowerCase();
2201
+ const title = w.title.toLowerCase();
2202
+ const cls = w.className.toLowerCase();
2203
+ return proc.includes("robloxstudiobeta") || proc === "robloxstudio" || title.includes("roblox studio") || cls.includes("qt5") && proc.includes("studio");
2204
+ }
2205
+ function isRobloxPlayerWindow(w) {
2206
+ if (isRobloxStudioWindow(w)) return false;
2207
+ const proc = w.processName.toLowerCase();
2208
+ const title = w.title.toLowerCase();
2209
+ const cls = w.className.toLowerCase();
2210
+ return proc.includes("robloxplayerbeta") || proc === "robloxplayer" || proc.includes("roblox") && !proc.includes("studio") || title === "roblox" || cls.includes("windowsclient");
2211
+ }
1604
2212
  function matchesWindowTarget(w, filter) {
1605
2213
  const f = filter.trim().toLowerCase();
1606
2214
  if (!f || f === "all") return true;
1607
- if (f === "roblox") {
1608
- return w.processName.toLowerCase().includes("roblox") || w.title.toLowerCase() === "roblox" || w.className.toLowerCase().includes("windowsclient");
2215
+ if (f === "roblox" || f === "roblox_player" || f === "player") {
2216
+ return isRobloxPlayerWindow(w);
2217
+ }
2218
+ if (f === "studio" || f === "roblox_studio" || f === "robloxstudiobeta") {
2219
+ return isRobloxStudioWindow(w);
1609
2220
  }
1610
2221
  if (f === "potassium") {
1611
2222
  return w.processName.toLowerCase().includes("potassium") || w.title.toLowerCase().includes("potassium");
@@ -1615,13 +2226,15 @@ function matchesWindowTarget(w, filter) {
1615
2226
  }
1616
2227
 
1617
2228
  // src/index.ts
1618
- var MCP_BRIDGE_VERSION = "0.2.2";
2229
+ var MCP_BRIDGE_VERSION = "0.2.3";
1619
2230
  var DEFAULT_MCP_URL = "https://luaward.com/mcp";
2231
+ var TOKEN_CREATE_URL = "https://dash.luaward.com/dashboard/ai";
1620
2232
  var TOKEN_SHAPE = /^lwm_[0-9a-f]{48}$/;
2233
+ var POTASSIUM_ENABLE_HINT = "To enable Potassium Local MCP (port 8225): open Potassium -> Settings (gear icon) -> MCP Server -> enable 'MCP Server' on port 8225 and attach Potassium to RobloxPlayerBeta.exe (or run editor_tabs action='install_autoexec' once to auto-connect on future attaches).";
1621
2234
  function resolveStoredToken(configDir) {
1622
- const base = configDir || process.env.LUAWARD_CONFIG_DIR || join3(homedir3(), ".config", "luaward");
1623
- const credPath = join3(base, "credentials.json");
1624
- if (!existsSync3(credPath)) return {};
2235
+ const base = configDir || process.env.LUAWARD_CONFIG_DIR || join4(homedir4(), ".config", "luaward");
2236
+ const credPath = join4(base, "credentials.json");
2237
+ if (!existsSync4(credPath)) return {};
1625
2238
  try {
1626
2239
  const raw = JSON.parse(readFileSync2(credPath, "utf8"));
1627
2240
  const token = typeof raw.token === "string" && TOKEN_SHAPE.test(raw.token.trim()) ? raw.token.trim() : void 0;
@@ -1868,7 +2481,7 @@ var LOCAL_HYBRID_TOOLS = [
1868
2481
  },
1869
2482
  target: {
1870
2483
  type: "string",
1871
- description: 'Target window: "roblox" (default), "potassium", window title substring, PID, or HWND'
2484
+ description: 'Target window: "roblox" (RobloxPlayerBeta only, default), "studio" (RobloxStudioBeta), "potassium", window title substring, PID, or HWND'
1872
2485
  },
1873
2486
  x: { type: "integer", description: "Window top-left X coordinate for resize (default 80)" },
1874
2487
  y: { type: "integer", description: "Window top-left Y coordinate for resize (default 80)" },
@@ -1899,7 +2512,7 @@ var LOCAL_HYBRID_TOOLS = [
1899
2512
  properties: {
1900
2513
  target: {
1901
2514
  type: "string",
1902
- description: '"roblox" (default), "potassium", "screen", or window title substring'
2515
+ description: '"roblox" (RobloxPlayerBeta only, default), "studio" (RobloxStudioBeta), "potassium", "screen", or window title substring'
1903
2516
  },
1904
2517
  focus_first: {
1905
2518
  type: "boolean",
@@ -1934,7 +2547,7 @@ var LOCAL_HYBRID_TOOLS = [
1934
2547
  properties: {
1935
2548
  target: {
1936
2549
  type: "string",
1937
- description: '"potassium" (default), "roblox", or window title substring'
2550
+ description: '"potassium" (default), "roblox" (RobloxPlayerBeta), "studio" (RobloxStudioBeta), or window title substring'
1938
2551
  },
1939
2552
  max_depth: {
1940
2553
  type: "integer",
@@ -2005,8 +2618,16 @@ var LOCAL_HYBRID_TOOLS = [
2005
2618
  },
2006
2619
  relative_to: {
2007
2620
  type: "string",
2008
- enum: ["screen", "roblox_client", "potassium_window"],
2621
+ enum: ["screen", "roblox_client", "potassium_window", "studio_window"],
2009
2622
  description: "Coordinate origin (default 'screen')"
2623
+ },
2624
+ verify: {
2625
+ type: "boolean",
2626
+ description: "When true, verify after clicking/moving by querying UserInputService:GetMouseLocation() and returning a gui_snapshot diff (default false)"
2627
+ },
2628
+ session: {
2629
+ type: "string",
2630
+ description: "Optional Luaward game session selector when verify=true"
2010
2631
  }
2011
2632
  },
2012
2633
  required: ["action"],
@@ -2050,7 +2671,7 @@ var LOCAL_HYBRID_TOOLS = [
2050
2671
  },
2051
2672
  target: {
2052
2673
  type: "string",
2053
- description: 'Optional window to focus before sending keys ("roblox" or "potassium")'
2674
+ description: 'Optional window to focus before sending keys ("roblox", "studio", or "potassium")'
2054
2675
  }
2055
2676
  },
2056
2677
  required: ["action"],
@@ -2092,6 +2713,10 @@ var LOCAL_HYBRID_TOOLS = [
2092
2713
  type: "integer",
2093
2714
  description: "Optional vertical pixel offset from element center (default 0)"
2094
2715
  },
2716
+ verify: {
2717
+ type: "boolean",
2718
+ description: "When true, verify after clicking by querying UserInputService:GetMouseLocation() and returning a before/after gui_snapshot diff (default false)"
2719
+ },
2095
2720
  session: {
2096
2721
  type: "string",
2097
2722
  description: "Optional Luaward game session selector"
@@ -2107,35 +2732,401 @@ var LOCAL_HYBRID_TOOLS = [
2107
2732
  idempotentHint: false,
2108
2733
  openWorldHint: false
2109
2734
  }
2110
- }
2111
- ];
2112
- var HybridMcpBridge = class {
2113
- token;
2114
- url;
2115
- potassium;
2116
- windows;
2117
- autoInject;
2118
- autoInjectPollMs;
2119
- autoInjectMaxPolls;
2120
- fetchFn;
2121
- cachedPairCommand;
2122
- lastLaunchParams;
2123
- rpcSeq = 5e3;
2124
- constructor(options = {}) {
2125
- const resolved = resolveBridgeConfig([], process.env, options.configDir);
2126
- this.token = options.token !== void 0 ? options.token || null : resolved.token;
2127
- this.url = options.url ?? resolved.url;
2128
- this.fetchFn = options.fetchImpl ?? fetch;
2129
- this.cachedPairCommand = options.pairCommand ?? resolved.pairCommand;
2130
- this.autoInject = options.autoInject ?? resolved.autoInject;
2735
+ },
2736
+ {
2737
+ name: "studio_mirror_remotes",
2738
+ title: "Mirror live game remotes hierarchy into Roblox Studio",
2739
+ description: "Scan RemoteEvent, RemoteFunction, UnreliableRemoteEvent, BindableEvent, and BindableFunction hierarchy from the live connected game and reconstruct the exact folder and remote tree inside Roblox Studio via %LOCALAPPDATA%\\Roblox\\mcp.bat (auto-selecting studio_id when one Studio is open).",
2740
+ inputSchema: {
2741
+ type: "object",
2742
+ properties: {
2743
+ root: {
2744
+ type: "string",
2745
+ description: "Root service/path to mirror (default 'ReplicatedStorage')"
2746
+ },
2747
+ filter: {
2748
+ type: "string",
2749
+ description: "Optional case-insensitive path substring filter"
2750
+ },
2751
+ kind: {
2752
+ type: "string",
2753
+ enum: ["network", "bindable", "all"],
2754
+ description: "Remote kind filter (default 'all')"
2755
+ },
2756
+ max: {
2757
+ type: "integer",
2758
+ minimum: 1,
2759
+ maximum: 500,
2760
+ description: "Maximum remotes to mirror (default 200)"
2761
+ },
2762
+ studio_id: {
2763
+ type: "string",
2764
+ description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
2765
+ },
2766
+ session: {
2767
+ type: "string",
2768
+ description: "Optional live game session selector"
2769
+ }
2770
+ },
2771
+ additionalProperties: false
2772
+ },
2773
+ annotations: {
2774
+ title: "Mirror live game remotes into Roblox Studio",
2775
+ readOnlyHint: false,
2776
+ destructiveHint: false,
2777
+ idempotentHint: true,
2778
+ openWorldHint: false
2779
+ }
2780
+ },
2781
+ {
2782
+ name: "studio_mirror_gui",
2783
+ title: "Mirror live game GUI hierarchy into Roblox Studio StarterGui",
2784
+ description: "Capture a ScreenGui/GuiObject tree from the live connected game (including ClassName, Name, Position, Size, AnchorPoint, Visible, ZIndex, colors, Text, Image, UICorner, UIStroke, and layouts) and reconstruct it inside Roblox Studio's StarterGui via %LOCALAPPDATA%\\Roblox\\mcp.bat.",
2785
+ inputSchema: {
2786
+ type: "object",
2787
+ properties: {
2788
+ target: {
2789
+ type: "string",
2790
+ description: "Live GUI root path or #n handle to mirror (default 'Players.LocalPlayer.PlayerGui')"
2791
+ },
2792
+ studio_root: {
2793
+ type: "string",
2794
+ description: "Destination container in Roblox Studio (default 'StarterGui')"
2795
+ },
2796
+ depth: {
2797
+ type: "integer",
2798
+ minimum: 1,
2799
+ maximum: 12,
2800
+ description: "Maximum hierarchy depth (default 6)"
2801
+ },
2802
+ max_instances: {
2803
+ type: "integer",
2804
+ minimum: 1,
2805
+ maximum: 600,
2806
+ description: "Maximum GUI instances to mirror (default 250)"
2807
+ },
2808
+ only_visible: {
2809
+ type: "boolean",
2810
+ description: "Only mirror visible GUI elements (default false)"
2811
+ },
2812
+ studio_id: {
2813
+ type: "string",
2814
+ description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
2815
+ },
2816
+ session: {
2817
+ type: "string",
2818
+ description: "Optional live game session selector"
2819
+ }
2820
+ },
2821
+ additionalProperties: false
2822
+ },
2823
+ annotations: {
2824
+ title: "Mirror live game GUI into Roblox Studio",
2825
+ readOnlyHint: false,
2826
+ destructiveHint: false,
2827
+ idempotentHint: true,
2828
+ openWorldHint: false
2829
+ }
2830
+ },
2831
+ {
2832
+ name: "studio_diff",
2833
+ title: "Diff scripts, remotes, or GUI between Roblox Studio and live game",
2834
+ description: "Compare scripts, remotes, or GUI hierarchy between Roblox Studio (%LOCALAPPDATA%\\Roblox\\mcp.bat) and the live connected Roblox game, reporting items only in live, only in Studio, modified items, and line diffs.",
2835
+ inputSchema: {
2836
+ type: "object",
2837
+ properties: {
2838
+ scope: {
2839
+ type: "string",
2840
+ enum: ["scripts", "remotes", "gui", "all"],
2841
+ description: "What to compare (default 'scripts')"
2842
+ },
2843
+ target: {
2844
+ type: "string",
2845
+ description: "Optional root or specific script path to compare (default 'ReplicatedStorage')"
2846
+ },
2847
+ studio_id: {
2848
+ type: "string",
2849
+ description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
2850
+ },
2851
+ session: {
2852
+ type: "string",
2853
+ description: "Optional live game session selector"
2854
+ }
2855
+ },
2856
+ additionalProperties: false
2857
+ },
2858
+ annotations: {
2859
+ title: "Diff Roblox Studio vs live game",
2860
+ readOnlyHint: true,
2861
+ destructiveHint: false,
2862
+ idempotentHint: true,
2863
+ openWorldHint: false
2864
+ }
2865
+ },
2866
+ {
2867
+ name: "studio_to_live",
2868
+ title: "Run a Roblox Studio script directly in the live game",
2869
+ description: "Read a Script/LocalScript/ModuleScript source from Roblox Studio (by studio_path or current Selection via %LOCALAPPDATA%\\Roblox\\mcp.bat) and execute it immediately in the live connected Roblox game via run_and_collect.",
2870
+ inputSchema: {
2871
+ type: "object",
2872
+ properties: {
2873
+ studio_path: {
2874
+ type: "string",
2875
+ description: "Script path in Roblox Studio (e.g. 'StarterPlayer.StarterPlayerScripts.Main') or 'Selection' for currently selected script (default 'Selection')"
2876
+ },
2877
+ clean_env: {
2878
+ type: "boolean",
2879
+ description: "Run in clean native Luau SAFEENV environment (default true)"
2880
+ },
2881
+ track_resources: {
2882
+ type: "boolean",
2883
+ description: "Track resources in snapshot mode for cleanup_run (default true)"
2884
+ },
2885
+ auto_cleanup: {
2886
+ type: "boolean",
2887
+ description: "Automatically clean up resources after collecting logs (default false)"
2888
+ },
2889
+ settle_ms: {
2890
+ type: "integer",
2891
+ minimum: 0,
2892
+ maximum: 15e3,
2893
+ description: "Settle window in ms after return (default 300)"
2894
+ },
2895
+ studio_id: {
2896
+ type: "string",
2897
+ description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
2898
+ },
2899
+ session: {
2900
+ type: "string",
2901
+ description: "Optional live game session selector"
2902
+ }
2903
+ },
2904
+ additionalProperties: false
2905
+ },
2906
+ annotations: {
2907
+ title: "Run Roblox Studio script in live game",
2908
+ readOnlyHint: false,
2909
+ destructiveHint: true,
2910
+ idempotentHint: false,
2911
+ openWorldHint: false
2912
+ }
2913
+ },
2914
+ {
2915
+ name: "studio_publish",
2916
+ title: "Publish a Roblox Studio script to Luaward Cloud",
2917
+ description: "Read a script's Luau source directly from Roblox Studio (%LOCALAPPDATA%\\Roblox\\mcp.bat) and deploy/protect it on Luaward Cloud via deploy_script.",
2918
+ inputSchema: {
2919
+ type: "object",
2920
+ properties: {
2921
+ script: {
2922
+ type: "string",
2923
+ description: "Target Luaward Cloud script name or ID"
2924
+ },
2925
+ studio_path: {
2926
+ type: "string",
2927
+ description: "Script path in Roblox Studio or 'Selection' for the currently selected script (default 'Selection')"
2928
+ },
2929
+ publish: {
2930
+ type: "boolean",
2931
+ description: "Promote build to live automatically (default true; false for staged draft)"
2932
+ },
2933
+ preset: {
2934
+ type: "string",
2935
+ enum: ["fast", "balanced", "max"],
2936
+ description: "Optional protection preset"
2937
+ },
2938
+ studio_id: {
2939
+ type: "string",
2940
+ description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
2941
+ }
2942
+ },
2943
+ required: ["script"],
2944
+ additionalProperties: false
2945
+ },
2946
+ annotations: {
2947
+ title: "Publish Roblox Studio script to Luaward Cloud",
2948
+ readOnlyHint: false,
2949
+ destructiveHint: false,
2950
+ idempotentHint: false,
2951
+ openWorldHint: false
2952
+ }
2953
+ },
2954
+ {
2955
+ name: "live_scripts_to_studio",
2956
+ title: "Decompile live game scripts and import them into Roblox Studio",
2957
+ description: "Decompile LocalScripts and ModuleScripts from the live connected game and create corresponding script instances with .Source populated inside Roblox Studio via %LOCALAPPDATA%\\Roblox\\mcp.bat.",
2958
+ inputSchema: {
2959
+ type: "object",
2960
+ properties: {
2961
+ targets: {
2962
+ type: "array",
2963
+ items: { type: "string" },
2964
+ description: "Explicit list of live script paths to import into Studio"
2965
+ },
2966
+ filter: {
2967
+ type: "string",
2968
+ description: "Case-insensitive path substring filter when targets is omitted (e.g. 'ReplicatedStorage')"
2969
+ },
2970
+ studio_root: {
2971
+ type: "string",
2972
+ description: "Optional destination container in Studio (e.g. 'ServerStorage.LiveImports'; omit to mirror into matching services)"
2973
+ },
2974
+ max: {
2975
+ type: "integer",
2976
+ minimum: 1,
2977
+ maximum: 100,
2978
+ description: "Maximum scripts to import in one call (default 15)"
2979
+ },
2980
+ disabled: {
2981
+ type: "boolean",
2982
+ description: "Set .Disabled = true on imported LocalScripts in Studio (default true)"
2983
+ },
2984
+ studio_id: {
2985
+ type: "string",
2986
+ description: "Optional Roblox Studio instance ID (auto-filled when 1 Studio is open)"
2987
+ },
2988
+ session: {
2989
+ type: "string",
2990
+ description: "Optional live game session selector"
2991
+ }
2992
+ },
2993
+ additionalProperties: false
2994
+ },
2995
+ annotations: {
2996
+ title: "Import live decompiled scripts into Roblox Studio",
2997
+ readOnlyHint: false,
2998
+ destructiveHint: false,
2999
+ idempotentHint: true,
3000
+ openWorldHint: false
3001
+ }
3002
+ },
3003
+ {
3004
+ name: "compare_screens",
3005
+ title: "Capture and compare screenshots between two windows (e.g. Roblox vs Studio)",
3006
+ description: "Capture screenshots of two desktop targets (default target_a='roblox' RobloxPlayerBeta vs target_b='studio' RobloxStudioBeta), compute pixel and 4x4 grid region similarity/difference metrics, and return both PNG images side by side.",
3007
+ inputSchema: {
3008
+ type: "object",
3009
+ properties: {
3010
+ target_a: {
3011
+ type: "string",
3012
+ description: "First window target (default 'roblox' - strictly RobloxPlayerBeta)"
3013
+ },
3014
+ target_b: {
3015
+ type: "string",
3016
+ description: "Second window target (default 'studio' - RobloxStudioBeta)"
3017
+ },
3018
+ client_only: {
3019
+ type: "boolean",
3020
+ description: "Capture inner client viewport only (default true)"
3021
+ },
3022
+ method: {
3023
+ type: "string",
3024
+ enum: ["auto", "copy", "printwindow"],
3025
+ description: "Capture method ('auto' uses WindowFromPoint occlusion detection + PrintWindow for background windows, default 'auto')"
3026
+ },
3027
+ focus_first: {
3028
+ type: "boolean",
3029
+ description: "Focus each window before capturing (default false)"
3030
+ }
3031
+ },
3032
+ additionalProperties: false
3033
+ },
3034
+ annotations: {
3035
+ title: "Compare screenshots between two windows",
3036
+ readOnlyHint: true,
3037
+ destructiveHint: false,
3038
+ idempotentHint: true,
3039
+ openWorldHint: false
3040
+ }
3041
+ }
3042
+ ];
3043
+ var HybridMcpBridge = class {
3044
+ token;
3045
+ url;
3046
+ potassium;
3047
+ windows;
3048
+ studio;
3049
+ autoInject;
3050
+ autoInjectPollMs;
3051
+ autoInjectMaxPolls;
3052
+ autoInjectCooldownMs;
3053
+ fetchFn;
3054
+ stderr;
3055
+ cachedPairCommand;
3056
+ lastLaunchParams;
3057
+ lastAutoInjectFailureAt = 0;
3058
+ lastAutoInjectFailureReason = "";
3059
+ scopeWarningEmitted = false;
3060
+ lastScopeWarning = null;
3061
+ rpcSeq = 5e3;
3062
+ constructor(options = {}) {
3063
+ const resolved = resolveBridgeConfig([], process.env, options.configDir);
3064
+ this.token = options.token !== void 0 ? options.token || null : resolved.token;
3065
+ this.url = options.url ?? resolved.url;
3066
+ this.fetchFn = options.fetchImpl ?? fetch;
3067
+ this.stderr = options.stderr ?? process.stderr;
3068
+ this.cachedPairCommand = options.pairCommand ?? resolved.pairCommand;
3069
+ this.autoInject = options.autoInject ?? resolved.autoInject;
2131
3070
  this.autoInjectPollMs = options.autoInjectPollMs ?? 400;
2132
3071
  this.autoInjectMaxPolls = options.autoInjectMaxPolls ?? 15;
3072
+ this.autoInjectCooldownMs = options.autoInjectCooldownMs ?? 3e4;
2133
3073
  this.potassium = options.potassiumClient ?? new PotassiumClient({
2134
3074
  url: options.potassiumUrl ?? resolved.potassiumUrl,
2135
3075
  token: options.potassiumToken !== void 0 ? options.potassiumToken : resolved.potassiumToken,
2136
3076
  fetchImpl: this.fetchFn
2137
3077
  });
2138
3078
  this.windows = options.windowsDriver ?? new PowerShellWindowsDriver();
3079
+ this.studio = options.studioClient ?? new RobloxStudioMcpClient(options.studioOptions);
3080
+ }
3081
+ evaluateTokenScopesFromTools(tools) {
3082
+ const names = new Set(tools.map((t) => String(t.name ?? "")));
3083
+ if (names.size === 0) {
3084
+ return { missingScopes: [], hiddenTools: [], warning: null };
3085
+ }
3086
+ const missingScopes = [];
3087
+ const hiddenTools = [];
3088
+ if (!names.has("spy_start") && !names.has("spy_stop")) {
3089
+ missingScopes.push("spy");
3090
+ hiddenTools.push("spy_start", "spy_stop");
3091
+ }
3092
+ if (!names.has("search_scripts") && !names.has("scripts_read") && !names.has("scripts_list")) {
3093
+ missingScopes.push("scripts");
3094
+ hiddenTools.push("search_scripts", "scripts_read", "scripts_list", "scripts_sync");
3095
+ }
3096
+ if (missingScopes.length === 0) {
3097
+ this.lastScopeWarning = null;
3098
+ return { missingScopes: [], hiddenTools: [], warning: null };
3099
+ }
3100
+ const warning = `[Luaward MCP Warning] Your MCP token is missing scope(s): ${missingScopes.join(", ")}. Tools (${hiddenTools.join(", ")}) will not appear in tools/list. Create a new token with full scopes (read, scripts, spy, control) at ${TOKEN_CREATE_URL}`;
3101
+ this.lastScopeWarning = warning;
3102
+ if (!this.scopeWarningEmitted) {
3103
+ this.scopeWarningEmitted = true;
3104
+ try {
3105
+ this.stderr.write(`${warning}
3106
+ `);
3107
+ } catch {
3108
+ }
3109
+ }
3110
+ return { missingScopes, hiddenTools, warning };
3111
+ }
3112
+ async checkTokenScopes() {
3113
+ if (!this.token) {
3114
+ return { missingScopes: [], hiddenTools: [], warning: null };
3115
+ }
3116
+ try {
3117
+ const res = await this.callCloudRpc({
3118
+ jsonrpc: "2.0",
3119
+ id: ++this.rpcSeq,
3120
+ method: "tools/list",
3121
+ params: {}
3122
+ });
3123
+ const tools = res.body?.result?.tools;
3124
+ if (Array.isArray(tools)) {
3125
+ return this.evaluateTokenScopesFromTools(tools);
3126
+ }
3127
+ } catch {
3128
+ }
3129
+ return { missingScopes: [], hiddenTools: [], warning: this.lastScopeWarning };
2139
3130
  }
2140
3131
  cloudHeaders(protoVer) {
2141
3132
  const headers = {
@@ -2218,54 +3209,83 @@ var HybridMcpBridge = class {
2218
3209
  }
2219
3210
  async tryZeroTouchAutoInject(opts) {
2220
3211
  const waitMs = Math.max(0, opts?.waitForClientMs ?? 0);
3212
+ if (!opts?.force && waitMs === 0 && this.lastAutoInjectFailureAt > 0 && this.autoInjectCooldownMs > 0) {
3213
+ const elapsed = Date.now() - this.lastAutoInjectFailureAt;
3214
+ if (elapsed < this.autoInjectCooldownMs) {
3215
+ const remSec = Math.max(1, Math.ceil((this.autoInjectCooldownMs - elapsed) / 1e3));
3216
+ return {
3217
+ injected: false,
3218
+ text: `Potassium auto-inject skipped (cooldown ${remSec}s remaining after: ${this.lastAutoInjectFailureReason}). ${POTASSIUM_ENABLE_HINT}`
3219
+ };
3220
+ }
3221
+ }
2221
3222
  const clientPollMs = Math.max(0, opts?.pollClientMs ?? Math.min(1e3, this.autoInjectPollMs || 500));
2222
3223
  const deadline = Date.now() + waitMs;
2223
3224
  let clientsRes = await this.potassium.listClients();
2224
- while ((!clientsRes.ok || clientsRes.clients.length === 0) && Date.now() < deadline) {
3225
+ while (clientsRes.ok && clientsRes.clients.length === 0 && Date.now() < deadline) {
2225
3226
  if (clientPollMs > 0) await sleep(clientPollMs);
2226
3227
  clientsRes = await this.potassium.listClients();
2227
3228
  }
2228
3229
  if (!clientsRes.ok) {
3230
+ this.lastAutoInjectFailureAt = Date.now();
3231
+ this.lastAutoInjectFailureReason = `Potassium local MCP error: ${clientsRes.rawText}`;
2229
3232
  return {
2230
3233
  injected: false,
2231
- text: `Potassium local MCP error: ${clientsRes.rawText}`
3234
+ text: `${this.lastAutoInjectFailureReason}. ${POTASSIUM_ENABLE_HINT}`
2232
3235
  };
2233
3236
  }
2234
3237
  if (clientsRes.clients.length === 0) {
3238
+ this.lastAutoInjectFailureAt = Date.now();
3239
+ this.lastAutoInjectFailureReason = waitMs > 0 ? `no attached Roblox client appeared in Potassium local MCP within ${Math.round(waitMs / 1e3)}s` : "no attached Roblox client found in Potassium local MCP";
2235
3240
  return {
2236
3241
  injected: false,
2237
- text: waitMs > 0 ? `no attached Roblox client appeared in Potassium local MCP within ${Math.round(waitMs / 1e3)}s` : "no attached Roblox client found in Potassium local MCP"
3242
+ text: this.lastAutoInjectFailureReason
2238
3243
  };
2239
3244
  }
2240
3245
  const pairCmd = await this.fetchWorkspacePairCommand();
2241
3246
  if (!pairCmd) {
2242
- return { injected: false, text: "could not fetch workspace pair command (luaward://pair)" };
3247
+ this.lastAutoInjectFailureAt = Date.now();
3248
+ this.lastAutoInjectFailureReason = "could not fetch workspace pair command (luaward://pair)";
3249
+ return { injected: false, text: this.lastAutoInjectFailureReason };
2243
3250
  }
2244
3251
  const pids = clientsRes.clients.map((c) => c.pid ?? c.id).filter((p) => p !== void 0 && p !== "");
2245
3252
  const execRes = await this.potassium.executeScript(pairCmd, pids.length > 0 ? pids : void 0);
2246
3253
  if (!execRes.ok) {
2247
- return { injected: false, text: `Potassium execute_script failed: ${execRes.text}` };
3254
+ this.lastAutoInjectFailureAt = Date.now();
3255
+ this.lastAutoInjectFailureReason = `Potassium execute_script failed: ${execRes.text}`;
3256
+ return { injected: false, text: this.lastAutoInjectFailureReason };
2248
3257
  }
2249
3258
  for (let i = 0; i < this.autoInjectMaxPolls; i++) {
2250
3259
  if (this.autoInjectPollMs > 0) await sleep(this.autoInjectPollMs);
2251
3260
  const check = await this.callCloudTool("list_sessions", {});
2252
3261
  if (check.ok && check.text && !check.text.includes("no game is connected")) {
3262
+ this.lastAutoInjectFailureAt = 0;
3263
+ this.lastAutoInjectFailureReason = "";
2253
3264
  return {
2254
3265
  injected: true,
2255
3266
  text: `Auto-injected Luaward agent via Potassium local MCP (${clientsRes.clients.length} client(s))`
2256
3267
  };
2257
3268
  }
2258
3269
  }
3270
+ this.lastAutoInjectFailureAt = Date.now();
3271
+ this.lastAutoInjectFailureReason = "injected pair command via Potassium, but session did not register within timeout";
2259
3272
  return {
2260
3273
  injected: false,
2261
- text: "injected pair command via Potassium, but session did not register within timeout"
3274
+ text: this.lastAutoInjectFailureReason
2262
3275
  };
2263
3276
  }
3277
+ formatPotassiumError(rawText) {
3278
+ if (/not reachable|offline|econnrefused|fetch failed|http [45]\d\d/i.test(rawText)) {
3279
+ return `${rawText}
3280
+ Hint: ${POTASSIUM_ENABLE_HINT}`;
3281
+ }
3282
+ return rawText;
3283
+ }
2264
3284
  resolveLocalFileArg(args, targetField) {
2265
3285
  const rawPath = args.file_path;
2266
3286
  if (typeof rawPath !== "string" || !rawPath.trim()) return;
2267
3287
  const fullPath = resolve2(rawPath.trim());
2268
- if (!existsSync3(fullPath)) {
3288
+ if (!existsSync4(fullPath)) {
2269
3289
  throw new Error(`Local file_path not found: ${fullPath}`);
2270
3290
  }
2271
3291
  const content = readFileSync2(fullPath, "utf8");
@@ -2278,7 +3298,9 @@ var HybridMcpBridge = class {
2278
3298
  switch (action) {
2279
3299
  case "list": {
2280
3300
  const res = await this.potassium.listTabs();
2281
- if (!res.ok) return { content: [{ type: "text", text: res.rawText }], isError: true };
3301
+ if (!res.ok) {
3302
+ return { content: [{ type: "text", text: this.formatPotassiumError(res.rawText) }], isError: true };
3303
+ }
2282
3304
  if (res.tabs.length === 0) {
2283
3305
  return { content: [{ type: "text", text: res.rawText || "no tabs in Potassium" }] };
2284
3306
  }
@@ -2292,7 +3314,9 @@ ${lines.join("\n")}` }]
2292
3314
  }
2293
3315
  case "read": {
2294
3316
  const res = await this.potassium.readTab(tabId);
2295
- if (!res.ok) return { content: [{ type: "text", text: res.content }], isError: true };
3317
+ if (!res.ok) {
3318
+ return { content: [{ type: "text", text: this.formatPotassiumError(res.content) }], isError: true };
3319
+ }
2296
3320
  const header = `-- Potassium tab ${res.tabId ?? "active"}${res.name ? ` ("${res.name}")` : ""}`;
2297
3321
  return { content: [{ type: "text", text: `${header}
2298
3322
  ${res.content}` }] };
@@ -2302,7 +3326,7 @@ ${res.content}` }] };
2302
3326
  let content = typeof args.content === "string" ? args.content : "";
2303
3327
  if (typeof args.file_path === "string" && args.file_path.trim()) {
2304
3328
  const fp = resolve2(args.file_path.trim());
2305
- if (!existsSync3(fp)) {
3329
+ if (!existsSync4(fp)) {
2306
3330
  return { content: [{ type: "text", text: `Local file_path not found: ${fp}` }], isError: true };
2307
3331
  }
2308
3332
  content = readFileSync2(fp, "utf8");
@@ -2313,7 +3337,10 @@ ${res.content}` }] };
2313
3337
  tabId: action === "write" ? tabId : void 0,
2314
3338
  reuseScratch: args.reuse_scratch !== false
2315
3339
  });
2316
- return { content: [{ type: "text", text: res.text }], isError: !res.ok };
3340
+ return {
3341
+ content: [{ type: "text", text: res.ok ? res.text : this.formatPotassiumError(res.text) }],
3342
+ isError: !res.ok
3343
+ };
2317
3344
  }
2318
3345
  case "activate": {
2319
3346
  if (!tabId) {
@@ -2324,7 +3351,12 @@ ${res.content}` }] };
2324
3351
  }
2325
3352
  const res = await this.potassium.callTool("tabs", { action: "activate", tab_id: tabId, id: tabId });
2326
3353
  return {
2327
- content: [{ type: "text", text: res.ok ? `activated tab ${tabId}` : res.text }],
3354
+ content: [
3355
+ {
3356
+ type: "text",
3357
+ text: res.ok ? `activated tab ${tabId}` : this.formatPotassiumError(res.text)
3358
+ }
3359
+ ],
2328
3360
  isError: !res.ok
2329
3361
  };
2330
3362
  }
@@ -2345,13 +3377,17 @@ ${res.content}` }] };
2345
3377
  };
2346
3378
  }
2347
3379
  return {
2348
- content: [{ type: "text", text: res.ok ? `closed tab ${tabId}` : res.text }],
3380
+ content: [
3381
+ { type: "text", text: res.ok ? `closed tab ${tabId}` : this.formatPotassiumError(res.text) }
3382
+ ],
2349
3383
  isError: !res.ok
2350
3384
  };
2351
3385
  }
2352
3386
  case "run_tab": {
2353
3387
  const read = await this.potassium.readTab(tabId);
2354
- if (!read.ok) return { content: [{ type: "text", text: read.content }], isError: true };
3388
+ if (!read.ok) {
3389
+ return { content: [{ type: "text", text: this.formatPotassiumError(read.content) }], isError: true };
3390
+ }
2355
3391
  if (!read.content.trim()) {
2356
3392
  return { content: [{ type: "text", text: "Target Potassium tab is empty" }], isError: true };
2357
3393
  }
@@ -2480,15 +3516,19 @@ ${luauBody}`,
2480
3516
  }),
2481
3517
  this.potassium.listClients()
2482
3518
  ]);
2483
- const rbxWins = wins.filter(
2484
- (w) => w.processName.toLowerCase().includes("roblox") || w.title === "Roblox"
2485
- );
3519
+ const rbxWins = wins.filter((w) => isRobloxPlayerWindow(w));
3520
+ const studioWins = wins.filter((w) => isRobloxStudioWindow(w));
2486
3521
  const potWins = wins.filter((w) => w.processName.toLowerCase().includes("potassium"));
2487
3522
  const lines = [
2488
3523
  ...winErr ? [`Desktop window query warning: ${winErr}`] : [],
2489
3524
  `Roblox windows: ${rbxWins.length}${rbxWins.length ? ` (${rbxWins.map((w) => `PID ${w.pid}, ${w.responding ? "responding" : "NOT RESPONDING"}, client ${w.clientRect.width}x${w.clientRect.height}`).join("; ")})` : ""}`,
3525
+ ...studioWins.length > 0 ? [
3526
+ `Roblox Studio windows: ${studioWins.length} (${studioWins.map((w) => `PID ${w.pid} "${w.title}", client ${w.clientRect.width}x${w.clientRect.height}`).join("; ")})`
3527
+ ] : [],
2490
3528
  `Potassium windows: ${potWins.length}${potWins.length ? ` (PID ${potWins.map((w) => w.pid).join(", ")})` : ""}`,
2491
- `Potassium MCP (${this.potassium.url}): ${kClients.ok ? `online (${kClients.clients.length} attached client(s))` : `offline (${kClients.rawText})`}`
3529
+ `Potassium MCP (${this.potassium.url}): ${kClients.ok ? `online (${kClients.clients.length} attached client(s))` : `offline (${kClients.rawText})
3530
+ Hint: ${POTASSIUM_ENABLE_HINT}`}`,
3531
+ ...this.lastScopeWarning ? [this.lastScopeWarning] : []
2492
3532
  ];
2493
3533
  return { content: [{ type: "text", text: lines.join("\n") }] };
2494
3534
  }
@@ -2738,22 +3778,856 @@ ${lines.join("\n")}` }]
2738
3778
  const screenX = Math.round(cr.screenLeft + clientX * scaleX);
2739
3779
  const screenY = Math.round(cr.screenTop + clientY * scaleY);
2740
3780
  const mouseAction = args.double_click === true ? "double_click" : args.button === "right" ? "right_click" : "click";
3781
+ const session = typeof args.session === "string" ? args.session : void 0;
3782
+ const shouldVerify = args.verify === true;
3783
+ const beforeSnap = shouldVerify ? await this.captureGuiSnapshotForVerify(session) : null;
2741
3784
  const clickRes = await this.windows.mouse({
2742
3785
  action: mouseAction,
2743
3786
  mode: "ui",
2744
3787
  x: screenX,
2745
3788
  y: screenY
2746
3789
  });
3790
+ let verifySuffix = "";
3791
+ if (shouldVerify) {
3792
+ const verifyText = await this.verifyMouseActionInGame(beforeSnap, session);
3793
+ verifySuffix = `
3794
+ ${verifyText}`;
3795
+ }
2747
3796
  return {
2748
3797
  content: [
2749
3798
  {
2750
3799
  type: "text",
2751
- text: `os_click ${mouseAction} on ${resolvedPath} (${target}): in-game client=(${Math.round(clientX)}, ${Math.round(clientY)}) -> Windows screen=(${screenX}, ${screenY})`
3800
+ text: `os_click ${mouseAction} on ${resolvedPath} (${target}): in-game client=(${Math.round(clientX)}, ${Math.round(clientY)}) -> Windows screen=(${screenX}, ${screenY})${verifySuffix}`
2752
3801
  }
2753
3802
  ],
2754
3803
  isError: !clickRes.ok
2755
3804
  };
2756
3805
  }
3806
+ async captureGuiSnapshotForVerify(session) {
3807
+ try {
3808
+ const res = await this.callCloudTool("gui_snapshot", {
3809
+ ...session ? { session } : {}
3810
+ });
3811
+ return res.ok ? res.text : null;
3812
+ } catch {
3813
+ return null;
3814
+ }
3815
+ }
3816
+ computeSnapshotLineDiff(beforeText, afterText) {
3817
+ if (afterText.includes("--- diff")) {
3818
+ const idx = afterText.indexOf("--- diff");
3819
+ return afterText.slice(idx).trim();
3820
+ }
3821
+ if (!beforeText) {
3822
+ return "captured post-click gui_snapshot (no baseline snapshot)";
3823
+ }
3824
+ const beforeLines = beforeText.split("\n").map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("GUI snapshot"));
3825
+ const afterLines = afterText.split("\n").map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("GUI snapshot"));
3826
+ const beforeSet = new Set(beforeLines);
3827
+ const afterSet = new Set(afterLines);
3828
+ const added = afterLines.filter((l) => !beforeSet.has(l));
3829
+ const removed = beforeLines.filter((l) => !afterSet.has(l));
3830
+ if (added.length === 0 && removed.length === 0) {
3831
+ return "no GUI state change detected";
3832
+ }
3833
+ const out = [];
3834
+ for (const r of removed.slice(0, 12)) out.push(`- ${r}`);
3835
+ for (const a of added.slice(0, 12)) out.push(`+ ${a}`);
3836
+ if (removed.length > 12 || added.length > 12) {
3837
+ out.push(`... (+${Math.max(0, added.length - 12)} added, -${Math.max(0, removed.length - 12)} removed)`);
3838
+ }
3839
+ return out.join("\n");
3840
+ }
3841
+ async verifyMouseActionInGame(beforeSnap, session) {
3842
+ const lines = ["Verification:"];
3843
+ try {
3844
+ const mouseCode = [
3845
+ "local uis = game:GetService('UserInputService')",
3846
+ "local m = uis:GetMouseLocation()",
3847
+ "local inset = game:GetService('GuiService'):GetGuiInset()",
3848
+ "return { mouseX = math.floor(m.X + 0.5), mouseY = math.floor(m.Y + 0.5), guiX = math.floor(m.X + 0.5), guiY = math.floor(m.Y - (inset and inset.Y or 0) + 0.5) }"
3849
+ ].join("; ");
3850
+ const mouseRes = await this.callCloudTool("exec", {
3851
+ code: mouseCode,
3852
+ readonly: true,
3853
+ ...session ? { session } : {}
3854
+ });
3855
+ if (mouseRes.ok) {
3856
+ const mx = /\bmouseX\s*=\s*(-?\d+(?:\.\d+)?)/.exec(mouseRes.text);
3857
+ const my = /\bmouseY\s*=\s*(-?\d+(?:\.\d+)?)/.exec(mouseRes.text);
3858
+ const gx = /\bguiX\s*=\s*(-?\d+(?:\.\d+)?)/.exec(mouseRes.text);
3859
+ const gy = /\bguiY\s*=\s*(-?\d+(?:\.\d+)?)/.exec(mouseRes.text);
3860
+ if (mx && my) {
3861
+ const guiPart = gx && gy ? ` \xB7 gui=(${gx[1]}, ${gy[1]})` : "";
3862
+ lines.push(`- GetMouseLocation: inset=(${mx[1]}, ${my[1]})${guiPart}`);
3863
+ } else {
3864
+ lines.push(`- GetMouseLocation: ${mouseRes.text.trim()}`);
3865
+ }
3866
+ } else {
3867
+ lines.push(`- GetMouseLocation unavailable: ${mouseRes.text}`);
3868
+ }
3869
+ } catch (err) {
3870
+ lines.push(`- GetMouseLocation error: ${err instanceof Error ? err.message : String(err)}`);
3871
+ }
3872
+ try {
3873
+ const snapRes = await this.callCloudTool("gui_snapshot", {
3874
+ diff_from: "latest",
3875
+ ...session ? { session } : {}
3876
+ });
3877
+ if (snapRes.ok) {
3878
+ const diffSummary = this.computeSnapshotLineDiff(beforeSnap, snapRes.text);
3879
+ lines.push(`- gui_snapshot diff:
3880
+ ${diffSummary}`);
3881
+ } else {
3882
+ lines.push(`- gui_snapshot diff unavailable: ${snapRes.text}`);
3883
+ }
3884
+ } catch (err) {
3885
+ lines.push(`- gui_snapshot diff error: ${err instanceof Error ? err.message : String(err)}`);
3886
+ }
3887
+ return lines.join("\n");
3888
+ }
3889
+ extractJsonPayloadFromExec(rawText) {
3890
+ const trimmed = rawText.trim();
3891
+ if (!trimmed) return null;
3892
+ const candidates = [trimmed];
3893
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
3894
+ try {
3895
+ const unquoted = JSON.parse(trimmed);
3896
+ if (typeof unquoted === "string") candidates.unshift(unquoted);
3897
+ } catch {
3898
+ }
3899
+ }
3900
+ const firstBracket = trimmed.search(/[\[{]/);
3901
+ const lastBracket = Math.max(trimmed.lastIndexOf("]"), trimmed.lastIndexOf("}"));
3902
+ if (firstBracket >= 0 && lastBracket > firstBracket) {
3903
+ candidates.push(trimmed.slice(firstBracket, lastBracket + 1));
3904
+ }
3905
+ for (const c of candidates) {
3906
+ try {
3907
+ return JSON.parse(c);
3908
+ } catch {
3909
+ }
3910
+ }
3911
+ return null;
3912
+ }
3913
+ async handleStudioMirrorRemotes(args) {
3914
+ const roots = Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "Workspace"];
3915
+ const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(12, args.max_depth)) : 6;
3916
+ const clearExisting = args.clear_existing === true;
3917
+ const session = typeof args.session === "string" ? args.session : void 0;
3918
+ const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
3919
+ const liveScanCode = [
3920
+ "local HttpService = game:GetService('HttpService')",
3921
+ `local roots = ${JSON.stringify(roots)}`,
3922
+ `local maxDepth = ${maxDepth}`,
3923
+ "local remoteClasses = { RemoteEvent = true, RemoteFunction = true, UnreliableRemoteEvent = true, BindableEvent = true, BindableFunction = true }",
3924
+ "local items = {}",
3925
+ "local function scan(inst, rootName, segs, depth)",
3926
+ " if depth > maxDepth then return end",
3927
+ " for _, child in ipairs(inst:GetChildren()) do",
3928
+ " local nextSegs = {}",
3929
+ " for i = 1, #segs do nextSegs[i] = segs[i] end",
3930
+ " nextSegs[#nextSegs + 1] = child.Name",
3931
+ " if remoteClasses[child.ClassName] then",
3932
+ " items[#items + 1] = { root = rootName, className = child.ClassName, segments = nextSegs, path = rootName .. '.' .. table.concat(nextSegs, '.') }",
3933
+ " end",
3934
+ " if #child:GetChildren() > 0 then",
3935
+ " scan(child, rootName, nextSegs, depth + 1)",
3936
+ " end",
3937
+ " end",
3938
+ "end",
3939
+ "for _, rName in ipairs(roots) do",
3940
+ " local ok, svc = pcall(function() return game:GetService(rName) end)",
3941
+ " if ok and svc then scan(svc, rName, {}, 1) end",
3942
+ "end",
3943
+ "return HttpService:JSONEncode(items)"
3944
+ ].join("\n");
3945
+ const liveRes = await this.callCloudTool("exec", {
3946
+ code: liveScanCode,
3947
+ readonly: true,
3948
+ ...session ? { session } : {}
3949
+ });
3950
+ if (!liveRes.ok) {
3951
+ return {
3952
+ content: [{ type: "text", text: `studio_mirror_remotes failed to read live remotes: ${liveRes.text}` }],
3953
+ isError: true
3954
+ };
3955
+ }
3956
+ const items = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
3957
+ const studioCode = [
3958
+ "local HttpService = game:GetService('HttpService')",
3959
+ `local items = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(items))})`,
3960
+ `local clearExisting = ${clearExisting ? "true" : "false"}`,
3961
+ "local created, existing = 0, 0",
3962
+ "for _, item in ipairs(items) do",
3963
+ " local ok, rootInst = pcall(function() return game:GetService(item.root) end)",
3964
+ " if ok and rootInst then",
3965
+ " local cur = rootInst",
3966
+ " for i = 1, #item.segments - 1 do",
3967
+ " local seg = item.segments[i]",
3968
+ " local nextInst = cur:FindFirstChild(seg)",
3969
+ " if not nextInst then",
3970
+ " nextInst = Instance.new('Folder')",
3971
+ " nextInst.Name = seg",
3972
+ " nextInst.Parent = cur",
3973
+ " end",
3974
+ " cur = nextInst",
3975
+ " end",
3976
+ " local leafName = item.segments[#item.segments]",
3977
+ " if leafName then",
3978
+ " local found = cur:FindFirstChild(leafName)",
3979
+ " if found and clearExisting and found.ClassName == item.className then",
3980
+ " found:Destroy()",
3981
+ " found = nil",
3982
+ " end",
3983
+ " if not found then",
3984
+ " local okNew, inst = pcall(Instance.new, item.className)",
3985
+ " if okNew and inst then",
3986
+ " inst.Name = leafName",
3987
+ " inst.Parent = cur",
3988
+ " created = created + 1",
3989
+ " end",
3990
+ " else",
3991
+ " existing = existing + 1",
3992
+ " end",
3993
+ " end",
3994
+ " end",
3995
+ "end",
3996
+ "return string.format('mirrored %d remotes (created=%d, existing=%d)', #items, created, existing)"
3997
+ ].join("\n");
3998
+ const studioRes = await this.studio.runStudioLuau(studioCode, requestedStudioId);
3999
+ if (!studioRes.ok) {
4000
+ return {
4001
+ content: [
4002
+ {
4003
+ type: "text",
4004
+ text: `studio_mirror_remotes collected ${items.length} live remotes but Studio execution failed: ${studioRes.text}`
4005
+ }
4006
+ ],
4007
+ isError: true
4008
+ };
4009
+ }
4010
+ const samplePaths = items.slice(0, 15).map((i) => ` - [${i.className}] ${i.path}`);
4011
+ return {
4012
+ content: [
4013
+ {
4014
+ type: "text",
4015
+ text: [
4016
+ `studio_mirror_remotes complete (studio_id=${studioRes.studioId ?? "auto"}):`,
4017
+ `- Live remotes discovered: ${items.length} across ${roots.join(", ")}`,
4018
+ `- Studio result: ${studioRes.text}`,
4019
+ ...samplePaths.length > 0 ? ["- Sample mirrored paths:", ...samplePaths] : []
4020
+ ].join("\n")
4021
+ }
4022
+ ]
4023
+ };
4024
+ }
4025
+ async handleStudioMirrorGui(args) {
4026
+ const targetPath = typeof args.target_path === "string" ? args.target_path.trim() : "";
4027
+ const containerName = typeof args.container_name === "string" && args.container_name.trim() ? args.container_name.trim() : "LuawardMirroredGui";
4028
+ const maxNodes = typeof args.max_nodes === "number" ? Math.max(10, Math.min(1e3, args.max_nodes)) : 250;
4029
+ const includeCoreGui = args.include_core_gui === true;
4030
+ const session = typeof args.session === "string" ? args.session : void 0;
4031
+ const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4032
+ const liveGuiCode = [
4033
+ "local HttpService = game:GetService('HttpService')",
4034
+ "local Players = game:GetService('Players')",
4035
+ `local targetPath = ${JSON.stringify(targetPath)}`,
4036
+ `local maxNodes = ${maxNodes}`,
4037
+ `local includeCore = ${includeCoreGui ? "true" : "false"}`,
4038
+ "local nodes = {}",
4039
+ "local count = 0",
4040
+ "local function serColor(c) return c and { c.R, c.G, c.B } or nil end",
4041
+ "local function serUDim2(u) return u and { u.X.Scale, u.X.Offset, u.Y.Scale, u.Y.Offset } or nil end",
4042
+ "local function serVec2(v) return v and { v.X, v.Y } or nil end",
4043
+ "local function serializeTree(inst, depth)",
4044
+ " if count >= maxNodes or depth > 10 then return nil end",
4045
+ " count = count + 1",
4046
+ " local node = { className = inst.ClassName, name = inst.Name, children = {} }",
4047
+ " pcall(function()",
4048
+ " if inst:IsA('LayerCollector') then node.enabled = inst.Enabled end",
4049
+ " if inst:IsA('GuiObject') then",
4050
+ " node.visible = inst.Visible",
4051
+ " node.pos = serUDim2(inst.Position)",
4052
+ " node.size = serUDim2(inst.Size)",
4053
+ " node.anchor = serVec2(inst.AnchorPoint)",
4054
+ " node.bg = serColor(inst.BackgroundColor3)",
4055
+ " node.bgTrans = inst.BackgroundTransparency",
4056
+ " node.zIndex = inst.ZIndex",
4057
+ " node.layoutOrder = inst.LayoutOrder",
4058
+ " end",
4059
+ " if inst:IsA('TextLabel') or inst:IsA('TextButton') or inst:IsA('TextBox') then",
4060
+ " node.text = tostring(inst.Text or ''):sub(1, 200)",
4061
+ " node.textColor = serColor(inst.TextColor3)",
4062
+ " node.textSize = inst.TextSize",
4063
+ " end",
4064
+ " if inst:IsA('UICorner') then",
4065
+ " node.corner = { inst.CornerRadius.Scale, inst.CornerRadius.Offset }",
4066
+ " end",
4067
+ " end)",
4068
+ " for _, child in ipairs(inst:GetChildren()) do",
4069
+ " if count >= maxNodes then break end",
4070
+ " local cNode = serializeTree(child, depth + 1)",
4071
+ " if cNode then node.children[#node.children + 1] = cNode end",
4072
+ " end",
4073
+ " return node",
4074
+ "end",
4075
+ "if targetPath ~= '' and lw and lw.resolve then",
4076
+ " local inst = lw.resolve(targetPath)",
4077
+ " if inst then nodes[#nodes + 1] = serializeTree(inst, 1) end",
4078
+ "else",
4079
+ " local lp = Players.LocalPlayer",
4080
+ " local pgui = lp and lp:FindFirstChildOfClass('PlayerGui')",
4081
+ " if pgui then",
4082
+ " for _, child in ipairs(pgui:GetChildren()) do",
4083
+ " if count >= maxNodes then break end",
4084
+ " local n = serializeTree(child, 1)",
4085
+ " if n then nodes[#nodes + 1] = n end",
4086
+ " end",
4087
+ " end",
4088
+ " if includeCore then",
4089
+ " local ok, cgui = pcall(function() return game:GetService('CoreGui') end)",
4090
+ " if ok and cgui then",
4091
+ " for _, child in ipairs(cgui:GetChildren()) do",
4092
+ " if count >= maxNodes then break end",
4093
+ " if child.Name ~= 'RobloxGui' then",
4094
+ " local n = serializeTree(child, 1)",
4095
+ " if n then nodes[#nodes + 1] = n end",
4096
+ " end",
4097
+ " end",
4098
+ " end",
4099
+ " end",
4100
+ "end",
4101
+ "return HttpService:JSONEncode({ count = count, trees = nodes })"
4102
+ ].join("\n");
4103
+ const liveRes = await this.callCloudTool("exec", {
4104
+ code: liveGuiCode,
4105
+ readonly: true,
4106
+ ...session ? { session } : {}
4107
+ });
4108
+ if (!liveRes.ok) {
4109
+ return {
4110
+ content: [{ type: "text", text: `studio_mirror_gui failed to read live GUI: ${liveRes.text}` }],
4111
+ isError: true
4112
+ };
4113
+ }
4114
+ const payload = this.extractJsonPayloadFromExec(liveRes.text) ?? {
4115
+ count: 0,
4116
+ trees: []
4117
+ };
4118
+ const studioBuildCode = [
4119
+ "local HttpService = game:GetService('HttpService')",
4120
+ "local StarterGui = game:GetService('StarterGui')",
4121
+ `local containerName = ${JSON.stringify(containerName)}`,
4122
+ `local payload = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(payload))})`,
4123
+ "local folder = StarterGui:FindFirstChild(containerName)",
4124
+ "if folder then folder:Destroy() end",
4125
+ "folder = Instance.new('Folder')",
4126
+ "folder.Name = containerName",
4127
+ "folder.Parent = StarterGui",
4128
+ "local created = 0",
4129
+ "local function buildNode(node, parent)",
4130
+ " local ok, inst = pcall(Instance.new, node.className)",
4131
+ " if not ok or not inst then",
4132
+ " inst = Instance.new('Frame')",
4133
+ " end",
4134
+ " inst.Name = node.name or node.className",
4135
+ " pcall(function()",
4136
+ " if node.enabled ~= nil and inst:IsA('LayerCollector') then inst.Enabled = node.enabled end",
4137
+ " if inst:IsA('GuiObject') then",
4138
+ " if node.visible ~= nil then inst.Visible = node.visible end",
4139
+ " if node.pos then inst.Position = UDim2.new(node.pos[1], node.pos[2], node.pos[3], node.pos[4]) end",
4140
+ " if node.size then inst.Size = UDim2.new(node.size[1], node.size[2], node.size[3], node.size[4]) end",
4141
+ " if node.anchor then inst.AnchorPoint = Vector2.new(node.anchor[1], node.anchor[2]) end",
4142
+ " if node.bg then inst.BackgroundColor3 = Color3.new(node.bg[1], node.bg[2], node.bg[3]) end",
4143
+ " if node.bgTrans ~= nil then inst.BackgroundTransparency = node.bgTrans end",
4144
+ " if node.zIndex ~= nil then inst.ZIndex = node.zIndex end",
4145
+ " if node.layoutOrder ~= nil then inst.LayoutOrder = node.layoutOrder end",
4146
+ " end",
4147
+ " if node.text ~= nil and (inst:IsA('TextLabel') or inst:IsA('TextButton') or inst:IsA('TextBox')) then",
4148
+ " inst.Text = node.text",
4149
+ " if node.textColor then inst.TextColor3 = Color3.new(node.textColor[1], node.textColor[2], node.textColor[3]) end",
4150
+ " if node.textSize then inst.TextSize = node.textSize end",
4151
+ " end",
4152
+ " if node.corner and inst:IsA('UICorner') then",
4153
+ " inst.CornerRadius = UDim.new(node.corner[1], node.corner[2])",
4154
+ " end",
4155
+ " end)",
4156
+ " inst.Parent = parent",
4157
+ " created = created + 1",
4158
+ " if type(node.children) == 'table' then",
4159
+ " for _, child in ipairs(node.children) do buildNode(child, inst) end",
4160
+ " end",
4161
+ "end",
4162
+ "for _, tree in ipairs(payload.trees or {}) do buildNode(tree, folder) end",
4163
+ "return string.format('mirrored %d GUI nodes into StarterGui.%s', created, containerName)"
4164
+ ].join("\n");
4165
+ const studioRes = await this.studio.runStudioLuau(studioBuildCode, requestedStudioId);
4166
+ if (!studioRes.ok) {
4167
+ return {
4168
+ content: [
4169
+ {
4170
+ type: "text",
4171
+ text: `studio_mirror_gui serialized ${payload.count} live GUI nodes but Studio execution failed: ${studioRes.text}`
4172
+ }
4173
+ ],
4174
+ isError: true
4175
+ };
4176
+ }
4177
+ return {
4178
+ content: [
4179
+ {
4180
+ type: "text",
4181
+ text: [
4182
+ `studio_mirror_gui complete (studio_id=${studioRes.studioId ?? "auto"}):`,
4183
+ `- Live GUI nodes serialized: ${payload.count} (${payload.trees.length} root trees)`,
4184
+ `- Studio container: StarterGui.${containerName}`,
4185
+ `- Studio result: ${studioRes.text}`
4186
+ ].join("\n")
4187
+ }
4188
+ ]
4189
+ };
4190
+ }
4191
+ async handleStudioDiff(args) {
4192
+ const roots = Array.isArray(args.roots) && args.roots.length > 0 ? args.roots.map(String) : ["ReplicatedStorage", "StarterGui", "Workspace"];
4193
+ const scope = typeof args.scope === "string" ? args.scope : "all";
4194
+ const maxDepth = typeof args.max_depth === "number" ? Math.max(1, Math.min(10, args.max_depth)) : 5;
4195
+ const session = typeof args.session === "string" ? args.session : void 0;
4196
+ const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4197
+ const buildDiffScanCode = (isLive) => [
4198
+ "local HttpService = game:GetService('HttpService')",
4199
+ `local roots = ${JSON.stringify(roots)}`,
4200
+ `local scope = ${JSON.stringify(scope)}`,
4201
+ `local maxDepth = ${maxDepth}`,
4202
+ `local isLive = ${isLive ? "true" : "false"}`,
4203
+ "local entries = {}",
4204
+ "local count = 0",
4205
+ "local remoteClasses = { RemoteEvent = true, RemoteFunction = true, UnreliableRemoteEvent = true, BindableEvent = true, BindableFunction = true }",
4206
+ "local scriptClasses = { LocalScript = true, ModuleScript = true, Script = true }",
4207
+ "local function matchesScope(inst)",
4208
+ " if scope == 'remotes' then return remoteClasses[inst.ClassName] == true end",
4209
+ " if scope == 'scripts' then return scriptClasses[inst.ClassName] == true end",
4210
+ " if scope == 'gui' then return inst:IsA('GuiBase2d') or inst:IsA('LayerCollector') end",
4211
+ " return true",
4212
+ "end",
4213
+ "local function scan(inst, prefix, depth)",
4214
+ " if depth > maxDepth or count >= 1500 then return end",
4215
+ " for _, child in ipairs(inst:GetChildren()) do",
4216
+ " local p = prefix .. '.' .. child.Name",
4217
+ " if matchesScope(child) then",
4218
+ " count = count + 1",
4219
+ " entries[#entries + 1] = { path = p, className = child.ClassName }",
4220
+ " end",
4221
+ " if #child:GetChildren() > 0 then scan(child, p, depth + 1) end",
4222
+ " end",
4223
+ "end",
4224
+ "for _, rName in ipairs(roots) do",
4225
+ " local rootInst = nil",
4226
+ " if isLive and rName == 'StarterGui' then",
4227
+ " local lp = game:GetService('Players').LocalPlayer",
4228
+ " rootInst = lp and lp:FindFirstChildOfClass('PlayerGui') or game:GetService('StarterGui')",
4229
+ " else",
4230
+ " pcall(function() rootInst = game:GetService(rName) end)",
4231
+ " end",
4232
+ " if rootInst then scan(rootInst, rName, 1) end",
4233
+ "end",
4234
+ "return HttpService:JSONEncode(entries)"
4235
+ ].join("\n");
4236
+ const [liveRes, studioRes] = await Promise.all([
4237
+ this.callCloudTool("exec", {
4238
+ code: buildDiffScanCode(true),
4239
+ readonly: true,
4240
+ ...session ? { session } : {}
4241
+ }),
4242
+ this.studio.runStudioLuau(buildDiffScanCode(false), requestedStudioId)
4243
+ ]);
4244
+ if (!liveRes.ok) {
4245
+ return {
4246
+ content: [{ type: "text", text: `studio_diff failed to scan live game: ${liveRes.text}` }],
4247
+ isError: true
4248
+ };
4249
+ }
4250
+ if (!studioRes.ok) {
4251
+ return {
4252
+ content: [{ type: "text", text: `studio_diff failed to scan Roblox Studio: ${studioRes.text}` }],
4253
+ isError: true
4254
+ };
4255
+ }
4256
+ const liveEntries = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
4257
+ const studioEntries = this.extractJsonPayloadFromExec(studioRes.text) ?? [];
4258
+ const liveMap = /* @__PURE__ */ new Map();
4259
+ for (const e of liveEntries) liveMap.set(e.path, e.className);
4260
+ const studioMap = /* @__PURE__ */ new Map();
4261
+ for (const e of studioEntries) studioMap.set(e.path, e.className);
4262
+ const onlyInLive = [];
4263
+ const onlyInStudio = [];
4264
+ const classMismatches = [];
4265
+ let matchedCount = 0;
4266
+ for (const [p, liveCls] of liveMap) {
4267
+ const studioCls = studioMap.get(p);
4268
+ if (!studioCls) {
4269
+ onlyInLive.push(`${p} [${liveCls}]`);
4270
+ } else if (studioCls !== liveCls) {
4271
+ classMismatches.push(`${p} (live=${liveCls}, studio=${studioCls})`);
4272
+ } else {
4273
+ matchedCount++;
4274
+ }
4275
+ }
4276
+ for (const [p, studioCls] of studioMap) {
4277
+ if (!liveMap.has(p)) {
4278
+ onlyInStudio.push(`${p} [${studioCls}]`);
4279
+ }
4280
+ }
4281
+ const lines = [
4282
+ `studio_diff report (scope=${scope}, roots=${roots.join(", ")}, studio_id=${studioRes.studioId ?? "auto"}):`,
4283
+ `- Matched instances: ${matchedCount}`,
4284
+ `- Only in Live Game: ${onlyInLive.length}`,
4285
+ ...onlyInLive.slice(0, 20).map((x) => ` + [Live] ${x}`),
4286
+ ...onlyInLive.length > 20 ? [` ... (+${onlyInLive.length - 20} more)`] : [],
4287
+ `- Only in Roblox Studio: ${onlyInStudio.length}`,
4288
+ ...onlyInStudio.slice(0, 20).map((x) => ` - [Studio] ${x}`),
4289
+ ...onlyInStudio.length > 20 ? [` ... (+${onlyInStudio.length - 20} more)`] : [],
4290
+ `- Class mismatches: ${classMismatches.length}`,
4291
+ ...classMismatches.slice(0, 10).map((x) => ` ! ${x}`)
4292
+ ];
4293
+ return {
4294
+ content: [{ type: "text", text: lines.join("\n") }]
4295
+ };
4296
+ }
4297
+ buildStudioReadScriptSourceCode(studioPath) {
4298
+ return [
4299
+ "local HttpService = game:GetService('HttpService')",
4300
+ `local pathStr = ${JSON.stringify(studioPath)}`,
4301
+ "local segs = {}",
4302
+ "for seg in string.gmatch(pathStr, '[^%.]+') do segs[#segs + 1] = seg end",
4303
+ "if #segs == 0 then error('Empty studio_path') end",
4304
+ "local startIdx = 1",
4305
+ "if segs[1] == 'game' then startIdx = 2 end",
4306
+ "local cur = game:GetService(segs[startIdx])",
4307
+ "for i = startIdx + 1, #segs do",
4308
+ " cur = cur and cur:FindFirstChild(segs[i])",
4309
+ "end",
4310
+ "if not cur then error('Studio instance not found: ' .. pathStr) end",
4311
+ "local ok, src = pcall(function() return cur.Source end)",
4312
+ "if not ok or type(src) ~= 'string' then error(pathStr .. ' (' .. cur.ClassName .. ') has no readable .Source') end",
4313
+ "return HttpService:JSONEncode({ name = cur.Name, className = cur.ClassName, path = cur:GetFullName(), source = src })"
4314
+ ].join("\n");
4315
+ }
4316
+ async handleStudioToLive(args) {
4317
+ const studioPath = typeof args.studio_path === "string" ? args.studio_path.trim() : "";
4318
+ const directCode = typeof args.code === "string" ? args.code : "";
4319
+ const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4320
+ const session = typeof args.session === "string" ? args.session : void 0;
4321
+ const collect = args.collect !== false;
4322
+ if (!studioPath && !directCode.trim()) {
4323
+ return {
4324
+ content: [{ type: "text", text: "studio_to_live requires either studio_path or code" }],
4325
+ isError: true
4326
+ };
4327
+ }
4328
+ let codeToRun = directCode;
4329
+ let sourceLabel = "inline Studio snippet";
4330
+ let resolvedStudioId = requestedStudioId;
4331
+ if (studioPath) {
4332
+ const studioRes = await this.studio.runStudioLuau(
4333
+ this.buildStudioReadScriptSourceCode(studioPath),
4334
+ requestedStudioId
4335
+ );
4336
+ if (!studioRes.ok) {
4337
+ return {
4338
+ content: [
4339
+ {
4340
+ type: "text",
4341
+ text: `studio_to_live failed to read ${studioPath} from Roblox Studio: ${studioRes.text}`
4342
+ }
4343
+ ],
4344
+ isError: true
4345
+ };
4346
+ }
4347
+ resolvedStudioId = studioRes.studioId;
4348
+ const parsed = this.extractJsonPayloadFromExec(studioRes.text);
4349
+ if (!parsed || typeof parsed.source !== "string") {
4350
+ return {
4351
+ content: [
4352
+ {
4353
+ type: "text",
4354
+ text: `studio_to_live could not parse script source from Studio response: ${studioRes.text}`
4355
+ }
4356
+ ],
4357
+ isError: true
4358
+ };
4359
+ }
4360
+ codeToRun = parsed.source;
4361
+ sourceLabel = `${parsed.path} [${parsed.className}] (${codeToRun.length} bytes, studio_id=${resolvedStudioId ?? "auto"})`;
4362
+ }
4363
+ const cloudTool = collect ? "run_and_collect" : "exec";
4364
+ const cloudArgs = {
4365
+ code: codeToRun,
4366
+ ...collect ? {
4367
+ wait_seconds: typeof args.wait_seconds === "number" ? args.wait_seconds : 1.5,
4368
+ clean_env: typeof args.clean_env === "boolean" ? args.clean_env : true
4369
+ } : {},
4370
+ ...session ? { session } : {}
4371
+ };
4372
+ const liveRes = await this.callCloudTool(cloudTool, cloudArgs);
4373
+ return {
4374
+ content: [
4375
+ {
4376
+ type: "text",
4377
+ text: `studio_to_live (${sourceLabel} -> ${cloudTool}):
4378
+ ${liveRes.text}`
4379
+ }
4380
+ ],
4381
+ isError: !liveRes.ok
4382
+ };
4383
+ }
4384
+ async handleStudioPublish(args) {
4385
+ const studioPath = typeof args.studio_path === "string" ? args.studio_path.trim() : "";
4386
+ if (!studioPath) {
4387
+ return {
4388
+ content: [{ type: "text", text: "studio_publish requires studio_path" }],
4389
+ isError: true
4390
+ };
4391
+ }
4392
+ const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4393
+ const studioRes = await this.studio.runStudioLuau(
4394
+ this.buildStudioReadScriptSourceCode(studioPath),
4395
+ requestedStudioId
4396
+ );
4397
+ if (!studioRes.ok) {
4398
+ return {
4399
+ content: [
4400
+ {
4401
+ type: "text",
4402
+ text: `studio_publish failed to read ${studioPath} from Roblox Studio: ${studioRes.text}`
4403
+ }
4404
+ ],
4405
+ isError: true
4406
+ };
4407
+ }
4408
+ const parsed = this.extractJsonPayloadFromExec(studioRes.text);
4409
+ if (!parsed || typeof parsed.source !== "string") {
4410
+ return {
4411
+ content: [
4412
+ {
4413
+ type: "text",
4414
+ text: `studio_publish could not parse script source from Studio response: ${studioRes.text}`
4415
+ }
4416
+ ],
4417
+ isError: true
4418
+ };
4419
+ }
4420
+ const scriptId = typeof args.script_id === "string" ? args.script_id.trim() : "";
4421
+ if (scriptId) {
4422
+ const deployRes = await this.callCloudTool("deploy_script", {
4423
+ script_id: scriptId,
4424
+ source: parsed.source,
4425
+ ...typeof args.note === "string" ? { note: args.note } : {}
4426
+ });
4427
+ return {
4428
+ content: [
4429
+ {
4430
+ type: "text",
4431
+ text: `studio_publish deployed ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}) to Luaward script ${scriptId}:
4432
+ ${deployRes.text}`
4433
+ }
4434
+ ],
4435
+ isError: !deployRes.ok
4436
+ };
4437
+ }
4438
+ const scriptName = typeof args.name === "string" && args.name.trim() ? args.name.trim() : parsed.name || "StudioScript";
4439
+ const createRes = await this.callCloudTool("create_script", {
4440
+ name: scriptName,
4441
+ source: parsed.source,
4442
+ ...typeof args.description === "string" ? { description: args.description } : {}
4443
+ });
4444
+ return {
4445
+ content: [
4446
+ {
4447
+ type: "text",
4448
+ text: `studio_publish created Luaward script "${scriptName}" from ${parsed.path} (${parsed.source.length} bytes, studio_id=${studioRes.studioId ?? "auto"}):
4449
+ ${createRes.text}`
4450
+ }
4451
+ ],
4452
+ isError: !createRes.ok
4453
+ };
4454
+ }
4455
+ async handleLiveScriptsToStudio(args) {
4456
+ const filter = typeof args.filter === "string" ? args.filter.trim() : "";
4457
+ const containerName = typeof args.container_name === "string" && args.container_name.trim() ? args.container_name.trim() : "LuawardLiveScripts";
4458
+ const limit = typeof args.limit === "number" ? Math.max(1, Math.min(50, args.limit)) : 15;
4459
+ const includeDecompiled = args.include_decompiled !== false;
4460
+ const session = typeof args.session === "string" ? args.session : void 0;
4461
+ const requestedStudioId = typeof args.studio_id === "string" ? args.studio_id : void 0;
4462
+ const liveCollectCode = [
4463
+ "local HttpService = game:GetService('HttpService')",
4464
+ `local filter = string.lower(${JSON.stringify(filter)})`,
4465
+ `local limit = ${limit}`,
4466
+ `local includeDecompiled = ${includeDecompiled ? "true" : "false"}`,
4467
+ "local roots = { game:GetService('ReplicatedStorage'), game:GetService('StarterPlayer'), game:GetService('Workspace'), game:GetService('Players').LocalPlayer }",
4468
+ "local results = {}",
4469
+ "local seen = {}",
4470
+ "local decompFn = (type(decompile) == 'function' and decompile) or (type(getscriptbytecode) == 'function' and function(s) local ok, b = pcall(getscriptbytecode, s); return ok and b and ('-- bytecode (' .. tostring(#b) .. ' bytes)') or nil end) or nil",
4471
+ "for _, root in ipairs(roots) do",
4472
+ " if root then",
4473
+ " local ok, list = pcall(function() return root:GetDescendants() end)",
4474
+ " if ok and type(list) == 'table' then",
4475
+ " for _, inst in ipairs(list) do",
4476
+ " if #results >= limit then break end",
4477
+ " if not seen[inst] and (inst.ClassName == 'LocalScript' or inst.ClassName == 'ModuleScript') then",
4478
+ " seen[inst] = true",
4479
+ " local fullPath = inst:GetFullName()",
4480
+ " if filter == '' or string.find(string.lower(fullPath), filter, 1, true) then",
4481
+ " local src = '-- Live script: ' .. fullPath .. '\\n-- ClassName: ' .. inst.ClassName",
4482
+ " if includeDecompiled and decompFn then",
4483
+ " local okD, dec = pcall(decompFn, inst)",
4484
+ " if okD and type(dec) == 'string' and #dec > 0 then",
4485
+ " src = src .. '\\n\\n' .. dec:sub(1, 32000)",
4486
+ " end",
4487
+ " end",
4488
+ " results[#results + 1] = { name = inst.Name, className = inst.ClassName, path = fullPath, source = src }",
4489
+ " end",
4490
+ " end",
4491
+ " end",
4492
+ " end",
4493
+ " end",
4494
+ "end",
4495
+ "return HttpService:JSONEncode(results)"
4496
+ ].join("\n");
4497
+ const liveRes = await this.callCloudTool("exec", {
4498
+ code: liveCollectCode,
4499
+ readonly: true,
4500
+ ...session ? { session } : {}
4501
+ });
4502
+ if (!liveRes.ok) {
4503
+ return {
4504
+ content: [
4505
+ {
4506
+ type: "text",
4507
+ text: `live_scripts_to_studio failed to collect live scripts: ${liveRes.text}`
4508
+ }
4509
+ ],
4510
+ isError: true
4511
+ };
4512
+ }
4513
+ const scripts = this.extractJsonPayloadFromExec(liveRes.text) ?? [];
4514
+ const studioImportCode = [
4515
+ "local HttpService = game:GetService('HttpService')",
4516
+ "local ServerStorage = game:GetService('ServerStorage')",
4517
+ `local containerName = ${JSON.stringify(containerName)}`,
4518
+ `local items = HttpService:JSONDecode(${JSON.stringify(JSON.stringify(scripts))})`,
4519
+ "local folder = ServerStorage:FindFirstChild(containerName)",
4520
+ "if not folder then",
4521
+ " folder = Instance.new('Folder')",
4522
+ " folder.Name = containerName",
4523
+ " folder.Parent = ServerStorage",
4524
+ "end",
4525
+ "local imported = 0",
4526
+ "for _, item in ipairs(items) do",
4527
+ " local ok, inst = pcall(Instance.new, item.className)",
4528
+ " if ok and inst then",
4529
+ " inst.Name = item.name .. '_' .. tostring(imported + 1)",
4530
+ " pcall(function() inst:SetAttribute('LivePath', item.path) end)",
4531
+ " pcall(function() inst.Source = item.source end)",
4532
+ " inst.Parent = folder",
4533
+ " imported = imported + 1",
4534
+ " end",
4535
+ "end",
4536
+ "return string.format('imported %d live scripts into ServerStorage.%s', imported, containerName)"
4537
+ ].join("\n");
4538
+ const studioRes = await this.studio.runStudioLuau(studioImportCode, requestedStudioId);
4539
+ if (!studioRes.ok) {
4540
+ return {
4541
+ content: [
4542
+ {
4543
+ type: "text",
4544
+ text: `live_scripts_to_studio collected ${scripts.length} scripts from live game, but Studio import failed: ${studioRes.text}`
4545
+ }
4546
+ ],
4547
+ isError: true
4548
+ };
4549
+ }
4550
+ const listLines = scripts.slice(0, 15).map((s) => ` - [${s.className}] ${s.path} (${s.source.length} bytes)`);
4551
+ return {
4552
+ content: [
4553
+ {
4554
+ type: "text",
4555
+ text: [
4556
+ `live_scripts_to_studio complete (studio_id=${studioRes.studioId ?? "auto"}):`,
4557
+ `- Scripts collected from live game: ${scripts.length}`,
4558
+ `- Studio container: ServerStorage.${containerName}`,
4559
+ `- Studio result: ${studioRes.text}`,
4560
+ ...listLines
4561
+ ].join("\n")
4562
+ }
4563
+ ]
4564
+ };
4565
+ }
4566
+ async handleCompareScreens(args) {
4567
+ const targetA = typeof args.target_a === "string" && args.target_a.trim() ? args.target_a.trim() : "roblox";
4568
+ const targetB = typeof args.target_b === "string" && args.target_b.trim() ? args.target_b.trim() : "studio";
4569
+ const rawMethod = typeof args.method === "string" ? args.method : "auto";
4570
+ const method = rawMethod === "copy" || rawMethod === "screen" ? "copy" : rawMethod === "printwindow" || rawMethod === "print_window" ? "printwindow" : "auto";
4571
+ const includeImages = args.include_images === true;
4572
+ let base64A = typeof args.base64_a === "string" && args.base64_a.trim() ? args.base64_a.trim() : "";
4573
+ let base64B = typeof args.base64_b === "string" && args.base64_b.trim() ? args.base64_b.trim() : "";
4574
+ let labelA = base64A ? "base64_a" : targetA;
4575
+ let labelB = base64B ? "base64_b" : targetB;
4576
+ let metaA;
4577
+ let metaB;
4578
+ if (!base64A) {
4579
+ const shotA = await this.windows.captureScreenshot({ target: targetA, method, clientOnly: true });
4580
+ if (!shotA.ok || !shotA.data) {
4581
+ return {
4582
+ content: [
4583
+ {
4584
+ type: "text",
4585
+ text: `compare_screens failed to capture target_a (${targetA}): ${shotA.err ?? "unknown error"}`
4586
+ }
4587
+ ],
4588
+ isError: true
4589
+ };
4590
+ }
4591
+ base64A = shotA.data;
4592
+ metaA = { width: shotA.width, height: shotA.height };
4593
+ labelA = `${targetA} (${shotA.width}x${shotA.height}, method=${shotA.captureMethod ?? method})`;
4594
+ }
4595
+ if (!base64B) {
4596
+ const shotB = await this.windows.captureScreenshot({ target: targetB, method, clientOnly: true });
4597
+ if (!shotB.ok || !shotB.data) {
4598
+ return {
4599
+ content: [
4600
+ {
4601
+ type: "text",
4602
+ text: `compare_screens failed to capture target_b (${targetB}): ${shotB.err ?? "unknown error"}`
4603
+ }
4604
+ ],
4605
+ isError: true
4606
+ };
4607
+ }
4608
+ base64B = shotB.data;
4609
+ metaB = { width: shotB.width, height: shotB.height };
4610
+ labelB = `${targetB} (${shotB.width}x${shotB.height}, method=${shotB.captureMethod ?? method})`;
4611
+ }
4612
+ const cmp = comparePngBase64(base64A, base64B, metaA, metaB);
4613
+ const content = [
4614
+ {
4615
+ type: "text",
4616
+ text: [
4617
+ `compare_screens (${labelA} vs ${labelB}):`,
4618
+ `- Similarity: ${cmp.similarityPct}% (diff=${cmp.diffPct}%)`,
4619
+ `- Dimensions: A=${cmp.widthA ?? "?"}x${cmp.heightA ?? "?"}, B=${cmp.widthB ?? "?"}x${cmp.heightB ?? "?"} (sameDimensions=${cmp.sameDimensions})`,
4620
+ `- Changed cells (>=5% diff): ${cmp.changedCells.length > 0 ? cmp.changedCells.join(", ") : "none"}`,
4621
+ `- ${cmp.gridSummary}`
4622
+ ].join("\n")
4623
+ }
4624
+ ];
4625
+ if (includeImages) {
4626
+ content.push({ type: "image", data: base64A, mimeType: "image/png" });
4627
+ content.push({ type: "image", data: base64B, mimeType: "image/png" });
4628
+ }
4629
+ return { content };
4630
+ }
2757
4631
  async handleLocalToolCall(name, args) {
2758
4632
  try {
2759
4633
  switch (name) {
@@ -2768,6 +4642,9 @@ ${lines.join("\n")}` }]
2768
4642
  case "desktop_ui_tree":
2769
4643
  return await this.handleDesktopUiTree(args);
2770
4644
  case "desktop_mouse": {
4645
+ const shouldVerify = args.verify === true;
4646
+ const session = typeof args.session === "string" ? args.session : void 0;
4647
+ const beforeSnap = shouldVerify ? await this.captureGuiSnapshotForVerify(session) : null;
2771
4648
  const res = await this.windows.mouse({
2772
4649
  action: String(args.action ?? "click"),
2773
4650
  mode: typeof args.mode === "string" ? args.mode : void 0,
@@ -2782,7 +4659,13 @@ ${lines.join("\n")}` }]
2782
4659
  holdMs: typeof args.hold_ms === "number" ? args.hold_ms : void 0,
2783
4660
  relativeTo: typeof args.relative_to === "string" ? args.relative_to : void 0
2784
4661
  });
2785
- return { content: [{ type: "text", text: res.text }], isError: !res.ok };
4662
+ let text = res.text;
4663
+ if (shouldVerify) {
4664
+ const verifyText = await this.verifyMouseActionInGame(beforeSnap, session);
4665
+ text = `${text}
4666
+ ${verifyText}`;
4667
+ }
4668
+ return { content: [{ type: "text", text }], isError: !res.ok };
2786
4669
  }
2787
4670
  case "desktop_keyboard": {
2788
4671
  const res = await this.windows.keyboard({
@@ -2797,6 +4680,20 @@ ${lines.join("\n")}` }]
2797
4680
  }
2798
4681
  case "os_click":
2799
4682
  return await this.handleOsClick(args);
4683
+ case "studio_mirror_remotes":
4684
+ return await this.handleStudioMirrorRemotes(args);
4685
+ case "studio_mirror_gui":
4686
+ return await this.handleStudioMirrorGui(args);
4687
+ case "studio_diff":
4688
+ return await this.handleStudioDiff(args);
4689
+ case "studio_to_live":
4690
+ return await this.handleStudioToLive(args);
4691
+ case "studio_publish":
4692
+ return await this.handleStudioPublish(args);
4693
+ case "live_scripts_to_studio":
4694
+ return await this.handleLiveScriptsToStudio(args);
4695
+ case "compare_screens":
4696
+ return await this.handleCompareScreens(args);
2800
4697
  default:
2801
4698
  return null;
2802
4699
  }
@@ -2896,9 +4793,20 @@ ${lines.join("\n")}` }]
2896
4793
  });
2897
4794
  }
2898
4795
  if (!res.body) return null;
4796
+ if (msg?.method === "initialize" && res.body.result && typeof res.body.result === "object") {
4797
+ const scopeRes = await this.checkTokenScopes();
4798
+ if (scopeRes.warning) {
4799
+ const initResult = res.body.result;
4800
+ const prevInstructions = typeof initResult.instructions === "string" ? initResult.instructions.trim() : "";
4801
+ initResult.instructions = prevInstructions ? `${prevInstructions}
4802
+
4803
+ ${scopeRes.warning}` : scopeRes.warning;
4804
+ }
4805
+ }
2899
4806
  if (msg?.method === "tools/list" && res.body.result && typeof res.body.result === "object") {
2900
4807
  const resultObj = res.body.result;
2901
4808
  if (Array.isArray(resultObj.tools)) {
4809
+ this.evaluateTokenScopesFromTools(resultObj.tools);
2902
4810
  const existingNames = new Set(resultObj.tools.map((t) => String(t.name ?? "")));
2903
4811
  for (const tool of resultObj.tools) {
2904
4812
  const tName = String(tool.name ?? "");
@@ -2976,9 +4884,13 @@ async function forwardJsonRpcLine(line, options) {
2976
4884
  autoInject: options.autoInject ?? false,
2977
4885
  autoInjectPollMs: options.autoInjectPollMs,
2978
4886
  autoInjectMaxPolls: options.autoInjectMaxPolls,
4887
+ autoInjectCooldownMs: options.autoInjectCooldownMs,
2979
4888
  fetchImpl: options.fetchImpl,
2980
4889
  potassiumClient: options.potassiumClient,
2981
- windowsDriver: options.windowsDriver
4890
+ windowsDriver: options.windowsDriver,
4891
+ studioClient: options.studioClient,
4892
+ studioOptions: options.studioOptions,
4893
+ stderr: options.stderr
2982
4894
  });
2983
4895
  return bridge.handleJsonRpcLine(line);
2984
4896
  }
@@ -2986,7 +4898,7 @@ function startStdioBridge(options = {}) {
2986
4898
  const stdin = options.stdin ?? process.stdin;
2987
4899
  const stdout = options.stdout ?? process.stdout;
2988
4900
  const bridge = new HybridMcpBridge(options);
2989
- const rl = createInterface2({ input: stdin, crlfDelay: Number.POSITIVE_INFINITY });
4901
+ const rl = createInterface3({ input: stdin, crlfDelay: Number.POSITIVE_INFINITY });
2990
4902
  const pending = /* @__PURE__ */ new Set();
2991
4903
  rl.on("line", (line) => {
2992
4904
  const task = (async () => {
@@ -3003,6 +4915,7 @@ function startStdioBridge(options = {}) {
3003
4915
  rl.on("close", async () => {
3004
4916
  await Promise.allSettled([...pending]);
3005
4917
  bridge.windows.dispose?.();
4918
+ bridge.studio.dispose?.();
3006
4919
  resolveDone();
3007
4920
  });
3008
4921
  });
@@ -3018,21 +4931,29 @@ export {
3018
4931
  HybridMcpBridge,
3019
4932
  LOCAL_HYBRID_TOOLS,
3020
4933
  MCP_BRIDGE_VERSION,
4934
+ POTASSIUM_ENABLE_HINT,
3021
4935
  PotassiumClient,
3022
4936
  PowerShellWindowsDriver,
4937
+ RobloxStudioMcpClient,
3023
4938
  SCRATCH_TAB_NAME,
4939
+ TOKEN_CREATE_URL,
3024
4940
  TOKEN_SHAPE,
3025
4941
  buildListWindowsPsScript,
3026
4942
  buildRobloxDeepLink,
3027
4943
  buildScreenshotPsScript,
3028
4944
  buildUiTreePsScript,
3029
4945
  buildUipiWarning,
4946
+ comparePngBase64,
4947
+ decodePngRgba,
3030
4948
  discoverPotassiumAutoexecDir,
3031
4949
  discoverPotassiumToken,
4950
+ discoverRobloxStudioMcpBatch,
3032
4951
  encodePowerShellCommand,
3033
4952
  findPotassiumBinary,
3034
4953
  findRobloxPlayerBinary,
3035
4954
  forwardJsonRpcLine,
4955
+ isRobloxPlayerWindow,
4956
+ isRobloxStudioWindow,
3036
4957
  matchesWindowTarget,
3037
4958
  resolveBridgeConfig,
3038
4959
  resolveStoredToken,