@evandu/super-pi 0.1.240 → 0.1.242
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/agents/code-auditor.md +52 -0
- package/agents/code-designer.md +52 -0
- package/agents/document-organizer.md +42 -0
- package/agents/solution-designer.md +52 -0
- package/agents/super-pi-memory/index.ts +3 -2
- package/dist/client/.super-pi-client-sources.json +8 -6
- package/dist/client/assets/{CodeMirrorEditor-CQea8mRO.js → CodeMirrorEditor-BXlGF-8I.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-DZDcD4zI.js → GitDiffEditor-zWN38BGh.js} +1 -1
- package/dist/client/assets/index-BbMji0nU.css +1 -0
- package/dist/client/assets/{index-DxjIxdVK.js → index-D8M5Jjzq.js} +32 -25
- package/dist/client/index.html +2 -2
- package/dist/server/active-memory.d.ts +37 -5
- package/dist/server/active-memory.js +191 -10
- package/dist/server/agents.d.ts +1 -1
- package/dist/server/agents.js +1 -1
- package/dist/server/application/extension-ui-service.d.ts +3 -1
- package/dist/server/application/extension-ui-service.js +20 -7
- package/dist/server/application/group-chat-service.d.ts +55 -0
- package/dist/server/application/group-chat-service.js +547 -0
- package/dist/server/application/run-service.d.ts +16 -12
- package/dist/server/application/run-service.js +203 -158
- package/dist/server/application/workspace-service.js +1 -1
- package/dist/server/engineering-learning.d.ts +30 -0
- package/dist/server/engineering-learning.js +106 -0
- package/dist/server/exec-service.d.ts +14 -7
- package/dist/server/exec-service.js +66 -40
- package/dist/server/http-server.js +63 -7
- package/dist/server/index.js +11 -7
- package/dist/server/memory-recall.d.ts +16 -1
- package/dist/server/memory-recall.js +22 -8
- package/dist/server/memory.d.ts +10 -1
- package/dist/server/memory.js +11 -6
- package/dist/server/runtime.d.ts +12 -12
- package/dist/server/runtime.js +68 -11
- package/dist/server/server-context.d.ts +1 -0
- package/dist/server/store.d.ts +7 -1
- package/dist/server/store.js +72 -35
- package/dist/server/subagent-runs.d.ts +3 -2
- package/dist/server/subagent-runs.js +45 -33
- package/dist/server/subagents.d.ts +1 -0
- package/dist/server/subagents.js +30 -12
- package/dist/server/types.d.ts +13 -11
- package/dist/server/ws-server.d.ts +3 -0
- package/dist/server/ws-server.js +40 -6
- package/dist/shared/background-task.d.ts +22 -0
- package/dist/shared/background-task.js +5 -0
- package/dist/shared/group-chat.d.ts +62 -0
- package/dist/shared/group-chat.js +1 -0
- package/package.json +4 -1
- package/dist/client/assets/index-BGbZwftQ.css +0 -1
|
@@ -0,0 +1,547 @@
|
|
|
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 = 3;
|
|
9
|
+
const MAX_CONTENT = 32_000;
|
|
10
|
+
const timestamp = () => new Date().toISOString();
|
|
11
|
+
function inputText(value, limit, label) {
|
|
12
|
+
if (typeof value !== "string" || value.length > limit)
|
|
13
|
+
throw new Error(`${label}格式无效或超过长度上限。`);
|
|
14
|
+
return value.trim();
|
|
15
|
+
}
|
|
16
|
+
function summary({ id, workspaceId, title, updatedAt }) {
|
|
17
|
+
return { id, workspaceId, title, updatedAt };
|
|
18
|
+
}
|
|
19
|
+
async function readReferences(workspacePath, input) {
|
|
20
|
+
if (!Array.isArray(input) || !input.length)
|
|
21
|
+
return undefined;
|
|
22
|
+
const paths = [...new Set(input)];
|
|
23
|
+
if (paths.length > 4)
|
|
24
|
+
throw new Error("一条群聊消息最多引用四个文件。");
|
|
25
|
+
const root = await realpath(workspacePath);
|
|
26
|
+
return Promise.all(paths.map(async (value) => {
|
|
27
|
+
const path = inputText(value, 2048, "引用文件路径");
|
|
28
|
+
const filePath = await realpath(resolve(root, path));
|
|
29
|
+
const inside = relative(root, filePath);
|
|
30
|
+
if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
|
|
31
|
+
throw new Error("群聊只能引用工作区内的文件。");
|
|
32
|
+
const file = await open(filePath, "r");
|
|
33
|
+
try {
|
|
34
|
+
const stat = await file.stat();
|
|
35
|
+
if (!stat.isFile())
|
|
36
|
+
throw new Error(`「${path}」不是普通文件。`);
|
|
37
|
+
const bytes = Buffer.alloc(Math.min(stat.size, 8192));
|
|
38
|
+
const { bytesRead } = await file.read(bytes, 0, bytes.length, 0);
|
|
39
|
+
const used = bytes.subarray(0, bytesRead);
|
|
40
|
+
if (used.includes(0))
|
|
41
|
+
throw new Error(`「${path}」不是文本文件。`);
|
|
42
|
+
const excerpt = used.toString("utf8") + (stat.size > bytesRead ? "\n[文件摘录已截断]" : "");
|
|
43
|
+
return { path, excerpt };
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
await file.close();
|
|
47
|
+
}
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
function route(text, members, anchors) {
|
|
51
|
+
const parsed = JSON.parse(text.trim().replace(/^```(?:json)?\s*|\s*```$/gi, ""));
|
|
52
|
+
if (!parsed || typeof parsed !== "object")
|
|
53
|
+
throw new Error("主持人未返回有效决定。");
|
|
54
|
+
const decision = parsed;
|
|
55
|
+
if (decision.action === "finish")
|
|
56
|
+
return undefined;
|
|
57
|
+
if (!["reply", "background"].includes(String(decision.action)) || typeof decision.memberId !== "string" || !members.some(member => member.id === decision.memberId)) {
|
|
58
|
+
throw new Error("主持人选择了无效的群成员。");
|
|
59
|
+
}
|
|
60
|
+
const replyTo = typeof decision.replyTo === "string" && anchors.has(decision.replyTo) ? decision.replyTo : undefined;
|
|
61
|
+
const assignment = inputText(decision.assignment, 1600, "接话任务");
|
|
62
|
+
if (!assignment)
|
|
63
|
+
throw new Error("主持人没有给出接话任务。");
|
|
64
|
+
const reason = typeof decision.reason === "string" ? decision.reason.trim().slice(0, 240) : undefined;
|
|
65
|
+
return { memberId: decision.memberId, replyTo, assignment, reason, background: decision.action === "background" };
|
|
66
|
+
}
|
|
67
|
+
export class GroupChatService {
|
|
68
|
+
filePath;
|
|
69
|
+
store;
|
|
70
|
+
runtime;
|
|
71
|
+
memory;
|
|
72
|
+
rooms = [];
|
|
73
|
+
writes = Promise.resolve();
|
|
74
|
+
running = new Map();
|
|
75
|
+
memberRuns = new Map();
|
|
76
|
+
controllers = new Map();
|
|
77
|
+
live = new Map();
|
|
78
|
+
streamRevisions = new Map();
|
|
79
|
+
closing = false;
|
|
80
|
+
constructor(filePath, store, runtime, memory) {
|
|
81
|
+
this.filePath = filePath;
|
|
82
|
+
this.store = store;
|
|
83
|
+
this.runtime = runtime;
|
|
84
|
+
this.memory = memory;
|
|
85
|
+
}
|
|
86
|
+
static async open(filePath, store, runtime, memory) {
|
|
87
|
+
const service = new GroupChatService(filePath, store, runtime, memory);
|
|
88
|
+
try {
|
|
89
|
+
service.rooms = JSON.parse(await readFile(filePath, "utf8"));
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error.code !== "ENOENT")
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
if (service.rooms.some(room => room.messages.some(post => post.status === "running" || (post.role === "assistant" && post.status === "queued")))) {
|
|
96
|
+
await service.edit(rooms => {
|
|
97
|
+
for (const room of rooms)
|
|
98
|
+
for (const post of room.messages)
|
|
99
|
+
if (post.status === "running" || (post.role === "assistant" && post.status === "queued")) {
|
|
100
|
+
post.status = "interrupted";
|
|
101
|
+
post.error = "服务重启,本次发言已中断。";
|
|
102
|
+
room.revision += 1;
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
for (const room of service.rooms)
|
|
107
|
+
service.kick(room.id);
|
|
108
|
+
return service;
|
|
109
|
+
}
|
|
110
|
+
workspace(id) {
|
|
111
|
+
const workspace = this.store.workspace(id);
|
|
112
|
+
if (!workspace || workspace.closedAt)
|
|
113
|
+
throw new Error("工作区不存在或已关闭。");
|
|
114
|
+
return workspace;
|
|
115
|
+
}
|
|
116
|
+
find(rooms, workspaceId, id) {
|
|
117
|
+
this.workspace(workspaceId);
|
|
118
|
+
const room = rooms.find(item => item.id === id && item.workspaceId === workspaceId);
|
|
119
|
+
if (!room)
|
|
120
|
+
throw new Error("此工作区没有这个群聊。");
|
|
121
|
+
return room;
|
|
122
|
+
}
|
|
123
|
+
edit(change) {
|
|
124
|
+
const write = this.writes.then(async () => {
|
|
125
|
+
const rooms = structuredClone(this.rooms);
|
|
126
|
+
const result = change(rooms);
|
|
127
|
+
const temporary = this.filePath + ".tmp";
|
|
128
|
+
await writeFile(temporary, JSON.stringify(rooms), { encoding: "utf8", mode: 0o600 });
|
|
129
|
+
await replaceFile(temporary, this.filePath);
|
|
130
|
+
this.rooms = rooms;
|
|
131
|
+
return result;
|
|
132
|
+
});
|
|
133
|
+
this.writes = write.then(() => undefined, () => undefined);
|
|
134
|
+
return write;
|
|
135
|
+
}
|
|
136
|
+
list(workspaceId) {
|
|
137
|
+
this.workspace(workspaceId);
|
|
138
|
+
return this.rooms.filter(room => room.workspaceId === workspaceId).map(summary).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
139
|
+
}
|
|
140
|
+
get(workspaceId, id) {
|
|
141
|
+
const room = structuredClone(this.find(this.rooms, workspaceId, id));
|
|
142
|
+
for (const post of room.messages)
|
|
143
|
+
if (post.status === "running")
|
|
144
|
+
post.content = this.live.get(post.id) ?? post.content;
|
|
145
|
+
return { ...room, revision: `${room.revision}:${this.streamRevisions.get(id) ?? 0}` };
|
|
146
|
+
}
|
|
147
|
+
async moderator(workspaceId, body) {
|
|
148
|
+
const workspace = this.workspace(workspaceId);
|
|
149
|
+
const prompt = inputText(body.prompt ?? "", 8_000, "主持人 Prompt");
|
|
150
|
+
if (!body.model)
|
|
151
|
+
return { prompt };
|
|
152
|
+
if (typeof body.model !== "object")
|
|
153
|
+
throw new Error("主持人模型无效。");
|
|
154
|
+
const requested = body.model;
|
|
155
|
+
const catalog = await this.runtime.catalog();
|
|
156
|
+
const model = catalog.models.find(item => item.provider === requested.provider && item.modelId === requested.modelId);
|
|
157
|
+
if (!model)
|
|
158
|
+
throw new Error("主持人模型不可用。");
|
|
159
|
+
assertModelAllowed(this.store.modelFilterRules(), workspace, model);
|
|
160
|
+
return { prompt, model: { provider: model.provider, modelId: model.modelId, label: model.label } };
|
|
161
|
+
}
|
|
162
|
+
async resolveMembers(id, input, existing = []) {
|
|
163
|
+
const memberIds = Array.isArray(input) ? [...new Set(input)] : [];
|
|
164
|
+
if (memberIds.length < 2 || memberIds.length > 8)
|
|
165
|
+
throw new Error("请选择 2 到 8 位主 Agent。");
|
|
166
|
+
return Promise.all(memberIds.map(async (memberId) => {
|
|
167
|
+
if (typeof memberId !== "string")
|
|
168
|
+
throw new Error("群成员无效。");
|
|
169
|
+
const saved = existing.find(member => member.id === memberId);
|
|
170
|
+
if (saved)
|
|
171
|
+
return saved;
|
|
172
|
+
const agent = await this.runtime.agentFor?.({ id, agentId: memberId });
|
|
173
|
+
if (!agent || agent.id !== memberId || agent.mode !== "primary" || agent.hidden)
|
|
174
|
+
throw new Error(`主 Agent ${memberId} 不可用。`);
|
|
175
|
+
return { id: agent.id, name: agent.name, description: agent.description };
|
|
176
|
+
}));
|
|
177
|
+
}
|
|
178
|
+
async create(workspaceId, input) {
|
|
179
|
+
this.workspace(workspaceId);
|
|
180
|
+
const title = inputText(input.title, 100, "群名");
|
|
181
|
+
if (!title)
|
|
182
|
+
throw new Error("请输入群名。");
|
|
183
|
+
const id = randomUUID();
|
|
184
|
+
const members = await this.resolveMembers(id, input.memberIds ?? DEFAULT_GROUP_MEMBER_IDS);
|
|
185
|
+
const moderator = await this.moderator(workspaceId, input.moderator ?? {});
|
|
186
|
+
const room = { id, workspaceId, title, updatedAt: timestamp(), revision: 0, members, moderator, messages: [] };
|
|
187
|
+
await this.edit(rooms => { rooms.push(room); });
|
|
188
|
+
return this.get(workspaceId, id);
|
|
189
|
+
}
|
|
190
|
+
async configure(workspaceId, id, input) {
|
|
191
|
+
const current = this.find(this.rooms, workspaceId, id);
|
|
192
|
+
const moderator = await this.moderator(workspaceId, input);
|
|
193
|
+
const members = input.memberIds === undefined ? undefined : await this.resolveMembers(id, input.memberIds, current.members);
|
|
194
|
+
await this.edit(rooms => {
|
|
195
|
+
const room = this.find(rooms, workspaceId, id);
|
|
196
|
+
if (members) {
|
|
197
|
+
for (const post of room.messages)
|
|
198
|
+
if (post.role === "assistant")
|
|
199
|
+
post.memberName ??= room.members.find(member => member.id === post.memberId)?.name;
|
|
200
|
+
room.members = members;
|
|
201
|
+
}
|
|
202
|
+
room.moderator = moderator;
|
|
203
|
+
room.revision += 1;
|
|
204
|
+
});
|
|
205
|
+
return this.get(workspaceId, id);
|
|
206
|
+
}
|
|
207
|
+
async send(workspaceId, id, input) {
|
|
208
|
+
if (this.closing)
|
|
209
|
+
throw new Error("服务正在关闭。");
|
|
210
|
+
const content = inputText(input.content, MAX_CONTENT, "消息");
|
|
211
|
+
const clientId = inputText(input.clientId, 128, "发送标识");
|
|
212
|
+
if (!content || !clientId)
|
|
213
|
+
throw new Error("消息内容和发送标识不能为空。");
|
|
214
|
+
const current = this.find(this.rooms, workspaceId, id);
|
|
215
|
+
if (current.messages.some(post => post.role === "user" && post.clientId === clientId))
|
|
216
|
+
return this.get(workspaceId, id);
|
|
217
|
+
const files = await readReferences(this.workspace(workspaceId).path, input.filePaths);
|
|
218
|
+
await this.edit(rooms => {
|
|
219
|
+
const room = this.find(rooms, workspaceId, id);
|
|
220
|
+
if (room.messages.some(post => post.role === "user" && post.clientId === clientId))
|
|
221
|
+
return;
|
|
222
|
+
const parent = typeof input.replyTo === "string" ? room.messages.find(post => post.id === input.replyTo) : undefined;
|
|
223
|
+
if (input.replyTo && !parent)
|
|
224
|
+
throw new Error("群里找不到引用的消息。");
|
|
225
|
+
const memberIds = [];
|
|
226
|
+
for (const memberId of Array.isArray(input.memberIds) ? input.memberIds : []) {
|
|
227
|
+
if (!room.members.some(member => member.id === memberId))
|
|
228
|
+
throw new Error("点名的 Agent 不在群里。");
|
|
229
|
+
if (!memberIds.includes(memberId))
|
|
230
|
+
memberIds.push(memberId);
|
|
231
|
+
}
|
|
232
|
+
if (!memberIds.length && parent?.role === "assistant" && room.members.some(member => member.id === parent.memberId))
|
|
233
|
+
memberIds.push(parent.memberId);
|
|
234
|
+
room.messages.push({ id: randomUUID(), role: "user", clientId, content, files, memberIds, replyTo: parent?.id, createdAt: timestamp(), status: "queued" });
|
|
235
|
+
room.updatedAt = timestamp();
|
|
236
|
+
room.revision += 1;
|
|
237
|
+
});
|
|
238
|
+
this.kick(id);
|
|
239
|
+
return this.get(workspaceId, id);
|
|
240
|
+
}
|
|
241
|
+
async stop(workspaceId, id, postId) {
|
|
242
|
+
const cancelled = await this.edit(rooms => {
|
|
243
|
+
const room = this.find(rooms, workspaceId, id);
|
|
244
|
+
const posts = room.messages.filter(post => (post.id === postId || (post.role === "assistant" && post.topicId === postId)) && ["queued", "running"].includes(post.status));
|
|
245
|
+
for (const post of posts) {
|
|
246
|
+
post.content = this.live.get(post.id) ?? post.content;
|
|
247
|
+
post.status = "cancelled";
|
|
248
|
+
}
|
|
249
|
+
room.revision += 1;
|
|
250
|
+
return posts.map(post => post.id);
|
|
251
|
+
});
|
|
252
|
+
for (const key of cancelled)
|
|
253
|
+
this.controllers.get(key)?.abort();
|
|
254
|
+
return this.get(workspaceId, id);
|
|
255
|
+
}
|
|
256
|
+
kick(id) {
|
|
257
|
+
if (this.closing)
|
|
258
|
+
return;
|
|
259
|
+
const room = this.rooms.find(item => item.id === id);
|
|
260
|
+
if (!room)
|
|
261
|
+
return;
|
|
262
|
+
for (const post of room.messages) {
|
|
263
|
+
if (post.role !== "user" || post.status !== "queued" || this.running.has(post.id))
|
|
264
|
+
continue;
|
|
265
|
+
const work = this.runTopic(room, post.id).catch(error => console.error("Super Pi: group chat failed to save its progress:", error))
|
|
266
|
+
.finally(() => this.running.delete(post.id));
|
|
267
|
+
this.running.set(post.id, work);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async runTopic(room, topicId) {
|
|
271
|
+
const topic = await this.edit(rooms => {
|
|
272
|
+
const current = rooms.find(item => item.id === room.id);
|
|
273
|
+
const next = current.messages.find((post) => post.role === "user" && post.id === topicId);
|
|
274
|
+
if (next?.status !== "queued")
|
|
275
|
+
return;
|
|
276
|
+
next.status = "running";
|
|
277
|
+
current.revision += 1;
|
|
278
|
+
return next;
|
|
279
|
+
});
|
|
280
|
+
if (!topic)
|
|
281
|
+
return;
|
|
282
|
+
const controller = new AbortController();
|
|
283
|
+
const pending = [];
|
|
284
|
+
this.controllers.set(topic.id, controller);
|
|
285
|
+
if (this.closing)
|
|
286
|
+
controller.abort();
|
|
287
|
+
try {
|
|
288
|
+
if (this.memory && CODING_STANDARD_REQUEST.test(topic.content) && !controller.signal.aborted) {
|
|
289
|
+
const notice = await this.memory.rememberGroupCodingStandards(room.workspaceId, room.id, topic.id, topic.content)
|
|
290
|
+
.catch(() => "平台未能保存代码规范,请检查主动记忆设置。");
|
|
291
|
+
if (notice)
|
|
292
|
+
await this.edit(rooms => {
|
|
293
|
+
const current = rooms.find(item => item.id === room.id);
|
|
294
|
+
const post = current.messages.find(item => item.id === topic.id && item.role === "user");
|
|
295
|
+
if (post?.role === "user") {
|
|
296
|
+
post.memoryNotice = notice;
|
|
297
|
+
current.revision += 1;
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
const start = async (targets) => {
|
|
302
|
+
const replies = await this.respond(room.id, topic, targets, controller.signal);
|
|
303
|
+
pending.push(...replies);
|
|
304
|
+
if (replies.length)
|
|
305
|
+
await Promise.race(replies.map(reply => reply.yields));
|
|
306
|
+
};
|
|
307
|
+
if (topic.memberIds.length)
|
|
308
|
+
await start(topic.memberIds.map(memberId => ({ memberId, replyTo: topic.replyTo ?? topic.id })));
|
|
309
|
+
let count = 0;
|
|
310
|
+
while (!controller.signal.aborted) {
|
|
311
|
+
const current = this.rooms.find(item => item.id === room.id);
|
|
312
|
+
if (current.messages.find(post => post.id === topic.id)?.status !== "running")
|
|
313
|
+
break;
|
|
314
|
+
const replies = current.messages.filter((post) => post.role === "assistant" && post.topicId === topic.id);
|
|
315
|
+
const active = pending.filter(reply => replies.some(post => post.id === reply.id && (post.status === "running" || post.status === "queued")));
|
|
316
|
+
const busy = new Set(current.messages.flatMap(post => post.role === "assistant" && (post.status === "running" || post.status === "queued") ? [post.memberId] : []));
|
|
317
|
+
const available = current.members.filter(member => {
|
|
318
|
+
const attempted = replies.filter(post => post.memberId === member.id);
|
|
319
|
+
return attempted.length < 2 && attempted.every(post => post.status === "completed");
|
|
320
|
+
});
|
|
321
|
+
const candidates = available.filter(member => !busy.has(member.id));
|
|
322
|
+
const next = count < MAX_AUTOMATIC_REPLIES && candidates.length ? await this.choose(current, topic, candidates, controller.signal) : undefined;
|
|
323
|
+
if (next) {
|
|
324
|
+
const replyTo = next.replyTo ?? replies.filter(post => post.status === "completed").at(-1)?.id ?? topic.id;
|
|
325
|
+
count += 1;
|
|
326
|
+
await start([{ ...next, replyTo }]);
|
|
327
|
+
}
|
|
328
|
+
else if (active.length) {
|
|
329
|
+
await Promise.race(active.map(reply => reply.done));
|
|
330
|
+
}
|
|
331
|
+
else if (!replies.length && available.length && this.memberRuns.size) {
|
|
332
|
+
const work = available.flatMap(member => this.memberRuns.get(JSON.stringify([room.id, member.id])) ?? []);
|
|
333
|
+
if (!work.length)
|
|
334
|
+
break;
|
|
335
|
+
await this.waitForWork(Promise.race(work), controller.signal);
|
|
336
|
+
}
|
|
337
|
+
else
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
const replies = this.rooms.find(item => item.id === room.id).messages.filter(post => post.role === "assistant" && post.topicId === topic.id);
|
|
341
|
+
await this.settle(room.id, topic.id, controller.signal, replies.some(post => post.status === "completed") ? undefined : "本轮没有收到完整回复。");
|
|
342
|
+
}
|
|
343
|
+
catch (error) {
|
|
344
|
+
await Promise.allSettled(pending.map(reply => reply.done));
|
|
345
|
+
await this.settle(room.id, topic.id, controller.signal, error instanceof Error ? error.message : String(error));
|
|
346
|
+
}
|
|
347
|
+
finally {
|
|
348
|
+
await Promise.allSettled(pending.map(reply => reply.done));
|
|
349
|
+
this.controllers.delete(topic.id);
|
|
350
|
+
const current = this.rooms.find(item => item.id === room.id);
|
|
351
|
+
const saved = current?.messages.find(post => post.id === topic.id);
|
|
352
|
+
if (!this.closing && current && (saved?.status === "completed" || saved?.status === "failed")) {
|
|
353
|
+
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)));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
context(room, topic) {
|
|
358
|
+
const topicIndex = room.messages.findIndex(post => post.id === topic.id);
|
|
359
|
+
const previous = room.messages.slice(0, topicIndex).filter(post => post.role === "user" && post.status !== "cancelled");
|
|
360
|
+
const topicIds = new Set(previous.map(post => post.id).concat(topic.id));
|
|
361
|
+
return room.messages.filter(post => post.role === "assistant" ? topicIds.has(post.topicId) && post.status === "completed"
|
|
362
|
+
: post.id !== topic.id && topicIds.has(post.id))
|
|
363
|
+
.slice(-20).map(post => ({
|
|
364
|
+
id: post.id, author: post.role === "user" ? "用户" : post.memberName ?? room.members.find(member => member.id === post.memberId)?.name,
|
|
365
|
+
content: post.content.slice(0, 4_000),
|
|
366
|
+
}));
|
|
367
|
+
}
|
|
368
|
+
async complete(room, input) {
|
|
369
|
+
const workspace = this.workspace(room.workspaceId);
|
|
370
|
+
const model = input.model ?? workspace.defaultModel;
|
|
371
|
+
const rules = this.store.modelFilterRules();
|
|
372
|
+
if (applicableRules(rules, workspace).length)
|
|
373
|
+
assertModelAllowed(rules, workspace, model ?? (await this.runtime.catalog()).defaultModel);
|
|
374
|
+
if (!this.runtime.askOnce)
|
|
375
|
+
throw new Error("当前运行时不支持群聊模型。");
|
|
376
|
+
return this.runtime.askOnce({ ...input, model, cwd: workspace.path });
|
|
377
|
+
}
|
|
378
|
+
async choose(room, topic, candidates, signal) {
|
|
379
|
+
const context = this.context(room, topic);
|
|
380
|
+
const performed = room.messages.filter((post) => post.role === "assistant" && post.topicId === topic.id)
|
|
381
|
+
.map(({ memberId, status, assignment, background }) => ({ memberId, status, assignment, background }));
|
|
382
|
+
const earlierTopics = new Set(room.messages.slice(0, room.messages.findIndex(post => post.id === topic.id))
|
|
383
|
+
.filter(post => post.role === "user").map(post => post.id));
|
|
384
|
+
const workInProgress = room.messages.filter((post) => post.role === "assistant" && earlierTopics.has(post.topicId) && post.status === "running")
|
|
385
|
+
.map(({ memberId, topicId, assignment }) => ({ memberId, topicId, assignment }));
|
|
386
|
+
const prompt = [
|
|
387
|
+
"你是群聊主持人。根据当前用户问题、公开发言和成员分工,只安排能补足缺口的一次接话。已有足够答案时结束。尊重用户点名和范围,避免重复、感谢式接话和无目的汇总。",
|
|
388
|
+
'只返回 JSON,格式为 {"action":"finish"} 或 {"action":"reply","memberId":"成员 ID","replyTo":"消息 ID","assignment":"本次要做的事","reason":"简短理由"}。将 action 改为 background 可交付独立工作,同时邀请其他成员继续讨论。适用于调研、改代码、调试、整理文档等。未收到在途任务结果时可以先结束这一段,结果回来后会再次征求你的决定。',
|
|
389
|
+
"同一工作区的并行任务应有独立的范围。涉及相同文件、依赖未完成的修改或需要前置证据时,等对应结果再安排。",
|
|
390
|
+
`主持人偏好:${room.moderator.prompt || "直接解决当前问题,结论够用就结束。"}`,
|
|
391
|
+
JSON.stringify({ topicId: topic.id, request: topic.content, files: topic.files?.map(file => file.path), candidates, performed, workInProgress, messages: context }),
|
|
392
|
+
].join("\n");
|
|
393
|
+
try {
|
|
394
|
+
const answer = await this.complete(room, { prompt, model: room.moderator.model, signal, timeoutMs: 35_000 });
|
|
395
|
+
const decision = route(answer, candidates, new Set([topic.id, ...context.map(post => post.id)]));
|
|
396
|
+
if (!decision && !performed.length)
|
|
397
|
+
return { memberId: candidates[0].id, replyTo: topic.id, assignment: "请回答用户当前的问题。", reason: "交给默认成员回答" };
|
|
398
|
+
return decision;
|
|
399
|
+
}
|
|
400
|
+
catch (error) {
|
|
401
|
+
if (signal.aborted)
|
|
402
|
+
return undefined;
|
|
403
|
+
throw new Error(`主持人未能安排回复:${error instanceof Error ? error.message : String(error)}`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
async respond(roomId, topic, targets, signal) {
|
|
407
|
+
const batch = await this.edit(rooms => {
|
|
408
|
+
const room = rooms.find(item => item.id === roomId);
|
|
409
|
+
if (signal.aborted || room.messages.find(post => post.id === topic.id)?.status !== "running")
|
|
410
|
+
return;
|
|
411
|
+
const replies = targets.filter(target => room.members.some(member => member.id === target.memberId)).map(target => ({
|
|
412
|
+
id: randomUUID(), role: "assistant", content: "", status: "queued", createdAt: timestamp(), topicId: topic.id,
|
|
413
|
+
memberId: target.memberId, memberName: room.members.find(member => member.id === target.memberId)?.name,
|
|
414
|
+
replyTo: target.replyTo, assignment: target.assignment, routeReason: target.reason, background: target.background || undefined,
|
|
415
|
+
}));
|
|
416
|
+
room.messages.push(...replies);
|
|
417
|
+
room.revision += 1;
|
|
418
|
+
room.updatedAt = timestamp();
|
|
419
|
+
return replies;
|
|
420
|
+
});
|
|
421
|
+
if (!batch)
|
|
422
|
+
return [];
|
|
423
|
+
return batch.map(reply => {
|
|
424
|
+
const key = JSON.stringify([roomId, reply.memberId]);
|
|
425
|
+
const prior = this.memberRuns.get(key);
|
|
426
|
+
const controller = new AbortController();
|
|
427
|
+
this.controllers.set(reply.id, controller);
|
|
428
|
+
const currentStatus = this.rooms.find(room => room.id === roomId)?.messages.find(post => post.id === reply.id)?.status;
|
|
429
|
+
if (currentStatus !== "queued")
|
|
430
|
+
controller.abort();
|
|
431
|
+
const memberSignal = AbortSignal.any([signal, controller.signal]);
|
|
432
|
+
let allowNext;
|
|
433
|
+
const yields = new Promise(resolve => { allowNext = resolve; });
|
|
434
|
+
const done = this.runMember(roomId, topic, reply, memberSignal, allowNext, prior).finally(() => {
|
|
435
|
+
allowNext();
|
|
436
|
+
this.live.delete(reply.id);
|
|
437
|
+
this.controllers.delete(reply.id);
|
|
438
|
+
});
|
|
439
|
+
if (reply.background || prior)
|
|
440
|
+
allowNext();
|
|
441
|
+
const tail = Promise.allSettled([prior, done]).then(() => undefined).finally(() => {
|
|
442
|
+
if (this.memberRuns.get(key) === tail)
|
|
443
|
+
this.memberRuns.delete(key);
|
|
444
|
+
});
|
|
445
|
+
this.memberRuns.set(key, tail);
|
|
446
|
+
return { id: reply.id, done, yields };
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
waitForWork(work, signal) {
|
|
450
|
+
if (signal.aborted)
|
|
451
|
+
return Promise.resolve();
|
|
452
|
+
return new Promise(resolve => {
|
|
453
|
+
const finish = () => { signal.removeEventListener("abort", finish); resolve(); };
|
|
454
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
455
|
+
void work.then(finish, finish);
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
async runMember(roomId, topic, reply, memberSignal, allowNext, prior) {
|
|
459
|
+
if (prior)
|
|
460
|
+
await this.waitForWork(prior, memberSignal);
|
|
461
|
+
const started = await this.edit(rooms => {
|
|
462
|
+
const room = rooms.find(item => item.id === roomId);
|
|
463
|
+
const post = room.messages.find(item => item.id === reply.id);
|
|
464
|
+
if (post?.status !== "queued")
|
|
465
|
+
return;
|
|
466
|
+
const cancelled = memberSignal.aborted || !room.members.some(member => member.id === reply.memberId);
|
|
467
|
+
post.status = cancelled ? this.closing ? "interrupted" : "cancelled" : "running";
|
|
468
|
+
room.revision += 1;
|
|
469
|
+
return cancelled ? undefined : room;
|
|
470
|
+
});
|
|
471
|
+
if (!started)
|
|
472
|
+
return;
|
|
473
|
+
let lastCheckpoint = Date.now();
|
|
474
|
+
let yielded = Boolean(reply.background);
|
|
475
|
+
const goBackground = () => {
|
|
476
|
+
if (yielded || memberSignal.aborted)
|
|
477
|
+
return;
|
|
478
|
+
yielded = true;
|
|
479
|
+
void this.edit(rooms => {
|
|
480
|
+
const room = rooms.find(item => item.id === roomId);
|
|
481
|
+
const post = room.messages.find(item => item.id === reply.id);
|
|
482
|
+
if (post?.role === "assistant" && post.status === "running") {
|
|
483
|
+
post.background = true;
|
|
484
|
+
room.revision += 1;
|
|
485
|
+
}
|
|
486
|
+
}).then(allowNext, allowNext);
|
|
487
|
+
};
|
|
488
|
+
const timer = setTimeout(goBackground, 4000);
|
|
489
|
+
try {
|
|
490
|
+
const agent = await this.runtime.agentFor?.({ id: reply.id, agentId: reply.memberId });
|
|
491
|
+
if (!agent || agent.id !== reply.memberId || agent.mode !== "primary")
|
|
492
|
+
throw new Error("该主 Agent 已不可用。");
|
|
493
|
+
const notes = await this.memory?.groupEngineeringNotes(started.workspaceId, agent.id, topic.content + "\n" + (reply.assignment ?? ""))
|
|
494
|
+
.catch(() => undefined);
|
|
495
|
+
const prompt = [
|
|
496
|
+
`你以 ${agent.name} 的身份在群聊中回答。请完成本次分工并给出可复核的结论。有可用工具且分工要求执行时,直接完成,其他成员可以继续讨论。只修改分工明确涉及的文件。`,
|
|
497
|
+
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, messages: this.context(started, topic), notes }),
|
|
498
|
+
].join("\n");
|
|
499
|
+
const answer = await this.complete(started, {
|
|
500
|
+
prompt, agent, model: agent.model && { ...agent.model, label: agent.model.modelId }, signal: memberSignal, timeoutMs: 15 * 60_000,
|
|
501
|
+
onToolStart: goBackground,
|
|
502
|
+
onText: delta => {
|
|
503
|
+
if (memberSignal.aborted)
|
|
504
|
+
return;
|
|
505
|
+
this.live.set(reply.id, ((this.live.get(reply.id) ?? "") + delta).slice(0, MAX_CONTENT));
|
|
506
|
+
this.streamRevisions.set(roomId, (this.streamRevisions.get(roomId) ?? 0) + 1);
|
|
507
|
+
if (Date.now() - lastCheckpoint < 800)
|
|
508
|
+
return;
|
|
509
|
+
lastCheckpoint = Date.now();
|
|
510
|
+
void this.edit(rooms => {
|
|
511
|
+
const post = rooms.find(room => room.id === roomId).messages.find(item => item.id === reply.id);
|
|
512
|
+
if (post?.status === "running")
|
|
513
|
+
post.content = this.live.get(reply.id) ?? post.content;
|
|
514
|
+
}).catch(error => console.warn("Super Pi: could not checkpoint group reply:", error));
|
|
515
|
+
},
|
|
516
|
+
});
|
|
517
|
+
await this.settle(roomId, reply.id, memberSignal, undefined, answer);
|
|
518
|
+
}
|
|
519
|
+
catch (error) {
|
|
520
|
+
await this.settle(roomId, reply.id, memberSignal, error instanceof Error ? error.message : String(error), this.live.get(reply.id));
|
|
521
|
+
}
|
|
522
|
+
finally {
|
|
523
|
+
clearTimeout(timer);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
async settle(roomId, postId, signal, error, content) {
|
|
527
|
+
await this.edit(rooms => {
|
|
528
|
+
const room = rooms.find(item => item.id === roomId);
|
|
529
|
+
const post = room.messages.find(item => item.id === postId);
|
|
530
|
+
if (post?.status !== "running")
|
|
531
|
+
return;
|
|
532
|
+
post.status = signal.aborted ? this.closing ? "interrupted" : "cancelled" : error ? "failed" : "completed";
|
|
533
|
+
if (content !== undefined)
|
|
534
|
+
post.content = content.slice(0, MAX_CONTENT);
|
|
535
|
+
post.error = signal.aborted ? (this.closing ? "服务停止,本次发言已中断。" : undefined) : error?.slice(0, 1600);
|
|
536
|
+
room.revision += 1;
|
|
537
|
+
room.updatedAt = timestamp();
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
async close() {
|
|
541
|
+
this.closing = true;
|
|
542
|
+
for (const controller of this.controllers.values())
|
|
543
|
+
controller.abort();
|
|
544
|
+
await Promise.allSettled(this.running.values());
|
|
545
|
+
await this.writes;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
@@ -6,6 +6,7 @@ import type { EventBroadcaster } from "../server-context.js";
|
|
|
6
6
|
import type { ExtensionUiService } from "./extension-ui-service.js";
|
|
7
7
|
import type { WorkflowEngine } from "../workflow-engine.js";
|
|
8
8
|
import { FileChangeTracker } from "../file-changes.js";
|
|
9
|
+
import type { ExecCompletion } from "../exec-service.js";
|
|
9
10
|
/**
|
|
10
11
|
* Validates a caller-supplied delivery mode without silently falling back on bogus values.
|
|
11
12
|
* Undefined defaults to `"queue"`; any other value is rejected explicitly.
|
|
@@ -72,6 +73,7 @@ export declare class RunService {
|
|
|
72
73
|
private readonly cancelledQuestionConversations;
|
|
73
74
|
private memory?;
|
|
74
75
|
setMemory(memory: import("../active-memory.js").ActiveMemory): void;
|
|
76
|
+
private recordCodingStandards;
|
|
75
77
|
/**
|
|
76
78
|
* WHAT THE AGENT CHANGED, and what each file looked like before.
|
|
77
79
|
*
|
|
@@ -117,6 +119,7 @@ export declare class RunService {
|
|
|
117
119
|
private readonly runCompletions;
|
|
118
120
|
/** A selected interrupt owns the next free run slot, even while the old child exits. */
|
|
119
121
|
private readonly interruptTargets;
|
|
122
|
+
private readonly pendingBackgroundWakeups;
|
|
120
123
|
private shuttingDown;
|
|
121
124
|
/** Preserve incoming background results as waiting messages while the server drains its producers. */
|
|
122
125
|
beginShutdown(): void;
|
|
@@ -155,7 +158,9 @@ export declare class RunService {
|
|
|
155
158
|
} | undefined;
|
|
156
159
|
waitForToolCall(conversationId: string, toolCallId: string | undefined): Promise<ReturnType<RunService["originForToolCall"]>>;
|
|
157
160
|
private execService;
|
|
158
|
-
|
|
161
|
+
private backgroundLogDirectory?;
|
|
162
|
+
private readonly execSettlements;
|
|
163
|
+
setExecService(execService: import("../exec-service.js").ExecService, logDirectory?: string): void;
|
|
159
164
|
/**
|
|
160
165
|
* Called by the exec completion handler in index.ts when a background exec session ends.
|
|
161
166
|
* Injects the result into the conversation and cleans up the background task record.
|
|
@@ -166,7 +171,10 @@ export declare class RunService {
|
|
|
166
171
|
* when nothing else is busy. The render stays as a 后台回传 block throughout - in dock and in
|
|
167
172
|
* transcript - so a `role: "user"` is never impersonated.
|
|
168
173
|
*/
|
|
169
|
-
enqueueExecResult(sessionId: string, exitCode: number, stdout: string, stderr: string): void;
|
|
174
|
+
enqueueExecResult(sessionId: string, exitCode: number, stdout: string, stderr: string, completion?: ExecCompletion): void;
|
|
175
|
+
failBackgroundTaskStart(taskId: string, reason: string, cancelled?: boolean): Promise<void>;
|
|
176
|
+
private finishBackgroundResult;
|
|
177
|
+
private startBackgroundResult;
|
|
170
178
|
/**
|
|
171
179
|
* Delivers an orchestrated child session's final output to its direct parent. This intentionally uses
|
|
172
180
|
* the same waiting-queue contract as background sub-agent results: one result per turn, ahead of
|
|
@@ -180,15 +188,7 @@ export declare class RunService {
|
|
|
180
188
|
error?: string;
|
|
181
189
|
}): Promise<void>;
|
|
182
190
|
private dispatchBackgroundResult;
|
|
183
|
-
|
|
184
|
-
* Stops an active background task (spawned process or detached subagent) on user request.
|
|
185
|
-
*
|
|
186
|
-
* 1. Kills the underlying PTY child process if one exists in `execService`.
|
|
187
|
-
* 2. If the task originated from a tool call in a conversation transcript, marks the tool
|
|
188
|
-
* call as failed with a clear message and broadcasts `message.tools`.
|
|
189
|
-
* 3. Removes the task from `state.backgroundTasks` and broadcasts `state` so the sidebar
|
|
190
|
-
* updates immediately.
|
|
191
|
-
*/
|
|
191
|
+
private wakeWaitingBackgroundResult;
|
|
192
192
|
stopBackgroundTask(taskId: string): Promise<void>;
|
|
193
193
|
hasActiveBackgroundTasks(conversationId: string): boolean;
|
|
194
194
|
settleBackgroundStatus(conversationId: string): Promise<void>;
|
|
@@ -278,6 +278,8 @@ export declare class RunService {
|
|
|
278
278
|
* left HTTP-only paths with no owner at all.
|
|
279
279
|
*/
|
|
280
280
|
verifyPrimaryCapability(conversationId: string, capability: unknown): import("../capability.js").CapabilityVerdict;
|
|
281
|
+
foregroundSignal(conversationId: string): AbortSignal | undefined;
|
|
282
|
+
canAdmitBackgroundTask(signal?: AbortSignal): boolean;
|
|
281
283
|
/**
|
|
282
284
|
* Aborts all active conversation runs and sub-agents.
|
|
283
285
|
*/
|
|
@@ -295,7 +297,9 @@ export declare class RunService {
|
|
|
295
297
|
/**
|
|
296
298
|
* Stops an active turn run for a conversation.
|
|
297
299
|
*/
|
|
298
|
-
stopRun(conversationId: string
|
|
300
|
+
stopRun(conversationId: string, options?: {
|
|
301
|
+
foregroundOnly?: boolean;
|
|
302
|
+
}): Promise<void>;
|
|
299
303
|
/** Releases waits that can prevent Pi's abort from reaching its idle state. Idempotent by design. */
|
|
300
304
|
private cancelPendingRunInteractions;
|
|
301
305
|
private stopRunUnsafe;
|