@luaward/mcp 0.1.0 → 0.2.1

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