playcanvas-agent-bridge-cli 0.3.0 → 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.
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.4.2";
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,7 @@ 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";
7
8
  import { fail, normalizeError, ok, } from "../shared/protocol.js";
8
9
  function readBody(req) {
9
10
  return new Promise((resolve, reject) => {
@@ -48,7 +49,6 @@ export function createDaemonServer(options) {
48
49
  host,
49
50
  port: options.frontendPort ?? DEFAULT_FRONTEND_PORT,
50
51
  rootDir: options.frontendRootDir || CONFIG_DIR,
51
- log,
52
52
  });
53
53
  function requireToken(req) {
54
54
  return req.headers["x-pcbridge-token"] === options.token;
@@ -94,6 +94,15 @@ export function createDaemonServer(options) {
94
94
  });
95
95
  });
96
96
  }
97
+ const workspace = new WorkspaceManager({
98
+ rootDir: options.workspaceRoot || process.cwd(),
99
+ requestTarget: (target, method, params = {}, timeoutMs = 15000) => sendToTarget({
100
+ target,
101
+ method,
102
+ params,
103
+ timeoutMs,
104
+ }),
105
+ });
97
106
  const server = http.createServer(async (req, res) => {
98
107
  try {
99
108
  const url = new URL(req.url || "/", `http://${req.headers.host || `${host}:${port}`}`);
@@ -108,6 +117,7 @@ export function createDaemonServer(options) {
108
117
  host,
109
118
  port: actualPort,
110
119
  targetCount: registry.list().filter((target) => target.connected).length,
120
+ workspaceRoot: workspace.rootDir,
111
121
  frontend: frontendStatus,
112
122
  }));
113
123
  return;
@@ -128,6 +138,85 @@ export function createDaemonServer(options) {
128
138
  writeJson(res, 200, ok(registry.list()));
129
139
  return;
130
140
  }
141
+ if (url.pathname === "/status" && req.method === "GET") {
142
+ if (!requireToken(req)) {
143
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
144
+ return;
145
+ }
146
+ const tabId = Number(url.searchParams.get("tabId"));
147
+ const target = Number.isFinite(tabId) ? registry.getByTabId(tabId) : undefined;
148
+ writeJson(res, 200, ok({
149
+ daemon: {
150
+ version: VERSION,
151
+ host,
152
+ port: actualPort,
153
+ workspaceRoot: workspace.rootDir,
154
+ targetCount: registry.list().filter((item) => item.connected).length,
155
+ },
156
+ target: target || null,
157
+ workspace: workspace.statusForTarget(target),
158
+ frontend: await frontend.status(),
159
+ }));
160
+ return;
161
+ }
162
+ if (url.pathname === "/workspace/status" && req.method === "GET") {
163
+ if (!requireToken(req)) {
164
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
165
+ return;
166
+ }
167
+ const resolved = registry.resolve(url.searchParams.get("target") || "current");
168
+ if (!resolved.ok) {
169
+ writeJson(res, 400, fail(resolved.code, resolved.message));
170
+ return;
171
+ }
172
+ writeJson(res, 200, ok(workspace.statusForTarget(resolved.target.info)));
173
+ return;
174
+ }
175
+ if (url.pathname === "/workspace/sync" && req.method === "POST") {
176
+ if (!requireToken(req)) {
177
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
178
+ return;
179
+ }
180
+ const body = await readBody(req);
181
+ const data = isJsonObject(body) ? body : {};
182
+ const selector = typeof data.target === "string" ? data.target : "current";
183
+ const resolved = registry.resolve(selector);
184
+ if (!resolved.ok) {
185
+ writeJson(res, 400, fail(resolved.code, resolved.message));
186
+ return;
187
+ }
188
+ try {
189
+ writeJson(res, 200, ok(await workspace.syncTarget(resolved.target.info)));
190
+ }
191
+ catch (error) {
192
+ writeJson(res, 400, fail("WORKSPACE_SYNC_FAILED", String(error)));
193
+ }
194
+ return;
195
+ }
196
+ if (url.pathname === "/workspace/pull" && req.method === "POST") {
197
+ if (!requireToken(req)) {
198
+ writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
199
+ return;
200
+ }
201
+ const body = await readBody(req);
202
+ if (!isJsonObject(body) || typeof body.assetId !== "string") {
203
+ writeJson(res, 400, fail("INVALID_REQUEST", "workspace pull requires assetId."));
204
+ return;
205
+ }
206
+ const selector = typeof body.target === "string" ? body.target : "current";
207
+ const resolved = registry.resolve(selector);
208
+ if (!resolved.ok) {
209
+ writeJson(res, 400, fail(resolved.code, resolved.message));
210
+ return;
211
+ }
212
+ try {
213
+ writeJson(res, 200, ok(await workspace.pullAsset(resolved.target.info, body.assetId)));
214
+ }
215
+ catch (error) {
216
+ writeJson(res, 400, fail("WORKSPACE_PULL_FAILED", String(error)));
217
+ }
218
+ return;
219
+ }
131
220
  if (url.pathname === "/rpc" && req.method === "POST") {
132
221
  if (!requireToken(req)) {
133
222
  writeJson(res, 403, fail("BAD_TOKEN", "Invalid pcbridge token."));
@@ -160,14 +249,35 @@ export function createDaemonServer(options) {
160
249
  wss.emit("connection", ws, req);
161
250
  });
162
251
  });
