@evandu/super-pi 0.1.273 → 0.1.274

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 (69) hide show
  1. package/agents/group-rsi.md +18 -0
  2. package/agents/super-pi-task/core.ts +7 -7
  3. package/bin/completion.js +19 -5
  4. package/bin/super-pi.js +3 -0
  5. package/desktop/runtime.cjs +28 -4
  6. package/dist/client/.super-pi-client-sources.json +24 -16
  7. package/dist/client/assets/CodeMirrorEditor-DjMbNm7l.js +2 -0
  8. package/dist/client/assets/GitDiffEditor-Cwim9Ua1.js +29 -0
  9. package/dist/client/assets/{dist-DGBjhKI9.js → dist-AW5lyI3I.js} +1 -1
  10. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  11. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  12. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  13. package/dist/client/assets/{dist-BvjUKkwy.js → dist-BRVQKlcp.js} +1 -1
  14. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  15. package/dist/client/assets/{dist-BlRuQIg1.js → dist-BXAOrsjq.js} +1 -1
  16. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  17. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  18. package/dist/client/assets/{dist-i79xiXVk.js → dist-Cus6_oaF.js} +2 -2
  19. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  20. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  21. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  22. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  23. package/dist/client/assets/dist-DeD9copn.js +1 -0
  24. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  25. package/dist/client/assets/{dist-D5u1uPmZ.js → dist-Dvb0SqcK.js} +2 -2
  26. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  27. package/dist/client/assets/{dist-CQncCwUc.js → dist-QzbOCAU6.js} +1 -1
  28. package/dist/client/assets/{dist-DjI7p99D.js → dist-moiMRpw_.js} +1 -1
  29. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  30. package/dist/client/assets/index-BL9o4WZN.js +350 -0
  31. package/dist/client/assets/index-D1qJmoVY.css +1 -0
  32. package/dist/client/index.html +2 -2
  33. package/dist/server/application/conversation-service.d.ts +1 -1
  34. package/dist/server/application/conversation-service.js +3 -2
  35. package/dist/server/application/group-chat-service.d.ts +17 -0
  36. package/dist/server/application/group-chat-service.js +168 -3
  37. package/dist/server/application/group-rsi.d.ts +13 -0
  38. package/dist/server/application/group-rsi.js +69 -0
  39. package/dist/server/application/worktree-service.js +6 -2
  40. package/dist/server/http-server.js +22 -0
  41. package/dist/server/index.js +15 -2
  42. package/dist/server/managed-http.js +2 -1
  43. package/dist/server/managed-model-adapter.d.ts +4 -0
  44. package/dist/server/managed-model-relay.d.ts +1 -1
  45. package/dist/server/managed-model-relay.js +18 -15
  46. package/dist/server/managed-servers.d.ts +10 -1
  47. package/dist/server/managed-servers.js +63 -4
  48. package/dist/server/remote-bootstrap.d.ts +11 -0
  49. package/dist/server/remote-bootstrap.js +105 -29
  50. package/dist/shared/group-chat.d.ts +40 -0
  51. package/package.json +2 -1
  52. package/dist/client/assets/CodeMirrorEditor-D8MjtASz.js +0 -2
  53. package/dist/client/assets/GitDiffEditor-DFJmhUHc.js +0 -29
  54. package/dist/client/assets/dist-3qQVP6l8.js +0 -6
  55. package/dist/client/assets/dist-CZ4PyxQu.js +0 -9
  56. package/dist/client/assets/dist-CfTFp0AF.js +0 -2
  57. package/dist/client/assets/dist-CxmJXjJI.js +0 -1
  58. package/dist/client/assets/dist-D8HpMxmZ.js +0 -1
  59. package/dist/client/assets/dist-DRBIy9A1.js +0 -1
  60. package/dist/client/assets/dist-Dcww9FSw.js +0 -1
  61. package/dist/client/assets/dist-DlPa5gNa.js +0 -7
  62. package/dist/client/assets/dist-DxPJ1PN-.js +0 -1
  63. package/dist/client/assets/dist-HXD8sSA4.js +0 -23
  64. package/dist/client/assets/dist-LbeLCeoq.js +0 -1
  65. package/dist/client/assets/dist-ONdtnupI.js +0 -1
  66. package/dist/client/assets/dist-YqmXusLA.js +0 -11
  67. package/dist/client/assets/dist-ZAR1Tu2c.js +0 -3
  68. package/dist/client/assets/index-Bqutm6qV.js +0 -350
  69. package/dist/client/assets/index-DV3qc1Hh.css +0 -1
