@evandu/super-pi-server 0.0.0-stage → 0.1.260
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/README.md +250 -3
- package/agents/code-auditor.md +64 -0
- package/agents/code-designer.md +64 -0
- package/agents/coder.md +24 -0
- package/agents/critic.md +24 -0
- package/agents/document-organizer.md +48 -0
- package/agents/patcher.md +27 -0
- package/agents/planner.md +30 -0
- package/agents/project-leader.md +28 -0
- package/agents/reviewer.md +27 -0
- package/agents/scout.md +27 -0
- package/agents/solution-designer.md +62 -0
- package/agents/super-pi-documents/index.ts +92 -0
- package/agents/super-pi-feishu/index.ts +88 -0
- package/agents/super-pi-knowledge/index.ts +70 -0
- package/agents/super-pi-managed-model/index.ts +9 -0
- package/agents/super-pi-memory/index.ts +75 -0
- package/agents/super-pi-native-tools/index.ts +1 -0
- package/agents/super-pi-task/core.ts +2262 -0
- package/agents/super-pi-task/index.ts +814 -0
- package/agents/super-pi-task/workflow-schema.ts +34 -0
- package/agents/super-pi-web/index.ts +32 -0
- package/agents/verifier.md +25 -0
- package/assets/fonts/LICENSE +92 -0
- package/assets/fonts/NotoSansSC-Bold.otf +0 -0
- package/assets/fonts/NotoSansSC-Regular.otf +0 -0
- package/assets/knowledge-model/README.md +37 -0
- package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
- package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
- package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
- package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
- package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
- package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
- package/bin/npm-prefix.d.ts +1 -0
- package/bin/npm-prefix.js +10 -0
- package/bin/super-pi.js +349 -0
- package/dist/client/.super-pi-client-sources.json +82 -0
- package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
- package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
- package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
- package/dist/client/assets/diff-ChtP43wD.js +1 -0
- package/dist/client/assets/dist-AW5lyI3I.js +1 -0
- package/dist/client/assets/dist-B3-a6uF0.js +7 -0
- package/dist/client/assets/dist-BGxkyh6e.js +1 -0
- package/dist/client/assets/dist-BJxfd7yb.js +11 -0
- package/dist/client/assets/dist-BRVQKlcp.js +1 -0
- package/dist/client/assets/dist-BV64A9Ji.js +1 -0
- package/dist/client/assets/dist-BXAOrsjq.js +1 -0
- package/dist/client/assets/dist-CKF2Jksy.js +1 -0
- package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
- package/dist/client/assets/dist-Cus6_oaF.js +2 -0
- package/dist/client/assets/dist-Cx00EZKR.js +23 -0
- package/dist/client/assets/dist-D71y2EI1.js +1 -0
- package/dist/client/assets/dist-D978o95T.js +5 -0
- package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
- package/dist/client/assets/dist-Dds-qLxY.js +9 -0
- package/dist/client/assets/dist-DeD9copn.js +1 -0
- package/dist/client/assets/dist-DuvGReu-.js +6 -0
- package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
- package/dist/client/assets/dist-J6XWqRpB.js +3 -0
- package/dist/client/assets/dist-QzbOCAU6.js +1 -0
- package/dist/client/assets/dist-moiMRpw_.js +1 -0
- package/dist/client/assets/dist-scBkrwv-.js +2 -0
- package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
- package/dist/client/assets/index-Cn7hdrDw.js +350 -0
- package/dist/client/assets/index-UfzqdECL.css +1 -0
- package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
- package/dist/client/assets/properties-C357ku5U.js +1 -0
- package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
- package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
- package/dist/client/assets/shell-DwuoZtxw.js +1 -0
- package/dist/client/assets/swift-DKB6_1j6.js +1 -0
- package/dist/client/assets/toml-BPTmHmyx.js +1 -0
- package/dist/client/favicon.ico +0 -0
- package/dist/client/favicon.png +0 -0
- package/dist/client/favicon.svg +10 -0
- package/dist/client/index.html +18 -0
- package/dist/extension.d.ts +15 -0
- package/dist/extension.js +126 -0
- package/dist/server/active-memory.d.ts +247 -0
- package/dist/server/active-memory.js +669 -0
- package/dist/server/agents.d.ts +245 -0
- package/dist/server/agents.js +701 -0
- package/dist/server/application/catalog-service.d.ts +98 -0
- package/dist/server/application/catalog-service.js +245 -0
- package/dist/server/application/conversation-service.d.ts +245 -0
- package/dist/server/application/conversation-service.js +654 -0
- package/dist/server/application/document-service.d.ts +68 -0
- package/dist/server/application/document-service.js +120 -0
- package/dist/server/application/extension-ui-service.d.ts +44 -0
- package/dist/server/application/extension-ui-service.js +135 -0
- package/dist/server/application/feishu-service.d.ts +179 -0
- package/dist/server/application/feishu-service.js +358 -0
- package/dist/server/application/group-chat-service.d.ts +75 -0
- package/dist/server/application/group-chat-service.js +953 -0
- package/dist/server/application/group-execution.d.ts +15 -0
- package/dist/server/application/group-execution.js +77 -0
- package/dist/server/application/project-service.d.ts +464 -0
- package/dist/server/application/project-service.js +2523 -0
- package/dist/server/application/provider-service.d.ts +174 -0
- package/dist/server/application/provider-service.js +510 -0
- package/dist/server/application/run-service.d.ts +547 -0
- package/dist/server/application/run-service.js +2683 -0
- package/dist/server/application/scheduled-task-service.d.ts +184 -0
- package/dist/server/application/scheduled-task-service.js +391 -0
- package/dist/server/application/session-orchestrator-service.d.ts +388 -0
- package/dist/server/application/session-orchestrator-service.js +1146 -0
- package/dist/server/application/session-reminder-service.d.ts +59 -0
- package/dist/server/application/session-reminder-service.js +141 -0
- package/dist/server/application/session-watchdog.d.ts +171 -0
- package/dist/server/application/session-watchdog.js +284 -0
- package/dist/server/application/workspace-service.d.ts +52 -0
- package/dist/server/application/workspace-service.js +186 -0
- package/dist/server/application/worktree-service.d.ts +13 -0
- package/dist/server/application/worktree-service.js +76 -0
- package/dist/server/browser-access.d.ts +34 -0
- package/dist/server/browser-access.js +89 -0
- package/dist/server/capability.d.ts +105 -0
- package/dist/server/capability.js +170 -0
- package/dist/server/command-handler.d.ts +93 -0
- package/dist/server/command-handler.js +540 -0
- package/dist/server/content-search.d.ts +16 -0
- package/dist/server/content-search.js +235 -0
- package/dist/server/conversation-usage.d.ts +22 -0
- package/dist/server/conversation-usage.js +43 -0
- package/dist/server/documents.d.ts +152 -0
- package/dist/server/documents.js +998 -0
- package/dist/server/engineering-learning.d.ts +30 -0
- package/dist/server/engineering-learning.js +106 -0
- package/dist/server/exec-service.d.ts +45 -0
- package/dist/server/exec-service.js +167 -0
- package/dist/server/explicit-file-open.d.ts +34 -0
- package/dist/server/explicit-file-open.js +105 -0
- package/dist/server/failure-text.d.ts +18 -0
- package/dist/server/failure-text.js +44 -0
- package/dist/server/feishu-cli.d.ts +223 -0
- package/dist/server/feishu-cli.js +464 -0
- package/dist/server/file-changes.d.ts +119 -0
- package/dist/server/file-changes.js +280 -0
- package/dist/server/file-diff.d.ts +41 -0
- package/dist/server/file-diff.js +97 -0
- package/dist/server/file-index.d.ts +100 -0
- package/dist/server/file-index.js +296 -0
- package/dist/server/file-name-index.d.ts +160 -0
- package/dist/server/file-name-index.js +411 -0
- package/dist/server/files.d.ts +269 -0
- package/dist/server/files.js +748 -0
- package/dist/server/git.d.ts +245 -0
- package/dist/server/git.js +903 -0
- package/dist/server/http-server.d.ts +45 -0
- package/dist/server/http-server.js +3830 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +485 -0
- package/dist/server/inline-thinking.d.ts +90 -0
- package/dist/server/inline-thinking.js +181 -0
- package/dist/server/json-comments.d.ts +14 -0
- package/dist/server/json-comments.js +71 -0
- package/dist/server/knowledge-embedding-worker.d.ts +1 -0
- package/dist/server/knowledge-embedding-worker.js +27 -0
- package/dist/server/knowledge-vectors.d.ts +150 -0
- package/dist/server/knowledge-vectors.js +385 -0
- package/dist/server/knowledge.d.ts +273 -0
- package/dist/server/knowledge.js +848 -0
- package/dist/server/length-continuation.d.ts +83 -0
- package/dist/server/length-continuation.js +118 -0
- package/dist/server/logging.d.ts +32 -0
- package/dist/server/logging.js +185 -0
- package/dist/server/managed-http-tunnel.d.ts +6 -0
- package/dist/server/managed-http-tunnel.js +85 -0
- package/dist/server/managed-http.d.ts +4 -0
- package/dist/server/managed-http.js +85 -0
- package/dist/server/managed-model-adapter.d.ts +17 -0
- package/dist/server/managed-model-adapter.js +75 -0
- package/dist/server/managed-model-gateway.d.ts +49 -0
- package/dist/server/managed-model-gateway.js +73 -0
- package/dist/server/managed-servers.d.ts +55 -0
- package/dist/server/managed-servers.js +396 -0
- package/dist/server/managed-ssh.d.ts +26 -0
- package/dist/server/managed-ssh.js +73 -0
- package/dist/server/manager-vault.d.ts +11 -0
- package/dist/server/manager-vault.js +67 -0
- package/dist/server/memory-recall.d.ts +25 -0
- package/dist/server/memory-recall.js +45 -0
- package/dist/server/memory.d.ts +67 -0
- package/dist/server/memory.js +216 -0
- package/dist/server/message-media.d.ts +7 -0
- package/dist/server/message-media.js +54 -0
- package/dist/server/model-context-window.d.ts +186 -0
- package/dist/server/model-context-window.js +444 -0
- package/dist/server/model-filter.d.ts +23 -0
- package/dist/server/model-filter.js +48 -0
- package/dist/server/models-store.d.ts +36 -0
- package/dist/server/models-store.js +132 -0
- package/dist/server/native-tool-settings.d.ts +25 -0
- package/dist/server/native-tool-settings.js +41 -0
- package/dist/server/native-tools-extension.d.ts +2 -0
- package/dist/server/native-tools-extension.js +39 -0
- package/dist/server/native-tools-service.d.ts +39 -0
- package/dist/server/native-tools-service.js +240 -0
- package/dist/server/persistence/app-state-repository.d.ts +65 -0
- package/dist/server/persistence/app-state-repository.js +1 -0
- package/dist/server/persistence/json-state-repository.d.ts +14 -0
- package/dist/server/persistence/json-state-repository.js +43 -0
- package/dist/server/persistence/open-state-store.d.ts +3 -0
- package/dist/server/persistence/open-state-store.js +35 -0
- package/dist/server/persistence/rename.d.ts +22 -0
- package/dist/server/persistence/rename.js +44 -0
- package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
- package/dist/server/persistence/sqlite-state-repository.js +264 -0
- package/dist/server/pi-command.d.ts +94 -0
- package/dist/server/pi-command.js +265 -0
- package/dist/server/pi-native.d.ts +12 -0
- package/dist/server/pi-native.js +16 -0
- package/dist/server/pi-session-events.d.ts +158 -0
- package/dist/server/pi-session-events.js +373 -0
- package/dist/server/pi-session-pool.d.ts +233 -0
- package/dist/server/pi-session-pool.js +382 -0
- package/dist/server/pi-session.d.ts +642 -0
- package/dist/server/pi-session.js +655 -0
- package/dist/server/presentations/schema.d.ts +120 -0
- package/dist/server/presentations/schema.js +128 -0
- package/dist/server/provider-network.d.ts +16 -0
- package/dist/server/provider-network.js +106 -0
- package/dist/server/provider-proxy.d.ts +18 -0
- package/dist/server/provider-proxy.js +200 -0
- package/dist/server/providers.d.ts +333 -0
- package/dist/server/providers.js +989 -0
- package/dist/server/remote-bootstrap.d.ts +17 -0
- package/dist/server/remote-bootstrap.js +119 -0
- package/dist/server/rpc-channel.d.ts +131 -0
- package/dist/server/rpc-channel.js +135 -0
- package/dist/server/runtime.d.ts +1393 -0
- package/dist/server/runtime.js +3286 -0
- package/dist/server/scheduled-tasks.d.ts +101 -0
- package/dist/server/scheduled-tasks.js +138 -0
- package/dist/server/server-context.d.ts +119 -0
- package/dist/server/server-context.js +1 -0
- package/dist/server/session-cwd.d.ts +19 -0
- package/dist/server/session-cwd.js +58 -0
- package/dist/server/session-ledger.d.ts +67 -0
- package/dist/server/session-ledger.js +76 -0
- package/dist/server/session-memory-scope.d.ts +4 -0
- package/dist/server/session-memory-scope.js +30 -0
- package/dist/server/session-repository.d.ts +100 -0
- package/dist/server/session-repository.js +246 -0
- package/dist/server/session-tree-scope.d.ts +125 -0
- package/dist/server/session-tree-scope.js +337 -0
- package/dist/server/skills.d.ts +23 -0
- package/dist/server/skills.js +190 -0
- package/dist/server/store.d.ts +1062 -0
- package/dist/server/store.js +3305 -0
- package/dist/server/subagent-runs.d.ts +185 -0
- package/dist/server/subagent-runs.js +383 -0
- package/dist/server/subagents.d.ts +200 -0
- package/dist/server/subagents.js +619 -0
- package/dist/server/task-tool.d.ts +282 -0
- package/dist/server/task-tool.js +507 -0
- package/dist/server/tavily.d.ts +32 -0
- package/dist/server/tavily.js +136 -0
- package/dist/server/team-context.d.ts +12 -0
- package/dist/server/team-context.js +180 -0
- package/dist/server/terminal.d.ts +163 -0
- package/dist/server/terminal.js +557 -0
- package/dist/server/thinking-level-discovery.d.ts +38 -0
- package/dist/server/thinking-level-discovery.js +183 -0
- package/dist/server/time-zone.d.ts +20 -0
- package/dist/server/time-zone.js +32 -0
- package/dist/server/tool-calls.d.ts +130 -0
- package/dist/server/tool-calls.js +341 -0
- package/dist/server/tool-llm.d.ts +72 -0
- package/dist/server/tool-llm.js +146 -0
- package/dist/server/tool-registry.d.ts +129 -0
- package/dist/server/tool-registry.js +249 -0
- package/dist/server/tool-runner.d.ts +112 -0
- package/dist/server/tool-runner.js +306 -0
- package/dist/server/turn-failure.d.ts +48 -0
- package/dist/server/turn-failure.js +148 -0
- package/dist/server/types.d.ts +2315 -0
- package/dist/server/types.js +11 -0
- package/dist/server/update-status.d.ts +14 -0
- package/dist/server/update-status.js +69 -0
- package/dist/server/update.d.ts +46 -0
- package/dist/server/update.js +104 -0
- package/dist/server/upload.d.ts +35 -0
- package/dist/server/upload.js +177 -0
- package/dist/server/version.d.ts +33 -0
- package/dist/server/version.js +111 -0
- package/dist/server/web.d.ts +27 -0
- package/dist/server/web.js +183 -0
- package/dist/server/workflow-engine.d.ts +47 -0
- package/dist/server/workflow-engine.js +255 -0
- package/dist/server/workflow.d.ts +329 -0
- package/dist/server/workflow.js +469 -0
- package/dist/server/workspace-file-indexes.d.ts +2 -0
- package/dist/server/workspace-file-indexes.js +61 -0
- package/dist/server/workspace-file-operations.d.ts +36 -0
- package/dist/server/workspace-file-operations.js +281 -0
- package/dist/server/workspace-file-response.d.ts +7 -0
- package/dist/server/workspace-file-response.js +79 -0
- package/dist/server/ws-server.d.ts +149 -0
- package/dist/server/ws-server.js +640 -0
- package/dist/shared/agent-order.d.ts +44 -0
- package/dist/shared/agent-order.js +50 -0
- package/dist/shared/archive-decisions.d.ts +44 -0
- package/dist/shared/archive-decisions.js +98 -0
- package/dist/shared/background-task.d.ts +25 -0
- package/dist/shared/background-task.js +183 -0
- package/dist/shared/child-session-lock.d.ts +37 -0
- package/dist/shared/child-session-lock.js +59 -0
- package/dist/shared/content-search.d.ts +22 -0
- package/dist/shared/content-search.js +1 -0
- package/dist/shared/conversation-title.d.ts +4 -0
- package/dist/shared/conversation-title.js +4 -0
- package/dist/shared/file-mentions.d.ts +17 -0
- package/dist/shared/file-mentions.js +91 -0
- package/dist/shared/git-commit.d.ts +11 -0
- package/dist/shared/git-commit.js +1 -0
- package/dist/shared/git-graph.d.ts +42 -0
- package/dist/shared/git-graph.js +30 -0
- package/dist/shared/group-chat.d.ts +132 -0
- package/dist/shared/group-chat.js +6 -0
- package/dist/shared/managed-servers.d.ts +36 -0
- package/dist/shared/managed-servers.js +1 -0
- package/dist/shared/message-media.d.ts +12 -0
- package/dist/shared/message-media.js +27 -0
- package/dist/shared/model-window-label.d.ts +39 -0
- package/dist/shared/model-window-label.js +55 -0
- package/dist/shared/native-tools.d.ts +43 -0
- package/dist/shared/native-tools.js +1 -0
- package/dist/shared/pi-cache-warming.d.ts +9 -0
- package/dist/shared/pi-cache-warming.js +4 -0
- package/dist/shared/project-overview.d.ts +107 -0
- package/dist/shared/project-overview.js +92 -0
- package/dist/shared/project-presentation.d.ts +55 -0
- package/dist/shared/project-presentation.js +111 -0
- package/dist/shared/provider-network.d.ts +30 -0
- package/dist/shared/provider-network.js +1 -0
- package/dist/shared/session-reporting.d.ts +40 -0
- package/dist/shared/session-reporting.js +97 -0
- package/dist/shared/session-search.d.ts +14 -0
- package/dist/shared/session-search.js +1 -0
- package/dist/shared/team-context-view.d.ts +33 -0
- package/dist/shared/team-context-view.js +49 -0
- package/dist/shared/team-context.d.ts +59 -0
- package/dist/shared/team-context.js +3 -0
- package/dist/shared/terminal-protocol.d.ts +71 -0
- package/dist/shared/terminal-protocol.js +1 -0
- package/dist/shared/thinking-levels.d.ts +53 -0
- package/dist/shared/thinking-levels.js +85 -0
- package/dist/shared/tool-glyph.d.ts +7 -0
- package/dist/shared/tool-glyph.js +19 -0
- package/dist/shared/transcript-order.d.ts +7 -0
- package/dist/shared/transcript-order.js +12 -0
- package/dist/shared/update-status.d.ts +28 -0
- package/dist/shared/update-status.js +1 -0
- package/dist/shared/workspace-file-preview.d.ts +4 -0
- package/dist/shared/workspace-file-preview.js +28 -0
- package/package.json +450 -4
- package/scripts/diagnose.mjs +603 -0
- package/scripts/patch-brace-expansion.mjs +260 -0
- package/scripts/restart-server.mjs +104 -0
- package/skills/presentation/SKILL.md +30 -0
- package/skills/presentation/references/data.md +10 -0
- package/skills/presentation/references/quality.md +12 -0
- package/skills/presentation/references/story.md +12 -0
- package/skills/presentation/references/templates-and-editing.md +11 -0
- package/skills/presentation/references/visual-system.md +10 -0
- package/skills/super-pi-agent-development/SKILL.md +25 -0
- package/skills/super-pi-development/SKILL.md +31 -0
- package/skills/super-pi-tool-development/SKILL.md +39 -0
|
@@ -0,0 +1,953 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { open, readFile, realpath, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { createGitWorktree } from "../git.js";
|
|
5
|
+
import { DEFAULT_GROUP_MEMBER_IDS } from "../../shared/group-chat.js";
|
|
6
|
+
import { CODING_STANDARD_REQUEST } from "../active-memory.js";
|
|
7
|
+
import { applicableRules, assertModelAllowed } from "../model-filter.js";
|
|
8
|
+
import { replaceFile } from "../persistence/rename.js";
|
|
9
|
+
import { finishGroupExecution, GroupExecutionRecorder } from "./group-execution.js";
|
|
10
|
+
const MAX_AUTOMATIC_REPLIES = 10;
|
|
11
|
+
const MAX_REPLIES_PER_MEMBER = 3;
|
|
12
|
+
const CONTEXT_MESSAGES = 20;
|
|
13
|
+
const MAX_CONTENT = 32_000;
|
|
14
|
+
const SAVED_EXECUTIONS_PER_ROOM = 64;
|
|
15
|
+
const timestamp = () => new Date().toISOString();
|
|
16
|
+
function inputText(value, limit, label) {
|
|
17
|
+
if (typeof value !== "string" || value.length > limit)
|
|
18
|
+
throw new Error(`${label}格式无效或超过长度上限。`);
|
|
19
|
+
return value.trim();
|
|
20
|
+
}
|
|
21
|
+
function activityStatus(messages) {
|
|
22
|
+
let latestTopic;
|
|
23
|
+
let activeTopic = false;
|
|
24
|
+
let activeBackground = false;
|
|
25
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
26
|
+
const post = messages[i];
|
|
27
|
+
if (post.role === "user") {
|
|
28
|
+
latestTopic ??= post.status;
|
|
29
|
+
if (post.status === "queued")
|
|
30
|
+
return "running";
|
|
31
|
+
activeTopic ||= post.status === "running";
|
|
32
|
+
}
|
|
33
|
+
else if (post.status === "queued" || post.status === "running") {
|
|
34
|
+
if (!post.background)
|
|
35
|
+
return "running";
|
|
36
|
+
activeBackground = true;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (activeBackground)
|
|
40
|
+
return "awaiting_background";
|
|
41
|
+
if (activeTopic)
|
|
42
|
+
return "running";
|
|
43
|
+
if (latestTopic === "completed")
|
|
44
|
+
return "completed";
|
|
45
|
+
if (latestTopic === "failed" || latestTopic === "interrupted")
|
|
46
|
+
return "failed";
|
|
47
|
+
return "idle";
|
|
48
|
+
}
|
|
49
|
+
function groupActivity(room) {
|
|
50
|
+
let lastReplyAt;
|
|
51
|
+
for (const post of room.messages) {
|
|
52
|
+
if (post.role !== "assistant" || (!post.content && !post.error))
|
|
53
|
+
continue;
|
|
54
|
+
const at = post.settledAt ?? post.createdAt;
|
|
55
|
+
if (!lastReplyAt || at > lastReplyAt)
|
|
56
|
+
lastReplyAt = at;
|
|
57
|
+
}
|
|
58
|
+
return { status: activityStatus(room.messages), revision: room.revision, ...(lastReplyAt ? { lastReplyAt } : {}) };
|
|
59
|
+
}
|
|
60
|
+
function summary(room) {
|
|
61
|
+
const { id, workspaceId, title, updatedAt, archivedAt } = room;
|
|
62
|
+
return { id, workspaceId, title, updatedAt, archivedAt, activity: groupActivity(room), cloneRequests: room.cloneRequests?.filter(item => item.status === "pending") };
|
|
63
|
+
}
|
|
64
|
+
async function readReferences(workspacePath, input) {
|
|
65
|
+
if (!Array.isArray(input) || !input.length)
|
|
66
|
+
return undefined;
|
|
67
|
+
const paths = [...new Set(input)];
|
|
68
|
+
if (paths.length > 4)
|
|
69
|
+
throw new Error("一条群聊消息最多引用四个文件。");
|
|
70
|
+
const root = await realpath(workspacePath);
|
|
71
|
+
return Promise.all(paths.map(async (value) => {
|
|
72
|
+
const path = inputText(value, 2048, "引用文件路径");
|
|
73
|
+
const filePath = await realpath(resolve(root, path));
|
|
74
|
+
const inside = relative(root, filePath);
|
|
75
|
+
if (!inside || inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside))
|
|
76
|
+
throw new Error("群聊只能引用工作区内的文件。");
|
|
77
|
+
const file = await open(filePath, "r");
|
|
78
|
+
try {
|
|
79
|
+
const stat = await file.stat();
|
|
80
|
+
if (!stat.isFile())
|
|
81
|
+
throw new Error(`「${path}」不是普通文件。`);
|
|
82
|
+
const bytes = Buffer.alloc(Math.min(stat.size, 8192));
|
|
83
|
+
const { bytesRead } = await file.read(bytes, 0, bytes.length, 0);
|
|
84
|
+
const used = bytes.subarray(0, bytesRead);
|
|
85
|
+
if (used.includes(0))
|
|
86
|
+
throw new Error(`「${path}」不是文本文件。`);
|
|
87
|
+
const excerpt = used.toString("utf8") + (stat.size > bytesRead ? "\n[文件摘录已截断]" : "");
|
|
88
|
+
return { path, excerpt };
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
await file.close();
|
|
92
|
+
}
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
function route(text, candidates, anchors) {
|
|
96
|
+
const parsed = JSON.parse(text.trim().replace(/^```(?:json)?\s*|\s*```$/gi, ""));
|
|
97
|
+
if (!parsed || typeof parsed !== "object")
|
|
98
|
+
throw new Error("主持人未返回有效决定。");
|
|
99
|
+
const decision = parsed;
|
|
100
|
+
const reason = typeof decision.reason === "string" ? decision.reason.trim().slice(0, 320) : undefined;
|
|
101
|
+
if (decision.action === "finish")
|
|
102
|
+
return { action: "finish", reason };
|
|
103
|
+
if (decision.action === "blocked" && reason)
|
|
104
|
+
return { action: "blocked", reason };
|
|
105
|
+
if (decision.action === "wait")
|
|
106
|
+
return { action: "wait", memberId: typeof decision.memberId === "string" ? decision.memberId : undefined };
|
|
107
|
+
if (decision.action === "clone" && typeof decision.memberId === "string")
|
|
108
|
+
return { action: "clone", memberId: decision.memberId, assignment: inputText(decision.assignment, 1600, "分身任务"), reason: reason || "同类成员正在工作,新任务可以独立开展。" };
|
|
109
|
+
if (!["reply", "background"].includes(String(decision.action)) || typeof decision.memberId !== "string" || !candidates.some(member => member.id === decision.memberId)) {
|
|
110
|
+
throw new Error("主持人选择了无效的群成员。");
|
|
111
|
+
}
|
|
112
|
+
const replyTo = typeof decision.replyTo === "string" && anchors.has(decision.replyTo) ? decision.replyTo : undefined;
|
|
113
|
+
const assignment = inputText(decision.assignment, 1600, "接话任务");
|
|
114
|
+
if (!assignment)
|
|
115
|
+
throw new Error("主持人没有给出接话任务。");
|
|
116
|
+
return { action: "reply", memberId: decision.memberId, replyTo, assignment, reason, background: decision.action === "background" };
|
|
117
|
+
}
|
|
118
|
+
function extractHandoff(author, content, members) {
|
|
119
|
+
const line = content.trimEnd().split(/\r?\n/u).at(-1)?.trim();
|
|
120
|
+
const request = line?.match(/^@([^::]{1,100})[::]\s*(.{1,800})$/u);
|
|
121
|
+
if (!request)
|
|
122
|
+
return;
|
|
123
|
+
const recipient = request[1].trim();
|
|
124
|
+
const matches = members.filter(member => member.id === recipient || member.name === recipient);
|
|
125
|
+
const assignment = request[2].trim();
|
|
126
|
+
if (matches.length === 1 && matches[0].id !== author && assignment)
|
|
127
|
+
return { memberId: matches[0].id, assignment };
|
|
128
|
+
}
|
|
129
|
+
function outstandingHandoffs(replies) {
|
|
130
|
+
return replies.flatMap(post => {
|
|
131
|
+
const handoff = post.status === "completed" ? post.handoff : undefined;
|
|
132
|
+
const delegated = handoff && replies.some(reply => reply.replyTo === post.id && reply.memberId === handoff.memberId && reply.status !== "failed");
|
|
133
|
+
return handoff && !delegated ? [{ ...handoff, replyTo: post.id, from: post.memberId }] : [];
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
export class GroupChatNotFoundError extends Error {
|
|
137
|
+
constructor(message = "此工作区没有这个群聊。") { super(message); }
|
|
138
|
+
}
|
|
139
|
+
export class GroupChatService {
|
|
140
|
+
filePath;
|
|
141
|
+
store;
|
|
142
|
+
runtime;
|
|
143
|
+
memory;
|
|
144
|
+
onActivity;
|
|
145
|
+
rooms = [];
|
|
146
|
+
writes = Promise.resolve();
|
|
147
|
+
running = new Map();
|
|
148
|
+
memberRuns = new Map();
|
|
149
|
+
cloneDecisions = new Map();
|
|
150
|
+
cloneWorktrees = new Map();
|
|
151
|
+
controllers = new Map();
|
|
152
|
+
live = new Map();
|
|
153
|
+
liveExecutions = new Map();
|
|
154
|
+
streamRevisions = new Map();
|
|
155
|
+
closing = false;
|
|
156
|
+
constructor(filePath, store, runtime, memory, onActivity) {
|
|
157
|
+
this.filePath = filePath;
|
|
158
|
+
this.store = store;
|
|
159
|
+
this.runtime = runtime;
|
|
160
|
+
this.memory = memory;
|
|
161
|
+
this.onActivity = onActivity;
|
|
162
|
+
}
|
|
163
|
+
static async open(filePath, store, runtime, memory, onActivity) {
|
|
164
|
+
const service = new GroupChatService(filePath, store, runtime, memory, onActivity);
|
|
165
|
+
try {
|
|
166
|
+
service.rooms = JSON.parse(await readFile(filePath, "utf8"));
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (error.code !== "ENOENT")
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
if (service.rooms.some(room => room.messages.some(post => post.status === "running" || (post.role === "assistant" && post.status === "queued")))) {
|
|
173
|
+
await service.edit(rooms => {
|
|
174
|
+
for (const room of rooms) {
|
|
175
|
+
for (const request of room.cloneRequests ?? [])
|
|
176
|
+
if (request.status === "pending") {
|
|
177
|
+
request.status = "expired";
|
|
178
|
+
room.revision += 1;
|
|
179
|
+
}
|
|
180
|
+
for (const post of room.messages)
|
|
181
|
+
if (post.status === "running" || (post.role === "assistant" && post.status === "queued")) {
|
|
182
|
+
post.status = "interrupted";
|
|
183
|
+
post.error = "服务重启,本次发言已中断。";
|
|
184
|
+
const trace = room.executions?.[post.id];
|
|
185
|
+
if (trace && room.executions)
|
|
186
|
+
room.executions[post.id] = finishGroupExecution(trace);
|
|
187
|
+
room.revision += 1;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
for (const room of service.rooms)
|
|
193
|
+
service.kick(room.id);
|
|
194
|
+
return service;
|
|
195
|
+
}
|
|
196
|
+
workspace(id) {
|
|
197
|
+
const workspace = this.store.workspace(id);
|
|
198
|
+
if (!workspace || workspace.closedAt)
|
|
199
|
+
throw new Error("工作区不存在或已关闭。");
|
|
200
|
+
return workspace;
|
|
201
|
+
}
|
|
202
|
+
find(rooms, workspaceId, id) {
|
|
203
|
+
this.workspace(workspaceId);
|
|
204
|
+
const room = rooms.find(item => item.id === id && item.workspaceId === workspaceId);
|
|
205
|
+
if (!room)
|
|
206
|
+
throw new GroupChatNotFoundError();
|
|
207
|
+
return room;
|
|
208
|
+
}
|
|
209
|
+
activeRoom(rooms, workspaceId, id) {
|
|
210
|
+
const room = this.find(rooms, workspaceId, id);
|
|
211
|
+
if (room.archivedAt)
|
|
212
|
+
throw new Error("群聊已归档,请先恢复。");
|
|
213
|
+
return room;
|
|
214
|
+
}
|
|
215
|
+
hasUnsettledWork(room) {
|
|
216
|
+
return room.messages.some(post => post.status === "queued" || post.status === "running" || this.running.has(post.id));
|
|
217
|
+
}
|
|
218
|
+
edit(change) {
|
|
219
|
+
const write = this.writes.then(async () => {
|
|
220
|
+
const previous = this.rooms;
|
|
221
|
+
const rooms = structuredClone(previous);
|
|
222
|
+
const result = change(rooms);
|
|
223
|
+
const temporary = this.filePath + ".tmp";
|
|
224
|
+
await writeFile(temporary, JSON.stringify(rooms), { encoding: "utf8", mode: 0o600 });
|
|
225
|
+
await replaceFile(temporary, this.filePath);
|
|
226
|
+
this.rooms = rooms;
|
|
227
|
+
this.publishActivity(previous);
|
|
228
|
+
return result;
|
|
229
|
+
});
|
|
230
|
+
this.writes = write.then(() => undefined, () => undefined);
|
|
231
|
+
return write;
|
|
232
|
+
}
|
|
233
|
+
publishActivity(previous) {
|
|
234
|
+
if (!this.onActivity)
|
|
235
|
+
return;
|
|
236
|
+
const prior = new Map(previous.map(room => [room.id, room]));
|
|
237
|
+
for (const room of this.rooms) {
|
|
238
|
+
const before = prior.get(room.id);
|
|
239
|
+
if (!before || before.revision === room.revision)
|
|
240
|
+
continue;
|
|
241
|
+
const workspace = this.store.workspace(room.workspaceId);
|
|
242
|
+
if (!workspace || workspace.closedAt)
|
|
243
|
+
continue;
|
|
244
|
+
const activity = groupActivity(room);
|
|
245
|
+
const priorActivity = groupActivity(before);
|
|
246
|
+
if (activity.status !== priorActivity.status || activity.lastReplyAt !== priorActivity.lastReplyAt || JSON.stringify(room.cloneRequests) !== JSON.stringify(before.cloneRequests))
|
|
247
|
+
this.onActivity({ id: room.id, workspaceId: room.workspaceId, activity, cloneRequests: room.cloneRequests?.filter(item => item.status === "pending") ?? [] });
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
list(workspaceId) {
|
|
251
|
+
this.workspace(workspaceId);
|
|
252
|
+
return this.rooms.filter(room => room.workspaceId === workspaceId).map(summary).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
253
|
+
}
|
|
254
|
+
get(workspaceId, id) {
|
|
255
|
+
const { executions, ...record } = this.find(this.rooms, workspaceId, id);
|
|
256
|
+
const room = structuredClone(record);
|
|
257
|
+
for (const post of room.messages)
|
|
258
|
+
if (post.status === "running") {
|
|
259
|
+
post.content = this.live.get(post.id) ?? post.content;
|
|
260
|
+
if (post.role === "assistant")
|
|
261
|
+
post.executionActivity = this.liveExecutions.get(post.id)?.activity;
|
|
262
|
+
}
|
|
263
|
+
return { ...room, activity: groupActivity(room), revision: `${room.revision}:${this.streamRevisions.get(id) ?? 0}` };
|
|
264
|
+
}
|
|
265
|
+
execution(workspaceId, id, postId) {
|
|
266
|
+
const room = this.find(this.rooms, workspaceId, id);
|
|
267
|
+
const post = room.messages.find(item => item.id === postId && item.role === "assistant");
|
|
268
|
+
if (!post)
|
|
269
|
+
throw new GroupChatNotFoundError("群聊里找不到该次执行。");
|
|
270
|
+
const live = post.status === "running" ? this.liveExecutions.get(postId) : undefined;
|
|
271
|
+
const trace = live?.trace ?? room.executions?.[postId] ?? { steps: [] };
|
|
272
|
+
return { ...structuredClone(trace), status: post.status, revision: `${room.revision}:${live?.revision ?? 0}` };
|
|
273
|
+
}
|
|
274
|
+
saveExecution(room, postId, settled = false) {
|
|
275
|
+
const live = this.liveExecutions.get(postId);
|
|
276
|
+
if (!live?.trace.steps.length)
|
|
277
|
+
return;
|
|
278
|
+
const trace = structuredClone(live.trace);
|
|
279
|
+
const executions = room.executions ??= {};
|
|
280
|
+
executions[postId] = settled ? finishGroupExecution(trace) : trace;
|
|
281
|
+
const ids = Object.keys(executions);
|
|
282
|
+
if (ids.length > SAVED_EXECUTIONS_PER_ROOM) {
|
|
283
|
+
const expired = ids.find(id => !this.liveExecutions.has(id));
|
|
284
|
+
if (expired)
|
|
285
|
+
delete executions[expired];
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
async setArchived(workspaceId, id, archived) {
|
|
289
|
+
return this.edit(rooms => {
|
|
290
|
+
const room = this.find(rooms, workspaceId, id);
|
|
291
|
+
if (Boolean(room.archivedAt) === archived)
|
|
292
|
+
return summary(room);
|
|
293
|
+
if (archived && this.hasUnsettledWork(room))
|
|
294
|
+
throw new Error("群聊还有任务未结束,请先停止任务或等它结束后再归档。");
|
|
295
|
+
room.updatedAt = timestamp();
|
|
296
|
+
if (archived)
|
|
297
|
+
room.archivedAt = room.updatedAt;
|
|
298
|
+
else
|
|
299
|
+
delete room.archivedAt;
|
|
300
|
+
room.revision += 1;
|
|
301
|
+
return summary(room);
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
async deleteArchived(workspaceId, id) {
|
|
305
|
+
this.workspace(workspaceId);
|
|
306
|
+
const removed = await this.edit(rooms => {
|
|
307
|
+
const index = rooms.findIndex(room => room.workspaceId === workspaceId && room.id === id);
|
|
308
|
+
if (index < 0)
|
|
309
|
+
return false;
|
|
310
|
+
const room = rooms[index];
|
|
311
|
+
if (!room.archivedAt)
|
|
312
|
+
throw new Error("请先归档群聊,再永久删除。");
|
|
313
|
+
if (this.hasUnsettledWork(room))
|
|
314
|
+
throw new Error("群聊还有任务未结束,请等它结束后再删除。");
|
|
315
|
+
rooms.splice(index, 1);
|
|
316
|
+
return true;
|
|
317
|
+
});
|
|
318
|
+
if (removed)
|
|
319
|
+
this.streamRevisions.delete(id);
|
|
320
|
+
}
|
|
321
|
+
async moderator(workspaceId, body) {
|
|
322
|
+
const workspace = this.workspace(workspaceId);
|
|
323
|
+
const prompt = inputText(body.prompt ?? "", 8_000, "主持人 Prompt");
|
|
324
|
+
const cloneLimit = typeof body.cloneLimit === "number" && Number.isInteger(body.cloneLimit) && body.cloneLimit >= 2 && body.cloneLimit <= 8 ? body.cloneLimit : undefined;
|
|
325
|
+
if (!body.model)
|
|
326
|
+
return { prompt, cloneLimit };
|
|
327
|
+
if (typeof body.model !== "object")
|
|
328
|
+
throw new Error("主持人模型无效。");
|
|
329
|
+
const requested = body.model;
|
|
330
|
+
const catalog = await this.runtime.catalog();
|
|
331
|
+
const model = catalog.models.find(item => item.provider === requested.provider && item.modelId === requested.modelId);
|
|
332
|
+
if (!model)
|
|
333
|
+
throw new Error("主持人模型不可用。");
|
|
334
|
+
assertModelAllowed(this.store.modelFilterRules(), workspace, model);
|
|
335
|
+
return { prompt, cloneLimit, model: { provider: model.provider, modelId: model.modelId, label: model.label } };
|
|
336
|
+
}
|
|
337
|
+
async resolveMembers(id, input, existing = []) {
|
|
338
|
+
const memberIds = Array.isArray(input) ? [...new Set(input)] : [];
|
|
339
|
+
if (memberIds.length < 2 || memberIds.length > 8)
|
|
340
|
+
throw new Error("请选择 2 到 8 位主 Agent。");
|
|
341
|
+
return Promise.all(memberIds.map(async (memberId) => {
|
|
342
|
+
if (typeof memberId !== "string")
|
|
343
|
+
throw new Error("群成员无效。");
|
|
344
|
+
const saved = existing.find(member => member.id === memberId);
|
|
345
|
+
if (saved)
|
|
346
|
+
return saved;
|
|
347
|
+
const agent = await this.runtime.agentFor?.({ id, agentId: memberId });
|
|
348
|
+
if (!agent || agent.id !== memberId || agent.mode !== "primary" || agent.hidden)
|
|
349
|
+
throw new Error(`主 Agent ${memberId} 不可用。`);
|
|
350
|
+
return { id: agent.id, name: agent.name, description: agent.description };
|
|
351
|
+
}));
|
|
352
|
+
}
|
|
353
|
+
async create(workspaceId, input) {
|
|
354
|
+
this.workspace(workspaceId);
|
|
355
|
+
const title = inputText(input.title, 100, "群名");
|
|
356
|
+
if (!title)
|
|
357
|
+
throw new Error("请输入群名。");
|
|
358
|
+
const id = randomUUID();
|
|
359
|
+
const members = await this.resolveMembers(id, input.memberIds ?? DEFAULT_GROUP_MEMBER_IDS);
|
|
360
|
+
const moderator = await this.moderator(workspaceId, input.moderator ?? {});
|
|
361
|
+
const room = { id, workspaceId, title, updatedAt: timestamp(), revision: 0, members, moderator, messages: [] };
|
|
362
|
+
await this.edit(rooms => { rooms.push(room); });
|
|
363
|
+
return this.get(workspaceId, id);
|
|
364
|
+
}
|
|
365
|
+
async resolveClone(workspaceId, id, input) {
|
|
366
|
+
const requestId = inputText(input.requestId, 100, "创建请求");
|
|
367
|
+
if (input.choice !== "create" && input.choice !== "wait")
|
|
368
|
+
throw new Error("请选择创建分身或等待。");
|
|
369
|
+
const name = input.choice === "create" ? inputText(input.name, 80, "分身名字") : "";
|
|
370
|
+
if (input.choice === "create" && !name)
|
|
371
|
+
throw new Error("请填写分身名字。");
|
|
372
|
+
const current = this.activeRoom(this.rooms, workspaceId, id);
|
|
373
|
+
const pending = current.cloneRequests?.find(item => item.id === requestId && item.status === "pending");
|
|
374
|
+
let worktreePath;
|
|
375
|
+
if (input.choice === "create" && pending) {
|
|
376
|
+
let creating = this.cloneWorktrees.get(requestId);
|
|
377
|
+
if (!creating) {
|
|
378
|
+
creating = createGitWorktree(this.workspace(workspaceId).path, join(dirname(this.filePath), "worktrees"), requestId, { branch: `group/clone-${requestId}` }).then(entry => entry.path);
|
|
379
|
+
this.cloneWorktrees.set(requestId, creating);
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
worktreePath = await creating;
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
this.cloneWorktrees.delete(requestId);
|
|
386
|
+
throw error;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
await this.edit(rooms => {
|
|
390
|
+
const room = this.activeRoom(rooms, workspaceId, id);
|
|
391
|
+
const request = room.cloneRequests?.find(item => item.id === requestId);
|
|
392
|
+
if (!request)
|
|
393
|
+
throw new Error("创建请求不存在。");
|
|
394
|
+
if (request.status !== "pending")
|
|
395
|
+
return;
|
|
396
|
+
const source = room.members.find(member => member.id === request.memberId);
|
|
397
|
+
const topic = room.messages.find(post => post.id === request.topicId);
|
|
398
|
+
const busy = room.messages.some(post => post.role === "assistant" && post.memberId === source?.id && (post.status === "running" || post.status === "queued"));
|
|
399
|
+
if (!source || topic?.status !== "running" || !busy)
|
|
400
|
+
request.status = "expired";
|
|
401
|
+
else if (input.choice === "wait")
|
|
402
|
+
request.status = "waiting";
|
|
403
|
+
else {
|
|
404
|
+
if (room.members.length >= 8)
|
|
405
|
+
throw new Error("群聊最多支持 8 位成员。");
|
|
406
|
+
if (room.members.some(member => member.name === name))
|
|
407
|
+
throw new Error("群里已有同名成员,请换一个名字。");
|
|
408
|
+
const cloneId = randomUUID();
|
|
409
|
+
room.members.push({ ...source, id: cloneId, name, agentId: source.agentId ?? source.id, worktreePath });
|
|
410
|
+
request.cloneId = cloneId;
|
|
411
|
+
request.status = "created";
|
|
412
|
+
}
|
|
413
|
+
room.revision += 1;
|
|
414
|
+
});
|
|
415
|
+
this.cloneDecisions.get(requestId)?.();
|
|
416
|
+
return this.get(workspaceId, id);
|
|
417
|
+
}
|
|
418
|
+
async configure(workspaceId, id, input) {
|
|
419
|
+
const current = this.activeRoom(this.rooms, workspaceId, id);
|
|
420
|
+
const moderator = await this.moderator(workspaceId, input);
|
|
421
|
+
const members = input.memberIds === undefined ? undefined : await this.resolveMembers(id, input.memberIds, current.members);
|
|
422
|
+
await this.edit(rooms => {
|
|
423
|
+
const room = this.activeRoom(rooms, workspaceId, id);
|
|
424
|
+
if (members) {
|
|
425
|
+
for (const post of room.messages)
|
|
426
|
+
if (post.role === "assistant")
|
|
427
|
+
post.memberName ??= room.members.find(member => member.id === post.memberId)?.name;
|
|
428
|
+
room.members = members;
|
|
429
|
+
}
|
|
430
|
+
room.moderator = moderator;
|
|
431
|
+
room.revision += 1;
|
|
432
|
+
});
|
|
433
|
+
return this.get(workspaceId, id);
|
|
434
|
+
}
|
|
435
|
+
async send(workspaceId, id, input) {
|
|
436
|
+
if (this.closing)
|
|
437
|
+
throw new Error("服务正在关闭。");
|
|
438
|
+
const content = inputText(input.content, MAX_CONTENT, "消息");
|
|
439
|
+
const clientId = inputText(input.clientId, 128, "发送标识");
|
|
440
|
+
if (!content || !clientId)
|
|
441
|
+
throw new Error("消息内容和发送标识不能为空。");
|
|
442
|
+
const current = this.activeRoom(this.rooms, workspaceId, id);
|
|
443
|
+
if (current.messages.some(post => post.role === "user" && post.clientId === clientId))
|
|
444
|
+
return this.get(workspaceId, id);
|
|
445
|
+
const files = await readReferences(this.workspace(workspaceId).path, input.filePaths);
|
|
446
|
+
await this.edit(rooms => {
|
|
447
|
+
const room = this.activeRoom(rooms, workspaceId, id);
|
|
448
|
+
if (room.messages.some(post => post.role === "user" && post.clientId === clientId))
|
|
449
|
+
return;
|
|
450
|
+
const parent = typeof input.replyTo === "string" ? room.messages.find(post => post.id === input.replyTo) : undefined;
|
|
451
|
+
if (input.replyTo && !parent)
|
|
452
|
+
throw new Error("群里找不到引用的消息。");
|
|
453
|
+
const memberIds = [];
|
|
454
|
+
for (const memberId of Array.isArray(input.memberIds) ? input.memberIds : []) {
|
|
455
|
+
if (!room.members.some(member => member.id === memberId))
|
|
456
|
+
throw new Error("点名的 Agent 不在群里。");
|
|
457
|
+
if (!memberIds.includes(memberId))
|
|
458
|
+
memberIds.push(memberId);
|
|
459
|
+
}
|
|
460
|
+
if (!memberIds.length && parent?.role === "assistant" && room.members.some(member => member.id === parent.memberId))
|
|
461
|
+
memberIds.push(parent.memberId);
|
|
462
|
+
room.messages.push({ id: randomUUID(), role: "user", clientId, content, files, memberIds, replyTo: parent?.id, createdAt: timestamp(), status: "queued" });
|
|
463
|
+
room.updatedAt = timestamp();
|
|
464
|
+
room.revision += 1;
|
|
465
|
+
});
|
|
466
|
+
this.kick(id);
|
|
467
|
+
return this.get(workspaceId, id);
|
|
468
|
+
}
|
|
469
|
+
async stop(workspaceId, id, postId) {
|
|
470
|
+
const cancelled = await this.edit(rooms => {
|
|
471
|
+
const room = this.activeRoom(rooms, workspaceId, id);
|
|
472
|
+
const posts = room.messages.filter(post => (post.id === postId || (post.role === "assistant" && post.topicId === postId)) && ["queued", "running"].includes(post.status));
|
|
473
|
+
for (const post of posts) {
|
|
474
|
+
post.content = this.live.get(post.id) ?? post.content;
|
|
475
|
+
post.status = "cancelled";
|
|
476
|
+
if (post.role === "assistant")
|
|
477
|
+
this.saveExecution(room, post.id, true);
|
|
478
|
+
}
|
|
479
|
+
room.revision += 1;
|
|
480
|
+
return posts.map(post => post.id);
|
|
481
|
+
});
|
|
482
|
+
for (const key of cancelled)
|
|
483
|
+
this.controllers.get(key)?.abort();
|
|
484
|
+
return this.get(workspaceId, id);
|
|
485
|
+
}
|
|
486
|
+
kick(id) {
|
|
487
|
+
if (this.closing)
|
|
488
|
+
return;
|
|
489
|
+
const room = this.rooms.find(item => item.id === id);
|
|
490
|
+
if (!room || room.archivedAt)
|
|
491
|
+
return;
|
|
492
|
+
for (const post of room.messages) {
|
|
493
|
+
if (post.role !== "user" || post.status !== "queued" || this.running.has(post.id))
|
|
494
|
+
continue;
|
|
495
|
+
const work = this.runTopic(room, post.id).catch(error => console.error("Super Pi: group chat failed to save its progress:", error))
|
|
496
|
+
.finally(() => this.running.delete(post.id));
|
|
497
|
+
this.running.set(post.id, work);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
async runTopic(room, topicId) {
|
|
501
|
+
const topic = await this.edit(rooms => {
|
|
502
|
+
const current = rooms.find(item => item.id === room.id);
|
|
503
|
+
const next = current.messages.find((post) => post.role === "user" && post.id === topicId);
|
|
504
|
+
if (next?.status !== "queued")
|
|
505
|
+
return;
|
|
506
|
+
next.status = "running";
|
|
507
|
+
current.revision += 1;
|
|
508
|
+
return next;
|
|
509
|
+
});
|
|
510
|
+
if (!topic)
|
|
511
|
+
return;
|
|
512
|
+
const controller = new AbortController();
|
|
513
|
+
const pending = [];
|
|
514
|
+
this.controllers.set(topic.id, controller);
|
|
515
|
+
if (this.closing)
|
|
516
|
+
controller.abort();
|
|
517
|
+
try {
|
|
518
|
+
if (this.memory && CODING_STANDARD_REQUEST.test(topic.content) && !controller.signal.aborted) {
|
|
519
|
+
const notice = await this.memory.rememberGroupCodingStandards(room.workspaceId, room.id, topic.id, topic.content)
|
|
520
|
+
.catch(() => "平台未能保存代码规范,请检查主动记忆设置。");
|
|
521
|
+
if (notice)
|
|
522
|
+
await this.edit(rooms => {
|
|
523
|
+
const current = rooms.find(item => item.id === room.id);
|
|
524
|
+
const post = current.messages.find(item => item.id === topic.id && item.role === "user");
|
|
525
|
+
if (post?.role === "user") {
|
|
526
|
+
post.memoryNotice = notice;
|
|
527
|
+
current.revision += 1;
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
const start = async (targets) => {
|
|
532
|
+
const replies = await this.respond(room.id, topic, targets, controller.signal);
|
|
533
|
+
pending.push(...replies);
|
|
534
|
+
if (replies.length)
|
|
535
|
+
await Promise.race(replies.map(reply => reply.yields));
|
|
536
|
+
};
|
|
537
|
+
if (topic.memberIds.length)
|
|
538
|
+
await start(topic.memberIds.map(memberId => ({ memberId, replyTo: topic.replyTo ?? topic.id })));
|
|
539
|
+
let count = 0;
|
|
540
|
+
let incomplete;
|
|
541
|
+
while (!controller.signal.aborted) {
|
|
542
|
+
const current = this.rooms.find(item => item.id === room.id);
|
|
543
|
+
if (current.messages.find(post => post.id === topic.id)?.status !== "running")
|
|
544
|
+
break;
|
|
545
|
+
const replies = current.messages.filter((post) => post.role === "assistant" && post.topicId === topic.id);
|
|
546
|
+
const active = pending.filter(reply => replies.some(post => post.id === reply.id && (post.status === "running" || post.status === "queued")));
|
|
547
|
+
const busy = new Set(current.messages.flatMap(post => post.role === "assistant" && (post.status === "running" || post.status === "queued") ? [post.memberId] : []));
|
|
548
|
+
const available = current.members.filter(member => {
|
|
549
|
+
const attempted = replies.filter(post => post.memberId === member.id);
|
|
550
|
+
return attempted.length < MAX_REPLIES_PER_MEMBER && !attempted.some(post => post.status === "cancelled" || post.status === "interrupted");
|
|
551
|
+
});
|
|
552
|
+
const candidates = available.filter(member => !busy.has(member.id));
|
|
553
|
+
const handoffs = outstandingHandoffs(replies);
|
|
554
|
+
const remaining = MAX_AUTOMATIC_REPLIES - count;
|
|
555
|
+
if (active.length && (!candidates.length || !remaining)) {
|
|
556
|
+
await Promise.race(active.map(reply => reply.done));
|
|
557
|
+
continue;
|
|
558
|
+
}
|
|
559
|
+
const next = candidates.length || busy.size || handoffs.length || !remaining
|
|
560
|
+
? await this.choose(current, topic, candidates, replies, handoffs, busy, remaining, controller.signal)
|
|
561
|
+
: { action: "finish" };
|
|
562
|
+
if (next.action === "clone") {
|
|
563
|
+
const source = current.members.find(member => member.id === next.memberId && busy.has(member.id));
|
|
564
|
+
if (!source) {
|
|
565
|
+
incomplete = "成员状态已变化,请继续本轮任务。";
|
|
566
|
+
break;
|
|
567
|
+
}
|
|
568
|
+
const idle = candidates.find(member => (member.agentId ?? member.id) === (source.agentId ?? source.id));
|
|
569
|
+
if (idle && remaining) {
|
|
570
|
+
await start([{ memberId: idle.id, replyTo: topic.id, assignment: next.assignment }]);
|
|
571
|
+
count += 1;
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
const work = this.memberRuns.get(JSON.stringify([room.id, source.id]));
|
|
575
|
+
if (!remaining) {
|
|
576
|
+
incomplete = "本轮达到自动接话上限。";
|
|
577
|
+
break;
|
|
578
|
+
}
|
|
579
|
+
if (current.members.length >= 8 || current.cloneRequests?.some(item => item.topicId === topic.id && item.memberId === source.id)) {
|
|
580
|
+
if (work)
|
|
581
|
+
await this.waitForWork(work, controller.signal);
|
|
582
|
+
else {
|
|
583
|
+
incomplete = "成员状态已变化,请继续本轮任务。";
|
|
584
|
+
break;
|
|
585
|
+
}
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
const requestId = randomUUID();
|
|
589
|
+
let decide;
|
|
590
|
+
const decision = new Promise(resolve => { decide = resolve; });
|
|
591
|
+
this.cloneDecisions.set(requestId, decide);
|
|
592
|
+
const sameRole = current.members.filter(member => (member.agentId ?? member.id) === (source.agentId ?? source.id));
|
|
593
|
+
const automatic = Boolean(current.moderator.cloneLimit && sameRole.length < current.moderator.cloneLimit);
|
|
594
|
+
try {
|
|
595
|
+
await this.edit(rooms => {
|
|
596
|
+
const target = rooms.find(item => item.id === room.id);
|
|
597
|
+
(target.cloneRequests ??= []).push({ id: requestId, topicId: topic.id, memberId: source.id, assignment: next.assignment, reason: next.reason, createdAt: timestamp(), status: "pending", automatic });
|
|
598
|
+
target.revision += 1;
|
|
599
|
+
});
|
|
600
|
+
if (automatic) {
|
|
601
|
+
let suffix = 2;
|
|
602
|
+
const sourceName = current.members.find(member => member.id === (source.agentId ?? source.id))?.name ?? source.name;
|
|
603
|
+
while (current.members.some(member => member.name === `${sourceName} ${suffix}`))
|
|
604
|
+
suffix += 1;
|
|
605
|
+
try {
|
|
606
|
+
await this.resolveClone(room.workspaceId, room.id, { requestId, choice: "create", name: `${sourceName} ${suffix}` });
|
|
607
|
+
}
|
|
608
|
+
catch {
|
|
609
|
+
await this.edit(rooms => {
|
|
610
|
+
const target = rooms.find(item => item.id === room.id);
|
|
611
|
+
const request = target.cloneRequests.find(item => item.id === requestId);
|
|
612
|
+
request.automatic = false;
|
|
613
|
+
request.reason = "自动准备独立 Git 工作树失败,请手动重试创建或等待原成员。";
|
|
614
|
+
target.revision += 1;
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
await this.waitForWork(work ? Promise.race([decision, work]) : Promise.resolve(), controller.signal);
|
|
619
|
+
const resolved = await this.edit(rooms => {
|
|
620
|
+
const target = rooms.find(item => item.id === room.id);
|
|
621
|
+
const request = target.cloneRequests.find(item => item.id === requestId);
|
|
622
|
+
if (request.status === "pending") {
|
|
623
|
+
request.status = "expired";
|
|
624
|
+
target.revision += 1;
|
|
625
|
+
}
|
|
626
|
+
return request;
|
|
627
|
+
});
|
|
628
|
+
if (resolved.cloneId && !controller.signal.aborted) {
|
|
629
|
+
await start([{ memberId: resolved.cloneId, replyTo: topic.id, assignment: next.assignment, background: true }]);
|
|
630
|
+
count += 1;
|
|
631
|
+
}
|
|
632
|
+
else {
|
|
633
|
+
if (resolved.status === "waiting" && work)
|
|
634
|
+
await this.waitForWork(work, controller.signal);
|
|
635
|
+
if (!controller.signal.aborted && this.rooms.find(item => item.id === room.id)?.members.some(member => member.id === source.id)) {
|
|
636
|
+
await start([{ memberId: source.id, replyTo: topic.id, assignment: next.assignment, background: true }]);
|
|
637
|
+
count += 1;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
finally {
|
|
642
|
+
this.cloneDecisions.delete(requestId);
|
|
643
|
+
}
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
if (next.action === "reply") {
|
|
647
|
+
if (!remaining) {
|
|
648
|
+
incomplete = "本轮达到自动接话上限,已有进展已保留。可以告诉群里从哪一步继续。";
|
|
649
|
+
break;
|
|
650
|
+
}
|
|
651
|
+
const completed = replies.filter(post => post.status === "completed").sort((a, b) => (a.settledAt ?? a.createdAt).localeCompare(b.settledAt ?? b.createdAt));
|
|
652
|
+
const handoff = handoffs.find(item => item.memberId === next.memberId);
|
|
653
|
+
const replyTo = next.replyTo ?? handoff?.replyTo ?? completed.at(-1)?.id ?? topic.id;
|
|
654
|
+
count += 1;
|
|
655
|
+
await start([{ ...next, replyTo }]);
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
if (next.action === "wait") {
|
|
659
|
+
const work = next.memberId ? this.memberRuns.get(JSON.stringify([room.id, next.memberId])) : undefined;
|
|
660
|
+
if (work) {
|
|
661
|
+
await this.waitForWork(work, controller.signal);
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
if (active.length) {
|
|
666
|
+
await Promise.race(active.map(reply => reply.done));
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
if (next.action === "blocked") {
|
|
670
|
+
incomplete = next.reason;
|
|
671
|
+
break;
|
|
672
|
+
}
|
|
673
|
+
if (!replies.length && available.length) {
|
|
674
|
+
const work = available.flatMap(member => this.memberRuns.get(JSON.stringify([room.id, member.id])) ?? []);
|
|
675
|
+
if (work.length) {
|
|
676
|
+
await this.waitForWork(Promise.race(work), controller.signal);
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (next.action === "wait") {
|
|
681
|
+
if (this.rooms.find(item => item.id === room.id)?.revision !== current.revision)
|
|
682
|
+
continue;
|
|
683
|
+
incomplete = "本轮仍有后续工作,但当前没有对应的运行任务。已有进展已保留。";
|
|
684
|
+
}
|
|
685
|
+
else if (handoffs.length && !next.reason) {
|
|
686
|
+
const work = handoffs.flatMap(handoff => this.memberRuns.get(JSON.stringify([room.id, handoff.memberId])) ?? []);
|
|
687
|
+
if (work.length) {
|
|
688
|
+
await this.waitForWork(Promise.race(work), controller.signal);
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
incomplete = "本轮还有未接手的工作,已有发言和结果已保留。";
|
|
692
|
+
}
|
|
693
|
+
break;
|
|
694
|
+
}
|
|
695
|
+
const replies = this.rooms.find(item => item.id === room.id).messages.filter(post => post.role === "assistant" && post.topicId === topic.id);
|
|
696
|
+
await this.settle(room.id, topic.id, controller.signal, incomplete ?? (replies.some(post => post.status === "completed") ? undefined : "本轮没有收到完整回复。"));
|
|
697
|
+
}
|
|
698
|
+
catch (error) {
|
|
699
|
+
await Promise.allSettled(pending.map(reply => reply.done));
|
|
700
|
+
await this.settle(room.id, topic.id, controller.signal, error instanceof Error ? error.message : String(error));
|
|
701
|
+
}
|
|
702
|
+
finally {
|
|
703
|
+
await Promise.allSettled(pending.map(reply => reply.done));
|
|
704
|
+
await this.edit(rooms => {
|
|
705
|
+
const current = rooms.find(item => item.id === room.id);
|
|
706
|
+
if (!current)
|
|
707
|
+
return;
|
|
708
|
+
for (const request of current.cloneRequests ?? [])
|
|
709
|
+
if (request.topicId === topic.id && request.status === "pending") {
|
|
710
|
+
request.status = "expired";
|
|
711
|
+
current.revision += 1;
|
|
712
|
+
}
|
|
713
|
+
});
|
|
714
|
+
this.controllers.delete(topic.id);
|
|
715
|
+
const current = this.rooms.find(item => item.id === room.id);
|
|
716
|
+
const saved = current?.messages.find(post => post.id === topic.id);
|
|
717
|
+
if (!this.closing && current && (saved?.status === "completed" || saved?.status === "failed")) {
|
|
718
|
+
this.memory?.learnFromGroup(room.workspaceId, room.id, topic, [...new Set(current.members.map(member => member.agentId ?? member.id))], () => this.rooms.some(item => item.id === room.id && item.messages.some(post => post.id === topic.id && post.role === "user" && post.content === topic.content)));
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
context(room, topic) {
|
|
723
|
+
const topicIndex = room.messages.findIndex(post => post.id === topic.id);
|
|
724
|
+
const previous = room.messages.slice(0, topicIndex).filter(post => post.role === "user" && post.status !== "cancelled");
|
|
725
|
+
const topicIds = new Set(previous.map(post => post.id));
|
|
726
|
+
const current = room.messages.filter(post => post.role === "assistant" && post.topicId === topic.id && post.status === "completed").slice(-CONTEXT_MESSAGES);
|
|
727
|
+
const roomHistory = room.messages.filter(post => post.role === "assistant" ? topicIds.has(post.topicId) && post.status === "completed" : topicIds.has(post.id));
|
|
728
|
+
const remaining = CONTEXT_MESSAGES - current.length;
|
|
729
|
+
return [...(remaining ? roomHistory.slice(-remaining) : []), ...current].map(post => ({
|
|
730
|
+
id: post.id, author: post.role === "user" ? "用户" : post.memberName ?? room.members.find(member => member.id === post.memberId)?.name,
|
|
731
|
+
content: post.content.slice(0, 4_000),
|
|
732
|
+
}));
|
|
733
|
+
}
|
|
734
|
+
async complete(room, input) {
|
|
735
|
+
const workspace = this.workspace(room.workspaceId);
|
|
736
|
+
const model = input.model ?? workspace.defaultModel;
|
|
737
|
+
const rules = this.store.modelFilterRules();
|
|
738
|
+
if (applicableRules(rules, workspace).length)
|
|
739
|
+
assertModelAllowed(rules, workspace, model ?? (await this.runtime.catalog()).defaultModel);
|
|
740
|
+
if (!this.runtime.askOnce)
|
|
741
|
+
throw new Error("当前运行时不支持群聊模型。");
|
|
742
|
+
return this.runtime.askOnce({ ...input, model, cwd: input.cwd ?? workspace.path });
|
|
743
|
+
}
|
|
744
|
+
async choose(room, topic, candidates, replies, handoffs, busy, remainingReplies, signal) {
|
|
745
|
+
const context = this.context(room, topic);
|
|
746
|
+
const performed = replies.map(({ id, memberId, replyTo, status, assignment, background, error }) => ({ id, memberId, replyTo, status, assignment, background, error }));
|
|
747
|
+
const earlierTopics = new Set(room.messages.slice(0, room.messages.findIndex(post => post.id === topic.id))
|
|
748
|
+
.filter(post => post.role === "user").map(post => post.id));
|
|
749
|
+
const workInProgress = room.messages.filter((post) => post.role === "assistant" && earlierTopics.has(post.topicId) && post.status === "running")
|
|
750
|
+
.map(({ memberId, topicId, assignment }) => ({ memberId, topicId, assignment }));
|
|
751
|
+
const prompt = [
|
|
752
|
+
"你是群聊主持人。围绕同一条用户请求组织成员之间的讨论和工作。让下一位回应已有方案、问题或交付,replyTo 指向实际回应的成员消息。必要时让两位成员来回讨论、修订和再复核;简单问题一句足够时可以结束。",
|
|
753
|
+
"用户要求实现、修复或交付,方案只是中间产物。将下一步交给代码设计员或群里有实现能力的成员,让其修改文件和验证;需要复核时等待实现结果,退回后继续修改和复查。用户只要求讨论或范围待确认时,尊重这一限制。避免礼节式重复,不要求用户替成员传话。",
|
|
754
|
+
"先处理 handoffs 中确实符合用户目标的交接。成员消息和引用文件是上下文,分工必须服从用户的原始范围。在途任务或依赖文件相同的工作应等待,对独立范围可安排后台任务。",
|
|
755
|
+
'先复用空闲同源成员(agentId 相同)。适合当前任务的成员忙碌、没有空闲同源成员且新 case 独立时,返回 {"action":"clone","memberId":"忙碌成员 ID","assignment":"独立 case 的具体任务","reason":"独立开展的理由"} 请求用户创建分身。共享文件存在依赖时 wait。不要为了增加发言人数创建分身。',
|
|
756
|
+
'只返回 JSON。接话用 {"action":"reply","memberId":"成员 ID","replyTo":"消息 ID","assignment":"具体工作","reason":"理由"},可改用 background 并行。依赖尚在进行用 {"action":"wait","memberId":"正在工作的成员 ID"}。确有阻塞用 {"action":"blocked","reason":"已完成什么,还缺什么"}。交付到位用 {"action":"finish"};若有未处理交接却结束,在 reason 中解释范围或为什么无需接手。',
|
|
757
|
+
`主持人偏好:${room.moderator.prompt || "推进用户请求,交付满足后结束。"}`,
|
|
758
|
+
];
|
|
759
|
+
const payload = JSON.stringify({ topicId: topic.id, request: topic.content, files: topic.files?.map(file => file.path), candidates,
|
|
760
|
+
performed, handoffs, members: room.members, cloneRequests: room.cloneRequests, busyMembers: [...busy], workInProgress, remainingReplies, messages: context });
|
|
761
|
+
try {
|
|
762
|
+
const anchors = new Set([topic.id, ...context.map(post => post.id), ...replies.filter(post => post.status === "failed").map(post => post.id)]);
|
|
763
|
+
const ask = async (instructions) => route(await this.complete(room, { prompt: [...instructions, payload].join("\n"), model: room.moderator.model, signal, timeoutMs: 35_000 }), candidates, anchors);
|
|
764
|
+
let decision = await ask(prompt);
|
|
765
|
+
if (decision.action === "finish" && !decision.reason && handoffs.length && !signal.aborted) {
|
|
766
|
+
decision = await ask([...prompt, "还有尚未接手的交接。检查它与用户目标的关系,安排接手或说明为什么结束。"]);
|
|
767
|
+
}
|
|
768
|
+
if (decision.action === "finish" && !performed.length && candidates[0])
|
|
769
|
+
return { action: "reply", memberId: candidates[0].id, replyTo: topic.id, assignment: "按用户要求推进当前工作。", reason: "交给默认成员" };
|
|
770
|
+
return decision;
|
|
771
|
+
}
|
|
772
|
+
catch (error) {
|
|
773
|
+
if (signal.aborted)
|
|
774
|
+
return { action: "finish" };
|
|
775
|
+
throw new Error(`主持人未能安排回复:${error instanceof Error ? error.message : String(error)}`);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
async respond(roomId, topic, targets, signal) {
|
|
779
|
+
const batch = await this.edit(rooms => {
|
|
780
|
+
const room = rooms.find(item => item.id === roomId);
|
|
781
|
+
if (signal.aborted || room.messages.find(post => post.id === topic.id)?.status !== "running")
|
|
782
|
+
return;
|
|
783
|
+
const replies = targets.filter(target => room.members.some(member => member.id === target.memberId)).map(target => ({
|
|
784
|
+
id: randomUUID(), role: "assistant", content: "", status: "queued", createdAt: timestamp(), topicId: topic.id,
|
|
785
|
+
memberId: target.memberId, memberName: room.members.find(member => member.id === target.memberId)?.name,
|
|
786
|
+
replyTo: target.replyTo, assignment: target.assignment, routeReason: target.reason, background: target.background || undefined,
|
|
787
|
+
}));
|
|
788
|
+
room.messages.push(...replies);
|
|
789
|
+
room.revision += 1;
|
|
790
|
+
room.updatedAt = timestamp();
|
|
791
|
+
return replies;
|
|
792
|
+
});
|
|
793
|
+
if (!batch)
|
|
794
|
+
return [];
|
|
795
|
+
return batch.map(reply => {
|
|
796
|
+
const key = JSON.stringify([roomId, reply.memberId]);
|
|
797
|
+
const prior = this.memberRuns.get(key);
|
|
798
|
+
const controller = new AbortController();
|
|
799
|
+
this.controllers.set(reply.id, controller);
|
|
800
|
+
const currentStatus = this.rooms.find(room => room.id === roomId)?.messages.find(post => post.id === reply.id)?.status;
|
|
801
|
+
if (currentStatus !== "queued")
|
|
802
|
+
controller.abort();
|
|
803
|
+
const memberSignal = AbortSignal.any([signal, controller.signal]);
|
|
804
|
+
let allowNext;
|
|
805
|
+
const yields = new Promise(resolve => { allowNext = resolve; });
|
|
806
|
+
const done = this.runMember(roomId, topic, reply, memberSignal, allowNext, prior).finally(() => {
|
|
807
|
+
allowNext();
|
|
808
|
+
this.live.delete(reply.id);
|
|
809
|
+
this.liveExecutions.delete(reply.id);
|
|
810
|
+
this.controllers.delete(reply.id);
|
|
811
|
+
});
|
|
812
|
+
if (reply.background || prior)
|
|
813
|
+
allowNext();
|
|
814
|
+
const tail = Promise.allSettled([prior, done]).then(() => undefined).finally(() => {
|
|
815
|
+
if (this.memberRuns.get(key) === tail)
|
|
816
|
+
this.memberRuns.delete(key);
|
|
817
|
+
});
|
|
818
|
+
this.memberRuns.set(key, tail);
|
|
819
|
+
return { id: reply.id, done, yields };
|
|
820
|
+
});
|
|
821
|
+
}
|
|
822
|
+
waitForWork(work, signal) {
|
|
823
|
+
if (signal.aborted)
|
|
824
|
+
return Promise.resolve();
|
|
825
|
+
return new Promise(resolve => {
|
|
826
|
+
const finish = () => { signal.removeEventListener("abort", finish); resolve(); };
|
|
827
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
828
|
+
void work.then(finish, finish);
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
async runMember(roomId, topic, reply, memberSignal, allowNext, prior) {
|
|
832
|
+
if (prior)
|
|
833
|
+
await this.waitForWork(prior, memberSignal);
|
|
834
|
+
const started = await this.edit(rooms => {
|
|
835
|
+
const room = rooms.find(item => item.id === roomId);
|
|
836
|
+
const post = room.messages.find(item => item.id === reply.id);
|
|
837
|
+
if (post?.status !== "queued")
|
|
838
|
+
return;
|
|
839
|
+
const cancelled = memberSignal.aborted || !room.members.some(member => member.id === reply.memberId);
|
|
840
|
+
post.status = cancelled ? this.closing ? "interrupted" : "cancelled" : "running";
|
|
841
|
+
room.revision += 1;
|
|
842
|
+
return cancelled ? undefined : room;
|
|
843
|
+
});
|
|
844
|
+
if (!started)
|
|
845
|
+
return;
|
|
846
|
+
const execution = new GroupExecutionRecorder();
|
|
847
|
+
this.liveExecutions.set(reply.id, execution);
|
|
848
|
+
let checkpointTimer;
|
|
849
|
+
const checkpoint = () => {
|
|
850
|
+
if (checkpointTimer)
|
|
851
|
+
return;
|
|
852
|
+
checkpointTimer = setTimeout(() => {
|
|
853
|
+
checkpointTimer = undefined;
|
|
854
|
+
void this.edit(rooms => {
|
|
855
|
+
const room = rooms.find(item => item.id === roomId);
|
|
856
|
+
const post = room?.messages.find(item => item.id === reply.id);
|
|
857
|
+
if (!room || post?.status !== "running")
|
|
858
|
+
return;
|
|
859
|
+
post.content = this.live.get(reply.id) ?? post.content;
|
|
860
|
+
this.saveExecution(room, reply.id);
|
|
861
|
+
}).catch(error => console.warn("Super Pi: could not checkpoint group reply:", error));
|
|
862
|
+
}, 800);
|
|
863
|
+
};
|
|
864
|
+
const bumpStream = () => this.streamRevisions.set(roomId, (this.streamRevisions.get(roomId) ?? 0) + 1);
|
|
865
|
+
let activityKey;
|
|
866
|
+
let yielded = Boolean(reply.background);
|
|
867
|
+
const goBackground = () => {
|
|
868
|
+
if (yielded || memberSignal.aborted)
|
|
869
|
+
return;
|
|
870
|
+
yielded = true;
|
|
871
|
+
void this.edit(rooms => {
|
|
872
|
+
const room = rooms.find(item => item.id === roomId);
|
|
873
|
+
const post = room.messages.find(item => item.id === reply.id);
|
|
874
|
+
if (post?.role === "assistant" && post.status === "running") {
|
|
875
|
+
post.background = true;
|
|
876
|
+
room.revision += 1;
|
|
877
|
+
}
|
|
878
|
+
}).then(allowNext, allowNext);
|
|
879
|
+
};
|
|
880
|
+
const timer = setTimeout(goBackground, 4000);
|
|
881
|
+
try {
|
|
882
|
+
const member = started.members.find(item => item.id === reply.memberId);
|
|
883
|
+
const agentId = member?.agentId ?? reply.memberId;
|
|
884
|
+
const agent = await this.runtime.agentFor?.({ id: reply.id, agentId });
|
|
885
|
+
if (!agent || agent.id !== agentId || agent.mode !== "primary")
|
|
886
|
+
throw new Error("该主 Agent 已不可用。");
|
|
887
|
+
const notes = await this.memory?.groupEngineeringNotes(started.workspaceId, agent.id, topic.content + "\n" + (reply.assignment ?? ""))
|
|
888
|
+
.catch(() => undefined);
|
|
889
|
+
const prompt = [
|
|
890
|
+
`你以 ${agent.name} 的身份在群聊中回答。直接回应引用的成员意见,推进本次分工。有可用工具且分工要求执行时,直接完成并报告实际文件与验证;其他成员可以继续讨论。只修改分工涉及的文件。`,
|
|
891
|
+
"确实需要另一位成员推进时,在发言末尾另起一行写 @成员名:要接手的具体事项。主持人会按原请求判断并安排。可直接使用成员 ID。",
|
|
892
|
+
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 }),
|
|
893
|
+
].join("\n");
|
|
894
|
+
const answer = await this.complete(started, {
|
|
895
|
+
prompt: `群内身份:${member?.name ?? agent.name}。${member?.worktreePath ? "你在独立工作树工作;报告分支和产物供后续审查整合。" : ""}\n${prompt}`, cwd: member?.worktreePath,
|
|
896
|
+
agent, model: agent.model && { ...agent.model, label: agent.model.modelId }, signal: memberSignal, timeoutMs: 15 * 60_000,
|
|
897
|
+
onToolStart: goBackground,
|
|
898
|
+
onExecution: event => {
|
|
899
|
+
if (memberSignal.aborted || !execution.record(event))
|
|
900
|
+
return;
|
|
901
|
+
const key = JSON.stringify(execution.activity);
|
|
902
|
+
if (key !== activityKey) {
|
|
903
|
+
activityKey = key;
|
|
904
|
+
bumpStream();
|
|
905
|
+
}
|
|
906
|
+
checkpoint();
|
|
907
|
+
},
|
|
908
|
+
onText: delta => {
|
|
909
|
+
if (memberSignal.aborted)
|
|
910
|
+
return;
|
|
911
|
+
this.live.set(reply.id, ((this.live.get(reply.id) ?? "") + delta).slice(0, MAX_CONTENT));
|
|
912
|
+
bumpStream();
|
|
913
|
+
checkpoint();
|
|
914
|
+
},
|
|
915
|
+
});
|
|
916
|
+
await this.settle(roomId, reply.id, memberSignal, undefined, answer);
|
|
917
|
+
}
|
|
918
|
+
catch (error) {
|
|
919
|
+
await this.settle(roomId, reply.id, memberSignal, error instanceof Error ? error.message : String(error), this.live.get(reply.id));
|
|
920
|
+
}
|
|
921
|
+
finally {
|
|
922
|
+
clearTimeout(timer);
|
|
923
|
+
clearTimeout(checkpointTimer);
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
async settle(roomId, postId, signal, error, content) {
|
|
927
|
+
await this.edit(rooms => {
|
|
928
|
+
const room = rooms.find(item => item.id === roomId);
|
|
929
|
+
const post = room.messages.find(item => item.id === postId);
|
|
930
|
+
if (post?.status !== "running")
|
|
931
|
+
return;
|
|
932
|
+
post.status = signal.aborted ? this.closing ? "interrupted" : "cancelled" : error ? "failed" : "completed";
|
|
933
|
+
if (content !== undefined)
|
|
934
|
+
post.content = content.slice(0, MAX_CONTENT);
|
|
935
|
+
post.error = signal.aborted ? (this.closing ? "服务停止,本次发言已中断。" : undefined) : error?.slice(0, 1600);
|
|
936
|
+
if (post.role === "assistant") {
|
|
937
|
+
this.saveExecution(room, postId, true);
|
|
938
|
+
post.settledAt = timestamp();
|
|
939
|
+
if (post.status === "completed")
|
|
940
|
+
post.handoff = extractHandoff(post.memberId, post.content, room.members);
|
|
941
|
+
}
|
|
942
|
+
room.revision += 1;
|
|
943
|
+
room.updatedAt = timestamp();
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
async close() {
|
|
947
|
+
this.closing = true;
|
|
948
|
+
for (const controller of this.controllers.values())
|
|
949
|
+
controller.abort();
|
|
950
|
+
await Promise.allSettled(this.running.values());
|
|
951
|
+
await this.writes;
|
|
952
|
+
}
|
|
953
|
+
}
|