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