playcanvas-agent-bridge-cli 0.2.2 → 0.4.2

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.
Files changed (34) hide show
  1. package/README.md +218 -52
  2. package/README.zh-CN.md +210 -51
  3. package/dist/cli.js +723 -92
  4. package/dist/config.js +6 -2
  5. package/dist/daemon/server.js +181 -19
  6. package/dist/daemon/target-registry.js +61 -3
  7. package/dist/frontend/server.js +191 -0
  8. package/dist/frontend/store.js +369 -0
  9. package/dist/shared/protocol.js +3 -1
  10. package/dist/snippets.js +764 -30
  11. package/dist/workspace/manager.js +536 -0
  12. package/extension/icons/concepts/pcbridge-bridge.png +0 -0
  13. package/extension/icons/concepts/pcbridge-cube.png +0 -0
  14. package/extension/icons/concepts/pcbridge-p-active.png +0 -0
  15. package/extension/icons/concepts/pcbridge-p-arch.png +0 -0
  16. package/extension/icons/concepts/pcbridge-p-bridge.png +0 -0
  17. package/extension/icons/concepts/pcbridge-p-emblem.png +0 -0
  18. package/extension/icons/concepts/pcbridge-signal.png +0 -0
  19. package/extension/icons/icon-128.png +0 -0
  20. package/extension/icons/icon-16.png +0 -0
  21. package/extension/icons/icon-32.png +0 -0
  22. package/extension/icons/icon-48.png +0 -0
  23. package/extension/isolated.js +214 -43
  24. package/extension/main.js +619 -32
  25. package/extension/manifest.json +29 -7
  26. package/extension/popup.html +188 -24
  27. package/extension/popup.js +199 -10
  28. package/extension/service-worker.js +268 -17
  29. package/package.json +4 -1
  30. package/skills/claude/playcanvas-agent-bridge-cli/SKILL.md +97 -24
  31. package/skills/codex/playcanvas-agent-bridge-cli/SKILL.md +167 -52
  32. package/skills/codex/playcanvas-agent-bridge-cli/agents/openai.yaml +2 -2
  33. package/skills/cursor/playcanvas-agent-bridge-cli.mdc +63 -23
  34. package/skills/windsurf/playcanvas-agent-bridge-cli.md +61 -23
package/dist/cli.js CHANGED
@@ -3,11 +3,12 @@ import { spawn } from "node:child_process";
3
3
  import { realpathSync } from "node:fs";
4
4
  import { readFile, writeFile, mkdir } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
- import { basename, dirname, extname, join } from "node:path";
6
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
- import { CONFIG_DIR, DEFAULT_HOST, DEFAULT_PORT, EXTENSION_INSTALL_DIR, VERSION, copyDir, findPackageRoot, readOrCreateSession, readSessionIfExists, } from "./config.js";
8
+ import { CONFIG_DIR, DEFAULT_FRONTEND_PORT, DEFAULT_HOST, DEFAULT_PORT, EXTENSION_INSTALL_DIR, VERSION, copyDir, findPackageRoot, readOrCreateSession, readSessionIfExists, } from "./config.js";
9
9
  import { createDaemonServer } from "./daemon/server.js";
10
- import { assetDeleteSnippet, assetFolderEnsureSnippet, assetCreateManySnippet, assetGetSnippet, assetInstantiateTemplateSnippet, assetListSnippet, entityAddComponentsSnippet, entityAddComponentSnippet, entityAddScriptSnippet, entityCreateManySnippet, entityCreateSnippet, entityDeleteSnippet, entityDuplicateSnippet, entityGetSnippet, entityListSnippet, entityPatchManySnippet, entityPatchSnippet, entityReparentSnippet, entityRemoveComponentsSnippet, entityRemoveComponentSnippet, entitySetMaterialSnippet, materialCreateSnippet, materialPatchSnippet, sceneSettingsGetSnippet, sceneSettingsPatchSnippet, scriptCreateSnippet, scriptParseSnippet, scriptSetTextSnippet, storeDownloadSnippet, storeGetSnippet, storeSearchSnippet, templateCreateSnippet, } from "./snippets.js";
10
+ import { FrontendError, getFrontendStatus, installFrontend, listFrontends, removeFrontend, useFrontend, } from "./frontend/store.js";
11
+ import { assetDeleteSnippet, assetFolderEnsureSnippet, assetCreateManySnippet, assetGetSnippet, assetInstantiateTemplateSnippet, assetListSnippet, entityAddComponentsSnippet, entityAddComponentSnippet, entityAddScriptSnippet, entityCreateManySnippet, entityCreateSnippet, entityDeleteSnippet, entityDuplicateSnippet, entityGetSnippet, entityListSnippet, entityPatchManySnippet, entityPatchSnippet, entityReparentSnippet, entityRemoveComponentsSnippet, entityRemoveComponentSnippet, entitySetMaterialSnippet, materialCreateSnippet, materialPatchSnippet, sceneSettingsGetSnippet, sceneSettingsPatchSnippet, scriptCreateSnippet, scriptParseSnippet, scriptSetTextSnippet, scriptUpsertSnippet, storeDownloadSnippet, storeGetSnippet, storeSearchSnippet, templateApplySnippet, templateCreateSnippet, templateOverridesSnippet, } from "./snippets.js";
11
12
  import { fail, ok } from "./shared/protocol.js";
12
13
  function parseArgs(argv) {
13
14
  const parsed = { _: [], flags: {} };
@@ -67,6 +68,53 @@ function flagList(args, name) {
67
68
  }
68
69
  function print(value) {
69
70
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
71
+ if (!value.ok)
72
+ process.exitCode = 1;
73
+ }
74
+ function nestedErrorCode(error) {
75
+ if (!error || typeof error !== "object")
76
+ return undefined;
77
+ const candidate = error;
78
+ if (typeof candidate.code === "string")
79
+ return candidate.code;
80
+ return nestedErrorCode(candidate.cause);
81
+ }
82
+ export function diagnoseDaemonConnection(error, port = DEFAULT_PORT) {
83
+ const code = nestedErrorCode(error) || "DAEMON_UNREACHABLE";
84
+ if (code === "EACCES" || code === "EPERM") {
85
+ return {
86
+ code: "LOOPBACK_ACCESS_DENIED",
87
+ message: `Daemon may be running, but this process cannot access ${DEFAULT_HOST}:${port}.`,
88
+ nextAction: "Retry from an execution context with local-loopback permission.",
89
+ };
90
+ }
91
+ if (code === "ECONNREFUSED") {
92
+ return {
93
+ code: "DAEMON_NOT_LISTENING",
94
+ message: `No pcbridge daemon is listening on ${DEFAULT_HOST}:${port}.`,
95
+ nextAction: "Run pcbridge daemon start in a terminal.",
96
+ };
97
+ }
98
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
99
+ return {
100
+ code: "DAEMON_HOST_UNRESOLVED",
101
+ message: `The configured pcbridge daemon host could not be resolved (${code}).`,
102
+ nextAction: "Check the generated pcbridge session configuration.",
103
+ };
104
+ }
105
+ return {
106
+ code: "DAEMON_UNREACHABLE",
107
+ message: `The pcbridge daemon is not reachable (${code}).`,
108
+ nextAction: "Check pcbridge daemon status, then start it if no listener is running.",
109
+ };
110
+ }
111
+ class DaemonConnectionError extends Error {
112
+ diagnosis;
113
+ constructor(diagnosis, cause) {
114
+ super(diagnosis.message, { cause });
115
+ this.name = "DaemonConnectionError";
116
+ this.diagnosis = diagnosis;
117
+ }
70
118
  }
