@weapp-container/agent 0.0.0-stage → 0.1.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/dist/cli.mjs ADDED
@@ -0,0 +1,2610 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ import process$1 from "node:process";
4
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
5
+ import { access, appendFile, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, writeFile } from "node:fs/promises";
6
+ import { createReadStream, createWriteStream } from "node:fs";
7
+ import { spawn } from "node:child_process";
8
+ import { createServer } from "node:http";
9
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
11
+ // src/starter.ts
12
+ function starterFiles(name) {
13
+ const json = (value) => JSON.stringify(value, null, 2) + "\n";
14
+ return {
15
+ "package.json": json({
16
+ name: "company-mini-program",
17
+ private: true,
18
+ scripts: { prepare: "wv prepare" },
19
+ devDependencies: { "weapp-vite": "7.5.0" }
20
+ }),
21
+ "project.config.json": json({
22
+ compileType: "miniprogram",
23
+ srcMiniprogramRoot: "src/",
24
+ miniprogramRoot: "dist/",
25
+ appid: "touristappid"
26
+ }),
27
+ "vite.config.ts": `import { defineConfig } from 'weapp-vite'
28
+
29
+ export default defineConfig({
30
+ weapp: { srcRoot: 'src' },
31
+ })
32
+ `,
33
+ ".gitignore": "node_modules/\ndist/\n.weapp-container/\n.weapp-vite/\n",
34
+ "src/app.json": json({
35
+ pages: ["pages/index/index"],
36
+ window: {
37
+ navigationBarTitleText: name,
38
+ navigationBarBackgroundColor: "#eef4f1",
39
+ navigationBarTextStyle: "black"
40
+ }
41
+ }),
42
+ "src/app.js": "App({})\n",
43
+ "src/app.wxss": `page { background: #eef4f1; color: #12362d; }
44
+ `,
45
+ "src/pages/index/brand.js": `export default ${json({
46
+ name,
47
+ logo: "",
48
+ summary: "在这里介绍你的业务,并连接宿主应用提供的服务。"
49
+ })}`,
50
+ "src/pages/index/index.js": `import brand from './brand.js'
51
+
52
+ Page({
53
+ data: { brand, loading: false, displayName: '', error: '' },
54
+ onUnload() {
55
+ this.unloaded = true
56
+ },
57
+ async loadProfile() {
58
+ if (this.data.loading) return
59
+ this.setData({ loading: true, displayName: '', error: '' })
60
+ try {
61
+ if (typeof weappContainer === 'undefined') throw new Error('请在支持宿主调用的预览或应用中打开')
62
+ const result = await weappContainer.invoke('company.getProfile', {}, { timeout: 5000 })
63
+ if (typeof result?.displayName !== 'string' || !result.displayName.trim()) {
64
+ throw new Error('宿主返回的名称无效')
65
+ }
66
+ if (!this.unloaded) this.setData({ displayName: result.displayName })
67
+ } catch (error) {
68
+ if (!this.unloaded) this.setData({ error: error?.message || '暂时无法获取资料,请重试' })
69
+ } finally {
70
+ if (!this.unloaded) this.setData({ loading: false })
71
+ }
72
+ },
73
+ })
74
+ `,
75
+ "src/pages/index/index.wxml": `<view class="page">
76
+ <image wx:if="{{brand.logo}}" class="logo" src="{{brand.logo}}" mode="aspectFit" />
77
+ <view class="title" id="brand-title">{{brand.name}}</view>
78
+ <view class="summary">{{brand.summary}}</view>
79
+ <view class="profile">
80
+ <button id="load-profile" bindtap="loadProfile" loading="{{loading}}" disabled="{{loading}}">{{error ? '重试' : '获取宿主用户资料'}}</button>
81
+ <view wx:if="{{displayName}}" id="profile-name" class="result">{{displayName}}</view>
82
+ <view wx:if="{{error}}" id="profile-error" class="error">{{error}}</view>
83
+ </view>
84
+ </view>
85
+ `,
86
+ "src/pages/index/index.wxss": `.page { padding: 80rpx 48rpx; }
87
+ .logo { display: block; width: 120rpx; height: 120rpx; margin-bottom: 36rpx; }
88
+ .title { font-size: 52rpx; font-weight: 700; line-height: 1.2; }
89
+ .summary { margin-top: 24rpx; max-width: 540rpx; font-size: 28rpx; line-height: 1.6; }
90
+ .profile { margin-top: 60rpx; padding: 28rpx; background: #fff; border-radius: 20rpx; }
91
+ .profile button { background: #155845; color: #fff; font-size: 28rpx; }
92
+ .result, .error { margin-top: 20rpx; font-size: 26rpx; }
93
+ .error { color: #87391e; }
94
+ `,
95
+ "preview/host-fixtures.json": json({ "company.getProfile": { resolve: { displayName: "预览用户" } } }),
96
+ "README.md": `# 小程序定制 / Customize this mini-program
97
+
98
+ 1. 运行 \`npm install\` 安装编译器 / Install the compiler with \`npm install\`.
99
+ 2. 在 \`src/app.json\` 修改导航栏,在 \`src/pages/index/brand.js\` 修改首页标题和介绍。将品牌图片放到 \`src/assets/\`,把 \`logo\` 设为 \`/assets/你的文件名.png\`。在 \`src/app.wxss\` 和首页 \`index.wxss\` 修改颜色。
100
+ 3. 运行 \`weapp-container-agent preview start --project . --simulator-bin /path/to/bin/weapp-simulator --host-fixtures preview/host-fixtures.json\`,打开输出的 Web 地址。使用 \`preview stop --project .\` 结束预览。
101
+ 4. 运行 \`weapp-container-agent build --project . --out ./portable-pack\`,将生成的整个目录交给宿主 SDK。
102
+
103
+ Edit the navigation in \`src/app.json\` and the home page in \`src/pages/index/brand.js\`. Put your logo in \`src/assets/\` and set \`logo\` to its app-relative path, such as \`/assets/logo.png\`. Edit colors in \`src/app.wxss\` and the page stylesheet.
104
+
105
+ The preview fixture supplies a sample result for \`company.getProfile\`. Your mobile host registers that method before loading the pack and returns \`{ displayName }\`.
106
+ `
107
+ };
108
+ }
109
+ // src/index.ts
110
+ const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
111
+ const SOURCE_ENTRY = resolve(dirname(fileURLToPath(import.meta.url))) === resolve(PACKAGE_ROOT, "src");
112
+ const CLI_ENTRY = SOURCE_ENTRY ? join(PACKAGE_ROOT, "src", "cli.ts") : join(PACKAGE_ROOT, "dist", "cli.mjs");
113
+ const CLI_RUNTIME_ARGS = SOURCE_ENTRY ? ["--experimental-strip-types"] : [];
114
+ const REPOSITORY_ROOT = resolve(PACKAGE_ROOT, "../..");
115
+ const DEFAULT_TIMEOUT_MS = 12e4;
116
+ var AgentError = class extends Error {
117
+ constructor(code, message, options = {}) {
118
+ super(message, options);
119
+ this.name = "AgentError";
120
+ this.code = code;
121
+ if (options.status) this.status = options.status;
122
+ }
123
+ };
124
+ function now() {
125
+ return (/* @__PURE__ */ new Date()).toISOString();
126
+ }
127
+ function sleep(ms, signal) {
128
+ if (!signal) return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
129
+ if (signal.aborted) return Promise.reject(signal.reason ?? new AgentError("ERR_CANCELLED", "Operation cancelled"));
130
+ return new Promise((resolvePromise, rejectPromise) => {
131
+ const finish = (callback) => (value) => {
132
+ clearTimeout(timer);
133
+ signal.removeEventListener("abort", abort);
134
+ callback(value);
135
+ };
136
+ const resolve = finish(resolvePromise);
137
+ const reject = finish(rejectPromise);
138
+ const abort = () => reject(signal.reason ?? new AgentError("ERR_CANCELLED", "Operation cancelled"));
139
+ const timer = setTimeout(resolve, ms);
140
+ signal.addEventListener("abort", abort, { once: true });
141
+ });
142
+ }
143
+ function safeJson(value) {
144
+ return JSON.stringify(value, null, 2) + "\n";
145
+ }
146
+ async function exists(path) {
147
+ return access(path).then(() => true).catch(() => false);
148
+ }
149
+ function inside(root, target) {
150
+ const rootPath = resolve(root);
151
+ const targetPath = resolve(target);
152
+ const suffix = relative(rootPath, targetPath);
153
+ return suffix === "" || suffix !== ".." && !suffix.startsWith(`..${sep}`) && !isAbsolute(suffix);
154
+ }
155
+ function projectPath(root, value) {
156
+ const target = resolve(root, value);
157
+ if (!inside(root, target)) throw new AgentError("ERR_PATH_OUTSIDE_PROJECT", `Path is outside project root: ${value}`);
158
+ return target;
159
+ }
160
+ async function readJson(path, fallback = {}) {
161
+ try {
162
+ return JSON.parse(await readFile(path, "utf8"));
163
+ } catch (error) {
164
+ if (error?.code === "ENOENT") return fallback;
165
+ throw error;
166
+ }
167
+ }
168
+ async function writeJson(path, value) {
169
+ await mkdir(dirname(path), { recursive: true });
170
+ const temporary = join(dirname(path), `.agent-json-${randomUUID()}.tmp`);
171
+ try {
172
+ await writeFile(temporary, safeJson(value), {
173
+ flag: "wx",
174
+ mode: 384
175
+ });
176
+ await rename(temporary, path);
177
+ } catch (error) {
178
+ await rm(temporary, { force: true });
179
+ throw error;
180
+ }
181
+ }
182
+ async function walkFiles(root, options = {}) {
183
+ const ignored = /* @__PURE__ */ new Set([
184
+ ".git",
185
+ ".weapp-container",
186
+ ".weapp-vite",
187
+ "node_modules",
188
+ "dist",
189
+ "coverage"
190
+ ]);
191
+ const includeHidden = options.includeHidden ?? false;
192
+ const ignoredDirectories = options.ignoredDirectories ?? ignored;
193
+ const files = [];
194
+ async function visit(directory) {
195
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
196
+ if (!includeHidden && entry.name.startsWith(".") && entry.name !== ".env.example") continue;
197
+ if (entry.isDirectory()) {
198
+ if (!ignoredDirectories.has(entry.name)) await visit(join(directory, entry.name));
199
+ } else if (entry.isFile()) files.push(join(directory, entry.name));
200
+ }
201
+ }
202
+ await visit(root);
203
+ return files.sort();
204
+ }
205
+ async function digestDirectory(root, options = {}) {
206
+ const hash = createHash("sha256");
207
+ for (const file of await walkFiles(root, options)) {
208
+ hash.update(relative(root, file).split(sep).join("/") + "\0");
209
+ hash.update(await readFile(file));
210
+ }
211
+ return hash.digest("hex");
212
+ }
213
+ async function packageManager(root) {
214
+ if (await exists(join(root, "pnpm-lock.yaml"))) return "pnpm";
215
+ if (await exists(join(root, "yarn.lock"))) return "yarn";
216
+ if (await exists(join(root, "bun.lockb"))) return "bun";
217
+ return "npm";
218
+ }
219
+ const templateTags = /* @__PURE__ */ new Set([
220
+ "include",
221
+ "import",
222
+ "slot",
223
+ "template",
224
+ "wxs"
225
+ ]);
226
+ const compatibilitySourceExtensions = /* @__PURE__ */ new Set([
227
+ ".js",
228
+ ".jsx",
229
+ ".ts",
230
+ ".tsx",
231
+ ".wxs",
232
+ ".wxml",
233
+ ".wxss",
234
+ ".json"
235
+ ]);
236
+ const styleFeaturePatterns = [
237
+ {
238
+ name: "wxss-rpx-units",
239
+ pattern: /\b\d+(?:\.\d+)?rpx\b/gi
240
+ },
241
+ {
242
+ name: "wxss-page-selector",
243
+ pattern: /(?:^|[},])\s*page\s*(?=[,{])/gim
244
+ },
245
+ {
246
+ name: "css-grid",
247
+ pattern: /\bdisplay\s*:\s*grid\b/gi
248
+ },
249
+ {
250
+ name: "css-sticky",
251
+ pattern: /\bposition\s*:\s*sticky\b/gi
252
+ },
253
+ {
254
+ name: "css-custom-properties",
255
+ pattern: /\bvar\(\s*--[\w-]+/gi
256
+ },
257
+ {
258
+ name: "css-safe-area",
259
+ pattern: /\benv\(\s*safe-area-inset-/gi
260
+ },
261
+ {
262
+ name: "css-host-selector",
263
+ pattern: /:host(?:\b|\s*\()/gi
264
+ },
265
+ {
266
+ name: "css-import",
267
+ pattern: /@import\b/gi
268
+ }
269
+ ];
270
+ function maskCode(source, mode) {
271
+ const characters = source.split("");
272
+ const blank = (index) => {
273
+ if (characters[index] !== "\n" && characters[index] !== "\r") characters[index] = " ";
274
+ };
275
+ let state = "code";
276
+ let quote = "";
277
+ for (let index = 0; index < characters.length; index += 1) {
278
+ const character = source[index];
279
+ const next = source[index + 1];
280
+ if (mode === "wxml") {
281
+ if (state === "comment") {
282
+ blank(index);
283
+ if (character === "-" && source.slice(index, index + 3) === "-->") {
284
+ blank(index + 1);
285
+ blank(index + 2);
286
+ index += 2;
287
+ state = "code";
288
+ }
289
+ } else if (character === "<" && source.slice(index, index + 4) === "<!--") {
290
+ blank(index);
291
+ blank(index + 1);
292
+ blank(index + 2);
293
+ blank(index + 3);
294
+ index += 3;
295
+ state = "comment";
296
+ }
297
+ continue;
298
+ }
299
+ if (state === "line-comment") {
300
+ blank(index);
301
+ if (character === "\n") state = "code";
302
+ continue;
303
+ }
304
+ if (state === "block-comment") {
305
+ blank(index);
306
+ if (character === "*" && next === "/") {
307
+ blank(index + 1);
308
+ index += 1;
309
+ state = "code";
310
+ }
311
+ continue;
312
+ }
313
+ if (state === "string") {
314
+ blank(index);
315
+ if (character === "\\") {
316
+ if (index + 1 < characters.length) blank(++index);
317
+ } else if (character === quote) state = "code";
318
+ continue;
319
+ }
320
+ if (character === "/" && next === "/") {
321
+ blank(index);
322
+ blank(index + 1);
323
+ index += 1;
324
+ state = "line-comment";
325
+ } else if (character === "/" && next === "*") {
326
+ blank(index);
327
+ blank(index + 1);
328
+ index += 1;
329
+ state = "block-comment";
330
+ } else if (mode === "javascript" && (character === "\"" || character === "'" || character === "`")) {
331
+ quote = character;
332
+ blank(index);
333
+ state = "string";
334
+ } else if (mode === "css" && (character === "\"" || character === "'")) {
335
+ quote = character;
336
+ blank(index);
337
+ state = "string";
338
+ }
339
+ }
340
+ return characters.join("");
341
+ }
342
+ function lineStarts(source) {
343
+ const starts = [0];
344
+ for (let index = 0; index < source.length; index += 1) if (source[index] === "\n") starts.push(index + 1);
345
+ return starts;
346
+ }
347
+ function sourceLocation(starts, offset) {
348
+ let low = 0;
349
+ let high = starts.length;
350
+ while (low + 1 < high) {
351
+ const middle = low + high >>> 1;
352
+ if (starts[middle] <= offset) low = middle;
353
+ else high = middle;
354
+ }
355
+ return {
356
+ line: low + 1,
357
+ column: offset - starts[low] + 1
358
+ };
359
+ }
360
+ function compatibilityFinding(kind, name, path, starts, offset, row = null, detail = {}) {
361
+ const status = [
362
+ "full",
363
+ "partial",
364
+ "unsupported"
365
+ ].includes(row?.weappContainer?.status) ? row.weappContainer.status : "unknown";
366
+ const messages = {
367
+ full: "The compatibility matrix records this capability as full. Static inspection does not verify runtime behavior.",
368
+ partial: "The compatibility matrix records partial support. Check the listed evidence and host-specific limits.",
369
+ unsupported: "The compatibility matrix records this capability as unsupported in the current baseline.",
370
+ unknown: "No compatibility evidence is recorded for this use. Verify it on every target host."
371
+ };
372
+ return {
373
+ kind,
374
+ name,
375
+ status,
376
+ severity: status === "unsupported" ? "error" : status === "partial" ? "warning" : "info",
377
+ priority: row?.priority ?? "P1",
378
+ path,
379
+ ...sourceLocation(starts, offset),
380
+ message: detail.message ?? messages[status],
381
+ recommendation: detail.recommendation ?? (status === "unsupported" ? "Replace this capability or guard the code path with wx.canIUse before targeting this runtime." : status === "partial" ? "Review the API limits and add a target-host scenario for the behavior this project relies on." : "Run a representative scenario on each target host and record the result before relying on this use."),
382
+ evidence: row?.weappContainer?.evidence ?? [],
383
+ ...row?.weappContainer?.hostCoverage ? { hostCoverage: row.weappContainer.hostCoverage } : {},
384
+ ...row?.weappContainer?.engineCoverage ? { engineCoverage: row.weappContainer.engineCoverage } : {}
385
+ };
386
+ }
387
+ function addRegexFindings(findings, { kind, name, path, source, starts, pattern, row, detail }) {
388
+ const matcher = new RegExp(pattern.source, pattern.flags);
389
+ for (const match of source.matchAll(matcher)) {
390
+ const findingName = typeof name === "function" ? name(match) : name;
391
+ const findingRow = typeof row === "function" ? row(match, findingName) : row;
392
+ findings.push(compatibilityFinding(kind, findingName, path, starts, match.index, findingRow, detail));
393
+ }
394
+ }
395
+ let compatibilityDataPromise;
396
+ async function compatibilityData() {
397
+ if (!compatibilityDataPromise) compatibilityDataPromise = (async () => {
398
+ const inventory = await readJson(join(REPOSITORY_ROOT, "docs/api-inventory-v1.json"), null);
399
+ const packaged = inventory ? null : await readJson(join(PACKAGE_ROOT, "dist/compatibility-baseline.json"), null);
400
+ const source = inventory ?? packaged ?? {
401
+ apiRows: [],
402
+ baseline: null
403
+ };
404
+ const apiRows = source.apiRows ?? source.apis.flatMap((api) => api.names.map((name) => ({
405
+ name,
406
+ priority: "P1",
407
+ weappContainer: {
408
+ status: api.support,
409
+ evidence: api.conformance,
410
+ hostCoverage: api.hostCoverage,
411
+ engineCoverage: api.engineCoverage
412
+ }
413
+ })));
414
+ return {
415
+ baseline: source.baseline ?? {
416
+ kind: "weapp-api-inventory",
417
+ schemaVersion: source.schemaVersion,
418
+ manifestVersion: source.manifestVersion,
419
+ protocolVersion: source.protocolVersion,
420
+ hosts: source.hosts,
421
+ engines: source.engines
422
+ },
423
+ rows: {
424
+ api: new Map(apiRows.map((row) => [row.name, row])),
425
+ component: /* @__PURE__ */ new Map(),
426
+ template: /* @__PURE__ */ new Map()
427
+ }
428
+ };
429
+ })();
430
+ return compatibilityDataPromise;
431
+ }
432
+ async function scanCompatibility(root, sourceFiles) {
433
+ const data = await compatibilityData();
434
+ const compatibilityRows = data.rows;
435
+ const findings = [];
436
+ const warnings = [];
437
+ const customComponents = /* @__PURE__ */ new Set();
438
+ for (const file of sourceFiles) {
439
+ if (!file.endsWith(".json")) continue;
440
+ try {
441
+ const value = JSON.parse(await readFile(file, "utf8"));
442
+ for (const name of Object.keys(value?.usingComponents ?? {})) customComponents.add(name);
443
+ } catch {}
444
+ }
445
+ for (const file of sourceFiles) {
446
+ const extension = file.slice(file.lastIndexOf(".")).toLowerCase();
447
+ if (!compatibilitySourceExtensions.has(extension) || extension === ".json") continue;
448
+ let original;
449
+ try {
450
+ original = await readFile(file, "utf8");
451
+ } catch (error) {
452
+ warnings.push({
453
+ path: relative(root, file).split(sep).join("/"),
454
+ message: `Could not read source for compatibility scan: ${error.message}`
455
+ });
456
+ continue;
457
+ }
458
+ const path = relative(root, file).split(sep).join("/");
459
+ const mode = extension === ".wxml" ? "wxml" : extension === ".wxss" ? "css" : "javascript";
460
+ const source = maskCode(original, mode);
461
+ const starts = lineStarts(original);
462
+ if (mode === "javascript") {
463
+ addRegexFindings(findings, {
464
+ kind: "api",
465
+ name: (match) => match[1] ? `wx.${match[1]}` : `wx.${match[3]}`,
466
+ path,
467
+ source,
468
+ starts,
469
+ pattern: /\bwx\s*(?:\?\.\s*|\.\s*)([$\w]+)|\bwx\s*\[\s*(['"])([^'"\]]+)\2\s*\]/g,
470
+ row: (_match, name) => compatibilityRows.api.get(name)
471
+ });
472
+ addRegexFindings(findings, {
473
+ kind: "api",
474
+ name: "wx[dynamic]",
475
+ path,
476
+ source,
477
+ starts,
478
+ pattern: /\bwx\s*\[\s*([A-Za-z_$][\w$]*)\s*\]/g,
479
+ row: null,
480
+ detail: {
481
+ message: "The API name is computed at runtime, so static inspection cannot determine its compatibility status.",
482
+ recommendation: "Use an explicit API name or add a target-host test for each possible computed value."
483
+ }
484
+ });
485
+ addRegexFindings(findings, {
486
+ kind: "api",
487
+ name: (match) => match[1],
488
+ path,
489
+ source,
490
+ starts,
491
+ pattern: /(?<![\w$.])(App|Page|Component)\s*\(/g,
492
+ row: (_match, name) => compatibilityRows.api.get(name)
493
+ });
494
+ } else if (mode === "wxml") {
495
+ addRegexFindings(findings, {
496
+ kind: "template",
497
+ name: (match) => match[1],
498
+ path,
499
+ source,
500
+ starts,
501
+ pattern: /\b(wx:[\w-]+)\b/g,
502
+ row: (_match, name) => compatibilityRows.template.get(name),
503
+ detail: {
504
+ message: "Static analysis does not maintain conformance status for WXML directives.",
505
+ recommendation: "Verify this directive in a representative scenario on every target host."
506
+ }
507
+ });
508
+ addRegexFindings(findings, {
509
+ kind: "template",
510
+ name: (match) => match[1],
511
+ path,
512
+ source,
513
+ starts,
514
+ pattern: /<\s*(include|import|slot|template|wxs)\b/gi,
515
+ row: (_match, name) => compatibilityRows.template.get(name)
516
+ });
517
+ addRegexFindings(findings, {
518
+ kind: "component",
519
+ name: (match) => match[1],
520
+ path,
521
+ source,
522
+ starts,
523
+ pattern: /<\s*([a-z][a-z0-9-]*)\b/gi,
524
+ row: (_match, name) => compatibilityRows.component.get(name)
525
+ });
526
+ for (let index = findings.length - 1; index >= 0; index -= 1) {
527
+ const finding = findings[index];
528
+ if (finding.path !== path || finding.kind !== "component") continue;
529
+ if (templateTags.has(finding.name) || customComponents.has(finding.name)) {
530
+ findings.splice(index, 1);
531
+ continue;
532
+ }
533
+ const row = compatibilityRows.component.get(finding.name);
534
+ Object.assign(finding, compatibilityFinding("component", finding.name, path, starts, starts[finding.line - 1] + finding.column - 1, row));
535
+ if (!row) {
536
+ finding.message = "This tag is not declared in project usingComponents, and the static baseline has no component status for it.";
537
+ finding.recommendation = "Check the component registration and verify any platform-specific component on each target host.";
538
+ }
539
+ }
540
+ for (const finding of findings) {
541
+ if (finding.path !== path || finding.kind !== "template") continue;
542
+ const row = compatibilityRows.template.get(finding.name);
543
+ const offset = starts[finding.line - 1] + finding.column - 1;
544
+ const detail = finding.name.startsWith("wx:") ? {
545
+ message: "Static analysis does not maintain conformance status for WXML directives.",
546
+ recommendation: "Verify this directive in a representative scenario on every target host."
547
+ } : void 0;
548
+ Object.assign(finding, compatibilityFinding("template", finding.name, path, starts, offset, row, detail));
549
+ }
550
+ } else if (mode === "css") for (const feature of styleFeaturePatterns) addRegexFindings(findings, {
551
+ kind: "style",
552
+ name: feature.name,
553
+ path,
554
+ source,
555
+ starts,
556
+ pattern: feature.pattern,
557
+ row: null,
558
+ detail: {
559
+ message: "The static baseline does not record compatibility status for this WXSS/CSS feature.",
560
+ recommendation: "Exercise the rendered style on each target host and record the layout result."
561
+ }
562
+ });
563
+ }
564
+ const counts = findings.reduce((result, finding) => {
565
+ result[finding.status] = (result[finding.status] ?? 0) + 1;
566
+ return result;
567
+ }, {});
568
+ return {
569
+ status: "unknown",
570
+ method: "static-source-scan",
571
+ baseline: data.baseline,
572
+ filesScanned: sourceFiles.filter((file) => compatibilitySourceExtensions.has(file.slice(file.lastIndexOf(".")).toLowerCase())).length,
573
+ findings,
574
+ counts,
575
+ warnings
576
+ };
577
+ }
578
+ async function inspectProject(projectRoot) {
579
+ const root = resolve(projectRoot);
580
+ const diagnostics = [];
581
+ async function readConfig(path, fallback) {
582
+ try {
583
+ return await readJson(join(root, path), fallback);
584
+ } catch (error) {
585
+ if (!(error instanceof SyntaxError)) throw error;
586
+ diagnostics.push({
587
+ code: "ERR_INVALID_JSON",
588
+ path,
589
+ message: error.message,
590
+ hint: `Correct the JSON in ${path} and run inspect again.`
591
+ });
592
+ return fallback;
593
+ }
594
+ }
595
+ const projectConfig = await readConfig("project.config.json", null);
596
+ const packageJson = await readConfig("package.json", {}) ?? {};
597
+ const configuredOutput = projectConfig?.miniprogramRoot;
598
+ let sourceRoot = projectConfig?.srcMiniprogramRoot;
599
+ if (!sourceRoot) {
600
+ if (await exists(join(root, "src/app.json"))) sourceRoot = "src";
601
+ else if (await exists(join(root, "app.json"))) sourceRoot = ".";
602
+ else if (configuredOutput && await exists(join(projectPath(root, configuredOutput), "app.json"))) sourceRoot = configuredOutput;
603
+ else sourceRoot = await exists(join(root, "src")) ? "src" : ".";
604
+ }
605
+ const outputRoot = configuredOutput || "dist";
606
+ const sourceDirectory = projectPath(root, sourceRoot);
607
+ projectPath(root, outputRoot);
608
+ const appJson = join(sourceDirectory, "app.json");
609
+ const app = await readConfig(relative(root, appJson), {}) ?? {};
610
+ const pages = Array.isArray(app.pages) ? app.pages : [];
611
+ const sourceFiles = await walkFiles(sourceDirectory).catch((error) => {
612
+ if (error.code !== "ENOENT") throw error;
613
+ diagnostics.push({
614
+ code: "ERR_SOURCE_ROOT_MISSING",
615
+ path: sourceRoot,
616
+ message: "Mini-program source directory is missing.",
617
+ hint: "Check srcMiniprogramRoot in project.config.json."
618
+ });
619
+ return [];
620
+ });
621
+ if (!projectConfig) diagnostics.push({
622
+ code: "WARN_PROJECT_CONFIG",
623
+ path: "project.config.json",
624
+ message: "Project configuration is missing or unreadable.",
625
+ hint: "Set compileType to miniprogram and srcMiniprogramRoot to the folder containing app.json."
626
+ });
627
+ if (!pages.length) diagnostics.push({
628
+ code: "WARN_APP_PAGES",
629
+ path: relative(root, appJson),
630
+ message: "No mini-program pages are configured.",
631
+ hint: "Add the first page route to the pages array in app.json."
632
+ });
633
+ if (packageJson.devDependencies?.["weapp-vite"] || packageJson.dependencies?.["weapp-vite"]) {
634
+ if (!projectCompiler(root)) diagnostics.push({
635
+ code: "WARN_COMPILER_NOT_INSTALLED",
636
+ path: "package.json",
637
+ message: "The project compiler is missing.",
638
+ hint: "Install the dependencies declared by this project, then run inspect again."
639
+ });
640
+ }
641
+ return {
642
+ root,
643
+ kind: pages.length > 0 || projectConfig ? "native" : "unknown",
644
+ packageManager: await packageManager(root),
645
+ sourceRoot,
646
+ outputRoot,
647
+ pages,
648
+ subPackages: app.subPackages ?? app.subpackages ?? [],
649
+ scripts: packageJson.scripts ?? {},
650
+ appId: projectConfig?.appid ?? null,
651
+ projectConfig: projectConfig ? join(root, "project.config.json") : null,
652
+ appJson: await exists(appJson) ? appJson : null,
653
+ sourceFileCount: sourceFiles.length,
654
+ sourceDigest: await digestDirectory(root),
655
+ compatibility: await scanCompatibility(root, sourceFiles),
656
+ diagnostics,
657
+ warnings: [...projectConfig ? [] : ["project.config.json is missing"], ...pages.length ? [] : ["app.json has no pages"]]
658
+ };
659
+ }
660
+ async function createProject(projectRoot, name) {
661
+ const root = resolve(projectRoot);
662
+ if (typeof name !== "string" || !name.trim() || [...name].some((character) => character.charCodeAt(0) < 32)) throw new AgentError("ERR_PROJECT_NAME", "Pass a non-empty, single-line display name with --name.");
663
+ const createdRoot = await mkdir(root, { recursive: true });
664
+ if (!(await lstat(root)).isDirectory()) throw new AgentError("ERR_PROJECT_EXISTS", `Project destination must be an empty directory: ${root}`);
665
+ const lock = join(root, ".weapp-container-create");
666
+ const owned = [];
667
+ try {
668
+ await mkdir(lock);
669
+ } catch (error) {
670
+ if (error.code !== "EEXIST") throw error;
671
+ throw new AgentError("ERR_PROJECT_EXISTS", `Project creation already in progress: ${root}`);
672
+ }
673
+ try {
674
+ if ((await readdir(root)).some((entry) => entry !== basename(lock))) throw new AgentError("ERR_PROJECT_EXISTS", `Project destination must be empty: ${root}`);
675
+ const files = starterFiles(name.trim());
676
+ for (const [path, content] of Object.entries(files)) {
677
+ const target = join(root, path);
678
+ const parent = await mkdir(dirname(target), { recursive: true });
679
+ if (parent) for (let directory = dirname(target); inside(parent, directory); directory = dirname(directory)) owned.push({
680
+ path: directory,
681
+ directory: true
682
+ });
683
+ const file = await open(target, "wx");
684
+ owned.push({
685
+ path: target,
686
+ directory: false
687
+ });
688
+ try {
689
+ await file.writeFile(content);
690
+ } finally {
691
+ await file.close();
692
+ }
693
+ }
694
+ return {
695
+ projectRoot: root,
696
+ name: name.trim(),
697
+ files: Object.keys(files)
698
+ };
699
+ } catch (error) {
700
+ for (const entry of owned.filter((entry) => !entry.directory)) await rm(entry.path, { force: true });
701
+ for (const entry of owned.filter((entry) => entry.directory).sort((a, b) => b.path.length - a.path.length)) await rmdir(entry.path).catch((cleanup) => {
702
+ if (cleanup.code !== "ENOTEMPTY") throw cleanup;
703
+ });
704
+ throw error;
705
+ } finally {
706
+ await rmdir(lock);
707
+ if (createdRoot) await rmdir(root).catch((error) => {
708
+ if (error.code !== "ENOTEMPTY") throw error;
709
+ });
710
+ }
711
+ }
712
+ async function resolveSourceFile(projectRoot, value, { createParents = false } = {}) {
713
+ if (typeof value !== "string" || !value.trim() || isAbsolute(value) || value.includes("\0")) throw new AgentError("ERR_SOURCE_PATH", "A project-relative source file path is required");
714
+ const segments = value.replaceAll("\\", "/").replace(/^\.\//, "").split("/");
715
+ if (segments.some((segment) => !segment || segment === "." || segment === ".." || segment === "node_modules" || segment === ".git" || segment === ".weapp-container" || segment === ".weapp-vite" || segment === "dist" || segment === "coverage" || segment === "target" || segment.startsWith(".env") && segment !== ".env.example")) throw new AgentError("ERR_SOURCE_PATH", `Source path is not writable: ${value}`);
716
+ const project = await inspectProject(projectRoot);
717
+ const root = project.root;
718
+ await realpath(root);
719
+ const target = projectPath(root, join(...segments));
720
+ let current = root;
721
+ for (const segment of segments.slice(0, -1)) {
722
+ current = join(current, segment);
723
+ try {
724
+ const entry = await lstat(current);
725
+ if (entry.isSymbolicLink() || !entry.isDirectory()) throw new AgentError("ERR_SOURCE_PATH", `Source path traverses a non-directory: ${segment}`);
726
+ } catch (error) {
727
+ if (error?.code !== "ENOENT" || !createParents) throw error;
728
+ await mkdir(current);
729
+ }
730
+ }
731
+ try {
732
+ const entry = await lstat(target);
733
+ if (entry.isSymbolicLink() || !entry.isFile()) throw new AgentError("ERR_SOURCE_PATH", `Source path is not a regular file: ${value}`);
734
+ } catch (error) {
735
+ if (error?.code !== "ENOENT") throw error;
736
+ }
737
+ return {
738
+ project,
739
+ target
740
+ };
741
+ }
742
+ async function listProjectFiles(projectRoot) {
743
+ const project = await inspectProject(projectRoot);
744
+ await realpath(project.root);
745
+ return { files: (await walkFiles(project.root)).map((file) => relative(project.root, file).split(sep).join("/")) };
746
+ }
747
+ async function readProjectFile(projectRoot, path) {
748
+ const { target } = await resolveSourceFile(projectRoot, path);
749
+ return {
750
+ path,
751
+ content: await readFile(target, "utf8")
752
+ };
753
+ }
754
+ async function writeProjectFile(projectRoot, path, content) {
755
+ if (typeof content !== "string") throw new AgentError("ERR_SOURCE_CONTENT", "File content must be a string");
756
+ if (Buffer.byteLength(content) > 5242880) throw new AgentError("ERR_SOURCE_CONTENT", "Source files must be 5 MB or smaller");
757
+ const { target } = await resolveSourceFile(projectRoot, path, { createParents: true });
758
+ const existing = await lstat(target).catch((error) => error?.code === "ENOENT" ? null : Promise.reject(error));
759
+ const temporary = join(dirname(target), `.agent-write-${randomUUID()}.tmp`);
760
+ try {
761
+ await writeFile(temporary, content, {
762
+ flag: "wx",
763
+ mode: existing ? existing.mode & 511 : 420
764
+ });
765
+ await rename(temporary, target);
766
+ } catch (error) {
767
+ await rm(temporary, { force: true });
768
+ throw error;
769
+ }
770
+ return {
771
+ path,
772
+ bytes: Buffer.byteLength(content),
773
+ digest: createHash("sha256").update(content).digest("hex")
774
+ };
775
+ }
776
+ async function initProject(projectRoot) {
777
+ const project = await inspectProject(projectRoot);
778
+ const stateRoot = join(project.root, ".weapp-container");
779
+ const configPath = join(stateRoot, "agent.json");
780
+ await mkdir(stateRoot, { recursive: true });
781
+ const config = {
782
+ schemaVersion: 1,
783
+ projectRoot: project.root,
784
+ sourceRoot: project.sourceRoot,
785
+ outputRoot: project.outputRoot,
786
+ packageManager: project.packageManager,
787
+ initializedAt: now()
788
+ };
789
+ try {
790
+ await writeFile(configPath, safeJson(config), {
791
+ flag: "wx",
792
+ mode: 384
793
+ });
794
+ } catch (error) {
795
+ if (error?.code !== "EEXIST") throw error;
796
+ throw new AgentError("ERR_ALREADY_INITIALIZED", `Agent configuration already exists: ${configPath}`);
797
+ }
798
+ return {
799
+ ...config,
800
+ configPath
801
+ };
802
+ }
803
+ function commandResult(command, args, result) {
804
+ return {
805
+ command: [command, ...args].join(" "),
806
+ code: result.code,
807
+ signal: result.signal,
808
+ stdout: result.stdout,
809
+ stderr: result.stderr
810
+ };
811
+ }
812
+ function runCommand(command, args, options = {}) {
813
+ const cwd = options.cwd ?? REPOSITORY_ROOT;
814
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
815
+ const signal = options.signal;
816
+ return new Promise((resolvePromise, rejectPromise) => {
817
+ const child = spawn(command, args, {
818
+ cwd,
819
+ env: {
820
+ ...process.env,
821
+ ...options.env ?? {}
822
+ },
823
+ stdio: [
824
+ "ignore",
825
+ "pipe",
826
+ "pipe"
827
+ ],
828
+ windowsHide: true
829
+ });
830
+ let stdout = "";
831
+ let stderr = "";
832
+ let settled = false;
833
+ let timer;
834
+ const append = (current, chunk) => (current + chunk.toString()).slice(-2097152);
835
+ const finish = (callback, value) => {
836
+ if (settled) return;
837
+ settled = true;
838
+ clearTimeout(timer);
839
+ signal?.removeEventListener("abort", abort);
840
+ callback(value);
841
+ };
842
+ const abort = () => {
843
+ child.kill("SIGTERM");
844
+ finish(rejectPromise, signal.reason ?? new AgentError("ERR_CANCELLED", "Command cancelled"));
845
+ };
846
+ child.stdout.on("data", (chunk) => {
847
+ stdout = append(stdout, chunk);
848
+ });
849
+ child.stderr.on("data", (chunk) => {
850
+ stderr = append(stderr, chunk);
851
+ });
852
+ child.once("error", (error) => finish(rejectPromise, error));
853
+ child.once("close", (code, signalName) => finish(resolvePromise, commandResult(command, args, {
854
+ code,
855
+ signal: signalName,
856
+ stdout,
857
+ stderr
858
+ })));
859
+ if (signal) {
860
+ if (signal.aborted) return abort();
861
+ signal.addEventListener("abort", abort, { once: true });
862
+ }
863
+ timer = setTimeout(() => {
864
+ child.kill("SIGTERM");
865
+ finish(rejectPromise, new AgentError("ERR_TIMEOUT", `Command timed out after ${timeoutMs}ms`, { cause: {
866
+ command,
867
+ args
868
+ } }));
869
+ }, timeoutMs);
870
+ });
871
+ }
872
+ function projectCompiler(projectRoot) {
873
+ try {
874
+ const require = createRequire(join(projectRoot, "package.json"));
875
+ const entry = require.resolve("weapp-vite/package.json");
876
+ const metadata = require(entry);
877
+ const bin = typeof metadata.bin === "string" ? metadata.bin : metadata.bin?.wv;
878
+ return bin ? {
879
+ entry: resolve(dirname(entry), bin),
880
+ commit: metadata.gitHead
881
+ } : null;
882
+ } catch (error) {
883
+ if (!["MODULE_NOT_FOUND", "ERR_PACKAGE_PATH_NOT_EXPORTED"].includes(error.code)) throw error;
884
+ return null;
885
+ }
886
+ }
887
+ async function resolveWv(projectRoot, explicit) {
888
+ if (explicit) return explicit;
889
+ if (process.env.WEAPP_CONTAINER_WV_BIN) return process.env.WEAPP_CONTAINER_WV_BIN;
890
+ const candidates = [join(projectRoot, "node_modules/.bin", process.platform === "win32" ? "wv.cmd" : "wv"), ...SOURCE_ENTRY ? [join(REPOSITORY_ROOT, "vendor/weapp-vite/node_modules/.bin/wv")] : []];
891
+ for (const candidate of candidates) if (await exists(candidate)) return candidate;
892
+ return "wv";
893
+ }
894
+ async function compilerCommit() {
895
+ const result = await runCommand("git", [
896
+ "-C",
897
+ join(REPOSITORY_ROOT, "vendor/weapp-vite"),
898
+ "rev-parse",
899
+ "HEAD"
900
+ ], { timeoutMs: 1e4 });
901
+ return result.code === 0 ? result.stdout.trim() : "unknown";
902
+ }
903
+ async function buildProject(projectRoot, options = {}) {
904
+ const project = await inspectProject(projectRoot);
905
+ const root = project.root;
906
+ const stateRoot = projectPath(root, options.stateRoot ?? ".weapp-container");
907
+ const buildRoot = join(stateRoot, "builds", options.jobId ?? randomUUID());
908
+ const configuredOutput = options.outputRoot ?? project.outputRoot;
909
+ const output = options.outputRoot === void 0 && resolve(root, configuredOutput) === resolve(root, project.sourceRoot) ? join(buildRoot, "raw") : projectPath(root, configuredOutput);
910
+ if (output === root || inside(output, resolve(root, project.sourceRoot))) throw new AgentError("ERR_BUILD_OUTPUT", "Set miniprogramRoot to a build directory separate from the source.");
911
+ const platform = options.platform ?? "weapp";
912
+ const createsPack = platform === "weapp";
913
+ const packDirectory = createsPack ? options.out ? resolve(root, options.out) : join(buildRoot, "pack") : null;
914
+ if (packDirectory && (inside(packDirectory, root) || inside(output, packDirectory) || inside(packDirectory, output))) throw new AgentError("ERR_PACK_OUTPUT", "Choose a pack destination separate from the project root and compiler output.");
915
+ await mkdir(stateRoot, { recursive: true });
916
+ const buildLock = join(stateRoot, "build.lock");
917
+ const packParent = packDirectory ? dirname(packDirectory) : null;
918
+ if (packParent) await mkdir(packParent, { recursive: true });
919
+ const packLock = packDirectory ? join(packParent, `.${basename(packDirectory)}.weapp-pack-lock`) : null;
920
+ try {
921
+ await mkdir(buildLock);
922
+ } catch (error) {
923
+ if (error.code !== "EEXIST") throw error;
924
+ throw new AgentError("ERR_BUILD_BUSY", `A build is already using ${output}`);
925
+ }
926
+ let packLockOwned = false;
927
+ let staging;
928
+ try {
929
+ if (packLock) {
930
+ try {
931
+ await mkdir(packLock);
932
+ packLockOwned = true;
933
+ } catch (error) {
934
+ if (error.code !== "EEXIST") throw error;
935
+ throw new AgentError("ERR_PACK_EXISTS", `Pack destination is in use: ${packDirectory}`);
936
+ }
937
+ if (await lstat(packDirectory).catch((error) => {
938
+ if (error.code !== "ENOENT") throw error;
939
+ })) throw new AgentError("ERR_PACK_EXISTS", `Pack destination already exists: ${packDirectory}`);
940
+ }
941
+ const compiler = !options.commandRunner && !options.wvBin && !process.env.WEAPP_CONTAINER_WV_BIN ? projectCompiler(root) : null;
942
+ const wv = compiler ? process.execPath : await resolveWv(root, options.wvBin);
943
+ const buildArgs = [
944
+ "build",
945
+ root,
946
+ "-p",
947
+ platform,
948
+ "--outDir",
949
+ output
950
+ ];
951
+ if (compiler) buildArgs.unshift(compiler.entry);
952
+ const build = await (options.commandRunner ?? runCommand)(wv, buildArgs, {
953
+ cwd: root,
954
+ timeoutMs: options.timeoutMs
955
+ }).catch((error) => {
956
+ if (error.code !== "ENOENT") throw error;
957
+ throw new AgentError("ERR_COMPILER_NOT_FOUND", "Install the project compiler or provide --wv-bin.", { cause: error });
958
+ });
959
+ if (build.code !== 0) throw new AgentError("ERR_BUILD_FAILED", build.stderr || build.stdout || "weapp-vite build failed", { cause: build });
960
+ await mkdir(buildRoot, { recursive: true });
961
+ const sourceDigest = await digestDirectory(root);
962
+ if (!createsPack) {
963
+ const result = {
964
+ project,
965
+ platform,
966
+ build: commandResult(wv, buildArgs, build),
967
+ pack: null,
968
+ packDirectory: null,
969
+ outputDirectory: output,
970
+ compilerCommit: compiler?.commit ?? "unknown",
971
+ sourceDigest,
972
+ manifest: null,
973
+ generatedAt: now()
974
+ };
975
+ await writeJson(join(buildRoot, "build-report.json"), result);
976
+ return result;
977
+ }
978
+ const commit = compiler?.commit ?? (SOURCE_ENTRY && wv.startsWith(join(REPOSITORY_ROOT, "vendor/weapp-vite") + sep) ? await compilerCommit() : "unknown");
979
+ staging = await mkdtemp(join(packParent, ".weapp-pack-"));
980
+ const pack = await (options.packContainer ?? (await import("@weapp-container/container-manifest")).packContainer)(output, staging, {
981
+ compilerCommit: commit,
982
+ project: root,
983
+ resolveRoot: root,
984
+ platform
985
+ }).catch((error) => {
986
+ const details = error.diagnostics?.filter((diagnostic) => diagnostic.severity === "error").map((diagnostic) => [diagnostic.path, diagnostic.message].filter(Boolean).join(" ")).join("\n");
987
+ throw new AgentError("ERR_PACK_FAILED", details || error.message, { cause: error });
988
+ });
989
+ const manifest = pack?.manifest ?? await readJson(join(staging, "manifest.json"), {});
990
+ const result = {
991
+ project,
992
+ platform,
993
+ build: commandResult(wv, buildArgs, build),
994
+ pack: pack ? {
995
+ diagnostics: pack.diagnostics,
996
+ blobCount: pack.blobCount
997
+ } : {
998
+ code: 0,
999
+ signal: null,
1000
+ stdout: "Portable pack created",
1001
+ stderr: ""
1002
+ },
1003
+ packDirectory,
1004
+ outputDirectory: output,
1005
+ compilerCommit: manifest.compiler?.commit ?? commit,
1006
+ integrityRoot: manifest.integrity?.root,
1007
+ sourceDigest,
1008
+ manifest,
1009
+ generatedAt: now()
1010
+ };
1011
+ await writeJson(join(buildRoot, "build-report.json"), result);
1012
+ await rename(staging, packDirectory);
1013
+ return result;
1014
+ } finally {
1015
+ if (staging) await rm(staging, {
1016
+ recursive: true,
1017
+ force: true
1018
+ });
1019
+ if (packLockOwned) await rmdir(packLock);
1020
+ await rmdir(buildLock);
1021
+ }
1022
+ }
1023
+ var JobStore = class {
1024
+ constructor(root) {
1025
+ this.root = resolve(root);
1026
+ this.stateRoot = join(this.root, ".weapp-container", "agent");
1027
+ this.jobsRoot = join(this.stateRoot, "jobs");
1028
+ this.jobs = /* @__PURE__ */ new Map();
1029
+ this.abortControllers = /* @__PURE__ */ new Map();
1030
+ this.writePromises = /* @__PURE__ */ new Map();
1031
+ this.executionPromises = /* @__PURE__ */ new Map();
1032
+ }
1033
+ async init() {
1034
+ await mkdir(this.jobsRoot, { recursive: true });
1035
+ }
1036
+ async save(job) {
1037
+ const snapshot = structuredClone(job);
1038
+ this.jobs.set(job.jobId, snapshot);
1039
+ const current = (this.writePromises.get(job.jobId) ?? Promise.resolve()).then(async () => {
1040
+ await writeJson(join(this.jobsRoot, `${job.jobId}.json`), snapshot);
1041
+ });
1042
+ this.writePromises.set(job.jobId, current);
1043
+ try {
1044
+ await current;
1045
+ } finally {
1046
+ if (this.writePromises.get(job.jobId) === current) this.writePromises.delete(job.jobId);
1047
+ }
1048
+ return job;
1049
+ }
1050
+ async create(kind, input = {}) {
1051
+ await this.init();
1052
+ const job = {
1053
+ schemaVersion: 1,
1054
+ jobId: randomUUID(),
1055
+ projectRoot: this.root,
1056
+ kind,
1057
+ status: "queued",
1058
+ createdAt: now(),
1059
+ sourceDigest: input.sourceDigest ?? null,
1060
+ input,
1061
+ artifacts: [],
1062
+ diagnostics: [],
1063
+ events: []
1064
+ };
1065
+ await this.save(job);
1066
+ return job;
1067
+ }
1068
+ async update(job, patch, event) {
1069
+ Object.assign(job, patch);
1070
+ let record;
1071
+ if (event) {
1072
+ record = {
1073
+ sequence: job.events.length + 1,
1074
+ timestamp: now(),
1075
+ ...event
1076
+ };
1077
+ job.events.push(record);
1078
+ }
1079
+ if (record) {
1080
+ const previous = this.writePromises.get(job.jobId) ?? Promise.resolve();
1081
+ const snapshot = structuredClone(job);
1082
+ this.jobs.set(job.jobId, snapshot);
1083
+ const current = previous.then(async () => {
1084
+ await appendFile(join(this.jobsRoot, `${job.jobId}.jsonl`), `${JSON.stringify(record)}\n`, { mode: 384 });
1085
+ await writeJson(join(this.jobsRoot, `${job.jobId}.json`), snapshot);
1086
+ });
1087
+ this.writePromises.set(job.jobId, current);
1088
+ try {
1089
+ await current;
1090
+ } finally {
1091
+ if (this.writePromises.get(job.jobId) === current) this.writePromises.delete(job.jobId);
1092
+ }
1093
+ } else await this.save(job);
1094
+ return job;
1095
+ }
1096
+ async start(kind, input, operation) {
1097
+ const job = await this.create(kind, input);
1098
+ const controller = new AbortController();
1099
+ this.abortControllers.set(job.jobId, controller);
1100
+ const execution = new Promise((resolvePromise) => setImmediate(resolvePromise)).then(() => this.execute(job, controller, operation));
1101
+ this.executionPromises.set(job.jobId, execution);
1102
+ execution.then(() => {
1103
+ if (this.executionPromises.get(job.jobId) === execution) this.executionPromises.delete(job.jobId);
1104
+ }, () => {
1105
+ if (this.executionPromises.get(job.jobId) === execution) this.executionPromises.delete(job.jobId);
1106
+ });
1107
+ return job;
1108
+ }
1109
+ async execute(job, controller, operation) {
1110
+ try {
1111
+ if (controller.signal.aborted) throw controller.signal.reason;
1112
+ await this.update(job, {
1113
+ status: "running",
1114
+ startedAt: now()
1115
+ }, { type: "job.started" });
1116
+ const result = await operation(job, controller.signal);
1117
+ const status = [
1118
+ "passed",
1119
+ "failed",
1120
+ "blocked"
1121
+ ].includes(result?.status) ? result.status : "passed";
1122
+ await this.update(job, {
1123
+ status,
1124
+ finishedAt: now(),
1125
+ result
1126
+ }, {
1127
+ type: `job.${status === "passed" ? "completed" : status}`,
1128
+ resultStatus: result?.status
1129
+ });
1130
+ } catch (error) {
1131
+ const status = error?.code === "ERR_CANCELLED" || controller.signal.aborted ? "cancelled" : error?.status === "blocked" ? "blocked" : "failed";
1132
+ await this.update(job, {
1133
+ status,
1134
+ finishedAt: now(),
1135
+ error: {
1136
+ code: error?.code ?? "ERR_JOB_FAILED",
1137
+ message: error?.message ?? String(error)
1138
+ }
1139
+ }, {
1140
+ type: `job.${status}`,
1141
+ error: error?.message ?? String(error)
1142
+ });
1143
+ } finally {
1144
+ this.abortControllers.delete(job.jobId);
1145
+ }
1146
+ }
1147
+ async status(jobId) {
1148
+ if (!/^[0-9a-f-]{36}$/i.test(jobId ?? "")) throw new AgentError("ERR_JOB_NOT_FOUND", `Unknown job: ${jobId}`);
1149
+ await this.writePromises.get(jobId);
1150
+ const inMemory = this.jobs.get(jobId);
1151
+ if (inMemory) return structuredClone(inMemory);
1152
+ return readJson(join(this.jobsRoot, `${jobId}.json`), null);
1153
+ }
1154
+ async cancel(jobId) {
1155
+ const controller = this.abortControllers.get(jobId);
1156
+ if (!controller) {
1157
+ const job = await this.status(jobId);
1158
+ if (!job) throw new AgentError("ERR_JOB_NOT_FOUND", `Unknown job: ${jobId}`);
1159
+ return job;
1160
+ }
1161
+ controller.abort(new AgentError("ERR_CANCELLED", "Job cancelled"));
1162
+ await this.executionPromises.get(jobId);
1163
+ return this.status(jobId);
1164
+ }
1165
+ async events(jobId) {
1166
+ await this.writePromises.get(jobId);
1167
+ if (!await this.status(jobId)) throw new AgentError("ERR_JOB_NOT_FOUND", `Unknown job: ${jobId}`);
1168
+ const path = join(this.jobsRoot, `${jobId}.jsonl`);
1169
+ try {
1170
+ return (await readFile(path, "utf8")).trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));
1171
+ } catch (error) {
1172
+ if (error?.code === "ENOENT") return [];
1173
+ throw error;
1174
+ }
1175
+ }
1176
+ };
1177
+ const jobStores = /* @__PURE__ */ new Map();
1178
+ function jobStoreFor(root) {
1179
+ const projectRoot = resolve(root);
1180
+ let store = jobStores.get(projectRoot);
1181
+ if (!store) {
1182
+ store = new JobStore(projectRoot);
1183
+ jobStores.set(projectRoot, store);
1184
+ }
1185
+ return store;
1186
+ }
1187
+ async function readProcessLog(path) {
1188
+ try {
1189
+ return await readFile(path, "utf8");
1190
+ } catch {
1191
+ return "";
1192
+ }
1193
+ }
1194
+ async function controlRequest(url, token, path, options = {}) {
1195
+ const response = await fetch(new URL(path, url), {
1196
+ ...options,
1197
+ headers: {
1198
+ ...options.headers ?? {},
1199
+ "x-weapp-container-token": token
1200
+ }
1201
+ });
1202
+ const text = await response.text();
1203
+ let value;
1204
+ try {
1205
+ value = JSON.parse(text);
1206
+ } catch {
1207
+ value = { text };
1208
+ }
1209
+ if (!response.ok) throw new AgentError("ERR_PREVIEW_CONTROL", `${path} HTTP ${response.status}`, { cause: value });
1210
+ return value;
1211
+ }
1212
+ function ownedToken(value, expected) {
1213
+ const actual = Buffer.from(String(value ?? ""));
1214
+ const target = Buffer.from(String(expected ?? ""));
1215
+ return actual.length === target.length && timingSafeEqual(actual, target);
1216
+ }
1217
+ function isLoopbackUrl(value) {
1218
+ try {
1219
+ const url = new URL(value);
1220
+ return url.protocol === "http:" && url.hostname === "127.0.0.1" && Number(url.port) > 0 && !url.username && !url.password;
1221
+ } catch {
1222
+ return false;
1223
+ }
1224
+ }
1225
+ async function runPreviewDaemon(options) {
1226
+ const root = resolve(options.projectRoot);
1227
+ const pathsRoot = join(root, ".weapp-container", "preview");
1228
+ await mkdir(pathsRoot, { recursive: true });
1229
+ const logPath = options.logPath ?? join(pathsRoot, `${Date.now()}-${randomUUID()}.log`);
1230
+ const sessionPath = options.sessionPath ?? join(root, ".weapp-container", "preview.json");
1231
+ const errorPath = options.errorPath ?? `${sessionPath}.error`;
1232
+ const token = options.token;
1233
+ if (!token) throw new AgentError("ERR_PREVIEW_CONTROL", "Preview daemon requires an ownership token");
1234
+ const simulator = options.simulatorCommand ? {
1235
+ command: options.simulatorCommand,
1236
+ prefix: options.simulatorPrefix ?? [],
1237
+ cwd: root
1238
+ } : await simulatorBinary(root);
1239
+ const args = [
1240
+ ...simulator.prefix,
1241
+ "dev",
1242
+ "--project",
1243
+ root,
1244
+ "--surface",
1245
+ options.surface ?? "web",
1246
+ "--engine",
1247
+ options.engine ?? "quickjs",
1248
+ "--renderer",
1249
+ options.renderer ?? "webview",
1250
+ "--port",
1251
+ String(options.port ?? 0),
1252
+ "--out-dir",
1253
+ pathsRoot
1254
+ ];
1255
+ if (options.hostFixtures) args.push("--host-fixtures", options.hostFixtures);
1256
+ const compiler = options.wvBin ?? process.env.WEAPP_CONTAINER_WV_BIN ?? projectCompiler(root)?.entry;
1257
+ if (compiler) args.push("--wv-bin", compiler);
1258
+ const log = createWriteStream(logPath, { mode: 384 });
1259
+ const child = spawn(simulator.command, args, {
1260
+ cwd: simulator.cwd,
1261
+ detached: process.platform !== "win32",
1262
+ stdio: [
1263
+ "ignore",
1264
+ "pipe",
1265
+ "pipe"
1266
+ ],
1267
+ windowsHide: true
1268
+ });
1269
+ child.stdout.pipe(log);
1270
+ child.stderr.pipe(log);
1271
+ let spawnError;
1272
+ child.once("error", (error) => {
1273
+ spawnError = error;
1274
+ });
1275
+ const startedAt = now();
1276
+ let url;
1277
+ const waitUntilReady = async () => {
1278
+ const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1279
+ while (Date.now() < deadline) {
1280
+ const match = (await readProcessLog(logPath)).match(/weapp-simulator: web surface (http:\/\/127\.0\.0\.1:\d+\/?)/);
1281
+ if (match) {
1282
+ url = match[1].endsWith("/") ? match[1] : `${match[1]}/`;
1283
+ return;
1284
+ }
1285
+ if (spawnError) throw new AgentError("ERR_PREVIEW_START_FAILED", `Could not start simulator: ${spawnError.message}`, { cause: spawnError });
1286
+ if (child.exitCode !== null) throw new AgentError("ERR_PREVIEW_START_FAILED", `Simulator exited with code ${child.exitCode}. See ${logPath}`);
1287
+ await sleep(100, options.signal);
1288
+ }
1289
+ throw new AgentError("ERR_PREVIEW_START_FAILED", `Simulator did not announce a Web URL. See ${logPath}`);
1290
+ };
1291
+ const terminate = async () => {
1292
+ if (child.exitCode !== null) return;
1293
+ if (process.platform !== "win32") try {
1294
+ process.kill(-child.pid, "SIGTERM");
1295
+ } catch {}
1296
+ else {
1297
+ const killer = spawn("taskkill", [
1298
+ "/PID",
1299
+ String(child.pid),
1300
+ "/T",
1301
+ "/F"
1302
+ ], {
1303
+ windowsHide: true,
1304
+ stdio: "ignore"
1305
+ });
1306
+ await new Promise((resolvePromise) => {
1307
+ killer.once("error", resolvePromise);
1308
+ killer.once("close", resolvePromise);
1309
+ });
1310
+ if (child.exitCode === null) child.kill("SIGTERM");
1311
+ }
1312
+ await new Promise((resolvePromise) => {
1313
+ const timer = setTimeout(resolvePromise, 5e3);
1314
+ child.once("close", () => {
1315
+ clearTimeout(timer);
1316
+ resolvePromise();
1317
+ });
1318
+ });
1319
+ };
1320
+ let server;
1321
+ let serverClosing = false;
1322
+ const closeServer = () => {
1323
+ if (!server || serverClosing) return;
1324
+ serverClosing = true;
1325
+ server.close();
1326
+ };
1327
+ const handleSignal = () => {
1328
+ terminate().finally(closeServer);
1329
+ };
1330
+ process.once("SIGINT", handleSignal);
1331
+ process.once("SIGTERM", handleSignal);
1332
+ try {
1333
+ await waitUntilReady();
1334
+ server = createServer(async (request, response) => {
1335
+ if (!ownedToken(request.headers["x-weapp-container-token"], token)) {
1336
+ response.writeHead(401, { "content-type": "application/json" });
1337
+ response.end(JSON.stringify({ error: "unauthorized" }));
1338
+ return;
1339
+ }
1340
+ if (request.url === "/status" && request.method === "GET") {
1341
+ let state = null;
1342
+ try {
1343
+ state = await fetch(new URL("/api/state", url)).then((result) => result.json());
1344
+ } catch {}
1345
+ response.writeHead(200, { "content-type": "application/json" });
1346
+ response.end(JSON.stringify({
1347
+ status: state?.status === "ready" ? "ready" : "starting",
1348
+ url,
1349
+ project: root,
1350
+ logPath,
1351
+ startedAt,
1352
+ pid: child.pid,
1353
+ state
1354
+ }));
1355
+ return;
1356
+ }
1357
+ if (request.url === "/stop" && request.method === "POST") {
1358
+ response.writeHead(202, { "content-type": "application/json" });
1359
+ response.end(JSON.stringify({ stopping: true }));
1360
+ await terminate();
1361
+ closeServer();
1362
+ return;
1363
+ }
1364
+ response.writeHead(404, { "content-type": "application/json" });
1365
+ response.end(JSON.stringify({ error: "not found" }));
1366
+ });
1367
+ await new Promise((resolvePromise, rejectPromise) => {
1368
+ server.once("error", rejectPromise);
1369
+ server.listen(0, "127.0.0.1", resolvePromise);
1370
+ });
1371
+ const address = server.address();
1372
+ await writeJson(sessionPath, {
1373
+ schemaVersion: 2,
1374
+ pid: child.pid,
1375
+ daemonPid: process.pid,
1376
+ controlUrl: `http://127.0.0.1:${address.port}/`,
1377
+ url,
1378
+ project: root,
1379
+ packDirectory: options.packDirectory ?? null,
1380
+ logPath,
1381
+ token,
1382
+ startedAt
1383
+ });
1384
+ child.once("close", () => {
1385
+ closeServer();
1386
+ rm(sessionPath, { force: true });
1387
+ });
1388
+ await new Promise((resolvePromise) => server.once("close", resolvePromise));
1389
+ } catch (error) {
1390
+ await writeJson(errorPath, {
1391
+ code: error?.code ?? "ERR_PREVIEW_START_FAILED",
1392
+ message: error?.message ?? String(error)
1393
+ }).catch(() => {});
1394
+ throw error;
1395
+ } finally {
1396
+ process.removeListener("SIGINT", handleSignal);
1397
+ process.removeListener("SIGTERM", handleSignal);
1398
+ await terminate();
1399
+ log.end();
1400
+ await rm(sessionPath, { force: true });
1401
+ }
1402
+ }
1403
+ async function simulatorBinary(projectRoot) {
1404
+ const configured = process.env.WEAPP_CONTAINER_SIMULATOR_BIN;
1405
+ if (configured) {
1406
+ if (await exists(configured)) return {
1407
+ command: configured,
1408
+ prefix: [],
1409
+ cwd: projectRoot
1410
+ };
1411
+ throw new AgentError("ERR_SIMULATOR_NOT_FOUND", `WEAPP_CONTAINER_SIMULATOR_BIN does not exist: ${configured}`);
1412
+ }
1413
+ const binaryName = process.platform === "win32" ? "weapp-simulator.exe" : "weapp-simulator";
1414
+ const candidates = [join(PACKAGE_ROOT, "bin", binaryName), join(projectRoot, "node_modules/.bin", binaryName)];
1415
+ for (const candidate of candidates) if (await exists(candidate)) return {
1416
+ command: candidate,
1417
+ prefix: [],
1418
+ cwd: projectRoot
1419
+ };
1420
+ const local = join(REPOSITORY_ROOT, "target/debug/weapp-simulator");
1421
+ if (await exists(local)) return {
1422
+ command: local,
1423
+ prefix: [],
1424
+ cwd: projectRoot
1425
+ };
1426
+ if (await exists(join(REPOSITORY_ROOT, "Cargo.toml"))) return {
1427
+ command: process.env.CARGO ?? "cargo",
1428
+ prefix: [
1429
+ "run",
1430
+ "-p",
1431
+ "container-simulator",
1432
+ "--locked",
1433
+ "--features",
1434
+ "quickjs-native",
1435
+ "--"
1436
+ ],
1437
+ cwd: REPOSITORY_ROOT
1438
+ };
1439
+ return {
1440
+ command: binaryName,
1441
+ prefix: [],
1442
+ cwd: projectRoot
1443
+ };
1444
+ }
1445
+ var PreviewStore = class {
1446
+ constructor(root) {
1447
+ this.root = resolve(root);
1448
+ this.file = join(this.root, ".weapp-container", "preview.json");
1449
+ }
1450
+ async status() {
1451
+ const session = await readJson(this.file, null);
1452
+ if (!session) return { status: "closed" };
1453
+ if (!session.controlUrl || !session.token) return {
1454
+ status: "unknown",
1455
+ reason: "legacy preview session has no ownership control"
1456
+ };
1457
+ if (session.project !== this.root || !isLoopbackUrl(session.controlUrl) || !/^[a-f0-9]{64}$/i.test(session.token)) return {
1458
+ status: "unknown",
1459
+ reason: "preview session ownership data is invalid"
1460
+ };
1461
+ try {
1462
+ const status = await controlRequest(session.controlUrl, session.token, "/status");
1463
+ return isLoopbackUrl(status.url) ? status : {
1464
+ status: "unknown",
1465
+ reason: "preview URL is not a loopback address"
1466
+ };
1467
+ } catch {
1468
+ return {
1469
+ status: "unknown",
1470
+ reason: "preview control endpoint is unreachable"
1471
+ };
1472
+ }
1473
+ }
1474
+ async start(options = {}) {
1475
+ const existing = await this.status();
1476
+ if (existing.status === "ready" || existing.status === "starting") return existing;
1477
+ if (existing.status === "unknown") throw new AgentError("ERR_PREVIEW_STATE_UNKNOWN", "An existing preview session cannot be authenticated or stopped safely");
1478
+ const pack = options.packDirectory;
1479
+ if (pack && !await exists(resolve(pack))) throw new AgentError("ERR_PACK_NOT_FOUND", `Pack directory does not exist: ${pack}`);
1480
+ const pathsRoot = join(this.root, ".weapp-container", "preview");
1481
+ await mkdir(pathsRoot, { recursive: true });
1482
+ const logPath = join(pathsRoot, `${Date.now()}-${randomUUID()}.log`);
1483
+ const errorPath = `${this.file}.error`;
1484
+ await rm(errorPath, { force: true });
1485
+ const token = randomBytes(32).toString("hex");
1486
+ const daemonArgs = [
1487
+ ...CLI_RUNTIME_ARGS,
1488
+ CLI_ENTRY,
1489
+ "--preview-daemon",
1490
+ "--project",
1491
+ this.root,
1492
+ "--token",
1493
+ token,
1494
+ "--surface",
1495
+ options.surface ?? "web",
1496
+ "--engine",
1497
+ options.engine ?? "quickjs",
1498
+ "--renderer",
1499
+ options.renderer ?? "webview",
1500
+ "--port",
1501
+ String(options.port ?? 0),
1502
+ "--log",
1503
+ logPath,
1504
+ "--error",
1505
+ errorPath
1506
+ ];
1507
+ if (pack) daemonArgs.push("--pack", resolve(pack));
1508
+ if (options.hostFixtures) daemonArgs.push("--host-fixtures", resolve(this.root, options.hostFixtures));
1509
+ if (options.wvBin) daemonArgs.push("--wv-bin", options.wvBin);
1510
+ if (options.simulatorCommand) daemonArgs.push("--simulator-command", options.simulatorCommand, "--simulator-prefix", JSON.stringify(options.simulatorPrefix ?? []));
1511
+ const daemon = spawn(process.execPath, daemonArgs, {
1512
+ cwd: REPOSITORY_ROOT,
1513
+ detached: true,
1514
+ stdio: "ignore",
1515
+ windowsHide: true
1516
+ });
1517
+ daemon.unref();
1518
+ try {
1519
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1520
+ const deadline = Date.now() + timeoutMs;
1521
+ while (Date.now() < deadline) {
1522
+ if (options.signal?.aborted) throw options.signal.reason ?? new AgentError("ERR_CANCELLED", "Preview start cancelled");
1523
+ if ((await readJson(this.file, null))?.token === token) return await waitForPreviewReady(this, timeoutMs, options.signal);
1524
+ const failure = await readJson(errorPath, null);
1525
+ if (failure) throw new AgentError(failure.code ?? "ERR_PREVIEW_START_FAILED", failure.message ?? "Preview daemon failed");
1526
+ try {
1527
+ process.kill(daemon.pid, 0);
1528
+ } catch {
1529
+ break;
1530
+ }
1531
+ await sleep(100, options.signal);
1532
+ }
1533
+ throw new AgentError("ERR_PREVIEW_START_FAILED", `Preview daemon did not become ready. See ${logPath}`);
1534
+ } catch (error) {
1535
+ const session = await readJson(this.file, null);
1536
+ if (session?.token === token) try {
1537
+ await controlRequest(session.controlUrl, token, "/stop", { method: "POST" });
1538
+ } catch (stopError) {
1539
+ throw new AgentError(error?.code ?? "ERR_PREVIEW_START_FAILED", `${error?.message ?? String(error)}. Preview cleanup failed: ${stopError.message}`, { cause: {
1540
+ error,
1541
+ stopError
1542
+ } });
1543
+ }
1544
+ else try {
1545
+ process.kill(daemon.pid, "SIGTERM");
1546
+ } catch {}
1547
+ throw error;
1548
+ }
1549
+ }
1550
+ async stop() {
1551
+ const session = await readJson(this.file, null);
1552
+ if (!session) return { status: "closed" };
1553
+ if (session.controlUrl && session.token) try {
1554
+ await controlRequest(session.controlUrl, session.token, "/stop", { method: "POST" });
1555
+ } catch (error) {
1556
+ throw new AgentError("ERR_PREVIEW_STOP_FAILED", error.message, { cause: error });
1557
+ }
1558
+ else throw new AgentError("ERR_PREVIEW_STOP_FAILED", "Preview session is not owned by this agent");
1559
+ await rm(this.file, { force: true });
1560
+ return {
1561
+ status: "closed",
1562
+ pid: session.pid,
1563
+ daemonPid: session.daemonPid
1564
+ };
1565
+ }
1566
+ async request(path, options = {}) {
1567
+ const status = await this.status();
1568
+ if (!status.url) throw new AgentError("ERR_PREVIEW_UNAVAILABLE", "Preview is not running");
1569
+ const response = await fetch(new URL(path, status.url), options);
1570
+ const text = await response.text();
1571
+ let value;
1572
+ try {
1573
+ value = JSON.parse(text);
1574
+ } catch {
1575
+ value = { text };
1576
+ }
1577
+ if (!response.ok) throw new AgentError("ERR_PREVIEW_HTTP", `${path} HTTP ${response.status}`, { cause: value });
1578
+ return value;
1579
+ }
1580
+ };
1581
+ async function waitForPreviewReady(preview, timeoutMs = DEFAULT_TIMEOUT_MS, signal) {
1582
+ const deadline = Date.now() + timeoutMs;
1583
+ while (Date.now() < deadline) {
1584
+ if (signal?.aborted) throw signal.reason ?? new AgentError("ERR_CANCELLED", "Preview readiness wait cancelled");
1585
+ const state = await preview.status();
1586
+ if (state.status === "ready") return state;
1587
+ if (state.status === "unknown") throw new AgentError("ERR_PREVIEW_STATE_UNKNOWN", state.reason ?? "Preview state is unknown");
1588
+ if (state.status === "closed") throw new AgentError("ERR_PREVIEW_START_FAILED", "Preview closed before becoming ready");
1589
+ await sleep(100, signal);
1590
+ }
1591
+ throw new AgentError("ERR_PREVIEW_READY_TIMEOUT", `Preview did not become ready within ${timeoutMs}ms`);
1592
+ }
1593
+ async function copyDirectory(source, destination) {
1594
+ await mkdir(destination, { recursive: true });
1595
+ for (const entry of await readdir(source, { withFileTypes: true })) {
1596
+ const from = join(source, entry.name);
1597
+ const to = join(destination, entry.name);
1598
+ if (entry.isDirectory()) await copyDirectory(from, to);
1599
+ else if (entry.isFile()) {
1600
+ await mkdir(dirname(to), { recursive: true });
1601
+ await new Promise((resolvePromise, rejectPromise) => createReadStream(from).pipe(createWriteStream(to)).on("finish", resolvePromise).on("error", rejectPromise));
1602
+ }
1603
+ }
1604
+ }
1605
+ async function prepareRelease(projectRoot, version, options = {}) {
1606
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) throw new AgentError("ERR_INVALID_VERSION", `Invalid release version: ${version}`);
1607
+ const root = resolve(projectRoot);
1608
+ const build = options.buildResult ?? await buildProject(root, options);
1609
+ if (build.platform && build.platform !== "weapp") throw new AgentError("ERR_RELEASE_PLATFORM", "Container releases require a weapp portable pack");
1610
+ if (!build.packDirectory) throw new AgentError("ERR_RELEASE_PACK_REQUIRED", "Container releases require a successful weapp portable pack");
1611
+ const releaseRoot = projectPath(root, options.releaseRoot ?? ".weapp-container/releases");
1612
+ const destination = join(releaseRoot, version);
1613
+ if (await exists(destination)) throw new AgentError("ERR_RELEASE_EXISTS", `Release already exists: ${version}`);
1614
+ const evidence = options.evidence ?? [await runRuntimeSmoke(build, options).catch((error) => ({
1615
+ type: "simulator-runtime-smoke",
1616
+ status: "failed",
1617
+ error: {
1618
+ code: error.code ?? "ERR_RUNTIME_SMOKE",
1619
+ message: error.message
1620
+ }
1621
+ }))];
1622
+ const releaseStatus = evidence.some((item) => item.status === "failed") ? "failed" : evidence.length > 0 && evidence.every((item) => item.status === "passed") ? "verified" : "draft";
1623
+ const staging = join(releaseRoot, `.prepare-${version}-${randomUUID()}`);
1624
+ await mkdir(releaseRoot, { recursive: true });
1625
+ let manifest;
1626
+ try {
1627
+ await mkdir(staging);
1628
+ await copyDirectory(build.packDirectory, join(staging, "pack"));
1629
+ manifest = {
1630
+ schemaVersion: 1,
1631
+ version,
1632
+ projectDigest: await digestDirectory(root),
1633
+ sourceDigest: build.sourceDigest,
1634
+ compilerIdentity: build.compilerCommit,
1635
+ packDigest: await digestDirectory(join(staging, "pack"), {
1636
+ includeHidden: true,
1637
+ ignoredDirectories: /* @__PURE__ */ new Set()
1638
+ }),
1639
+ evidence,
1640
+ createdAt: now(),
1641
+ status: releaseStatus,
1642
+ buildReport: "build-report.json"
1643
+ };
1644
+ await writeJson(join(staging, "build-report.json"), {
1645
+ ...build,
1646
+ evidence
1647
+ });
1648
+ await writeJson(join(staging, "release.json"), manifest);
1649
+ await rename(staging, destination);
1650
+ } catch (error) {
1651
+ await rm(staging, {
1652
+ recursive: true,
1653
+ force: true
1654
+ });
1655
+ if (error?.code === "EEXIST" || error?.code === "ENOTEMPTY") throw new AgentError("ERR_RELEASE_EXISTS", `Release already exists: ${version}`, { cause: error });
1656
+ throw error;
1657
+ }
1658
+ return {
1659
+ ...manifest,
1660
+ path: destination
1661
+ };
1662
+ }
1663
+ async function runRuntimeSmoke(build, options = {}) {
1664
+ const simulator = await simulatorBinary(build.project.root);
1665
+ const reportPath = join(dirname(build.packDirectory), "runtime-smoke.json");
1666
+ const route = build.project.pages?.[0];
1667
+ const args = [
1668
+ ...simulator.prefix,
1669
+ "run",
1670
+ "--pack",
1671
+ build.packDirectory,
1672
+ ...route ? ["--route", route] : [],
1673
+ "--report",
1674
+ reportPath
1675
+ ];
1676
+ const result = await runCommand(simulator.command, args, {
1677
+ cwd: REPOSITORY_ROOT,
1678
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS
1679
+ });
1680
+ const report = await readJson(reportPath, null);
1681
+ if (result.code !== 0 || report?.status !== "passed") throw new AgentError("ERR_RUNTIME_SMOKE_FAILED", result.stderr || report?.error || result.stdout || "Simulator runtime smoke did not pass", { cause: {
1682
+ command: commandResult(simulator.command, args, result),
1683
+ report
1684
+ } });
1685
+ return {
1686
+ type: "simulator-runtime-smoke",
1687
+ status: "passed",
1688
+ engine: report.engine ?? "quickjs",
1689
+ route: report.route ?? route ?? null,
1690
+ reportPath,
1691
+ report
1692
+ };
1693
+ }
1694
+ async function verifyReleasePack(destination, manifest) {
1695
+ const packPath = join(destination, "pack");
1696
+ if (!await exists(packPath)) throw new AgentError("ERR_RELEASE_INTEGRITY", "Release pack is missing");
1697
+ if (await digestDirectory(packPath, {
1698
+ includeHidden: true,
1699
+ ignoredDirectories: /* @__PURE__ */ new Set()
1700
+ }) !== manifest.packDigest) throw new AgentError("ERR_RELEASE_INTEGRITY", "Release pack digest does not match its manifest");
1701
+ if (!await exists(join(packPath, "manifest.json"))) throw new AgentError("ERR_RELEASE_INTEGRITY", "Release pack manifest is missing");
1702
+ }
1703
+ async function commitRelease(projectRoot, version, options = {}) {
1704
+ if (options.confirmed !== true) throw new AgentError("ERR_CONFIRMATION_REQUIRED", "Release commit requires explicit confirmation");
1705
+ const root = resolve(projectRoot);
1706
+ const releaseRoot = projectPath(root, ".weapp-container/releases");
1707
+ const destination = join(releaseRoot, version);
1708
+ const manifestPath = join(destination, "release.json");
1709
+ const manifest = await readJson(manifestPath, null);
1710
+ if (!manifest) throw new AgentError("ERR_RELEASE_NOT_FOUND", `Release does not exist: ${version}`);
1711
+ if (manifest.status !== "verified" && manifest.status !== "committed") throw new AgentError("ERR_RELEASE_INVALID_STATE", `Release cannot be committed from ${manifest.status}`);
1712
+ await verifyReleasePack(destination, manifest);
1713
+ if (await digestDirectory(root) !== manifest.projectDigest) throw new AgentError("ERR_RELEASE_SOURCE_CHANGED", "Project source changed after release preparation");
1714
+ const updated = {
1715
+ ...manifest,
1716
+ status: "committed",
1717
+ committedAt: now()
1718
+ };
1719
+ await writeJson(manifestPath, updated);
1720
+ await writeJson(join(releaseRoot, "current.json"), {
1721
+ schemaVersion: 1,
1722
+ version,
1723
+ updatedAt: now()
1724
+ });
1725
+ return {
1726
+ ...updated,
1727
+ path: destination
1728
+ };
1729
+ }
1730
+ async function listReleases(projectRoot) {
1731
+ const releaseRoot = projectPath(resolve(projectRoot), ".weapp-container/releases");
1732
+ const entries = await readdir(releaseRoot, { withFileTypes: true }).catch(() => []);
1733
+ const releases = [];
1734
+ for (const entry of entries.filter((entry) => entry.isDirectory())) {
1735
+ const manifest = await readJson(join(releaseRoot, entry.name, "release.json"), null);
1736
+ if (manifest) releases.push({
1737
+ ...manifest,
1738
+ path: join(releaseRoot, entry.name)
1739
+ });
1740
+ }
1741
+ releases.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1742
+ return {
1743
+ current: await readJson(join(releaseRoot, "current.json"), null),
1744
+ releases
1745
+ };
1746
+ }
1747
+ async function rollbackRelease(projectRoot, version, options = {}) {
1748
+ if (options.confirmed !== true) throw new AgentError("ERR_CONFIRMATION_REQUIRED", "Release rollback requires explicit confirmation");
1749
+ const target = (await listReleases(projectRoot)).releases.find((release) => release.version === version);
1750
+ if (!target) throw new AgentError("ERR_RELEASE_NOT_FOUND", `Release does not exist: ${version}`);
1751
+ if (target.status !== "committed") throw new AgentError("ERR_RELEASE_INVALID_STATE", `Release cannot be rolled back from ${target.status}`);
1752
+ await verifyReleasePack(target.path, target);
1753
+ await writeJson(join(resolve(projectRoot), ".weapp-container/releases/current.json"), {
1754
+ schemaVersion: 1,
1755
+ version,
1756
+ updatedAt: now(),
1757
+ rolledBack: true
1758
+ });
1759
+ return {
1760
+ ...target,
1761
+ status: "rolled_back",
1762
+ current: version
1763
+ };
1764
+ }
1765
+ async function publishRelease(projectRoot, version, options = {}) {
1766
+ if (options.confirmed !== true) throw new AgentError("ERR_CONFIRMATION_REQUIRED", "Release publish requires explicit confirmation");
1767
+ const root = resolve(projectRoot);
1768
+ const target = (await listReleases(root)).releases.find((release) => release.version === version);
1769
+ if (!target) throw new AgentError("ERR_RELEASE_NOT_FOUND", `Release does not exist: ${version}`);
1770
+ if (target.status !== "committed") throw new AgentError("ERR_RELEASE_INVALID_STATE", `Release cannot be published from ${target.status}`);
1771
+ await verifyReleasePack(target.path, target);
1772
+ if (await digestDirectory(root) !== target.projectDigest) throw new AgentError("ERR_RELEASE_SOURCE_CHANGED", "Project source changed after release preparation");
1773
+ const platform = options.platform ?? "weapp";
1774
+ const configuredKeyPath = options.privateKeyPath ?? process.env.WEAPP_CI_PRIVATE_KEY_PATH;
1775
+ const privateKeyPath = configuredKeyPath ? resolve(root, configuredKeyPath) : void 0;
1776
+ if (platform === "weapp" && !privateKeyPath) throw new AgentError("ERR_PUBLISH_CREDENTIALS", "微信发布需要 WEAPP_CI_PRIVATE_KEY_PATH 指向代码上传私钥", { status: "blocked" });
1777
+ if (platform === "weapp" && privateKeyPath && !await exists(privateKeyPath)) throw new AgentError("ERR_PUBLISH_CREDENTIALS", `微信上传私钥文件不存在: ${privateKeyPath}`, { status: "blocked" });
1778
+ const wv = await resolveWv(root, options.wvBin);
1779
+ const args = [
1780
+ "build",
1781
+ "--upload",
1782
+ "-p",
1783
+ platform,
1784
+ "--uv",
1785
+ version,
1786
+ "--desc",
1787
+ options.description ?? `weapp-container ${version}`
1788
+ ];
1789
+ const publish = await (options.commandRunner ?? runCommand)(wv, args, {
1790
+ cwd: root,
1791
+ timeoutMs: options.timeoutMs,
1792
+ env: privateKeyPath ? { WEAPP_CI_PRIVATE_KEY_PATH: privateKeyPath } : void 0,
1793
+ signal: options.signal
1794
+ });
1795
+ if (publish.code !== 0) throw new AgentError("ERR_PUBLISH_FAILED", publish.stderr || publish.stdout || "Mini-program publish failed", { cause: commandResult(wv, args, publish) });
1796
+ const receipt = {
1797
+ schemaVersion: 1,
1798
+ version,
1799
+ platform,
1800
+ status: "uploaded",
1801
+ command: [wv, ...args].join(" "),
1802
+ uploadedAt: now()
1803
+ };
1804
+ await writeJson(join(target.path, "publish.json"), receipt);
1805
+ return {
1806
+ ...receipt,
1807
+ releasePath: target.path
1808
+ };
1809
+ }
1810
+ async function loadPlaywright(root) {
1811
+ const candidates = [
1812
+ process.env.WEAPP_CONTAINER_PLAYWRIGHT_MODULE,
1813
+ join(PACKAGE_ROOT, "node_modules/playwright/index.mjs"),
1814
+ join(REPOSITORY_ROOT, "vendor/weapp-vite/node_modules/playwright/index.mjs"),
1815
+ join(root, "node_modules/playwright/index.mjs")
1816
+ ].filter(Boolean);
1817
+ for (const candidate of candidates) if (await exists(candidate)) return import(pathToFileURL(candidate).href);
1818
+ throw new AgentError("ERR_BROWSER_UNAVAILABLE", "Playwright is unavailable. Set WEAPP_CONTAINER_PLAYWRIGHT_MODULE or install playwright in the project.", { status: "blocked" });
1819
+ }
1820
+ async function browserLaunch(root, browserOptions = {}) {
1821
+ const playwright = await loadPlaywright(root);
1822
+ if (browserOptions.headless !== void 0 && typeof browserOptions.headless !== "boolean") throw new AgentError("ERR_SCENARIO_INVALID", "browser.headless must be a boolean");
1823
+ const launchOptions = {
1824
+ headless: browserOptions.headless ?? true,
1825
+ handleSIGINT: false,
1826
+ handleSIGTERM: false
1827
+ };
1828
+ const executablePath = browserOptions.executablePath ?? process.env.WEAPP_CONTAINER_BROWSER_EXECUTABLE_PATH;
1829
+ if (executablePath) launchOptions.executablePath = executablePath;
1830
+ else if (await exists(process.platform === "darwin" ? "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" : process.platform === "win32" ? "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" : "/usr/bin/google-chrome")) launchOptions.channel = "chrome";
1831
+ try {
1832
+ return await playwright.chromium.launch(launchOptions);
1833
+ } catch (error) {
1834
+ throw new AgentError("ERR_BROWSER_UNAVAILABLE", `Could not launch Chromium: ${error.message}. Install a browser with npx playwright install chromium or set WEAPP_CONTAINER_BROWSER_EXECUTABLE_PATH.`, {
1835
+ cause: error,
1836
+ status: "blocked"
1837
+ });
1838
+ }
1839
+ }
1840
+ async function browserProperty(locator, property, attributeName) {
1841
+ if (property === "text" || property === "textContent") return locator.textContent();
1842
+ if (property === "value") return locator.inputValue();
1843
+ if (property === "count") return locator.count();
1844
+ if (property === "visible") return locator.isVisible();
1845
+ if (property === "enabled") return locator.isEnabled();
1846
+ if (property === "attribute") {
1847
+ if (typeof attributeName !== "string" || !attributeName) throw new AgentError("ERR_SCENARIO_INVALID", "Browser attribute property requires an attribute name");
1848
+ return locator.getAttribute(attributeName);
1849
+ }
1850
+ throw new AgentError("ERR_SCENARIO_INVALID", `Unsupported browser locator property: ${property}`);
1851
+ }
1852
+ function scenarioArtifactPath(root, artifactRoot, value) {
1853
+ const target = resolve(artifactRoot, value ?? "screenshot.png");
1854
+ if (!inside(root, target) || !inside(artifactRoot, target)) throw new AgentError("ERR_PATH_OUTSIDE_PROJECT", `Browser artifact path is outside the artifact directory: ${value ?? "screenshot.png"}`);
1855
+ return target;
1856
+ }
1857
+ async function runBrowserStep(browserState, step, root, artifactRoot, timeoutMs) {
1858
+ const page = browserState.page;
1859
+ page.setDefaultTimeout(timeoutMs);
1860
+ const selector = step.selector;
1861
+ if (step.frame !== void 0 && (typeof step.frame !== "string" || !step.frame.trim())) throw new AgentError("ERR_SCENARIO_INVALID", "Browser frame requires a non-empty selector");
1862
+ const scope = step.frame ? page.frameLocator(step.frame) : page;
1863
+ const locator = selector ? scope.locator(selector) : null;
1864
+ if (step.action === "goto") {
1865
+ const targetUrl = new URL(step.url ?? "/", browserState.baseUrl);
1866
+ if (targetUrl.origin !== new URL(browserState.baseUrl).origin) throw new AgentError("ERR_SCENARIO_URL", "Browser navigation must stay on the local preview origin");
1867
+ const target = targetUrl.toString();
1868
+ await page.goto(target, { waitUntil: step.waitUntil ?? "domcontentloaded" });
1869
+ return {
1870
+ action: step.action,
1871
+ url: page.url()
1872
+ };
1873
+ }
1874
+ if (step.action === "click") {
1875
+ if (!locator) throw new AgentError("ERR_SCENARIO_INVALID", "Browser click requires selector");
1876
+ await locator.click();
1877
+ return {
1878
+ action: step.action,
1879
+ selector
1880
+ };
1881
+ }
1882
+ if (step.action === "fill") {
1883
+ if (!locator) throw new AgentError("ERR_SCENARIO_INVALID", "Browser fill requires selector");
1884
+ await locator.fill(String(step.value ?? ""));
1885
+ return {
1886
+ action: step.action,
1887
+ selector,
1888
+ value: String(step.value ?? "")
1889
+ };
1890
+ }
1891
+ if (step.action === "press") {
1892
+ if (!locator || typeof step.key !== "string") throw new AgentError("ERR_SCENARIO_INVALID", "Browser press requires selector and key");
1893
+ await locator.press(step.key);
1894
+ return {
1895
+ action: step.action,
1896
+ selector,
1897
+ key: step.key
1898
+ };
1899
+ }
1900
+ if (step.action === "wait") {
1901
+ if (locator) await locator.waitFor({ state: step.state ?? "visible" });
1902
+ else await page.waitForTimeout(Number(step.ms ?? 100));
1903
+ return {
1904
+ action: step.action,
1905
+ selector: selector ?? null
1906
+ };
1907
+ }
1908
+ if (step.action === "locator") {
1909
+ if (!locator) throw new AgentError("ERR_SCENARIO_INVALID", "Browser locator requires selector");
1910
+ const property = step.property ?? "text";
1911
+ return {
1912
+ action: step.action,
1913
+ selector,
1914
+ property,
1915
+ value: await browserProperty(locator, property, step.name)
1916
+ };
1917
+ }
1918
+ if (step.action === "screenshot") {
1919
+ const path = scenarioArtifactPath(root, artifactRoot, step.path);
1920
+ await mkdir(dirname(path), { recursive: true });
1921
+ await page.screenshot({
1922
+ path,
1923
+ fullPage: step.fullPage ?? true
1924
+ });
1925
+ return {
1926
+ action: step.action,
1927
+ path,
1928
+ url: page.url()
1929
+ };
1930
+ }
1931
+ throw new AgentError("ERR_SCENARIO_UNSUPPORTED", `Unsupported browser action: ${step.action}`);
1932
+ }
1933
+ async function runScenario(preview, scenario = {}, options = {}) {
1934
+ const steps = Array.isArray(scenario.steps) ? scenario.steps : [];
1935
+ const results = [];
1936
+ const scenarioLeases = /* @__PURE__ */ new Set();
1937
+ const root = resolve(options.projectRoot ?? process.cwd());
1938
+ const artifactRoot = resolve(options.artifactRoot ?? join(root, ".weapp-container", "agent", "artifacts", options.jobId ?? randomUUID()));
1939
+ let browserState;
1940
+ const assertExpected = (value, expected, index) => {
1941
+ if (expected === void 0) return;
1942
+ const matches = (actual, wanted) => {
1943
+ if (wanted && typeof wanted === "object") {
1944
+ if (!actual || typeof actual !== "object") return false;
1945
+ return Object.entries(wanted).every(([key, expectedValue]) => matches(actual[key], expectedValue));
1946
+ }
1947
+ return Object.is(actual, wanted);
1948
+ };
1949
+ if (!matches(value, expected)) throw new AgentError("ERR_SCENARIO_ASSERTION", `Scenario step ${index} assertion failed`, { cause: {
1950
+ actual: value,
1951
+ expected
1952
+ } });
1953
+ };
1954
+ try {
1955
+ for (const [index, step] of steps.entries()) {
1956
+ if (!step || typeof step.op !== "string") throw new AgentError("ERR_SCENARIO_INVALID", `Scenario step ${index} requires an op`);
1957
+ if (step.op === "state") {
1958
+ const value = await preview.request("/api/state");
1959
+ assertExpected(value, step.expect, index);
1960
+ results.push({
1961
+ index,
1962
+ op: step.op,
1963
+ value
1964
+ });
1965
+ } else if (step.op === "snapshot") {
1966
+ const value = await preview.request("/api/snapshot");
1967
+ assertExpected(value, step.expect, index);
1968
+ results.push({
1969
+ index,
1970
+ op: step.op,
1971
+ value
1972
+ });
1973
+ } else if (step.op === "bridge") {
1974
+ const state = await preview.request("/api/state");
1975
+ if (state.status !== "ready" || typeof state.sessionId !== "string") throw new AgentError("ERR_SCENARIO_RUNTIME_NOT_READY", "Simulator runtime is not ready for bridge requests");
1976
+ const input = step.request ?? {};
1977
+ const messages = (Array.isArray(input.messages) ? input.messages : [input]).map((message) => structuredClone(message));
1978
+ const requestIds = messages.map((message) => {
1979
+ if (!message || typeof message.op !== "string") throw new AgentError("ERR_SCENARIO_INVALID", `Scenario step ${index} bridge request requires an op`);
1980
+ if (message.sessionId && message.sessionId !== state.sessionId) throw new AgentError("ERR_SCENARIO_SESSION", "Bridge request belongs to a different simulator session");
1981
+ message.protocolVersion ??= "1.0";
1982
+ message.sessionId = state.sessionId;
1983
+ message.requestId ??= randomUUID();
1984
+ message.kind ??= "request";
1985
+ message.payload ??= {};
1986
+ return message.requestId;
1987
+ });
1988
+ const requiresPreviewFence = messages.some((message) => message.op.startsWith("view."));
1989
+ const scenarioClientId = step.clientId ?? scenario.clientId ?? `container-agent-${randomUUID().slice(0, 12)}`;
1990
+ const lease = requiresPreviewFence ? await ensureScenarioLease(preview, state, scenarioClientId, step.timeoutMs ?? 1e4, options.signal) : {
1991
+ state,
1992
+ fence: null,
1993
+ created: false
1994
+ };
1995
+ if (lease.created) scenarioLeases.add(scenarioClientId);
1996
+ if (requiresPreviewFence) for (const message of messages) {
1997
+ if (message.preview && JSON.stringify(message.preview) !== JSON.stringify(lease.fence)) throw new AgentError("ERR_SCENARIO_PREVIEW_FENCE", `Scenario step ${index} contains a preview fence that does not match the current lease`);
1998
+ delete message.preview;
1999
+ }
2000
+ const request = Array.isArray(input.messages) ? {
2001
+ ...input,
2002
+ messages,
2003
+ ...lease.fence ? { preview: lease.fence } : {}
2004
+ } : {
2005
+ ...messages[0],
2006
+ ...lease.fence ? { preview: lease.fence } : {}
2007
+ };
2008
+ let queued;
2009
+ const trigger = () => preview.request("/api/bridge", {
2010
+ method: "POST",
2011
+ headers: { "content-type": "application/json" },
2012
+ body: JSON.stringify(request)
2013
+ }).then((value) => {
2014
+ queued = value;
2015
+ return value;
2016
+ });
2017
+ const value = await waitForBridgeEvent(preview, messages, state.sessionId, step.timeoutMs ?? 1e4, trigger, options.signal);
2018
+ if (!queued?.queued && !queued?.messages) throw new AgentError("ERR_SCENARIO_BRIDGE", "Bridge request did not produce a simulator receipt", { cause: queued });
2019
+ if (!step.expect && value?.messages && value.messages.some((message) => message.kind === "response" && (message.payload?.ok === false || message.payload?.error?.code))) throw new AgentError("ERR_SCENARIO_BRIDGE_REJECTED", "Simulator rejected the bridge request", { cause: value });
2020
+ assertExpected(value, step.expect, index);
2021
+ results.push({
2022
+ index,
2023
+ op: step.op,
2024
+ requestIds,
2025
+ value
2026
+ });
2027
+ } else if (step.op === "wait") {
2028
+ const waitedMs = Number(step.ms ?? 100);
2029
+ await sleep(waitedMs, options.signal);
2030
+ results.push({
2031
+ index,
2032
+ op: step.op,
2033
+ waitedMs
2034
+ });
2035
+ } else if (step.op === "browser") {
2036
+ if (!browserState) {
2037
+ const status = await preview.status();
2038
+ if (!status.url) throw new AgentError("ERR_PREVIEW_UNAVAILABLE", "Preview is not running");
2039
+ browserState = {
2040
+ browser: await browserLaunch(root, scenario.browser),
2041
+ context: null,
2042
+ page: null,
2043
+ baseUrl: status.url
2044
+ };
2045
+ const viewport = scenario.browser?.viewport;
2046
+ if (viewport && (!Number.isInteger(viewport.width) || !Number.isInteger(viewport.height) || viewport.width < 1 || viewport.height < 1)) throw new AgentError("ERR_SCENARIO_INVALID", "browser.viewport requires positive integer width and height");
2047
+ browserState.context = await browserState.browser.newContext({ viewport: viewport ?? {
2048
+ width: 1280,
2049
+ height: 720
2050
+ } });
2051
+ browserState.page = await browserState.context.newPage();
2052
+ await browserState.page.goto(status.url, { waitUntil: "domcontentloaded" });
2053
+ }
2054
+ const value = await runBrowserStep(browserState, step, root, artifactRoot, step.timeoutMs ?? scenario.timeoutMs ?? 1e4);
2055
+ assertExpected(value, step.expect, index);
2056
+ results.push({
2057
+ index,
2058
+ op: step.op,
2059
+ value
2060
+ });
2061
+ } else throw new AgentError("ERR_SCENARIO_UNSUPPORTED", `Unsupported scenario operation: ${step.op}`);
2062
+ }
2063
+ return {
2064
+ schemaVersion: 1,
2065
+ name: scenario.name ?? "unnamed",
2066
+ status: "passed",
2067
+ steps: results,
2068
+ finishedAt: now()
2069
+ };
2070
+ } finally {
2071
+ if (browserState) await browserState.browser.close().catch(() => {});
2072
+ for (const clientId of scenarioLeases) {
2073
+ const state = await preview.request("/api/state").catch(() => null);
2074
+ if (state?.preview?.ownerClientId !== clientId) continue;
2075
+ await preview.request("/api/preview", {
2076
+ method: "POST",
2077
+ headers: { "content-type": "application/json" },
2078
+ body: JSON.stringify({
2079
+ version: "1.0",
2080
+ requestId: `agent-release-${randomUUID()}`,
2081
+ clientId,
2082
+ op: "release",
2083
+ epoch: state.preview.epoch
2084
+ })
2085
+ }).catch(() => {});
2086
+ }
2087
+ }
2088
+ }
2089
+ async function ensureScenarioLease(preview, state, clientId, timeoutMs, signal) {
2090
+ if (!/^[A-Za-z0-9._:-]{1,128}$/.test(clientId)) throw new AgentError("ERR_SCENARIO_PREVIEW_CLIENT", `Invalid scenario preview client id: ${clientId}`);
2091
+ const currentOwner = state.preview?.ownerClientId;
2092
+ if (currentOwner && currentOwner !== clientId) throw new AgentError("ERR_SCENARIO_PREVIEW_BUSY", `Preview is owned by ${currentOwner}`);
2093
+ if (currentOwner !== clientId) await preview.request("/api/preview", {
2094
+ method: "POST",
2095
+ headers: { "content-type": "application/json" },
2096
+ body: JSON.stringify({
2097
+ version: "1.0",
2098
+ requestId: `agent-connect-${randomUUID()}`,
2099
+ clientId,
2100
+ op: "connect"
2101
+ }),
2102
+ signal
2103
+ });
2104
+ const ready = await waitForState(preview, (value) => value.status === "ready" && value.preview?.ownerClientId === clientId, timeoutMs, signal, "ERR_SCENARIO_PREVIEW_TIMEOUT");
2105
+ const authority = ready.viewAuthority ?? {};
2106
+ const epoch = ready.preview?.epoch;
2107
+ if (typeof epoch !== "string") throw new AgentError("ERR_SCENARIO_PREVIEW_FENCE", "Simulator did not expose a preview epoch");
2108
+ return {
2109
+ state: ready,
2110
+ created: currentOwner !== clientId,
2111
+ fence: {
2112
+ clientId,
2113
+ epoch,
2114
+ ...typeof authority.revision === "string" ? { requestRevision: authority.revision } : {}
2115
+ }
2116
+ };
2117
+ }
2118
+ async function waitForState(preview, predicate, timeoutMs, signal, timeoutCode) {
2119
+ const deadline = Date.now() + timeoutMs;
2120
+ while (Date.now() < deadline) {
2121
+ if (signal?.aborted) throw signal.reason ?? new AgentError("ERR_CANCELLED", "Scenario cancelled");
2122
+ const state = await preview.request("/api/state", { signal });
2123
+ if (predicate(state)) return state;
2124
+ await sleep(100, signal);
2125
+ }
2126
+ throw new AgentError(timeoutCode, `Simulator did not reach the expected state within ${timeoutMs}ms`);
2127
+ }
2128
+ async function waitForBridgeEvent(preview, requests, sessionId, timeoutMs, trigger, externalSignal) {
2129
+ const status = await preview.status();
2130
+ if (!status.url) throw new AgentError("ERR_PREVIEW_UNAVAILABLE", "Preview is not running");
2131
+ const timeoutController = new AbortController();
2132
+ const signal = externalSignal ? AbortSignal.any([externalSignal, timeoutController.signal]) : timeoutController.signal;
2133
+ const timer = setTimeout(() => timeoutController.abort(), timeoutMs);
2134
+ try {
2135
+ const response = await fetch(new URL("/api/events", status.url), { signal });
2136
+ if (!response.ok || !response.body) throw new AgentError("ERR_SCENARIO_EVENTS", `Event stream HTTP ${response.status}`);
2137
+ await trigger();
2138
+ const reader = response.body.getReader();
2139
+ const decoder = new TextDecoder();
2140
+ let buffer = "";
2141
+ while (true) {
2142
+ const { value, done } = await reader.read();
2143
+ if (done) break;
2144
+ buffer += decoder.decode(value, { stream: true });
2145
+ const events = buffer.split("\n\n");
2146
+ buffer = events.pop() ?? "";
2147
+ for (const event of events) {
2148
+ const type = event.match(/^event:[ \t]*(\S[^\r\n]*)$/m)?.[1];
2149
+ const data = event.match(/^data:[ \t]*(\S[^\r\n]*)$/m)?.[1];
2150
+ if (type !== "bridge" || !data) continue;
2151
+ let payload;
2152
+ try {
2153
+ payload = JSON.parse(data);
2154
+ } catch {
2155
+ continue;
2156
+ }
2157
+ const messages = Array.isArray(payload?.messages) ? payload.messages : [payload];
2158
+ if (requests.every((request) => messages.some((message) => message?.kind === "response" && message?.requestId === request.requestId && message?.sessionId === sessionId && message?.op === request.op))) return payload;
2159
+ }
2160
+ }
2161
+ throw new AgentError("ERR_SCENARIO_EVENTS", `Bridge response event not observed for requests ${requests.map((request) => request.requestId).join(", ")}`);
2162
+ } catch (error) {
2163
+ if (externalSignal?.aborted) throw externalSignal.reason ?? new AgentError("ERR_CANCELLED", "Scenario cancelled");
2164
+ if (timeoutController.signal.aborted) throw new AgentError("ERR_SCENARIO_TIMEOUT", `Timed out waiting for bridge requests ${requests.map((request) => request.requestId).join(", ")}`);
2165
+ throw error;
2166
+ } finally {
2167
+ clearTimeout(timer);
2168
+ timeoutController.abort();
2169
+ }
2170
+ }
2171
+ function toolCatalog() {
2172
+ return [
2173
+ [
2174
+ "container_project_init",
2175
+ "Initialize local agent state for a mini-program project.",
2176
+ { projectPath: { type: "string" } }
2177
+ ],
2178
+ [
2179
+ "container_project_inspect",
2180
+ "Inspect a local mini-program project.",
2181
+ { projectPath: { type: "string" } }
2182
+ ],
2183
+ [
2184
+ "container_project_files",
2185
+ "List source files available to the coding agent.",
2186
+ { projectPath: { type: "string" } }
2187
+ ],
2188
+ [
2189
+ "container_project_file_read",
2190
+ "Read a project-relative source file.",
2191
+ {
2192
+ projectPath: { type: "string" },
2193
+ path: { type: "string" }
2194
+ }
2195
+ ],
2196
+ [
2197
+ "container_project_file_write",
2198
+ "Write a project-relative source file atomically.",
2199
+ {
2200
+ projectPath: { type: "string" },
2201
+ path: { type: "string" },
2202
+ content: { type: "string" }
2203
+ }
2204
+ ],
2205
+ [
2206
+ "container_build",
2207
+ "Build a project for one compiler target and create a portable pack for weapp output.",
2208
+ {
2209
+ projectPath: { type: "string" },
2210
+ platform: { type: "string" },
2211
+ out: { type: "string" },
2212
+ wvBin: { type: "string" },
2213
+ timeoutMs: { type: "number" }
2214
+ }
2215
+ ],
2216
+ [
2217
+ "container_preview_start",
2218
+ "Start a local Web simulator preview from project sources.",
2219
+ {
2220
+ projectPath: { type: "string" },
2221
+ packDirectory: { type: "string" },
2222
+ hostFixtures: { type: "string" },
2223
+ wvBin: { type: "string" },
2224
+ surface: { type: "string" },
2225
+ renderer: { type: "string" },
2226
+ port: { type: "number" },
2227
+ timeoutMs: { type: "number" },
2228
+ simulatorCommand: { type: "string" },
2229
+ simulatorPrefix: {
2230
+ type: "array",
2231
+ items: { type: "string" }
2232
+ }
2233
+ }
2234
+ ],
2235
+ [
2236
+ "container_preview_status",
2237
+ "Read preview status and simulator state.",
2238
+ { projectPath: { type: "string" } }
2239
+ ],
2240
+ [
2241
+ "container_preview_stop",
2242
+ "Stop the preview owned by this project session.",
2243
+ { projectPath: { type: "string" } }
2244
+ ],
2245
+ [
2246
+ "container_preview_snapshot",
2247
+ "Read a preview state or snapshot endpoint.",
2248
+ {
2249
+ projectPath: { type: "string" },
2250
+ resource: { type: "string" }
2251
+ }
2252
+ ],
2253
+ [
2254
+ "container_test_start",
2255
+ "Run a deterministic scenario against the current preview.",
2256
+ {
2257
+ projectPath: { type: "string" },
2258
+ scenario: { type: "object" }
2259
+ }
2260
+ ],
2261
+ [
2262
+ "container_job_status",
2263
+ "Read a job status.",
2264
+ {
2265
+ projectPath: { type: "string" },
2266
+ jobId: { type: "string" }
2267
+ }
2268
+ ],
2269
+ [
2270
+ "container_job_events",
2271
+ "Read durable job events.",
2272
+ {
2273
+ projectPath: { type: "string" },
2274
+ jobId: { type: "string" }
2275
+ }
2276
+ ],
2277
+ [
2278
+ "container_job_cancel",
2279
+ "Cancel a running agent job.",
2280
+ {
2281
+ projectPath: { type: "string" },
2282
+ jobId: { type: "string" }
2283
+ }
2284
+ ],
2285
+ [
2286
+ "container_test_cancel",
2287
+ "Cancel a running test job.",
2288
+ {
2289
+ projectPath: { type: "string" },
2290
+ jobId: { type: "string" }
2291
+ }
2292
+ ],
2293
+ [
2294
+ "container_release_prepare",
2295
+ "Create a local versioned release artifact.",
2296
+ {
2297
+ projectPath: { type: "string" },
2298
+ version: { type: "string" }
2299
+ }
2300
+ ],
2301
+ [
2302
+ "container_release_commit",
2303
+ "Commit a verified local release after explicit confirmation.",
2304
+ {
2305
+ projectPath: { type: "string" },
2306
+ version: { type: "string" },
2307
+ confirmed: { type: "boolean" }
2308
+ }
2309
+ ],
2310
+ [
2311
+ "container_release_list",
2312
+ "List local releases and current version.",
2313
+ { projectPath: { type: "string" } }
2314
+ ],
2315
+ [
2316
+ "container_release_rollback",
2317
+ "Switch the current local release pointer after explicit confirmation.",
2318
+ {
2319
+ projectPath: { type: "string" },
2320
+ version: { type: "string" },
2321
+ confirmed: { type: "boolean" }
2322
+ }
2323
+ ],
2324
+ [
2325
+ "container_release_publish",
2326
+ "Publish a committed release through the configured mini-program upload provider.",
2327
+ {
2328
+ projectPath: { type: "string" },
2329
+ version: { type: "string" },
2330
+ platform: { type: "string" },
2331
+ description: { type: "string" },
2332
+ privateKeyPath: { type: "string" },
2333
+ wvBin: { type: "string" },
2334
+ timeoutMs: { type: "number" },
2335
+ confirmed: { type: "boolean" }
2336
+ }
2337
+ ]
2338
+ ].map(([name, description, properties]) => ({
2339
+ name,
2340
+ description,
2341
+ inputSchema: {
2342
+ type: "object",
2343
+ properties,
2344
+ additionalProperties: false
2345
+ }
2346
+ }));
2347
+ }
2348
+ async function callTool(name, args = {}) {
2349
+ const root = resolve(args.projectPath ?? process.cwd());
2350
+ if (name === "container_project_init") return initProject(root);
2351
+ if (name === "container_project_inspect") return inspectProject(root);
2352
+ if (name === "container_project_files") return listProjectFiles(root);
2353
+ if (name === "container_project_file_read") return readProjectFile(root, args.path);
2354
+ if (name === "container_project_file_write") return writeProjectFile(root, args.path, args.content);
2355
+ if (name === "container_build") return buildProject(root, args);
2356
+ if (name === "container_preview_start") return new PreviewStore(root).start(args);
2357
+ if (name === "container_preview_status") return new PreviewStore(root).status();
2358
+ if (name === "container_preview_stop") return new PreviewStore(root).stop();
2359
+ if (name === "container_preview_snapshot") return new PreviewStore(root).request(args.resource === "state" ? "/api/state" : "/api/snapshot");
2360
+ const jobs = jobStoreFor(root);
2361
+ if (name === "container_test_start") {
2362
+ const preview = new PreviewStore(root);
2363
+ return jobs.start("test", { scenario: args.scenario ?? {} }, async (job, signal) => {
2364
+ let ownedPreview = false;
2365
+ const before = await preview.status();
2366
+ if (before.status === "closed") {
2367
+ await preview.start({
2368
+ ...args.preview ?? {},
2369
+ signal
2370
+ });
2371
+ ownedPreview = true;
2372
+ }
2373
+ if (before.status === "unknown") throw new AgentError("ERR_PREVIEW_STATE_UNKNOWN", "An existing preview session cannot be authenticated");
2374
+ try {
2375
+ await waitForPreviewReady(preview, args.timeoutMs ?? DEFAULT_TIMEOUT_MS, signal);
2376
+ return await runScenario({
2377
+ request: (path, options) => preview.request(path, {
2378
+ ...options,
2379
+ signal
2380
+ }),
2381
+ status: () => preview.status()
2382
+ }, args.scenario, {
2383
+ signal,
2384
+ projectRoot: root,
2385
+ jobId: job.jobId,
2386
+ artifactRoot: join(root, ".weapp-container", "agent", "artifacts", job.jobId)
2387
+ });
2388
+ } finally {
2389
+ if (ownedPreview) await preview.stop().catch(() => {});
2390
+ }
2391
+ });
2392
+ }
2393
+ if (name === "container_job_status") return jobs.status(args.jobId);
2394
+ if (name === "container_job_events") return jobs.events(args.jobId);
2395
+ if (name === "container_job_cancel" || name === "container_test_cancel") return jobs.cancel(args.jobId);
2396
+ if (name === "container_release_prepare") return prepareRelease(root, args.version, args);
2397
+ if (name === "container_release_commit") return commitRelease(root, args.version, { confirmed: args.confirmed });
2398
+ if (name === "container_release_list") return listReleases(root);
2399
+ if (name === "container_release_rollback") return rollbackRelease(root, args.version, { confirmed: args.confirmed });
2400
+ if (name === "container_release_publish") return jobs.start("release-publish", {
2401
+ version: args.version,
2402
+ platform: args.platform ?? "weapp",
2403
+ description: args.description ?? null
2404
+ }, async (_job, signal) => publishRelease(root, args.version, {
2405
+ ...args,
2406
+ signal
2407
+ }));
2408
+ throw new AgentError("ERR_TOOL_NOT_FOUND", `Unknown tool: ${name}`);
2409
+ }
2410
+ async function serveMcp(projectRoot = process.cwd(), input = process.stdin, output = process.stdout) {
2411
+ const tools = toolCatalog();
2412
+ let buffer = "";
2413
+ for await (const chunk of input) {
2414
+ buffer += chunk.toString();
2415
+ let index;
2416
+ while ((index = buffer.indexOf("\n")) >= 0) {
2417
+ const line = buffer.slice(0, index).trim();
2418
+ buffer = buffer.slice(index + 1);
2419
+ if (!line) continue;
2420
+ let request;
2421
+ try {
2422
+ request = JSON.parse(line);
2423
+ } catch {
2424
+ output.write(`${JSON.stringify({
2425
+ jsonrpc: "2.0",
2426
+ id: null,
2427
+ error: {
2428
+ code: -32700,
2429
+ message: "Parse error"
2430
+ }
2431
+ })}\n`);
2432
+ continue;
2433
+ }
2434
+ if (request.method?.startsWith("notifications/")) continue;
2435
+ if (request.id === void 0) continue;
2436
+ const response = {
2437
+ jsonrpc: "2.0",
2438
+ id: request.id
2439
+ };
2440
+ try {
2441
+ if (request.method === "initialize") response.result = {
2442
+ protocolVersion: request.params?.protocolVersion ?? "2024-11-05",
2443
+ capabilities: { tools: {} },
2444
+ serverInfo: {
2445
+ name: "weapp-container-agent",
2446
+ version: "0.1.0"
2447
+ }
2448
+ };
2449
+ else if (request.method === "tools/list") response.result = { tools };
2450
+ else if (request.method === "tools/call") {
2451
+ const result = await callTool(request.params?.name, {
2452
+ projectPath: projectRoot,
2453
+ ...request.params?.arguments ?? {}
2454
+ });
2455
+ response.result = {
2456
+ content: [{
2457
+ type: "text",
2458
+ text: JSON.stringify(result)
2459
+ }],
2460
+ structuredContent: result
2461
+ };
2462
+ } else throw new AgentError("ERR_METHOD_NOT_FOUND", `Unsupported MCP method: ${request.method}`);
2463
+ } catch (error) {
2464
+ if (request.method === "tools/call") {
2465
+ const errorValue = {
2466
+ code: error?.code ?? "ERR_MCP",
2467
+ message: error?.message ?? String(error)
2468
+ };
2469
+ response.result = {
2470
+ isError: true,
2471
+ content: [{
2472
+ type: "text",
2473
+ text: JSON.stringify(errorValue)
2474
+ }],
2475
+ structuredContent: errorValue
2476
+ };
2477
+ } else response.error = {
2478
+ code: -32e3,
2479
+ message: error?.message ?? String(error),
2480
+ data: { code: error?.code ?? "ERR_MCP" }
2481
+ };
2482
+ }
2483
+ output.write(`${JSON.stringify(response)}\n`);
2484
+ }
2485
+ }
2486
+ }
2487
+ // src/cli.ts
2488
+ function usage() {
2489
+ console.log(`Usage: weapp-container-agent <command> [options]
2490
+
2491
+ Commands:
2492
+ create --project <dir> --name <display-name>
2493
+ init --project <dir>
2494
+ inspect --project <dir>
2495
+ build --project <dir> [--platform weapp|alipay|swan|tt|jd|xhs] [--out <pack-dir>] [--wv-bin <file>]
2496
+ preview start|status|stop --project <dir> [--host-fixtures <file>] [--simulator-bin <file>]
2497
+ test run --project <dir> --scenario <file>
2498
+ release prepare|commit|list|rollback|publish --project <dir> [--version <version>]
2499
+ job status|events|cancel --project <dir> --job <id>
2500
+ mcp --project <dir>
2501
+
2502
+ All commands emit JSON when --json is supplied.`);
2503
+ }
2504
+ function value(args, name, fallback) {
2505
+ const index = args.indexOf(name);
2506
+ if (index < 0) return fallback;
2507
+ const result = args[index + 1];
2508
+ if (!result || result.startsWith("--")) throw new Error(`${name} requires a value`);
2509
+ return result;
2510
+ }
2511
+ function jsonOutput(valueToPrint, json) {
2512
+ process$1.stdout.write(`${json ? JSON.stringify(valueToPrint, null, 2) : JSON.stringify(valueToPrint, null, 2)}\n`);
2513
+ }
2514
+ const args = process$1.argv.slice(2);
2515
+ const json = args.includes("--json");
2516
+ const command = args[0];
2517
+ const project = value(args, "--project", process$1.cwd());
2518
+ try {
2519
+ if (command === "--preview-daemon") {
2520
+ const simulatorPrefix = value(args, "--simulator-prefix", "[]");
2521
+ await runPreviewDaemon({
2522
+ projectRoot: project,
2523
+ token: value(args, "--token", void 0),
2524
+ surface: value(args, "--surface", "web"),
2525
+ engine: value(args, "--engine", "quickjs"),
2526
+ renderer: value(args, "--renderer", "webview"),
2527
+ port: Number(value(args, "--port", "0")),
2528
+ packDirectory: value(args, "--pack", void 0),
2529
+ hostFixtures: value(args, "--host-fixtures", void 0),
2530
+ wvBin: value(args, "--wv-bin", void 0),
2531
+ logPath: value(args, "--log", void 0),
2532
+ errorPath: value(args, "--error", void 0),
2533
+ simulatorCommand: value(args, "--simulator-command", void 0),
2534
+ simulatorPrefix: JSON.parse(simulatorPrefix)
2535
+ });
2536
+ process$1.exitCode = 0;
2537
+ } else if (!command || command === "--help" || command === "-h") {
2538
+ usage();
2539
+ process$1.exit(0);
2540
+ } else if (command === "mcp") await serveMcp(project);
2541
+ if (command === "--preview-daemon" || !command || command === "--help" || command === "-h" || command === "mcp") {} else {
2542
+ let result;
2543
+ if (command === "create") result = await createProject(project, value(args, "--name", void 0));
2544
+ else if (command === "init") result = await initProject(project);
2545
+ else if (command === "inspect") result = await inspectProject(project);
2546
+ else if (command === "build") result = await callTool("container_build", {
2547
+ projectPath: project,
2548
+ platform: value(args, "--platform", "weapp"),
2549
+ wvBin: value(args, "--wv-bin", void 0),
2550
+ out: value(args, "--out", void 0)
2551
+ });
2552
+ else if (command === "preview") {
2553
+ const action = args[1];
2554
+ if (action === "start") result = await callTool("container_preview_start", {
2555
+ projectPath: project,
2556
+ packDirectory: value(args, "--pack", void 0),
2557
+ hostFixtures: value(args, "--host-fixtures", void 0),
2558
+ wvBin: value(args, "--wv-bin", void 0),
2559
+ surface: value(args, "--surface", "web"),
2560
+ renderer: value(args, "--renderer", "webview"),
2561
+ port: Number(value(args, "--port", "0")),
2562
+ timeoutMs: Number(value(args, "--timeout-ms", "120000")),
2563
+ simulatorCommand: value(args, "--simulator-bin", void 0),
2564
+ simulatorPrefix: JSON.parse(value(args, "--simulator-prefix", "[]"))
2565
+ });
2566
+ else if (action === "status") result = await callTool("container_preview_status", { projectPath: project });
2567
+ else if (action === "stop") result = await callTool("container_preview_stop", { projectPath: project });
2568
+ else throw new Error("preview requires start, status or stop");
2569
+ } else if (command === "test") {
2570
+ if (args[1] !== "run") throw new Error("test requires run");
2571
+ result = await callTool("container_test_start", {
2572
+ projectPath: project,
2573
+ scenario: JSON.parse(await (await import("node:fs/promises")).readFile(value(args, "--scenario", void 0), "utf8"))
2574
+ });
2575
+ } else if (command === "release") {
2576
+ const action = args[1];
2577
+ const version = value(args, "--version", void 0);
2578
+ if (action === "prepare") result = await prepareRelease(project, version);
2579
+ else if (action === "commit") result = await commitRelease(project, version, { confirmed: args.includes("--confirm") });
2580
+ else if (action === "list") result = await listReleases(project);
2581
+ else if (action === "rollback") result = await rollbackRelease(project, version, { confirmed: args.includes("--confirm") });
2582
+ else if (action === "publish") result = await publishRelease(project, version, {
2583
+ confirmed: args.includes("--confirm"),
2584
+ platform: value(args, "--platform", "weapp"),
2585
+ description: value(args, "--desc", void 0),
2586
+ privateKeyPath: value(args, "--private-key", void 0),
2587
+ wvBin: value(args, "--wv-bin", void 0),
2588
+ timeoutMs: Number(value(args, "--timeout-ms", "120000"))
2589
+ });
2590
+ else throw new Error("release requires prepare, commit, list, rollback or publish");
2591
+ } else if (command === "job") {
2592
+ const job = value(args, "--job", void 0);
2593
+ const action = args[1];
2594
+ const tool = action === "status" ? "container_job_status" : action === "events" ? "container_job_events" : action === "cancel" ? "container_job_cancel" : void 0;
2595
+ if (!tool) throw new Error("job requires status, events or cancel");
2596
+ result = await callTool(tool, {
2597
+ projectPath: project,
2598
+ jobId: job
2599
+ });
2600
+ } else throw new Error(`Unknown command: ${command}`);
2601
+ jsonOutput(result, json);
2602
+ }
2603
+ } catch (error) {
2604
+ process$1.stderr.write(`${JSON.stringify({
2605
+ error: error.message,
2606
+ code: error.code ?? "ERR_AGENT"
2607
+ })}\n`);
2608
+ process$1.exitCode = error.code === "ERR_CANCELLED" ? 130 : 1;
2609
+ }
2610
+ export {};