@evandu/super-pi 0.1.241 → 0.1.243

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/agents/code-auditor.md +58 -0
  2. package/agents/code-designer.md +58 -0
  3. package/agents/document-organizer.md +42 -0
  4. package/agents/solution-designer.md +56 -0
  5. package/agents/super-pi-memory/index.ts +3 -2
  6. package/dist/client/.super-pi-client-sources.json +11 -6
  7. package/dist/client/assets/{CodeMirrorEditor-CiOKD-_q.js → CodeMirrorEditor-B7eDr7dY.js} +1 -1
  8. package/dist/client/assets/{GitDiffEditor-D5VMi7K-.js → GitDiffEditor-pYaHOM0Q.js} +1 -1
  9. package/dist/client/assets/index-CfAcuYba.css +1 -0
  10. package/dist/client/assets/{index-oUDSLOqG.js → index-D0Po7xmY.js} +54 -54
  11. package/dist/client/index.html +2 -2
  12. package/dist/server/active-memory.d.ts +37 -5
  13. package/dist/server/active-memory.js +191 -10
  14. package/dist/server/agents.d.ts +1 -1
  15. package/dist/server/agents.js +1 -1
  16. package/dist/server/application/group-chat-service.d.ts +55 -0
  17. package/dist/server/application/group-chat-service.js +624 -0
  18. package/dist/server/application/run-service.d.ts +1 -0
  19. package/dist/server/application/run-service.js +20 -1
  20. package/dist/server/engineering-learning.d.ts +30 -0
  21. package/dist/server/engineering-learning.js +106 -0
  22. package/dist/server/http-server.js +171 -91
  23. package/dist/server/index.js +5 -1
  24. package/dist/server/memory-recall.d.ts +16 -1
  25. package/dist/server/memory-recall.js +22 -8
  26. package/dist/server/memory.d.ts +10 -1
  27. package/dist/server/memory.js +11 -6
  28. package/dist/server/runtime.d.ts +12 -12
  29. package/dist/server/runtime.js +68 -11
  30. package/dist/server/server-context.d.ts +1 -0
  31. package/dist/server/update-status.d.ts +14 -0
  32. package/dist/server/update-status.js +69 -0
  33. package/dist/server/update.d.ts +0 -17
  34. package/dist/server/update.js +0 -26
  35. package/dist/shared/group-chat.d.ts +67 -0
  36. package/dist/shared/group-chat.js +1 -0
  37. package/dist/shared/update-status.d.ts +28 -0
  38. package/dist/shared/update-status.js +1 -0
  39. package/package.json +4 -1
  40. package/scripts/restart-server.mjs +9 -1
  41. package/dist/client/assets/index-CwH7sttH.css +0 -1
