playcanvas-agent-bridge-cli 0.6.2 → 0.7.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/config.js CHANGED
@@ -4,7 +4,10 @@ import { existsSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- export const VERSION = "0.6.2";
7
+ export const VERSION = "0.7.0";
8
+ export const PACKAGE_NAME = "playcanvas-agent-bridge-cli";
9
+ export const DEFAULT_PCBRIDGE_REPOSITORY = "Q-My99/playcanvas-agent-bridge-cli";
10
+ export const DEFAULT_PCBRIDGE_REF = "main";
8
11
  export const DEFAULT_HOST = "127.0.0.1";
9
12
  export const DEFAULT_PORT = 17329;
10
13
  export const DEFAULT_FRONTEND_PORT = 3487;
@@ -14,6 +17,25 @@ export const CONFIG_DIR = process.env.PCBRIDGE_CONFIG_DIR
14
17
  : join(homedir(), ".pcbridge");
15
18
  export const SESSION_FILE = join(CONFIG_DIR, "session.json");
16
19
  export const EXTENSION_INSTALL_DIR = join(CONFIG_DIR, "extension");
20
+ export const UPDATE_STATE_FILE = join(CONFIG_DIR, "update-state.json");
21
+ export const INSTALLED_SKILLS_FILE = join(CONFIG_DIR, "installed-skills.json");
22
+ export function parseSemver(version) {
23
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version.trim());
24
+ if (!match)
25
+ return null;
26
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
27
+ }
28
+ export function compareSemver(left, right) {
29
+ const a = parseSemver(left);
30
+ const b = parseSemver(right);
31
+ if (!a || !b)
32
+ return left.localeCompare(right);
33
+ for (let index = 0; index < 3; index += 1) {
34
+ if (a[index] !== b[index])
35
+ return a[index] - b[index];
36
+ }
37
+ return 0;
38
+ }
17
39
  export async function readOrCreateSession() {
18
40
  await mkdir(CONFIG_DIR, { recursive: true });
19
41
  try {
@@ -7,7 +7,9 @@ import { CONFIG_DIR, DEFAULT_FRONTEND_PORT, DEFAULT_HOST, DEFAULT_PORT, VERSION,
7
7
  import { createFrontendServer, } from "../frontend/server.js";
8
8
  import { TargetRegistry } from "./target-registry.js";
9
9
  import { WorkspaceManager } from "../workspace/manager.js";
10
- import { BuilderManager } from "../builder/manager.js";
10
+ import { PluginHost } from "../plugins/host.js";
11
+ import { parsePluginSource, PluginStore } from "../plugins/store.js";
12
+ import { executeOneClickUpdate, formatHumanUpdateHint, getUpdateReport, readGeneratedExtensionVersion, UPDATE_CACHE_TTL_MS, } from "../updates.js";
11
13
  import { fail, normalizeError, ok, } from "../shared/protocol.js";
12
14
  function readBody(req) {
13
15
  return new Promise((resolve, reject) => {
@@ -50,17 +52,40 @@ export function createDaemonServer(options) {
50
52
  const host = options.host || DEFAULT_HOST;
51
53
  const port = Number(options.port ?? DEFAULT_PORT);
52
54
  let actualPort = port;
55
+ let restartRequested = false;
56
+ const configDir = options.frontendRootDir || CONFIG_DIR;
53
57
  const registry = new TargetRegistry();
54
58
  const pending = new Map();
59
+ const autoReloadedClients = new Set();
55
60
  const log = options.log || (() => undefined);
56
61
  const frontend = createFrontendServer({
57
62
  host,
58
63
  port: options.frontendPort ?? DEFAULT_FRONTEND_PORT,
59
- rootDir: options.frontendRootDir || CONFIG_DIR,
64
+ rootDir: configDir,
60
65
  });
61
66
  function requireToken(req) {
62
67
  return req.headers["x-pcbridge-token"] === options.token;
63
68
  }
69
+ function connectedExtensionVersions() {
70
+ return [
71
+ ...new Set(registry
72
+ .list()
73
+ .filter((item) => item.connected && typeof item.extensionVersion === "string" && item.extensionVersion)
74
+ .map((item) => item.extensionVersion)),
75
+ ];
76
+ }
77
+ async function reloadConnectedExtensions(reloadTabs = true) {
78
+ const connected = registry.list().find((item) => item.connected);
79
+ if (!connected)
80
+ return false;
81
+ const response = await sendToTarget({
82
+ target: connected.id,
83
+ method: "bridge:reloadExtension",
84
+ params: { reloadTabs },
85
+ timeoutMs: 5000,
86
+ });
87
+ return response.ok;
88
+ }
64
89
  async function sendToTarget(request) {
65
90
  if (!request.method) {
66
91
  return fail("INVALID_REQUEST", "RPC method is required.");
@@ -104,7 +129,7 @@ export function createDaemonServer(options) {
104
129
  }
105
130
  const workspace = new WorkspaceManager({
106
131
  rootDir: options.workspaceRoot || process.cwd(),
107
- settingsPath: join(options.frontendRootDir || CONFIG_DIR, "workspace-settings.json"),
132
+ settingsPath: join(configDir, "workspace-settings.json"),
108
133
  requestTarget: (target, method, params = {}, timeoutMs = 15000) => sendToTarget({
109
134
  target,
110
135
  method,
@@ -112,15 +137,20 @@ export function createDaemonServer(options) {
112
137
  timeoutMs,
113
138
  }),
114
139
  });
115
- const builder = new BuilderManager({
116
- rootDir: workspace.rootDir,
140
+ const pluginStore = new PluginStore(join(configDir, "plugins"), {
141
+ fetch: options.fetch,
142
+ });
143
+ const plugins = new PluginHost({
144
+ store: pluginStore,
145
+ workspace,
117
146
  requestTarget: (target, method, params = {}, timeoutMs = 15000) => sendToTarget({
118
147
  target,
119
148
  method,
120
149
  params,
121
150
  timeoutMs,
122
151
  }),
123
- workspace,
152
+ listTargets: () => registry.list(),
153
+ log,
124
154
  });
125
155
  const processing = new ProcessingManager(target => {
126
156
  const status = workspace.statusForTarget(target);
@@ -171,6 +201,97 @@ export function createDaemonServer(options) {
171
201
  });
172
202
  return;
173
203
  }
204
+ if (url.pathname === "/restart" && req.method === "POST") {
205
+ if (!requireToken(req)) {
206
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
207
+ return;
208
+ }
209
+ restartRequested = true;
210
+ writeJson(res, 200, ok({
211
+ service: "pcbridge-daemon",
212
+ restarting: true,
213
+ version: VERSION,
214
+ workspaceRoot: workspace.rootDir,
215
+ }));
216
+ res.once("finish", () => {
217
+ setImmediate(() => {
218
+ void closeDaemon().catch((error) => {
219
+ log(`daemon restart shutdown failed: ${String(error)}`);
220
+ });
221
+ });
222
+ });
223
+ return;
224
+ }
225
+ if (url.pathname === "/extension/reload" && req.method === "POST") {
226
+ if (!requireToken(req)) {
227
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
228
+ return;
229
+ }
230
+ const body = await readBody(req);
231
+ const data = isJsonObject(body) ? body : {};
232
+ const reloadTabs = data.reloadTabs !== false;
233
+ const reloaded = await reloadConnectedExtensions(reloadTabs);
234
+ writeJson(res, 200, ok({ reloaded, reloadTabs }));
235
+ return;
236
+ }
237
+ if (url.pathname === "/updates" && req.method === "GET") {
238
+ if (!requireToken(req)) {
239
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
240
+ return;
241
+ }
242
+ const refresh = url.searchParams.get("refresh") === "1";
243
+ const report = await getUpdateReport({
244
+ refresh,
245
+ allowNetwork: true,
246
+ configDir,
247
+ store: pluginStore,
248
+ daemonVersion: VERSION,
249
+ connectedExtensionVersions: connectedExtensionVersions(),
250
+ fetch: options.fetch,
251
+ });
252
+ writeJson(res, 200, ok(report));
253
+ return;
254
+ }
255
+ if (url.pathname === "/update" && req.method === "POST") {
256
+ if (!requireToken(req)) {
257
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
258
+ return;
259
+ }
260
+ const body = await readBody(req);
261
+ const data = isJsonObject(body) ? body : {};
262
+ try {
263
+ const result = await executeOneClickUpdate({
264
+ configDir,
265
+ store: pluginStore,
266
+ includePlugins: Boolean(data.includePlugins),
267
+ reloadTabs: data.reloadTabs !== false,
268
+ daemonVersion: VERSION,
269
+ connectedExtensionVersions: connectedExtensionVersions(),
270
+ updatePlugins: () => plugins.updateAll(),
271
+ fetch: options.fetch,
272
+ });
273
+ const shouldRestart = result.packageUpdated || result.version !== VERSION;
274
+ if (shouldRestart) {
275
+ restartRequested = true;
276
+ result.daemonRestartTriggered = true;
277
+ }
278
+ writeJson(res, 200, ok(result));
279
+ if (shouldRestart) {
280
+ res.once("finish", () => {
281
+ setImmediate(() => {
282
+ void closeDaemon().catch((error) => {
283
+ log(`daemon update restart failed: ${String(error)}`);
284
+ });
285
+ });
286
+ });
287
+ }
288
+ }
289
+ catch (error) {
290
+ const code = error.code;
291
+ writeJson(res, 400, fail(typeof code === "string" ? code : "UPDATE_FAILED", error instanceof Error ? error.message : String(error)));
292
+ }
293
+ return;
294
+ }
174
295
  if (url.pathname === "/frontend/status" && req.method === "GET") {
175
296
  if (!requireToken(req)) {
176
297
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
@@ -193,7 +314,20 @@ export function createDaemonServer(options) {
193
314
  return;
194
315
  }
195
316
  const tabId = Number(url.searchParams.get("tabId"));
317
+ const refresh = url.searchParams.get("refresh") === "1";
196
318
  const target = Number.isFinite(tabId) ? registry.getByTabId(tabId) : undefined;
319
+ const [frontendStatus, updates] = await Promise.all([
320
+ frontend.status(),
321
+ getUpdateReport({
322
+ refresh,
323
+ allowNetwork: refresh,
324
+ configDir,
325
+ store: pluginStore,
326
+ daemonVersion: VERSION,
327
+ connectedExtensionVersions: connectedExtensionVersions(),
328
+ fetch: options.fetch,
329
+ }),
330
+ ]);
197
331
  writeJson(res, 200, ok({
198
332
  daemon: {
199
333
  version: VERSION,
@@ -205,7 +339,8 @@ export function createDaemonServer(options) {
205
339
  },
206
340
  target: target || null,
207
341
  workspace: workspace.statusForTarget(target),
208
- frontend: await frontend.status(),
342
+ frontend: frontendStatus,
343
+ updates: updates,
209
344
  }));
210
345
  return;
211
346
  }
@@ -318,39 +453,70 @@ export function createDaemonServer(options) {
318
453
  }
319
454
  return;
320
455
  }
321
- if (url.pathname === "/builder/jobs" && req.method === "POST") {
456
+ if (url.pathname === "/plugins" && req.method === "GET") {
322
457
  if (!requireToken(req)) {
323
458
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
324
459
  return;
325
460
  }
326
- const body = await readBody(req);
327
- if (!isJsonObject(body) || typeof body.templateAssetId !== "string") {
328
- writeJson(res, 400, fail("INVALID_REQUEST", "Template build requires templateAssetId."));
461
+ const refresh = url.searchParams.get("refresh") === "1";
462
+ writeJson(res, 200, ok(await plugins.list({ refresh })));
463
+ return;
464
+ }
465
+ if (url.pathname === "/plugins/update-all" && req.method === "POST") {
466
+ if (!requireToken(req)) {
467
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
329
468
  return;
330
469
  }
331
- const selector = typeof body.target === "string" ? body.target : "current";
332
- const resolved = registry.resolve(selector);
333
- if (!resolved.ok) {
334
- writeJson(res, 400, fail(resolved.code, resolved.message));
335
- return;
470
+ try {
471
+ writeJson(res, 200, ok(await plugins.updateAll()));
472
+ }
473
+ catch (error) {
474
+ const code = error.code;
475
+ writeJson(res, 400, fail(typeof code === "string" ? code : "PLUGIN_ERROR", error instanceof Error ? error.message : String(error)));
336
476
  }
337
- const suffix = typeof body.suffix === "string" ? body.suffix : undefined;
338
- const prefix = typeof body.prefix === "string" ? body.prefix : undefined;
339
- writeJson(res, 202, ok(builder.start(resolved.target.info, body.templateAssetId, { suffix, prefix })));
340
477
  return;
341
478
  }
342
- const builderJobMatch = url.pathname.match(/^\/builder\/jobs\/([^/]+)$/);
343
- if (builderJobMatch && req.method === "GET") {
479
+ const pluginMatch = url.pathname.match(/^\/plugins\/(?:(add)|([a-z0-9-]+)\/(enable|disable|remove|update|reload|actions\/([\w.-]+)))$/);
480
+ if (pluginMatch && req.method === "POST") {
344
481
  if (!requireToken(req)) {
345
482
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
346
483
  return;
347
484
  }
348
- const job = builder.get(decodeURIComponent(builderJobMatch[1]));
349
- if (!job) {
350
- writeJson(res, 404, fail("BUILD_NOT_FOUND", "Template build job was not found."));
351
- return;
485
+ const body = await readBody(req);
486
+ const data = isJsonObject(body) ? body : {};
487
+ const [, add, id, operation, action] = pluginMatch;
488
+ try {
489
+ let result;
490
+ if (add) {
491
+ if (typeof data.source !== "string") {
492
+ writeJson(res, 400, fail("INVALID_REQUEST", "plugin add requires source."));
493
+ return;
494
+ }
495
+ result = await plugins.add(parsePluginSource(data.source, data.link === true));
496
+ }
497
+ else if (action) {
498
+ let target = null;
499
+ const resolved = registry.resolve(typeof data.target === "string" ? data.target : "current");
500
+ if (resolved.ok)
501
+ target = resolved.target.info;
502
+ else if (typeof data.target === "string") {
503
+ writeJson(res, 400, fail(resolved.code, resolved.message));
504
+ return;
505
+ }
506
+ result = await plugins.callAction(id, action, isJsonObject(data.params) ? data.params : {}, target);
507
+ }
508
+ else if (operation === "enable" || operation === "disable") {
509
+ result = await plugins.setEnabled(id, operation === "enable");
510
+ }
511
+ else {
512
+ result = await plugins[operation](id);
513
+ }
514
+ writeJson(res, 200, ok(result));
515
+ }
516
+ catch (error) {
517
+ const code = error.code;
518
+ writeJson(res, 400, fail(typeof code === "string" ? code : "PLUGIN_ERROR", error instanceof Error ? error.message : String(error)));
352
519
  }
353
- writeJson(res, 200, ok(job));
354
520
  return;
355
521
  }
356
522
  if (url.pathname === "/rpc" && req.method === "POST") {
@@ -409,11 +575,31 @@ export function createDaemonServer(options) {
409
575
  log(`connected ${result.info.id} project=${result.info.projectId || "unknown"} ` +
410
576
  `scene=${result.info.sceneId || "unknown"}`);
411
577
  }
578
+ if (result.info.extensionVersion &&
579
+ result.info.extensionVersion !== VERSION &&
580
+ !autoReloadedClients.has(`${result.info.clientId}:${VERSION}`)) {
581
+ void readGeneratedExtensionVersion(join(configDir, "extension"))
582
+ .then((diskExtVersion) => {
583
+ if (diskExtVersion === VERSION) {
584
+ autoReloadedClients.add(`${result.info.clientId}:${VERSION}`);
585
+ log(`reloading stale Chrome extension (${result.info.extensionVersion} -> ${VERSION}) for ${result.info.id}`);
586
+ return sendToTarget({
587
+ target: result.info.id,
588
+ method: "bridge:reloadExtension",
589
+ params: { reloadTabs: true },
590
+ timeoutMs: 5000,
591
+ });
592
+ }
593
+ return null;
594
+ })
595
+ .catch(() => undefined);
596
+ }
412
597
  if (result.connected || result.changed) {
413
598
  void workspace.handleTarget(result.info).catch((error) => {
414
599
  log(`workspace initialization failed for ${result.info.id}: ${String(error)}`);
415
600
  });
416
601
  }
602
+ plugins.handleTarget(result.info);
417
603
  return;
418
604
  }
419
605
  if (message.type === "workspace:delta" && message.delta && typeof message.delta === "object") {
@@ -472,24 +658,52 @@ export function createDaemonServer(options) {
472
658
  }
473
659
  else
474
660
  workspace.markDisconnected(info);
661
+ plugins.forgetTarget(info);
475
662
  log(`disconnected ${info.id} project=${info.projectId || "unknown"} ` +
476
663
  `scene=${info.sceneId || "unknown"}`);
477
664
  }
478
665
  });
479
666
  });
667
+ let updateCheckTimer = null;
668
+ let lastLoggedUpdateHint = null;
669
+ async function runBackgroundUpdateCheck(refresh) {
670
+ try {
671
+ const report = await getUpdateReport({
672
+ refresh,
673
+ allowNetwork: true,
674
+ configDir,
675
+ store: pluginStore,
676
+ daemonVersion: VERSION,
677
+ connectedExtensionVersions: connectedExtensionVersions(),
678
+ fetch: options.fetch,
679
+ });
680
+ const hint = formatHumanUpdateHint(report);
681
+ if (hint && hint !== lastLoggedUpdateHint) {
682
+ lastLoggedUpdateHint = hint;
683
+ log(hint.replace(/^\[pcbridge\]\s*/, ""));
684
+ }
685
+ }
686
+ catch {
687
+ // Background update checks must never disrupt the daemon.
688
+ }
689
+ }
480
690
  function closeDaemon() {
481
691
  if (closePromise)
482
692
  return closePromise;
483
693
  closePromise = (async () => {
484
694
  clearInterval(pingTimer);
695
+ if (updateCheckTimer) {
696
+ clearInterval(updateCheckTimer);
697
+ updateCheckTimer = null;
698
+ }
485
699
  for (const waiter of pending.values()) {
486
700
  clearTimeout(waiter.timer);
487
701
  waiter.resolve(fail("DAEMON_STOPPING", "pcbridge daemon is stopping."));
488
702
  }
489
703
  pending.clear();
490
- const builderCleanup = await Promise.allSettled([builder.close(), processing.close()]);
704
+ const pluginCleanup = await Promise.allSettled([plugins.close(), processing.close()]);
491
705
  const cleanupResults = [
492
- ...builderCleanup,
706
+ ...pluginCleanup,
493
707
  ...await Promise.allSettled([
494
708
  workspace.close(),
495
709
  frontend.close(),
@@ -526,10 +740,13 @@ export function createDaemonServer(options) {
526
740
  get port() {
527
741
  return actualPort;
528
742
  },
743
+ get restartRequested() {
744
+ return restartRequested;
745
+ },
529
746
  registry,
530
747
  frontend,
531
748
  workspace,
532
- builder,
749
+ plugins,
533
750
  closed,
534
751
  listen: async () => {
535
752
  await new Promise((resolveListen, reject) => {
@@ -548,6 +765,19 @@ export function createDaemonServer(options) {
548
765
  catch (error) {
549
766
  log(`frontend server unavailable: ${String(error)}`);
550
767
  }
768
+ try {
769
+ await plugins.start();
770
+ }
771
+ catch (error) {
772
+ log(`plugins unavailable: ${String(error)}`);
773
+ }
774
+ if (options.enableBackgroundUpdateCheck) {
775
+ void runBackgroundUpdateCheck(false);
776
+ updateCheckTimer = setInterval(() => {
777
+ void runBackgroundUpdateCheck(true);
778
+ }, UPDATE_CACHE_TTL_MS);
779
+ updateCheckTimer.unref();
780
+ }
551
781
  },
552
782
  close: closeDaemon,
553
783
  };