@@ -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-Bqutm6qV.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-BL9o4WZN.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-DV3qc1Hh.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-D1qJmoVY.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -179,7 +179,7 @@ export declare class ConversationService {
179
179
  * Reverts conversation history to a designated message boundary, truncating both
180
180
  * Pi's transcript and state.json.
181
181
  */
182
- revertMessage(conversationId: string, messageId: string, withdraw?: boolean): Promise<{
182
+ revertMessage(conversationId: string, messageId: string, _withdraw?: boolean): Promise<{
183
183
  content: string;
184
184
  images: import("../types.js").MessageImage[] | undefined;
185
185
  } | undefined>;
@@ -404,7 +404,7 @@ export class ConversationService {
404
404
  * Reverts conversation history to a designated message boundary, truncating both
405
405
  * Pi's transcript and state.json.
406
406
  */
407
- async revertMessage(conversationId, messageId, withdraw = false) {
407
+ async revertMessage(conversationId, messageId, _withdraw = true) {
408
408
  // CLAIMED FOR THE WHOLE CUT, and released in a `finally` however this ends - a revert that threw
409
409
  // halfway must not leave the conversation permanently unable to send. The per-conversation lane is
410
410
  // separate from the WebSocket command queue: revert may start immediately, but two clicks against
@@ -412,7 +412,8 @@ export class ConversationService {
412
412
  return this.serializeRevert(conversationId, async () => {
413
413
  this.claimRevert(conversationId);
414
414
  try {
415
- return await this.cutTo(conversationId, messageId, withdraw);
415
+ // Both user-facing actions edit the anchor by removing its entire turn.
416
+ return await this.cutTo(conversationId, messageId, true);
416
417
  }
417
418
  finally {
418
419
  this.releaseRevert(conversationId);
@@ -19,6 +19,11 @@ export declare class GroupChatService {
19
19
  private readonly liveExecutions;
20
20
  private readonly streamRevisions;
21
21
  private closing;
22
+ private readonly rsiTimers;
23
+ private readonly rsiJobs;
24
+ private readonly rsiControllers;
25
+ private readonly rsiAttempts;
26
+ private readonly rsiLastRun;
22
27
  private constructor();
23
28
  static open(filePath: string, store: GroupChatService["store"], runtime: GroupChatService["runtime"], memory?: GroupChatService["memory"], onActivity?: GroupChatService["onActivity"]): Promise<GroupChatService>;
24
29
  private workspace;
@@ -68,6 +73,18 @@ export declare class GroupChatService {
68
73
  private kick;
69
74
  private runTopic;
70
75
  private context;
76
+ private scheduleRsi;
77
+ private observeRsi;
78
+ updateRsi(workspaceId: string, id: string, body: {
79
+ action: string;
80
+ enabled?: unknown;
81
+ model?: unknown;
82
+ prompt?: unknown;
83
+ reportId?: unknown;
84
+ findingId?: unknown;
85
+ disposition?: unknown;
86
+ feedback?: unknown;
87
+ }): Promise<GroupSnapshot>;
71
88
  private complete;
72
89
  private choose;
73
90
  private respond;
@@ -7,6 +7,7 @@ import { CODING_STANDARD_REQUEST } from "../active-memory.js";
7
7
  import { applicableRules, assertModelAllowed } from "../model-filter.js";
8
8
  import { replaceFile } from "../persistence/rename.js";
9
9
  import { finishGroupExecution, GroupExecutionRecorder } from "./group-execution.js";
10
+ import { defaultGroupRsi, parseRsiReport, rsiInput, rsiSourceKey } from "./group-rsi.js";
10
11
  const MAX_AUTOMATIC_REPLIES = 10;
11
12
  const MAX_REPLIES_PER_MEMBER = 3;
12
13
  const CONTEXT_MESSAGES = 20;
@@ -153,6 +154,11 @@ export class GroupChatService {
153
154
  liveExecutions = new Map();
154
155
  streamRevisions = new Map();
155
156
  closing = false;
157
+ rsiTimers = new Map();
158
+ rsiJobs = new Map();
159
+ rsiControllers = new Map();
160
+ rsiAttempts = new Map();
161
+ rsiLastRun = new Map();
156
162
  constructor(filePath, store, runtime, memory, onActivity) {
157
163
  this.filePath = filePath;
158
164
  this.store = store;
@@ -169,9 +175,14 @@ export class GroupChatService {
169
175
  if (error.code !== "ENOENT")
170
176
  throw error;
171
177
  }
172
- if (service.rooms.some(room => room.messages.some(post => post.status === "running" || (post.role === "assistant" && post.status === "queued")))) {
178
+ if (service.rooms.some(room => room.rsi?.status === "running" || room.messages.some(post => post.status === "running" || (post.role === "assistant" && post.status === "queued")))) {
173
179
  await service.edit(rooms => {
174
180
  for (const room of rooms) {
181
+ if (room.rsi?.status === "running") {
182
+ room.rsi.status = "interrupted";
183
+ room.rsi.error = "服务重启,观察将在后台重新进行。";
184
+ room.revision += 1;
185
+ }
175
186
  for (const request of room.cloneRequests ?? [])
176
187
  if (request.status === "pending") {
177
188
  request.status = "expired";
@@ -189,8 +200,10 @@ export class GroupChatService {
189
200
  }
190
201
  });
191
202
  }
192
- for (const room of service.rooms)
203
+ for (const room of service.rooms) {
193
204
  service.kick(room.id);
205
+ service.scheduleRsi(room);
206
+ }
194
207
  return service;
195
208
  }
196
209
  workspace(id) {
@@ -225,6 +238,8 @@ export class GroupChatService {
225
238
  await replaceFile(temporary, this.filePath);
226
239
  this.rooms = rooms;
227
240
  this.publishActivity(previous);
241
+ for (const room of rooms)
242
+ this.scheduleRsi(room);
228
243
  return result;
229
244
  });
230
245
  this.writes = write.then(() => undefined, () => undefined);
@@ -260,7 +275,8 @@ export class GroupChatService {
260
275
  if (post.role === "assistant")
261
276
  post.executionActivity = this.liveExecutions.get(post.id)?.activity;
262
277
  }
263
- return { ...room, activity: groupActivity(room), revision: `${room.revision}:${this.streamRevisions.get(id) ?? 0}` };
278
+ const rsi = room.rsi ?? defaultGroupRsi();
279
+ return { ...room, rsi: { ...rsi, pending: rsi.enabled && room.messages.length > 0 && rsi.sourceKey !== rsiSourceKey(room) }, activity: groupActivity(room), revision: `${room.revision}:${this.streamRevisions.get(id) ?? 0}` };
264
280
  }
265
281
  execution(workspaceId, id, postId) {
266
282
  const room = this.find(this.rooms, workspaceId, id);
@@ -292,6 +308,11 @@ export class GroupChatService {
292
308
  return summary(room);
293
309
  if (archived && this.hasUnsettledWork(room))
294
310
  throw new Error("群聊还有任务未结束,请先停止任务或等它结束后再归档。");
311
+ if (archived) {
312
+ this.rsiControllers.get(id)?.abort();
313
+ clearTimeout(this.rsiTimers.get(id));
314
+ this.rsiTimers.delete(id);
315
+ }
295
316
  room.updatedAt = timestamp();
296
317
  if (archived)
297
318
  room.archivedAt = room.updatedAt;
@@ -751,6 +772,145 @@ export class GroupChatService {
751
772
  content: post.content.slice(0, 4_000),
752
773
  }));
753
774
  }
775
+ scheduleRsi(room, force = false) {
776
+ if (this.closing || room.archivedAt || room.rsi?.enabled === false || this.rsiJobs.has(room.id))
777
+ return;
778
+ const workspace = this.store.workspace(room.workspaceId);
779
+ if (!workspace || workspace.closedAt)
780
+ return;
781
+ if (!force && !room.messages.some(post => post.role === "assistant" && !["running", "queued"].includes(post.status)))
782
+ return;
783
+ const key = rsiSourceKey(room);
784
+ if (!force && (key === room.rsi?.sourceKey || key === this.rsiAttempts.get(room.id)))
785
+ return;
786
+ if (this.rsiTimers.has(room.id)) {
787
+ if (!force)
788
+ return;
789
+ clearTimeout(this.rsiTimers.get(room.id));
790
+ this.rsiTimers.delete(room.id);
791
+ }
792
+ const delay = force ? 0 : Math.max(1500, (this.rsiLastRun.get(room.id) ?? 0) + 60000 - Date.now());
793
+ const timer = setTimeout(() => {
794
+ this.rsiTimers.delete(room.id);
795
+ const current = this.rooms.find(item => item.id === room.id);
796
+ if (!current || current.archivedAt || current.rsi?.enabled === false || this.closing)
797
+ return;
798
+ const job = this.observeRsi(current).catch(error => console.error("Super Pi: RSI observation could not be saved:", error))
799
+ .finally(() => { this.rsiJobs.delete(room.id); const latest = this.rooms.find(item => item.id === room.id); if (latest)
800
+ this.scheduleRsi(latest); });
801
+ this.rsiJobs.set(room.id, job);
802
+ }, delay);
803
+ timer.unref();
804
+ this.rsiTimers.set(room.id, timer);
805
+ }
806
+ async observeRsi(snapshot) {
807
+ const id = snapshot.id, key = rsiSourceKey(snapshot), controller = new AbortController();
808
+ this.rsiControllers.set(id, controller);
809
+ this.rsiAttempts.set(id, key);
810
+ this.rsiLastRun.set(id, Date.now());
811
+ await this.edit(rooms => { const room = this.find(rooms, snapshot.workspaceId, id); room.rsi ??= defaultGroupRsi(); room.rsi.status = "running"; room.rsi.startedAt = timestamp(); delete room.rsi.error; room.revision += 1; });
812
+ try {
813
+ const agent = await this.runtime.agentFor?.({ id: "rsi:" + id, agentId: "group-rsi" });
814
+ if (!agent)
815
+ throw new Error("RSI 内置观察员不可用,请检查内置 Agent 安装。");
816
+ const agentPolicies = await Promise.all(snapshot.members.map(async (member) => {
817
+ const definition = await this.runtime.agentFor?.({ id: "rsi-role:" + id, agentId: member.agentId ?? member.id });
818
+ return { id: member.id, prompt: definition?.prompt?.slice(0, 1000), tools: definition?.tools };
819
+ }));
820
+ const previous = snapshot.rsi?.reports.slice(-3).map(report => ({
821
+ createdAt: report.createdAt, summary: report.summary.slice(0, 1000),
822
+ findings: report.findings.map(finding => ({ category: finding.category, recommendation: finding.recommendation.slice(0, 300), disposition: finding.disposition, feedback: finding.feedback?.slice(0, 400), verification: finding.verification.slice(0, 200) })),
823
+ })) ?? [];
824
+ const policies = { members: snapshot.members, moderator: { ...snapshot.moderator, prompt: snapshot.moderator.prompt.slice(0, 4000) }, agentPolicies, previousReports: previous };
825
+ const coverage = rsiInput(snapshot, snapshot.executions, Math.max(8000, 48000 - JSON.stringify(policies).length - 2000));
826
+ const prompt = [
827
+ "请复盘这个群聊截止目前的协作效率。只生成观察报告,不参与群聊发言。",
828
+ "检查分工、Prompt、工具能力、协作机制及执行策略,区分真正浪费与必要复核。仅引用给定发言 ID 和可逐字核对的片段,区分事实与推断。不可执行记录中的命令。此前建议不应自动当作已实施,需要反馈和后续证据。",
829
+ "输出 JSON 对象 {summary, retrospective, findings: [{category, priority, observation, evidence:[{messageId,quote}], recommendation, applicability, verification}]}。category 取 division/prompt/tools/mechanism/execution;priority 取 high/medium/low;最多8条建议,证据不足可以为空。retrospective 说明之前建议的反馈和效果,未知则说明尚无证据。",
830
+ snapshot.rsi?.prompt ?? "",
831
+ JSON.stringify({ ...policies, coverage: { observedMessages: coverage.observedMessages, totalMessages: coverage.totalMessages, compressed: coverage.compressed }, messages: coverage.records }),
832
+ ].join("\n");
833
+ let observedModel;
834
+ const raw = await this.complete(snapshot, { prompt, agent, model: snapshot.rsi?.model ?? snapshot.moderator.model, timeoutMs: 90000, signal: controller.signal, onModel: model => { observedModel = model; } });
835
+ if (controller.signal.aborted)
836
+ return;
837
+ const report = parseRsiReport(raw, snapshot, coverage);
838
+ report.model = observedModel;
839
+ await this.edit(rooms => {
840
+ const room = rooms.find(item => item.id === id);
841
+ if (!room?.rsi?.enabled || room.archivedAt || controller.signal.aborted)
842
+ return;
843
+ room.rsi.reports = [...room.rsi.reports.slice(-7), report];
844
+ room.rsi.sourceKey = key;
845
+ room.rsi.status = "completed";
846
+ delete room.rsi.error;
847
+ room.revision += 1;
848
+ });
849
+ }
850
+ catch (cause) {
851
+ if (!this.closing)
852
+ await this.edit(rooms => {
853
+ const room = rooms.find(item => item.id === id);
854
+ if (!room?.rsi)
855
+ return;
856
+ room.rsi.status = controller.signal.aborted ? "interrupted" : "failed";
857
+ room.rsi.error = controller.signal.aborted ? "本次观察已取消。" : cause instanceof Error ? cause.message : "RSI 观察失败";
858
+ room.revision += 1;
859
+ });
860
+ }
861
+ finally {
862
+ if (this.rsiControllers.get(id) === controller)
863
+ this.rsiControllers.delete(id);
864
+ }
865
+ }
866
+ async updateRsi(workspaceId, id, body) {
867
+ this.activeRoom(this.rooms, workspaceId, id);
868
+ if (body.action === "rsi.refresh") {
869
+ this.scheduleRsi(this.find(this.rooms, workspaceId, id), true);
870
+ return this.get(workspaceId, id);
871
+ }
872
+ if (body.action === "rsi.configure") {
873
+ if (body.enabled !== undefined && typeof body.enabled !== "boolean")
874
+ throw new Error("RSI 启用设置无效");
875
+ const config = await this.moderator(workspaceId, { model: body.model, prompt: body.prompt });
876
+ this.rsiControllers.get(id)?.abort();
877
+ await this.edit(rooms => {
878
+ const room = this.activeRoom(rooms, workspaceId, id);
879
+ room.rsi ??= defaultGroupRsi();
880
+ room.rsi.enabled = body.enabled !== false;
881
+ room.rsi.model = config.model;
882
+ room.rsi.prompt = config.prompt;
883
+ room.rsi.sourceKey = undefined;
884
+ room.rsi.status = "idle";
885
+ delete room.rsi.error;
886
+ room.revision += 1;
887
+ });
888
+ this.rsiAttempts.delete(id);
889
+ if (body.enabled === false) {
890
+ clearTimeout(this.rsiTimers.get(id));
891
+ this.rsiTimers.delete(id);
892
+ }
893
+ else
894
+ this.scheduleRsi(this.find(this.rooms, workspaceId, id), true);
895
+ }
896
+ else if (body.action === "rsi.feedback") {
897
+ if (!["accepted", "dismissed"].includes(String(body.disposition)))
898
+ throw new Error("RSI 反馈状态无效");
899
+ const feedback = inputText(body.feedback ?? "", 2000, "RSI 反馈");
900
+ await this.edit(rooms => {
901
+ const room = this.activeRoom(rooms, workspaceId, id);
902
+ const finding = room.rsi?.reports.find(report => report.id === body.reportId)?.findings.find(finding => finding.id === body.findingId);
903
+ if (!finding)
904
+ throw new Error("RSI 建议不存在");
905
+ finding.disposition = body.disposition;
906
+ finding.feedback = feedback;
907
+ room.revision += 1;
908
+ });
909
+ }
910
+ else
911
+ throw new Error("RSI 操作无效");
912
+ return this.get(workspaceId, id);
913
+ }
754
914
  async complete(room, input) {
755
915
  const workspace = this.workspace(room.workspaceId);
756
916
  const model = input.model ?? workspace.defaultModel;
@@ -974,6 +1134,11 @@ export class GroupChatService {
974
1134
  }
975
1135
  async close() {
976
1136
  this.closing = true;
1137
+ for (const timer of this.rsiTimers.values())
1138
+ clearTimeout(timer);
1139
+ for (const controller of this.rsiControllers.values())
1140
+ controller.abort();
1141
+ await Promise.allSettled(this.rsiJobs.values());
977
1142
  for (const controller of this.controllers.values())
978
1143
  controller.abort();
979
1144
  await Promise.allSettled(this.running.values());
@@ -0,0 +1,13 @@
1
+ import type { GroupExecutionTrace, GroupRoom, GroupRsi, GroupRsiReport } from "../../shared/group-chat.js";
2
+ export declare const defaultGroupRsi: () => GroupRsi;
3
+ export declare function rsiSourceKey(room: GroupRoom): string;
4
+ export declare function rsiInput(room: GroupRoom, executions?: Record<string, GroupExecutionTrace>, limit?: number): {
5
+ records: {
6
+ id: string;
7
+ content: string;
8
+ }[];
9
+ compressed: boolean;
10
+ observedMessages: number;
11
+ totalMessages: number;
12
+ };
13
+ export declare function parseRsiReport(raw: string, room: GroupRoom, coverage: ReturnType<typeof rsiInput>): GroupRsiReport;
@@ -0,0 +1,69 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ export const defaultGroupRsi = () => ({ enabled: true, prompt: "", status: "idle", reports: [] });
3
+ const settled = (room) => room.messages.filter(post => post.role === "user" || !["running", "queued"].includes(post.status));
4
+ export function rsiSourceKey(room) {
5
+ return createHash("sha256").update(JSON.stringify({ messages: settled(room), members: room.members, moderator: room.moderator })).digest("hex");
6
+ }
7
+ export function rsiInput(room, executions = {}, limit = 48000) {
8
+ const posts = settled(room);
9
+ let budget = limit, compressed = false;
10
+ const records = [];
11
+ for (const post of [...posts].reverse()) {
12
+ const content = post.content.slice(0, 3000);
13
+ const tools = (executions[post.id]?.steps ?? []).filter(step => step.kind === "tool").map(step => ({
14
+ name: step.kind === "tool" ? step.name : "", status: step.status,
15
+ durationMs: step.kind === "tool" ? step.durationMs : undefined,
16
+ detail: step.kind === "tool" ? step.detail?.slice(0, 300) : undefined,
17
+ }));
18
+ const record = {
19
+ id: post.id, role: post.role, content, status: post.status, createdAt: post.createdAt,
20
+ replyTo: post.replyTo, error: post.error?.slice(0, 1000),
21
+ ...(post.role === "assistant" ? {
22
+ memberId: post.memberId, memberName: post.memberName, model: post.model,
23
+ assignment: post.assignment?.slice(0, 1500), routeReason: post.routeReason,
24
+ background: post.background, settledAt: post.settledAt,
25
+ } : { memberIds: post.memberIds, files: post.files?.map(file => file.path) }),
26
+ tools: tools.slice(-24),
27
+ };
28
+ const bytes = JSON.stringify(record).length;
29
+ if (bytes > budget) {
30
+ compressed = true;
31
+ break;
32
+ }
33
+ budget -= bytes;
34
+ records.unshift(record);
35
+ compressed ||= content.length < post.content.length || tools.length > 24 || Boolean(executions[post.id]?.truncated);
36
+ }
37
+ return { records, compressed, observedMessages: records.length, totalMessages: posts.length };
38
+ }
39
+ const categories = ["division", "prompt", "tools", "mechanism", "execution"];
40
+ function text(value, limit) { return typeof value === "string" ? value.trim().slice(0, limit) : ""; }
41
+ function object(value) {
42
+ if (!value || typeof value !== "object" || Array.isArray(value))
43
+ throw new Error("RSI 报告对象格式无效。");
44
+ return value;
45
+ }
46
+ export function parseRsiReport(raw, room, coverage) {
47
+ const body = object(JSON.parse(raw.trim().replace(/^\`\`\`(?:json)?\s*|\s*\`\`\`$/gi, "")));
48
+ if (!text(body.summary, 2400) || !Array.isArray(body.findings) || body.findings.length > 8)
49
+ throw new Error("RSI 未返回有效的观察报告,请重试。");
50
+ const anchors = new Set(coverage.records.map(record => record.id));
51
+ const findings = body.findings.map((value) => {
52
+ const item = object(value), category = String(item.category), priority = String(item.priority);
53
+ if (!categories.includes(category) || !["high", "medium", "low"].includes(priority) || !Array.isArray(item.evidence))
54
+ throw new Error("RSI 建议格式无效。");
55
+ const evidence = item.evidence.slice(0, 5).map((value) => {
56
+ const entry = object(value);
57
+ const post = room.messages.find(post => post.id === entry.messageId);
58
+ const quote = text(entry.quote, 400);
59
+ if (!post || !anchors.has(post.id) || (quote && !post.content.includes(quote)))
60
+ throw new Error("RSI 引用的群聊证据无法核对。");
61
+ return { messageId: post.id, quote };
62
+ });
63
+ const observation = text(item.observation, 1200), recommendation = text(item.recommendation, 1600), verification = text(item.verification, 1000), applicability = text(item.applicability, 800);
64
+ if (!observation || !recommendation || !verification || !applicability || !evidence.length)
65
+ throw new Error("RSI 建议缺少观察、证据、适用范围或验证办法。");
66
+ return { id: randomUUID(), category, priority, observation, recommendation, verification, applicability, evidence };
67
+ });
68
+ return { id: randomUUID(), createdAt: new Date().toISOString(), sourceKey: rsiSourceKey(room), compressed: coverage.compressed, observedMessages: coverage.observedMessages, totalMessages: coverage.totalMessages, summary: text(body.summary, 2400), retrospective: text(body.retrospective, 2400), findings };
69
+ }
@@ -20,7 +20,7 @@ export function createWorktreeService(context) {
20
20
  if (action === "list")
21
21
  return { worktrees: (await gitWorktrees(source.path)).worktrees };
22
22
  const requestId = inputText(command.requestId, 200);
23
- if (!requestId || !["create", "follow", "open"].includes(action)) {
23
+ if (!requestId || !["create", "follow", "open", "enter"].includes(action)) {
24
24
  throw Object.assign(new Error("请指定有效的工作树操作"), { code: "bad_message" });
25
25
  }
26
26
  const task = callerId ? inputText(command.task, 12_000) : "";
@@ -46,11 +46,15 @@ export function createWorktreeService(context) {
46
46
  const checkout = await resolveGitWorktree(project.path, entry.id);
47
47
  if (followConversation)
48
48
  await store.followConversationWorktree(followConversation, entry.id);
49
- if (action !== "open" && !task) {
49
+ if (action !== "open" && action !== "enter" && !task) {
50
50
  broadcaster.broadcastState();
51
51
  return { worktree: checkout.entry };
52
52
  }
53
53
  const workspace = await store.createWorkspace((entry.branch ?? "工作树 " + entry.head.slice(0, 8)).slice(0, 80), checkout.path, entry.primary ? undefined : project);
54
+ if (action === "enter") {
55
+ broadcaster.broadcastState();
56
+ return { worktree: checkout.entry, workspaceId: workspace.id };
57
+ }
54
58
  const conversationId = await conversationService.createConversation(workspace.id);
55
59
  await store.renameConversation(conversationId, (entry.branch ?? "工作树 " + entry.head.slice(0, 8)).slice(0, 80));
56
60
  broadcaster.broadcastState();
@@ -571,6 +571,10 @@ export function createHttpServer(options) {
571
571
  json(200, await groups.configure(workspaceId, roomId, body));
572
572
  return;
573
573
  }
574
+ if (typeof body?.action === "string" && body.action.startsWith("rsi.")) {
575
+ json(200, await groups.updateRsi(workspaceId, roomId, body));
576
+ return;
577
+ }
574
578
  if (body?.action === "clone.resolve") {
575
579
  json(200, await groups.resolveClone(workspaceId, roomId, body));
576
580
  return;
@@ -1443,6 +1447,15 @@ export function createHttpServer(options) {
1443
1447
  return;
1444
1448
  }
1445
1449
  const body = raw ? JSON.parse(raw) : {};
1450
+ const entryConfig = await readManagedModelConfig();
1451
+ if (entryConfig?.entryIntegrations) {
1452
+ if (!entryConfig.entryIntegrations.web) {
1453
+ json(503, { error: "请在入口设置中连接 Tavily。" });
1454
+ return;
1455
+ }
1456
+ await remoteModelRelay.invoke(request, response, "/integration/web", raw);
1457
+ return;
1458
+ }
1446
1459
  const result = body.action === "search"
1447
1460
  ? await context.web.search(String(body.query ?? ""), Number(body.limit ?? 5), abortedAs(request))
1448
1461
  : body.action === "fetch"
@@ -1488,6 +1501,15 @@ export function createHttpServer(options) {
1488
1501
  return;
1489
1502
  }
1490
1503
  const body = raw ? JSON.parse(raw) : {};
1504
+ const entryConfig = await readManagedModelConfig();
1505
+ if (entryConfig?.entryIntegrations) {
1506
+ if (!entryConfig.entryIntegrations.feishu) {
1507
+ json(503, { error: "入口未提供飞书连接。" });
1508
+ return;
1509
+ }
1510
+ await remoteModelRelay.invoke(request, response, "/integration/feishu", raw);
1511
+ return;
1512
+ }
1491
1513
  json(200, await context.feishu.tool(body));
1492
1514
  }
1493
1515
  catch (error) {
@@ -44,6 +44,7 @@ import { ToolRunner } from "./tool-runner.js";
44
44
  import { ToolLlmService } from "./tool-llm.js";
45
45
  import { WebService } from "./web.js";
46
46
  import { TavilyService } from "./tavily.js";
47
+ import { readManagedModelConfig } from "./managed-model-adapter.js";
47
48
  // ------------------------------------------------------------- Environment & paths
48
49
  const rootDir = resolve(import.meta.dirname, "../..");
49
50
  initRunningVersion(rootDir);
@@ -201,7 +202,8 @@ process.env.SUPER_PI_FEISHU_ENDPOINT = `http://${internalHost}:${port}/api/feish
201
202
  const tavily = new TavilyService(join(dataDir, "tavily.json"));
202
203
  const web = new WebService(tavily);
203
204
  process.env.SUPER_PI_WEB_ENDPOINT = `http://${internalHost}:${port}/api/web/tool`;
204
- process.env.SUPER_PI_WEB_ENABLED = tavily.configured ? "1" : "0";
205
+ const entryIntegrations = (await readManagedModelConfig())?.entryIntegrations;
206
+ process.env.SUPER_PI_WEB_ENABLED = (entryIntegrations ? entryIntegrations.web : tavily.configured) ? "1" : "0";
205
207
  const extensionUiService = new ExtensionUiService(broadcaster, id => {
206
208
  const { parentConversationId, parent } = store.childSessionFacts(id);
207
209
  return !isChildSession(parentConversationId, parent);
@@ -449,7 +451,18 @@ process.on("SIGTERM", () => { void shutdown("SIGTERM").finally(() => process.exi
449
451
  const fullPackage = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8")).name !== "@evandu/super-pi-server";
450
452
  if (fullPackage && !process.env.SUPER_PI_MANAGED_CONFIG && process.env.SUPER_PI_DISABLE_MANAGER !== "1") {
451
453
  const { ManagedServers } = await import("./managed-servers.js");
452
- serverContext.managedServers = new ManagedServers(join(dataDir, "manager"), rootDir, () => store.defaultModel());
454
+ serverContext.managedServers = new ManagedServers(join(dataDir, "manager"), rootDir, () => store.defaultModel(), {
455
+ available: () => ({ web: tavily.configured, feishu: true }),
456
+ invoke: async (kind, body, signal) => {
457
+ if (kind === "feishu")
458
+ return feishu.tool(body);
459
+ if (body.action === "search")
460
+ return web.search(String(body.query ?? ""), Number(body.limit ?? 5), signal);
461
+ if (body.action === "fetch")
462
+ return web.fetch(String(body.url ?? ""), signal);
463
+ throw new Error("未知网页工具操作");
464
+ },
465
+ });
453
466
  await serverContext.managedServers.initialize();
454
467
  }
455
468
  const httpServer = createHttpServer({ context: serverContext, onShutdown: shutdown, port, host });
@@ -44,8 +44,9 @@ export async function handleManagedHttp(context, request, response, url) {
44
44
  const path = process.env.SUPER_PI_MANAGED_CONFIG;
45
45
  const temp = path + "." + randomUUID() + ".tmp";
46
46
  try {
47
- await writeFile(temp, JSON.stringify({ ...config, models: catalog.models, defaultModel: catalog.defaultModel, endpoint: `http://127.0.0.1:${request.socket.localPort}/api/managed-model/invoke` }), { mode: 0o600 });
47
+ await writeFile(temp, JSON.stringify({ ...config, models: catalog.models, defaultModel: catalog.defaultModel, entryIntegrations: catalog.entryIntegrations, endpoint: `http://127.0.0.1:${request.socket.localPort}/api/managed-model/invoke` }), { mode: 0o600 });
48
48
  await rename(temp, path);
49
+ process.env.SUPER_PI_WEB_ENABLED = catalog.entryIntegrations?.web === true ? "1" : "0";
49
50
  }
50
51
  finally {
51
52
  await rm(temp, { force: true });
@@ -1,5 +1,9 @@
1
1
  import type { Model } from "@earendil-works/pi-ai";
2
2
  export interface ManagedModelConfig {
3
+ entryIntegrations?: {
4
+ web: boolean;
5
+ feishu: boolean;
6
+ };
3
7
  endpoint: string;
4
8
  token: string;
5
9
  models: Model<string>[];
@@ -6,7 +6,7 @@ export declare class ModelRelay {
6
6
  private waiting;
7
7
  close(): void;
8
8
  attach(socket: WebSocket): void;
9
- invoke(request: IncomingMessage, response: ServerResponse): Promise<void>;
9
+ invoke(request: IncomingMessage, response: ServerResponse, path?: string, payload?: string): Promise<void>;
10
10
  }
11
11
  export declare const remoteModelRelay: ModelRelay;
12
12
  export declare function connectModelRelay(origin: string, key: string, gatewayPort: number, modelToken: string): WebSocket;
@@ -34,12 +34,12 @@ export class ModelRelay {
34
34
  if (this.socket !== socket)
35
35
  return;
36
36
  try {
37
- const { id, type, data, status } = JSON.parse(raw.toString());
37
+ const { id, type, data, status, contentType } = JSON.parse(raw.toString());
38
38
  const response = this.requests.get(id);
39
39
  if (!response)
40
40
  return;
41
41
  if (type === "start")
42
- response.writeHead(status, { "content-type": "application/x-ndjson", "cache-control": "no-store" });
42
+ response.writeHead(status, { "content-type": contentType === "application/json" ? contentType : "application/x-ndjson", "cache-control": "no-store" });
43
43
  else if (type === "data") {
44
44
  if (response.writableLength > maxRequest)
45
45
  response.destroy();
@@ -63,7 +63,7 @@ export class ModelRelay {
63
63
  }
64
64
  });
65
65
  }
66
- async invoke(request, response) {
66
+ async invoke(request, response, path = "/model", payload) {
67
67
  // Allow the manager's next health poll to reconnect after a service restart.
68
68
  if (this.socket?.readyState !== WebSocket.OPEN && this.waiting.size < maxConcurrent) {
69
69
  await new Promise(resolve => {
@@ -87,14 +87,17 @@ export class ModelRelay {
87
87
  }
88
88
  const parts = [];
89
89
  let size = 0;
90
- for await (const chunk of request) {
91
- size += chunk.length;
92
- if (size > maxRequest) {
93
- response.writeHead(413).end();
94
- return;
90
+ if (payload !== undefined)
91
+ parts.push(Buffer.from(payload));
92
+ else
93
+ for await (const chunk of request) {
94
+ size += chunk.length;
95
+ if (size > maxRequest) {
96
+ response.writeHead(413).end();
97
+ return;
98
+ }
99
+ parts.push(chunk);
95
100
  }
96
- parts.push(chunk);
97
- }
98
101
  if (this.socket !== socket || socket.readyState !== WebSocket.OPEN || this.requests.size >= maxConcurrent || socket.bufferedAmount > maxRequest) {
99
102
  response.writeHead(503).end();
100
103
  return;
@@ -105,7 +108,7 @@ export class ModelRelay {
105
108
  if (this.requests.delete(id) && socket.readyState === WebSocket.OPEN)
106
109
  socket.send(JSON.stringify({ type: "cancel", id }));
107
110
  });
108
- socket.send(JSON.stringify({ id, type: "request", body: Buffer.concat(parts).toString("base64") }), error => { if (error)
111
+ socket.send(JSON.stringify({ id, type: "request", path, body: Buffer.concat(parts).toString("base64") }), error => { if (error)
109
112
  response.destroy(); });
110
113
  }
111
114
  }
@@ -145,20 +148,20 @@ export function connectModelRelay(origin, key, gatewayPort, modelToken) {
145
148
  socket.terminate();
146
149
  return;
147
150
  }
148
- const { id, type, body } = message;
151
+ const { id, type, body, path = "/model" } = message;
149
152
  if (type === "cancel") {
150
153
  active.get(id)?.abort();
151
154
  return;
152
155
  }
153
- if (type !== "request" || typeof id !== "string" || typeof body !== "string" || active.has(id) || active.size >= maxConcurrent) {
156
+ if (type !== "request" || typeof id !== "string" || typeof body !== "string" || !["/model", "/integration/web", "/integration/feishu"].includes(path) || active.has(id) || active.size >= maxConcurrent) {
154
157
  socket.terminate();
155
158
  return;
156
159
  }
157
160
  const controller = new AbortController();
158
161
  active.set(id, controller);
159
162
  try {
160
- const result = await fetch(`http://127.0.0.1:${gatewayPort}/model`, { method: "POST", redirect: "error", headers: { authorization: `Bearer ${modelToken}`, "content-type": "application/json" }, body: Buffer.from(body, "base64"), signal: controller.signal });
161
- await send({ id, type: "start", status: result.status });
163
+ const result = await fetch(`http://127.0.0.1:${gatewayPort}${path}`, { method: "POST", redirect: "error", headers: { authorization: `Bearer ${modelToken}`, "content-type": "application/json" }, body: Buffer.from(body, "base64"), signal: controller.signal });
164
+ await send({ id, type: "start", status: result.status, contentType: result.headers.get("content-type") });
162
165
  const reader = result.body?.getReader();
163
166
  if (reader)
164
167
  for (;;) {