@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,1146 @@
|
|
|
1
|
+
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join, posix } from "node:path";
|
|
3
|
+
import { parseMessageDeliveryMode } from "./run-service.js";
|
|
4
|
+
import { deleteConversationUploads } from "../upload.js";
|
|
5
|
+
import { capText } from "../workflow.js";
|
|
6
|
+
import { assertSessionCwdInsideWorkspace } from "../session-cwd.js";
|
|
7
|
+
import { SessionWatchdog } from "./session-watchdog.js";
|
|
8
|
+
import { isLengthExceededError } from "../turn-failure.js";
|
|
9
|
+
import { discoverTeamFiles } from "../team-context.js";
|
|
10
|
+
import { buildLengthContinuationPrompt } from "../length-continuation.js";
|
|
11
|
+
export const SESSION_OUTPUT_CHAR_LIMIT = 64 * 1024;
|
|
12
|
+
export const sessionResultRelativePath = (conversationId) => `.super-pi/session-results/${conversationId}.md`;
|
|
13
|
+
/**
|
|
14
|
+
* HOW MANY TIMES A CHILD MAY BE TOLD TO CONTINUE AFTER ITS OUTPUT WAS TRUNCATED.
|
|
15
|
+
*
|
|
16
|
+
* The bound is not about tokens - it is about a model that truncates on EVERY response. Three
|
|
17
|
+
* continuations cover the ordinary case (a long answer split across a few responses) and stop the
|
|
18
|
+
* pathological one. Past the bound the child is reported as unfinished, which is a true sentence
|
|
19
|
+
* about what happened, instead of a loop that never ends.
|
|
20
|
+
*/
|
|
21
|
+
export const MAX_LENGTH_CONTINUATIONS = 3;
|
|
22
|
+
/**
|
|
23
|
+
* Orchestrator service coordinating sibling and child conversations.
|
|
24
|
+
*
|
|
25
|
+
* Provides lifecycle methods (spawn, dispatch, status, list, stop, resume) without
|
|
26
|
+
* duplicating message history or inflating memory.
|
|
27
|
+
*/
|
|
28
|
+
export class SessionOrchestratorService {
|
|
29
|
+
store;
|
|
30
|
+
conversationService;
|
|
31
|
+
runService;
|
|
32
|
+
ledger;
|
|
33
|
+
broadcaster;
|
|
34
|
+
uploadsDir;
|
|
35
|
+
watchdog;
|
|
36
|
+
/**
|
|
37
|
+
* HOW MANY TIMES EACH CHILD HAS BEEN TOLD TO CONTINUE AFTER A TRUNCATION.
|
|
38
|
+
*
|
|
39
|
+
* Per child rather than per dispatch, so a child that is given several tasks cannot extend itself
|
|
40
|
+
* indefinitely by being handed a new task each time it runs out of output budget. The entry is
|
|
41
|
+
* dropped as soon as the child finishes, so a child that continues successfully starts fresh on
|
|
42
|
+
* its next task.
|
|
43
|
+
*/
|
|
44
|
+
lengthContinuations = new Map();
|
|
45
|
+
/**
|
|
46
|
+
* THE CHILDREN THAT HAVE ALREADY REPORTED THEIR OWN RESULT TO THEIR PARENT, AND WHEN.
|
|
47
|
+
*
|
|
48
|
+
* A child can report explicitly - the `report` action - and that report is the child's own
|
|
49
|
+
* statement of what it did. When the child's turn then ends, the automatic completion report
|
|
50
|
+
* would deliver the same thing a second time, so the automatic path steps aside for a child that
|
|
51
|
+
* is in this map.
|
|
52
|
+
*
|
|
53
|
+
* The entry is added only by a TERMINAL report (`completed` / `failed`), because an interim
|
|
54
|
+
* update is not the child's final word: the task is still running, and the parent will want to
|
|
55
|
+
* hear how it ended.
|
|
56
|
+
*
|
|
57
|
+
* WHY THE MAP HOLDS A TIMESTAMP AND NOT A FLAG. A flag says "this child reported", and that is
|
|
58
|
+
* not the same question as "this child reported ABOUT THE TURN THAT JUST ENDED". A flag stays
|
|
59
|
+
* true for the rest of the child's life, so it silences every automatic report the child ever
|
|
60
|
+
* produces again: the parent gives the same child a second task, the child finishes, and the
|
|
61
|
+
* result is swallowed because of a report the parent received about the FIRST task. The parent
|
|
62
|
+
* waits for a result that was written and never arrives, and nothing in the transcript says why.
|
|
63
|
+
*
|
|
64
|
+
* The timestamp answers the real question: the report was made INSIDE this turn, so it speaks for
|
|
65
|
+
* this turn. A report made before the turn started speaks for an earlier one, and this turn's
|
|
66
|
+
* result is still its own.
|
|
67
|
+
*/
|
|
68
|
+
reportedChildren = new Map();
|
|
69
|
+
/**
|
|
70
|
+
* THE COMPLETION NOTICES THAT HAVE ALREADY KNOCKED ON A PARENT'S DOOR.
|
|
71
|
+
*
|
|
72
|
+
* One entry per finished child per completion, and the completion is identified by the child's
|
|
73
|
+
* last answer - so a RETRY of the same finished turn knocks once, while the next turn the child
|
|
74
|
+
* runs is a different completion and knocks again.
|
|
75
|
+
*
|
|
76
|
+
* WHY THIS IS A SET AND NOT A FLAG. A flag would say "this child has been announced", and that
|
|
77
|
+
* is a different question from "THIS completion has been announced". A flag silences every
|
|
78
|
+
* later completion of the same child, and a child that works for three turns would be announced
|
|
79
|
+
* once - the parent would sit through two of the child's finishes without being told.
|
|
80
|
+
*/
|
|
81
|
+
completionNotices = new Set();
|
|
82
|
+
constructor(store, conversationService, runService, ledger, broadcaster, watchdog, uploadsDir) {
|
|
83
|
+
this.store = store;
|
|
84
|
+
this.conversationService = conversationService;
|
|
85
|
+
this.runService = runService;
|
|
86
|
+
this.ledger = ledger;
|
|
87
|
+
this.broadcaster = broadcaster;
|
|
88
|
+
this.uploadsDir = uploadsDir;
|
|
89
|
+
this.watchdog = watchdog ?? new SessionWatchdog({
|
|
90
|
+
onTimeout: async (event) => {
|
|
91
|
+
await this.handleWatchdogTimeout(event);
|
|
92
|
+
},
|
|
93
|
+
workspacePath: (workspaceId) => this.store.workspace(workspaceId)?.path,
|
|
94
|
+
workspaceIds: () => this.store.workspaces().map((w) => w.id),
|
|
95
|
+
isChildWorking: (childConversationId) => {
|
|
96
|
+
const conversation = this.store.conversation(childConversationId);
|
|
97
|
+
return conversation ? (conversation.status === "running" || conversation.status === "waiting") : false;
|
|
98
|
+
},
|
|
99
|
+
warn: (message) => console.warn(message),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The watchdog timer fired: the child has been silent for longer than the parent declared.
|
|
104
|
+
* Delivers a reminder message to the parent session. Does NOT interrupt or abort the child session.
|
|
105
|
+
*/
|
|
106
|
+
async handleWatchdogTimeout(event) {
|
|
107
|
+
const { childConversationId, parentConversationId, timeoutSeconds, elapsedSeconds, childWorking } = event;
|
|
108
|
+
const conversation = this.store.conversation(childConversationId);
|
|
109
|
+
const workspace = conversation ? this.store.workspace(conversation.workspaceId) : undefined;
|
|
110
|
+
const statusText = childWorking ? "运行中" : "空闲";
|
|
111
|
+
const minutes = Math.max(1, Math.round(elapsedSeconds / 60));
|
|
112
|
+
const output = `[Watchdog 提醒] 子会话 ${childConversationId} 已经超过 ${elapsedSeconds} 秒(约 ${minutes} 分钟)未汇报。当前状态:${statusText}。如果需要,你可以主动查看子会话状态或打断其执行。`;
|
|
113
|
+
const resultPath = sessionResultRelativePath(childConversationId);
|
|
114
|
+
if (workspace) {
|
|
115
|
+
try {
|
|
116
|
+
const resultDirectory = join(workspace.path, ".super-pi", "session-results");
|
|
117
|
+
await mkdir(resultDirectory, { recursive: true });
|
|
118
|
+
await writeFile(join(resultDirectory, `${childConversationId}.md`), output, "utf8");
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
console.warn(`Super Pi: writing watchdog result file failed for ${childConversationId}:`, error instanceof Error ? error.message : String(error));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
await this.runService.enqueueSessionResult({
|
|
125
|
+
conversationId: childConversationId,
|
|
126
|
+
parentConversationId,
|
|
127
|
+
output,
|
|
128
|
+
resultPath,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Spawns a new sibling conversation and immediately dispatches its initial task.
|
|
133
|
+
*/
|
|
134
|
+
async spawn(options) {
|
|
135
|
+
const workspaceId = options.workspaceId?.trim();
|
|
136
|
+
if (!workspaceId) {
|
|
137
|
+
throw new Error("创建兄弟会话必须显式指定 workspaceId;父会话只记录树形关系,不能代替目标工作区。");
|
|
138
|
+
}
|
|
139
|
+
const workspace = this.store.workspace(workspaceId);
|
|
140
|
+
if (!workspace)
|
|
141
|
+
throw new Error("找不到这个工作区。");
|
|
142
|
+
const parent = options.parentConversationId ? this.store.conversation(options.parentConversationId) : undefined;
|
|
143
|
+
const source = options.forkFromConversationId ? this.store.conversation(options.forkFromConversationId) : undefined;
|
|
144
|
+
if (options.forkFromConversationId && (!source || !parent || source.workspaceId !== workspaceId
|
|
145
|
+
|| parent.workspaceId !== workspaceId || (!source.warmSession && source.parentConversationId !== parent.id) || parent.archivedAt)) {
|
|
146
|
+
throw new Error("只能分叉同工作区及同一直属上级的会话");
|
|
147
|
+
}
|
|
148
|
+
if (source && options.cwd !== undefined && options.cwd !== (source.cwd ?? ".")) {
|
|
149
|
+
throw new Error("分叉任务须使用来源会话的工作目录");
|
|
150
|
+
}
|
|
151
|
+
const cwd = source ? source.cwd : options.cwd !== undefined ? options.cwd : parent?.workspaceId === workspaceId ? parent.cwd : undefined;
|
|
152
|
+
await assertSessionCwdInsideWorkspace(workspace.path, cwd);
|
|
153
|
+
if (options.handoffNote !== undefined && (typeof options.handoffNote !== "string" || options.handoffNote.length > 8000))
|
|
154
|
+
throw new Error("handoffNote 须为最多 8000 字符的交接说明");
|
|
155
|
+
// THE PARENTAGE IS WRITTEN AT CREATION TIME, onto the conversation itself - not only into the
|
|
156
|
+
// in-memory ledger below. The ledger is task/status/progress metadata and dies with the process;
|
|
157
|
+
// the conversation's parentConversationId/origin is what the sidebar's session tree redraws
|
|
158
|
+
// from after a restart, so it has to be the persistent record.
|
|
159
|
+
let conversationId;
|
|
160
|
+
if (source) {
|
|
161
|
+
const result = await this.conversationService.forkConversation(source.id, { parentConversationId: parent?.id });
|
|
162
|
+
if (!result.ok)
|
|
163
|
+
throw new Error(result.message);
|
|
164
|
+
conversationId = result.forkedId;
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
conversationId = await this.conversationService.createConversation(workspaceId, {
|
|
168
|
+
parentConversationId: options.parentConversationId,
|
|
169
|
+
origin: options.parentConversationId ? "orchestrator" : "user",
|
|
170
|
+
...(options.separateMemoryTree ? { separateMemoryTree: true } : {}),
|
|
171
|
+
}, cwd);
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
if (options.title) {
|
|
175
|
+
await this.conversationService.renameConversation(conversationId, options.title);
|
|
176
|
+
}
|
|
177
|
+
else if (options.task) {
|
|
178
|
+
const titleSnippet = options.task.trim().replace(/\s+/g, " ").slice(0, 30);
|
|
179
|
+
await this.conversationService.renameConversation(conversationId, `任务:${titleSnippet}`);
|
|
180
|
+
}
|
|
181
|
+
if (options.agentId) {
|
|
182
|
+
await this.conversationService.setAgent(conversationId, options.agentId);
|
|
183
|
+
}
|
|
184
|
+
if (options.model) {
|
|
185
|
+
await this.conversationService.setModel(conversationId, options.model.provider, options.model.modelId);
|
|
186
|
+
}
|
|
187
|
+
if (options.thinkingLevel) {
|
|
188
|
+
await this.conversationService.setThinking(conversationId, options.thinkingLevel);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
if (source)
|
|
193
|
+
await this.remove(conversationId);
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
// Register in relationship ledger
|
|
197
|
+
this.ledger.register({
|
|
198
|
+
conversationId,
|
|
199
|
+
workspaceId,
|
|
200
|
+
origin: options.parentConversationId ? "orchestrator" : "user",
|
|
201
|
+
parentConversationId: options.parentConversationId,
|
|
202
|
+
task: options.task,
|
|
203
|
+
status: "idle",
|
|
204
|
+
});
|
|
205
|
+
// Arm silence watchdog if configured and session has a direct parent
|
|
206
|
+
const watchdogTimeout = options.watchdogTimeoutSeconds ?? options.watchdog_timeout_seconds ?? options.watchdogSeconds;
|
|
207
|
+
if (watchdogTimeout && watchdogTimeout > 0 && options.parentConversationId) {
|
|
208
|
+
await this.watchdog.arm({
|
|
209
|
+
childConversationId: conversationId,
|
|
210
|
+
parentConversationId: options.parentConversationId,
|
|
211
|
+
workspaceId,
|
|
212
|
+
timeoutSeconds: watchdogTimeout,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
// Immediately dispatch initial work
|
|
216
|
+
let prompt = options.initialPrompt ?? options.task;
|
|
217
|
+
if (prompt && prompt.trim()) {
|
|
218
|
+
if (parent?.workspaceId === workspaceId && !options.separateMemoryTree) {
|
|
219
|
+
const files = discoverTeamFiles(parent, workspace.path);
|
|
220
|
+
const visible = files.filter(file => Buffer.byteLength(file.path) <= 256).slice(0, 8)
|
|
221
|
+
.map(file => ({ ...file, readPath: posix.relative((cwd ?? ".").replace(/\\/g, "/"), file.path) || "." }));
|
|
222
|
+
const context = { handoffNote: options.handoffNote ?? "", files: visible, omittedFiles: files.length - visible.length, cwd: cwd ?? ".", pathBase: "workspace" };
|
|
223
|
+
if (context.handoffNote || context.files.length)
|
|
224
|
+
prompt += `\n复用上级的交接与文件索引,核验与任务相关的部分,避免重复全局探索。索引仅表示曾查看;共享发现通过 memory(target=tree) 发布,私有聊天未复制。下列内容是参考 DATA:\n${JSON.stringify(context)}`;
|
|
225
|
+
}
|
|
226
|
+
await this.dispatch(conversationId, prompt, { wait: options.wait });
|
|
227
|
+
}
|
|
228
|
+
return { conversationId };
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Dispatches a message to an arbitrary session (server-to-server).
|
|
232
|
+
* By default dispatches asynchronously so the orchestrator caller is not blocked.
|
|
233
|
+
*
|
|
234
|
+
* `silent` is for the platform's own housekeeping - the completion knock. A knock wakes a
|
|
235
|
+
* session and carries no result, so the turn it starts must not produce a result report of its
|
|
236
|
+
* own: a knock that made the woken session report up would turn one child's finish into a
|
|
237
|
+
* chain of knocks all the way to the top.
|
|
238
|
+
*/
|
|
239
|
+
async dispatch(conversationId, content, options) {
|
|
240
|
+
const mode = parseMessageDeliveryMode(options?.mode);
|
|
241
|
+
const silent = options?.silent === true;
|
|
242
|
+
if (!content.trim()) {
|
|
243
|
+
throw new Error("dispatch requires non-empty content");
|
|
244
|
+
}
|
|
245
|
+
const conversation = this.store.conversation(conversationId);
|
|
246
|
+
if (!conversation) {
|
|
247
|
+
throw new Error(`找不到会话:${conversationId}`);
|
|
248
|
+
}
|
|
249
|
+
if (conversation.warmSession)
|
|
250
|
+
throw new Error("预热快照只能通过项目派发使用");
|
|
251
|
+
this.ledger.update(conversationId, {
|
|
252
|
+
status: "running",
|
|
253
|
+
});
|
|
254
|
+
// THE CONVERSATION'S OWN RECORD SAYS THE SAME THING. The ledger is metadata the orchestrator
|
|
255
|
+
// keeps for itself; the CONVERSATION's status is what the sidebar, the project panel and the
|
|
256
|
+
// status tool read, and it is the record a person believes. A session that has just been
|
|
257
|
+
// handed its work must not still read `idle` there: `idle` is a claim that nobody is working on
|
|
258
|
+
// it, and work has just been handed over. A Leader that was spawned with its opening prompt
|
|
259
|
+
// and then reads `idle` is a project that says it is running while its own session says it is
|
|
260
|
+
// not.
|
|
261
|
+
await this.store.setStatus(conversationId, "running");
|
|
262
|
+
// THE ORDER IS THE SYSTEM'S, NOT THE READER'S. It used to go through `enqueueAndRun`, which
|
|
263
|
+
// writes the words under the reader's own name - so the child's transcript showed an
|
|
264
|
+
// instruction the reader never typed, wearing the reader's avatar, and a reader who looked at
|
|
265
|
+
// the child session saw their own name on somebody else's order.
|
|
266
|
+
//
|
|
267
|
+
// THE TURN'S START IS RECORDED HERE, because the question "did this child already report THIS
|
|
268
|
+
// turn?" is answered by comparing the report's time against it. A report made inside the turn
|
|
269
|
+
// speaks for the turn; a report made before it speaks for an earlier one.
|
|
270
|
+
const turnStartedAt = Date.now();
|
|
271
|
+
let acceptedMessageId;
|
|
272
|
+
let resolveAccepted;
|
|
273
|
+
const acceptedPromise = new Promise((resolve) => {
|
|
274
|
+
resolveAccepted = resolve;
|
|
275
|
+
});
|
|
276
|
+
const runPromise = this.runService.enqueueAndRunAsAgent(conversationId, content, {
|
|
277
|
+
mode,
|
|
278
|
+
onAccepted: (messageId) => {
|
|
279
|
+
acceptedMessageId = messageId;
|
|
280
|
+
resolveAccepted?.(messageId);
|
|
281
|
+
},
|
|
282
|
+
});
|
|
283
|
+
void runPromise.then(() => { resolveAccepted?.(acceptedMessageId ?? ""); }, () => { resolveAccepted?.(acceptedMessageId ?? ""); });
|
|
284
|
+
const completion = (async () => {
|
|
285
|
+
let failure;
|
|
286
|
+
try {
|
|
287
|
+
await runPromise;
|
|
288
|
+
// A dispatch into an already-running child returns after queueing, not after that child settles.
|
|
289
|
+
await this.runService.waitForConversationIdle(conversationId);
|
|
290
|
+
}
|
|
291
|
+
catch (error) {
|
|
292
|
+
failure = error;
|
|
293
|
+
await this.runService.waitForConversationIdle(conversationId);
|
|
294
|
+
}
|
|
295
|
+
// A TRUNCATED ANSWER IS NOT A DEAD CHILD. The model filled its single-response output budget
|
|
296
|
+
// and stopped mid-sentence; everything it said is already on the child's transcript, and the
|
|
297
|
+
// work it was doing is NOT over. Treating that as a failure is what killed the child: the run
|
|
298
|
+
// service stamped the conversation `failed`, the orchestrator reported a failure to the
|
|
299
|
+
// parent, and a task that was one turn from done was thrown away.
|
|
300
|
+
//
|
|
301
|
+
// So a length stop is CONTINUED, not reported. The child is told to pick up where the output
|
|
302
|
+
// stopped, and it runs again. The bound is real: a model that truncates forever would
|
|
303
|
+
// otherwise loop until the watchdog gave up, and a task that cannot finish is better REPORTED
|
|
304
|
+
// as unfinished than retried until the server falls over.
|
|
305
|
+
//
|
|
306
|
+
// A CONTINUED CHILD IS NOT A FAILED ONE, SO THE FAILURE IS CLEARED. Everything below reads
|
|
307
|
+
// `failure` to decide what the parent is told and what the ledger records; a child that
|
|
308
|
+
// finished its answer has neither a failure to report nor a result to hand over - the parent
|
|
309
|
+
// reads the child's session, exactly as it does for a child that finished normally.
|
|
310
|
+
if (failure !== undefined && isLengthExceededError(failure)) {
|
|
311
|
+
const continued = await this.continueAfterLengthStop(conversationId, failure);
|
|
312
|
+
if (continued)
|
|
313
|
+
failure = undefined;
|
|
314
|
+
}
|
|
315
|
+
// THE RESULT FILE IS ALWAYS WRITTEN, AND THE PARENT IS ALWAYS TOLD.
|
|
316
|
+
//
|
|
317
|
+
// The file is the child's product and the reader may open it. The report is a message to the
|
|
318
|
+
// parent, and it goes out WHETHER THE CHILD SUCCEEDED OR FAILED - because a parent that
|
|
319
|
+
// delegated a task has to be told how it went. A parent that heard nothing would wait forever,
|
|
320
|
+
// or would have to poll the child's session to find out, which is exactly what the automatic
|
|
321
|
+
// report exists to avoid.
|
|
322
|
+
//
|
|
323
|
+
// The envelope already tells the two apart: `state="completed"` with `<task_result>` for a
|
|
324
|
+
// child that finished, `state="error"` with `<task_error>` for one that broke. Reporting only
|
|
325
|
+
// the failures was a real defect - it left a parent that had successfully delegated a task
|
|
326
|
+
// staring at an empty transcript, and the child looking finished to everyone except the one
|
|
327
|
+
// person waiting for it.
|
|
328
|
+
// DID THIS TURN REPORT ITSELF? A child that reported from inside its turn has already told
|
|
329
|
+
// the parent everything the knock would have said - and a knock on top of that report would
|
|
330
|
+
// make the parent hear about one finished turn twice. The knock exists for the child that
|
|
331
|
+
// FORGOT to report, so a child that did report is not knocked.
|
|
332
|
+
let reportedItself = false;
|
|
333
|
+
try {
|
|
334
|
+
const result = await this.persistSessionResult(conversationId, failure);
|
|
335
|
+
if (result && !silent) {
|
|
336
|
+
const current = this.store.conversation(conversationId);
|
|
337
|
+
// THE REPORT GOES OUT ONLY WHEN THE CHILD'S TURN ENDED. The statuses that mean "the turn is
|
|
338
|
+
// over" are `completed` and `failed`; `running` and `awaiting_background` mean work is still
|
|
339
|
+
// in flight and its result is not final, and `stopped` means somebody pressed stop, so the
|
|
340
|
+
// half-finished answer on screen is not a result anybody stated.
|
|
341
|
+
//
|
|
342
|
+
// This is what separates the two channels. The automatic report says "the task ended, here
|
|
343
|
+
// is what it produced"; the explicit report says "the child is telling its parent something
|
|
344
|
+
// now", and can be called at any point in the task's life.
|
|
345
|
+
const turnEnded = current?.status === "completed" || current?.status === "failed";
|
|
346
|
+
// A CHILD THAT REPORTED ITSELF IS NOT REPORTED TWICE - BUT ONLY FOR THE TURN IT REPORTED.
|
|
347
|
+
// The explicit terminal report is the child's own statement of what it did, so the
|
|
348
|
+
// automatic completion steps aside for it - when the report was made inside THIS turn.
|
|
349
|
+
// A report from an earlier turn says nothing about this one's result, and silencing this
|
|
350
|
+
// one because of that would swallow a result the parent is still waiting for.
|
|
351
|
+
const reportedAt = this.reportedChildren.get(conversationId);
|
|
352
|
+
const alreadyReported = reportedAt !== undefined && reportedAt >= turnStartedAt;
|
|
353
|
+
reportedItself = alreadyReported;
|
|
354
|
+
if (turnEnded && !alreadyReported) {
|
|
355
|
+
await this.runService.enqueueSessionResult({
|
|
356
|
+
conversationId,
|
|
357
|
+
parentConversationId: current?.parentConversationId,
|
|
358
|
+
output: result.output,
|
|
359
|
+
resultPath: result.resultPath,
|
|
360
|
+
// THE ERROR GOES ONLY WHEN THERE IS ONE. `enqueueSessionResult` reads the presence of
|
|
361
|
+
// `error` as "this failed", so a successful report must NOT carry the key - carrying it
|
|
362
|
+
// with the output would tell the parent the child failed.
|
|
363
|
+
...(failure !== undefined ? { error: result.output } : {}),
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
// Result reporting is best-effort: a missing/archived parent or a workspace I/O problem must not
|
|
370
|
+
// turn an already-finished child turn into a second failure.
|
|
371
|
+
console.warn(`Super Pi: session result callback failed for ${conversationId}:`, error instanceof Error ? error.message : String(error));
|
|
372
|
+
}
|
|
373
|
+
finally {
|
|
374
|
+
// THE RECORD IS SPENT BY THE TURN IT SPOKE FOR. Whatever it was about, that turn is over.
|
|
375
|
+
//
|
|
376
|
+
// A record left behind would be harmless - the timestamp comparison already keeps it from
|
|
377
|
+
// silencing a later turn - but it would keep saying "this child reported" to every future
|
|
378
|
+
// reader of this code, and the next thing that consults it would have to re-derive the
|
|
379
|
+
// timestamp rule. Dropping it here keeps one rule in one place: a report belongs to the
|
|
380
|
+
// turn that was running when it was made.
|
|
381
|
+
this.reportedChildren.delete(conversationId);
|
|
382
|
+
}
|
|
383
|
+
// THE PLATFORM KNOCKS ON THE PARENT'S DOOR. The turn is over, so the parent has to hear
|
|
384
|
+
// about it - whether the child remembered to say so or not. What the knock carries is the
|
|
385
|
+
// child's identity and nothing else: the parent reads the child's session itself.
|
|
386
|
+
//
|
|
387
|
+
// ONLY A FINISHED TURN KNOCKS. A turn that failed or was stopped did not finish its work,
|
|
388
|
+
// and the knock says 「完成」 - a broken turn is reported through the failure report, which
|
|
389
|
+
// carries the diagnosis.
|
|
390
|
+
//
|
|
391
|
+
// A PROJECT EMPLOYEE IS NOT ANNOUNCED HERE. Its turn ending is not its task being done, and
|
|
392
|
+
// the project announces the task's completion instead - one knock per piece of work.
|
|
393
|
+
//
|
|
394
|
+
// AND A CHILD THAT REPORTED ITSELF IS NOT KNOCKED. The knock exists for the child that
|
|
395
|
+
// FORGOT to report up; a child that did report has already said everything the knock would
|
|
396
|
+
// have said, and knocking as well would make the parent hear about one finished turn twice.
|
|
397
|
+
const finished = this.store.conversation(conversationId);
|
|
398
|
+
if (!silent
|
|
399
|
+
&& !reportedItself
|
|
400
|
+
&& finished?.status === "completed"
|
|
401
|
+
&& finished.parentConversationId
|
|
402
|
+
&& !this.projectParticipant(conversationId)) {
|
|
403
|
+
try {
|
|
404
|
+
await this.notifyChildCompleted(conversationId);
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
console.warn(`Super Pi: 子会话 ${conversationId} 的完成通知失败:${error instanceof Error ? error.message : String(error)}`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
if (failure !== undefined) {
|
|
411
|
+
console.warn(`Super Pi: dispatch failed for conversation ${conversationId}:`, failure instanceof Error ? failure.message : String(failure));
|
|
412
|
+
this.ledger.update(conversationId, { status: "failed" });
|
|
413
|
+
throw failure;
|
|
414
|
+
}
|
|
415
|
+
})();
|
|
416
|
+
if (options?.wait)
|
|
417
|
+
await completion;
|
|
418
|
+
else {
|
|
419
|
+
void completion.catch(() => undefined);
|
|
420
|
+
await acceptedPromise;
|
|
421
|
+
}
|
|
422
|
+
return { conversationId, ...(acceptedMessageId ? { messageId: acceptedMessageId } : {}), mode };
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* THE PLATFORM KNOCKS ON THE PARENT'S DOOR WHEN A CHILD SESSION ENDS.
|
|
426
|
+
*
|
|
427
|
+
* A child that finished its work is a child the parent has to hear about, and the PLATFORM is the
|
|
428
|
+
* one that knows the turn ended: the child may forget to say so, and a parent that was not
|
|
429
|
+
* present for the turn cannot see that it happened. This is the platform's own housekeeping -
|
|
430
|
+
* it is not something the child is asked to do and not something the model has to remember.
|
|
431
|
+
*
|
|
432
|
+
* THE KNOCK CARRIES NO WORK. It says WHICH child session finished and nothing else: no output,
|
|
433
|
+
* no summary, no last message, no result, no task result. The parent reads the child's session
|
|
434
|
+
* itself, so a platform that summarized here would be writing the report the parent is supposed
|
|
435
|
+
* to write - and a summary written by the platform is a summary nobody verified.
|
|
436
|
+
*
|
|
437
|
+
* ONLY THE DIRECT PARENT IS TOLD. The parent wakes up and looks at its own child; the
|
|
438
|
+
* grandparent is not told about a grandchild's finish, because the parent is the one who has to
|
|
439
|
+
* decide what that means.
|
|
440
|
+
*
|
|
441
|
+
* A TOP-LEVEL SESSION HAS NOBODY TO TELL, so a session without a parent produces nothing - and
|
|
442
|
+
* the user's own session is one of those.
|
|
443
|
+
*/
|
|
444
|
+
async notifyChildCompleted(childConversationId, options = {}) {
|
|
445
|
+
const child = this.store.conversation(childConversationId);
|
|
446
|
+
if (!child)
|
|
447
|
+
return { delivered: false };
|
|
448
|
+
const parentConversationId = child.parentConversationId;
|
|
449
|
+
if (!parentConversationId)
|
|
450
|
+
return { delivered: false };
|
|
451
|
+
const parent = this.store.conversation(parentConversationId);
|
|
452
|
+
if (!parent || parent.archivedAt)
|
|
453
|
+
return { delivered: false };
|
|
454
|
+
const unit = options.unit ?? this.completionUnit(child);
|
|
455
|
+
const key = `${childConversationId}:${unit}`;
|
|
456
|
+
// ONE COMPLETION, ONE KNOCK. A retry, or a second report about the same finished turn, must
|
|
457
|
+
// not knock twice - and the knock is remembered even if the delivery fails, so a parent that
|
|
458
|
+
// cannot be reached does not turn into a storm of retries.
|
|
459
|
+
if (this.completionNotices.has(key))
|
|
460
|
+
return { delivered: false, parentConversationId };
|
|
461
|
+
this.completionNotices.add(key);
|
|
462
|
+
const notice = `子会话已完成:${child.title || child.id}(${child.id})。`;
|
|
463
|
+
try {
|
|
464
|
+
await this.dispatch(parentConversationId, notice, { wait: false, silent: true });
|
|
465
|
+
}
|
|
466
|
+
catch (error) {
|
|
467
|
+
console.warn(`Super Pi: 子会话 ${childConversationId} 已完成,但叫不醒父会话 ${parentConversationId}:${error instanceof Error ? error.message : String(error)}`);
|
|
468
|
+
}
|
|
469
|
+
return { delivered: true, parentConversationId };
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* WHAT MAKES TWO COMPLETION REPORTS THE SAME COMPLETION.
|
|
473
|
+
*
|
|
474
|
+
* The child's last answer is the thing the completion is about, so two reports that arrive after
|
|
475
|
+
* the same answer are the same completion - a retry, a repeated settle, a second report about a
|
|
476
|
+
* turn that already ended. The next turn produces the next answer, and that is a new completion
|
|
477
|
+
* the parent has not been told about yet.
|
|
478
|
+
*/
|
|
479
|
+
completionUnit(conversation) {
|
|
480
|
+
const lastAnswer = [...conversation.messages].reverse().find((message) => message.role === "assistant");
|
|
481
|
+
return lastAnswer?.id ?? conversation.messages.at(-1)?.id ?? "end";
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* IS THIS SESSION ONE OF A PROJECT'S EMPLOYEES?
|
|
485
|
+
*
|
|
486
|
+
* A project member's turn ending is NOT its work being done: the delivery still has to be
|
|
487
|
+
* reviewed. The moment that counts is the task being completed, and the project announces that
|
|
488
|
+
* one - announcing both would wake the Leader twice for one piece of work.
|
|
489
|
+
*/
|
|
490
|
+
projectParticipant(conversationId) {
|
|
491
|
+
return this.store.projects().some(project => project.tasks.some(task => task.ownerConversationId === conversationId || task.reviewerConversationId === conversationId));
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* THE CHILD'S OUTPUT WAS CUT OFF. TELL IT TO CARRY ON, AND LET IT.
|
|
495
|
+
*
|
|
496
|
+
* This is the recovery for a length stop, and it exists because a truncated answer is not a
|
|
497
|
+
* finished one. The child has already said most of what it had to say - that text is on its
|
|
498
|
+
* transcript - so the work left to do is the tail of the answer, not the whole of it.
|
|
499
|
+
*
|
|
500
|
+
* WHY THE CONTINUATION IS A NEW TURN RATHER THAN A RESUME OF THE SAME ONE. Pi has already settled
|
|
501
|
+
* the turn that was truncated: the model stopped, the message was written, the run ended. There is
|
|
502
|
+
* no live turn to resume, so the only way to get more output is to ask again - and asking again in
|
|
503
|
+
* the SAME conversation is what makes the continuation work, because the child's own partial
|
|
504
|
+
* answer is in its context and the model can see exactly where it stopped.
|
|
505
|
+
*
|
|
506
|
+
* WHY IT IS AN AGENT-SENT ORDER RATHER THAN A USER MESSAGE. The person never typed this, and the
|
|
507
|
+
* child's transcript must not show words under their name that they never said - the same reason
|
|
508
|
+
* `dispatch` uses `enqueueAndRunAsAgent` in the first place.
|
|
509
|
+
*
|
|
510
|
+
* Returns true when the child was continued (and the caller must NOT report a failure), and false
|
|
511
|
+
* when the continuation could not be made or the bound was reached - in which case the caller
|
|
512
|
+
* reports the original failure, which is then the honest description of what happened.
|
|
513
|
+
*/
|
|
514
|
+
async continueAfterLengthStop(conversationId, failure) {
|
|
515
|
+
if (!this.store.conversation(conversationId))
|
|
516
|
+
return false;
|
|
517
|
+
// THE LOOP, BECAUSE A CONTINUATION CAN BE TRUNCATED TOO. A long answer often needs more than
|
|
518
|
+
// one continuation: each response fills its own output budget, so a three-part answer runs out
|
|
519
|
+
// of room twice before it is done. The bound counts every continuation this child has been
|
|
520
|
+
// given, so the loop cannot run forever - a model that truncates on EVERY response reaches
|
|
521
|
+
// the bound and is reported as unfinished, which is the honest sentence about what happened.
|
|
522
|
+
for (;;) {
|
|
523
|
+
const used = this.lengthContinuations.get(conversationId) ?? 0;
|
|
524
|
+
if (used >= MAX_LENGTH_CONTINUATIONS) {
|
|
525
|
+
console.warn(`Super Pi: session ${conversationId} hit the output limit ${MAX_LENGTH_CONTINUATIONS} times; reporting it as unfinished.`);
|
|
526
|
+
this.lengthContinuations.delete(conversationId);
|
|
527
|
+
return false;
|
|
528
|
+
}
|
|
529
|
+
this.lengthContinuations.set(conversationId, used + 1);
|
|
530
|
+
const reason = failure instanceof Error ? failure.message : String(failure);
|
|
531
|
+
console.warn(`Super Pi: session ${conversationId} was truncated (${reason}); asking it to continue (${used + 1}/${MAX_LENGTH_CONTINUATIONS}).`);
|
|
532
|
+
let continuationFailure;
|
|
533
|
+
try {
|
|
534
|
+
// THE ORDER GOES IN AS A SYSTEM MESSAGE, AND THE RUN IS WAITED FOR. The child must be given
|
|
535
|
+
// the chance to finish before anything is reported to the parent - otherwise the parent would
|
|
536
|
+
// receive a result that is missing the tail the child was about to write.
|
|
537
|
+
const lastAssistant = this.store.conversation(conversationId)?.messages.filter((m) => m.role === "assistant").pop();
|
|
538
|
+
const prompt = buildLengthContinuationPrompt(lastAssistant);
|
|
539
|
+
await this.runService.enqueueAndRunAsAgent(conversationId, prompt);
|
|
540
|
+
await this.runService.waitForConversationIdle(conversationId);
|
|
541
|
+
}
|
|
542
|
+
catch (error) {
|
|
543
|
+
continuationFailure = error;
|
|
544
|
+
}
|
|
545
|
+
if (continuationFailure !== undefined) {
|
|
546
|
+
// A CONTINUATION THAT IS ITSELF TRUNCATED IS THE SAME SITUATION AGAIN, AND THE LOOP
|
|
547
|
+
// CONTINUES. It is only a different thing when the continuation failed for a reason that
|
|
548
|
+
// is NOT the output limit - a provider error, a refused tool - and those are the child's
|
|
549
|
+
// real failure, reported through the normal path below.
|
|
550
|
+
if (isLengthExceededError(continuationFailure)) {
|
|
551
|
+
failure = continuationFailure;
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
console.warn(`Super Pi: continuing session ${conversationId} failed:`, continuationFailure instanceof Error ? continuationFailure.message : String(continuationFailure));
|
|
555
|
+
this.lengthContinuations.delete(conversationId);
|
|
556
|
+
return false;
|
|
557
|
+
}
|
|
558
|
+
// THE CHILD SETTLED WITHOUT ANOTHER TRUNCATION. Its work is done: the answer on its transcript
|
|
559
|
+
// is now complete, and there is nothing to report to the parent - the parent reads the child's
|
|
560
|
+
// result from the session itself, exactly as it does for a child that finished normally.
|
|
561
|
+
//
|
|
562
|
+
// THE WARNING IS CLEARED HERE. It described the answer that was cut short, and the child has
|
|
563
|
+
// now finished that answer; leaving it up would tell the reader the answer is still truncated
|
|
564
|
+
// when it is not.
|
|
565
|
+
await this.store.setWarningReason(conversationId, undefined);
|
|
566
|
+
this.lengthContinuations.delete(conversationId);
|
|
567
|
+
this.ledger.update(conversationId, { status: "completed" });
|
|
568
|
+
return true;
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Explicit report from a child session to its direct parent.
|
|
573
|
+
* Can be called multiple times at any point during execution.
|
|
574
|
+
*/
|
|
575
|
+
async report(childConversationId, options) {
|
|
576
|
+
const conversation = this.store.conversation(childConversationId);
|
|
577
|
+
if (!conversation) {
|
|
578
|
+
throw new Error(`找不到会话:${childConversationId}`);
|
|
579
|
+
}
|
|
580
|
+
const parentConversationId = conversation.parentConversationId;
|
|
581
|
+
if (!parentConversationId) {
|
|
582
|
+
throw new Error(`会话 ${childConversationId} 没有直属父会话,无法汇报`);
|
|
583
|
+
}
|
|
584
|
+
const parent = this.store.conversation(parentConversationId);
|
|
585
|
+
if (!parent) {
|
|
586
|
+
throw new Error(`直属父会话 ${parentConversationId} 不存在`);
|
|
587
|
+
}
|
|
588
|
+
const content = options.content ?? "";
|
|
589
|
+
const status = options.status ?? "in_progress";
|
|
590
|
+
const failed = status === "failed";
|
|
591
|
+
const workspace = this.store.workspace(conversation.workspaceId);
|
|
592
|
+
const resultPath = sessionResultRelativePath(childConversationId);
|
|
593
|
+
if (workspace) {
|
|
594
|
+
const resultDirectory = join(workspace.path, ".super-pi", "session-results");
|
|
595
|
+
await mkdir(resultDirectory, { recursive: true });
|
|
596
|
+
await writeFile(join(resultDirectory, `${childConversationId}.md`), content, "utf8");
|
|
597
|
+
}
|
|
598
|
+
await this.runService.enqueueSessionResult({
|
|
599
|
+
conversationId: childConversationId,
|
|
600
|
+
parentConversationId,
|
|
601
|
+
output: content,
|
|
602
|
+
resultPath,
|
|
603
|
+
...(failed ? { error: content } : {}),
|
|
604
|
+
});
|
|
605
|
+
// THE CHILD HAS NOW SPOKEN FOR ITSELF. The automatic report that fires when the child's turn
|
|
606
|
+
// ends would otherwise repeat what was just delivered - the parent would receive the same
|
|
607
|
+
// answer twice, once as the child's own report and once as the automatic completion.
|
|
608
|
+
//
|
|
609
|
+
// An EXPLICIT report is the child's own statement of what it did, so it is the better of the
|
|
610
|
+
// two and the automatic one steps aside. A report that is NOT terminal (an interim update)
|
|
611
|
+
// does not silence the automatic report: the child is still working, and the parent will want
|
|
612
|
+
// to hear how the task ended.
|
|
613
|
+
if (status === "completed" || status === "failed") {
|
|
614
|
+
// THE TIME OF THE REPORT IS THE PART THAT MATTERS. It is what tells the completion path
|
|
615
|
+
// whether this report spoke for the turn that is ending or for an earlier one, and it is
|
|
616
|
+
// stamped here - where the report is made - rather than where it is looked up later.
|
|
617
|
+
this.reportedChildren.set(childConversationId, Date.now());
|
|
618
|
+
await this.watchdog.cancel(childConversationId);
|
|
619
|
+
}
|
|
620
|
+
else {
|
|
621
|
+
await this.watchdog.noteSignal(childConversationId);
|
|
622
|
+
}
|
|
623
|
+
return { delivered: true, parentConversationId };
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* Sets or updates a silence watchdog timer on a child session.
|
|
627
|
+
*/
|
|
628
|
+
async setWatchdog(options) {
|
|
629
|
+
const child = this.store.conversation(options.childConversationId);
|
|
630
|
+
if (!child) {
|
|
631
|
+
throw new Error(`找不到会话:${options.childConversationId}`);
|
|
632
|
+
}
|
|
633
|
+
await this.watchdog.arm({
|
|
634
|
+
childConversationId: options.childConversationId,
|
|
635
|
+
parentConversationId: options.parentConversationId,
|
|
636
|
+
workspaceId: child.workspaceId,
|
|
637
|
+
timeoutSeconds: options.timeoutSeconds,
|
|
638
|
+
});
|
|
639
|
+
return { ok: true, childConversationId: options.childConversationId, timeoutSeconds: options.timeoutSeconds };
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Cancels a silence watchdog timer on a child session.
|
|
643
|
+
*/
|
|
644
|
+
async cancelWatchdog(childConversationId) {
|
|
645
|
+
await this.watchdog.cancel(childConversationId);
|
|
646
|
+
return { ok: true };
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Re-arms persisted watchdogs from disk.
|
|
650
|
+
*/
|
|
651
|
+
async restoreWatchdogs() {
|
|
652
|
+
await this.watchdog.restore();
|
|
653
|
+
}
|
|
654
|
+
async persistSessionResult(conversationId, failure) {
|
|
655
|
+
const conversation = this.store.conversation(conversationId);
|
|
656
|
+
const workspace = conversation ? this.store.workspace(conversation.workspaceId) : undefined;
|
|
657
|
+
if (!conversation || !workspace)
|
|
658
|
+
return undefined;
|
|
659
|
+
// THE FILE IS THE CHILD'S PRODUCT, AND THE REPORT USES IT. They used to be the same thing, and
|
|
660
|
+
// the split is what the user asked for:
|
|
661
|
+
// - the FILE is written on every turn, so the reader can open it and `status(includeOutput)`
|
|
662
|
+
// can return what the child actually produced;
|
|
663
|
+
// - the REPORT to the parent carries that same text, because the parent is waiting for an
|
|
664
|
+
// answer. A failure reports the DIAGNOSIS rather than whatever the model managed to say,
|
|
665
|
+
// because a broken turn's last words are not a diagnosis of why it broke.
|
|
666
|
+
const output = failure !== undefined
|
|
667
|
+
? (failure instanceof Error ? failure.message : String(failure))
|
|
668
|
+
: ([...conversation.messages].reverse().find((message) => message.role === "assistant")?.content ?? "");
|
|
669
|
+
const resultPath = sessionResultRelativePath(conversationId);
|
|
670
|
+
const resultDirectory = join(workspace.path, ".super-pi", "session-results");
|
|
671
|
+
await mkdir(resultDirectory, { recursive: true });
|
|
672
|
+
await writeFile(join(resultDirectory, `${conversationId}.md`), output, "utf8");
|
|
673
|
+
return { output, resultPath };
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Returns a high-level summary of a session's progress without returning full transcripts.
|
|
677
|
+
* Uses narrow store reader `store.conversation(id)` to avoid cloning the entire state.
|
|
678
|
+
*/
|
|
679
|
+
async status(conversationId, options) {
|
|
680
|
+
const conversation = this.store.conversation(conversationId);
|
|
681
|
+
if (!conversation) {
|
|
682
|
+
throw new Error(`找不到会话:${conversationId}`);
|
|
683
|
+
}
|
|
684
|
+
const ledgerEntry = this.ledger.get(conversationId);
|
|
685
|
+
const messages = conversation.messages ?? [];
|
|
686
|
+
let turnCount = 0;
|
|
687
|
+
let lastAssistantSnippet;
|
|
688
|
+
let lastUserSnippet;
|
|
689
|
+
let activeTool;
|
|
690
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
691
|
+
const msg = messages[i];
|
|
692
|
+
if (!lastAssistantSnippet && msg.role === "assistant") {
|
|
693
|
+
const raw = msg.content || (msg.thinkingBlocks ? msg.thinkingBlocks.map((b) => b.text).join(" ") : "") || "";
|
|
694
|
+
lastAssistantSnippet = raw.slice(0, 300);
|
|
695
|
+
}
|
|
696
|
+
if (!lastUserSnippet && msg.role === "user") {
|
|
697
|
+
lastUserSnippet = (msg.content || "").slice(0, 300);
|
|
698
|
+
}
|
|
699
|
+
if (msg.role === "assistant") {
|
|
700
|
+
turnCount++;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
if (conversation.status === "running" || conversation.status === "waiting") {
|
|
704
|
+
const lastAssistant = [...messages].reverse().find((m) => m.role === "assistant");
|
|
705
|
+
if (lastAssistant?.toolCalls?.length) {
|
|
706
|
+
const isCompleted = (t) => t.status === "ok" || t.status === "error" || t.status === "done" || t.status === "failed";
|
|
707
|
+
const isRunning = (t) => !isCompleted(t) && (Boolean(t.preparing) || Boolean(t.live) || !t.status || t.status === "running");
|
|
708
|
+
const runningCall = [...lastAssistant.toolCalls].reverse().find(isRunning)
|
|
709
|
+
?? (!isCompleted(lastAssistant.toolCalls[lastAssistant.toolCalls.length - 1])
|
|
710
|
+
? lastAssistant.toolCalls[lastAssistant.toolCalls.length - 1]
|
|
711
|
+
: undefined);
|
|
712
|
+
if (runningCall) {
|
|
713
|
+
activeTool = {
|
|
714
|
+
label: runningCall.label || runningCall.name || "tool",
|
|
715
|
+
detail: runningCall.detail || runningCall.live,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
if (!activeTool && ledgerEntry?.activeTool) {
|
|
720
|
+
activeTool = { ...ledgerEntry.activeTool };
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
const hasPendingQuestion = this.store.pendingQuestions(conversationId).length > 0;
|
|
724
|
+
let output;
|
|
725
|
+
let outputTruncated;
|
|
726
|
+
const resultPath = sessionResultRelativePath(conversationId);
|
|
727
|
+
if (options?.includeOutput) {
|
|
728
|
+
const workspace = this.store.workspace(conversation.workspaceId);
|
|
729
|
+
if (workspace) {
|
|
730
|
+
try {
|
|
731
|
+
const fullOutput = await readFile(join(workspace.path, ".super-pi", "session-results", `${conversationId}.md`), "utf8");
|
|
732
|
+
const capped = capText(fullOutput, SESSION_OUTPUT_CHAR_LIMIT, "会话输出");
|
|
733
|
+
output = capped.text;
|
|
734
|
+
outputTruncated = capped.truncated;
|
|
735
|
+
}
|
|
736
|
+
catch (error) {
|
|
737
|
+
if (error.code !== "ENOENT")
|
|
738
|
+
throw error;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
const effectiveStatus = conversation.error
|
|
743
|
+
? "failed"
|
|
744
|
+
: conversation.status;
|
|
745
|
+
const finalProgress = lastAssistantSnippet ?? ledgerEntry?.lastProgress ?? lastUserSnippet;
|
|
746
|
+
// Sync ledger status if present
|
|
747
|
+
if (ledgerEntry && (ledgerEntry.status !== effectiveStatus || ledgerEntry.activeTool !== activeTool || ledgerEntry.lastProgress !== finalProgress)) {
|
|
748
|
+
this.ledger.update(conversationId, {
|
|
749
|
+
status: effectiveStatus,
|
|
750
|
+
lastProgress: finalProgress,
|
|
751
|
+
activeTool,
|
|
752
|
+
...(conversation.error ? { error: conversation.error } : {}),
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
const waiting = this.store.listWaitingMessages(conversationId);
|
|
756
|
+
const queuedMessages = waiting.length > 0
|
|
757
|
+
? waiting.map((item) => ({
|
|
758
|
+
id: item.id,
|
|
759
|
+
delivery: item.delivery === "sending" ? "sending" : "waiting",
|
|
760
|
+
role: item.role === "tool" ? "tool" : "user",
|
|
761
|
+
snippet: item.content.replace(/\s+/g, " ").trim().slice(0, 120),
|
|
762
|
+
}))
|
|
763
|
+
: undefined;
|
|
764
|
+
return {
|
|
765
|
+
conversationId: conversation.id,
|
|
766
|
+
workspaceId: conversation.workspaceId,
|
|
767
|
+
title: conversation.title,
|
|
768
|
+
status: effectiveStatus,
|
|
769
|
+
origin: ledgerEntry?.origin ?? conversation.origin ?? "user",
|
|
770
|
+
parentConversationId: conversation.parentConversationId ?? ledgerEntry?.parentConversationId,
|
|
771
|
+
task: ledgerEntry?.task ?? (conversation.title && conversation.title !== "新会话" ? conversation.title : undefined),
|
|
772
|
+
messageCount: messages.length,
|
|
773
|
+
turnCount,
|
|
774
|
+
lastAssistantSnippet,
|
|
775
|
+
lastUserSnippet,
|
|
776
|
+
hasPendingQuestion,
|
|
777
|
+
activeTool,
|
|
778
|
+
error: conversation.error ?? ledgerEntry?.error,
|
|
779
|
+
updatedAt: conversation.updatedAt,
|
|
780
|
+
createdAt: ledgerEntry?.createdAt ?? (conversation.messages?.[0]?.createdAt ? new Date(conversation.messages[0].createdAt).getTime() : (conversation.updatedAt ? new Date(conversation.updatedAt).getTime() : Date.now())),
|
|
781
|
+
lastProgress: finalProgress,
|
|
782
|
+
...(queuedMessages ? { queuedMessages } : {}),
|
|
783
|
+
...(options?.includeOutput ? { outputPath: resultPath } : {}),
|
|
784
|
+
...(output !== undefined ? { output, outputTruncated } : {}),
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Lists summaries of all sessions, optionally filtered by parent conversation.
|
|
789
|
+
*
|
|
790
|
+
* Persisted store conversations are the authoritative source for session tree
|
|
791
|
+
* parent-child relationships across server restarts, while SessionLedger
|
|
792
|
+
* enriches live in-memory task, progress, and activeTool state.
|
|
793
|
+
*/
|
|
794
|
+
async list(parentConversationId) {
|
|
795
|
+
const targetParentId = parentConversationId?.trim();
|
|
796
|
+
const candidateIds = new Set();
|
|
797
|
+
if (targetParentId) {
|
|
798
|
+
// 1. Check parent in store to know parent's workspace
|
|
799
|
+
const parentConv = this.store.conversation(targetParentId);
|
|
800
|
+
if (parentConv) {
|
|
801
|
+
const workspaceChildren = this.store.conversationsForWorkspace(parentConv.workspaceId);
|
|
802
|
+
for (const child of workspaceChildren) {
|
|
803
|
+
if (child.parentConversationId === targetParentId) {
|
|
804
|
+
candidateIds.add(child.id);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
else {
|
|
809
|
+
// Fallback: check all conversations in store
|
|
810
|
+
const allConversations = this.store.snapshot().conversations;
|
|
811
|
+
for (const conv of allConversations) {
|
|
812
|
+
if (conv.parentConversationId === targetParentId) {
|
|
813
|
+
candidateIds.add(conv.id);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
// 2. Also check in-memory ledger entries
|
|
818
|
+
const ledgerEntries = this.ledger.listByParent(targetParentId);
|
|
819
|
+
for (const entry of ledgerEntries) {
|
|
820
|
+
candidateIds.add(entry.conversationId);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
else {
|
|
824
|
+
// No parent specified: list all orchestrator / child sessions
|
|
825
|
+
for (const conv of this.store.snapshot().conversations) {
|
|
826
|
+
if (conv.parentConversationId || conv.origin === "orchestrator") {
|
|
827
|
+
candidateIds.add(conv.id);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
for (const entry of this.ledger.listAll()) {
|
|
831
|
+
candidateIds.add(entry.conversationId);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
const parentConv = targetParentId ? this.store.conversation(targetParentId) : undefined;
|
|
835
|
+
const summaries = [];
|
|
836
|
+
for (const conversationId of candidateIds) {
|
|
837
|
+
const conv = this.store.conversation(conversationId);
|
|
838
|
+
if (!conv) {
|
|
839
|
+
// Conversation was removed from store; prune ledger
|
|
840
|
+
this.ledger.delete(conversationId);
|
|
841
|
+
continue;
|
|
842
|
+
}
|
|
843
|
+
if (conv.archivedAt) {
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
try {
|
|
847
|
+
const summary = await this.status(conversationId);
|
|
848
|
+
// Workspace boundary enforcement: do not leak sessions across different workspaces
|
|
849
|
+
if (parentConv && summary.workspaceId !== parentConv.workspaceId) {
|
|
850
|
+
continue;
|
|
851
|
+
}
|
|
852
|
+
if (targetParentId && summary.parentConversationId !== targetParentId) {
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
summaries.push(summary);
|
|
856
|
+
}
|
|
857
|
+
catch {
|
|
858
|
+
// Conversation was removed from store; prune ledger
|
|
859
|
+
this.ledger.delete(conversationId);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
// Sort newest first by creation time or updated timestamp
|
|
863
|
+
return summaries.sort((a, b) => {
|
|
864
|
+
const timeA = a.createdAt ?? (a.updatedAt ? new Date(a.updatedAt).getTime() : 0);
|
|
865
|
+
const timeB = b.createdAt ?? (b.updatedAt ? new Date(b.updatedAt).getTime() : 0);
|
|
866
|
+
return timeB - timeA;
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
/**
|
|
870
|
+
* Stops a target session.
|
|
871
|
+
* Can distinguish between interrupting an active turn, cancelling queued messages, or both.
|
|
872
|
+
*/
|
|
873
|
+
async stop(conversationId, options) {
|
|
874
|
+
const conversation = this.store.conversation(conversationId);
|
|
875
|
+
if (!conversation) {
|
|
876
|
+
throw new Error(`找不到会话:${conversationId}`);
|
|
877
|
+
}
|
|
878
|
+
if (options?.messageIds !== undefined) {
|
|
879
|
+
if (options.messageId) {
|
|
880
|
+
throw new Error("不能同时传入 messageId 和 messageIds。");
|
|
881
|
+
}
|
|
882
|
+
if (!Array.isArray(options.messageIds) || options.messageIds.length === 0) {
|
|
883
|
+
throw new Error("messageIds 必须是非空字符串数组。");
|
|
884
|
+
}
|
|
885
|
+
for (const rawId of options.messageIds) {
|
|
886
|
+
if (typeof rawId !== "string" || !rawId.trim()) {
|
|
887
|
+
throw new Error("messageIds 中的每一项都必须是非空消息 ID。");
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
const { withdrawn, missingIds } = await this.runService.cancelQueuedMany(conversationId, options.messageIds, { actor: "agent" });
|
|
891
|
+
if (withdrawn.length === 0) {
|
|
892
|
+
throw new Error("指定的排队消息不存在、已发送或已被撤回。");
|
|
893
|
+
}
|
|
894
|
+
return {
|
|
895
|
+
stopped: false,
|
|
896
|
+
mode: "queued-withdraw",
|
|
897
|
+
withdrawn,
|
|
898
|
+
...(missingIds.length > 0 ? { missingIds } : {}),
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
let mode = options?.mode ?? "all";
|
|
902
|
+
if (options?.messageId) {
|
|
903
|
+
await this.runService.interruptQueued(conversationId, options.messageId);
|
|
904
|
+
mode = "queued-interrupt";
|
|
905
|
+
}
|
|
906
|
+
else if (mode === "queued") {
|
|
907
|
+
const waiting = this.store.listWaitingMessages(conversationId);
|
|
908
|
+
for (const msg of waiting) {
|
|
909
|
+
await this.runService.cancelQueued(conversationId, msg.id);
|
|
910
|
+
}
|
|
911
|
+
mode = "queued-cancel";
|
|
912
|
+
}
|
|
913
|
+
else if (mode === "active") {
|
|
914
|
+
await this.runService.stopRun(conversationId);
|
|
915
|
+
mode = "active-stop";
|
|
916
|
+
}
|
|
917
|
+
else {
|
|
918
|
+
// mode === "all"
|
|
919
|
+
await this.runService.stopRun(conversationId);
|
|
920
|
+
const waiting = this.store.listWaitingMessages(conversationId);
|
|
921
|
+
for (const msg of waiting) {
|
|
922
|
+
await this.runService.cancelQueued(conversationId, msg.id);
|
|
923
|
+
}
|
|
924
|
+
mode = "all";
|
|
925
|
+
}
|
|
926
|
+
this.ledger.update(conversationId, { status: "stopped" });
|
|
927
|
+
await this.watchdog.cancel(conversationId);
|
|
928
|
+
return { stopped: true, mode };
|
|
929
|
+
}
|
|
930
|
+
/**
|
|
931
|
+
* THE SESSIONS UNDER ONE SESSION, DEEPEST LAST.
|
|
932
|
+
*
|
|
933
|
+
* The tree edge lives on the conversation itself (`parentConversationId`), so "who is under this
|
|
934
|
+
* one?" is a walk over the workspace's conversations rather than a separate structure that could
|
|
935
|
+
* disagree with it. The order is breadth-first, which is depth order - and the caller stops them
|
|
936
|
+
* in reverse, so the deepest work dies before the session that owns it.
|
|
937
|
+
*/
|
|
938
|
+
descendantsOf(rootConversationId) {
|
|
939
|
+
const root = this.store.conversation(rootConversationId);
|
|
940
|
+
if (!root)
|
|
941
|
+
return [];
|
|
942
|
+
const childrenByParent = new Map();
|
|
943
|
+
for (const conversation of this.store.conversationsForWorkspace(root.workspaceId)) {
|
|
944
|
+
const parentId = conversation.parentConversationId;
|
|
945
|
+
if (!parentId)
|
|
946
|
+
continue;
|
|
947
|
+
const siblings = childrenByParent.get(parentId);
|
|
948
|
+
if (siblings)
|
|
949
|
+
siblings.push(conversation.id);
|
|
950
|
+
else
|
|
951
|
+
childrenByParent.set(parentId, [conversation.id]);
|
|
952
|
+
}
|
|
953
|
+
const ordered = [];
|
|
954
|
+
const seen = new Set([rootConversationId]);
|
|
955
|
+
const queue = [rootConversationId];
|
|
956
|
+
while (queue.length) {
|
|
957
|
+
const current = queue.shift();
|
|
958
|
+
for (const child of childrenByParent.get(current) ?? []) {
|
|
959
|
+
// A cycle in the stored edges must not turn this into an endless walk.
|
|
960
|
+
if (seen.has(child))
|
|
961
|
+
continue;
|
|
962
|
+
seen.add(child);
|
|
963
|
+
ordered.push(child);
|
|
964
|
+
queue.push(child);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
return ordered;
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* STOPS A SESSION AND EVERYTHING UNDER IT.
|
|
971
|
+
*
|
|
972
|
+
* THIS IS NOT THE SAME THING AS STOPPING A SESSION, and it is deliberately a separate operation
|
|
973
|
+
* rather than a flag on the other one. Stopping a session stops THAT session: its turn, its queued
|
|
974
|
+
* messages, its watchdog. Nothing else. That behaviour is right for the ordinary case - a child
|
|
975
|
+
* that went down the wrong path should not take its own children down with it, because those
|
|
976
|
+
* children may be doing work the parent still wants.
|
|
977
|
+
*
|
|
978
|
+
* But there is a case where the ordinary case leaves a mess. A supervisor whose own supervisor has
|
|
979
|
+
* stopped is an ORPHAN, and the sessions it started are orphans too: they keep burning tokens,
|
|
980
|
+
* keep writing files, and report their results to a session that is no longer running - nobody is
|
|
981
|
+
* left to read them. The parent sees a child that has gone wrong, stops it, and the grandchildren
|
|
982
|
+
* keep running with no parent to stop them.
|
|
983
|
+
*
|
|
984
|
+
* So this operation takes the whole tree: the root, its children, its grandchildren, deepest
|
|
985
|
+
* first. The descendants are stopped AS A CONSEQUENCE of the root being stopped - the caller is
|
|
986
|
+
* still only managing its OWN direct child, and the cross-level reach the scope rules forbid is
|
|
987
|
+
* not what happens here: a grandchild cannot be stopped on its own, and it cannot be spared
|
|
988
|
+
* either, because it cannot outlive the session that owns it.
|
|
989
|
+
*/
|
|
990
|
+
async stopSubtree(conversationId, options) {
|
|
991
|
+
const root = this.store.conversation(conversationId);
|
|
992
|
+
if (!root) {
|
|
993
|
+
throw new Error(`找不到会话:${conversationId}`);
|
|
994
|
+
}
|
|
995
|
+
const descendants = this.descendantsOf(conversationId);
|
|
996
|
+
const stoppedIds = [];
|
|
997
|
+
// DEEPEST FIRST. A session that is stopped while its children still run is exactly the zombie
|
|
998
|
+
// this operation exists to prevent, so the leaves go before their parents.
|
|
999
|
+
for (const descendantId of [...descendants].reverse()) {
|
|
1000
|
+
try {
|
|
1001
|
+
await this.stop(descendantId, options);
|
|
1002
|
+
stoppedIds.push(descendantId);
|
|
1003
|
+
}
|
|
1004
|
+
catch (error) {
|
|
1005
|
+
// ONE SESSION THAT WILL NOT STOP MUST NOT LEAVE THE REST RUNNING. The point of the cascade
|
|
1006
|
+
// is that nothing survives, so a failure on one session is recorded and the sweep goes on.
|
|
1007
|
+
console.warn(`Super Pi: stopping descendant ${descendantId} failed:`, error instanceof Error ? error.message : String(error));
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
const result = await this.stop(conversationId, options);
|
|
1011
|
+
stoppedIds.push(conversationId);
|
|
1012
|
+
return {
|
|
1013
|
+
stopped: result.stopped,
|
|
1014
|
+
mode: result.mode,
|
|
1015
|
+
stoppedIds,
|
|
1016
|
+
descendantCount: descendants.length,
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
async removeWarmSession(conversationId) {
|
|
1020
|
+
const conversation = this.store.conversation(conversationId);
|
|
1021
|
+
if (!conversation)
|
|
1022
|
+
return;
|
|
1023
|
+
if (!conversation.warmSession)
|
|
1024
|
+
throw new Error("只能通过此操作移除预热快照");
|
|
1025
|
+
await this.remove(conversationId);
|
|
1026
|
+
}
|
|
1027
|
+
/**
|
|
1028
|
+
* Permanently destroys a direct child session and its entire descendant subtree (stopping any
|
|
1029
|
+
* running/queued turns first) and removes all transcripts, outputs, runs, and auxiliary state.
|
|
1030
|
+
*/
|
|
1031
|
+
async remove(conversationId, options) {
|
|
1032
|
+
const reason = options?.reason?.trim() || undefined;
|
|
1033
|
+
const conversation = this.store.conversation(conversationId);
|
|
1034
|
+
if (!conversation) {
|
|
1035
|
+
this.ledger.delete(conversationId);
|
|
1036
|
+
this.reportedChildren.delete(conversationId);
|
|
1037
|
+
await this.watchdog.cancel(conversationId);
|
|
1038
|
+
return {
|
|
1039
|
+
removed: false,
|
|
1040
|
+
alreadyRemoved: true,
|
|
1041
|
+
conversationId,
|
|
1042
|
+
destroyedIds: [],
|
|
1043
|
+
stoppedFirst: false,
|
|
1044
|
+
...(reason ? { reason } : {}),
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
if (!conversation.parentConversationId && !conversation.warmSession) {
|
|
1048
|
+
throw new Error("顶层会话不能销毁,只能由用户归档。");
|
|
1049
|
+
}
|
|
1050
|
+
const descendants = this.descendantsOf(conversationId);
|
|
1051
|
+
const subtreeIdsDeepestFirst = [...descendants.reverse(), conversationId];
|
|
1052
|
+
let stoppedFirst = false;
|
|
1053
|
+
for (const id of subtreeIdsDeepestFirst) {
|
|
1054
|
+
const target = this.store.conversation(id);
|
|
1055
|
+
if (!target)
|
|
1056
|
+
continue;
|
|
1057
|
+
const waiting = this.store.listWaitingMessages(id);
|
|
1058
|
+
const isActive = target.status === "running" ||
|
|
1059
|
+
target.status === "waiting" ||
|
|
1060
|
+
target.status === "awaiting_background" ||
|
|
1061
|
+
Boolean(this.runService.isRunning?.(id)) ||
|
|
1062
|
+
waiting.length > 0;
|
|
1063
|
+
if (isActive) {
|
|
1064
|
+
await this.stop(id, { mode: "all" });
|
|
1065
|
+
stoppedFirst = true;
|
|
1066
|
+
}
|
|
1067
|
+
else {
|
|
1068
|
+
await this.watchdog.cancel(id);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
for (const id of subtreeIdsDeepestFirst) {
|
|
1072
|
+
const afterStop = this.store.conversation(id);
|
|
1073
|
+
if (!afterStop)
|
|
1074
|
+
continue;
|
|
1075
|
+
if (afterStop.status === "running" ||
|
|
1076
|
+
afterStop.status === "awaiting_background" ||
|
|
1077
|
+
Boolean(this.runService.isRunning?.(id))) {
|
|
1078
|
+
throw new Error("目标会话或其下属会话仍在运行且未能停止,无法销毁。");
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
for (const id of subtreeIdsDeepestFirst) {
|
|
1082
|
+
this.runService.reviewMemoryBoundary?.(id);
|
|
1083
|
+
await this.conversationService.prepareDestroyConversation?.(id);
|
|
1084
|
+
}
|
|
1085
|
+
const { destroyed } = await this.store.deleteConversationSubtree(conversationId);
|
|
1086
|
+
if (destroyed.length === 0) {
|
|
1087
|
+
return {
|
|
1088
|
+
removed: false,
|
|
1089
|
+
alreadyRemoved: true,
|
|
1090
|
+
conversationId,
|
|
1091
|
+
title: conversation.title,
|
|
1092
|
+
destroyedIds: [],
|
|
1093
|
+
stoppedFirst,
|
|
1094
|
+
...(reason ? { reason } : {}),
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
const remainingSessionFiles = new Set(this.store.snapshot().conversations.map((item) => item.piSessionFile).filter((file) => Boolean(file)));
|
|
1098
|
+
for (const item of destroyed) {
|
|
1099
|
+
this.ledger.delete(item.id);
|
|
1100
|
+
this.reportedChildren.delete(item.id);
|
|
1101
|
+
await this.watchdog.cancel(item.id);
|
|
1102
|
+
const workspace = this.store.workspace(item.workspaceId);
|
|
1103
|
+
if (workspace) {
|
|
1104
|
+
await rm(join(workspace.path, ".super-pi", "session-results", `${item.id}.md`), { force: true }).catch(() => { });
|
|
1105
|
+
}
|
|
1106
|
+
if (item.piSessionFile && !remainingSessionFiles.has(item.piSessionFile)) {
|
|
1107
|
+
await rm(item.piSessionFile, { force: true }).catch(() => { });
|
|
1108
|
+
}
|
|
1109
|
+
if (this.uploadsDir) {
|
|
1110
|
+
await deleteConversationUploads(this.uploadsDir, item.id).catch(() => { });
|
|
1111
|
+
}
|
|
1112
|
+
await this.conversationService.cleanupDestroyedConversation?.(item);
|
|
1113
|
+
}
|
|
1114
|
+
this.broadcaster?.broadcastState();
|
|
1115
|
+
return {
|
|
1116
|
+
removed: true,
|
|
1117
|
+
alreadyRemoved: false,
|
|
1118
|
+
conversationId,
|
|
1119
|
+
title: conversation.title,
|
|
1120
|
+
destroyedIds: destroyed.map((item) => item.id),
|
|
1121
|
+
stoppedFirst,
|
|
1122
|
+
...(reason ? { reason } : {}),
|
|
1123
|
+
};
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Resumes execution in a conversation.
|
|
1127
|
+
* If prompt is provided, sends it as a new turn.
|
|
1128
|
+
* Otherwise, if there is a waiting message in the queue, kicks off its execution.
|
|
1129
|
+
*/
|
|
1130
|
+
async resume(conversationId, prompt, options) {
|
|
1131
|
+
const conversation = this.store.conversation(conversationId);
|
|
1132
|
+
if (!conversation) {
|
|
1133
|
+
throw new Error(`找不到会话:${conversationId}`);
|
|
1134
|
+
}
|
|
1135
|
+
if (prompt && prompt.trim()) {
|
|
1136
|
+
return this.dispatch(conversationId, prompt, options);
|
|
1137
|
+
}
|
|
1138
|
+
const waiting = this.store.listWaitingMessages(conversationId).find((item) => item.delivery === "waiting");
|
|
1139
|
+
if (waiting) {
|
|
1140
|
+
await this.runService.sendQueued(conversationId, waiting.id);
|
|
1141
|
+
this.ledger.update(conversationId, { status: "running" });
|
|
1142
|
+
return { conversationId };
|
|
1143
|
+
}
|
|
1144
|
+
throw new Error("该会话没有排队的消息可恢复,请提供 prompt 发送新消息。");
|
|
1145
|
+
}
|
|
1146
|
+
}
|