playcanvas-agent-bridge-cli 0.3.0 → 0.5.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,7 @@ 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.3.0";
7
+ export const VERSION = "0.5.0";
8
8
  export const DEFAULT_HOST = "127.0.0.1";
9
9
  export const DEFAULT_PORT = 17329;
10
10
  export const DEFAULT_FRONTEND_PORT = 3487;
@@ -4,6 +4,8 @@ import { WebSocketServer } from "ws";
4
4
  import { CONFIG_DIR, DEFAULT_FRONTEND_PORT, DEFAULT_HOST, DEFAULT_PORT, VERSION, } from "../config.js";
5
5
  import { createFrontendServer, } from "../frontend/server.js";
6
6
  import { TargetRegistry } from "./target-registry.js";
7
+ import { WorkspaceManager } from "../workspace/manager.js";
8
+ import { BuilderManager } from "../builder/manager.js";
7
9
  import { fail, normalizeError, ok, } from "../shared/protocol.js";
8
10
  function readBody(req) {
9
11
  return new Promise((resolve, reject) => {
@@ -48,7 +50,6 @@ export function createDaemonServer(options) {
48
50
  host,
49
51
  port: options.frontendPort ?? DEFAULT_FRONTEND_PORT,
50
52
  rootDir: options.frontendRootDir || CONFIG_DIR,
51
- log,
52
53
  });
53
54
  function requireToken(req) {
54
55
  return req.headers["x-pcbridge-token"] === options.token;
@@ -94,6 +95,25 @@ export function createDaemonServer(options) {
94
95
  });
95
96
  });
96
97
  }
