openprototype 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/AGENTS.md +58 -0
  2. package/CONVENTIONS.md +54 -0
  3. package/LICENSE +21 -0
  4. package/README.md +233 -2
  5. package/bin/cli.js +297 -0
  6. package/lib/config.js +162 -0
  7. package/package.json +32 -10
  8. package/product/demo/pc/customer/customer_form.html +134 -0
  9. package/product/demo/pc/customer/customer_form.md +33 -0
  10. package/product/demo/pc/customer/customer_list.html +129 -0
  11. package/product/demo/pc/customer/customer_list.md +35 -0
  12. package/product/demo/pc/demo-data.js +23 -0
  13. package/product/demo/pc/index.html +1069 -0
  14. package/product/demo/pc/nav-tree.json +15 -0
  15. package/proto-kit.config.json +13 -0
  16. package/runtime/server.js +664 -0
  17. package/runtime/shared/ai-polish.js +159 -0
  18. package/runtime/shared/base-manager.js +168 -0
  19. package/runtime/shared/common/component-renderer.js +917 -0
  20. package/runtime/shared/common/copy-manager.js +134 -0
  21. package/runtime/shared/common/data-bridge.js +45 -0
  22. package/runtime/shared/common/form-renderer.js +211 -0
  23. package/runtime/shared/common/form.js +357 -0
  24. package/runtime/shared/common/formatter.js +78 -0
  25. package/runtime/shared/common/index.js +37 -0
  26. package/runtime/shared/common/line-chart.js +357 -0
  27. package/runtime/shared/common/modal-manager.js +82 -0
  28. package/runtime/shared/common/prd-panel.js +1014 -0
  29. package/runtime/shared/common/prd-popup.js +168 -0
  30. package/runtime/shared/common/search-renderer.js +95 -0
  31. package/runtime/shared/common/table-renderer.js +177 -0
  32. package/runtime/shared/common/table.js +160 -0
  33. package/runtime/shared/common/toast.js +99 -0
  34. package/runtime/shared/common/ui-preference-manager.js +74 -0
  35. package/runtime/shared/common/view-mode.js +30 -0
  36. package/runtime/shared/common.js +43 -0
  37. package/runtime/shared/constants/icons.js +28 -0
  38. package/runtime/shared/constants/status.js +67 -0
  39. package/runtime/shared/libs/marked.min.js +69 -0
  40. package/runtime/shared/prd-content.js +9 -0
  41. package/runtime/shared/styles.css +7673 -0
  42. package/runtime/shared/utils.js +110 -0
  43. package/runtime/shared/view-controls.js +148 -0
  44. package/runtime/shell/agent-panel.css +429 -0
  45. package/runtime/shell/agent-panel.js +629 -0
  46. package/scripts/check/run-checks.js +58 -0
  47. package/scripts/check/smoke-test.js +244 -0
  48. package/scripts/check/static-check.js +248 -0
  49. package/scripts/check/sync-nav-tree.js +139 -0
  50. package/templates/AGENTS.md +58 -0
  51. package/templates/CONVENTIONS.md +54 -0
  52. package/templates/gitignore +10 -0
  53. package/templates/product-shell/index.html +1069 -0
  54. package/templates/skills/auto-test/SKILL.md +62 -0
  55. package/templates/skills/xiaojia/SKILL.md +299 -0
  56. package/cli.js +0 -4
