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