playcanvas-agent-bridge-cli 0.5.3 → 0.6.1
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/README.md +120 -13
- package/README.zh-CN.md +111 -12
- package/dist/builder/manager.js +166 -61
- package/dist/cli.js +194 -38
- package/dist/config.js +1 -1
- package/dist/daemon/server.js +72 -9
- package/dist/workspace/manager.js +697 -118
- package/extension/manifest.json +1 -1
- package/package.json +6 -1
- package/skills/claude/playcanvas-agent-bridge-cli/SKILL.md +39 -10
- package/skills/codex/playcanvas-agent-bridge-cli/SKILL.md +42 -10
- package/skills/cursor/playcanvas-agent-bridge-cli.mdc +28 -5
- package/skills/windsurf/playcanvas-agent-bridge-cli.md +29 -6
package/dist/builder/manager.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import { createReadStream, existsSync } from "node:fs";
|
|
3
3
|
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
4
|
-
import {
|
|
4
|
+
import { extname, join } from "node:path";
|
|
5
5
|
import { PutObjectCommand, S3Client, } from "@aws-sdk/client-s3";
|
|
6
|
+
import { transformAsync } from "@babel/core";
|
|
7
|
+
import presetEnv from "@babel/preset-env";
|
|
6
8
|
import { parse as parseEnv } from "dotenv";
|
|
9
|
+
import { minify } from "terser";
|
|
7
10
|
const OMITTED_ASSET_FIELDS = new Set([
|
|
8
11
|
"uniqueId",
|
|
9
12
|
"createdAt",
|
|
@@ -36,6 +39,47 @@ function md5(value) {
|
|
|
36
39
|
function clone(value) {
|
|
37
40
|
return JSON.parse(JSON.stringify(value));
|
|
38
41
|
}
|
|
42
|
+
export async function compileGameScript(code) {
|
|
43
|
+
const transformed = await transformAsync(code, {
|
|
44
|
+
babelrc: false,
|
|
45
|
+
configFile: false,
|
|
46
|
+
sourceType: "script",
|
|
47
|
+
comments: false,
|
|
48
|
+
presets: [[presetEnv, {
|
|
49
|
+
targets: { ie: "11" },
|
|
50
|
+
modules: false,
|
|
51
|
+
useBuiltIns: false,
|
|
52
|
+
}]],
|
|
53
|
+
});
|
|
54
|
+
if (!transformed?.code)
|
|
55
|
+
throw new Error("Babel produced no ES5 game script output.");
|
|
56
|
+
const compressed = await minify(transformed.code, {
|
|
57
|
+
ecma: 5,
|
|
58
|
+
compress: { arrows: false },
|
|
59
|
+
mangle: true,
|
|
60
|
+
keep_classnames: true,
|
|
61
|
+
keep_fnames: true,
|
|
62
|
+
format: {
|
|
63
|
+
comments: false,
|
|
64
|
+
ecma: 5,
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
if (!compressed.code)
|
|
68
|
+
throw new Error("Terser produced no compressed game script output.");
|
|
69
|
+
return `${compressed.code}\n`;
|
|
70
|
+
}
|
|
71
|
+
async function mapWithConcurrency(values, limit, operation) {
|
|
72
|
+
const results = new Array(values.length);
|
|
73
|
+
let cursor = 0;
|
|
74
|
+
const worker = async () => {
|
|
75
|
+
while (cursor < values.length) {
|
|
76
|
+
const index = cursor++;
|
|
77
|
+
results[index] = await operation(values[index], index);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
await Promise.all(Array.from({ length: Math.min(limit, values.length) }, () => worker()));
|
|
81
|
+
return results;
|
|
82
|
+
}
|
|
39
83
|
function envValue(env, ...names) {
|
|
40
84
|
for (const name of names) {
|
|
41
85
|
const value = env[name];
|
|
@@ -75,6 +119,9 @@ function timestamp() {
|
|
|
75
119
|
return `${date.getFullYear()}_${part(date.getMonth() + 1)}_${part(date.getDate())}-` +
|
|
76
120
|
`${part(date.getHours())}_${part(date.getMinutes())}_${part(date.getSeconds())}`;
|
|
77
121
|
}
|
|
122
|
+
function workspaceResourceKey(assetId, filename) {
|
|
123
|
+
return `${assetId}\0${filename.normalize("NFKC").toLocaleLowerCase()}`;
|
|
124
|
+
}
|
|
78
125
|
function contentType(path) {
|
|
79
126
|
const types = {
|
|
80
127
|
".bin": "application/octet-stream",
|
|
@@ -100,6 +147,21 @@ function publicObjectUrl(base, key) {
|
|
|
100
147
|
const encoded = key.split("/").map(encodeURIComponent).join("/");
|
|
101
148
|
return `${base.replace(/\/$/, "")}/${encoded}`;
|
|
102
149
|
}
|
|
150
|
+
export function normalizeS3Endpoint(endpoint, bucket) {
|
|
151
|
+
if (!endpoint)
|
|
152
|
+
return undefined;
|
|
153
|
+
try {
|
|
154
|
+
const parsed = new URL(endpoint);
|
|
155
|
+
const bucketPrefix = `${bucket.toLowerCase()}.`;
|
|
156
|
+
if (!parsed.hostname.toLowerCase().startsWith(bucketPrefix))
|
|
157
|
+
return endpoint;
|
|
158
|
+
parsed.hostname = parsed.hostname.slice(bucketPrefix.length);
|
|
159
|
+
return parsed.toString().replace(/\/$/, "");
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return endpoint;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
103
165
|
function sanitizeAsset(asset) {
|
|
104
166
|
const result = clone(asset);
|
|
105
167
|
for (const field of OMITTED_ASSET_FIELDS)
|
|
@@ -149,7 +211,8 @@ async function loadS3Settings(rootDir, projectDirectory) {
|
|
|
149
211
|
return {
|
|
150
212
|
client: new S3Client({
|
|
151
213
|
region,
|
|
152
|
-
endpoint,
|
|
214
|
+
endpoint: normalizeS3Endpoint(endpoint, bucket),
|
|
215
|
+
requestChecksumCalculation: "WHEN_REQUIRED",
|
|
153
216
|
forcePathStyle: booleanValue(envValue(env, "PCBRIDGE_S3_FORCE_PATH_STYLE", "S3_FORCE_PATH_STYLE"), false),
|
|
154
217
|
credentials: { accessKeyId, secretAccessKey, sessionToken },
|
|
155
218
|
}),
|
|
@@ -181,12 +244,17 @@ export class BuilderManager {
|
|
|
181
244
|
#requestTarget;
|
|
182
245
|
#workspace;
|
|
183
246
|
#jobs = new Map();
|
|
247
|
+
#activeRuns = new Set();
|
|
248
|
+
#activeClients = new Set();
|
|
249
|
+
#closing = false;
|
|
184
250
|
constructor(options) {
|
|
185
251
|
this.rootDir = options.rootDir;
|
|
186
252
|
this.#requestTarget = options.requestTarget;
|
|
187
253
|
this.#workspace = options.workspace;
|
|
188
254
|
}
|
|
189
255
|
start(info, templateAssetId, options = {}) {
|
|
256
|
+
if (this.#closing)
|
|
257
|
+
throw new Error("Tiny Builder is stopping with the daemon.");
|
|
190
258
|
const now = new Date().toISOString();
|
|
191
259
|
const job = {
|
|
192
260
|
id: `build_${randomUUID()}`,
|
|
@@ -208,9 +276,17 @@ export class BuilderManager {
|
|
|
208
276
|
this.#jobs.set(job.id, job);
|
|
209
277
|
while (this.#jobs.size > 100)
|
|
210
278
|
this.#jobs.delete(this.#jobs.keys().next().value);
|
|
211
|
-
|
|
279
|
+
const run = this.#run(job);
|
|
280
|
+
this.#activeRuns.add(run);
|
|
281
|
+
void run.finally(() => this.#activeRuns.delete(run));
|
|
212
282
|
return this.#publicJob(job);
|
|
213
283
|
}
|
|
284
|
+
async close() {
|
|
285
|
+
this.#closing = true;
|
|
286
|
+
for (const client of this.#activeClients)
|
|
287
|
+
client.destroy();
|
|
288
|
+
await Promise.allSettled(this.#activeRuns);
|
|
289
|
+
}
|
|
214
290
|
get(jobId) {
|
|
215
291
|
const job = this.#jobs.get(jobId);
|
|
216
292
|
return job ? this.#publicJob(job) : null;
|
|
@@ -228,33 +304,11 @@ export class BuilderManager {
|
|
|
228
304
|
throw new Error(response.error.message);
|
|
229
305
|
return descriptorFrom(response.data);
|
|
230
306
|
}
|
|
231
|
-
async #cacheRemoteFile(info, projectDirectory, assetId, filename, url, expectedHash) {
|
|
232
|
-
const path = join(projectDirectory, "tmp", "cache", "assets", safeSegment(assetId, "asset"), safeSegment(filename, "file.bin"));
|
|
233
|
-
if (existsSync(path)) {
|
|
234
|
-
const content = await readFile(path);
|
|
235
|
-
const hash = md5(content);
|
|
236
|
-
if (!expectedHash || hash === expectedHash)
|
|
237
|
-
return { path, hash };
|
|
238
|
-
}
|
|
239
|
-
const response = await this.#requestTarget(info.id, "bridge:readAssetResource", { assetId, url }, 120000);
|
|
240
|
-
if (!response.ok)
|
|
241
|
-
throw new Error(response.error.message);
|
|
242
|
-
const data = response.data;
|
|
243
|
-
const base64 = typeof data.base64 === "string" ? data.base64 : "";
|
|
244
|
-
if (!base64)
|
|
245
|
-
throw new Error(`Asset ${assetId} resource ${filename} returned no data.`);
|
|
246
|
-
const content = Buffer.from(base64, "base64");
|
|
247
|
-
const hash = md5(content);
|
|
248
|
-
if (expectedHash && hash !== expectedHash) {
|
|
249
|
-
throw new Error(`Asset ${assetId} resource ${filename} did not match its PlayCanvas MD5.`);
|
|
250
|
-
}
|
|
251
|
-
await mkdir(dirname(path), { recursive: true });
|
|
252
|
-
await writeFile(path, content);
|
|
253
|
-
return { path, hash };
|
|
254
|
-
}
|
|
255
307
|
async #run(job) {
|
|
256
308
|
let activeClient = null;
|
|
257
309
|
try {
|
|
310
|
+
if (this.#closing)
|
|
311
|
+
throw new Error("Build cancelled because the daemon is stopping.");
|
|
258
312
|
this.#update(job, { state: "collecting", message: "Collecting Template dependencies" });
|
|
259
313
|
const descriptors = new Map();
|
|
260
314
|
const visit = async (assetId, stack) => {
|
|
@@ -277,8 +331,47 @@ export class BuilderManager {
|
|
|
277
331
|
}
|
|
278
332
|
const prepared = await this.#workspace.prepareAssetFiles(job.info, [...allAssetIds]);
|
|
279
333
|
const preparedById = new Map(prepared.assets.map((asset) => [asset.id, asset]));
|
|
334
|
+
const resourceRequests = new Map();
|
|
335
|
+
for (const descriptor of descriptors.values()) {
|
|
336
|
+
for (const asset of descriptor.assets) {
|
|
337
|
+
const id = String(asset.id);
|
|
338
|
+
for (const variant of Object.values(asset.file?.variants || {})) {
|
|
339
|
+
if (!variant.url || !variant.filename)
|
|
340
|
+
continue;
|
|
341
|
+
resourceRequests.set(workspaceResourceKey(id, variant.filename), {
|
|
342
|
+
assetId: id,
|
|
343
|
+
filename: variant.filename,
|
|
344
|
+
url: variant.url,
|
|
345
|
+
hash: variant.hash,
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
const fontMaps = asset.type === "font" && Array.isArray(asset.data?.info &&
|
|
349
|
+
asset.data.info.maps)
|
|
350
|
+
? asset.data.info.maps
|
|
351
|
+
: [];
|
|
352
|
+
if (!asset.file?.url || !asset.file.filename || fontMaps.length <= 1)
|
|
353
|
+
continue;
|
|
354
|
+
for (let index = 1; index < fontMaps.length; index += 1) {
|
|
355
|
+
const filename = asset.file.filename.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
356
|
+
const url = asset.file.url.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
357
|
+
resourceRequests.set(workspaceResourceKey(id, filename), {
|
|
358
|
+
assetId: id,
|
|
359
|
+
filename,
|
|
360
|
+
url,
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
const preparedResources = await this.#workspace.prepareAssetResources(job.info, [...resourceRequests.values()]);
|
|
366
|
+
const preparedResourceByKey = new Map(preparedResources.map((resource) => [
|
|
367
|
+
workspaceResourceKey(resource.assetId, resource.filename),
|
|
368
|
+
resource,
|
|
369
|
+
]));
|
|
280
370
|
const settings = await loadS3Settings(this.rootDir, prepared.projectDirectory);
|
|
281
371
|
activeClient = settings.client;
|
|
372
|
+
this.#activeClients.add(activeClient);
|
|
373
|
+
if (this.#closing)
|
|
374
|
+
throw new Error("Build cancelled because the daemon is stopping.");
|
|
282
375
|
job.configSource = settings.source;
|
|
283
376
|
const prefix = normalizePrefix(job.options.prefix || settings.defaultPrefix);
|
|
284
377
|
const uploads = new Map();
|
|
@@ -333,26 +426,34 @@ export class BuilderManager {
|
|
|
333
426
|
if (output.file && local?.path && local.filename) {
|
|
334
427
|
const relativeUrl = `${buildName}/${id}/${safeSegment(local.filename, `asset-${id}`)}`;
|
|
335
428
|
const key = `${prefix}/${relativeUrl}`;
|
|
429
|
+
const hash = local.hash || md5(await readFile(local.path));
|
|
430
|
+
const fileInfo = await stat(local.path);
|
|
336
431
|
output.file.url = relativeUrl;
|
|
432
|
+
output.file.hash = hash;
|
|
433
|
+
output.file.size = fileInfo.size;
|
|
337
434
|
uploads.set(key, {
|
|
338
435
|
key,
|
|
339
436
|
path: local.path,
|
|
340
437
|
contentType: contentType(local.path),
|
|
341
|
-
hash
|
|
438
|
+
hash,
|
|
342
439
|
});
|
|
343
440
|
}
|
|
344
441
|
for (const variant of Object.values(output.file?.variants || {})) {
|
|
345
442
|
if (!variant.url || !variant.filename)
|
|
346
443
|
continue;
|
|
347
|
-
const
|
|
444
|
+
const resource = preparedResourceByKey.get(workspaceResourceKey(id, variant.filename));
|
|
445
|
+
if (!resource) {
|
|
446
|
+
throw new Error(`Asset ${id} resource ${variant.filename} was not prepared.`);
|
|
447
|
+
}
|
|
348
448
|
const relativeUrl = `${buildName}/${id}/${safeSegment(variant.filename, "variant.bin")}`;
|
|
349
449
|
const key = `${prefix}/${relativeUrl}`;
|
|
350
450
|
variant.url = relativeUrl;
|
|
451
|
+
variant.hash = resource.hash;
|
|
351
452
|
uploads.set(key, {
|
|
352
453
|
key,
|
|
353
|
-
path:
|
|
354
|
-
contentType: contentType(
|
|
355
|
-
hash:
|
|
454
|
+
path: resource.path,
|
|
455
|
+
contentType: contentType(resource.path),
|
|
456
|
+
hash: resource.hash,
|
|
356
457
|
});
|
|
357
458
|
}
|
|
358
459
|
const fontMaps = asset.type === "font" && Array.isArray(asset.data?.info &&
|
|
@@ -363,13 +464,16 @@ export class BuilderManager {
|
|
|
363
464
|
for (let index = 1; index < fontMaps.length; index += 1) {
|
|
364
465
|
const filename = originalFilename.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
365
466
|
const url = originalFileUrl.replace(/(\.[^.]*)$/, `${index}$1`);
|
|
366
|
-
const
|
|
467
|
+
const resource = preparedResourceByKey.get(workspaceResourceKey(id, filename));
|
|
468
|
+
if (!resource) {
|
|
469
|
+
throw new Error(`Asset ${id} resource ${filename} was not prepared.`);
|
|
470
|
+
}
|
|
367
471
|
const key = `${prefix}/${buildName}/${id}/${safeSegment(filename, `font-map-${index}`)}`;
|
|
368
472
|
uploads.set(key, {
|
|
369
473
|
key,
|
|
370
|
-
path:
|
|
371
|
-
contentType: contentType(
|
|
372
|
-
hash:
|
|
474
|
+
path: resource.path,
|
|
475
|
+
contentType: contentType(resource.path),
|
|
476
|
+
hash: resource.hash,
|
|
373
477
|
});
|
|
374
478
|
}
|
|
375
479
|
}
|
|
@@ -385,8 +489,9 @@ export class BuilderManager {
|
|
|
385
489
|
scriptText += "\n";
|
|
386
490
|
}
|
|
387
491
|
if (scriptText.trim()) {
|
|
492
|
+
const gameScript = await compileGameScript(scriptText);
|
|
388
493
|
const scriptPath = join(buildRoot, "gamescript.js");
|
|
389
|
-
await writeFile(scriptPath,
|
|
494
|
+
await writeFile(scriptPath, gameScript);
|
|
390
495
|
const relativeUrl = `${buildName}/gamescript.js`;
|
|
391
496
|
const key = `${prefix}/${relativeUrl}`;
|
|
392
497
|
rootData.scriptUrl = relativeUrl;
|
|
@@ -394,7 +499,7 @@ export class BuilderManager {
|
|
|
394
499
|
key,
|
|
395
500
|
path: scriptPath,
|
|
396
501
|
contentType: contentType(scriptPath),
|
|
397
|
-
hash: md5(
|
|
502
|
+
hash: md5(gameScript),
|
|
398
503
|
});
|
|
399
504
|
}
|
|
400
505
|
const rootPath = join(buildRoot, "tinyapp.json");
|
|
@@ -416,28 +521,25 @@ export class BuilderManager {
|
|
|
416
521
|
job.totalFiles = uploads.size;
|
|
417
522
|
const uploadFiles = [...uploads.values()];
|
|
418
523
|
this.#update(job, { state: "uploading", message: `Uploading 0/${uploadFiles.length} files` });
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
}
|
|
439
|
-
};
|
|
440
|
-
await Promise.all(Array.from({ length: concurrency }, () => worker()));
|
|
524
|
+
await mapWithConcurrency(uploadFiles, 4, async (file) => {
|
|
525
|
+
if (this.#closing)
|
|
526
|
+
throw new Error("Build cancelled because the daemon is stopping.");
|
|
527
|
+
const info = await stat(file.path);
|
|
528
|
+
const input = {
|
|
529
|
+
Bucket: settings.bucket,
|
|
530
|
+
Key: file.key,
|
|
531
|
+
Body: createReadStream(file.path),
|
|
532
|
+
ContentLength: info.size,
|
|
533
|
+
ContentMD5: Buffer.from(file.hash, "hex").toString("base64"),
|
|
534
|
+
ContentType: file.contentType,
|
|
535
|
+
Metadata: { "pcbridge-md5": file.hash },
|
|
536
|
+
};
|
|
537
|
+
await settings.client.send(new PutObjectCommand(input));
|
|
538
|
+
job.completedFiles += 1;
|
|
539
|
+
this.#update(job, {
|
|
540
|
+
message: `Uploading ${job.completedFiles}/${uploadFiles.length} files`,
|
|
541
|
+
});
|
|
542
|
+
});
|
|
441
543
|
this.#update(job, {
|
|
442
544
|
state: "completed",
|
|
443
545
|
message: `Uploaded ${uploadFiles.length} files`,
|
|
@@ -453,7 +555,10 @@ export class BuilderManager {
|
|
|
453
555
|
});
|
|
454
556
|
}
|
|
455
557
|
finally {
|
|
456
|
-
activeClient
|
|
558
|
+
if (activeClient) {
|
|
559
|
+
this.#activeClients.delete(activeClient);
|
|
560
|
+
activeClient.destroy();
|
|
561
|
+
}
|
|
457
562
|
}
|
|
458
563
|
}
|
|
459
564
|
}
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
import { realpathSync } from "node:fs";
|
|
4
|
-
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
|
4
|
+
import { readFile, writeFile, mkdir, stat } from "node:fs/promises";
|
|
5
|
+
import { createConnection } from "node:net";
|
|
5
6
|
import { homedir } from "node:os";
|
|
6
7
|
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
@@ -523,40 +524,182 @@ async function pathExists(path) {
|
|
|
523
524
|
return false;
|
|
524
525
|
}
|
|
525
526
|
}
|
|
527
|
+
async function resolveDaemonWorkspace(args) {
|
|
528
|
+
const hasWorkspace = Object.prototype.hasOwnProperty.call(args.flags, "workspace");
|
|
529
|
+
const requested = flagString(args, "workspace")?.trim();
|
|
530
|
+
if (hasWorkspace && !requested) {
|
|
531
|
+
throw new Error("daemon --workspace requires a directory.");
|
|
532
|
+
}
|
|
533
|
+
const workspaceRoot = resolve(requested || process.cwd());
|
|
534
|
+
let info;
|
|
535
|
+
try {
|
|
536
|
+
info = await stat(workspaceRoot);
|
|
537
|
+
}
|
|
538
|
+
catch {
|
|
539
|
+
throw new Error(`Daemon workspace does not exist: ${workspaceRoot}`);
|
|
540
|
+
}
|
|
541
|
+
if (!info.isDirectory()) {
|
|
542
|
+
throw new Error(`Daemon workspace is not a directory: ${workspaceRoot}`);
|
|
543
|
+
}
|
|
544
|
+
return workspaceRoot;
|
|
545
|
+
}
|
|
546
|
+
function daemonLog(args, message) {
|
|
547
|
+
if (flagBool(args, "json")) {
|
|
548
|
+
process.stderr.write(`${JSON.stringify({ time: new Date().toISOString(), message })}\n`);
|
|
549
|
+
}
|
|
550
|
+
else {
|
|
551
|
+
process.stderr.write(`[pcbridge] ${message}\n`);
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
async function runDaemon(args, workspaceRoot, restarted) {
|
|
555
|
+
const session = await readOrCreateSession();
|
|
556
|
+
const port = session.port || DEFAULT_PORT;
|
|
557
|
+
const server = createDaemonServer({
|
|
558
|
+
host: DEFAULT_HOST,
|
|
559
|
+
port,
|
|
560
|
+
token: session.token,
|
|
561
|
+
workspaceRoot,
|
|
562
|
+
log: (message) => daemonLog(args, message),
|
|
563
|
+
});
|
|
564
|
+
try {
|
|
565
|
+
await server.listen();
|
|
566
|
+
}
|
|
567
|
+
catch (error) {
|
|
568
|
+
print(fail("PORT_BUSY", `Cannot listen on ${DEFAULT_HOST}:${port}. ${String(error)}`));
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
const handleSignal = (signal) => {
|
|
572
|
+
daemonLog(args, `received ${signal}; stopping daemon`);
|
|
573
|
+
void server.close().catch((error) => {
|
|
574
|
+
daemonLog(args, `daemon shutdown failed: ${String(error)}`);
|
|
575
|
+
process.exitCode = 1;
|
|
576
|
+
});
|
|
577
|
+
};
|
|
578
|
+
const handleSigint = () => handleSignal("SIGINT");
|
|
579
|
+
const handleSigterm = () => handleSignal("SIGTERM");
|
|
580
|
+
process.once("SIGINT", handleSigint);
|
|
581
|
+
process.once("SIGTERM", handleSigterm);
|
|
582
|
+
print(ok({
|
|
583
|
+
version: VERSION,
|
|
584
|
+
host: DEFAULT_HOST,
|
|
585
|
+
port,
|
|
586
|
+
workspaceRoot,
|
|
587
|
+
restarted,
|
|
588
|
+
extensionPath: EXTENSION_INSTALL_DIR,
|
|
589
|
+
frontend: await server.frontend.status(),
|
|
590
|
+
}));
|
|
591
|
+
try {
|
|
592
|
+
await server.closed;
|
|
593
|
+
}
|
|
594
|
+
finally {
|
|
595
|
+
process.off("SIGINT", handleSigint);
|
|
596
|
+
process.off("SIGTERM", handleSigterm);
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function isPortListening(port) {
|
|
600
|
+
return new Promise((resolveListening) => {
|
|
601
|
+
const socket = createConnection({ host: DEFAULT_HOST, port });
|
|
602
|
+
let settled = false;
|
|
603
|
+
const finish = (listening) => {
|
|
604
|
+
if (settled)
|
|
605
|
+
return;
|
|
606
|
+
settled = true;
|
|
607
|
+
socket.destroy();
|
|
608
|
+
resolveListening(listening);
|
|
609
|
+
};
|
|
610
|
+
socket.setTimeout(500);
|
|
611
|
+
socket.once("connect", () => finish(true));
|
|
612
|
+
socket.once("error", () => finish(false));
|
|
613
|
+
socket.once("timeout", () => finish(true));
|
|
614
|
+
});
|
|
615
|
+
}
|
|
616
|
+
async function waitForPortRelease(port, timeoutMs = 10000) {
|
|
617
|
+
const deadline = Date.now() + timeoutMs;
|
|
618
|
+
while (Date.now() < deadline) {
|
|
619
|
+
if (!await isPortListening(port))
|
|
620
|
+
return true;
|
|
621
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 50));
|
|
622
|
+
}
|
|
623
|
+
return !await isPortListening(port);
|
|
624
|
+
}
|
|
625
|
+
async function stopDaemon() {
|
|
626
|
+
const session = await readOrCreateSession();
|
|
627
|
+
const port = session.port || DEFAULT_PORT;
|
|
628
|
+
let health;
|
|
629
|
+
try {
|
|
630
|
+
health = await fetchDaemon("/health");
|
|
631
|
+
}
|
|
632
|
+
catch (error) {
|
|
633
|
+
if (error instanceof DaemonConnectionError &&
|
|
634
|
+
error.diagnosis.code === "DAEMON_NOT_LISTENING") {
|
|
635
|
+
return ok({ stopped: false, alreadyStopped: true, host: DEFAULT_HOST, port });
|
|
636
|
+
}
|
|
637
|
+
if (error instanceof DaemonConnectionError) {
|
|
638
|
+
return fail(error.diagnosis.code, error.diagnosis.message, undefined, { nextAction: error.diagnosis.nextAction });
|
|
639
|
+
}
|
|
640
|
+
return fail("DAEMON_UNREACHABLE", String(error));
|
|
641
|
+
}
|
|
642
|
+
if (!health.ok) {
|
|
643
|
+
if (health.error.code === "DAEMON_INVALID_RESPONSE") {
|
|
644
|
+
return fail("NOT_PCBRIDGE_DAEMON", `The listener on ${DEFAULT_HOST}:${port} is not a pcbridge daemon; it was not stopped.`);
|
|
645
|
+
}
|
|
646
|
+
return health;
|
|
647
|
+
}
|
|
648
|
+
const healthData = health.data && typeof health.data === "object" && !Array.isArray(health.data)
|
|
649
|
+
? health.data
|
|
650
|
+
: {};
|
|
651
|
+
if (healthData.service !== "pcbridge-daemon") {
|
|
652
|
+
if (typeof healthData.version === "string" && typeof healthData.workspaceRoot === "string") {
|
|
653
|
+
return fail("DAEMON_SHUTDOWN_UNSUPPORTED", "The running pcbridge daemon does not support authenticated shutdown. Stop it once with Ctrl+C, then start the updated daemon.");
|
|
654
|
+
}
|
|
655
|
+
return fail("NOT_PCBRIDGE_DAEMON", `The listener on ${DEFAULT_HOST}:${port} is not a restartable pcbridge daemon; it was not stopped.`);
|
|
656
|
+
}
|
|
657
|
+
let response;
|
|
658
|
+
try {
|
|
659
|
+
response = await fetchDaemon("/shutdown", { method: "POST" });
|
|
660
|
+
}
|
|
661
|
+
catch (error) {
|
|
662
|
+
if (error instanceof DaemonConnectionError) {
|
|
663
|
+
return fail(error.diagnosis.code, error.diagnosis.message);
|
|
664
|
+
}
|
|
665
|
+
return fail("DAEMON_STOP_FAILED", String(error));
|
|
666
|
+
}
|
|
667
|
+
if (!response.ok)
|
|
668
|
+
return response;
|
|
669
|
+
if (!await waitForPortRelease(port)) {
|
|
670
|
+
return fail("DAEMON_STOP_TIMEOUT", `pcbridge daemon accepted shutdown, but ${DEFAULT_HOST}:${port} is still occupied. No process was forcefully terminated.`);
|
|
671
|
+
}
|
|
672
|
+
return ok({
|
|
673
|
+
stopped: true,
|
|
674
|
+
alreadyStopped: false,
|
|
675
|
+
host: DEFAULT_HOST,
|
|
676
|
+
port,
|
|
677
|
+
previousVersion: healthData.version || null,
|
|
678
|
+
previousWorkspaceRoot: healthData.workspaceRoot || null,
|
|
679
|
+
});
|
|
680
|
+
}
|
|
526
681
|
async function daemon(args) {
|
|
527
682
|
const subcommand = args._[1] || "status";
|
|
528
|
-
if (subcommand === "start") {
|
|
529
|
-
|
|
530
|
-
const server = createDaemonServer({
|
|
531
|
-
host: DEFAULT_HOST,
|
|
532
|
-
port: session.port || DEFAULT_PORT,
|
|
533
|
-
token: session.token,
|
|
534
|
-
workspaceRoot: process.cwd(),
|
|
535
|
-
log: (message) => {
|
|
536
|
-
if (flagBool(args, "json")) {
|
|
537
|
-
process.stderr.write(`${JSON.stringify({ time: new Date().toISOString(), message })}\n`);
|
|
538
|
-
}
|
|
539
|
-
else {
|
|
540
|
-
process.stderr.write(`[pcbridge] ${message}\n`);
|
|
541
|
-
}
|
|
542
|
-
},
|
|
543
|
-
});
|
|
683
|
+
if (subcommand === "start" || subcommand === "restart") {
|
|
684
|
+
let workspaceRoot;
|
|
544
685
|
try {
|
|
545
|
-
await
|
|
686
|
+
workspaceRoot = await resolveDaemonWorkspace(args);
|
|
546
687
|
}
|
|
547
688
|
catch (error) {
|
|
548
|
-
print(fail("
|
|
549
|
-
process.exitCode = 1;
|
|
689
|
+
print(fail("INVALID_WORKSPACE", String(error)));
|
|
550
690
|
return;
|
|
551
691
|
}
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
692
|
+
if (subcommand === "restart") {
|
|
693
|
+
const stopped = await stopDaemon();
|
|
694
|
+
if (!stopped.ok) {
|
|
695
|
+
print(stopped);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
await runDaemon(args, workspaceRoot, subcommand === "restart");
|
|
700
|
+
}
|
|
701
|
+
else if (subcommand === "stop") {
|
|
702
|
+
print(await stopDaemon());
|
|
560
703
|
}
|
|
561
704
|
else if (subcommand === "status") {
|
|
562
705
|
try {
|
|
@@ -686,39 +829,49 @@ function openChromeExtensions() {
|
|
|
686
829
|
}
|
|
687
830
|
async function installSkill(args) {
|
|
688
831
|
const agent = flagString(args, "agent", "codex") || "codex";
|
|
832
|
+
const supportedAgents = new Set(["codex", "claude", "cursor", "windsurf"]);
|
|
833
|
+
if (agent !== "all" && !supportedAgents.has(agent)) {
|
|
834
|
+
return fail("UNKNOWN_AGENT", `Unsupported agent: ${agent}. Use codex, claude, cursor, windsurf, or all.`);
|
|
835
|
+
}
|
|
836
|
+
const hasCustomPath = Object.prototype.hasOwnProperty.call(args.flags, "path");
|
|
837
|
+
const customPath = flagString(args, "path")?.trim();
|
|
838
|
+
if (hasCustomPath && !customPath) {
|
|
839
|
+
return fail("INVALID_REQUEST", "install-skill --path requires a parent directory.");
|
|
840
|
+
}
|
|
841
|
+
if (customPath && agent === "all") {
|
|
842
|
+
return fail("INVALID_REQUEST", "install-skill --path requires one explicit agent, not --agent all.");
|
|
843
|
+
}
|
|
844
|
+
const customParent = customPath ? resolve(customPath) : null;
|
|
689
845
|
const root = await findPackageRoot();
|
|
690
846
|
const installed = [];
|
|
691
847
|
const agents = agent === "all" ? ["codex", "claude", "cursor", "windsurf"] : [agent];
|
|
692
848
|
for (const item of agents) {
|
|
693
849
|
if (item === "codex") {
|
|
694
|
-
const dest = join(process.env.CODEX_HOME || join(homedir(), ".codex"), "skills");
|
|
850
|
+
const dest = customParent || join(process.env.CODEX_HOME || join(homedir(), ".codex"), "skills");
|
|
695
851
|
const source = join(root, "skills", "codex", "playcanvas-agent-bridge-cli");
|
|
696
852
|
const target = join(dest, "playcanvas-agent-bridge-cli");
|
|
697
853
|
await copyDir(source, target, { clean: true });
|
|
698
854
|
installed.push({ agent: item, path: target });
|
|
699
855
|
}
|
|
700
856
|
else if (item === "claude") {
|
|
701
|
-
const target = join(homedir(), ".claude", "skills", "playcanvas-agent-bridge-cli");
|
|
857
|
+
const target = join(customParent || join(homedir(), ".claude", "skills"), "playcanvas-agent-bridge-cli");
|
|
702
858
|
await copyDir(join(root, "skills", "claude", "playcanvas-agent-bridge-cli"), target, {
|
|
703
859
|
clean: true,
|
|
704
860
|
});
|
|
705
861
|
installed.push({ agent: item, path: target });
|
|
706
862
|
}
|
|
707
863
|
else if (item === "cursor") {
|
|
708
|
-
const target = join(homedir(), ".cursor", "rules", "playcanvas-agent-bridge-cli.mdc");
|
|
864
|
+
const target = join(customParent || join(homedir(), ".cursor", "rules"), "playcanvas-agent-bridge-cli.mdc");
|
|
709
865
|
await mkdir(dirname(target), { recursive: true });
|
|
710
866
|
await writeFile(target, await readFile(join(root, "skills", "cursor", "playcanvas-agent-bridge-cli.mdc")));
|
|
711
867
|
installed.push({ agent: item, path: target });
|
|
712
868
|
}
|
|
713
869
|
else if (item === "windsurf") {
|
|
714
|
-
const target = join(homedir(), ".windsurf", "rules", "playcanvas-agent-bridge-cli.md");
|
|
870
|
+
const target = join(customParent || join(homedir(), ".windsurf", "rules"), "playcanvas-agent-bridge-cli.md");
|
|
715
871
|
await mkdir(dirname(target), { recursive: true });
|
|
716
872
|
await writeFile(target, await readFile(join(root, "skills", "windsurf", "playcanvas-agent-bridge-cli.md")));
|
|
717
873
|
installed.push({ agent: item, path: target });
|
|
718
874
|
}
|
|
719
|
-
else {
|
|
720
|
-
return fail("UNKNOWN_AGENT", `Unsupported agent: ${item}. Use codex, claude, cursor, windsurf, or all.`);
|
|
721
|
-
}
|
|
722
875
|
}
|
|
723
876
|
return ok(installed);
|
|
724
877
|
}
|
|
@@ -1468,8 +1621,11 @@ function help(group = "overview") {
|
|
|
1468
1621
|
core: [
|
|
1469
1622
|
"pcbridge doctor",
|
|
1470
1623
|
"pcbridge install-extension",
|
|
1471
|
-
"pcbridge install-skill --agent codex|claude|cursor|windsurf|all",
|
|
1472
|
-
"
|
|
1624
|
+
"pcbridge install-skill --agent codex|claude|cursor|windsurf|all [--path <parent_directory>]",
|
|
1625
|
+
"--path is allowed only with one agent and appends the standard skill/rule name.",
|
|
1626
|
+
"pcbridge daemon start [--workspace <directory>]",
|
|
1627
|
+
"pcbridge daemon restart [--workspace <directory>]",
|
|
1628
|
+
"pcbridge daemon stop",
|
|
1473
1629
|
"pcbridge daemon status",
|
|
1474
1630
|
"pcbridge targets",
|
|
1475
1631
|
"pcbridge version",
|
|
@@ -1485,7 +1641,7 @@ function help(group = "overview") {
|
|
|
1485
1641
|
"pcbridge workspace path --target editor:<sceneId>",
|
|
1486
1642
|
"pcbridge workspace sync --target editor:<sceneId>",
|
|
1487
1643
|
"pcbridge workspace pull --target editor:<sceneId> --asset <assetId>",
|
|
1488
|
-
"
|
|
1644
|
+
"daemon start/restart uses --workspace when provided, otherwise the current directory.",
|
|
1489
1645
|
],
|
|
1490
1646
|
builder: [
|
|
1491
1647
|
"pcbridge builder start --target editor:<sceneId> --asset <template_asset_id> [--suffix '-${time}'] [--prefix assets]",
|
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.
|
|
7
|
+
export const VERSION = "0.6.1";
|
|
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;
|