98
+ const workspace = new WorkspaceManager({
99
+ rootDir: options.workspaceRoot || process.cwd(),
100
+ requestTarget: (target, method, params = {}, timeoutMs = 15000) => sendToTarget({
101
+ target,
102
+ method,
103
+ params,
104
+ timeoutMs,
105
+ }),
106
+ });
107
+ const builder = new BuilderManager({
108
+ rootDir: workspace.rootDir,
109
+ requestTarget: (target, method, params = {}, timeoutMs = 15000) => sendToTarget({
110
+ target,
111
+ method,
112
+ params,
113
+ timeoutMs,
114
+ }),
115
+ workspace,
116
+ });
97
117
  const server = http.createServer(async (req, res) => {
98
118
  try {
99
119
  const url = new URL(req.url || "/", `http://${req.headers.host || `${host}:${port}`}`);
@@ -108,6 +128,7 @@ export function createDaemonServer(options) {
108
128
  host,
109
129
  port: actualPort,
110
130
  targetCount: registry.list().filter((target) => target.connected).length,
131
+ workspaceRoot: workspace.rootDir,
111
132
  frontend: frontendStatus,
112
133
  }));
113
134
  return;
@@ -128,6 +149,120 @@ export function createDaemonServer(options) {
128
149
  writeJson(res, 200, ok(registry.list()));
129
150
  return;
130
151
  }
152
+ if (url.pathname === "/status" && req.method === "GET") {
153
+ if (!requireToken(req)) {
154
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
155
+ return;
156
+ }
157
+ const tabId = Number(url.searchParams.get("tabId"));
158
+ const target = Number.isFinite(tabId) ? registry.getByTabId(tabId) : undefined;
159
+ writeJson(res, 200, ok({
160
+ daemon: {
161
+ version: VERSION,
162
+ host,
163
+ port: actualPort,
164
+ workspaceRoot: workspace.rootDir,
165
+ targetCount: registry.list().filter((item) => item.connected).length,
166
+ },
167
+ target: target || null,
168
+ workspace: workspace.statusForTarget(target),
169
+ frontend: await frontend.status(),
170
+ }));
171
+ return;
172
+ }
173
+ if (url.pathname === "/workspace/status" && req.method === "GET") {
174
+ if (!requireToken(req)) {
175
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
176
+ return;
177
+ }
178
+ const resolved = registry.resolve(url.searchParams.get("target") || "current");
179
+ if (!resolved.ok) {
180
+ writeJson(res, 400, fail(resolved.code, resolved.message));
181
+ return;
182
+ }
183
+ writeJson(res, 200, ok(workspace.statusForTarget(resolved.target.info)));
184
+ return;
185
+ }
186
+ if (url.pathname === "/workspace/sync" && req.method === "POST") {
187
+ if (!requireToken(req)) {
188
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
189
+ return;
190
+ }
191
+ const body = await readBody(req);
192
+ const data = isJsonObject(body) ? body : {};
193
+ const selector = typeof data.target === "string" ? data.target : "current";
194
+ const resolved = registry.resolve(selector);
195
+ if (!resolved.ok) {
196
+ writeJson(res, 400, fail(resolved.code, resolved.message));
197
+ return;
198
+ }
199
+ try {
200
+ writeJson(res, 200, ok(await workspace.syncTarget(resolved.target.info)));
201
+ }
202
+ catch (error) {
203
+ writeJson(res, 400, fail("WORKSPACE_SYNC_FAILED", String(error)));
204
+ }
205
+ return;
206
+ }
207
+ if (url.pathname === "/workspace/pull" && req.method === "POST") {
208
+ if (!requireToken(req)) {
209
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
210
+ return;
211
+ }
212
+ const body = await readBody(req);
213
+ if (!isJsonObject(body) || typeof body.assetId !== "string") {
214
+ writeJson(res, 400, fail("INVALID_REQUEST", "workspace pull requires assetId."));
215
+ return;
216
+ }
217
+ const selector = typeof body.target === "string" ? body.target : "current";
218
+ const resolved = registry.resolve(selector);
219
+ if (!resolved.ok) {
220
+ writeJson(res, 400, fail(resolved.code, resolved.message));
221
+ return;
222
+ }
223
+ try {
224
+ writeJson(res, 200, ok(await workspace.pullAsset(resolved.target.info, body.assetId)));
225
+ }
226
+ catch (error) {
227
+ writeJson(res, 400, fail("WORKSPACE_PULL_FAILED", String(error)));
228
+ }
229
+ return;
230
+ }
231
+ if (url.pathname === "/builder/jobs" && req.method === "POST") {
232
+ if (!requireToken(req)) {
233
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
234
+ return;
235
+ }
236
+ const body = await readBody(req);
237
+ if (!isJsonObject(body) || typeof body.templateAssetId !== "string") {
238
+ writeJson(res, 400, fail("INVALID_REQUEST", "Template build requires templateAssetId."));
239
+ return;
240
+ }
241
+ const selector = typeof body.target === "string" ? body.target : "current";
242
+ const resolved = registry.resolve(selector);
243
+ if (!resolved.ok) {
244
+ writeJson(res, 400, fail(resolved.code, resolved.message));
245
+ return;
246
+ }
247
+ const suffix = typeof body.suffix === "string" ? body.suffix : undefined;
248
+ const prefix = typeof body.prefix === "string" ? body.prefix : undefined;
249
+ writeJson(res, 202, ok(builder.start(resolved.target.info, body.templateAssetId, { suffix, prefix })));
250
+ return;
251
+ }
252
+ const builderJobMatch = url.pathname.match(/^\/builder\/jobs\/([^/]+)$/);
253
+ if (builderJobMatch && req.method === "GET") {
254
+ if (!requireToken(req)) {
255
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
256
+ return;
257
+ }
258
+ const job = builder.get(decodeURIComponent(builderJobMatch[1]));
259
+ if (!job) {
260
+ writeJson(res, 404, fail("BUILD_NOT_FOUND", "Template build job was not found."));
261
+ return;
262
+ }
263
+ writeJson(res, 200, ok(job));
264
+ return;
265
+ }
131
266
  if (url.pathname === "/rpc" && req.method === "POST") {
132
267
  if (!requireToken(req)) {
133
268
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
@@ -160,14 +295,35 @@ export function createDaemonServer(options) {
160
295
  wss.emit("connection", ws, req);
161
296
  });
162
297
  });
