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/extension/main.js CHANGED
@@ -5,6 +5,80 @@
5
5
  if (window.__pcbridgeMainWorld) return;
6
6
  window.__pcbridgeMainWorld = true;
7
7
 
8
+ const MAX_LOGS = 500;
9
+ const capturedLogs = [];
10
+ let nextLogSeq = 1;
11
+
12
+ function formatLogArg(value) {
13
+ if (typeof value === "string") return value;
14
+ if (value instanceof Error) return value.stack || value.message;
15
+ try {
16
+ return JSON.stringify(serialize(value, {
17
+ maxDepth: 3,
18
+ maxArray: 20,
19
+ maxKeys: 30,
20
+ maxString: 1000
21
+ }));
22
+ } catch {
23
+ return String(value);
24
+ }
25
+ }
26
+
27
+ function pushLog(level, args, source) {
28
+ const list = Array.from(args || []);
29
+ const entry = {
30
+ seq: nextLogSeq,
31
+ time: new Date().toISOString(),
32
+ level,
33
+ source,
34
+ text: list.map(formatLogArg).join(" "),
35
+ args: list.map((item) => serialize(item, {
36
+ maxDepth: 3,
37
+ maxArray: 20,
38
+ maxKeys: 30,
39
+ maxString: 1000
40
+ }))
41
+ };
42
+ nextLogSeq += 1;
43
+ capturedLogs.push(entry);
44
+ while (capturedLogs.length > MAX_LOGS) capturedLogs.shift();
45
+ }
46
+
47
+ function patchConsoleCapture() {
48
+ if (window.__pcbridgeConsoleCapture) return;
49
+ window.__pcbridgeConsoleCapture = true;
50
+
51
+ const methods = ["debug", "log", "info", "warn", "error"];
52
+ for (const method of methods) {
53
+ const original = window.console && window.console[method];
54
+ if (typeof original !== "function") continue;
55
+ window.console[method] = function pcbridgeConsoleProxy(...args) {
56
+ try {
57
+ pushLog(method === "log" ? "info" : method, args, "console");
58
+ } catch {
59
+ // Preserve page console behavior even if log serialization fails.
60
+ }
61
+ return original.apply(this, args);
62
+ };
63
+ }
64
+
65
+ window.addEventListener("error", (event) => {
66
+ pushLog("error", [
67
+ event.message || "Uncaught error",
68
+ event.filename || "",
69
+ event.lineno || 0,
70
+ event.colno || 0,
71
+ event.error || null
72
+ ], "window.error");
73
+ });
74
+
75
+ window.addEventListener("unhandledrejection", (event) => {
76
+ pushLog("error", ["Unhandled promise rejection", event.reason || null], "unhandledrejection");
77
+ });
78
+ }
79
+
80
+ patchConsoleCapture();
81
+
8
82
  function safeGetEditorValue(value, path) {
9
83
  try {
10
84
  return value && typeof value.get === "function" ? value.get(path) : undefined;
@@ -71,11 +145,14 @@
71
145
  if (editorSummary) return editorSummary;
72
146
 
73
147
  if (current instanceof Error) {
74
- return {
148
+ const normalized = {
75
149
  name: current.name,
76
150
  message: current.message,
77
151
  stack: current.stack
78
152
  };
153
+ if (typeof current.code === "string") normalized.code = current.code;
154
+ if (current.details !== undefined) normalized.details = normalize(current.details, depth + 1);
155
+ return normalized;
79
156
  }
80
157
 
81
158
  if (depth >= settings.maxDepth) {
@@ -108,23 +185,311 @@
108
185
  return normalize(value, 0);
109
186
  }
110
187
 
188
+ function getTargetKind() {
189
+ if (location.hostname === "launch.playcanvas.com") return "launch";
190
+ if (location.pathname.startsWith("/editor")) return "editor";
191
+ return "playcanvas";
192
+ }
193
+
194
+ function getAppCanvas(app) {
195
+ return (
196
+ (app && app.graphicsDevice && app.graphicsDevice.canvas) ||
197
+ (app && app.canvas) ||
198
+ null
199
+ );
200
+ }
201
+
202
+ function getPrimaryCanvas(app) {
203
+ return getAppCanvas(app) || document.querySelector("canvas");
204
+ }
205
+
206
+ function isVisibleElement(element) {
207
+ if (!element) return false;
208
+ const style = typeof window.getComputedStyle === "function"
209
+ ? window.getComputedStyle(element)
210
+ : null;
211
+ if (
212
+ style &&
213
+ (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0)
214
+ ) {
215
+ return false;
216
+ }
217
+ if (typeof element.getBoundingClientRect !== "function") return true;
218
+ const rect = element.getBoundingClientRect();
219
+ return rect.width > 0 && rect.height > 0;
220
+ }
221
+
222
+ function runtimeRegistryEntries(registry) {
223
+ if (!registry) return [];
224
+ if (typeof registry.entries === "function") {
225
+ try {
226
+ return Array.from(registry.entries());
227
+ } catch {
228
+ // Fall through to object entries.
229
+ }
230
+ }
231
+ if (Array.isArray(registry)) return registry.map((app, index) => [String(index), app]);
232
+ if (typeof registry === "object") return Object.entries(registry);
233
+ return [];
234
+ }
235
+
236
+ function isLiveRuntimeApp(app) {
237
+ return Boolean(app && app.root);
238
+ }
239
+
240
+ function resolveRuntimeApp() {
241
+ const explicitCandidates = [];
242
+ const fallbackCandidates = [];
243
+ const seen = new Set();
244
+ const add = (list, app, source) => {
245
+ if (!isLiveRuntimeApp(app) || seen.has(app)) return;
246
+ seen.add(app);
247
+ list.push({ app, source, order: list.length });
248
+ };
249
+ const callGetter = (list, owner, id, source) => {
250
+ try {
251
+ if (owner && typeof owner.getApplication === "function") {
252
+ add(list, owner.getApplication(id), source);
253
+ }
254
+ } catch {
255
+ // Continue through the compatibility fallbacks.
256
+ }
257
+ };
258
+
259
+ const pc = window.pc;
260
+ try {
261
+ if (window.editor && typeof window.editor.call === "function") {
262
+ add(explicitCandidates, window.editor.call("viewport:app"), "editor.call(viewport:app)");
263
+ }
264
+ } catch {
265
+ // Launch can expose only a partial Editor event bus during startup.
266
+ }
267
+ const canvasIds = [
268
+ "application-canvas",
269
+ ...Array.from(document.querySelectorAll("canvas"))
270
+ .map((canvas) => canvas && canvas.id)
271
+ .filter((id) => id && id !== "application-canvas")
272
+ ];
273
+ for (const id of canvasIds) {
274
+ callGetter(
275
+ explicitCandidates,
276
+ pc && pc.AppBase,
277
+ id,
278
+ "pc.AppBase.getApplication(" + id + ")"
279
+ );
280
+ }
281
+ for (const [owner, label] of [
282
+ [pc && pc.AppBase, "pc.AppBase._applications"],
283
+ [pc && pc.Application, "pc.Application._applications"]
284
+ ]) {
285
+ for (const id of canvasIds) {
286
+ const match = runtimeRegistryEntries(owner && owner._applications)
287
+ .find(([key]) => String(key) === String(id));
288
+ if (match) add(explicitCandidates, match[1], label + "[" + id + "]");
289
+ }
290
+ }
291
+ for (const id of canvasIds) {
292
+ callGetter(
293
+ explicitCandidates,
294
+ pc && pc.Application,
295
+ id,
296
+ "pc.Application.getApplication(" + id + ")"
297
+ );
298
+ }
299
+
300
+ if (explicitCandidates.length) {
301
+ const selected = explicitCandidates[0];
302
+ return {
303
+ ...selected,
304
+ canvas: getAppCanvas(selected.app),
305
+ rootChildCount: selected.app.root && Array.isArray(selected.app.root.children)
306
+ ? selected.app.root.children.length
307
+ : 0,
308
+ score: null
309
+ };
310
+ }
311
+
312
+ callGetter(fallbackCandidates, pc && pc.AppBase, undefined, "pc.AppBase.getApplication()");
313
+ callGetter(fallbackCandidates, pc && pc.Application, undefined, "pc.Application.getApplication()");
314
+
315
+ for (const [owner, label] of [
316
+ [pc && pc.AppBase, "pc.AppBase._applications"],
317
+ [pc && pc.Application, "pc.Application._applications"]
318
+ ]) {
319
+ for (const [key, app] of runtimeRegistryEntries(owner && owner._applications)) {
320
+ add(fallbackCandidates, app, label + "[" + key + "]");
321
+ }
322
+ }
323
+
324
+ add(fallbackCandidates, window.app, "window.app");
325
+ add(fallbackCandidates, pc && pc.app, "pc.app");
326
+
327
+ const ownedMatches = fallbackCandidates.filter((candidate) => {
328
+ const canvas = getAppCanvas(candidate.app);
329
+ return Boolean(canvas && canvas.id && canvasIds.includes(canvas.id));
330
+ });
331
+ const mainCanvasMatches = ownedMatches.filter(
332
+ (candidate) => getAppCanvas(candidate.app).id === "application-canvas"
333
+ );
334
+ const selected = mainCanvasMatches.length === 1
335
+ ? mainCanvasMatches[0]
336
+ : ownedMatches.length === 1
337
+ ? ownedMatches[0]
338
+ : fallbackCandidates.length === 1
339
+ ? fallbackCandidates[0]
340
+ : null;
341
+ if (selected) {
342
+ return {
343
+ ...selected,
344
+ canvas: getAppCanvas(selected.app),
345
+ rootChildCount: Array.isArray(selected.app.root.children)
346
+ ? selected.app.root.children.length
347
+ : 0,
348
+ ambiguous: false,
349
+ candidateSources: fallbackCandidates.map((candidate) => candidate.source)
350
+ };
351
+ }
352
+
353
+ return {
354
+ app: null,
355
+ source: null,
356
+ canvas: null,
357
+ rootChildCount: 0,
358
+ ambiguous: fallbackCandidates.length > 1,
359
+ candidateSources: fallbackCandidates.map((candidate) => candidate.source)
360
+ };
361
+ }
362
+
363
+ function getScriptTypeCount(app) {
364
+ try {
365
+ return app && app.scripts && typeof app.scripts.list === "function"
366
+ ? app.scripts.list().length
367
+ : null;
368
+ } catch {
369
+ return null;
370
+ }
371
+ }
372
+
373
+ function getRuntimeApp() {
374
+ return resolveRuntimeApp().app;
375
+ }
376
+
377
+ function isLaunchSplashVisible() {
378
+ const selectors = [
379
+ "#application-splash-wrapper",
380
+ "#application-splash",
381
+ ".application-splash-wrapper",
382
+ ".application-splash"
383
+ ];
384
+ return selectors.some((selector) => isVisibleElement(document.querySelector(selector)));
385
+ }
386
+
387
+ function getSceneIdFromUrl() {
388
+ const editorMatch = location.href.match(/\/editor\/scene\/([^/?#]+)/);
389
+ if (editorMatch) return editorMatch[1];
390
+
391
+ if (location.hostname === "launch.playcanvas.com") {
392
+ const launchMatch = location.pathname.match(/^\/([^/?#]+)/);
393
+ if (launchMatch) return launchMatch[1];
394
+ }
395
+
396
+ return undefined;
397
+ }
398
+
111
399
  function describeTarget() {
112
400
  const config = window.config || {};
113
- const ready = Boolean(window.editor && window.editor.api && window.editor.api.globals);
114
- const matchScene = location.href.match(/\/editor\/scene\/([^/?#]+)/);
401
+ const kind = getTargetKind();
402
+ const editorReady = Boolean(window.editor && window.editor.api && window.editor.api.globals);
403
+ const runtime = resolveRuntimeApp();
404
+ const app = runtime.app;
405
+ const canvasCount = document.querySelectorAll("canvas").length;
406
+ const pageReady = document.readyState !== "loading";
407
+ const visibilityState = document.visibilityState || "unknown";
408
+ const runtimeCreated = Boolean(app && app.root);
409
+ const ownedCanvas = getAppCanvas(app);
410
+ const graphicsContextLost = Boolean(app && app.graphicsDevice && app.graphicsDevice.contextLost);
411
+ const graphicsReady = Boolean(
412
+ runtimeCreated && app.graphicsDevice && ownedCanvas && !graphicsContextLost
413
+ );
414
+ const rootChildren = app && app.root && Array.isArray(app.root.children)
415
+ ? app.root.children
416
+ : [];
417
+ const sceneRoot = app && app.scene ? app.scene.root : null;
418
+ const sceneLoaded = Boolean(
419
+ graphicsReady && rootChildren.length > 0 && (!sceneRoot || rootChildren.includes(sceneRoot))
420
+ );
421
+ const runtimeFrame = app && Number.isFinite(Number(app.frame)) ? Number(app.frame) : null;
422
+ const runtimeStarted = Boolean(sceneLoaded && runtimeFrame !== null && runtimeFrame > 0);
423
+ const scriptsReady = runtimeStarted;
424
+ const scriptTypeCount = getScriptTypeCount(app);
425
+ const splashVisible = kind === "launch" && isLaunchSplashVisible();
426
+ const lifecycleReady = Boolean(
427
+ pageReady && runtimeCreated && graphicsReady && sceneLoaded && runtimeStarted && !splashVisible
428
+ );
429
+ const readinessBlockers = [];
430
+ if (kind === "launch") {
431
+ if (!pageReady) readinessBlockers.push("page-loading");
432
+ if (visibilityState !== "visible") readinessBlockers.push("tab-hidden");
433
+ if (!runtimeCreated) readinessBlockers.push("runtime-not-created");
434
+ if (runtimeCreated && graphicsContextLost) readinessBlockers.push("graphics-context-lost");
435
+ if (runtimeCreated && !graphicsReady && !graphicsContextLost) {
436
+ readinessBlockers.push("graphics-not-ready");
437
+ }
438
+ if (runtimeCreated && !sceneLoaded) readinessBlockers.push("scene-not-loaded");
439
+ if (sceneLoaded && !runtimeStarted) readinessBlockers.push("runtime-not-started");
440
+ if (splashVisible) readinessBlockers.push("splash-visible");
441
+ }
442
+ const launchReady = kind === "launch" && lifecycleReady && visibilityState === "visible";
443
+ const ready = kind === "launch" ? launchReady : editorReady;
115
444
  return {
445
+ kind,
116
446
  url: location.href,
117
447
  title: document.title || "",
118
448
  ready,
449
+ hasEditor: Boolean(window.editor),
450
+ hasPc: Boolean(window.pc),
451
+ hasRuntimeApp: Boolean(app),
452
+ runtimeAppSource: runtime.source || undefined,
453
+ runtimeAppAmbiguous: kind === "launch" ? Boolean(runtime.ambiguous) : undefined,
454
+ runtimeAppCandidateSources: kind === "launch" ? runtime.candidateSources || [] : undefined,
455
+ runtimeCanvasId: app && runtime.canvas && runtime.canvas.id
456
+ ? String(runtime.canvas.id)
457
+ : undefined,
458
+ engineVersion: kind === "launch" && window.pc && window.pc.version
459
+ ? String(window.pc.version)
460
+ : undefined,
461
+ readinessMode: kind === "launch" ? "heuristic" : undefined,
462
+ pageReady: kind === "launch" ? pageReady : undefined,
463
+ visibilityState: kind === "launch" ? visibilityState : undefined,
464
+ lifecycleReady: kind === "launch" ? lifecycleReady : undefined,
465
+ runtimeCreated: kind === "launch" ? runtimeCreated : undefined,
466
+ graphicsReady: kind === "launch" ? graphicsReady : undefined,
467
+ graphicsContextLost: kind === "launch" ? graphicsContextLost : undefined,
468
+ runtimeStarted: kind === "launch" ? runtimeStarted : undefined,
469
+ runtimeFrame: kind === "launch" ? runtimeFrame : undefined,
470
+ sceneLoaded: kind === "launch" ? sceneLoaded : undefined,
471
+ scriptsReady: kind === "launch" ? scriptsReady : undefined,
472
+ scriptTypeCount: kind === "launch" ? scriptTypeCount : undefined,
473
+ splashVisible: kind === "launch" ? splashVisible : undefined,
474
+ rootChildCount: kind === "launch" ? runtime.rootChildCount : undefined,
475
+ readinessBlockers: kind === "launch" ? readinessBlockers : undefined,
476
+ canvasCount,
119
477
  projectId: config.project && config.project.id ? String(config.project.id) : undefined,
478
+ projectName: config.project && config.project.name ? String(config.project.name) : undefined,
120
479
  sceneId:
121
480
  (config.scene && config.scene.id ? String(config.scene.id) : undefined) ||
122
- (matchScene ? matchScene[1] : undefined),
481
+ getSceneIdFromUrl(),
482
+ sceneName: config.scene && config.scene.name ? String(config.scene.name) : undefined,
123
483
  branchId:
124
484
  (config.self && config.self.branch && config.self.branch.id
125
485
  ? String(config.self.branch.id)
126
486
  : undefined) ||
127
- (config.branch && config.branch.id ? String(config.branch.id) : undefined)
487
+ (config.branch && config.branch.id ? String(config.branch.id) : undefined),
488
+ branchName:
489
+ (config.self && config.self.branch && config.self.branch.name
490
+ ? String(config.self.branch.name)
491
+ : undefined) ||
492
+ (config.branch && config.branch.name ? String(config.branch.name) : undefined)
128
493
  };
129
494
  }
130
495
 
@@ -200,6 +565,122 @@
200
565
  return bytes;
201
566
  }
202
567
 
568
+ function base64FromBytes(bytes) {
569
+ const chunkSize = 0x8000;
570
+ let binary = "";
571
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
572
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
573
+ }
574
+ return btoa(binary);
575
+ }
576
+
577
+ function requireEditorAsset(assetId) {
578
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
579
+ throw new Error("Workspace operations require a ready PlayCanvas Editor target.");
580
+ }
581
+ const asset = window.editor.api.globals.assets.get(Number(assetId));
582
+ if (!asset) throw new Error("Asset not found: " + assetId);
583
+ return asset;
584
+ }
585
+
586
+ async function fetchAssetFile(asset) {
587
+ const filename = asset.get("file.filename") || asset.get("name");
588
+ if (!filename) throw new Error("Asset has no downloadable file: " + asset.get("id"));
589
+ const branchId =
590
+ (window.config && window.config.self && window.config.self.branch && window.config.self.branch.id) ||
591
+ (window.config && window.config.branch && window.config.branch.id);
592
+ const query = branchId ? "?branchId=" + encodeURIComponent(String(branchId)) : "";
593
+ const headers = {};
594
+ const accessToken = window.editor.api.globals.accessToken;
595
+ if (accessToken) headers.Authorization = "Bearer " + accessToken;
596
+ const response = await fetch(
597
+ "/api/assets/" + encodeURIComponent(String(asset.get("id"))) +
598
+ "/file/" + encodeURIComponent(String(filename)) + query,
599
+ { headers }
600
+ );
601
+ if (!response.ok) {
602
+ const body = await response.text().catch(() => "");
603
+ throw new Error(body || "Failed to download asset " + asset.get("id") + ".");
604
+ }
605
+ return { response, filename };
606
+ }
607
+
608
+ function workspaceSnapshot() {
609
+ if (!window.editor || !window.editor.api || !window.editor.api.globals) {
610
+ throw new Error("Workspace operations require a ready PlayCanvas Editor target.");
611
+ }
612
+ return {
613
+ assets: window.editor.api.globals.assets.list().map(readAsset)
614
+ };
615
+ }
616
+
617
+ async function readAssetText(params) {
618
+ const asset = requireEditorAsset(params.assetId);
619
+ if (asset.get("type") !== "script") {
620
+ throw new Error("Asset is not a script: " + params.assetId);
621
+ }
622
+ const { response, filename } = await fetchAssetFile(asset);
623
+ return {
624
+ assetId: String(asset.get("id")),
625
+ filename,
626
+ text: await response.text()
627
+ };
628
+ }
629
+
630
+ async function readAssetFile(params) {
631
+ const asset = requireEditorAsset(params.assetId);
632
+ const { response, filename } = await fetchAssetFile(asset);
633
+ const bytes = new Uint8Array(await response.arrayBuffer());
634
+ return {
635
+ assetId: String(asset.get("id")),
636
+ filename,
637
+ mime: response.headers.get("content-type") || "application/octet-stream",
638
+ size: bytes.length,
639
+ base64: base64FromBytes(bytes)
640
+ };
641
+ }
642
+
643
+ async function writeScriptText(params) {
644
+ const asset = requireEditorAsset(params.assetId);
645
+ if (asset.get("type") !== "script") {
646
+ throw new Error("Asset is not a script: " + params.assetId);
647
+ }
648
+ const filename = asset.get("file.filename") || asset.get("name");
649
+ const form = new FormData();
650
+ form.append("filename", filename);
651
+ form.append("file", new Blob([String(params.text || "")], { type: "text/javascript" }), filename);
652
+ const branchId =
653
+ (window.config && window.config.self && window.config.self.branch && window.config.self.branch.id) ||
654
+ (window.config && window.config.branch && window.config.branch.id);
655
+ if (branchId) form.append("branchId", String(branchId));
656
+ const headers = {};
657
+ const accessToken = window.editor.api.globals.accessToken;
658
+ if (accessToken) headers.Authorization = "Bearer " + accessToken;
659
+ const response = await fetch("/api/assets/" + encodeURIComponent(String(asset.get("id"))), {
660
+ method: "PUT",
661
+ headers,
662
+ body: form
663
+ });
664
+ const body = await response.json().catch(() => ({}));
665
+ if (!response.ok || body.error) {
666
+ throw new Error(body.error || "Failed to update script asset.");
667
+ }
668
+
669
+ const parseResult = await new Promise((resolve, reject) => {
670
+ window.editor.call("scripts:parse", asset.observer, (error, data) => {
671
+ if (error) reject(new Error(String(error)));
672
+ else resolve(data || {});
673
+ });
674
+ });
675
+ return {
676
+ assetId: String(asset.get("id")),
677
+ filename,
678
+ parsed: true,
679
+ scripts: parseResult.scripts || {},
680
+ response: body
681
+ };
682
+ }
683
+
203
684
  function withTimeout(promise, timeoutMs) {
204
685
  return new Promise((resolve, reject) => {
205
686
  const timer = setTimeout(() => reject(new Error(`Timed out after ${timeoutMs}ms.`)), timeoutMs);
@@ -233,6 +714,7 @@
233
714
  editor: window.editor,
234
715
  pc: window.pc,
235
716
  pcui: window.pcui,
717
+ runtimeApp: getRuntimeApp(),
236
718
  command,
237
719
  serialize
238
720
  };
@@ -246,6 +728,7 @@
246
728
  const editor = ctx.editor;
247
729
  const pc = ctx.pc;
248
730
  const pcui = ctx.pcui;
731
+ const runtimeApp = ctx.runtimeApp;
249
732
  const command = ctx.command;
250
733
  const serialize = ctx.serialize;
251
734
  return (async () => {
@@ -254,21 +737,35 @@
254
737
  `
255
738
  );
256
739
 
257
- return serialize(await withTimeout(fn(context), timeoutMs));
740
+ return serialize(await withTimeout(fn(context), timeoutMs), params.serializeOptions);
258
741
  }
259
742
 
260
- function captureViewport(params) {
261
- const app = window.editor.call("viewport:app");
262
- if (!app) throw new Error("Viewport app not found.");
263
- const device = app.graphicsDevice;
264
- const gl = device && device.gl;
265
- if (!gl) throw new Error("WebGL context not found.");
743
+ function encodeCanvas(canvas, params, source) {
744
+ const maxWidth = Number(params.maxWidth || 1200);
745
+ let outWidth = canvas.width;
746
+ let outHeight = canvas.height;
747
+ if (maxWidth > 0 && canvas.width > maxWidth) {
748
+ outWidth = maxWidth;
749
+ outHeight = Math.round(canvas.height * (maxWidth / canvas.width));
750
+ }
266
751
 
267
- window.editor.call("viewport:render");
268
- app.tick();
752
+ const dstCanvas = document.createElement("canvas");
753
+ dstCanvas.width = outWidth;
754
+ dstCanvas.height = outHeight;
755
+ dstCanvas.getContext("2d").drawImage(canvas, 0, 0, outWidth, outHeight);
269
756
 
270
- const width = device.width;
271
- const height = device.height;
757
+ const mime = params.format === "webp" ? "image/webp" : "image/png";
758
+ const dataUrl = dstCanvas.toDataURL(mime, Number(params.quality || 0.85));
759
+ return {
760
+ mime,
761
+ width: outWidth,
762
+ height: outHeight,
763
+ source,
764
+ base64: dataUrl.split(",")[1]
765
+ };
766
+ }
767
+
768
+ function canvasFromWebglPixels(gl, width, height) {
272
769
  const pixels = new Uint8Array(width * height * 4);
273
770
  gl.bindFramebuffer(gl.FRAMEBUFFER, null);
274
771
  gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
@@ -288,30 +785,114 @@
288
785
  srcCanvas
289
786
  .getContext("2d")
290
787
  .putImageData(new ImageData(new Uint8ClampedArray(flipped.buffer), width, height), 0, 0);
788
+ return srcCanvas;
789
+ }
291
790
 
292
- const maxWidth = Number(params.maxWidth || 1200);
293
- let outWidth = width;
294
- let outHeight = height;
295
- if (maxWidth > 0 && width > maxWidth) {
296
- outWidth = maxWidth;
297
- outHeight = Math.round(height * (maxWidth / width));
791
+ function captureEditorViewport(params) {
792
+ const app = window.editor.call("viewport:app");
793
+ if (!app) throw new Error("Viewport app not found.");
794
+ const device = app.graphicsDevice;
795
+ const gl = device && device.gl;
796
+ if (!gl) throw new Error("WebGL context not found.");
797
+
798
+ window.editor.call("viewport:render");
799
+ app.tick();
800
+
801
+ const width = device.width;
802
+ const height = device.height;
803
+ const srcCanvas = canvasFromWebglPixels(gl, width, height);
804
+ return encodeCanvas(srcCanvas, params, "editor-viewport");
805
+ }
806
+
807
+ function getCanvasWebglContext(canvas) {
808
+ const app = getRuntimeApp();
809
+ const appCanvas = getPrimaryCanvas(app);
810
+ if (appCanvas === canvas && app && app.graphicsDevice && app.graphicsDevice.gl) {
811
+ return app.graphicsDevice.gl;
298
812
  }
299
813
 
300
- const dstCanvas = document.createElement("canvas");
301
- dstCanvas.width = outWidth;
302
- dstCanvas.height = outHeight;
303
- dstCanvas.getContext("2d").drawImage(srcCanvas, 0, 0, outWidth, outHeight);
814
+ return (
815
+ canvas.getContext("webgl2") ||
816
+ canvas.getContext("webgl") ||
817
+ canvas.getContext("experimental-webgl")
818
+ );
819
+ }
820
+
821
+ function captureRuntimeCanvas(params) {
822
+ const app = getRuntimeApp();
823
+ const canvas = getPrimaryCanvas(app);
824
+ if (!canvas) {
825
+ throw new Error("PlayCanvas launch canvas not found.");
826
+ }
827
+
828
+ try {
829
+ const gl = getCanvasWebglContext(canvas);
830
+ if (gl && typeof gl.readPixels === "function") {
831
+ const width =
832
+ (app && app.graphicsDevice && app.graphicsDevice.width) ||
833
+ gl.drawingBufferWidth ||
834
+ canvas.width;
835
+ const height =
836
+ (app && app.graphicsDevice && app.graphicsDevice.height) ||
837
+ gl.drawingBufferHeight ||
838
+ canvas.height;
839
+ const srcCanvas = canvasFromWebglPixels(gl, width, height);
840
+ return encodeCanvas(srcCanvas, params, "launch-webgl");
841
+ }
842
+ } catch (error) {
843
+ pushLog("warn", ["WebGL capture failed; falling back to canvas capture.", error], "pcbridge");
844
+ }
845
+
846
+ return encodeCanvas(canvas, params, "launch-canvas");
847
+ }
848
+
849
+ function captureViewport(params) {
850
+ if (window.editor && typeof window.editor.call === "function") {
851
+ return captureEditorViewport(params);
852
+ }
853
+
854
+ return captureRuntimeCanvas(params);
855
+ }
856
+
857
+ function getLogs(params) {
858
+ const level = params.level ? String(params.level).toLowerCase() : null;
859
+ const since = params.since === undefined || params.since === null || params.since === ""
860
+ ? null
861
+ : Number(params.since);
862
+ const limit = Math.max(1, Math.min(Number(params.limit || 100), 500));
863
+ let items = capturedLogs;
864
+
865
+ if (level) {
866
+ items = items.filter((entry) => entry.level === level);
867
+ }
868
+ if (since !== null && Number.isFinite(since)) {
869
+ items = items.filter((entry) => entry.seq > since);
870
+ }
871
+
872
+ const total = items.length;
873
+ const hasExplicitOffset =
874
+ params.offset !== undefined && params.offset !== null && params.offset !== "";
875
+ const offset = hasExplicitOffset
876
+ ? Math.max(0, Number(params.offset || 0))
877
+ : Math.max(0, total - limit);
878
+ const page = items.slice(offset, offset + limit);
304
879
 
305
- const mime = params.format === "webp" ? "image/webp" : "image/png";
306
- const dataUrl = dstCanvas.toDataURL(mime, Number(params.quality || 0.85));
307
880
  return {
308
- mime,
309
- width: outWidth,
310
- height: outHeight,
311
- base64: dataUrl.split(",")[1]
881
+ items: page,
882
+ total,
883
+ offset,
884
+ limit,
885
+ hasMore: offset + page.length < total,
886
+ nextSince: page.length ? page[page.length - 1].seq : since
312
887
  };
313
888
  }
314
889
 
890
+ function clearLogs() {
891
+ const affected = capturedLogs.length;
892
+ capturedLogs.length = 0;
893
+ return { affected };
894
+ }
895
+
315
896
  async function uploadAsset(params) {
316
897
  if (!params.base64) throw new Error("base64 file content is required.");
317
898
  if (!params.name) throw new Error("name is required.");
@@ -399,8 +980,14 @@
399
980
  if (method === "bridge:describeTarget") return describeTarget();
400
981
  if (method === "bridge:eval") return evalInPage(params || {}, requestId);
401
982
  if (method === "bridge:captureViewport") return captureViewport(params || {});
983
+ if (method === "bridge:getLogs") return getLogs(params || {});
984
+ if (method === "bridge:clearLogs") return clearLogs();
402
985
  if (method === "bridge:uploadAsset") return uploadAsset(params || {});
403
986
  if (method === "bridge:focusViewport") return focusViewport(params || {});
987
+ if (method === "bridge:workspaceSnapshot") return workspaceSnapshot();
988
+ if (method === "bridge:readAssetText") return readAssetText(params || {});
989
+ if (method === "bridge:readAssetFile") return readAssetFile(params || {});
990
+ if (method === "bridge:writeScriptText") return writeScriptText(params || {});
404
991
  throw new Error(`Unknown bridge method: ${method}`);
405
992
  }
406
993