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.
- package/LICENSE +21 -0
- package/README.md +128 -2
- package/README.zh-CN.md +130 -0
- package/assets/icon.svg +9 -0
- package/cordis.patch.yml +7 -0
- package/lib/agentActivity.js +1180 -0
- package/lib/agentContext.js +146 -0
- package/lib/agentTranscript.js +1398 -0
- package/lib/analyze.js +625 -0
- package/lib/attribute.js +205 -0
- package/lib/backup.js +366 -0
- package/lib/desktopAgents.js +123 -0
- package/lib/diary.js +333 -0
- package/lib/dingtalk.js +412 -0
- package/lib/feishu.js +580 -0
- package/lib/giteaClient.js +810 -0
- package/lib/giteeClient.js +372 -0
- package/lib/githubClient.js +361 -0
- package/lib/heatmap.js +99 -0
- package/lib/imNotify.js +378 -0
- package/lib/inbox.js +438 -0
- package/lib/instanceLock.js +122 -0
- package/lib/jobs.js +56 -0
- package/lib/learn.js +1388 -0
- package/lib/learnImport.js +283 -0
- package/lib/learnSeeds.js +97 -0
- package/lib/learnSeedsAiEng.js +77 -0
- package/lib/mcpCore.js +135 -0
- package/lib/members.js +160 -0
- package/lib/migration.js +403 -0
- package/lib/overview.js +376 -0
- package/lib/postmortem.js +148 -0
- package/lib/radarIgnore.js +134 -0
- package/lib/redact.js +76 -0
- package/lib/router.js +246 -0
- package/lib/routes-gitea.js +262 -0
- package/lib/routes-setup.js +40 -0
- package/lib/scorecard.js +111 -0
- package/lib/sessionRef.js +227 -0
- package/lib/sessionSnapshot.js +67 -0
- package/lib/sessionSuggest.js +186 -0
- package/lib/settings.js +783 -0
- package/lib/setupCheck.js +330 -0
- package/lib/ssrfGuard.js +145 -0
- package/lib/store.js +564 -0
- package/lib/storeDb.js +418 -0
- package/lib/taskEvents.js +243 -0
- package/lib/webhookOut.js +125 -0
- package/lib/weekly.js +439 -0
- package/lib/workSearch.js +220 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +46 -4
- package/plugin/adapter.js +157 -0
- package/plugin/client.js +282 -0
- package/plugin/index.mjs +116 -0
- package/plugin/static.js +99 -0
- package/scripts/backup-data.js +41 -0
- package/scripts/mcp-server.mjs +68 -0
- package/scripts/migrate-data.js +301 -0
- package/scripts/migrate-storage.js +47 -0
- package/scripts/seed-demo.js +200 -0
- package/scripts/write-agent-context.js +43 -0
- package/test/helpers/appAssembler.js +1078 -0
- package/web/client/fde-client.js +292 -0
- package/web/css/app.css +1510 -0
- package/web/index.html +69 -0
- package/web/js/api.js +72 -0
- package/web/js/app.js +313 -0
- package/web/js/icons.js +48 -0
- package/web/js/mock.js +1150 -0
- package/web/js/state.js +7 -0
- package/web/js/ui.js +276 -0
- package/web/js/views/activity.js +410 -0
- package/web/js/views/agents.js +892 -0
- package/web/js/views/board.js +1656 -0
- package/web/js/views/learn.js +530 -0
- package/web/js/views/members.js +344 -0
- package/web/js/views/onboarding.js +103 -0
- package/web/js/views/overview.js +508 -0
- package/web/js/views/radar.js +1359 -0
- package/web/js/views/search.js +149 -0
- package/web/js/views/settings.js +1351 -0
- package/web/js/views/topology.js +471 -0
- package/web/mock.json +2363 -0
|
@@ -0,0 +1,1078 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* appAssembler.js — WP3 测试装配器:server.js 装配逻辑的单一真相(可注入 config 的纯装配)
|
|
5
|
+
*
|
|
6
|
+
* buildApp({configPath, configDir, rootDir, env, persistentEnv, poller})
|
|
7
|
+
* → { ctx, router, config, configPath, version,
|
|
8
|
+
* handle, // 边界管线:Host 头校验(403) → Sec-Fetch-Site 校验(403) → /api/* 分发 | 其余静态
|
|
9
|
+
* handleApi, // router.dispatch 直通(插件态 adapter 在自己防线内直委,见 plugin/adapter.js)
|
|
10
|
+
* handleStatic, // 静态托管直通(plugin/static.js)
|
|
11
|
+
* fetch, // 进程内 mock 客户端:createMockReq/createMockRes + handle,fetch 形响应答
|
|
12
|
+
* pollTick, // Gitea 轮询单飞 tick(插件态由宿主 ctx.interval 驱动)
|
|
13
|
+
* close } // 收尾:停轮询定时器、还原 persistentEnv
|
|
14
|
+
*
|
|
15
|
+
* 与旧 server.js 的唯一语义差异:
|
|
16
|
+
* 1. 启动期校验失败由 process.exit(2) 改为 throw(独立版 server.js catch 后仍打印 [config] 并 exit 2,
|
|
17
|
+
* 消息文本一致——radar 启动期体检用例因此平移为 assert.throws 断言装配器);
|
|
18
|
+
* 2. host 校验放宽为 127.0.0.1|0.0.0.0(SPEC-PLUGIN 2.1:与宿主 webServer schema 同源,业主拍板允许
|
|
19
|
+
* 显式配置 LAN 绑定);监听权在独立版仍属 server.js、插件态属宿主,本模块从不 listen。
|
|
20
|
+
*
|
|
21
|
+
* mock 传输层(真端口用例 → router.handle(mockReq, mockRes) 的迁移底座):
|
|
22
|
+
* - createMockReq/createMockRes 实现 router.dispatch/readBody/静态/adapter 所需的
|
|
23
|
+
* IncomingMessage/ServerResponse 最小面(on/destroy/url/headers/method、writeHead/setHeader/end/headersSent);
|
|
24
|
+
* - app.fetch(method, p, {headers, body}) 走与 http 层完全相同的 app.handle 管线;
|
|
25
|
+
* - env 注入:独立版按子进程 env 注 fixture(DINGTALK_FIXTURE/GITEA_FIXTURE/...);
|
|
26
|
+
* 进程内改为分发期间临时注入(persistentEnv 时在 build 即写入、close 还原,供 radar 后台 job 在
|
|
27
|
+
* 响应之后继续读 env 的场景)。(v2.2:网关 fixture 型 env 键特判随网关集成移除,不再特判)
|
|
28
|
+
* - 并发约定:同进程多 app 的 env 注入依赖 node:test 同文件内用例串行执行(现状即如此)。
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const path = require('path');
|
|
32
|
+
|
|
33
|
+
const {
|
|
34
|
+
Router,
|
|
35
|
+
sendJSON,
|
|
36
|
+
sendError,
|
|
37
|
+
noContent,
|
|
38
|
+
HttpError,
|
|
39
|
+
mountGiteaRoutes,
|
|
40
|
+
} = require('../../lib/router');
|
|
41
|
+
const store = require('../../lib/store');
|
|
42
|
+
const settingsMod = require('../../lib/settings');
|
|
43
|
+
const overviewMod = require('../../lib/overview');
|
|
44
|
+
const membersMod = require('../../lib/members');
|
|
45
|
+
const setupRoutesMod = require('../../lib/routes-setup');
|
|
46
|
+
const taskEvents = require('../../lib/taskEvents');
|
|
47
|
+
const diaryMod = require('../../lib/diary');
|
|
48
|
+
const agentTranscriptMod = require('../../lib/agentTranscript');
|
|
49
|
+
const sessionRefMod = require('../../lib/sessionRef');
|
|
50
|
+
const attributeMod = require('../../lib/attribute');
|
|
51
|
+
const workSearchMod = require('../../lib/workSearch');
|
|
52
|
+
const sessionSuggestMod = require('../../lib/sessionSuggest');
|
|
53
|
+
const { serveStatic } = require('../../plugin/static');
|
|
54
|
+
|
|
55
|
+
// 应用版本:直接取根 package.json,避免「发版改了 package.json、这里忘了同步」的漂移
|
|
56
|
+
// (曾出现 ping 仍报 2.9.13 而实际已跑 2.9.15 的假象)。
|
|
57
|
+
const VERSION = require('../../package.json').version;
|
|
58
|
+
|
|
59
|
+
// ---------- ID 生成 ----------
|
|
60
|
+
|
|
61
|
+
/** t-<base36 时间戳>-<4 位随机> */
|
|
62
|
+
function genTaskId(existing) {
|
|
63
|
+
const taken = new Set(existing.map((t) => t.id));
|
|
64
|
+
let id;
|
|
65
|
+
do {
|
|
66
|
+
id = `t-${Date.now().toString(36)}-${store.randomToken(4)}`;
|
|
67
|
+
} while (taken.has(id));
|
|
68
|
+
return id;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function slugify(name) {
|
|
72
|
+
return name
|
|
73
|
+
.toLowerCase()
|
|
74
|
+
.normalize('NFKD')
|
|
75
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
76
|
+
.replace(/^-+|-+$/g, '');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---------- B2:任务 / 列 ----------
|
|
80
|
+
|
|
81
|
+
function registerTaskRoutes(router, ctx) {
|
|
82
|
+
const TASK_WRITABLE = ['title', 'status', 'agentId', 'repo', 'branch', 'prUrl', 'notes'];
|
|
83
|
+
|
|
84
|
+
function validateTitle(v) {
|
|
85
|
+
if (typeof v !== 'string' || v.trim().length < 1 || v.trim().length > 200) {
|
|
86
|
+
throw new HttpError(400, 'TITLE_INVALID', 'title 必填且为 1..200 字符');
|
|
87
|
+
}
|
|
88
|
+
return v.trim();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function requireColumn(columns, status) {
|
|
92
|
+
if (!columns.some((c) => c.id === status)) {
|
|
93
|
+
throw new HttpError(400, 'COLUMN_NOT_FOUND', `列 "${status}" 不存在`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function nullableString(v) {
|
|
98
|
+
if (v === undefined || v === null) return null;
|
|
99
|
+
if (typeof v !== 'string') throw new HttpError(400, 'FIELD_INVALID', '字段必须为字符串或 null');
|
|
100
|
+
return v;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// v1.2:任务负责成员(人类成员 id,≤64 字符;不强制存在于名册,可与 agentId 同设)
|
|
104
|
+
// v2.0:泛化为 nullableMemberId(v, label),复用于验收签字人 acceptorId(同一校验语义与 64 字符上限)
|
|
105
|
+
function nullableMemberId(v, label) {
|
|
106
|
+
const key = label || 'memberId';
|
|
107
|
+
if (v === undefined || v === null) return null;
|
|
108
|
+
if (typeof v !== 'string') throw new HttpError(400, 'FIELD_INVALID', `${key} 必须为字符串或 null`);
|
|
109
|
+
if (v.length > 64) throw new HttpError(400, 'FIELD_INVALID', `${key} 长度不能超过 64 字符`);
|
|
110
|
+
return v;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// v1.2:任务多行描述(≤2000 字符,允许空串与多行,缺省 "")
|
|
114
|
+
function validateDesc(v) {
|
|
115
|
+
if (v === undefined) return '';
|
|
116
|
+
if (typeof v !== 'string') throw new HttpError(400, 'FIELD_INVALID', 'desc 必须为字符串');
|
|
117
|
+
if (v.length > 2000) throw new HttpError(400, 'FIELD_INVALID', 'desc 长度不能超过 2000 字符');
|
|
118
|
+
return v;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// #7:URL 字段仅接受 http(s),杜绝 javascript: 等伪协议落库被前端当链接渲染
|
|
122
|
+
const HTTP_URL_RE = /^https?:\/\/\S+$/i;
|
|
123
|
+
function nullableUrl(v, label) {
|
|
124
|
+
const s = nullableString(v);
|
|
125
|
+
if (s === null || s.trim() === '') return null;
|
|
126
|
+
const t = s.trim();
|
|
127
|
+
if (!HTTP_URL_RE.test(t)) throw new HttpError(400, 'URL_INVALID', `${label} 必须为 http(s):// 开头的 URL`);
|
|
128
|
+
return t;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// v1.4:任务截止时间(YYYY-MM-DD 字符串或 null)。正则通过后还需本地日历回读校验,
|
|
132
|
+
// 拦住 2026-13-99、2026-02-30 这类正则通过但日历不存在/溢出的日期——
|
|
133
|
+
// 注意 V8 的 new Date('2026-02-30') 会滚动到 3 月 2 日所以不能只判 NaN。
|
|
134
|
+
// 允许过去日期,不做逾期拦截。
|
|
135
|
+
const DUE_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
136
|
+
function nullableDueDate(v) {
|
|
137
|
+
if (v === undefined || v === null) return null;
|
|
138
|
+
if (typeof v !== 'string' || !DUE_DATE_RE.test(v)) {
|
|
139
|
+
throw new HttpError(400, 'FIELD_INVALID', 'dueDate 必须为 YYYY-MM-DD 格式字符串或 null');
|
|
140
|
+
}
|
|
141
|
+
const parts = v.split('-');
|
|
142
|
+
const y = Number(parts[0]);
|
|
143
|
+
const m = Number(parts[1]);
|
|
144
|
+
const d = Number(parts[2]);
|
|
145
|
+
const dt = new Date(y, m - 1, d);
|
|
146
|
+
if (dt.getFullYear() !== y || dt.getMonth() !== m - 1 || dt.getDate() !== d) {
|
|
147
|
+
throw new HttpError(400, 'FIELD_INVALID', 'dueDate 不是有效日期');
|
|
148
|
+
}
|
|
149
|
+
return v;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// v1.4:任务优先级(high/medium/low;undefined/null/'' 缺省 medium,非法值 400)
|
|
153
|
+
const PRIORITIES = ['high', 'medium', 'low'];
|
|
154
|
+
function normalizePriority(v) {
|
|
155
|
+
if (v === undefined || v === null || v === '') return 'medium';
|
|
156
|
+
if (!PRIORITIES.includes(v)) {
|
|
157
|
+
throw new HttpError(400, 'FIELD_INVALID', 'priority 必须为 high/medium/low 之一');
|
|
158
|
+
}
|
|
159
|
+
return v;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
router.add('GET', '/api/tasks', (c) => {
|
|
163
|
+
const { tasks } = store.loadTasks(ctx);
|
|
164
|
+
let out = tasks;
|
|
165
|
+
const status = c.query.get('status');
|
|
166
|
+
if (status) out = out.filter((t) => t.status === status);
|
|
167
|
+
const memberId = c.query.get('memberId');
|
|
168
|
+
if (memberId) out = out.filter((t) => t.memberId === memberId);
|
|
169
|
+
// v1.4:priority 查询过滤,与既有 status/q/memberId 完全叠加;取值非法时自然过滤为空数组,不额外报错
|
|
170
|
+
const priority = c.query.get('priority');
|
|
171
|
+
if (priority) out = out.filter((t) => t.priority === priority);
|
|
172
|
+
const q = (c.query.get('q') || '').trim().toLowerCase();
|
|
173
|
+
if (q) {
|
|
174
|
+
out = out.filter((t) =>
|
|
175
|
+
[t.title, t.branch, t.notes, t.desc].some((f) => typeof f === 'string' && f.toLowerCase().includes(q))
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
// v2.9.7:projectDir 过滤(归一口径与项目绑定/会话钻取一致:去尾分隔符+分隔符统一+小写)
|
|
179
|
+
const projectDir = (c.query.get('projectDir') || '').trim();
|
|
180
|
+
if (projectDir) {
|
|
181
|
+
const want = agentTranscriptMod.normalizeProjectKey(projectDir);
|
|
182
|
+
out = out.filter((t) => agentTranscriptMod.normalizeProjectKey(t.projectDir) === want);
|
|
183
|
+
}
|
|
184
|
+
// v2.9.15:成果提交说明读取时回填(url ↔ activities.json 映射,仅响应不落盘;
|
|
185
|
+
// 存量任务/手动挂接的成果在活动窗口内自动带出 title/messageBody)
|
|
186
|
+
attributeMod.backfillArtifactMeta(out, store.loadActivities(ctx));
|
|
187
|
+
sendJSON(c.res, 200, store.clone(out));
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
router.add('POST', '/api/tasks', (c) => {
|
|
191
|
+
const data = store.loadTasks(ctx);
|
|
192
|
+
const body = c.body || {};
|
|
193
|
+
const title = validateTitle(body.title);
|
|
194
|
+
const status = body.status === undefined || body.status === null || body.status === '' ? 'todo' : body.status;
|
|
195
|
+
requireColumn(data.columns, status);
|
|
196
|
+
|
|
197
|
+
const now = new Date().toISOString();
|
|
198
|
+
const task = {
|
|
199
|
+
id: genTaskId(data.tasks),
|
|
200
|
+
title,
|
|
201
|
+
status,
|
|
202
|
+
agentId: nullableString(body.agentId),
|
|
203
|
+
memberId: nullableMemberId(body.memberId),
|
|
204
|
+
// v2.0:验收签字人 acceptorId(完成工作的验收签字,与 memberId 负责人、agentId 执行者三方独立;
|
|
205
|
+
// 不校验存在于名册)
|
|
206
|
+
acceptorId: nullableMemberId(body.acceptorId, 'acceptorId'),
|
|
207
|
+
repo: nullableString(body.repo),
|
|
208
|
+
branch: nullableString(body.branch),
|
|
209
|
+
// v2.9.4:项目级绑定——任务关联一个项目目录(ambient 关联,不自动产生 artifacts;
|
|
210
|
+
// null=未绑定。语义口径见 SPEC「项目绑定」)
|
|
211
|
+
projectDir: nullableString(body.projectDir),
|
|
212
|
+
prUrl: nullableUrl(body.prUrl, 'prUrl'),
|
|
213
|
+
notes: typeof body.notes === 'string' ? body.notes : '',
|
|
214
|
+
desc: validateDesc(body.desc),
|
|
215
|
+
dueDate: nullableDueDate(body.dueDate), // v1.4:截止时间(YYYY-MM-DD 或 null)
|
|
216
|
+
priority: normalizePriority(body.priority), // v1.4:优先级(缺省 medium)
|
|
217
|
+
artifacts: [], // v1.9(Q3-L1):Gitea 成果手动挂接;存量任务无字段容错(读写两端均容忍缺失)
|
|
218
|
+
// v1.7:完成日期——创建即落在内置 done 列时记当前时间,否则 null
|
|
219
|
+
completedAt: status === 'done' ? now : null,
|
|
220
|
+
createdAt: now,
|
|
221
|
+
updatedAt: now,
|
|
222
|
+
};
|
|
223
|
+
data.tasks.push(task);
|
|
224
|
+
store.saveTasks(ctx, data);
|
|
225
|
+
// v1.7:created 事件(detail 含 origin 来源描述,如有)
|
|
226
|
+
taskEvents.appendEvents(ctx, [taskEvents.createdEvent(task, now)]);
|
|
227
|
+
sendJSON(c.res, 201, store.clone(task));
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
router.add('GET', '/api/tasks/:id', (c) => {
|
|
231
|
+
const { tasks } = store.loadTasks(ctx);
|
|
232
|
+
const task = tasks.find((t) => t.id === c.params.id);
|
|
233
|
+
if (!task) throw new HttpError(404, 'TASK_NOT_FOUND', '任务不存在');
|
|
234
|
+
// v1.7:详情带事件流(倒序最近 100 条);存量老任务无事件自然为空数组,不回填
|
|
235
|
+
const events = taskEvents.eventsForTask(ctx, task.id);
|
|
236
|
+
// v2.9.15:成果提交说明读取时回填(同 GET 列表口径,仅响应不落盘)
|
|
237
|
+
attributeMod.backfillArtifactMeta([task], store.loadActivities(ctx));
|
|
238
|
+
sendJSON(c.res, 200, Object.assign(store.clone(task), { events }));
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
router.add('PATCH', '/api/tasks/:id', (c) => {
|
|
242
|
+
const data = store.loadTasks(ctx);
|
|
243
|
+
const task = data.tasks.find((t) => t.id === c.params.id);
|
|
244
|
+
if (!task) throw new HttpError(404, 'TASK_NOT_FOUND', '任务不存在');
|
|
245
|
+
const body = c.body || {};
|
|
246
|
+
// v1.7:事件流需要变更前快照(每字段类型最多一条,防噪合并)
|
|
247
|
+
const before = taskEvents.snapshotOf(task);
|
|
248
|
+
if (body.title !== undefined) task.title = validateTitle(body.title);
|
|
249
|
+
if (body.status !== undefined) {
|
|
250
|
+
requireColumn(data.columns, body.status);
|
|
251
|
+
task.status = body.status;
|
|
252
|
+
}
|
|
253
|
+
if (body.agentId !== undefined) task.agentId = nullableString(body.agentId);
|
|
254
|
+
if (body.memberId !== undefined) task.memberId = nullableMemberId(body.memberId);
|
|
255
|
+
// v2.0:验收签字人——PATCH 传 null 即清除
|
|
256
|
+
if (body.acceptorId !== undefined) task.acceptorId = nullableMemberId(body.acceptorId, 'acceptorId');
|
|
257
|
+
if (body.repo !== undefined) task.repo = nullableString(body.repo);
|
|
258
|
+
if (body.branch !== undefined) task.branch = nullableString(body.branch);
|
|
259
|
+
// v2.9.4:项目级绑定——PATCH 传 null 即解绑
|
|
260
|
+
if (body.projectDir !== undefined) task.projectDir = nullableString(body.projectDir);
|
|
261
|
+
if (body.prUrl !== undefined) task.prUrl = nullableUrl(body.prUrl, 'prUrl');
|
|
262
|
+
if (body.notes !== undefined) {
|
|
263
|
+
if (typeof body.notes !== 'string') throw new HttpError(400, 'FIELD_INVALID', 'notes 必须为字符串');
|
|
264
|
+
task.notes = body.notes;
|
|
265
|
+
}
|
|
266
|
+
if (body.desc !== undefined) task.desc = validateDesc(body.desc);
|
|
267
|
+
// v1.4:dueDate——PATCH 传 null 即清空
|
|
268
|
+
if (body.dueDate !== undefined) task.dueDate = nullableDueDate(body.dueDate);
|
|
269
|
+
// v1.4:priority——PATCH 时必须严格属于 PRIORITIES(null/数字/其他值一律非法,不同于 POST 的缺省 medium)
|
|
270
|
+
if (body.priority !== undefined) {
|
|
271
|
+
if (!PRIORITIES.includes(body.priority)) {
|
|
272
|
+
throw new HttpError(400, 'FIELD_INVALID', 'priority 必须为 high/medium/low 之一');
|
|
273
|
+
}
|
|
274
|
+
task.priority = body.priority;
|
|
275
|
+
}
|
|
276
|
+
// v1.7:completedAt 完成日期——PATCH 带 status 才处置:进内置 done 列记当前时间
|
|
277
|
+
//(已设则刷新为最新,重进 done 亦然);移出 done 清为 null;不带 status 不 touch
|
|
278
|
+
const now = new Date().toISOString();
|
|
279
|
+
if (body.status !== undefined) {
|
|
280
|
+
task.completedAt = task.status === 'done' ? now : null;
|
|
281
|
+
}
|
|
282
|
+
task.updatedAt = now;
|
|
283
|
+
store.saveTasks(ctx, data);
|
|
284
|
+
// v1.7:PATCH 差异事件(在任务落盘成功后追加;每字段类型最多一条)
|
|
285
|
+
taskEvents.appendEvents(ctx, taskEvents.patchEvents(task.id, before, taskEvents.snapshotOf(task), now));
|
|
286
|
+
sendJSON(c.res, 200, store.clone(task));
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
router.add('DELETE', '/api/tasks/:id', (c) => {
|
|
290
|
+
const data = store.loadTasks(ctx);
|
|
291
|
+
const idx = data.tasks.findIndex((t) => t.id === c.params.id);
|
|
292
|
+
if (idx === -1) throw new HttpError(404, 'TASK_NOT_FOUND', '任务不存在');
|
|
293
|
+
data.tasks.splice(idx, 1);
|
|
294
|
+
store.saveTasks(ctx, data);
|
|
295
|
+
// v1.7:删任务顺带清理其事件(文件本就无该任务事件时不写盘)
|
|
296
|
+
taskEvents.removeTaskEvents(ctx, c.params.id);
|
|
297
|
+
// v2.7:删任务顺带清理其全部日报(同纪律:文件本就无该任务日报时不写盘)
|
|
298
|
+
diaryMod.removeTaskDiaries(ctx, c.params.id);
|
|
299
|
+
noContent(c.res);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
// ---------- v1.9(任务叙事线第一批 · Q3-L1):Gitea 成果手动挂接 ----------
|
|
303
|
+
|
|
304
|
+
// v2.3 D3(SMOKE v2.3 回归 P0-A):kind 增 'session'——会话阅读器「挂到任务成果区」闭环,
|
|
305
|
+
// 该类成果无 http(s) url,以 sessionRef(不透明引用)+ title 独立字段承载(见下方 POST 分支)
|
|
306
|
+
const ARTIFACT_KINDS = ['commit', 'pr', 'session'];
|
|
307
|
+
|
|
308
|
+
// 可选字符串字段(repo/ref):缺省 null;提供时必须为 ≤200 字符字符串
|
|
309
|
+
function optionalArtifactField(v, label) {
|
|
310
|
+
if (v === undefined || v === null || v === '') return null;
|
|
311
|
+
if (typeof v !== 'string' || v.trim().length > 200) {
|
|
312
|
+
throw new HttpError(400, 'FIELD_INVALID', `${label} 必须为不超过 200 字符的字符串`);
|
|
313
|
+
}
|
|
314
|
+
return v.trim();
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// 挂接成果:{url 必填 http(s),kind 必填枚举,repo?/ref?} → 追加进 task.artifacts
|
|
318
|
+
// + 事件流 type:"artifact"(时间轴「成果节点」)+ updatedAt 刷新
|
|
319
|
+
// v2.3 D3(SMOKE v2.3 回归 P0-A):kind='session' 字段语义切换——url/repo/ref 一律不入库置
|
|
320
|
+
// null,不复用 ref 字段(board.js 按 PR 序号/commit 哈希渲染,双义会漏 base64 串进成果区);
|
|
321
|
+
// 改由 sessionRef(必填 ≤512 字符,过 sessionRef §3.3 校验)+ title(必填 1..200)独立承载。
|
|
322
|
+
// kind 判别必须先于 url 校验(否则 kind=session 无 url 会误吃「url 必填」——即本轮回归根因)
|
|
323
|
+
router.add('POST', '/api/tasks/:id/artifacts', (c) => {
|
|
324
|
+
const data = store.loadTasks(ctx);
|
|
325
|
+
const task = data.tasks.find((t) => t.id === c.params.id);
|
|
326
|
+
if (!task) throw new HttpError(404, 'TASK_NOT_FOUND', '任务不存在');
|
|
327
|
+
const body = c.body || {};
|
|
328
|
+
if (!ARTIFACT_KINDS.includes(body.kind)) {
|
|
329
|
+
throw new HttpError(400, 'FIELD_INVALID', 'kind 必须为 commit/pr/session 之一');
|
|
330
|
+
}
|
|
331
|
+
const now = new Date().toISOString();
|
|
332
|
+
let artifact;
|
|
333
|
+
let detail;
|
|
334
|
+
if (body.kind === 'session') {
|
|
335
|
+
const ref = typeof body.sessionRef === 'string' ? body.sessionRef : '';
|
|
336
|
+
if (!ref) throw new HttpError(400, 'FIELD_INVALID', 'sessionRef 必填(kind=session)');
|
|
337
|
+
if (ref.length > 512) {
|
|
338
|
+
throw new HttpError(400, 'FIELD_INVALID', 'sessionRef 长度不能超过 512 字符');
|
|
339
|
+
}
|
|
340
|
+
sessionRefMod.validateRef(ref, ctx.config); // 格式闸(§3.3):非法 throw 400 BAD_REF,零路径回显
|
|
341
|
+
const title = typeof body.title === 'string' ? body.title.trim() : '';
|
|
342
|
+
if (title.length < 1 || title.length > 200) {
|
|
343
|
+
throw new HttpError(400, 'FIELD_INVALID', 'title 必填且为 1..200 字符');
|
|
344
|
+
}
|
|
345
|
+
artifact = {
|
|
346
|
+
url: null,
|
|
347
|
+
kind: 'session',
|
|
348
|
+
repo: null,
|
|
349
|
+
ref: null,
|
|
350
|
+
sessionRef: ref,
|
|
351
|
+
title,
|
|
352
|
+
at: now,
|
|
353
|
+
};
|
|
354
|
+
detail = `挂接成果:session ${title.slice(0, 40)}`;
|
|
355
|
+
} else {
|
|
356
|
+
const url = typeof body.url === 'string' ? body.url.trim() : '';
|
|
357
|
+
if (!url || !HTTP_URL_RE.test(url)) {
|
|
358
|
+
throw new HttpError(400, 'FIELD_INVALID', 'url 必填且为 http(s):// 开头的 URL');
|
|
359
|
+
}
|
|
360
|
+
artifact = {
|
|
361
|
+
url,
|
|
362
|
+
kind: body.kind,
|
|
363
|
+
repo: optionalArtifactField(body.repo, 'repo'),
|
|
364
|
+
ref: optionalArtifactField(body.ref, 'ref'),
|
|
365
|
+
at: now,
|
|
366
|
+
};
|
|
367
|
+
// 事件 detail:kind + repo(repo 缺省时不留空洞,如「挂接成果:pr」)
|
|
368
|
+
detail = `挂接成果:${artifact.kind}${artifact.repo ? ` ${artifact.repo}` : ''}`;
|
|
369
|
+
}
|
|
370
|
+
if (!Array.isArray(task.artifacts)) task.artifacts = []; // 存量任务无字段容错:首次挂接时初始化
|
|
371
|
+
task.artifacts.push(artifact);
|
|
372
|
+
task.updatedAt = now;
|
|
373
|
+
store.saveTasks(ctx, data);
|
|
374
|
+
taskEvents.appendEvents(ctx, [taskEvents.makeEvent(task.id, 'artifact', null, null, detail, now)]);
|
|
375
|
+
sendJSON(c.res, 201, store.clone(artifact));
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
// 解除挂接:按数组下标移除;不记事件(列表即真相);越界/非法下标/任务缺失均 404
|
|
379
|
+
router.add('DELETE', '/api/tasks/:id/artifacts/:idx', (c) => {
|
|
380
|
+
const data = store.loadTasks(ctx);
|
|
381
|
+
const task = data.tasks.find((t) => t.id === c.params.id);
|
|
382
|
+
if (!task) throw new HttpError(404, 'TASK_NOT_FOUND', '任务不存在');
|
|
383
|
+
const arr = Array.isArray(task.artifacts) ? task.artifacts : [];
|
|
384
|
+
const i = Number(c.params.idx);
|
|
385
|
+
if (!Number.isInteger(i) || i < 0 || i >= arr.length) {
|
|
386
|
+
throw new HttpError(404, 'ARTIFACT_NOT_FOUND', '成果不存在(下标越界)');
|
|
387
|
+
}
|
|
388
|
+
arr.splice(i, 1);
|
|
389
|
+
store.saveTasks(ctx, data);
|
|
390
|
+
noContent(c.res);
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function registerColumnRoutes(router, ctx) {
|
|
395
|
+
router.add('GET', '/api/columns', (c) => {
|
|
396
|
+
const { columns } = store.loadTasks(ctx);
|
|
397
|
+
const out = [...columns]
|
|
398
|
+
.sort((a, b) => (a.order || 0) - (b.order || 0))
|
|
399
|
+
.map((col) => ({ id: col.id, name: col.name, order: col.order }));
|
|
400
|
+
sendJSON(c.res, 200, out);
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
router.add('POST', '/api/columns', (c) => {
|
|
404
|
+
const data = store.loadTasks(ctx);
|
|
405
|
+
const body = c.body || {};
|
|
406
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
407
|
+
if (!name || name.length > 50) throw new HttpError(400, 'INVALID_NAME', '列名必填且不超过 50 字符');
|
|
408
|
+
|
|
409
|
+
let id = slugify(name);
|
|
410
|
+
if (!id || data.columns.some((col) => col.id === id)) {
|
|
411
|
+
const taken = new Set(data.columns.map((col) => col.id));
|
|
412
|
+
do {
|
|
413
|
+
id = `col-${store.randomToken(4)}`;
|
|
414
|
+
} while (taken.has(id));
|
|
415
|
+
}
|
|
416
|
+
const order = data.columns.reduce((m, col) => Math.max(m, col.order || 0), 0) + 1;
|
|
417
|
+
const col = { id, name, order };
|
|
418
|
+
data.columns.push(col);
|
|
419
|
+
store.saveTasks(ctx, data);
|
|
420
|
+
sendJSON(c.res, 201, store.clone(col));
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
router.add('PATCH', '/api/columns/:id', (c) => {
|
|
424
|
+
const data = store.loadTasks(ctx);
|
|
425
|
+
const col = data.columns.find((x) => x.id === c.params.id);
|
|
426
|
+
if (!col) throw new HttpError(404, 'COLUMN_NOT_FOUND', '列不存在');
|
|
427
|
+
const body = c.body || {};
|
|
428
|
+
if (body.name !== undefined) {
|
|
429
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
430
|
+
if (!name || name.length > 50) throw new HttpError(400, 'INVALID_NAME', '列名必填且不超过 50 字符');
|
|
431
|
+
col.name = name;
|
|
432
|
+
}
|
|
433
|
+
let orderSet = false;
|
|
434
|
+
if (body.order !== undefined) {
|
|
435
|
+
if (!Number.isInteger(body.order) || body.order < 1) {
|
|
436
|
+
throw new HttpError(400, 'ORDER_INVALID', 'order 必须为 ≥1 的正整数');
|
|
437
|
+
}
|
|
438
|
+
col.order = body.order; // 先记绝对序号,下方统一归一化
|
|
439
|
+
orderSet = true;
|
|
440
|
+
}
|
|
441
|
+
// v1.2:order 语义——被移列取请求的绝对序号(收敛到 1..n,超界取末位),其余列按原有
|
|
442
|
+
// 相对顺序填充剩余序号位。该语义天然对 ←/→ 两个方向对称:target 位被被移列独占,
|
|
443
|
+
// 其余列依次绕过该位,因此响应 order === 请求值(1..n 内)且全列归一化为 1..n 连续序列。
|
|
444
|
+
// (旧实现「全列按序排序 + 并列时被移列优先」只在向左移动方向成立,向右会被并列对象
|
|
445
|
+
// 抢走目标位静默偏移——goose 真机验收 P1-1,勿回退。)
|
|
446
|
+
if (orderSet) {
|
|
447
|
+
const n = data.columns.length;
|
|
448
|
+
const target = Math.min(Math.max(col.order, 1), n);
|
|
449
|
+
const others = data.columns
|
|
450
|
+
.filter((x) => x !== col)
|
|
451
|
+
.sort((a, b) => (a.order || 0) - (b.order || 0)); // Node sort 稳定 = 原有相对顺序
|
|
452
|
+
let slot = 1;
|
|
453
|
+
for (const x of others) {
|
|
454
|
+
if (slot === target) slot += 1; // 跳过被移列占用的目标位
|
|
455
|
+
x.order = slot;
|
|
456
|
+
slot += 1;
|
|
457
|
+
}
|
|
458
|
+
col.order = target;
|
|
459
|
+
}
|
|
460
|
+
store.saveTasks(ctx, data);
|
|
461
|
+
sendJSON(c.res, 200, { id: col.id, name: col.name, order: col.order });
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
router.add('DELETE', '/api/columns/:id', (c) => {
|
|
465
|
+
const data = store.loadTasks(ctx);
|
|
466
|
+
const idx = data.columns.findIndex((x) => x.id === c.params.id);
|
|
467
|
+
if (idx === -1) throw new HttpError(404, 'COLUMN_NOT_FOUND', '列不存在');
|
|
468
|
+
const n = data.tasks.filter((t) => t.status === c.params.id).length;
|
|
469
|
+
if (n > 0) throw new HttpError(409, 'COLUMN_NOT_EMPTY', `先移走该列的 ${n} 个任务`);
|
|
470
|
+
data.columns.splice(idx, 1);
|
|
471
|
+
store.saveTasks(ctx, data);
|
|
472
|
+
noContent(c.res);
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// ---------- B2:智能体只读注册表(GET:任务表单执行者下拉 + overview 排除清单的数据源) ----------
|
|
477
|
+
|
|
478
|
+
function agentView(a) {
|
|
479
|
+
return {
|
|
480
|
+
id: a.id,
|
|
481
|
+
name: a.name,
|
|
482
|
+
command: a.command,
|
|
483
|
+
commandTemplate: a.commandTemplate,
|
|
484
|
+
builtin: !!a.builtin,
|
|
485
|
+
enabled: a.enabled !== false,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function registerAgentRoutes(router, ctx) {
|
|
490
|
+
router.add('GET', '/api/agents', (c) => {
|
|
491
|
+
sendJSON(c.res, 200, store.loadAgents(ctx.agentsPath).map(agentView));
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// ---------- #3/#4:Gitea 轮询器(单飞)+ 组织成员缓存 ----------
|
|
496
|
+
|
|
497
|
+
/** #4:拉取 /orgs/{org}/members 写 data/gitea-members.json(login/full_name/name)。
|
|
498
|
+
* 凭据按 giteaClient 同款模式内存使用、绝不落盘不进日志;GITEA_FIXTURE 模式零出网直接跳过。 */
|
|
499
|
+
async function refreshMembersCache(ctx, giteaClient, ssrf) {
|
|
500
|
+
try {
|
|
501
|
+
if (process.env.GITEA_FIXTURE) return; // fixture 模式不出网
|
|
502
|
+
const g = ctx.config.gitea;
|
|
503
|
+
const url = `${String(g.baseUrl).replace(/\/+$/, '')}${g.apiPrefix || '/api/v1'}/orgs/${encodeURIComponent(g.org)}/members`;
|
|
504
|
+
if (ssrf && typeof ssrf.assertSafeUrl === 'function') {
|
|
505
|
+
ssrf.assertSafeUrl(url, ctx.config); // 白名单复检,违规即抛(零出站)
|
|
506
|
+
}
|
|
507
|
+
let credential = null;
|
|
508
|
+
try {
|
|
509
|
+
credential = giteaClient.readCredential(ctx.config);
|
|
510
|
+
} catch (e) {
|
|
511
|
+
credential = null; // 无凭据时尝试匿名拉取(公开组织可读)
|
|
512
|
+
}
|
|
513
|
+
// 与 giteaClient.authHeaders 同款拆分:extraheader 原值 "Name: value";无冒号则作 Authorization 值。
|
|
514
|
+
// 凭据仅存内存用于本次请求头,绝不落盘、不进日志。
|
|
515
|
+
const headers = { Accept: 'application/json' };
|
|
516
|
+
if (credential) {
|
|
517
|
+
const idx = credential.indexOf(':');
|
|
518
|
+
if (idx > 0) headers[credential.slice(0, idx).trim()] = credential.slice(idx + 1).trim();
|
|
519
|
+
else headers.Authorization = credential;
|
|
520
|
+
}
|
|
521
|
+
const ctrl = new AbortController();
|
|
522
|
+
const timer = setTimeout(() => ctrl.abort(), 10000);
|
|
523
|
+
let list;
|
|
524
|
+
try {
|
|
525
|
+
const res = await fetch(url, { headers, signal: ctrl.signal });
|
|
526
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
527
|
+
list = await res.json();
|
|
528
|
+
} finally {
|
|
529
|
+
clearTimeout(timer);
|
|
530
|
+
}
|
|
531
|
+
if (!Array.isArray(list)) throw new Error('members 响应不是数组');
|
|
532
|
+
const members = list
|
|
533
|
+
.filter((m) => m && typeof m.login === 'string')
|
|
534
|
+
.map((m) => ({ login: m.login, full_name: m.full_name || '', name: m.full_name || m.login }));
|
|
535
|
+
store.writeJSON(ctx.giteaMembersPath, members);
|
|
536
|
+
} catch (err) {
|
|
537
|
+
console.error('[poller] 成员缓存更新失败(不影响活动流):', (err && err.message) || err);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* #3:按 pollIntervalSec 定时调 giteaClient.pollActivities(写 activities.json + gitea-status.json),
|
|
543
|
+
* 单飞(上一轮未完成不重入);PATCH settings 改 pollIntervalSec 后经 ctx.reschedulePoller 重排。
|
|
544
|
+
* GITEA_FIXTURE 模式同样生效(fixture 模式 pollActivities 零网络)。
|
|
545
|
+
* poller 模式:'auto' = 独立版行为(自起定时器 + ctx.reschedulePoller 可重排);
|
|
546
|
+
* 'manual' = 插件态(只暴露 pollTick,由宿主 ctx.interval 驱动,SPEC-PLUGIN 1.4)。
|
|
547
|
+
*/
|
|
548
|
+
function setupPoller(ctx, mode) {
|
|
549
|
+
let giteaClient;
|
|
550
|
+
let ssrf = null;
|
|
551
|
+
try {
|
|
552
|
+
giteaClient = require('../../lib/giteaClient.js');
|
|
553
|
+
} catch (e) {
|
|
554
|
+
console.warn('[poller] giteaClient.js 缺位,轮询器未启动');
|
|
555
|
+
return { pollOnce: async () => {}, stop() {}, reschedule() {} };
|
|
556
|
+
}
|
|
557
|
+
try {
|
|
558
|
+
ssrf = require('../../lib/ssrfGuard.js');
|
|
559
|
+
} catch (e) {
|
|
560
|
+
ssrf = null;
|
|
561
|
+
}
|
|
562
|
+
// v2.9 GitHub 组织动态源(可选,enabled 时随同一轮 pollTick 拉取)
|
|
563
|
+
let githubClient = null;
|
|
564
|
+
try {
|
|
565
|
+
githubClient = require('../../lib/githubClient.js');
|
|
566
|
+
} catch (e) {
|
|
567
|
+
githubClient = null;
|
|
568
|
+
}
|
|
569
|
+
// v2.9.18 Gitee 组织动态源(可选,enabled 时随同一轮 pollTick 拉取)
|
|
570
|
+
let giteeClient = null;
|
|
571
|
+
try {
|
|
572
|
+
giteeClient = require('../../lib/giteeClient.js');
|
|
573
|
+
} catch (e) {
|
|
574
|
+
giteeClient = null;
|
|
575
|
+
}
|
|
576
|
+
// v2.9.6 数字员工日报自动档(每天 ≥08:00 首个 tick 生成昨日窗口,失败每小时重试)
|
|
577
|
+
let weeklyMod = null;
|
|
578
|
+
try {
|
|
579
|
+
weeklyMod = require('../../lib/weekly.js');
|
|
580
|
+
} catch (e) {
|
|
581
|
+
weeklyMod = null;
|
|
582
|
+
}
|
|
583
|
+
if (typeof giteaClient.pollActivities !== 'function') {
|
|
584
|
+
console.warn('[poller] giteaClient.pollActivities 不可用,轮询器未启动');
|
|
585
|
+
return { pollOnce: async () => {}, stop() {}, reschedule() {} };
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
let timer = null;
|
|
589
|
+
let polling = false;
|
|
590
|
+
|
|
591
|
+
async function pollOnce() {
|
|
592
|
+
if (polling) return; // 单飞
|
|
593
|
+
polling = true;
|
|
594
|
+
try {
|
|
595
|
+
await giteaClient.pollActivities(ctx.config);
|
|
596
|
+
// v2.9.6 日报自动档:守卫在 maybeAutoDaily 内(今日已有/未到 08:00/失败 1h 内均跳过),
|
|
597
|
+
// 引擎调用失败只记日志,绝不影响 Gitea 源与成员缓存
|
|
598
|
+
if (weeklyMod && typeof weeklyMod.maybeAutoDaily === 'function') {
|
|
599
|
+
try {
|
|
600
|
+
const r = weeklyMod.maybeAutoDaily(ctx);
|
|
601
|
+
if (r && typeof r.catch === 'function') {
|
|
602
|
+
r.catch((err) => console.error('[poller] 日报自动生成失败(下小时重试):', (err && err.message) || err));
|
|
603
|
+
}
|
|
604
|
+
} catch (err) {
|
|
605
|
+
console.error('[poller] 日报自动档异常:', (err && err.message) || err);
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
// v2.9 GitHub 源:独立 try/catch——单源失败不拖垮 Gitea 源与成员缓存(状态各落各的文件)
|
|
609
|
+
if (githubClient && ctx.config.github && ctx.config.github.enabled === true) {
|
|
610
|
+
try {
|
|
611
|
+
await githubClient.pollActivities(ctx.config);
|
|
612
|
+
} catch (err) {
|
|
613
|
+
console.error('[poller] GitHub 轮询失败(不影响 Gitea 源):', (err && err.message) || err);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
// v2.9.18 Gitee 源:独立 try/catch——单源失败不拖垮其他源(状态落 data/gitee-status.json)
|
|
617
|
+
if (giteeClient && ctx.config.gitee && ctx.config.gitee.enabled === true) {
|
|
618
|
+
try {
|
|
619
|
+
await giteeClient.pollActivities(ctx.config);
|
|
620
|
+
} catch (err) {
|
|
621
|
+
console.error('[poller] gitee 源拉取失败(不拖垮其他源):', (err && err.message) || String(err));
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
await refreshMembersCache(ctx, giteaClient, ssrf);
|
|
625
|
+
// v2.9.39 IM 每日摘要:到点/已发/次数用尽都在 maybeRunDigest 内部短路,失败只记日志
|
|
626
|
+
try {
|
|
627
|
+
const r = require('../../lib/imNotify.js').maybeRunDigest(ctx);
|
|
628
|
+
if (r && typeof r.catch === 'function') {
|
|
629
|
+
r.catch((err) => console.error('[poller] IM 摘要失败(不影响其他源):', (err && err.message) || err));
|
|
630
|
+
}
|
|
631
|
+
} catch (err) {
|
|
632
|
+
console.error('[poller] IM 摘要异常:', (err && err.message) || err);
|
|
633
|
+
}
|
|
634
|
+
// v2.9.41 每日自动备份(默认开启,纯本地拷贝;到点且当日未跑才跑,失败只记日志)
|
|
635
|
+
try {
|
|
636
|
+
const bk = require('../../lib/backup.js').maybeDailyBackup(ctx);
|
|
637
|
+
if (bk && bk.ran) console.log(`[backup] 自动备份完成:${path.basename(bk.dir)}(清理 ${bk.pruned} 份)`);
|
|
638
|
+
} catch (err) {
|
|
639
|
+
console.error('[poller] 自动备份失败(数据未改动):', (err && err.message) || err);
|
|
640
|
+
}
|
|
641
|
+
} catch (err) {
|
|
642
|
+
// pollActivities 失败时已自行写 gitea-status.json(ok:false),这里只记日志
|
|
643
|
+
console.error('[poller] 轮询失败:', (err && err.message) || err);
|
|
644
|
+
} finally {
|
|
645
|
+
polling = false;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function reschedule(intervalSec) {
|
|
650
|
+
if (timer) {
|
|
651
|
+
clearInterval(timer);
|
|
652
|
+
timer = null;
|
|
653
|
+
}
|
|
654
|
+
const sec = Number(intervalSec);
|
|
655
|
+
if (!Number.isFinite(sec) || sec <= 0) {
|
|
656
|
+
console.warn('[poller] pollIntervalSec 非法,轮询器停止');
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
timer = setInterval(() => {
|
|
660
|
+
pollOnce().catch(() => {});
|
|
661
|
+
}, sec * 1000);
|
|
662
|
+
timer.unref();
|
|
663
|
+
console.log(`[poller] 已启动:间隔 ${sec}s,GITEA_FIXTURE=${process.env.GITEA_FIXTURE ? 'on' : 'off'}`);
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function stop() {
|
|
667
|
+
if (timer) {
|
|
668
|
+
clearInterval(timer);
|
|
669
|
+
timer = null;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
if (mode === 'auto') {
|
|
674
|
+
ctx.reschedulePoller = reschedule;
|
|
675
|
+
const initialSec = Number(ctx.config.gitea.pollIntervalSec);
|
|
676
|
+
if (Number.isFinite(initialSec) && initialSec > 0) {
|
|
677
|
+
reschedule(initialSec);
|
|
678
|
+
pollOnce().catch(() => {}); // 首轮立即拉取(不阻塞监听)
|
|
679
|
+
} else {
|
|
680
|
+
console.log('[poller] pollIntervalSec<=0,轮询器未启动(可经 PATCH /api/settings 开启)');
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
return { pollOnce, stop, reschedule };
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// ---------- mock 传输层(真端口用例的进程内迁移底座) ----------
|
|
687
|
+
|
|
688
|
+
/** IncomingMessage 最小面:router.readBody / rawBody handler / adapter 够用 */
|
|
689
|
+
function createMockReq({ method = 'GET', url = '/', headers = {}, body } = {}) {
|
|
690
|
+
const h = {};
|
|
691
|
+
for (const [k, v] of Object.entries(headers || {})) {
|
|
692
|
+
if (v !== undefined && v !== null) h[String(k).toLowerCase()] = String(v);
|
|
693
|
+
}
|
|
694
|
+
const chunks = [];
|
|
695
|
+
if (body !== undefined && body !== null && body !== '') {
|
|
696
|
+
const buf = Buffer.isBuffer(body) ? body : Buffer.from(String(body));
|
|
697
|
+
chunks.push(buf);
|
|
698
|
+
// 真实 fetch/http 客户端自动携带 Content-Length;router 的「有体才校验 Content-Type」
|
|
699
|
+
// CSRF 防线依赖该头判定 hasBody,mock 必须同形
|
|
700
|
+
if (h['content-length'] === undefined) h['content-length'] = String(buf.length);
|
|
701
|
+
}
|
|
702
|
+
let ended = false;
|
|
703
|
+
const endCbs = [];
|
|
704
|
+
const errorCbs = [];
|
|
705
|
+
const req = {
|
|
706
|
+
method: String(method).toUpperCase(),
|
|
707
|
+
url,
|
|
708
|
+
headers: h,
|
|
709
|
+
statusCode: null,
|
|
710
|
+
aborted: false,
|
|
711
|
+
destroyed: false,
|
|
712
|
+
socket: { remoteAddress: '127.0.0.1', remotePort: 0 },
|
|
713
|
+
_isMockReq: true,
|
|
714
|
+
on(ev, cb) {
|
|
715
|
+
const e = String(ev);
|
|
716
|
+
if (e === 'data') {
|
|
717
|
+
if (!ended) {
|
|
718
|
+
for (const ch of chunks.splice(0)) cb(ch);
|
|
719
|
+
}
|
|
720
|
+
} else if (e === 'end') {
|
|
721
|
+
if (ended) queueMicrotask(cb);
|
|
722
|
+
else endCbs.push(cb);
|
|
723
|
+
} else if (e === 'error') {
|
|
724
|
+
errorCbs.push(cb);
|
|
725
|
+
}
|
|
726
|
+
return req;
|
|
727
|
+
},
|
|
728
|
+
once(ev, cb) {
|
|
729
|
+
return req.on(ev, cb);
|
|
730
|
+
},
|
|
731
|
+
destroy(err) {
|
|
732
|
+
req.destroyed = true;
|
|
733
|
+
req.aborted = true;
|
|
734
|
+
if (err) {
|
|
735
|
+
for (const cb of errorCbs.splice(0)) cb(err);
|
|
736
|
+
}
|
|
737
|
+
return req;
|
|
738
|
+
},
|
|
739
|
+
resume() {},
|
|
740
|
+
};
|
|
741
|
+
process.nextTick(() => {
|
|
742
|
+
ended = true;
|
|
743
|
+
for (const cb of endCbs.splice(0)) cb();
|
|
744
|
+
});
|
|
745
|
+
return req;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** ServerResponse 最小面:writeHead/setHeader/end/statusCode/headersSent/finish */
|
|
749
|
+
function createMockRes() {
|
|
750
|
+
const headers = Object.create(null);
|
|
751
|
+
const chunks = [];
|
|
752
|
+
const res = {
|
|
753
|
+
statusCode: 200,
|
|
754
|
+
headersSent: false,
|
|
755
|
+
finished: false,
|
|
756
|
+
_isMockRes: true,
|
|
757
|
+
setHeader(k, v) {
|
|
758
|
+
headers[String(k).toLowerCase()] = String(v);
|
|
759
|
+
},
|
|
760
|
+
getHeader(k) {
|
|
761
|
+
return headers[String(k).toLowerCase()];
|
|
762
|
+
},
|
|
763
|
+
removeHeader(k) {
|
|
764
|
+
delete headers[String(k).toLowerCase()];
|
|
765
|
+
},
|
|
766
|
+
writeHead(status, head) {
|
|
767
|
+
if (res.headersSent) throw new Error('Cannot set headers after they are sent to the client');
|
|
768
|
+
res.statusCode = status;
|
|
769
|
+
if (head) {
|
|
770
|
+
for (const [k, v] of Object.entries(head)) headers[String(k).toLowerCase()] = String(v);
|
|
771
|
+
}
|
|
772
|
+
res.headersSent = true;
|
|
773
|
+
return res;
|
|
774
|
+
},
|
|
775
|
+
write(chunk) {
|
|
776
|
+
if (chunk) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
|
|
777
|
+
return true;
|
|
778
|
+
},
|
|
779
|
+
end(body) {
|
|
780
|
+
if (body) chunks.push(Buffer.isBuffer(body) ? body : Buffer.from(String(body)));
|
|
781
|
+
if (!res.headersSent) res.headersSent = true;
|
|
782
|
+
if (!res.finished) {
|
|
783
|
+
res.finished = true;
|
|
784
|
+
for (const cb of finishCbs.splice(0)) cb();
|
|
785
|
+
}
|
|
786
|
+
return res;
|
|
787
|
+
},
|
|
788
|
+
destroy() {},
|
|
789
|
+
on(ev, cb) {
|
|
790
|
+
if (String(ev) === 'finish' && res.finished) cb();
|
|
791
|
+
else if (String(ev) === 'finish') finishCbs.push(cb);
|
|
792
|
+
return res;
|
|
793
|
+
},
|
|
794
|
+
once(ev, cb) {
|
|
795
|
+
return res.on(ev, cb);
|
|
796
|
+
},
|
|
797
|
+
get raw() {
|
|
798
|
+
return { headers, chunks };
|
|
799
|
+
},
|
|
800
|
+
get text() {
|
|
801
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
802
|
+
},
|
|
803
|
+
};
|
|
804
|
+
const finishCbs = [];
|
|
805
|
+
return res;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// ---------- buildApp ----------
|
|
809
|
+
|
|
810
|
+
function buildApp(options) {
|
|
811
|
+
const opts = options || {};
|
|
812
|
+
const rootDir = opts.rootDir ? path.resolve(opts.rootDir) : path.resolve(__dirname, '..', '..');
|
|
813
|
+
let configPath = opts.configPath ? path.resolve(opts.configPath) : null;
|
|
814
|
+
const configDir = opts.configDir ? path.resolve(opts.configDir) : configPath ? path.dirname(configPath) : rootDir;
|
|
815
|
+
if (!configPath) configPath = path.join(configDir, 'config.json');
|
|
816
|
+
|
|
817
|
+
// ---- 启动期校验(§5):与旧 server.js 逐条同构,以 throw 代替 process.exit(2) ----
|
|
818
|
+
// 配置一律经 configPath 从磁盘加载(与 server.js --config 同路径,PATCH 写回落同一文件)
|
|
819
|
+
const config = store.loadOrCreateConfig(configPath);
|
|
820
|
+
if (config.host !== '127.0.0.1' && config.host !== '0.0.0.0') {
|
|
821
|
+
throw new Error(`host 仅接受 127.0.0.1/0.0.0.0(与宿主 webServer 配置同源),当前为 "${config.host}"(独立版退出码 2 语义)`);
|
|
822
|
+
}
|
|
823
|
+
if (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535) {
|
|
824
|
+
throw new Error(`port 非法: ${config.port}`);
|
|
825
|
+
}
|
|
826
|
+
for (const entry of config.gitea.hostWhitelist || []) {
|
|
827
|
+
const bad = settingsMod.forbiddenWhitelistEntry(entry);
|
|
828
|
+
if (bad) {
|
|
829
|
+
throw new Error(`hostWhitelist 含禁止项 "${entry}"(${bad}),启动即拒绝`);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
// 任务雷达:钉钉域白名单同一红线(localhost/IP 字面量启动即拒,PRD §4 + SPEC §5-②)
|
|
833
|
+
try {
|
|
834
|
+
require('../../lib/ssrfGuard.js').validateWhitelistEntries(config.dingtalk.hostWhitelist || []);
|
|
835
|
+
} catch (e) {
|
|
836
|
+
throw new Error(`dingtalk.hostWhitelist 体检失败: ${e.message}`);
|
|
837
|
+
}
|
|
838
|
+
// 飞书妙记通道:hostWhitelist 同一红线(与 dingtalk 同款启动即拒)
|
|
839
|
+
try {
|
|
840
|
+
require('../../lib/ssrfGuard.js').validateWhitelistEntries(config.feishu.hostWhitelist || []);
|
|
841
|
+
} catch (e) {
|
|
842
|
+
throw new Error(`feishu.hostWhitelist 体检失败: ${e.message}`);
|
|
843
|
+
}
|
|
844
|
+
// security.trustedHosts(插件态 Host 防线 allowlist 扩展,SPEC-PLUGIN 2.5):字符串数组
|
|
845
|
+
const trustedHosts = (config.security && config.security.trustedHosts) || [];
|
|
846
|
+
if (!Array.isArray(trustedHosts) || trustedHosts.some((x) => typeof x !== 'string')) {
|
|
847
|
+
throw new Error('security.trustedHosts 必须为字符串数组');
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
const absDir = (d) => (path.isAbsolute(d) ? d : path.join(configDir, d));
|
|
851
|
+
// #6:dataDir/webDir 在装配侧归一化为绝对路径后整体注入(含传给 gitea 模块的 config provider),
|
|
852
|
+
// 使 giteaClient/routes-gitea 的路径解析与主服务完全一致,PROJECT_ROOT 兜底不再触发
|
|
853
|
+
//(v2.2:gateway.logDir 归一化已随 网关集成移除)
|
|
854
|
+
config.dataDir = absDir(config.dataDir);
|
|
855
|
+
config.webDir = absDir(config.webDir);
|
|
856
|
+
const dataDir = config.dataDir;
|
|
857
|
+
|
|
858
|
+
const ctx = {
|
|
859
|
+
config,
|
|
860
|
+
configPath,
|
|
861
|
+
rootDir,
|
|
862
|
+
dataDir,
|
|
863
|
+
webDir: config.webDir,
|
|
864
|
+
agentsPath: path.join(configDir, 'agents.json'),
|
|
865
|
+
membersPath: path.join(configDir, 'members.json'),
|
|
866
|
+
tasksPath: path.join(dataDir, 'tasks.json'),
|
|
867
|
+
// v2.3:sessionsPath 已随会话登记表退役移除(数据层收口,规格 §6)
|
|
868
|
+
activitiesPath: path.join(dataDir, 'activities.json'),
|
|
869
|
+
giteaStatusPath: path.join(dataDir, 'gitea-status.json'),
|
|
870
|
+
giteaMembersPath: path.join(dataDir, 'gitea-members.json'),
|
|
871
|
+
messagesPath: path.join(dataDir, 'messages.json'),
|
|
872
|
+
inboxPath: path.join(dataDir, 'inbox.json'),
|
|
873
|
+
taskEventsPath: path.join(dataDir, 'task_events.json'),
|
|
874
|
+
diaryPath: path.join(dataDir, 'diary.json'), // v2.7 任务日报(唯一键 taskId+date)
|
|
875
|
+
version: VERSION,
|
|
876
|
+
startedAt: Date.now(),
|
|
877
|
+
adapters: opts.adapters, // 测试注入缝(v2.9.14):桌面源适配器覆盖 { id: fn },prod 恒 undefined
|
|
878
|
+
// v2.9.47 宿主 LLM 服务(插件态由 plugin/index.mjs 注入;测试可注入假实现):
|
|
879
|
+
// 有它就用宿主默认模型(桌面端正在用的那个),没有则 lib/learn 回落 spawn 引擎
|
|
880
|
+
llm: opts.llm || null,
|
|
881
|
+
agentDefaultModel: opts.agentDefaultModel || null,
|
|
882
|
+
};
|
|
883
|
+
|
|
884
|
+
store.loadOrCreateAgentsFile(ctx.agentsPath);
|
|
885
|
+
|
|
886
|
+
// #10:把 config.security.redactKeys 同步给 redact 层,日志/错误出口统一脱敏
|
|
887
|
+
try {
|
|
888
|
+
require('../../lib/redact.js').setRedactKeys(config.security.redactKeys || []);
|
|
889
|
+
} catch (e) {
|
|
890
|
+
console.warn('[security] redact.js 缺位,redactKeys 同步跳过');
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
// 路由装配
|
|
894
|
+
const router = new Router();
|
|
895
|
+
router.add('GET', '/api/health', (c) => {
|
|
896
|
+
sendJSON(c.res, 200, {
|
|
897
|
+
ok: true,
|
|
898
|
+
version: VERSION,
|
|
899
|
+
uptimeSec: Math.floor((Date.now() - ctx.startedAt) / 1000),
|
|
900
|
+
});
|
|
901
|
+
});
|
|
902
|
+
registerTaskRoutes(router, ctx);
|
|
903
|
+
// v2.9.24 会话归因建议:GET /api/tasks/:id/session-suggestions(排序候选,人工确认挂接)
|
|
904
|
+
sessionSuggestMod.registerSessionSuggestRoute(router, ctx);
|
|
905
|
+
// v2.7 任务日报:GET/PUT /api/tasks/:id/diary、DELETE :date、GET prefill(内部先注册 prefill 再注册 :date)
|
|
906
|
+
diaryMod.registerDiaryRoutes(router, ctx);
|
|
907
|
+
registerColumnRoutes(router, ctx);
|
|
908
|
+
registerAgentRoutes(router, ctx);
|
|
909
|
+
membersMod.registerMemberRoutes(router, ctx);
|
|
910
|
+
// v2.3:会话登记表退役(GET /api/sessions + POST /api/sessions/:id/stop 已删,规格 §6)
|
|
911
|
+
overviewMod.registerOverviewRoutes(router, ctx);
|
|
912
|
+
settingsMod.registerSettingsRoutes(router, ctx);
|
|
913
|
+
// 智能体工作观测(v2.2):四源适配器聚合端点,GET /api/agent-activity(?agent= 过滤)
|
|
914
|
+
require('../../lib/agentActivity').registerAgentActivityRoutes(router, ctx);
|
|
915
|
+
// v2.3 会话阅读器:GET /api/agent-sessions + GET /api/agent-session(六源归一化)
|
|
916
|
+
agentTranscriptMod.registerAgentSessionRoutes(router, ctx);
|
|
917
|
+
// v2.9.23 工作搜索:GET /api/work-search?q=(任务/会话/提交/日报四组聚合,Ctrl+K 后端)
|
|
918
|
+
workSearchMod.registerWorkSearchRoute(router, ctx);
|
|
919
|
+
// v2.9.26 Agent 时间线热力图:GET /api/agent-heatmap(六源会话 日×agent 聚合)
|
|
920
|
+
require('../../lib/heatmap.js').registerHeatmapRoute(router, ctx);
|
|
921
|
+
// v2.9.27 Scorecard 传播卡:GET /api/scorecard/<agent>.svg(image/svg+xml)
|
|
922
|
+
require('../../lib/scorecard.js').registerScorecardRoute(router, ctx);
|
|
923
|
+
// v2.9.28 任务复盘:GET /api/tasks/:id/postmortem(done 时刻确定性蒸馏)
|
|
924
|
+
require('../../lib/postmortem.js').registerPostmortemRoute(router, ctx);
|
|
925
|
+
// v2.9.5 数字员工周报:会话数据聚合 → harness 引擎蒸馏(POST generate / GET job / GET weekly)
|
|
926
|
+
require('../../lib/weekly.js').registerWeeklyRoutes(router, ctx);
|
|
927
|
+
// v2.2:会话网关可观测端点(/api/gateway/*)已随 网关集成整体移除
|
|
928
|
+
// 环境体检聚合端点(分发部署自检):GET /api/setup/check 五项(node/dws/dsh/llmRoute/gitea)
|
|
929
|
+
setupRoutesMod.registerSetupRoutes(router, ctx);
|
|
930
|
+
// v2.9.39 IM 通知(飞书/钉钉自定义机器人):POST /api/im/test 通道测试(保存前先验)
|
|
931
|
+
require('../../lib/imNotify.js').registerImRoutes(router, ctx);
|
|
932
|
+
// v2.9.41 数据备份:GET /api/backup/list · POST /api/backup/now · POST /api/backup/restore
|
|
933
|
+
require('../../lib/backup.js').registerBackupRoutes(router, ctx);
|
|
934
|
+
// v2.9.44 知识库学习(只读 vault):status/today/scan/items/session 系列
|
|
935
|
+
require('../../lib/learn.js').registerLearnRoutes(router, ctx);
|
|
936
|
+
mountGiteaRoutes(router, ctx);
|
|
937
|
+
// 任务雷达(PRD-task-inbox):采集器 + AI 拆解 + 收件箱
|
|
938
|
+
try {
|
|
939
|
+
require('../../lib/dingtalk.js').registerRadarRoutes(router, ctx);
|
|
940
|
+
require('../../lib/feishu.js').registerFeishuRoutes(router, ctx);
|
|
941
|
+
require('../../lib/analyze.js').registerAnalyzeRoutes(router, ctx);
|
|
942
|
+
require('../../lib/inbox.js').registerInboxRoutes(router, ctx);
|
|
943
|
+
} catch (e) {
|
|
944
|
+
console.error('[radar] 雷达路由挂载失败:', e.message);
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// ---- env 注入(独立版「子进程 env」的进程内等价物) ----
|
|
948
|
+
const envMap = opts.env && typeof opts.env === 'object' ? opts.env : null;
|
|
949
|
+
const envKeys = envMap ? Object.keys(envMap) : [];
|
|
950
|
+
const savedEnv = new Map();
|
|
951
|
+
|
|
952
|
+
function applyEnv() {
|
|
953
|
+
if (!envMap) return;
|
|
954
|
+
for (const k of envKeys) {
|
|
955
|
+
if (!savedEnv.has(k)) savedEnv.set(k, process.env[k]);
|
|
956
|
+
const v = envMap[k];
|
|
957
|
+
if (v === null || v === undefined) delete process.env[k];
|
|
958
|
+
else process.env[k] = String(v);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
function restoreEnv() {
|
|
963
|
+
for (const [k, v] of savedEnv) {
|
|
964
|
+
if (v === undefined) delete process.env[k];
|
|
965
|
+
else process.env[k] = v;
|
|
966
|
+
}
|
|
967
|
+
savedEnv.clear();
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
// persistentEnv(radar 系/轮询器子实例):后台 job 与定时器在响应之后继续执行并读 env,
|
|
971
|
+
// 分发期临时注入不够——必须在 setupPoller(首轮 pollOnce)之前写入,close 还原
|
|
972
|
+
//(node --test 每文件独立进程,泄露面=本文件)
|
|
973
|
+
if (envMap && opts.persistentEnv) applyEnv();
|
|
974
|
+
|
|
975
|
+
const pollerMode = opts.poller === 'manual' ? 'manual' : 'auto';
|
|
976
|
+
const poller = setupPoller(ctx, pollerMode);
|
|
977
|
+
|
|
978
|
+
// ---- 边界管线(与旧 server.js http 层逐行同构) ----
|
|
979
|
+
function handle(req, res) {
|
|
980
|
+
const host = req.headers.host || '';
|
|
981
|
+
if (host !== `127.0.0.1:${config.port}`) {
|
|
982
|
+
return sendError(res, 403, 'HOST_FORBIDDEN', `Host 头必须为 127.0.0.1:${config.port}`);
|
|
983
|
+
}
|
|
984
|
+
// CSRF 防线②:浏览器发出的跨站请求自带 Sec-Fetch-Site,非 same-origin/none 一律 403;
|
|
985
|
+
// curl 等非浏览器客户端无此头,不受影响
|
|
986
|
+
const sfs = req.headers['sec-fetch-site'];
|
|
987
|
+
if (sfs !== undefined) {
|
|
988
|
+
const v = String(sfs).trim().toLowerCase();
|
|
989
|
+
if (v !== 'same-origin' && v !== 'none') {
|
|
990
|
+
return sendError(res, 403, 'CSRF_REJECTED', `跨站请求被拒绝(Sec-Fetch-Site: ${v})`);
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
const pathname = (req.url || '/').split('?')[0];
|
|
994
|
+
if (pathname === '/api' || pathname.startsWith('/api/')) {
|
|
995
|
+
return router.dispatch(ctx, req, res);
|
|
996
|
+
}
|
|
997
|
+
return serveStatic(ctx, req, res, req.url || '/');
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
function handleApi(req, res) {
|
|
1001
|
+
return router.dispatch(ctx, req, res);
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
function handleStatic(req, res) {
|
|
1005
|
+
return serveStatic(ctx, req, res, req.url || '/');
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// ---- 进程内 fetch:与 http 层同一条 handle 管线 ----
|
|
1009
|
+
async function appFetch(method, p, requestOptions) {
|
|
1010
|
+
const o = requestOptions || {};
|
|
1011
|
+
const headers = Object.assign({}, o.headers || {});
|
|
1012
|
+
if (!Object.keys(headers).some((k) => k.toLowerCase() === 'host')) {
|
|
1013
|
+
headers.host = `127.0.0.1:${config.port}`;
|
|
1014
|
+
}
|
|
1015
|
+
const res = createMockRes();
|
|
1016
|
+
const req = createMockReq({ method, url: p, headers, body: o.body });
|
|
1017
|
+
const dispatch = () => handle(req, res);
|
|
1018
|
+
if (envMap && !opts.persistentEnv && envKeys.length > 0) {
|
|
1019
|
+
applyEnv();
|
|
1020
|
+
try {
|
|
1021
|
+
await dispatch();
|
|
1022
|
+
} finally {
|
|
1023
|
+
restoreEnv();
|
|
1024
|
+
}
|
|
1025
|
+
} else {
|
|
1026
|
+
await dispatch();
|
|
1027
|
+
}
|
|
1028
|
+
const text = res.text;
|
|
1029
|
+
let json = null;
|
|
1030
|
+
try {
|
|
1031
|
+
json = text ? JSON.parse(text) : null;
|
|
1032
|
+
} catch (e) {
|
|
1033
|
+
json = null;
|
|
1034
|
+
}
|
|
1035
|
+
return {
|
|
1036
|
+
status: res.statusCode,
|
|
1037
|
+
ok: res.statusCode >= 200 && res.statusCode < 300,
|
|
1038
|
+
headers: {
|
|
1039
|
+
get(name) {
|
|
1040
|
+
const got = res.raw.headers[String(name).toLowerCase()];
|
|
1041
|
+
return got === undefined ? null : got;
|
|
1042
|
+
},
|
|
1043
|
+
},
|
|
1044
|
+
text,
|
|
1045
|
+
body: json,
|
|
1046
|
+
json: () => Promise.resolve(json),
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
const app = {
|
|
1051
|
+
ctx,
|
|
1052
|
+
router,
|
|
1053
|
+
config,
|
|
1054
|
+
configPath,
|
|
1055
|
+
version: VERSION,
|
|
1056
|
+
handle,
|
|
1057
|
+
handleApi,
|
|
1058
|
+
handleStatic,
|
|
1059
|
+
fetch: appFetch,
|
|
1060
|
+
pollTick: () => poller.pollOnce(),
|
|
1061
|
+
reschedulePoller: (sec) => poller.reschedule(sec),
|
|
1062
|
+
close() {
|
|
1063
|
+
poller.stop();
|
|
1064
|
+
if (envMap && opts.persistentEnv) restoreEnv();
|
|
1065
|
+
},
|
|
1066
|
+
};
|
|
1067
|
+
return app;
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
module.exports = {
|
|
1071
|
+
VERSION,
|
|
1072
|
+
buildApp,
|
|
1073
|
+
createMockReq,
|
|
1074
|
+
createMockRes,
|
|
1075
|
+
registerTaskRoutes,
|
|
1076
|
+
registerColumnRoutes,
|
|
1077
|
+
registerAgentRoutes,
|
|
1078
|
+
};
|