@luaward/mcp 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,17 +1,1220 @@
1
1
  // src/index.ts
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { homedir } from "node:os";
4
- import { join } from "node:path";
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
5
  import { createInterface } from "node:readline";
6
- var MCP_BRIDGE_VERSION = "0.1.0";
6
+
7
+ // src/potassium.ts
8
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { dirname, join, resolve } from "node:path";
11
+ var DEFAULT_POTASSIUM_URL = "http://127.0.0.1:8225/mcp";
12
+ var SCRATCH_TAB_NAME = "luaward_scratch.luau";
13
+ function discoverPotassiumToken(env = process.env) {
14
+ const fromEnv = (env.POTASSIUM_MCP_TOKEN || env.POTASSIUM_TOKEN || "").trim();
15
+ if (fromEnv) return fromEnv;
16
+ const home = homedir();
17
+ const appData = env.APPDATA || join(home, "AppData", "Roaming");
18
+ const localAppData = env.LOCALAPPDATA || join(home, "AppData", "Local");
19
+ const candidates = [
20
+ join(appData, "Potassium", "mcp.json"),
21
+ join(appData, "Potassium", "config.json"),
22
+ join(appData, "Potassium", "settings.json"),
23
+ join(localAppData, "Potassium", "mcp.json"),
24
+ join(localAppData, "Potassium", "config.json"),
25
+ join(localAppData, "Potassium", "settings.json"),
26
+ join(home, ".potassium", "mcp.json")
27
+ ];
28
+ for (const path of candidates) {
29
+ if (!existsSync(path)) continue;
30
+ try {
31
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
32
+ for (const key of ["mcpToken", "mcp_token", "bearerToken", "token", "apiKey"]) {
33
+ const val = parsed[key];
34
+ if (typeof val === "string" && val.trim()) return val.trim();
35
+ }
36
+ const mcp = parsed.mcp;
37
+ if (mcp && typeof mcp === "object") {
38
+ const t = mcp.token ?? mcp.bearerToken;
39
+ if (typeof t === "string" && t.trim()) return t.trim();
40
+ }
41
+ } catch {
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+ function discoverPotassiumAutoexecDir(customDir, env = process.env) {
47
+ if (customDir?.trim()) return resolve(customDir.trim());
48
+ if (env.POTASSIUM_AUTOEXEC_DIR?.trim()) {
49
+ return resolve(env.POTASSIUM_AUTOEXEC_DIR.trim());
50
+ }
51
+ const home = homedir();
52
+ const appData = env.APPDATA || join(home, "AppData", "Roaming");
53
+ const localAppData = env.LOCALAPPDATA || join(home, "AppData", "Local");
54
+ const candidates = [
55
+ join(appData, "Potassium", "autoexec"),
56
+ join(appData, "Potassium", "AUTO EXECUTE"),
57
+ join(localAppData, "Potassium", "autoexec"),
58
+ join(localAppData, "Potassium", "AUTO EXECUTE"),
59
+ join(home, "Potassium", "autoexec"),
60
+ join(home, "Potassium", "AUTO EXECUTE")
61
+ ];
62
+ for (const dir of candidates) {
63
+ if (existsSync(dir)) return dir;
64
+ }
65
+ for (const dir of candidates) {
66
+ if (existsSync(dirname(dir))) return dir;
67
+ }
68
+ return candidates[0];
69
+ }
70
+ function parseRpcPayload(rawText) {
71
+ const trimmed = rawText.trim();
72
+ if (!trimmed) return null;
73
+ if (trimmed.startsWith("{")) {
74
+ try {
75
+ return JSON.parse(trimmed);
76
+ } catch {
77
+ }
78
+ }
79
+ let lastJson = null;
80
+ for (const line of trimmed.split(/\r?\n/)) {
81
+ const clean = line.trim();
82
+ const jsonPart = clean.startsWith("data:") ? clean.slice(5).trim() : clean;
83
+ if (jsonPart.startsWith("{")) {
84
+ try {
85
+ lastJson = JSON.parse(jsonPart);
86
+ } catch {
87
+ }
88
+ }
89
+ }
90
+ return lastJson;
91
+ }
92
+ function extractToolResultText(rpcRes) {
93
+ if (!rpcRes) {
94
+ return { ok: false, text: "Empty response from Potassium local MCP", isError: true };
95
+ }
96
+ if (rpcRes.error && typeof rpcRes.error === "object") {
97
+ const err = rpcRes.error;
98
+ return {
99
+ ok: false,
100
+ text: err.message || `Potassium MCP error (${String(err.code ?? "unknown")})`,
101
+ isError: true
102
+ };
103
+ }
104
+ const result = rpcRes.result;
105
+ if (!result || typeof result !== "object") {
106
+ return { ok: true, text: JSON.stringify(rpcRes.result ?? {}) };
107
+ }
108
+ const texts = [];
109
+ if (Array.isArray(result.content)) {
110
+ for (const item of result.content) {
111
+ if (item && typeof item.text === "string") {
112
+ texts.push(item.text);
113
+ }
114
+ }
115
+ }
116
+ const joined = texts.join("\n").trim();
117
+ let structured = result.structuredContent;
118
+ if (structured === void 0 && joined.startsWith("{")) {
119
+ try {
120
+ structured = JSON.parse(joined);
121
+ } catch {
122
+ }
123
+ } else if (structured === void 0 && joined.startsWith("[")) {
124
+ try {
125
+ structured = JSON.parse(joined);
126
+ } catch {
127
+ }
128
+ }
129
+ return {
130
+ ok: !result.isError,
131
+ text: joined || (structured !== void 0 ? JSON.stringify(structured) : "ok"),
132
+ structured,
133
+ isError: Boolean(result.isError)
134
+ };
135
+ }
136
+ var PotassiumClient = class {
137
+ url;
138
+ token;
139
+ autoexecDir;
140
+ fetchFn;
141
+ sessionId = null;
142
+ initialized = false;
143
+ rpcSeq = 1e3;
144
+ constructor(options = {}) {
145
+ this.url = (options.url || process.env.POTASSIUM_MCP_URL || DEFAULT_POTASSIUM_URL).trim();
146
+ this.token = options.token !== void 0 ? options.token : discoverPotassiumToken();
147
+ this.autoexecDir = options.autoexecDir;
148
+ this.fetchFn = options.fetchImpl ?? fetch;
149
+ }
150
+ buildHeaders() {
151
+ const h = {
152
+ "content-type": "application/json",
153
+ accept: "application/json, text/event-stream"
154
+ };
155
+ if (this.token) {
156
+ h.authorization = this.token.startsWith("Bearer ") ? this.token : `Bearer ${this.token}`;
157
+ }
158
+ if (this.sessionId) {
159
+ h["mcp-session-id"] = this.sessionId;
160
+ }
161
+ return h;
162
+ }
163
+ async ensureInitialized() {
164
+ if (this.initialized) return true;
165
+ try {
166
+ const res = await this.fetchFn(this.url, {
167
+ method: "POST",
168
+ headers: this.buildHeaders(),
169
+ body: JSON.stringify({
170
+ jsonrpc: "2.0",
171
+ id: ++this.rpcSeq,
172
+ method: "initialize",
173
+ params: {
174
+ protocolVersion: "2025-03-26",
175
+ capabilities: {},
176
+ clientInfo: { name: "@luaward/mcp", version: "0.2.0" }
177
+ }
178
+ })
179
+ });
180
+ const sid = res.headers?.get?.("mcp-session-id");
181
+ if (sid) this.sessionId = sid;
182
+ if (!res.ok) return false;
183
+ this.initialized = true;
184
+ return true;
185
+ } catch {
186
+ return false;
187
+ }
188
+ }
189
+ async callTool(name, args = {}) {
190
+ await this.ensureInitialized();
191
+ try {
192
+ const res = await this.fetchFn(this.url, {
193
+ method: "POST",
194
+ headers: this.buildHeaders(),
195
+ body: JSON.stringify({
196
+ jsonrpc: "2.0",
197
+ id: ++this.rpcSeq,
198
+ method: "tools/call",
199
+ params: { name, arguments: args }
200
+ })
201
+ });
202
+ const sid = res.headers?.get?.("mcp-session-id");
203
+ if (sid) this.sessionId = sid;
204
+ const rawText = await res.text();
205
+ if (!res.ok) {
206
+ return {
207
+ ok: false,
208
+ text: `Potassium local MCP at ${this.url} returned HTTP ${res.status}: ${rawText.slice(0, 200)}`,
209
+ isError: true
210
+ };
211
+ }
212
+ return extractToolResultText(parseRpcPayload(rawText));
213
+ } catch (err) {
214
+ const msg = err instanceof Error ? err.message : String(err);
215
+ return {
216
+ ok: false,
217
+ text: `Potassium local MCP (${this.url}) is not reachable: ${msg}`,
218
+ isError: true
219
+ };
220
+ }
221
+ }
222
+ async listClients() {
223
+ const res = await this.callTool("list_clients", {});
224
+ if (!res.ok) return { ok: false, clients: [], rawText: res.text };
225
+ const clients = [];
226
+ const s = res.structured;
227
+ const arr = Array.isArray(s) ? s : s && typeof s === "object" && Array.isArray(s.clients) ? s.clients : null;
228
+ if (arr) {
229
+ for (const item of arr) {
230
+ if (item && typeof item === "object") {
231
+ const obj = item;
232
+ clients.push({
233
+ pid: obj.pid ?? obj.processId ?? obj.id,
234
+ id: String(obj.id ?? obj.pid ?? ""),
235
+ username: typeof obj.username === "string" ? obj.username : obj.user,
236
+ userId: obj.userId ?? obj.user_id,
237
+ placeId: obj.placeId ?? obj.place_id,
238
+ raw: obj
239
+ });
240
+ }
241
+ }
242
+ return { ok: true, clients, rawText: res.text };
243
+ }
244
+ const pidMatches = [...res.text.matchAll(/\b(?:pid|process|client)[:=\s#]*(\d{2,10})\b/gi)];
245
+ for (const m of pidMatches) {
246
+ if (m[1]) clients.push({ pid: Number(m[1]), id: m[1] });
247
+ }
248
+ return { ok: true, clients, rawText: res.text };
249
+ }
250
+ async executeScript(code, pids) {
251
+ const args = { script: code, code };
252
+ if (pids && pids.length > 0) {
253
+ args.pids = pids;
254
+ args.pid = pids[0];
255
+ args.clients = pids;
256
+ }
257
+ return this.callTool("execute_script", args);
258
+ }
259
+ async listTabs() {
260
+ const res = await this.callTool("tabs", { action: "list" });
261
+ if (!res.ok) return { ok: false, tabs: [], rawText: res.text };
262
+ const tabs = [];
263
+ const s = res.structured;
264
+ const arr = Array.isArray(s) ? s : s && typeof s === "object" && Array.isArray(s.tabs) ? s.tabs : null;
265
+ if (arr) {
266
+ for (const item of arr) {
267
+ if (item && typeof item === "object") {
268
+ const obj = item;
269
+ const id = String(obj.id ?? obj.tab_id ?? obj.tabId ?? "");
270
+ const name = String(obj.name ?? obj.title ?? id);
271
+ if (id) {
272
+ tabs.push({
273
+ id,
274
+ name,
275
+ dirty: Boolean(obj.dirty),
276
+ active: Boolean(obj.active ?? obj.selected),
277
+ content: typeof obj.content === "string" ? obj.content : void 0
278
+ });
279
+ }
280
+ }
281
+ }
282
+ }
283
+ return { ok: true, tabs, rawText: res.text };
284
+ }
285
+ async readTab(tabId) {
286
+ let targetId = tabId;
287
+ let targetName;
288
+ if (!targetId) {
289
+ const listed = await this.listTabs();
290
+ const active = listed.tabs.find((t) => t.active) ?? listed.tabs[0];
291
+ if (active) {
292
+ targetId = active.id;
293
+ targetName = active.name;
294
+ }
295
+ }
296
+ const res = await this.callTool("tabs", {
297
+ action: "read",
298
+ ...targetId ? { tab_id: targetId, id: targetId } : {}
299
+ });
300
+ if (!res.ok) return { ok: false, content: res.text, tabId: targetId };
301
+ if (res.structured && typeof res.structured === "object") {
302
+ const obj = res.structured;
303
+ if (typeof obj.content === "string") {
304
+ return {
305
+ ok: true,
306
+ content: obj.content,
307
+ tabId: String(obj.id ?? obj.tab_id ?? targetId ?? ""),
308
+ name: typeof obj.name === "string" ? obj.name : obj.title ?? targetName
309
+ };
310
+ }
311
+ }
312
+ return { ok: true, content: res.text, tabId: targetId, name: targetName };
313
+ }
314
+ /**
315
+ * Potassium marks every tab created via `open` or modified via `write` as `dirty: true` and refuses to `close` dirty
316
+ * tabs without a save command. To prevent tab clutter, we reuse an existing tab with the same name or `luaward_scratch.luau`.
317
+ */
318
+ async openOrReuseTab(opts) {
319
+ const desiredName = (opts.name || SCRATCH_TAB_NAME).trim();
320
+ const reuseScratch = opts.reuseScratch !== false;
321
+ if (opts.tabId) {
322
+ const w = await this.callTool("tabs", {
323
+ action: "write",
324
+ tab_id: opts.tabId,
325
+ id: opts.tabId,
326
+ content: opts.content
327
+ });
328
+ await this.callTool("tabs", { action: "activate", tab_id: opts.tabId, id: opts.tabId });
329
+ return {
330
+ ok: w.ok,
331
+ tabId: opts.tabId,
332
+ name: desiredName,
333
+ reused: true,
334
+ text: w.ok ? `updated tab ${opts.tabId} (${desiredName})` : w.text
335
+ };
336
+ }
337
+ const listed = await this.listTabs();
338
+ if (listed.ok && listed.tabs.length > 0) {
339
+ const exact = listed.tabs.find((t) => t.name.toLowerCase() === desiredName.toLowerCase());
340
+ const scratch = reuseScratch ? listed.tabs.find(
341
+ (t) => t.name.toLowerCase() === SCRATCH_TAB_NAME.toLowerCase() || t.name.toLowerCase() === "luaward_scratch"
342
+ ) : void 0;
343
+ const target = exact ?? scratch;
344
+ if (target) {
345
+ const w = await this.callTool("tabs", {
346
+ action: "write",
347
+ tab_id: target.id,
348
+ id: target.id,
349
+ content: opts.content
350
+ });
351
+ await this.callTool("tabs", { action: "activate", tab_id: target.id, id: target.id });
352
+ return {
353
+ ok: w.ok,
354
+ tabId: target.id,
355
+ name: target.name,
356
+ reused: true,
357
+ text: w.ok ? `reused tab "${target.name}" (id ${target.id}, ${opts.content.length} chars)` : w.text
358
+ };
359
+ }
360
+ }
361
+ const opened = await this.callTool("tabs", {
362
+ action: "open",
363
+ name: desiredName,
364
+ title: desiredName,
365
+ content: opts.content
366
+ });
367
+ let newId = desiredName;
368
+ if (opened.structured && typeof opened.structured === "object") {
369
+ const obj = opened.structured;
370
+ if (obj.id ?? obj.tab_id) newId = String(obj.id ?? obj.tab_id);
371
+ }
372
+ return {
373
+ ok: opened.ok,
374
+ tabId: newId,
375
+ name: desiredName,
376
+ reused: false,
377
+ text: opened.ok ? `opened tab "${desiredName}" (id ${newId}, ${opts.content.length} chars)` : opened.text
378
+ };
379
+ }
380
+ installAutoexecBootstrapper(pairCommand, customDir) {
381
+ const dir = discoverPotassiumAutoexecDir(customDir || this.autoexecDir);
382
+ const filePath = join(dir, "luaward_init.luau");
383
+ const scriptBody = [
384
+ "-- Luaward Zero-Touch Auto-Connect Bootstrapper (managed by @luaward/mcp)",
385
+ "-- Runs automatically when Potassium attaches with Auto Execute enabled.",
386
+ "task.spawn(function()",
387
+ " if not game:IsLoaded() then",
388
+ " game.Loaded:Wait()",
389
+ " end",
390
+ " task.wait(1)",
391
+ " pcall(function()",
392
+ ` ${pairCommand.trim()}`,
393
+ " end)",
394
+ "end)",
395
+ ""
396
+ ].join("\n");
397
+ try {
398
+ mkdirSync(dir, { recursive: true });
399
+ writeFileSync(filePath, scriptBody, "utf8");
400
+ return {
401
+ ok: true,
402
+ filePath,
403
+ text: `installed Luaward autoexec bootstrapper at ${filePath}`
404
+ };
405
+ } catch (err) {
406
+ return {
407
+ ok: false,
408
+ filePath,
409
+ text: `failed to write autoexec bootstrapper at ${filePath}: ${err instanceof Error ? err.message : String(err)}`
410
+ };
411
+ }
412
+ }
413
+ };
414
+
415
+ // src/windows.ts
416
+ import { execFile } from "node:child_process";
417
+ import { existsSync as existsSync2, readdirSync, statSync } from "node:fs";
418
+ import { homedir as homedir2 } from "node:os";
419
+ import { join as join2 } from "node:path";
420
+ import { promisify } from "node:util";
421
+ var execFileAsync = promisify(execFile);
422
+ function buildRobloxDeepLink(params) {
423
+ const place = String(params.placeId).trim();
424
+ if (!/^\d+$/.test(place)) {
425
+ throw new Error(`Invalid Roblox place_id "${place}" (must be numeric)`);
426
+ }
427
+ const queryParts = [`placeId=${encodeURIComponent(place)}`];
428
+ if (params.jobId?.trim()) {
429
+ queryParts.push(`gameInstanceId=${encodeURIComponent(params.jobId.trim())}`);
430
+ }
431
+ if (params.accessCode?.trim()) {
432
+ queryParts.push(`accessCode=${encodeURIComponent(params.accessCode.trim())}`);
433
+ }
434
+ if (params.launchData?.trim()) {
435
+ queryParts.push(`launchData=${encodeURIComponent(params.launchData.trim())}`);
436
+ }
437
+ return `roblox://experiences/start?${queryParts.join("&")}`;
438
+ }
439
+ function findRobloxPlayerBinary(env = process.env) {
440
+ if (env.ROBLOX_PLAYER_PATH && existsSync2(env.ROBLOX_PLAYER_PATH)) {
441
+ return env.ROBLOX_PLAYER_PATH;
442
+ }
443
+ const home = homedir2();
444
+ const localAppData = env.LOCALAPPDATA || join2(home, "AppData", "Local");
445
+ const roots = [
446
+ join2(localAppData, "Roblox", "Versions"),
447
+ join2(localAppData, "Bloxstrap", "Versions"),
448
+ join2(localAppData, "Fishstrap", "Versions"),
449
+ "C:\\Program Files (x86)\\Roblox\\Versions"
450
+ ];
451
+ let newestExe = null;
452
+ let newestMtime = -1;
453
+ for (const root of roots) {
454
+ if (!existsSync2(root)) continue;
455
+ try {
456
+ for (const entry of readdirSync(root)) {
457
+ const exe = join2(root, entry, "RobloxPlayerBeta.exe");
458
+ if (existsSync2(exe)) {
459
+ const st = statSync(exe);
460
+ if (st.mtimeMs > newestMtime) {
461
+ newestMtime = st.mtimeMs;
462
+ newestExe = exe;
463
+ }
464
+ }
465
+ }
466
+ } catch {
467
+ }
468
+ }
469
+ return newestExe;
470
+ }
471
+ function findPotassiumBinary(customPath, env = process.env) {
472
+ if (customPath && existsSync2(customPath)) return customPath;
473
+ if (env.POTASSIUM_PATH && existsSync2(env.POTASSIUM_PATH)) return env.POTASSIUM_PATH;
474
+ const home = homedir2();
475
+ const localAppData = env.LOCALAPPDATA || join2(home, "AppData", "Local");
476
+ const appData = env.APPDATA || join2(home, "AppData", "Roaming");
477
+ const candidates = [
478
+ join2(localAppData, "Potassium", "Potassium.exe"),
479
+ join2(appData, "Potassium", "Potassium.exe"),
480
+ join2(home, "Desktop", "Potassium.exe"),
481
+ join2(home, "Desktop", "Potassium", "Potassium.exe"),
482
+ join2(home, "Downloads", "Potassium", "Potassium.exe"),
483
+ "C:\\Potassium\\Potassium.exe"
484
+ ];
485
+ for (const c of candidates) {
486
+ if (existsSync2(c)) return c;
487
+ }
488
+ return null;
489
+ }
490
+ var VK_MAP = {
491
+ BACKSPACE: 8,
492
+ TAB: 9,
493
+ RETURN: 13,
494
+ ENTER: 13,
495
+ SHIFT: 16,
496
+ LEFTSHIFT: 160,
497
+ RIGHTSHIFT: 161,
498
+ CTRL: 17,
499
+ CONTROL: 17,
500
+ LEFTCONTROL: 162,
501
+ RIGHTCONTROL: 163,
502
+ ALT: 18,
503
+ MENU: 18,
504
+ LEFTALT: 164,
505
+ RIGHTALT: 165,
506
+ PAUSE: 19,
507
+ CAPSLOCK: 20,
508
+ ESCAPE: 27,
509
+ ESC: 27,
510
+ SPACE: 32,
511
+ PAGEUP: 33,
512
+ PAGEDOWN: 34,
513
+ END: 35,
514
+ HOME: 36,
515
+ LEFT: 37,
516
+ UP: 38,
517
+ RIGHT: 39,
518
+ DOWN: 40,
519
+ INSERT: 45,
520
+ DELETE: 46,
521
+ F1: 112,
522
+ F2: 113,
523
+ F3: 114,
524
+ F4: 115,
525
+ F5: 116,
526
+ F6: 117,
527
+ F7: 118,
528
+ F8: 119,
529
+ F9: 120,
530
+ F10: 121,
531
+ F11: 122,
532
+ F12: 123
533
+ };
534
+ function resolveVirtualKeyCode(keyName) {
535
+ const clean = keyName.trim().toUpperCase().replace(/^ENUM\.KEYCODE\./, "");
536
+ if (VK_MAP[clean] !== void 0) return VK_MAP[clean];
537
+ if (clean.length === 1) {
538
+ const ch = clean.charCodeAt(0);
539
+ if (ch >= 48 && ch <= 57 || ch >= 65 && ch <= 90) {
540
+ return ch;
541
+ }
542
+ }
543
+ const numMap = {
544
+ ZERO: 48,
545
+ ONE: 49,
546
+ TWO: 50,
547
+ THREE: 51,
548
+ FOUR: 52,
549
+ FIVE: 53,
550
+ SIX: 54,
551
+ SEVEN: 55,
552
+ EIGHT: 56,
553
+ NINE: 57
554
+ };
555
+ if (numMap[clean] !== void 0) return numMap[clean];
556
+ throw new Error(
557
+ `Unsupported key name "${keyName}". Use standard key names like W, A, S, D, E, Space, Return, Escape, F1-F12.`
558
+ );
559
+ }
560
+ var WIN32_CSHARP_PRELUDE = `
561
+ if (-not ("Luaward.Win32Desktop" -as [type])) {
562
+ Add-Type -AssemblyName System.Drawing
563
+ Add-Type -AssemblyName System.Windows.Forms
564
+ Add-Type -AssemblyName UIAutomationClient
565
+ Add-Type -AssemblyName UIAutomationTypes
566
+ Add-Type @"
567
+ using System;
568
+ using System.Runtime.InteropServices;
569
+ using System.Text;
570
+
571
+ namespace Luaward {
572
+ [StructLayout(LayoutKind.Sequential)]
573
+ public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
574
+
575
+ [StructLayout(LayoutKind.Sequential)]
576
+ public struct POINT { public int X; public int Y; }
577
+
578
+ [StructLayout(LayoutKind.Sequential)]
579
+ public struct MOUSEINPUT {
580
+ public int dx;
581
+ public int dy;
582
+ public uint mouseData;
583
+ public uint dwFlags;
584
+ public uint time;
585
+ public IntPtr dwExtraInfo;
586
+ }
587
+
588
+ [StructLayout(LayoutKind.Sequential)]
589
+ public struct KEYBDINPUT {
590
+ public ushort wVk;
591
+ public ushort wScan;
592
+ public uint dwFlags;
593
+ public uint time;
594
+ public IntPtr dwExtraInfo;
595
+ }
596
+
597
+ [StructLayout(LayoutKind.Explicit)]
598
+ public struct INPUTUNION {
599
+ [FieldOffset(0)] public MOUSEINPUT mi;
600
+ [FieldOffset(0)] public KEYBDINPUT ki;
601
+ }
602
+
603
+ [StructLayout(LayoutKind.Sequential)]
604
+ public struct INPUT {
605
+ public uint type;
606
+ public INPUTUNION u;
607
+ }
608
+
609
+ public static class Win32Desktop {
610
+ public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
611
+ [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
612
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
613
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
614
+ [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
615
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
616
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
617
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
618
+ [DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
619
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
620
+ [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
621
+ [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
622
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
623
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
624
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
625
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y);
626
+ [DllImport("user32.dll")] public static extern int GetSystemMetrics(int nIndex);
627
+ [DllImport("user32.dll")] public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
628
+ [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint uCode, uint uMapType);
629
+
630
+ public const uint INPUT_MOUSE = 0;
631
+ public const uint INPUT_KEYBOARD = 1;
632
+ public const uint MOUSEEVENTF_MOVE = 0x0001;
633
+ public const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
634
+ public const uint MOUSEEVENTF_LEFTUP = 0x0004;
635
+ public const uint MOUSEEVENTF_RIGHTDOWN = 0x0008;
636
+ public const uint MOUSEEVENTF_RIGHTUP = 0x0010;
637
+ public const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020;
638
+ public const uint MOUSEEVENTF_MIDDLEUP = 0x0040;
639
+ public const uint MOUSEEVENTF_WHEEL = 0x0800;
640
+ public const uint MOUSEEVENTF_VIRTUALDESK = 0x4000;
641
+ public const uint MOUSEEVENTF_ABSOLUTE = 0x8000;
642
+ public const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
643
+ public const uint KEYEVENTF_KEYUP = 0x0002;
644
+ public const uint KEYEVENTF_UNICODE = 0x0004;
645
+ public const uint KEYEVENTF_SCANCODE = 0x0008;
646
+
647
+ public static void SendMouseMoveAbs(int screenX, int screenY) {
648
+ SetCursorPos(screenX, screenY);
649
+ int vx = GetSystemMetrics(76); // SM_XVIRTUALSCREEN
650
+ int vy = GetSystemMetrics(77); // SM_YVIRTUALSCREEN
651
+ int vw = Math.Max(1, GetSystemMetrics(78) - 1); // SM_CXVIRTUALSCREEN
652
+ int vh = Math.Max(1, GetSystemMetrics(79) - 1); // SM_CYVIRTUALSCREEN
653
+ INPUT[] inp = new INPUT[1];
654
+ inp[0].type = INPUT_MOUSE;
655
+ inp[0].u.mi.dx = (int)Math.Round(((screenX - vx) * 65535.0) / vw);
656
+ inp[0].u.mi.dy = (int)Math.Round(((screenY - vy) * 65535.0) / vh);
657
+ inp[0].u.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK;
658
+ SendInput(1, inp, Marshal.SizeOf(typeof(INPUT)));
659
+ }
660
+
661
+ public static void SendMouseMoveRel(int dx, int dy) {
662
+ INPUT[] inp = new INPUT[1];
663
+ inp[0].type = INPUT_MOUSE;
664
+ inp[0].u.mi.dx = dx;
665
+ inp[0].u.mi.dy = dy;
666
+ inp[0].u.mi.dwFlags = MOUSEEVENTF_MOVE;
667
+ SendInput(1, inp, Marshal.SizeOf(typeof(INPUT)));
668
+ }
669
+
670
+ public static void SendMouseButton(uint flag, uint mouseData = 0) {
671
+ INPUT[] inp = new INPUT[1];
672
+ inp[0].type = INPUT_MOUSE;
673
+ inp[0].u.mi.dwFlags = flag;
674
+ inp[0].u.mi.mouseData = mouseData;
675
+ SendInput(1, inp, Marshal.SizeOf(typeof(INPUT)));
676
+ }
677
+
678
+ public static void SendKeyVk(ushort vk, bool keyUp) {
679
+ ushort scan = (ushort)MapVirtualKey(vk, 0);
680
+ uint flags = KEYEVENTF_SCANCODE | (keyUp ? KEYEVENTF_KEYUP : 0u);
681
+ if ((vk >= 0x21 && vk <= 0x2e) || vk == 0xa3 || vk == 0xa5) flags |= KEYEVENTF_EXTENDEDKEY;
682
+ INPUT[] inp = new INPUT[1];
683
+ inp[0].type = INPUT_KEYBOARD;
684
+ inp[0].u.ki.wVk = vk;
685
+ inp[0].u.ki.wScan = scan;
686
+ inp[0].u.ki.dwFlags = flags;
687
+ SendInput(1, inp, Marshal.SizeOf(typeof(INPUT)));
688
+ }
689
+
690
+ public static void SendUnicodeString(string text) {
691
+ foreach (char c in text) {
692
+ INPUT[] inp = new INPUT[2];
693
+ inp[0].type = INPUT_KEYBOARD;
694
+ inp[0].u.ki.wScan = (ushort)c;
695
+ inp[0].u.ki.dwFlags = KEYEVENTF_UNICODE;
696
+ inp[1].type = INPUT_KEYBOARD;
697
+ inp[1].u.ki.wScan = (ushort)c;
698
+ inp[1].u.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
699
+ SendInput(2, inp, Marshal.SizeOf(typeof(INPUT)));
700
+ }
701
+ }
702
+ }
703
+ }
704
+ "@
705
+ [void][Luaward.Win32Desktop]::SetProcessDPIAware()
706
+ }
707
+ `;
708
+ var PowerShellWindowsDriver = class {
709
+ async runPsJson(scriptBody, timeoutMs = 2e4) {
710
+ if (process.platform !== "win32") {
711
+ throw new Error(
712
+ "Windows Computer Use tools require Windows OS (win32) or a configured WindowsDriver mock."
713
+ );
714
+ }
715
+ const full = `${WIN32_CSHARP_PRELUDE}
716
+ $ErrorActionPreference = 'Stop'
717
+ ${scriptBody}`;
718
+ const { stdout } = await execFileAsync(
719
+ "powershell.exe",
720
+ ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", full],
721
+ { timeout: timeoutMs, maxBuffer: 25 * 1024 * 1024 }
722
+ );
723
+ const trimmed = stdout.trim();
724
+ const jsonLine = trimmed.split(/\r?\n/).reverse().find((l) => l.trim().startsWith("{") || l.trim().startsWith("["));
725
+ return JSON.parse(jsonLine || trimmed);
726
+ }
727
+ async listWindows(targetFilter) {
728
+ const filterStr = (targetFilter || "").trim().toLowerCase();
729
+ const ps = `
730
+ $fg = [Luaward.Win32Desktop]::GetForegroundWindow()
731
+ $list = New-Object System.Collections.Generic.List[object]
732
+ $cb = [Luaward.Win32Desktop+EnumWindowsProc]{
733
+ param($hWnd, $lParam)
734
+ if (-not [Luaward.Win32Desktop]::IsWindowVisible($hWnd)) { return $true }
735
+ $sb = New-Object System.Text.StringBuilder 256
736
+ [void][Luaward.Win32Desktop]::GetWindowText($hWnd, $sb, $sb.Capacity)
737
+ $title = $sb.ToString()
738
+ if ([string]::IsNullOrWhiteSpace($title)) { return $true }
739
+ $csb = New-Object System.Text.StringBuilder 128
740
+ [void][Luaward.Win32Desktop]::GetClassName($hWnd, $csb, $csb.Capacity)
741
+ $cls = $csb.ToString()
742
+ $pidVal = [uint32]0
743
+ [void][Luaward.Win32Desktop]::GetWindowThreadProcessId($hWnd, [ref]$pidVal)
744
+ $procName = ""
745
+ $resp = $true
746
+ try {
747
+ $p = Get-Process -Id $pidVal -ErrorAction SilentlyContinue
748
+ if ($p) { $procName = $p.ProcessName; $resp = [bool]$p.Responding }
749
+ } catch {}
750
+ $wr = New-Object Luaward.RECT
751
+ [void][Luaward.Win32Desktop]::GetWindowRect($hWnd, [ref]$wr)
752
+ $cr = New-Object Luaward.RECT
753
+ [void][Luaward.Win32Desktop]::GetClientRect($hWnd, [ref]$cr)
754
+ $pt = New-Object Luaward.POINT
755
+ [void][Luaward.Win32Desktop]::ClientToScreen($hWnd, [ref]$pt)
756
+ $list.Add(@{
757
+ hwnd = "0x" + $hWnd.ToString("X")
758
+ pid = [int]$pidVal
759
+ processName = $procName
760
+ title = $title
761
+ className = $cls
762
+ responding = $resp
763
+ isMinimized = [Luaward.Win32Desktop]::IsIconic($hWnd)
764
+ isForeground = ($hWnd -eq $fg)
765
+ rect = @{ left = $wr.Left; top = $wr.Top; width = ($wr.Right - $wr.Left); height = ($wr.Bottom - $wr.Top) }
766
+ clientRect = @{ screenLeft = $pt.X; screenTop = $pt.Y; width = ($cr.Right - $cr.Left); height = ($cr.Bottom - $cr.Top) }
767
+ })
768
+ return $true
769
+ }
770
+ [void][Luaward.Win32Desktop]::EnumWindows($cb, [IntPtr]::Zero)
771
+ ConvertTo-Json -InputObject @($list) -Depth 5 -Compress
772
+ `;
773
+ const all = await this.runPsJson(ps);
774
+ if (!filterStr) return all;
775
+ return all.filter((w) => matchesWindowTarget(w, filterStr));
776
+ }
777
+ async focusWindow(target) {
778
+ const wins = await this.listWindows(target);
779
+ const win = wins[0];
780
+ if (!win) return { ok: false, err: `No window matching "${target}" found` };
781
+ await this.runPsJson(
782
+ `
783
+ $h = [IntPtr]::new([Convert]::ToInt64("${win.hwnd}", 16))
784
+ if ([Luaward.Win32Desktop]::IsIconic($h)) { [void][Luaward.Win32Desktop]::ShowWindow($h, 9) }
785
+ [void][Luaward.Win32Desktop]::SetForegroundWindow($h)
786
+ @{ ok = $true } | ConvertTo-Json -Compress
787
+ `
788
+ );
789
+ const refreshed = (await this.listWindows(target))[0] ?? win;
790
+ return { ok: true, window: refreshed };
791
+ }
792
+ async resizeWindow(opts) {
793
+ const wins = await this.listWindows(opts.target);
794
+ const win = wins[0];
795
+ if (!win) return { ok: false, err: `No window matching "${opts.target}" found` };
796
+ let outerW = Math.round(opts.width);
797
+ let outerH = Math.round(opts.height);
798
+ if (opts.clientArea !== false && win.clientRect.width > 0 && win.clientRect.height > 0) {
799
+ const borderW = Math.max(0, win.rect.width - win.clientRect.width);
800
+ const borderH = Math.max(0, win.rect.height - win.clientRect.height);
801
+ outerW += borderW;
802
+ outerH += borderH;
803
+ }
804
+ await this.runPsJson(
805
+ `
806
+ $h = [IntPtr]::new([Convert]::ToInt64("${win.hwnd}", 16))
807
+ if ([Luaward.Win32Desktop]::IsIconic($h)) { [void][Luaward.Win32Desktop]::ShowWindow($h, 9) }
808
+ [void][Luaward.Win32Desktop]::MoveWindow($h, ${Math.round(opts.x)}, ${Math.round(opts.y)}, ${outerW}, ${outerH}, $true)
809
+ @{ ok = $true } | ConvertTo-Json -Compress
810
+ `
811
+ );
812
+ const refreshed = (await this.listWindows(opts.target))[0] ?? win;
813
+ return { ok: true, window: refreshed };
814
+ }
815
+ async setWindowState(target, state) {
816
+ const wins = await this.listWindows(target);
817
+ const win = wins[0];
818
+ if (!win) return { ok: false, text: `No window matching "${target}" found` };
819
+ const cmd = state === "minimize" ? 6 : state === "maximize" ? 3 : 9;
820
+ await this.runPsJson(
821
+ `
822
+ $h = [IntPtr]::new([Convert]::ToInt64("${win.hwnd}", 16))
823
+ [void][Luaward.Win32Desktop]::ShowWindow($h, ${cmd})
824
+ @{ ok = $true } | ConvertTo-Json -Compress
825
+ `
826
+ );
827
+ return { ok: true, text: `${state}d window "${win.title}" (${win.hwnd})` };
828
+ }
829
+ async captureScreenshot(opts) {
830
+ const target = (opts.target || "roblox").trim();
831
+ let win;
832
+ if (target.toLowerCase() !== "screen") {
833
+ if (opts.focusFirst) {
834
+ const f = await this.focusWindow(target);
835
+ win = f.window;
836
+ } else {
837
+ win = (await this.listWindows(target))[0];
838
+ }
839
+ if (!win) {
840
+ return { ok: false, mimeType: "image/png", err: `Window "${target}" not found` };
841
+ }
842
+ if (win.isMinimized) {
843
+ return { ok: false, mimeType: "image/png", err: `Window "${win.title}" is minimized` };
844
+ }
845
+ }
846
+ const useClient = opts.clientOnly !== false && win && win.clientRect.width > 10 && win.clientRect.height > 10;
847
+ let capLeft = win ? useClient ? win.clientRect.screenLeft : win.rect.left : 0;
848
+ let capTop = win ? useClient ? win.clientRect.screenTop : win.rect.top : 0;
849
+ let capW = win ? useClient ? win.clientRect.width : win.rect.width : 0;
850
+ let capH = win ? useClient ? win.clientRect.height : win.rect.height : 0;
851
+ if (opts.crop) {
852
+ capLeft += Math.max(0, Math.round(opts.crop.x));
853
+ capTop += Math.max(0, Math.round(opts.crop.y));
854
+ capW = Math.max(10, Math.round(opts.crop.width));
855
+ capH = Math.max(10, Math.round(opts.crop.height));
856
+ }
857
+ const res = await this.runPsJson(`
858
+ $left = ${capLeft}
859
+ $top = ${capTop}
860
+ $w = ${capW}
861
+ $h = ${capH}
862
+ if ($w -le 0 -or $h -le 0) {
863
+ $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
864
+ $left = $bounds.Left
865
+ $top = $bounds.Top
866
+ $w = $bounds.Width
867
+ $h = $bounds.Height
868
+ }
869
+ $bmp = New-Object System.Drawing.Bitmap $w, $h
870
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
871
+ try {
872
+ $g.CopyFromScreen($left, $top, 0, 0, (New-Object System.Drawing.Size($w, $h)))
873
+ $ms = New-Object System.IO.MemoryStream
874
+ $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
875
+ @{
876
+ ok = $true
877
+ width = $w
878
+ height = $h
879
+ data = [Convert]::ToBase64String($ms.ToArray())
880
+ } | ConvertTo-Json -Compress
881
+ } finally {
882
+ $g.Dispose()
883
+ $bmp.Dispose()
884
+ }
885
+ `);
886
+ return {
887
+ ok: res.ok,
888
+ mimeType: "image/png",
889
+ data: res.data,
890
+ width: res.width,
891
+ height: res.height,
892
+ windowRect: win?.rect,
893
+ clientRect: win?.clientRect,
894
+ err: res.err
895
+ };
896
+ }
897
+ async getUiTree(opts) {
898
+ const target = (opts.target || "potassium").trim();
899
+ const wins = await this.listWindows(target);
900
+ const win = wins[0];
901
+ if (!win) return { ok: false, nodes: [], err: `No window matching "${target}" found` };
902
+ const maxDepth = Math.max(1, Math.min(12, Math.floor(opts.maxDepth ?? 5)));
903
+ const maxElements = Math.max(1, Math.min(500, Math.floor(opts.maxElements ?? 150)));
904
+ const interactiveOnly = opts.interactiveOnly !== false;
905
+ const nodes = await this.runPsJson(`
906
+ $h = [IntPtr]::new([Convert]::ToInt64("${win.hwnd}", 16))
907
+ $root = [System.Windows.Automation.AutomationElement]::FromHandle($h)
908
+ $walker = [System.Windows.Automation.TreeWalker]::ControlViewWalker
909
+ $nodes = New-Object System.Collections.Generic.List[object]
910
+ $script:seq = 0
911
+ $interactiveTypes = @("Button", "Edit", "TabItem", "ListItem", "CheckBox", "RadioButton", "ComboBox", "MenuItem", "Hyperlink", "Slider", "Document", "Text", "Window")
912
+
913
+ function Walk-Ui($el, [int]$depth) {
914
+ if ($null -eq $el -or $depth -gt ${maxDepth} -or $nodes.Count -ge ${maxElements}) { return }
915
+ $child = $walker.GetFirstChild($el)
916
+ while ($null -ne $child -and $nodes.Count -lt ${maxElements}) {
917
+ try {
918
+ $cur = $child.Current
919
+ $ct = ($cur.ControlType.ProgrammaticName -replace '^ControlType\\.', '')
920
+ $r = $cur.BoundingRectangle
921
+ $hasBounds = (-not [double]::IsInfinity($r.Width)) -and $r.Width -gt 1 -and $r.Height -gt 1
922
+ $keep = $hasBounds -and ((-not $${interactiveOnly}) -or ($interactiveTypes -contains $ct) -or (-not [string]::IsNullOrWhiteSpace($cur.Name)))
923
+ if ($keep) {
924
+ $script:seq++
925
+ $lx = [int][Math]::Round($r.Left)
926
+ $ly = [int][Math]::Round($r.Top)
927
+ $lw = [int][Math]::Round($r.Width)
928
+ $lh = [int][Math]::Round($r.Height)
929
+ $nodes.Add(@{
930
+ id = $script:seq
931
+ depth = $depth
932
+ controlType = $ct
933
+ name = [string]$cur.Name
934
+ automationId = [string]$cur.AutomationId
935
+ className = [string]$cur.ClassName
936
+ isEnabled = [bool]$cur.IsEnabled
937
+ rect = @{ left = $lx; top = $ly; width = $lw; height = $lh }
938
+ center = @{ x = [int]($lx + $lw / 2); y = [int]($ly + $lh / 2) }
939
+ })
940
+ }
941
+ Walk-Ui $child ($depth + 1)
942
+ } catch {}
943
+ $child = $walker.GetNextSibling($child)
944
+ }
945
+ }
946
+ Walk-Ui $root 1
947
+ ConvertTo-Json -InputObject @($nodes) -Depth 5 -Compress
948
+ `);
949
+ return { ok: true, windowTitle: win.title, nodes };
950
+ }
951
+ async mouse(params) {
952
+ let baseX = 0;
953
+ let baseY = 0;
954
+ if (params.relativeTo === "roblox_client") {
955
+ const rw = (await this.listWindows("roblox"))[0];
956
+ if (!rw) return { ok: false, text: "Roblox window not found for relative_to=roblox_client" };
957
+ baseX = rw.clientRect.screenLeft;
958
+ baseY = rw.clientRect.screenTop;
959
+ } else if (params.relativeTo === "potassium_window") {
960
+ const pw = (await this.listWindows("potassium"))[0];
961
+ if (!pw) return { ok: false, text: "Potassium window not found for relative_to=potassium_window" };
962
+ baseX = pw.rect.left;
963
+ baseY = pw.rect.top;
964
+ }
965
+ const screenX = Math.round((params.x ?? 0) + baseX);
966
+ const screenY = Math.round((params.y ?? 0) + baseY);
967
+ const mode = params.mode ?? (params.action === "camera_rotate" ? "camera" : "ui");
968
+ const steps = Math.max(1, Math.min(100, Math.floor(params.steps ?? 10)));
969
+ const holdMs = Math.max(10, Math.min(2e3, Math.floor(params.holdMs ?? 35)));
970
+ if (mode === "camera" || params.action === "camera_rotate") {
971
+ const totalDx = Math.round(params.dx ?? 0);
972
+ const totalDy = Math.round(params.dy ?? 0);
973
+ await this.runPsJson(`
974
+ $steps = ${steps}
975
+ $remX = ${totalDx}
976
+ $remY = ${totalDy}
977
+ for ($i = 1; $i -le $steps; $i++) {
978
+ $sx = [int][Math]::Round($remX / ($steps - $i + 1))
979
+ $sy = [int][Math]::Round($remY / ($steps - $i + 1))
980
+ [Luaward.Win32Desktop]::SendMouseMoveRel($sx, $sy)
981
+ $remX -= $sx
982
+ $remY -= $sy
983
+ Start-Sleep -Milliseconds 8
984
+ }
985
+ @{ ok = $true } | ConvertTo-Json -Compress
986
+ `);
987
+ return {
988
+ ok: true,
989
+ text: `rotated camera via relative Raw Input (dx=${totalDx}, dy=${totalDy}, steps=${steps})`
990
+ };
991
+ }
992
+ if (params.action === "drag_and_drop") {
993
+ const toX = Math.round((params.toX ?? screenX) + baseX);
994
+ const toY = Math.round((params.toY ?? screenY) + baseY);
995
+ await this.runPsJson(`
996
+ [Luaward.Win32Desktop]::SendMouseMoveAbs(${screenX}, ${screenY})
997
+ Start-Sleep -Milliseconds 15
998
+ [Luaward.Win32Desktop]::SendMouseMoveRel(1, 0)
999
+ Start-Sleep -Milliseconds 15
1000
+ [Luaward.Win32Desktop]::SendMouseButton([Luaward.Win32Desktop]::MOUSEEVENTF_LEFTDOWN, 0)
1001
+ Start-Sleep -Milliseconds 25
1002
+ $steps = ${steps}
1003
+ for ($i = 1; $i -le $steps; $i++) {
1004
+ $cx = [int][Math]::Round(${screenX} + ((${toX} - ${screenX}) * $i) / $steps)
1005
+ $cy = [int][Math]::Round(${screenY} + ((${toY} - ${screenY}) * $i) / $steps)
1006
+ [Luaward.Win32Desktop]::SendMouseMoveAbs($cx, $cy)
1007
+ [Luaward.Win32Desktop]::SendMouseMoveRel(1, 0)
1008
+ Start-Sleep -Milliseconds 12
1009
+ }
1010
+ Start-Sleep -Milliseconds ${holdMs}
1011
+ [Luaward.Win32Desktop]::SendMouseButton([Luaward.Win32Desktop]::MOUSEEVENTF_LEFTUP, 0)
1012
+ @{ ok = $true } | ConvertTo-Json -Compress
1013
+ `);
1014
+ return {
1015
+ ok: true,
1016
+ screenX: toX,
1017
+ screenY: toY,
1018
+ text: `dragged from (${screenX}, ${screenY}) to (${toX}, ${toY})`
1019
+ };
1020
+ }
1021
+ if (params.action === "scroll") {
1022
+ const delta = Math.round(params.scrollDelta ?? -120);
1023
+ await this.runPsJson(`
1024
+ if (${params.x !== void 0 ? "$true" : "$false"}) {
1025
+ [Luaward.Win32Desktop]::SendMouseMoveAbs(${screenX}, ${screenY})
1026
+ Start-Sleep -Milliseconds 10
1027
+ }
1028
+ $uDelta = [BitConverter]::ToUInt32([BitConverter]::GetBytes([int]${delta}), 0)
1029
+ [Luaward.Win32Desktop]::SendMouseButton([Luaward.Win32Desktop]::MOUSEEVENTF_WHEEL, $uDelta)
1030
+ @{ ok = $true } | ConvertTo-Json -Compress
1031
+ `);
1032
+ return { ok: true, screenX, screenY, text: `scrolled wheel delta=${delta}` };
1033
+ }
1034
+ if (params.action === "move") {
1035
+ await this.runPsJson(`
1036
+ [Luaward.Win32Desktop]::SendMouseMoveAbs(${screenX}, ${screenY})
1037
+ Start-Sleep -Milliseconds 12
1038
+ [Luaward.Win32Desktop]::SendMouseMoveRel(1, 0)
1039
+ @{ ok = $true } | ConvertTo-Json -Compress
1040
+ `);
1041
+ return {
1042
+ ok: true,
1043
+ screenX,
1044
+ screenY,
1045
+ text: `moved cursor to (${screenX}, ${screenY}) with Roblox hover wake`
1046
+ };
1047
+ }
1048
+ const downFlag = params.action === "right_click" ? "MOUSEEVENTF_RIGHTDOWN" : params.action === "middle_click" ? "MOUSEEVENTF_MIDDLEDOWN" : "MOUSEEVENTF_LEFTDOWN";
1049
+ const upFlag = params.action === "right_click" ? "MOUSEEVENTF_RIGHTUP" : params.action === "middle_click" ? "MOUSEEVENTF_MIDDLEUP" : "MOUSEEVENTF_LEFTUP";
1050
+ const clicks = params.action === "double_click" ? 2 : 1;
1051
+ await this.runPsJson(`
1052
+ [Luaward.Win32Desktop]::SendMouseMoveAbs(${screenX}, ${screenY})
1053
+ Start-Sleep -Milliseconds 15
1054
+ [Luaward.Win32Desktop]::SendMouseMoveRel(1, 0)
1055
+ Start-Sleep -Milliseconds 15
1056
+ for ($c = 1; $c -le ${clicks}; $c++) {
1057
+ [Luaward.Win32Desktop]::SendMouseButton([Luaward.Win32Desktop]::${downFlag}, 0)
1058
+ Start-Sleep -Milliseconds ${holdMs}
1059
+ [Luaward.Win32Desktop]::SendMouseButton([Luaward.Win32Desktop]::${upFlag}, 0)
1060
+ if ($c -lt ${clicks}) { Start-Sleep -Milliseconds 40 }
1061
+ }
1062
+ @{ ok = $true } | ConvertTo-Json -Compress
1063
+ `);
1064
+ return {
1065
+ ok: true,
1066
+ screenX,
1067
+ screenY,
1068
+ text: `performed ${params.action} at screen (${screenX}, ${screenY}) [mode=ui, hover_wake=dx+1]`
1069
+ };
1070
+ }
1071
+ async keyboard(params) {
1072
+ if (params.target) {
1073
+ await this.focusWindow(params.target);
1074
+ }
1075
+ const holdMs = Math.max(15, Math.min(5e3, Math.floor(params.holdMs ?? 50)));
1076
+ if (params.action === "type") {
1077
+ const text = String(params.text ?? "");
1078
+ const b64 = Buffer.from(text, "utf8").toString("base64");
1079
+ await this.runPsJson(`
1080
+ $str = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("${b64}"))
1081
+ [Luaward.Win32Desktop]::SendUnicodeString($str)
1082
+ @{ ok = $true } | ConvertTo-Json -Compress
1083
+ `);
1084
+ return { ok: true, text: `typed ${text.length} characters via Win32 Unicode SendInput` };
1085
+ }
1086
+ if (params.action === "hotkey") {
1087
+ const keys = Array.isArray(params.keys) && params.keys.length > 0 ? params.keys : [];
1088
+ if (keys.length === 0) throw new Error("keys array is required for action=hotkey");
1089
+ const vks = keys.map((k) => resolveVirtualKeyCode(k));
1090
+ const downCalls = vks.map((vk2) => `[Luaward.Win32Desktop]::SendKeyVk(${vk2}, $false); Start-Sleep -Milliseconds 15`).join("\n");
1091
+ const upCalls = [...vks].reverse().map((vk2) => `[Luaward.Win32Desktop]::SendKeyVk(${vk2}, $true); Start-Sleep -Milliseconds 15`).join("\n");
1092
+ await this.runPsJson(
1093
+ `${downCalls}
1094
+ Start-Sleep -Milliseconds ${holdMs}
1095
+ ${upCalls}
1096
+ @{ ok = $true } | ConvertTo-Json -Compress`
1097
+ );
1098
+ return { ok: true, text: `pressed hotkey ${keys.join("+")} via ScanCode SendInput` };
1099
+ }
1100
+ const vk = resolveVirtualKeyCode(String(params.key ?? ""));
1101
+ if (params.action === "key_down") {
1102
+ await this.runPsJson(
1103
+ `[Luaward.Win32Desktop]::SendKeyVk(${vk}, $false)
1104
+ @{ ok = $true } | ConvertTo-Json -Compress`
1105
+ );
1106
+ return { ok: true, text: `held key_down ${params.key} (vk=0x${vk.toString(16)})` };
1107
+ }
1108
+ if (params.action === "key_up") {
1109
+ await this.runPsJson(
1110
+ `[Luaward.Win32Desktop]::SendKeyVk(${vk}, $true)
1111
+ @{ ok = $true } | ConvertTo-Json -Compress`
1112
+ );
1113
+ return { ok: true, text: `released key_up ${params.key} (vk=0x${vk.toString(16)})` };
1114
+ }
1115
+ await this.runPsJson(`
1116
+ [Luaward.Win32Desktop]::SendKeyVk(${vk}, $false)
1117
+ Start-Sleep -Milliseconds ${holdMs}
1118
+ [Luaward.Win32Desktop]::SendKeyVk(${vk}, $true)
1119
+ @{ ok = $true } | ConvertTo-Json -Compress
1120
+ `);
1121
+ return { ok: true, text: `pressed key ${params.key} for ${holdMs}ms via ScanCode SendInput` };
1122
+ }
1123
+ async launchRoblox(params) {
1124
+ const deepLink = buildRobloxDeepLink(params);
1125
+ const bin = params.binaryPath || (params.directBinary ? findRobloxPlayerBinary() : null);
1126
+ if (bin && existsSync2(bin)) {
1127
+ const b64Bin = Buffer.from(bin, "utf8").toString("base64");
1128
+ const b64Link2 = Buffer.from(deepLink, "utf8").toString("base64");
1129
+ const res = await this.runPsJson(`
1130
+ $exe = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("${b64Bin}"))
1131
+ $link = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("${b64Link2}"))
1132
+ $p = Start-Process -FilePath $exe -ArgumentList @("--app", "--deeplink", $link) -PassThru
1133
+ @{ ok = $true; pid = [int]$p.Id } | ConvertTo-Json -Compress
1134
+ `);
1135
+ return {
1136
+ ok: true,
1137
+ deepLink,
1138
+ method: "binary",
1139
+ binaryPath: bin,
1140
+ pid: res.pid,
1141
+ text: `launched RobloxPlayerBeta.exe (PID ${res.pid ?? "?"}) with ${deepLink}`
1142
+ };
1143
+ }
1144
+ const b64Link = Buffer.from(deepLink, "utf8").toString("base64");
1145
+ await this.runPsJson(`
1146
+ $link = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("${b64Link}"))
1147
+ Start-Process -FilePath $link
1148
+ @{ ok = $true } | ConvertTo-Json -Compress
1149
+ `);
1150
+ return {
1151
+ ok: true,
1152
+ deepLink,
1153
+ method: "deeplink",
1154
+ text: `launched Roblox via protocol handler: ${deepLink}`
1155
+ };
1156
+ }
1157
+ async launchPotassium(executablePath) {
1158
+ const exe = findPotassiumBinary(executablePath);
1159
+ if (!exe) {
1160
+ return {
1161
+ ok: false,
1162
+ text: "Could not locate Potassium.exe automatically. Pass potassium_path or set POTASSIUM_PATH."
1163
+ };
1164
+ }
1165
+ const b64Exe = Buffer.from(exe, "utf8").toString("base64");
1166
+ const res = await this.runPsJson(`
1167
+ $exe = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("${b64Exe}"))
1168
+ $p = Start-Process -FilePath $exe -WorkingDirectory ([System.IO.Path]::GetDirectoryName($exe)) -PassThru
1169
+ @{ ok = $true; pid = [int]$p.Id } | ConvertTo-Json -Compress
1170
+ `);
1171
+ return {
1172
+ ok: true,
1173
+ path: exe,
1174
+ pid: res.pid,
1175
+ text: `launched Potassium.exe (PID ${res.pid ?? "?"}) from ${exe}`
1176
+ };
1177
+ }
1178
+ async killProcess(processName) {
1179
+ const clean = processName.replace(/\.exe$/i, "").replace(/[^A-Za-z0-9_-]/g, "");
1180
+ const res = await this.runPsJson(`
1181
+ $procs = @(Get-Process -Name "${clean}" -ErrorAction SilentlyContinue)
1182
+ $cnt = $procs.Count
1183
+ if ($cnt -gt 0) {
1184
+ $procs | Stop-Process -Force -ErrorAction SilentlyContinue
1185
+ }
1186
+ @{ ok = $true; count = [int]$cnt } | ConvertTo-Json -Compress
1187
+ `);
1188
+ return {
1189
+ ok: true,
1190
+ killedCount: res.count,
1191
+ text: `terminated ${res.count} process(es) named ${clean}`
1192
+ };
1193
+ }
1194
+ };
1195
+ function matchesWindowTarget(w, filter) {
1196
+ const f = filter.trim().toLowerCase();
1197
+ if (!f || f === "all") return true;
1198
+ if (f === "roblox") {
1199
+ return w.processName.toLowerCase().includes("roblox") || w.title.toLowerCase() === "roblox" || w.className.toLowerCase().includes("windowsclient");
1200
+ }
1201
+ if (f === "potassium") {
1202
+ return w.processName.toLowerCase().includes("potassium") || w.title.toLowerCase().includes("potassium");
1203
+ }
1204
+ if (w.hwnd.toLowerCase() === f || String(w.pid) === f) return true;
1205
+ return w.title.toLowerCase().includes(f) || w.processName.toLowerCase().includes(f);
1206
+ }
1207
+
1208
+ // src/index.ts
1209
+ var MCP_BRIDGE_VERSION = "0.2.0";
7
1210
  var DEFAULT_MCP_URL = "https://luaward.com/mcp";
8
1211
  var TOKEN_SHAPE = /^lwm_[0-9a-f]{48}$/;
9
1212
  function resolveStoredToken(configDir) {
10
- const base = configDir || process.env.LUAWARD_CONFIG_DIR || join(homedir(), ".config", "luaward");
11
- const credPath = join(base, "credentials.json");
12
- if (!existsSync(credPath)) return {};
1213
+ const base = configDir || process.env.LUAWARD_CONFIG_DIR || join3(homedir3(), ".config", "luaward");
1214
+ const credPath = join3(base, "credentials.json");
1215
+ if (!existsSync3(credPath)) return {};
13
1216
  try {
14
- const raw = JSON.parse(readFileSync(credPath, "utf8"));
1217
+ const raw = JSON.parse(readFileSync2(credPath, "utf8"));
15
1218
  const token = typeof raw.token === "string" && TOKEN_SHAPE.test(raw.token.trim()) ? raw.token.trim() : void 0;
16
1219
  const apiUrl = typeof raw.apiUrl === "string" ? raw.apiUrl.trim().replace(/\/+$/, "") : void 0;
17
1220
  return { token, apiUrl };
@@ -22,6 +1225,10 @@ function resolveStoredToken(configDir) {
22
1225
  function resolveBridgeConfig(args = [], env = process.env, configDir) {
23
1226
  let flagToken;
24
1227
  let flagUrl;
1228
+ let flagPotassiumUrl;
1229
+ let flagPotassiumToken;
1230
+ let flagPairCommand;
1231
+ let autoInject = env.LUAWARD_AUTO_INJECT !== "0" && env.LUAWARD_AUTO_INJECT !== "false";
25
1232
  let showHelp = false;
26
1233
  let showVersion = false;
27
1234
  for (let i = 0; i < args.length; i++) {
@@ -30,6 +1237,8 @@ function resolveBridgeConfig(args = [], env = process.env, configDir) {
30
1237
  showHelp = true;
31
1238
  } else if (a === "--version" || a === "-v") {
32
1239
  showVersion = true;
1240
+ } else if (a === "--no-auto-inject") {
1241
+ autoInject = false;
33
1242
  } else if (a === "--token" && args[i + 1]) {
34
1243
  flagToken = args[++i];
35
1244
  } else if (a?.startsWith("--token=")) {
@@ -38,6 +1247,18 @@ function resolveBridgeConfig(args = [], env = process.env, configDir) {
38
1247
  flagUrl = args[++i];
39
1248
  } else if (a?.startsWith("--url=")) {
40
1249
  flagUrl = a.slice("--url=".length);
1250
+ } else if (a === "--potassium-url" && args[i + 1]) {
1251
+ flagPotassiumUrl = args[++i];
1252
+ } else if (a?.startsWith("--potassium-url=")) {
1253
+ flagPotassiumUrl = a.slice("--potassium-url=".length);
1254
+ } else if (a === "--potassium-token" && args[i + 1]) {
1255
+ flagPotassiumToken = args[++i];
1256
+ } else if (a?.startsWith("--potassium-token=")) {
1257
+ flagPotassiumToken = a.slice("--potassium-token=".length);
1258
+ } else if (a === "--pair-command" && args[i + 1]) {
1259
+ flagPairCommand = args[++i];
1260
+ } else if (a?.startsWith("--pair-command=")) {
1261
+ flagPairCommand = a.slice("--pair-command=".length);
41
1262
  }
42
1263
  }
43
1264
  const stored = resolveStoredToken(configDir || env.LUAWARD_CONFIG_DIR);
@@ -48,13 +1269,25 @@ function resolveBridgeConfig(args = [], env = process.env, configDir) {
48
1269
  const baseApi = (env.LUAWARD_API_URL || stored.apiUrl || "").trim().replace(/\/+$/, "");
49
1270
  url = baseApi ? `${baseApi}/mcp` : DEFAULT_MCP_URL;
50
1271
  }
51
- return { token, url, showHelp, showVersion };
1272
+ const potassiumUrl = (flagPotassiumUrl || env.POTASSIUM_MCP_URL || DEFAULT_POTASSIUM_URL).trim();
1273
+ const potassiumToken = flagPotassiumToken !== void 0 ? flagPotassiumToken : discoverPotassiumToken(env);
1274
+ const pairCommand = (flagPairCommand || env.LUAWARD_PAIR_COMMAND || "").trim() || void 0;
1275
+ return {
1276
+ token,
1277
+ url,
1278
+ potassiumUrl,
1279
+ potassiumToken,
1280
+ pairCommand,
1281
+ autoInject,
1282
+ showHelp,
1283
+ showVersion
1284
+ };
52
1285
  }
53
1286
  function extractRequestId(parsed) {
54
1287
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && "id" in parsed) {
55
1288
  const idVal = parsed.id;
56
- if (typeof idVal === "string" || typeof idVal === "number" || idVal === null) {
57
- return { hasId: true, id: idVal };
1289
+ if (typeof idVal === "string" || typeof idVal === "number" || typeof idVal === "object") {
1290
+ return { hasId: true, id: idVal ?? null };
58
1291
  }
59
1292
  }
60
1293
  return { hasId: false, id: null };
@@ -68,102 +1301,1234 @@ function extractProtocolVersion(parsed) {
68
1301
  }
69
1302
  return void 0;
70
1303
  }
71
- async function forwardJsonRpcLine(line, options) {
72
- const trimmed = line.trim();
73
- if (!trimmed) return null;
74
- let parsed;
75
- try {
76
- parsed = JSON.parse(trimmed);
77
- } catch {
78
- return JSON.stringify({
1304
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1305
+ var LOCAL_HYBRID_TOOLS = [
1306
+ {
1307
+ name: "editor_tabs",
1308
+ title: "Potassium local editor tabs & cloud sync",
1309
+ description: "Manage tabs in the local Potassium executor (127.0.0.1:8225/mcp) and bridge them with Luaward Cloud. Actions: list, read, open, write, activate, close, run_tab (reads tab code and runs it via Luaward exec with full return/console capture), sync_tab_to_cloud (deploys tab code to Luaward Cloud via deploy_script), open_cloud_script_in_tab (pulls decrypted script source from Luaward Cloud into a Potassium tab), and install_autoexec (writes AUTO EXECUTE/luaward_init.luau for zero-touch auto-connect). Reuses 'luaward_scratch.luau' by default because Potassium refuses to close dirty:true tabs.",
1310
+ inputSchema: {
1311
+ type: "object",
1312
+ properties: {
1313
+ action: {
1314
+ type: "string",
1315
+ enum: [
1316
+ "list",
1317
+ "read",
1318
+ "open",
1319
+ "write",
1320
+ "activate",
1321
+ "close",
1322
+ "run_tab",
1323
+ "sync_tab_to_cloud",
1324
+ "open_cloud_script_in_tab",
1325
+ "install_autoexec"
1326
+ ],
1327
+ description: "Operation to perform"
1328
+ },
1329
+ tab_id: {
1330
+ type: "string",
1331
+ description: "Tab ID from list (optional for read/write/run_tab; defaults to active or scratch tab)"
1332
+ },
1333
+ name: {
1334
+ type: "string",
1335
+ description: `Tab title for open/write (defaults to "${SCRATCH_TAB_NAME}")`
1336
+ },
1337
+ content: {
1338
+ type: "string",
1339
+ description: "Luau source code to write into the tab"
1340
+ },
1341
+ file_path: {
1342
+ type: "string",
1343
+ description: "Optional local file path (.luau/.lua) to load content from for open/write"
1344
+ },
1345
+ reuse_scratch: {
1346
+ type: "boolean",
1347
+ description: "Reuse existing tab with matching name or luaward_scratch.luau to avoid unclosable dirty tabs (default true)"
1348
+ },
1349
+ script: {
1350
+ type: "string",
1351
+ description: "Luaward Cloud script name or ID (for sync_tab_to_cloud / open_cloud_script_in_tab)"
1352
+ },
1353
+ publish: {
1354
+ type: "boolean",
1355
+ description: "For sync_tab_to_cloud: promote build to live automatically (default true; false for draft)"
1356
+ },
1357
+ preset: {
1358
+ type: "string",
1359
+ enum: ["fast", "balanced", "max"],
1360
+ description: "Optional protection preset for sync_tab_to_cloud"
1361
+ },
1362
+ readonly: {
1363
+ type: "boolean",
1364
+ description: "For run_tab: run in readonly mode"
1365
+ },
1366
+ guard: {
1367
+ type: "boolean",
1368
+ description: "For run_tab: block FireServer/InvokeServer/teleport/kick"
1369
+ },
1370
+ session: {
1371
+ type: "string",
1372
+ description: "Optional Luaward game session selector for run_tab"
1373
+ },
1374
+ autoexec_dir: {
1375
+ type: "string",
1376
+ description: "Optional custom Potassium autoexec folder path for install_autoexec"
1377
+ }
1378
+ },
1379
+ required: ["action"],
1380
+ additionalProperties: false
1381
+ },
1382
+ annotations: {
1383
+ title: "Potassium local editor tabs & cloud sync",
1384
+ readOnlyHint: false,
1385
+ destructiveHint: false,
1386
+ idempotentHint: false,
1387
+ openWorldHint: false
1388
+ }
1389
+ },
1390
+ {
1391
+ name: "desktop_launch",
1392
+ title: "Launch & recover Roblox and Potassium on Windows",
1393
+ description: "Control the Windows OS lifecycle of RobloxPlayerBeta.exe and Potassium.exe. Actions: status (checks processes, windows, and port 8225), launch_potassium, launch_roblox (via roblox://experiences/start?placeId=...&gameInstanceId=... deep link or direct RobloxPlayerBeta.exe binary), rejoin (crash/hang recovery: kills stale RobloxPlayerBeta.exe and rejoins the last or specified place_id/job_id, then auto-injects Luaward agent), and kill_roblox.",
1394
+ inputSchema: {
1395
+ type: "object",
1396
+ properties: {
1397
+ action: {
1398
+ type: "string",
1399
+ enum: ["status", "launch_potassium", "launch_roblox", "rejoin", "kill_roblox"],
1400
+ description: "Lifecycle action"
1401
+ },
1402
+ place_id: {
1403
+ type: "string",
1404
+ description: "Roblox PlaceId to launch or rejoin"
1405
+ },
1406
+ job_id: {
1407
+ type: "string",
1408
+ description: "Optional Roblox server JobId (gameInstanceId)"
1409
+ },
1410
+ access_code: {
1411
+ type: "string",
1412
+ description: "Optional private server accessCode"
1413
+ },
1414
+ launch_data: {
1415
+ type: "string",
1416
+ description: "Optional launchData string"
1417
+ },
1418
+ direct_binary: {
1419
+ type: "boolean",
1420
+ description: 'Launch "%LOCALAPPDATA%\\Roblox\\Versions\\<version>\\RobloxPlayerBeta.exe" --app --deeplink directly'
1421
+ },
1422
+ potassium_path: {
1423
+ type: "string",
1424
+ description: "Optional explicit path to Potassium.exe"
1425
+ },
1426
+ auto_inject: {
1427
+ type: "boolean",
1428
+ description: "Auto-inject Luaward agent via Potassium once client attaches (default true)"
1429
+ }
1430
+ },
1431
+ required: ["action"],
1432
+ additionalProperties: false
1433
+ },
1434
+ annotations: {
1435
+ title: "Launch & recover Roblox and Potassium on Windows",
1436
+ readOnlyHint: false,
1437
+ destructiveHint: true,
1438
+ idempotentHint: false,
1439
+ openWorldHint: false
1440
+ }
1441
+ },
1442
+ {
1443
+ name: "desktop_window",
1444
+ title: "Manage Windows desktop windows (list, focus, resize 1280x720)",
1445
+ description: "List, focus (SetForegroundWindow), resize (MoveWindow, e.g. locking Roblox client area to 1280x720 for deterministic UI clicking), minimize, maximize, or restore Windows desktop windows.",
1446
+ inputSchema: {
1447
+ type: "object",
1448
+ properties: {
1449
+ action: {
1450
+ type: "string",
1451
+ enum: ["list", "focus", "resize", "minimize", "maximize", "restore"],
1452
+ description: "Window action"
1453
+ },
1454
+ target: {
1455
+ type: "string",
1456
+ description: 'Target window: "roblox" (default), "potassium", window title substring, PID, or HWND'
1457
+ },
1458
+ x: { type: "integer", description: "Window top-left X coordinate for resize (default 80)" },
1459
+ y: { type: "integer", description: "Window top-left Y coordinate for resize (default 80)" },
1460
+ width: { type: "integer", description: "Target width in pixels for resize (default 1280)" },
1461
+ height: { type: "integer", description: "Target height in pixels for resize (default 720)" },
1462
+ client_area: {
1463
+ type: "boolean",
1464
+ description: "Size the inner client viewport to exact width x height (default true)"
1465
+ }
1466
+ },
1467
+ required: ["action"],
1468
+ additionalProperties: false
1469
+ },
1470
+ annotations: {
1471
+ title: "Manage Windows desktop windows",
1472
+ readOnlyHint: false,
1473
+ destructiveHint: false,
1474
+ idempotentHint: true,
1475
+ openWorldHint: false
1476
+ }
1477
+ },
1478
+ {
1479
+ name: "desktop_screenshot",
1480
+ title: "Capture OS window or full-screen PNG screenshot",
1481
+ description: "Capture a live PNG screenshot directly from Windows OS (Roblox client area, Potassium window, or full screen) without running capture.ps1 separately. Shows CoreGui, gethui(), and Drawing/DrawingImmediate overlays invisible to in-game gui_snapshot.",
1482
+ inputSchema: {
1483
+ type: "object",
1484
+ properties: {
1485
+ target: {
1486
+ type: "string",
1487
+ description: '"roblox" (default), "potassium", "screen", or window title substring'
1488
+ },
1489
+ focus_first: {
1490
+ type: "boolean",
1491
+ description: "Bring the window to foreground before capturing (default false)"
1492
+ },
1493
+ client_only: {
1494
+ type: "boolean",
1495
+ description: "Capture only the inner client viewport excluding window title bar/borders (default true)"
1496
+ }
1497
+ },
1498
+ additionalProperties: false
1499
+ },
1500
+ annotations: {
1501
+ title: "Capture OS window or full-screen PNG screenshot",
1502
+ readOnlyHint: true,
1503
+ destructiveHint: false,
1504
+ idempotentHint: true,
1505
+ openWorldHint: false
1506
+ }
1507
+ },
1508
+ {
1509
+ name: "desktop_ui_tree",
1510
+ title: "Inspect Windows UI Automation control tree",
1511
+ description: "Extract buttons, inputs, tabs, list items, and screen bounding coordinates from a Windows desktop application (such as Potassium or Roblox Launcher) via Windows UI Automation (System.Windows.Automation).",
1512
+ inputSchema: {
1513
+ type: "object",
1514
+ properties: {
1515
+ target: {
1516
+ type: "string",
1517
+ description: '"potassium" (default), "roblox", or window title substring'
1518
+ },
1519
+ max_depth: {
1520
+ type: "integer",
1521
+ minimum: 1,
1522
+ maximum: 12,
1523
+ description: "Maximum UI Automation tree depth (default 5)"
1524
+ },
1525
+ max_elements: {
1526
+ type: "integer",
1527
+ minimum: 1,
1528
+ maximum: 500,
1529
+ description: "Maximum elements to return (default 150)"
1530
+ },
1531
+ interactive_only: {
1532
+ type: "boolean",
1533
+ description: "Only include interactive controls and named elements (default true)"
1534
+ }
1535
+ },
1536
+ additionalProperties: false
1537
+ },
1538
+ annotations: {
1539
+ title: "Inspect Windows UI Automation control tree",
1540
+ readOnlyHint: true,
1541
+ destructiveHint: false,
1542
+ idempotentHint: true,
1543
+ openWorldHint: false
1544
+ }
1545
+ },
1546
+ {
1547
+ name: "desktop_mouse",
1548
+ title: "Win32 OS mouse control (Roblox UI hover-wake & Raw Input 3D camera)",
1549
+ description: "Control the Windows mouse via Win32 SendInput tailored for Roblox. In mode='ui' (Cursor Unlocked), moves to (x, y) via SetCursorPos + MOUSEEVENTF_ABSOLUTE, sends a 1px relative MOUSEEVENTF_MOVE (dx=1, dy=0) to trigger Roblox GuiObject MouseEnter/MouseMovement, then clicks. In mode='camera' (or action='camera_rotate', Cursor Locked / Shift-Lock / First-Person), sends pure relative MOUSEEVENTF_MOVE (dx, dy) for Windows Raw Input (WM_INPUT) camera rotation.",
1550
+ inputSchema: {
1551
+ type: "object",
1552
+ properties: {
1553
+ action: {
1554
+ type: "string",
1555
+ enum: [
1556
+ "click",
1557
+ "double_click",
1558
+ "right_click",
1559
+ "middle_click",
1560
+ "move",
1561
+ "camera_rotate",
1562
+ "drag_and_drop",
1563
+ "scroll"
1564
+ ],
1565
+ description: "Mouse operation"
1566
+ },
1567
+ mode: {
1568
+ type: "string",
1569
+ enum: ["ui", "camera"],
1570
+ description: '"ui" (Cursor Unlocked with dx=1 hover wake) or "camera" (Cursor Locked pure relative WM_INPUT)'
1571
+ },
1572
+ x: { type: "integer", description: "Target X coordinate" },
1573
+ y: { type: "integer", description: "Target Y coordinate" },
1574
+ dx: { type: "integer", description: "Relative horizontal pixels for camera_rotate / mode='camera'" },
1575
+ dy: { type: "integer", description: "Relative vertical pixels for camera_rotate / mode='camera'" },
1576
+ to_x: { type: "integer", description: "Destination X for drag_and_drop" },
1577
+ to_y: { type: "integer", description: "Destination Y for drag_and_drop" },
1578
+ scroll_delta: { type: "integer", description: "Mouse wheel delta for scroll (e.g. -120 or 120)" },
1579
+ steps: { type: "integer", minimum: 1, maximum: 100, description: "Interpolation steps (default 10)" },
1580
+ hold_ms: {
1581
+ type: "integer",
1582
+ minimum: 10,
1583
+ maximum: 2e3,
1584
+ description: "Button hold duration in ms (default 35)"
1585
+ },
1586
+ relative_to: {
1587
+ type: "string",
1588
+ enum: ["screen", "roblox_client", "potassium_window"],
1589
+ description: "Coordinate origin (default 'screen')"
1590
+ }
1591
+ },
1592
+ required: ["action"],
1593
+ additionalProperties: false
1594
+ },
1595
+ annotations: {
1596
+ title: "Win32 OS mouse control",
1597
+ readOnlyHint: false,
1598
+ destructiveHint: true,
1599
+ idempotentHint: false,
1600
+ openWorldHint: false
1601
+ }
1602
+ },
1603
+ {
1604
+ name: "desktop_keyboard",
1605
+ title: "Win32 OS keyboard control (ScanCode & Unicode SendInput)",
1606
+ description: "Send keyboard input via Win32 SendInput. Uses hardware ScanCodes (KEYEVENTF_SCANCODE) for press, key_down, key_up, and hotkey so Roblox DirectInput/RawInput registers movement and keybinds, and KEYEVENTF_UNICODE for typing arbitrary text.",
1607
+ inputSchema: {
1608
+ type: "object",
1609
+ properties: {
1610
+ action: {
1611
+ type: "string",
1612
+ enum: ["type", "press", "key_down", "key_up", "hotkey"],
1613
+ description: "Keyboard action"
1614
+ },
1615
+ text: { type: "string", description: "Text to type when action='type'" },
1616
+ key: {
1617
+ type: "string",
1618
+ description: "Key name for press/key_down/key_up (e.g. W, A, S, D, E, Space, Return, Escape, LeftShift, F9)"
1619
+ },
1620
+ keys: {
1621
+ type: "array",
1622
+ items: { type: "string" },
1623
+ description: 'Key chord for hotkey, e.g. ["Ctrl", "S"]'
1624
+ },
1625
+ hold_ms: {
1626
+ type: "integer",
1627
+ minimum: 15,
1628
+ maximum: 5e3,
1629
+ description: "Hold duration in ms for press (default 50)"
1630
+ },
1631
+ target: {
1632
+ type: "string",
1633
+ description: 'Optional window to focus before sending keys ("roblox" or "potassium")'
1634
+ }
1635
+ },
1636
+ required: ["action"],
1637
+ additionalProperties: false
1638
+ },
1639
+ annotations: {
1640
+ title: "Win32 OS keyboard control",
1641
+ readOnlyHint: false,
1642
+ destructiveHint: true,
1643
+ idempotentHint: false,
1644
+ openWorldHint: false
1645
+ }
1646
+ },
1647
+ {
1648
+ name: "os_click",
1649
+ title: "Hybrid In-Game #n GUI handle + OS Win32 Mouse Click",
1650
+ description: "Resolve a GuiObject's live position in the connected Roblox game (by #n handle from gui_snapshot or full Instance path), combine it with GuiService:GetGuiInset() and the Windows Roblox client rect (GetClientRect + ClientToScreen), and click its exact screen center using a real OS-level Win32 mouse input (SetCursorPos + dx=1 hover wake + MOUSEEVENTF_LEFTDOWN/UP).",
1651
+ inputSchema: {
1652
+ type: "object",
1653
+ properties: {
1654
+ target: {
1655
+ type: "string",
1656
+ description: 'Target GuiObject: "#3" from gui_snapshot or full path like "Players.LocalPlayer.PlayerGui.HUD.Shop.Buy"'
1657
+ },
1658
+ button: {
1659
+ type: "string",
1660
+ enum: ["left", "right"],
1661
+ description: "Mouse button (default 'left')"
1662
+ },
1663
+ double_click: {
1664
+ type: "boolean",
1665
+ description: "Double-click the target (default false)"
1666
+ },
1667
+ offset_x: {
1668
+ type: "integer",
1669
+ description: "Optional horizontal pixel offset from element center (default 0)"
1670
+ },
1671
+ offset_y: {
1672
+ type: "integer",
1673
+ description: "Optional vertical pixel offset from element center (default 0)"
1674
+ },
1675
+ session: {
1676
+ type: "string",
1677
+ description: "Optional Luaward game session selector"
1678
+ }
1679
+ },
1680
+ required: ["target"],
1681
+ additionalProperties: false
1682
+ },
1683
+ annotations: {
1684
+ title: "Hybrid In-Game #n + OS Win32 Click",
1685
+ readOnlyHint: false,
1686
+ destructiveHint: true,
1687
+ idempotentHint: false,
1688
+ openWorldHint: false
1689
+ }
1690
+ }
1691
+ ];
1692
+ var HybridMcpBridge = class {
1693
+ token;
1694
+ url;
1695
+ potassium;
1696
+ windows;
1697
+ autoInject;
1698
+ autoInjectPollMs;
1699
+ autoInjectMaxPolls;
1700
+ fetchFn;
1701
+ cachedPairCommand;
1702
+ lastLaunchParams;
1703
+ rpcSeq = 5e3;
1704
+ constructor(options = {}) {
1705
+ const resolved = resolveBridgeConfig([], process.env, options.configDir);
1706
+ this.token = options.token !== void 0 ? options.token || null : resolved.token;
1707
+ this.url = options.url ?? resolved.url;
1708
+ this.fetchFn = options.fetchImpl ?? fetch;
1709
+ this.cachedPairCommand = options.pairCommand ?? resolved.pairCommand;
1710
+ this.autoInject = options.autoInject ?? resolved.autoInject;
1711
+ this.autoInjectPollMs = options.autoInjectPollMs ?? 400;
1712
+ this.autoInjectMaxPolls = options.autoInjectMaxPolls ?? 15;
1713
+ this.potassium = options.potassiumClient ?? new PotassiumClient({
1714
+ url: options.potassiumUrl ?? resolved.potassiumUrl,
1715
+ token: options.potassiumToken !== void 0 ? options.potassiumToken : resolved.potassiumToken,
1716
+ fetchImpl: this.fetchFn
1717
+ });
1718
+ this.windows = options.windowsDriver ?? new PowerShellWindowsDriver();
1719
+ }
1720
+ cloudHeaders(protoVer) {
1721
+ const headers = {
1722
+ "content-type": "application/json",
1723
+ accept: "application/json",
1724
+ authorization: `Bearer ${this.token}`,
1725
+ "user-agent": `@luaward/mcp/${MCP_BRIDGE_VERSION}`
1726
+ };
1727
+ if (protoVer) headers["mcp-protocol-version"] = protoVer;
1728
+ return headers;
1729
+ }
1730
+ async callCloudRpc(payload, protoVer) {
1731
+ const res = await this.fetchFn(this.url, {
1732
+ method: "POST",
1733
+ headers: this.cloudHeaders(protoVer),
1734
+ body: JSON.stringify(payload)
1735
+ });
1736
+ if (res.status === 202 || res.status === 204) {
1737
+ return { status: res.status, ok: true, body: null, rawText: "" };
1738
+ }
1739
+ const rawText = await res.text();
1740
+ let body = null;
1741
+ if (rawText.trim()) {
1742
+ try {
1743
+ body = JSON.parse(rawText);
1744
+ } catch {
1745
+ body = null;
1746
+ }
1747
+ }
1748
+ return { status: res.status, ok: res.ok, body, rawText };
1749
+ }
1750
+ async callCloudTool(name, args = {}) {
1751
+ const res = await this.callCloudRpc({
79
1752
  jsonrpc: "2.0",
80
- id: null,
81
- error: { code: -32700, message: "Parse error: invalid JSON on stdin" }
1753
+ id: ++this.rpcSeq,
1754
+ method: "tools/call",
1755
+ params: { name, arguments: args }
82
1756
  });
1757
+ if (!res.ok || !res.body) {
1758
+ return { ok: false, text: `Cloud tool "${name}" failed (HTTP ${res.status})`, isError: true };
1759
+ }
1760
+ if (res.body.error && typeof res.body.error === "object") {
1761
+ const err = res.body.error;
1762
+ return { ok: false, text: err.message ?? "Cloud RPC error", isError: true };
1763
+ }
1764
+ const result = res.body.result;
1765
+ const text = result?.content?.find((c) => c.type === "text")?.text ?? "";
1766
+ return {
1767
+ ok: !result?.isError,
1768
+ text,
1769
+ isError: Boolean(result?.isError),
1770
+ rawResult: result
1771
+ };
83
1772
  }
84
- const { hasId, id } = extractRequestId(parsed);
85
- if (!options.token) {
86
- if (!hasId) return null;
87
- return JSON.stringify({
1773
+ async fetchWorkspacePairCommand() {
1774
+ if (this.cachedPairCommand) return this.cachedPairCommand;
1775
+ const res = await this.callCloudRpc({
88
1776
  jsonrpc: "2.0",
89
- id,
90
- error: {
91
- code: -32001,
92
- message: "Missing Luaward MCP token. Set LUAWARD_MCP_TOKEN=lwm_... in your MCP config or sign in with 'npx @luaward/cli login'."
93
- }
1777
+ id: ++this.rpcSeq,
1778
+ method: "resources/read",
1779
+ params: { uri: "luaward://pair" }
94
1780
  });
1781
+ if (!res.ok || !res.body) return null;
1782
+ const contents = res.body.result?.contents;
1783
+ const firstText = contents?.[0]?.text;
1784
+ if (!firstText) return null;
1785
+ try {
1786
+ const parsed = JSON.parse(firstText);
1787
+ if (typeof parsed.pairCommand === "string" && parsed.pairCommand.trim()) {
1788
+ this.cachedPairCommand = parsed.pairCommand.trim();
1789
+ return this.cachedPairCommand;
1790
+ }
1791
+ } catch {
1792
+ if (firstText.includes("loadstring(")) {
1793
+ this.cachedPairCommand = firstText.trim();
1794
+ return this.cachedPairCommand;
1795
+ }
1796
+ }
1797
+ return null;
95
1798
  }
96
- const fetchFn = options.fetchImpl ?? fetch;
97
- const headers = {
98
- "content-type": "application/json",
99
- accept: "application/json",
100
- authorization: `Bearer ${options.token}`,
101
- "user-agent": `@luaward/mcp/${MCP_BRIDGE_VERSION}`
102
- };
103
- const protoVer = extractProtocolVersion(parsed);
104
- if (protoVer) headers["mcp-protocol-version"] = protoVer;
105
- try {
106
- const res = await fetchFn(options.url, {
107
- method: "POST",
108
- headers,
109
- body: trimmed
1799
+ async tryZeroTouchAutoInject() {
1800
+ const clientsRes = await this.potassium.listClients();
1801
+ if (!clientsRes.ok || clientsRes.clients.length === 0) {
1802
+ return { injected: false, text: "no attached Roblox client found in Potassium local MCP" };
1803
+ }
1804
+ const pairCmd = await this.fetchWorkspacePairCommand();
1805
+ if (!pairCmd) {
1806
+ return { injected: false, text: "could not fetch workspace pair command (luaward://pair)" };
1807
+ }
1808
+ const pids = clientsRes.clients.map((c) => c.pid ?? c.id).filter((p) => p !== void 0 && p !== "");
1809
+ const execRes = await this.potassium.executeScript(pairCmd, pids.length > 0 ? pids : void 0);
1810
+ if (!execRes.ok) {
1811
+ return { injected: false, text: `Potassium execute_script failed: ${execRes.text}` };
1812
+ }
1813
+ for (let i = 0; i < this.autoInjectMaxPolls; i++) {
1814
+ if (this.autoInjectPollMs > 0) await sleep(this.autoInjectPollMs);
1815
+ const check = await this.callCloudTool("list_sessions", {});
1816
+ if (check.ok && check.text && !check.text.includes("no game is connected")) {
1817
+ return {
1818
+ injected: true,
1819
+ text: `Auto-injected Luaward agent via Potassium local MCP (${clientsRes.clients.length} client(s))`
1820
+ };
1821
+ }
1822
+ }
1823
+ return {
1824
+ injected: false,
1825
+ text: "injected pair command via Potassium, but session did not register within timeout"
1826
+ };
1827
+ }
1828
+ resolveLocalFileArg(args, targetField) {
1829
+ const rawPath = args.file_path;
1830
+ if (typeof rawPath !== "string" || !rawPath.trim()) return;
1831
+ const fullPath = resolve2(rawPath.trim());
1832
+ if (!existsSync3(fullPath)) {
1833
+ throw new Error(`Local file_path not found: ${fullPath}`);
1834
+ }
1835
+ const content = readFileSync2(fullPath, "utf8");
1836
+ args[targetField] = content;
1837
+ delete args.file_path;
1838
+ }
1839
+ async handleEditorTabs(args) {
1840
+ const action = String(args.action ?? "");
1841
+ const tabId = typeof args.tab_id === "string" && args.tab_id.trim() ? args.tab_id.trim() : void 0;
1842
+ switch (action) {
1843
+ case "list": {
1844
+ const res = await this.potassium.listTabs();
1845
+ if (!res.ok) return { content: [{ type: "text", text: res.rawText }], isError: true };
1846
+ if (res.tabs.length === 0) {
1847
+ return { content: [{ type: "text", text: res.rawText || "no tabs in Potassium" }] };
1848
+ }
1849
+ const lines = res.tabs.map(
1850
+ (t) => `${t.id} "${t.name}"${t.active ? " [active]" : ""}${t.dirty ? " [dirty]" : ""}`
1851
+ );
1852
+ return {
1853
+ content: [{ type: "text", text: `${res.tabs.length} Potassium tab(s):
1854
+ ${lines.join("\n")}` }]
1855
+ };
1856
+ }
1857
+ case "read": {
1858
+ const res = await this.potassium.readTab(tabId);
1859
+ if (!res.ok) return { content: [{ type: "text", text: res.content }], isError: true };
1860
+ const header = `-- Potassium tab ${res.tabId ?? "active"}${res.name ? ` ("${res.name}")` : ""}`;
1861
+ return { content: [{ type: "text", text: `${header}
1862
+ ${res.content}` }] };
1863
+ }
1864
+ case "open":
1865
+ case "write": {
1866
+ let content = typeof args.content === "string" ? args.content : "";
1867
+ if (typeof args.file_path === "string" && args.file_path.trim()) {
1868
+ const fp = resolve2(args.file_path.trim());
1869
+ if (!existsSync3(fp)) {
1870
+ return { content: [{ type: "text", text: `Local file_path not found: ${fp}` }], isError: true };
1871
+ }
1872
+ content = readFileSync2(fp, "utf8");
1873
+ }
1874
+ const res = await this.potassium.openOrReuseTab({
1875
+ name: typeof args.name === "string" ? args.name : void 0,
1876
+ content,
1877
+ tabId: action === "write" ? tabId : void 0,
1878
+ reuseScratch: args.reuse_scratch !== false
1879
+ });
1880
+ return { content: [{ type: "text", text: res.text }], isError: !res.ok };
1881
+ }
1882
+ case "activate": {
1883
+ if (!tabId) {
1884
+ return {
1885
+ content: [{ type: "text", text: "tab_id is required for action=activate" }],
1886
+ isError: true
1887
+ };
1888
+ }
1889
+ const res = await this.potassium.callTool("tabs", { action: "activate", tab_id: tabId, id: tabId });
1890
+ return {
1891
+ content: [{ type: "text", text: res.ok ? `activated tab ${tabId}` : res.text }],
1892
+ isError: !res.ok
1893
+ };
1894
+ }
1895
+ case "close": {
1896
+ if (!tabId) {
1897
+ return { content: [{ type: "text", text: "tab_id is required for action=close" }], isError: true };
1898
+ }
1899
+ const res = await this.potassium.callTool("tabs", { action: "close", tab_id: tabId, id: tabId });
1900
+ if (!res.ok && res.text.toLowerCase().includes("dirty")) {
1901
+ return {
1902
+ content: [
1903
+ {
1904
+ type: "text",
1905
+ text: `${res.text} (Note: Potassium MCP refuses to close tabs marked dirty:true; reuse "${SCRATCH_TAB_NAME}" via editor_tabs write/open with reuse_scratch=true instead.)`
1906
+ }
1907
+ ],
1908
+ isError: true
1909
+ };
1910
+ }
1911
+ return {
1912
+ content: [{ type: "text", text: res.ok ? `closed tab ${tabId}` : res.text }],
1913
+ isError: !res.ok
1914
+ };
1915
+ }
1916
+ case "run_tab": {
1917
+ const read = await this.potassium.readTab(tabId);
1918
+ if (!read.ok) return { content: [{ type: "text", text: read.content }], isError: true };
1919
+ if (!read.content.trim()) {
1920
+ return { content: [{ type: "text", text: "Target Potassium tab is empty" }], isError: true };
1921
+ }
1922
+ let execRes = await this.callCloudTool("exec", {
1923
+ code: read.content,
1924
+ ...typeof args.session === "string" ? { session: args.session } : {},
1925
+ ...args.readonly === true ? { readonly: true } : {},
1926
+ ...args.guard === true ? { guard: true } : {}
1927
+ });
1928
+ if (this.autoInject && execRes.isError && execRes.text.includes("no game is connected")) {
1929
+ const inj = await this.tryZeroTouchAutoInject();
1930
+ if (inj.injected) {
1931
+ execRes = await this.callCloudTool("exec", {
1932
+ code: read.content,
1933
+ ...typeof args.session === "string" ? { session: args.session } : {},
1934
+ ...args.readonly === true ? { readonly: true } : {},
1935
+ ...args.guard === true ? { guard: true } : {}
1936
+ });
1937
+ }
1938
+ }
1939
+ return {
1940
+ content: [
1941
+ {
1942
+ type: "text",
1943
+ text: `[ran Potassium tab ${read.tabId ?? "active"}${read.name ? ` "${read.name}"` : ""} via Luaward exec]
1944
+ ${execRes.text}`
1945
+ }
1946
+ ],
1947
+ isError: execRes.isError
1948
+ };
1949
+ }
1950
+ case "sync_tab_to_cloud": {
1951
+ const script = typeof args.script === "string" ? args.script.trim() : "";
1952
+ if (!script) {
1953
+ return {
1954
+ content: [{ type: "text", text: "script (name or id) is required for sync_tab_to_cloud" }],
1955
+ isError: true
1956
+ };
1957
+ }
1958
+ const read = await this.potassium.readTab(tabId);
1959
+ if (!read.ok) return { content: [{ type: "text", text: read.content }], isError: true };
1960
+ const deployRes = await this.callCloudTool("deploy_script", {
1961
+ script,
1962
+ source: read.content,
1963
+ ...typeof args.publish === "boolean" ? { publish: args.publish } : {},
1964
+ ...typeof args.preset === "string" ? { preset: args.preset } : {}
1965
+ });
1966
+ return {
1967
+ content: [
1968
+ {
1969
+ type: "text",
1970
+ text: `[synced Potassium tab ${read.tabId ?? "active"} -> Luaward Cloud "${script}"]
1971
+ ${deployRes.text}`
1972
+ }
1973
+ ],
1974
+ isError: deployRes.isError
1975
+ };
1976
+ }
1977
+ case "open_cloud_script_in_tab": {
1978
+ const script = typeof args.script === "string" ? args.script.trim() : "";
1979
+ if (!script) {
1980
+ return {
1981
+ content: [{ type: "text", text: "script (name or id) is required for open_cloud_script_in_tab" }],
1982
+ isError: true
1983
+ };
1984
+ }
1985
+ const srcRes = await this.callCloudTool("get_script_source", { script });
1986
+ if (!srcRes.ok) {
1987
+ return { content: [{ type: "text", text: srcRes.text }], isError: true };
1988
+ }
1989
+ const nl = srcRes.text.indexOf("\n");
1990
+ const headerLine = nl !== -1 ? srcRes.text.slice(0, nl) : "";
1991
+ const luauBody = nl !== -1 ? srcRes.text.slice(nl + 1) : srcRes.text;
1992
+ const tabName = typeof args.name === "string" && args.name.trim() ? args.name.trim() : `${script.replace(/[^A-Za-z0-9_-]/g, "_")}.luau`;
1993
+ const opened = await this.potassium.openOrReuseTab({
1994
+ name: tabName,
1995
+ content: `-- ${headerLine}
1996
+ ${luauBody}`,
1997
+ tabId,
1998
+ reuseScratch: args.reuse_scratch !== false
1999
+ });
2000
+ return {
2001
+ content: [{ type: "text", text: `${opened.text} (from Luaward Cloud script "${script}")` }],
2002
+ isError: !opened.ok
2003
+ };
2004
+ }
2005
+ case "install_autoexec": {
2006
+ const pairCmd = await this.fetchWorkspacePairCommand();
2007
+ if (!pairCmd) {
2008
+ return {
2009
+ content: [{ type: "text", text: "Could not retrieve workspace pair command from Luaward Cloud" }],
2010
+ isError: true
2011
+ };
2012
+ }
2013
+ const installed = this.potassium.installAutoexecBootstrapper(
2014
+ pairCmd,
2015
+ typeof args.autoexec_dir === "string" ? args.autoexec_dir : void 0
2016
+ );
2017
+ return {
2018
+ content: [{ type: "text", text: installed.text }],
2019
+ isError: !installed.ok
2020
+ };
2021
+ }
2022
+ default:
2023
+ return {
2024
+ content: [{ type: "text", text: `Unknown editor_tabs action "${action}"` }],
2025
+ isError: true
2026
+ };
2027
+ }
2028
+ }
2029
+ async handleDesktopLaunch(args) {
2030
+ const action = String(args.action ?? "");
2031
+ switch (action) {
2032
+ case "status": {
2033
+ const [wins, kClients] = await Promise.all([
2034
+ this.windows.listWindows().catch(() => []),
2035
+ this.potassium.listClients()
2036
+ ]);
2037
+ const rbxWins = wins.filter(
2038
+ (w) => w.processName.toLowerCase().includes("roblox") || w.title === "Roblox"
2039
+ );
2040
+ const potWins = wins.filter((w) => w.processName.toLowerCase().includes("potassium"));
2041
+ const lines = [
2042
+ `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("; ")})` : ""}`,
2043
+ `Potassium windows: ${potWins.length}${potWins.length ? ` (PID ${potWins.map((w) => w.pid).join(", ")})` : ""}`,
2044
+ `Potassium MCP (${this.potassium.url}): ${kClients.ok ? `online (${kClients.clients.length} attached client(s))` : `offline (${kClients.rawText})`}`
2045
+ ];
2046
+ return { content: [{ type: "text", text: lines.join("\n") }] };
2047
+ }
2048
+ case "launch_potassium": {
2049
+ const check = await this.potassium.listClients();
2050
+ if (check.ok) {
2051
+ return {
2052
+ content: [
2053
+ {
2054
+ type: "text",
2055
+ text: `Potassium MCP is already running at ${this.potassium.url} (${check.clients.length} client(s) attached)`
2056
+ }
2057
+ ]
2058
+ };
2059
+ }
2060
+ const launched = await this.windows.launchPotassium(
2061
+ typeof args.potassium_path === "string" ? args.potassium_path : void 0
2062
+ );
2063
+ return { content: [{ type: "text", text: launched.text }], isError: !launched.ok };
2064
+ }
2065
+ case "launch_roblox":
2066
+ case "rejoin": {
2067
+ const placeId = typeof args.place_id === "string" && args.place_id.trim() ? args.place_id.trim() : this.lastLaunchParams?.placeId;
2068
+ if (!placeId) {
2069
+ return {
2070
+ content: [{ type: "text", text: "place_id is required to launch or rejoin Roblox" }],
2071
+ isError: true
2072
+ };
2073
+ }
2074
+ const launchCfg = {
2075
+ placeId,
2076
+ jobId: typeof args.job_id === "string" ? args.job_id : this.lastLaunchParams?.jobId,
2077
+ accessCode: typeof args.access_code === "string" ? args.access_code : this.lastLaunchParams?.accessCode,
2078
+ launchData: typeof args.launch_data === "string" ? args.launch_data : this.lastLaunchParams?.launchData,
2079
+ directBinary: typeof args.direct_binary === "boolean" ? args.direct_binary : this.lastLaunchParams?.directBinary
2080
+ };
2081
+ this.lastLaunchParams = launchCfg;
2082
+ const notes = [];
2083
+ if (action === "rejoin") {
2084
+ const killed = await this.windows.killProcess("RobloxPlayerBeta");
2085
+ notes.push(killed.text);
2086
+ }
2087
+ const launched = await this.windows.launchRoblox(launchCfg);
2088
+ notes.push(launched.text);
2089
+ if (args.auto_inject !== false && this.autoInject) {
2090
+ const inj = await this.tryZeroTouchAutoInject();
2091
+ if (inj.injected) notes.push(inj.text);
2092
+ }
2093
+ return { content: [{ type: "text", text: notes.join("\n") }], isError: !launched.ok };
2094
+ }
2095
+ case "kill_roblox": {
2096
+ const killed = await this.windows.killProcess("RobloxPlayerBeta");
2097
+ return { content: [{ type: "text", text: killed.text }], isError: !killed.ok };
2098
+ }
2099
+ default:
2100
+ return {
2101
+ content: [{ type: "text", text: `Unknown desktop_launch action "${action}"` }],
2102
+ isError: true
2103
+ };
2104
+ }
2105
+ }
2106
+ async handleDesktopWindow(args) {
2107
+ const action = String(args.action ?? "");
2108
+ const target = typeof args.target === "string" && args.target.trim() ? args.target.trim() : "roblox";
2109
+ switch (action) {
2110
+ case "list": {
2111
+ const wins = await this.windows.listWindows(
2112
+ typeof args.target === "string" ? args.target : void 0
2113
+ );
2114
+ if (wins.length === 0) return { content: [{ type: "text", text: "no matching visible windows" }] };
2115
+ const lines = wins.map(
2116
+ (w) => `${w.hwnd} PID ${w.pid} (${w.processName}) "${w.title}" \xB7 window ${w.rect.width}x${w.rect.height} at (${w.rect.left},${w.rect.top}) \xB7 client ${w.clientRect.width}x${w.clientRect.height} at screen (${w.clientRect.screenLeft},${w.clientRect.screenTop})${w.isForeground ? " [foreground]" : ""}${w.isMinimized ? " [minimized]" : ""}${!w.responding ? " [NOT RESPONDING]" : ""}`
2117
+ );
2118
+ return { content: [{ type: "text", text: lines.join("\n") }] };
2119
+ }
2120
+ case "focus": {
2121
+ const res = await this.windows.focusWindow(target);
2122
+ if (!res.ok) return { content: [{ type: "text", text: res.err ?? "focus failed" }], isError: true };
2123
+ return {
2124
+ content: [
2125
+ {
2126
+ type: "text",
2127
+ text: `focused "${res.window?.title ?? target}" (${res.window?.hwnd ?? ""})`
2128
+ }
2129
+ ]
2130
+ };
2131
+ }
2132
+ case "resize": {
2133
+ const x = typeof args.x === "number" ? args.x : 80;
2134
+ const y = typeof args.y === "number" ? args.y : 80;
2135
+ const width = typeof args.width === "number" ? args.width : 1280;
2136
+ const height = typeof args.height === "number" ? args.height : 720;
2137
+ const res = await this.windows.resizeWindow({
2138
+ target,
2139
+ x,
2140
+ y,
2141
+ width,
2142
+ height,
2143
+ clientArea: args.client_area !== false
2144
+ });
2145
+ if (!res.ok) return { content: [{ type: "text", text: res.err ?? "resize failed" }], isError: true };
2146
+ const w = res.window;
2147
+ return {
2148
+ content: [
2149
+ {
2150
+ type: "text",
2151
+ text: `resized "${w?.title ?? target}" -> client ${w?.clientRect.width ?? width}x${w?.clientRect.height ?? height} at screen (${w?.clientRect.screenLeft ?? x}, ${w?.clientRect.screenTop ?? y})`
2152
+ }
2153
+ ]
2154
+ };
2155
+ }
2156
+ case "minimize":
2157
+ case "maximize":
2158
+ case "restore": {
2159
+ const res = await this.windows.setWindowState(target, action);
2160
+ return { content: [{ type: "text", text: res.text }], isError: !res.ok };
2161
+ }
2162
+ default:
2163
+ return {
2164
+ content: [{ type: "text", text: `Unknown desktop_window action "${action}"` }],
2165
+ isError: true
2166
+ };
2167
+ }
2168
+ }
2169
+ async handleDesktopScreenshot(args) {
2170
+ const shot = await this.windows.captureScreenshot({
2171
+ target: typeof args.target === "string" ? args.target : "roblox",
2172
+ focusFirst: args.focus_first === true,
2173
+ clientOnly: args.client_only !== false
110
2174
  });
111
- if (res.status === 202 || res.status === 204) {
112
- return null;
2175
+ if (!shot.ok || !shot.data) {
2176
+ return {
2177
+ content: [{ type: "text", text: `desktop_screenshot failed: ${shot.err ?? "unknown error"}` }],
2178
+ isError: true
2179
+ };
113
2180
  }
114
- const text = await res.text();
2181
+ const meta = `desktop_screenshot (${shot.width ?? "?"}x${shot.height ?? "?"}${shot.clientRect ? `, client origin screen=(${shot.clientRect.screenLeft},${shot.clientRect.screenTop})` : ""})`;
2182
+ return {
2183
+ content: [
2184
+ { type: "text", text: meta },
2185
+ { type: "image", mimeType: shot.mimeType || "image/png", data: shot.data }
2186
+ ]
2187
+ };
2188
+ }
2189
+ async handleDesktopUiTree(args) {
2190
+ const res = await this.windows.getUiTree({
2191
+ target: typeof args.target === "string" ? args.target : "potassium",
2192
+ maxDepth: typeof args.max_depth === "number" ? args.max_depth : 5,
2193
+ maxElements: typeof args.max_elements === "number" ? args.max_elements : 150,
2194
+ interactiveOnly: args.interactive_only !== false
2195
+ });
115
2196
  if (!res.ok) {
2197
+ return {
2198
+ content: [{ type: "text", text: `desktop_ui_tree failed: ${res.err ?? "unknown error"}` }],
2199
+ isError: true
2200
+ };
2201
+ }
2202
+ const lines = res.nodes.map((n) => {
2203
+ const indent = " ".repeat(Math.max(0, n.depth - 1));
2204
+ const label = n.name ? ` "${n.name}"` : "";
2205
+ const aid = n.automationId ? ` [id=${n.automationId}]` : "";
2206
+ return `${indent}#${n.id} [${n.controlType}]${label}${aid} (${n.rect.left},${n.rect.top} ${n.rect.width}x${n.rect.height} \xB7 center=${n.center.x},${n.center.y})${n.isEnabled ? "" : " [disabled]"}`;
2207
+ });
2208
+ const header = `UI Automation tree for "${res.windowTitle ?? args.target ?? "window"}" (${res.nodes.length} elements):`;
2209
+ return {
2210
+ content: [{ type: "text", text: `${header}
2211
+ ${lines.join("\n")}` }]
2212
+ };
2213
+ }
2214
+ async handleOsClick(args) {
2215
+ const target = typeof args.target === "string" ? args.target.trim() : "";
2216
+ if (!target) {
2217
+ return {
2218
+ content: [{ type: "text", text: "target (#n or GuiObject path) is required" }],
2219
+ isError: true
2220
+ };
2221
+ }
2222
+ const lookupCode = [
2223
+ `local inst, err = lw.resolve(${JSON.stringify(target)})`,
2224
+ "if not inst then error(err or 'target not found') end",
2225
+ "local pos, size = inst.AbsolutePosition, inst.AbsoluteSize",
2226
+ "if not (pos and size) then error(lw.path(inst) .. ' has no AbsolutePosition/AbsoluteSize') end",
2227
+ "local inset = game:GetService('GuiService'):GetGuiInset()",
2228
+ "local cam = game:GetService('Workspace').CurrentCamera",
2229
+ "local vp = cam and cam.ViewportSize or Vector2.new(0, 0)",
2230
+ "return { path = lw.path(inst), x = pos.X + size.X / 2, y = pos.Y + size.Y / 2 + (inset and inset.Y or 0), vpX = vp.X, vpY = vp.Y }"
2231
+ ].join("; ");
2232
+ let queryRes = await this.callCloudTool("exec", {
2233
+ code: lookupCode,
2234
+ readonly: true,
2235
+ ...typeof args.session === "string" ? { session: args.session } : {}
2236
+ });
2237
+ if (this.autoInject && queryRes.isError && queryRes.text.includes("no game is connected")) {
2238
+ const inj = await this.tryZeroTouchAutoInject();
2239
+ if (inj.injected) {
2240
+ queryRes = await this.callCloudTool("exec", {
2241
+ code: lookupCode,
2242
+ readonly: true,
2243
+ ...typeof args.session === "string" ? { session: args.session } : {}
2244
+ });
2245
+ }
2246
+ }
2247
+ if (!queryRes.ok) {
2248
+ return {
2249
+ content: [{ type: "text", text: `os_click could not resolve ${target}: ${queryRes.text}` }],
2250
+ isError: true
2251
+ };
2252
+ }
2253
+ const text = queryRes.text;
2254
+ const xMatch = /\bx\s*=\s*(-?\d+(?:\.\d+)?)/.exec(text);
2255
+ const yMatch = /\by\s*=\s*(-?\d+(?:\.\d+)?)/.exec(text);
2256
+ const vpXMatch = /\bvpX\s*=\s*(-?\d+(?:\.\d+)?)/.exec(text);
2257
+ const vpYMatch = /\bvpY\s*=\s*(-?\d+(?:\.\d+)?)/.exec(text);
2258
+ const pathMatch = /\bpath\s*=\s*"([^"]+)"/.exec(text);
2259
+ if (!xMatch || !yMatch) {
2260
+ return {
2261
+ content: [{ type: "text", text: `os_click could not parse coordinates from game answer: ${text}` }],
2262
+ isError: true
2263
+ };
2264
+ }
2265
+ const clientX = Number(xMatch[1]) + (typeof args.offset_x === "number" ? args.offset_x : 0);
2266
+ const clientY = Number(yMatch[1]) + (typeof args.offset_y === "number" ? args.offset_y : 0);
2267
+ const vpX = vpXMatch ? Number(vpXMatch[1]) : 0;
2268
+ const vpY = vpYMatch ? Number(vpYMatch[1]) : 0;
2269
+ const resolvedPath = pathMatch?.[1] ?? target;
2270
+ const focusRes = await this.windows.focusWindow("roblox");
2271
+ if (!focusRes.ok || !focusRes.window) {
2272
+ return {
2273
+ content: [
2274
+ { type: "text", text: `os_click could not find Roblox window: ${focusRes.err ?? "not found"}` }
2275
+ ],
2276
+ isError: true
2277
+ };
2278
+ }
2279
+ const cr = focusRes.window.clientRect;
2280
+ const scaleX = vpX > 0 && cr.width > 0 ? cr.width / vpX : 1;
2281
+ const scaleY = vpY > 0 && cr.height > 0 ? cr.height / vpY : 1;
2282
+ const screenX = Math.round(cr.screenLeft + clientX * scaleX);
2283
+ const screenY = Math.round(cr.screenTop + clientY * scaleY);
2284
+ const mouseAction = args.double_click === true ? "double_click" : args.button === "right" ? "right_click" : "click";
2285
+ const clickRes = await this.windows.mouse({
2286
+ action: mouseAction,
2287
+ mode: "ui",
2288
+ x: screenX,
2289
+ y: screenY
2290
+ });
2291
+ return {
2292
+ content: [
2293
+ {
2294
+ type: "text",
2295
+ text: `os_click ${mouseAction} on ${resolvedPath} (${target}): in-game client=(${Math.round(clientX)}, ${Math.round(clientY)}) -> Windows screen=(${screenX}, ${screenY})`
2296
+ }
2297
+ ],
2298
+ isError: !clickRes.ok
2299
+ };
2300
+ }
2301
+ async handleLocalToolCall(name, args) {
2302
+ try {
2303
+ switch (name) {
2304
+ case "editor_tabs":
2305
+ return await this.handleEditorTabs(args);
2306
+ case "desktop_launch":
2307
+ return await this.handleDesktopLaunch(args);
2308
+ case "desktop_window":
2309
+ return await this.handleDesktopWindow(args);
2310
+ case "desktop_screenshot":
2311
+ return await this.handleDesktopScreenshot(args);
2312
+ case "desktop_ui_tree":
2313
+ return await this.handleDesktopUiTree(args);
2314
+ case "desktop_mouse": {
2315
+ const res = await this.windows.mouse({
2316
+ action: String(args.action ?? "click"),
2317
+ mode: typeof args.mode === "string" ? args.mode : void 0,
2318
+ x: typeof args.x === "number" ? args.x : void 0,
2319
+ y: typeof args.y === "number" ? args.y : void 0,
2320
+ dx: typeof args.dx === "number" ? args.dx : void 0,
2321
+ dy: typeof args.dy === "number" ? args.dy : void 0,
2322
+ toX: typeof args.to_x === "number" ? args.to_x : void 0,
2323
+ toY: typeof args.to_y === "number" ? args.to_y : void 0,
2324
+ scrollDelta: typeof args.scroll_delta === "number" ? args.scroll_delta : void 0,
2325
+ steps: typeof args.steps === "number" ? args.steps : void 0,
2326
+ holdMs: typeof args.hold_ms === "number" ? args.hold_ms : void 0,
2327
+ relativeTo: typeof args.relative_to === "string" ? args.relative_to : void 0
2328
+ });
2329
+ return { content: [{ type: "text", text: res.text }], isError: !res.ok };
2330
+ }
2331
+ case "desktop_keyboard": {
2332
+ const res = await this.windows.keyboard({
2333
+ action: String(args.action ?? "press"),
2334
+ text: typeof args.text === "string" ? args.text : void 0,
2335
+ key: typeof args.key === "string" ? args.key : void 0,
2336
+ keys: Array.isArray(args.keys) ? args.keys.map(String) : void 0,
2337
+ holdMs: typeof args.hold_ms === "number" ? args.hold_ms : void 0,
2338
+ target: typeof args.target === "string" ? args.target : void 0
2339
+ });
2340
+ return { content: [{ type: "text", text: res.text }], isError: !res.ok };
2341
+ }
2342
+ case "os_click":
2343
+ return await this.handleOsClick(args);
2344
+ default:
2345
+ return null;
2346
+ }
2347
+ } catch (err) {
2348
+ return {
2349
+ content: [
2350
+ {
2351
+ type: "text",
2352
+ text: `${name} error: ${err instanceof Error ? err.message : String(err)}`
2353
+ }
2354
+ ],
2355
+ isError: true
2356
+ };
2357
+ }
2358
+ }
2359
+ async handleJsonRpcLine(line) {
2360
+ const trimmed = line.trim();
2361
+ if (!trimmed) return null;
2362
+ let parsed;
2363
+ try {
2364
+ parsed = JSON.parse(trimmed);
2365
+ } catch {
2366
+ return JSON.stringify({
2367
+ jsonrpc: "2.0",
2368
+ id: null,
2369
+ error: { code: -32700, message: "Parse error: invalid JSON on stdin" }
2370
+ });
2371
+ }
2372
+ const { hasId, id } = extractRequestId(parsed);
2373
+ if (!this.token) {
116
2374
  if (!hasId) return null;
117
- let detail = `HTTP ${res.status}`;
2375
+ return JSON.stringify({
2376
+ jsonrpc: "2.0",
2377
+ id,
2378
+ error: {
2379
+ code: -32001,
2380
+ message: "Missing Luaward MCP token. Set LUAWARD_MCP_TOKEN=lwm_... in your MCP config or sign in with 'npx @luaward/cli login'."
2381
+ }
2382
+ });
2383
+ }
2384
+ const msg = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2385
+ if (msg?.method === "tools/call" && msg.params && typeof msg.params === "object") {
2386
+ const toolName = typeof msg.params.name === "string" ? msg.params.name : "";
2387
+ const rawArgs = msg.params.arguments && typeof msg.params.arguments === "object" && !Array.isArray(msg.params.arguments) ? { ...msg.params.arguments } : {};
2388
+ const localResult = await this.handleLocalToolCall(toolName, rawArgs);
2389
+ if (localResult !== null) {
2390
+ return JSON.stringify({ jsonrpc: "2.0", id, result: localResult });
2391
+ }
118
2392
  try {
119
- const errObj = JSON.parse(text);
120
- if (errObj && typeof errObj === "object" && "jsonrpc" in errObj) {
121
- return JSON.stringify(errObj);
2393
+ if (toolName === "exec" && rawArgs.file_path !== void 0) {
2394
+ this.resolveLocalFileArg(rawArgs, "code");
2395
+ msg.params = { ...msg.params, arguments: rawArgs };
2396
+ } else if ((toolName === "create_script" || toolName === "deploy_script") && rawArgs.file_path !== void 0) {
2397
+ this.resolveLocalFileArg(rawArgs, "source");
2398
+ msg.params = { ...msg.params, arguments: rawArgs };
2399
+ }
2400
+ } catch (fileErr) {
2401
+ return JSON.stringify({
2402
+ jsonrpc: "2.0",
2403
+ id,
2404
+ result: {
2405
+ content: [
2406
+ {
2407
+ type: "text",
2408
+ text: fileErr instanceof Error ? fileErr.message : String(fileErr)
2409
+ }
2410
+ ],
2411
+ isError: true
2412
+ }
2413
+ });
2414
+ }
2415
+ }
2416
+ const protoVer = extractProtocolVersion(parsed);
2417
+ try {
2418
+ const forwardPayload = msg ?? parsed;
2419
+ const res = await this.callCloudRpc(forwardPayload, protoVer);
2420
+ if (res.status === 202 || res.status === 204) return null;
2421
+ if (!res.ok) {
2422
+ if (!hasId) return null;
2423
+ let detail = `HTTP ${res.status}`;
2424
+ if (res.body && "jsonrpc" in res.body) {
2425
+ return JSON.stringify(res.body);
2426
+ }
2427
+ if (res.body) {
2428
+ const errObj = res.body;
2429
+ detail = errObj.error_description || errObj.message || (typeof errObj.error === "string" ? errObj.error : detail);
2430
+ } else if (res.rawText.trim()) {
2431
+ detail = `${detail}: ${res.rawText.trim().slice(0, 160)}`;
2432
+ }
2433
+ return JSON.stringify({
2434
+ jsonrpc: "2.0",
2435
+ id,
2436
+ error: {
2437
+ code: res.status === 401 || res.status === 403 ? -32001 : -32e3,
2438
+ message: `Luaward MCP server rejected request (${detail})`
2439
+ }
2440
+ });
2441
+ }
2442
+ if (!res.body) return null;
2443
+ if (msg?.method === "tools/list" && res.body.result && typeof res.body.result === "object") {
2444
+ const resultObj = res.body.result;
2445
+ if (Array.isArray(resultObj.tools)) {
2446
+ const existingNames = new Set(resultObj.tools.map((t) => String(t.name ?? "")));
2447
+ for (const tool of resultObj.tools) {
2448
+ const tName = String(tool.name ?? "");
2449
+ if ((tName === "exec" || tName === "create_script" || tName === "deploy_script") && tool.inputSchema && typeof tool.inputSchema === "object") {
2450
+ const schema = tool.inputSchema;
2451
+ schema.properties = {
2452
+ ...schema.properties ?? {},
2453
+ file_path: {
2454
+ type: "string",
2455
+ description: "Optional local .luau/.lua file path on disk; @luaward/mcp reads it automatically so you do not need to paste large code in JSON."
2456
+ }
2457
+ };
2458
+ if (tName === "exec" && Array.isArray(schema.required)) {
2459
+ schema.required = schema.required.filter((r) => r !== "code");
2460
+ }
2461
+ if ((tName === "create_script" || tName === "deploy_script") && Array.isArray(schema.required)) {
2462
+ schema.required = schema.required.filter((r) => r !== "source");
2463
+ }
2464
+ }
2465
+ }
2466
+ for (const localTool of LOCAL_HYBRID_TOOLS) {
2467
+ if (!existingNames.has(localTool.name)) {
2468
+ resultObj.tools.push(localTool);
2469
+ }
2470
+ }
2471
+ }
2472
+ }
2473
+ if (this.autoInject && msg?.method === "tools/call" && res.body.result && typeof res.body.result === "object") {
2474
+ const resultObj = res.body.result;
2475
+ const firstText = resultObj.content?.find((c) => c.type === "text")?.text ?? "";
2476
+ if (firstText.includes("no game is connected")) {
2477
+ const inj = await this.tryZeroTouchAutoInject();
2478
+ if (inj.injected) {
2479
+ const retryRes = await this.callCloudRpc(forwardPayload, protoVer);
2480
+ if (retryRes.ok && retryRes.body) {
2481
+ const retryResult = retryRes.body.result;
2482
+ const retryContent = retryResult?.content?.[0];
2483
+ if (retryContent && typeof retryContent.text === "string") {
2484
+ retryContent.text = `[${inj.text}]
2485
+ ${retryContent.text}`;
2486
+ }
2487
+ return JSON.stringify(retryRes.body);
2488
+ }
2489
+ }
122
2490
  }
123
- detail = errObj.error_description || errObj.message || (typeof errObj.error === "string" ? errObj.error : detail);
124
- } catch {
125
- if (text.trim()) detail = `${detail}: ${text.trim().slice(0, 160)}`;
126
2491
  }
2492
+ return JSON.stringify(res.body);
2493
+ } catch (err) {
2494
+ if (!hasId) return null;
2495
+ const msgText = err instanceof Error ? err.message : String(err);
127
2496
  return JSON.stringify({
128
2497
  jsonrpc: "2.0",
129
2498
  id,
130
2499
  error: {
131
- code: res.status === 401 || res.status === 403 ? -32001 : -32e3,
132
- message: `Luaward MCP server rejected request (${detail})`
2500
+ code: -32e3,
2501
+ message: `Failed to reach Luaward MCP server at ${this.url}: ${msgText}`
133
2502
  }
134
2503
  });
135
2504
  }
136
- if (!text.trim()) return null;
137
- const outParsed = JSON.parse(text);
138
- return JSON.stringify(outParsed);
139
- } catch (err) {
140
- if (!hasId) return null;
141
- const msg = err instanceof Error ? err.message : String(err);
142
- return JSON.stringify({
143
- jsonrpc: "2.0",
144
- id,
145
- error: {
146
- code: -32e3,
147
- message: `Failed to reach Luaward MCP server at ${options.url}: ${msg}`
148
- }
149
- });
150
2505
  }
2506
+ };
2507
+ async function forwardJsonRpcLine(line, options) {
2508
+ const bridge = new HybridMcpBridge({
2509
+ token: options.token,
2510
+ url: options.url,
2511
+ potassiumUrl: options.potassiumUrl,
2512
+ potassiumToken: options.potassiumToken,
2513
+ pairCommand: options.pairCommand,
2514
+ autoInject: options.autoInject ?? false,
2515
+ autoInjectPollMs: options.autoInjectPollMs,
2516
+ autoInjectMaxPolls: options.autoInjectMaxPolls,
2517
+ fetchImpl: options.fetchImpl,
2518
+ potassiumClient: options.potassiumClient,
2519
+ windowsDriver: options.windowsDriver
2520
+ });
2521
+ return bridge.handleJsonRpcLine(line);
151
2522
  }
152
2523
  function startStdioBridge(options = {}) {
153
2524
  const stdin = options.stdin ?? process.stdin;
154
2525
  const stdout = options.stdout ?? process.stdout;
155
- const resolved = resolveBridgeConfig([], process.env, options.configDir);
156
- const token = options.token !== void 0 ? options.token : resolved.token;
157
- const url = options.url ?? resolved.url;
2526
+ const bridge = new HybridMcpBridge(options);
158
2527
  const rl = createInterface({ input: stdin, crlfDelay: Number.POSITIVE_INFINITY });
159
2528
  const pending = /* @__PURE__ */ new Set();
160
2529
  rl.on("line", (line) => {
161
2530
  const task = (async () => {
162
- const reply = await forwardJsonRpcLine(line, {
163
- token: token ?? null,
164
- url,
165
- fetchImpl: options.fetchImpl
166
- });
2531
+ const reply = await bridge.handleJsonRpcLine(line);
167
2532
  if (reply !== null) {
168
2533
  stdout.write(`${reply}
169
2534
  `);
@@ -172,24 +2537,38 @@ function startStdioBridge(options = {}) {
172
2537
  pending.add(task);
173
2538
  task.finally(() => pending.delete(task));
174
2539
  });
175
- const done = new Promise((resolve) => {
2540
+ const done = new Promise((resolveDone) => {
176
2541
  rl.on("close", async () => {
177
2542
  await Promise.allSettled([...pending]);
178
- resolve();
2543
+ resolveDone();
179
2544
  });
180
2545
  });
181
2546
  return {
2547
+ bridge,
182
2548
  close: () => rl.close(),
183
2549
  done
184
2550
  };
185
2551
  }
186
2552
  export {
187
2553
  DEFAULT_MCP_URL,
2554
+ DEFAULT_POTASSIUM_URL,
2555
+ HybridMcpBridge,
2556
+ LOCAL_HYBRID_TOOLS,
188
2557
  MCP_BRIDGE_VERSION,
2558
+ PotassiumClient,
2559
+ PowerShellWindowsDriver,
2560
+ SCRATCH_TAB_NAME,
189
2561
  TOKEN_SHAPE,
2562
+ buildRobloxDeepLink,
2563
+ discoverPotassiumAutoexecDir,
2564
+ discoverPotassiumToken,
2565
+ findPotassiumBinary,
2566
+ findRobloxPlayerBinary,
190
2567
  forwardJsonRpcLine,
2568
+ matchesWindowTarget,
191
2569
  resolveBridgeConfig,
192
2570
  resolveStoredToken,
2571
+ resolveVirtualKeyCode,
193
2572
  startStdioBridge
194
2573
  };
195
2574
  //# sourceMappingURL=index.js.map