@@ -0,0 +1,624 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { open, readFile, realpath, writeFile } from "node:fs/promises";
3
+ import { isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { DEFAULT_GROUP_MEMBER_IDS } from "../../shared/group-chat.js";
5
+ import { CODING_STANDARD_REQUEST } from "../active-memory.js";
6
+ import { applicableRules, assertModelAllowed } from "../model-filter.js";
7
+ import { replaceFile } from "../persistence/rename.js";
8
+ const MAX_AUTOMATIC_REPLIES = 10;
9
+ const MAX_REPLIES_PER_MEMBER = 3;
10
+ const CONTEXT_MESSAGES = 20;
11
+ const MAX_CONTENT = 32_000;
12
+ const timestamp = () => new Date().toISOString();
13
+ function inputText(value, limit, label) {
14
+ if (typeof value !== "string" || value.length > limit)
15
+ throw new Error(`${label}格式无效或超过长度上限。`);
16
+ return value.trim();
17
+ }
18
+ function summary({ id, workspaceId, title, updatedAt }) {
19
+ return { id, workspaceId, title, updatedAt };
20
+ }
21
+ async function readReferences(workspacePath, input) {
22
+ if (!Array.isArray(input) || !input.length)
23
+ return undefined;
24
+ const paths = [...new Set(input)];
25
+ if (paths.length > 4)
26
+ throw new Error("一条群聊消息最多引用四个文件。");
27
+ const root = await realpath(workspacePath);
28
+ return Promise.all(paths.map(async (value) => {
29
+ const path = inputText(value, 2048, "引用文件路径");
30
+ const filePath = await realpath(resolve(root, path));
31
+ const inside = relative(root, filePath);
32
+ if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
33
+ throw new Error("群聊只能引用工作区内的文件。");
34
+ const file = await open(filePath, "r");
35
+ try {
36
+ const stat = await file.stat();
37
+ if (!stat.isFile())
38
+ throw new Error(`「${path}」不是普通文件。`);
39
+ const bytes = Buffer.alloc(Math.min(stat.size, 8192));
40
+ const { bytesRead } = await file.read(bytes, 0, bytes.length, 0);
41
+ const used = bytes.subarray(0, bytesRead);
42
+ if (used.includes(0))
43
+ throw new Error(`「${path}」不是文本文件。`);
44
+ const excerpt = used.toString("utf8") + (stat.size > bytesRead ? "\n[文件摘录已截断]" : "");
45
+ return { path, excerpt };
46
+ }
47
+ finally {
48
+ await file.close();
49
+ }
50
+ }));
51
+ }
52
+ function route(text, candidates, anchors) {
53
+ const parsed = JSON.parse(text.trim().replace(/^```(?:json)?\s*|\s*```$/gi, ""));
54
+ if (!parsed || typeof parsed !== "object")
55
+ throw new Error("主持人未返回有效决定。");
56
+ const decision = parsed;
57
+ const reason = typeof decision.reason === "string" ? decision.reason.trim().slice(0, 320) : undefined;
58
+ if (decision.action === "finish")
59
+ return { action: "finish", reason };
60
+ if (decision.action === "blocked" && reason)
61
+ return { action: "blocked", reason };
62
+ if (decision.action === "wait")
63
+ return { action: "wait", memberId: typeof decision.memberId === "string" ? decision.memberId : undefined };
64
+ if (!["reply", "background"].includes(String(decision.action)) || typeof decision.memberId !== "string" || !candidates.some(member => member.id === decision.memberId)) {
65
+ throw new Error("主持人选择了无效的群成员。");
66
+ }
67
+ const replyTo = typeof decision.replyTo === "string" && anchors.has(decision.replyTo) ? decision.replyTo : undefined;
68
+ const assignment = inputText(decision.assignment, 1600, "接话任务");
69
+ if (!assignment)
70
+ throw new Error("主持人没有给出接话任务。");
71
+ return { action: "reply", memberId: decision.memberId, replyTo, assignment, reason, background: decision.action === "background" };
72
+ }
73
+ function extractHandoff(author, content, members) {
74
+ const line = content.trimEnd().split(/\r?\n/u).at(-1)?.trim();
75
+ const request = line?.match(/^@([^::]{1,100})[::]\s*(.{1,800})$/u);
76
+ if (!request)
77
+ return;
78
+ const recipient = request[1].trim();
79
+ const matches = members.filter(member => member.id === recipient || member.name === recipient);
80
+ const assignment = request[2].trim();
81
+ if (matches.length === 1 && matches[0].id !== author && assignment)
82
+ return { memberId: matches[0].id, assignment };
83
+ }
84
+ function outstandingHandoffs(replies) {
85
+ return replies.flatMap(post => {
86
+ const handoff = post.status === "completed" ? post.handoff : undefined;
87
+ const delegated = handoff && replies.some(reply => reply.replyTo === post.id && reply.memberId === handoff.memberId && reply.status !== "failed");
88
+ return handoff && !delegated ? [{ ...handoff, replyTo: post.id, from: post.memberId }] : [];
89
+ });
90
+ }
91
+ export class GroupChatService {
92
+ filePath;
93
+ store;
94
+ runtime;
95
+ memory;
96
+ rooms = [];
97
+ writes = Promise.resolve();
98
+ running = new Map();
99
+ memberRuns = new Map();
100
+ controllers = new Map();
101
+ live = new Map();
102
+ streamRevisions = new Map();
103
+ closing = false;
104
+ constructor(filePath, store, runtime, memory) {
105
+ this.filePath = filePath;
106
+ this.store = store;
107
+ this.runtime = runtime;
108
+ this.memory = memory;
109
+ }
110
+ static async open(filePath, store, runtime, memory) {
111
+ const service = new GroupChatService(filePath, store, runtime, memory);
112
+ try {
113
+ service.rooms = JSON.parse(await readFile(filePath, "utf8"));
114
+ }
115
+ catch (error) {
116
+ if (error.code !== "ENOENT")
117
+ throw error;
118
+ }
119
+ if (service.rooms.some(room => room.messages.some(post => post.status === "running" || (post.role === "assistant" && post.status === "queued")))) {
120
+ await service.edit(rooms => {
121
+ for (const room of rooms)
122
+ for (const post of room.messages)
123
+ if (post.status === "running" || (post.role === "assistant" && post.status === "queued")) {
124
+ post.status = "interrupted";
125
+ post.error = "服务重启,本次发言已中断。";
126
+ room.revision += 1;
127
+ }
128
+ });
129
+ }
130
+ for (const room of service.rooms)
131
+ service.kick(room.id);
132
+ return service;
133
+ }
134
+ workspace(id) {
135
+ const workspace = this.store.workspace(id);
136
+ if (!workspace || workspace.closedAt)
137
+ throw new Error("工作区不存在或已关闭。");
138
+ return workspace;
139
+ }
140
+ find(rooms, workspaceId, id) {
141
+ this.workspace(workspaceId);
142
+ const room = rooms.find(item => item.id === id && item.workspaceId === workspaceId);
143
+ if (!room)
144
+ throw new Error("此工作区没有这个群聊。");
145
+ return room;
146
+ }
147
+ edit(change) {
148
+ const write = this.writes.then(async () => {
149
+ const rooms = structuredClone(this.rooms);
150
+ const result = change(rooms);
151
+ const temporary = this.filePath + ".tmp";
152
+ await writeFile(temporary, JSON.stringify(rooms), { encoding: "utf8", mode: 0o600 });
153
+ await replaceFile(temporary, this.filePath);
154
+ this.rooms = rooms;
155
+ return result;
156
+ });
157
+ this.writes = write.then(() => undefined, () => undefined);
158
+ return write;
159
+ }
160
+ list(workspaceId) {
161
+ this.workspace(workspaceId);
162
+ return this.rooms.filter(room => room.workspaceId === workspaceId).map(summary).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
163
+ }
164
+ get(workspaceId, id) {
165
+ const room = structuredClone(this.find(this.rooms, workspaceId, id));
166
+ for (const post of room.messages)
167
+ if (post.status === "running")
168
+ post.content = this.live.get(post.id) ?? post.content;
169
+ return { ...room, revision: `${room.revision}:${this.streamRevisions.get(id) ?? 0}` };
170
+ }
171
+ async moderator(workspaceId, body) {
172
+ const workspace = this.workspace(workspaceId);
173
+ const prompt = inputText(body.prompt ?? "", 8_000, "主持人 Prompt");
174
+ if (!body.model)
175
+ return { prompt };
176
+ if (typeof body.model !== "object")
177
+ throw new Error("主持人模型无效。");
178
+ const requested = body.model;
179
+ const catalog = await this.runtime.catalog();
180
+ const model = catalog.models.find(item => item.provider === requested.provider && item.modelId === requested.modelId);
181
+ if (!model)
182
+ throw new Error("主持人模型不可用。");
183
+ assertModelAllowed(this.store.modelFilterRules(), workspace, model);
184
+ return { prompt, model: { provider: model.provider, modelId: model.modelId, label: model.label } };
185
+ }
186
+ async resolveMembers(id, input, existing = []) {
187
+ const memberIds = Array.isArray(input) ? [...new Set(input)] : [];
188
+ if (memberIds.length < 2 || memberIds.length > 8)
189
+ throw new Error("请选择 2 到 8 位主 Agent。");
190
+ return Promise.all(memberIds.map(async (memberId) => {
191
+ if (typeof memberId !== "string")
192
+ throw new Error("群成员无效。");
193
+ const saved = existing.find(member => member.id === memberId);
194
+ if (saved)
195
+ return saved;
196
+ const agent = await this.runtime.agentFor?.({ id, agentId: memberId });
197
+ if (!agent || agent.id !== memberId || agent.mode !== "primary" || agent.hidden)
198
+ throw new Error(`主 Agent ${memberId} 不可用。`);
199
+ return { id: agent.id, name: agent.name, description: agent.description };
200
+ }));
201
+ }
202
+ async create(workspaceId, input) {
203
+ this.workspace(workspaceId);
204
+ const title = inputText(input.title, 100, "群名");
205
+ if (!title)
206
+ throw new Error("请输入群名。");
207
+ const id = randomUUID();
208
+ const members = await this.resolveMembers(id, input.memberIds ?? DEFAULT_GROUP_MEMBER_IDS);
209
+ const moderator = await this.moderator(workspaceId, input.moderator ?? {});
210
+ const room = { id, workspaceId, title, updatedAt: timestamp(), revision: 0, members, moderator, messages: [] };
211
+ await this.edit(rooms => { rooms.push(room); });
212
+ return this.get(workspaceId, id);
213
+ }
214
+ async configure(workspaceId, id, input) {
215
+ const current = this.find(this.rooms, workspaceId, id);
216
+ const moderator = await this.moderator(workspaceId, input);
217
+ const members = input.memberIds === undefined ? undefined : await this.resolveMembers(id, input.memberIds, current.members);
218
+ await this.edit(rooms => {
219
+ const room = this.find(rooms, workspaceId, id);
220
+ if (members) {
221
+ for (const post of room.messages)
222
+ if (post.role === "assistant")
223
+ post.memberName ??= room.members.find(member => member.id === post.memberId)?.name;
224
+ room.members = members;
225
+ }
226
+ room.moderator = moderator;
227
+ room.revision += 1;
228
+ });
229
+ return this.get(workspaceId, id);
230
+ }
231
+ async send(workspaceId, id, input) {
232
+ if (this.closing)
233
+ throw new Error("服务正在关闭。");
234
+ const content = inputText(input.content, MAX_CONTENT, "消息");
235
+ const clientId = inputText(input.clientId, 128, "发送标识");
236
+ if (!content || !clientId)
237
+ throw new Error("消息内容和发送标识不能为空。");
238
+ const current = this.find(this.rooms, workspaceId, id);
239
+ if (current.messages.some(post => post.role === "user" && post.clientId === clientId))
240
+ return this.get(workspaceId, id);
241
+ const files = await readReferences(this.workspace(workspaceId).path, input.filePaths);
242
+ await this.edit(rooms => {
243
+ const room = this.find(rooms, workspaceId, id);
244
+ if (room.messages.some(post => post.role === "user" && post.clientId === clientId))
245
+ return;
246
+ const parent = typeof input.replyTo === "string" ? room.messages.find(post => post.id === input.replyTo) : undefined;
247
+ if (input.replyTo && !parent)
248
+ throw new Error("群里找不到引用的消息。");
249
+ const memberIds = [];
250
+ for (const memberId of Array.isArray(input.memberIds) ? input.memberIds : []) {
251
+ if (!room.members.some(member => member.id === memberId))
252
+ throw new Error("点名的 Agent 不在群里。");
253
+ if (!memberIds.includes(memberId))
254
+ memberIds.push(memberId);
255
+ }
256
+ if (!memberIds.length && parent?.role === "assistant" && room.members.some(member => member.id === parent.memberId))
257
+ memberIds.push(parent.memberId);
258
+ room.messages.push({ id: randomUUID(), role: "user", clientId, content, files, memberIds, replyTo: parent?.id, createdAt: timestamp(), status: "queued" });
259
+ room.updatedAt = timestamp();
260
+ room.revision += 1;
261
+ });
262
+ this.kick(id);
263
+ return this.get(workspaceId, id);
264
+ }
265
+ async stop(workspaceId, id, postId) {
266
+ const cancelled = await this.edit(rooms => {
267
+ const room = this.find(rooms, workspaceId, id);
268
+ const posts = room.messages.filter(post => (post.id === postId || (post.role === "assistant" && post.topicId === postId)) && ["queued", "running"].includes(post.status));
269
+ for (const post of posts) {
270
+ post.content = this.live.get(post.id) ?? post.content;
271
+ post.status = "cancelled";
272
+ }
273
+ room.revision += 1;
274
+ return posts.map(post => post.id);
275
+ });
276
+ for (const key of cancelled)
277
+ this.controllers.get(key)?.abort();
278
+ return this.get(workspaceId, id);
279
+ }
280
+ kick(id) {
281
+ if (this.closing)
282
+ return;
283
+ const room = this.rooms.find(item => item.id === id);
284
+ if (!room)
285
+ return;
286
+ for (const post of room.messages) {
287
+ if (post.role !== "user" || post.status !== "queued" || this.running.has(post.id))
288
+ continue;
289
+ const work = this.runTopic(room, post.id).catch(error => console.error("Super Pi: group chat failed to save its progress:", error))
290
+ .finally(() => this.running.delete(post.id));
291
+ this.running.set(post.id, work);
292
+ }
293
+ }
294
+ async runTopic(room, topicId) {
295
+ const topic = await this.edit(rooms => {
296
+ const current = rooms.find(item => item.id === room.id);
297
+ const next = current.messages.find((post) => post.role === "user" && post.id === topicId);
298
+ if (next?.status !== "queued")
299
+ return;
300
+ next.status = "running";
301
+ current.revision += 1;
302
+ return next;
303
+ });
304
+ if (!topic)
305
+ return;
306
+ const controller = new AbortController();
307
+ const pending = [];
308
+ this.controllers.set(topic.id, controller);
309
+ if (this.closing)
310
+ controller.abort();
311
+ try {
312
+ if (this.memory && CODING_STANDARD_REQUEST.test(topic.content) && !controller.signal.aborted) {
313
+ const notice = await this.memory.rememberGroupCodingStandards(room.workspaceId, room.id, topic.id, topic.content)
314
+ .catch(() => "平台未能保存代码规范,请检查主动记忆设置。");
315
+ if (notice)
316
+ await this.edit(rooms => {
317
+ const current = rooms.find(item => item.id === room.id);
318
+ const post = current.messages.find(item => item.id === topic.id && item.role === "user");
319
+ if (post?.role === "user") {
320
+ post.memoryNotice = notice;
321
+ current.revision += 1;
322
+ }
323
+ });
324
+ }
325
+ const start = async (targets) => {
326
+ const replies = await this.respond(room.id, topic, targets, controller.signal);
327
+ pending.push(...replies);
328
+ if (replies.length)
329
+ await Promise.race(replies.map(reply => reply.yields));
330
+ };
331
+ if (topic.memberIds.length)
332
+ await start(topic.memberIds.map(memberId => ({ memberId, replyTo: topic.replyTo ?? topic.id })));
333
+ let count = 0;
334
+ let incomplete;
335
+ while (!controller.signal.aborted) {
336
+ const current = this.rooms.find(item => item.id === room.id);
337
+ if (current.messages.find(post => post.id === topic.id)?.status !== "running")
338
+ break;
339
+ const replies = current.messages.filter((post) => post.role === "assistant" && post.topicId === topic.id);
340
+ const active = pending.filter(reply => replies.some(post => post.id === reply.id && (post.status === "running" || post.status === "queued")));
341
+ const busy = new Set(current.messages.flatMap(post => post.role === "assistant" && (post.status === "running" || post.status === "queued") ? [post.memberId] : []));
342
+ const available = current.members.filter(member => {
343
+ const attempted = replies.filter(post => post.memberId === member.id);
344
+ return attempted.length < MAX_REPLIES_PER_MEMBER && !attempted.some(post => post.status === "cancelled" || post.status === "interrupted");
345
+ });
346
+ const candidates = available.filter(member => !busy.has(member.id));
347
+ const handoffs = outstandingHandoffs(replies);
348
+ const remaining = MAX_AUTOMATIC_REPLIES - count;
349
+ if (active.length && (!candidates.length || !remaining)) {
350
+ await Promise.race(active.map(reply => reply.done));
351
+ continue;
352
+ }
353
+ const next = candidates.length || handoffs.length || !remaining || (replies.length && available.some(member => busy.has(member.id)))
354
+ ? await this.choose(current, topic, candidates, replies, handoffs, busy, remaining, controller.signal)
355
+ : { action: "finish" };
356
+ if (next.action === "reply") {
357
+ if (!remaining) {
358
+ incomplete = "本轮达到自动接话上限,已有进展已保留。可以告诉群里从哪一步继续。";
359
+ break;
360
+ }
361
+ const completed = replies.filter(post => post.status === "completed").sort((a, b) => (a.settledAt ?? a.createdAt).localeCompare(b.settledAt ?? b.createdAt));
362
+ const handoff = handoffs.find(item => item.memberId === next.memberId);
363
+ const replyTo = next.replyTo ?? handoff?.replyTo ?? completed.at(-1)?.id ?? topic.id;
364
+ count += 1;
365
+ await start([{ ...next, replyTo }]);
366
+ continue;
367
+ }
368
+ if (next.action === "wait") {
369
+ const work = next.memberId ? this.memberRuns.get(JSON.stringify([room.id, next.memberId])) : undefined;
370
+ if (work) {
371
+ await this.waitForWork(work, controller.signal);
372
+ continue;
373
+ }
374
+ }
375
+ if (active.length) {
376
+ await Promise.race(active.map(reply => reply.done));
377
+ continue;
378
+ }
379
+ if (next.action === "blocked") {
380
+ incomplete = next.reason;
381
+ break;
382
+ }
383
+ if (!replies.length && available.length) {
384
+ const work = available.flatMap(member => this.memberRuns.get(JSON.stringify([room.id, member.id])) ?? []);
385
+ if (work.length) {
386
+ await this.waitForWork(Promise.race(work), controller.signal);
387
+ continue;
388
+ }
389
+ }
390
+ if (next.action === "wait") {
391
+ if (this.rooms.find(item => item.id === room.id)?.revision !== current.revision)
392
+ continue;
393
+ incomplete = "本轮仍有后续工作,但当前没有对应的运行任务。已有进展已保留。";
394
+ }
395
+ else if (handoffs.length && !next.reason) {
396
+ const work = handoffs.flatMap(handoff => this.memberRuns.get(JSON.stringify([room.id, handoff.memberId])) ?? []);
397
+ if (work.length) {
398
+ await this.waitForWork(Promise.race(work), controller.signal);
399
+ continue;
400
+ }
401
+ incomplete = "本轮还有未接手的工作,已有发言和结果已保留。";
402
+ }
403
+ break;
404
+ }
405
+ const replies = this.rooms.find(item => item.id === room.id).messages.filter(post => post.role === "assistant" && post.topicId === topic.id);
406
+ await this.settle(room.id, topic.id, controller.signal, incomplete ?? (replies.some(post => post.status === "completed") ? undefined : "本轮没有收到完整回复。"));
407
+ }
408
+ catch (error) {
409
+ await Promise.allSettled(pending.map(reply => reply.done));
410
+ await this.settle(room.id, topic.id, controller.signal, error instanceof Error ? error.message : String(error));
411
+ }
412
+ finally {
413
+ await Promise.allSettled(pending.map(reply => reply.done));
414
+ this.controllers.delete(topic.id);
415
+ const current = this.rooms.find(item => item.id === room.id);
416
+ const saved = current?.messages.find(post => post.id === topic.id);
417
+ if (!this.closing && current && (saved?.status === "completed" || saved?.status === "failed")) {
418
+ this.memory?.learnFromGroup(room.workspaceId, room.id, topic, current.members.map(member => member.id), () => this.rooms.some(item => item.id === room.id && item.messages.some(post => post.id === topic.id && post.role === "user" && post.content === topic.content)));
419
+ }
420
+ }
421
+ }
422
+ context(room, topic) {
423
+ const topicIndex = room.messages.findIndex(post => post.id === topic.id);
424
+ const previous = room.messages.slice(0, topicIndex).filter(post => post.role === "user" && post.status !== "cancelled");
425
+ const topicIds = new Set(previous.map(post => post.id));
426
+ const current = room.messages.filter(post => post.role === "assistant" && post.topicId === topic.id && post.status === "completed").slice(-CONTEXT_MESSAGES);
427
+ const roomHistory = room.messages.filter(post => post.role === "assistant" ? topicIds.has(post.topicId) && post.status === "completed" : topicIds.has(post.id));
428
+ const remaining = CONTEXT_MESSAGES - current.length;
429
+ return [...(remaining ? roomHistory.slice(-remaining) : []), ...current].map(post => ({
430
+ id: post.id, author: post.role === "user" ? "用户" : post.memberName ?? room.members.find(member => member.id === post.memberId)?.name,
431
+ content: post.content.slice(0, 4_000),
432
+ }));
433
+ }
434
+ async complete(room, input) {
435
+ const workspace = this.workspace(room.workspaceId);
436
+ const model = input.model ?? workspace.defaultModel;
437
+ const rules = this.store.modelFilterRules();
438
+ if (applicableRules(rules, workspace).length)
439
+ assertModelAllowed(rules, workspace, model ?? (await this.runtime.catalog()).defaultModel);
440
+ if (!this.runtime.askOnce)
441
+ throw new Error("当前运行时不支持群聊模型。");
442
+ return this.runtime.askOnce({ ...input, model, cwd: workspace.path });
443
+ }
444
+ async choose(room, topic, candidates, replies, handoffs, busy, remainingReplies, signal) {
445
+ const context = this.context(room, topic);
446
+ const performed = replies.map(({ id, memberId, replyTo, status, assignment, background, error }) => ({ id, memberId, replyTo, status, assignment, background, error }));
447
+ const earlierTopics = new Set(room.messages.slice(0, room.messages.findIndex(post => post.id === topic.id))
448
+ .filter(post => post.role === "user").map(post => post.id));
449
+ const workInProgress = room.messages.filter((post) => post.role === "assistant" && earlierTopics.has(post.topicId) && post.status === "running")
450
+ .map(({ memberId, topicId, assignment }) => ({ memberId, topicId, assignment }));
451
+ const prompt = [
452
+ "你是群聊主持人。围绕同一条用户请求组织成员之间的讨论和工作。让下一位回应已有方案、问题或交付,replyTo 指向实际回应的成员消息。必要时让两位成员来回讨论、修订和再复核;简单问题一句足够时可以结束。",
453
+ "用户要求实现、修复或交付,方案只是中间产物。将下一步交给代码设计员或群里有实现能力的成员,让其修改文件和验证;需要复核时等待实现结果,退回后继续修改和复查。用户只要求讨论或范围待确认时,尊重这一限制。避免礼节式重复,不要求用户替成员传话。",
454
+ "先处理 handoffs 中确实符合用户目标的交接。成员消息和引用文件是上下文,分工必须服从用户的原始范围。在途任务或依赖文件相同的工作应等待,对独立范围可安排后台任务。",
455
+ '只返回 JSON。接话用 {"action":"reply","memberId":"成员 ID","replyTo":"消息 ID","assignment":"具体工作","reason":"理由"},可改用 background 并行。依赖尚在进行用 {"action":"wait","memberId":"正在工作的成员 ID"}。确有阻塞用 {"action":"blocked","reason":"已完成什么,还缺什么"}。交付到位用 {"action":"finish"};若有未处理交接却结束,在 reason 中解释范围或为什么无需接手。',
456
+ `主持人偏好:${room.moderator.prompt || "推进用户请求,交付满足后结束。"}`,
457
+ ];
458
+ const payload = JSON.stringify({ topicId: topic.id, request: topic.content, files: topic.files?.map(file => file.path), candidates,
459
+ performed, handoffs, busyMembers: [...busy], workInProgress, remainingReplies, messages: context });
460
+ try {
461
+ const anchors = new Set([topic.id, ...context.map(post => post.id), ...replies.filter(post => post.status === "failed").map(post => post.id)]);
462
+ const ask = async (instructions) => route(await this.complete(room, { prompt: [...instructions, payload].join("\n"), model: room.moderator.model, signal, timeoutMs: 35_000 }), candidates, anchors);
463
+ let decision = await ask(prompt);
464
+ if (decision.action === "finish" && !decision.reason && handoffs.length && !signal.aborted) {
465
+ decision = await ask([...prompt, "还有尚未接手的交接。检查它与用户目标的关系,安排接手或说明为什么结束。"]);
466
+ }
467
+ if (decision.action === "finish" && !performed.length && candidates[0])
468
+ return { action: "reply", memberId: candidates[0].id, replyTo: topic.id, assignment: "按用户要求推进当前工作。", reason: "交给默认成员" };
469
+ return decision;
470
+ }
471
+ catch (error) {
472
+ if (signal.aborted)
473
+ return { action: "finish" };
474
+ throw new Error(`主持人未能安排回复:${error instanceof Error ? error.message : String(error)}`);
475
+ }
476
+ }
477
+ async respond(roomId, topic, targets, signal) {
478
+ const batch = await this.edit(rooms => {
479
+ const room = rooms.find(item => item.id === roomId);
480
+ if (signal.aborted || room.messages.find(post => post.id === topic.id)?.status !== "running")
481
+ return;
482
+ const replies = targets.filter(target => room.members.some(member => member.id === target.memberId)).map(target => ({
483
+ id: randomUUID(), role: "assistant", content: "", status: "queued", createdAt: timestamp(), topicId: topic.id,
484
+ memberId: target.memberId, memberName: room.members.find(member => member.id === target.memberId)?.name,
485
+ replyTo: target.replyTo, assignment: target.assignment, routeReason: target.reason, background: target.background || undefined,
486
+ }));
487
+ room.messages.push(...replies);
488
+ room.revision += 1;
489
+ room.updatedAt = timestamp();
490
+ return replies;
491
+ });
492
+ if (!batch)
493
+ return [];
494
+ return batch.map(reply => {
495
+ const key = JSON.stringify([roomId, reply.memberId]);
496
+ const prior = this.memberRuns.get(key);
497
+ const controller = new AbortController();
498
+ this.controllers.set(reply.id, controller);
499
+ const currentStatus = this.rooms.find(room => room.id === roomId)?.messages.find(post => post.id === reply.id)?.status;
500
+ if (currentStatus !== "queued")
501
+ controller.abort();
502
+ const memberSignal = AbortSignal.any([signal, controller.signal]);
503
+ let allowNext;
504
+ const yields = new Promise(resolve => { allowNext = resolve; });
505
+ const done = this.runMember(roomId, topic, reply, memberSignal, allowNext, prior).finally(() => {
506
+ allowNext();
507
+ this.live.delete(reply.id);
508
+ this.controllers.delete(reply.id);
509
+ });
510
+ if (reply.background || prior)
511
+ allowNext();
512
+ const tail = Promise.allSettled([prior, done]).then(() => undefined).finally(() => {
513
+ if (this.memberRuns.get(key) === tail)
514
+ this.memberRuns.delete(key);
515
+ });
516
+ this.memberRuns.set(key, tail);
517
+ return { id: reply.id, done, yields };
518
+ });
519
+ }
520
+ waitForWork(work, signal) {
521
+ if (signal.aborted)
522
+ return Promise.resolve();
523
+ return new Promise(resolve => {
524
+ const finish = () => { signal.removeEventListener("abort", finish); resolve(); };
525
+ signal.addEventListener("abort", finish, { once: true });
526
+ void work.then(finish, finish);
527
+ });
528
+ }
529
+ async runMember(roomId, topic, reply, memberSignal, allowNext, prior) {
530
+ if (prior)
531
+ await this.waitForWork(prior, memberSignal);
532
+ const started = await this.edit(rooms => {
533
+ const room = rooms.find(item => item.id === roomId);
534
+ const post = room.messages.find(item => item.id === reply.id);
535
+ if (post?.status !== "queued")
536
+ return;
537
+ const cancelled = memberSignal.aborted || !room.members.some(member => member.id === reply.memberId);
538
+ post.status = cancelled ? this.closing ? "interrupted" : "cancelled" : "running";
539
+ room.revision += 1;
540
+ return cancelled ? undefined : room;
541
+ });
542
+ if (!started)
543
+ return;
544
+ let lastCheckpoint = Date.now();
545
+ let yielded = Boolean(reply.background);
546
+ const goBackground = () => {
547
+ if (yielded || memberSignal.aborted)
548
+ return;
549
+ yielded = true;
550
+ void this.edit(rooms => {
551
+ const room = rooms.find(item => item.id === roomId);
552
+ const post = room.messages.find(item => item.id === reply.id);
553
+ if (post?.role === "assistant" && post.status === "running") {
554
+ post.background = true;
555
+ room.revision += 1;
556
+ }
557
+ }).then(allowNext, allowNext);
558
+ };
559
+ const timer = setTimeout(goBackground, 4000);
560
+ try {
561
+ const agent = await this.runtime.agentFor?.({ id: reply.id, agentId: reply.memberId });
562
+ if (!agent || agent.id !== reply.memberId || agent.mode !== "primary")
563
+ throw new Error("该主 Agent 已不可用。");
564
+ const notes = await this.memory?.groupEngineeringNotes(started.workspaceId, agent.id, topic.content + "\n" + (reply.assignment ?? ""))
565
+ .catch(() => undefined);
566
+ const prompt = [
567
+ `你以 ${agent.name} 的身份在群聊中回答。直接回应引用的成员意见,推进本次分工。有可用工具且分工要求执行时,直接完成并报告实际文件与验证;其他成员可以继续讨论。只修改分工涉及的文件。`,
568
+ "确实需要另一位成员推进时,在发言末尾另起一行写 @成员名:要接手的具体事项。主持人会按原请求判断并安排。可直接使用成员 ID。",
569
+ JSON.stringify({ request: topic.content, files: topic.files, replyTo: reply.replyTo, quote: started.messages.find(post => post.id === reply.replyTo)?.content.slice(0, 4_000), assignment: reply.assignment, members: started.members, messages: this.context(started, topic), notes }),
570
+ ].join("\n");
571
+ const answer = await this.complete(started, {
572
+ prompt, agent, model: agent.model && { ...agent.model, label: agent.model.modelId }, signal: memberSignal, timeoutMs: 15 * 60_000,
573
+ onToolStart: goBackground,
574
+ onText: delta => {
575
+ if (memberSignal.aborted)
576
+ return;
577
+ this.live.set(reply.id, ((this.live.get(reply.id) ?? "") + delta).slice(0, MAX_CONTENT));
578
+ this.streamRevisions.set(roomId, (this.streamRevisions.get(roomId) ?? 0) + 1);
579
+ if (Date.now() - lastCheckpoint < 800)
580
+ return;
581
+ lastCheckpoint = Date.now();
582
+ void this.edit(rooms => {
583
+ const post = rooms.find(room => room.id === roomId).messages.find(item => item.id === reply.id);
584
+ if (post?.status === "running")
585
+ post.content = this.live.get(reply.id) ?? post.content;
586
+ }).catch(error => console.warn("Super Pi: could not checkpoint group reply:", error));
587
+ },
588
+ });
589
+ await this.settle(roomId, reply.id, memberSignal, undefined, answer);
590
+ }
591
+ catch (error) {
592
+ await this.settle(roomId, reply.id, memberSignal, error instanceof Error ? error.message : String(error), this.live.get(reply.id));
593
+ }
594
+ finally {
595
+ clearTimeout(timer);
596
+ }
597
+ }
598
+ async settle(roomId, postId, signal, error, content) {
599
+ await this.edit(rooms => {
600
+ const room = rooms.find(item => item.id === roomId);
601
+ const post = room.messages.find(item => item.id === postId);
602
+ if (post?.status !== "running")
603
+ return;
604
+ post.status = signal.aborted ? this.closing ? "interrupted" : "cancelled" : error ? "failed" : "completed";
605
+ if (content !== undefined)
606
+ post.content = content.slice(0, MAX_CONTENT);
607
+ post.error = signal.aborted ? (this.closing ? "服务停止,本次发言已中断。" : undefined) : error?.slice(0, 1600);
608
+ if (post.role === "assistant") {
609
+ post.settledAt = timestamp();
610
+ if (post.status === "completed")
611
+ post.handoff = extractHandoff(post.memberId, post.content, room.members);
612
+ }
613
+ room.revision += 1;
614
+ room.updatedAt = timestamp();
615
+ });
616
+ }
617
+ async close() {
618
+ this.closing = true;
619
+ for (const controller of this.controllers.values())
620
+ controller.abort();
621
+ await Promise.allSettled(this.running.values());
622
+ await this.writes;
623
+ }
624
+ }
@@ -73,6 +73,7 @@ export declare class RunService {
73
73
  private readonly cancelledQuestionConversations;
74
74
  private memory?;
75
75
  setMemory(memory: import("../active-memory.js").ActiveMemory): void;
76
+ private recordCodingStandards;
76
77
  /**
77
78
  * WHAT THE AGENT CHANGED, and what each file looked like before.
78
79
  *