@evandu/super-pi 0.1.242 → 0.1.244
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 +8 -2
- package/agents/code-designer.md +10 -4
- package/agents/solution-designer.md +5 -1
- package/dist/client/.super-pi-client-sources.json +12 -8
- package/dist/client/assets/{CodeMirrorEditor-BXlGF-8I.js → CodeMirrorEditor-B1T8wU12.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-zWN38BGh.js → GitDiffEditor-LCXbSvsh.js} +1 -1
- package/dist/client/assets/{index-D8M5Jjzq.js → index-DDrbcKk9.js} +52 -52
- package/dist/client/assets/index-DltiyYgr.css +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/application/group-chat-service.d.ts +14 -2
- package/dist/server/application/group-chat-service.js +298 -64
- package/dist/server/application/group-execution.d.ts +15 -0
- package/dist/server/application/group-execution.js +77 -0
- package/dist/server/http-server.js +140 -95
- package/dist/server/index.js +1 -1
- package/dist/server/runtime.d.ts +10 -0
- package/dist/server/runtime.js +26 -1
- package/dist/server/types.d.ts +4 -1
- package/dist/server/update-status.d.ts +14 -0
- package/dist/server/update-status.js +69 -0
- package/dist/server/update.d.ts +0 -17
- package/dist/server/update.js +0 -26
- package/dist/shared/group-chat.d.ts +52 -2
- package/dist/shared/update-status.d.ts +28 -0
- package/dist/shared/update-status.js +1 -0
- package/package.json +1 -1
- package/scripts/restart-server.mjs +9 -1
- package/dist/client/assets/index-BbMji0nU.css +0 -1
package/dist/client/index.html
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
<link rel="alternate icon" href="/favicon.ico" />
|
|
9
9
|
<link rel="apple-touch-icon" href="/favicon.svg" />
|
|
10
10
|
<title>Super Pi</title>
|
|
11
|
-
<script type="module" crossorigin src="/assets/index-
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-DDrbcKk9.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
|
|
13
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
13
|
+
<link rel="stylesheet" crossorigin href="/assets/index-DltiyYgr.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
|
16
16
|
<div id="root"></div>
|
|
@@ -1,24 +1,36 @@
|
|
|
1
|
-
import type { GroupSnapshot, GroupSummary } from "../../shared/group-chat.js";
|
|
1
|
+
import type { GroupExecutionSnapshot, GroupSnapshot, GroupSummary } from "../../shared/group-chat.js";
|
|
2
|
+
export declare class GroupChatNotFoundError extends Error {
|
|
3
|
+
constructor(message?: string);
|
|
4
|
+
}
|
|
2
5
|
export declare class GroupChatService {
|
|
3
6
|
private readonly filePath;
|
|
4
7
|
private readonly store;
|
|
5
8
|
private readonly runtime;
|
|
6
9
|
private readonly memory?;
|
|
10
|
+
private readonly onActivity?;
|
|
7
11
|
private rooms;
|
|
8
12
|
private writes;
|
|
9
13
|
private readonly running;
|
|
10
14
|
private readonly memberRuns;
|
|
11
15
|
private readonly controllers;
|
|
12
16
|
private readonly live;
|
|
17
|
+
private readonly liveExecutions;
|
|
13
18
|
private readonly streamRevisions;
|
|
14
19
|
private closing;
|
|
15
20
|
private constructor();
|
|
16
|
-
static open(filePath: string, store: GroupChatService["store"], runtime: GroupChatService["runtime"], memory?: GroupChatService["memory"]): Promise<GroupChatService>;
|
|
21
|
+
static open(filePath: string, store: GroupChatService["store"], runtime: GroupChatService["runtime"], memory?: GroupChatService["memory"], onActivity?: GroupChatService["onActivity"]): Promise<GroupChatService>;
|
|
17
22
|
private workspace;
|
|
18
23
|
private find;
|
|
24
|
+
private activeRoom;
|
|
25
|
+
private hasUnsettledWork;
|
|
19
26
|
private edit;
|
|
27
|
+
private publishActivity;
|
|
20
28
|
list(workspaceId: string): GroupSummary[];
|
|
21
29
|
get(workspaceId: string, id: string): GroupSnapshot;
|
|
30
|
+
execution(workspaceId: string, id: string, postId: string): GroupExecutionSnapshot;
|
|
31
|
+
private saveExecution;
|
|
32
|
+
setArchived(workspaceId: string, id: string, archived: boolean): Promise<GroupSummary>;
|
|
33
|
+
deleteArchived(workspaceId: string, id: string): Promise<void>;
|
|
22
34
|
private moderator;
|
|
23
35
|
private resolveMembers;
|
|
24
36
|
create(workspaceId: string, input: {
|
|
@@ -5,16 +5,52 @@ import { DEFAULT_GROUP_MEMBER_IDS } from "../../shared/group-chat.js";
|
|
|
5
5
|
import { CODING_STANDARD_REQUEST } from "../active-memory.js";
|
|
6
6
|
import { applicableRules, assertModelAllowed } from "../model-filter.js";
|
|
7
7
|
import { replaceFile } from "../persistence/rename.js";
|
|
8
|
-
|
|
8
|
+
import { finishGroupExecution, GroupExecutionRecorder } from "./group-execution.js";
|
|
9
|
+
const MAX_AUTOMATIC_REPLIES = 10;
|
|
10
|
+
const MAX_REPLIES_PER_MEMBER = 3;
|
|
11
|
+
const CONTEXT_MESSAGES = 20;
|
|
9
12
|
const MAX_CONTENT = 32_000;
|
|
13
|
+
const SAVED_EXECUTIONS_PER_ROOM = 64;
|
|
10
14
|
const timestamp = () => new Date().toISOString();
|
|
11
15
|
function inputText(value, limit, label) {
|
|
12
16
|
if (typeof value !== "string" || value.length > limit)
|
|
13
17
|
throw new Error(`${label}格式无效或超过长度上限。`);
|
|
14
18
|
return value.trim();
|
|
15
19
|
}
|
|
16
|
-
function
|
|
17
|
-
|
|
20
|
+
function activityStatus(messages) {
|
|
21
|
+
let latestTopic;
|
|
22
|
+
let activeTopic = false;
|
|
23
|
+
let activeBackground = false;
|
|
24
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
25
|
+
const post = messages[i];
|
|
26
|
+
if (post.role === "user") {
|
|
27
|
+
latestTopic ??= post.status;
|
|
28
|
+
if (post.status === "queued")
|
|
29
|
+
return "running";
|
|
30
|
+
activeTopic ||= post.status === "running";
|
|
31
|
+
}
|
|
32
|
+
else if (post.status === "queued" || post.status === "running") {
|
|
33
|
+
if (!post.background)
|
|
34
|
+
return "running";
|
|
35
|
+
activeBackground = true;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (activeBackground)
|
|
39
|
+
return "awaiting_background";
|
|
40
|
+
if (activeTopic)
|
|
41
|
+
return "running";
|
|
42
|
+
if (latestTopic === "completed")
|
|
43
|
+
return "completed";
|
|
44
|
+
if (latestTopic === "failed" || latestTopic === "interrupted")
|
|
45
|
+
return "failed";
|
|
46
|
+
return "idle";
|
|
47
|
+
}
|
|
48
|
+
function groupActivity(room) {
|
|
49
|
+
return { status: activityStatus(room.messages), revision: room.revision };
|
|
50
|
+
}
|
|
51
|
+
function summary(room) {
|
|
52
|
+
const { id, workspaceId, title, updatedAt, archivedAt } = room;
|
|
53
|
+
return { id, workspaceId, title, updatedAt, archivedAt, activity: groupActivity(room) };
|
|
18
54
|
}
|
|
19
55
|
async function readReferences(workspacePath, input) {
|
|
20
56
|
if (!Array.isArray(input) || !input.length)
|
|
@@ -47,44 +83,72 @@ async function readReferences(workspacePath, input) {
|
|
|
47
83
|
}
|
|
48
84
|
}));
|
|
49
85
|
}
|
|
50
|
-
function route(text,
|
|
86
|
+
function route(text, candidates, anchors) {
|
|
51
87
|
const parsed = JSON.parse(text.trim().replace(/^```(?:json)?\s*|\s*```$/gi, ""));
|
|
52
88
|
if (!parsed || typeof parsed !== "object")
|
|
53
89
|
throw new Error("主持人未返回有效决定。");
|
|
54
90
|
const decision = parsed;
|
|
91
|
+
const reason = typeof decision.reason === "string" ? decision.reason.trim().slice(0, 320) : undefined;
|
|
55
92
|
if (decision.action === "finish")
|
|
56
|
-
return
|
|
57
|
-
if (
|
|
93
|
+
return { action: "finish", reason };
|
|
94
|
+
if (decision.action === "blocked" && reason)
|
|
95
|
+
return { action: "blocked", reason };
|
|
96
|
+
if (decision.action === "wait")
|
|
97
|
+
return { action: "wait", memberId: typeof decision.memberId === "string" ? decision.memberId : undefined };
|
|
98
|
+
if (!["reply", "background"].includes(String(decision.action)) || typeof decision.memberId !== "string" || !candidates.some(member => member.id === decision.memberId)) {
|
|
58
99
|
throw new Error("主持人选择了无效的群成员。");
|
|
59
100
|
}
|
|
60
101
|
const replyTo = typeof decision.replyTo === "string" && anchors.has(decision.replyTo) ? decision.replyTo : undefined;
|
|
61
102
|
const assignment = inputText(decision.assignment, 1600, "接话任务");
|
|
62
103
|
if (!assignment)
|
|
63
104
|
throw new Error("主持人没有给出接话任务。");
|
|
64
|
-
|
|
65
|
-
|
|
105
|
+
return { action: "reply", memberId: decision.memberId, replyTo, assignment, reason, background: decision.action === "background" };
|
|
106
|
+
}
|
|
107
|
+
function extractHandoff(author, content, members) {
|
|
108
|
+
const line = content.trimEnd().split(/\r?\n/u).at(-1)?.trim();
|
|
109
|
+
const request = line?.match(/^@([^::]{1,100})[::]\s*(.{1,800})$/u);
|
|
110
|
+
if (!request)
|
|
111
|
+
return;
|
|
112
|
+
const recipient = request[1].trim();
|
|
113
|
+
const matches = members.filter(member => member.id === recipient || member.name === recipient);
|
|
114
|
+
const assignment = request[2].trim();
|
|
115
|
+
if (matches.length === 1 && matches[0].id !== author && assignment)
|
|
116
|
+
return { memberId: matches[0].id, assignment };
|
|
117
|
+
}
|
|
118
|
+
function outstandingHandoffs(replies) {
|
|
119
|
+
return replies.flatMap(post => {
|
|
120
|
+
const handoff = post.status === "completed" ? post.handoff : undefined;
|
|
121
|
+
const delegated = handoff && replies.some(reply => reply.replyTo === post.id && reply.memberId === handoff.memberId && reply.status !== "failed");
|
|
122
|
+
return handoff && !delegated ? [{ ...handoff, replyTo: post.id, from: post.memberId }] : [];
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
export class GroupChatNotFoundError extends Error {
|
|
126
|
+
constructor(message = "此工作区没有这个群聊。") { super(message); }
|
|
66
127
|
}
|
|
67
128
|
export class GroupChatService {
|
|
68
129
|
filePath;
|
|
69
130
|
store;
|
|
70
131
|
runtime;
|
|
71
132
|
memory;
|
|
133
|
+
onActivity;
|
|
72
134
|
rooms = [];
|
|
73
135
|
writes = Promise.resolve();
|
|
74
136
|
running = new Map();
|
|
75
137
|
memberRuns = new Map();
|
|
76
138
|
controllers = new Map();
|
|
77
139
|
live = new Map();
|
|
140
|
+
liveExecutions = new Map();
|
|
78
141
|
streamRevisions = new Map();
|
|
79
142
|
closing = false;
|
|
80
|
-
constructor(filePath, store, runtime, memory) {
|
|
143
|
+
constructor(filePath, store, runtime, memory, onActivity) {
|
|
81
144
|
this.filePath = filePath;
|
|
82
145
|
this.store = store;
|
|
83
146
|
this.runtime = runtime;
|
|
84
147
|
this.memory = memory;
|
|
148
|
+
this.onActivity = onActivity;
|
|
85
149
|
}
|
|
86
|
-
static async open(filePath, store, runtime, memory) {
|
|
87
|
-
const service = new GroupChatService(filePath, store, runtime, memory);
|
|
150
|
+
static async open(filePath, store, runtime, memory, onActivity) {
|
|
151
|
+
const service = new GroupChatService(filePath, store, runtime, memory, onActivity);
|
|
88
152
|
try {
|
|
89
153
|
service.rooms = JSON.parse(await readFile(filePath, "utf8"));
|
|
90
154
|
}
|
|
@@ -99,6 +163,9 @@ export class GroupChatService {
|
|
|
99
163
|
if (post.status === "running" || (post.role === "assistant" && post.status === "queued")) {
|
|
100
164
|
post.status = "interrupted";
|
|
101
165
|
post.error = "服务重启,本次发言已中断。";
|
|
166
|
+
const trace = room.executions?.[post.id];
|
|
167
|
+
if (trace && room.executions)
|
|
168
|
+
room.executions[post.id] = finishGroupExecution(trace);
|
|
102
169
|
room.revision += 1;
|
|
103
170
|
}
|
|
104
171
|
});
|
|
@@ -117,32 +184,119 @@ export class GroupChatService {
|
|
|
117
184
|
this.workspace(workspaceId);
|
|
118
185
|
const room = rooms.find(item => item.id === id && item.workspaceId === workspaceId);
|
|
119
186
|
if (!room)
|
|
120
|
-
throw new
|
|
187
|
+
throw new GroupChatNotFoundError();
|
|
188
|
+
return room;
|
|
189
|
+
}
|
|
190
|
+
activeRoom(rooms, workspaceId, id) {
|
|
191
|
+
const room = this.find(rooms, workspaceId, id);
|
|
192
|
+
if (room.archivedAt)
|
|
193
|
+
throw new Error("群聊已归档,请先恢复。");
|
|
121
194
|
return room;
|
|
122
195
|
}
|
|
196
|
+
hasUnsettledWork(room) {
|
|
197
|
+
return room.messages.some(post => post.status === "queued" || post.status === "running" || this.running.has(post.id));
|
|
198
|
+
}
|
|
123
199
|
edit(change) {
|
|
124
200
|
const write = this.writes.then(async () => {
|
|
125
|
-
const
|
|
201
|
+
const previous = this.rooms;
|
|
202
|
+
const rooms = structuredClone(previous);
|
|
126
203
|
const result = change(rooms);
|
|
127
204
|
const temporary = this.filePath + ".tmp";
|
|
128
205
|
await writeFile(temporary, JSON.stringify(rooms), { encoding: "utf8", mode: 0o600 });
|
|
129
206
|
await replaceFile(temporary, this.filePath);
|
|
130
207
|
this.rooms = rooms;
|
|
208
|
+
this.publishActivity(previous);
|
|
131
209
|
return result;
|
|
132
210
|
});
|
|
133
211
|
this.writes = write.then(() => undefined, () => undefined);
|
|
134
212
|
return write;
|
|
135
213
|
}
|
|
214
|
+
publishActivity(previous) {
|
|
215
|
+
if (!this.onActivity)
|
|
216
|
+
return;
|
|
217
|
+
const prior = new Map(previous.map(room => [room.id, room]));
|
|
218
|
+
for (const room of this.rooms) {
|
|
219
|
+
const before = prior.get(room.id);
|
|
220
|
+
if (!before || before.revision === room.revision)
|
|
221
|
+
continue;
|
|
222
|
+
const workspace = this.store.workspace(room.workspaceId);
|
|
223
|
+
if (!workspace || workspace.closedAt)
|
|
224
|
+
continue;
|
|
225
|
+
const activity = groupActivity(room);
|
|
226
|
+
if (activity.status !== activityStatus(before.messages))
|
|
227
|
+
this.onActivity({ id: room.id, workspaceId: room.workspaceId, activity });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
136
230
|
list(workspaceId) {
|
|
137
231
|
this.workspace(workspaceId);
|
|
138
232
|
return this.rooms.filter(room => room.workspaceId === workspaceId).map(summary).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
139
233
|
}
|
|
140
234
|
get(workspaceId, id) {
|
|
141
|
-
const
|
|
235
|
+
const { executions, ...record } = this.find(this.rooms, workspaceId, id);
|
|
236
|
+
const room = structuredClone(record);
|
|
142
237
|
for (const post of room.messages)
|
|
143
|
-
if (post.status === "running")
|
|
238
|
+
if (post.status === "running") {
|
|
144
239
|
post.content = this.live.get(post.id) ?? post.content;
|
|
145
|
-
|
|
240
|
+
if (post.role === "assistant")
|
|
241
|
+
post.executionActivity = this.liveExecutions.get(post.id)?.activity;
|
|
242
|
+
}
|
|
243
|
+
return { ...room, activity: groupActivity(room), revision: `${room.revision}:${this.streamRevisions.get(id) ?? 0}` };
|
|
244
|
+
}
|
|
245
|
+
execution(workspaceId, id, postId) {
|
|
246
|
+
const room = this.find(this.rooms, workspaceId, id);
|
|
247
|
+
const post = room.messages.find(item => item.id === postId && item.role === "assistant");
|
|
248
|
+
if (!post)
|
|
249
|
+
throw new GroupChatNotFoundError("群聊里找不到该次执行。");
|
|
250
|
+
const live = post.status === "running" ? this.liveExecutions.get(postId) : undefined;
|
|
251
|
+
const trace = live?.trace ?? room.executions?.[postId] ?? { steps: [] };
|
|
252
|
+
return { ...structuredClone(trace), status: post.status, revision: `${room.revision}:${live?.revision ?? 0}` };
|
|
253
|
+
}
|
|
254
|
+
saveExecution(room, postId, settled = false) {
|
|
255
|
+
const live = this.liveExecutions.get(postId);
|
|
256
|
+
if (!live?.trace.steps.length)
|
|
257
|
+
return;
|
|
258
|
+
const trace = structuredClone(live.trace);
|
|
259
|
+
const executions = room.executions ??= {};
|
|
260
|
+
executions[postId] = settled ? finishGroupExecution(trace) : trace;
|
|
261
|
+
const ids = Object.keys(executions);
|
|
262
|
+
if (ids.length > SAVED_EXECUTIONS_PER_ROOM) {
|
|
263
|
+
const expired = ids.find(id => !this.liveExecutions.has(id));
|
|
264
|
+
if (expired)
|
|
265
|
+
delete executions[expired];
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
async setArchived(workspaceId, id, archived) {
|
|
269
|
+
return this.edit(rooms => {
|
|
270
|
+
const room = this.find(rooms, workspaceId, id);
|
|
271
|
+
if (Boolean(room.archivedAt) === archived)
|
|
272
|
+
return summary(room);
|
|
273
|
+
if (archived && this.hasUnsettledWork(room))
|
|
274
|
+
throw new Error("群聊还有任务未结束,请先停止任务或等它结束后再归档。");
|
|
275
|
+
room.updatedAt = timestamp();
|
|
276
|
+
if (archived)
|
|
277
|
+
room.archivedAt = room.updatedAt;
|
|
278
|
+
else
|
|
279
|
+
delete room.archivedAt;
|
|
280
|
+
room.revision += 1;
|
|
281
|
+
return summary(room);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
async deleteArchived(workspaceId, id) {
|
|
285
|
+
this.workspace(workspaceId);
|
|
286
|
+
const removed = await this.edit(rooms => {
|
|
287
|
+
const index = rooms.findIndex(room => room.workspaceId === workspaceId && room.id === id);
|
|
288
|
+
if (index < 0)
|
|
289
|
+
return false;
|
|
290
|
+
const room = rooms[index];
|
|
291
|
+
if (!room.archivedAt)
|
|
292
|
+
throw new Error("请先归档群聊,再永久删除。");
|
|
293
|
+
if (this.hasUnsettledWork(room))
|
|
294
|
+
throw new Error("群聊还有任务未结束,请等它结束后再删除。");
|
|
295
|
+
rooms.splice(index, 1);
|
|
296
|
+
return true;
|
|
297
|
+
});
|
|
298
|
+
if (removed)
|
|
299
|
+
this.streamRevisions.delete(id);
|
|
146
300
|
}
|
|
147
301
|
async moderator(workspaceId, body) {
|
|
148
302
|
const workspace = this.workspace(workspaceId);
|
|
@@ -188,11 +342,11 @@ export class GroupChatService {
|
|
|
188
342
|
return this.get(workspaceId, id);
|
|
189
343
|
}
|
|
190
344
|
async configure(workspaceId, id, input) {
|
|
191
|
-
const current = this.
|
|
345
|
+
const current = this.activeRoom(this.rooms, workspaceId, id);
|
|
192
346
|
const moderator = await this.moderator(workspaceId, input);
|
|
193
347
|
const members = input.memberIds === undefined ? undefined : await this.resolveMembers(id, input.memberIds, current.members);
|
|
194
348
|
await this.edit(rooms => {
|
|
195
|
-
const room = this.
|
|
349
|
+
const room = this.activeRoom(rooms, workspaceId, id);
|
|
196
350
|
if (members) {
|
|
197
351
|
for (const post of room.messages)
|
|
198
352
|
if (post.role === "assistant")
|
|
@@ -211,12 +365,12 @@ export class GroupChatService {
|
|
|
211
365
|
const clientId = inputText(input.clientId, 128, "发送标识");
|
|
212
366
|
if (!content || !clientId)
|
|
213
367
|
throw new Error("消息内容和发送标识不能为空。");
|
|
214
|
-
const current = this.
|
|
368
|
+
const current = this.activeRoom(this.rooms, workspaceId, id);
|
|
215
369
|
if (current.messages.some(post => post.role === "user" && post.clientId === clientId))
|
|
216
370
|
return this.get(workspaceId, id);
|
|
217
371
|
const files = await readReferences(this.workspace(workspaceId).path, input.filePaths);
|
|
218
372
|
await this.edit(rooms => {
|
|
219
|
-
const room = this.
|
|
373
|
+
const room = this.activeRoom(rooms, workspaceId, id);
|
|
220
374
|
if (room.messages.some(post => post.role === "user" && post.clientId === clientId))
|
|
221
375
|
return;
|
|
222
376
|
const parent = typeof input.replyTo === "string" ? room.messages.find(post => post.id === input.replyTo) : undefined;
|
|
@@ -240,11 +394,13 @@ export class GroupChatService {
|
|
|
240
394
|
}
|
|
241
395
|
async stop(workspaceId, id, postId) {
|
|
242
396
|
const cancelled = await this.edit(rooms => {
|
|
243
|
-
const room = this.
|
|
397
|
+
const room = this.activeRoom(rooms, workspaceId, id);
|
|
244
398
|
const posts = room.messages.filter(post => (post.id === postId || (post.role === "assistant" && post.topicId === postId)) && ["queued", "running"].includes(post.status));
|
|
245
399
|
for (const post of posts) {
|
|
246
400
|
post.content = this.live.get(post.id) ?? post.content;
|
|
247
401
|
post.status = "cancelled";
|
|
402
|
+
if (post.role === "assistant")
|
|
403
|
+
this.saveExecution(room, post.id, true);
|
|
248
404
|
}
|
|
249
405
|
room.revision += 1;
|
|
250
406
|
return posts.map(post => post.id);
|
|
@@ -257,7 +413,7 @@ export class GroupChatService {
|
|
|
257
413
|
if (this.closing)
|
|
258
414
|
return;
|
|
259
415
|
const room = this.rooms.find(item => item.id === id);
|
|
260
|
-
if (!room)
|
|
416
|
+
if (!room || room.archivedAt)
|
|
261
417
|
return;
|
|
262
418
|
for (const post of room.messages) {
|
|
263
419
|
if (post.role !== "user" || post.status !== "queued" || this.running.has(post.id))
|
|
@@ -307,6 +463,7 @@ export class GroupChatService {
|
|
|
307
463
|
if (topic.memberIds.length)
|
|
308
464
|
await start(topic.memberIds.map(memberId => ({ memberId, replyTo: topic.replyTo ?? topic.id })));
|
|
309
465
|
let count = 0;
|
|
466
|
+
let incomplete;
|
|
310
467
|
while (!controller.signal.aborted) {
|
|
311
468
|
const current = this.rooms.find(item => item.id === room.id);
|
|
312
469
|
if (current.messages.find(post => post.id === topic.id)?.status !== "running")
|
|
@@ -316,29 +473,69 @@ export class GroupChatService {
|
|
|
316
473
|
const busy = new Set(current.messages.flatMap(post => post.role === "assistant" && (post.status === "running" || post.status === "queued") ? [post.memberId] : []));
|
|
317
474
|
const available = current.members.filter(member => {
|
|
318
475
|
const attempted = replies.filter(post => post.memberId === member.id);
|
|
319
|
-
return attempted.length <
|
|
476
|
+
return attempted.length < MAX_REPLIES_PER_MEMBER && !attempted.some(post => post.status === "cancelled" || post.status === "interrupted");
|
|
320
477
|
});
|
|
321
478
|
const candidates = available.filter(member => !busy.has(member.id));
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
479
|
+
const handoffs = outstandingHandoffs(replies);
|
|
480
|
+
const remaining = MAX_AUTOMATIC_REPLIES - count;
|
|
481
|
+
if (active.length && (!candidates.length || !remaining)) {
|
|
482
|
+
await Promise.race(active.map(reply => reply.done));
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
const next = candidates.length || handoffs.length || !remaining || (replies.length && available.some(member => busy.has(member.id)))
|
|
486
|
+
? await this.choose(current, topic, candidates, replies, handoffs, busy, remaining, controller.signal)
|
|
487
|
+
: { action: "finish" };
|
|
488
|
+
if (next.action === "reply") {
|
|
489
|
+
if (!remaining) {
|
|
490
|
+
incomplete = "本轮达到自动接话上限,已有进展已保留。可以告诉群里从哪一步继续。";
|
|
491
|
+
break;
|
|
492
|
+
}
|
|
493
|
+
const completed = replies.filter(post => post.status === "completed").sort((a, b) => (a.settledAt ?? a.createdAt).localeCompare(b.settledAt ?? b.createdAt));
|
|
494
|
+
const handoff = handoffs.find(item => item.memberId === next.memberId);
|
|
495
|
+
const replyTo = next.replyTo ?? handoff?.replyTo ?? completed.at(-1)?.id ?? topic.id;
|
|
325
496
|
count += 1;
|
|
326
497
|
await start([{ ...next, replyTo }]);
|
|
498
|
+
continue;
|
|
499
|
+
}
|
|
500
|
+
if (next.action === "wait") {
|
|
501
|
+
const work = next.memberId ? this.memberRuns.get(JSON.stringify([room.id, next.memberId])) : undefined;
|
|
502
|
+
if (work) {
|
|
503
|
+
await this.waitForWork(work, controller.signal);
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
327
506
|
}
|
|
328
|
-
|
|
507
|
+
if (active.length) {
|
|
329
508
|
await Promise.race(active.map(reply => reply.done));
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
if (next.action === "blocked") {
|
|
512
|
+
incomplete = next.reason;
|
|
513
|
+
break;
|
|
330
514
|
}
|
|
331
|
-
|
|
515
|
+
if (!replies.length && available.length) {
|
|
332
516
|
const work = available.flatMap(member => this.memberRuns.get(JSON.stringify([room.id, member.id])) ?? []);
|
|
333
|
-
if (
|
|
334
|
-
|
|
335
|
-
|
|
517
|
+
if (work.length) {
|
|
518
|
+
await this.waitForWork(Promise.race(work), controller.signal);
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
336
521
|
}
|
|
337
|
-
|
|
338
|
-
|
|
522
|
+
if (next.action === "wait") {
|
|
523
|
+
if (this.rooms.find(item => item.id === room.id)?.revision !== current.revision)
|
|
524
|
+
continue;
|
|
525
|
+
incomplete = "本轮仍有后续工作,但当前没有对应的运行任务。已有进展已保留。";
|
|
526
|
+
}
|
|
527
|
+
else if (handoffs.length && !next.reason) {
|
|
528
|
+
const work = handoffs.flatMap(handoff => this.memberRuns.get(JSON.stringify([room.id, handoff.memberId])) ?? []);
|
|
529
|
+
if (work.length) {
|
|
530
|
+
await this.waitForWork(Promise.race(work), controller.signal);
|
|
531
|
+
continue;
|
|
532
|
+
}
|
|
533
|
+
incomplete = "本轮还有未接手的工作,已有发言和结果已保留。";
|
|
534
|
+
}
|
|
535
|
+
break;
|
|
339
536
|
}
|
|
340
537
|
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 : "本轮没有收到完整回复。");
|
|
538
|
+
await this.settle(room.id, topic.id, controller.signal, incomplete ?? (replies.some(post => post.status === "completed") ? undefined : "本轮没有收到完整回复。"));
|
|
342
539
|
}
|
|
343
540
|
catch (error) {
|
|
344
541
|
await Promise.allSettled(pending.map(reply => reply.done));
|
|
@@ -357,10 +554,11 @@ export class GroupChatService {
|
|
|
357
554
|
context(room, topic) {
|
|
358
555
|
const topicIndex = room.messages.findIndex(post => post.id === topic.id);
|
|
359
556
|
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)
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
557
|
+
const topicIds = new Set(previous.map(post => post.id));
|
|
558
|
+
const current = room.messages.filter(post => post.role === "assistant" && post.topicId === topic.id && post.status === "completed").slice(-CONTEXT_MESSAGES);
|
|
559
|
+
const roomHistory = room.messages.filter(post => post.role === "assistant" ? topicIds.has(post.topicId) && post.status === "completed" : topicIds.has(post.id));
|
|
560
|
+
const remaining = CONTEXT_MESSAGES - current.length;
|
|
561
|
+
return [...(remaining ? roomHistory.slice(-remaining) : []), ...current].map(post => ({
|
|
364
562
|
id: post.id, author: post.role === "user" ? "用户" : post.memberName ?? room.members.find(member => member.id === post.memberId)?.name,
|
|
365
563
|
content: post.content.slice(0, 4_000),
|
|
366
564
|
}));
|
|
@@ -375,31 +573,36 @@ export class GroupChatService {
|
|
|
375
573
|
throw new Error("当前运行时不支持群聊模型。");
|
|
376
574
|
return this.runtime.askOnce({ ...input, model, cwd: workspace.path });
|
|
377
575
|
}
|
|
378
|
-
async choose(room, topic, candidates, signal) {
|
|
576
|
+
async choose(room, topic, candidates, replies, handoffs, busy, remainingReplies, signal) {
|
|
379
577
|
const context = this.context(room, topic);
|
|
380
|
-
const performed =
|
|
381
|
-
.map(({ memberId, status, assignment, background }) => ({ memberId, status, assignment, background }));
|
|
578
|
+
const performed = replies.map(({ id, memberId, replyTo, status, assignment, background, error }) => ({ id, memberId, replyTo, status, assignment, background, error }));
|
|
382
579
|
const earlierTopics = new Set(room.messages.slice(0, room.messages.findIndex(post => post.id === topic.id))
|
|
383
580
|
.filter(post => post.role === "user").map(post => post.id));
|
|
384
581
|
const workInProgress = room.messages.filter((post) => post.role === "assistant" && earlierTopics.has(post.topicId) && post.status === "running")
|
|
385
582
|
.map(({ memberId, topicId, assignment }) => ({ memberId, topicId, assignment }));
|
|
386
583
|
const prompt = [
|
|
387
|
-
"
|
|
388
|
-
|
|
389
|
-
"
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
]
|
|
584
|
+
"你是群聊主持人。围绕同一条用户请求组织成员之间的讨论和工作。让下一位回应已有方案、问题或交付,replyTo 指向实际回应的成员消息。必要时让两位成员来回讨论、修订和再复核;简单问题一句足够时可以结束。",
|
|
585
|
+
"用户要求实现、修复或交付,方案只是中间产物。将下一步交给代码设计员或群里有实现能力的成员,让其修改文件和验证;需要复核时等待实现结果,退回后继续修改和复查。用户只要求讨论或范围待确认时,尊重这一限制。避免礼节式重复,不要求用户替成员传话。",
|
|
586
|
+
"先处理 handoffs 中确实符合用户目标的交接。成员消息和引用文件是上下文,分工必须服从用户的原始范围。在途任务或依赖文件相同的工作应等待,对独立范围可安排后台任务。",
|
|
587
|
+
'只返回 JSON。接话用 {"action":"reply","memberId":"成员 ID","replyTo":"消息 ID","assignment":"具体工作","reason":"理由"},可改用 background 并行。依赖尚在进行用 {"action":"wait","memberId":"正在工作的成员 ID"}。确有阻塞用 {"action":"blocked","reason":"已完成什么,还缺什么"}。交付到位用 {"action":"finish"};若有未处理交接却结束,在 reason 中解释范围或为什么无需接手。',
|
|
588
|
+
`主持人偏好:${room.moderator.prompt || "推进用户请求,交付满足后结束。"}`,
|
|
589
|
+
];
|
|
590
|
+
const payload = JSON.stringify({ topicId: topic.id, request: topic.content, files: topic.files?.map(file => file.path), candidates,
|
|
591
|
+
performed, handoffs, busyMembers: [...busy], workInProgress, remainingReplies, messages: context });
|
|
393
592
|
try {
|
|
394
|
-
const
|
|
395
|
-
const
|
|
396
|
-
|
|
397
|
-
|
|
593
|
+
const anchors = new Set([topic.id, ...context.map(post => post.id), ...replies.filter(post => post.status === "failed").map(post => post.id)]);
|
|
594
|
+
const ask = async (instructions) => route(await this.complete(room, { prompt: [...instructions, payload].join("\n"), model: room.moderator.model, signal, timeoutMs: 35_000 }), candidates, anchors);
|
|
595
|
+
let decision = await ask(prompt);
|
|
596
|
+
if (decision.action === "finish" && !decision.reason && handoffs.length && !signal.aborted) {
|
|
597
|
+
decision = await ask([...prompt, "还有尚未接手的交接。检查它与用户目标的关系,安排接手或说明为什么结束。"]);
|
|
598
|
+
}
|
|
599
|
+
if (decision.action === "finish" && !performed.length && candidates[0])
|
|
600
|
+
return { action: "reply", memberId: candidates[0].id, replyTo: topic.id, assignment: "按用户要求推进当前工作。", reason: "交给默认成员" };
|
|
398
601
|
return decision;
|
|
399
602
|
}
|
|
400
603
|
catch (error) {
|
|
401
604
|
if (signal.aborted)
|
|
402
|
-
return
|
|
605
|
+
return { action: "finish" };
|
|
403
606
|
throw new Error(`主持人未能安排回复:${error instanceof Error ? error.message : String(error)}`);
|
|
404
607
|
}
|
|
405
608
|
}
|
|
@@ -434,6 +637,7 @@ export class GroupChatService {
|
|
|
434
637
|
const done = this.runMember(roomId, topic, reply, memberSignal, allowNext, prior).finally(() => {
|
|
435
638
|
allowNext();
|
|
436
639
|
this.live.delete(reply.id);
|
|
640
|
+
this.liveExecutions.delete(reply.id);
|
|
437
641
|
this.controllers.delete(reply.id);
|
|
438
642
|
});
|
|
439
643
|
if (reply.background || prior)
|
|
@@ -470,7 +674,26 @@ export class GroupChatService {
|
|
|
470
674
|
});
|
|
471
675
|
if (!started)
|
|
472
676
|
return;
|
|
473
|
-
|
|
677
|
+
const execution = new GroupExecutionRecorder();
|
|
678
|
+
this.liveExecutions.set(reply.id, execution);
|
|
679
|
+
let checkpointTimer;
|
|
680
|
+
const checkpoint = () => {
|
|
681
|
+
if (checkpointTimer)
|
|
682
|
+
return;
|
|
683
|
+
checkpointTimer = setTimeout(() => {
|
|
684
|
+
checkpointTimer = undefined;
|
|
685
|
+
void this.edit(rooms => {
|
|
686
|
+
const room = rooms.find(item => item.id === roomId);
|
|
687
|
+
const post = room?.messages.find(item => item.id === reply.id);
|
|
688
|
+
if (!room || post?.status !== "running")
|
|
689
|
+
return;
|
|
690
|
+
post.content = this.live.get(reply.id) ?? post.content;
|
|
691
|
+
this.saveExecution(room, reply.id);
|
|
692
|
+
}).catch(error => console.warn("Super Pi: could not checkpoint group reply:", error));
|
|
693
|
+
}, 800);
|
|
694
|
+
};
|
|
695
|
+
const bumpStream = () => this.streamRevisions.set(roomId, (this.streamRevisions.get(roomId) ?? 0) + 1);
|
|
696
|
+
let activityKey;
|
|
474
697
|
let yielded = Boolean(reply.background);
|
|
475
698
|
const goBackground = () => {
|
|
476
699
|
if (yielded || memberSignal.aborted)
|
|
@@ -493,25 +716,29 @@ export class GroupChatService {
|
|
|
493
716
|
const notes = await this.memory?.groupEngineeringNotes(started.workspaceId, agent.id, topic.content + "\n" + (reply.assignment ?? ""))
|
|
494
717
|
.catch(() => undefined);
|
|
495
718
|
const prompt = [
|
|
496
|
-
`你以 ${agent.name}
|
|
497
|
-
|
|
719
|
+
`你以 ${agent.name} 的身份在群聊中回答。直接回应引用的成员意见,推进本次分工。有可用工具且分工要求执行时,直接完成并报告实际文件与验证;其他成员可以继续讨论。只修改分工涉及的文件。`,
|
|
720
|
+
"确实需要另一位成员推进时,在发言末尾另起一行写 @成员名:要接手的具体事项。主持人会按原请求判断并安排。可直接使用成员 ID。",
|
|
721
|
+
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 }),
|
|
498
722
|
].join("\n");
|
|
499
723
|
const answer = await this.complete(started, {
|
|
500
724
|
prompt, agent, model: agent.model && { ...agent.model, label: agent.model.modelId }, signal: memberSignal, timeoutMs: 15 * 60_000,
|
|
501
725
|
onToolStart: goBackground,
|
|
726
|
+
onExecution: event => {
|
|
727
|
+
if (memberSignal.aborted || !execution.record(event))
|
|
728
|
+
return;
|
|
729
|
+
const key = JSON.stringify(execution.activity);
|
|
730
|
+
if (key !== activityKey) {
|
|
731
|
+
activityKey = key;
|
|
732
|
+
bumpStream();
|
|
733
|
+
}
|
|
734
|
+
checkpoint();
|
|
735
|
+
},
|
|
502
736
|
onText: delta => {
|
|
503
737
|
if (memberSignal.aborted)
|
|
504
738
|
return;
|
|
505
739
|
this.live.set(reply.id, ((this.live.get(reply.id) ?? "") + delta).slice(0, MAX_CONTENT));
|
|
506
|
-
|
|
507
|
-
|
|
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));
|
|
740
|
+
bumpStream();
|
|
741
|
+
checkpoint();
|
|
515
742
|
},
|
|
516
743
|
});
|
|
517
744
|
await this.settle(roomId, reply.id, memberSignal, undefined, answer);
|
|
@@ -521,6 +748,7 @@ export class GroupChatService {
|
|
|
521
748
|
}
|
|
522
749
|
finally {
|
|
523
750
|
clearTimeout(timer);
|
|
751
|
+
clearTimeout(checkpointTimer);
|
|
524
752
|
}
|
|
525
753
|
}
|
|
526
754
|
async settle(roomId, postId, signal, error, content) {
|
|
@@ -533,6 +761,12 @@ export class GroupChatService {
|
|
|
533
761
|
if (content !== undefined)
|
|
534
762
|
post.content = content.slice(0, MAX_CONTENT);
|
|
535
763
|
post.error = signal.aborted ? (this.closing ? "服务停止,本次发言已中断。" : undefined) : error?.slice(0, 1600);
|
|
764
|
+
if (post.role === "assistant") {
|
|
765
|
+
this.saveExecution(room, postId, true);
|
|
766
|
+
post.settledAt = timestamp();
|
|
767
|
+
if (post.status === "completed")
|
|
768
|
+
post.handoff = extractHandoff(post.memberId, post.content, room.members);
|
|
769
|
+
}
|
|
536
770
|
room.revision += 1;
|
|
537
771
|
room.updatedAt = timestamp();
|
|
538
772
|
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { GroupExecutionActivity, GroupExecutionTrace } from "../../shared/group-chat.js";
|
|
2
|
+
import type { IsolatedExecutionEvent } from "../runtime.js";
|
|
3
|
+
export declare function finishGroupExecution(trace: GroupExecutionTrace): GroupExecutionTrace;
|
|
4
|
+
export declare class GroupExecutionRecorder {
|
|
5
|
+
private sequence;
|
|
6
|
+
private thinkingChars;
|
|
7
|
+
private currentThinking?;
|
|
8
|
+
private changed;
|
|
9
|
+
readonly trace: GroupExecutionTrace;
|
|
10
|
+
get revision(): number;
|
|
11
|
+
get activity(): GroupExecutionActivity | undefined;
|
|
12
|
+
private add;
|
|
13
|
+
private endThinking;
|
|
14
|
+
record(event: IsolatedExecutionEvent): boolean;
|
|
15
|
+
}
|