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/extension/main.js CHANGED
@@ -9,10 +9,8 @@
9
9
  const capturedLogs = [];
10
10
  const daemonWaiters = new Map();
11
11
  let nextLogSeq = 1;
12
- let builderPanel = null;
13
- let builderRefreshTimer = null;
14
- let selectedTemplateId = null;
15
- let selectedTemplateAsset = null;
12
+ const loadedPlugins = new Map();
13
+ let pluginSyncQueue = Promise.resolve();
16
14
  let workspaceEventsInstalled = false;
17
15
  let sceneEventsInstalled = false;
18
16
  let observedAssets = new WeakSet();
@@ -1460,96 +1458,6 @@
1460
1458
  return null;
1461
1459
  }
1462
1460
 
1463
- function collectAssetReferences(assets, value, ids, depth = 0) {
1464
- if (!value || typeof value !== "object" || depth > 100) return;
1465
- for (const [key, child] of Object.entries(value)) {
1466
- if (["id", "path", "uniqueId", "scope", "testTemplate"].includes(key)) continue;
1467
- if (Number.isInteger(child)) {
1468
- const referenced = assets.get(Number(child));
1469
- const id = String(child);
1470
- if (referenced && !ids.has(id)) {
1471
- ids.add(id);
1472
- collectAssetReferences(assets, plainAssetJson(referenced), ids, depth + 1);
1473
- }
1474
- } else if (child && typeof child === "object") {
1475
- collectAssetReferences(assets, child, ids, depth + 1);
1476
- }
1477
- }
1478
- }
1479
-
1480
- function templateScriptNames(templateData) {
1481
- const names = new Set();
1482
- for (const entity of Object.values((templateData && templateData.entities) || {})) {
1483
- const scripts = entity && entity.components && entity.components.script &&
1484
- entity.components.script.scripts;
1485
- for (const name of Object.keys(scripts || {})) names.add(name);
1486
- }
1487
- return [...names];
1488
- }
1489
-
1490
- function templateChildren(templateData) {
1491
- const ids = new Set();
1492
- for (const entity of Object.values((templateData && templateData.entities) || {})) {
1493
- const attributes = entity && entity.components && entity.components.script &&
1494
- entity.components.script.scripts &&
1495
- entity.components.script.scripts.sdsTinyRootHandler &&
1496
- entity.components.script.scripts.sdsTinyRootHandler.attributes;
1497
- if (attributes && attributes.type === "testTemplate" && Number.isInteger(attributes.testTemplate)) {
1498
- ids.add(String(attributes.testTemplate));
1499
- }
1500
- }
1501
- return [...ids];
1502
- }
1503
-
1504
- function collectTemplateDependencies(params) {
1505
- if (!window.editor || !window.editor.api || !window.editor.api.globals) {
1506
- throw new Error("Template builds require a ready PlayCanvas Editor target.");
1507
- }
1508
- const assets = window.editor.api.globals.assets;
1509
- const template = assets.get(Number(params.assetId));
1510
- if (!template || template.get("type") !== "template") {
1511
- throw new Error("Template asset not found: " + params.assetId);
1512
- }
1513
- const templateJson = plainAssetJson(template);
1514
- if (!templateJson || !templateJson.data) {
1515
- throw new Error("Template asset has no serializable data: " + params.assetId);
1516
- }
1517
-
1518
- const ids = new Set();
1519
- collectAssetReferences(assets, templateJson.data, ids);
1520
- const scripts = [];
1521
- for (const name of templateScriptNames(templateJson.data)) {
1522
- const scriptAsset =
1523
- (typeof assets.getAssetForScript === "function" && assets.getAssetForScript(name)) ||
1524
- (window.editor.assets && typeof window.editor.assets.getAssetForScript === "function" &&
1525
- window.editor.assets.getAssetForScript(name)) ||
1526
- assets.list().find((asset) =>
1527
- asset.get("type") === "script" &&
1528
- (asset.get("name") === name || asset.get("data.scripts." + name) !== undefined)
1529
- );
1530
- if (!scriptAsset) continue;
1531
- const scriptJson = plainAssetJson(scriptAsset);
1532
- const filename = scriptJson && scriptJson.file && scriptJson.file.filename;
1533
- if (
1534
- name.startsWith("sds") ||
1535
- String(filename || (scriptJson && scriptJson.name) || "").startsWith("sds")
1536
- ) continue;
1537
- ids.add(String(scriptAsset.get("id")));
1538
- scripts.push({ name, assetId: String(scriptAsset.get("id")) });
1539
- }
1540
-
1541
- return {
1542
- template: templateJson,
1543
- assets: [...ids].map((id) => plainAssetJson(assets.get(Number(id)))).filter(Boolean),
1544
- scripts,
1545
- childTemplateIds: templateChildren(templateJson.data),
1546
- projectUrl: window.config && window.config.project && window.config.project.id
1547
- ? "https://playcanvas.com/project/" + window.config.project.id + "/overview"
1548
- : null,
1549
- sceneUrl: location.href
1550
- };
1551
- }
1552
-
1553
1461
  function withTimeout(promise, timeoutMs) {
1554
1462
  return new Promise((resolve, reject) => {
1555
1463
  const timer = setTimeout(() => reject(new Error(`Timed out after ${timeoutMs}ms.`)), timeoutMs);
@@ -1586,165 +1494,83 @@
1586
1494
  });
1587
1495
  }
