@evandu/super-pi 0.1.273 → 0.1.275

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 (97) hide show
  1. package/agents/group-rsi.md +18 -0
  2. package/agents/super-pi-documents/index.ts +16 -1
  3. package/agents/super-pi-task/core.ts +8 -8
  4. package/bin/completion.js +19 -5
  5. package/bin/render-presentation.ps1 +35 -0
  6. package/bin/super-pi.js +3 -0
  7. package/desktop/main.cjs +16 -9
  8. package/desktop/notifications.cjs +2 -1
  9. package/desktop/relaunch.cjs +5 -2
  10. package/desktop/restart-handoff.cjs +35 -0
  11. package/desktop/runtime.cjs +28 -4
  12. package/dist/client/.super-pi-client-sources.json +34 -19
  13. package/dist/client/assets/CodeMirrorEditor-DJgZdigq.js +2 -0
  14. package/dist/client/assets/{GitDiffEditor-CpoDDQrA.css → GitDiffEditor-DIRyUxnb.css} +1 -1
  15. package/dist/client/assets/GitDiffEditor-lOnvlR42.js +29 -0
  16. package/dist/client/assets/{dist-DGBjhKI9.js → dist-AW5lyI3I.js} +1 -1
  17. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  18. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  19. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  20. package/dist/client/assets/{dist-BvjUKkwy.js → dist-BRVQKlcp.js} +1 -1
  21. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  22. package/dist/client/assets/{dist-BlRuQIg1.js → dist-BXAOrsjq.js} +1 -1
  23. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  24. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  25. package/dist/client/assets/{dist-i79xiXVk.js → dist-Cus6_oaF.js} +2 -2
  26. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  27. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  28. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  29. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  30. package/dist/client/assets/dist-DeD9copn.js +1 -0
  31. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  32. package/dist/client/assets/{dist-D5u1uPmZ.js → dist-Dvb0SqcK.js} +2 -2
  33. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  34. package/dist/client/assets/{dist-CQncCwUc.js → dist-QzbOCAU6.js} +1 -1
  35. package/dist/client/assets/{dist-DjI7p99D.js → dist-moiMRpw_.js} +1 -1
  36. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  37. package/dist/client/assets/index-BWm699nV.js +350 -0
  38. package/dist/client/assets/index-CnNljc5p.css +1 -0
  39. package/dist/client/index.html +2 -2
  40. package/dist/server/agents.d.ts +1 -1
  41. package/dist/server/agents.js +10 -3
  42. package/dist/server/application/conversation-service.d.ts +1 -1
  43. package/dist/server/application/conversation-service.js +3 -2
  44. package/dist/server/application/document-service.d.ts +134 -0
  45. package/dist/server/application/document-service.js +9 -0
  46. package/dist/server/application/group-chat-service.d.ts +17 -0
  47. package/dist/server/application/group-chat-service.js +168 -3
  48. package/dist/server/application/group-rsi.d.ts +13 -0
  49. package/dist/server/application/group-rsi.js +69 -0
  50. package/dist/server/application/worktree-service.js +6 -2
  51. package/dist/server/http-server.js +54 -3
  52. package/dist/server/index.js +15 -2
  53. package/dist/server/managed-http.js +2 -1
  54. package/dist/server/managed-model-adapter.d.ts +4 -0
  55. package/dist/server/managed-model-relay.d.ts +1 -1
  56. package/dist/server/managed-model-relay.js +18 -15
  57. package/dist/server/managed-servers.d.ts +10 -1
  58. package/dist/server/managed-servers.js +63 -4
  59. package/dist/server/presentations/brief.d.ts +49 -0
  60. package/dist/server/presentations/brief.js +132 -0
  61. package/dist/server/presentations/inspect.d.ts +15 -0
  62. package/dist/server/presentations/inspect.js +30 -0
  63. package/dist/server/presentations/native.d.ts +8 -0
  64. package/dist/server/presentations/native.js +33 -0
  65. package/dist/server/presentations/render.d.ts +16 -0
  66. package/dist/server/presentations/render.js +152 -0
  67. package/dist/server/presentations/service.d.ts +176 -0
  68. package/dist/server/presentations/service.js +155 -0
  69. package/dist/server/remote-bootstrap.d.ts +11 -0
  70. package/dist/server/remote-bootstrap.js +105 -29
  71. package/dist/server/runtime.js +3 -2
  72. package/dist/shared/group-chat.d.ts +40 -0
  73. package/dist/shared/message-source-link.d.ts +1 -0
  74. package/dist/shared/message-source-link.js +4 -0
  75. package/dist/shared/workspace-file-preview.d.ts +1 -1
  76. package/dist/shared/workspace-file-preview.js +2 -0
  77. package/package.json +5 -1
  78. package/skills/presentation/SKILL.md +23 -1
  79. package/skills/presentation/references/spec.md +15 -0
  80. package/dist/client/assets/CodeMirrorEditor-D8MjtASz.js +0 -2
  81. package/dist/client/assets/GitDiffEditor-DFJmhUHc.js +0 -29
  82. package/dist/client/assets/dist-3qQVP6l8.js +0 -6
  83. package/dist/client/assets/dist-CZ4PyxQu.js +0 -9
  84. package/dist/client/assets/dist-CfTFp0AF.js +0 -2
  85. package/dist/client/assets/dist-CxmJXjJI.js +0 -1
  86. package/dist/client/assets/dist-D8HpMxmZ.js +0 -1
  87. package/dist/client/assets/dist-DRBIy9A1.js +0 -1
  88. package/dist/client/assets/dist-Dcww9FSw.js +0 -1
  89. package/dist/client/assets/dist-DlPa5gNa.js +0 -7
  90. package/dist/client/assets/dist-DxPJ1PN-.js +0 -1
  91. package/dist/client/assets/dist-HXD8sSA4.js +0 -23
  92. package/dist/client/assets/dist-LbeLCeoq.js +0 -1
  93. package/dist/client/assets/dist-ONdtnupI.js +0 -1
  94. package/dist/client/assets/dist-YqmXusLA.js +0 -11
  95. package/dist/client/assets/dist-ZAR1Tu2c.js +0 -3
  96. package/dist/client/assets/index-Bqutm6qV.js +0 -350
  97. 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-BWm699nV.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-CnNljc5p.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -38,7 +38,7 @@ type Frontmatter = Record<string, unknown>;