71
119
  async function readStdin() {
72
120
  const chunks = [];
@@ -81,7 +129,7 @@ async function readCode(args) {
81
129
  if (code !== undefined)
82
130
  return code;
83
131
  if (file)
84
- return readFile(file, "utf8");
132
+ return readFile(await resolveWorkspaceFile(args, file, "eval file"), "utf8");
85
133
  if (flagBool(args, "stdin"))
86
134
  return readStdin();
87
135
  throw new Error("Provide --code, --file, or --stdin.");
@@ -108,19 +156,74 @@ function parseSets(values) {
108
156
  }
109
157
  async function fetchDaemon(path, init = {}) {
110
158
  const session = await readOrCreateSession();
111
- const response = await fetch(`http://${DEFAULT_HOST}:${session.port || DEFAULT_PORT}${path}`, {
112
- ...init,
113
- headers: {
114
- "Content-Type": "application/json",
115
- "X-PCBridge-Token": session.token,
116
- ...(init.headers || {}),
117
- },
118
- });
119
- const body = (await response.json());
120
- return body;
159
+ const port = session.port || DEFAULT_PORT;
160
+ let response;
161
+ try {
162
+ response = await fetch(`http://${DEFAULT_HOST}:${port}${path}`, {
163
+ ...init,
164
+ headers: {
165
+ "Content-Type": "application/json",
166
+ "X-PCBridge-Token": session.token,
167
+ ...(init.headers || {}),
168
+ },
169
+ });
170
+ }
171
+ catch (error) {
172
+ throw new DaemonConnectionError(diagnoseDaemonConnection(error, port), error);
173
+ }
174
+ try {
175
+ return (await response.json());
176
+ }
177
+ catch {
178
+ return fail("DAEMON_INVALID_RESPONSE", `pcbridge daemon returned a non-JSON response (HTTP ${response.status}).`, undefined, { status: response.status, path });
179
+ }
180
+ }
181
+ async function resolveWorkspaceFile(args, path, label) {
182
+ const resolvedPath = resolve(path);
183
+ if (flagBool(args, "allow-external-path"))
184
+ return resolvedPath;
185
+ const target = flagString(args, "target", "current") || "current";
186
+ const response = await fetchDaemon(`/workspace/status?target=${encodeURIComponent(target)}`);
187
+ if (!response.ok)
188
+ throw new Error(response.error.message);
189
+ const status = objectJson(response.data, "workspace status");
190
+ const projectDirectory = typeof status.projectDirectory === "string"
191
+ ? resolve(status.projectDirectory)
192
+ : null;
193
+ if (!projectDirectory) {
194
+ throw new Error(`${label} requires an initialized project workspace. ` +
195
+ "Use --allow-external-path only for an intentional external file.");
196
+ }
197
+ let checkedPath = resolvedPath;
198
+ try {
199
+ checkedPath = realpathSync(resolvedPath);
200
+ }
201
+ catch {
202
+ let ancestor = dirname(resolvedPath);
203
+ while (ancestor !== dirname(ancestor)) {
204
+ try {
205
+ const realAncestor = realpathSync(ancestor);
206
+ checkedPath = resolve(realAncestor, relative(ancestor, resolvedPath));
207
+ break;
208
+ }
209
+ catch {
210
+ ancestor = dirname(ancestor);
211
+ }
212
+ }
213
+ }
214
+ const checkedProject = realpathSync(projectDirectory);
215
+ if (checkedPath !== checkedProject && !checkedPath.startsWith(`${checkedProject}${sep}`)) {
216
+ throw new Error(`${label} must be inside ${checkedProject}. ` +
217
+ "Use --allow-external-path to override this workspace guard.");
218
+ }
219
+ return resolvedPath;
121
220
  }
122
- async function rpcCall(args, method, params = {}, defaultTimeoutMs = 15000) {
123
- const timeoutMs = Number(flagString(args, "timeout-ms", String(defaultTimeoutMs)));
221
+ async function rpcCall(args, method, params = {}, defaultTimeoutMs = 15000, honorTimeoutFlag = true) {
222
+ const timeoutMs = honorTimeoutFlag
223
+ ? readTimeoutMs(args, defaultTimeoutMs)
224
+ : defaultTimeoutMs;
225
+ if (timeoutMs === null)
226
+ return invalidTimeoutEnvelope();
124
227
  return fetchDaemon("/rpc", {
125
228
  method: "POST",
126
229
  body: JSON.stringify({
@@ -134,10 +237,35 @@ async function rpcCall(args, method, params = {}, defaultTimeoutMs = 15000) {
134
237
  }),
135
238
  });
136
239
  }
240
+ function readTimeoutMs(args, defaultTimeoutMs) {
241
+ const value = Number(flagString(args, "timeout-ms", String(defaultTimeoutMs)));
242
+ return Number.isInteger(value) && value >= 1000 && value <= 120000 ? value : null;
243
+ }
244
+ function invalidTimeoutEnvelope() {
245
+ return fail("INVALID_REQUEST", "--timeout-ms must be an integer from 1000 to 120000.");
246
+ }
137
247
  async function rpcEval(args, code, commandArgs = {}, defaultTimeoutMs = 15000) {
248
+ const serializeOptions = {};
249
+ const optionFlags = [
250
+ ["max-depth", "maxDepth", 1, 20],
251
+ ["max-items", "maxArray", 1, 5000],
252
+ ["max-keys", "maxKeys", 1, 2000],
253
+ ["max-string", "maxString", 1, 100000],
254
+ ];
255
+ for (const [flag, key, minimum, maximum] of optionFlags) {
256
+ const raw = flagString(args, flag);
257
+ if (raw === undefined)
258
+ continue;
259
+ const value = Number(raw);
260
+ if (!Number.isInteger(value) || value < minimum || value > maximum) {
261
+ return fail("INVALID_REQUEST", `--${flag} must be an integer from ${minimum} to ${maximum}.`);
262
+ }
263
+ serializeOptions[key] = value;
264
+ }
138
265
  return rpcCall(args, "bridge:eval", {
139
266
  code,
140
267
  args: commandArgs,
268
+ serializeOptions: serializeOptions,
141
269
  }, defaultTimeoutMs);
142
270
  }
143
271
  function listEnvelope(raw) {
@@ -200,7 +328,8 @@ async function readJsonFlag(args, flagName) {
200
328
  const file = flagString(args, flagName);
201
329
  if (!file)
202
330
  return undefined;
203
- return JSON.parse(await readFile(file, "utf8"));
331
+ const path = await resolveWorkspaceFile(args, file, `--${flagName}`);
332
+ return JSON.parse(await readFile(path, "utf8"));
204
333
  }
205
334
  function objectJson(value, label) {
206
335
  if (value === undefined || value === null)
@@ -210,11 +339,54 @@ function objectJson(value, label) {
210
339
  }
211
340
  return value;
212
341
  }
342
+ function uploadSpecFromJson(value, label) {
343
+ const data = objectJson(value, label);
344
+ const file = typeof data.file === "string" ? data.file : "";
345
+ if (!file) {
346
+ throw new Error(`${label}.file is required.`);
347
+ }
348
+ return {
349
+ key: typeof data.key === "string" ? data.key : undefined,
350
+ file,
351
+ name: typeof data.name === "string" ? data.name : undefined,
352
+ filename: typeof data.filename === "string" ? data.filename : undefined,
353
+ type: typeof data.type === "string" ? data.type : undefined,
354
+ mime: typeof data.mime === "string" ? data.mime : undefined,
355
+ folder: typeof data.folder === "string" ? data.folder : undefined,
356
+ folderId: typeof data.folderId === "string" || typeof data.folderId === "number"
357
+ ? String(data.folderId)
358
+ : undefined,
359
+ preload: typeof data.preload === "boolean" ? data.preload : undefined,
360
+ };
361
+ }
362
+ function resolveManifestFile(manifestPath, file) {
363
+ return isAbsolute(file) ? file : resolve(dirname(manifestPath), file);
364
+ }
365
+ async function uploadAsset(args, spec) {
366
+ spec.file = await resolveWorkspaceFile(args, spec.file, "asset upload file");
367
+ const fileBuffer = await readFile(spec.file);
368
+ const type = spec.type || inferAssetType(spec.file);
369
+ if (!type)
370
+ return fail("INVALID_REQUEST", `asset upload requires --type for ${spec.file}.`);
371
+ const filename = spec.filename || basename(spec.file);
372
+ return rpcCall(args, "bridge:uploadAsset", {
373
+ base64: fileBuffer.toString("base64"),
374
+ mime: spec.mime || inferMime(spec.file),
375
+ name: spec.name || nameFromFile(spec.file),
376
+ filename,
377
+ type,
378
+ folder: spec.folder || null,
379
+ folderId: spec.folderId || null,
380
+ preload: spec.preload !== false,
381
+ }, 120000);
382
+ }
213
383
  async function doctor() {
214
384
  const session = await readSessionIfExists();
215
385
  const checks = [];
216
386
  const nextActions = [];
217
387
  const major = Number(process.versions.node.split(".", 1)[0]);
388
+ let daemonOk = false;
389
+ let connectedExtensionVersionsOk = true;
218
390
  checks.push({
219
391
  name: "node",
220
392
  ok: major >= 20,
@@ -226,20 +398,55 @@ async function doctor() {
226
398
  }
227
399
  try {
228
400
  const health = await fetchDaemon("/health");
401
+ const daemonData = health.ok ? objectJson(health.data, "daemon health") : null;
402
+ const daemonVersion = daemonData && typeof daemonData.version === "string"
403
+ ? daemonData.version
404
+ : null;
405
+ daemonOk = health.ok && daemonVersion === VERSION;
229
406
  checks.push({
230
407
  name: "daemon",
231
- ok: health.ok,
232
- message: health.ok ? "Daemon is reachable." : health.error.message,
408
+ ok: daemonOk,
409
+ code: health.ok ? null : health.error.code,
410
+ version: daemonVersion,
411
+ expectedVersion: VERSION,
412
+ message: !health.ok
413
+ ? health.error.message
414
+ : daemonVersion === VERSION
415
+ ? "Daemon is reachable and matches the CLI version."
416
+ : "Daemon is reachable but its version does not match the CLI.",
233
417
  data: health.ok ? health.data : null,
234
418
  });
419
+ if (!health.ok && health.error.code === "BAD_TOKEN") {
420
+ nextActions.push("Stop the stale daemon, start it again with this pcbridge install, then regenerate/reload the extension.");
421
+ }
422
+ else if (health.ok && daemonVersion !== VERSION) {
423
+ nextActions.push("Restart the daemon with the same pcbridge version as this CLI.");
424
+ }
235
425
  }
236
426
  catch (error) {
427
+ const diagnosis = error instanceof DaemonConnectionError
428
+ ? error.diagnosis
429
+ : diagnoseDaemonConnection(error);
237
430
  checks.push({
238
431
  name: "daemon",
239
432
  ok: false,
240
- message: "Daemon is not reachable.",
433
+ code: diagnosis.code,
434
+ message: diagnosis.message,
241
435
  });
242
- nextActions.push("Run pcbridge daemon start in a terminal.");
436
+ nextActions.push(diagnosis.nextAction);
437
+ }
438
+ const frontend = await getFrontendStatus();
439
+ checks.push({
440
+ name: "frontend",
441
+ ok: frontend.ready,
442
+ activeRelease: frontend.activeRelease,
443
+ installedCount: frontend.installed.length,
444
+ message: frontend.ready
445
+ ? `Frontend ${frontend.activeRelease} is ready.`
446
+ : "No active custom Editor frontend is installed.",
447
+ });
448
+ if (!frontend.ready) {
449
+ nextActions.push("Run pcbridge frontend install latest.");
243
450
  }
244
451
  const extensionExists = Boolean(session) && (await pathExists(EXTENSION_INSTALL_DIR));
245
452
  let generatedExtensionVersion = null;
@@ -277,17 +484,18 @@ async function doctor() {
277
484
  .map((target) => (target && typeof target === "object" && !Array.isArray(target) ? target.extensionVersion : null))
278
485
  .filter(Boolean);
279
486
  const mismatched = connectedVersions.filter((version) => version !== VERSION);
487
+ connectedExtensionVersionsOk = mismatched.length === 0;
280
488
  checks.push({
281
489
  name: "connected-extension-version",
282
490
  ok: mismatched.length === 0,
283
491
  versions: connectedVersions,
284
492
  expectedVersion: VERSION,
285
493
  message: mismatched.length
286
- ? "One or more connected Editor tabs are using an older extension version."
494
+ ? "One or more connected PlayCanvas tabs are using an older extension version."
287
495
  : "Connected extension versions match the package version.",
288
496
  });
289
497
  if (mismatched.length) {
290
- nextActions.push("Reload the unpacked extension and refresh the PlayCanvas Editor tab.");
498
+ nextActions.push("Reload the unpacked extension and refresh the PlayCanvas Editor or Launch tab.");
291
499
  }
292
500
  }
293
501
  }
@@ -296,6 +504,11 @@ async function doctor() {
296
504
  }
297
505
  return ok({
298
506
  version: VERSION,
507
+ healthy: major >= 20 &&
508
+ daemonOk &&
509
+ extensionExists &&
510
+ generatedExtensionVersion === VERSION &&
511
+ connectedExtensionVersionsOk,
299
512
  configDir: CONFIG_DIR,
300
513
  checks,
301
514
  nextActions,
@@ -318,6 +531,7 @@ async function daemon(args) {
318
531
  host: DEFAULT_HOST,
319
532
  port: session.port || DEFAULT_PORT,
320
533
  token: session.token,
534
+ workspaceRoot: process.cwd(),
321
535
  log: (message) => {
322
536
  if (flagBool(args, "json")) {
323
537
  process.stderr.write(`${JSON.stringify({ time: new Date().toISOString(), message })}\n`);
@@ -339,7 +553,9 @@ async function daemon(args) {
339
553
  version: VERSION,
340
554
  host: DEFAULT_HOST,
341
555
  port: session.port || DEFAULT_PORT,
556
+ workspaceRoot: process.cwd(),
342
557
  extensionPath: EXTENSION_INSTALL_DIR,
558
+ frontend: await server.frontend.status(),
343
559
  }));
344
560
  }
345
561
  else if (subcommand === "status") {
@@ -356,6 +572,70 @@ async function daemon(args) {
356
572
  process.exitCode = 1;
357
573
  }
358
574
  }
575
+ async function handleFrontend(args) {
576
+ const subcommand = args._[1] || "status";
577
+ try {
578
+ if (subcommand === "install" || subcommand === "update") {
579
+ const requestedRelease = subcommand === "update" ? "latest" : args._[2] || "latest";
580
+ const installed = await installFrontend(requestedRelease, {
581
+ activate: !flagBool(args, "no-activate"),
582
+ });
583
+ const status = await getFrontendStatus();
584
+ return ok({
585
+ release: installed.manifest.release,
586
+ editorVersion: installed.manifest.editorVersion,
587
+ sourceCommit: installed.manifest.sourceCommit,
588
+ path: installed.path,
589
+ alreadyInstalled: installed.alreadyInstalled,
590
+ active: status.activeRelease === installed.manifest.release,
591
+ nextActions: [
592
+ "Run pcbridge daemon start if it is not already running.",
593
+ "Use the extension popup on a playcanvas.com Editor tab to select the custom frontend.",
594
+ ],
595
+ });
596
+ }
597
+ if (subcommand === "list") {
598
+ return ok(await listFrontends());
599
+ }
600
+ if (subcommand === "status") {
601
+ try {
602
+ return await fetchDaemon("/frontend/status");
603
+ }
604
+ catch {
605
+ return ok({
606
+ ...(await getFrontendStatus()),
607
+ server: {
608
+ host: DEFAULT_HOST,
609
+ port: DEFAULT_FRONTEND_PORT,
610
+ listening: false,
611
+ error: "Daemon is not reachable.",
612
+ },
613
+ });
614
+ }
615
+ }
616
+ if (subcommand === "use") {
617
+ const release = args._[2];
618
+ if (!release) {
619
+ return fail("INVALID_REQUEST", "frontend use requires a release name.");
620
+ }
621
+ return ok(await useFrontend(release));
622
+ }
623
+ if (subcommand === "remove") {
624
+ const release = args._[2];
625
+ if (!release) {
626
+ return fail("INVALID_REQUEST", "frontend remove requires a release name.");
627
+ }
628
+ return ok(await removeFrontend(release));
629
+ }
630
+ return fail("UNKNOWN_COMMAND", `Unknown frontend command: ${subcommand}`);
631
+ }
632
+ catch (error) {
633
+ if (error instanceof FrontendError) {
634
+ return fail(error.code, error.message);
635
+ }
636
+ throw error;
637
+ }
638
+ }
359
639
  async function installExtension(args) {
360
640
  const session = await readOrCreateSession();
361
641
  const root = await findPackageRoot();
@@ -379,7 +659,7 @@ async function installExtension(args) {
379
659
  "Enable Developer Mode in Chrome.",
380
660
  "Click Load unpacked.",
381
661
  `Select ${EXTENSION_INSTALL_DIR}.`,
382
- "Open or refresh a PlayCanvas Editor tab, then run pcbridge daemon start.",
662
+ "Open or refresh a PlayCanvas Editor or Launch tab, then run pcbridge daemon start.",
383
663
  ],
384
664
  });
385
665
  }
@@ -464,14 +744,14 @@ async function handleEntity(args) {
464
744
  const file = flagString(args, "json");
465
745
  if (!file)
466
746
  return fail("INVALID_REQUEST", "entity create requires --json <file>.");
467
- const data = JSON.parse(await readFile(file, "utf8"));
747
+ const data = JSON.parse(await readFile(await resolveWorkspaceFile(args, file, "entity JSON"), "utf8"));
468
748
  return rpcEval(args, entityCreateSnippet(), { data });
469
749
  }
470
750
  if (subcommand === "create-many") {
471
751
  const file = flagString(args, "json");
472
752
  if (!file)
473
753
  return fail("INVALID_REQUEST", "entity create-many requires --json <file>.");
474
- const data = JSON.parse(await readFile(file, "utf8"));
754
+ const data = JSON.parse(await readFile(await resolveWorkspaceFile(args, file, "entity JSON"), "utf8"));
475
755
  const entities = Array.isArray(data)
476
756
  ? data
477
757
  : objectJson(data, "entity create-many data").entities;
@@ -487,7 +767,7 @@ async function handleEntity(args) {
487
767
  const file = flagString(args, "json");
488
768
  if (!file)
489
769
  return fail("INVALID_REQUEST", "entity patch-many requires --json <file>.");
490
- const data = JSON.parse(await readFile(file, "utf8"));
770
+ const data = JSON.parse(await readFile(await resolveWorkspaceFile(args, file, "entity JSON"), "utf8"));
491
771
  const edits = Array.isArray(data)
492
772
  ? data
493
773
  : objectJson(data, "entity patch-many data").edits;
@@ -592,12 +872,17 @@ async function handleEntity(args) {
592
872
  const id = flagString(args, "id");
593
873
  if (!id)
594
874
  return fail("INVALID_REQUEST", "entity add-script requires --id.");
875
+ const scriptName = flagString(args, "script-name");
876
+ const assetId = flagString(args, "asset-id");
877
+ if (Boolean(scriptName) === Boolean(assetId)) {
878
+ return fail("INVALID_REQUEST", "entity add-script requires exactly one of --asset-id or --script-name.");
879
+ }
595
880
  const attributes = (await readJsonFlag(args, "attributes-json")) ??
596
881
  (flagString(args, "attributes") ? parseJsonValue(flagString(args, "attributes") || "{}") : {});
597
882
  return rpcEval(args, entityAddScriptSnippet(), {
598
883
  id,
599
- scriptName: flagString(args, "script-name") || null,
600
- assetId: flagString(args, "asset-id") || null,
884
+ scriptName: scriptName || null,
885
+ assetId: assetId || null,
601
886
  attributes: objectJson(attributes, "script attributes"),
602
887
  enabled: !flagBool(args, "disabled"),
603
888
  });
@@ -626,7 +911,7 @@ async function handleAsset(args) {
626
911
  const file = flagString(args, "json");
627
912
  if (!file)
628
913
  return fail("INVALID_REQUEST", "asset create requires --json <file>.");
629
- const data = JSON.parse(await readFile(file, "utf8"));
914
+ const data = JSON.parse(await readFile(await resolveWorkspaceFile(args, file, "asset JSON"), "utf8"));
630
915
  const assets = Array.isArray(data)
631
916
  ? data
632
917
  : objectJson(data, "asset create data").assets || [data];
@@ -652,21 +937,64 @@ async function handleAsset(args) {
652
937
  const file = flagString(args, "file");
653
938
  if (!file)
654
939
  return fail("INVALID_REQUEST", "asset upload requires --file.");
655
- const fileBuffer = await readFile(file);
656
- const type = flagString(args, "type") || inferAssetType(file);
657
- if (!type)
658
- return fail("INVALID_REQUEST", "asset upload requires --type for this file.");
659
- const filename = flagString(args, "filename") || basename(file);
660
- return rpcCall(args, "bridge:uploadAsset", {
661
- base64: fileBuffer.toString("base64"),
662
- mime: flagString(args, "mime") || inferMime(file),
663
- name: flagString(args, "name") || nameFromFile(file),
664
- filename,
665
- type,
666
- folder: flagString(args, "folder") || null,
667
- folderId: flagString(args, "folder-id") || null,
940
+ return uploadAsset(args, {
941
+ file,
942
+ type: flagString(args, "type"),
943
+ mime: flagString(args, "mime"),
944
+ name: flagString(args, "name"),
945
+ filename: flagString(args, "filename"),
946
+ folder: flagString(args, "folder"),
947
+ folderId: flagString(args, "folder-id"),
668
948
  preload: !flagBool(args, "no-preload"),
669
- }, 120000);
949
+ });
950
+ }
951
+ if (subcommand === "upload-many") {
952
+ const manifestPath = flagString(args, "json");
953
+ if (!manifestPath)
954
+ return fail("INVALID_REQUEST", "asset upload-many requires --json <file>.");
955
+ const safeManifestPath = await resolveWorkspaceFile(args, manifestPath, "upload manifest");
956
+ const manifest = JSON.parse(await readFile(safeManifestPath, "utf8"));
957
+ const rawItems = Array.isArray(manifest)
958
+ ? manifest
959
+ : objectJson(manifest, "asset upload-many manifest").assets;
960
+ const items = Array.isArray(rawItems) ? rawItems : [];
961
+ if (!items.length) {
962
+ return fail("INVALID_REQUEST", "asset upload-many manifest must contain a non-empty assets array.");
963
+ }
964
+ const uploads = [];
965
+ const errors = [];
966
+ for (let index = 0; index < items.length; index += 1) {
967
+ const spec = uploadSpecFromJson(items[index], `assets[${index}]`);
968
+ spec.file = resolveManifestFile(safeManifestPath, spec.file);
969
+ const result = await uploadAsset(args, spec);
970
+ uploads.push({
971
+ index,
972
+ key: spec.key || null,
973
+ file: spec.file,
974
+ name: spec.name || nameFromFile(spec.file),
975
+ result: result,
976
+ });
977
+ if (!result.ok) {
978
+ errors.push({
979
+ index,
980
+ file: spec.file,
981
+ error: result.error,
982
+ });
983
+ }
984
+ }
985
+ if (errors.length) {
986
+ return fail("UPLOAD_MANY_FAILED", `${errors.length} of ${items.length} uploads failed.`, {
987
+ affected: items.length - errors.length,
988
+ failed: errors.length,
989
+ }, { uploads, errors });
990
+ }
991
+ return ok({
992
+ affected: uploads.length,
993
+ uploads,
994
+ }, {
995
+ affected: uploads.length,
996
+ failed: 0,
997
+ });
670
998
  }
671
999
  if (subcommand === "delete") {
672
1000
  const ids = flagList(args, "id");
@@ -745,10 +1073,76 @@ async function handleTemplate(args) {
745
1073
  id: id || null,
746
1074
  }, 60000);
747
1075
  }
1076
+ if (subcommand === "overrides") {
1077
+ const entityId = flagString(args, "entity-id") || flagString(args, "id");
1078
+ if (!entityId)
1079
+ return fail("INVALID_REQUEST", "template overrides requires --entity-id.");
1080
+ return rpcEval(args, templateOverridesSnippet(), { entityId });
1081
+ }
1082
+ if (subcommand === "apply") {
1083
+ const entityId = flagString(args, "entity-id") || flagString(args, "id");
1084
+ if (!entityId)
1085
+ return fail("INVALID_REQUEST", "template apply requires --entity-id.");
1086
+ const waitTimeoutMs = readTimeoutMs(args, 60000);
1087
+ if (waitTimeoutMs === null)
1088
+ return invalidTimeoutEnvelope();
1089
+ return rpcEval(args, templateApplySnippet(), {
1090
+ entityId,
1091
+ waitTimeoutMs,
1092
+ }, 60000);
1093
+ }
1094
+ if (subcommand === "apply-many") {
1095
+ const input = await readJsonFlag(args, "json");
1096
+ if (input === undefined) {
1097
+ return fail("INVALID_REQUEST", "template apply-many requires --json <file>.");
1098
+ }
1099
+ const values = Array.isArray(input)
1100
+ ? input
1101
+ : Array.isArray(objectJson(input, "template apply manifest").entityIds)
1102
+ ? objectJson(input, "template apply manifest").entityIds
1103
+ : [];
1104
+ const entityIds = values.map((value) => {
1105
+ if (typeof value === "string" || typeof value === "number")
1106
+ return String(value);
1107
+ const item = objectJson(value, "template apply item");
1108
+ const id = item.entityId ?? item.id;
1109
+ return typeof id === "string" || typeof id === "number" ? String(id) : "";
1110
+ }).filter(Boolean);
1111
+ if (!entityIds.length) {
1112
+ return fail("INVALID_REQUEST", "template apply-many JSON must be an array of entity ids/items or {\"entityIds\":[...] }.");
1113
+ }
1114
+ const waitTimeoutMs = readTimeoutMs(args, 120000);
1115
+ if (waitTimeoutMs === null)
1116
+ return invalidTimeoutEnvelope();
1117
+ return rpcEval(args, templateApplySnippet(), {
1118
+ entityIds: entityIds,
1119
+ waitTimeoutMs,
1120
+ }, 120000);
1121
+ }
748
1122
  return fail("UNKNOWN_COMMAND", `Unknown template command: ${subcommand || ""}`);
749
1123
  }
750
1124
  async function handleScript(args) {
751
1125
  const subcommand = args._[1];
1126
+ if (subcommand === "upsert") {
1127
+ const filename = flagString(args, "filename") || (flagString(args, "file") ? basename(flagString(args, "file") || "") : undefined);
1128
+ const file = flagString(args, "file");
1129
+ if (!filename || !file) {
1130
+ return fail("INVALID_REQUEST", "script upsert requires --filename and --file.");
1131
+ }
1132
+ const waitTimeoutMs = readTimeoutMs(args, 60000);
1133
+ if (waitTimeoutMs === null)
1134
+ return invalidTimeoutEnvelope();
1135
+ return rpcEval(args, scriptUpsertSnippet(), {
1136
+ filename,
1137
+ text: await readFile(await resolveWorkspaceFile(args, file, "script file"), "utf8"),
1138
+ folder: flagString(args, "folder") || null,
1139
+ folderId: flagString(args, "folder-id") || null,
1140
+ preload: !flagBool(args, "no-preload"),
1141
+ parse: flagBool(args, "parse"),
1142
+ wait: flagBool(args, "wait"),
1143
+ waitTimeoutMs,
1144
+ }, 60000);
1145
+ }
752
1146
  if (subcommand === "create") {
753
1147
  const filename = flagString(args, "filename") || (flagString(args, "file") ? basename(flagString(args, "file") || "") : undefined);
754
1148
  const file = flagString(args, "file");
@@ -757,7 +1151,7 @@ async function handleScript(args) {
757
1151
  }
758
1152
  return rpcEval(args, scriptCreateSnippet(), {
759
1153
  filename,
760
- text: await readFile(file, "utf8"),
1154
+ text: await readFile(await resolveWorkspaceFile(args, file, "script file"), "utf8"),
761
1155
  folder: flagString(args, "folder") || null,
762
1156
  folderId: flagString(args, "folder-id") || null,
763
1157
  preload: !flagBool(args, "no-preload"),
@@ -769,16 +1163,26 @@ async function handleScript(args) {
769
1163
  if (!assetId || !file) {
770
1164
  return fail("INVALID_REQUEST", "script set-text requires --asset-id and --file.");
771
1165
  }
1166
+ const waitTimeoutMs = readTimeoutMs(args, 60000);
1167
+ if (waitTimeoutMs === null)
1168
+ return invalidTimeoutEnvelope();
772
1169
  return rpcEval(args, scriptSetTextSnippet(), {
773
1170
  assetId,
774
- text: await readFile(file, "utf8"),
775
- });
1171
+ filename: basename(file),
1172
+ text: await readFile(await resolveWorkspaceFile(args, file, "script file"), "utf8"),
1173
+ parse: flagBool(args, "parse"),
1174
+ wait: flagBool(args, "wait"),
1175
+ waitTimeoutMs,
1176
+ }, 60000);
776
1177
  }
777
1178
  if (subcommand === "parse") {
778
1179
  const assetId = flagString(args, "asset-id");
779
1180
  if (!assetId)
780
1181
  return fail("INVALID_REQUEST", "script parse requires --asset-id.");
781
- return rpcEval(args, scriptParseSnippet(), { assetId });
1182
+ const waitTimeoutMs = readTimeoutMs(args, 60000);
1183
+ if (waitTimeoutMs === null)
1184
+ return invalidTimeoutEnvelope();
1185
+ return rpcEval(args, scriptParseSnippet(), { assetId, waitTimeoutMs }, 60000);
782
1186
  }
783
1187
  return fail("UNKNOWN_COMMAND", `Unknown script command: ${subcommand || ""}`);
784
1188
  }
@@ -835,6 +1239,94 @@ async function handleStore(args) {
835
1239
  }
836
1240
  return fail("UNKNOWN_COMMAND", `Unknown store command: ${subcommand}`);
837
1241
  }
1242
+ async function handleTarget(args) {
1243
+ const subcommand = args._[1];
1244
+ if (subcommand === "focus") {
1245
+ if (!flagString(args, "target")) {
1246
+ return fail("INVALID_REQUEST", "target focus requires an explicit --target selector.");
1247
+ }
1248
+ return rpcCall(args, "bridge:focusTarget");
1249
+ }
1250
+ return fail("UNKNOWN_COMMAND", `Unknown target command: ${subcommand || ""}`);
1251
+ }
1252
+ function launchReadinessSuggestions(data) {
1253
+ const blockers = Array.isArray(data.readinessBlockers)
1254
+ ? data.readinessBlockers.map(String)
1255
+ : [];
1256
+ const suggestions = [];
1257
+ if (blockers.includes("tab-hidden")) {
1258
+ suggestions.push("Run pcbridge target focus with the same --target selector.");
1259
+ }
1260
+ if (blockers.includes("runtime-not-created") ||
1261
+ blockers.includes("runtime-not-started") ||
1262
+ blockers.includes("graphics-not-ready") ||
1263
+ blockers.includes("scene-not-loaded")) {
1264
+ suggestions.push("Focus the Launch tab and wait; refresh it if the state remains unchanged.");
1265
+ }
1266
+ if (blockers.includes("graphics-context-lost")) {
1267
+ suggestions.push("Refresh the Launch tab to recreate its graphics context.");
1268
+ }
1269
+ if (blockers.includes("splash-visible")) {
1270
+ suggestions.push("Wait for the PlayCanvas startup splash to finish.");
1271
+ }
1272
+ return suggestions;
1273
+ }
1274
+ async function diagnoseLaunch(args, pollTimeoutMs = 3000) {
1275
+ const raw = await rpcCall(args, "bridge:describeTarget", {}, pollTimeoutMs, false);
1276
+ if (!raw.ok)
1277
+ return raw;
1278
+ const data = objectJson(raw.data, "Launch target status");
1279
+ if (data.kind !== "launch") {
1280
+ return fail("INVALID_TARGET_KIND", `Selected target is ${String(data.kind || "unknown")}; choose launch:<sceneId> or a Launch tab:<id>.`, raw.meta, raw.data);
1281
+ }
1282
+ return ok({
1283
+ ...data,
1284
+ suggestions: launchReadinessSuggestions(data),
1285
+ }, raw.meta);
1286
+ }
1287
+ async function handleLaunch(args) {
1288
+ const subcommand = args._[1] || "diagnose";
1289
+ if (!flagString(args, "target")) {
1290
+ return fail("INVALID_REQUEST", "launch commands require an explicit --target selector.");
1291
+ }
1292
+ if (subcommand === "diagnose")
1293
+ return diagnoseLaunch(args);
1294
+ if (subcommand !== "wait-ready") {
1295
+ return fail("UNKNOWN_COMMAND", `Unknown launch command: ${subcommand}`);
1296
+ }
1297
+ const timeoutMs = readTimeoutMs(args, 30000);
1298
+ if (timeoutMs === null)
1299
+ return invalidTimeoutEnvelope();
1300
+ if (flagBool(args, "focus")) {
1301
+ const focused = await rpcCall(args, "bridge:focusTarget", {}, 5000);
1302
+ if (!focused.ok)
1303
+ return focused;
1304
+ }
1305
+ const startedAt = Date.now();
1306
+ let last = null;
1307
+ while (Date.now() - startedAt < timeoutMs) {
1308
+ const remainingMs = timeoutMs - (Date.now() - startedAt);
1309
+ last = await diagnoseLaunch(args, Math.max(1, Math.min(3000, remainingMs)));
1310
+ if (!last.ok)
1311
+ return last;
1312
+ const data = objectJson(last.data, "Launch target status");
1313
+ if (data.ready === true) {
1314
+ return ok({
1315
+ ready: true,
1316
+ waitedMs: Date.now() - startedAt,
1317
+ target: data,
1318
+ }, last.meta);
1319
+ }
1320
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 250));
1321
+ }
1322
+ const lastData = last && last.ok
1323
+ ? objectJson(last.data, "Launch target status")
1324
+ : {};
1325
+ const blockers = Array.isArray(lastData.readinessBlockers)
1326
+ ? lastData.readinessBlockers.map(String).join(", ")
1327
+ : "unknown";
1328
+ return fail("LAUNCH_NOT_READY", `Launch did not become ready within ${timeoutMs}ms (blockers: ${blockers}).`, last?.meta, last && last.ok ? last.data : null);
1329
+ }
838
1330
  async function handleViewport(args) {
839
1331
  const subcommand = args._[1];
840
1332
  if (subcommand === "focus") {
@@ -861,7 +1353,10 @@ async function handleViewport(args) {
861
1353
  if (!raw.ok)
862
1354
  return raw;
863
1355
  const data = raw.data;
864
- const out = flagString(args, "out");
1356
+ const requestedOut = flagString(args, "out");
1357
+ const out = requestedOut
1358
+ ? await resolveWorkspaceFile(args, requestedOut, "viewport output")
1359
+ : undefined;
865
1360
  if (out && data.base64) {
866
1361
  await writeFile(out, Buffer.from(data.base64, "base64"));
867
1362
  return ok({
@@ -873,10 +1368,63 @@ async function handleViewport(args) {
873
1368
  }
874
1369
  return raw;
875
1370
  }
1371
+ async function handleLogs(args) {
1372
+ const subcommand = args._[1] || "get";
1373
+ if (subcommand === "get" || subcommand === "list") {
1374
+ return listEnvelope(await rpcCall(args, "bridge:getLogs", {
1375
+ level: flagString(args, "level") || null,
1376
+ limit: Number(flagString(args, "limit", "100")),
1377
+ offset: flagString(args, "offset") === undefined ? null : Number(flagString(args, "offset")),
1378
+ since: flagString(args, "since") || null,
1379
+ }));
1380
+ }
1381
+ if (subcommand === "clear") {
1382
+ return rpcCall(args, "bridge:clearLogs");
1383
+ }
1384
+ return fail("UNKNOWN_COMMAND", `Unknown logs command: ${subcommand}`);
1385
+ }
1386
+ async function handleWorkspace(args) {
1387
+ const subcommand = args._[1] || "status";
1388
+ const target = flagString(args, "target", "current") || "current";
1389
+ if (subcommand === "status") {
1390
+ return fetchDaemon(`/workspace/status?target=${encodeURIComponent(target)}`);
1391
+ }
1392
+ if (subcommand === "path") {
1393
+ const status = await fetchDaemon(`/workspace/status?target=${encodeURIComponent(target)}`);
1394
+ if (!status.ok)
1395
+ return status;
1396
+ const data = objectJson(status.data, "workspace status");
1397
+ return ok({
1398
+ rootDirectory: data.rootDirectory || null,
1399
+ projectDirectory: data.projectDirectory || null,
1400
+ assetsDirectory: data.assetsDirectory || null,
1401
+ tmpDirectory: data.tmpDirectory || null,
1402
+ });
1403
+ }
1404
+ if (subcommand === "sync") {
1405
+ return fetchDaemon("/workspace/sync", {
1406
+ method: "POST",
1407
+ body: JSON.stringify({ target }),
1408
+ });
1409
+ }
1410
+ if (subcommand === "pull") {
1411
+ const assetId = flagString(args, "asset") || flagString(args, "asset-id") || flagString(args, "id");
1412
+ if (!assetId)
1413
+ return fail("INVALID_REQUEST", "workspace pull requires --asset <assetId>.");
1414
+ return fetchDaemon("/workspace/pull", {
1415
+ method: "POST",
1416
+ body: JSON.stringify({ target, assetId }),
1417
+ });
1418
+ }
1419
+ return fail("UNKNOWN_COMMAND", `Unknown workspace command: ${subcommand}`);
1420
+ }
876
1421
  function help(group = "overview") {
877
1422
  const groups = {
878
1423
  overview: [
879
1424
  "pcbridge help core",
1425
+ "pcbridge help workspace",
1426
+ "pcbridge help frontend",
1427
+ "pcbridge help target",
880
1428
  "pcbridge help entity",
881
1429
  "pcbridge help asset",
882
1430
  "pcbridge help material",
@@ -885,6 +1433,8 @@ function help(group = "overview") {
885
1433
  "pcbridge help scene",
886
1434
  "pcbridge help store",
887
1435
  "pcbridge help viewport",
1436
+ "pcbridge help launch",
1437
+ "pcbridge help logs",
888
1438
  "pcbridge help eval",
889
1439
  ],
890
1440
  core: [
@@ -896,65 +1446,126 @@ function help(group = "overview") {
896
1446
  "pcbridge targets",
897
1447
  "pcbridge version",
898
1448
  ],
1449
+ target: [
1450
+ "pcbridge target focus --target launch:<sceneId>",
1451
+ "pcbridge target focus --target tab:<id>",
1452
+ "Focus activates both the PlayCanvas tab and its Chrome window.",
1453
+ "Use editor:<sceneId> for writes and launch:<sceneId> for runtime checks; current can be ambiguous.",
1454
+ ],
1455
+ workspace: [
1456
+ "pcbridge workspace status --target editor:<sceneId>",
1457
+ "pcbridge workspace path --target editor:<sceneId>",
1458
+ "pcbridge workspace sync --target editor:<sceneId>",
1459
+ "pcbridge workspace pull --target editor:<sceneId> --asset <assetId>",
1460
+ "The directory where `pcbridge daemon start` runs is the workspace root.",
1461
+ ],
1462
+ frontend: [
1463
+ "pcbridge frontend install [latest|playcanvas-editor-v<version>-r<revision>] [--no-activate]",
1464
+ "pcbridge frontend update",
1465
+ "pcbridge frontend status",
1466
+ "pcbridge frontend list",
1467
+ "pcbridge frontend use playcanvas-editor-v<version>-r<revision>",
1468
+ "pcbridge frontend remove playcanvas-editor-v<version>-r<revision>",
1469
+ "The active frontend is served from http://localhost:3487 while the daemon is running.",
1470
+ ],
899
1471
  entity: [
900
- "pcbridge entity list --target current --limit 50 [--name Player] [--component render] [--tag enemy] [--full]",
901
- "pcbridge entity get --target current --id <resource_id> [--full]",
902
- "pcbridge entity create --target current --json ./entity.json",
903
- "pcbridge entity create-many --target current --json ./entities.json",
904
- "pcbridge entity patch --target current --id <resource_id> --set position='[0,1,0]'",
905
- "pcbridge entity patch-many --target current --json ./edits.json",
906
- "pcbridge entity duplicate --target current --id <resource_id>",
907
- "pcbridge entity reparent --target current --id <resource_id> --parent <parent_resource_id> [--index 0] [--no-preserve-transform]",
908
- "pcbridge entity add-component --target current --id <resource_id> --component render --data '{\"type\":\"box\"}'",
909
- "pcbridge entity add-components --target current --id <resource_id> --json ./components.json",
910
- "pcbridge entity remove-component --target current --id <resource_id> --component render",
911
- "pcbridge entity set-material --target current --id <resource_id> --material-id <asset_id>",
912
- "pcbridge entity add-script --target current --id <resource_id> --asset-id <script_asset_id> --attributes-json ./attrs.json",
913
- "pcbridge entity delete --target current --id <resource_id>",
1472
+ "pcbridge entity list --target editor:<sceneId> [--limit 50] [--offset 0] [--name Player] [--component render] [--tag enemy] [--full]",
1473
+ "pcbridge entity get --target editor:<sceneId> --id <resource_id> [--full]",
1474
+ "pcbridge entity create --target editor:<sceneId> --json ./entity.json",
1475
+ "pcbridge entity create-many --target editor:<sceneId> --json ./entities.json",
1476
+ "pcbridge entity patch --target editor:<sceneId> --id <resource_id> --set position='[0,1,0]'",
1477
+ "pcbridge entity patch-many --target editor:<sceneId> --json ./edits.json",
1478
+ "pcbridge entity duplicate --target editor:<sceneId> --id <resource_id>",
1479
+ "pcbridge entity reparent --target editor:<sceneId> --id <resource_id> --parent <parent_resource_id> [--index 0] [--no-preserve-transform]",
1480
+ "pcbridge entity add-component --target editor:<sceneId> --id <resource_id> --component render --data '{\"type\":\"box\"}'",
1481
+ "pcbridge entity add-components --target editor:<sceneId> --id <resource_id> --json ./components.json",
1482
+ "pcbridge entity remove-component --target editor:<sceneId> --id <resource_id> --component render",
1483
+ "pcbridge entity remove-components --target editor:<sceneId> --id <resource_id> --component render --component collision",
1484
+ "pcbridge entity set-material --target editor:<sceneId> --id <resource_id> --material-id <asset_id>",
1485
+ "pcbridge entity add-script --target editor:<sceneId> --id <resource_id> (--asset-id <script_asset_id> | --script-name <registered_type>) [--attributes-json ./attrs.json] [--disabled]",
1486
+ "pcbridge entity delete --target editor:<sceneId> --id <resource_id>",
914
1487
  ],
915
1488
  asset: [
916
- "pcbridge asset list --target current [--type script] [--name controller] [--tag ui] [--limit 50] [--full]",
917
- "pcbridge asset get --target current --id <asset_id> [--full]",
918
- "pcbridge asset create --target current --json ./assets.json",
919
- "pcbridge asset folder ensure --target current --path \"AI Agent Bridge/Task/Textures\"",
920
- "pcbridge asset upload --target current --file ./texture.png --folder \"AI Agent Bridge/Task/Textures\"",
921
- "pcbridge asset instantiate --target current --id <template_asset_id>",
922
- "pcbridge asset delete --target current --id <asset_id>",
1489
+ "pcbridge asset list --target editor:<sceneId> [--type script] [--name controller] [--tag ui] [--limit 50] [--offset 0] [--full]",
1490
+ "pcbridge asset get --target editor:<sceneId> --id <asset_id> [--full]",
1491
+ "pcbridge asset create --target editor:<sceneId> --json ./assets.json",
1492
+ "pcbridge asset folder ensure --target editor:<sceneId> --path \"AI Agent Bridge/Task/Textures\"",
1493
+ "pcbridge asset upload --target editor:<sceneId> --file ./texture.png --folder \"AI Agent Bridge/Task/Textures\"",
1494
+ "pcbridge asset upload-many --target editor:<sceneId> --json ./upload-manifest.json",
1495
+ "pcbridge asset instantiate --target editor:<sceneId> --id <template_asset_id>",
1496
+ "pcbridge asset delete --target editor:<sceneId> --id <asset_id>",
923
1497
  ],
924
1498
  material: [
925
- "pcbridge material create --target current --name Mat --diffuse-map <texture_asset_id>",
926
- "pcbridge material patch --target current --asset-id <asset_id> --set diffuse='[1,0,0]'",
927
- "pcbridge material patch --target current --asset-id <asset_id> --json ./material-data.json",
928
- "pcbridge material set-diffuse --target current --asset-id <asset_id> --color '[1,0,0]'",
1499
+ "pcbridge material create --target editor:<sceneId> --name Mat --diffuse-map <texture_asset_id>",
1500
+ "pcbridge material patch --target editor:<sceneId> --asset-id <asset_id> --set diffuse='[1,0,0]'",
1501
+ "pcbridge material patch --target editor:<sceneId> --asset-id <asset_id> --json ./material-data.json",
1502
+ "pcbridge material set-diffuse --target editor:<sceneId> --asset-id <asset_id> --color '[1,0,0]'",
929
1503
  ],
930
1504
  template: [
931
- "pcbridge template create --target current --entity-id <resource_id> --name TemplateName --folder \"AI Agent Bridge/Task/Templates\"",
932
- "pcbridge template instantiate --target current --id <template_asset_id>",
1505
+ "pcbridge template create --target editor:<sceneId> --entity-id <resource_id> --name TemplateName --folder \"AI Agent Bridge/Task/Templates\"",
1506
+ "pcbridge template instantiate --target editor:<sceneId> --id <template_asset_id>",
1507
+ "pcbridge template overrides --target editor:<sceneId> --entity-id <resource_id>",
1508
+ "pcbridge template apply --target editor:<sceneId> --entity-id <resource_id> [--timeout-ms 60000]",
1509
+ "pcbridge template apply-many --target editor:<sceneId> --json ./template-roots.json [--timeout-ms 120000]",
1510
+ "When apply is needed, completion requires the pipeline callback plus two zero-override observations; timeout is an error.",
1511
+ "verified covers the current Editor observer only, not persistence across a reload; apply-many runs serially.",
933
1512
  ],
934
1513
  script: [
935
- "pcbridge script create --target current --filename controller.js --file ./controller.js",
936
- "pcbridge script set-text --target current --asset-id <asset_id> --file ./controller.js",
937
- "pcbridge script parse --target current --asset-id <asset_id>",
1514
+ "pcbridge script upsert --target editor:<sceneId> --filename controller.js --file ./controller.js --folder \"AI Agent Bridge/Task/Scripts\" [--parse] [--wait]",
1515
+ "pcbridge script create --target editor:<sceneId> --filename controller.js --file ./controller.js",
1516
+ "pcbridge script set-text --target editor:<sceneId> --asset-id <asset_id> --file ./controller.js [--parse] [--wait]",
1517
+ "pcbridge script parse --target editor:<sceneId> --asset-id <asset_id> [--timeout-ms 60000]",
1518
+ "Combine --parse --wait for completion-checked updates; it verifies remote content and current Editor metadata, not a later workspace mirror sync.",
938
1519
  ],
939
1520
  scene: [
940
- "pcbridge scene settings get --target current",
941
- "pcbridge scene settings patch --target current --json ./scene-settings.json",
942
- "pcbridge scene settings patch --target current --set render.fog='\"linear\"' --set physics.gravity='[0,-9.8,0]'",
1521
+ "pcbridge scene settings get --target editor:<sceneId>",
1522
+ "pcbridge scene settings patch --target editor:<sceneId> --json ./scene-settings.json",
1523
+ "pcbridge scene settings patch --target editor:<sceneId> --set render.fog='\"linear\"' --set physics.gravity='[0,-9.8,0]'",
943
1524
  ],
944
1525
  store: [
945
- "pcbridge store search --target current --search vehicle --limit 20",
946
- "pcbridge store get --target current --id <store_asset_id>",
947
- "pcbridge store download --target current --id <store_asset_id> --name AssetName --license-json ./license.json",
1526
+ "pcbridge store search --target editor:<sceneId> --search vehicle --limit 20",
1527
+ "pcbridge store get --target editor:<sceneId> --id <store_asset_id>",
1528
+ "pcbridge store download --target editor:<sceneId> --id <store_asset_id> --name AssetName --license-json ./license.json",
948
1529
  ],
949
1530
  viewport: [
950
- "pcbridge viewport capture --target current --out ./tmp/viewport.png [--format png|webp]",
951
- "pcbridge viewport focus --target current --id <resource_id> [--view perspective|top|bottom|front|back|left|right]",
1531
+ "pcbridge viewport capture --target editor:<sceneId> --out ./tmp/viewport.png [--format png|webp] [--max-width 1200] [--quality 0.85]",
1532
+ "pcbridge viewport capture --target launch:<sceneId> --out ./tmp/launch.png [--format png|webp] [--max-width 1200] [--quality 0.85]",
1533
+ "pcbridge viewport focus --target editor:<sceneId> --id <resource_id> [--view perspective|top|bottom|front|back|left|right] [--yaw 45] [--pitch -25]",
1534
+ "Capture defaults to max-width 1200 and may downscale the current canvas; it does not resize Chrome or emulate DPR.",
1535
+ ],
1536
+ launch: [
1537
+ "pcbridge targets",
1538
+ "pcbridge launch diagnose --target launch:<sceneId>",
1539
+ "pcbridge launch wait-ready --target launch:<sceneId> [--focus] [--timeout-ms 30000]",
1540
+ "pcbridge target focus --target launch:<sceneId>",
1541
+ "pcbridge eval --target launch:<sceneId> --code \"return { href: location.href, runtimeCreated: !!runtimeApp, rootChildCount: runtimeApp?.root?.children?.length ?? 0 }\"",
1542
+ "pcbridge viewport capture --target launch:<sceneId> --out ./tmp/launch.png [--format png|webp]",
1543
+ "pcbridge logs get --target launch:<sceneId> [--limit 100] [--level error|warn|info|debug] [--since <seq>]",
1544
+ "pcbridge logs clear --target launch:<sceneId>",
1545
+ "Use --target tab:<id> when multiple Launch tabs are open for the same scene.",
1546
+ "ready is a best-effort heuristic requiring a visible tab, owned graphics canvas, attached scene, completed first frame, and no recognized splash.",
1547
+ "scriptsReady/scriptTypeCount are diagnostic only; they do not prove every ScriptType registered.",
1548
+ ],
1549
+ logs: [
1550
+ "pcbridge logs get --target editor:<sceneId> [--limit 100] [--offset 0] [--level error|warn|info|debug] [--since <seq>]",
1551
+ "pcbridge logs get --target launch:<sceneId> [--limit 100] [--offset 0] [--level error|warn|info|debug] [--since <seq>]",
1552
+ "pcbridge logs clear --target editor:<sceneId>",
1553
+ "pcbridge logs clear --target launch:<sceneId>",
1554
+ ],
1555
+ log: [
1556
+ "pcbridge logs get --target editor:<sceneId> [--limit 100] [--offset 0] [--level error|warn|info|debug] [--since <seq>]",
1557
+ "pcbridge logs get --target launch:<sceneId> [--limit 100] [--offset 0] [--level error|warn|info|debug] [--since <seq>]",
1558
+ "pcbridge logs clear --target editor:<sceneId>",
1559
+ "pcbridge logs clear --target launch:<sceneId>",
952
1560
  ],
953
1561
  eval: [
954
- "Use eval for custom Editor/Engine workflows, large multi-step scene edits, exploratory API inspection, and operations not yet structured.",
955
- "pcbridge eval --target current --code \"return { href: location.href, hasEditor: !!editor }\"",
956
- "pcbridge eval --target current --file ./task.js",
957
- "pcbridge eval --target current --stdin",
1562
+ "Use eval for custom Editor/Engine workflows, PlayCanvas Launch debugging, large multi-step scene edits, exploratory API inspection, and operations not yet structured.",
1563
+ "pcbridge eval --target editor:<sceneId> --code \"return { href: location.href, hasEditor: !!editor }\" [--timeout-ms 15000]",
1564
+ "pcbridge eval --target launch:<sceneId> --code \"return { href: location.href, runtimeCreated: !!runtimeApp, rootChildCount: runtimeApp?.root?.children?.length ?? 0 }\"",
1565
+ "pcbridge eval --target editor:<sceneId> --file ./task.js [--timeout-ms 15000]",
1566
+ "pcbridge eval --target editor:<sceneId> --file ./task.js --args-json ./task-args.json [--timeout-ms 15000]",
1567
+ "pcbridge eval --target editor:<sceneId> --stdin [--timeout-ms 15000]",
1568
+ "Add --max-depth <1..20>, --max-items <1..5000>, --max-keys <1..2000>, or --max-string <1..100000> only when a compact projection is insufficient.",
958
1569
  ],
959
1570
  };
960
1571
  const commands = groups[group];
@@ -992,11 +1603,21 @@ async function main() {
992
1603
  else if (command === "install-skill") {
993
1604
  print(await installSkill(args));
994
1605
  }
1606
+ else if (command === "frontend") {
1607
+ print(await handleFrontend(args));
1608
+ }
995
1609
  else if (command === "targets") {
996
1610
  print(await fetchDaemon("/targets"));
997
1611
  }
1612
+ else if (command === "target") {
1613
+ print(await handleTarget(args));
1614
+ }
1615
+ else if (command === "workspace") {
1616
+ print(await handleWorkspace(args));
1617
+ }
998
1618
  else if (command === "eval") {
999
- print(await rpcEval(args, await readCode(args)));
1619
+ const commandArgs = await readJsonFlag(args, "args-json");
1620
+ print(await rpcEval(args, await readCode(args), objectJson(commandArgs, "eval args")));
1000
1621
  }
1001
1622
  else if (command === "entity") {
1002
1623
  print(await handleEntity(args));
@@ -1019,9 +1640,15 @@ async function main() {
1019
1640
  else if (command === "store") {
1020
1641
  print(await handleStore(args));
1021
1642
  }
1643
+ else if (command === "launch") {
1644
+ print(await handleLaunch(args));
1645
+ }
1022
1646
  else if (command === "viewport") {
1023
1647
  print(await handleViewport(args));
1024
1648
  }
1649
+ else if (command === "logs" || command === "log") {
1650
+ print(await handleLogs(args));
1651
+ }
1025
1652
  else if (command === "version" || command === "--version" || command === "-v") {
1026
1653
  print(ok({ version: VERSION }));
1027
1654
  }
@@ -1031,6 +1658,10 @@ async function main() {
1031
1658
  }
1032
1659
  }
1033
1660
  catch (error) {
1661
+ if (error instanceof DaemonConnectionError) {
1662
+ print(fail(error.diagnosis.code, error.diagnosis.message, undefined, { nextAction: error.diagnosis.nextAction }));
1663
+ return;
1664
+ }
1034
1665
  print(fail("CLI_ERROR", error instanceof Error ? error.message : String(error)));
1035
1666
  process.exitCode = 1;
1036
1667
  }