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