@evandu/super-pi-server 0.0.0-stage → 0.1.259
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 +248 -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 +392 -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 +448 -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,2683 @@
|
|
|
1
|
+
import { CODING_STANDARD_REQUEST } from "../active-memory.js";
|
|
2
|
+
import { SteerUnavailableError } from "../runtime.js";
|
|
3
|
+
import { checkSubagentDepth, parentDeniedTools, subagentRoster } from "../task-tool.js";
|
|
4
|
+
import { newSubagentRunId } from "../subagents.js";
|
|
5
|
+
import { readAgents } from "../agents.js";
|
|
6
|
+
import { verifyCapability } from "../capability.js";
|
|
7
|
+
import { capText, validateWorkflowPlan, workflowSummary } from "../workflow.js";
|
|
8
|
+
import { ensureNameIndex, recordWorkspacePath } from "../file-name-index.js";
|
|
9
|
+
import { formatTurnFailure, isLengthExceededError } from "../turn-failure.js";
|
|
10
|
+
import { isLengthContinuation, lengthContinuationText, MAX_LENGTH_CONTINUATIONS, buildLengthContinuationPrompt } from "../length-continuation.js";
|
|
11
|
+
import { describeThrownWithStack } from "../failure-text.js";
|
|
12
|
+
import { toWorkspaceRelative } from "../files.js";
|
|
13
|
+
import { inScope, refreshWorkspaceIndex } from "../file-index.js";
|
|
14
|
+
import { resolveSessionCwd } from "../session-cwd.js";
|
|
15
|
+
import { CHILD_QUESTION_LOCK_REASON, isChildSession } from "../../shared/child-session-lock.js";
|
|
16
|
+
import { BACKGROUND_LOG_LIMIT, sanitizeBackgroundOutput, subagentProgress } from "../../shared/background-task.js";
|
|
17
|
+
import { execFile } from "node:child_process";
|
|
18
|
+
import { promisify } from "node:util";
|
|
19
|
+
import { randomUUID } from "node:crypto";
|
|
20
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
21
|
+
import { lstat, mkdir, writeFile } from "node:fs/promises";
|
|
22
|
+
import { explorerPath, serializeWorkspaceWrite } from "../workspace-file-operations.js";
|
|
23
|
+
const execFileAsync = promisify(execFile);
|
|
24
|
+
/**
|
|
25
|
+
* Validates a caller-supplied delivery mode without silently falling back on bogus values.
|
|
26
|
+
* Undefined defaults to `"queue"`; any other value is rejected explicitly.
|
|
27
|
+
*/
|
|
28
|
+
export function parseMessageDeliveryMode(mode) {
|
|
29
|
+
if (mode === undefined)
|
|
30
|
+
return "queue";
|
|
31
|
+
if (mode === "queue" || mode === "steer")
|
|
32
|
+
return mode;
|
|
33
|
+
throw new Error(`不支持的消息投递模式:${JSON.stringify(mode)}(仅支持 "queue" 或 "steer")`);
|
|
34
|
+
}
|
|
35
|
+
/** Expands composer references into explicit context for the model. */
|
|
36
|
+
async function expandAtReferences(store, workspace, content) {
|
|
37
|
+
const refs = [...content.matchAll(/@(worktree|session):([^\s]+)/gi)];
|
|
38
|
+
if (!refs.length)
|
|
39
|
+
return content;
|
|
40
|
+
const blocks = [];
|
|
41
|
+
for (const [, kind, raw] of refs) {
|
|
42
|
+
const key = raw.trim();
|
|
43
|
+
if (kind.toLowerCase() === "session") {
|
|
44
|
+
const state = store.snapshot();
|
|
45
|
+
const found = state.conversations.find(c => c.id === key || c.title.toLocaleLowerCase().includes(key.toLocaleLowerCase()));
|
|
46
|
+
if (!found)
|
|
47
|
+
continue;
|
|
48
|
+
const text = found.messages
|
|
49
|
+
.filter(message => message.role === "user" || message.role === "assistant" || message.source === "session-reminder")
|
|
50
|
+
.slice(-12)
|
|
51
|
+
.map(message => `${message.source === "session-reminder" ? "定时提醒" : message.role}: ${message.content}`)
|
|
52
|
+
.join("\n");
|
|
53
|
+
blocks.push(`\n[引用会话 ${found.title} (${found.id})]\n${text.slice(-12000)}\n[/引用会话]`);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const { stdout } = await execFileAsync("git", ["-C", workspace.path, "worktree", "list", "--porcelain"], { maxBuffer: 1024 * 1024 });
|
|
58
|
+
const entries = stdout.split(/\n\n+/).map(block => {
|
|
59
|
+
const path = block.match(/^worktree (.+)$/m)?.[1];
|
|
60
|
+
return path ? { path, block } : undefined;
|
|
61
|
+
}).filter(Boolean);
|
|
62
|
+
const found = entries.find(e => e.path === key || e.path.endsWith(`\\${key}`) || e.path.endsWith(`/${key}`));
|
|
63
|
+
if (found)
|
|
64
|
+
blocks.push(`\n[引用 worktree ${found.path}]\n该 worktree 的路径是:${found.path}\n[/引用 worktree]`);
|
|
65
|
+
}
|
|
66
|
+
catch { /* non-git workspaces simply have no worktree references */ }
|
|
67
|
+
}
|
|
68
|
+
return blocks.length ? `${content}\n${blocks.join("\n")}` : content;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The text the model is handed when a waiting message becomes its turn.
|
|
72
|
+
*
|
|
73
|
+
* `role: "user"` is the user's own words - pass through verbatim. `role: "tool"` is a 后台回传 block
|
|
74
|
+
* whose `message.content` is the `<task>` envelope the transcript and dock render from; handing the raw
|
|
75
|
+
* XML to Pi asks it to parse the format itself, which is the "未定义行为" path that 0.1.66 worked around
|
|
76
|
+
* by simply not triggering a turn. We DO trigger a turn now (queue semantics), so we synthesise prose
|
|
77
|
+
* the model can read like any other user message.
|
|
78
|
+
*
|
|
79
|
+
* The envelope and the prose are NOT redundant: the envelope is what the reader sees in the transcript
|
|
80
|
+
* column, what they cancel or reorder; the prose is what leaves the server for Pi.
|
|
81
|
+
*/
|
|
82
|
+
/**
|
|
83
|
+
* THE TEXT THE MODEL IS HANDED WHEN A 后台回传 BECOMES ITS TURN.
|
|
84
|
+
*
|
|
85
|
+
* Pi's SDK has ONE entry point for a new turn - `session.prompt(text)` - and every text sent
|
|
86
|
+
* through it is a USER MESSAGE in Pi's transcript. There is no "the agent said this" channel to
|
|
87
|
+
* use. So a delivered result has to travel as prose, and the only question left is what that prose
|
|
88
|
+
* SAYS.
|
|
89
|
+
*
|
|
90
|
+
* IT USED TO SAY `[后台任务「...」已完成]`, which reads as a thing the PERSON said - a bracketed
|
|
91
|
+
* label, then the body, with nothing saying who is speaking. The model therefore answered it as a
|
|
92
|
+
* user would be answered ("已收到:[后台任务「...」]"), and the reader saw their own result coming
|
|
93
|
+
* back in the user's voice, inside the user's own turn. The delivery had become a quotation.
|
|
94
|
+
*
|
|
95
|
+
* So the prose now says WHO IS SPEAKING and that this is information, not an instruction:
|
|
96
|
+
* 「子会话「...」已完成,结果如下」. The model is told what happened and what it received, and it
|
|
97
|
+
* answers about THAT - which is what a primary agent should do with a child's result.
|
|
98
|
+
*/
|
|
99
|
+
function composePrompt(message) {
|
|
100
|
+
if (message.source === "session-reminder")
|
|
101
|
+
return `[定时提醒] ${message.content}`;
|
|
102
|
+
if (message.role !== "tool")
|
|
103
|
+
return message.content;
|
|
104
|
+
const content = message.content;
|
|
105
|
+
// A CONTINUATION ORDER IS NOT AN ORDER FROM A PARENT AGENT. It is the system telling the session
|
|
106
|
+
// to finish an answer that was cut short, and the model has to hear THAT - "here is a task you
|
|
107
|
+
// were given" would make it start the work over rather than finish what it had already said.
|
|
108
|
+
if (isLengthContinuation(content)) {
|
|
109
|
+
return `(上一条回答因达到输出长度上限被截断,请接着写完)\n\n${lengthContinuationText(content)}`;
|
|
110
|
+
}
|
|
111
|
+
// A DISPATCHED ORDER IS NOT A DELIVERED RESULT. The two both travel as a `tool` message, and the
|
|
112
|
+
// envelope tells them apart: a result carries `<task ...>`, an order does not.
|
|
113
|
+
if (!/<task id="[^"]+" state="[^"]+"/.test(content)) {
|
|
114
|
+
return `上级智能体下发的任务:\n\n${content}`;
|
|
115
|
+
}
|
|
116
|
+
const summaryMatch = /<summary>([\s\S]*?)<\/summary>/.exec(content);
|
|
117
|
+
const summary = summaryMatch ? summaryMatch[1].trim() : "后台任务";
|
|
118
|
+
const stateMatch = /<task id="[^"]+" state="([^"]+)"/.exec(content);
|
|
119
|
+
const state = stateMatch ? stateMatch[1] : "completed";
|
|
120
|
+
// GREEDY ON PURPOSE. The envelope is machine-built with the command's RAW output interpolated before
|
|
121
|
+
// its closing tags, so the body may itself contain `</task_result>` - printed XML, a log excerpt, the
|
|
122
|
+
// model's own echoed envelope format. A non-greedy match stops at the FIRST such tag and hands the
|
|
123
|
+
// model a truncated half-result while the reader sees the full one (measured by
|
|
124
|
+
// scripts/background-result-body.test.mjs with `hello </task_result> world`). Matching greedily lands
|
|
125
|
+
// on the envelope's own closing tag - the LAST one in the content - which is where the body ends
|
|
126
|
+
// regardless of what the command printed.
|
|
127
|
+
const bodyMatch = /<task_(?:result|error)>\n?([\s\S]*)\n?<\/(?:task_result|task_error)>/.exec(content);
|
|
128
|
+
const body = bodyMatch ? bodyMatch[1] : content;
|
|
129
|
+
const stateLabel = state === "completed" ? "已完成" : state === "error" ? "失败" : state;
|
|
130
|
+
// THE SPEAKER IS NAMED, AND IT IS NOT THE READER. A line that starts 「[」 looks like a note the
|
|
131
|
+
// person pasted in; a line that starts 「子会话」 or 「后台任务」 says the SYSTEM is reporting.
|
|
132
|
+
const speaker = /kind="session"/.test(content) ? "子会话" : "后台任务";
|
|
133
|
+
return `${speaker}「${summary}」${stateLabel},结果如下:\n\n${body}`;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Service managing execution of conversation turns, message queueing,
|
|
137
|
+
* follow-ups, and sub-agent dispatching.
|
|
138
|
+
*/
|
|
139
|
+
export class RunService {
|
|
140
|
+
store;
|
|
141
|
+
runtime;
|
|
142
|
+
subagents;
|
|
143
|
+
broadcaster;
|
|
144
|
+
extensionUiService;
|
|
145
|
+
agentsDir;
|
|
146
|
+
workflows;
|
|
147
|
+
questionWaiters = new Map();
|
|
148
|
+
/** A stop can race a late question callback; remember the stopped turn so it cannot park forever. */
|
|
149
|
+
cancelledQuestionConversations = new Set();
|
|
150
|
+
memory;
|
|
151
|
+
setMemory(memory) { this.memory = memory; }
|
|
152
|
+
async recordCodingStandards(conversationId, messageId) {
|
|
153
|
+
return this.memory?.rememberCodingStandards(conversationId, messageId).catch(() => "平台未能保存代码规范,请检查主动记忆设置。");
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* WHAT THE AGENT CHANGED, and what each file looked like before.
|
|
157
|
+
*
|
|
158
|
+
* The tracker is a SETTER rather than a constructor argument, for the same reason `memory` is: it is
|
|
159
|
+
* optional, and a service that must be handed one cannot be built before the thing that builds it.
|
|
160
|
+
*/
|
|
161
|
+
fileChanges;
|
|
162
|
+
fileIndexes;
|
|
163
|
+
/**
|
|
164
|
+
* The NAME indexes, for the same reason the content-search ones are here: the agent's writes have to
|
|
165
|
+
* reach the index a filename search reads, or a file the agent just created would be invisible to the
|
|
166
|
+
* person looking for it.
|
|
167
|
+
*/
|
|
168
|
+
nameIndexes;
|
|
169
|
+
setFileChanges(tracker) { this.fileChanges = tracker; }
|
|
170
|
+
setFileIndexes(indexes) { this.fileIndexes = indexes; }
|
|
171
|
+
setNameIndexes(indexes) { this.nameIndexes = indexes; }
|
|
172
|
+
reviewMemoryBoundary(conversationId) {
|
|
173
|
+
const conversation = this.store.snapshot().conversations.find(c => c.id === conversationId);
|
|
174
|
+
if (conversation)
|
|
175
|
+
this.memory?.review(conversation);
|
|
176
|
+
}
|
|
177
|
+
activeRuns = new Map();
|
|
178
|
+
stoppingConversationIds() {
|
|
179
|
+
return [...this.activeRuns].filter(([, controller]) => controller.signal.aborted).map(([id]) => id);
|
|
180
|
+
}
|
|
181
|
+
acceptingSends = new Map();
|
|
182
|
+
lengthContinuations = new Map();
|
|
183
|
+
turnEventScopes = new Map();
|
|
184
|
+
historyCutClaims = new Map();
|
|
185
|
+
holdHistoryCut(conversationId) {
|
|
186
|
+
this.historyCutClaims.set(conversationId, (this.historyCutClaims.get(conversationId) ?? 0) + 1);
|
|
187
|
+
}
|
|
188
|
+
releaseHistoryCut(conversationId) {
|
|
189
|
+
const count = this.historyCutClaims.get(conversationId) ?? 0;
|
|
190
|
+
if (count <= 1)
|
|
191
|
+
this.historyCutClaims.delete(conversationId);
|
|
192
|
+
else
|
|
193
|
+
this.historyCutClaims.set(conversationId, count - 1);
|
|
194
|
+
}
|
|
195
|
+
assertHistoryAvailable(conversationId) {
|
|
196
|
+
if (this.historyCutClaims.has(conversationId))
|
|
197
|
+
throw new Error("正在撤回上一条消息,Pi 的历史还没截断完成,请等撤回结束后再发送。");
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Whether a conversation is a child session with an active (unarchived) parent.
|
|
201
|
+
*
|
|
202
|
+
* Reuses the canonical judgement in `src/shared/child-session-lock.ts`: child sessions
|
|
203
|
+
* must report upwards via `session_report` rather than asking the user directly.
|
|
204
|
+
*/
|
|
205
|
+
isChildConversation(conversationId) {
|
|
206
|
+
const facts = this.store.childSessionFacts(conversationId);
|
|
207
|
+
return isChildSession(facts.parentConversationId, facts.parent);
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* The completion of the run currently holding a conversation's slot.
|
|
211
|
+
*
|
|
212
|
+
* The slot and the promise are two halves of one fact - "this conversation has a run" and "that run is
|
|
213
|
+
* over" - and they are claimed and released together. A waiter that needs the slot (an interrupt, a
|
|
214
|
+
* send-now) AWAITS the promise rather than polling the map: polling samples a flag on a 10ms clock and
|
|
215
|
+
* has to guess at the state around it, while the promise IS the event, fired by the run's own `finally`.
|
|
216
|
+
*/
|
|
217
|
+
runCompletions = new Map();
|
|
218
|
+
/** A selected interrupt owns the next free run slot, even while the old child exits. */
|
|
219
|
+
interruptTargets = new Map();
|
|
220
|
+
pendingBackgroundWakeups = new Map();
|
|
221
|
+
shuttingDown = false;
|
|
222
|
+
/** Preserve incoming background results as waiting messages while the server drains its producers. */
|
|
223
|
+
beginShutdown() {
|
|
224
|
+
this.shuttingDown = true;
|
|
225
|
+
}
|
|
226
|
+
/** Claims the run slot and arms its completion promise. Call sites release with `releaseRunSlot`. */
|
|
227
|
+
claimRunSlot(conversationId, controller) {
|
|
228
|
+
if (this.shuttingDown)
|
|
229
|
+
throw new Error("服务正在关闭,请重启后再发送消息。");
|
|
230
|
+
let resolve;
|
|
231
|
+
const promise = new Promise((resolvePromise) => { resolve = resolvePromise; });
|
|
232
|
+
this.runCompletions.set(conversationId, { promise, resolve });
|
|
233
|
+
this.activeRuns.set(conversationId, controller);
|
|
234
|
+
}
|
|
235
|
+
/** Releases the run slot and settles its completion promise, so a waiter wakes on the SAME instruction. */
|
|
236
|
+
releaseRunSlot(conversationId, expectedController) {
|
|
237
|
+
// Ownership matters even on cleanup: a delayed finally MUST NOT delete a newer turn's slot or
|
|
238
|
+
// resolve its completion promise. Only the run that claimed the slot may release it.
|
|
239
|
+
const current = this.activeRuns.get(conversationId);
|
|
240
|
+
if (expectedController && current !== expectedController)
|
|
241
|
+
return;
|
|
242
|
+
if (!current)
|
|
243
|
+
return;
|
|
244
|
+
this.activeRuns.delete(conversationId);
|
|
245
|
+
this.runCompletions.get(conversationId)?.resolve();
|
|
246
|
+
this.runCompletions.delete(conversationId);
|
|
247
|
+
if (!current.signal.aborted)
|
|
248
|
+
this.wakeWaitingBackgroundResult(conversationId);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* WHERE EACH TOOL CALL LANDED, per conversation, for as long as the turn that made it is still running.
|
|
252
|
+
*
|
|
253
|
+
* Keyed by Pi's own `toolCallId` - the id the model sees, which Pi also hands to the tool as `execute`'s
|
|
254
|
+
* first argument. That is the only handle shared by the two halves of a dispatch: the server learns the
|
|
255
|
+
* call exists while streaming the turn, and learns it was a sub-agent only when the child, running in a
|
|
256
|
+
* SEPARATE process, posts back over HTTP. `rowByToolCallId` already maps the same key to a row, but it is
|
|
257
|
+
* a local of `streamTurn` and the dispatch arrives in `dispatchTask` - a different closure, reached by an
|
|
258
|
+
* HTTP request. Without a bridge between them the server could only stamp a card with a start time, and
|
|
259
|
+
* a card sorted by start time lands BELOW every message still streaming after the call that asked for it.
|
|
260
|
+
*
|
|
261
|
+
* The outer map is per conversation rather than global so two conversations cannot read each other's
|
|
262
|
+
* positions, and it is dropped when the turn ends because that is when the fact stops being true: a
|
|
263
|
+
* dispatch that arrives after its turn has finished gets no anchor, which renders as it always did.
|
|
264
|
+
*/
|
|
265
|
+
toolCallLanes = new Map();
|
|
266
|
+
toolCallWaiters = new Map();
|
|
267
|
+
toolCallSites = new Map();
|
|
268
|
+
/** Records that Pi's `toolCallId` became row `row` of `messageId`. */
|
|
269
|
+
noteToolCallSite(conversationId, toolCallId, messageId, row) {
|
|
270
|
+
if (!toolCallId)
|
|
271
|
+
return;
|
|
272
|
+
let sites = this.toolCallSites.get(conversationId);
|
|
273
|
+
if (!sites) {
|
|
274
|
+
sites = new Map();
|
|
275
|
+
this.toolCallSites.set(conversationId, sites);
|
|
276
|
+
}
|
|
277
|
+
sites.set(toolCallId, { messageId, row });
|
|
278
|
+
for (const wake of this.toolCallWaiters.get(`${conversationId}:${toolCallId}`) ?? [])
|
|
279
|
+
wake();
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* The call a dispatch belongs to, as the two fields a card carries. Absent - rather than row zero - when
|
|
283
|
+
* there is no call to point at: a person pressing 派子智能体 has no tool call, a dispatch from an older
|
|
284
|
+
* extension has no id, and a dispatch that landed after its turn ended has outlived the map.
|
|
285
|
+
*/
|
|
286
|
+
originForToolCall(conversationId, toolCallId) {
|
|
287
|
+
if (!toolCallId)
|
|
288
|
+
return undefined;
|
|
289
|
+
const site = this.toolCallSites.get(conversationId)?.get(toolCallId);
|
|
290
|
+
return site ? { originMessageId: site.messageId, originCallRow: site.row } : undefined;
|
|
291
|
+
}
|
|
292
|
+
async waitForToolCall(conversationId, toolCallId) {
|
|
293
|
+
const origin = this.originForToolCall(conversationId, toolCallId);
|
|
294
|
+
if (origin) {
|
|
295
|
+
await this.toolCallLanes.get(conversationId);
|
|
296
|
+
return origin;
|
|
297
|
+
}
|
|
298
|
+
if (!toolCallId || !this.activeRuns.has(conversationId))
|
|
299
|
+
return undefined;
|
|
300
|
+
// The tool POST and Pi's stdout use independent transports. HTTP may win even
|
|
301
|
+
// though Pi emitted tool_execution_start first; wait for that event, not a clock position.
|
|
302
|
+
const key = `${conversationId}:${toolCallId}`;
|
|
303
|
+
await new Promise(resolve => {
|
|
304
|
+
const waiters = this.toolCallWaiters.get(key) ?? new Set();
|
|
305
|
+
const wake = () => { clearTimeout(timer); waiters.delete(wake); if (!waiters.size)
|
|
306
|
+
this.toolCallWaiters.delete(key); resolve(); };
|
|
307
|
+
const timer = setTimeout(wake, 2000);
|
|
308
|
+
waiters.add(wake);
|
|
309
|
+
this.toolCallWaiters.set(key, waiters);
|
|
310
|
+
});
|
|
311
|
+
await this.toolCallLanes.get(conversationId);
|
|
312
|
+
return this.originForToolCall(conversationId, toolCallId);
|
|
313
|
+
}
|
|
314
|
+
execService;
|
|
315
|
+
backgroundLogDirectory;
|
|
316
|
+
execSettlements = new Map();
|
|
317
|
+
setExecService(execService, logDirectory) {
|
|
318
|
+
this.execService = execService;
|
|
319
|
+
this.backgroundLogDirectory = logDirectory;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Called by the exec completion handler in index.ts when a background exec session ends.
|
|
323
|
+
* Injects the result into the conversation and cleans up the background task record.
|
|
324
|
+
*
|
|
325
|
+
* The result is now a REAL queue item, not a one-way notice the model never gets to read: it lands
|
|
326
|
+
* with `delivery: "waiting"` (so the dock shows it), at the front of the waiting set (so any pending
|
|
327
|
+
* user sends wait behind it), and the conversation auto-starts a turn for the agent to handle it
|
|
328
|
+
* when nothing else is busy. The render stays as a 后台回传 block throughout - in dock and in
|
|
329
|
+
* transcript - so a `role: "user"` is never impersonated.
|
|
330
|
+
*/
|
|
331
|
+
enqueueExecResult(sessionId, exitCode, stdout, stderr, completion) {
|
|
332
|
+
const task = this.store.backgroundTask(sessionId);
|
|
333
|
+
if (!task)
|
|
334
|
+
return;
|
|
335
|
+
const rawOutput = stdout + stderr;
|
|
336
|
+
const output = sanitizeBackgroundOutput(rawOutput).slice(-BACKGROUND_LOG_LIMIT);
|
|
337
|
+
const offset = completion?.offset ?? stdout.length + stderr.length;
|
|
338
|
+
const status = completion?.status === "cancelled" || completion?.status === "interrupted"
|
|
339
|
+
? completion.status : exitCode === 0 && !completion?.signal ? "completed" : "failed";
|
|
340
|
+
const reason = status === "cancelled" ? "已由用户终止"
|
|
341
|
+
: status === "interrupted" ? "服务停止,任务已中断"
|
|
342
|
+
: completion?.signal ? `进程收到信号 ${completion.signal}`
|
|
343
|
+
: status === "failed" ? `Command exited with code ${exitCode}` : undefined;
|
|
344
|
+
const settling = this.trackDetached(this.finishBackgroundResult(task, {
|
|
345
|
+
status, output, outputOffset: offset, outputTruncated: offset > rawOutput.length,
|
|
346
|
+
exitCode, signal: completion?.signal, reason,
|
|
347
|
+
}, status === "completed" || status === "failed")).catch(error => {
|
|
348
|
+
console.warn("Super Pi: could not record background command completion:", error);
|
|
349
|
+
}).finally(() => {
|
|
350
|
+
if (this.execSettlements.get(sessionId) === settling)
|
|
351
|
+
this.execSettlements.delete(sessionId);
|
|
352
|
+
});
|
|
353
|
+
this.execSettlements.set(sessionId, settling);
|
|
354
|
+
}
|
|
355
|
+
async failBackgroundTaskStart(taskId, reason, cancelled = false) {
|
|
356
|
+
const task = this.store.backgroundTask(taskId);
|
|
357
|
+
if (task)
|
|
358
|
+
await this.finishBackgroundResult(task, { status: cancelled ? "cancelled" : "failed", reason }, false);
|
|
359
|
+
}
|
|
360
|
+
async finishBackgroundResult(task, outcome, deliver, summary) {
|
|
361
|
+
const queued = await this.serializeConversation(task.conversationId, async () => {
|
|
362
|
+
if (!this.store.backgroundTask(task.id))
|
|
363
|
+
return;
|
|
364
|
+
let logPath;
|
|
365
|
+
if (outcome.output && this.backgroundLogDirectory && /^[A-Za-z0-9_-]+$/u.test(task.id)) {
|
|
366
|
+
try {
|
|
367
|
+
await mkdir(this.backgroundLogDirectory, { recursive: true });
|
|
368
|
+
const path = join(this.backgroundLogDirectory, task.id + ".log");
|
|
369
|
+
await writeFile(path, outcome.output, "utf8");
|
|
370
|
+
logPath = path;
|
|
371
|
+
}
|
|
372
|
+
catch (error) {
|
|
373
|
+
console.warn("Super Pi: could not save background log file:", error);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
const excerpt = capText(summary ?? outcome.output ?? "", 4000, "后台输出").text.trim();
|
|
377
|
+
const details = [
|
|
378
|
+
outcome.reason,
|
|
379
|
+
outcome.exitCode === undefined ? "" : `退出码:${outcome.exitCode}`,
|
|
380
|
+
excerpt || (!outcome.output ? "本次任务未产生输出。" : ""),
|
|
381
|
+
logPath ? `${outcome.outputTruncated ? "保留的日志尾部" : "日志文件"}:${logPath}` : "",
|
|
382
|
+
].filter(Boolean).join("\n\n");
|
|
383
|
+
const ok = outcome.status === "completed";
|
|
384
|
+
const tag = ok ? "task_result" : "task_error";
|
|
385
|
+
const kind = task.agentId === "exec" ? "exec" : "subagent";
|
|
386
|
+
const result = `<task id="${task.id}" state="${ok ? "completed" : "error"}" kind="${kind}">\n<summary>${task.title}</summary>\n<${tag}>\n${details}</${tag}>\n</task>`;
|
|
387
|
+
return this.store.finishBackgroundTask(task.id, outcome, result, deliver);
|
|
388
|
+
});
|
|
389
|
+
if (!queued)
|
|
390
|
+
return;
|
|
391
|
+
if (task.agentId === "exec") {
|
|
392
|
+
this.broadcaster.broadcast({ type: "exec.exit", sessionId: task.id, conversationId: task.conversationId, exitCode: outcome.exitCode, stdout: outcome.output ?? "", stderr: "" });
|
|
393
|
+
}
|
|
394
|
+
this.broadcaster.broadcastState();
|
|
395
|
+
if (queued.delivery === "waiting")
|
|
396
|
+
this.startBackgroundResult(task.conversationId, queued.id);
|
|
397
|
+
await this.settleBackgroundStatus(task.conversationId);
|
|
398
|
+
}
|
|
399
|
+
startBackgroundResult(conversationId, messageId) {
|
|
400
|
+
void this.trackDetached(this.dispatchBackgroundResult(conversationId, messageId)).catch(error => {
|
|
401
|
+
console.warn("Super Pi: could not start a background completion turn:", error);
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Delivers an orchestrated child session's final output to its direct parent. This intentionally uses
|
|
406
|
+
* the same waiting-queue contract as background sub-agent results: one result per turn, ahead of
|
|
407
|
+
* unclaimed user messages, with an automatic follow-up turn only when the parent is idle.
|
|
408
|
+
*/
|
|
409
|
+
async enqueueSessionResult(input) {
|
|
410
|
+
await this.trackDetached((async () => {
|
|
411
|
+
const parentId = input.parentConversationId;
|
|
412
|
+
if (!parentId)
|
|
413
|
+
return;
|
|
414
|
+
const parent = this.store.conversation(parentId);
|
|
415
|
+
if (!parent || parent.archivedAt)
|
|
416
|
+
return;
|
|
417
|
+
// A corrupt or manually edited parent chain must not bounce a result around a cycle forever.
|
|
418
|
+
const seen = new Set();
|
|
419
|
+
let ancestor = parent;
|
|
420
|
+
while (ancestor && !seen.has(ancestor.id)) {
|
|
421
|
+
if (ancestor.id === input.conversationId)
|
|
422
|
+
return;
|
|
423
|
+
seen.add(ancestor.id);
|
|
424
|
+
ancestor = ancestor.parentConversationId ? this.store.conversation(ancestor.parentConversationId) : undefined;
|
|
425
|
+
}
|
|
426
|
+
const failed = input.error !== undefined;
|
|
427
|
+
const state = failed ? "error" : "completed";
|
|
428
|
+
const tag = failed ? "task_error" : "task_result";
|
|
429
|
+
const output = failed ? input.error : input.output;
|
|
430
|
+
const inline = output.length <= 8_000 ? output : capText(output, 4_000, "子会话输出").text;
|
|
431
|
+
const summary = `Child session ${input.conversationId} ${failed ? "failed" : "completed"}. The full result is in ${input.resultPath}; use the read tool to inspect it.`;
|
|
432
|
+
const message = `<task id="${input.conversationId}" state="${state}" kind="session">\n<summary>${summary}</summary>\n<result_file>${input.resultPath}</result_file>\n<${tag}>\n${inline}\n</${tag}>\n</task>`;
|
|
433
|
+
const queued = await this.serializeConversation(parentId, async () => {
|
|
434
|
+
// The parent can disappear or become archived while this delivery waits for its command lane.
|
|
435
|
+
const current = this.store.conversation(parentId);
|
|
436
|
+
if (!current || current.archivedAt)
|
|
437
|
+
return undefined;
|
|
438
|
+
const row = await this.store.addToolMessage(parentId, message, { delivery: "waiting", prioritizeWaiting: true });
|
|
439
|
+
await this.store.markConversationReported(input.conversationId);
|
|
440
|
+
this.broadcaster.broadcastState();
|
|
441
|
+
return row;
|
|
442
|
+
});
|
|
443
|
+
if (!queued)
|
|
444
|
+
return;
|
|
445
|
+
void this.trackDetached(this.dispatchBackgroundResult(parentId, queued.id)).catch((error) => {
|
|
446
|
+
console.warn(`Super Pi: dispatch child session result failed: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
447
|
+
});
|
|
448
|
+
})());
|
|
449
|
+
}
|
|
450
|
+
dispatchBackgroundResult(conversationId, messageId) {
|
|
451
|
+
return this.processWaitingMessage(conversationId, messageId, { ifIdle: true, backgroundResult: true });
|
|
452
|
+
}
|
|
453
|
+
wakeWaitingBackgroundResult(conversationId) {
|
|
454
|
+
if (this.shuttingDown || this.interruptTargets.has(conversationId) || this.activeRuns.has(conversationId))
|
|
455
|
+
return;
|
|
456
|
+
const pending = this.pendingBackgroundWakeups.get(conversationId);
|
|
457
|
+
if (!pending)
|
|
458
|
+
return;
|
|
459
|
+
const waiting = this.store.listWaitingMessages(conversationId).filter(item => item.delivery === "waiting" && pending.has(item.id));
|
|
460
|
+
const [next, ...remaining] = waiting;
|
|
461
|
+
if (remaining.length)
|
|
462
|
+
this.pendingBackgroundWakeups.set(conversationId, new Set(remaining.map(item => item.id)));
|
|
463
|
+
else
|
|
464
|
+
this.pendingBackgroundWakeups.delete(conversationId);
|
|
465
|
+
if (next)
|
|
466
|
+
this.startBackgroundResult(conversationId, next.id);
|
|
467
|
+
}
|
|
468
|
+
async stopBackgroundTask(taskId) {
|
|
469
|
+
const task = this.store.backgroundTask(taskId);
|
|
470
|
+
if (task?.agentId === "exec" && await this.execService?.stop?.(taskId)) {
|
|
471
|
+
await this.execSettlements.get(taskId);
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
if (task?.agentId === "exec")
|
|
475
|
+
this.execService?.kill(taskId);
|
|
476
|
+
this.subagents.stop(taskId);
|
|
477
|
+
if (!task)
|
|
478
|
+
return;
|
|
479
|
+
const run = task.agentId === "exec" ? undefined : this.store.snapshot().subagentRuns.find(item => item.id === task.id);
|
|
480
|
+
const output = run ? subagentProgress(run) : task.output;
|
|
481
|
+
await this.finishBackgroundResult(task, {
|
|
482
|
+
status: "cancelled",
|
|
483
|
+
reason: "已由用户手动终止",
|
|
484
|
+
output: output?.slice(-BACKGROUND_LOG_LIMIT),
|
|
485
|
+
outputOffset: task.outputOffset,
|
|
486
|
+
outputTruncated: task.outputTruncated || run?.outputTruncated || (output?.length ?? 0) > BACKGROUND_LOG_LIMIT || run?.toolCalls?.some(call => call.outputTruncated),
|
|
487
|
+
}, false);
|
|
488
|
+
}
|
|
489
|
+
hasActiveBackgroundTasks(conversationId) {
|
|
490
|
+
const tasks = this.store.snapshot().backgroundTasks ?? [];
|
|
491
|
+
return tasks.some((t) => t.conversationId === conversationId && (t.status === "running" || !t.status));
|
|
492
|
+
}
|
|
493
|
+
async settleBackgroundStatus(conversationId) {
|
|
494
|
+
const conv = this.store.conversation(conversationId);
|
|
495
|
+
if (!conv || conv.status !== "awaiting_background")
|
|
496
|
+
return;
|
|
497
|
+
if (this.activeRuns.has(conversationId))
|
|
498
|
+
return;
|
|
499
|
+
if (this.hasActiveBackgroundTasks(conversationId))
|
|
500
|
+
return;
|
|
501
|
+
const hasWaiting = this.store.listWaitingMessages(conversationId).some(m => m.delivery === "waiting");
|
|
502
|
+
if (!hasWaiting) {
|
|
503
|
+
await this.store.setStatus(conversationId, "completed");
|
|
504
|
+
this.broadcaster.broadcastState();
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/** Per-conversation command lane. All queue mutations and run claims use the same lane, so
|
|
508
|
+
* two browser tabs cannot both observe an idle conversation and start duplicate turns. */
|
|
509
|
+
conversationOps = new Map();
|
|
510
|
+
/** Detached work (human and background sub-agents) which shutdown must still await. */
|
|
511
|
+
detached = new Set();
|
|
512
|
+
constructor(store, runtime, subagents, broadcaster, extensionUiService, agentsDir, workflows) {
|
|
513
|
+
this.store = store;
|
|
514
|
+
this.runtime = runtime;
|
|
515
|
+
this.subagents = subagents;
|
|
516
|
+
this.broadcaster = broadcaster;
|
|
517
|
+
this.extensionUiService = extensionUiService;
|
|
518
|
+
this.agentsDir = agentsDir;
|
|
519
|
+
this.workflows = workflows;
|
|
520
|
+
}
|
|
521
|
+
setAgentsDir(dir) {
|
|
522
|
+
this.agentsDir = dir;
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* TELLS THE BROWSER WHICH FILES THE AGENT CHANGED.
|
|
526
|
+
*
|
|
527
|
+
* The whole list goes every time rather than just the newest file, because the event is a SNAPSHOT
|
|
528
|
+
* (like `state` and `subagent.event`): a browser that missed one rebuilds the list from the next
|
|
529
|
+
* one, instead of holding a list assembled from a partial sequence of deltas.
|
|
530
|
+
*/
|
|
531
|
+
broadcastFileChanges(workspaceId) {
|
|
532
|
+
const tracker = this.fileChanges;
|
|
533
|
+
if (!tracker)
|
|
534
|
+
return;
|
|
535
|
+
const { changes, dropped } = tracker.list(workspaceId);
|
|
536
|
+
this.broadcaster.broadcast({
|
|
537
|
+
type: "files.changed",
|
|
538
|
+
workspaceId,
|
|
539
|
+
dropped,
|
|
540
|
+
changes: changes.map((change) => ({
|
|
541
|
+
path: change.path,
|
|
542
|
+
baseline: change.before,
|
|
543
|
+
...(change.beforeUnknown ? { baselineUnknown: true } : {}),
|
|
544
|
+
...(change.conversationId ? { conversationId: change.conversationId } : {}),
|
|
545
|
+
at: change.at,
|
|
546
|
+
})),
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* RECORDS WHAT THE PERSON CHOSE, ON THE `question` CALL THAT ASKED.
|
|
551
|
+
*
|
|
552
|
+
* The call is addressed by its index in the message's `toolCalls`, which is the same addressing every
|
|
553
|
+
* other tool update uses - and the client can only get that index from the row it is already rendering.
|
|
554
|
+
*/
|
|
555
|
+
async answerQuestion(command) {
|
|
556
|
+
const existing = this.store.question(command.conversationId, command.messageId, command.callIndex);
|
|
557
|
+
if (!existing)
|
|
558
|
+
throw new Error("这个工具调用不是一个问题");
|
|
559
|
+
if (existing.status !== "pending")
|
|
560
|
+
return;
|
|
561
|
+
const answers = command.answers ?? [];
|
|
562
|
+
if (!command.cancelled) {
|
|
563
|
+
const seen = new Set();
|
|
564
|
+
if (!Array.isArray(answers) || !answers.length)
|
|
565
|
+
throw new Error("请选择至少一个选项。");
|
|
566
|
+
for (const answer of answers) {
|
|
567
|
+
const item = answer && existing.items.find(item => item.id === answer.id);
|
|
568
|
+
if (!item || seen.has(item.id) || !Array.isArray(answer.selected)
|
|
569
|
+
|| (!item.multiple && answer.selected.length > 1) || new Set(answer.selected).size !== answer.selected.length
|
|
570
|
+
|| answer.selected.some(option => !item.options.includes(option))
|
|
571
|
+
|| (answer.note !== undefined && (!item.extraNote || typeof answer.note !== "string"))) {
|
|
572
|
+
throw new Error("答案与提问选项不匹配。");
|
|
573
|
+
}
|
|
574
|
+
seen.add(item.id);
|
|
575
|
+
}
|
|
576
|
+
if (!answers.some(answer => answer.selected.length))
|
|
577
|
+
throw new Error("请选择至少一个选项。");
|
|
578
|
+
}
|
|
579
|
+
const calls = await this.store.updateToolCall(command.conversationId, command.messageId, command.callIndex, {
|
|
580
|
+
question: {
|
|
581
|
+
items: existing.items,
|
|
582
|
+
status: command.cancelled ? "cancelled" : "answered",
|
|
583
|
+
...(command.cancelled ? {} : { answers }),
|
|
584
|
+
},
|
|
585
|
+
});
|
|
586
|
+
this.broadcaster.broadcast({ type: "message.tools", conversationId: command.conversationId, messageId: command.messageId, toolCalls: calls });
|
|
587
|
+
this.broadcaster.broadcastState();
|
|
588
|
+
this.settleQuestion(command.conversationId, command.messageId, command.callIndex, calls[command.callIndex]?.question);
|
|
589
|
+
}
|
|
590
|
+
questionKey(conversationId, messageId, index) {
|
|
591
|
+
return `${conversationId}\0${messageId}\0${index}`;
|
|
592
|
+
}
|
|
593
|
+
answerPayload(current) {
|
|
594
|
+
const answers = (current.answers ?? []).map((answer) => {
|
|
595
|
+
const asked = current.items.find((item) => item.id === answer.id);
|
|
596
|
+
return { question: asked?.question, selected: answer.selected, ...(answer.note ? { note: answer.note } : {}) };
|
|
597
|
+
});
|
|
598
|
+
return { answers, summary: `用户回答:${answers.map((answer) => answer.selected.join("、")).join(";")}` };
|
|
599
|
+
}
|
|
600
|
+
settleQuestion(conversationId, messageId, index, question) {
|
|
601
|
+
if (!question || question.status === "pending")
|
|
602
|
+
return;
|
|
603
|
+
const key = this.questionKey(conversationId, messageId, index);
|
|
604
|
+
const waiter = this.questionWaiters.get(key);
|
|
605
|
+
if (!waiter)
|
|
606
|
+
return;
|
|
607
|
+
this.questionWaiters.delete(key);
|
|
608
|
+
if (question.status === "answered")
|
|
609
|
+
waiter.resolve(this.answerPayload(question));
|
|
610
|
+
else
|
|
611
|
+
waiter.reject(new Error("用户没有回答这个问题"));
|
|
612
|
+
}
|
|
613
|
+
cancelQuestionWaiters(conversationId) {
|
|
614
|
+
const reason = new Error("用户已停止当前回合,问题未回答");
|
|
615
|
+
for (const [key, waiter] of [...this.questionWaiters]) {
|
|
616
|
+
if (!key.startsWith(`${conversationId}\0`))
|
|
617
|
+
continue;
|
|
618
|
+
this.questionWaiters.delete(key);
|
|
619
|
+
waiter.reject(reason);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* THE `question` TOOL BLOCKS HERE, ON THE CALL THAT ASKED IT.
|
|
624
|
+
*
|
|
625
|
+
* It used to APPEND A BLOCK TO THE MESSAGE and poll the store for an answer, which meant the question
|
|
626
|
+
* had no position in the answer at all: the card rendered after everything the model said, so the text
|
|
627
|
+
* streamed in response to the answer appeared ABOVE the card it was answering. The call is already on
|
|
628
|
+
* screen, already positioned by its `at`, already persisted, already reloads - so the pending wait is
|
|
629
|
+
* registered against it and nothing else is created.
|
|
630
|
+
*
|
|
631
|
+
* A DISMISSAL FAILS THE CALL. It used to resolve with `{cancelled:true}` and let the run continue, so
|
|
632
|
+
* closing a card handed the model a turn it would answer as though it had been told something. OpenCode
|
|
633
|
+
* is unambiguous about this and is the reference here: rejecting a question fails the deferred, the tool
|
|
634
|
+
* dies and the run is interrupted (`packages/core/src/question.ts:128-141`). Nothing is invented to fill
|
|
635
|
+
* the gap - the same rule the Extension UI path already follows, where a cancelled method is never
|
|
636
|
+
* backfilled with `options[0]`.
|
|
637
|
+
*/
|
|
638
|
+
async askQuestion(conversationId) {
|
|
639
|
+
if (this.isChildConversation(conversationId)) {
|
|
640
|
+
const pending = this.store.pendingQuestion(conversationId);
|
|
641
|
+
if (pending) {
|
|
642
|
+
void this.store.updateToolCall(conversationId, pending.messageId, pending.index, {
|
|
643
|
+
question: { items: pending.question.items, status: "cancelled" },
|
|
644
|
+
}).then(() => {
|
|
645
|
+
this.broadcaster.broadcastState();
|
|
646
|
+
}).catch(() => { });
|
|
647
|
+
}
|
|
648
|
+
throw new Error(CHILD_QUESTION_LOCK_REASON);
|
|
649
|
+
}
|
|
650
|
+
// The HTTP callback belongs to the run that admitted it. A stop followed by a new turn clears
|
|
651
|
+
// the conversation's cancellation marker, but must never let an old polling ask bind its row.
|
|
652
|
+
const owner = this.activeRuns.get(conversationId);
|
|
653
|
+
const cancelled = () => this.cancelledQuestionConversations.has(conversationId)
|
|
654
|
+
|| owner?.signal.aborted === true || this.activeRuns.get(conversationId) !== owner;
|
|
655
|
+
// THE ROW ARRIVES AFTER THE REQUEST, AND THAT IS A RACE, NOT A BUG IN THE CALLER.
|
|
656
|
+
//
|
|
657
|
+
// The extension lives INSIDE the Pi process. When Pi starts running the tool it writes
|
|
658
|
+
// `tool_execution_start` to stdout AND calls the tool - so the tool's HTTP request can reach this
|
|
659
|
+
// server while the transcript drain loop is still reading that very record off the pipe. The endpoint
|
|
660
|
+
// therefore asked for a tool call that had not been stored yet, and answered 「这个会话里没有正在
|
|
661
|
+
// 等待回答的 question 工具调用」 - which is a refusal, so the tool FAILED, and the person was never
|
|
662
|
+
// shown the question at all.
|
|
663
|
+
//
|
|
664
|
+
// So the lookup WAITS. A few hundred milliseconds of polling covers the drain, and a question that
|
|
665
|
+
// genuinely has no pending call still fails - just not instantly.
|
|
666
|
+
let found;
|
|
667
|
+
for (let attempt = 0; attempt < 50 && !found; attempt += 1) {
|
|
668
|
+
if (cancelled())
|
|
669
|
+
throw new Error("用户已停止当前回合,问题未回答");
|
|
670
|
+
found = this.store.pendingQuestion(conversationId);
|
|
671
|
+
if (found)
|
|
672
|
+
break;
|
|
673
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
674
|
+
}
|
|
675
|
+
if (!found)
|
|
676
|
+
throw new Error("这个会话里没有正在等待回答的 question 工具调用");
|
|
677
|
+
if (cancelled())
|
|
678
|
+
throw new Error("用户已停止当前回合,问题未回答");
|
|
679
|
+
const { messageId, index } = found;
|
|
680
|
+
return new Promise((resolve, reject) => {
|
|
681
|
+
// No timeout. The promise resolves when the question is answered, rejects when it is cancelled
|
|
682
|
+
// (the only honest "I will not answer" state - resolving with a default would be the model
|
|
683
|
+
// continuing from a question that was never decided). The run-level teardown (stop / abort /
|
|
684
|
+
// shutdown) clears the underlying ask and the client settles it as cancelled, which lands here
|
|
685
|
+
// and rejects. A question that is simply unanswered waits indefinitely.
|
|
686
|
+
if (cancelled()) {
|
|
687
|
+
reject(new Error("用户已停止当前回合,问题未回答"));
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
this.questionWaiters.set(this.questionKey(conversationId, messageId, index), { resolve, reject });
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
/**
|
|
694
|
+
* Resolves the conversation and workspace synchronously for a run.
|
|
695
|
+
*
|
|
696
|
+
* TWO CLONES, NOT TWO SNAPSHOTS. This used to call `store.snapshot()` twice - once for the
|
|
697
|
+
* conversation and once for the workspace - and a snapshot deep-clones the ENTIRE application
|
|
698
|
+
* state: every other conversation, every message in it, every tool result. It runs a handful of
|
|
699
|
+
* times per turn, twice of them before the frame that tells the browser a turn has started, so the
|
|
700
|
+
* size of the whole state was part of the wait between clicking 发送 and seeing 等待 LLM 返回.
|
|
701
|
+
*/
|
|
702
|
+
turnContext(conversationId) {
|
|
703
|
+
const context = this.store.turnContext(conversationId);
|
|
704
|
+
if (!context) {
|
|
705
|
+
// One snapshot, on the error path only, to say WHICH of the two is missing - the messages are
|
|
706
|
+
// what a person acts on, and this path never runs for a conversation that is merely being used.
|
|
707
|
+
const conversation = this.store.snapshot().conversations.find((item) => item.id === conversationId);
|
|
708
|
+
if (!conversation)
|
|
709
|
+
throw new Error("会话不存在");
|
|
710
|
+
throw new Error(`会话所属的工作区 ${conversation.workspaceId} 已不存在,拒绝运行`);
|
|
711
|
+
}
|
|
712
|
+
if (context.conversation.warmSession)
|
|
713
|
+
throw new Error("预热快照只能通过项目派发使用");
|
|
714
|
+
return context;
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Resolves conversation and workspace working directory for subagent dispatch.
|
|
718
|
+
*/
|
|
719
|
+
async dispatchContext(conversationId) {
|
|
720
|
+
const { conversation, workspace } = this.turnContext(conversationId);
|
|
721
|
+
return { conversation, cwd: await resolveSessionCwd(workspace.path, conversation.cwd) };
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* Checks whether a conversation has an active turn running.
|
|
725
|
+
*/
|
|
726
|
+
isRunning(conversationId) {
|
|
727
|
+
return this.activeRuns.has(conversationId);
|
|
728
|
+
}
|
|
729
|
+
/** Waits for this conversation's current producer, without waiting for unrelated sessions. */
|
|
730
|
+
async waitForConversationIdle(conversationId) {
|
|
731
|
+
while (this.activeRuns.has(conversationId)) {
|
|
732
|
+
const completion = this.runCompletions.get(conversationId)?.promise;
|
|
733
|
+
if (completion)
|
|
734
|
+
await completion;
|
|
735
|
+
else
|
|
736
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
/** Returns true while a stop has been requested and the old producer is still unwinding. */
|
|
740
|
+
isStopping(conversationId) {
|
|
741
|
+
// Use the same identity as the slot; a separate conversation-keyed flag can leak across owners.
|
|
742
|
+
return this.activeRuns.get(conversationId)?.signal.aborted === true;
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Checks the session credential together with the application-level turn truth.
|
|
746
|
+
*
|
|
747
|
+
* `activeRuns` is set synchronously before `runtime.answer()` is entered and cleared in that same
|
|
748
|
+
* turn's finally block. It is therefore the authoritative answer to "is there a primary turn to act
|
|
749
|
+
* for?". Keeping a second set in the runtime made correctness depend on two lifecycles agreeing and
|
|
750
|
+
* left HTTP-only paths with no owner at all.
|
|
751
|
+
*/
|
|
752
|
+
verifyPrimaryCapability(conversationId, capability) {
|
|
753
|
+
const controller = this.activeRuns.get(conversationId);
|
|
754
|
+
return verifyCapability(conversationId, capability, { running: Boolean(controller && !controller.signal.aborted) });
|
|
755
|
+
}
|
|
756
|
+
foregroundSignal(conversationId) {
|
|
757
|
+
return this.activeRuns.get(conversationId)?.signal;
|
|
758
|
+
}
|
|
759
|
+
canAdmitBackgroundTask(signal) {
|
|
760
|
+
return !this.shuttingDown && !signal?.aborted;
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Aborts all active conversation runs and sub-agents.
|
|
764
|
+
*/
|
|
765
|
+
abortAll() {
|
|
766
|
+
this.interruptTargets.clear();
|
|
767
|
+
this.memory?.cancelAll();
|
|
768
|
+
for (const controller of this.activeRuns.values()) {
|
|
769
|
+
controller.abort();
|
|
770
|
+
}
|
|
771
|
+
this.subagents.abortAll();
|
|
772
|
+
}
|
|
773
|
+
/**
|
|
774
|
+
* Waits for conversation turns and detached dispatches to run their finally blocks.
|
|
775
|
+
* The recorder has its own wait because workflow steps can reach it without being
|
|
776
|
+
* represented by a detached promise here.
|
|
777
|
+
*/
|
|
778
|
+
async waitForIdle() {
|
|
779
|
+
while (this.activeRuns.size > 0 || this.detached.size > 0) {
|
|
780
|
+
const pending = [...this.detached];
|
|
781
|
+
if (pending.length)
|
|
782
|
+
await Promise.allSettled(pending);
|
|
783
|
+
else
|
|
784
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
785
|
+
}
|
|
786
|
+
await this.subagents.waitForIdle();
|
|
787
|
+
await this.memory?.waitForIdle();
|
|
788
|
+
}
|
|
789
|
+
trackDetached(work) {
|
|
790
|
+
this.detached.add(work);
|
|
791
|
+
// Do not discard `finally()`: its returned promise would reject a second time
|
|
792
|
+
// when the tracked work fails, producing an unhandled rejection during shutdown.
|
|
793
|
+
void work.then(() => this.detached.delete(work), () => this.detached.delete(work));
|
|
794
|
+
return work;
|
|
795
|
+
}
|
|
796
|
+
serializeConversation(conversationId, work) {
|
|
797
|
+
const previous = this.conversationOps.get(conversationId) ?? Promise.resolve();
|
|
798
|
+
const next = previous.catch(() => undefined).then(work);
|
|
799
|
+
const lane = next.then(() => undefined, () => undefined);
|
|
800
|
+
this.conversationOps.set(conversationId, lane);
|
|
801
|
+
void lane.finally(() => { if (this.conversationOps.get(conversationId) === lane)
|
|
802
|
+
this.conversationOps.delete(conversationId); });
|
|
803
|
+
return next;
|
|
804
|
+
}
|
|
805
|
+
/** Priority begins immediately after messages already handed to Pi, in their FIFO order. */
|
|
806
|
+
async moveAheadOfUnclaimed(conversationId, messageId) {
|
|
807
|
+
const waiting = this.store.listWaitingMessages(conversationId);
|
|
808
|
+
const lastClaimed = waiting.reduce((last, item, index) => item.delivery === "sending" ? index : last, -1);
|
|
809
|
+
await this.store.reorderWaitingMessage(conversationId, messageId, lastClaimed + 1);
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Stops an active turn run for a conversation.
|
|
813
|
+
*/
|
|
814
|
+
async stopRun(conversationId, options) {
|
|
815
|
+
// Abort immediately before waiting for the conversation lane; otherwise a stop queued behind a
|
|
816
|
+
// long streaming command could never reach the controller that it is meant to cancel.
|
|
817
|
+
const controller = this.activeRuns.get(conversationId);
|
|
818
|
+
controller?.abort();
|
|
819
|
+
this.broadcaster.broadcast({ type: "run.stopping", conversationId });
|
|
820
|
+
// A synchronous task tool can be waiting for its child HTTP response. Stop children and plans
|
|
821
|
+
// before awaiting the parent's idle promise, otherwise parent and child wait on each other until
|
|
822
|
+
// the SDK's five-second backstop. Do this before any await so a stale stop cannot reach new work.
|
|
823
|
+
this.workflows.stopConversation(conversationId);
|
|
824
|
+
let backgroundStops;
|
|
825
|
+
if (!options?.foregroundOnly) {
|
|
826
|
+
this.subagents.stopConversation(conversationId);
|
|
827
|
+
const tasks = this.store.snapshot().backgroundTasks.filter(task => task.conversationId === conversationId);
|
|
828
|
+
backgroundStops = Promise.allSettled(tasks.map(task => this.stopBackgroundTask(task.id)));
|
|
829
|
+
}
|
|
830
|
+
// Cancel human-facing waits BEFORE asking Pi to become idle. A session can be blocked inside an
|
|
831
|
+
// extension UI bridge or the question tool; Pi's idle promise cannot settle until that wait is
|
|
832
|
+
// released, so cancelling after `runtime.stop()` turns a click into the full idle backstop.
|
|
833
|
+
await this.cancelPendingRunInteractions(conversationId, options?.foregroundOnly);
|
|
834
|
+
// Persisting cancelled question rows yields to other commands. The old turn can finish and a
|
|
835
|
+
// new one can claim its slot during that await; runtime.stop looks up the CURRENT SDK turn by id,
|
|
836
|
+
// so calling it unconditionally here would abort the new turn on behalf of the old stop click.
|
|
837
|
+
if (this.activeRuns.get(conversationId) === controller)
|
|
838
|
+
await this.runtime.stop?.(conversationId);
|
|
839
|
+
await this.serializeConversation(conversationId, () => this.stopRunUnsafe(conversationId, controller, options?.foregroundOnly));
|
|
840
|
+
const failed = (await backgroundStops)?.find(result => result.status === "rejected");
|
|
841
|
+
if (failed)
|
|
842
|
+
throw failed.reason;
|
|
843
|
+
}
|
|
844
|
+
/** Releases waits that can prevent Pi's abort from reaching its idle state. Idempotent by design. */
|
|
845
|
+
async cancelPendingRunInteractions(conversationId, foregroundOnly) {
|
|
846
|
+
this.cancelledQuestionConversations.add(conversationId);
|
|
847
|
+
this.cancelQuestionWaiters(conversationId);
|
|
848
|
+
this.memory?.cancel(conversationId);
|
|
849
|
+
this.extensionUiService.cancelPendingUi(conversationId, "aborted", foregroundOnly ? {} : undefined);
|
|
850
|
+
// Read only this conversation. The old full-state snapshot cloned every historical transcript before
|
|
851
|
+
// the stop could even settle its pending questions.
|
|
852
|
+
await Promise.all(this.store.pendingQuestions(conversationId).map(async (pending) => {
|
|
853
|
+
try {
|
|
854
|
+
const calls = await this.store.updateToolCall(conversationId, pending.messageId, pending.index, { question: { items: pending.question.items, status: "cancelled" } });
|
|
855
|
+
this.broadcaster.broadcast({ type: "message.tools", conversationId, messageId: pending.messageId, toolCalls: calls });
|
|
856
|
+
this.broadcaster.broadcastState();
|
|
857
|
+
this.settleQuestion(conversationId, pending.messageId, pending.index, calls[pending.index]?.question);
|
|
858
|
+
}
|
|
859
|
+
catch (error) {
|
|
860
|
+
console.warn(`Super Pi: could not cancel pending question for ${conversationId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
861
|
+
}
|
|
862
|
+
}));
|
|
863
|
+
}
|
|
864
|
+
async stopRunUnsafe(conversationId, expectedController, foregroundOnly) {
|
|
865
|
+
// A newer turn may have claimed this conversation while the old SDK session was draining. Its
|
|
866
|
+
// pending question belongs to the new turn and must never be cancelled by the stale stop.
|
|
867
|
+
// The first cancellation happens at stop arrival, before waiting for Pi idle. Keep this call here
|
|
868
|
+
// as an idempotent safety net for callers that enter the serialized cleanup directly. If a new run
|
|
869
|
+
// has claimed the slot while the old stop was waiting, this cleanup belongs to the old controller and
|
|
870
|
+
// must not cancel the new run's questions or stamp its conversation stopped.
|
|
871
|
+
const currentAtEntry = this.activeRuns.get(conversationId);
|
|
872
|
+
// A stop captured no controller (for example, the old run released just before the click) must
|
|
873
|
+
// never cancel a newer run that appeared while its command was in flight. The no-active case is
|
|
874
|
+
// still allowed through for cleanup of a pending question fixture/HTTP ask with no slot owner.
|
|
875
|
+
if (!expectedController && currentAtEntry)
|
|
876
|
+
return;
|
|
877
|
+
if (expectedController && currentAtEntry && currentAtEntry !== expectedController)
|
|
878
|
+
return;
|
|
879
|
+
await this.cancelPendingRunInteractions(conversationId, foregroundOnly);
|
|
880
|
+
// THE `question` TOOL IS A PENDING ASK THE STOP MUST SETTLE, not a client-only state. Its row only
|
|
881
|
+
// ever leaves `pending` through the user's `question.answer` command, so a stop used to leave the
|
|
882
|
+
// ask waiting forever: the extension's HTTP handler never returned, the ask's 250ms full-snapshot
|
|
883
|
+
// poll never cleared, and the card stayed interactive on a dead turn (measured by
|
|
884
|
+
// scripts/question-stop.test.mjs). The same settlement the Extension UI channel gets from
|
|
885
|
+
// `cancelPendingUi` above - answered `cancelled`, never a default - applied to the question rows.
|
|
886
|
+
// AWAIT RUN SLOT RELEASE BEFORE CLAIMING "STOPPED".
|
|
887
|
+
// A stop previously called setStatus("stopped") immediately, while activeRuns still held the
|
|
888
|
+
// conversation slot and the streaming lane was still draining. This produced the contradiction:
|
|
889
|
+
// the UI displayed 「已停止」 and offered 「发送」, but sending a new message hit an active
|
|
890
|
+
// run slot and was falsely placed into 「排队中」, while the previous turn might still produce text.
|
|
891
|
+
await this.awaitRunSlotReleased(conversationId, false, 3_000);
|
|
892
|
+
const current = this.activeRuns.get(conversationId);
|
|
893
|
+
if (current && expectedController && current === expectedController) {
|
|
894
|
+
// The deadline is a bound on this command, not proof that Pi stopped. Force-releasing here lets
|
|
895
|
+
// a new prompt reuse an SDK session that is still running and lets the old turn's final writes
|
|
896
|
+
// race the new one. Keep the slot until its owner's finally releases it; a later completion will
|
|
897
|
+
// broadcast the truthful stopped state.
|
|
898
|
+
throw new Error("停止超时:上一轮仍未退出,当前回合尚未退出。可以重试停止或检查运行时状态。");
|
|
899
|
+
}
|
|
900
|
+
// A newer turn may have started after the aborted turn released its slot but before this cleanup
|
|
901
|
+
// acquired the conversation lane. Never stamp that new turn as stopped.
|
|
902
|
+
if (this.activeRuns.get(conversationId) && this.activeRuns.get(conversationId) !== expectedController)
|
|
903
|
+
return;
|
|
904
|
+
await this.store.setStatus(conversationId, "stopped");
|
|
905
|
+
this.broadcaster.broadcastState();
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Handles queue snapshot updates from Pi RPC.
|
|
909
|
+
*
|
|
910
|
+
* NOW PURELY OBSERVATIONAL, and that is the fix rather than a simplification. It used to INFER a
|
|
911
|
+
* delivery from a drop in `steering.length` and act on it by deleting the oldest `sending` row - which is
|
|
912
|
+
* how a steered message could reach the model, be answered at length, and leave no trace in the
|
|
913
|
+
* transcript the user was reading. A count also cannot say WHICH row, so a snapshot arriving out of
|
|
914
|
+
* order could delete a message that had not been delivered at all.
|
|
915
|
+
*
|
|
916
|
+
* Delivery is now announced by Pi itself, through `onSteerDelivered`, and applied by `streamTurn`. What
|
|
917
|
+
* is left here is the one thing this event is genuinely good for: telling the browser what Pi holds, at
|
|
918
|
+
* the moment Pi holds it.
|
|
919
|
+
*/
|
|
920
|
+
onPiQueue(conversationId, snapshot) {
|
|
921
|
+
this.broadcaster.broadcast({ type: "pi.queue", conversationId, ...snapshot });
|
|
922
|
+
}
|
|
923
|
+
/** Ordinary waiting rows belong to Super Pi and cannot be delivered by a Pi event. */
|
|
924
|
+
matchDeliveredMessage(conversationId, text) {
|
|
925
|
+
if (!text)
|
|
926
|
+
return undefined;
|
|
927
|
+
return this.store.listWaitingMessages(conversationId)
|
|
928
|
+
.find((item) => item.delivery === "sending" && composePrompt(item) === text)?.id;
|
|
929
|
+
}
|
|
930
|
+
/**
|
|
931
|
+
* Empties Pi's steering and follow-up queues for a conversation.
|
|
932
|
+
*
|
|
933
|
+
* WHY A HOST HAS TO DO THIS. Pi delivers whatever is left in those queues when the run ends, and it
|
|
934
|
+
* cannot take back a single message - `clear_queue` is the only queue command it has. So whenever
|
|
935
|
+
* Super Pi takes a message back, the queues have to be emptied, or Pi answers words the user believes
|
|
936
|
+
* they took back.
|
|
937
|
+
*
|
|
938
|
+
* NOTHING IS LOST. Every message Pi was holding is still in Super Pi's own waiting list, and the run's
|
|
939
|
+
* loop answers those as turns of their own.
|
|
940
|
+
*
|
|
941
|
+
* THE STEERS COME BACK. Emptying the queues also empties the steering queue, and a steer is a message
|
|
942
|
+
* the user asked to be answered NOW - so the ones Pi had not delivered go back in, and clearing the
|
|
943
|
+
* queues for one message does not silently un-steer another.
|
|
944
|
+
*/
|
|
945
|
+
/**
|
|
946
|
+
* Empties Pi's steering and follow-up queues for a conversation, returning any steering message
|
|
947
|
+
* IDs that were intentionally withheld because they appear in `excludeMessageIds`.
|
|
948
|
+
*
|
|
949
|
+
* Remaining steering messages not in `excludeMessageIds` are put back into Pi's steering queue
|
|
950
|
+
* in FIFO order (matching at most once per message ID even when two messages share identical text).
|
|
951
|
+
*/
|
|
952
|
+
async clearPiQueues(conversationId, options) {
|
|
953
|
+
const evictedSteerIds = new Set();
|
|
954
|
+
if (!this.runtime.clearQueues)
|
|
955
|
+
return evictedSteerIds;
|
|
956
|
+
let cleared;
|
|
957
|
+
try {
|
|
958
|
+
cleared = await this.runtime.clearQueues(conversationId);
|
|
959
|
+
}
|
|
960
|
+
catch (error) {
|
|
961
|
+
console.warn(`Super Pi: clearing Pi's queues for ${conversationId} failed: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
962
|
+
return evictedSteerIds;
|
|
963
|
+
}
|
|
964
|
+
const matchedSteerIds = new Set();
|
|
965
|
+
const excludeIds = options?.excludeMessageIds;
|
|
966
|
+
for (const text of cleared.steering ?? []) {
|
|
967
|
+
const message = this.store.listWaitingMessages(conversationId)
|
|
968
|
+
.find((item) => item.delivery === "sending" && composePrompt(item) === text && !matchedSteerIds.has(item.id));
|
|
969
|
+
if (!message)
|
|
970
|
+
continue;
|
|
971
|
+
matchedSteerIds.add(message.id);
|
|
972
|
+
if (excludeIds?.has(message.id)) {
|
|
973
|
+
evictedSteerIds.add(message.id);
|
|
974
|
+
continue;
|
|
975
|
+
}
|
|
976
|
+
// A STEER NEEDS A TURN TO GO INTO. With no turn running there is nothing to steer, and the message
|
|
977
|
+
// is released back to `waiting` when the run ends anyway - so it is answered as a turn of its own.
|
|
978
|
+
if (this.runtime.canSteer && !this.runtime.canSteer(conversationId))
|
|
979
|
+
continue;
|
|
980
|
+
try {
|
|
981
|
+
await this.runtime.steer?.(conversationId, text, message.images);
|
|
982
|
+
}
|
|
983
|
+
catch (error) {
|
|
984
|
+
console.warn(`Super Pi: putting a steered message back failed: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
return evictedSteerIds;
|
|
988
|
+
}
|
|
989
|
+
/**
|
|
990
|
+
* Opens a turn on a message that is ALREADY IN THE TRANSCRIPT.
|
|
991
|
+
*
|
|
992
|
+
* It creates no user message. The words were written when the user pressed send - that is the whole
|
|
993
|
+
* promise the client is making - so opening a turn can only mark that message as no longer waiting and
|
|
994
|
+
* put the answer beneath it. `store.openTurnOnMessage` does both in one write, and splices the assistant
|
|
995
|
+
* message in directly AFTER rather than appending it, which is what keeps a second waiting message below
|
|
996
|
+
* the reply to the first.
|
|
997
|
+
*/
|
|
998
|
+
async openTurn(conversationId, messageId) {
|
|
999
|
+
const conversation = this.store.snapshot().conversations.find(item => item.id === conversationId);
|
|
1000
|
+
if (!conversation)
|
|
1001
|
+
throw new Error("找不到这个会话。");
|
|
1002
|
+
const agent = await this.runtime.agentFor?.(conversation);
|
|
1003
|
+
const identity = agent ? { id: agent.id, name: agent.name } : { name: "Pi" };
|
|
1004
|
+
const opened = await this.store.openTurnOnMessage(conversationId, messageId, identity);
|
|
1005
|
+
this.broadcaster.broadcastState();
|
|
1006
|
+
return opened;
|
|
1007
|
+
}
|
|
1008
|
+
/**
|
|
1009
|
+
* Streams a turn via AgentRuntime.
|
|
1010
|
+
*
|
|
1011
|
+
* A TURN CAN CONTAIN MORE THAN ONE ANSWER. When Pi delivers a steered message it announces the
|
|
1012
|
+
* boundary (`message_start`), and everything streamed after it is the answer to THAT message rather than
|
|
1013
|
+
* more of the same one. So this function can be handed a different `assistant` mid-flight: `assistant`
|
|
1014
|
+
* is a parameter rather than a const precisely so one assignment redirects every handler below, each of
|
|
1015
|
+
* which closes over the binding rather than over the value it saw when it was made.
|
|
1016
|
+
*
|
|
1017
|
+
* Before this, a delivered steer's answer was appended to the message that was already streaming. The
|
|
1018
|
+
* model was answering words that existed in no message at all, and the transcript showed a reply with
|
|
1019
|
+
* nothing above it - the user could not find what they had typed, while the agent quoted it back.
|
|
1020
|
+
*/
|
|
1021
|
+
async streamTurn(conversation, workspace, prompt, assistantMessage, controller, userMessageId, images, agentIdentity) {
|
|
1022
|
+
const scope = { id: randomUUID(), controller, accepting: true };
|
|
1023
|
+
this.turnEventScopes.set(conversation.id, scope);
|
|
1024
|
+
const ownsScope = () => this.turnEventScopes.get(conversation.id) === scope
|
|
1025
|
+
&& this.activeRuns.get(conversation.id) === scope.controller;
|
|
1026
|
+
// Abort closes new work, while an existing tool outcome and transcript locator may still settle.
|
|
1027
|
+
// Iterator completion closes ALL runtime callbacks before the accepted write lane is drained.
|
|
1028
|
+
const rejectedEvents = new Set();
|
|
1029
|
+
const acceptsEvent = (event, settlement = false) => {
|
|
1030
|
+
const current = ownsScope() && scope.accepting;
|
|
1031
|
+
if (!current && !rejectedEvents.has(event)) {
|
|
1032
|
+
rejectedEvents.add(event);
|
|
1033
|
+
console.warn(`Super Pi: ignored stale turn event conversation=${conversation.id} turn=${scope.id} event=${event}`);
|
|
1034
|
+
}
|
|
1035
|
+
return current && (settlement || !controller.signal.aborted);
|
|
1036
|
+
};
|
|
1037
|
+
const traceScope = (phase) => {
|
|
1038
|
+
if (process.env.SUPER_PI_TRACE_LATENCY === "1") {
|
|
1039
|
+
console.info(`[super-pi turn] conversation=${conversation.id} turn=${scope.id} phase=${phase} aborted=${controller.signal.aborted}`);
|
|
1040
|
+
}
|
|
1041
|
+
};
|
|
1042
|
+
traceScope("opened");
|
|
1043
|
+
this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
|
|
1044
|
+
const uiHost = this.extensionUiService.createHost(conversation.id);
|
|
1045
|
+
let assistant = assistantMessage;
|
|
1046
|
+
let currentUserMessageId = userMessageId;
|
|
1047
|
+
let closedOwnScope = false;
|
|
1048
|
+
let toolCalls = [];
|
|
1049
|
+
let pendingTools = Promise.resolve();
|
|
1050
|
+
// A TURN MOVES FROM `waiting` TO `running` ONCE THE MODEL HAS PRODUCED ANY SIGNAL: a text delta
|
|
1051
|
+
// OR a tool-call notice. The `running` state means "we have data flowing", and that is true the
|
|
1052
|
+
// moment Pi yields anything back, regardless of shape. Without this, a pure tool-call turn would
|
|
1053
|
+
// stay in `waiting` until the very end and the reader would see a stuck turn for the whole of a
|
|
1054
|
+
// long tool execution. The flag is the only way to make the flip one-shot: calling `setStatus` on
|
|
1055
|
+
// every delta would be a per-token status write.
|
|
1056
|
+
let firstSignal = true;
|
|
1057
|
+
/**
|
|
1058
|
+
* Promotes the turn to `running`, and ANSWERS WHETHER IT PUBLISHED A STATE SNAPSHOT.
|
|
1059
|
+
*
|
|
1060
|
+
* The answer matters because a state snapshot and a live event are two carriers of the same
|
|
1061
|
+
* information: the snapshot is the whole truth (it carries the text, the thinking and the block
|
|
1062
|
+
* boundaries), and a live `message.delta` / `message.thinking` event is an increment on top of it.
|
|
1063
|
+
* A caller that has ALREADY put a delta into the store must therefore not also publish it as a
|
|
1064
|
+
* live event, or the browser receives it twice and counts it twice - the reasoning the reader
|
|
1065
|
+
* sees is longer than the reasoning the model wrote.
|
|
1066
|
+
*
|
|
1067
|
+
* So the rule is: WHOEVER PUTS THE DELTA IN THE STORE OWNS THE DELIVERY. The promotion publishes
|
|
1068
|
+
* a snapshot only when it actually flips the status, and the caller asks.
|
|
1069
|
+
*/
|
|
1070
|
+
const promoteToRunning = async () => {
|
|
1071
|
+
// Accepted tool writes may drain after the producer closed; that is normal cleanup, not a stale event.
|
|
1072
|
+
if (!ownsScope() || !scope.accepting || controller.signal.aborted || !firstSignal)
|
|
1073
|
+
return false;
|
|
1074
|
+
firstSignal = false;
|
|
1075
|
+
if (this.store.conversationStatus(conversation.id) === "waiting") {
|
|
1076
|
+
await this.store.setStatus(conversation.id, "running");
|
|
1077
|
+
if (!ownsScope() || !scope.accepting || controller.signal.aborted)
|
|
1078
|
+
return false;
|
|
1079
|
+
this.broadcaster.broadcastState();
|
|
1080
|
+
return true;
|
|
1081
|
+
}
|
|
1082
|
+
return false;
|
|
1083
|
+
};
|
|
1084
|
+
// Live events are independent from durable checkpoints. Persisting every token made the stdout
|
|
1085
|
+
// reader wait for one disk transaction per token; over a remote browser connection that backlog
|
|
1086
|
+
// looked exactly like a slow model. Keep the in-memory transcript current, publish immediately, and
|
|
1087
|
+
// checkpoint at most once per short window plus unconditionally at the end of the turn.
|
|
1088
|
+
let checkpointTimer;
|
|
1089
|
+
let checkpointPending = false;
|
|
1090
|
+
const checkpointNow = () => {
|
|
1091
|
+
if (checkpointTimer !== undefined) {
|
|
1092
|
+
clearTimeout(checkpointTimer);
|
|
1093
|
+
checkpointTimer = undefined;
|
|
1094
|
+
}
|
|
1095
|
+
if (!checkpointPending)
|
|
1096
|
+
return;
|
|
1097
|
+
checkpointPending = false;
|
|
1098
|
+
if (!ownsScope())
|
|
1099
|
+
return;
|
|
1100
|
+
// Tool updates and message checkpoints both replace the persisted message. They share this lane
|
|
1101
|
+
// so an earlier text snapshot cannot commit after a newer tool state and erase it on disk.
|
|
1102
|
+
pendingTools = pendingTools.then(async () => {
|
|
1103
|
+
if (ownsScope())
|
|
1104
|
+
await this.store.checkpointMessage(conversation.id, assistant.id);
|
|
1105
|
+
}).catch((error) => {
|
|
1106
|
+
console.warn(`Super Pi: streaming checkpoint failed: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
1107
|
+
});
|
|
1108
|
+
};
|
|
1109
|
+
const scheduleCheckpoint = () => {
|
|
1110
|
+
// The final checkpoint owns all accepted live text after the producer closes.
|
|
1111
|
+
if (!scope.accepting || !ownsScope())
|
|
1112
|
+
return;
|
|
1113
|
+
checkpointPending = true;
|
|
1114
|
+
if (checkpointTimer !== undefined)
|
|
1115
|
+
return;
|
|
1116
|
+
checkpointTimer = setTimeout(checkpointNow, 50);
|
|
1117
|
+
};
|
|
1118
|
+
const enqueueTools = (what, work) => {
|
|
1119
|
+
pendingTools = pendingTools.then(async () => {
|
|
1120
|
+
if (!ownsScope())
|
|
1121
|
+
return;
|
|
1122
|
+
// A TOOL CALL IS A SIGNAL THE MODEL IS ALIVE. Promote `waiting` → `running` on the same
|
|
1123
|
+
// path as text deltas: a tool row appearing on screen is the same "we have data" event
|
|
1124
|
+
// the status needs to reflect. Doing it BEFORE the tool write keeps the order
|
|
1125
|
+
// honest - a client that saw the new tool row in the same frame also saw the running
|
|
1126
|
+
// status, instead of flashing back to a still-spinning waiting mark for the next paint.
|
|
1127
|
+
await promoteToRunning();
|
|
1128
|
+
if (!ownsScope())
|
|
1129
|
+
return;
|
|
1130
|
+
const hadPendingQuestion = toolCalls.some(call => call.question?.status === "pending");
|
|
1131
|
+
toolCalls = await work();
|
|
1132
|
+
if (!ownsScope())
|
|
1133
|
+
return;
|
|
1134
|
+
// Stop may have scanned pending questions before this accepted write reached the Store.
|
|
1135
|
+
// Keep the tool record, but do not resurrect a human wait after cancellation.
|
|
1136
|
+
if (controller.signal.aborted) {
|
|
1137
|
+
for (let index = 0; index < toolCalls.length; index++) {
|
|
1138
|
+
const question = toolCalls[index].question;
|
|
1139
|
+
if (question?.status !== "pending")
|
|
1140
|
+
continue;
|
|
1141
|
+
toolCalls = await this.store.updateToolCall(conversation.id, assistant.id, index, {
|
|
1142
|
+
question: { items: question.items, status: "cancelled" },
|
|
1143
|
+
});
|
|
1144
|
+
if (!ownsScope())
|
|
1145
|
+
return;
|
|
1146
|
+
this.settleQuestion(conversation.id, assistant.id, index, toolCalls[index]?.question);
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
this.broadcaster.broadcast({ type: "message.tools", conversationId: conversation.id, messageId: assistant.id, toolCalls });
|
|
1150
|
+
if (hadPendingQuestion !== toolCalls.some(call => call.question?.status === "pending"))
|
|
1151
|
+
this.broadcaster.broadcastState();
|
|
1152
|
+
}).catch((error) => {
|
|
1153
|
+
console.warn(`Super Pi: recording ${what} failed: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
1154
|
+
});
|
|
1155
|
+
this.toolCallLanes.set(conversation.id, pendingTools);
|
|
1156
|
+
};
|
|
1157
|
+
// HOW MUCH OF THE ANSWER HAD BEEN SPOKEN WHEN EACH CALL WAS ANNOUNCED, counted HERE rather than read
|
|
1158
|
+
// from the store when the write runs.
|
|
1159
|
+
//
|
|
1160
|
+
// The counter is the only ordering that survives the queue below. `enqueueTools` serialises tool writes
|
|
1161
|
+
// onto `pendingTools` so the store cannot be written concurrently, which means a write can land after
|
|
1162
|
+
// text deltas that Pi emitted BEFORE the call - so a length read at write time describes the order of
|
|
1163
|
+
// our own disk writes, not the order the agent produced them, and the browser then renders the turn in
|
|
1164
|
+
// an order that never happened. The runtime calls `onToolCall` synchronously between yields, so a
|
|
1165
|
+
// counter advanced once per yielded delta is the real position of the call in the answer.
|
|
1166
|
+
let spoken = 0;
|
|
1167
|
+
// AND HOW MUCH REASONING HAD BEEN STREAMED, for the same reason and from the same place. The store's
|
|
1168
|
+
// `message.thinking` is only updated at the end of the turn (in `finally`), so it cannot be read here.
|
|
1169
|
+
// The running total is what lets a call made during reasoning anchor inside the thinking block rather than
|
|
1170
|
+
// after it, which is the order the events had.
|
|
1171
|
+
let thought = 0;
|
|
1172
|
+
let thinkingActive = false;
|
|
1173
|
+
let thinkingBlock = -1;
|
|
1174
|
+
let thinkingAnswerAt = -1;
|
|
1175
|
+
let thinkingInterrupted = false;
|
|
1176
|
+
let answerAfterThinking = false;
|
|
1177
|
+
const currentThinkingBlock = () => {
|
|
1178
|
+
if (thinkingBlock >= 0 && !thinkingInterrupted && !answerAfterThinking)
|
|
1179
|
+
return thinkingBlock;
|
|
1180
|
+
// An outside call separates two thoughts even if no answer text was emitted.
|
|
1181
|
+
if (thinkingBlock >= 0)
|
|
1182
|
+
thinkingInterrupted = true;
|
|
1183
|
+
return null;
|
|
1184
|
+
};
|
|
1185
|
+
/**
|
|
1186
|
+
* ONE COUNTER FOR EVERY ROW, AND THE ONLY WAY A ROW NUMBER IS EVER MADE.
|
|
1187
|
+
*
|
|
1188
|
+
* Both maps below are addressed by POSITION in the message's `toolCalls` array, so both have to count
|
|
1189
|
+
* in the same space. They did not: each kept its own `map.size`, and those two numbers stop agreeing
|
|
1190
|
+
* the moment a turn makes two tool calls - the first call's placeholder is consumed and the map is
|
|
1191
|
+
* cleared, so the SECOND placeholder is handed the row number `0` while `appendToolCall` actually put
|
|
1192
|
+
* it at `1`. From there every later write lands on the wrong row: the second call's arguments overwrote
|
|
1193
|
+
* the first call's finished block, and the second call's own row was never settled, so it kept
|
|
1194
|
+
* 「正在生成参数…」 for the rest of the turn. A finished tool that still claims to be generating its
|
|
1195
|
+
* arguments is worse than a missing one - it says the agent is stuck on work it already did.
|
|
1196
|
+
*/
|
|
1197
|
+
let rows = 0;
|
|
1198
|
+
const rowByToolCallId = new Map();
|
|
1199
|
+
/**
|
|
1200
|
+
* Rows for calls the model is STILL WRITING, keyed by the contentIndex its toolcall_start named, and
|
|
1201
|
+
* carrying the name that index announced when it had one.
|
|
1202
|
+
*
|
|
1203
|
+
* The index is the only handle that exists before the arguments are parsed: the tool's id arrives
|
|
1204
|
+
* with toolcall_end, and the host is told nothing until tool_execution_start. Keeping the index → row
|
|
1205
|
+
* map here rather than in the store is what lets tool_execution_start FILL IN the row the reader is
|
|
1206
|
+
* already looking at, instead of appending a second block for the same call and making one call look
|
|
1207
|
+
* like two.
|
|
1208
|
+
*/
|
|
1209
|
+
const preparingRows = new Map();
|
|
1210
|
+
const onToolPreparing = (call) => {
|
|
1211
|
+
if (!acceptsEvent("tool.preparing"))
|
|
1212
|
+
return;
|
|
1213
|
+
const existing = preparingRows.get(call.contentIndex);
|
|
1214
|
+
if (existing === undefined && call.final) {
|
|
1215
|
+
// `toolcall_end` FOR A CALL THAT IS ALREADY ON SCREEN. Pi closes an argument document whenever it
|
|
1216
|
+
// closes one, which is usually before the call runs - but a turn can also close it afterwards, and
|
|
1217
|
+
// by then the row this notice describes has been filled in and its placeholder consumed. Creating
|
|
1218
|
+
// a row here would append a SECOND block for a call the reader is already looking at, which is
|
|
1219
|
+
// the "the agent called a tool it never called" reading. Nothing to do, and saying so here is
|
|
1220
|
+
// cheaper than a row that has to be deleted later.
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
if (existing !== undefined) {
|
|
1224
|
+
// THE NAME IS RE-FILED WHENEVER A BETTER ONE ARRIVES, and an empty one never overwrites a good
|
|
1225
|
+
// one. This is the second half of the pairing fix: `toolcall_start` is allowed to reveal nothing
|
|
1226
|
+
// about the tool, and the row it creates is then filed under `""`, which `onToolCall` below can
|
|
1227
|
+
// never match against a real name. `toolcall_end` carries the authoritative one.
|
|
1228
|
+
if (call.name)
|
|
1229
|
+
existing.name = call.name;
|
|
1230
|
+
// The line naming the call IMPROVES as the arguments arrive - a `read` learns its path from the
|
|
1231
|
+
// first fragment - so it is patched rather than frozen at whatever the first frame could say. The
|
|
1232
|
+
// text is patched as well, and it is the WHOLE text written so far rather than the newest
|
|
1233
|
+
// fragment: it is the same field the execution output later lands in, and the reader watches it
|
|
1234
|
+
// grow in one piece either way.
|
|
1235
|
+
// `args` is patched only when there are any, which is the `toolcall_end` case - a row whose
|
|
1236
|
+
// arguments were never completed has nothing to add, and a patch that changes nothing must not
|
|
1237
|
+
// publish a frame.
|
|
1238
|
+
const patch = {
|
|
1239
|
+
...(call.live ? { live: call.live } : {}),
|
|
1240
|
+
...(call.detail ? { detail: call.detail } : {}),
|
|
1241
|
+
...(call.args ? { args: call.args } : {}),
|
|
1242
|
+
};
|
|
1243
|
+
if (Object.keys(patch).length)
|
|
1244
|
+
enqueueTools("a tool call argument", () => this.store.updateToolCall(conversation.id, assistant.id, existing.row, patch));
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
// No name yet is the normal first token, and it is NOT a reason to wait: the block appearing with an
|
|
1248
|
+
// empty name the instant the model starts writing is what tells the reader anything is happening at
|
|
1249
|
+
// all, and it fills in on the next delta.
|
|
1250
|
+
const at = spoken;
|
|
1251
|
+
const row = rows++;
|
|
1252
|
+
// THE OFFSET IS TAKEN NOW, NOT WHEN THE QUEUED APPEND RUNS. `thought` is the LIVE counter, and the
|
|
1253
|
+
// append below runs when the enqueue chain drains - by which time it may already hold the whole
|
|
1254
|
+
// turn's reasoning, so a call made during reasoning would anchor at the END of the text it was made
|
|
1255
|
+
// inside of and render outside the thinking block. `at` above is captured for exactly this reason;
|
|
1256
|
+
// this one was not, and the JSON persistence backend's slower writes widen the window enough for
|
|
1257
|
+
// the browser test to catch the difference between capturing and reading.
|
|
1258
|
+
const thinkingAt = thought;
|
|
1259
|
+
// The block says WHICH TOOL and WHAT IT IS AIMED AT as soon as either is known. 「工具」 as the name
|
|
1260
|
+
// and 「正在生成参数…」 as the only line below it told a reader nothing for the seconds a large `edit`
|
|
1261
|
+
// spends writing its replacement text - and by the time the file path was on screen, the block looked
|
|
1262
|
+
// broken rather than early. The placeholder word is now only the FALLBACK for the first fragment, when
|
|
1263
|
+
// Pi has not yet said what the call is or what it opens.
|
|
1264
|
+
// Ownership is fixed when the call is announced: once a thinking block is open on this message,
|
|
1265
|
+
// the thinking stage remains open across thinking_end until answer text appears.
|
|
1266
|
+
const callThinkingBlock = (thinkingBlock >= 0 && !thinkingInterrupted && !answerAfterThinking) ? thinkingBlock : null;
|
|
1267
|
+
enqueueTools("a tool call being prepared", () => this.store.appendToolCall(conversation.id, assistant.id, {
|
|
1268
|
+
label: call.name || "工具",
|
|
1269
|
+
...(call.detail ? { detail: call.detail } : { detail: "正在生成参数…" }),
|
|
1270
|
+
preparing: true,
|
|
1271
|
+
at,
|
|
1272
|
+
thinkingAt,
|
|
1273
|
+
thinkingBlock: callThinkingBlock,
|
|
1274
|
+
}));
|
|
1275
|
+
// `thinkingAt` GOES WITH THE PLACEHOLDER. It is how much reasoning had been written when the
|
|
1276
|
+
// model announced this call, and the real call needs it to work out whether the reasoning kept
|
|
1277
|
+
// going afterwards - which is the fact that says whether the call belongs inside the reasoning
|
|
1278
|
+
// fold or in the answer (see `onToolCall`).
|
|
1279
|
+
// THE BLOCK INDEX GOES WITH THE PLACEHOLDER TOO, and it is captured HERE - at the moment the
|
|
1280
|
+
// model announced the call - because that is the only moment the block it belongs to is the
|
|
1281
|
+
// OPEN one. By the time the call runs, the reasoning may have ended and a LATER block may have
|
|
1282
|
+
// opened, and the index of the block the call belongs to is no longer the current one.
|
|
1283
|
+
// THE FOLD THIS CALL BELONGS TO, DECIDED AT THE MOMENT THE MODEL ANNOUNCED IT. A call announced
|
|
1284
|
+
// after the answer started belongs to no fold, even when the reasoning is still running.
|
|
1285
|
+
preparingRows.set(call.contentIndex, {
|
|
1286
|
+
row,
|
|
1287
|
+
name: call.name,
|
|
1288
|
+
thinkingAt,
|
|
1289
|
+
thinkingActive,
|
|
1290
|
+
thinkingBlock: callThinkingBlock,
|
|
1291
|
+
at,
|
|
1292
|
+
});
|
|
1293
|
+
};
|
|
1294
|
+
/**
|
|
1295
|
+
* THE AGENT IS ABOUT TO WRITE A FILE.
|
|
1296
|
+
*
|
|
1297
|
+
* The baseline is captured HERE, at the announcement, because this is the last moment the old content
|
|
1298
|
+
* is still on the disk. By the time the tool has finished, the file holds the new content and the
|
|
1299
|
+
* "before" is gone - which is why a diff cannot be reconstructed afterwards from the file itself.
|
|
1300
|
+
*
|
|
1301
|
+
* The read inside `record` is SYNCHRONOUS on purpose (see `file-changes.ts` for the race it
|
|
1302
|
+
* closes), and it is bounded by a size cap, so it costs a fraction of a millisecond for an
|
|
1303
|
+
* ordinary source file.
|
|
1304
|
+
*/
|
|
1305
|
+
/**
|
|
1306
|
+
* THE PATHS THE AGENT IS WRITING, keyed by tool call id.
|
|
1307
|
+
*
|
|
1308
|
+
* The key is what lets the tool's END confirm the baseline of the right file. The alternative - the
|
|
1309
|
+
* tool card's one-line summary - is a DISPLAY string: whitespace-collapsed and length-capped, so
|
|
1310
|
+
* it is not a path the server can read a file by, and a path with a run of spaces in it would come
|
|
1311
|
+
* back as a path with one space.
|
|
1312
|
+
*/
|
|
1313
|
+
const fileWritePaths = new Map();
|
|
1314
|
+
let runCwd = workspace.path;
|
|
1315
|
+
const onFileWrite = (path, _toolName, toolCallId) => {
|
|
1316
|
+
if (!acceptsEvent("file.write"))
|
|
1317
|
+
return;
|
|
1318
|
+
const tracker = this.fileChanges;
|
|
1319
|
+
if (!tracker)
|
|
1320
|
+
return;
|
|
1321
|
+
// THE PATH AS THE WORKSPACE SPELLS IT, TRANSLATED ONCE.
|
|
1322
|
+
//
|
|
1323
|
+
// This path comes from the MODEL - it is the `path` argument of `write`/`edit` - and a model
|
|
1324
|
+
// that has been told where the workspace is writes an ABSOLUTE path: `/home/me/project/src/a.ts`
|
|
1325
|
+
// is the same file as `src/a.ts`. Every consumer below keys its rows by the workspace's own
|
|
1326
|
+
// spelling - the change tracker, the file index and the name index - so the translation happens
|
|
1327
|
+
// once, here, and all three get the same answer.
|
|
1328
|
+
//
|
|
1329
|
+
// WITHOUT IT the three disagreed: the tracker resolved the path against the workspace and got
|
|
1330
|
+
// it right, while the name index stored the absolute path with its leading slash stripped
|
|
1331
|
+
// (`home/me/project/src/a.ts`) - an entry that matched by name and then pointed at a file that
|
|
1332
|
+
// does not exist.
|
|
1333
|
+
let relative;
|
|
1334
|
+
try {
|
|
1335
|
+
relative = toWorkspaceRelative(workspace.path, isAbsolute(path) ? path : resolve(runCwd, path));
|
|
1336
|
+
}
|
|
1337
|
+
catch {
|
|
1338
|
+
return;
|
|
1339
|
+
}
|
|
1340
|
+
if (!relative)
|
|
1341
|
+
return;
|
|
1342
|
+
tracker.record(workspace.id, relative, { root: workspace.path, conversationId: conversation.id });
|
|
1343
|
+
if (toolCallId)
|
|
1344
|
+
fileWritePaths.set(toolCallId, relative);
|
|
1345
|
+
this.broadcastFileChanges(workspace.id);
|
|
1346
|
+
};
|
|
1347
|
+
const onToolCall = (call) => {
|
|
1348
|
+
if (!acceptsEvent("tool.start"))
|
|
1349
|
+
return;
|
|
1350
|
+
const at = spoken;
|
|
1351
|
+
// THE PLACEHOLDER THAT BELONGS TO THIS CALL, IF ONE IS ON SCREEN.
|
|
1352
|
+
//
|
|
1353
|
+
// A model writing two tool calls writes their arguments in one unbroken stream, so more than one
|
|
1354
|
+
// placeholder can be waiting when the first execution starts. The NAME is what pairs them: Pi
|
|
1355
|
+
// announces `tool_execution_start` with the tool's name and it runs calls in the order it wrote
|
|
1356
|
+
// them, so a name match wins and WRITE ORDER is the fallback.
|
|
1357
|
+
//
|
|
1358
|
+
// IT USED TO FALL BACK ONTO THE NEWEST (`at(-1)`), and that is the wrong end. It never mattered
|
|
1359
|
+
// while the name match worked, and the name match never worked: the runtime read the name out of
|
|
1360
|
+
// `toolcall_start.partial`, which real Pi does not send (`hasPartial:false` on a live probe), so
|
|
1361
|
+
// every placeholder was filed under `""` and every lookup fell through to recency. Two calls then
|
|
1362
|
+
// came back swapped - the row anchored where the model wrote the first one displayed the second -
|
|
1363
|
+
// and a call whose arguments were never completed rendered as a block with no parameters at all.
|
|
1364
|
+
// `entry.name` is also required to be non-empty here, so a run of nameless placeholders can never
|
|
1365
|
+
// "match" each other on two empty strings.
|
|
1366
|
+
const pending = [...preparingRows];
|
|
1367
|
+
const prepared = pending.find(([, entry]) => entry.name !== "" && entry.name === call.name) ?? pending.at(0);
|
|
1368
|
+
// THE CALL THAT IS ALREADY ON SCREEN GETS FILLED IN. Appending here instead would show one call
|
|
1369
|
+
// twice - once as a placeholder, once as the real thing - which reads as the agent calling a tool
|
|
1370
|
+
// it never called.
|
|
1371
|
+
if (prepared !== undefined) {
|
|
1372
|
+
const row = prepared[1].row;
|
|
1373
|
+
preparingRows.delete(prepared[0]);
|
|
1374
|
+
// The id is bound to the row it was FILLED IN, not to a row of the caller's own counting. Every
|
|
1375
|
+
// later update and the outcome resolve through this binding, so a wrong number here is a block
|
|
1376
|
+
// that never settles and one that belongs to a different call.
|
|
1377
|
+
if (call.id) {
|
|
1378
|
+
rowByToolCallId.set(call.id, row);
|
|
1379
|
+
this.noteToolCallSite(conversation.id, call.id, assistant.id, row);
|
|
1380
|
+
}
|
|
1381
|
+
// THE FOLD WAS DECIDED WHEN THE CALL WAS ANNOUNCED, and it stays decided.
|
|
1382
|
+
//
|
|
1383
|
+
// This line used to re-judge the ownership at execution time ("the reasoning had already
|
|
1384
|
+
// stopped AND the answer has started since" - the two-fact rule added in 0.1.181). Two
|
|
1385
|
+
// judgements of one fact is one fact too many: the placeholder row was filed in the fold
|
|
1386
|
+
// when the model announced the call, and this line filed it back outside a moment later.
|
|
1387
|
+
// The reader watched the block JUMP out of the fold and into the answer flow - a wrong
|
|
1388
|
+
// intermediate state, even though the final state was right.
|
|
1389
|
+
//
|
|
1390
|
+
// The rule is the reader's, from 11-09: a call announced before the body text stays in the
|
|
1391
|
+
// block it was announced in. The announcement is the only moment that knows which block that
|
|
1392
|
+
// was, so it is the only moment allowed to decide.
|
|
1393
|
+
const callThinkingBlock = prepared[1].thinkingBlock;
|
|
1394
|
+
// at 也保持宣布时刻的 spoken 偏移,不按执行时刻重算;只有无占位符的调用才用执行时刻的 spoken
|
|
1395
|
+
const callAt = prepared[1].at;
|
|
1396
|
+
enqueueTools("a tool call", () => this.store.updateToolCall(conversation.id, assistant.id, row, {
|
|
1397
|
+
label: call.name,
|
|
1398
|
+
detail: call.detail,
|
|
1399
|
+
args: call.args,
|
|
1400
|
+
live: "",
|
|
1401
|
+
preparing: false,
|
|
1402
|
+
at: callAt,
|
|
1403
|
+
thinkingBlock: callThinkingBlock,
|
|
1404
|
+
...(call.question && !this.isChildConversation(conversation.id) ? { question: call.question } : {}),
|
|
1405
|
+
}));
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
const row = rows++;
|
|
1409
|
+
if (call.id) {
|
|
1410
|
+
rowByToolCallId.set(call.id, row);
|
|
1411
|
+
this.noteToolCallSite(conversation.id, call.id, assistant.id, row);
|
|
1412
|
+
}
|
|
1413
|
+
// Captured for the same reason as the preparing path above: the queued append must anchor the call
|
|
1414
|
+
// where it was MADE, not where the queue happened to be when it drained.
|
|
1415
|
+
//
|
|
1416
|
+
// THIS IS THE PATH WITH NO PLACEHOLDER - Pi never announced a `toolcall_start` for this call,
|
|
1417
|
+
// so there is no earlier moment to compare offsets against, and the reasoning offset is taken
|
|
1418
|
+
// here, at the announcement. Ownership follows the same stage boundary as `onToolPreparing`:
|
|
1419
|
+
// once a thinking block is open on this message, the call belongs to it until answer text arrives.
|
|
1420
|
+
const thinkingAt = thought;
|
|
1421
|
+
// A CALL ANNOUNCED AFTER THE ANSWER BELONGS TO NO FOLD, even when the reasoning is still running.
|
|
1422
|
+
// `currentThinkingBlock()` also marks the thinking as interrupted when it is not active, so it
|
|
1423
|
+
// must NOT be called once the answer has started - that would file an after-answer call between
|
|
1424
|
+
// two stretches of reasoning that were never separated by one.
|
|
1425
|
+
const callThinkingBlock = answerAfterThinking ? null : currentThinkingBlock();
|
|
1426
|
+
enqueueTools("a tool call", () => this.store.appendToolCall(conversation.id, assistant.id, { label: call.name, detail: call.detail, args: call.args, at, thinkingAt, thinkingBlock: callThinkingBlock, ...(call.question && !this.isChildConversation(conversation.id) ? { question: call.question } : {}) }));
|
|
1427
|
+
};
|
|
1428
|
+
const onToolUpdate = (call) => {
|
|
1429
|
+
if (!acceptsEvent("tool.update"))
|
|
1430
|
+
return;
|
|
1431
|
+
const index = call.id ? rowByToolCallId.get(call.id) : undefined;
|
|
1432
|
+
if (index === undefined)
|
|
1433
|
+
return;
|
|
1434
|
+
enqueueTools("a tool call update", () => this.store.updateToolCall(conversation.id, assistant.id, index, { ...(call.args ? { args: call.args } : {}), ...(call.live !== undefined ? { live: call.live } : {}) }));
|
|
1435
|
+
};
|
|
1436
|
+
const onToolEnd = (call) => {
|
|
1437
|
+
if (!acceptsEvent("tool.end", true))
|
|
1438
|
+
return;
|
|
1439
|
+
// THE WRITE IS FINISHED, so the baseline can be CHECKED. The tracker recorded the file's etag when
|
|
1440
|
+
// the write was announced; if the file's etag now differs, the baseline really is the content
|
|
1441
|
+
// from before the write. If it does not, the baseline was taken too late to be shown, and the
|
|
1442
|
+
// tracker says so rather than letting the diff view claim two identical versions are the same.
|
|
1443
|
+
const writtenPath = call.id ? fileWritePaths.get(call.id) : undefined;
|
|
1444
|
+
if (writtenPath) {
|
|
1445
|
+
this.fileChanges?.confirm(workspace.id, writtenPath, workspace.path);
|
|
1446
|
+
if (call.id)
|
|
1447
|
+
fileWritePaths.delete(call.id);
|
|
1448
|
+
this.broadcastFileChanges(workspace.id);
|
|
1449
|
+
void serializeWorkspaceWrite(workspace.path, async () => {
|
|
1450
|
+
const target = await explorerPath(workspace.path, workspace.path, writtenPath);
|
|
1451
|
+
const info = await lstat(target).catch((error) => {
|
|
1452
|
+
if (error.code !== "ENOENT" && error.code !== "ENOTDIR")
|
|
1453
|
+
throw error;
|
|
1454
|
+
});
|
|
1455
|
+
refreshWorkspaceIndex(this.fileIndexes, workspace.id, writtenPath, workspace.path);
|
|
1456
|
+
if (this.nameIndexes && info?.isFile()) {
|
|
1457
|
+
ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
|
|
1458
|
+
recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, writtenPath);
|
|
1459
|
+
}
|
|
1460
|
+
else if (!info)
|
|
1461
|
+
for (const index of this.nameIndexes?.values() ?? []) {
|
|
1462
|
+
if (index.workspaceId !== workspace.id)
|
|
1463
|
+
continue;
|
|
1464
|
+
const target = inScope(workspace.path, index.cwd, writtenPath);
|
|
1465
|
+
if (target)
|
|
1466
|
+
index.removeTree(target);
|
|
1467
|
+
}
|
|
1468
|
+
this.broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id, paths: [writtenPath] });
|
|
1469
|
+
}).catch((error) => {
|
|
1470
|
+
if (error && typeof error === "object" && "status" in error && error.status === 403)
|
|
1471
|
+
return;
|
|
1472
|
+
console.warn("Super Pi: could not update the workspace file tree", error);
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
else if (/^(bash|powershell|shell|command|apply_patch|write|edit)$/i.test(call.name)) {
|
|
1476
|
+
this.broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id });
|
|
1477
|
+
}
|
|
1478
|
+
const index = call.id ? rowByToolCallId.get(call.id) : undefined;
|
|
1479
|
+
if (index === undefined)
|
|
1480
|
+
return;
|
|
1481
|
+
enqueueTools("a tool call outcome", () => this.store.settleToolCall(conversation.id, assistant.id, index, { status: call.status, durationMs: call.durationMs, ...(call.result ? { result: call.result } : {}) }));
|
|
1482
|
+
};
|
|
1483
|
+
/**
|
|
1484
|
+
* PI DELIVERED A STEERED MESSAGE. Everything it streams from here belongs to that message, not to the
|
|
1485
|
+
* one this turn opened with.
|
|
1486
|
+
*
|
|
1487
|
+
* The work goes on the SAME lane as tool writes, which is what makes it safe: the delta handler above
|
|
1488
|
+
* awaits that lane before its first line, so by the time another token is handled the reassignment
|
|
1489
|
+
* below has already happened. Running it inline instead would put a `store` round trip in the middle
|
|
1490
|
+
* of the stdout drain, which is precisely the latency the streaming lane exists to avoid.
|
|
1491
|
+
*
|
|
1492
|
+
* EVERY PER-MESSAGE COUNTER IS RESET, and each for its own reason. `spoken` and `thought` are OFFSETS
|
|
1493
|
+
* WITHIN ONE MESSAGE - the `at` a tool call anchors at, and where a thinking block begins - so
|
|
1494
|
+
* carrying them across would anchor this message's first tool call halfway down the previous answer.
|
|
1495
|
+
* `rows` numbers tool blocks within a message, so it must restart at zero or the new message's first
|
|
1496
|
+
* block is numbered after the old one's. The two maps bind rows and call ids to those numbers and are
|
|
1497
|
+
* cleared rather than reassigned for the same reason. `thinkingBlock` continues numbering on purpose:
|
|
1498
|
+
* it is a global fold sequence, and restarting it would make the browser render two folds numbered 0.
|
|
1499
|
+
*/
|
|
1500
|
+
const onSteerDelivered = (text) => {
|
|
1501
|
+
if (!acceptsEvent("steer.delivered"))
|
|
1502
|
+
return Promise.resolve();
|
|
1503
|
+
enqueueTools("a queued message being delivered", async () => {
|
|
1504
|
+
// A delayed SDK delivery during abort still belongs to the stopped producer.
|
|
1505
|
+
if (!acceptsEvent("steer.delivered"))
|
|
1506
|
+
return toolCalls;
|
|
1507
|
+
const previous = assistant;
|
|
1508
|
+
// Checkpoint first: the message being left behind is complete - Pi drains its queues at a turn
|
|
1509
|
+
// boundary - and this is the last chance to write it durably with the lane it belongs to.
|
|
1510
|
+
await this.store.checkpointMessage(conversation.id, previous.id);
|
|
1511
|
+
if (!acceptsEvent("steer.delivered"))
|
|
1512
|
+
return toolCalls;
|
|
1513
|
+
// Match explicitly steered messages by text. Pi can expand commands, so an unmatched
|
|
1514
|
+
// event can still correspond to a claimed steer. Waiting rows are never considered.
|
|
1515
|
+
const target = this.matchDeliveredMessage(conversation.id, text);
|
|
1516
|
+
const delivered = await this.store.deliverWaitingMessage(conversation.id, agentIdentity, target);
|
|
1517
|
+
// NOTHING TO DELIVER MEANS NOTHING TO SPLIT. Pi may announce a user `message_start` that this
|
|
1518
|
+
// server never handed it - the prompt that opened the turn is the obvious case - and inventing an
|
|
1519
|
+
// assistant message for one of those would open an empty bubble before every single turn.
|
|
1520
|
+
if (!delivered)
|
|
1521
|
+
return toolCalls;
|
|
1522
|
+
if (!ownsScope())
|
|
1523
|
+
return toolCalls;
|
|
1524
|
+
if (this.memory) {
|
|
1525
|
+
const checkpointed = this.store.conversation(conversation.id);
|
|
1526
|
+
if (checkpointed)
|
|
1527
|
+
this.memory.learnFromTurn(checkpointed, currentUserMessageId, previous.id);
|
|
1528
|
+
}
|
|
1529
|
+
currentUserMessageId = delivered.user.id;
|
|
1530
|
+
if (CODING_STANDARD_REQUEST.test(delivered.user.content))
|
|
1531
|
+
await this.recordCodingStandards(conversation.id, delivered.user.id);
|
|
1532
|
+
const next = delivered.assistant;
|
|
1533
|
+
this.broadcaster.broadcastState();
|
|
1534
|
+
assistant = next;
|
|
1535
|
+
spoken = 0;
|
|
1536
|
+
thought = 0;
|
|
1537
|
+
thinkingActive = false;
|
|
1538
|
+
thinkingInterrupted = true;
|
|
1539
|
+
answerAfterThinking = false;
|
|
1540
|
+
rows = 0;
|
|
1541
|
+
rowByToolCallId.clear();
|
|
1542
|
+
preparingRows.clear();
|
|
1543
|
+
toolCalls = [];
|
|
1544
|
+
return [];
|
|
1545
|
+
});
|
|
1546
|
+
return pendingTools;
|
|
1547
|
+
};
|
|
1548
|
+
try {
|
|
1549
|
+
runCwd = await resolveSessionCwd(workspace.path, conversation.cwd);
|
|
1550
|
+
if (this.memory && CODING_STANDARD_REQUEST.test(prompt) && !controller.signal.aborted) {
|
|
1551
|
+
const result = await this.recordCodingStandards(conversation.id, userMessageId);
|
|
1552
|
+
if (result)
|
|
1553
|
+
prompt += `\n\n[平台记忆操作结果] ${result}`;
|
|
1554
|
+
}
|
|
1555
|
+
for await (const delta of this.runtime.answer({
|
|
1556
|
+
conversation,
|
|
1557
|
+
prompt,
|
|
1558
|
+
signal: controller.signal,
|
|
1559
|
+
cwd: runCwd,
|
|
1560
|
+
host: {
|
|
1561
|
+
notify: (request) => { if (acceptsEvent("ui.notify"))
|
|
1562
|
+
uiHost.notify(request); },
|
|
1563
|
+
ask: (request) => acceptsEvent("ui.ask") ? uiHost.ask(request) : Promise.resolve({ cancelled: true }),
|
|
1564
|
+
},
|
|
1565
|
+
onPiQueue: (snapshot) => { if (acceptsEvent("pi.queue"))
|
|
1566
|
+
this.onPiQueue(conversation.id, snapshot); },
|
|
1567
|
+
onSteerDelivered,
|
|
1568
|
+
onUserEntry: async (entryId) => {
|
|
1569
|
+
if (acceptsEvent("transcript.entry", true))
|
|
1570
|
+
await this.store.setMessagePiEntryId(conversation.id, userMessageId, entryId);
|
|
1571
|
+
},
|
|
1572
|
+
onSessionFile: async (path) => {
|
|
1573
|
+
if (acceptsEvent("transcript.file", true))
|
|
1574
|
+
await this.store.setConversationPiSessionFile(conversation.id, path);
|
|
1575
|
+
},
|
|
1576
|
+
onUsage: async (readout) => {
|
|
1577
|
+
if (acceptsEvent("usage", true))
|
|
1578
|
+
await this.store.recordConversationUsage(conversation.id, readout);
|
|
1579
|
+
},
|
|
1580
|
+
onToolCall,
|
|
1581
|
+
onFileWrite,
|
|
1582
|
+
onToolPreparing,
|
|
1583
|
+
onToolUpdate,
|
|
1584
|
+
onToolEnd,
|
|
1585
|
+
// BROADCAST AND KEEP. It used to only broadcast, into an event no one handled - so the reasoning
|
|
1586
|
+
// reached nobody, live or afterwards. Both halves now happen: the browser draws the delta as it
|
|
1587
|
+
// arrives, and the message keeps it so the finished turn has something to go back to.
|
|
1588
|
+
//
|
|
1589
|
+
// `active: true` on every delta is not a field Pi sent - it is the conclusion Super Pi draws from
|
|
1590
|
+
// having received one. Pi announces the END of reasoning with `thinking_end` and puts nothing on
|
|
1591
|
+
// the delta, so these two halves together are the whole lifecycle.
|
|
1592
|
+
onThinking: async (delta) => {
|
|
1593
|
+
if (!delta || !acceptsEvent("thinking.delta"))
|
|
1594
|
+
return;
|
|
1595
|
+
// THINKING IS THE MODEL PRODUCING SOMETHING, SO THE TURN IS RUNNING. The contract above
|
|
1596
|
+
// says a turn moves from `waiting` to `running` once the model has produced ANY signal -
|
|
1597
|
+
// "regardless of shape" - and a thinking delta is the same signal as a text delta: it is Pi
|
|
1598
|
+
// yielding data back. Only two shapes promoted the turn (text and a tool-call notice), so a
|
|
1599
|
+
// model that thinks before it answers sat in `waiting` for the whole of its reasoning: the
|
|
1600
|
+
// panel said 「等待 LLM 返回」 while the model was plainly working, and - because the stop
|
|
1601
|
+
// button appears while a turn is in flight - the reader had no way to stop it for exactly
|
|
1602
|
+
// as long as the thinking lasted.
|
|
1603
|
+
const newBlock = thinkingAnswerAt !== spoken || thinkingInterrupted;
|
|
1604
|
+
if (newBlock) {
|
|
1605
|
+
thinkingBlock++;
|
|
1606
|
+
thinkingAnswerAt = spoken;
|
|
1607
|
+
answerAfterThinking = false;
|
|
1608
|
+
}
|
|
1609
|
+
thinkingInterrupted = false;
|
|
1610
|
+
thinkingActive = true;
|
|
1611
|
+
this.store.setThinkingActiveLive(conversation.id, assistant.id, true);
|
|
1612
|
+
thought += delta.length;
|
|
1613
|
+
// THE DELTA GOES INTO THE STORE FIRST, and the promotion that follows broadcasts a state
|
|
1614
|
+
// snapshot that therefore CARRIES it - the text, the thinking and the block boundary the
|
|
1615
|
+
// browser needs to put this fragment in the right fold. That snapshot is the delta's
|
|
1616
|
+
// delivery, so the live event is not sent as well: sent twice, the browser appends the
|
|
1617
|
+
// first fragment to a copy that already has it, and the reasoning the reader sees is longer
|
|
1618
|
+
// than the reasoning the model wrote.
|
|
1619
|
+
//
|
|
1620
|
+
// THE OTHER ORDER HAD ITS OWN FAILURE, and it is why the snapshot is not simply left to
|
|
1621
|
+
// carry everything: promoting BEFORE the append publishes a snapshot WITHOUT this delta,
|
|
1622
|
+
// and the browser - which rebuilds its fold blocks from the snapshot's boundaries - then
|
|
1623
|
+
// starts a second block for the same stretch of reasoning, so one continuous train of
|
|
1624
|
+
// thought arrives as two fold bars and the tool call inside it falls out of the block it
|
|
1625
|
+
// belonged to.
|
|
1626
|
+
//
|
|
1627
|
+
// So: the snapshot carries the delta, and only the deltas the snapshot did not carry are
|
|
1628
|
+
// published live. `promoteToRunning` answers whether it published one.
|
|
1629
|
+
this.store.appendThinkingDeltaLive(conversation.id, assistant.id, delta, spoken, newBlock);
|
|
1630
|
+
const promoted = await promoteToRunning();
|
|
1631
|
+
if (!ownsScope())
|
|
1632
|
+
return;
|
|
1633
|
+
if (!promoted && acceptsEvent("thinking.delta")) {
|
|
1634
|
+
this.broadcaster.broadcast({ type: "message.thinking", conversationId: conversation.id, messageId: assistant.id, delta, active: true, at: spoken, blockIndex: thinkingBlock });
|
|
1635
|
+
}
|
|
1636
|
+
scheduleCheckpoint();
|
|
1637
|
+
},
|
|
1638
|
+
// AN EMPTY DELTA THAT ONLY CARRIES THE FLAG. `thinking_end` is a fact the browser needs and not
|
|
1639
|
+
// text, so it rides as a delta of length zero and the client is required to leave `thinking` and
|
|
1640
|
+
// `thinkingBlocks` alone when it sees one. Without that rule this event appends an EMPTY fold
|
|
1641
|
+
// block to every turn whose second reasoning run starts after the answer has already begun,
|
|
1642
|
+
// because that block's `at` then differs from the previous one's.
|
|
1643
|
+
onThinkingEnd: () => {
|
|
1644
|
+
if (!acceptsEvent("thinking.end"))
|
|
1645
|
+
return;
|
|
1646
|
+
thinkingActive = false;
|
|
1647
|
+
this.store.setThinkingActiveLive(conversation.id, assistant.id, false);
|
|
1648
|
+
this.broadcaster.broadcast({ type: "message.thinking", conversationId: conversation.id, messageId: assistant.id, delta: "", active: false });
|
|
1649
|
+
},
|
|
1650
|
+
images,
|
|
1651
|
+
})) {
|
|
1652
|
+
// AWAITED FIRST, BEFORE THE LIVE WRITE, because `assistant` may be reassigned by a steer
|
|
1653
|
+
// delivery that is still in flight on this same lane. It used to be awaited after
|
|
1654
|
+
// `appendAssistantDeltaLive`, which is harmless for tool writes - a tool write never changes
|
|
1655
|
+
// which message text belongs to - and is NOT harmless for a split: a token would land in the
|
|
1656
|
+
// message that just stopped being answered, in front of the reader, and then the split would
|
|
1657
|
+
// publish a new message underneath it. One `await` at the top covers both, and costs nothing:
|
|
1658
|
+
// the lane is empty most of the time.
|
|
1659
|
+
await pendingTools;
|
|
1660
|
+
if (!acceptsEvent("text.delta"))
|
|
1661
|
+
continue;
|
|
1662
|
+
if (!acceptsEvent("text.delta"))
|
|
1663
|
+
continue;
|
|
1664
|
+
// THE ANSWER ENDS THE PREVIOUS THINKING STAGE, WHATEVER THE REASONING IS DOING. It used to wait
|
|
1665
|
+
// for `!thinkingActive`, which meant a model that writes text while it is still reasoning never ended
|
|
1666
|
+
// its thinking stage at all - and every call after that text was filed inside the thinking fold.
|
|
1667
|
+
if (thinkingBlock >= 0)
|
|
1668
|
+
answerAfterThinking = true;
|
|
1669
|
+
this.store.appendAssistantDeltaLive(conversation.id, assistant.id, delta);
|
|
1670
|
+
spoken += delta.length;
|
|
1671
|
+
// Promote to running AFTER the store has received the first delta, so any state
|
|
1672
|
+
// snapshot emitted carries the live delta and does not wipe out client stream bounds.
|
|
1673
|
+
await promoteToRunning();
|
|
1674
|
+
this.broadcaster.broadcast({ type: "message.delta", conversationId: conversation.id, messageId: assistant.id, delta });
|
|
1675
|
+
scheduleCheckpoint();
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
finally {
|
|
1679
|
+
scope.accepting = false;
|
|
1680
|
+
traceScope("draining");
|
|
1681
|
+
// A failed or cancelled producer still owns live text and a checkpoint timer.
|
|
1682
|
+
// Drain the lane before the caller changes status or permits another turn.
|
|
1683
|
+
if (ownsScope()) {
|
|
1684
|
+
this.store.setThinkingActiveLive(conversation.id, assistant.id, false);
|
|
1685
|
+
checkpointPending = true;
|
|
1686
|
+
}
|
|
1687
|
+
checkpointNow();
|
|
1688
|
+
// A CALL THE MODEL STARTED AND NEVER RAN. Pi announces a call with `toolcall_start` and only tells
|
|
1689
|
+
// the host it is running with `tool_execution_start`, so an abort, a cancelled turn or an upstream
|
|
1690
|
+
// error in between leaves a row nothing will ever fill in - and nothing below used to look at those
|
|
1691
|
+
// rows, so each one kept 「生成参数中…」 for the rest of the conversation. Queued HERE, before the
|
|
1692
|
+
// await below, so it drains behind the last real tool write rather than racing it; `preparingRows`
|
|
1693
|
+
// is read here because by this line no further call can be announced.
|
|
1694
|
+
if (ownsScope() && preparingRows.size) {
|
|
1695
|
+
const stranded = [...preparingRows.values()].map((entry) => entry.row);
|
|
1696
|
+
preparingRows.clear();
|
|
1697
|
+
enqueueTools("unfinished tool calls", () => this.store.clearPreparingToolCalls(conversation.id, assistant.id, stranded));
|
|
1698
|
+
}
|
|
1699
|
+
await pendingTools;
|
|
1700
|
+
// The positions are facts ABOUT THIS TURN and stop being true when it ends, so they go with it.
|
|
1701
|
+
// A dispatch whose POST arrives after this line gets no anchor and renders where it always did -
|
|
1702
|
+
// which is the honest outcome, because by then the call that asked for it may no longer be on screen.
|
|
1703
|
+
if (this.turnEventScopes.get(conversation.id) === scope) {
|
|
1704
|
+
closedOwnScope = ownsScope();
|
|
1705
|
+
this.turnEventScopes.delete(conversation.id);
|
|
1706
|
+
this.toolCallSites.delete(conversation.id);
|
|
1707
|
+
this.toolCallLanes.delete(conversation.id);
|
|
1708
|
+
for (const [key, waiters] of this.toolCallWaiters) {
|
|
1709
|
+
if (key.startsWith(`${conversation.id}:`))
|
|
1710
|
+
for (const wake of waiters)
|
|
1711
|
+
wake();
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
traceScope("closed");
|
|
1715
|
+
}
|
|
1716
|
+
if (closedOwnScope && this.activeRuns.get(conversation.id) === controller && !controller.signal.aborted) {
|
|
1717
|
+
const completed = this.store.snapshot().conversations.find(c => c.id === conversation.id);
|
|
1718
|
+
if (completed)
|
|
1719
|
+
await this.memory?.completed(completed, { userMessageId: currentUserMessageId, assistantMessageId: assistant.id })
|
|
1720
|
+
.catch(error => console.warn("Super Pi memory scheduling failed:", error));
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
/**
|
|
1724
|
+
* Loops running turns for as long as waiting messages exist.
|
|
1725
|
+
*
|
|
1726
|
+
* The FIRST message is passed in rather than opened here, because it was written into the transcript
|
|
1727
|
+
* before this method was called: the user pressed send, and their words were on screen in that frame. The
|
|
1728
|
+
* loop then does the same thing for each message after it - take the next waiting one, open its turn,
|
|
1729
|
+
* stream it - which is why the two cases are expressed identically and cannot drift apart.
|
|
1730
|
+
*/
|
|
1731
|
+
async runConversationTurns(conversation, workspace, prompt, controller, firstMessageId, initialImages) {
|
|
1732
|
+
try {
|
|
1733
|
+
const agent = await this.runtime.agentFor?.(conversation);
|
|
1734
|
+
const identity = agent ? { id: agent.id, name: agent.name } : { name: "Pi" };
|
|
1735
|
+
await this.assertModelSupportsImages(conversation, Boolean(initialImages?.length), firstMessageId);
|
|
1736
|
+
const opened = await this.openTurn(conversation.id, firstMessageId);
|
|
1737
|
+
await this.streamTurn(conversation, workspace, prompt, opened.assistant, controller, opened.user.id, initialImages, identity);
|
|
1738
|
+
for (;;) {
|
|
1739
|
+
if (controller.signal.aborted)
|
|
1740
|
+
break;
|
|
1741
|
+
// Return any undelivered explicit steer to the durable queue before starting another turn.
|
|
1742
|
+
await this.clearPiQueues(conversation.id);
|
|
1743
|
+
await this.store.releaseSendingMessages(conversation.id);
|
|
1744
|
+
if (controller.signal.aborted)
|
|
1745
|
+
break;
|
|
1746
|
+
const next = this.store.listWaitingMessages(conversation.id).find((message) => message.delivery === "waiting");
|
|
1747
|
+
if (!next)
|
|
1748
|
+
break;
|
|
1749
|
+
const current = this.turnContext(conversation.id).conversation;
|
|
1750
|
+
await this.assertModelSupportsImages(current, Boolean(next.images?.length), next.id);
|
|
1751
|
+
if (controller.signal.aborted)
|
|
1752
|
+
break;
|
|
1753
|
+
// Preflight can yield to an edit, withdrawal or higher-priority arrival. Open the head
|
|
1754
|
+
// only if it is still first, clearing its delivery flag and adding the reply together.
|
|
1755
|
+
const head = this.store.listWaitingMessages(conversation.id).find((message) => message.delivery === "waiting");
|
|
1756
|
+
if (head?.id !== next.id)
|
|
1757
|
+
continue;
|
|
1758
|
+
const followUp = await this.store.openTurnOnMessage(conversation.id, next.id, identity);
|
|
1759
|
+
this.broadcaster.broadcastState();
|
|
1760
|
+
const activeConversation = this.turnContext(conversation.id).conversation;
|
|
1761
|
+
// `composePrompt` synthesises the prose for a 后台回传 (the `<task>` envelope is what the transcript
|
|
1762
|
+
// column reads from; the prose is what leaves the server for Pi). For user messages it is a no-op.
|
|
1763
|
+
await this.streamTurn(activeConversation, workspace, composePrompt(followUp.user), followUp.assistant, controller, followUp.user.id, followUp.user.images, identity);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
finally {
|
|
1767
|
+
await this.store.releaseSendingMessages(conversation.id);
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* Refuses a turn when the selected model cannot accept image input, either because the incoming
|
|
1772
|
+
* message carries images or because previous messages in the conversation contain images.
|
|
1773
|
+
*/
|
|
1774
|
+
async assertModelSupportsImages(conversation, currentTurnHasImages, excludingMessageId) {
|
|
1775
|
+
const hasHistoryImages = conversation.messages.some((m) => m.id !== excludingMessageId && Boolean(m.images && m.images.length > 0));
|
|
1776
|
+
if (!currentTurnHasImages && !hasHistoryImages)
|
|
1777
|
+
return;
|
|
1778
|
+
const catalog = await this.runtime.catalog(conversation.model);
|
|
1779
|
+
const currentModel = catalog.models.find((model) => model.provider === conversation.model?.provider && model.modelId === conversation.model?.modelId)
|
|
1780
|
+
?? catalog.models.find((m) => m.provider === catalog.defaultModel?.provider && m.modelId === catalog.defaultModel?.modelId);
|
|
1781
|
+
if (currentModel && !currentModel.imageInput) {
|
|
1782
|
+
if (currentTurnHasImages) {
|
|
1783
|
+
throw new Error(`当前选择的模型「${currentModel.label || currentModel.modelId}」不支持图片输入`);
|
|
1784
|
+
}
|
|
1785
|
+
throw new Error(`会话历史包含图片,当前模型「${currentModel.label || currentModel.modelId}」不支持图片输入;请切回支持图文的模型继续对话`);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
/** Keep admission owned through final persistence and recheck the durable queue before releasing. */
|
|
1789
|
+
async runUntilDrained(conversation, workspace, prompt, controller, messageId, images) {
|
|
1790
|
+
for (;;) {
|
|
1791
|
+
if (!controller.signal.aborted)
|
|
1792
|
+
await this.runConversationTurns(conversation, workspace, prompt, controller, messageId, images);
|
|
1793
|
+
// The `runConversationTurns` loop above drains every waiting message before returning, so a
|
|
1794
|
+
// turn that ends with `hasBg` true really is idle - it is waiting on a background task, not
|
|
1795
|
+
// about to start another turn.
|
|
1796
|
+
const hasBg = this.hasActiveBackgroundTasks(conversation.id);
|
|
1797
|
+
const finalStatus = controller.signal.aborted ? "stopped" : hasBg ? "awaiting_background" : "completed";
|
|
1798
|
+
await this.store.setStatus(conversation.id, finalStatus);
|
|
1799
|
+
if (controller.signal.aborted)
|
|
1800
|
+
return;
|
|
1801
|
+
// No await between the last empty observation and releasing the slot.
|
|
1802
|
+
// A send admitted during setStatus must be answered here, even though Pi's previous turn ended.
|
|
1803
|
+
const next = this.store.listWaitingMessages(conversation.id).find(item => item.delivery === "waiting");
|
|
1804
|
+
if (!next) {
|
|
1805
|
+
// Release on the same instruction turn as the empty observation. Returning to an awaiting
|
|
1806
|
+
// caller first would create another microtask window for a send to enter the old run's queue.
|
|
1807
|
+
this.releaseRunSlot(conversation.id, controller);
|
|
1808
|
+
return;
|
|
1809
|
+
}
|
|
1810
|
+
conversation = this.turnContext(conversation.id).conversation;
|
|
1811
|
+
prompt = composePrompt(next);
|
|
1812
|
+
messageId = next.id;
|
|
1813
|
+
images = next.images;
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
/**
|
|
1817
|
+
* Enqueues or starts execution for a user message.
|
|
1818
|
+
*/
|
|
1819
|
+
/**
|
|
1820
|
+
* STARTS A TURN FROM A SENDER THAT IS NOT THE READER.
|
|
1821
|
+
*
|
|
1822
|
+
* `enqueueAndRun` below is the person's path: it writes the words under the reader's own name, in
|
|
1823
|
+
* the reader's bubble, so the reader can see that they said it. The orchestrator's path is the
|
|
1824
|
+
* same machinery with a different speaker - a primary agent handing a task to a child session -
|
|
1825
|
+
* and writing THAT under the reader's name was the bug the reader reported: the child's
|
|
1826
|
+
* transcript showed an instruction they never typed, wearing their avatar.
|
|
1827
|
+
*
|
|
1828
|
+
* So the write goes through `addAgentMessage` instead, which records the words as the system's,
|
|
1829
|
+
* and the turn runs on them exactly as before. `composePrompt` is what tells the model who is
|
|
1830
|
+
* speaking, so the model is addressed in the same words.
|
|
1831
|
+
*/
|
|
1832
|
+
async enqueueAndRunAsAgent(conversationId, content, options) {
|
|
1833
|
+
const deliveryMode = parseMessageDeliveryMode(options?.mode);
|
|
1834
|
+
this.assertHistoryAvailable(conversationId);
|
|
1835
|
+
this.memory?.cancel(conversationId);
|
|
1836
|
+
const trimmed = content.trim();
|
|
1837
|
+
if (!trimmed)
|
|
1838
|
+
return;
|
|
1839
|
+
const { conversation, workspace } = this.turnContext(conversationId);
|
|
1840
|
+
const active = this.activeRuns.get(conversation.id);
|
|
1841
|
+
if (active?.signal.aborted)
|
|
1842
|
+
await this.awaitRunSlotReleased(conversation.id, false);
|
|
1843
|
+
this.assertHistoryAvailable(conversationId);
|
|
1844
|
+
const busy = this.activeRuns.has(conversation.id) || this.interruptTargets.has(conversation.id);
|
|
1845
|
+
const queueOnly = busy || this.shuttingDown;
|
|
1846
|
+
const reservedController = queueOnly ? undefined : new AbortController();
|
|
1847
|
+
if (reservedController) {
|
|
1848
|
+
this.cancelledQuestionConversations.delete(conversation.id);
|
|
1849
|
+
this.claimRunSlot(conversation.id, reservedController);
|
|
1850
|
+
}
|
|
1851
|
+
let message;
|
|
1852
|
+
try {
|
|
1853
|
+
message = await this.store.addAgentMessage(conversationId, trimmed, { ...(queueOnly ? { delivery: "waiting" } : {}) });
|
|
1854
|
+
}
|
|
1855
|
+
catch (error) {
|
|
1856
|
+
if (reservedController)
|
|
1857
|
+
this.releaseRunSlot(conversation.id, reservedController);
|
|
1858
|
+
throw error;
|
|
1859
|
+
}
|
|
1860
|
+
this.broadcaster.broadcastState();
|
|
1861
|
+
if (!reservedController) {
|
|
1862
|
+
const waiting = this.store.listWaitingMessages(conversationId).find((item) => item.id === message.id && item.delivery === "waiting");
|
|
1863
|
+
if (!waiting) {
|
|
1864
|
+
options?.onAccepted?.(message.id);
|
|
1865
|
+
return;
|
|
1866
|
+
}
|
|
1867
|
+
if (deliveryMode === "steer")
|
|
1868
|
+
await this.steerWaitingMessageOnBusyRun(conversationId, message.id);
|
|
1869
|
+
else
|
|
1870
|
+
await this.processWaitingMessage(conversationId, message.id, { ifIdle: true });
|
|
1871
|
+
options?.onAccepted?.(message.id);
|
|
1872
|
+
return;
|
|
1873
|
+
}
|
|
1874
|
+
options?.onAccepted?.(message.id);
|
|
1875
|
+
const controller = reservedController;
|
|
1876
|
+
try {
|
|
1877
|
+
if (controller.signal.aborted) {
|
|
1878
|
+
await this.store.setStatus(conversation.id, "stopped");
|
|
1879
|
+
return;
|
|
1880
|
+
}
|
|
1881
|
+
await this.assertModelSupportsImages(conversation, false, message.id);
|
|
1882
|
+
await this.runUntilDrained(conversation, workspace, composePrompt(message), controller, message.id);
|
|
1883
|
+
// Turn completed cleanly without truncation; clear any stale warning and continuation tracking
|
|
1884
|
+
this.lengthContinuations.delete(conversationId);
|
|
1885
|
+
await this.store.setWarningReason(conversationId, undefined).catch(() => undefined);
|
|
1886
|
+
}
|
|
1887
|
+
catch (error) {
|
|
1888
|
+
// A TRUNCATED ANSWER IS NOT A DEAD CHILD. The model filled its single-response output budget
|
|
1889
|
+
// and stopped mid-sentence; the work it was doing is not over. The conversation goes back to
|
|
1890
|
+
// `idle` - usable, not failed - and the error is raised so orchestrators can auto-continue.
|
|
1891
|
+
if (isLengthExceededError(error)) {
|
|
1892
|
+
await this.store.setStatus(conversation.id, "idle");
|
|
1893
|
+
console.warn("Super Pi agent-dispatched turn was truncated by the output limit:", describeThrownWithStack(error));
|
|
1894
|
+
throw error;
|
|
1895
|
+
}
|
|
1896
|
+
await this.store.setStatus(conversation.id, controller.signal.aborted ? "stopped" : "failed");
|
|
1897
|
+
if (controller.signal.aborted)
|
|
1898
|
+
return;
|
|
1899
|
+
await this.store.setFailureReason(conversationId, formatTurnFailure(error));
|
|
1900
|
+
console.error("Super Pi agent-dispatched turn failed:", describeThrownWithStack(error));
|
|
1901
|
+
throw error;
|
|
1902
|
+
}
|
|
1903
|
+
finally {
|
|
1904
|
+
this.releaseRunSlot(conversation.id, controller);
|
|
1905
|
+
if (!this.activeRuns.has(conversation.id))
|
|
1906
|
+
this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
|
|
1907
|
+
this.broadcaster.broadcastState();
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
async acknowledgeAcceptedSend(conversationId, clientId) {
|
|
1911
|
+
if (!clientId)
|
|
1912
|
+
return false;
|
|
1913
|
+
const pending = this.acceptingSends.get(JSON.stringify([conversationId, clientId]));
|
|
1914
|
+
if (pending)
|
|
1915
|
+
await pending;
|
|
1916
|
+
return this.store.hasAcceptedSend(conversationId, clientId);
|
|
1917
|
+
}
|
|
1918
|
+
enqueueAndRun(conversationId, content, images, attachments, clientId, mode, onAccepted) {
|
|
1919
|
+
if (!clientId)
|
|
1920
|
+
return this.enqueueMessage(conversationId, content, { images, attachments, mode });
|
|
1921
|
+
const key = JSON.stringify([conversationId, clientId]);
|
|
1922
|
+
const pending = this.acceptingSends.get(key);
|
|
1923
|
+
if (pending)
|
|
1924
|
+
return pending.then(() => { if (this.store.hasAcceptedSend(conversationId, clientId))
|
|
1925
|
+
onAccepted?.(); });
|
|
1926
|
+
if (this.store.hasAcceptedSend(conversationId, clientId)) {
|
|
1927
|
+
onAccepted?.();
|
|
1928
|
+
return Promise.resolve();
|
|
1929
|
+
}
|
|
1930
|
+
let accepted;
|
|
1931
|
+
const receipt = new Promise(resolve => { accepted = resolve; });
|
|
1932
|
+
const work = this.enqueueMessage(conversationId, content, {
|
|
1933
|
+
images, attachments, clientId, mode,
|
|
1934
|
+
accepted: () => { accepted(); onAccepted?.(); },
|
|
1935
|
+
});
|
|
1936
|
+
const admission = Promise.race([work, receipt]);
|
|
1937
|
+
this.acceptingSends.set(key, admission);
|
|
1938
|
+
void admission.finally(() => { if (this.acceptingSends.get(key) === admission)
|
|
1939
|
+
this.acceptingSends.delete(key); }).catch(() => { });
|
|
1940
|
+
return work;
|
|
1941
|
+
}
|
|
1942
|
+
enqueueReminder(conversationId, note) {
|
|
1943
|
+
return this.enqueueMessage(conversationId, note, { source: "session-reminder" });
|
|
1944
|
+
}
|
|
1945
|
+
async enqueueMessage(conversationId, content, { images, attachments, clientId, mode, source, accepted }) {
|
|
1946
|
+
const deliveryMode = parseMessageDeliveryMode(mode);
|
|
1947
|
+
this.assertHistoryAvailable(conversationId);
|
|
1948
|
+
this.memory?.cancel(conversationId);
|
|
1949
|
+
if (source || !isLengthContinuation(content)) {
|
|
1950
|
+
this.lengthContinuations.delete(conversationId);
|
|
1951
|
+
await this.store.setWarningReason(conversationId, undefined).catch(() => undefined);
|
|
1952
|
+
}
|
|
1953
|
+
const trimmed = content.trim();
|
|
1954
|
+
const validImages = Array.isArray(images) && images.length > 0 ? images : undefined;
|
|
1955
|
+
if (!trimmed && !validImages?.length)
|
|
1956
|
+
return;
|
|
1957
|
+
const { conversation, workspace } = this.turnContext(conversationId);
|
|
1958
|
+
// THE MESSAGE IS WRITTEN FIRST, ALWAYS, AND THE RUN GUARD IS ASKED SECOND.
|
|
1959
|
+
//
|
|
1960
|
+
// This ordering is the fix for a bug that was not a slip but a consequence: the words used to be
|
|
1961
|
+
// written by `openTurn`, at the moment the turn started, so a send into a running turn had nowhere to
|
|
1962
|
+
// put them until a turn began. The browser was therefore told to draw nothing on a send-while-busy,
|
|
1963
|
+
// and the composer emptied into silence for as long as the round trip took - a state the reader reads
|
|
1964
|
+
// as "it did not send", not as "it is queued".
|
|
1965
|
+
//
|
|
1966
|
+
// Written first, the message is in the transcript in the same frame, whether it starts a turn or
|
|
1967
|
+
// waits for one, and the guard below only decides WHICH. It also means the client-supplied `clientId`
|
|
1968
|
+
// is attached to a real message either way, so there is nothing to reconcile afterwards.
|
|
1969
|
+
//
|
|
1970
|
+
// BUT "WHICH" IS DECIDED BEFORE THE WRITE, not at the guard, and that ordering is the fix for a bug
|
|
1971
|
+
// the other order cannot fix: a message that is going to start a turn has no business passing through
|
|
1972
|
+
// 「等待回答」 on its way there. Send into an idle conversation and the reader watches a queue badge
|
|
1973
|
+
// light up, a row appear in the dock, and both disappear a frame later - a queue that was never one,
|
|
1974
|
+
// for a turn that had already begun. The state a message is born into is a claim about it, and a claim
|
|
1975
|
+
// retracted in the next frame is worse than never making it.
|
|
1976
|
+
//
|
|
1977
|
+
// An aborted run is unwinding its slot and will not drain new waiting messages.
|
|
1978
|
+
const active = this.activeRuns.get(conversation.id);
|
|
1979
|
+
if (active?.signal.aborted) {
|
|
1980
|
+
await this.awaitRunSlotReleased(conversation.id, false);
|
|
1981
|
+
}
|
|
1982
|
+
this.assertHistoryAvailable(conversationId);
|
|
1983
|
+
const busy = this.activeRuns.has(conversation.id) || this.interruptTargets.has(conversation.id);
|
|
1984
|
+
const queueOnly = busy || this.shuttingDown;
|
|
1985
|
+
// Reserve BEFORE the first persistence await. Revert/stop must see this admitted send even while
|
|
1986
|
+
// its message write is pending; otherwise a cut can start while this send goes on to launch Pi.
|
|
1987
|
+
const reservedController = queueOnly ? undefined : new AbortController();
|
|
1988
|
+
if (reservedController) {
|
|
1989
|
+
this.cancelledQuestionConversations.delete(conversation.id);
|
|
1990
|
+
this.claimRunSlot(conversation.id, reservedController);
|
|
1991
|
+
}
|
|
1992
|
+
let message;
|
|
1993
|
+
try {
|
|
1994
|
+
const delivery = queueOnly ? "waiting" : undefined;
|
|
1995
|
+
message = source
|
|
1996
|
+
? await this.store.addAgentMessage(conversationId, trimmed, { source, delivery })
|
|
1997
|
+
: await this.store.addUserMessage(conversationId, trimmed, validImages, attachments, { clientId, delivery });
|
|
1998
|
+
}
|
|
1999
|
+
catch (error) {
|
|
2000
|
+
if (reservedController)
|
|
2001
|
+
this.releaseRunSlot(conversation.id, reservedController);
|
|
2002
|
+
throw error;
|
|
2003
|
+
}
|
|
2004
|
+
this.broadcaster.broadcastState();
|
|
2005
|
+
accepted?.();
|
|
2006
|
+
if (!reservedController) {
|
|
2007
|
+
// The current producer drains ordinary waiting messages one per turn.
|
|
2008
|
+
const waiting = this.store.listWaitingMessages(conversationId).find(item => item.id === message.id && item.delivery === "waiting");
|
|
2009
|
+
if (!waiting)
|
|
2010
|
+
return; // The owner already opened/delivered it while this write was pending.
|
|
2011
|
+
if (deliveryMode === "steer")
|
|
2012
|
+
await this.steerWaitingMessageOnBusyRun(conversationId, message.id);
|
|
2013
|
+
else
|
|
2014
|
+
await this.processWaitingMessage(conversationId, message.id, { ifIdle: true });
|
|
2015
|
+
return;
|
|
2016
|
+
}
|
|
2017
|
+
const controller = reservedController;
|
|
2018
|
+
try {
|
|
2019
|
+
if (controller.signal.aborted) {
|
|
2020
|
+
await this.store.setStatus(conversation.id, "stopped");
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
let expanded;
|
|
2024
|
+
try {
|
|
2025
|
+
const currentConv = this.turnContext(conversationId).conversation;
|
|
2026
|
+
await this.assertModelSupportsImages(currentConv, Boolean(validImages?.length), message.id);
|
|
2027
|
+
expanded = await expandAtReferences(this.store, workspace, composePrompt(message));
|
|
2028
|
+
}
|
|
2029
|
+
catch (error) {
|
|
2030
|
+
// EVERY REFUSAL ABOVE HAPPENS BEFORE A TURN EXISTS. The words are on screen and no model has seen
|
|
2031
|
+
// them, so failing here must not leave a bubble that nothing will ever answer: they go back to
|
|
2032
|
+
// the queue, where they can be seen, cancelled or sent again. On the queueing path this is the
|
|
2033
|
+
// state they were born in and nothing changed; on the idle path it is the difference between
|
|
2034
|
+
// 「消息发出去了但没有回答」 and a message the person can still act on.
|
|
2035
|
+
//
|
|
2036
|
+
// The boundary is the shape of the code, not a flag: `runConversationTurns` opens the turn on its
|
|
2037
|
+
// first line, so it is outside this try for exactly that reason. A failure from in there is a turn
|
|
2038
|
+
// that has already consumed these words, and putting them back would send them twice.
|
|
2039
|
+
await this.store.markMessageWaiting(conversationId, message.id).catch(() => undefined);
|
|
2040
|
+
// The reason for the refusal is also worth showing - a banner above the transcript is the only
|
|
2041
|
+
// place the user can read it from, because the message itself was rolled back to the queue and
|
|
2042
|
+
// the banner is the difference between "the message is waiting" and "I know why it is
|
|
2043
|
+
// waiting". The banner is cleared by the next `addUserMessage` so a stale reason cannot
|
|
2044
|
+
// survive a retry into the same conversation.
|
|
2045
|
+
await this.store.setFailureReason(conversationId, formatTurnFailure(error));
|
|
2046
|
+
// The refusal is written for the reader, but the reader is not the only one who needs to know
|
|
2047
|
+
// why a turn never started: the server log is where the stack survives.
|
|
2048
|
+
console.warn("Super Pi turn refused before it started:", describeThrownWithStack(error));
|
|
2049
|
+
// Status is restored here, not relied on the outer catch to handle: a preflight failure never
|
|
2050
|
+
// opened a turn, so the right state is the one the conversation had a moment ago (idle). The
|
|
2051
|
+
// outer catch would otherwise flip it to `failed`, which the reader would render as a turn
|
|
2052
|
+
// that ran and broke - the opposite of what actually happened.
|
|
2053
|
+
await this.store.setStatus(conversationId, "idle");
|
|
2054
|
+
// Tag the error so the outer catch knows to stay out of the way: no status flip, no second
|
|
2055
|
+
// setFailureReason (the one above is the only one the reader should see). A free-standing
|
|
2056
|
+
// property on the Error object is enough - it is checked with `in`, not by class, and the
|
|
2057
|
+
// throw immediately below carries it through the propagation.
|
|
2058
|
+
error.__superPiPreflight = true;
|
|
2059
|
+
this.broadcaster.broadcastState();
|
|
2060
|
+
throw error;
|
|
2061
|
+
}
|
|
2062
|
+
await this.runUntilDrained(conversation, workspace, expanded, controller, message.id, validImages);
|
|
2063
|
+
// Turn completed cleanly without truncation; clear any stale warning and continuation tracking
|
|
2064
|
+
this.lengthContinuations.delete(conversationId);
|
|
2065
|
+
await this.store.setWarningReason(conversationId, undefined).catch(() => undefined);
|
|
2066
|
+
}
|
|
2067
|
+
catch (error) {
|
|
2068
|
+
// A failing turn needs to be READ AS A FAILING TURN, not just stamped "failed" in a corner no one
|
|
2069
|
+
// watches. The status flip is necessary but not sufficient: a turn that was answering the user a
|
|
2070
|
+
// moment ago, now reporting 「failed」 with no reason, looks identical to a turn that the user
|
|
2071
|
+
// stopped themselves, and the reader has no way to tell which one it is. The only honest move
|
|
2072
|
+
// is to put the reason in front of them - `Conversation.error` is the banner above the
|
|
2073
|
+
// transcript that the failure state was never reaching.
|
|
2074
|
+
//
|
|
2075
|
+
// The reason is taken from the error itself, with the most common upstream cases translated to
|
|
2076
|
+
// the wording a person reads. The literal `error.message` would say "Pi RPC channel closed
|
|
2077
|
+
// before producing a record (code 3)" - that is true and useless. The translate here is what
|
|
2078
|
+
// the model-provider documentation actually says and what the reader can act on (retry, change
|
|
2079
|
+
// model, check the key), and it matches the banner the reader sees elsewhere in the app.
|
|
2080
|
+
//
|
|
2081
|
+
// NOT EVERY CATCH PATH IS A FAILURE the reader should see. A stop signalled through the
|
|
2082
|
+
// controller reaches the catch too (the abort propagates as a throw), and a stop is not a
|
|
2083
|
+
// failure - it is what the user asked for, and painting it red would be both wrong and a
|
|
2084
|
+
// regression from the pre-change behavior of these very lines. The reason is recorded only
|
|
2085
|
+
// when the controller was NOT aborted.
|
|
2086
|
+
//
|
|
2087
|
+
// Preflight refusals - bad model choice, unresolvable `@`-reference - carry the same shape but
|
|
2088
|
+
// never opened a turn, so flipping status to `failed` would be a lie: the previous state was
|
|
2089
|
+
// `idle` (or whatever the conversation was before the send) and that is what the conversation
|
|
2090
|
+
// is now. The preflight branch above already wrote the reason and set status back to `idle`,
|
|
2091
|
+
// so this catch only has to stay out of the way. The marker is set on the error there and
|
|
2092
|
+
// checked here.
|
|
2093
|
+
if (error?.__superPiPreflight) {
|
|
2094
|
+
throw error;
|
|
2095
|
+
}
|
|
2096
|
+
// A TRUNCATED ANSWER IS NOT A FAILED TURN. The model filled its single-response output budget
|
|
2097
|
+
// and stopped mid-sentence: everything it said is on screen, and the conversation is still
|
|
2098
|
+
// usable - the reader's next move is to let it carry on, not to retry from scratch.
|
|
2099
|
+
//
|
|
2100
|
+
// So the conversation goes back to `idle` rather than `failed`, and the fact that the answer
|
|
2101
|
+
// was cut short is recorded as a WARNING. Marking it `failed` is what made an orchestrated
|
|
2102
|
+
// child session die: the orchestrator read the status, told the parent the task had failed,
|
|
2103
|
+
// and a task that was one turn from done was thrown away.
|
|
2104
|
+
//
|
|
2105
|
+
// AND THE TURN DOES NOT THROW. The reader's message WAS accepted and WAS answered - partially.
|
|
2106
|
+
// Throwing here would tell the browser the send failed, and the browser's response to a failed
|
|
2107
|
+
// send is to offer a retry, which is the wrong move: retrying asks for the same answer again
|
|
2108
|
+
// instead of asking for the rest of this one.
|
|
2109
|
+
if (isLengthExceededError(error)) {
|
|
2110
|
+
const used = this.lengthContinuations.get(conversation.id) ?? 0;
|
|
2111
|
+
if (used < MAX_LENGTH_CONTINUATIONS && !controller.signal.aborted) {
|
|
2112
|
+
this.lengthContinuations.set(conversation.id, used + 1);
|
|
2113
|
+
console.warn(`Super Pi turn was truncated by output limit (${used + 1}/${MAX_LENGTH_CONTINUATIONS}); auto-continuing silently.`);
|
|
2114
|
+
const lastAssistant = conversation.messages.filter((m) => m.role === "assistant").pop();
|
|
2115
|
+
const continuationPrompt = buildLengthContinuationPrompt(lastAssistant);
|
|
2116
|
+
// Auto continue without exposing warning banner to user
|
|
2117
|
+
queueMicrotask(() => {
|
|
2118
|
+
void this.enqueueAndRunAsAgent(conversation.id, continuationPrompt).catch((contErr) => {
|
|
2119
|
+
console.warn("Super Pi auto-continuation dispatch error:", describeThrownWithStack(contErr));
|
|
2120
|
+
});
|
|
2121
|
+
});
|
|
2122
|
+
return;
|
|
2123
|
+
}
|
|
2124
|
+
this.lengthContinuations.delete(conversation.id);
|
|
2125
|
+
await this.store.setStatus(conversation.id, "idle");
|
|
2126
|
+
await this.store.setWarningReason(conversation.id, formatTurnFailure(error));
|
|
2127
|
+
console.warn("Super Pi turn reached maximum continuations after truncation:", describeThrownWithStack(error));
|
|
2128
|
+
return;
|
|
2129
|
+
}
|
|
2130
|
+
await this.store.setStatus(conversation.id, controller.signal.aborted ? "stopped" : "failed");
|
|
2131
|
+
if (controller.signal.aborted)
|
|
2132
|
+
return;
|
|
2133
|
+
await this.store.setFailureReason(conversation.id, formatTurnFailure(error));
|
|
2134
|
+
// A turn that broke is the failure the reader will complain about, and the banner only carries
|
|
2135
|
+
// the sentence. The stack goes to the server log, where it can still be found.
|
|
2136
|
+
console.error("Super Pi turn failed:", describeThrownWithStack(error));
|
|
2137
|
+
throw error;
|
|
2138
|
+
}
|
|
2139
|
+
finally {
|
|
2140
|
+
this.releaseRunSlot(conversation.id, controller);
|
|
2141
|
+
// An old turn can unwind after stop has admitted a new one. Do not cancel the new turn's
|
|
2142
|
+
// extension dialog merely because this turn's finally block ran late.
|
|
2143
|
+
if (!this.activeRuns.has(conversation.id))
|
|
2144
|
+
this.extensionUiService.cancelPendingUi(conversation.id, "expired", {});
|
|
2145
|
+
this.broadcaster.broadcastState();
|
|
2146
|
+
}
|
|
2147
|
+
}
|
|
2148
|
+
/**
|
|
2149
|
+
* Steers a queued message into the in-flight turn.
|
|
2150
|
+
*/
|
|
2151
|
+
async steer(conversationId, messageId) {
|
|
2152
|
+
return this.serializeConversation(conversationId, () => this.steerUnsafe(conversationId, messageId));
|
|
2153
|
+
}
|
|
2154
|
+
/** Starts a chosen waiting message as the next turn, only when the conversation is idle. */
|
|
2155
|
+
async sendQueued(conversationId, messageId) {
|
|
2156
|
+
if (this.interruptTargets.has(conversationId))
|
|
2157
|
+
throw new Error("打断回复正在启动,请等待所选消息开始回答");
|
|
2158
|
+
// A stop broadcasts `stopped` before the previous run has finished its finally block. Allow that
|
|
2159
|
+
// short cleanup window; a click on the newly visible button must not race the old run slot.
|
|
2160
|
+
await this.awaitRunSlotReleased(conversationId, true);
|
|
2161
|
+
await this.processWaitingMessage(conversationId, messageId);
|
|
2162
|
+
}
|
|
2163
|
+
/**
|
|
2164
|
+
* Waits for the run holding a conversation's slot to release it, by AWAITING ITS COMPLETION rather
|
|
2165
|
+
* than polling a flag.
|
|
2166
|
+
*
|
|
2167
|
+
* Bounded, because a wedged run must not hang the message the user just asked for: after the deadline
|
|
2168
|
+
* the caller proceeds to `processWaitingMessage`, whose slot check then refuses in words. With the
|
|
2169
|
+
* session path the wait is short by construction - `runtime.stop()` has already awaited Pi going idle,
|
|
2170
|
+
* so what is left is the old run's `finally` unwinding, which is local bookkeeping.
|
|
2171
|
+
*
|
|
2172
|
+
* `onlyWhileStopped` is `sendQueued`'s contract: it waits out the stop-clearing window after a stop,
|
|
2173
|
+
* and nothing more. Waiting out an arbitrarily long RUNNING turn would turn "send now" into "send
|
|
2174
|
+
* whenever the current answer finishes", which is what the queue is for.
|
|
2175
|
+
*/
|
|
2176
|
+
async awaitRunSlotReleased(conversationId, onlyWhileStopped = false, timeoutMs = 15_000) {
|
|
2177
|
+
const deadline = Date.now() + timeoutMs;
|
|
2178
|
+
while (this.activeRuns.has(conversationId) && Date.now() < deadline) {
|
|
2179
|
+
if (onlyWhileStopped && this.store.conversationStatus(conversationId) !== "stopped")
|
|
2180
|
+
return;
|
|
2181
|
+
const completion = this.runCompletions.get(conversationId)?.promise;
|
|
2182
|
+
if (!completion)
|
|
2183
|
+
return;
|
|
2184
|
+
// The completion usually wins this race by a wide margin; the timer is what re-checks the
|
|
2185
|
+
// `onlyWhileStopped` condition if the run keeps going, and what enforces the deadline.
|
|
2186
|
+
await Promise.race([completion, new Promise((resolve) => setTimeout(resolve, Math.min(500, Math.max(1, deadline - Date.now()))))]);
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Stops the current turn and immediately gives one waiting message its own fresh turn.
|
|
2191
|
+
*
|
|
2192
|
+
* `steer` cannot provide this meaning: Pi only reads its steering queue after the current tool batch
|
|
2193
|
+
* finishes. Stopping first is what makes a long-running tool give way now.
|
|
2194
|
+
*
|
|
2195
|
+
* THE HAND-OFF IS AN AWAITED HAND-OFF, not a poll. `stopRun` aborts the turn and - on the session
|
|
2196
|
+
* path - `runtime.stop()` has already awaited Pi going idle, so what remains is the old run's own
|
|
2197
|
+
* `finally` unwinding. `awaitRunSlotReleased` waits for exactly that event (the run's completion
|
|
2198
|
+
* promise), then the selected message opens its turn ON THE SAME SESSION: the pool's fingerprint has
|
|
2199
|
+
* not changed, so no process is spawned and no history is replayed.
|
|
2200
|
+
*/
|
|
2201
|
+
async interruptQueued(conversationId, messageId) {
|
|
2202
|
+
this.assertHistoryAvailable(conversationId);
|
|
2203
|
+
if (this.interruptTargets.has(conversationId))
|
|
2204
|
+
throw new Error("已有一条打断回复正在启动,请稍候");
|
|
2205
|
+
const selected = this.store.listWaitingMessages(conversationId).find((item) => item.id === messageId);
|
|
2206
|
+
if (!selected || selected.delivery !== "waiting")
|
|
2207
|
+
throw new Error("这条消息已不在等待队列中,无法打断并回答");
|
|
2208
|
+
this.interruptTargets.set(conversationId, messageId);
|
|
2209
|
+
try {
|
|
2210
|
+
// Clear before abort so the old turn cannot drain an explicit steer while winding down.
|
|
2211
|
+
await this.clearPiQueues(conversationId);
|
|
2212
|
+
if (this.activeRuns.has(conversationId))
|
|
2213
|
+
await this.stopRun(conversationId, { foregroundOnly: true });
|
|
2214
|
+
// Drop any undelivered steers before the selected message claims the next turn.
|
|
2215
|
+
await this.clearPiQueues(conversationId);
|
|
2216
|
+
await this.awaitRunSlotReleased(conversationId);
|
|
2217
|
+
await this.processWaitingMessage(conversationId, messageId);
|
|
2218
|
+
}
|
|
2219
|
+
finally {
|
|
2220
|
+
if (this.interruptTargets.get(conversationId) === messageId)
|
|
2221
|
+
this.interruptTargets.delete(conversationId);
|
|
2222
|
+
this.wakeWaitingBackgroundResult(conversationId);
|
|
2223
|
+
}
|
|
2224
|
+
}
|
|
2225
|
+
/**
|
|
2226
|
+
* The lower-level "wait for run slot, open the turn on a specific waiting message, run it" sequence.
|
|
2227
|
+
*
|
|
2228
|
+
* Automatic callers leave the row waiting if another producer owns the conversation.
|
|
2229
|
+
* Explicit actions report a conflict if their selected message cannot start.
|
|
2230
|
+
*
|
|
2231
|
+
* `runConversationTurns` owns opening the first turn. It must be the ONLY opener: opening here and
|
|
2232
|
+
* then asking that loop to run the same message used to splice two assistant placeholders under one
|
|
2233
|
+
* queued item. The first got no deltas, which rendered as a stray avatar before the real response.
|
|
2234
|
+
*
|
|
2235
|
+
* `composePrompt` is what makes the `role: "tool"` path real - the `<task>` envelope stays in the
|
|
2236
|
+
* transcript, but the prose form of the same fact is what reaches Pi.
|
|
2237
|
+
*/
|
|
2238
|
+
async processWaitingMessage(conversationId, messageId, options) {
|
|
2239
|
+
// Serialize only the run claim. Holding the command lane for the entire Pi turn makes every
|
|
2240
|
+
// steer/reorder/cancel wait until that turn ends, which is especially visible after a background
|
|
2241
|
+
// result auto-starts a long follow-up. The activeRuns slot protects the turn after this lane exits.
|
|
2242
|
+
const controller = await this.serializeConversation(conversationId, async () => {
|
|
2243
|
+
if (this.shuttingDown)
|
|
2244
|
+
return undefined;
|
|
2245
|
+
const reserved = this.interruptTargets.get(conversationId);
|
|
2246
|
+
const busy = this.activeRuns.has(conversationId);
|
|
2247
|
+
if (options?.ifIdle && (reserved || busy)) {
|
|
2248
|
+
if (options.backgroundResult) {
|
|
2249
|
+
const pending = this.pendingBackgroundWakeups.get(conversationId) ?? new Set();
|
|
2250
|
+
pending.add(messageId);
|
|
2251
|
+
this.pendingBackgroundWakeups.set(conversationId, pending);
|
|
2252
|
+
}
|
|
2253
|
+
return undefined;
|
|
2254
|
+
}
|
|
2255
|
+
this.assertHistoryAvailable(conversationId);
|
|
2256
|
+
if (reserved && reserved !== messageId)
|
|
2257
|
+
throw new Error("打断回复正在启动,请等待所选消息开始回答");
|
|
2258
|
+
if (busy)
|
|
2259
|
+
throw new Error("当前轮仍在运行;停止或等待它结束后再发送这条消息");
|
|
2260
|
+
const message = this.store.listWaitingMessages(conversationId).find((item) => item.id === messageId);
|
|
2261
|
+
if (!message || message.delivery !== "waiting") {
|
|
2262
|
+
if (options?.ifIdle)
|
|
2263
|
+
return undefined;
|
|
2264
|
+
throw new Error("等待中的消息不存在或已被处理");
|
|
2265
|
+
}
|
|
2266
|
+
const controller = new AbortController();
|
|
2267
|
+
this.cancelledQuestionConversations.delete(conversationId);
|
|
2268
|
+
this.claimRunSlot(conversationId, controller);
|
|
2269
|
+
// THE MARKER ONLY GUARDS THE HAND-OFF WINDOW. Once this turn owns the run slot, `activeRuns`
|
|
2270
|
+
// guards it, and the marker would only keep a SECOND interrupt-and-reply from interrupting this
|
|
2271
|
+
// one - which is exactly what the user asks for when they interrupt B's answer to answer C.
|
|
2272
|
+
if (this.interruptTargets.get(conversationId) === messageId)
|
|
2273
|
+
this.interruptTargets.delete(conversationId);
|
|
2274
|
+
return controller;
|
|
2275
|
+
});
|
|
2276
|
+
if (!controller)
|
|
2277
|
+
return;
|
|
2278
|
+
try {
|
|
2279
|
+
const { conversation, workspace } = this.turnContext(conversationId);
|
|
2280
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2281
|
+
if (!message)
|
|
2282
|
+
throw new Error("消息不存在或已被撤回");
|
|
2283
|
+
await this.assertModelSupportsImages(conversation, Boolean(message.images?.length), message.id);
|
|
2284
|
+
// runConversationTurns opens this first message; do not create a second assistant placeholder.
|
|
2285
|
+
await this.runUntilDrained(conversation, workspace, composePrompt(message), controller, message.id, message.images);
|
|
2286
|
+
}
|
|
2287
|
+
catch (error) {
|
|
2288
|
+
await this.store.setStatus(conversationId, controller.signal.aborted ? "stopped" : "failed");
|
|
2289
|
+
if (controller.signal.aborted)
|
|
2290
|
+
return;
|
|
2291
|
+
await this.store.setFailureReason(conversationId, formatTurnFailure(error));
|
|
2292
|
+
throw error;
|
|
2293
|
+
}
|
|
2294
|
+
finally {
|
|
2295
|
+
this.releaseRunSlot(conversationId, controller);
|
|
2296
|
+
if (!this.activeRuns.has(conversationId))
|
|
2297
|
+
this.extensionUiService.cancelPendingUi(conversationId, "expired", {});
|
|
2298
|
+
this.broadcaster.broadcastState();
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
async steerUnsafe(conversationId, messageId) {
|
|
2302
|
+
if (this.interruptTargets.has(conversationId))
|
|
2303
|
+
throw new Error("打断回复正在启动,请稍后再插队");
|
|
2304
|
+
// Already-sent Pi steers are FIFO. Put this row directly behind them, ahead of unclaimed rows.
|
|
2305
|
+
await this.moveAheadOfUnclaimed(conversationId, messageId);
|
|
2306
|
+
this.broadcaster.broadcastState();
|
|
2307
|
+
if (!this.runtime.steer)
|
|
2308
|
+
return;
|
|
2309
|
+
// A running conversation may be in the tiny hand-off window after Pi ended but before this service
|
|
2310
|
+
// opens the next waiting message. The message is at the front of the waiting set, so there is nothing
|
|
2311
|
+
// left to promise and nothing to report as an error - the click did what it was for either way.
|
|
2312
|
+
if (this.runtime.canSteer && !this.runtime.canSteer(conversationId))
|
|
2313
|
+
return;
|
|
2314
|
+
const claimed = await this.store.claimWaitingMessage(conversationId, messageId);
|
|
2315
|
+
this.broadcaster.broadcastState();
|
|
2316
|
+
try {
|
|
2317
|
+
// `composePrompt` turns a 后台回传 into the prose the model can read as a user message; for a
|
|
2318
|
+
// user waiting message it is the no-op identity. `claimed.images` is always undefined for a
|
|
2319
|
+
// `role: "tool"` row, and that is correct - 后台回传 carries no images today.
|
|
2320
|
+
await this.runtime.steer(conversationId, composePrompt(claimed), claimed.images);
|
|
2321
|
+
}
|
|
2322
|
+
catch (error) {
|
|
2323
|
+
// Back to waiting in every failure case, including the "Pi is gone" one. It is still at the front of
|
|
2324
|
+
// whatever is waiting, which is the most this could promise once the transport has refused.
|
|
2325
|
+
await this.store.releaseWaitingMessage(conversationId, claimed.id);
|
|
2326
|
+
this.broadcaster.broadcastState();
|
|
2327
|
+
if (error instanceof SteerUnavailableError)
|
|
2328
|
+
return;
|
|
2329
|
+
throw error;
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
/**
|
|
2333
|
+
* Steers a newly queued message into the running turn at the next turn boundary.
|
|
2334
|
+
* Starts a fresh turn if the active run ends before the conversation lane is entered.
|
|
2335
|
+
*/
|
|
2336
|
+
async steerWaitingMessageOnBusyRun(conversationId, messageId) {
|
|
2337
|
+
const startWaiting = await this.serializeConversation(conversationId, async () => {
|
|
2338
|
+
if (this.shuttingDown || this.interruptTargets.has(conversationId)) {
|
|
2339
|
+
if (!this.shuttingDown) {
|
|
2340
|
+
await this.moveAheadOfUnclaimed(conversationId, messageId);
|
|
2341
|
+
this.broadcaster.broadcastState();
|
|
2342
|
+
}
|
|
2343
|
+
return false;
|
|
2344
|
+
}
|
|
2345
|
+
if (!this.activeRuns.has(conversationId))
|
|
2346
|
+
return true;
|
|
2347
|
+
const waiting = this.store.listWaitingMessages(conversationId);
|
|
2348
|
+
if (!waiting.some((item) => item.id === messageId && item.delivery === "waiting"))
|
|
2349
|
+
return false;
|
|
2350
|
+
await this.moveAheadOfUnclaimed(conversationId, messageId);
|
|
2351
|
+
this.broadcaster.broadcastState();
|
|
2352
|
+
if (!this.runtime.steer)
|
|
2353
|
+
return false;
|
|
2354
|
+
if (this.runtime.canSteer && !this.runtime.canSteer(conversationId))
|
|
2355
|
+
return false;
|
|
2356
|
+
const claimed = await this.store.claimWaitingMessage(conversationId, messageId);
|
|
2357
|
+
this.broadcaster.broadcastState();
|
|
2358
|
+
try {
|
|
2359
|
+
await this.runtime.steer(conversationId, composePrompt(claimed), claimed.images);
|
|
2360
|
+
return false;
|
|
2361
|
+
}
|
|
2362
|
+
catch (error) {
|
|
2363
|
+
await this.store.releaseWaitingMessage(conversationId, claimed.id);
|
|
2364
|
+
this.broadcaster.broadcastState();
|
|
2365
|
+
if (error instanceof SteerUnavailableError)
|
|
2366
|
+
return !this.activeRuns.has(conversationId);
|
|
2367
|
+
throw error;
|
|
2368
|
+
}
|
|
2369
|
+
});
|
|
2370
|
+
if (startWaiting) {
|
|
2371
|
+
await this.processWaitingMessage(conversationId, messageId, { ifIdle: true });
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
/**
|
|
2375
|
+
* Withdraws a waiting message.
|
|
2376
|
+
*/
|
|
2377
|
+
async cancelQueued(conversationId, messageId) {
|
|
2378
|
+
return this.serializeConversation(conversationId, () => this.cancelQueuedUnsafe(conversationId, messageId));
|
|
2379
|
+
}
|
|
2380
|
+
async cancelQueuedUnsafe(conversationId, messageId) {
|
|
2381
|
+
if (this.interruptTargets.get(conversationId) === messageId)
|
|
2382
|
+
throw new Error("这条消息正在打断并回答,无法撤回");
|
|
2383
|
+
// PI'S QUEUES ARE EMPTIED BEFORE THE MESSAGE IS TAKEN BACK. A message that was handed to Pi's
|
|
2384
|
+
// follow-up queue is in Pi's hands as well as in Super Pi's, and Pi would deliver it when the run
|
|
2385
|
+
// ends - the model would answer words the user believes they withdrew. Pi cannot take back one
|
|
2386
|
+
// message, so its queues are emptied; the other messages Pi was holding are still in Super Pi's
|
|
2387
|
+
// waiting list and are answered as turns of their own.
|
|
2388
|
+
await this.clearPiQueues(conversationId, { excludeMessageIds: new Set([messageId]) });
|
|
2389
|
+
const removed = await this.store.cancelWaitingMessage(conversationId, messageId);
|
|
2390
|
+
this.broadcaster.broadcastState();
|
|
2391
|
+
if (removed) {
|
|
2392
|
+
this.broadcaster.broadcast({
|
|
2393
|
+
type: "queue.withdrawn",
|
|
2394
|
+
conversationId,
|
|
2395
|
+
withdrawn: [{ id: removed.id, content: removed.content, role: removed.role === "tool" ? "tool" : "user" }],
|
|
2396
|
+
actor: "user",
|
|
2397
|
+
});
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
/**
|
|
2401
|
+
* Selectively withdraws a specific subset of queued/steered messages by id while preserving
|
|
2402
|
+
* all remaining waiting and steered messages.
|
|
2403
|
+
*/
|
|
2404
|
+
async cancelQueuedMany(conversationId, messageIds, options) {
|
|
2405
|
+
const normalizedIds = [];
|
|
2406
|
+
const seen = new Set();
|
|
2407
|
+
for (const raw of messageIds) {
|
|
2408
|
+
const id = typeof raw === "string" ? raw.trim() : "";
|
|
2409
|
+
if (!id || seen.has(id))
|
|
2410
|
+
continue;
|
|
2411
|
+
seen.add(id);
|
|
2412
|
+
normalizedIds.push(id);
|
|
2413
|
+
}
|
|
2414
|
+
if (normalizedIds.length === 0) {
|
|
2415
|
+
throw new Error("请至少选择一条要撤回的排队消息");
|
|
2416
|
+
}
|
|
2417
|
+
return this.serializeConversation(conversationId, async () => {
|
|
2418
|
+
const interruptTarget = this.interruptTargets.get(conversationId);
|
|
2419
|
+
if (interruptTarget && seen.has(interruptTarget)) {
|
|
2420
|
+
throw new Error("所选消息中有一条正在打断并回答,无法撤回");
|
|
2421
|
+
}
|
|
2422
|
+
const waitingBefore = this.store.listWaitingMessages(conversationId);
|
|
2423
|
+
const evictedSteerIds = await this.clearPiQueues(conversationId, { excludeMessageIds: seen });
|
|
2424
|
+
const unwithdrawable = waitingBefore.find((item) => seen.has(item.id) && item.delivery === "sending" && !evictedSteerIds.has(item.id));
|
|
2425
|
+
if (unwithdrawable) {
|
|
2426
|
+
throw new Error("所选消息中有已经交给 Agent 的消息,取消不掉(Pi 没有撤回单条队列消息的能力)");
|
|
2427
|
+
}
|
|
2428
|
+
for (const id of evictedSteerIds) {
|
|
2429
|
+
await this.store.releaseWaitingMessage(conversationId, id);
|
|
2430
|
+
}
|
|
2431
|
+
const withdrawn = [];
|
|
2432
|
+
const missingIds = [];
|
|
2433
|
+
for (const id of normalizedIds) {
|
|
2434
|
+
const removed = await this.store.cancelWaitingMessage(conversationId, id);
|
|
2435
|
+
if (removed) {
|
|
2436
|
+
withdrawn.push({
|
|
2437
|
+
id: removed.id,
|
|
2438
|
+
content: removed.content,
|
|
2439
|
+
role: removed.role === "tool" ? "tool" : "user",
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
else {
|
|
2443
|
+
missingIds.push(id);
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
this.broadcaster.broadcastState();
|
|
2447
|
+
if (withdrawn.length > 0) {
|
|
2448
|
+
this.broadcaster.broadcast({
|
|
2449
|
+
type: "queue.withdrawn",
|
|
2450
|
+
conversationId,
|
|
2451
|
+
withdrawn,
|
|
2452
|
+
actor: options?.actor ?? "user",
|
|
2453
|
+
});
|
|
2454
|
+
}
|
|
2455
|
+
return { withdrawn, missingIds };
|
|
2456
|
+
});
|
|
2457
|
+
}
|
|
2458
|
+
/**
|
|
2459
|
+
* Rewrites a waiting message, in place, where the user can see it change.
|
|
2460
|
+
*/
|
|
2461
|
+
async editQueued(conversationId, messageId, content) {
|
|
2462
|
+
return this.serializeConversation(conversationId, async () => {
|
|
2463
|
+
if (this.interruptTargets.get(conversationId) === messageId)
|
|
2464
|
+
throw new Error("这条消息正在打断并回答,无法修改");
|
|
2465
|
+
await this.clearPiQueues(conversationId);
|
|
2466
|
+
await this.store.editWaitingMessage(conversationId, messageId, content);
|
|
2467
|
+
this.broadcaster.broadcastState();
|
|
2468
|
+
});
|
|
2469
|
+
}
|
|
2470
|
+
/**
|
|
2471
|
+
* Moves a waiting message within the waiting set.
|
|
2472
|
+
*/
|
|
2473
|
+
async reorderQueued(conversationId, messageId, toIndex) {
|
|
2474
|
+
return this.serializeConversation(conversationId, async () => {
|
|
2475
|
+
if (this.interruptTargets.get(conversationId) === messageId)
|
|
2476
|
+
throw new Error("这条消息正在打断并回答,无法移动");
|
|
2477
|
+
await this.clearPiQueues(conversationId);
|
|
2478
|
+
await this.store.reorderWaitingMessage(conversationId, messageId, toIndex);
|
|
2479
|
+
this.broadcaster.broadcastState();
|
|
2480
|
+
});
|
|
2481
|
+
}
|
|
2482
|
+
/**
|
|
2483
|
+
* Dispatches a subagent from client command (human dispatch).
|
|
2484
|
+
*/
|
|
2485
|
+
async dispatchSubagent(params) {
|
|
2486
|
+
const task = params.task.trim();
|
|
2487
|
+
if (!task)
|
|
2488
|
+
throw new Error("子 agent 的任务不能为空");
|
|
2489
|
+
const { conversation, cwd } = await this.dispatchContext(params.conversationId);
|
|
2490
|
+
void this.trackDetached(this.subagents.dispatch({
|
|
2491
|
+
conversationId: conversation.id,
|
|
2492
|
+
agentId: params.agentId,
|
|
2493
|
+
task,
|
|
2494
|
+
cwd,
|
|
2495
|
+
model: conversation.model,
|
|
2496
|
+
denyTools: parentDeniedTools(await this.runtime.agentFor?.(conversation)),
|
|
2497
|
+
})).catch((error) => {
|
|
2498
|
+
console.warn(`Super Pi: sub-agent dispatch of ${params.agentId} failed before it could be recorded: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
2499
|
+
this.broadcaster.broadcast({
|
|
2500
|
+
type: "error",
|
|
2501
|
+
message: `无法派发子 agent ${JSON.stringify(params.agentId)}:${error instanceof Error ? error.message : "未知错误"}`,
|
|
2502
|
+
});
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
/**
|
|
2506
|
+
* Dispatches a subagent task requested by the task tool HTTP endpoint.
|
|
2507
|
+
*/
|
|
2508
|
+
async dispatchTask(body) {
|
|
2509
|
+
const conversationId = body.conversationId?.trim();
|
|
2510
|
+
const subagentType = body.subagent_type?.trim();
|
|
2511
|
+
const task = body.prompt?.trim();
|
|
2512
|
+
if (!conversationId || !subagentType || !task) {
|
|
2513
|
+
throw new Error("task requires conversationId, subagent_type and prompt");
|
|
2514
|
+
}
|
|
2515
|
+
// BEFORE anything else, including before the conversation is looked up: a request that cannot prove it
|
|
2516
|
+
// came from this server's primary agent gets no answer about what exists. Everything below this line
|
|
2517
|
+
// is about shaping a dispatch; this line is about whether the caller may have one at all.
|
|
2518
|
+
const capability = this.verifyPrimaryCapability(conversationId, body.capability);
|
|
2519
|
+
if (!capability.ok)
|
|
2520
|
+
throw new Error(capability.message);
|
|
2521
|
+
if (body.depth !== undefined)
|
|
2522
|
+
checkSubagentDepth(body.depth);
|
|
2523
|
+
const signal = this.activeRuns.get(conversationId)?.signal;
|
|
2524
|
+
const { conversation, cwd } = await this.dispatchContext(conversationId);
|
|
2525
|
+
const parent = body.parentRunId ? this.store.snapshot().subagentRuns.find((run) => run.id === body.parentRunId) : undefined;
|
|
2526
|
+
if (body.parentRunId && (!parent || parent.conversationId !== conversation.id)) {
|
|
2527
|
+
throw new Error("Invalid parentRunId: dispatch ancestry is not recorded for this conversation");
|
|
2528
|
+
}
|
|
2529
|
+
const authoritativeDepth = parent ? (parent.depth ?? 0) + 1 : 0;
|
|
2530
|
+
checkSubagentDepth(authoritativeDepth);
|
|
2531
|
+
if (parent)
|
|
2532
|
+
checkSubagentDepth(1);
|
|
2533
|
+
const backgroundId = body.background === true ? newSubagentRunId() : undefined;
|
|
2534
|
+
// WHERE THE CARD GOES. Resolved once, here, and written onto the record at creation - the run is born
|
|
2535
|
+
// knowing where it was asked for, so no later update has to supply it and a card cannot drift.
|
|
2536
|
+
const origin = await this.waitForToolCall(conversationId, body.toolCallId);
|
|
2537
|
+
const dispatch = {
|
|
2538
|
+
conversationId: conversation.id,
|
|
2539
|
+
agentId: subagentType,
|
|
2540
|
+
task,
|
|
2541
|
+
cwd,
|
|
2542
|
+
model: conversation.model,
|
|
2543
|
+
dispatchedBy: "model",
|
|
2544
|
+
...(origin ? origin : {}),
|
|
2545
|
+
...(parent ? { parentRunId: parent.id } : {}),
|
|
2546
|
+
depth: authoritativeDepth,
|
|
2547
|
+
...(body.loopId ? { loopId: body.loopId } : {}),
|
|
2548
|
+
...(body.role ? { role: body.role } : {}),
|
|
2549
|
+
denyTools: parentDeniedTools(await this.runtime.agentFor?.(conversation)),
|
|
2550
|
+
};
|
|
2551
|
+
if (!this.canAdmitBackgroundTask(signal))
|
|
2552
|
+
throw new Error("原回合已停止,任务未启动");
|
|
2553
|
+
if (backgroundId) {
|
|
2554
|
+
const taskRecord = {
|
|
2555
|
+
id: backgroundId,
|
|
2556
|
+
conversationId, title: body.description?.trim() || subagentType, agentId: subagentType,
|
|
2557
|
+
status: "running", startedAt: new Date().toISOString(), resultBlockId: backgroundId, ...origin,
|
|
2558
|
+
};
|
|
2559
|
+
await this.store.setBackgroundTask(taskRecord);
|
|
2560
|
+
if (!this.canAdmitBackgroundTask(signal) || !this.store.backgroundTask(backgroundId)) {
|
|
2561
|
+
await this.failBackgroundTaskStart(backgroundId, "原回合已停止,任务未启动", true);
|
|
2562
|
+
throw new Error("原回合已停止,任务未启动");
|
|
2563
|
+
}
|
|
2564
|
+
this.broadcaster.broadcastState();
|
|
2565
|
+
// Once admitted, this run owns its controller in the recorder.
|
|
2566
|
+
const settled = (async () => {
|
|
2567
|
+
let run;
|
|
2568
|
+
try {
|
|
2569
|
+
run = await this.subagents.dispatch({ id: backgroundId, ...dispatch });
|
|
2570
|
+
}
|
|
2571
|
+
catch (error) {
|
|
2572
|
+
await this.finishBackgroundResult(taskRecord, {
|
|
2573
|
+
status: "failed", reason: error instanceof Error ? error.message : String(error),
|
|
2574
|
+
}, true);
|
|
2575
|
+
return;
|
|
2576
|
+
}
|
|
2577
|
+
const cancelled = run.status === "stopped";
|
|
2578
|
+
const status = run.status === "completed" ? "completed" : cancelled
|
|
2579
|
+
? this.shuttingDown ? "interrupted" : "cancelled" : "failed";
|
|
2580
|
+
const lines = subagentProgress(run);
|
|
2581
|
+
await this.finishBackgroundResult(taskRecord, {
|
|
2582
|
+
status, reason: run.error, output: lines.slice(-BACKGROUND_LOG_LIMIT),
|
|
2583
|
+
outputTruncated: run.outputTruncated || lines.length > BACKGROUND_LOG_LIMIT || run.toolCalls?.some(call => call.outputTruncated),
|
|
2584
|
+
}, !cancelled, run.output ?? run.partialOutput ?? lines);
|
|
2585
|
+
if (run.status === "completed") {
|
|
2586
|
+
const current = this.store.conversation(conversationId);
|
|
2587
|
+
if (current && !current.archivedAt)
|
|
2588
|
+
this.memory?.review(current, { task: body.prompt, result: run.output });
|
|
2589
|
+
}
|
|
2590
|
+
})();
|
|
2591
|
+
void this.trackDetached(settled).catch(error => console.warn("Super Pi: could not record background sub-agent completion:", error));
|
|
2592
|
+
return {
|
|
2593
|
+
mode: "async",
|
|
2594
|
+
status: 202,
|
|
2595
|
+
body: { run: { id: backgroundId, status: "running", agentId: subagentType }, background: true },
|
|
2596
|
+
};
|
|
2597
|
+
}
|
|
2598
|
+
const run = await this.subagents.dispatch({ ...dispatch, signal });
|
|
2599
|
+
if (run.status === "completed")
|
|
2600
|
+
this.memory?.review(this.turnContext(conversationId).conversation, { task: body.prompt, result: run.output });
|
|
2601
|
+
return {
|
|
2602
|
+
mode: "sync",
|
|
2603
|
+
status: run.status === "completed" ? 200 : 422,
|
|
2604
|
+
body: {
|
|
2605
|
+
run: { id: run.id, status: run.status, agentId: run.agentId },
|
|
2606
|
+
output: run.output ?? "",
|
|
2607
|
+
error: run.error,
|
|
2608
|
+
outputTruncated: run.outputTruncated ?? false,
|
|
2609
|
+
},
|
|
2610
|
+
};
|
|
2611
|
+
}
|
|
2612
|
+
/**
|
|
2613
|
+
* Validates and executes one orchestrated plan to its end.
|
|
2614
|
+
*
|
|
2615
|
+
* BLOCKS, unlike `dispatchTask`'s background path, and that asymmetry is the whole design. A background
|
|
2616
|
+
* dispatch returns immediately because the model is expected to keep working meanwhile; a plan is the
|
|
2617
|
+
* model handing the work over and wanting the chain back, so the request stays open until the last step
|
|
2618
|
+
* settles. The cost is a long-held connection - a three-step pipeline is minutes - which is the same
|
|
2619
|
+
* cost `task` already carries, and is bounded by the same AbortSignal the extension already forwards,
|
|
2620
|
+
* plus the wall-clock cap below.
|
|
2621
|
+
*
|
|
2622
|
+
* 200 FOR A PLAN THAT RAN, 422 FOR ONE THAT SETTLED AS SOMETHING ELSE - `completed` including deliberate
|
|
2623
|
+
* skips, and anything else the terminal status can be. Same rule `dispatchTask` applies to a single run,
|
|
2624
|
+
* applied to a whole plan: the transport reports whether the work concluded, and the body says how.
|
|
2625
|
+
*/
|
|
2626
|
+
async runWorkflow(body) {
|
|
2627
|
+
const conversationId = body.conversationId?.trim();
|
|
2628
|
+
if (!conversationId)
|
|
2629
|
+
throw new Error("workflow requires conversationId");
|
|
2630
|
+
// Same rule as `dispatchTask`, and for a larger reason: this endpoint triggers a SEQUENCE of
|
|
2631
|
+
// dispatches, so a caller that cannot prove it is the primary agent would get an unattended pipeline
|
|
2632
|
+
// of sub-agents writing to the workspace rather than one delegation.
|
|
2633
|
+
const capability = this.verifyPrimaryCapability(conversationId, body.capability);
|
|
2634
|
+
if (!capability.ok)
|
|
2635
|
+
throw new Error(capability.message);
|
|
2636
|
+
const { conversation, cwd } = await this.dispatchContext(conversationId);
|
|
2637
|
+
const signal = this.activeRuns.get(conversationId)?.signal;
|
|
2638
|
+
// Validated against the roster THIS CALL reads from disk, for the same freshness reason the task tool
|
|
2639
|
+
// builds its roster per turn: a sub-agent added while the server is running is dispatchable on the next
|
|
2640
|
+
// message with no restart, because a person edits `agents/*.md` while the server runs.
|
|
2641
|
+
const { agents } = await readAgents(this.agentsDir, { mode: "subagent" });
|
|
2642
|
+
const validated = validateWorkflowPlan(body, subagentRoster(agents));
|
|
2643
|
+
if (!validated.plan)
|
|
2644
|
+
throw new Error(validated.refusal);
|
|
2645
|
+
const { workflow } = await this.workflows.run({
|
|
2646
|
+
conversationId: conversation.id,
|
|
2647
|
+
cwd,
|
|
2648
|
+
plan: validated.plan,
|
|
2649
|
+
signal,
|
|
2650
|
+
...(conversation.model ? { model: conversation.model } : {}),
|
|
2651
|
+
// The same inheritance a single dispatch applies: a parent's DENY reaches its children, its
|
|
2652
|
+
// allowlist does not. Every step gets the primary's denials, exactly as one dispatch would.
|
|
2653
|
+
denyTools: parentDeniedTools(await this.runtime.agentFor?.(conversation)),
|
|
2654
|
+
});
|
|
2655
|
+
return {
|
|
2656
|
+
status: workflow.status === "completed" ? 200 : 422,
|
|
2657
|
+
body: { workflow: workflowSummary(workflow) },
|
|
2658
|
+
};
|
|
2659
|
+
}
|
|
2660
|
+
/**
|
|
2661
|
+
* Stops a specific subagent run by runId.
|
|
2662
|
+
*/
|
|
2663
|
+
stopSubagent(runId) {
|
|
2664
|
+
this.subagents.stop(runId);
|
|
2665
|
+
}
|
|
2666
|
+
/**
|
|
2667
|
+
* Stops one orchestrated plan, and says whether there was anything to stop.
|
|
2668
|
+
*
|
|
2669
|
+
* REACHES THE CHILD, not just the loop: the engine dispatches every step under one controller's signal,
|
|
2670
|
+
* so aborting it reaches the child Pi and `killTree`s it exactly as the run recorder's stop does. A stop
|
|
2671
|
+
* that only ended the loop would leave the sub-agent still running and still holding the workspace
|
|
2672
|
+
* directory, which is the precise gap the run card's own stop button was added to close.
|
|
2673
|
+
*/
|
|
2674
|
+
stopWorkflow(workflowId) {
|
|
2675
|
+
return this.workflows.stop(workflowId);
|
|
2676
|
+
}
|
|
2677
|
+
/**
|
|
2678
|
+
* Stops all subagent runs belonging to a conversation.
|
|
2679
|
+
*/
|
|
2680
|
+
stopConversationSubagents(conversationId) {
|
|
2681
|
+
return this.subagents.stopConversation(conversationId);
|
|
2682
|
+
}
|
|
2683
|
+
}
|