playcanvas-agent-bridge-cli 0.2.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.
@@ -0,0 +1,224 @@
1
+ (() => {
2
+ "use strict";
3
+
4
+ const CHANNEL = "playcanvas-agent-bridge";
5
+ const DEFAULT_CONFIG = {
6
+ host: "127.0.0.1",
7
+ port: 17329,
8
+ token: ""
9
+ };
10
+ const clientId =
11
+ "pcbridge-" +
12
+ Date.now().toString(36) +
13
+ "-" +
14
+ Math.random().toString(36).slice(2);
15
+
16
+ let ws = null;
17
+ let reconnectTimer = null;
18
+ let config = DEFAULT_CONFIG;
19
+ let tabInfo = {};
20
+ const pending = new Map();
21
+
22
+ function requestId() {
23
+ if (crypto && crypto.randomUUID) return crypto.randomUUID();
24
+ return "req-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
25
+ }
26
+
27
+ function serializeError(error) {
28
+ if (error && typeof error === "object" && error.message) {
29
+ return {
30
+ code: error.code || "EXTENSION_ERROR",
31
+ message: String(error.message)
32
+ };
33
+ }
34
+ return { code: "EXTENSION_ERROR", message: String(error) };
35
+ }
36
+
37
+ function requestRuntime(message) {
38
+ return new Promise((resolve) => {
39
+ try {
40
+ chrome.runtime.sendMessage(message, (response) => {
41
+ resolve(response || null);
42
+ });
43
+ } catch {
44
+ resolve(null);
45
+ }
46
+ });
47
+ }
48
+
49
+ function callMain(method, params, timeoutMs) {
50
+ const id = requestId();
51
+ const timeout = Number(timeoutMs || 15000);
52
+
53
+ return new Promise((resolve, reject) => {
54
+ const timer = setTimeout(() => {
55
+ pending.delete(id);
56
+ reject(new Error(`No response from PlayCanvas page after ${timeout}ms.`));
57
+ }, timeout + 250);
58
+
59
+ pending.set(id, { resolve, reject, timer });
60
+ window.postMessage(
61
+ {
62
+ channel: CHANNEL,
63
+ side: "isolated",
64
+ type: "request",
65
+ id,
66
+ method,
67
+ params: params || {}
68
+ },
69
+ "*"
70
+ );
71
+ });
72
+ }
73
+
74
+ window.addEventListener("message", (event) => {
75
+ if (event.source !== window) return;
76
+ const message = event.data;
77
+ if (!message || message.channel !== CHANNEL || message.side !== "main") return;
78
+
79
+ if (message.type === "response" && message.id) {
80
+ const waiter = pending.get(message.id);
81
+ if (!waiter) return;
82
+ pending.delete(message.id);
83
+ clearTimeout(waiter.timer);
84
+ if (message.ok) {
85
+ waiter.resolve(message);
86
+ } else {
87
+ waiter.reject(message.error || new Error("Page request failed."));
88
+ }
89
+ }
90
+ });
91
+
92
+ async function loadConfig() {
93
+ const loaded = await requestRuntime({ type: "pcbridge:getConfig" });
94
+ const next = { ...DEFAULT_CONFIG, ...(loaded || {}) };
95
+ if (!next.token) {
96
+ console.warn(
97
+ "[pcbridge] Missing local token. Run pcbridge install-extension and load the generated extension directory."
98
+ );
99
+ }
100
+ return next;
101
+ }
102
+
103
+ function getTabInfo() {
104
+ return requestRuntime({ type: "pcbridge:getTabInfo" });
105
+ }
106
+
107
+ async function describeTarget() {
108
+ try {
109
+ const response = await callMain("bridge:describeTarget", {}, 3000);
110
+ return {
111
+ clientId,
112
+ tabId: tabInfo.tabId,
113
+ windowId: tabInfo.windowId,
114
+ ...(response.data || {}),
115
+ url: (response.data && response.data.url) || location.href,
116
+ title: (response.data && response.data.title) || document.title || "",
117
+ ready: Boolean(response.data && response.data.ready)
118
+ };
119
+ } catch {
120
+ return {
121
+ clientId,
122
+ tabId: tabInfo.tabId,
123
+ windowId: tabInfo.windowId,
124
+ url: location.href,
125
+ title: document.title || "",
126
+ ready: false
127
+ };
128
+ }
129
+ }
130
+
131
+ async function sendTargetUpdate() {
132
+ if (!ws || ws.readyState !== WebSocket.OPEN) return;
133
+ ws.send(
134
+ JSON.stringify({
135
+ type: "target:update",
136
+ target: await describeTarget()
137
+ })
138
+ );
139
+ }
140
+
141
+ function scheduleReconnect() {
142
+ if (reconnectTimer) return;
143
+ reconnectTimer = setTimeout(() => {
144
+ reconnectTimer = null;
145
+ connect();
146
+ }, 1000);
147
+ }
148
+
149
+ function connect() {
150
+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
151
+ return;
152
+ }
153
+
154
+ const url =
155
+ `ws://${config.host}:${config.port}/extension?` +
156
+ `token=${encodeURIComponent(config.token || "")}&clientId=${encodeURIComponent(clientId)}`;
157
+
158
+ try {
159
+ ws = new WebSocket(url);
160
+ } catch {
161
+ scheduleReconnect();
162
+ return;
163
+ }
164
+
165
+ ws.addEventListener("open", () => {
166
+ console.info("[pcbridge] connected to local daemon");
167
+ sendTargetUpdate();
168
+ });
169
+
170
+ ws.addEventListener("message", async (event) => {
171
+ let message;
172
+ try {
173
+ message = JSON.parse(event.data);
174
+ } catch {
175
+ return;
176
+ }
177
+
178
+ if (!message || message.type !== "request" || !message.id) return;
179
+
180
+ try {
181
+ const response = await callMain(message.method, message.params || {}, message.timeoutMs);
182
+ ws.send(
183
+ JSON.stringify({
184
+ type: "response",
185
+ id: message.id,
186
+ ok: true,
187
+ data: response.data,
188
+ meta: response.meta || {}
189
+ })
190
+ );
191
+ } catch (error) {
192
+ ws.send(
193
+ JSON.stringify({
194
+ type: "response",
195
+ id: message.id,
196
+ ok: false,
197
+ error: serializeError(error)
198
+ })
199
+ );
200
+ }
201
+ });
202
+
203
+ ws.addEventListener("close", () => {
204
+ scheduleReconnect();
205
+ });
206
+
207
+ ws.addEventListener("error", () => {
208
+ try {
209
+ ws.close();
210
+ } catch {
211
+ scheduleReconnect();
212
+ }
213
+ });
214
+ }
215
+
216
+ async function start() {
217
+ config = await loadConfig();
218
+ tabInfo = await getTabInfo();
219
+ connect();
220
+ setInterval(sendTargetUpdate, 2000);
221
+ }
222
+
223
+ start();
224
+ })();
@@ -0,0 +1,288 @@
1
+ (() => {
2
+ "use strict";
3
+
4
+ const CHANNEL = "playcanvas-agent-bridge";
5
+ if (window.__pcbridgeMainWorld) return;
6
+ window.__pcbridgeMainWorld = true;
7
+
8
+ function safeGetEditorValue(value, path) {
9
+ try {
10
+ return value && typeof value.get === "function" ? value.get(path) : undefined;
11
+ } catch {
12
+ return undefined;
13
+ }
14
+ }
15
+
16
+ function summarizeEditorObject(value) {
17
+ const name = safeGetEditorValue(value, "name");
18
+ const resourceId = safeGetEditorValue(value, "resource_id");
19
+ const id = safeGetEditorValue(value, "id");
20
+ const type = safeGetEditorValue(value, "type");
21
+
22
+ if (name === undefined && resourceId === undefined && id === undefined && type === undefined) {
23
+ return null;
24
+ }
25
+
26
+ const components = safeGetEditorValue(value, "components") || {};
27
+ const summary = {
28
+ __type: (value && value.constructor && value.constructor.name) || "EditorObject",
29
+ name,
30
+ resource_id: resourceId,
31
+ id,
32
+ type
33
+ };
34
+
35
+ const parent = safeGetEditorValue(value, "parent");
36
+ if (parent !== undefined) summary.parent = parent;
37
+ if (components && typeof components === "object") {
38
+ summary.components = Object.keys(components);
39
+ }
40
+
41
+ return summary;
42
+ }
43
+
44
+ function serialize(value, options) {
45
+ const settings = {
46
+ maxDepth: 6,
47
+ maxArray: 100,
48
+ maxKeys: 80,
49
+ maxString: 4000,
50
+ ...(options || {})
51
+ };
52
+ const seen = new WeakSet();
53
+
54
+ function normalize(current, depth) {
55
+ if (current === undefined) return "[undefined]";
56
+ if (current === null) return null;
57
+
58
+ const type = typeof current;
59
+ if (type === "string") {
60
+ return current.length > settings.maxString
61
+ ? current.slice(0, settings.maxString) + "...[truncated]"
62
+ : current;
63
+ }
64
+ if (type === "number" || type === "boolean") return current;
65
+ if (type === "bigint") return current.toString();
66
+ if (type === "symbol") return String(current);
67
+ if (type === "function") return `[Function ${current.name || "anonymous"}]`;
68
+ if (seen.has(current)) return "[Circular]";
69
+
70
+ const editorSummary = summarizeEditorObject(current);
71
+ if (editorSummary) return editorSummary;
72
+
73
+ if (current instanceof Error) {
74
+ return {
75
+ name: current.name,
76
+ message: current.message,
77
+ stack: current.stack
78
+ };
79
+ }
80
+
81
+ if (depth >= settings.maxDepth) {
82
+ return `[MaxDepth ${(current.constructor && current.constructor.name) || "Object"}]`;
83
+ }
84
+
85
+ seen.add(current);
86
+
87
+ if (Array.isArray(current)) {
88
+ const result = current
89
+ .slice(0, settings.maxArray)
90
+ .map((item) => normalize(item, depth + 1));
91
+ if (current.length > settings.maxArray) {
92
+ result.push(`[${current.length - settings.maxArray} more items]`);
93
+ }
94
+ return result;
95
+ }
96
+
97
+ const result = {};
98
+ const keys = Object.keys(current);
99
+ for (const key of keys.slice(0, settings.maxKeys)) {
100
+ result[key] = normalize(current[key], depth + 1);
101
+ }
102
+ if (keys.length > settings.maxKeys) {
103
+ result.__truncatedKeys = keys.length - settings.maxKeys;
104
+ }
105
+ return result;
106
+ }
107
+
108
+ return normalize(value, 0);
109
+ }
110
+
111
+ function describeTarget() {
112
+ 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\/([^/?#]+)/);
115
+ return {
116
+ url: location.href,
117
+ title: document.title || "",
118
+ ready,
119
+ projectId: config.project && config.project.id ? String(config.project.id) : undefined,
120
+ sceneId:
121
+ (config.scene && config.scene.id ? String(config.scene.id) : undefined) ||
122
+ (matchScene ? matchScene[1] : undefined),
123
+ branchId:
124
+ (config.self && config.self.branch && config.self.branch.id
125
+ ? String(config.self.branch.id)
126
+ : undefined) ||
127
+ (config.branch && config.branch.id ? String(config.branch.id) : undefined)
128
+ };
129
+ }
130
+
131
+ function withTimeout(promise, timeoutMs) {
132
+ return new Promise((resolve, reject) => {
133
+ const timer = setTimeout(() => reject(new Error(`Timed out after ${timeoutMs}ms.`)), timeoutMs);
134
+ Promise.resolve(promise).then(
135
+ (value) => {
136
+ clearTimeout(timer);
137
+ resolve(value);
138
+ },
139
+ (error) => {
140
+ clearTimeout(timer);
141
+ reject(error);
142
+ }
143
+ );
144
+ });
145
+ }
146
+
147
+ async function evalInPage(params, requestId) {
148
+ const timeoutMs = Number(params.timeoutMs || 15000);
149
+ const command = {
150
+ id: requestId,
151
+ method: "bridge:eval",
152
+ args: params.args || {},
153
+ params,
154
+ timeoutMs
155
+ };
156
+
157
+ const context = {
158
+ page: window,
159
+ window,
160
+ document,
161
+ editor: window.editor,
162
+ pc: window.pc,
163
+ pcui: window.pcui,
164
+ command,
165
+ serialize
166
+ };
167
+
168
+ const fn = new window.Function(
169
+ "ctx",
170
+ `
171
+ const page = ctx.page;
172
+ const window = ctx.window;
173
+ const document = ctx.document;
174
+ const editor = ctx.editor;
175
+ const pc = ctx.pc;
176
+ const pcui = ctx.pcui;
177
+ const command = ctx.command;
178
+ const serialize = ctx.serialize;
179
+ return (async () => {
180
+ ${String(params.code || "")}
181
+ })();
182
+ `
183
+ );
184
+
185
+ return serialize(await withTimeout(fn(context), timeoutMs));
186
+ }
187
+
188
+ function captureViewport(params) {
189
+ const app = window.editor.call("viewport:app");
190
+ if (!app) throw new Error("Viewport app not found.");
191
+ const device = app.graphicsDevice;
192
+ const gl = device && device.gl;
193
+ if (!gl) throw new Error("WebGL context not found.");
194
+
195
+ window.editor.call("viewport:render");
196
+ app.tick();
197
+
198
+ const width = device.width;
199
+ const height = device.height;
200
+ const pixels = new Uint8Array(width * height * 4);
201
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
202
+ gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
203
+
204
+ const flipped = new Uint8Array(width * height * 4);
205
+ const rowSize = width * 4;
206
+ for (let y = 0; y < height; y += 1) {
207
+ flipped.set(
208
+ pixels.subarray((height - 1 - y) * rowSize, (height - y) * rowSize),
209
+ y * rowSize
210
+ );
211
+ }
212
+
213
+ const srcCanvas = document.createElement("canvas");
214
+ srcCanvas.width = width;
215
+ srcCanvas.height = height;
216
+ srcCanvas
217
+ .getContext("2d")
218
+ .putImageData(new ImageData(new Uint8ClampedArray(flipped.buffer), width, height), 0, 0);
219
+
220
+ const maxWidth = Number(params.maxWidth || 1200);
221
+ let outWidth = width;
222
+ let outHeight = height;
223
+ if (maxWidth > 0 && width > maxWidth) {
224
+ outWidth = maxWidth;
225
+ outHeight = Math.round(height * (maxWidth / width));
226
+ }
227
+
228
+ const dstCanvas = document.createElement("canvas");
229
+ dstCanvas.width = outWidth;
230
+ dstCanvas.height = outHeight;
231
+ dstCanvas.getContext("2d").drawImage(srcCanvas, 0, 0, outWidth, outHeight);
232
+
233
+ const mime = params.format === "webp" ? "image/webp" : "image/png";
234
+ const dataUrl = dstCanvas.toDataURL(mime, Number(params.quality || 0.85));
235
+ return {
236
+ mime,
237
+ width: outWidth,
238
+ height: outHeight,
239
+ base64: dataUrl.split(",")[1]
240
+ };
241
+ }
242
+
243
+ async function callMethod(method, params, requestId) {
244
+ if (method === "bridge:ping") return { pong: true, href: location.href };
245
+ if (method === "bridge:describeTarget") return describeTarget();
246
+ if (method === "bridge:eval") return evalInPage(params || {}, requestId);
247
+ if (method === "bridge:captureViewport") return captureViewport(params || {});
248
+ throw new Error(`Unknown bridge method: ${method}`);
249
+ }
250
+
251
+ window.addEventListener("message", async (event) => {
252
+ if (event.source !== window) return;
253
+ const message = event.data;
254
+ if (!message || message.channel !== CHANNEL || message.side !== "isolated") return;
255
+ if (message.type !== "request") return;
256
+
257
+ const startedAt = performance.now();
258
+ try {
259
+ const data = await callMethod(message.method, message.params || {}, message.id);
260
+ window.postMessage(
261
+ {
262
+ channel: CHANNEL,
263
+ side: "main",
264
+ type: "response",
265
+ id: message.id,
266
+ ok: true,
267
+ data,
268
+ meta: { durationMs: Math.round(performance.now() - startedAt) }
269
+ },
270
+ "*"
271
+ );
272
+ } catch (error) {
273
+ window.postMessage(
274
+ {
275
+ channel: CHANNEL,
276
+ side: "main",
277
+ type: "response",
278
+ id: message.id,
279
+ ok: false,
280
+ error: serialize(error)
281
+ },
282
+ "*"
283
+ );
284
+ }
285
+ });
286
+
287
+ window.postMessage({ channel: CHANNEL, side: "main", type: "ready" }, "*");
288
+ })();
@@ -0,0 +1,39 @@
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "PlayCanvas Agent Bridge",
4
+ "description": "Connects open PlayCanvas Editor tabs to the local pcbridge daemon.",
5
+ "version": "0.2.0",
6
+ "permissions": ["activeTab", "storage"],
7
+ "host_permissions": [
8
+ "http://playcanvas.com/*",
9
+ "https://playcanvas.com/*",
10
+ "http://127.0.0.1/*",
11
+ "http://localhost/*",
12
+ "ws://127.0.0.1/*",
13
+ "ws://localhost/*"
14
+ ],
15
+ "action": {
16
+ "default_popup": "popup.html",
17
+ "default_title": "PlayCanvas Agent Bridge"
18
+ },
19
+ "background": {
20
+ "service_worker": "service-worker.js"
21
+ },
22
+ "content_scripts": [
23
+ {
24
+ "matches": ["http://playcanvas.com/editor*", "https://playcanvas.com/editor*"],
25
+ "js": ["main.js"],
26
+ "world": "MAIN",
27
+ "run_at": "document_idle"
28
+ },
29
+ {
30
+ "matches": ["http://playcanvas.com/editor*", "https://playcanvas.com/editor*"],
31
+ "js": ["isolated.js"],
32
+ "world": "ISOLATED",
33
+ "run_at": "document_idle"
34
+ }
35
+ ],
36
+ "content_security_policy": {
37
+ "extension_pages": "script-src 'self'; object-src 'self'; connect-src http://127.0.0.1:* ws://127.0.0.1:* http://localhost:* ws://localhost:*"
38
+ }
39
+ }
@@ -0,0 +1,47 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>PlayCanvas Agent Bridge</title>
6
+ <style>
7
+ body {
8
+ color: #1f2937;
9
+ font: 13px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
10
+ margin: 0;
11
+ min-width: 280px;
12
+ padding: 14px;
13
+ }
14
+
15
+ h1 {
16
+ font-size: 15px;
17
+ margin: 0 0 10px;
18
+ }
19
+
20
+ dl {
21
+ display: grid;
22
+ grid-template-columns: auto 1fr;
23
+ gap: 6px 10px;
24
+ margin: 0;
25
+ }
26
+
27
+ dt {
28
+ color: #6b7280;
29
+ }
30
+
31
+ dd {
32
+ margin: 0;
33
+ word-break: break-all;
34
+ }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <h1>PlayCanvas Agent Bridge</h1>
39
+ <dl>
40
+ <dt>Daemon</dt>
41
+ <dd id="daemon">Loading</dd>
42
+ <dt>Tab</dt>
43
+ <dd id="tab">Loading</dd>
44
+ </dl>
45
+ <script src="popup.js"></script>
46
+ </body>
47
+ </html>
@@ -0,0 +1,26 @@
1
+ async function loadConfig() {
2
+ try {
3
+ const response = await fetch(chrome.runtime.getURL("config.json"));
4
+ if (!response.ok) return null;
5
+ return response.json();
6
+ } catch {
7
+ return null;
8
+ }
9
+ }
10
+
11
+ async function main() {
12
+ const config = await loadConfig();
13
+ const daemon = document.getElementById("daemon");
14
+ const tab = document.getElementById("tab");
15
+
16
+ daemon.textContent = config
17
+ ? `${config.host || "127.0.0.1"}:${config.port || 17329}`
18
+ : "Run pcbridge install-extension";
19
+
20
+ const [active] = await chrome.tabs.query({ active: true, currentWindow: true });
21
+ tab.textContent = active && active.url && active.url.includes("playcanvas.com/editor")
22
+ ? "PlayCanvas Editor"
23
+ : "Open a PlayCanvas Editor tab";
24
+ }
25
+
26
+ main();
@@ -0,0 +1,33 @@
1
+ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
2
+ if (message && message.type === "pcbridge:getTabInfo") {
3
+ sendResponse({
4
+ tabId: sender.tab && sender.tab.id,
5
+ windowId: sender.tab && sender.tab.windowId
6
+ });
7
+ return true;
8
+ }
9
+
10
+ if (message && message.type === "pcbridge:getConfig") {
11
+ fetch(chrome.runtime.getURL("config.json"))
12
+ .then((response) => (response.ok ? response.json() : null))
13
+ .then((config) => {
14
+ sendResponse(
15
+ config || {
16
+ host: "127.0.0.1",
17
+ port: 17329,
18
+ token: ""
19
+ }
20
+ );
21
+ })
22
+ .catch(() => {
23
+ sendResponse({
24
+ host: "127.0.0.1",
25
+ port: 17329,
26
+ token: ""
27
+ });
28
+ });
29
+ return true;
30
+ }
31
+
32
+ return false;
33
+ });
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "playcanvas-agent-bridge-cli",
3
+ "version": "0.2.0",
4
+ "description": "CLI-first local bridge for automating open PlayCanvas Editor tabs from AI coding agents.",
5
+ "type": "module",
6
+ "bin": {
7
+ "pcbridge": "./dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist",
11
+ "extension",
12
+ "skills",
13
+ "README.md",
14
+ "README.zh-CN.md",
15
+ "LICENSE"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc -p tsconfig.json",
19
+ "check": "tsc -p tsconfig.json --noEmit",
20
+ "prepare": "npm run build"
21
+ },
22
+ "keywords": [
23
+ "playcanvas",
24
+ "cli",
25
+ "chrome-extension",
26
+ "automation",
27
+ "agent"
28
+ ],
29
+ "author": "",
30
+ "license": "MIT",
31
+ "engines": {
32
+ "node": ">=20"
33
+ },
34
+ "dependencies": {
35
+ "ws": "^8.18.3"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^24.0.4",
39
+ "@types/ws": "^8.18.1",
40
+ "typescript": "5.8.3"
41
+ }
42
+ }