lemma-agent 0.0.0-stage → 1.0.1
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/README.md +140 -2
- package/bin/lemma.mjs +60 -0
- package/dist/acceptance.js +63 -0
- package/dist/admin.js +1482 -0
- package/dist/agents.js +245 -0
- package/dist/api-member.js +537 -0
- package/dist/app.js +161 -0
- package/dist/board.js +185 -0
- package/dist/business-tools.js +153 -0
- package/dist/change-ops.js +91 -0
- package/dist/changes.js +46 -0
- package/dist/cli-runner.js +106 -0
- package/dist/code-tools.js +396 -0
- package/dist/coding-benchmark-fixtures.js +1049 -0
- package/dist/coding-benchmark-suite.js +1252 -0
- package/dist/collaboration-benchmark.js +349 -0
- package/dist/config.js +392 -0
- package/dist/context-benchmark.js +91 -0
- package/dist/conventions.js +282 -0
- package/dist/conversation.js +39 -0
- package/dist/credentials.js +44 -0
- package/dist/deliverables.js +43 -0
- package/dist/digest.js +129 -0
- package/dist/dispatch.js +801 -0
- package/dist/execution-settings.js +24 -0
- package/dist/git-workbench.js +800 -0
- package/dist/git.js +149 -0
- package/dist/integration-git.js +108 -0
- package/dist/integrations.js +557 -0
- package/dist/jobs.js +100 -0
- package/dist/lead.js +263 -0
- package/dist/learning.js +36 -0
- package/dist/main.js +1459 -0
- package/dist/mcp-settings.js +45 -0
- package/dist/mcp-tools.js +102 -0
- package/dist/member-settings.js +245 -0
- package/dist/model-selection.js +48 -0
- package/dist/models.js +145 -0
- package/dist/native-selectors.js +45 -0
- package/dist/native-terminal-components.js +100 -0
- package/dist/ood-benchmark.js +660 -0
- package/dist/operations.js +21 -0
- package/dist/printer.js +113 -0
- package/dist/projects.js +282 -0
- package/dist/repair.js +102 -0
- package/dist/resources.js +31 -0
- package/dist/result-summary.js +8 -0
- package/dist/results.js +41 -0
- package/dist/scope.js +114 -0
- package/dist/sessions.js +95 -0
- package/dist/settings.js +32 -0
- package/dist/task-commands.js +37 -0
- package/dist/task-lifecycle.js +49 -0
- package/dist/task-readiness.js +22 -0
- package/dist/task-recovery.js +116 -0
- package/dist/task-review.js +70 -0
- package/dist/task-workflow.js +424 -0
- package/dist/terminal-layout.js +27 -0
- package/dist/terminal-state.js +145 -0
- package/dist/terminal.js +800 -0
- package/dist/tool-settings.js +111 -0
- package/dist/tools.js +1043 -0
- package/dist/ux-telemetry.js +127 -0
- package/dist/view.js +114 -0
- package/package.json +80 -6
- package/web/index.html +136 -0
- package/web/js/conversations.js +312 -0
- package/web/js/dag.js +495 -0
- package/web/js/drawer.js +139 -0
- package/web/js/editors.js +424 -0
- package/web/js/gitlens.js +844 -0
- package/web/js/main.js +152 -0
- package/web/js/sankey.js +476 -0
- package/web/js/store.js +291 -0
- package/web/js/ticket.js +151 -0
- package/web/js/timeline.js +183 -0
- package/web/js/topology.js +454 -0
- package/web/js/util.js +232 -0
- package/web/js/views.js +1496 -0
- package/web/style.css +5299 -0
package/dist/admin.js
ADDED
|
@@ -0,0 +1,1482 @@
|
|
|
1
|
+
// 后台管理网页:嵌在终端进程里,和终端共用同一个 Harness,所以终端里的每一步都能实时看到。
|
|
2
|
+
// 网页只看 + 控制(中止本轮、开始新上下文),任务只从终端下发。
|
|
3
|
+
// 只监听 127.0.0.1:这个进程能驱动 agent 改文件、执行命令,绝不能暴露给局域网。
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { extname, join, normalize } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { agentAdapter } from "./agents.js";
|
|
10
|
+
import { memberKey, memberToolNames } from "./api-member.js";
|
|
11
|
+
import { applyChange, cleanChanges, dropChange } from "./change-ops.js";
|
|
12
|
+
import { commitManagedRepo, fetchManagedRepo, GitWorkbench, inspectRepoCommit, inspectRepoGraph, listManagedRepos, pullManagedRepo, pushManagedRepo, resolvePushGate, setGitPushPolicy, } from "./git-workbench.js";
|
|
13
|
+
import { Operations, operationList, resolveOperation } from "./operations.js";
|
|
14
|
+
import { CostLedger, Resources, resourceSnapshot } from "./resources.js";
|
|
15
|
+
import { applyApiMemberDraft, applyAutonomyDraft, applyLimitsDraft, applyOrchestratorDraft, applyQuickMemberDraft } from "./member-settings.js";
|
|
16
|
+
import { Board, boardTasks } from "./board.js";
|
|
17
|
+
import { readConvention, scanConventions } from "./conventions.js";
|
|
18
|
+
import { diffText } from "./git.js";
|
|
19
|
+
import { Jobs } from "./jobs.js";
|
|
20
|
+
import { LEAD_TOOL } from "./lead.js";
|
|
21
|
+
import { editSettings } from "./settings.js";
|
|
22
|
+
import { prepareRecovery } from "./task-recovery.js";
|
|
23
|
+
import { AgentSessions, RunBudget } from "./tools.js";
|
|
24
|
+
import { UxTelemetry, appendUxEvent, computeUxMetrics } from "./ux-telemetry.js";
|
|
25
|
+
import { Learning } from "./learning.js";
|
|
26
|
+
import { Integrations, integrationSummary } from "./integrations.js";
|
|
27
|
+
import { readyTasks } from "./task-readiness.js";
|
|
28
|
+
import { Workflow } from "./task-workflow.js";
|
|
29
|
+
import { parseToolResult, toViewItem, toViewLive } from "./view.js";
|
|
30
|
+
const WEB_DIR = fileURLToPath(new URL("../web/", import.meta.url));
|
|
31
|
+
const HOST = "127.0.0.1";
|
|
32
|
+
const RESUME_COMMAND = {
|
|
33
|
+
claude: (id) => `claude --resume ${id}`,
|
|
34
|
+
codex: (id) => `codex resume ${id}`,
|
|
35
|
+
gemini: (id) => `gemini --resume ${id}`,
|
|
36
|
+
deepseek: () => "(Pi 子对话,由 Lemma 续接)",
|
|
37
|
+
};
|
|
38
|
+
function hostOf(url) {
|
|
39
|
+
try {
|
|
40
|
+
return new URL(url).host;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return url;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const MIME = {
|
|
47
|
+
".html": "text/html; charset=utf-8",
|
|
48
|
+
".css": "text/css; charset=utf-8",
|
|
49
|
+
".js": "text/javascript; charset=utf-8",
|
|
50
|
+
".svg": "image/svg+xml",
|
|
51
|
+
};
|
|
52
|
+
export async function startAdmin(options) {
|
|
53
|
+
const startedAt = Date.now();
|
|
54
|
+
let port = options.port;
|
|
55
|
+
let binding;
|
|
56
|
+
let closing = false;
|
|
57
|
+
let operations = Promise.resolve();
|
|
58
|
+
let closed;
|
|
59
|
+
const server = createServer((req, res) => {
|
|
60
|
+
// 请求开始时固定绑定,await 期间不会误读另一个会话。
|
|
61
|
+
const current = binding;
|
|
62
|
+
if (!current || closing) {
|
|
63
|
+
res.writeHead(503, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
64
|
+
res.end(JSON.stringify({ error: "后台正在切换或关闭,请稍后重试" }));
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
void current.handle(req, res).catch((error) => {
|
|
68
|
+
if (res.destroyed || res.writableEnded)
|
|
69
|
+
return;
|
|
70
|
+
if (!res.headersSent)
|
|
71
|
+
res.writeHead(500, { "content-type": "application/json; charset=utf-8" });
|
|
72
|
+
res.end(JSON.stringify({ error: error instanceof Error ? error.message : String(error) }));
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
try {
|
|
76
|
+
for (let attempt = 0;; attempt++) {
|
|
77
|
+
try {
|
|
78
|
+
await new Promise((resolve, reject) => {
|
|
79
|
+
server.once("error", reject);
|
|
80
|
+
server.listen(port, HOST, () => { server.off("error", reject); resolve(); });
|
|
81
|
+
});
|
|
82
|
+
port = server.address().port;
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (error?.code !== "EADDRINUSE" || attempt >= 9)
|
|
87
|
+
throw error;
|
|
88
|
+
port++;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
binding = await createAdminBinding({ ...options, port }, startedAt);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
server.closeAllConnections();
|
|
95
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
url: "http://" + HOST + ":" + port,
|
|
100
|
+
rebind(nextOptions) {
|
|
101
|
+
if (closing)
|
|
102
|
+
return Promise.reject(new Error("后台已关闭,不能切换会话"));
|
|
103
|
+
const operation = operations.then(async () => {
|
|
104
|
+
if (closing)
|
|
105
|
+
throw new Error("后台已关闭,不能切换会话");
|
|
106
|
+
// 先准备新视图,失败时保留旧绑定。
|
|
107
|
+
const next = await createAdminBinding({ ...nextOptions, port }, startedAt);
|
|
108
|
+
if (closing) {
|
|
109
|
+
await next.dispose();
|
|
110
|
+
throw new Error("后台正在关闭");
|
|
111
|
+
}
|
|
112
|
+
const previous = binding;
|
|
113
|
+
binding = next;
|
|
114
|
+
await previous?.dispose();
|
|
115
|
+
});
|
|
116
|
+
operations = operation.catch(() => { });
|
|
117
|
+
return operation;
|
|
118
|
+
},
|
|
119
|
+
close() {
|
|
120
|
+
if (closed)
|
|
121
|
+
return closed;
|
|
122
|
+
closing = true;
|
|
123
|
+
closed = operations.then(async () => {
|
|
124
|
+
await binding?.dispose();
|
|
125
|
+
binding = undefined;
|
|
126
|
+
const stopped = new Promise((resolve) => server.close(() => resolve()));
|
|
127
|
+
server.closeAllConnections();
|
|
128
|
+
await stopped;
|
|
129
|
+
});
|
|
130
|
+
return closed;
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
async function createAdminBinding(options, startedAt) {
|
|
135
|
+
let disposed = false;
|
|
136
|
+
const cleanup = [];
|
|
137
|
+
const dispose = async () => {
|
|
138
|
+
if (disposed)
|
|
139
|
+
return;
|
|
140
|
+
disposed = true;
|
|
141
|
+
await Promise.allSettled(cleanup.map((fn) => Promise.resolve().then(fn)));
|
|
142
|
+
};
|
|
143
|
+
try {
|
|
144
|
+
const { app, config, orchestrator, context } = options;
|
|
145
|
+
const { harness, root, agents, changes, project } = app;
|
|
146
|
+
// ---------- 派工汇总:启动时扫一遍全部历史,之后随新条目增量更新 ----------
|
|
147
|
+
const dispatches = new Map(); // key -> 派工
|
|
148
|
+
const latestByCall = new Map(); // callId -> 最近一次使用它的派工 key
|
|
149
|
+
let entryCount = 0;
|
|
150
|
+
const leads = new Map();
|
|
151
|
+
const latestLeadByCall = new Map();
|
|
152
|
+
const childWatches = [];
|
|
153
|
+
cleanup.push(async () => { await Promise.allSettled(childWatches.map((watch) => watch.stop())); });
|
|
154
|
+
const attached = new Set();
|
|
155
|
+
/** lead:这条记录来自哪个子调度的子对话(总调度自己的记录不传) */
|
|
156
|
+
function ingest(entry, lead) {
|
|
157
|
+
if (!lead)
|
|
158
|
+
entryCount++;
|
|
159
|
+
const item = toViewItem(entry);
|
|
160
|
+
if (!item)
|
|
161
|
+
return;
|
|
162
|
+
const scope = lead ? `${lead}>` : "";
|
|
163
|
+
if (item.type === "assistant") {
|
|
164
|
+
for (const call of item.toolCalls) {
|
|
165
|
+
if (!lead && call.name === LEAD_TOOL) {
|
|
166
|
+
const key = `${item.id}:${call.id}`;
|
|
167
|
+
if (leads.has(key))
|
|
168
|
+
continue;
|
|
169
|
+
latestLeadByCall.set(call.id, key);
|
|
170
|
+
leads.set(key, {
|
|
171
|
+
key,
|
|
172
|
+
callId: call.id,
|
|
173
|
+
name: typeof call.args.name === "string" ? call.args.name : "子调度",
|
|
174
|
+
goal: typeof call.args.goal === "string" ? call.args.goal : "",
|
|
175
|
+
taskId: typeof call.args.task_id === "string" ? call.args.task_id : undefined,
|
|
176
|
+
at: item.at,
|
|
177
|
+
status: "open",
|
|
178
|
+
});
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
if (!call.name.startsWith("ask_"))
|
|
182
|
+
continue; // 只有派给成员的才算派工(分工表工具不算)
|
|
183
|
+
const key = `${scope}${item.id}:${call.id}`;
|
|
184
|
+
if (dispatches.has(key))
|
|
185
|
+
continue;
|
|
186
|
+
latestByCall.set(`${scope}${call.id}`, key);
|
|
187
|
+
dispatches.set(key, {
|
|
188
|
+
key,
|
|
189
|
+
...(lead ? { lead } : {}),
|
|
190
|
+
callId: call.id,
|
|
191
|
+
agent: call.name.replace(/^ask_/, ""),
|
|
192
|
+
task: typeof call.args.task === "string" ? call.args.task : JSON.stringify(call.args),
|
|
193
|
+
resume: typeof call.args.session_id === "string" ? call.args.session_id : null,
|
|
194
|
+
at: item.at,
|
|
195
|
+
entryId: item.id,
|
|
196
|
+
status: "open",
|
|
197
|
+
model: typeof call.args.model === "string" ? call.args.model : config.agents[call.name.replace(/^ask_/, "")]?.defaultModel,
|
|
198
|
+
basedOn: typeof call.args.based_on === "string" ? call.args.based_on : undefined,
|
|
199
|
+
taskId: typeof call.args.task_id === "string" ? call.args.task_id : undefined,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
else if (item.type === "tool") {
|
|
204
|
+
if (!lead && item.name === LEAD_TOOL) {
|
|
205
|
+
const l = leads.get(latestLeadByCall.get(item.callId) ?? "");
|
|
206
|
+
if (!l)
|
|
207
|
+
return;
|
|
208
|
+
const details = item.details;
|
|
209
|
+
l.status = item.isError ? (/<harness>[\s\S]*aborted/i.test(item.text) ? "aborted" : "error") : "done";
|
|
210
|
+
l.endAt = item.at;
|
|
211
|
+
if (typeof details?.dispatches === "number")
|
|
212
|
+
l.dispatches = details.dispatches;
|
|
213
|
+
if (typeof details?.conversationId === "string")
|
|
214
|
+
attachLead(l, details.conversationId);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (!item.name.startsWith("ask_"))
|
|
218
|
+
return;
|
|
219
|
+
const known = latestByCall.get(`${scope}${item.callId}`);
|
|
220
|
+
let d = known ? dispatches.get(known) : undefined;
|
|
221
|
+
if (!d) {
|
|
222
|
+
// 派工消息不在历史里(不应发生,兜底)
|
|
223
|
+
const key = `${scope}r${item.id}:${item.callId}`;
|
|
224
|
+
d = { key, ...(lead ? { lead } : {}), callId: item.callId, agent: item.name.replace(/^ask_/, ""), task: "", resume: null, status: "open" };
|
|
225
|
+
dispatches.set(key, d);
|
|
226
|
+
}
|
|
227
|
+
const details = item.details;
|
|
228
|
+
const parsed = parseToolResult(item.text, item.isError, details);
|
|
229
|
+
d.status = parsed.status;
|
|
230
|
+
d.endAt = item.at;
|
|
231
|
+
d.resultEntryId = item.id;
|
|
232
|
+
d.durationMs = parsed.durationMs;
|
|
233
|
+
d.cost = typeof details?.costUsd === "number" ? details.costUsd : parsed.cost;
|
|
234
|
+
d.sessionId = parsed.sessionId ?? undefined;
|
|
235
|
+
d.cwd = parsed.cwd;
|
|
236
|
+
d.exitCode = parsed.exitCode;
|
|
237
|
+
d.preview = parsed.body.slice(0, 280);
|
|
238
|
+
if (typeof details?.model === "string")
|
|
239
|
+
d.model = details.model;
|
|
240
|
+
d.costEstimated = details?.costEstimated === true || undefined;
|
|
241
|
+
if (typeof details?.changeId === "string")
|
|
242
|
+
d.changeId = details.changeId;
|
|
243
|
+
if (details?.readonly === true)
|
|
244
|
+
d.readonly = true;
|
|
245
|
+
if (details?.fastPath === true)
|
|
246
|
+
d.fastPath = true;
|
|
247
|
+
if (details?.escalated === true)
|
|
248
|
+
d.escalated = true;
|
|
249
|
+
// 后台派工:这条结果只是「已开工」,真正的结果在后台派工记录里(见 withJob)
|
|
250
|
+
if (typeof details?.job === "string") {
|
|
251
|
+
d.job = details.job;
|
|
252
|
+
d.status = "open";
|
|
253
|
+
d.endAt = undefined;
|
|
254
|
+
d.durationMs = undefined;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** 找到子调度的子对话后:读它已有的记录,再跟着它的新记录(派工汇总、拓扑都会算上) */
|
|
259
|
+
let onLeadActivity = () => { };
|
|
260
|
+
function attachLead(l, conversationId) {
|
|
261
|
+
l.conversationId = conversationId;
|
|
262
|
+
if (disposed || attached.has(conversationId))
|
|
263
|
+
return;
|
|
264
|
+
attached.add(conversationId);
|
|
265
|
+
void (async () => {
|
|
266
|
+
const child = await harness.conversation(Number(conversationId), context);
|
|
267
|
+
if (!child || disposed)
|
|
268
|
+
return;
|
|
269
|
+
let cursor;
|
|
270
|
+
do {
|
|
271
|
+
const page = await child.entries({ order: "ascending" }, 500, cursor, context);
|
|
272
|
+
if (disposed)
|
|
273
|
+
return;
|
|
274
|
+
for (const entry of page.items)
|
|
275
|
+
ingest(entry, l.key);
|
|
276
|
+
cursor = page.next;
|
|
277
|
+
} while (cursor);
|
|
278
|
+
const watch = await child.watch(context);
|
|
279
|
+
if (disposed) {
|
|
280
|
+
await watch.stop();
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const seenChild = new Set(watch.value.entries.map((e) => String(e.id)));
|
|
284
|
+
watch.start(async (call) => {
|
|
285
|
+
if (disposed || call.kind !== "value")
|
|
286
|
+
return;
|
|
287
|
+
let fresh = false;
|
|
288
|
+
for (const entry of call.value.entries) {
|
|
289
|
+
if (seenChild.has(String(entry.id)))
|
|
290
|
+
continue;
|
|
291
|
+
seenChild.add(String(entry.id));
|
|
292
|
+
ingest(entry, l.key);
|
|
293
|
+
fresh = true;
|
|
294
|
+
}
|
|
295
|
+
if (fresh)
|
|
296
|
+
onLeadActivity();
|
|
297
|
+
});
|
|
298
|
+
childWatches.push(watch);
|
|
299
|
+
onLeadActivity();
|
|
300
|
+
})().catch(() => { });
|
|
301
|
+
}
|
|
302
|
+
// ---------- 后台派工:Pi Durable 文档里的记录,叠加到派工汇总上 ----------
|
|
303
|
+
let jobs = {};
|
|
304
|
+
async function refreshJobs() {
|
|
305
|
+
jobs = (await harness.snapshot(Jobs, context))?.jobs ?? {};
|
|
306
|
+
}
|
|
307
|
+
await refreshJobs();
|
|
308
|
+
/** 后台派工以后台记录为准(状态、会话、花费、结束时间) */
|
|
309
|
+
function withJob(d) {
|
|
310
|
+
const j = d.job ? jobs[d.job] : undefined;
|
|
311
|
+
if (!j)
|
|
312
|
+
return d;
|
|
313
|
+
const status = j.status === "running" ? "open" : j.status === "done" ? "done" : j.status === "failed" ? "error" : "aborted";
|
|
314
|
+
return {
|
|
315
|
+
...d,
|
|
316
|
+
status,
|
|
317
|
+
at: j.startedAt,
|
|
318
|
+
endAt: j.endedAt,
|
|
319
|
+
durationMs: j.durationMs,
|
|
320
|
+
cost: j.costUsd,
|
|
321
|
+
costEstimated: j.costEstimated,
|
|
322
|
+
sessionId: j.sessionId,
|
|
323
|
+
model: j.model ?? d.model,
|
|
324
|
+
changeId: j.changeId,
|
|
325
|
+
preview: j.result ? j.result.slice(0, 280) : d.preview,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
function jobToDispatch(j) {
|
|
329
|
+
const status = j.status === "running" ? "open" : j.status === "done" ? "done" : j.status === "failed" ? "error" : "aborted";
|
|
330
|
+
const checkerMatch = j.callId.match(/^checker:(T\d+):/);
|
|
331
|
+
return {
|
|
332
|
+
key: `job:${j.id}`,
|
|
333
|
+
callId: j.callId,
|
|
334
|
+
job: j.id,
|
|
335
|
+
agent: j.agent,
|
|
336
|
+
task: j.task,
|
|
337
|
+
taskId: j.taskId ?? checkerMatch?.[1],
|
|
338
|
+
basedOn: j.basedOn,
|
|
339
|
+
resume: j.resume ?? null,
|
|
340
|
+
at: j.startedAt,
|
|
341
|
+
endAt: j.endedAt,
|
|
342
|
+
durationMs: j.durationMs,
|
|
343
|
+
status,
|
|
344
|
+
model: j.model ?? config.agents[j.agent]?.defaultModel,
|
|
345
|
+
cost: j.costUsd,
|
|
346
|
+
costEstimated: j.costEstimated,
|
|
347
|
+
sessionId: j.sessionId,
|
|
348
|
+
changeId: j.changeId,
|
|
349
|
+
preview: j.result ? j.result.slice(0, 280) : undefined,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
const allDispatches = () => {
|
|
353
|
+
const explicit = [...dispatches.values()].map(withJob);
|
|
354
|
+
const seenJobs = new Set(explicit.map((d) => d.job).filter(Boolean));
|
|
355
|
+
const seenCalls = new Set(explicit.map((d) => d.callId));
|
|
356
|
+
const internal = Object.values(jobs)
|
|
357
|
+
.filter((j) => (!j.conversation || j.conversation === String(root.id)) && !seenJobs.has(j.id) && !seenCalls.has(j.callId))
|
|
358
|
+
.map(jobToDispatch);
|
|
359
|
+
return [...explicit, ...internal];
|
|
360
|
+
};
|
|
361
|
+
let cursor;
|
|
362
|
+
do {
|
|
363
|
+
const page = await root.entries({ order: "ascending" }, 500, cursor, context);
|
|
364
|
+
for (const entry of page.items)
|
|
365
|
+
ingest(entry);
|
|
366
|
+
cursor = page.next;
|
|
367
|
+
} while (cursor);
|
|
368
|
+
function agentStats() {
|
|
369
|
+
const stats = {};
|
|
370
|
+
for (const d of allDispatches()) {
|
|
371
|
+
const s = (stats[d.agent] ??= { total: 0, done: 0, error: 0, aborted: 0, open: 0, durationMs: 0, timed: 0, cost: 0 });
|
|
372
|
+
s.total++;
|
|
373
|
+
if (d.status === "done")
|
|
374
|
+
s.done++;
|
|
375
|
+
else if (d.status === "error")
|
|
376
|
+
s.error++;
|
|
377
|
+
else if (d.status === "aborted" || d.status === "interrupted")
|
|
378
|
+
s.aborted++;
|
|
379
|
+
else
|
|
380
|
+
s.open++;
|
|
381
|
+
if (d.durationMs !== undefined) {
|
|
382
|
+
s.durationMs += d.durationMs;
|
|
383
|
+
s.timed++;
|
|
384
|
+
}
|
|
385
|
+
s.cost += d.cost ?? 0;
|
|
386
|
+
const at = d.endAt ?? d.at;
|
|
387
|
+
if (at && (!s.lastAt || at > s.lastAt))
|
|
388
|
+
s.lastAt = at;
|
|
389
|
+
}
|
|
390
|
+
return stats;
|
|
391
|
+
}
|
|
392
|
+
/** 按 成员 × 模型 汇总:用来对比不同模型的花费和成功率 */
|
|
393
|
+
function modelStats() {
|
|
394
|
+
const rows = new Map();
|
|
395
|
+
for (const d of allDispatches()) {
|
|
396
|
+
const model = d.model ?? "(CLI 默认)";
|
|
397
|
+
const key = `${d.agent}|${model}`;
|
|
398
|
+
let r = rows.get(key);
|
|
399
|
+
if (!r)
|
|
400
|
+
rows.set(key, (r = { agent: d.agent, model, total: 0, done: 0, error: 0, durationMs: 0, timed: 0, cost: 0, estimated: false }));
|
|
401
|
+
r.total++;
|
|
402
|
+
if (d.status === "done")
|
|
403
|
+
r.done++;
|
|
404
|
+
else if (d.status === "error")
|
|
405
|
+
r.error++;
|
|
406
|
+
if (d.durationMs !== undefined) {
|
|
407
|
+
r.durationMs += d.durationMs;
|
|
408
|
+
r.timed++;
|
|
409
|
+
}
|
|
410
|
+
r.cost += d.cost ?? 0;
|
|
411
|
+
if (d.costEstimated)
|
|
412
|
+
r.estimated = true;
|
|
413
|
+
}
|
|
414
|
+
return [...rows.values()].sort((a, b) => a.agent.localeCompare(b.agent) || b.total - a.total);
|
|
415
|
+
}
|
|
416
|
+
// ---------- 实时状态:一个 watch,广播给所有浏览器 ----------
|
|
417
|
+
const clients = new Set();
|
|
418
|
+
cleanup.push(() => { for (const res of clients)
|
|
419
|
+
res.end(); clients.clear(); });
|
|
420
|
+
const broadcast = (event, data) => {
|
|
421
|
+
if (disposed)
|
|
422
|
+
return;
|
|
423
|
+
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
424
|
+
for (const res of clients)
|
|
425
|
+
res.write(payload);
|
|
426
|
+
};
|
|
427
|
+
const resourceChanges = harness.observeCommits({ advance(publication) {
|
|
428
|
+
if (publication.changes.some((change) => change.type === "document" && ["lemma.resources", "lemma.cost-ledger", "lemma.business-operations"].includes(change.record.kind)))
|
|
429
|
+
broadcast("resources", null);
|
|
430
|
+
if (publication.changes.some((change) => change.type === "document" && ["lemma.integrations", "lemma.task-workflow", "pi-agent.board"].includes(change.record.kind)))
|
|
431
|
+
broadcast("project", null);
|
|
432
|
+
if (publication.changes.some((change) => change.type === "document" && change.record.kind === "pi-agent.jobs"))
|
|
433
|
+
onJobs();
|
|
434
|
+
}, end() { } });
|
|
435
|
+
cleanup.push(() => resourceChanges.detach());
|
|
436
|
+
const watch = await root.watch(context);
|
|
437
|
+
cleanup.push(() => watch.stop());
|
|
438
|
+
const seen = new Set(watch.value.entries.map((e) => Number(e.id)));
|
|
439
|
+
let lastLive = toViewLive(watch.value.docs["pi.live"], watch.value.docs["pi.inbox"]);
|
|
440
|
+
let lastLiveJson = JSON.stringify(lastLive);
|
|
441
|
+
watch.start(async (call) => {
|
|
442
|
+
if (disposed || call.kind !== "value")
|
|
443
|
+
return;
|
|
444
|
+
const fresh = [];
|
|
445
|
+
for (const entry of call.value.entries) {
|
|
446
|
+
const id = Number(entry.id);
|
|
447
|
+
if (seen.has(id))
|
|
448
|
+
continue;
|
|
449
|
+
seen.add(id);
|
|
450
|
+
ingest(entry);
|
|
451
|
+
const item = toViewItem(entry);
|
|
452
|
+
if (item)
|
|
453
|
+
fresh.push(item);
|
|
454
|
+
}
|
|
455
|
+
if (fresh.length > 0)
|
|
456
|
+
broadcast("items", fresh);
|
|
457
|
+
const live = toViewLive(call.value.docs["pi.live"], call.value.docs["pi.inbox"]);
|
|
458
|
+
for (const slot of live.tools) {
|
|
459
|
+
const conv = slot.details?.conversationId;
|
|
460
|
+
if (slot.name !== LEAD_TOOL || typeof conv !== "string")
|
|
461
|
+
continue;
|
|
462
|
+
const l = leads.get(latestLeadByCall.get(slot.callId) ?? "");
|
|
463
|
+
if (l && !l.conversationId)
|
|
464
|
+
attachLead(l, conv);
|
|
465
|
+
}
|
|
466
|
+
const json = JSON.stringify(live);
|
|
467
|
+
if (json !== lastLiveJson) {
|
|
468
|
+
lastLive = live;
|
|
469
|
+
lastLiveJson = json;
|
|
470
|
+
broadcast("live", live);
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
// 改动记录变了(派工收尾、终端里 /apply /drop):通知页面刷新
|
|
474
|
+
const onChange = (record) => broadcast("change", record);
|
|
475
|
+
changes.on("change", onChange);
|
|
476
|
+
cleanup.push(() => changes.off("change", onChange));
|
|
477
|
+
// 目标或分工表变了:通知页面刷新「项目」
|
|
478
|
+
const onProject = () => broadcast("project", null);
|
|
479
|
+
project.on("change", onProject);
|
|
480
|
+
cleanup.push(() => project.off("change", onProject));
|
|
481
|
+
// 后台派工开工 / 结束:刷新记录并通知页面;成员的实时输出直接转发
|
|
482
|
+
onLeadActivity = () => broadcast("lead", null);
|
|
483
|
+
const onJobs = () => {
|
|
484
|
+
if (disposed)
|
|
485
|
+
return;
|
|
486
|
+
void refreshJobs().then(() => broadcast("jobs", Object.values(jobs))).catch(() => { });
|
|
487
|
+
};
|
|
488
|
+
const onJobOutput = (id, line) => broadcast("job-output", { id, line });
|
|
489
|
+
app.jobs.on("change", onJobs);
|
|
490
|
+
app.jobs.on("output", onJobOutput);
|
|
491
|
+
cleanup.push(() => { app.jobs.off("change", onJobs); app.jobs.off("output", onJobOutput); });
|
|
492
|
+
const ping = setInterval(() => {
|
|
493
|
+
for (const res of clients)
|
|
494
|
+
res.write(": ping\n\n");
|
|
495
|
+
}, 20_000);
|
|
496
|
+
ping.unref();
|
|
497
|
+
cleanup.push(() => clearInterval(ping));
|
|
498
|
+
// ---------- 数据 ----------
|
|
499
|
+
/** 往前取 limit 条能显示的条目(系统提示更新等不显示的条目不占名额) */
|
|
500
|
+
async function history(limit, before) {
|
|
501
|
+
const query = before ? { maxEntryId: (before - 1) } : {};
|
|
502
|
+
const items = [];
|
|
503
|
+
let cursor;
|
|
504
|
+
let hasMore = false;
|
|
505
|
+
do {
|
|
506
|
+
const page = await root.entries(query, limit, cursor, context);
|
|
507
|
+
for (const entry of page.items) {
|
|
508
|
+
const item = toViewItem(entry);
|
|
509
|
+
if (!item)
|
|
510
|
+
continue;
|
|
511
|
+
if (items.length === limit) {
|
|
512
|
+
hasMore = true;
|
|
513
|
+
break;
|
|
514
|
+
}
|
|
515
|
+
items.push(item);
|
|
516
|
+
}
|
|
517
|
+
cursor = page.next;
|
|
518
|
+
if (!hasMore && items.length === limit && cursor)
|
|
519
|
+
hasMore = true;
|
|
520
|
+
} while (cursor && items.length < limit);
|
|
521
|
+
items.sort((a, b) => a.id - b.id);
|
|
522
|
+
return { items, hasMore };
|
|
523
|
+
}
|
|
524
|
+
/** 后台派工列表:进行中的在前,带最近的实时输出 */
|
|
525
|
+
function jobList() {
|
|
526
|
+
return Object.values(jobs)
|
|
527
|
+
.sort((a, b) => Number(b.status === "running") - Number(a.status === "running") || b.startedAt - a.startedAt)
|
|
528
|
+
.map((j) => ({ ...j, waiter: undefined, output: j.status === "running" ? app.jobs.recent(j.id).slice(-20) : undefined }));
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* 协作拓扑:总调度 → 成员 → 会话(泳道)→ 每次派工(时间条),加上「基于某次改动」的依赖。
|
|
532
|
+
* 同一个成员的多条泳道 = 它同时 / 先后开的多个会话;时间条重叠 = 并行。
|
|
533
|
+
*/
|
|
534
|
+
async function topology(limit = 80) {
|
|
535
|
+
await refreshJobs();
|
|
536
|
+
const controller = await root.agent(context);
|
|
537
|
+
const sessions = (await harness.snapshot(AgentSessions, context))?.sessions ?? {};
|
|
538
|
+
const boardDoc = (await harness.snapshot(Board, context));
|
|
539
|
+
const integrationsDoc = await harness.snapshot(Integrations, context);
|
|
540
|
+
const live = lastLive;
|
|
541
|
+
const now = Date.now();
|
|
542
|
+
const list = allDispatches()
|
|
543
|
+
.filter((d) => d.at !== undefined)
|
|
544
|
+
.sort((a, b) => a.at - b.at)
|
|
545
|
+
.slice(-limit);
|
|
546
|
+
const lanes = new Map();
|
|
547
|
+
// 真的在跑:同步派工有实时槽位,后台派工的记录在跑,子调度派的工要它的子调度还在跑。
|
|
548
|
+
// 没有结果、也不在跑的(比如进程中途退出过),只是「中断」,不能画成一直在执行。
|
|
549
|
+
const slotRunning = (callId) => live.busy && live.tools.some((t) => t.callId === callId && t.status !== "done");
|
|
550
|
+
const leadRunning = (key) => {
|
|
551
|
+
const l = leads.get(key);
|
|
552
|
+
return !!l && l.status === "open" && slotRunning(l.callId);
|
|
553
|
+
};
|
|
554
|
+
const isRunning = (d) => {
|
|
555
|
+
if (d.status !== "open")
|
|
556
|
+
return false;
|
|
557
|
+
if (d.job)
|
|
558
|
+
return jobs[d.job]?.status === "running";
|
|
559
|
+
if (d.lead)
|
|
560
|
+
return leadRunning(d.lead);
|
|
561
|
+
return slotRunning(d.callId);
|
|
562
|
+
};
|
|
563
|
+
const bars = list.map((d) => {
|
|
564
|
+
const running = isRunning(d);
|
|
565
|
+
if (d.status === "open" && !running)
|
|
566
|
+
d = { ...d, status: "interrupted" };
|
|
567
|
+
// 同步派工还在跑时,会话 ID 在实时槽位的 details 里
|
|
568
|
+
const slot = running && !d.job ? live.tools.find((t) => t.callId === d.callId) : undefined;
|
|
569
|
+
const session = d.resume ?? d.sessionId ?? slot?.details?.sessionId ?? null;
|
|
570
|
+
const laneId = session ?? `solo:${d.key}`;
|
|
571
|
+
const end = d.endAt ?? (running ? now : d.at);
|
|
572
|
+
let lane = lanes.get(laneId);
|
|
573
|
+
if (!lane)
|
|
574
|
+
lanes.set(laneId, (lane = { id: laneId, agent: d.agent, session, rounds: 0, first: d.at, last: end, running: false, tasks: [] }));
|
|
575
|
+
lane.rounds++;
|
|
576
|
+
lane.last = Math.max(lane.last, end);
|
|
577
|
+
lane.running ||= running;
|
|
578
|
+
if (d.model)
|
|
579
|
+
lane.model = d.model;
|
|
580
|
+
lane.lastTask = d.task.replace(/\s+/g, " ").trim().slice(0, 80);
|
|
581
|
+
if (d.taskId && !lane.tasks.includes(d.taskId))
|
|
582
|
+
lane.tasks.push(d.taskId);
|
|
583
|
+
return {
|
|
584
|
+
key: d.key,
|
|
585
|
+
lane: laneId,
|
|
586
|
+
agent: d.agent,
|
|
587
|
+
start: d.at,
|
|
588
|
+
end,
|
|
589
|
+
running,
|
|
590
|
+
status: d.status,
|
|
591
|
+
mode: d.job ? "async" : "sync",
|
|
592
|
+
lead: d.lead,
|
|
593
|
+
job: d.job ?? null,
|
|
594
|
+
task: d.task.replace(/\s+/g, " ").trim().slice(0, 140),
|
|
595
|
+
taskId: d.taskId ?? null,
|
|
596
|
+
changeId: d.changeId ?? null,
|
|
597
|
+
basedOn: d.basedOn ?? null,
|
|
598
|
+
resume: d.resume,
|
|
599
|
+
model: d.model ?? null,
|
|
600
|
+
cost: d.cost ?? null,
|
|
601
|
+
reviewRole: d.callId.startsWith("checker:"),
|
|
602
|
+
};
|
|
603
|
+
});
|
|
604
|
+
// 联合集成:合并多成员分支并运行检查
|
|
605
|
+
const integrationRecords = Object.values(integrationsDoc?.records ?? {})
|
|
606
|
+
.filter((r) => r.integration?.controllerId === String(root.id))
|
|
607
|
+
.sort((a, b) => a.createdAt - b.createdAt)
|
|
608
|
+
.slice(-Math.max(10, Math.floor(limit / 2)));
|
|
609
|
+
const integrationBars = integrationRecords.map((r) => {
|
|
610
|
+
const current = changes.get(r.id) ?? r;
|
|
611
|
+
const st = current.integration.status;
|
|
612
|
+
const running = ["preparing", "merging", "repairing", "testing"].includes(st);
|
|
613
|
+
const end = running ? now : Math.max(current.createdAt + 80, current.updatedAt);
|
|
614
|
+
const laneId = `integration:${current.id}`;
|
|
615
|
+
lanes.set(laneId, { id: laneId, agent: "integration", session: current.id, rounds: current.integration.checks.length || 1, first: current.createdAt, last: end, running, lastTask: current.task.slice(0, 80), tasks: [], model: st });
|
|
616
|
+
const barStatus = running ? "open" : st === "passed" ? "done" : st === "cancelled" ? "aborted" : "error";
|
|
617
|
+
return {
|
|
618
|
+
key: `integration:${current.id}`,
|
|
619
|
+
lane: laneId,
|
|
620
|
+
agent: "integration",
|
|
621
|
+
lead: undefined,
|
|
622
|
+
start: current.createdAt,
|
|
623
|
+
end,
|
|
624
|
+
running,
|
|
625
|
+
status: barStatus,
|
|
626
|
+
mode: "integration",
|
|
627
|
+
job: null,
|
|
628
|
+
task: `${current.task} · ${st}`,
|
|
629
|
+
taskId: null,
|
|
630
|
+
changeId: current.id,
|
|
631
|
+
basedOn: current.integration.repair?.fromId ?? null,
|
|
632
|
+
resume: null,
|
|
633
|
+
model: `${current.integration.reports.filter((rep) => rep.passed).length}/${current.integration.checks.length} 检查`,
|
|
634
|
+
cost: null,
|
|
635
|
+
reviewRole: false,
|
|
636
|
+
};
|
|
637
|
+
});
|
|
638
|
+
// 子调度:每个一条泳道,时间条覆盖它从接手到汇报的整段
|
|
639
|
+
const leadBars = [...leads.values()]
|
|
640
|
+
.filter((l) => l.at !== undefined && (l.at >= (list[0]?.at ?? 0) || bars.some((b) => b.lead === l.key)))
|
|
641
|
+
.map((l) => {
|
|
642
|
+
const running = leadRunning(l.key);
|
|
643
|
+
const end = l.endAt ?? (running ? now : l.at);
|
|
644
|
+
const laneId = `lead:${l.key}`;
|
|
645
|
+
lanes.set(laneId, { id: laneId, agent: "lead", session: l.conversationId ?? null, rounds: 1, first: l.at, last: end, running, lastTask: l.goal.slice(0, 80), tasks: l.taskId ? [l.taskId] : [], model: l.name });
|
|
646
|
+
return {
|
|
647
|
+
key: l.key,
|
|
648
|
+
lane: laneId,
|
|
649
|
+
agent: "lead",
|
|
650
|
+
lead: undefined,
|
|
651
|
+
start: l.at,
|
|
652
|
+
end,
|
|
653
|
+
running,
|
|
654
|
+
status: l.status === "open" && !running ? "interrupted" : l.status,
|
|
655
|
+
mode: "lead",
|
|
656
|
+
job: null,
|
|
657
|
+
task: `${l.name}:${l.goal.replace(/\s+/g, " ").trim().slice(0, 120)}`,
|
|
658
|
+
taskId: l.taskId ?? null,
|
|
659
|
+
changeId: null,
|
|
660
|
+
basedOn: null,
|
|
661
|
+
resume: null,
|
|
662
|
+
model: null,
|
|
663
|
+
cost: null,
|
|
664
|
+
reviewRole: false,
|
|
665
|
+
};
|
|
666
|
+
});
|
|
667
|
+
// 依赖:基于某次改动开工的派工 ← 产出那次改动的派工 / 联合集成
|
|
668
|
+
const byChange = new Map([
|
|
669
|
+
...bars.filter((b) => b.changeId).map((b) => [b.changeId, b.key]),
|
|
670
|
+
...integrationBars.map((b) => [b.changeId, b.key]),
|
|
671
|
+
]);
|
|
672
|
+
const byJob = new Map(bars.filter((b) => b.job).map((b) => [b.job, b]));
|
|
673
|
+
const reviewLinks = [];
|
|
674
|
+
for (const t of Object.values(boardDoc?.tasks ?? {})) {
|
|
675
|
+
const execBars = bars.filter((b) => b.taskId === t.id && !b.reviewRole);
|
|
676
|
+
for (const check of t.checksByMember ?? []) {
|
|
677
|
+
const checkerBar = check.jobId ? byJob.get(check.jobId) : undefined;
|
|
678
|
+
const sourceBar = (check.sourceChangeId ? bars.find((b) => b.changeId === check.sourceChangeId) : undefined) ?? execBars.filter((b) => b.end <= (checkerBar?.start ?? Infinity)).at(-1) ?? execBars[0];
|
|
679
|
+
if (sourceBar && checkerBar && !sourceBar.basedOn) {
|
|
680
|
+
reviewLinks.push({ from: sourceBar.key, to: checkerBar.key, change: check.sourceChangeId ?? t.id, type: "review" });
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
const links = [
|
|
685
|
+
...bars.filter((b) => b.basedOn && byChange.has(b.basedOn)).map((b) => ({ from: byChange.get(b.basedOn), to: b.key, change: b.basedOn, type: "based_on" })),
|
|
686
|
+
...integrationRecords.flatMap((r) => r.integration.sources.filter((s) => byChange.has(s.id)).map((s) => ({ from: byChange.get(s.id), to: `integration:${r.id}`, change: s.id, type: "integrate" }))),
|
|
687
|
+
...reviewLinks,
|
|
688
|
+
// 子调度 → 它派的工
|
|
689
|
+
...bars.filter((b) => b.lead && leads.has(b.lead)).map((b) => ({ from: b.lead, to: b.key, type: "spawn" })),
|
|
690
|
+
];
|
|
691
|
+
bars.push(...integrationBars, ...leadBars);
|
|
692
|
+
// 同一时刻最多有几个派工在跑
|
|
693
|
+
const edges = bars.flatMap((b) => [
|
|
694
|
+
{ t: b.start, d: 1 },
|
|
695
|
+
{ t: b.end, d: -1 },
|
|
696
|
+
]);
|
|
697
|
+
edges.sort((a, b) => a.t - b.t || a.d - b.d);
|
|
698
|
+
let current = 0;
|
|
699
|
+
let peak = 0;
|
|
700
|
+
for (const e of edges)
|
|
701
|
+
peak = Math.max(peak, (current += e.d));
|
|
702
|
+
return {
|
|
703
|
+
now,
|
|
704
|
+
orchestrator: { model: controller.model?.modelId ?? config.orchestrator.modelId, busy: live.busy, turns: live.turns },
|
|
705
|
+
members: [
|
|
706
|
+
...agents.map((a) => ({ kind: a.kind, label: agentAdapter(a.kind, config.agents[a.kind]).label, available: a.available })),
|
|
707
|
+
...(integrationBars.length ? [{ kind: "integration", label: "联合集成", available: true }] : []),
|
|
708
|
+
...(leads.size ? [{ kind: "lead", label: "子调度", available: true }] : []),
|
|
709
|
+
],
|
|
710
|
+
lanes: [...lanes.values()].map((l) => ({ ...l, known: l.session ? !!sessions[l.session] : false })),
|
|
711
|
+
bars,
|
|
712
|
+
links,
|
|
713
|
+
tasks: boardTasks(boardDoc),
|
|
714
|
+
readyTasks: boardDoc ? readyTasks(boardDoc, String(root.id)) : [],
|
|
715
|
+
integrations: integrationRecords.map((r) => integrationSummary(changes.get(r.id) ?? r)),
|
|
716
|
+
stats: { running: bars.filter((b) => b.running).length, peak, async: bars.filter((b) => b.mode === "async").length, total: bars.length },
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
async function state() {
|
|
720
|
+
await refreshJobs();
|
|
721
|
+
const controller = await root.agent(context);
|
|
722
|
+
const usage = (await harness.usage(context));
|
|
723
|
+
const sessions = (await harness.snapshot(AgentSessions, context))?.sessions ?? {};
|
|
724
|
+
const useCount = new Map();
|
|
725
|
+
for (const d of allDispatches())
|
|
726
|
+
if (d.sessionId)
|
|
727
|
+
useCount.set(d.sessionId, (useCount.get(d.sessionId) ?? 0) + 1);
|
|
728
|
+
const o = config.orchestrator;
|
|
729
|
+
const boardDoc = (await harness.snapshot(Board, context));
|
|
730
|
+
const workflowDoc = await harness.snapshot(Workflow, context);
|
|
731
|
+
const integrationsDoc = await harness.snapshot(Integrations, context);
|
|
732
|
+
return {
|
|
733
|
+
canEditSettings: !!options.settings,
|
|
734
|
+
workflow: { paused: workflowDoc?.controllers[String(root.id)]?.paused ?? false },
|
|
735
|
+
readyTasks: boardDoc ? readyTasks(boardDoc, String(root.id)) : [],
|
|
736
|
+
integrations: Object.values(integrationsDoc?.records ?? {})
|
|
737
|
+
.filter((r) => r.integration?.controllerId === String(root.id))
|
|
738
|
+
.sort((a, b) => b.createdAt - a.createdAt)
|
|
739
|
+
.map((r) => integrationSummary(changes.get(r.id) ?? r)),
|
|
740
|
+
operations: operationList(await harness.snapshot(Operations, context)).map(({ id, member, tool, method, status, createdAt, updatedAt, result, resolution }) => ({ id, member, tool, method, status, createdAt, updatedAt, failure: result?.failure, resolution })),
|
|
741
|
+
gitWorkbench: await (async () => {
|
|
742
|
+
const wb = await harness.snapshot(GitWorkbench, context);
|
|
743
|
+
return {
|
|
744
|
+
requireHumanPush: wb?.requireHumanPush ?? false,
|
|
745
|
+
pendingGates: Object.values(wb?.gates ?? {}).filter((g) => g.status === "pending").sort((a, b) => b.createdAt - a.createdAt),
|
|
746
|
+
};
|
|
747
|
+
})(),
|
|
748
|
+
pid: process.pid,
|
|
749
|
+
startedAt,
|
|
750
|
+
configPath: options.configPath,
|
|
751
|
+
workdir: config.workdir,
|
|
752
|
+
storage: config.storage,
|
|
753
|
+
conversation: { ...(options.session ?? { id: "default", title: "默认会话" }), controllerId: String(root.id) },
|
|
754
|
+
autonomy: { ...config.autonomy, learning: await harness.snapshot(Learning, context) },
|
|
755
|
+
lead: config.lead,
|
|
756
|
+
execution: { maxConcurrent: 8, perMember: 4, perService: 8, ...config.execution },
|
|
757
|
+
entries: entryCount,
|
|
758
|
+
jobs: jobList(),
|
|
759
|
+
orchestrator: {
|
|
760
|
+
describe: controller.model ? `${controller.model.provider}/${controller.model.modelId}` : orchestrator.describe,
|
|
761
|
+
type: orchestrator.info?.type ?? o.type,
|
|
762
|
+
modelId: controller.model?.modelId ?? o.modelId,
|
|
763
|
+
baseUrl: o.baseUrl ?? null,
|
|
764
|
+
host: orchestrator.info?.host,
|
|
765
|
+
keySource: orchestrator.info?.keySource ?? "",
|
|
766
|
+
hasCredential: !!o.credential,
|
|
767
|
+
maxTurns: o.maxTurns ?? 40,
|
|
768
|
+
price: o.price ?? null,
|
|
769
|
+
},
|
|
770
|
+
stripEnv: config.stripEnv,
|
|
771
|
+
isolation: config.isolation,
|
|
772
|
+
budget: { ...config.budget, ...(await harness.snapshot(RunBudget, context)) },
|
|
773
|
+
resources: resourceSnapshot(await harness.snapshot(Resources, context)),
|
|
774
|
+
costLedger: Object.values((await harness.snapshot(CostLedger, context))?.entries ?? {}),
|
|
775
|
+
uxTelemetry: computeUxMetrics(((await harness.snapshot(UxTelemetry, context))?.events ?? [])),
|
|
776
|
+
modelStats: modelStats(),
|
|
777
|
+
project: {
|
|
778
|
+
goal: project.goal() ?? null,
|
|
779
|
+
goalPath: project.goalPath,
|
|
780
|
+
assignPath: project.assignPath,
|
|
781
|
+
tasks: boardTasks(boardDoc),
|
|
782
|
+
roles: config.roles,
|
|
783
|
+
},
|
|
784
|
+
changeCounts: changes.list().reduce((m, ch) => ((m[ch.status] = (m[ch.status] ?? 0) + 1), m), {}),
|
|
785
|
+
agents: agents.map((a) => {
|
|
786
|
+
const c = config.agents[a.kind];
|
|
787
|
+
return {
|
|
788
|
+
kind: a.kind,
|
|
789
|
+
label: agentAdapter(a.kind, c).label,
|
|
790
|
+
transport: c.api ? "api" : "cli",
|
|
791
|
+
workspace: c.workspace ?? "code",
|
|
792
|
+
available: a.available,
|
|
793
|
+
reason: a.reason,
|
|
794
|
+
enabled: c.enabled,
|
|
795
|
+
description: c.description,
|
|
796
|
+
instructions: c.instructions ?? "",
|
|
797
|
+
command: a.command ?? c.command ?? null,
|
|
798
|
+
extraArgs: c.extraArgs,
|
|
799
|
+
timeoutMinutes: c.timeoutMinutes,
|
|
800
|
+
maxOutputChars: c.maxOutputChars,
|
|
801
|
+
canResume: agentAdapter(a.kind, c).canResume,
|
|
802
|
+
models: c.models,
|
|
803
|
+
defaultModel: c.defaultModel ?? null,
|
|
804
|
+
api: c.api
|
|
805
|
+
? {
|
|
806
|
+
type: c.api.type,
|
|
807
|
+
baseUrl: c.api.baseUrl,
|
|
808
|
+
host: hostOf(c.api.baseUrl),
|
|
809
|
+
keySource: memberKey(c.api).source,
|
|
810
|
+
hasCredential: !!c.api.credential,
|
|
811
|
+
builtinTools: memberToolNames(c.api),
|
|
812
|
+
bash: c.api.bash,
|
|
813
|
+
bashAllow: c.api.bashAllow,
|
|
814
|
+
tools: [...memberToolNames(c.api), ...(c.api.httpTools ?? []).map((tool) => tool.id), ...(c.api.mcpServers ?? []).flatMap((grant) => grant.tools.map((tool) => `mcp_${grant.id}_${tool.name}`))],
|
|
815
|
+
codeTools: (c.workspace ?? "code") !== "none" && memberToolNames(c.api).includes("read") ? ["list_files", "search_code", "git_diff", "outline_file", "find_symbol"] : [],
|
|
816
|
+
}
|
|
817
|
+
: null,
|
|
818
|
+
};
|
|
819
|
+
}),
|
|
820
|
+
agentStats: agentStats(),
|
|
821
|
+
sessions: Object.entries(sessions)
|
|
822
|
+
.map(([id, s]) => ({
|
|
823
|
+
id,
|
|
824
|
+
agent: s.agent,
|
|
825
|
+
cwd: s.cwd,
|
|
826
|
+
updatedAt: s.updatedAt,
|
|
827
|
+
uses: useCount.get(id) ?? 0,
|
|
828
|
+
rounds: s.rounds ?? null,
|
|
829
|
+
createdAt: s.createdAt ?? null,
|
|
830
|
+
lastTask: s.lastTask ?? null,
|
|
831
|
+
model: s.model ?? null,
|
|
832
|
+
change: s.change ?? null,
|
|
833
|
+
resume: config.agents[s.agent]?.api ? "(Pi 子对话,由 Lemma 续接)" : RESUME_COMMAND[s.agent]?.(id) ?? null,
|
|
834
|
+
}))
|
|
835
|
+
.sort((a, b) => b.updatedAt - a.updatedAt),
|
|
836
|
+
// 只算总调度(含子调度)自己的模型;API 成员(member-*)的子对话用量已经算在成员花费里,不能再算一遍
|
|
837
|
+
usage: Object.entries(usage?.models ?? {}).filter(([model]) => !model.startsWith("member-")).map(([model, u]) => ({
|
|
838
|
+
model,
|
|
839
|
+
input: u.input ?? 0,
|
|
840
|
+
output: u.output ?? 0,
|
|
841
|
+
cacheRead: u.cacheRead ?? 0,
|
|
842
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
843
|
+
cost: u.cost?.total ?? 0,
|
|
844
|
+
})),
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
/** 按 key 查;也接受 callId(取最近一次) */
|
|
848
|
+
async function dispatchDetail(id) {
|
|
849
|
+
const raw = dispatches.get(id) ?? dispatches.get(latestByCall.get(id) ?? "");
|
|
850
|
+
let d = raw ? withJob(raw) : undefined;
|
|
851
|
+
if (!d) {
|
|
852
|
+
const jobKey = id.startsWith("job:") ? id.slice(4) : Object.values(jobs).find((j) => j.callId === id)?.id;
|
|
853
|
+
const j = jobKey ? jobs[jobKey] : undefined;
|
|
854
|
+
if (j && (!j.conversation || j.conversation === String(root.id)))
|
|
855
|
+
d = jobToDispatch(j);
|
|
856
|
+
}
|
|
857
|
+
if (!d)
|
|
858
|
+
return undefined;
|
|
859
|
+
let result;
|
|
860
|
+
if (d.resultEntryId !== undefined) {
|
|
861
|
+
const page = await root.entries({ minEntryId: d.resultEntryId, maxEntryId: d.resultEntryId }, 1, undefined, context);
|
|
862
|
+
const item = page.items[0] ? toViewItem(page.items[0]) : undefined;
|
|
863
|
+
if (item?.type === "tool")
|
|
864
|
+
result = parseToolResult(item.text, item.isError, item.details).body;
|
|
865
|
+
}
|
|
866
|
+
const job = d.job ? jobs[d.job] : undefined;
|
|
867
|
+
if (job)
|
|
868
|
+
result = job.result ?? (job.status === "running" ? undefined : result);
|
|
869
|
+
return { ...d, result, output: job?.status === "running" ? app.jobs.recent(job.id) : undefined };
|
|
870
|
+
}
|
|
871
|
+
// ---------- HTTP ----------
|
|
872
|
+
const port = options.port;
|
|
873
|
+
const allowed = () => ({
|
|
874
|
+
hosts: new Set([`127.0.0.1:${port}`, `localhost:${port}`]),
|
|
875
|
+
origins: new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]),
|
|
876
|
+
});
|
|
877
|
+
function forbidden(req) {
|
|
878
|
+
const { hosts, origins } = allowed();
|
|
879
|
+
// Host 校验防 DNS 重绑定;Origin 校验防其他网站跨站发起控制操作
|
|
880
|
+
if (!hosts.has(String(req.headers.host ?? "")))
|
|
881
|
+
return "bad host";
|
|
882
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
883
|
+
const origin = req.headers.origin;
|
|
884
|
+
if (origin !== undefined && !origins.has(origin))
|
|
885
|
+
return "bad origin";
|
|
886
|
+
if (!String(req.headers["content-type"] ?? "").startsWith("application/json"))
|
|
887
|
+
return "json required";
|
|
888
|
+
}
|
|
889
|
+
return undefined;
|
|
890
|
+
}
|
|
891
|
+
const sendJson = (res, status, body) => {
|
|
892
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
|
893
|
+
res.end(JSON.stringify(body));
|
|
894
|
+
};
|
|
895
|
+
class HttpError extends Error {
|
|
896
|
+
status;
|
|
897
|
+
constructor(status, message) {
|
|
898
|
+
super(message);
|
|
899
|
+
this.status = status;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
async function readJson(req, maxBytes = 4096) {
|
|
903
|
+
let size = 0;
|
|
904
|
+
const chunks = [];
|
|
905
|
+
for await (const chunk of req) {
|
|
906
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
907
|
+
size += bytes.length;
|
|
908
|
+
if (size > maxBytes)
|
|
909
|
+
throw new HttpError(400, "请求内容过长");
|
|
910
|
+
chunks.push(bytes);
|
|
911
|
+
}
|
|
912
|
+
let value;
|
|
913
|
+
try {
|
|
914
|
+
value = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
|
915
|
+
}
|
|
916
|
+
catch {
|
|
917
|
+
throw new HttpError(400, "需要有效的 JSON");
|
|
918
|
+
}
|
|
919
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
920
|
+
throw new HttpError(400, "需要 JSON 对象");
|
|
921
|
+
return value;
|
|
922
|
+
}
|
|
923
|
+
async function readControlBody(req, maxBytes = 4096) {
|
|
924
|
+
const body = await readJson(req, maxBytes);
|
|
925
|
+
if (disposed)
|
|
926
|
+
throw new HttpError(409, "对话已切换,未执行操作");
|
|
927
|
+
if (body.expectedSession !== undefined && body.expectedSession !== (options.session?.id ?? "default"))
|
|
928
|
+
throw new HttpError(409, "对话已切换,未执行操作");
|
|
929
|
+
return body;
|
|
930
|
+
}
|
|
931
|
+
let configuring = false;
|
|
932
|
+
async function mutateSettings(req, controller, fn) {
|
|
933
|
+
if (!options.settings)
|
|
934
|
+
throw new HttpError(503, "当前运行入口不支持在网页修改配置");
|
|
935
|
+
const body = await readControlBody(req, 32768);
|
|
936
|
+
if (configuring)
|
|
937
|
+
throw new HttpError(409, "正在保存其他配置,请稍后重试");
|
|
938
|
+
configuring = true;
|
|
939
|
+
try {
|
|
940
|
+
try {
|
|
941
|
+
await options.settings.assertIdle();
|
|
942
|
+
}
|
|
943
|
+
catch (error) {
|
|
944
|
+
throw new HttpError(409, error instanceof Error ? error.message : String(error));
|
|
945
|
+
}
|
|
946
|
+
const draft = editSettings(options.settings.path);
|
|
947
|
+
const current = options.settings.config();
|
|
948
|
+
const { next, notify, result } = fn(body, draft, current);
|
|
949
|
+
await options.settings.commit(draft, next, controller);
|
|
950
|
+
options.notify?.(notify);
|
|
951
|
+
return { ok: true, ...(result && typeof result === "object" ? result : {}) };
|
|
952
|
+
}
|
|
953
|
+
catch (error) {
|
|
954
|
+
if (error instanceof HttpError)
|
|
955
|
+
throw error;
|
|
956
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
957
|
+
throw new HttpError(/正在执行|请先|切换|退出/.test(msg) ? 409 : /没有成员/.test(msg) ? 404 : 400, msg);
|
|
958
|
+
}
|
|
959
|
+
finally {
|
|
960
|
+
configuring = false;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
const afterResponse = (res, id) => {
|
|
964
|
+
// 先响应再切换数据绑定;HTTP 监听器始终保留。
|
|
965
|
+
res.once("finish", () => setImmediate(() => {
|
|
966
|
+
if (disposed)
|
|
967
|
+
return;
|
|
968
|
+
void options.conversations.select(id).catch((error) => options.notify?.(`切换对话失败:${error instanceof Error ? error.message : String(error)}`)).finally(() => { changingConversation = false; });
|
|
969
|
+
}));
|
|
970
|
+
};
|
|
971
|
+
let changingConversation = false;
|
|
972
|
+
async function serveStatic(pathname, res) {
|
|
973
|
+
const rel = pathname === "/" ? "index.html" : decodeURIComponent(pathname).slice(1);
|
|
974
|
+
const file = normalize(join(WEB_DIR, rel));
|
|
975
|
+
if (!file.startsWith(normalize(WEB_DIR)))
|
|
976
|
+
return sendJson(res, 403, { error: "forbidden" });
|
|
977
|
+
try {
|
|
978
|
+
const body = await readFile(file);
|
|
979
|
+
res.writeHead(200, { "content-type": MIME[extname(file)] ?? "application/octet-stream", "cache-control": "no-cache" });
|
|
980
|
+
res.end(body);
|
|
981
|
+
}
|
|
982
|
+
catch {
|
|
983
|
+
sendJson(res, 404, { error: "not found" });
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
const handle = async (req, res) => {
|
|
987
|
+
const denied = forbidden(req);
|
|
988
|
+
if (denied)
|
|
989
|
+
return sendJson(res, 403, { error: denied });
|
|
990
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
|
|
991
|
+
try {
|
|
992
|
+
const requestedConversation = url.searchParams.get("conversation");
|
|
993
|
+
if (requestedConversation && requestedConversation !== (options.session?.id ?? "default"))
|
|
994
|
+
return sendJson(res, 409, { error: "对话已切换,不能读取另一个对话的数据" });
|
|
995
|
+
if (url.pathname === "/api/conversations" && req.method === "GET") {
|
|
996
|
+
return sendJson(res, 200, { current: options.session?.id ?? "default", conversations: options.conversations ? await options.conversations.list() : [] });
|
|
997
|
+
}
|
|
998
|
+
const conversationAction = url.pathname.match(/^\/api\/conversations\/([a-z0-9_-]+)\/(select|title)$/);
|
|
999
|
+
if ((url.pathname === "/api/conversations" || conversationAction) && req.method === "POST") {
|
|
1000
|
+
if (!options.conversations)
|
|
1001
|
+
return sendJson(res, 503, { error: "当前运行入口未启用对话管理" });
|
|
1002
|
+
let body;
|
|
1003
|
+
try {
|
|
1004
|
+
body = await readJson(req);
|
|
1005
|
+
}
|
|
1006
|
+
catch (error) {
|
|
1007
|
+
return sendJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
1008
|
+
}
|
|
1009
|
+
if (disposed)
|
|
1010
|
+
return sendJson(res, 409, { error: "对话已切换,请刷新后重试" });
|
|
1011
|
+
if (body.expectedSession !== (options.session?.id ?? "default"))
|
|
1012
|
+
return sendJson(res, 409, { error: "当前对话已变化,请刷新后重试" });
|
|
1013
|
+
if (changingConversation || options.conversations.busy())
|
|
1014
|
+
return sendJson(res, 409, { error: "正在切换对话,请稍后重试" });
|
|
1015
|
+
changingConversation = true;
|
|
1016
|
+
try {
|
|
1017
|
+
if (conversationAction?.[2] === "title") {
|
|
1018
|
+
changingConversation = false;
|
|
1019
|
+
if (typeof body.title !== "string")
|
|
1020
|
+
return sendJson(res, 400, { error: "需要对话标题" });
|
|
1021
|
+
await options.conversations.rename(conversationAction[1], body.title);
|
|
1022
|
+
if (options.session && options.session.id === conversationAction[1])
|
|
1023
|
+
options.session.title = body.title.trim();
|
|
1024
|
+
return sendJson(res, 200, { ok: true });
|
|
1025
|
+
}
|
|
1026
|
+
let id;
|
|
1027
|
+
if (conversationAction) {
|
|
1028
|
+
id = conversationAction[1];
|
|
1029
|
+
const list = await options.conversations.list();
|
|
1030
|
+
if (disposed)
|
|
1031
|
+
return sendJson(res, 409, { error: "对话已切换,未执行切换" });
|
|
1032
|
+
if (!list.some((item) => item.id === id)) {
|
|
1033
|
+
changingConversation = false;
|
|
1034
|
+
return sendJson(res, 404, { error: "没有这个对话" });
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
else {
|
|
1038
|
+
if (body.title !== undefined && typeof body.title !== "string") {
|
|
1039
|
+
changingConversation = false;
|
|
1040
|
+
return sendJson(res, 400, { error: "标题需要是文字" });
|
|
1041
|
+
}
|
|
1042
|
+
({ id } = await options.conversations.create(body.title ?? ""));
|
|
1043
|
+
}
|
|
1044
|
+
afterResponse(res, id);
|
|
1045
|
+
return sendJson(res, 202, { ok: true, id, preserved: true });
|
|
1046
|
+
}
|
|
1047
|
+
catch (error) {
|
|
1048
|
+
changingConversation = false;
|
|
1049
|
+
return sendJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
if (url.pathname === "/api/events" && req.method === "GET") {
|
|
1053
|
+
res.writeHead(200, { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-store", connection: "keep-alive" });
|
|
1054
|
+
const { items, hasMore } = await history(400);
|
|
1055
|
+
if (disposed || res.destroyed) {
|
|
1056
|
+
res.end();
|
|
1057
|
+
return;
|
|
1058
|
+
}
|
|
1059
|
+
res.write(`event: snapshot\ndata: ${JSON.stringify({ items, hasMore, live: lastLive, conversation: { id: options.session?.id ?? "default", controllerId: String(root.id), storage: config.storage } })}\n\n`);
|
|
1060
|
+
clients.add(res);
|
|
1061
|
+
req.on("close", () => clients.delete(res));
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
if (url.pathname === "/api/state" && req.method === "GET")
|
|
1065
|
+
return sendJson(res, 200, await state());
|
|
1066
|
+
if (url.pathname === "/api/history" && req.method === "GET") {
|
|
1067
|
+
const before = Number(url.searchParams.get("before"));
|
|
1068
|
+
const limit = Math.min(Math.max(Number(url.searchParams.get("limit")) || 400, 1), 1000);
|
|
1069
|
+
return sendJson(res, 200, await history(limit, Number.isFinite(before) && before > 0 ? before : undefined));
|
|
1070
|
+
}
|
|
1071
|
+
if (url.pathname === "/api/dispatches" && req.method === "GET") {
|
|
1072
|
+
const list = allDispatches().sort((a, b) => (b.entryId ?? b.resultEntryId ?? 0) - (a.entryId ?? a.resultEntryId ?? 0));
|
|
1073
|
+
return sendJson(res, 200, { dispatches: list });
|
|
1074
|
+
}
|
|
1075
|
+
const detail = url.pathname.match(/^\/api\/dispatches\/([^/]+)$/);
|
|
1076
|
+
if (detail && req.method === "GET") {
|
|
1077
|
+
const d = await dispatchDetail(decodeURIComponent(detail[1]));
|
|
1078
|
+
return d ? sendJson(res, 200, d) : sendJson(res, 404, { error: "没有这次派工" });
|
|
1079
|
+
}
|
|
1080
|
+
// Agent 规范文件:扫描结果(不含内容);按编号读单个文件(打码)
|
|
1081
|
+
if (url.pathname === "/api/conventions" && req.method === "GET") {
|
|
1082
|
+
const scan = scanConventions(config.workdir);
|
|
1083
|
+
return sendJson(res, 200, { ...scan, files: scan.files.map(({ path: _p, ...f }) => f) });
|
|
1084
|
+
}
|
|
1085
|
+
if (url.pathname === "/api/conventions/file" && req.method === "GET") {
|
|
1086
|
+
const scan = scanConventions(config.workdir);
|
|
1087
|
+
const file = readConvention(scan, url.searchParams.get("id") ?? "");
|
|
1088
|
+
if (!file)
|
|
1089
|
+
return sendJson(res, 404, { error: "没有这个文件" });
|
|
1090
|
+
const { path: _p, ...meta } = file.file;
|
|
1091
|
+
return sendJson(res, 200, { file: meta, text: file.text, truncated: file.truncated });
|
|
1092
|
+
}
|
|
1093
|
+
if (url.pathname === "/api/topology" && req.method === "GET")
|
|
1094
|
+
return sendJson(res, 200, await topology(Math.min(Math.max(Number(url.searchParams.get("limit")) || 40, 5), 200)));
|
|
1095
|
+
if (url.pathname === "/api/jobs" && req.method === "GET")
|
|
1096
|
+
return sendJson(res, 200, { jobs: jobList() });
|
|
1097
|
+
// 取消后台派工(控制操作,和「中止本轮」同级)
|
|
1098
|
+
const jobCancel = url.pathname.match(/^\/api\/jobs\/([^/]+)\/cancel$/);
|
|
1099
|
+
if (jobCancel && req.method === "POST") {
|
|
1100
|
+
const body = await readJson(req);
|
|
1101
|
+
if (disposed)
|
|
1102
|
+
return sendJson(res, 409, { error: "对话已切换,未执行取消" });
|
|
1103
|
+
if (body.expectedSession !== undefined && body.expectedSession !== (options.session?.id ?? "default"))
|
|
1104
|
+
return sendJson(res, 409, { error: "对话已切换,未执行取消" });
|
|
1105
|
+
const id = decodeURIComponent(jobCancel[1]);
|
|
1106
|
+
const r = await app.jobs.cancel(id, "user", context);
|
|
1107
|
+
if (r === "cancelled")
|
|
1108
|
+
options.notify?.(`后台网页:已取消后台派工 ${id}`);
|
|
1109
|
+
return sendJson(res, r === "not_found" ? 404 : 200, { ok: r === "cancelled", result: r });
|
|
1110
|
+
}
|
|
1111
|
+
if (url.pathname === "/api/changes" && req.method === "GET")
|
|
1112
|
+
return sendJson(res, 200, { changes: changes.list() });
|
|
1113
|
+
if (url.pathname === "/api/git/repos" && req.method === "GET") {
|
|
1114
|
+
const wb = await harness.snapshot(GitWorkbench, context);
|
|
1115
|
+
return sendJson(res, 200, {
|
|
1116
|
+
repos: await listManagedRepos(config, changes),
|
|
1117
|
+
workbench: {
|
|
1118
|
+
requireHumanPush: wb?.requireHumanPush ?? false,
|
|
1119
|
+
gates: Object.values(wb?.gates ?? {}).sort((a, b) => b.createdAt - a.createdAt),
|
|
1120
|
+
},
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
if (url.pathname === "/api/git/graph" && req.method === "GET") {
|
|
1124
|
+
const repo = url.searchParams.get("repo") ?? undefined;
|
|
1125
|
+
const limitParam = Number(url.searchParams.get("limit") ?? 60);
|
|
1126
|
+
const data = await inspectRepoGraph(config, changes, repo, Number.isFinite(limitParam) ? limitParam : 60);
|
|
1127
|
+
const wb = await harness.snapshot(GitWorkbench, context);
|
|
1128
|
+
return sendJson(res, 200, {
|
|
1129
|
+
...data,
|
|
1130
|
+
workbench: {
|
|
1131
|
+
requireHumanPush: wb?.requireHumanPush ?? false,
|
|
1132
|
+
gates: Object.values(wb?.gates ?? {}).sort((a, b) => b.createdAt - a.createdAt),
|
|
1133
|
+
},
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
if (url.pathname === "/api/git/commit" && req.method === "GET") {
|
|
1137
|
+
const repo = url.searchParams.get("repo") ?? undefined;
|
|
1138
|
+
const sha = url.searchParams.get("sha") ?? "";
|
|
1139
|
+
const file = url.searchParams.get("file") ?? undefined;
|
|
1140
|
+
if (!sha)
|
|
1141
|
+
return sendJson(res, 400, { error: "缺少 sha 参数" });
|
|
1142
|
+
return sendJson(res, 200, await inspectRepoCommit(config, changes, repo, sha, file));
|
|
1143
|
+
}
|
|
1144
|
+
if (url.pathname === "/api/git/fetch" && req.method === "POST") {
|
|
1145
|
+
const body = await readControlBody(req);
|
|
1146
|
+
const out = await fetchManagedRepo(config, changes, typeof body.repo === "string" ? body.repo : undefined, typeof body.remote === "string" ? body.remote : undefined);
|
|
1147
|
+
broadcast("changes", changes.list());
|
|
1148
|
+
options.notify?.(`后台网页:已刷新远端状态(${out.repo.name})`);
|
|
1149
|
+
return sendJson(res, 200, { ok: true, ...out });
|
|
1150
|
+
}
|
|
1151
|
+
if (url.pathname === "/api/git/pull" && req.method === "POST") {
|
|
1152
|
+
const body = await readControlBody(req);
|
|
1153
|
+
const out = await pullManagedRepo({ config, changes, harness, context }, {
|
|
1154
|
+
repo: typeof body.repo === "string" ? body.repo : undefined,
|
|
1155
|
+
remote: typeof body.remote === "string" ? body.remote : undefined,
|
|
1156
|
+
branch: typeof body.branch === "string" ? body.branch : undefined,
|
|
1157
|
+
actor: "human",
|
|
1158
|
+
});
|
|
1159
|
+
broadcast("changes", changes.list());
|
|
1160
|
+
options.notify?.(`后台网页:已拉取更新(${out.repo.name})`);
|
|
1161
|
+
return sendJson(res, 200, { ok: true, ...out });
|
|
1162
|
+
}
|
|
1163
|
+
if (url.pathname === "/api/git/commit" && req.method === "POST") {
|
|
1164
|
+
const body = await readControlBody(req, 65536);
|
|
1165
|
+
const files = Array.isArray(body.files) ? body.files.map(String) : undefined;
|
|
1166
|
+
const out = await commitManagedRepo({ config, changes, harness, context }, {
|
|
1167
|
+
repo: typeof body.repo === "string" ? body.repo : undefined,
|
|
1168
|
+
message: typeof body.message === "string" ? body.message : "",
|
|
1169
|
+
files,
|
|
1170
|
+
actor: "human",
|
|
1171
|
+
});
|
|
1172
|
+
broadcast("changes", changes.list());
|
|
1173
|
+
options.notify?.(`后台网页:已提交 ${out.repo.name}@${out.sha.slice(0, 7)}(${out.committedFiles} 个文件)`);
|
|
1174
|
+
return sendJson(res, 200, { ok: true, ...out });
|
|
1175
|
+
}
|
|
1176
|
+
if (url.pathname === "/api/git/push" && req.method === "POST") {
|
|
1177
|
+
const body = await readControlBody(req);
|
|
1178
|
+
const out = await pushManagedRepo({ config, changes, harness, context }, {
|
|
1179
|
+
repo: typeof body.repo === "string" ? body.repo : undefined,
|
|
1180
|
+
branch: typeof body.branch === "string" ? body.branch : undefined,
|
|
1181
|
+
remote: typeof body.remote === "string" ? body.remote : undefined,
|
|
1182
|
+
forceWithLease: body.forceWithLease === true,
|
|
1183
|
+
setUpstream: body.setUpstream === true,
|
|
1184
|
+
actor: "human",
|
|
1185
|
+
});
|
|
1186
|
+
broadcast("changes", changes.list());
|
|
1187
|
+
options.notify?.(`后台网页:已推送 ${out.repo.name} (${out.remote}/${out.branch})`);
|
|
1188
|
+
return sendJson(res, 200, { ok: true, ...out });
|
|
1189
|
+
}
|
|
1190
|
+
if (url.pathname === "/api/git/policy" && req.method === "POST") {
|
|
1191
|
+
const body = await readControlBody(req);
|
|
1192
|
+
if (typeof body.requireHumanPush !== "boolean")
|
|
1193
|
+
throw new HttpError(400, "requireHumanPush 需要为布尔值");
|
|
1194
|
+
const wb = await setGitPushPolicy(harness, context, body.requireHumanPush);
|
|
1195
|
+
broadcast("state", await state());
|
|
1196
|
+
options.notify?.(`后台网页:${wb.requireHumanPush ? "已切换为“推送前须人工确认”" : "已允许 Agent 执行无分叉快进推送"}`);
|
|
1197
|
+
return sendJson(res, 200, { ok: true, requireHumanPush: wb.requireHumanPush });
|
|
1198
|
+
}
|
|
1199
|
+
const gitGateMatch = url.pathname.match(/^\/api\/git\/gates\/([^/]+)\/resolve$/);
|
|
1200
|
+
if (gitGateMatch && req.method === "POST") {
|
|
1201
|
+
const body = await readControlBody(req);
|
|
1202
|
+
const id = decodeURIComponent(gitGateMatch[1]);
|
|
1203
|
+
const action = body.action;
|
|
1204
|
+
if (action !== "approve" && action !== "reject")
|
|
1205
|
+
throw new HttpError(400, "action 需要为 approve 或 reject");
|
|
1206
|
+
const note = typeof body.note === "string" ? body.note : undefined;
|
|
1207
|
+
const out = await resolvePushGate({ config, changes, harness, context }, id, action, note);
|
|
1208
|
+
broadcast("changes", changes.list());
|
|
1209
|
+
broadcast("state", await state());
|
|
1210
|
+
options.notify?.(`后台网页:${action === "approve" ? "已批准并执行" : "已驳回"} Git 确认单 #${id}`);
|
|
1211
|
+
return sendJson(res, 200, { ok: true, ...out });
|
|
1212
|
+
}
|
|
1213
|
+
const changeDiff = url.pathname.match(/^\/api\/changes\/([^/]+)\/diff$/);
|
|
1214
|
+
if (changeDiff && req.method === "GET") {
|
|
1215
|
+
const ch = changes.get(decodeURIComponent(changeDiff[1]));
|
|
1216
|
+
if (!ch)
|
|
1217
|
+
return sendJson(res, 404, { error: "没有这个改动" });
|
|
1218
|
+
// 已合并的看完整改动,其余看还没合并的部分
|
|
1219
|
+
const [from, to] = ch.status === "applied" ? [ch.base, ch.head] : changes.range(ch);
|
|
1220
|
+
if (from === to)
|
|
1221
|
+
return sendJson(res, 200, { text: "", truncated: false });
|
|
1222
|
+
try {
|
|
1223
|
+
return sendJson(res, 200, await diffText(ch.root, from, to));
|
|
1224
|
+
}
|
|
1225
|
+
catch (error) {
|
|
1226
|
+
return sendJson(res, 200, { text: "", truncated: false, error: error instanceof Error ? error.message : String(error) });
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
if (url.pathname === "/api/agents" && req.method === "POST") {
|
|
1230
|
+
const out = await mutateSettings(req, false, (body, draft, current) => {
|
|
1231
|
+
const { id, member, next } = applyApiMemberDraft(draft, options.settings.path, current, {
|
|
1232
|
+
mode: "add",
|
|
1233
|
+
id: String(body.id ?? ""),
|
|
1234
|
+
name: typeof body.name === "string" ? body.name : undefined,
|
|
1235
|
+
description: typeof body.description === "string" ? body.description : undefined,
|
|
1236
|
+
instructions: typeof body.instructions === "string" ? body.instructions : undefined,
|
|
1237
|
+
enabled: typeof body.enabled === "boolean" ? body.enabled : undefined,
|
|
1238
|
+
workspace: body.workspace === "none" || body.workspace === "code" ? body.workspace : undefined,
|
|
1239
|
+
type: typeof body.type === "string" ? body.type : undefined,
|
|
1240
|
+
baseUrl: typeof body.baseUrl === "string" ? body.baseUrl : undefined,
|
|
1241
|
+
defaultModel: typeof body.defaultModel === "string" ? body.defaultModel : undefined,
|
|
1242
|
+
tools: Array.isArray(body.tools) ? body.tools.map(String) : undefined,
|
|
1243
|
+
bashAllow: Array.isArray(body.bashAllow) ? body.bashAllow.map(String) : undefined,
|
|
1244
|
+
secret: typeof body.secret === "string" ? body.secret : undefined,
|
|
1245
|
+
});
|
|
1246
|
+
return { next, notify: `后台网页:已新增成员 ${member.name ?? id}(${id})`, result: { id } };
|
|
1247
|
+
});
|
|
1248
|
+
return sendJson(res, 200, out);
|
|
1249
|
+
}
|
|
1250
|
+
const agentEdit = url.pathname.match(/^\/api\/agents\/([^/]+)$/);
|
|
1251
|
+
if (agentEdit && req.method === "POST") {
|
|
1252
|
+
const id = decodeURIComponent(agentEdit[1]);
|
|
1253
|
+
const out = await mutateSettings(req, false, (body, draft, current) => {
|
|
1254
|
+
const existing = current.agents[id];
|
|
1255
|
+
if (!existing)
|
|
1256
|
+
throw new Error(`没有成员 ${id}`);
|
|
1257
|
+
const fullEdit = existing.api && body.quick !== true && ["name", "description", "instructions", "workspace", "type", "baseUrl", "tools", "bashAllow"].some((k) => body[k] !== undefined);
|
|
1258
|
+
const { next, member } = fullEdit
|
|
1259
|
+
? applyApiMemberDraft(draft, options.settings.path, current, {
|
|
1260
|
+
mode: "edit",
|
|
1261
|
+
id,
|
|
1262
|
+
name: typeof body.name === "string" ? body.name : undefined,
|
|
1263
|
+
description: typeof body.description === "string" ? body.description : undefined,
|
|
1264
|
+
instructions: typeof body.instructions === "string" ? body.instructions : undefined,
|
|
1265
|
+
enabled: typeof body.enabled === "boolean" ? body.enabled : undefined,
|
|
1266
|
+
workspace: body.workspace === "none" || body.workspace === "code" ? body.workspace : undefined,
|
|
1267
|
+
type: typeof body.type === "string" ? body.type : undefined,
|
|
1268
|
+
baseUrl: typeof body.baseUrl === "string" ? body.baseUrl : undefined,
|
|
1269
|
+
defaultModel: typeof body.defaultModel === "string" ? body.defaultModel : undefined,
|
|
1270
|
+
tools: Array.isArray(body.tools) ? body.tools.map(String) : undefined,
|
|
1271
|
+
bashAllow: Array.isArray(body.bashAllow) ? body.bashAllow.map(String) : undefined,
|
|
1272
|
+
secret: typeof body.secret === "string" ? body.secret : undefined,
|
|
1273
|
+
})
|
|
1274
|
+
: applyQuickMemberDraft(draft, current, id, {
|
|
1275
|
+
enabled: typeof body.enabled === "boolean" ? body.enabled : undefined,
|
|
1276
|
+
defaultModel: typeof body.defaultModel === "string" ? body.defaultModel : undefined,
|
|
1277
|
+
secret: typeof body.secret === "string" ? body.secret : undefined,
|
|
1278
|
+
});
|
|
1279
|
+
return { next, notify: `后台网页:已更新成员 ${member.name ?? id}(${id})`, result: { id } };
|
|
1280
|
+
});
|
|
1281
|
+
return sendJson(res, 200, out);
|
|
1282
|
+
}
|
|
1283
|
+
if (url.pathname === "/api/limits" && req.method === "POST") {
|
|
1284
|
+
const out = await mutateSettings(req, false, (body, draft, current) => ({
|
|
1285
|
+
next: applyLimitsDraft(draft, current, {
|
|
1286
|
+
maxConcurrent: body.maxConcurrent === undefined ? undefined : Number(body.maxConcurrent),
|
|
1287
|
+
perMember: body.perMember === undefined ? undefined : Number(body.perMember),
|
|
1288
|
+
perService: body.perService === undefined ? undefined : Number(body.perService),
|
|
1289
|
+
perRunUsd: body.perRunUsd === null || body.perRunUsd === "" ? null : body.perRunUsd === undefined ? undefined : Number(body.perRunUsd),
|
|
1290
|
+
reservePerDispatchUsd: body.reservePerDispatchUsd === undefined ? undefined : Number(body.reservePerDispatchUsd),
|
|
1291
|
+
}),
|
|
1292
|
+
notify: "后台网页:已更新并发与预算配额",
|
|
1293
|
+
}));
|
|
1294
|
+
return sendJson(res, 200, out);
|
|
1295
|
+
}
|
|
1296
|
+
if (url.pathname === "/api/orchestrator" && req.method === "POST") {
|
|
1297
|
+
const out = await mutateSettings(req, true, (body, draft, current) => ({
|
|
1298
|
+
next: applyOrchestratorDraft(draft, current, {
|
|
1299
|
+
type: typeof body.type === "string" ? body.type : "",
|
|
1300
|
+
baseUrl: typeof body.baseUrl === "string" ? body.baseUrl : "",
|
|
1301
|
+
modelId: typeof body.modelId === "string" ? body.modelId : "",
|
|
1302
|
+
secret: typeof body.secret === "string" ? body.secret : undefined,
|
|
1303
|
+
}),
|
|
1304
|
+
notify: `后台网页:已更新总控模型为 ${String(body.modelId ?? "").trim()}`,
|
|
1305
|
+
}));
|
|
1306
|
+
return sendJson(res, 200, out);
|
|
1307
|
+
}
|
|
1308
|
+
if (url.pathname === "/api/autonomy" && req.method === "POST") {
|
|
1309
|
+
const out = await mutateSettings(req, false, (body, draft, current) => {
|
|
1310
|
+
const checks = body.checks === undefined ? undefined : Array.isArray(body.checks) ? body.checks.map((item) => {
|
|
1311
|
+
if (!item || typeof item !== "object")
|
|
1312
|
+
return item;
|
|
1313
|
+
const row = item;
|
|
1314
|
+
return {
|
|
1315
|
+
name: row.name,
|
|
1316
|
+
command: row.command,
|
|
1317
|
+
args: row.args,
|
|
1318
|
+
...(row.timeoutSeconds === undefined || row.timeoutSeconds === null || row.timeoutSeconds === "" ? {} : { timeoutSeconds: Number(row.timeoutSeconds) }),
|
|
1319
|
+
};
|
|
1320
|
+
}) : body.checks;
|
|
1321
|
+
return {
|
|
1322
|
+
next: applyAutonomyDraft(draft, current, {
|
|
1323
|
+
enabled: body.enabled,
|
|
1324
|
+
maxRepairAttempts: body.maxRepairAttempts === undefined ? undefined : Number(body.maxRepairAttempts),
|
|
1325
|
+
resultMaxChars: body.resultMaxChars === undefined ? undefined : Number(body.resultMaxChars),
|
|
1326
|
+
checks: checks,
|
|
1327
|
+
}),
|
|
1328
|
+
notify: "后台网页:已更新自动验收设置",
|
|
1329
|
+
};
|
|
1330
|
+
});
|
|
1331
|
+
return sendJson(res, 200, out);
|
|
1332
|
+
}
|
|
1333
|
+
if (url.pathname === "/api/workflow" && req.method === "POST") {
|
|
1334
|
+
const body = await readControlBody(req);
|
|
1335
|
+
if (body.action !== "pause" && body.action !== "resume")
|
|
1336
|
+
throw new HttpError(400, "action 需要为 pause 或 resume");
|
|
1337
|
+
const wf = await app.workflow(body.action, context);
|
|
1338
|
+
broadcast("project", null);
|
|
1339
|
+
options.notify?.(`后台网页:${wf.paused ? "已暂停自动协作" : "已恢复自动协作"}`);
|
|
1340
|
+
return sendJson(res, 200, { ok: true, ...wf });
|
|
1341
|
+
}
|
|
1342
|
+
if (url.pathname === "/api/changes/clean" && req.method === "POST") {
|
|
1343
|
+
await readControlBody(req);
|
|
1344
|
+
const r = await cleanChanges(changes);
|
|
1345
|
+
options.notify?.(`后台网页:${r.message}`);
|
|
1346
|
+
return sendJson(res, r.ok ? 200 : 409, r);
|
|
1347
|
+
}
|
|
1348
|
+
const changeAction = url.pathname.match(/^\/api\/changes\/([^/]+)\/(apply|drop)$/);
|
|
1349
|
+
if (changeAction && req.method === "POST") {
|
|
1350
|
+
await readControlBody(req);
|
|
1351
|
+
const id = decodeURIComponent(changeAction[1]);
|
|
1352
|
+
const r = changeAction[2] === "apply" ? await applyChange(changes, id) : await dropChange(changes, id);
|
|
1353
|
+
if (!r.ok)
|
|
1354
|
+
throw new HttpError(r.message.startsWith("找不到") ? 404 : 409, r.message);
|
|
1355
|
+
if (changeAction[2] === "apply") {
|
|
1356
|
+
const applied = changes.get(id);
|
|
1357
|
+
await harness.commit((tx) => appendUxEvent(tx, {
|
|
1358
|
+
sessionId: String(root.id),
|
|
1359
|
+
eventType: "APPLIED",
|
|
1360
|
+
payload: { changeId: id, lines: (applied?.add ?? 0) + (applied?.del ?? 0), via: "web" },
|
|
1361
|
+
createdAt: Date.now(),
|
|
1362
|
+
}), context);
|
|
1363
|
+
}
|
|
1364
|
+
options.notify?.(`后台网页:${r.message}`);
|
|
1365
|
+
return sendJson(res, 200, r);
|
|
1366
|
+
}
|
|
1367
|
+
if (url.pathname === "/api/integrations" && req.method === "POST") {
|
|
1368
|
+
const body = await readControlBody(req);
|
|
1369
|
+
const changeIds = Array.isArray(body.changeIds) ? body.changeIds.map((x) => String(x).trim()).filter(Boolean) : [];
|
|
1370
|
+
if (changeIds.length < 2)
|
|
1371
|
+
throw new HttpError(400, "联合集成至少需要选择 2 个改动 ID");
|
|
1372
|
+
const record = await app.integrate(root.id, changeIds, context);
|
|
1373
|
+
options.notify?.(`后台网页:已发起联合集成 #${record.id}(${changeIds.map((x) => `#${x}`).join(" + ")})`);
|
|
1374
|
+
return sendJson(res, 200, { ok: true, integration: integrationSummary(record) });
|
|
1375
|
+
}
|
|
1376
|
+
const integrationAction = url.pathname.match(/^\/api\/integrations\/([^/]+)\/(rerun|repair|cancel)$/);
|
|
1377
|
+
if (integrationAction && req.method === "POST") {
|
|
1378
|
+
const body = await readControlBody(req);
|
|
1379
|
+
const id = decodeURIComponent(integrationAction[1]);
|
|
1380
|
+
const act = integrationAction[2];
|
|
1381
|
+
if (act === "cancel") {
|
|
1382
|
+
await app.cancelIntegration(root.id, id, context);
|
|
1383
|
+
options.notify?.(`后台网页:已取消集成 #${id}`);
|
|
1384
|
+
return sendJson(res, 200, { ok: true });
|
|
1385
|
+
}
|
|
1386
|
+
if (act === "rerun") {
|
|
1387
|
+
const record = await app.rerunIntegration(root.id, id, context);
|
|
1388
|
+
options.notify?.(`后台网页:已重跑集成检查 #${record.id}`);
|
|
1389
|
+
return sendJson(res, 200, { ok: true, integration: integrationSummary(record) });
|
|
1390
|
+
}
|
|
1391
|
+
const member = typeof body.member === "string" ? body.member.trim() : "";
|
|
1392
|
+
if (!member)
|
|
1393
|
+
throw new HttpError(400, "需要指定修复成员 ID");
|
|
1394
|
+
const note = typeof body.note === "string" ? body.note.trim() || undefined : undefined;
|
|
1395
|
+
const record = await app.repairIntegration(root.id, id, member, note, context);
|
|
1396
|
+
options.notify?.(`后台网页:已派 ${member} 修复集成 #${record.id}`);
|
|
1397
|
+
return sendJson(res, 200, { ok: true, integration: integrationSummary(record) });
|
|
1398
|
+
}
|
|
1399
|
+
const taskRecover = url.pathname.match(/^\/api\/tasks\/([^/]+)\/recover$/);
|
|
1400
|
+
if (taskRecover && req.method === "POST") {
|
|
1401
|
+
const body = await readControlBody(req, 16384);
|
|
1402
|
+
const id = decodeURIComponent(taskRecover[1]);
|
|
1403
|
+
const action = body.action;
|
|
1404
|
+
if (!["resume", "supply", "reassign", "cancel"].includes(String(action)))
|
|
1405
|
+
throw new HttpError(400, "action 需要为 resume、supply、reassign 或 cancel");
|
|
1406
|
+
const args = {
|
|
1407
|
+
id,
|
|
1408
|
+
action: action,
|
|
1409
|
+
note: typeof body.note === "string" ? body.note : "",
|
|
1410
|
+
...(typeof body.member === "string" && body.member.trim() ? { member: body.member.trim() } : {}),
|
|
1411
|
+
};
|
|
1412
|
+
if (args.action === "cancel") {
|
|
1413
|
+
const board = await harness.commit(async (tx) => {
|
|
1414
|
+
await prepareRecovery(tx, root.id, config, changes, args, randomUUID(), Date.now());
|
|
1415
|
+
return JSON.parse(JSON.stringify(await tx.doc(Board)));
|
|
1416
|
+
}, context);
|
|
1417
|
+
try {
|
|
1418
|
+
app.project.writeAssign(board);
|
|
1419
|
+
}
|
|
1420
|
+
catch { }
|
|
1421
|
+
options.notify?.(`后台网页:已取消任务 ${id} 的恢复计划`);
|
|
1422
|
+
return sendJson(res, 200, { ok: true, cancelled: true });
|
|
1423
|
+
}
|
|
1424
|
+
const job = await app.recoverTask(root.id, args, randomUUID(), context);
|
|
1425
|
+
options.notify?.(`后台网页:恢复任务 ${id} 已交给 ${job.agent}(后台 ${job.id})`);
|
|
1426
|
+
return sendJson(res, 200, { ok: true, jobId: job.id, agent: job.agent });
|
|
1427
|
+
}
|
|
1428
|
+
const opResolve = url.pathname.match(/^\/api\/operations\/([^/]+)\/resolve$/);
|
|
1429
|
+
if (opResolve && req.method === "POST") {
|
|
1430
|
+
const body = await readControlBody(req, 8192);
|
|
1431
|
+
const id = decodeURIComponent(opResolve[1]);
|
|
1432
|
+
const outcome = body.outcome;
|
|
1433
|
+
if (outcome !== "succeeded" && outcome !== "not_applied")
|
|
1434
|
+
throw new HttpError(400, "outcome 需要为 succeeded 或 not_applied");
|
|
1435
|
+
const evidence = typeof body.evidence === "string" ? body.evidence : "";
|
|
1436
|
+
const message = await harness.commit((tx) => resolveOperation(tx, id, outcome, evidence, Date.now()), context);
|
|
1437
|
+
options.notify?.(`后台网页:已核对外部操作 ${id}(${outcome})`);
|
|
1438
|
+
return sendJson(res, 200, { ok: true, message });
|
|
1439
|
+
}
|
|
1440
|
+
if (url.pathname === "/api/abort" && req.method === "POST") {
|
|
1441
|
+
await readControlBody(req);
|
|
1442
|
+
await root.abort(context);
|
|
1443
|
+
options.notify?.("后台网页:已中止本轮");
|
|
1444
|
+
return sendJson(res, 200, { ok: true });
|
|
1445
|
+
}
|
|
1446
|
+
if (url.pathname === "/api/reset" && req.method === "POST") {
|
|
1447
|
+
await readControlBody(req);
|
|
1448
|
+
await root.reset(undefined, context);
|
|
1449
|
+
options.notify?.("后台网页:已开始新的上下文");
|
|
1450
|
+
return sendJson(res, 200, { ok: true });
|
|
1451
|
+
}
|
|
1452
|
+
if (url.pathname.startsWith("/api/"))
|
|
1453
|
+
return sendJson(res, 404, { error: "unknown api" });
|
|
1454
|
+
if (req.method === "GET")
|
|
1455
|
+
return serveStatic(url.pathname, res);
|
|
1456
|
+
sendJson(res, 405, { error: "method not allowed" });
|
|
1457
|
+
}
|
|
1458
|
+
catch (error) {
|
|
1459
|
+
if (error instanceof HttpError)
|
|
1460
|
+
return sendJson(res, error.status, { error: error.message });
|
|
1461
|
+
const ge = error;
|
|
1462
|
+
if (ge && typeof ge.statusCode === "number") {
|
|
1463
|
+
return sendJson(res, ge.statusCode, {
|
|
1464
|
+
error: ge.message,
|
|
1465
|
+
...(ge.code ? { code: ge.code } : {}),
|
|
1466
|
+
...(ge.ahead !== undefined ? { ahead: ge.ahead } : {}),
|
|
1467
|
+
...(ge.behind !== undefined ? { behind: ge.behind } : {}),
|
|
1468
|
+
...(ge.gate ? { gate: ge.gate } : {}),
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1472
|
+
const status = /找不到|没有这个/.test(message) ? 404 : /仍在运行|已有恢复计划|已暂停|busy|冲突/i.test(message) ? 409 : /需要|无效|不能|不可用|不能为空/.test(message) ? 400 : 500;
|
|
1473
|
+
sendJson(res, status, { error: message });
|
|
1474
|
+
}
|
|
1475
|
+
};
|
|
1476
|
+
return { handle, dispose };
|
|
1477
|
+
}
|
|
1478
|
+
catch (error) {
|
|
1479
|
+
await dispose();
|
|
1480
|
+
throw error;
|
|
1481
|
+
}
|
|
1482
|
+
}
|