252
+ const liveness = new WeakMap();
253
+ const pingTimer = setInterval(() => {
254
+ for (const client of wss.clients) {
255
+ if (liveness.get(client) === false) {
256
+ client.terminate();
257
+ continue;
258
+ }
259
+ liveness.set(client, false);
260
+ client.ping();
261
+ }
262
+ }, 15000);
263
+ pingTimer.unref();
163
264
  wss.on("connection", (ws) => {
164
- log("extension connected");
265
+ liveness.set(ws, true);
266
+ ws.on("pong", () => liveness.set(ws, true));
165
267
  ws.on("message", (raw) => {
166
268
  try {
167
269
  const message = JSON.parse(raw.toString());
168
270
  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}`);
271
+ const result = registry.upsert(message.target, ws);
272
+ if (result.connected) {
273
+ log(`connected ${result.info.id} project=${result.info.projectId || "unknown"} ` +
274
+ `scene=${result.info.sceneId || "unknown"}`);
275
+ }
276
+ if (result.connected || result.changed) {
277
+ void workspace.handleTarget(result.info).catch((error) => {
278
+ log(`workspace initialization failed for ${result.info.id}: ${String(error)}`);
279
+ });
280
+ }
171
281
  return;
172
282
  }
173
283
  if (message.type === "response" && message.id) {
@@ -199,8 +309,22 @@ export function createDaemonServer(options) {
199
309
  }
200
310
  });
201
311
  ws.on("close", () => {
202
- registry.markDisconnected(ws);
203
- log("extension disconnected");
312
+ for (const info of registry.markDisconnected(ws)) {
313
+ const replacement = registry.list().find((candidate) => candidate.connected &&
314
+ candidate.ready &&
315
+ candidate.kind === "editor" &&
316
+ candidate.projectId === info.projectId &&
317
+ candidate.branchId === info.branchId);
318
+ if (replacement) {
319
+ void workspace.handleTarget(replacement).catch((error) => {
320
+ log(`workspace failover failed for ${replacement.id}: ${String(error)}`);
321
+ });
322
+ }
323
+ else
324
+ workspace.markDisconnected(info);
325
+ log(`disconnected ${info.id} project=${info.projectId || "unknown"} ` +
326
+ `scene=${info.sceneId || "unknown"}`);
327
+ }
204
328
  });
205
329
  });
206
330
  return {
@@ -210,6 +334,7 @@ export function createDaemonServer(options) {
210
334
  },
211
335
  registry,
212
336
  frontend,
337
+ workspace,
213
338
  listen: async () => {
214
339
  await new Promise((resolveListen, reject) => {
215
340
  server.once("error", reject);
@@ -229,6 +354,8 @@ export function createDaemonServer(options) {
229
354
  }
230
355
  },
231
356
  close: async () => {
357
+ clearInterval(pingTimer);
358
+ await workspace.close();
232
359
  await frontend.close();
233
360
  await new Promise((resolveClose) => {
234
361
  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 };