@@ -0,0 +1,15 @@
1
+ [
2
+ {
3
+ "name": "customer",
4
+ "children": [
5
+ {
6
+ "file": "customer_form.html",
7
+ "path": "customer/customer_form.html"
8
+ },
9
+ {
10
+ "file": "customer_list.html",
11
+ "path": "customer/customer_list.html"
12
+ }
13
+ ]
14
+ }
15
+ ]
@@ -0,0 +1,13 @@
1
+ {
2
+ "port": 8082,
3
+ "opencode": {
4
+ "bin": "auto",
5
+ "model": "deepseek/deepseek-v4-flash",
6
+ "agent": "build",
7
+ "host": "127.0.0.1",
8
+ "port": 4097
9
+ },
10
+ "products": [
11
+ { "id": "demo", "roots": ["pc"] }
12
+ ]
13
+ }
@@ -0,0 +1,664 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * openprototype 本地服务器。
5
+ *
6
+ * 职责:
7
+ * 1. 把项目根目录当静态站点跑(原型页面、nav-tree.json、PRD .md)。
8
+ * 2. 把内置运行时(runtime/)挂在 /_kit/ 下,供各产品壳引用(agent-panel、shared 引擎)。
9
+ * 3. /api/agent/* —— 代理到本机 OpenCode,驱动右侧 Agent 面板。
10
+ * 4. /api/save-prd、/api/build-update-page-prompt、/api/update-page-from-prd。
11
+ *
12
+ * 所有可配置项来自 proto-kit.config.json(见 lib/config.js),此文件不含任何硬编码路径 / 私有信息。
13
+ */
14
+
15
+ const http = require('http');
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const { spawn } = require('child_process');
19
+ const { loadConfig } = require('../lib/config');
20
+
21
+ function resolvePortArg(fallback) {
22
+ const i = process.argv.indexOf('--port');
23
+ if (i !== -1 && process.argv[i + 1]) return Number(process.argv[i + 1]);
24
+ return fallback;
25
+ }
26
+
27
+ function resolveHostArg(fallback) {
28
+ const i = process.argv.indexOf('--host');
29
+ if (i !== -1 && process.argv[i + 1]) return process.argv[i + 1];
30
+ return fallback;
31
+ }
32
+
33
+ let CONFIG = loadConfig();
34
+ // 当前目录没有 proto-kit.config.json 时(例如直接跑本包自带 demo),回退用本包自己的配置
35
+ if (!CONFIG.hasConfigFile) {
36
+ const pkgConfig = loadConfig(__dirname);
37
+ if (pkgConfig.hasConfigFile) CONFIG = pkgConfig;
38
+ }
39
+ const ROOT_DIR = CONFIG.rootDir;
40
+ const KIT_RUNTIME_DIR = __dirname; // 本包 runtime/ 目录(可能位于 node_modules 内)
41
+ const PORT = resolvePortArg(CONFIG.port);
42
+ const HOST = resolveHostArg(CONFIG.host || '127.0.0.1');
43
+ const PRODUCT_ROOT = path.resolve(ROOT_DIR, 'product');
44
+ const AGENT_WRITE_ROOTS = CONFIG.productRoots.map((r) => r.dir); // Agent 只能写这些产品目录
45
+ const IS_WIN = process.platform === 'win32';
46
+
47
+ const OC = CONFIG.opencode;
48
+
49
+ let openCodeProcess = null;
50
+ let openCodeReadyPromise = null;
51
+ let openCodeOwned = false;
52
+ let openCodeStartError = '';
53
+
54
+ const MIME_TYPES = {
55
+ '.html': 'text/html; charset=utf-8',
56
+ '.css': 'text/css; charset=utf-8',
57
+ '.js': 'text/javascript; charset=utf-8',
58
+ '.jsx': 'text/javascript; charset=utf-8',
59
+ '.json': 'application/json; charset=utf-8',
60
+ '.md': 'text/markdown; charset=utf-8',
61
+ '.png': 'image/png',
62
+ '.jpg': 'image/jpeg',
63
+ '.jpeg': 'image/jpeg',
64
+ '.svg': 'image/svg+xml',
65
+ '.ico': 'image/x-icon',
66
+ '.woff': 'font/woff',
67
+ '.woff2': 'font/woff2'
68
+ };
69
+
70
+ function sendJson(res, statusCode, data) {
71
+ res.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8' });
72
+ res.end(JSON.stringify(data));
73
+ }
74
+
75
+ function readJsonBodyAsync(req, maxBytes) {
76
+ return new Promise((resolve, reject) => {
77
+ readJsonBody(req, maxBytes, (err, data) => (err ? reject(err) : resolve(data)));
78
+ });
79
+ }
80
+
81
+ function readJsonBody(req, maxBytes, callback) {
82
+ let body = '';
83
+ req.on('data', (chunk) => {
84
+ body += chunk;
85
+ if (body.length > maxBytes) req.destroy();
86
+ });
87
+ req.on('end', () => {
88
+ try {
89
+ callback(null, JSON.parse(body || '{}'));
90
+ } catch (err) {
91
+ callback(err);
92
+ }
93
+ });
94
+ }
95
+
96
+ function resolveProductPath(inputPath, expectedExt) {
97
+ const targetPath = String(inputPath || '').split('?')[0].split('#')[0];
98
+ if (!targetPath.toLowerCase().endsWith(expectedExt)) {
99
+ throw new Error(`仅允许 ${expectedExt} 文件`);
100
+ }
101
+ const resolved = path.resolve(ROOT_DIR, '.' + targetPath);
102
+ if (resolved !== PRODUCT_ROOT && !resolved.startsWith(PRODUCT_ROOT + path.sep)) {
103
+ throw new Error('路径超出 product/ 允许范围');
104
+ }
105
+ return resolved;
106
+ }
107
+
108
+ /** Agent 只能改注册在配置里的产品入口目录内的文件 */
109
+ function resolveAgentWritablePath(inputPath, expectedExt) {
110
+ const resolved = resolveProductPath(inputPath, expectedExt);
111
+ const ok = AGENT_WRITE_ROOTS.some((root) => resolved === root || resolved.startsWith(root + path.sep));
112
+ if (!ok) throw new Error('Agent 只能操作已注册产品的页面(见 proto-kit.config.json)');
113
+ return resolved;
114
+ }
115
+
116
+ function isLoopbackRequest(req) {
117
+ const remoteAddress = String(req.socket.remoteAddress || '');
118
+ return remoteAddress === '127.0.0.1' || remoteAddress === '::1' || remoteAddress === '::ffff:127.0.0.1';
119
+ }
120
+
121
+ /** 写入 / Agent 类接口一律只接受本机请求,即使服务器用 --host 0.0.0.0 对局域网开放预览 */
122
+ function requireLoopback(req, res) {
123
+ if (isLoopbackRequest(req)) return true;
124
+ sendJson(res, 403, { ok: false, error: '该接口仅允许从本机访问' });
125
+ return false;
126
+ }
127
+
128
+ // ── PRD 保存 ───────────────────────────────────────────
129
+ function handleSavePrd(req, res) {
130
+ readJsonBody(req, 5 * 1024 * 1024, (parseErr, data) => {
131
+ try {
132
+ if (parseErr) throw parseErr;
133
+ const resolved = resolveProductPath(data.path, '.md');
134
+ fs.writeFile(resolved, String(data.content || ''), 'utf8', (err) => {
135
+ if (err) {
136
+ console.log(`[500] POST /api/save-prd -> ${err.message}`);
137
+ return sendJson(res, 500, { ok: false, error: err.message });
138
+ }
139
+ console.log(`[200] POST /api/save-prd -> ${resolved}`);
140
+ sendJson(res, 200, { ok: true });
141
+ });
142
+ } catch (err) {
143
+ console.log(`[400] POST /api/save-prd -> ${err.message}`);
144
+ sendJson(res, 400, { ok: false, error: err.message });
145
+ }
146
+ });
147
+ }
148
+
149
+ // ── PRD 标红提取 ───────────────────────────────────────
150
+ function normalizeRedMarkedContent(text) {
151
+ return String(text || '')
152
+ .replace(/<br\s*\/?>/gi, '\n')
153
+ .replace(/<\/?[^>]+>/g, '')
154
+ .replace(/\s+\n/g, '\n')
155
+ .replace(/\n{3,}/g, '\n\n')
156
+ .trim();
157
+ }
158
+
159
+ function extractRedMarkedSections(markdown) {
160
+ const sections = [];
161
+ const redSpanRegex = /<span\b[^>]*\bstyle\s*=\s*["'][^"']*\bcolor\s*:\s*(?:#e53935|red)\b[^"']*["'][^>]*>([\s\S]*?)<\/span>/gi;
162
+ let match;
163
+ while ((match = redSpanRegex.exec(markdown)) !== null) {
164
+ const content = normalizeRedMarkedContent(match[1]);
165
+ if (content) sections.push(content);
166
+ }
167
+ return sections;
168
+ }
169
+
170
+ function buildRedMarkedSummary(sections) {
171
+ return sections.map((section, index) => `${index + 1}. ${section}`).join('\n\n');
172
+ }
173
+
174
+ function isH5Path(file) {
175
+ return file.includes(`${path.sep}h5${path.sep}`);
176
+ }
177
+
178
+ function surfaceRule(file) {
179
+ return isH5Path(file)
180
+ ? '当前页面为移动端 H5 原型:遵守单列、卡片列表、顶部栏、底部操作栏、安全区与 H5 设计系统;不要套用 PC 三栏表单、TableRenderer、SearchRenderer 或侧边栏菜单规则。'
181
+ : '当前页面为 PC 原型:遵守脚本加载顺序、Renderer 渲染、BaseDataManager、STATUS_LABELS、mode=view 物理隐藏、系统字体栈、表单三栏栅格与查询区按钮聚拢规则。';
182
+ }
183
+
184
+ function buildOpenCodePrompt(htmlFile, prdFile, redMarkedSections) {
185
+ return [
186
+ '请根据 PRD Markdown 中标红的部分更新对应的 HTML/JS 原型页面。',
187
+ '',
188
+ `PRD 文件:${prdFile}`,
189
+ `页面 HTML:${htmlFile}`,
190
+ '',
191
+ '本次只处理以下标红内容:',
192
+ buildRedMarkedSummary(redMarkedSections),
193
+ '',
194
+ '工作要求:',
195
+ '1. 先阅读 AGENTS.md 及 rules/ 下相关规范(项目规则、UI 组件、业务逻辑、bug 预防),以及所属产品的 shared/templates 资产。',
196
+ '2. 只识别这份 MD 里 <span style="color:red">...</span> 或 <span style="color:#e53935">...</span> 标红的内容;不要用 git diff 作为更新范围。',
197
+ '3. 只根据标红内容涉及的字段、规则、按钮、文案或数据变化更新对应 HTML/JS/mock/constants;未标红的历史内容一律视为背景,不得据此重写或"优化"页面。',
198
+ '4. 不要修改 PRD 文件本身,不要改 PRD 版本号;不要动与本次标红无关的区域、字段、样式、mock 或交互。',
199
+ surfaceRule(htmlFile),
200
+ '5. 改完后运行 npm run check:changed,修复 ERROR 后再结束。',
201
+ '6. 不要新建后端代码、数据库 schema 或 contracts/data-model 层;不要改无关文件。'
202
+ ].join('\n');
203
+ }
204
+
205
+ function buildAgentSystemPrompt(htmlFile, prdFile) {
206
+ return [
207
+ '你是原型工作台的 AI 协作 Agent,帮用户把 PRD 与 HTML/JS 原型保持一致。',
208
+ `当前页面:${htmlFile}`,
209
+ `当前 PRD:${prdFile || '未识别'}`,
210
+ surfaceRule(htmlFile),
211
+ '',
212
+ '执行规则:',
213
+ '1. 每次先阅读 AGENTS.md,以及任务涉及的 rules 与所属产品的 shared/templates/references 资产。',
214
+ '2. 用户未点名其他范围时,只处理当前页面、当前 PRD 及其直接关联的 JS、mock、constants。',
215
+ '3. 页面、PRD 与 mock 数据必须最终一致;允许按用户指令修改 PRD,但不得填写、修改或推断 PRD 版本号。',
216
+ '4. 不得新增后端业务代码、数据库 schema、contracts 或 data-model 层,不得改无关文件。',
217
+ '5. 修改 HTML/JS 原型后运行 npm run check:changed,修复全部 ERROR 后再结束。',
218
+ '6. 用中文简洁回复结果、修改文件和验证结论。'
219
+ ].join('\n');
220
+ }
221
+
222
+ // ── OpenCode 交互 ──────────────────────────────────────
223
+ function getOpenCodeModel() {
224
+ const parts = OC.model.split('/');
225
+ return { providerID: parts.shift(), modelID: parts.join('/') };
226
+ }
227
+
228
+ function getOpenCodeUrl(apiPath, includeDirectory) {
229
+ const url = new URL(apiPath, OC.baseUrl);
230
+ if (includeDirectory !== false) url.searchParams.set('directory', ROOT_DIR);
231
+ return url;
232
+ }
233
+
234
+ function requestOpenCode(method, apiPath, body, options) {
235
+ const requestOptions = options || {};
236
+ const url = getOpenCodeUrl(apiPath, requestOptions.includeDirectory);
237
+ const payload = body === undefined || body === null ? '' : JSON.stringify(body);
238
+
239
+ return new Promise((resolve, reject) => {
240
+ const request = http.request({
241
+ hostname: url.hostname,
242
+ port: url.port,
243
+ path: url.pathname + url.search,
244
+ method,
245
+ headers: {
246
+ Accept: 'application/json',
247
+ ...(payload ? {
248
+ 'Content-Type': 'application/json; charset=utf-8',
249
+ 'Content-Length': Buffer.byteLength(payload)
250
+ } : {})
251
+ },
252
+ timeout: requestOptions.timeout || 10000
253
+ }, (response) => {
254
+ let responseBody = '';
255
+ response.setEncoding('utf8');
256
+ response.on('data', (chunk) => { responseBody += chunk; });
257
+ response.on('end', () => {
258
+ let data = null;
259
+ if (responseBody) {
260
+ try { data = JSON.parse(responseBody); } catch (err) { data = responseBody; }
261
+ }
262
+ if (response.statusCode >= 200 && response.statusCode < 300) return resolve(data);
263
+ const message = data && data.error ? data.error : `OpenCode 请求失败: ${response.statusCode}`;
264
+ reject(new Error(message));
265
+ });
266
+ });
267
+ request.on('timeout', () => request.destroy(new Error('OpenCode 请求超时')));
268
+ request.on('error', reject);
269
+ if (payload) request.write(payload);
270
+ request.end();
271
+ });
272
+ }
273
+
274
+ async function waitForOpenCode() {
275
+ const startedAt = Date.now();
276
+ while (Date.now() - startedAt < OC.startTimeoutMs) {
277
+ try {
278
+ return await requestOpenCode('GET', '/global/health', null, { includeDirectory: false, timeout: 800 });
279
+ } catch (err) {
280
+ await new Promise((resolve) => setTimeout(resolve, 250));
281
+ }
282
+ }
283
+ throw new Error(openCodeStartError || 'OpenCode 服务启动超时');
284
+ }
285
+
286
+ async function startOrReuseOpenCode() {
287
+ try {
288
+ return await requestOpenCode('GET', '/global/health', null, { includeDirectory: false, timeout: 800 });
289
+ } catch (err) {
290
+ openCodeStartError = '';
291
+ }
292
+
293
+ if (!OC.bin) {
294
+ throw new Error('未找到 opencode 可执行文件。请先安装 OpenCode 并在 proto-kit.config.json 的 opencode.bin 指定路径,或运行 npx openprototype doctor 查看安装引导。');
295
+ }
296
+
297
+ openCodeProcess = spawn(OC.bin, ['serve', '--hostname', OC.host, '--port', String(OC.port)], {
298
+ cwd: ROOT_DIR,
299
+ stdio: ['ignore', 'pipe', 'pipe'],
300
+ shell: IS_WIN // Windows 上 opencode 常是 .cmd,需要 shell
301
+ });
302
+ openCodeOwned = true;
303
+ openCodeProcess.stdout.on('data', () => {});
304
+ openCodeProcess.stderr.on('data', (chunk) => {
305
+ openCodeStartError = String(chunk || '').trim() || openCodeStartError;
306
+ });
307
+ openCodeProcess.on('exit', () => {
308
+ openCodeProcess = null;
309
+ openCodeOwned = false;
310
+ openCodeReadyPromise = null;
311
+ });
312
+ openCodeProcess.on('error', (err) => { openCodeStartError = err.message; });
313
+
314
+ return waitForOpenCode();
315
+ }
316
+
317
+ function ensureOpenCode() {
318
+ if (!openCodeReadyPromise) {
319
+ openCodeReadyPromise = startOrReuseOpenCode().catch((err) => {
320
+ openCodeReadyPromise = null;
321
+ throw err;
322
+ });
323
+ }
324
+ return openCodeReadyPromise;
325
+ }
326
+
327
+ async function createOpenCodeSession(title) {
328
+ const model = getOpenCodeModel();
329
+ return requestOpenCode('POST', '/session', {
330
+ title: title || '原型 Agent',
331
+ agent: OC.agent,
332
+ model: { id: model.modelID, providerID: model.providerID },
333
+ metadata: { source: 'openprototype' }
334
+ });
335
+ }
336
+
337
+ async function sendOpenCodeMessage(sessionID, text, systemPrompt) {
338
+ const model = getOpenCodeModel();
339
+ await requestOpenCode('POST', `/session/${sessionID}/prompt_async`, {
340
+ agent: OC.agent,
341
+ model: { providerID: model.providerID, modelID: model.modelID },
342
+ system: systemPrompt,
343
+ parts: [{ type: 'text', text }]
344
+ });
345
+ }
346
+
347
+ function handleUpdatePageFromPrd(req, res) {
348
+ readJsonBody(req, 2 * 1024 * 1024, async (parseErr, data) => {
349
+ try {
350
+ if (parseErr) throw parseErr;
351
+ const htmlFile = resolveProductPath(data.htmlPath, '.html');
352
+ const prdFile = resolveProductPath(data.prdPath, '.md');
353
+ const prdContent = fs.readFileSync(prdFile, 'utf8');
354
+ const redMarkedSections = extractRedMarkedSections(prdContent);
355
+ if (!redMarkedSections.length) {
356
+ console.log(`[200] POST /api/update-page-from-prd -> no red marks: ${prdFile}`);
357
+ return sendJson(res, 200, { ok: false, code: 'NO_PRD_RED_MARKS', error: 'MD 文件没有标红内容,无需更新' });
358
+ }
359
+ const prompt = String(data.prompt || '').trim() || buildOpenCodePrompt(htmlFile, prdFile, redMarkedSections);
360
+ await ensureOpenCode();
361
+ const session = await createOpenCodeSession(`根据PRD更新 ${path.basename(htmlFile)}`);
362
+ await sendOpenCodeMessage(session.id, prompt, buildAgentSystemPrompt(htmlFile, prdFile));
363
+ console.log(`[202] POST /api/update-page-from-prd -> session ${session.id}`);
364
+ sendJson(res, 202, { ok: true, mode: 'agent', sessionId: session.id });
365
+ } catch (err) {
366
+ console.log(`[400] POST /api/update-page-from-prd -> ${err.message}`);
367
+ sendJson(res, 400, { ok: false, error: err.message });
368
+ }
369
+ });
370
+ }
371
+
372
+ function handleBuildUpdatePagePrompt(req, res) {
373
+ readJsonBody(req, 32 * 1024, (parseErr, data) => {
374
+ try {
375
+ if (parseErr) throw parseErr;
376
+ const htmlFile = resolveProductPath(data.htmlPath, '.html');
377
+ const prdFile = resolveProductPath(data.prdPath, '.md');
378
+ const prdContent = fs.readFileSync(prdFile, 'utf8');
379
+ const redMarkedSections = extractRedMarkedSections(prdContent);
380
+ if (!redMarkedSections.length) {
381
+ console.log(`[200] POST /api/build-update-page-prompt -> no red marks: ${prdFile}`);
382
+ return sendJson(res, 200, { ok: false, code: 'NO_PRD_RED_MARKS', error: 'MD 文件没有标红内容,无需更新' });
383
+ }
384
+ const prompt = buildOpenCodePrompt(htmlFile, prdFile, redMarkedSections);
385
+ console.log(`[200] POST /api/build-update-page-prompt -> ${prdFile}`);
386
+ sendJson(res, 200, { ok: true, prompt });
387
+ } catch (err) {
388
+ console.log(`[400] POST /api/build-update-page-prompt -> ${err.message}`);
389
+ sendJson(res, 400, { ok: false, error: err.message });
390
+ }
391
+ });
392
+ }
393
+
394
+ // ── SSE 事件代理 ───────────────────────────────────────
395
+ function eventMatchesSession(event, sessionID) {
396
+ return JSON.stringify(event || {}).includes(`"sessionID":"${sessionID}"`);
397
+ }
398
+
399
+ async function proxyOpenCodeEvents(req, res, sessionID) {
400
+ await ensureOpenCode();
401
+ const url = getOpenCodeUrl('/event');
402
+ const upstream = http.request({
403
+ hostname: url.hostname,
404
+ port: url.port,
405
+ path: url.pathname + url.search,
406
+ method: 'GET',
407
+ headers: { Accept: 'text/event-stream' }
408
+ }, (upstreamResponse) => {
409
+ if (upstreamResponse.statusCode !== 200) {
410
+ sendJson(res, 502, { ok: false, error: 'OpenCode 事件流连接失败' });
411
+ upstreamResponse.resume();
412
+ return;
413
+ }
414
+ res.writeHead(200, {
415
+ 'Content-Type': 'text/event-stream; charset=utf-8',
416
+ 'Cache-Control': 'no-cache, no-transform',
417
+ Connection: 'keep-alive'
418
+ });
419
+ res.write(`data: ${JSON.stringify({ type: 'proxy.ready', properties: { sessionID } })}\n\n`);
420
+
421
+ let buffer = '';
422
+ upstreamResponse.setEncoding('utf8');
423
+ upstreamResponse.on('data', (chunk) => {
424
+ buffer += chunk;
425
+ const blocks = buffer.split(/\r?\n\r?\n/);
426
+ buffer = blocks.pop() || '';
427
+ blocks.forEach((block) => {
428
+ const dataLines = block.split(/\r?\n/)
429
+ .filter((line) => line.startsWith('data:'))
430
+ .map((line) => line.slice(5).trim());
431
+ if (!dataLines.length) return;
432
+ try {
433
+ const event = JSON.parse(dataLines.join('\n'));
434
+ if (eventMatchesSession(event, sessionID)) res.write(`data: ${JSON.stringify(event)}\n\n`);
435
+ } catch (err) {
436
+ // 忽略坏事件,保持连接
437
+ }
438
+ });
439
+ });
440
+ upstreamResponse.on('end', () => res.end());
441
+ req.on('close', () => upstreamResponse.destroy());
442
+ });
443
+ upstream.on('error', (err) => {
444
+ if (!res.headersSent) sendJson(res, 502, { ok: false, error: err.message });
445
+ else {
446
+ res.write(`data: ${JSON.stringify({ type: 'proxy.error', properties: { message: err.message } })}\n\n`);
447
+ res.end();
448
+ }
449
+ });
450
+ upstream.end();
451
+ }
452
+
453
+ async function handleAgentApi(req, res, urlPath) {
454
+ if (!urlPath.startsWith('/api/agent/')) return false;
455
+ if (!requireLoopback(req, res)) return true;
456
+
457
+ try {
458
+ if (req.method === 'GET' && urlPath === '/api/agent/status') {
459
+ const health = await ensureOpenCode();
460
+ sendJson(res, 200, {
461
+ ok: true,
462
+ healthy: !!(health && health.healthy),
463
+ version: health && health.version,
464
+ agent: OC.agent,
465
+ model: OC.model
466
+ });
467
+ return true;
468
+ }
469
+
470
+ if (req.method === 'POST' && urlPath === '/api/agent/sessions') {
471
+ const data = await readJsonBodyAsync(req, 32 * 1024);
472
+ await ensureOpenCode();
473
+ const session = await createOpenCodeSession(String(data.title || '').trim());
474
+ sendJson(res, 201, { ok: true, session });
475
+ return true;
476
+ }
477
+
478
+ let match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/events$/);
479
+ if (req.method === 'GET' && match) {
480
+ await proxyOpenCodeEvents(req, res, match[1]);
481
+ return true;
482
+ }
483
+
484
+ match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/messages$/);
485
+ if (match && req.method === 'GET') {
486
+ await ensureOpenCode();
487
+ const messages = await requestOpenCode('GET', `/session/${match[1]}/message`);
488
+ sendJson(res, 200, { ok: true, messages: messages || [] });
489
+ return true;
490
+ }
491
+ if (match && req.method === 'POST') {
492
+ const data = await readJsonBodyAsync(req, 2 * 1024 * 1024);
493
+ const message = String(data.message || '').trim();
494
+ if (!message) throw new Error('消息不能为空');
495
+ const htmlFile = resolveAgentWritablePath(data.htmlPath, '.html');
496
+ const prdFile = data.prdPath ? resolveAgentWritablePath(data.prdPath, '.md') : '';
497
+ await ensureOpenCode();
498
+ await sendOpenCodeMessage(match[1], message, buildAgentSystemPrompt(htmlFile, prdFile));
499
+ sendJson(res, 202, { ok: true });
500
+ return true;
501
+ }
502
+
503
+ match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/status$/);
504
+ if (req.method === 'GET' && match) {
505
+ await ensureOpenCode();
506
+ const statuses = await requestOpenCode('GET', '/session/status');
507
+ sendJson(res, 200, { ok: true, status: statuses && statuses[match[1]] ? statuses[match[1]] : { type: 'idle' } });
508
+ return true;
509
+ }
510
+ match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/abort$/);
511
+ if (req.method === 'POST' && match) {
512
+ await ensureOpenCode();
513
+ await requestOpenCode('POST', `/session/${match[1]}/abort`, {});
514
+ sendJson(res, 200, { ok: true });
515
+ return true;
516
+ }
517
+
518
+ match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/diff$/);
519
+ if (req.method === 'GET' && match) {
520
+ await ensureOpenCode();
521
+ const diff = await requestOpenCode('GET', `/session/${match[1]}/diff`);
522
+ sendJson(res, 200, { ok: true, diff: diff || [] });
523
+ return true;
524
+ }
525
+
526
+ match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/pending$/);
527
+ if (req.method === 'GET' && match) {
528
+ await ensureOpenCode();
529
+ const [permissions, questions] = await Promise.all([
530
+ requestOpenCode('GET', '/permission'),
531
+ requestOpenCode('GET', '/question')
532
+ ]);
533
+ sendJson(res, 200, {
534
+ ok: true,
535
+ permissions: (permissions || []).filter((item) => eventMatchesSession(item, match[1])),
536
+ questions: (questions || []).filter((item) => eventMatchesSession(item, match[1]))
537
+ });
538
+ return true;
539
+ }
540
+
541
+ match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/permissions\/(per_[A-Za-z0-9]+)$/);
542
+ if (req.method === 'POST' && match) {
543
+ const data = await readJsonBodyAsync(req, 32 * 1024);
544
+ if (!['once', 'always', 'reject'].includes(data.reply)) throw new Error('无效的权限回复');
545
+ await ensureOpenCode();
546
+ await requestOpenCode('POST', `/permission/${match[2]}/reply`, { reply: data.reply, message: String(data.message || '') });
547
+ sendJson(res, 200, { ok: true });
548
+ return true;
549
+ }
550
+
551
+ match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/questions\/(que_[A-Za-z0-9]+)$/);
552
+ if (req.method === 'POST' && match) {
553
+ const data = await readJsonBodyAsync(req, 64 * 1024);
554
+ if (!Array.isArray(data.answers)) throw new Error('问题答案格式无效');
555
+ await ensureOpenCode();
556
+ await requestOpenCode('POST', `/question/${match[2]}/reply`, { answers: data.answers });
557
+ sendJson(res, 200, { ok: true });
558
+ return true;
559
+ }
560
+
561
+ sendJson(res, 404, { ok: false, error: 'Agent API 不存在' });
562
+ return true;
563
+ } catch (err) {
564
+ console.log(`[500] ${req.method} ${urlPath} -> ${err.message}`);
565
+ sendJson(res, 500, { ok: false, error: err.message });
566
+ return true;
567
+ }
568
+ }
569
+
570
+ // ── 静态文件 ───────────────────────────────────────────
571
+ function serveStatic(req, res, baseDir, relPath) {
572
+ const safeRel = path.normalize(relPath).replace(/^(\.\.[/\\])+/, '');
573
+ // 点开头的路径段(.git / .env / .claude …)不对外提供,避免 --host 0.0.0.0 演示时泄露
574
+ if (safeRel.split(/[/\\]/).some((seg) => seg.length > 1 && seg.startsWith('.'))) {
575
+ console.log(`[403] ${req.url} -> dotfile`);
576
+ res.writeHead(403);
577
+ return res.end('Forbidden');
578
+ }
579
+ const filePath = path.join(baseDir, safeRel === '' || safeRel === '.' ? 'index.html' : safeRel);
580
+ if (!filePath.startsWith(baseDir)) {
581
+ res.writeHead(403);
582
+ return res.end('Forbidden');
583
+ }
584
+ const ext = path.extname(filePath).toLowerCase();
585
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
586
+ fs.readFile(filePath, (err, content) => {
587
+ if (err) {
588
+ if (err.code === 'ENOENT' || err.code === 'EISDIR') {
589
+ console.log(`[404] ${req.url} -> Not Found`);
590
+ res.writeHead(404);
591
+ res.end('File Not Found');
592
+ } else {
593
+ console.log(`[500] ${req.url} -> ${err.code}`);
594
+ res.writeHead(500);
595
+ res.end(`Server Error: ${err.code}`);
596
+ }
597
+ return;
598
+ }
599
+ console.log(`[200] ${req.url}`);
600
+ res.writeHead(200, { 'Content-Type': contentType });
601
+ res.end(content, 'utf-8');
602
+ });
603
+ }
604
+
605
+ const server = http.createServer(async (req, res) => {
606
+ let urlPath;
607
+ try {
608
+ urlPath = decodeURIComponent(req.url.split('?')[0]);
609
+ } catch (err) {
610
+ console.log(`[400] ${req.url} -> URI malformed`);
611
+ res.writeHead(400);
612
+ return res.end('Bad Request');
613
+ }
614
+
615
+ if (await handleAgentApi(req, res, urlPath)) return;
616
+
617
+ if (req.method === 'POST' && urlPath === '/api/save-prd') return requireLoopback(req, res) && handleSavePrd(req, res);
618
+ if (req.method === 'POST' && urlPath === '/api/build-update-page-prompt') return requireLoopback(req, res) && handleBuildUpdatePagePrompt(req, res);
619
+ if (req.method === 'POST' && urlPath === '/api/update-page-from-prd') return requireLoopback(req, res) && handleUpdatePageFromPrd(req, res);
620
+
621
+ // 内置运行时挂在 /_kit/ 下(agent 面板、shared 引擎),随包升级
622
+ if (urlPath.startsWith('/_kit/')) {
623
+ return serveStatic(req, res, KIT_RUNTIME_DIR, urlPath.slice('/_kit/'.length));
624
+ }
625
+
626
+ // 产品引擎回退:product/<id>/shared/** 在项目里不存在时,回退到内置引擎(等价 /_kit/shared/**)。
627
+ // 存量页面用相对路径引用 ../shared/xxx.js 时无需改动即可吃到框架引擎;本地同名文件优先。
628
+ // constants/ 与 components/ 是产品业务资产,缺失就该 404 暴露问题,绝不回退到框架通用版
629
+ //(否则产品状态文案会被静默换成内置 demo 值)。
630
+ const sharedFallback = urlPath.match(/^\/product\/[^/]+\/shared\/(.+)$/);
631
+ if (
632
+ sharedFallback &&
633
+ !/^(constants|components)\//.test(sharedFallback[1]) &&
634
+ !fs.existsSync(path.join(ROOT_DIR, '.' + urlPath))
635
+ ) {
636
+ return serveStatic(req, res, path.join(KIT_RUNTIME_DIR, 'shared'), sharedFallback[1]);
637
+ }
638
+
639
+ serveStatic(req, res, ROOT_DIR, urlPath.replace(/^\//, ''));
640
+ });
641
+
642
+ server.on('error', (err) => {
643
+ if (err.code === 'EADDRINUSE') console.error(`端口 ${PORT} 已被占用,请先关闭相关进程或改 proto-kit.config.json 的 port。`);
644
+ else console.error('服务器错误:', err);
645
+ process.exit(1);
646
+ });
647
+
648
+ server.listen(PORT, HOST, () => {
649
+ console.log('====================================');
650
+ console.log('openprototype 服务器已启动');
651
+ console.log(`地址: http://127.0.0.1:${PORT}`);
652
+ console.log(`监听: ${HOST}${HOST === '127.0.0.1' ? '(仅本机;局域网演示用 --host 0.0.0.0)' : '(局域网可访问预览;/api/* 写入与 Agent 接口仍仅限本机)'}`);
653
+ console.log(`项目根: ${ROOT_DIR}`);
654
+ console.log(`OpenCode: ${OC.bin || '未检测到(Agent 面板需要它,运行 doctor 查看安装引导)'}`);
655
+ console.log('====================================');
656
+ });
657
+
658
+ function stopOwnedOpenCode() {
659
+ if (openCodeOwned && openCodeProcess && !openCodeProcess.killed) openCodeProcess.kill('SIGTERM');
660
+ }
661
+ process.on('SIGINT', () => { stopOwnedOpenCode(); process.exit(0); });
662
+ process.on('SIGTERM', () => { stopOwnedOpenCode(); process.exit(0); });
663
+
664
+ module.exports = { server };