38
38
  */
39
39
  export declare const PI_TOOL_NAMES: readonly ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls", "codemode", "tool_search", "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"];
40
40
  /** Tools shipped by this package. Authors must be able to explicitly deny host extras. */
41
- export declare const SUPER_PI_TOOL_NAMES: readonly ["task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove", "memory", "skill_manage", "session_search", "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder", "knowledge_search", "knowledge_import", "document_read", "document_write", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write"];
41
+ export declare const SUPER_PI_TOOL_NAMES: readonly ["task", "todowrite", "workflow", "run_async", "worktree", "scheduled_task", "project", "question", "tool_register", "tool_shortcut", "tool_remove", "memory", "skill_manage", "session_search", "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder", "knowledge_search", "knowledge_import", "document_read", "document_write", "presentation_create", "presentation_read", "presentation_edit", "presentation_render", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write"];
42
42
  /**
43
43
  * Whether a name can be a real Pi tool. A name is real if it is one of `PI_TOOL_NAMES`, an MCP
44
44
  * server tool, or a PATTERN.
@@ -43,7 +43,7 @@ export const SUPER_PI_TOOL_NAMES = [
43
43
  "memory", "skill_manage", "session_search",
44
44
  "session_spawn", "session_status", "session_dispatch", "session_stop", "session_report", "session_stop_subtree", "session_remove", "session_reminder",
45
45
  "knowledge_search", "knowledge_import",
46
- "document_read", "document_write", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write",
46
+ "document_read", "document_write", "presentation_create", "presentation_read", "presentation_edit", "presentation_render", "web_search", "web_fetch", "feishu_doc_read", "feishu_doc_write",
47
47
  ];
48
48
  const KNOWN_TOOL_NAMES = [...PI_TOOL_NAMES, ...SUPER_PI_TOOL_NAMES];
49
49
  const PI_TOOL_NAME_SET = new Set(KNOWN_TOOL_NAMES);
@@ -249,6 +249,13 @@ function unquote(value) {
249
249
  return value.slice(1, -1);
250
250
  return value;
251
251
  }
252
+ /** New artifact writers must not widen an existing read-only or document-write-denied role. */
253
+ function presentationWriteDenials(tools, options) {
254
+ if (!tools || typeof tools !== "object")
255
+ return [];
256
+ const readOnly = tools["*"] === false && !["write", "edit", "bash", "powershell", "document_write"].some(name => tools[name] === true);
257
+ return ["presentation_create", "presentation_edit"].filter(name => options.extraAllowedTools?.includes(name) && tools[name] !== true && (tools.document_write === false || readOnly));
258
+ }
252
259
  /**
253
260
  * The Pi CLI flags an agent's `tools` map becomes. Returned flat so the caller can push them into the
254
261
  * spawn argv in order, and so a test can assert on the exact list.
@@ -268,7 +275,7 @@ function unquote(value) {
268
275
  * see a schema for it. Naming a tool on the allowlist also activates it (agent-session.ts:3569-3574).
269
276
  */
270
277
  export function toolFlags(tools, options = {}) {
271
- const denied = new Set((options.denyTools ?? []).filter((name) => name !== ""));
278
+ const denied = new Set([...(options.denyTools ?? []), ...presentationWriteDenials(tools, options)].filter((name) => name !== ""));
272
279
  // An agent with no `tools:` map runs on Pi's own default set, so there is nothing to translate - but a
273
280
  // DENY inherited from a parent still has to become an explicit exclusion, because there is no allowlist
274
281
  // here to drop the name from.
@@ -330,7 +337,7 @@ export function deniesAllTools(tools) {
330
337
  * do for every shape of `tools:` map.
331
338
  */
332
339
  export function toolSelection(tools, options = {}) {
333
- const denied = new Set((options.denyTools ?? []).filter((name) => name !== ""));
340
+ const denied = new Set([...(options.denyTools ?? []), ...presentationWriteDenials(tools, options)].filter((name) => name !== ""));
334
341
  // No map at all is Pi's own default set. An inherited deny still has to become an exclusion, because
335
342
  // there is no allowlist here to drop the name from.
336
343
  if (!tools || typeof tools !== "object") {
@@ -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);
@@ -22,6 +22,140 @@ export declare const MAX_DOCUMENT_REQUEST_BYTES: number;
22
22
  export declare class DocumentService {
23
23
  private readonly store;
24
24
  constructor(store: Store);
25
+ presentation(conversationId: string, body: Record<string, unknown>): Promise<{
26
+ version: 1;
27
+ etag: string;
28
+ operation: string;
29
+ sourceHash: string;
30
+ title: string;
31
+ verification: "layout-only" | "native-office";
32
+ renderer: string;
33
+ nativeReason?: string;
34
+ inspection: Awaited<ReturnType<typeof import("../presentations/inspect.js").inspectPptx>>;
35
+ contactSheets: {
36
+ asset: string;
37
+ hash: string;
38
+ }[];
39
+ warnings: {
40
+ slideId: string;
41
+ elementId: string;
42
+ message: string;
43
+ }[];
44
+ baseline?: {
45
+ path: string;
46
+ etag: string;
47
+ };
48
+ slides: {
49
+ id: string;
50
+ title: string;
51
+ notes: string;
52
+ asset: string;
53
+ hash: string;
54
+ }[];
55
+ source: import("../presentations/brief.js").PresentationSource;
56
+ path: string;
57
+ contactSheetPaths: string[];
58
+ link: string;
59
+ } | {
60
+ version: 1;
61
+ etag: string;
62
+ operation: string;
63
+ sourceHash: string;
64
+ title: string;
65
+ verification: "layout-only" | "native-office";
66
+ renderer: string;
67
+ nativeReason?: string;
68
+ inspection: Awaited<ReturnType<typeof import("../presentations/inspect.js").inspectPptx>>;
69
+ contactSheets: {
70
+ asset: string;
71
+ hash: string;
72
+ }[];
73
+ slides: {
74
+ id: string;
75
+ title: string;
76
+ notes: string;
77
+ asset: string;
78
+ hash: string;
79
+ }[];
80
+ warnings: {
81
+ slideId: string;
82
+ elementId: string;
83
+ message: string;
84
+ }[];
85
+ baseline?: {
86
+ path: string;
87
+ etag: string;
88
+ };
89
+ path: string;
90
+ contactSheetPaths: string[];
91
+ reused: boolean;
92
+ link: string;
93
+ } | {
94
+ version: 1;
95
+ etag: string;
96
+ operation: string;
97
+ sourceHash: string;
98
+ title: string;
99
+ verification: "layout-only" | "native-office";
100
+ renderer: string;
101
+ nativeReason?: string;
102
+ inspection: Awaited<ReturnType<typeof import("../presentations/inspect.js").inspectPptx>>;
103
+ contactSheets: {
104
+ asset: string;
105
+ hash: string;
106
+ }[];
107
+ slides: {
108
+ id: string;
109
+ title: string;
110
+ notes: string;
111
+ asset: string;
112
+ hash: string;
113
+ }[];
114
+ warnings: {
115
+ slideId: string;
116
+ elementId: string;
117
+ message: string;
118
+ }[];
119
+ baseline?: {
120
+ path: string;
121
+ etag: string;
122
+ };
123
+ path: string;
124
+ bytes: number;
125
+ contactSheetPaths: string[];
126
+ link: string;
127
+ } | {
128
+ path: string;
129
+ etag: string;
130
+ verification: "layout-only" | "native-office";
131
+ renderer: string;
132
+ nativeReason: string | undefined;
133
+ inspection: {
134
+ slides: number;
135
+ notes: number;
136
+ nativeCharts: number;
137
+ nativeTables: number;
138
+ editableTextShapes: number;
139
+ embeddedWorkbooks: number;
140
+ canvasInches: {
141
+ width: number;
142
+ height: number;
143
+ } | undefined;
144
+ relationships: string;
145
+ verification: string;
146
+ };
147
+ warnings: {
148
+ slideId: string;
149
+ elementId: string;
150
+ message: string;
151
+ }[];
152
+ sheet: number;
153
+ totalSheets: number;
154
+ images: {
155
+ mimeType: string;
156
+ data: string;
157
+ }[];
158
+ }>;
25
159
  /**
26
160
  * The workspace a conversation works in, taken from the store.
27
161
  *
@@ -2,6 +2,8 @@ import { mkdir, stat, writeFile } from "node:fs/promises";
2
2
  import { dirname, extname } from "node:path";
3
3
  import { buildDocument, documentFormatOf, DocumentError, extractText } from "../documents.js";
4
4
  import { fileEtag, resolveInsideRoot } from "../files.js";
5
+ import { resolveFileCwd } from "../session-cwd.js";
6
+ import { presentationTool } from "../presentations/service.js";
5
7
  /**
6
8
  * The largest request the document endpoint accepts.
7
9
  *
@@ -26,6 +28,13 @@ export class DocumentService {
26
28
  constructor(store) {
27
29
  this.store = store;
28
30
  }
31
+ async presentation(conversationId, body) {
32
+ const conversation = this.store.snapshot().conversations.find(item => item.id === conversationId);
33
+ if (!conversation?.workspaceId)
34
+ throw new Error("会话或工作区不存在");
35
+ const root = await resolveFileCwd(this.workspacePath(conversationId), conversation.cwd ?? "");
36
+ return presentationTool(root, body);
37
+ }
29
38
  /**
30
39
  * The workspace a conversation works in, taken from the store.
31
40
  *
@@ -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();