1588
1496
 
1589
- function selectedAssetStateFromEditor() {
1590
- if (!window.editor) return { known: false, asset: null };
1591
- try {
1592
- const items = window.editor.call && window.editor.call("selector:items");
1593
- if (Array.isArray(items)) return { known: true, asset: items[0] || null };
1594
- } catch {
1595
- // Fall through to the public selection API.
1596
- }
1597
- const selection = window.editor.api && window.editor.api.globals &&
1598
- window.editor.api.globals.selection;
1599
- const items = selection && (
1600
- (Array.isArray(selection.items) && selection.items) ||
1601
- (typeof selection.list === "function" && selection.list()) ||
1602
- (typeof selection.get === "function" && selection.get())
1603
- );
1604
- return Array.isArray(items)
1605
- ? { known: true, asset: items[0] || null }
1606
- : { known: false, asset: null };
1497
+ async function disposePlugin(id) {
1498
+ const state = loadedPlugins.get(id);
1499
+ if (!state) return;
1500
+ loadedPlugins.delete(id);
1501
+ for (const dispose of state.disposers.reverse()) {
1502
+ try {
1503
+ await dispose();
1504
+ } catch (error) {
1505
+ console.warn(`[pcbridge] plugin ${id} dispose failed`, error);
1506
+ }
1507
+ }
1607
1508
  }
1608
1509
 
1609
- function destroyBuilderPanel() {
1610
- if (builderPanel && typeof builderPanel.destroy === "function") builderPanel.destroy();
1611
- builderPanel = null;
1612
- selectedTemplateId = null;
1613
- selectedTemplateAsset = null;
1510
+ async function loadPlugin(spec) {
1511
+ const state = { code: spec.code, handlers: new Map(), disposers: [] };
1512
+ loadedPlugins.set(spec.id, state);
1513
+ const plugin = {
1514
+ id: spec.id,
1515
+ version: spec.version,
1516
+ kind: getTargetKind(),
1517
+ handle(name, handler) { state.handlers.set(String(name), handler); },
1518
+ onDispose(dispose) { state.disposers.push(dispose); },
1519
+ call(name, params, timeoutMs) {
1520
+ return daemonRequest(
1521
+ `/plugins/${spec.id}/actions/${encodeURIComponent(name)}`,
1522
+ "POST",
1523
+ { params: params || {} },
1524
+ timeoutMs
1525
+ );
1526
+ }
1527
+ };
1528
+ const run = new window.Function(
1529
+ "plugin",
1530
+ "editor",
1531
+ "pc",
1532
+ "pcui",
1533
+ "runtimeApp",
1534
+ `return (async () => {\n${spec.code}\n})();\n//# sourceURL=pcbridge-plugin/${spec.id}/${plugin.kind}.js`
1535
+ );
1536
+ await withTimeout(run(plugin, window.editor, window.pc, window.pcui, getRuntimeApp()), 10000);
1614
1537
  }
1615
1538
 
1616
- function builderPanelIsAttached(layout) {
1617
- if (!builderPanel || builderPanel.destroyed === true) return false;
1618
- if (builderPanel.dom && typeof builderPanel.dom.isConnected === "boolean") {
1619
- return builderPanel.dom.isConnected;
1539
+ async function applyPluginSync(params) {
1540
+ const wanted = new Map(params.plugins.map((spec) => [spec.id, spec]));
1541
+ for (const [id, state] of [...loadedPlugins]) {
1542
+ const spec = wanted.get(id);
1543
+ if (!spec || spec.code !== state.code) await disposePlugin(id);
1544
+ }
1545
+ const plugins = [];
1546
+ for (const spec of wanted.values()) {
1547
+ if (!loadedPlugins.has(spec.id)) {
1548
+ try {
1549
+ await loadPlugin(spec);
1550
+ } catch (error) {
1551
+ await disposePlugin(spec.id);
1552
+ plugins.push({ id: spec.id, ok: false, error: String((error && error.message) || error) });
1553
+ continue;
1554
+ }
1555
+ }
1556
+ plugins.push({ id: spec.id, ok: true });
1620
1557
  }
1621
- if ("parent" in builderPanel) return builderPanel.parent === layout;
1622
- return true;
1558
+ return { plugins };
1623
1559
  }
1624
1560
 
1625
- function appendRow(pcui, container, labelText, control) {
1626
- const row = new pcui.Container();
1627
- row.flex = true;
1628
- row.flexDirection = "row";
1629
- row.append(new pcui.Label({ text: labelText }));
1630
- row.append(control);
1631
- container.append(row);
1561
+ // A sync must finish before the next starts, or a plugin still activating could outlive its disposal.
1562
+ function syncPlugins(params) {
1563
+ const run = () => applyPluginSync(params);
1564
+ pluginSyncQueue = pluginSyncQueue.then(run, run);
1565
+ return pluginSyncQueue;
1632
1566
  }
1633
1567
 
1634
- function showBuilderPanel(asset) {
1635
- const type = asset && typeof asset.get === "function" ? asset.get("type") : null;
1636
- const id = asset && typeof asset.get === "function" ? String(asset.get("id")) : null;
1637
- if (type !== "template" || !id) {
1638
- destroyBuilderPanel();
1639
- return;
1640
- }
1641
- const pcui = window.pcui;
1642
- const layout = window.editor && window.editor.call && window.editor.call("layout.attributes");
1643
- if (!pcui || !pcui.Container || !pcui.Button || !pcui.Label || !pcui.TextInput || !layout) return;
1644
- if (builderPanel && selectedTemplateId === id && builderPanelIsAttached(layout)) return;
1645
- destroyBuilderPanel();
1646
-
1647
- const projectId = window.config && window.config.project && window.config.project.id
1648
- ? String(window.config.project.id)
1649
- : "project";
1650
- const suffixKey = `pcbridge:builder:${id}:suffix`;
1651
- const prefixKey = `pcbridge:builder:${projectId}:prefix`;
1652
- const container = new pcui.Container();
1653
- container.flex = true;
1654
- container.flexDirection = "column";
1655
- if (container.class && typeof container.class.add === "function") {
1656
- container.class.add("pcbridge-tiny-builder");
1657
- }
1658
- container.append(new pcui.Label({ text: "pcbridge Tiny Builder" }));
1659
- const prefixInput = new pcui.TextInput({ value: localStorage.getItem(prefixKey) || "" });
1660
- const suffixInput = new pcui.TextInput({ value: localStorage.getItem(suffixKey) || "" });
1661
- if (typeof prefixInput.on === "function") {
1662
- prefixInput.on("change", () => localStorage.setItem(prefixKey, String(prefixInput.value || "")));
1663
- suffixInput.on("change", () => localStorage.setItem(suffixKey, String(suffixInput.value || "")));
1664
- }
1665
- appendRow(pcui, container, "上传目录", prefixInput);
1666
- appendRow(pcui, container, "文件后缀", suffixInput);
1667
- const pathLabel = new pcui.Label({ text: localStorage.getItem(`pcbridge:builder:${id}:url`) || "" });
1668
- appendRow(pcui, container, "引用路径", pathLabel);
1669
- const buildButton = new pcui.Button({ text: "构建并上传到 S3" });
1670
- const copyButton = new pcui.Button({ text: "复制引用路径" });
1671
- const logLabel = new pcui.Label({ text: "从项目 .env 或工作区 .env 读取 S3 配置" });
1672
- copyButton.on("click", () => {
1673
- if (pathLabel.text) void navigator.clipboard.writeText(pathLabel.text);
1674
- });
1675
- buildButton.on("click", async () => {
1676
- buildButton.enabled = false;
1677
- try {
1678
- let job = await daemonRequest("/builder/jobs", "POST", {
1679
- templateAssetId: id,
1680
- suffix: String(suffixInput.value || ""),
1681
- prefix: String(prefixInput.value || "")
1682
- });
1683
- while (job && job.state !== "completed" && job.state !== "error") {
1684
- logLabel.text = job.message || job.state;
1685
- await new Promise((resolve) => setTimeout(resolve, 1000));
1686
- job = await daemonRequest(
1687
- "/builder/jobs/" + encodeURIComponent(job.id),
1688
- "GET",
1689
- {},
1690
- 30000
1691
- );
1692
- }
1693
- if (!job || job.state === "error") {
1694
- throw new Error((job && job.error) || "Template build failed.");
1695
- }
1696
- pathLabel.text = job.publicUrl || "";
1697
- localStorage.setItem(`pcbridge:builder:${id}:url`, pathLabel.text);
1698
- logLabel.text = job.message || "上传完成";
1699
- } catch (error) {
1700
- logLabel.text = "构建失败: " + String((error && error.message) || error);
1701
- } finally {
1702
- buildButton.enabled = true;
1703
- }
1704
- });
1705
- container.append(buildButton);
1706
- container.append(copyButton);
1707
- container.append(logLabel);
1708
- layout.append(container);
1709
- builderPanel = container;
1710
- selectedTemplateId = id;
1711
- selectedTemplateAsset = asset;
1712
- }
1713
-
1714
- function scheduleBuilderPanelRefresh(asset) {
1715
- if (builderRefreshTimer !== null) clearTimeout(builderRefreshTimer);
1716
- builderRefreshTimer = setTimeout(() => {
1717
- builderRefreshTimer = null;
1718
- const selection = selectedAssetStateFromEditor();
1719
- if (selection.known) showBuilderPanel(selection.asset);
1720
- else showBuilderPanel(asset || selectedTemplateAsset);
1721
- }, 150);
1722
- }
1723
-
1724
- function installBuilderPanel() {
1725
- if (!location.pathname.startsWith("/editor") || typeof setInterval !== "function") return;
1726
- let subscribed = false;
1727
- setInterval(() => {
1728
- if (!window.editor || !window.editor.api || !window.editor.api.globals) return;
1729
- if (!subscribed) {
1730
- subscribed = true;
1731
- const refresh = (asset) => scheduleBuilderPanelRefresh(asset);
1732
- const legacy = window.editor.selection;
1733
- if (legacy && typeof legacy.on === "function") {
1734
- legacy.on("add", refresh);
1735
- legacy.on("remove", () => refresh());
1736
- }
1737
- const selection = window.editor.api.globals.selection;
1738
- if (selection && typeof selection.on === "function") {
1739
- selection.on("add", refresh);
1740
- selection.on("remove", () => refresh());
1741
- selection.on("change", () => refresh());
1742
- }
1743
- }
1744
- const selection = selectedAssetStateFromEditor();
1745
- if (selection.known) showBuilderPanel(selection.asset);
1746
- else if (selectedTemplateAsset) showBuilderPanel(selectedTemplateAsset);
1747
- }, 1000);
1568
+ function callPlugin(method, params) {
1569
+ const [, id, name] = method.match(/^plugin:([^:]+):(.+)$/) || [];
1570
+ const state = loadedPlugins.get(id);
1571
+ const handler = state && state.handlers.get(name);
1572
+ if (!handler) throw new Error(`Plugin page handler not found: ${method}`);
1573
+ return handler(params);
1748
1574
  }
1749
1575
 
1750
1576
  async function evalInPage(params, requestId) {
@@ -2064,7 +1890,8 @@
2064
1890
  installWorkspaceEvents();
2065
1891
  return workspaceSnapshot();
2066
1892
  }
2067
- if (method === "bridge:collectTemplateDependencies") return collectTemplateDependencies(params || {});
1893
+ if (method === "bridge:syncPlugins") return syncPlugins(params || {});
1894
+ if (method.startsWith("plugin:")) return callPlugin(method, params || {});
2068
1895
  if (method === "bridge:readAssetText") return readAssetText(params || {});
2069
1896
  if (method === "bridge:readAssetFile") return readAssetFile(params || {});
2070
1897
  if (method === "bridge:readAssetResource") return readAssetResource(params || {});
@@ -2125,6 +1952,5 @@
2125
1952
  }
2126
1953
  });
2127
1954
 
2128
- installBuilderPanel();
2129
1955
  window.postMessage({ channel: CHANNEL, side: "main", type: "ready" }, "*");
2130
1956
  })();
@@ -2,7 +2,7 @@
2
2
  "manifest_version": 3,
3
3
  "name": "PlayCanvas Agent Bridge",
4
4
  "description": "Connects open PlayCanvas Editor and Launch tabs to the local pcbridge daemon.",
5
- "version": "0.6.2",
5
+ "version": "0.7.0",
6
6
  "permissions": [
7
7
  "activeTab",
8
8
  "storage",
@@ -161,6 +161,38 @@
161
161
  button.primary { background: oklch(0.58 0.16 246); border-color: oklch(0.66 0.16 246); }
162
162
  button:disabled { cursor: not-allowed; opacity: 0.4; }
163
163
  button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
164
+
165
+ nav { border-bottom: 1px solid var(--border); display: grid; grid-template-columns: 1fr 1fr; }
166
+ nav button {
167
+ background: none;
168
+ border: 0;
169
+ border-bottom: 2px solid transparent;
170
+ border-radius: 0;
171
+ color: var(--muted);
172
+ font-weight: 650;
173
+ }
174
+ nav button:hover:not(:disabled) { background: var(--surface); border-color: transparent; }
175
+ nav button[aria-selected="true"] { border-bottom-color: var(--accent); color: var(--foreground); }
176
+
177
+ .plugin { border-top: 1px solid var(--border); display: grid; gap: 5px; padding: 10px 12px; }
178
+ .plugin-head { align-items: baseline; display: flex; gap: 8px; }
179
+ .plugin-head strong { font-size: 13px; }
180
+ .plugin-head .status { margin-left: auto; }
181
+ .plugin p { color: var(--muted); margin: 0; overflow-wrap: anywhere; }
182
+ .plugin p.error { color: var(--red); }
183
+ .plugin-actions { display: flex; gap: 7px; margin-top: 3px; }
184
+ .plugin-actions button { flex: 1; min-height: 30px; padding: 4px 9px; }
185
+ .plugin-add { display: flex; gap: 7px; padding: 0 12px 10px; }
186
+ .plugin-add input {
187
+ background: var(--background);
188
+ border: 1px solid var(--border);
189
+ border-radius: 7px;
190
+ color: var(--foreground);
191
+ flex: 1;
192
+ min-width: 0;
193
+ padding: 7px 8px;
194
+ }
195
+ .plugin-add input:focus-visible { border-color: var(--accent); outline: none; }
164
196
  [hidden] { display: none !important; }
165
197
  </style>
166
198
  </head>
@@ -176,7 +208,24 @@
176
208
  <span class="status" id="overall-status" data-state="neutral">Loading</span>
177
209
  </header>
178
210
 
179
- <main>
211
+ <nav role="tablist">
212
+ <button id="tab-bridge" type="button" role="tab" aria-selected="true" aria-controls="view-bridge">Bridge</button>
213
+ <button id="tab-plugins" type="button" role="tab" aria-selected="false" aria-controls="view-plugins">Plugins</button>
214
+ </nav>
215
+
216
+ <main id="view-bridge" role="tabpanel" aria-labelledby="tab-bridge">
217
+ <section id="update-banner" aria-labelledby="update-title" hidden>
218
+ <div class="section-heading">
219
+ <h2 id="update-title">Update Available</h2>
220
+ <span class="status" id="update-status" data-state="warning">Update</span>
221
+ </div>
222
+ <p class="note" id="update-note"></p>
223
+ <div class="actions">
224
+ <button id="update-apply" class="primary" type="button">Update &amp; Reload</button>
225
+ <button id="update-reload-ext" type="button">Reload Extension</button>
226
+ </div>
227
+ </section>
228
+
180
229
  <section aria-labelledby="connection-title">
181
230
  <div class="section-heading">
182
231
  <h2 id="connection-title">Connection</h2>
@@ -237,6 +286,38 @@
237
286
  <button id="site-toggle" type="button" disabled>Enable on this site</button>
238
287
  </section>
239
288
  </main>
289
+
290
+ <main id="view-plugins" role="tabpanel" aria-labelledby="tab-plugins" hidden>
291
+ <section aria-labelledby="plugins-title">
292
+ <div class="section-heading">
293
+ <h2 id="plugins-title">Installed</h2>
294
+ <div style="display:flex;align-items:center;gap:8px;">
295
+ <button id="plugin-update-all" class="primary" type="button" hidden style="min-height:24px;padding:2px 8px;font-size:11px;">Update all</button>
296
+ <span class="status" id="plugin-count" data-state="neutral">Checking</span>
297
+ </div>
298
+ </div>
299
+ <p class="note" id="plugin-empty" hidden>No plugins installed.</p>
300
+ <div id="plugin-list"></div>
301
+ </section>
302
+
303
+ <section aria-labelledby="plugin-available-title" id="plugin-available-section" hidden>
304
+ <div class="section-heading">
305
+ <h2 id="plugin-available-title">Available</h2>
306
+ </div>
307
+ <div id="plugin-available"></div>
308
+ </section>
309
+
310
+ <section aria-labelledby="plugin-add-title">
311
+ <div class="section-heading">
312
+ <h2 id="plugin-add-title">Add plugin</h2>
313
+ </div>
314
+ <div class="plugin-add">
315
+ <input class="mono" id="plugin-source" type="text" spellcheck="false" aria-label="Plugin source" placeholder="github:owner/repo or /path/to/plugin">
316
+ <button id="plugin-add" class="primary" type="button">Add</button>
317
+ </div>
318
+ <p class="note" id="plugin-note">Plugins run with full local and page access. Add only plugins you trust.</p>
319
+ </section>
320
+ </main>
240
321
  <script src="popup.js"></script>
241
322
  </body>
242
323
  </html>