fde-console 0.0.0-stage → 2.9.68

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 (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -2
  3. package/README.zh-CN.md +130 -0
  4. package/assets/icon.svg +9 -0
  5. package/cordis.patch.yml +7 -0
  6. package/lib/agentActivity.js +1180 -0
  7. package/lib/agentContext.js +146 -0
  8. package/lib/agentTranscript.js +1398 -0
  9. package/lib/analyze.js +625 -0
  10. package/lib/attribute.js +205 -0
  11. package/lib/backup.js +366 -0
  12. package/lib/desktopAgents.js +123 -0
  13. package/lib/diary.js +333 -0
  14. package/lib/dingtalk.js +412 -0
  15. package/lib/feishu.js +580 -0
  16. package/lib/giteaClient.js +810 -0
  17. package/lib/giteeClient.js +372 -0
  18. package/lib/githubClient.js +361 -0
  19. package/lib/heatmap.js +99 -0
  20. package/lib/imNotify.js +378 -0
  21. package/lib/inbox.js +438 -0
  22. package/lib/instanceLock.js +122 -0
  23. package/lib/jobs.js +56 -0
  24. package/lib/learn.js +1388 -0
  25. package/lib/learnImport.js +283 -0
  26. package/lib/learnSeeds.js +97 -0
  27. package/lib/learnSeedsAiEng.js +77 -0
  28. package/lib/mcpCore.js +135 -0
  29. package/lib/members.js +160 -0
  30. package/lib/migration.js +403 -0
  31. package/lib/overview.js +376 -0
  32. package/lib/postmortem.js +148 -0
  33. package/lib/radarIgnore.js +134 -0
  34. package/lib/redact.js +76 -0
  35. package/lib/router.js +246 -0
  36. package/lib/routes-gitea.js +262 -0
  37. package/lib/routes-setup.js +40 -0
  38. package/lib/scorecard.js +111 -0
  39. package/lib/sessionRef.js +227 -0
  40. package/lib/sessionSnapshot.js +67 -0
  41. package/lib/sessionSuggest.js +186 -0
  42. package/lib/settings.js +783 -0
  43. package/lib/setupCheck.js +330 -0
  44. package/lib/ssrfGuard.js +145 -0
  45. package/lib/store.js +564 -0
  46. package/lib/storeDb.js +418 -0
  47. package/lib/taskEvents.js +243 -0
  48. package/lib/webhookOut.js +125 -0
  49. package/lib/weekly.js +439 -0
  50. package/lib/workSearch.js +220 -0
  51. package/locale/en.json +6 -0
  52. package/locale/zh.json +6 -0
  53. package/package.json +46 -4
  54. package/plugin/adapter.js +157 -0
  55. package/plugin/client.js +282 -0
  56. package/plugin/index.mjs +116 -0
  57. package/plugin/static.js +99 -0
  58. package/scripts/backup-data.js +41 -0
  59. package/scripts/mcp-server.mjs +68 -0
  60. package/scripts/migrate-data.js +301 -0
  61. package/scripts/migrate-storage.js +47 -0
  62. package/scripts/seed-demo.js +200 -0
  63. package/scripts/write-agent-context.js +43 -0
  64. package/test/helpers/appAssembler.js +1078 -0
  65. package/web/client/fde-client.js +292 -0
  66. package/web/css/app.css +1510 -0
  67. package/web/index.html +69 -0
  68. package/web/js/api.js +72 -0
  69. package/web/js/app.js +313 -0
  70. package/web/js/icons.js +48 -0
  71. package/web/js/mock.js +1150 -0
  72. package/web/js/state.js +7 -0
  73. package/web/js/ui.js +276 -0
  74. package/web/js/views/activity.js +410 -0
  75. package/web/js/views/agents.js +892 -0
  76. package/web/js/views/board.js +1656 -0
  77. package/web/js/views/learn.js +530 -0
  78. package/web/js/views/members.js +344 -0
  79. package/web/js/views/onboarding.js +103 -0
  80. package/web/js/views/overview.js +508 -0
  81. package/web/js/views/radar.js +1359 -0
  82. package/web/js/views/search.js +149 -0
  83. package/web/js/views/settings.js +1351 -0
  84. package/web/js/views/topology.js +471 -0
  85. package/web/mock.json +2363 -0
@@ -0,0 +1,220 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * workSearch.js — v2.9.23 工作搜索(考古层):跨任务/会话/提交/日报的统一只读检索
5
+ *
6
+ * 定位:把观测层的「看见」升级成「找到」——程序员工作台的找回入口(Ctrl+K)。
7
+ * 数据面=全部既有数据的读时聚合,零新存储、零写盘、零出网:
8
+ * ① tasks.json 标题+描述+成果提交说明(artifacts.title/messageBody)
9
+ * ② 六源会话标题 listAgentSessions 聚合(60s TTL 索引;标题即首问/首条文本,4/6 源原生;
10
+ * zcode 为客户端会话题名)——不做全文转录提取(每会话 ≤4MB 读入,搜索场景不经济)
11
+ * ③ activities.json 统一动态流的 commit/pr(title+messageBody+repo,≤500 条滚动窗)
12
+ * ④ diary.json 日报全文(≤2000 字/篇)
13
+ * 匹配口径:查询按空白拆词(≤6 词),全部词项出现在该条目的字段拼接文本中才算命中
14
+ * (AND across terms / OR across fields);大小写不敏感;摘要=首个命中字段词项首现 ± 窗口。
15
+ * 脱敏:全部出口文本过 redact(会话标题在 listAgentSessions 内已过,其余在此补)。
16
+ * 红线:单源/单文件故障该组空返不拖垮整体;响应只增不改(新端点)。
17
+ */
18
+
19
+ const path = require('node:path');
20
+ const { HttpError, sendJSON } = require('./router');
21
+ const store = require('./store');
22
+ const redactMod = require('./redact');
23
+ const diaryMod = require('./diary');
24
+ const at = require('./agentTranscript');
25
+
26
+ const PROJECT_ROOT = path.resolve(__dirname, '..');
27
+
28
+ const MAX_TERMS = 6; // 查询最多取前 6 个词项(防病态长查询)
29
+ const MAX_PER_GROUP = 8;
30
+ const SESSION_INDEX_TTL_MS = 60 * 1000;
31
+ const SESSION_INDEX_LIMIT = 50; // 每源最近 50 条(sessionList.maxLimit 上限,单次调用不翻页)
32
+ const SNIPPET_BEFORE = 40;
33
+ const SNIPPET_AFTER = 90;
34
+
35
+ /** 会话标题索引(进程内 TTL 缓存;重建=六源 listAgentSessions,源失败该源跳过) */
36
+ let sessionIndex = { at: 0, items: [] };
37
+
38
+ function redactText(t) {
39
+ try {
40
+ return redactMod.redact(t);
41
+ } catch (e) {
42
+ return String(t);
43
+ }
44
+ }
45
+
46
+ function parseTerms(q) {
47
+ return String(q || '').trim().split(/\s+/).filter(Boolean).slice(0, MAX_TERMS);
48
+ }
49
+
50
+ /** 命中判定:全部词项出现在字段拼接的小写文本里(AND across terms / OR across fields) */
51
+ function fieldsHit(fields, lowerTerms) {
52
+ const hay = fields.map((f) => String(f || '').toLowerCase()).join('\n');
53
+ return lowerTerms.every((t) => hay.includes(t));
54
+ }
55
+
56
+ /** 摘要:首个命中字段取词项首现位置 ± 窗口;压平空白;无命中兜底首字段截断 */
57
+ function snippetOf(fields, lowerTerms) {
58
+ for (const raw of fields) {
59
+ if (!raw) continue;
60
+ const s = String(raw);
61
+ const low = s.toLowerCase();
62
+ let idx = -1;
63
+ for (const t of lowerTerms) {
64
+ const i = low.indexOf(t);
65
+ if (i >= 0 && (idx < 0 || i < idx)) idx = i;
66
+ }
67
+ if (idx >= 0) {
68
+ const start = Math.max(0, idx - SNIPPET_BEFORE);
69
+ const end = Math.min(s.length, idx + SNIPPET_AFTER);
70
+ return (start > 0 ? '…' : '') + s.slice(start, end).replace(/\s+/g, ' ').trim() + (end < s.length ? '…' : '');
71
+ }
72
+ }
73
+ return String(fields.find(Boolean) || '').slice(0, 80);
74
+ }
75
+
76
+ function buildSessionIndex(config, now, fresh) {
77
+ if (!fresh && now - sessionIndex.at < SESSION_INDEX_TTL_MS) return sessionIndex.items;
78
+ const items = [];
79
+ for (const agent of at.SOURCE_IDS) {
80
+ try {
81
+ const page = at.listAgentSessions(config, { agent, limit: SESSION_INDEX_LIMIT });
82
+ for (const it of page.items || []) {
83
+ items.push({
84
+ agent,
85
+ ref: it.ref,
86
+ title: it.title,
87
+ projectId: it.projectId,
88
+ lastActiveAt: it.lastActiveAt,
89
+ });
90
+ }
91
+ } catch (e) { /* 单源故障隔离:该源跳过(HttpError 也在内——索引场景没有可上报语义) */ }
92
+ }
93
+ sessionIndex = { at: now, items };
94
+ return items;
95
+ }
96
+
97
+ /** 相对 dataDir 以项目根兜底(与 lib/attribute.js dataPath 同口径;只拼路径不建目录) */
98
+ function dataPath(cfg, name) {
99
+ const dir = path.isAbsolute(cfg.dataDir) ? cfg.dataDir : path.join(PROJECT_ROOT, cfg.dataDir);
100
+ return path.join(dir, name);
101
+ }
102
+
103
+ /**
104
+ * workSearch(config, q, opts) → { q, tookMs, total, groups:{tasks,sessions,commits,diaries} }
105
+ * 四组各截 MAX_PER_GROUP 条;组序固定=任务/会话/提交/日报。组内按各自时间倒序。
106
+ * @param {{freshIndex?:boolean, now?:number}} opts freshIndex=跳过会话索引 TTL(测试用)
107
+ */
108
+ function workSearch(config, q, opts) {
109
+ const o = opts || {};
110
+ const started = Date.now();
111
+ const terms = parseTerms(q);
112
+ if (!terms.length) throw new HttpError(400, 'FIELD_INVALID', '搜索词不能为空');
113
+ const lowerTerms = terms.map((t) => t.toLowerCase());
114
+ const now = Number.isFinite(o.now) ? o.now : Date.now();
115
+
116
+ // ① 任务(标题+描述+成果说明;时间倒序)
117
+ const tasks = [];
118
+ try {
119
+ const data = store.loadTasks({ tasksPath: dataPath(config, 'tasks.json') });
120
+ for (const t of Array.isArray(data.tasks) ? data.tasks : []) {
121
+ if (!t || typeof t.id !== 'string') continue;
122
+ const arts = Array.isArray(t.artifacts) ? t.artifacts : [];
123
+ const artText = arts
124
+ .map((a) => [a && a.title, a && a.messageBody].filter(Boolean).join(' '))
125
+ .join(' ');
126
+ const fields = [t.title, t.desc, artText];
127
+ if (!fieldsHit(fields, lowerTerms)) continue;
128
+ tasks.push({
129
+ id: t.id,
130
+ title: redactText(String(t.title || '')),
131
+ status: typeof t.status === 'string' ? t.status : '',
132
+ snippet: redactText(snippetOf(fields, lowerTerms)),
133
+ updatedAt: t.updatedAt || null,
134
+ });
135
+ }
136
+ tasks.sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));
137
+ } catch (e) { /* tasks.json 缺失/损坏:任务组空返 */ }
138
+
139
+ // ② 会话(六源标题索引,TTL;标题已被 listAgentSessions redact)
140
+ const sessions = [];
141
+ try {
142
+ for (const it of buildSessionIndex(config, now, o.freshIndex)) {
143
+ if (!fieldsHit([it.title, it.projectId], lowerTerms)) continue;
144
+ sessions.push({
145
+ agent: it.agent,
146
+ ref: it.ref,
147
+ title: it.title,
148
+ projectId: it.projectId,
149
+ lastActiveAt: it.lastActiveAt,
150
+ });
151
+ }
152
+ sessions.sort((a, b) => String(b.lastActiveAt || '').localeCompare(String(a.lastActiveAt || '')));
153
+ } catch (e) { /* 索引失败:会话组空返 */ }
154
+
155
+ // ③ 提交 / PR(activities.json 统一动态流;无 url 的条目仍返回、前端降级不可点)
156
+ const commits = [];
157
+ try {
158
+ const acts = store.loadActivities({ activitiesPath: dataPath(config, 'activities.json') });
159
+ for (const a of Array.isArray(acts) ? acts : []) {
160
+ if (!a || (a.type !== 'commit' && a.type !== 'pr')) continue;
161
+ const fields = [a.title, a.messageBody, a.repo];
162
+ if (!fieldsHit(fields, lowerTerms)) continue;
163
+ commits.push({
164
+ kind: a.type,
165
+ title: redactText(String(a.title || '')),
166
+ repo: a.repo == null ? null : String(a.repo),
167
+ url: typeof a.url === 'string' ? a.url : '',
168
+ at: a.occurredAt || null,
169
+ snippet: redactText(snippetOf(fields, lowerTerms)),
170
+ });
171
+ }
172
+ commits.sort((x, y) => String(y.at || '').localeCompare(String(x.at || '')));
173
+ } catch (e) { /* activities.json 缺失:提交组空返 */ }
174
+
175
+ // ④ 日报(diary.json 全文;命中挂 taskId 深链)
176
+ const diaries = [];
177
+ try {
178
+ const list = diaryMod.loadDiaries({ diaryPath: dataPath(config, 'diary.json') });
179
+ for (const d of list) {
180
+ const fields = [d.content, d.date];
181
+ if (!fieldsHit(fields, lowerTerms)) continue;
182
+ diaries.push({
183
+ taskId: d.taskId,
184
+ date: d.date,
185
+ snippet: redactText(snippetOf(fields, lowerTerms)),
186
+ updatedAt: d.updatedAt || null,
187
+ });
188
+ }
189
+ diaries.sort((a, b) => String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));
190
+ } catch (e) { /* diary.json 缺失:日报组空返 */ }
191
+
192
+ const groups = {
193
+ tasks: tasks.slice(0, MAX_PER_GROUP),
194
+ sessions: sessions.slice(0, MAX_PER_GROUP),
195
+ commits: commits.slice(0, MAX_PER_GROUP),
196
+ diaries: diaries.slice(0, MAX_PER_GROUP),
197
+ };
198
+ let total = 0;
199
+ for (const k of Object.keys(groups)) total += groups[k].length;
200
+ return { q: String(q || ''), tookMs: Date.now() - started, total, groups };
201
+ }
202
+
203
+ /** 路由挂载:GET /api/work-search?q=(空 q → 400 FIELD_INVALID) */
204
+ function registerWorkSearchRoute(router, ctx) {
205
+ router.add('GET', '/api/work-search', (c) => {
206
+ const q = c.query.get('q') || '';
207
+ sendJSON(c.res, 200, workSearch(ctx.config, q, {}));
208
+ });
209
+ }
210
+
211
+ module.exports = {
212
+ workSearch,
213
+ registerWorkSearchRoute,
214
+ parseTerms,
215
+ fieldsHit,
216
+ snippetOf,
217
+ buildSessionIndex,
218
+ MAX_PER_GROUP,
219
+ MAX_TERMS,
220
+ };
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "超级工作台",
4
+ "description": "Personal FDE cockpit: task board, task radar, agent activity, team feed and daily/weekly reports, all inside DeepSeek Harness."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "超级工作台",
4
+ "description": "个人 FDE 驾驶舱:任务看板、任务雷达、智能体动态、团队动态与数字员工日报/周报,装在 DeepSeek Harness 里。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "fde-console",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.9.68",
4
+ "description": "Super Workbench (fde-console) — local-first workbench plugin for DeepSeek Harness (DSH): turns your local AI coding agents into an observable, accountable team. Zero runtime dependencies; data stays on your machine.",
5
+ "license": "MIT",
6
+ "icon": "./assets/icon.svg",
7
+ "main": "./plugin/index.mjs",
8
+ "engines": {
9
+ "node": ">=22.13",
10
+ "dsh": ">=0.2.1-rc.2 <0.3.0-0"
11
+ },
12
+ "exports": {
13
+ ".": "./plugin/index.mjs",
14
+ "./client": "./plugin/client.js",
15
+ "./locale/*.json": "./locale/*.json",
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "plugin/",
20
+ "lib/",
21
+ "web/",
22
+ "assets/",
23
+ "locale/",
24
+ "scripts/migrate-data.js",
25
+ "scripts/migrate-storage.js",
26
+ "scripts/backup-data.js",
27
+ "scripts/seed-demo.js",
28
+ "scripts/mcp-server.mjs",
29
+ "scripts/write-agent-context.js",
30
+ "test/helpers/appAssembler.js",
31
+ "cordis.patch.yml"
32
+ ],
33
+ "scripts": {
34
+ "test": "node --test \"test/*.test.js\""
35
+ },
36
+ "dsh": {
37
+ "manifestVersion": 1,
38
+ "bundle": {
39
+ "patch": "./cordis.patch.yml"
40
+ },
41
+ "client": {
42
+ "platform": "web",
43
+ "inject": [
44
+ "react"
45
+ ]
46
+ }
47
+ }
48
+ }
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * adapter.js — DSH 宿主适配层(WP2):Host 防线 + 前缀剥离 + 统一 500
5
+ *
6
+ * 职责边界(SPEC-PLUGIN 2.1/2.5,P1/P4 实测定型):
7
+ * - P1:webServer route.handler = Node (IncomingMessage, ServerResponse) 双参单态
8
+ * (源码 `await route.handler(req, res)`)→ adaptHttp 定型单态 req/res 适配,无双态实现;
9
+ * - Host 防线只护自有路由(/fde-api/* 与 /fde/*):DSH 的 /api browser-trust fence 不波及
10
+ * 第三方 prefix 路由(P4 实测:伪造 Host 打 /fde-api → 200),防线必须自持,不依赖宿主(R-S2)。
11
+ * allowlist = 回环字面量(127.0.0.1 / localhost / ::1,恒在)+ config.security.trustedHosts
12
+ * (新 config 键,默认 ["127.0.0.1","localhost"],对齐 DSH fence 的 extra-authority 思路);
13
+ * 其余 Host 一律 403 HOST_FORBIDDEN。Host 头比较取 authority 的 host 部分(端口不敏感,
14
+ * 因宿主端口运行期才确定);IPv6 字面量按 [::1]:port 形态解析。
15
+ * - CSRF 防线①(写请求 Content-Type: application/json)在 lib/router.dispatch 内,两态共用;
16
+ * 防线②(Sec-Fetch-Site)留在装配器边界管线(独立版过渡路径),插件态按 2.5 安全表以
17
+ * Host 防线 + CSRF① 承接,不重复实现。
18
+ * - R-S1 进程内共生:插件异常不得击穿 DSH 进程——adaptHttp 全路由 try/catch + 统一 500 JSON
19
+ * (宿主对 handler 抛错的兜底是 warn + 400,非 500,故统一 500 必须自持)。错误文本过 redact。
20
+ * - 本文件不触碰任何 DSH API(那是 plugin/index.mjs 的专属职责),可独立单测。
21
+ */
22
+
23
+ const { sendError } = require('../lib/router');
24
+
25
+ let redactFn = null;
26
+ let redactTried = false;
27
+ /** #9 同款纪律:日志出口过 redact(redact.js 缺位时原样输出,绝不因日志崩溃) */
28
+ function redactText(text) {
29
+ if (!redactTried) {
30
+ redactTried = true;
31
+ try {
32
+ redactFn = require('../lib/redact.js').redact;
33
+ } catch (e) {
34
+ redactFn = null;
35
+ }
36
+ }
37
+ try {
38
+ return redactFn ? redactFn(String(text)) : String(text);
39
+ } catch (e) {
40
+ return String(text);
41
+ }
42
+ }
43
+
44
+ /**
45
+ * 统一 500 包装:handler 抛错 → 记日志(redact)→ 未发送头则 500 INTERNAL JSON,已发送则尽力收尾。
46
+ * 返回的函数即 webServer route.handler 形态:async (req, res)。
47
+ */
48
+ function adaptHttp(handler, opts) {
49
+ const label = (opts && opts.label) || 'handler';
50
+ return async function adapted(req, res) {
51
+ try {
52
+ await handler(req, res);
53
+ } catch (e) {
54
+ console.error(`[fde-adapter] ${label} 未捕获错误:`, redactText((e && e.stack) || e));
55
+ if (!res.headersSent) {
56
+ sendError(res, 500, 'INTERNAL', '服务器内部错误');
57
+ } else {
58
+ try {
59
+ res.end();
60
+ } catch (_) { /* 已断开 */ }
61
+ }
62
+ }
63
+ };
64
+ }
65
+
66
+ /** Host 头 authority → host 部分:'127.0.0.1:7788'→'127.0.0.1';'[::1]:80'→'::1';无端口原样 */
67
+ function hostOf(authority) {
68
+ const s = String(authority || '').trim().toLowerCase();
69
+ if (s.startsWith('[')) {
70
+ const i = s.indexOf(']');
71
+ return i > 0 ? s.slice(1, i) : s;
72
+ }
73
+ const first = s.indexOf(':');
74
+ const last = s.lastIndexOf(':');
75
+ // 单冒号视为 host:port;多冒号为裸 IPv6 字面量
76
+ if (first > -1 && first === last) return s.slice(0, first);
77
+ return s;
78
+ }
79
+
80
+ const LOOPBACK_LITERALS = new Set(['127.0.0.1', 'localhost', '::1']);
81
+
82
+ /**
83
+ * Host 防线工厂。config.security.trustedHosts(字符串数组)在回环字面量基础上扩展 allowlist。
84
+ * 返回 guard(req, res) → true(放行)/ false(已代答 403)。
85
+ */
86
+ function createHostGuard(opts) {
87
+ const config = opts && opts.config;
88
+ const extra = (config && config.security && config.security.trustedHosts) || [];
89
+ const allow = new Set(LOOPBACK_LITERALS);
90
+ for (const entry of Array.isArray(extra) ? extra : []) {
91
+ const h = hostOf(entry);
92
+ if (h) allow.add(h);
93
+ }
94
+ return function hostGuard(req, res) {
95
+ const host = hostOf(req.headers && req.headers.host);
96
+ if (allow.has(host)) return true;
97
+ sendError(
98
+ res,
99
+ 403,
100
+ 'HOST_FORBIDDEN',
101
+ 'Host 不在受信任列表(fde-console 防线自持,不依赖宿主 fence)'
102
+ );
103
+ return false;
104
+ };
105
+ }
106
+
107
+ /**
108
+ * 剥 prefix 后的 req 视图(原型链保留,readBody/on 等行为不变);不匹配返回 null。
109
+ * '/fde-api' → '/';'/fde-api?x=1' → '/?x=1';'/fde-apix' → null(防前缀误吞)。
110
+ */
111
+ function stripPrefix(req, prefix) {
112
+ const url = req.url || '/';
113
+ if (url !== prefix && !url.startsWith(prefix + '/') && !url.startsWith(prefix + '?')) return null;
114
+ let rest = url.slice(prefix.length);
115
+ if (rest === '' || rest.startsWith('?')) rest = '/' + rest;
116
+ const view = Object.create(req);
117
+ view.url = rest;
118
+ return view;
119
+ }
120
+
121
+ /**
122
+ * 生成挂到 webServer 的一对 handler(/fde-api → app.handleApi、/fde → app.handleStatic)与轮询 tick。
123
+ * app 形态 = 装配器 buildApp() 产物(handleApi/handleStatic/pollTick);hostGuard 可注入替换。
124
+ * 每个 handler 依次过:Host 防线(403 代答)→ 前缀剥离(404)→ adaptHttp 统一 500。
125
+ */
126
+ function createRouteHandlers(opts) {
127
+ const app = opts.app;
128
+ const guard = opts.hostGuard || null;
129
+ const apiPrefix = opts.apiPrefix || '/fde-api';
130
+ const staticPrefix = opts.staticPrefix || '/fde';
131
+
132
+ const api = adaptHttp(async (req, res) => {
133
+ if (guard && !guard(req, res)) return;
134
+ const stripped = stripPrefix(req, apiPrefix);
135
+ if (!stripped) return sendError(res, 404, 'NOT_FOUND', '接口不存在');
136
+ // /fde-api/* → /api/* 同构重定基:SPA 原 fetch 路径(/api/tasks 等)在 lib 路由零改动的前提下
137
+ // 经宿主前缀原样到达(/fde-api/ping ↔ /api/ping,对齐 WP1 spike 契约)
138
+ const rebased = Object.create(stripped);
139
+ rebased.url = '/api' + (stripped.url === '/' ? '' : stripped.url);
140
+ await app.handleApi(rebased, res);
141
+ }, { label: '/fde-api' });
142
+
143
+ const staticHandler = adaptHttp(async (req, res) => {
144
+ if (guard && !guard(req, res)) return;
145
+ const stripped = stripPrefix(req, staticPrefix);
146
+ if (!stripped) return sendError(res, 404, 'NOT_FOUND', '静态资源不存在');
147
+ await app.handleStatic(stripped, res);
148
+ }, { label: '/fde' });
149
+
150
+ return {
151
+ api,
152
+ static: staticHandler,
153
+ pollTick: () => app.pollTick(),
154
+ };
155
+ }
156
+
157
+ module.exports = { adaptHttp, createHostGuard, createRouteHandlers, stripPrefix, hostOf, LOOPBACK_LITERALS };