298
+ const liveness = new WeakMap();
299
+ const pingTimer = setInterval(() => {
300
+ for (const client of wss.clients) {
301
+ if (liveness.get(client) === false) {
302
+ client.terminate();
303
+ continue;
304
+ }
305
+ liveness.set(client, false);
306
+ client.ping();
307
+ }
308
+ }, 15000);
309
+ pingTimer.unref();
163
310
  wss.on("connection", (ws) => {
164
- log("extension connected");
311
+ liveness.set(ws, true);
312
+ ws.on("pong", () => liveness.set(ws, true));
165
313
  ws.on("message", (raw) => {
166
314
  try {
167
315
  const message = JSON.parse(raw.toString());
168
316
  if (message.type === "target:update" && message.target?.clientId) {
169
- const info = registry.upsert(message.target, ws);
170
- log(`target ${info.id} kind=${info.kind || "unknown"} ready=${info.ready} url=${info.url}`);
317
+ const result = registry.upsert(message.target, ws);
318
+ if (result.connected) {
319
+ log(`connected ${result.info.id} project=${result.info.projectId || "unknown"} ` +
320
+ `scene=${result.info.sceneId || "unknown"}`);
321
+ }
322
+ if (result.connected || result.changed) {
323
+ void workspace.handleTarget(result.info).catch((error) => {
324
+ log(`workspace initialization failed for ${result.info.id}: ${String(error)}`);
325
+ });
326
+ }
171
327
  return;
172
328
  }
173
329
  if (message.type === "response" && message.id) {
@@ -199,8 +355,22 @@ export function createDaemonServer(options) {
199
355
  }
200
356
  });
201
357
  ws.on("close", () => {
202
- registry.markDisconnected(ws);
203
- log("extension disconnected");
358
+ for (const info of registry.markDisconnected(ws)) {
359
+ const replacement = registry.list().find((candidate) => candidate.connected &&
360
+ candidate.ready &&
361
+ candidate.kind === "editor" &&
362
+ candidate.projectId === info.projectId &&
363
+ candidate.branchId === info.branchId);
364
+ if (replacement) {
365
+ void workspace.handleTarget(replacement).catch((error) => {
366
+ log(`workspace failover failed for ${replacement.id}: ${String(error)}`);
367
+ });
368
+ }
369
+ else
370
+ workspace.markDisconnected(info);
371
+ log(`disconnected ${info.id} project=${info.projectId || "unknown"} ` +
372
+ `scene=${info.sceneId || "unknown"}`);
373
+ }
204
374
  });
205
375
  });
206
376
  return {
@@ -210,6 +380,8 @@ export function createDaemonServer(options) {
210
380
  },
211
381
  registry,
212
382
  frontend,
383
+ workspace,
384
+ builder,
213
385
  listen: async () => {
214
386
  await new Promise((resolveListen, reject) => {
215
387
  server.once("error", reject);
@@ -229,6 +401,8 @@ export function createDaemonServer(options) {
229
401
  }
230
402
  },
231
403
  close: async () => {
404
+ clearInterval(pingTimer);
405
+ await workspace.close();
232
406
  await frontend.close();
233
407
  await new Promise((resolveClose) => {
234
408
  wss.close();
@@ -5,21 +5,46 @@ export class TargetRegistry {
5
5
  const targetId = info.tabId !== undefined ? `tab:${info.tabId}` : `client:${info.clientId}`;
6
6
  const now = new Date().toISOString();
7
7
  const existing = this.#targets.get(targetId)?.info;
8
+ const kind = info.kind || existing?.kind || "unknown";
9
+ const launchValue = (value, previous) => kind === "launch" ? value ?? previous : undefined;
8
10
  const next = {
9
11
  id: targetId,
10
12
  clientId: info.clientId,
11
13
  tabId: info.tabId,
12
14
  windowId: info.windowId,
13
- kind: info.kind || existing?.kind || "unknown",
15
+ kind,
14
16
  url: info.url || existing?.url || "",
15
17
  title: info.title || existing?.title,
16
18
  projectId: info.projectId || existing?.projectId,
19
+ projectName: info.projectName || existing?.projectName,
17
20
  sceneId: info.sceneId || existing?.sceneId,
21
+ sceneName: info.sceneName || existing?.sceneName,
18
22
  branchId: info.branchId || existing?.branchId,
23
+ branchName: info.branchName || existing?.branchName,
19
24
  extensionVersion: info.extensionVersion || existing?.extensionVersion,
20
25
  hasEditor: info.hasEditor ?? existing?.hasEditor,
21
26
  hasPc: info.hasPc ?? existing?.hasPc,
22
27
  hasRuntimeApp: info.hasRuntimeApp ?? existing?.hasRuntimeApp,
28
+ runtimeAppSource: launchValue(info.runtimeAppSource, existing?.runtimeAppSource),
29
+ runtimeAppAmbiguous: launchValue(info.runtimeAppAmbiguous, existing?.runtimeAppAmbiguous),
30
+ runtimeAppCandidateSources: launchValue(info.runtimeAppCandidateSources, existing?.runtimeAppCandidateSources),
31
+ runtimeCanvasId: launchValue(info.runtimeCanvasId, existing?.runtimeCanvasId),
32
+ engineVersion: launchValue(info.engineVersion, existing?.engineVersion),
33
+ readinessMode: launchValue(info.readinessMode, existing?.readinessMode),
34
+ pageReady: launchValue(info.pageReady, existing?.pageReady),
35
+ visibilityState: launchValue(info.visibilityState, existing?.visibilityState),
36
+ lifecycleReady: launchValue(info.lifecycleReady, existing?.lifecycleReady),
37
+ runtimeCreated: launchValue(info.runtimeCreated, existing?.runtimeCreated),
38
+ graphicsReady: launchValue(info.graphicsReady, existing?.graphicsReady),
39
+ graphicsContextLost: launchValue(info.graphicsContextLost, existing?.graphicsContextLost),
40
+ runtimeStarted: launchValue(info.runtimeStarted, existing?.runtimeStarted),
41
+ runtimeFrame: launchValue(info.runtimeFrame, existing?.runtimeFrame),
42
+ sceneLoaded: launchValue(info.sceneLoaded, existing?.sceneLoaded),
43
+ scriptsReady: launchValue(info.scriptsReady, existing?.scriptsReady),
44
+ scriptTypeCount: launchValue(info.scriptTypeCount, existing?.scriptTypeCount),
45
+ splashVisible: launchValue(info.splashVisible, existing?.splashVisible),
46
+ rootChildCount: launchValue(info.rootChildCount, existing?.rootChildCount),
47
+ readinessBlockers: launchValue(info.readinessBlockers, existing?.readinessBlockers),
23
48
  canvasCount: info.canvasCount ?? existing?.canvasCount,
24
49
  ready: Boolean(info.ready),
25
50
  connected: true,
@@ -27,17 +52,32 @@ export class TargetRegistry {
27
52
  };
28
53
  this.#targets.set(targetId, { info: next, ws });
29
54
  this.#clientToTarget.set(info.clientId, targetId);
30
- return next;
55
+ const comparable = (target) => target ? {
56
+ ...target,
57
+ lastSeen: undefined,
58
+ connected: undefined,
59
+ } : null;
60
+ return {
61
+ info: next,
62
+ connected: !existing?.connected,
63
+ changed: JSON.stringify(comparable(existing)) !== JSON.stringify(comparable(next)),
64
+ };
31
65
  }
32
66
  markDisconnected(ws) {
67
+ const disconnected = [];
33
68
  for (const [id, connection] of this.#targets.entries()) {
34
- if (connection.ws === ws) {
69
+ if (connection.ws === ws && connection.info.connected) {
35
70
  connection.info.connected = false;
36
71
  connection.info.ready = false;
37
72
  connection.info.lastSeen = new Date().toISOString();
38
73
  this.#targets.set(id, connection);
74
+ disconnected.push(connection.info);
39
75
  }
40
76
  }
77
+ return disconnected;
78
+ }
79
+ getByTabId(tabId) {
80
+ return this.#targets.get(`tab:${tabId}`)?.info;
41
81
  }
42
82
  list() {
43
83
  return Array.from(this.#targets.values())
@@ -11,7 +11,9 @@ export function normalizeError(value) {
11
11
  if (value && typeof value === "object") {
12
12
  const candidate = value;
13
13
  if (typeof candidate.code === "string" && typeof candidate.message === "string") {
14
- return { code: candidate.code, message: candidate.message };
14
+ return candidate.details === undefined
15
+ ? { code: candidate.code, message: candidate.message }
16
+ : { code: candidate.code, message: candidate.message, details: candidate.details };
15
17
  }
16
18
  if (typeof candidate.message === "string") {
17
19
  return { code: "PAGE_ERROR", message: candidate.message };