playcanvas-agent-bridge-cli 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,702 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, extname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { CONFIG_DIR, DEFAULT_HOST, DEFAULT_PORT, EXTENSION_INSTALL_DIR, VERSION, copyDir, findPackageRoot, readOrCreateSession, readSessionIfExists, } from "./config.js";
8
+ import { createDaemonServer } from "./daemon/server.js";
9
+ import { assetDeleteSnippet, assetFolderEnsureSnippet, assetGetSnippet, assetListSnippet, assetUploadSnippet, entityAddComponentSnippet, entityAddScriptSnippet, entityCreateSnippet, entityDeleteSnippet, entityGetSnippet, entityListSnippet, entityPatchSnippet, entityRemoveComponentSnippet, entitySetMaterialSnippet, materialCreateSnippet, scriptCreateSnippet, scriptParseSnippet, scriptSetTextSnippet, } from "./snippets.js";
10
+ import { fail, ok } from "./shared/protocol.js";
11
+ function parseArgs(argv) {
12
+ const parsed = { _: [], flags: {} };
13
+ for (let index = 0; index < argv.length; index += 1) {
14
+ const item = argv[index];
15
+ if (!item.startsWith("--")) {
16
+ parsed._.push(item);
17
+ continue;
18
+ }
19
+ const eq = item.indexOf("=");
20
+ const key = eq === -1 ? item.slice(2) : item.slice(2, eq);
21
+ let value;
22
+ if (eq !== -1) {
23
+ value = item.slice(eq + 1);
24
+ }
25
+ else {
26
+ const next = argv[index + 1];
27
+ if (next && !next.startsWith("--")) {
28
+ value = next;
29
+ index += 1;
30
+ }
31
+ else {
32
+ value = true;
33
+ }
34
+ }
35
+ const existing = parsed.flags[key];
36
+ if (existing === undefined) {
37
+ parsed.flags[key] = value;
38
+ }
39
+ else if (Array.isArray(existing)) {
40
+ existing.push(String(value));
41
+ }
42
+ else {
43
+ parsed.flags[key] = [String(existing), String(value)];
44
+ }
45
+ }
46
+ return parsed;
47
+ }
48
+ function flagString(args, name, fallback) {
49
+ const value = args.flags[name];
50
+ if (Array.isArray(value))
51
+ return value[value.length - 1];
52
+ if (typeof value === "string")
53
+ return value;
54
+ return fallback;
55
+ }
56
+ function flagBool(args, name) {
57
+ return args.flags[name] === true || args.flags[name] === "true";
58
+ }
59
+ function flagList(args, name) {
60
+ const value = args.flags[name];
61
+ if (Array.isArray(value))
62
+ return value.map(String);
63
+ if (typeof value === "string")
64
+ return [value];
65
+ return [];
66
+ }
67
+ function print(value) {
68
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
69
+ }
70
+ async function readStdin() {
71
+ const chunks = [];
72
+ for await (const chunk of process.stdin) {
73
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
74
+ }
75
+ return Buffer.concat(chunks).toString("utf8");
76
+ }
77
+ async function readCode(args) {
78
+ const code = flagString(args, "code");
79
+ const file = flagString(args, "file");
80
+ if (code !== undefined)
81
+ return code;
82
+ if (file)
83
+ return readFile(file, "utf8");
84
+ if (flagBool(args, "stdin"))
85
+ return readStdin();
86
+ throw new Error("Provide --code, --file, or --stdin.");
87
+ }
88
+ function parseJsonValue(raw) {
89
+ try {
90
+ return JSON.parse(raw);
91
+ }
92
+ catch {
93
+ return raw;
94
+ }
95
+ }
96
+ function parseSets(values) {
97
+ return values.map((item) => {
98
+ const eq = item.indexOf("=");
99
+ if (eq === -1) {
100
+ throw new Error(`Invalid --set value: ${item}. Use path=value.`);
101
+ }
102
+ return {
103
+ path: item.slice(0, eq),
104
+ value: parseJsonValue(item.slice(eq + 1)),
105
+ };
106
+ });
107
+ }
108
+ async function fetchDaemon(path, init = {}) {
109
+ const session = await readOrCreateSession();
110
+ const response = await fetch(`http://${DEFAULT_HOST}:${session.port || DEFAULT_PORT}${path}`, {
111
+ ...init,
112
+ headers: {
113
+ "Content-Type": "application/json",
114
+ "X-PCBridge-Token": session.token,
115
+ ...(init.headers || {}),
116
+ },
117
+ });
118
+ const body = (await response.json());
119
+ return body;
120
+ }
121
+ async function rpcCall(args, method, params = {}, defaultTimeoutMs = 15000) {
122
+ const timeoutMs = Number(flagString(args, "timeout-ms", String(defaultTimeoutMs)));
123
+ return fetchDaemon("/rpc", {
124
+ method: "POST",
125
+ body: JSON.stringify({
126
+ target: flagString(args, "target", "current"),
127
+ method,
128
+ timeoutMs,
129
+ params: {
130
+ ...params,
131
+ timeoutMs,
132
+ },
133
+ }),
134
+ });
135
+ }
136
+ async function rpcEval(args, code, commandArgs = {}, defaultTimeoutMs = 15000) {
137
+ return rpcCall(args, "bridge:eval", {
138
+ code,
139
+ args: commandArgs,
140
+ }, defaultTimeoutMs);
141
+ }
142
+ function listEnvelope(raw) {
143
+ if (!raw.ok)
144
+ return raw;
145
+ const data = raw.data;
146
+ if (!data || !Array.isArray(data.items))
147
+ return raw;
148
+ return ok(data.items, {
149
+ ...(raw.meta || {}),
150
+ total: data.total ?? data.items.length,
151
+ offset: data.offset ?? 0,
152
+ limit: data.limit ?? data.items.length,
153
+ hasMore: data.hasMore ?? false,
154
+ });
155
+ }
156
+ function inferAssetType(path) {
157
+ const ext = extname(path).toLowerCase();
158
+ if ([".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tga"].includes(ext))
159
+ return "texture";
160
+ if ([".mp3", ".wav", ".ogg", ".m4a"].includes(ext))
161
+ return "audio";
162
+ if (ext === ".json")
163
+ return "json";
164
+ if (ext === ".css")
165
+ return "css";
166
+ if (ext === ".html" || ext === ".htm")
167
+ return "html";
168
+ if (ext === ".txt")
169
+ return "text";
170
+ return undefined;
171
+ }
172
+ function inferMime(path) {
173
+ const ext = extname(path).toLowerCase();
174
+ const mimes = {
175
+ ".png": "image/png",
176
+ ".jpg": "image/jpeg",
177
+ ".jpeg": "image/jpeg",
178
+ ".webp": "image/webp",
179
+ ".gif": "image/gif",
180
+ ".json": "application/json",
181
+ ".js": "text/javascript",
182
+ ".mjs": "text/javascript",
183
+ ".css": "text/css",
184
+ ".html": "text/html",
185
+ ".htm": "text/html",
186
+ ".txt": "text/plain",
187
+ ".mp3": "audio/mpeg",
188
+ ".wav": "audio/wav",
189
+ ".ogg": "audio/ogg",
190
+ };
191
+ return mimes[ext] || "application/octet-stream";
192
+ }
193
+ function nameFromFile(path) {
194
+ const file = basename(path);
195
+ const ext = extname(file);
196
+ return ext ? file.slice(0, -ext.length) : file;
197
+ }
198
+ async function readJsonFlag(args, flagName) {
199
+ const file = flagString(args, flagName);
200
+ if (!file)
201
+ return undefined;
202
+ return JSON.parse(await readFile(file, "utf8"));
203
+ }
204
+ function objectJson(value, label) {
205
+ if (value === undefined || value === null)
206
+ return {};
207
+ if (typeof value !== "object" || Array.isArray(value)) {
208
+ throw new Error(`${label} must be a JSON object.`);
209
+ }
210
+ return value;
211
+ }
212
+ async function doctor() {
213
+ const session = await readSessionIfExists();
214
+ const checks = [];
215
+ const nextActions = [];
216
+ const major = Number(process.versions.node.split(".", 1)[0]);
217
+ checks.push({
218
+ name: "node",
219
+ ok: major >= 20,
220
+ version: process.version,
221
+ message: major >= 20 ? "Node version is supported." : "Node 20 or newer is required.",
222
+ });
223
+ if (!session) {
224
+ nextActions.push("Run pcbridge install-extension to create a local session token.");
225
+ }
226
+ try {
227
+ const health = await fetchDaemon("/health");
228
+ checks.push({
229
+ name: "daemon",
230
+ ok: health.ok,
231
+ message: health.ok ? "Daemon is reachable." : health.error.message,
232
+ data: health.ok ? health.data : null,
233
+ });
234
+ }
235
+ catch (error) {
236
+ checks.push({
237
+ name: "daemon",
238
+ ok: false,
239
+ message: "Daemon is not reachable.",
240
+ });
241
+ nextActions.push("Run pcbridge daemon start in a terminal.");
242
+ }
243
+ const extensionExists = Boolean(session) && (await pathExists(EXTENSION_INSTALL_DIR));
244
+ checks.push({
245
+ name: "extension",
246
+ ok: extensionExists,
247
+ path: EXTENSION_INSTALL_DIR,
248
+ message: extensionExists
249
+ ? "Generated unpacked extension directory exists."
250
+ : "Generated unpacked extension directory was not found.",
251
+ });
252
+ if (!extensionExists) {
253
+ nextActions.push("Run pcbridge install-extension and load the printed directory in Chrome.");
254
+ }
255
+ return ok({
256
+ version: VERSION,
257
+ configDir: CONFIG_DIR,
258
+ checks,
259
+ nextActions,
260
+ });
261
+ }
262
+ async function pathExists(path) {
263
+ try {
264
+ await readFile(join(path, "manifest.json"), "utf8");
265
+ return true;
266
+ }
267
+ catch {
268
+ return false;
269
+ }
270
+ }
271
+ async function daemon(args) {
272
+ const subcommand = args._[1] || "status";
273
+ if (subcommand === "start") {
274
+ const session = await readOrCreateSession();
275
+ const server = createDaemonServer({
276
+ host: DEFAULT_HOST,
277
+ port: session.port || DEFAULT_PORT,
278
+ token: session.token,
279
+ log: (message) => {
280
+ if (flagBool(args, "json")) {
281
+ process.stderr.write(`${JSON.stringify({ time: new Date().toISOString(), message })}\n`);
282
+ }
283
+ else {
284
+ process.stderr.write(`[pcbridge] ${message}\n`);
285
+ }
286
+ },
287
+ });
288
+ try {
289
+ await server.listen();
290
+ }
291
+ catch (error) {
292
+ print(fail("PORT_BUSY", `Cannot listen on ${DEFAULT_HOST}:${session.port || DEFAULT_PORT}. ${String(error)}`));
293
+ process.exitCode = 1;
294
+ return;
295
+ }
296
+ print(ok({
297
+ version: VERSION,
298
+ host: DEFAULT_HOST,
299
+ port: session.port || DEFAULT_PORT,
300
+ extensionPath: EXTENSION_INSTALL_DIR,
301
+ }));
302
+ }
303
+ else if (subcommand === "status") {
304
+ try {
305
+ print(await fetchDaemon("/health"));
306
+ }
307
+ catch (error) {
308
+ print(fail("DAEMON_UNREACHABLE", "Daemon is not reachable."));
309
+ process.exitCode = 1;
310
+ }
311
+ }
312
+ else {
313
+ print(fail("UNKNOWN_COMMAND", `Unknown daemon command: ${subcommand}`));
314
+ process.exitCode = 1;
315
+ }
316
+ }
317
+ async function installExtension(args) {
318
+ const session = await readOrCreateSession();
319
+ const root = await findPackageRoot();
320
+ const source = join(root, "extension");
321
+ await copyDir(source, EXTENSION_INSTALL_DIR, {
322
+ clean: true,
323
+ ignore: new Set(["config.example.json"]),
324
+ });
325
+ await writeFile(join(EXTENSION_INSTALL_DIR, "config.json"), `${JSON.stringify({
326
+ host: DEFAULT_HOST,
327
+ port: session.port || DEFAULT_PORT,
328
+ token: session.token,
329
+ }, null, 2)}\n`, { mode: 0o600 });
330
+ if (!flagBool(args, "no-open")) {
331
+ openChromeExtensions();
332
+ }
333
+ return ok({
334
+ extensionPath: EXTENSION_INSTALL_DIR,
335
+ chromeUrl: "chrome://extensions",
336
+ nextActions: [
337
+ "Enable Developer Mode in Chrome.",
338
+ "Click Load unpacked.",
339
+ `Select ${EXTENSION_INSTALL_DIR}.`,
340
+ "Open or refresh a PlayCanvas Editor tab, then run pcbridge daemon start.",
341
+ ],
342
+ });
343
+ }
344
+ function openChromeExtensions() {
345
+ const platform = process.platform;
346
+ const command = platform === "darwin"
347
+ ? "open"
348
+ : platform === "win32"
349
+ ? "cmd"
350
+ : "xdg-open";
351
+ const args = platform === "darwin"
352
+ ? ["-a", "Google Chrome", "chrome://extensions"]
353
+ : platform === "win32"
354
+ ? ["/c", "start", "chrome://extensions"]
355
+ : ["chrome://extensions"];
356
+ try {
357
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
358
+ child.on("error", () => undefined);
359
+ child.unref();
360
+ }
361
+ catch {
362
+ // The printed chrome://extensions URL is enough when opening fails.
363
+ }
364
+ }
365
+ async function installSkill(args) {
366
+ const agent = flagString(args, "agent", "codex") || "codex";
367
+ const root = await findPackageRoot();
368
+ const installed = [];
369
+ const agents = agent === "all" ? ["codex", "claude", "cursor", "windsurf"] : [agent];
370
+ for (const item of agents) {
371
+ if (item === "codex") {
372
+ const dest = join(process.env.CODEX_HOME || join(homedir(), ".codex"), "skills");
373
+ const source = join(root, "skills", "codex", "playcanvas-agent-bridge-cli");
374
+ const target = join(dest, "playcanvas-agent-bridge-cli");
375
+ await copyDir(source, target, { clean: true });
376
+ installed.push({ agent: item, path: target });
377
+ }
378
+ else if (item === "claude") {
379
+ const target = join(homedir(), ".claude", "skills", "playcanvas-agent-bridge-cli");
380
+ await copyDir(join(root, "skills", "claude", "playcanvas-agent-bridge-cli"), target, {
381
+ clean: true,
382
+ });
383
+ installed.push({ agent: item, path: target });
384
+ }
385
+ else if (item === "cursor") {
386
+ const target = join(homedir(), ".cursor", "rules", "playcanvas-agent-bridge-cli.mdc");
387
+ await mkdir(dirname(target), { recursive: true });
388
+ await writeFile(target, await readFile(join(root, "skills", "cursor", "playcanvas-agent-bridge-cli.mdc")));
389
+ installed.push({ agent: item, path: target });
390
+ }
391
+ else if (item === "windsurf") {
392
+ const target = join(homedir(), ".windsurf", "rules", "playcanvas-agent-bridge-cli.md");
393
+ await mkdir(dirname(target), { recursive: true });
394
+ await writeFile(target, await readFile(join(root, "skills", "windsurf", "playcanvas-agent-bridge-cli.md")));
395
+ installed.push({ agent: item, path: target });
396
+ }
397
+ else {
398
+ return fail("UNKNOWN_AGENT", `Unsupported agent: ${item}. Use codex, claude, cursor, windsurf, or all.`);
399
+ }
400
+ }
401
+ return ok(installed);
402
+ }
403
+ async function handleEntity(args) {
404
+ const subcommand = args._[1] || "list";
405
+ if (subcommand === "list") {
406
+ return listEnvelope(await rpcEval(args, entityListSnippet(), {
407
+ name: flagString(args, "name") || null,
408
+ component: flagString(args, "component") || null,
409
+ limit: Number(flagString(args, "limit", "50")),
410
+ offset: Number(flagString(args, "offset", "0")),
411
+ full: flagBool(args, "full"),
412
+ }));
413
+ }
414
+ if (subcommand === "get") {
415
+ const id = flagString(args, "id");
416
+ if (!id)
417
+ return fail("INVALID_REQUEST", "entity get requires --id.");
418
+ return rpcEval(args, entityGetSnippet(), { id, full: flagBool(args, "full") });
419
+ }
420
+ if (subcommand === "create") {
421
+ const file = flagString(args, "json");
422
+ if (!file)
423
+ return fail("INVALID_REQUEST", "entity create requires --json <file>.");
424
+ const data = JSON.parse(await readFile(file, "utf8"));
425
+ return rpcEval(args, entityCreateSnippet(), { data });
426
+ }
427
+ if (subcommand === "patch") {
428
+ const id = flagString(args, "id");
429
+ if (!id)
430
+ return fail("INVALID_REQUEST", "entity patch requires --id.");
431
+ return rpcEval(args, entityPatchSnippet(), { id, sets: parseSets(flagList(args, "set")) });
432
+ }
433
+ if (subcommand === "delete") {
434
+ const ids = flagList(args, "id");
435
+ const id = flagString(args, "id");
436
+ if (!ids.length && !id)
437
+ return fail("INVALID_REQUEST", "entity delete requires --id.");
438
+ return rpcEval(args, entityDeleteSnippet(), { ids: ids, id: id || null });
439
+ }
440
+ if (subcommand === "add-component") {
441
+ const id = flagString(args, "id");
442
+ const component = flagString(args, "component");
443
+ if (!id || !component) {
444
+ return fail("INVALID_REQUEST", "entity add-component requires --id and --component.");
445
+ }
446
+ const data = (await readJsonFlag(args, "json")) ??
447
+ (flagString(args, "data") ? parseJsonValue(flagString(args, "data") || "{}") : {});
448
+ return rpcEval(args, entityAddComponentSnippet(), {
449
+ id,
450
+ component,
451
+ data: objectJson(data, "component data"),
452
+ });
453
+ }
454
+ if (subcommand === "remove-component") {
455
+ const id = flagString(args, "id");
456
+ const component = flagString(args, "component");
457
+ if (!id || !component) {
458
+ return fail("INVALID_REQUEST", "entity remove-component requires --id and --component.");
459
+ }
460
+ return rpcEval(args, entityRemoveComponentSnippet(), { id, component });
461
+ }
462
+ if (subcommand === "set-material") {
463
+ const id = flagString(args, "id");
464
+ const materialId = flagString(args, "material-id");
465
+ if (!id || !materialId) {
466
+ return fail("INVALID_REQUEST", "entity set-material requires --id and --material-id.");
467
+ }
468
+ return rpcEval(args, entitySetMaterialSnippet(), {
469
+ id,
470
+ materialId,
471
+ slot: Number(flagString(args, "slot", "0")),
472
+ renderType: flagString(args, "render-type", "box") || "box",
473
+ });
474
+ }
475
+ if (subcommand === "add-script") {
476
+ const id = flagString(args, "id");
477
+ if (!id)
478
+ return fail("INVALID_REQUEST", "entity add-script requires --id.");
479
+ const attributes = (await readJsonFlag(args, "attributes-json")) ??
480
+ (flagString(args, "attributes") ? parseJsonValue(flagString(args, "attributes") || "{}") : {});
481
+ return rpcEval(args, entityAddScriptSnippet(), {
482
+ id,
483
+ scriptName: flagString(args, "script-name") || null,
484
+ assetId: flagString(args, "asset-id") || null,
485
+ attributes: objectJson(attributes, "script attributes"),
486
+ enabled: !flagBool(args, "disabled"),
487
+ });
488
+ }
489
+ return fail("UNKNOWN_COMMAND", `Unknown entity command: ${subcommand}`);
490
+ }
491
+ async function handleAsset(args) {
492
+ const subcommand = args._[1] || "list";
493
+ if (subcommand === "list") {
494
+ return listEnvelope(await rpcEval(args, assetListSnippet(), {
495
+ name: flagString(args, "name") || null,
496
+ type: flagString(args, "type") || null,
497
+ limit: Number(flagString(args, "limit", "50")),
498
+ offset: Number(flagString(args, "offset", "0")),
499
+ full: flagBool(args, "full"),
500
+ }));
501
+ }
502
+ if (subcommand === "get") {
503
+ const id = flagString(args, "id");
504
+ if (!id)
505
+ return fail("INVALID_REQUEST", "asset get requires --id.");
506
+ return rpcEval(args, assetGetSnippet(), { id, full: flagBool(args, "full") });
507
+ }
508
+ if (subcommand === "folder" && args._[2] === "ensure") {
509
+ const path = flagString(args, "path");
510
+ if (!path)
511
+ return fail("INVALID_REQUEST", "asset folder ensure requires --path.");
512
+ return rpcEval(args, assetFolderEnsureSnippet(), { path });
513
+ }
514
+ if (subcommand === "upload") {
515
+ const file = flagString(args, "file");
516
+ if (!file)
517
+ return fail("INVALID_REQUEST", "asset upload requires --file.");
518
+ const fileBuffer = await readFile(file);
519
+ const type = flagString(args, "type") || inferAssetType(file);
520
+ if (!type)
521
+ return fail("INVALID_REQUEST", "asset upload requires --type for this file.");
522
+ const filename = flagString(args, "filename") || basename(file);
523
+ return rpcEval(args, assetUploadSnippet(), {
524
+ base64: fileBuffer.toString("base64"),
525
+ mime: flagString(args, "mime") || inferMime(file),
526
+ name: flagString(args, "name") || nameFromFile(file),
527
+ filename,
528
+ type,
529
+ folder: flagString(args, "folder") || null,
530
+ folderId: flagString(args, "folder-id") || null,
531
+ preload: !flagBool(args, "no-preload"),
532
+ }, 120000);
533
+ }
534
+ if (subcommand === "delete") {
535
+ const ids = flagList(args, "id");
536
+ const id = flagString(args, "id");
537
+ if (!ids.length && !id)
538
+ return fail("INVALID_REQUEST", "asset delete requires --id.");
539
+ return rpcEval(args, assetDeleteSnippet(), { ids: ids, id: id || null }, 30000);
540
+ }
541
+ return fail("UNKNOWN_COMMAND", `Unknown asset command: ${subcommand}`);
542
+ }
543
+ async function handleMaterial(args) {
544
+ const subcommand = args._[1];
545
+ if (subcommand === "create") {
546
+ const name = flagString(args, "name");
547
+ if (!name)
548
+ return fail("INVALID_REQUEST", "material create requires --name.");
549
+ const data = (await readJsonFlag(args, "json")) ??
550
+ (flagString(args, "data") ? parseJsonValue(flagString(args, "data") || "{}") : {});
551
+ return rpcEval(args, materialCreateSnippet(), {
552
+ name,
553
+ folder: flagString(args, "folder") || null,
554
+ folderId: flagString(args, "folder-id") || null,
555
+ diffuseMap: flagString(args, "diffuse-map") || null,
556
+ emissiveMap: flagString(args, "emissive-map") || null,
557
+ normalMap: flagString(args, "normal-map") || null,
558
+ data: objectJson(data, "material data"),
559
+ preload: !flagBool(args, "no-preload"),
560
+ }, 30000);
561
+ }
562
+ return fail("UNKNOWN_COMMAND", `Unknown material command: ${subcommand || ""}`);
563
+ }
564
+ async function handleScript(args) {
565
+ const subcommand = args._[1];
566
+ if (subcommand === "create") {
567
+ const filename = flagString(args, "filename") || (flagString(args, "file") ? basename(flagString(args, "file") || "") : undefined);
568
+ const file = flagString(args, "file");
569
+ if (!filename || !file) {
570
+ return fail("INVALID_REQUEST", "script create requires --filename and --file.");
571
+ }
572
+ return rpcEval(args, scriptCreateSnippet(), {
573
+ filename,
574
+ text: await readFile(file, "utf8"),
575
+ folder: flagString(args, "folder") || null,
576
+ folderId: flagString(args, "folder-id") || null,
577
+ preload: !flagBool(args, "no-preload"),
578
+ }, 60000);
579
+ }
580
+ if (subcommand === "set-text") {
581
+ const assetId = flagString(args, "asset-id");
582
+ const file = flagString(args, "file");
583
+ if (!assetId || !file) {
584
+ return fail("INVALID_REQUEST", "script set-text requires --asset-id and --file.");
585
+ }
586
+ return rpcEval(args, scriptSetTextSnippet(), {
587
+ assetId,
588
+ text: await readFile(file, "utf8"),
589
+ });
590
+ }
591
+ if (subcommand === "parse") {
592
+ const assetId = flagString(args, "asset-id");
593
+ if (!assetId)
594
+ return fail("INVALID_REQUEST", "script parse requires --asset-id.");
595
+ return rpcEval(args, scriptParseSnippet(), { assetId });
596
+ }
597
+ return fail("UNKNOWN_COMMAND", `Unknown script command: ${subcommand || ""}`);
598
+ }
599
+ async function handleViewport(args) {
600
+ const subcommand = args._[1];
601
+ if (subcommand !== "capture") {
602
+ return fail("UNKNOWN_COMMAND", `Unknown viewport command: ${subcommand || ""}`);
603
+ }
604
+ const raw = await rpcCall(args, "bridge:captureViewport", {
605
+ format: flagString(args, "format") || "png",
606
+ quality: Number(flagString(args, "quality", "0.85")),
607
+ maxWidth: Number(flagString(args, "max-width", "1200")),
608
+ });
609
+ if (!raw.ok)
610
+ return raw;
611
+ const data = raw.data;
612
+ const out = flagString(args, "out");
613
+ if (out && data.base64) {
614
+ await writeFile(out, Buffer.from(data.base64, "base64"));
615
+ return ok({
616
+ path: out,
617
+ mime: data.mime || null,
618
+ width: data.width || null,
619
+ height: data.height || null,
620
+ }, raw.meta);
621
+ }
622
+ return raw;
623
+ }
624
+ function usage() {
625
+ return ok({
626
+ usage: [
627
+ "pcbridge doctor",
628
+ "pcbridge install-extension",
629
+ "pcbridge install-skill --agent codex|claude|cursor|windsurf|all",
630
+ "pcbridge daemon start",
631
+ "pcbridge daemon status",
632
+ "pcbridge targets",
633
+ "pcbridge eval --target current --code \"return location.href\"",
634
+ "pcbridge entity list --target current",
635
+ "pcbridge asset list --target current --type script",
636
+ "pcbridge asset upload --target current --file ./texture.png --folder \"AI Agent Bridge/Textures\"",
637
+ "pcbridge material create --target current --name Mat --diffuse-map <asset_id>",
638
+ "pcbridge script create --target current --filename controller.js --file ./controller.js",
639
+ "pcbridge entity set-material --target current --id <resource_id> --material-id <asset_id>",
640
+ "pcbridge entity add-script --target current --id <resource_id> --script-name controller",
641
+ "pcbridge viewport capture --target current --out ./tmp/viewport.png",
642
+ ],
643
+ });
644
+ }
645
+ async function main() {
646
+ const args = parseArgs(process.argv.slice(2));
647
+ const command = args._[0] || "help";
648
+ if (command === "daemon") {
649
+ await daemon(args);
650
+ return;
651
+ }
652
+ try {
653
+ if (command === "help" || command === "--help" || command === "-h") {
654
+ print(usage());
655
+ }
656
+ else if (command === "doctor") {
657
+ print(await doctor());
658
+ }
659
+ else if (command === "install-extension") {
660
+ print(await installExtension(args));
661
+ }
662
+ else if (command === "install-skill") {
663
+ print(await installSkill(args));
664
+ }
665
+ else if (command === "targets") {
666
+ print(await fetchDaemon("/targets"));
667
+ }
668
+ else if (command === "eval") {
669
+ print(await rpcEval(args, await readCode(args)));
670
+ }
671
+ else if (command === "entity") {
672
+ print(await handleEntity(args));
673
+ }
674
+ else if (command === "asset") {
675
+ print(await handleAsset(args));
676
+ }
677
+ else if (command === "material") {
678
+ print(await handleMaterial(args));
679
+ }
680
+ else if (command === "script") {
681
+ print(await handleScript(args));
682
+ }
683
+ else if (command === "viewport") {
684
+ print(await handleViewport(args));
685
+ }
686
+ else if (command === "version" || command === "--version" || command === "-v") {
687
+ print(ok({ version: VERSION }));
688
+ }
689
+ else {
690
+ print(fail("UNKNOWN_COMMAND", `Unknown command: ${command}`));
691
+ process.exitCode = 1;
692
+ }
693
+ }
694
+ catch (error) {
695
+ print(fail("CLI_ERROR", error instanceof Error ? error.message : String(error)));
696
+ process.exitCode = 1;
697
+ }
698
+ }
699
+ const isMain = process.argv[1] === fileURLToPath(import.meta.url);
700
+ if (isMain) {
701
+ main();
702
+ }