@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,3305 @@
|
|
|
1
|
+
import { SESSION_SEARCH_LIMIT } from "../shared/session-search.js";
|
|
2
|
+
import { rename } from "node:fs/promises";
|
|
3
|
+
import { JsonStateRepository, defaultJsonStatePath } from "./persistence/json-state-repository.js";
|
|
4
|
+
import { normalizeTodos } from "./task-tool.js";
|
|
5
|
+
import { initializeMemoryTrees, memoryTreeId } from "./session-memory-scope.js";
|
|
6
|
+
import { TOOL_ARG_CAP } from "./tool-calls.js";
|
|
7
|
+
import { BACKGROUND_LOG_LIMIT, subagentProgress } from "../shared/background-task.js";
|
|
8
|
+
import { serverTimeZone } from "./time-zone.js";
|
|
9
|
+
import { pendingUserDecisionsByOwner } from "../shared/archive-decisions.js";
|
|
10
|
+
function id(prefix) { return `${prefix}_${crypto.randomUUID()}`; }
|
|
11
|
+
/** Mints the id a forked conversation will have, BEFORE its Pi transcript exists.
|
|
12
|
+
*
|
|
13
|
+
* Exported because the ordering demands it and no other arrangement provides it. Pi's copied file's header
|
|
14
|
+
* `id` has to BE the new conversation's id (it is what `findLocalSessionByExactId` matches), so the id has
|
|
15
|
+
* to be decided before the file is written; and the conversation must not exist until the file is safely on
|
|
16
|
+
* disk, or a failed write would leave a conversation whose model context is silently empty. The runtime is
|
|
17
|
+
* therefore handed the id and the store is handed the same one back. See `ForkRequest.forkedConversationId`. */
|
|
18
|
+
export function newConversationId() { return id("conversation"); }
|
|
19
|
+
/**
|
|
20
|
+
* ONE FOLDER, ONE KEY.
|
|
21
|
+
*
|
|
22
|
+
* The same directory reaches the app spelled several ways - `F:\code\app` and `F:/code/app/` and
|
|
23
|
+
* `f:\code\app` are one folder - and two workspaces for one folder are one project split in half.
|
|
24
|
+
* The key folds the separators and the trailing slash away, and folds case away only where the
|
|
25
|
+
* filesystem folds it too: Windows and macOS treat `F:\Code` and `f:\code` as one directory, Linux
|
|
26
|
+
* does not, and pretending otherwise would merge two real projects into one.
|
|
27
|
+
*/
|
|
28
|
+
export function workspacePathKey(path) {
|
|
29
|
+
const folded = path.trim().replace(/\\/g, "/").replace(/\/+$/, "");
|
|
30
|
+
return process.platform === "linux" ? folded : folded.toLowerCase();
|
|
31
|
+
}
|
|
32
|
+
function now() { return new Date().toISOString(); }
|
|
33
|
+
const DEFAULT_CONVERSATION_TITLE = "\u65b0\u4f1a\u8bdd";
|
|
34
|
+
/** Whether a value survives a `new Date()` round-trip. `createdAt` is typed string, but state.json only
|
|
35
|
+
* has to be JSON to be read back: an old build, an import, or a hand edit owes TypeScript nothing. */
|
|
36
|
+
function parseableTimestamp(value) {
|
|
37
|
+
return typeof value === "string" && value.length > 0 && !Number.isNaN(new Date(value).getTime());
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The server's own guard, so a poisoned message can only be rendered safe ONCE, at the boundary where
|
|
41
|
+
* outside data enters: `Store.open` reads state.json blind (`JSON.parse ... as AppState`), so a message
|
|
42
|
+
* whose `createdAt` is missing or unparseable would otherwise flow into every snapshot and every
|
|
43
|
+
* broadcast untouched. Why the store and not the client alone: the client's `time()` guard makes one bad
|
|
44
|
+
* stamp render without crashing, but by then the invalid value has already propagated through state
|
|
45
|
+
* broadcasts and persisted copies of it keep resurfacing on every restart. Normalizing here - anchored on
|
|
46
|
+
* the conversation's own updatedAt, falling back to the load instant - keeps the on-disk file untouched
|
|
47
|
+
* (the next normal persist rewrites it clean) while every snapshot handed out satisfies the declared
|
|
48
|
+
* type from this point on. The conversation's `updatedAt` was deliberately NOT audited: it feeds string
|
|
49
|
+
* sorting and a `relativeTime` that already degrades, so a bad one loses at most a sidebar label, and the
|
|
50
|
+
* type stays required so callers cannot learn to omit it.
|
|
51
|
+
*
|
|
52
|
+
* Never rebuilds conversation objects: the normalization is field-deep, so old state files load with no
|
|
53
|
+
* migration step, exactly like archivedAt and the agent/model keys do.
|
|
54
|
+
*/
|
|
55
|
+
function normalizeMessageTimestamps(state) {
|
|
56
|
+
const fallback = now();
|
|
57
|
+
for (const conversation of state.conversations ?? []) {
|
|
58
|
+
const anchor = parseableTimestamp(conversation.updatedAt) ? conversation.updatedAt : fallback;
|
|
59
|
+
for (const message of conversation.messages ?? []) {
|
|
60
|
+
if (parseableTimestamp(message?.createdAt))
|
|
61
|
+
continue;
|
|
62
|
+
if (message)
|
|
63
|
+
message.createdAt = anchor;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return state;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Why a run that was still `running` when the file was read is failed rather than left alone.
|
|
70
|
+
*
|
|
71
|
+
* Chinese because it lands in the run's `error`, which the card shows to a person; the surrounding
|
|
72
|
+
* `console.warn` is the developer-facing half of the same fact. It names the cause rather than just the
|
|
73
|
+
* verdict, because "failed" on its own leaves the reader guessing whether the child crashed, the run
|
|
74
|
+
* was cut short, or the server simply went away - and those have different fixes.
|
|
75
|
+
*/
|
|
76
|
+
const ORPHANED_RUN_ERROR = "服务器上次退出时这个子进程仍在运行;进程已随服务器消失,本次运行被标记为失败。";
|
|
77
|
+
/**
|
|
78
|
+
* Startup reconciliation: every run the previous process left `running` is an orphan.
|
|
79
|
+
*
|
|
80
|
+
* The reasoning is the same one that applies to any work claimed as in-flight by a process that no
|
|
81
|
+
* longer exists - the record is a CLAIM, and the claim cannot still be true when nothing is running.
|
|
82
|
+
* `status` is the only thing that can be wrong about such a record, so it is the only thing changed;
|
|
83
|
+
* `output`, `usage` and `sessionId` were written before the crash and are still true. `finishedAt` is
|
|
84
|
+
* the load instant rather than a guess at when the child died, because the file records no death time
|
|
85
|
+
* and inventing one would be a worse lie than an honest "we noticed this now".
|
|
86
|
+
*
|
|
87
|
+
* Mutated in place, like `normalizeMessageTimestamps`: the on-disk file is rewritten by the single
|
|
88
|
+
* persist `open` performs when this returns a non-empty list, and a state file written before sub-agent
|
|
89
|
+
* runs existed simply gains the key with no migration step.
|
|
90
|
+
*
|
|
91
|
+
* Returns the orphans so the caller can announce each one - a run that failed while nobody was watching
|
|
92
|
+
* is invisible otherwise, and the user who dispatched it deserves to learn what happened to it.
|
|
93
|
+
*/
|
|
94
|
+
function reconcileSubagentRuns(state) {
|
|
95
|
+
// `Array.isArray` rather than `?? []`: `state.json` is read blind, so a hand edit or an older build
|
|
96
|
+
// can leave anything here, and a truthy non-array would then make every iteration below throw on the
|
|
97
|
+
// first unrelated key of an unrelated failure.
|
|
98
|
+
const runs = Array.isArray(state.subagentRuns) ? state.subagentRuns : [];
|
|
99
|
+
state.subagentRuns = runs;
|
|
100
|
+
const orphaned = [];
|
|
101
|
+
for (const run of runs) {
|
|
102
|
+
if (!run || run.status !== "running")
|
|
103
|
+
continue;
|
|
104
|
+
run.status = "failed";
|
|
105
|
+
run.error = ORPHANED_RUN_ERROR;
|
|
106
|
+
run.finishedAt = now();
|
|
107
|
+
orphaned.push(run);
|
|
108
|
+
}
|
|
109
|
+
return orphaned;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* ONE RUN'S USAGE, FOLDED INTO THE LEDGER OF THE CONVERSATION THAT DISPATCHED IT.
|
|
113
|
+
*
|
|
114
|
+
* WHY THE CHILD'S MONEY BELONGS TO THE PARENT'S LEDGER. A one-shot call spends real money on a
|
|
115
|
+
* child Pi, and the only number a budget is compared against is a conversation's `usage`. A ledger
|
|
116
|
+
* that held the parent's own turns alone would let a conversation multiply its real cost past its
|
|
117
|
+
* own cap simply by dispatching children instead of answering - which is precisely what design §5
|
|
118
|
+
* exists to prevent ("写预算的人必须能自己算出这个数是多少钱"). So the child's FINAL accumulated
|
|
119
|
+
* usage is added to the parent's, once, when the run settles.
|
|
120
|
+
*
|
|
121
|
+
* ONCE, AND ONLY ONCE, AND WHY THE FLAG IS THE WHOLE MECHANISM. A run reports its usage on every
|
|
122
|
+
* finished assistant message, and the recorder settles the run with the run's TOTAL - so folding
|
|
123
|
+
* per message would bill every message twice. The fold therefore happens once, on the settled run,
|
|
124
|
+
* and `usageAccounted` says which side of that line the run is on. The flag and the ledger entry
|
|
125
|
+
* are written in ONE store write, so a server that dies between them cannot leave the money
|
|
126
|
+
* counted twice or not at all.
|
|
127
|
+
*
|
|
128
|
+
* THE FIELDS ARE ADDED, NOT RE-DERIVED. A conversation's usage and a run's usage are the same
|
|
129
|
+
* shape (`input` / `output` / `cacheRead` / `cacheWrite` / `cost` / `turns`), so the sum is a sum -
|
|
130
|
+
* no second pricing formula, and no place where the two could disagree about what a token costs.
|
|
131
|
+
*
|
|
132
|
+
* A RUN WITH NO CONVERSATION IS NOT FOLDED, and is not an error: the conversation it belonged to
|
|
133
|
+
* was deleted while the child was running, so there is no ledger left to add to. Deleting a
|
|
134
|
+
* conversation deletes its runs too, so the money is not counted twice either - it is simply not
|
|
135
|
+
* counted, because nobody is left to be billed for it.
|
|
136
|
+
*/
|
|
137
|
+
function foldRunUsage(state, run) {
|
|
138
|
+
if (!run?.usage || run.usageAccounted)
|
|
139
|
+
return false;
|
|
140
|
+
const conversation = (state.conversations ?? []).find((item) => item?.id === run.conversationId);
|
|
141
|
+
if (!conversation)
|
|
142
|
+
return false;
|
|
143
|
+
const previous = conversation.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
144
|
+
conversation.usage = {
|
|
145
|
+
input: previous.input + run.usage.input,
|
|
146
|
+
output: previous.output + run.usage.output,
|
|
147
|
+
cacheRead: previous.cacheRead + run.usage.cacheRead,
|
|
148
|
+
cacheWrite: previous.cacheWrite + run.usage.cacheWrite,
|
|
149
|
+
cost: previous.cost + run.usage.cost,
|
|
150
|
+
turns: previous.turns + run.usage.turns,
|
|
151
|
+
};
|
|
152
|
+
conversation.usageUpdatedAt = now();
|
|
153
|
+
run.usageAccounted = true;
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* THE STARTUP SWEEP FOR RUNS THAT PREDATE THE LEDGER.
|
|
158
|
+
*
|
|
159
|
+
* A `state.json` written before the conversation ledger existed holds runs whose usage was never
|
|
160
|
+
* added to the conversation that dispatched them - because at the time, nothing did that. Left
|
|
161
|
+
* alone, the project's budget would silently DROP for every project that had already spent money
|
|
162
|
+
* on one-shot calls, which is the kind of change nobody can explain afterwards.
|
|
163
|
+
*
|
|
164
|
+
* So every run that carries usage and has not been accounted for is folded in here, once, on the
|
|
165
|
+
* next boot. The flag makes the sweep idempotent: a run folded by this sweep is flagged, and the
|
|
166
|
+
* next boot leaves it alone. Mutated in place, like every other sweep in this file, and persisted
|
|
167
|
+
* by the single write `open` performs when this reports a change.
|
|
168
|
+
*/
|
|
169
|
+
function foldUnaccountedRunUsage(state) {
|
|
170
|
+
let folded = 0;
|
|
171
|
+
for (const run of state.subagentRuns ?? [])
|
|
172
|
+
if (foldRunUsage(state, run))
|
|
173
|
+
folded += 1;
|
|
174
|
+
return folded;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Why a conversation the previous process left `running` is failed, in the same spirit and for the same
|
|
178
|
+
* audience as `ORPHANED_RUN_ERROR`: this lands in a field the chat pane renders verbatim, so it names the
|
|
179
|
+
* cause, states the verdict, and says what to do next. "failed" alone would leave the reader unable to
|
|
180
|
+
* tell a crash from a stop, and unable to tell whether their work was lost or is still worth resuming.
|
|
181
|
+
*/
|
|
182
|
+
const ORPHANED_CONVERSATION_ERROR = "服务器上次退出时这次任务还在运行,没有跑完就被中断了,已标记为失败。可以直接重新发送任务继续。";
|
|
183
|
+
/**
|
|
184
|
+
* Startup reconciliation for ORDINARY conversations - the same treatment `reconcileSubagentRuns` gives a
|
|
185
|
+
* child's run, on the same reasoning: `status: "running"` is a CLAIM that some process was working on this,
|
|
186
|
+
* and the claim cannot still be true when the process that made it no longer exists. Without this, a server
|
|
187
|
+
* killed mid-turn leaves a conversation that spins in the UI forever, never settles, and cannot be closed.
|
|
188
|
+
*
|
|
189
|
+
* ARCHIVED CONVERSATIONS ARE RECONCILED TOO, and that is a decision rather than an oversight.
|
|
190
|
+
* `archiveConversation` refuses a running conversation, so an archived one carrying `running` is only
|
|
191
|
+
* reachable from an older build, a hand edit, or a file copied between installs - which makes it rare, not
|
|
192
|
+
* impossible. Skipping them would be strictly worse than reconciling them: the row would sit quiet in the
|
|
193
|
+
* Archived group until someone pressed restore, at which point the SAME unkillable spinner reappears on a
|
|
194
|
+
* conversation the user had every reason to believe was closed. Reconciling costs one status write and one
|
|
195
|
+
* reason field on a row nobody is looking at, and it removes a landmine rather than arming one.
|
|
196
|
+
*
|
|
197
|
+
* `updatedAt` is deliberately NOT touched, and this is the one place where copying the sub-agent sweep
|
|
198
|
+
* field-for-field would be wrong: `SubagentRun.finishedAt` is a field that EXISTS to be stamped with the
|
|
199
|
+
* moment an orphan was noticed, while a conversation has no such field, and `updatedAt` is the opposite of
|
|
200
|
+
* one - it is the sidebar's recency key. Bumping it would teleport every interrupted conversation to the
|
|
201
|
+
* top of the list at once, so repairing the file would reorder the UI as a side effect of a repair the user
|
|
202
|
+
* did not ask for. `archiveConversation` and `renameConversation` both decline to touch it for the same
|
|
203
|
+
* reason. Repair is not activity.
|
|
204
|
+
*
|
|
205
|
+
* `messages` is untouched for the same reason `output`/`usage` are untouched over there: everything in them
|
|
206
|
+
* was written before the crash and is still true. Only the claim, and the reason the claim is now false, are
|
|
207
|
+
* wrong.
|
|
208
|
+
*
|
|
209
|
+
* Mutated in place and persisted by `open`, exactly like the sub-agent sweep, so a state.json written before
|
|
210
|
+
* conversations were reconciled simply gains the reason with no migration step, and a record repaired on one
|
|
211
|
+
* boot is not repaired again on the next.
|
|
212
|
+
*/
|
|
213
|
+
function reconcileConversations(state) {
|
|
214
|
+
// `Array.isArray` rather than `?? []`, for precisely the reason `reconcileSubagentRuns` does it: state.json
|
|
215
|
+
// is read blind, and a truthy non-array left by a hand edit would make every iteration below throw on the
|
|
216
|
+
// first unrelated key of an unrelated failure.
|
|
217
|
+
const conversations = Array.isArray(state.conversations) ? state.conversations : [];
|
|
218
|
+
state.conversations = conversations;
|
|
219
|
+
const orphaned = [];
|
|
220
|
+
for (const conversation of conversations) {
|
|
221
|
+
// `waiting` joins the orphan set for the same reason `running` does: the turn was opened (a prompt
|
|
222
|
+
// was sent) and the server died before any settled state was recorded. A conversation that was in
|
|
223
|
+
// either of those two states when the process went away has a half-open turn whose outcome nobody
|
|
224
|
+
// can determine from the file alone - exactly the situation this sweep exists to remove.
|
|
225
|
+
if (!conversation || (conversation.status !== "running" && conversation.status !== "waiting" && conversation.status !== "awaiting_background"))
|
|
226
|
+
continue;
|
|
227
|
+
conversation.status = "failed";
|
|
228
|
+
conversation.error = ORPHANED_CONVERSATION_ERROR;
|
|
229
|
+
orphaned.push(conversation);
|
|
230
|
+
}
|
|
231
|
+
return orphaned;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* How many SETTLED sub-agent runs `state.json` keeps, so the file cannot grow without bound.
|
|
235
|
+
*
|
|
236
|
+
* WHY A BOUND IS NEEDED AT ALL. `beginSubagentRun` unshifts and nothing ever removes a run, so a long
|
|
237
|
+
* session that dispatches sub-agents - which is exactly what this feature encourages - would otherwise
|
|
238
|
+
* accumulate records forever. The file is not a log on disk that costs nothing to grow: it is rewritten
|
|
239
|
+
* in full on EVERY text delta of EVERY running child (see `SubagentRunRecorder.publish`), cloned into
|
|
240
|
+
* the browser on every `state` broadcast, and read at startup. A run record is bounded but not small -
|
|
241
|
+
* `output` is the last assistant message, up to the 50 KB cap of §6, plus the task text and one label
|
|
242
|
+
* per tool call - so an unbounded array makes every one of those operations slower for everybody.
|
|
243
|
+
*
|
|
244
|
+
* WHY 100. It has to be big enough that a person can scroll back through a working day without a card
|
|
245
|
+
* going missing, and small enough that the worst case stays in the range a JSON file and a browser
|
|
246
|
+
* snapshot handle comfortably. At 100 settled runs, and a deliberately pessimistic 50 KB per output,
|
|
247
|
+
* the array is ~5 MB; at 1000 it would be ~50 MB, which is enough to be felt as the app hanging on
|
|
248
|
+
* every broadcast. 100 is roughly a day's worth of sub-agent work for a person using this as a tool
|
|
249
|
+
* rather than as a load generator, and a run older than that is still recoverable in full through Pi -
|
|
250
|
+
* the record carries `sessionId`, and `switch_session` or `export_html` reads the real transcript. So
|
|
251
|
+
* what the bound costs is a scrollback affordance, not history.
|
|
252
|
+
*
|
|
253
|
+
* Exported so a test can assert the bound against the same number the store uses rather than
|
|
254
|
+
* re-deriving it.
|
|
255
|
+
*/
|
|
256
|
+
export const SUBAGENT_RUN_RETENTION = 100;
|
|
257
|
+
/**
|
|
258
|
+
* Evicts settled runs down to `SUBAGENT_RUN_RETENTION`, newest first.
|
|
259
|
+
*
|
|
260
|
+
* TWO RUNS ARE NEVER EVICTED, and both rules exist because eviction is the one operation here that can
|
|
261
|
+
* destroy evidence:
|
|
262
|
+
*
|
|
263
|
+
* 1. Anything still `running`. That row is the CLAIM that startup reconciliation looks for; removing it
|
|
264
|
+
* would silently forget a child that is still out there, which is the exact orphan this whole feature
|
|
265
|
+
* was built to make recoverable.
|
|
266
|
+
* 2. Runs of a conversation that still exists and is not archived, until there is nothing else left to
|
|
267
|
+
* drop. The alternatives go first because they are the ones nobody is looking at: the conversation
|
|
268
|
+
* was archived or deleted, so there is no transcript for the card to sit under and no `state` the
|
|
269
|
+
* user is reading. That is why this is not a plain "keep the newest N" slice - the newest N would
|
|
270
|
+
* evict an active conversation's run in favour of an archived one's.
|
|
271
|
+
*
|
|
272
|
+
* Mutated in place, like the reconciliation above, and never throws: an `archivedAt` that is not a
|
|
273
|
+
* string counts as archived rather than as a reason to keep the row.
|
|
274
|
+
*/
|
|
275
|
+
function trimSubagentRuns(runs, conversations) {
|
|
276
|
+
const settled = runs.filter((run) => run?.status !== "running");
|
|
277
|
+
// Over the bound by at most the number of live runs, so one pass is enough: everything older than
|
|
278
|
+
// `keep` settled rows is dropped, and live runs were never in that slice to begin with.
|
|
279
|
+
const excess = settled.length - SUBAGENT_RUN_RETENTION;
|
|
280
|
+
if (excess <= 0)
|
|
281
|
+
return;
|
|
282
|
+
const live = new Set(conversations.filter((conversation) => conversation && typeof conversation.archivedAt !== "string").map((conversation) => conversation.id));
|
|
283
|
+
const droppableOldestFirst = [...settled].reverse();
|
|
284
|
+
const doomed = new Set();
|
|
285
|
+
for (const run of droppableOldestFirst)
|
|
286
|
+
if (!live.has(run.conversationId))
|
|
287
|
+
doomed.add(run.id);
|
|
288
|
+
for (const run of droppableOldestFirst) {
|
|
289
|
+
if (doomed.size >= excess)
|
|
290
|
+
break;
|
|
291
|
+
if (!doomed.has(run.id))
|
|
292
|
+
doomed.add(run.id);
|
|
293
|
+
}
|
|
294
|
+
runs.splice(0, runs.length, ...runs.filter((run) => !doomed.has(run.id)));
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* How many orchestrated plans are kept.
|
|
298
|
+
*
|
|
299
|
+
* SMALLER THAN THE RUN RETENTION, and deliberately so. A plan does not duplicate the runs it executed -
|
|
300
|
+
* it holds one row per STEP - so fifty plans point at runs that are themselves evicted at 100. Keeping
|
|
301
|
+
* more plans than runs would leave timelines whose cards have all been trimmed away, which is a worse
|
|
302
|
+
* outcome than forgetting the plan: an empty timeline reads as "nothing ran" rather than as "the details
|
|
303
|
+
* aged out". Fifty is also well past what one working day of orchestration produces, since a plan is a
|
|
304
|
+
* request that needed several specialists rather than a unit of work.
|
|
305
|
+
*/
|
|
306
|
+
export const WORKFLOW_RETENTION = 50;
|
|
307
|
+
/**
|
|
308
|
+
* Evicts settled plans down to `WORKFLOW_RETENTION`, newest first.
|
|
309
|
+
*
|
|
310
|
+
* A `running` plan is NEVER evicted, for the reason runs are not: that row is the claim startup
|
|
311
|
+
* reconciliation looks for, and forgetting it would leave a plan that claims to be executing with nothing
|
|
312
|
+
* executing it - the one state that is unreconcilable rather than merely stale.
|
|
313
|
+
*
|
|
314
|
+
* Unlike `trimSubagentRuns` this makes no attempt to favour live conversations. A plan's own steps name
|
|
315
|
+
* the runs they dispatched, so an evicted plan is the one thing that must survive as long as the cards it
|
|
316
|
+
* explains; the flat newest-N bound keeps that simple and keeps the bound honest.
|
|
317
|
+
*/
|
|
318
|
+
function trimWorkflows(workflows) {
|
|
319
|
+
const settled = workflows.filter((plan) => plan?.status !== "running");
|
|
320
|
+
const excess = settled.length - WORKFLOW_RETENTION;
|
|
321
|
+
if (excess <= 0)
|
|
322
|
+
return;
|
|
323
|
+
const doomed = new Set();
|
|
324
|
+
for (const plan of [...settled].reverse()) {
|
|
325
|
+
if (doomed.size >= excess)
|
|
326
|
+
break;
|
|
327
|
+
doomed.add(plan.id);
|
|
328
|
+
}
|
|
329
|
+
workflows.splice(0, workflows.length, ...workflows.filter((plan) => !doomed.has(plan.id)));
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* How many scheduled tasks are kept.
|
|
333
|
+
*
|
|
334
|
+
* A task is a standing arrangement, not a record of something that happened, so the bound here is much
|
|
335
|
+
* looser than the run retention: a person who keeps a daily task for a year has one task, and the
|
|
336
|
+
* hundredth is already a sign that the list is being used as a log rather than as a list of intentions.
|
|
337
|
+
*/
|
|
338
|
+
export const SCHEDULED_TASK_RETENTION = 100;
|
|
339
|
+
/** Evicts the OLDEST scheduled tasks once there are more than `SCHEDULED_TASK_RETENTION`. */
|
|
340
|
+
function trimScheduledTasks(tasks) {
|
|
341
|
+
const excess = tasks.length - SCHEDULED_TASK_RETENTION;
|
|
342
|
+
if (excess <= 0)
|
|
343
|
+
return;
|
|
344
|
+
const doomed = new Set();
|
|
345
|
+
for (const task of [...tasks].sort((a, b) => a.createdAt - b.createdAt)) {
|
|
346
|
+
if (doomed.size >= excess)
|
|
347
|
+
break;
|
|
348
|
+
doomed.add(task.id);
|
|
349
|
+
}
|
|
350
|
+
tasks.splice(0, tasks.length, ...tasks.filter((task) => !doomed.has(task.id)));
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Why a plan the previous process left `running` is stopped rather than resumed, in the same spirit and
|
|
354
|
+
* for the same audience as `ORPHANED_RUN_ERROR`.
|
|
355
|
+
*
|
|
356
|
+
* It says the work was NOT finished, not that it failed. The distinction matters to the person reading
|
|
357
|
+
* it: a verifier that never reported is a question left open, while a patcher that reported and was then
|
|
358
|
+
* interrupted is a question already answered. The plan keeps every attempt it made, so what is actually
|
|
359
|
+
* known is still on the timeline underneath this line.
|
|
360
|
+
*/
|
|
361
|
+
const ORPHANED_WORKFLOW_ERROR = "服务器上次退出时这个编排仍在运行;它的步骤已经随进程消失,本次编排被标记为停止,没有自动续跑。";
|
|
362
|
+
/**
|
|
363
|
+
* Startup reconciliation: every plan the previous process left `running` is an orphan.
|
|
364
|
+
*
|
|
365
|
+
* THE SAME ARGUMENT AS `reconcileSubagentRuns`, applied one level up. A plan marked `running` is a claim
|
|
366
|
+
* that a loop is walking it, and no such loop can survive the process that owned it.
|
|
367
|
+
*
|
|
368
|
+
* WHY `stopped` AND NOT `failed`, which is the one place this deliberately differs from a run. A failed
|
|
369
|
+
* step is a verdict the sub-agent reached; nothing here was reached, so calling it failed would report a
|
|
370
|
+
* conclusion that does not exist. `stopped` is the status this project already uses for work that was
|
|
371
|
+
* cut short rather than completed, and it is what the timeline's own stop button produces, so a plan
|
|
372
|
+
* abandoned by a crash looks like the thing it actually is: halted, with its steps' work intact.
|
|
373
|
+
*
|
|
374
|
+
* Steps are NOT rewritten. A step left `running` keeps that status - it is the true account of the child
|
|
375
|
+
* process that is gone - while every step still `pending` becomes `stopped`, because those never started
|
|
376
|
+
* and leaving them `pending` would show a plan as still having work ahead of it that nothing will do.
|
|
377
|
+
*/
|
|
378
|
+
function reconcileWorkflows(state) {
|
|
379
|
+
// LEFT ABSENT WHEN IT WAS ABSENT, which is the opposite of `reconcileSubagentRuns` and deliberate. That
|
|
380
|
+
// one assigns unconditionally because `subagentRuns` is a required field that must be an array. This one
|
|
381
|
+
// is optional, and the project rule for optional lists is the one `setTodos` states: absence and an
|
|
382
|
+
// empty list mean the same thing to every reader, so the key is DELETED rather than stored as `[]`. A
|
|
383
|
+
// server that has never run an orchestration should not leave behind a `workflows: []` claiming it has
|
|
384
|
+
// considered plans and found none - and writing one would mean this sweep marked the file changed and
|
|
385
|
+
// persisted it, for a key that did not need to exist.
|
|
386
|
+
if (!Array.isArray(state.workflows)) {
|
|
387
|
+
// A present-but-not-an-array value is still normalized, because `state.json` is read blind and a
|
|
388
|
+
// hand edit or an older build can leave anything here; ignoring it would let it reach every reader.
|
|
389
|
+
if (state.workflows !== undefined)
|
|
390
|
+
state.workflows = [];
|
|
391
|
+
return [];
|
|
392
|
+
}
|
|
393
|
+
const orphaned = [];
|
|
394
|
+
for (const plan of state.workflows) {
|
|
395
|
+
if (!plan || plan.status !== "running")
|
|
396
|
+
continue;
|
|
397
|
+
for (const step of plan.steps ?? []) {
|
|
398
|
+
if (step?.status === "pending")
|
|
399
|
+
step.status = "stopped";
|
|
400
|
+
}
|
|
401
|
+
plan.status = "stopped";
|
|
402
|
+
plan.finishedAt = now();
|
|
403
|
+
orphaned.push(plan);
|
|
404
|
+
}
|
|
405
|
+
return orphaned;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Startup reconciliation for the waiting messages: one the previous process left `sending` goes back
|
|
409
|
+
* to `waiting`, and any legacy waiting list is folded back into the transcripts it belonged to.
|
|
410
|
+
*
|
|
411
|
+
* `sending` is one claim only: "this text has been written to a live Pi child's stdin as a `steer` and
|
|
412
|
+
* Pi has not confirmed delivering it". The claim dies with the process that made it, exactly like the
|
|
413
|
+
* `running` claims above - the Pi that would have delivered it was a child of the server that is no
|
|
414
|
+
* longer running, so it can never confirm anything now.
|
|
415
|
+
*
|
|
416
|
+
* RETURNING IT TO THE WAITING SET, RATHER THAN DROPPING IT OR LEAVING IT SENDING, is the only honest
|
|
417
|
+
* third option:
|
|
418
|
+
*
|
|
419
|
+
* - Dropping it would lose a message the user is looking at in their own transcript, silently and
|
|
420
|
+
* permanently - and unlike the old separate list, that message is not one entry among several, it is
|
|
421
|
+
* the only copy of those words there is.
|
|
422
|
+
* - Leaving it `sending` would show a message as "already handed to the agent, cannot be cancelled"
|
|
423
|
+
* that in fact never reached any model and can be cancelled - a UI claiming an irreversible fact
|
|
424
|
+
* about a reversible state.
|
|
425
|
+
* - Re-queueing is TRUE: Pi drains steering before its loop can end (`agent-loop.ts:295`), and it
|
|
426
|
+
* announces the delivery with `message_start` before the turn settles
|
|
427
|
+
* (`agent-session.ts:1116-1136`), which this server consumes and applies. So a message still `sending`
|
|
428
|
+
* when the process died provably was not delivered. Re-queued, the user sees it again and can steer it
|
|
429
|
+
* into the next turn.
|
|
430
|
+
*
|
|
431
|
+
* THE LEGACY FOLD IS WHAT MAKES THIS AN UPGRADE RATHER THAN A RESET. A state file written by a build
|
|
432
|
+
* that kept waiting messages in their own array holds real words the user typed, in a shape this build
|
|
433
|
+
* no longer reads. Dropping that array would silently lose every message that was waiting at the moment
|
|
434
|
+
* of the upgrade - and that is the one moment where a reader is most likely to be looking at the queue.
|
|
435
|
+
* So each legacy entry is appended to its own conversation as a waiting MESSAGE, keeping its id, text
|
|
436
|
+
* and images, in the order the array had them.
|
|
437
|
+
*
|
|
438
|
+
* IT IS ONE-WAY, deliberately: the key is deleted after the fold, so a second boot cannot duplicate
|
|
439
|
+
* them, and a folded message keeps its `q_`-prefixed id so nothing can mistake one for a message this
|
|
440
|
+
* build wrote (`claimClientMessageId` only accepts `message_` ids, and a collision there falls back to
|
|
441
|
+
* a minted id rather than to a fold).
|
|
442
|
+
*
|
|
443
|
+
* Mutated in place and persisted by `open`, so a queue written by a build that predates it, or by a
|
|
444
|
+
* hand edit, is repaired on the first boot rather than read as permanently stuck.
|
|
445
|
+
*
|
|
446
|
+
* `changed` is reported separately from `recovered` because they are different repairs with different
|
|
447
|
+
* consequences: a `recovered` message is one the user can see and therefore needs announcing, while a
|
|
448
|
+
* DROPPED row is a broken file that has to be rewritten or it is re-dropped on every single boot. Neither
|
|
449
|
+
* is worth a persist on its own account - `open` persists once, for all the sweeps together.
|
|
450
|
+
*/
|
|
451
|
+
function reconcileWaitingMessages(state) {
|
|
452
|
+
// The legacy array, read blind: `Array.isArray` rather than `?? []`, for the same reason the sweeps
|
|
453
|
+
// above do it, because a truthy non-array left by a hand edit would make every call below throw.
|
|
454
|
+
const legacy = state.queuedMessages;
|
|
455
|
+
const queue = Array.isArray(legacy) ? legacy : [];
|
|
456
|
+
const hadKey = Array.isArray(legacy);
|
|
457
|
+
// An entry that is not usable is dropped rather than repaired: every field is load-bearing (the id is
|
|
458
|
+
// what cancel/steer name, the content is what the user wrote), so a partial entry has no safe default
|
|
459
|
+
// and keeping it would put `undefined` text on the wire.
|
|
460
|
+
const usable = queue.filter((item) => Boolean(item) && typeof item.id === "string"
|
|
461
|
+
&& typeof item.conversationId === "string"
|
|
462
|
+
&& typeof item.content === "string");
|
|
463
|
+
// DELETED UNCONDITIONALLY, before anything else reads it. The fold below is the only consumer, and
|
|
464
|
+
// leaving the key in place would re-fold the same words on every single boot.
|
|
465
|
+
delete state.queuedMessages;
|
|
466
|
+
const recovered = [];
|
|
467
|
+
for (const conversation of state.conversations) {
|
|
468
|
+
for (const message of conversation.messages) {
|
|
469
|
+
// A `delivery` on an ASSISTANT message is still a broken file: rendering a waiting state on an
|
|
470
|
+
// assistant bubble would be a claim about nothing, and nothing in the code path writes one. Tool
|
|
471
|
+
// messages with `delivery` are queue items now (exec / sub-agent background completions) - if they
|
|
472
|
+
// died in `sending`, recover them to `waiting` just like user messages, so a crashed server does
|
|
473
|
+
// not strand a 后台回传 whose delivery it had already accepted.
|
|
474
|
+
if (message.role === "assistant") {
|
|
475
|
+
delete message.delivery;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (message.role !== "user" && message.role !== "tool") {
|
|
479
|
+
delete message.delivery;
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
if (message.delivery !== "sending")
|
|
483
|
+
continue;
|
|
484
|
+
message.delivery = "waiting";
|
|
485
|
+
recovered.push({ conversationId: conversation.id, message });
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const folded = [];
|
|
489
|
+
for (const entry of usable) {
|
|
490
|
+
const conversation = state.conversations.find((item) => item.id === entry.conversationId);
|
|
491
|
+
// An entry naming a conversation that is gone has nowhere to go. That is the one legacy case that is
|
|
492
|
+
// genuinely dropped, and it is reported through `changed` so the key's removal is written to disk.
|
|
493
|
+
if (!conversation)
|
|
494
|
+
continue;
|
|
495
|
+
const message = {
|
|
496
|
+
id: entry.id,
|
|
497
|
+
role: "user",
|
|
498
|
+
content: entry.content,
|
|
499
|
+
createdAt: typeof entry.createdAt === "string" ? entry.createdAt : now(),
|
|
500
|
+
// ALWAYS `waiting`, never the legacy `sending`: the claim died with the process that made it, which
|
|
501
|
+
// is the same argument the sweep above makes about a message that is genuinely `sending`.
|
|
502
|
+
delivery: "waiting",
|
|
503
|
+
};
|
|
504
|
+
if (entry.images && entry.images.length > 0)
|
|
505
|
+
message.images = structuredClone(entry.images);
|
|
506
|
+
if (entry.attachments && entry.attachments.length > 0)
|
|
507
|
+
message.attachments = structuredClone(entry.attachments);
|
|
508
|
+
conversation.messages.push(message);
|
|
509
|
+
folded.push({ conversationId: conversation.id, message });
|
|
510
|
+
}
|
|
511
|
+
return { recovered, folded, changed: hadKey || usable.length !== queue.length || recovered.length > 0 };
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Which messages and which sub-agent runs a revert to `messageId` removes.
|
|
515
|
+
*
|
|
516
|
+
* THE BOUNDARY IS AN ARRAY INDEX, NEVER A TIMESTAMP. `store.ts` stamps both halves of a turn with
|
|
517
|
+
* `now()` at millisecond precision, so a user message and the assistant reply after it very often share
|
|
518
|
+
* one timestamp - the same reason the browser sorts messages with an explicit `seq` tiebreak
|
|
519
|
+
* (`App.tsx:870`). Sorting by time and cutting there would cut mid-turn at random. `messages` is append
|
|
520
|
+
* only and nothing ever reorders it, so its order IS the conversation's order.
|
|
521
|
+
*
|
|
522
|
+
* WHICH RUNS ARE DOOMED is decided by `startedAt` against the first removed message's `createdAt`, and
|
|
523
|
+
* that comparison is safe for the same reason the index is: a child can only be dispatched AFTER the user
|
|
524
|
+
* message of its turn exists, and both stamps come from this one process's clock. A run at or after the
|
|
525
|
+
* first removed message's stamp was therefore dispatched by a removed turn; one before it belonged to a
|
|
526
|
+
* turn that survives.
|
|
527
|
+
*
|
|
528
|
+
* Throws rather than returning an empty plan, because every caller would otherwise have to invent its
|
|
529
|
+
* own message for "that message is not in this conversation" - and a revert that silently did nothing is
|
|
530
|
+
* the failure this whole feature exists to avoid.
|
|
531
|
+
*/
|
|
532
|
+
function planRevert(state, conversationId, messageId, withdraw = false) {
|
|
533
|
+
const conversation = state.conversations.find((item) => item?.id === conversationId);
|
|
534
|
+
if (!conversation)
|
|
535
|
+
throw new Error("会话不存在");
|
|
536
|
+
const boundaryIndex = conversation.messages.findIndex((item) => item?.id === messageId);
|
|
537
|
+
if (boundaryIndex < 0)
|
|
538
|
+
throw new Error("要回退的那条消息不在这个会话里");
|
|
539
|
+
const boundary = conversation.messages[boundaryIndex];
|
|
540
|
+
if (!withdraw && !boundary?.piEntryId)
|
|
541
|
+
throw new Error("这条消息没有对应的 Pi 记录,不能作为回退位置。请在它之后的任意一条消息上回退。");
|
|
542
|
+
if (withdraw && boundary.role !== "user")
|
|
543
|
+
throw new Error("只能撤回你自己发送的消息。");
|
|
544
|
+
const removed = conversation.messages.slice(boundaryIndex + (withdraw ? 0 : 1));
|
|
545
|
+
// Unparseable stamps are compared as 0, i.e. "older than everything", which keeps a corrupted run
|
|
546
|
+
// record ALIVE rather than deleting a child that may still be the user's most recent work. Deleting on a
|
|
547
|
+
// guess is the irreversible direction; keeping a stale record costs one card that startup reconciliation
|
|
548
|
+
// already knows how to explain.
|
|
549
|
+
const firstRemovedAt = removed.length ? Date.parse(removed[0].createdAt) || 0 : Number.POSITIVE_INFINITY;
|
|
550
|
+
const doomedRunIds = state.subagentRuns
|
|
551
|
+
.filter((run) => run?.conversationId === conversationId && (Date.parse(run.startedAt) || 0) >= firstRemovedAt)
|
|
552
|
+
.map((run) => run.id);
|
|
553
|
+
return { boundaryIndex, boundaryEntryId: boundary.piEntryId ?? conversation.messages.slice(0, boundaryIndex).reverse().find(item => item.piEntryId)?.piEntryId ?? "", removedMessageIds: removed.map((item) => item.id), doomedRunIds };
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
556
|
+
* Brings `state.todosByConversation` back to a shape the browser can render, on boot.
|
|
557
|
+
*
|
|
558
|
+
* THE SAME REASON `reconcileWaitingMessages` EXISTS, and the same three cases, but nothing here RECOVERS
|
|
559
|
+
* anything: there is no "still running" claim in a todo list to contradict, because the list is not a
|
|
560
|
+
* record of a running thing - it is a record of what a model last said it was doing. So there is nothing to
|
|
561
|
+
* reconcile against a fact and nothing to announce; the sweep exists purely because `state.json` is read
|
|
562
|
+
* blind by `JSON.parse(...) as AppState` and owes nothing to the declared type.
|
|
563
|
+
*
|
|
564
|
+
* What it does buy, and it is not nothing:
|
|
565
|
+
*
|
|
566
|
+
* - A hand-edited or half-written `todos` (an object, a string, a list holding `null`) is replaced by the
|
|
567
|
+
* empty list rather than reaching the sidebar, where `todos.map` would throw inside React's render and
|
|
568
|
+
* unmount the whole tree. That is the `.shell` gone / zero messages / one solid #0d111b frame measured in
|
|
569
|
+
* `scripts/message-timestamps.test.mjs` for `createdAt`, one field over.
|
|
570
|
+
* - A `status` the stylesheet has no rule for is coerced to `pending`, so a typo can never render as the
|
|
571
|
+
* completed style by falling through every `===` comparison.
|
|
572
|
+
* - A missing `id` is filled in, which is what stops two identical lines of text sharing one React key.
|
|
573
|
+
*
|
|
574
|
+
* `changed` is reported so `open` persists the repair. Unlike the two sweeps beside it, this one has
|
|
575
|
+
* nothing to warn about on stdout - a repaired todo list is a fixed file, not a fact the user was shown -
|
|
576
|
+
* so it is the quietest of the three and deliberately so.
|
|
577
|
+
*/
|
|
578
|
+
function reconcileTodos(state) {
|
|
579
|
+
const before = JSON.stringify({ todos: state.todos, todosByConversation: state.todosByConversation });
|
|
580
|
+
const legacy = state.todos;
|
|
581
|
+
if (Array.isArray(legacy) && legacy.length) {
|
|
582
|
+
const targetConversationId = state.conversations[0]?.id;
|
|
583
|
+
// The former global list had no ownership metadata. Assign it to the most-recent conversation
|
|
584
|
+
// (the first row in the persisted sidebar order) so an upgrade preserves the user's visible plan;
|
|
585
|
+
// inventing a new session or copying the list to every session would misrepresent its ownership.
|
|
586
|
+
if (targetConversationId)
|
|
587
|
+
state.todosByConversation = { ...(state.todosByConversation ?? {}), [targetConversationId]: legacy };
|
|
588
|
+
}
|
|
589
|
+
delete state.todos;
|
|
590
|
+
if (state.todosByConversation) {
|
|
591
|
+
const conversationIds = new Set(state.conversations.map((conversation) => conversation.id));
|
|
592
|
+
for (const [id, raw] of Object.entries(state.todosByConversation)) {
|
|
593
|
+
const normalized = conversationIds.has(id) ? normalizeTodos(raw).todos : [];
|
|
594
|
+
if (normalized.length)
|
|
595
|
+
state.todosByConversation[id] = normalized;
|
|
596
|
+
else
|
|
597
|
+
delete state.todosByConversation[id];
|
|
598
|
+
}
|
|
599
|
+
if (!Object.keys(state.todosByConversation).length)
|
|
600
|
+
delete state.todosByConversation;
|
|
601
|
+
}
|
|
602
|
+
const after = JSON.stringify({ todos: state.todos, todosByConversation: state.todosByConversation });
|
|
603
|
+
return { changed: before !== after };
|
|
604
|
+
}
|
|
605
|
+
function backgroundTaskMessage(conversation, task, outcome, content, deliver) {
|
|
606
|
+
const finished = { ...task, ...outcome, finishedAt: now() };
|
|
607
|
+
const origin = conversation.messages.find(message => message.id === task.originMessageId);
|
|
608
|
+
const call = task.originCallRow === undefined ? undefined : origin?.toolCalls?.[task.originCallRow];
|
|
609
|
+
const anchored = task.agentId === "exec" && call?.backgroundTask?.id === task.id;
|
|
610
|
+
if (anchored && call)
|
|
611
|
+
call.backgroundTask = { id: task.id, ...outcome };
|
|
612
|
+
const message = {
|
|
613
|
+
id: id("message"),
|
|
614
|
+
role: "tool",
|
|
615
|
+
content,
|
|
616
|
+
createdAt: finished.finishedAt,
|
|
617
|
+
backgroundTask: anchored ? { ...finished, output: undefined } : finished,
|
|
618
|
+
...(deliver && !conversation.archivedAt ? { delivery: "waiting" } : {}),
|
|
619
|
+
};
|
|
620
|
+
conversation.messages.push(message);
|
|
621
|
+
conversation.updatedAt = message.createdAt;
|
|
622
|
+
return message;
|
|
623
|
+
}
|
|
624
|
+
// Restore interrupted tasks and their checkpoints to the owning transcript on startup.
|
|
625
|
+
function reconcileBackgroundTasks(state) {
|
|
626
|
+
const tasks = Array.isArray(state.backgroundTasks) ? state.backgroundTasks : [];
|
|
627
|
+
state.backgroundTasks = [];
|
|
628
|
+
if (!tasks.length)
|
|
629
|
+
return { orphaned: [], changed: false, unlinked: [] };
|
|
630
|
+
const orphaned = [];
|
|
631
|
+
const unlinked = [];
|
|
632
|
+
for (const task of tasks) {
|
|
633
|
+
if (!task)
|
|
634
|
+
continue;
|
|
635
|
+
const conversation = state.conversations?.find(c => c?.id === task.conversationId);
|
|
636
|
+
if (!conversation) {
|
|
637
|
+
unlinked.push(task);
|
|
638
|
+
state.backgroundTasks.push(task);
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
orphaned.push(task);
|
|
642
|
+
const reason = "任务随服务重启被终止";
|
|
643
|
+
const kind = task.agentId === "exec" ? "exec" : "subagent";
|
|
644
|
+
const content = `<task id="${task.id}" state="error" kind="${kind}">\n<summary>${task.title}</summary>\n<task_error>\n${reason}</task_error>\n</task>`;
|
|
645
|
+
const run = task.agentId === "exec" ? undefined : state.subagentRuns.find(item => item.id === task.id);
|
|
646
|
+
const output = run ? subagentProgress(run) : task.output;
|
|
647
|
+
backgroundTaskMessage(conversation, task, {
|
|
648
|
+
status: "interrupted", reason, output: output?.slice(-BACKGROUND_LOG_LIMIT), outputOffset: task.outputOffset,
|
|
649
|
+
outputTruncated: task.outputTruncated || (output?.length ?? 0) > BACKGROUND_LOG_LIMIT || run?.outputTruncated || run?.toolCalls?.some(call => call.outputTruncated),
|
|
650
|
+
}, content, false);
|
|
651
|
+
if (conversation.status === "awaiting_background")
|
|
652
|
+
conversation.status = "stopped";
|
|
653
|
+
}
|
|
654
|
+
return { orphaned, changed: orphaned.length > 0, unlinked };
|
|
655
|
+
}
|
|
656
|
+
function normalizeProjectEscalations(project, conversation) {
|
|
657
|
+
let changed = false;
|
|
658
|
+
for (const item of project.escalations ?? []) {
|
|
659
|
+
if (String(item.status) === "pending") {
|
|
660
|
+
item.status = "open";
|
|
661
|
+
changed = true;
|
|
662
|
+
}
|
|
663
|
+
if (item.status !== "open" || item.audience === "supervisor" || !item.requestedByConversationId)
|
|
664
|
+
continue;
|
|
665
|
+
const requester = conversation(item.requestedByConversationId);
|
|
666
|
+
const assigned = item.requestedByConversationId !== project.ownerConversationId
|
|
667
|
+
&& item.requestedByConversationId !== project.initiatorConversationId
|
|
668
|
+
? project.tasks?.find(task => task.ownerConversationId === item.requestedByConversationId
|
|
669
|
+
|| task.reviewerConversationId === item.requestedByConversationId) : undefined;
|
|
670
|
+
const taskManager = assigned?.parentTaskId
|
|
671
|
+
? project.tasks.find(task => task.id === assigned.parentTaskId)?.ownerConversationId : project.ownerConversationId;
|
|
672
|
+
const fallback = !requester && item.requestedByConversationId === project.ownerConversationId ? project.initiatorConversationId : undefined;
|
|
673
|
+
if (!requester?.parentConversationId && !assigned && !fallback)
|
|
674
|
+
continue;
|
|
675
|
+
// Old versions let project leaders address the user while they still had a parent.
|
|
676
|
+
const parent = [requester?.parentConversationId, assigned ? taskManager : undefined, fallback]
|
|
677
|
+
.filter((id) => Boolean(id && id !== item.requestedByConversationId))
|
|
678
|
+
.map(conversation)
|
|
679
|
+
.find(candidate => candidate?.workspaceId === project.workspaceId && !candidate.archivedAt
|
|
680
|
+
&& (candidate.id === project.ownerConversationId || candidate.id === project.initiatorConversationId
|
|
681
|
+
|| project.tasks?.some(task => task.ownerConversationId === candidate.id || task.reviewerConversationId === candidate.id)));
|
|
682
|
+
item.audience = "supervisor";
|
|
683
|
+
item.targetConversationId = parent?.id;
|
|
684
|
+
if (!parent) {
|
|
685
|
+
item.status = "dismissed";
|
|
686
|
+
item.decision = "旧例外找不到可处理的直属上级,原始记录已保留。";
|
|
687
|
+
item.resolvedAt = now();
|
|
688
|
+
}
|
|
689
|
+
changed = true;
|
|
690
|
+
}
|
|
691
|
+
return changed;
|
|
692
|
+
}
|
|
693
|
+
export class Store {
|
|
694
|
+
repository;
|
|
695
|
+
state;
|
|
696
|
+
constructor(repository, state) {
|
|
697
|
+
this.repository = repository;
|
|
698
|
+
this.state = state;
|
|
699
|
+
initializeMemoryTrees(state.conversations);
|
|
700
|
+
}
|
|
701
|
+
static async open(filePath) {
|
|
702
|
+
return this.openRepository(new JsonStateRepository(filePath));
|
|
703
|
+
}
|
|
704
|
+
/** Opens an injected repository, retaining domain reconciliation here. */
|
|
705
|
+
static async openRepository(repository) {
|
|
706
|
+
try {
|
|
707
|
+
const state = await repository.load();
|
|
708
|
+
// A COLLECTION THE FILE DID NOT HAVE IS A REPAIR TOO, and it is counted as one here rather than left
|
|
709
|
+
// to the sweeps below - which is what this branch used to do by accident. The follow-up queue sweep
|
|
710
|
+
// reported `changed` for any file without a `queuedMessages` key, so every state written before that
|
|
711
|
+
// feature shipped was rewritten on its first boot, and a hand-seeded file still is. Deleting the
|
|
712
|
+
// queue took that side effect with it, and with it the observable fact that a server which had just
|
|
713
|
+
// defaulted a collection says so on disk.
|
|
714
|
+
//
|
|
715
|
+
// The rule is the one already written above the queue sweep: a repaired file has to be rewritten, or
|
|
716
|
+
// it is repaired again on every single boot - and until it is, anything reading the file sees the
|
|
717
|
+
// un-normalised shape rather than the one the store is actually running on.
|
|
718
|
+
const defaulted = ["workspaces", "conversations", "subagentRuns"].filter((key) => !Array.isArray(state[key])).length > 0
|
|
719
|
+
|| !Array.isArray(state.backgroundTasks)
|
|
720
|
+
|| (state.scheduledTasks !== undefined && !Array.isArray(state.scheduledTasks))
|
|
721
|
+
|| (state.projects !== undefined && !Array.isArray(state.projects));
|
|
722
|
+
if (!Array.isArray(state.backgroundTasks))
|
|
723
|
+
state.backgroundTasks = [];
|
|
724
|
+
// A scheduled-task list that is not a list is not a list of tasks. The key is dropped rather than
|
|
725
|
+
// coerced, so a corrupted file reads as "this install has no scheduled tasks" - the same thing a
|
|
726
|
+
// fresh install reads - instead of crashing the panel on every poll.
|
|
727
|
+
if (state.scheduledTasks !== undefined && !Array.isArray(state.scheduledTasks))
|
|
728
|
+
delete state.scheduledTasks;
|
|
729
|
+
if (state.projects !== undefined && !Array.isArray(state.projects))
|
|
730
|
+
delete state.projects;
|
|
731
|
+
let migratedProjects = false;
|
|
732
|
+
const conversationsById = new Map((state.conversations ?? []).filter(Boolean).map(item => [item.id, item]));
|
|
733
|
+
for (const project of state.projects ?? []) {
|
|
734
|
+
if (normalizeProjectEscalations(project, id => conversationsById.get(id)))
|
|
735
|
+
migratedProjects = true;
|
|
736
|
+
if (String(project.status) !== "completed")
|
|
737
|
+
continue;
|
|
738
|
+
project.status = project.ownerConversationId ? "active" : "awaiting_start";
|
|
739
|
+
const delivery = [...(project.reports ?? [])].reverse().find((report) => report.kind === "delivery" && !report.taskId);
|
|
740
|
+
if (delivery && !delivery.createdAt)
|
|
741
|
+
delivery.createdAt = project.closedAt ?? project.updatedAt;
|
|
742
|
+
delete project.closedAt;
|
|
743
|
+
migratedProjects = true;
|
|
744
|
+
}
|
|
745
|
+
// Every sweep runs before the store is constructed, so a single persist below publishes them together.
|
|
746
|
+
// Reconciling them in separate writes would put a file on disk in which one kind of orphan was fixed
|
|
747
|
+
// and the other was not - a half-repaired state that still needs a second restart to finish.
|
|
748
|
+
const orphaned = reconcileSubagentRuns(state);
|
|
749
|
+
const orphanedWorkflows = reconcileWorkflows(state);
|
|
750
|
+
const orphanedTasks = reconcileBackgroundTasks(state);
|
|
751
|
+
const interrupted = reconcileConversations(state);
|
|
752
|
+
const requeued = reconcileWaitingMessages(state);
|
|
753
|
+
const todos = reconcileTodos(state);
|
|
754
|
+
// THE USAGE SWEEP. A run recorded before the conversation ledger existed has its money sitting in
|
|
755
|
+
// the run record and nowhere else, so the ledger is brought up to date here - once, and only
|
|
756
|
+
// for the runs that carry usage and have not been accounted for.
|
|
757
|
+
const foldedUsage = foldUnaccountedRunUsage(state);
|
|
758
|
+
const store = new Store(repository, normalizeMessageTimestamps(state));
|
|
759
|
+
// Persisted here, in `open`, rather than left for the first unrelated write: a reconciled record that
|
|
760
|
+
// is only rewritten by a later mutation would still read `running` to anything that opened the file
|
|
761
|
+
// in the meantime, and would be reconciled a SECOND time on the next restart.
|
|
762
|
+
if (defaulted || migratedProjects || orphaned.length || orphanedWorkflows.length || orphanedTasks.changed || interrupted.length || requeued.recovered.length || requeued.changed || todos.changed || foldedUsage) {
|
|
763
|
+
for (const run of orphaned)
|
|
764
|
+
console.warn(`Super Pi: sub-agent run ${run.id} was still marked running when the last server stopped - it is now failed, because no child process survived it.`);
|
|
765
|
+
for (const plan of orphanedWorkflows)
|
|
766
|
+
console.warn(`Super Pi: workflow ${plan.id} was still marked running when the last server stopped - it is now stopped, because no step can still be executing.`);
|
|
767
|
+
for (const task of orphanedTasks.orphaned)
|
|
768
|
+
console.warn(`Super Pi: background task ${task.id} (${task.title}) was left in flight when the last server stopped - it has been cleaned up.`);
|
|
769
|
+
// The unlinked ones are said out loud rather than swept silently. They cannot come from this
|
|
770
|
+
// server - `/api/exec` requires a conversationId - so they are a hand-written or legacy entry,
|
|
771
|
+
// and the reader is told they were left alone instead of wondering why one task vanished and
|
|
772
|
+
// another did not.
|
|
773
|
+
for (const task of orphanedTasks.unlinked)
|
|
774
|
+
console.warn(`Super Pi: background task ${task.id} (${task.title}) has no conversation to be traced back to - it was left in place, because there is no tool call to mark as interrupted.`);
|
|
775
|
+
// Announced for the same reason: a conversation that failed while nobody was watching is invisible
|
|
776
|
+
// otherwise, and the user who was watching a spinner when the server died deserves to learn that
|
|
777
|
+
// their run is over rather than guessing from the fact that it stopped moving.
|
|
778
|
+
for (const conversation of interrupted)
|
|
779
|
+
console.warn(`Super Pi: conversation ${conversation.id} was still marked running when the last server stopped - it is now failed, because no turn was in flight any more.`);
|
|
780
|
+
for (const entry of requeued.recovered)
|
|
781
|
+
console.warn(`Super Pi: message ${entry.message.id} of conversation ${entry.conversationId} was still marked sending when the last server stopped - it is waiting again and cancellable, because the Pi that would have delivered it is gone.`);
|
|
782
|
+
for (const entry of requeued.folded)
|
|
783
|
+
console.warn(`Super Pi: message ${entry.message.id} of conversation ${entry.conversationId} was waiting in the old queue format - it has been moved into that conversation's transcript.`);
|
|
784
|
+
// Announced, because a budget that silently changed shape is a budget nobody can explain: this
|
|
785
|
+
// says the money those runs spent is now part of the conversations that dispatched them.
|
|
786
|
+
if (foldedUsage)
|
|
787
|
+
console.warn(`Super Pi: the usage of ${foldedUsage} sub-agent run(s) recorded before the usage ledger existed was added to the conversations that dispatched them.`);
|
|
788
|
+
await store.persist();
|
|
789
|
+
}
|
|
790
|
+
return store;
|
|
791
|
+
}
|
|
792
|
+
catch (error) {
|
|
793
|
+
const code = error instanceof Error ? error.code : undefined;
|
|
794
|
+
if (code !== "ENOENT") {
|
|
795
|
+
// A file-backed JSON state that cannot be parsed (or read) must not crash startup: the bad file is
|
|
796
|
+
// moved aside so a later run can still inspect it, and the server starts from a fresh state.
|
|
797
|
+
// Repositories without a file behind them keep failing loudly - there is nothing to quarantine.
|
|
798
|
+
if (!(repository instanceof JsonStateRepository))
|
|
799
|
+
throw error;
|
|
800
|
+
const quarantine = `${repository.filePath}.corrupt-${Date.now()}`;
|
|
801
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
802
|
+
try {
|
|
803
|
+
await rename(repository.filePath, quarantine);
|
|
804
|
+
console.warn(`Super Pi: state file ${repository.filePath} could not be loaded (${reason}) - it was moved to ${quarantine} and the server starts with a fresh state.`);
|
|
805
|
+
}
|
|
806
|
+
catch (moveError) {
|
|
807
|
+
console.warn(`Super Pi: state file ${repository.filePath} could not be loaded (${reason}) and could not be moved aside either (${moveError instanceof Error ? moveError.message : String(moveError)}) - the server starts with a fresh state; the unreadable file is still at ${repository.filePath}.`);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
// NO WRITE HERE, AND THAT IS AN INVARIANT RATHER THAN AN OMISSION: a store with no file behind it
|
|
811
|
+
// stays lazy, so opening one never creates a file and never has to un-create one. `persistence-
|
|
812
|
+
// repository.test.mjs` asserts it by reading the path and expecting ENOENT. Repairing an EXISTING
|
|
813
|
+
// file is the other case and is handled above; this branch invented its contents and says nothing
|
|
814
|
+
// until something actually happens.
|
|
815
|
+
//
|
|
816
|
+
// A fresh state starts with NO workspace, and that is a constraint rather than a gap: this branch
|
|
817
|
+
// used to seed one named after process.cwd(), so whatever directory the server happened to be
|
|
818
|
+
// launched from silently became a workspace. The first workspace is always an explicit decision -
|
|
819
|
+
// the client's zero-workspace empty state (App.tsx) asks for one instead.
|
|
820
|
+
return new Store(repository, { workspaces: [], conversations: [], subagentRuns: [], backgroundTasks: [] });
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* THE MODEL FILTER RULES, WITHOUT CLONING THE STATE TO READ THEM.
|
|
825
|
+
*
|
|
826
|
+
* `snapshot()` deep-clones the WHOLE application - every workspace, every conversation, every
|
|
827
|
+
* message of every conversation - and the model filter check needs ONE small array. Reading that
|
|
828
|
+
* array through a full clone is the difference between a few hundred bytes and the entire
|
|
829
|
+
* transcript of the app, on the path that runs every time a message is sent.
|
|
830
|
+
*
|
|
831
|
+
* So the rules get their own narrow reader. It returns a COPY of the array (the caller may keep
|
|
832
|
+
* it, and the store's own state must not change under it), and the individual rules are treated
|
|
833
|
+
* as read-only - which is what the filter does with them.
|
|
834
|
+
*/
|
|
835
|
+
modelFilterRules() {
|
|
836
|
+
return this.state.modelFilterRules ? [...this.state.modelFilterRules] : [];
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* THE WORKSPACE A CONVERSATION BELONGS TO, WITHOUT CLONING THE STATE TO FIND ONE ROW.
|
|
840
|
+
*
|
|
841
|
+
* The same argument as the rules above: the filter needs to know WHICH workspace the conversation
|
|
842
|
+
* is in (the rules are per workspace), and the only way to know that today is to clone everything
|
|
843
|
+
* and look. This returns a shallow copy of the one workspace - cheap, and detached enough that a
|
|
844
|
+
* caller cannot reach into the store's state through it.
|
|
845
|
+
*/
|
|
846
|
+
workspaceForConversation(conversationId) {
|
|
847
|
+
const conversation = this.state.conversations.find((item) => item.id === conversationId);
|
|
848
|
+
const workspace = this.state.workspaces.find((item) => item.id === conversation?.workspaceId);
|
|
849
|
+
return workspace ? { ...workspace } : undefined;
|
|
850
|
+
}
|
|
851
|
+
workspace(workspaceId) {
|
|
852
|
+
const workspace = this.state.workspaces.find((item) => item.id === workspaceId);
|
|
853
|
+
return workspace ? { ...workspace } : undefined;
|
|
854
|
+
}
|
|
855
|
+
/** Read every workspace as detached shallow copies. */
|
|
856
|
+
workspaces() {
|
|
857
|
+
return this.state.workspaces.map((item) => ({ ...item }));
|
|
858
|
+
}
|
|
859
|
+
/** Read the app-wide default without cloning conversations or transcripts. */
|
|
860
|
+
defaultModel() {
|
|
861
|
+
const model = this.state.defaultModel;
|
|
862
|
+
return model ? { ...model } : undefined;
|
|
863
|
+
}
|
|
864
|
+
/** Read one detached conversation for lifecycle operations. */
|
|
865
|
+
conversation(conversationId) {
|
|
866
|
+
const conversation = this.state.conversations.find((item) => item.id === conversationId);
|
|
867
|
+
if (!conversation)
|
|
868
|
+
return undefined;
|
|
869
|
+
const clone = structuredClone(conversation);
|
|
870
|
+
const escalationAudience = this.openEscalationAudiences().get(conversation.id);
|
|
871
|
+
if (escalationAudience) {
|
|
872
|
+
clone.hasOpenEscalation = true;
|
|
873
|
+
clone.escalationAudience = escalationAudience;
|
|
874
|
+
}
|
|
875
|
+
if (this.pendingResultConversationIds().has(conversation.id)) {
|
|
876
|
+
clone.hasPendingResult = true;
|
|
877
|
+
}
|
|
878
|
+
return clone;
|
|
879
|
+
}
|
|
880
|
+
/** Return every pending question in one conversation without cloning unrelated history. */
|
|
881
|
+
pendingQuestions(conversationId) {
|
|
882
|
+
const conversation = this.state.conversations.find((item) => item.id === conversationId);
|
|
883
|
+
if (!conversation)
|
|
884
|
+
return [];
|
|
885
|
+
const pending = [];
|
|
886
|
+
for (const message of conversation.messages) {
|
|
887
|
+
for (let index = 0; index < (message.toolCalls?.length ?? 0); index += 1) {
|
|
888
|
+
const question = message.toolCalls?.[index]?.question;
|
|
889
|
+
if (message.toolCalls?.[index]?.label === "question" && question?.status === "pending") {
|
|
890
|
+
pending.push({ messageId: message.id, index, question: structuredClone(question) });
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
return pending;
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* THE SCHEDULED TASKS, WITHOUT CLONING THE STATE TO FIND THEM.
|
|
898
|
+
*
|
|
899
|
+
* The same argument as the readers above, with a sharper edge: the scheduled-task clock sweeps
|
|
900
|
+
* every fifteen seconds and used to read its three-to-zero tasks through `snapshot()` - a deep
|
|
901
|
+
* clone of the whole application, every fifteen seconds, whether the user has any scheduled task or
|
|
902
|
+
* not. On a server holding a long transcript that is a full copy of the app four times a minute,
|
|
903
|
+
* produced for a list that is usually empty.
|
|
904
|
+
*
|
|
905
|
+
* The tasks are returned as a shallow copy of the array: the sweep reads `enabled` and
|
|
906
|
+
* `nextRunAt` and then hands the whole task back to the store, which owns the real one.
|
|
907
|
+
*/
|
|
908
|
+
scheduledTasks() {
|
|
909
|
+
return this.state.scheduledTasks ? [...this.state.scheduledTasks] : [];
|
|
910
|
+
}
|
|
911
|
+
projects() { return structuredClone(this.state.projects ?? []); }
|
|
912
|
+
project(projectId) { const project = this.state.projects?.find((item) => item.id === projectId); return project ? structuredClone(project) : undefined; }
|
|
913
|
+
/** Conversation IDs that currently have an unresolved escalation requested. */
|
|
914
|
+
openEscalationConversationIds() {
|
|
915
|
+
return new Set(this.openEscalationAudiences().keys());
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* 每条未决例外该谁拍板,按发起会话归拢。
|
|
919
|
+
*
|
|
920
|
+
* `supervisor` = 团队内部的事(会话在等自己的直属上级),`boss` = 到了顶层。
|
|
921
|
+
* 一个会话同时开着内部和顶层两条时,顶层那条赢:那是唯一需要用户听见的一条。
|
|
922
|
+
* 旧的子会话记录在加载时归回父会话,此处仅聚合规范化后的受众。
|
|
923
|
+
*/
|
|
924
|
+
openEscalationAudiences() {
|
|
925
|
+
const audiences = new Map();
|
|
926
|
+
for (const project of this.state.projects ?? []) {
|
|
927
|
+
for (const e of project.escalations ?? []) {
|
|
928
|
+
if ((e.status === "open" || e.status === "pending") && e.requestedByConversationId) {
|
|
929
|
+
const audience = e.audience ?? "boss";
|
|
930
|
+
if (audiences.get(e.requestedByConversationId) !== "boss") {
|
|
931
|
+
audiences.set(e.requestedByConversationId, audience);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
return audiences;
|
|
937
|
+
}
|
|
938
|
+
/** Child conversation IDs whose enqueued session result is still waiting or sending on a non-archived parent. */
|
|
939
|
+
pendingResultConversationIds() {
|
|
940
|
+
const set = new Set();
|
|
941
|
+
for (const parent of this.state.conversations) {
|
|
942
|
+
if (parent.archivedAt)
|
|
943
|
+
continue;
|
|
944
|
+
for (const message of parent.messages) {
|
|
945
|
+
if (message.role !== "tool" || !message.delivery || message.source === "session-reminder")
|
|
946
|
+
continue;
|
|
947
|
+
const tagMatch = /^<task\b([^>]*)>/.exec(message.content);
|
|
948
|
+
if (!tagMatch)
|
|
949
|
+
continue;
|
|
950
|
+
const attrs = tagMatch[1];
|
|
951
|
+
if (!/\bkind="session"/.test(attrs))
|
|
952
|
+
continue;
|
|
953
|
+
const idMatch = /\bid="([^"]+)"/.exec(attrs);
|
|
954
|
+
if (idMatch?.[1]) {
|
|
955
|
+
set.add(idMatch[1]);
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
return set;
|
|
960
|
+
}
|
|
961
|
+
async setProject(project) {
|
|
962
|
+
if (!this.state.projects)
|
|
963
|
+
this.state.projects = [];
|
|
964
|
+
const stored = structuredClone(project);
|
|
965
|
+
normalizeProjectEscalations(stored, id => this.state.conversations.find(item => item.id === id));
|
|
966
|
+
const index = this.state.projects.findIndex((item) => item.id === stored.id);
|
|
967
|
+
if (index < 0)
|
|
968
|
+
this.state.projects.unshift(stored);
|
|
969
|
+
else
|
|
970
|
+
this.state.projects[index] = stored;
|
|
971
|
+
await this.persistCollections("projects");
|
|
972
|
+
return structuredClone(stored);
|
|
973
|
+
}
|
|
974
|
+
async removeProject(projectId) {
|
|
975
|
+
if (!this.state.projects)
|
|
976
|
+
return;
|
|
977
|
+
this.state.projects = this.state.projects.filter((item) => item.id !== projectId);
|
|
978
|
+
if (!this.state.projects.length)
|
|
979
|
+
delete this.state.projects;
|
|
980
|
+
await this.persistCollections("projects");
|
|
981
|
+
}
|
|
982
|
+
/** Small detached rows used when refreshing each conversation's scoped model catalog. */
|
|
983
|
+
catalogConversationTargets() {
|
|
984
|
+
return this.state.conversations.map(({ id, archivedAt, model }) => ({
|
|
985
|
+
id,
|
|
986
|
+
archivedAt,
|
|
987
|
+
model: model ? { ...model } : undefined,
|
|
988
|
+
}));
|
|
989
|
+
}
|
|
990
|
+
/** Clone only one workspace's transcripts, never unrelated workspaces or app state. */
|
|
991
|
+
conversationsForWorkspace(workspaceId) {
|
|
992
|
+
const openEscalations = this.openEscalationAudiences();
|
|
993
|
+
const pendingResults = this.pendingResultConversationIds();
|
|
994
|
+
return structuredClone(this.state.conversations.filter((item) => item.workspaceId === workspaceId && !item.warmSession)).map((c) => {
|
|
995
|
+
const escalationAudience = openEscalations.get(c.id);
|
|
996
|
+
const hasPendingResult = pendingResults.has(c.id);
|
|
997
|
+
if (!escalationAudience && !hasPendingResult)
|
|
998
|
+
return c;
|
|
999
|
+
return {
|
|
1000
|
+
...c,
|
|
1001
|
+
...(escalationAudience ? { hasOpenEscalation: true, escalationAudience } : {}),
|
|
1002
|
+
...(hasPendingResult ? { hasPendingResult: true } : {}),
|
|
1003
|
+
};
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
async setModelFilterRules(rules) {
|
|
1007
|
+
if (!Array.isArray(rules) || rules.some(rule => !rule || typeof rule.id !== "string" || typeof rule.workspacePattern !== "string" || typeof rule.modelPattern !== "string" || (rule.label !== undefined && typeof rule.label !== "string")))
|
|
1008
|
+
throw new Error("模型过滤规则格式不合法");
|
|
1009
|
+
const previous = this.state.modelFilterRules;
|
|
1010
|
+
this.state.modelFilterRules = structuredClone(rules);
|
|
1011
|
+
try {
|
|
1012
|
+
await this.persist();
|
|
1013
|
+
}
|
|
1014
|
+
catch (error) {
|
|
1015
|
+
this.state.modelFilterRules = previous;
|
|
1016
|
+
throw error;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
/**
|
|
1020
|
+
* Sets (or clears) the app-wide default model.
|
|
1021
|
+
*
|
|
1022
|
+
* `undefined` DELETES the key, for the same reason the workspace defaults do it that way: "follow
|
|
1023
|
+
* Pi" has to be the ABSENCE of a value, not a frozen copy of whatever Pi's default was when the
|
|
1024
|
+
* setting was saved. A stored copy would keep answering with a model the user had already
|
|
1025
|
+
* removed, and Pi's own default may have changed underneath us in the meantime.
|
|
1026
|
+
*
|
|
1027
|
+
* The pair is written field by field, never as a spread, because the type declares exactly three
|
|
1028
|
+
* fields and a spread would quietly start persisting whatever is added to `ModelSelection` next.
|
|
1029
|
+
*/
|
|
1030
|
+
async setDefaultModel(model) {
|
|
1031
|
+
const previous = this.state.defaultModel;
|
|
1032
|
+
if (model === undefined)
|
|
1033
|
+
delete this.state.defaultModel;
|
|
1034
|
+
else
|
|
1035
|
+
this.state.defaultModel = { provider: model.provider, modelId: model.modelId, label: model.label };
|
|
1036
|
+
try {
|
|
1037
|
+
await this.persist();
|
|
1038
|
+
}
|
|
1039
|
+
catch (error) {
|
|
1040
|
+
this.state.defaultModel = previous;
|
|
1041
|
+
throw error;
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
async setTerminalShell(shell) {
|
|
1045
|
+
const previous = this.state.terminalShell;
|
|
1046
|
+
if (shell === undefined)
|
|
1047
|
+
delete this.state.terminalShell;
|
|
1048
|
+
else
|
|
1049
|
+
this.state.terminalShell = { file: shell.file, args: [...shell.args] };
|
|
1050
|
+
try {
|
|
1051
|
+
await this.persist();
|
|
1052
|
+
}
|
|
1053
|
+
catch (error) {
|
|
1054
|
+
this.state.terminalShell = previous;
|
|
1055
|
+
throw error;
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
snapshot() {
|
|
1059
|
+
const startedAt = process.env.SUPER_PI_TRACE_LATENCY === "1" ? performance.now() : 0;
|
|
1060
|
+
const value = structuredClone(this.state);
|
|
1061
|
+
const openEscalations = this.openEscalationConversationIds();
|
|
1062
|
+
const pendingResults = this.pendingResultConversationIds();
|
|
1063
|
+
for (const conv of value.conversations) {
|
|
1064
|
+
if (openEscalations.has(conv.id)) {
|
|
1065
|
+
conv.hasOpenEscalation = true;
|
|
1066
|
+
}
|
|
1067
|
+
if (pendingResults.has(conv.id)) {
|
|
1068
|
+
conv.hasPendingResult = true;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
// Do not stringify here just to count bytes: that makes tracing add a second full serialization
|
|
1072
|
+
// and mislabels that extra work as clone time. The broadcaster measures the actual JSON payload.
|
|
1073
|
+
if (startedAt)
|
|
1074
|
+
console.warn(`[super-pi latency] phase=state.snapshot cloneMs=${Math.round(performance.now() - startedAt)}`);
|
|
1075
|
+
return value;
|
|
1076
|
+
}
|
|
1077
|
+
/** Cheap scalar/entity reads for hot paths. Never expose the live mutable state object. */
|
|
1078
|
+
hasWorkspace(workspaceId) {
|
|
1079
|
+
return this.state.workspaces.some((workspace) => workspace.id === workspaceId);
|
|
1080
|
+
}
|
|
1081
|
+
searchConversationMessages(workspaceId, query) {
|
|
1082
|
+
const literal = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu");
|
|
1083
|
+
const sessions = this.state.conversations
|
|
1084
|
+
.filter(item => item.workspaceId === workspaceId && !item.archivedAt && !item.warmSession)
|
|
1085
|
+
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
1086
|
+
const hits = [];
|
|
1087
|
+
for (const session of sessions) {
|
|
1088
|
+
for (let index = session.messages.length - 1; index >= 0; index--) {
|
|
1089
|
+
const { id, content, role, delivery } = session.messages[index];
|
|
1090
|
+
if (delivery || (role !== "user" && role !== "assistant"))
|
|
1091
|
+
continue;
|
|
1092
|
+
const match = literal.exec(content);
|
|
1093
|
+
if (!match)
|
|
1094
|
+
continue;
|
|
1095
|
+
if (hits.length === SESSION_SEARCH_LIMIT)
|
|
1096
|
+
return { hits, truncated: true };
|
|
1097
|
+
const start = Math.max(0, match.index - 72);
|
|
1098
|
+
const endOfMatch = match.index + match[0].length;
|
|
1099
|
+
const end = Math.min(content.length, endOfMatch + 96);
|
|
1100
|
+
hits.push({
|
|
1101
|
+
conversationId: session.id, title: session.title, messageId: id, role,
|
|
1102
|
+
before: (start ? "…" : "") + content.slice(start, match.index),
|
|
1103
|
+
match: match[0],
|
|
1104
|
+
after: content.slice(endOfMatch, end) + (end < content.length ? "…" : ""),
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
return { hits, truncated: false };
|
|
1109
|
+
}
|
|
1110
|
+
conversationStatus(conversationId) {
|
|
1111
|
+
return this.state.conversations.find((conversation) => conversation.id === conversationId)?.status;
|
|
1112
|
+
}
|
|
1113
|
+
question(conversationId, messageId, index) {
|
|
1114
|
+
const question = this.state.conversations.find((conversation) => conversation.id === conversationId)
|
|
1115
|
+
?.messages.find((message) => message.id === messageId)?.toolCalls?.[index]?.question;
|
|
1116
|
+
return question ? structuredClone(question) : undefined;
|
|
1117
|
+
}
|
|
1118
|
+
pendingQuestion(conversationId) {
|
|
1119
|
+
const conversation = this.state.conversations.find((item) => item.id === conversationId);
|
|
1120
|
+
if (!conversation)
|
|
1121
|
+
return undefined;
|
|
1122
|
+
for (let messageIndex = conversation.messages.length - 1; messageIndex >= 0; messageIndex -= 1) {
|
|
1123
|
+
const message = conversation.messages[messageIndex];
|
|
1124
|
+
if (message.role !== "assistant")
|
|
1125
|
+
continue;
|
|
1126
|
+
for (let index = (message.toolCalls?.length ?? 0) - 1; index >= 0; index -= 1) {
|
|
1127
|
+
const question = message.toolCalls?.[index]?.question;
|
|
1128
|
+
if (message.toolCalls?.[index]?.label === "question" && question?.status === "pending") {
|
|
1129
|
+
return { messageId: message.id, index, question: structuredClone(question) };
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
return undefined;
|
|
1134
|
+
}
|
|
1135
|
+
/**
|
|
1136
|
+
* Whether a conversation already holds a message with this id.
|
|
1137
|
+
*
|
|
1138
|
+
* A LIVE read with no clone, because its one caller is the send path's duplicate check: a resend
|
|
1139
|
+
* that arrives within milliseconds of the original must be answered without paying for a full
|
|
1140
|
+
* copy of every conversation in the app. The answer is a boolean and the message is not handed
|
|
1141
|
+
* out, so nothing can mutate the store through it.
|
|
1142
|
+
*/
|
|
1143
|
+
hasMessage(conversationId, messageId) {
|
|
1144
|
+
return Boolean(this.state.conversations.find((item) => item.id === conversationId)?.messages.some((message) => message.id === messageId));
|
|
1145
|
+
}
|
|
1146
|
+
hasAcceptedSend(conversationId, clientId) {
|
|
1147
|
+
const conversation = this.state.conversations.find(item => item.id === conversationId);
|
|
1148
|
+
return Boolean(conversation?.acceptedSendIds?.includes(clientId) || conversation?.messages.some(message => message.id === clientId && message.role === "user"));
|
|
1149
|
+
}
|
|
1150
|
+
/**
|
|
1151
|
+
* One conversation and its workspace, as DETACHED copies, without cloning the whole state.
|
|
1152
|
+
*
|
|
1153
|
+
* The alternative - what the run path used to do - was two `snapshot()` calls, and `snapshot()`
|
|
1154
|
+
* deep-clones every conversation, every message and every tool result in the app. That is the
|
|
1155
|
+
* shape of the bug it fixes: reading one conversation's model cost O(entire state), and it sat on
|
|
1156
|
+
* the path between a click on 发送 and the frame that tells the browser a turn has started.
|
|
1157
|
+
*
|
|
1158
|
+
* The two objects are still CLONES, because every caller of this is allowed to keep them after the
|
|
1159
|
+
* store has moved on (a streamed turn holds its conversation for minutes), and handing out live
|
|
1160
|
+
* references would turn the first such caller into a corruption bug that only shows up under load.
|
|
1161
|
+
*/
|
|
1162
|
+
turnContext(conversationId) {
|
|
1163
|
+
const conversation = this.state.conversations.find((item) => item.id === conversationId);
|
|
1164
|
+
if (!conversation)
|
|
1165
|
+
return undefined;
|
|
1166
|
+
const workspace = this.state.workspaces.find((item) => item.id === conversation.workspaceId);
|
|
1167
|
+
if (!workspace)
|
|
1168
|
+
return undefined;
|
|
1169
|
+
return { conversation: structuredClone(conversation), workspace: structuredClone(workspace) };
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* THE PHYSICAL DIRECTORY IS THE WORKSPACE'S IDENTITY.
|
|
1173
|
+
*
|
|
1174
|
+
* A workspace is a folder, not a row in a table: two workspaces pointing at the same directory are
|
|
1175
|
+
* the same project, and the app used to mint a fresh UUID for each one. That is what broke
|
|
1176
|
+
* re-adding a workspace - the new id matched none of the conversations that belonged to that
|
|
1177
|
+
* directory, so the history was unreachable (and, before the soft unmount, actually deleted).
|
|
1178
|
+
*
|
|
1179
|
+
* So the same folder always means the same workspace id, and the id is what the conversations
|
|
1180
|
+
* point at.
|
|
1181
|
+
*/
|
|
1182
|
+
async createWorkspace(name, path, project) {
|
|
1183
|
+
const cleanName = name.trim();
|
|
1184
|
+
if (!cleanName || cleanName.length > 80)
|
|
1185
|
+
throw new Error("工作区名称需要 1-80 个字符。");
|
|
1186
|
+
const cleanPath = path?.trim() || process.cwd();
|
|
1187
|
+
if (cleanPath.length > 500)
|
|
1188
|
+
throw new Error("工作区路径太长了。");
|
|
1189
|
+
// THE SAME FOLDER IS THE SAME WORKSPACE. Adding a directory that is already here re-opens it
|
|
1190
|
+
// instead of forking a second one: the id stays, the conversations stay attached to it, and the
|
|
1191
|
+
// name is left alone (renaming is an explicit action elsewhere, and silently renaming a
|
|
1192
|
+
// workspace because someone typed a name into the add dialog would be its own surprise).
|
|
1193
|
+
const existing = this.state.workspaces.find((item) => workspacePathKey(item.path) === workspacePathKey(cleanPath));
|
|
1194
|
+
if (existing) {
|
|
1195
|
+
const open = Boolean(existing.closedAt);
|
|
1196
|
+
const attach = project && project.id !== existing.id && (existing.worktreeOf !== project.id || existing.worktreeProjectPath !== project.path);
|
|
1197
|
+
if (attach) {
|
|
1198
|
+
existing.worktreeOf = project.id;
|
|
1199
|
+
existing.worktreeProjectPath = project.path;
|
|
1200
|
+
}
|
|
1201
|
+
if (open || attach) {
|
|
1202
|
+
delete existing.closedAt;
|
|
1203
|
+
existing.updatedAt = now();
|
|
1204
|
+
await this.persist();
|
|
1205
|
+
}
|
|
1206
|
+
return structuredClone(existing);
|
|
1207
|
+
}
|
|
1208
|
+
const workspace = { id: id("workspace"), name: cleanName, path: cleanPath, updatedAt: now(), ...(project ? {
|
|
1209
|
+
worktreeOf: project.id, worktreeProjectPath: project.path, defaultModel: project.defaultModel,
|
|
1210
|
+
defaultThinkingLevel: project.defaultThinkingLevel, defaultAgentId: project.defaultAgentId,
|
|
1211
|
+
} : {}) };
|
|
1212
|
+
this.state.workspaces.push(workspace);
|
|
1213
|
+
await this.persist();
|
|
1214
|
+
return structuredClone(workspace);
|
|
1215
|
+
}
|
|
1216
|
+
async renameWorkspace(workspaceId, name) {
|
|
1217
|
+
const cleanName = name.trim();
|
|
1218
|
+
if (!cleanName || cleanName.length > 80)
|
|
1219
|
+
throw new Error("工作区名称需要 1-80 个字符。");
|
|
1220
|
+
const workspace = this.state.workspaces.find((item) => item.id === workspaceId);
|
|
1221
|
+
if (!workspace)
|
|
1222
|
+
throw new Error("找不到这个工作区。");
|
|
1223
|
+
workspace.name = cleanName;
|
|
1224
|
+
workspace.updatedAt = now();
|
|
1225
|
+
await this.persist();
|
|
1226
|
+
return structuredClone(workspace);
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* Replaces the workspace's two defaults. `undefined` DELETES the key rather than storing Pi's
|
|
1230
|
+
* default as this app's state - the same convention as setConversationThinking, and for the same
|
|
1231
|
+
* reason: "follow Pi" must be the absence of a value, not a frozen copy of whatever Pi's default
|
|
1232
|
+
* happened to be when the dialog was saved. Only conversations created AFTER this call ever see
|
|
1233
|
+
* the new values; existing ones are not migrated, by design.
|
|
1234
|
+
*/
|
|
1235
|
+
/**
|
|
1236
|
+
* Replaces the workspace's defaults. `model`/`thinkingLevel` are ALWAYS sent whole (null clears one of
|
|
1237
|
+
* them); `agentId` is tri-state, which is why it is not part of that pair: a string sets it, `null`
|
|
1238
|
+
* clears it, and `undefined` leaves it alone. Bundling a tri-state field into an "absent means delete"
|
|
1239
|
+
* pair would make any caller that only wanted to change the model silently drop the default agent.
|
|
1240
|
+
*
|
|
1241
|
+
* ONE persist for all three, deliberately. Two writes would publish an intermediate state - the pair
|
|
1242
|
+
* saved but not the agent - and the window between them is observable: a client that reopens the
|
|
1243
|
+
* settings dialog after seeing the first write on disk would mount from a broadcast that has not been
|
|
1244
|
+
* sent yet, and its draft would then be frozen at the stale value. One write, one broadcast, no window.
|
|
1245
|
+
*/
|
|
1246
|
+
async setWorkspaceDefaults(workspaceId, defaults) {
|
|
1247
|
+
const workspace = this.state.workspaces.find((item) => item.id === workspaceId);
|
|
1248
|
+
if (!workspace)
|
|
1249
|
+
throw new Error("找不到这个工作区。");
|
|
1250
|
+
if (defaults.model === undefined)
|
|
1251
|
+
delete workspace.defaultModel;
|
|
1252
|
+
else
|
|
1253
|
+
workspace.defaultModel = { provider: defaults.model.provider, modelId: defaults.model.modelId, label: defaults.model.label };
|
|
1254
|
+
if (defaults.thinkingLevel === undefined)
|
|
1255
|
+
delete workspace.defaultThinkingLevel;
|
|
1256
|
+
else
|
|
1257
|
+
workspace.defaultThinkingLevel = defaults.thinkingLevel;
|
|
1258
|
+
if (defaults.agentId === undefined) { /* absent: leave the default agent exactly as it is */ }
|
|
1259
|
+
else if (defaults.agentId === null)
|
|
1260
|
+
delete workspace.defaultAgentId;
|
|
1261
|
+
else
|
|
1262
|
+
workspace.defaultAgentId = defaults.agentId;
|
|
1263
|
+
workspace.updatedAt = now();
|
|
1264
|
+
await this.persist();
|
|
1265
|
+
return structuredClone(workspace);
|
|
1266
|
+
}
|
|
1267
|
+
/** Applies the shared model defaults to every mounted workspace and writes them together. */
|
|
1268
|
+
async setMountedWorkspaceDefaults(defaults) {
|
|
1269
|
+
const workspaces = this.state.workspaces.filter((workspace) => !workspace.closedAt);
|
|
1270
|
+
if (!workspaces.length)
|
|
1271
|
+
throw new Error("没有可更新的工作区。");
|
|
1272
|
+
const previous = workspaces.map((workspace) => ({
|
|
1273
|
+
workspace,
|
|
1274
|
+
defaultModel: workspace.defaultModel ? { ...workspace.defaultModel } : undefined,
|
|
1275
|
+
defaultThinkingLevel: workspace.defaultThinkingLevel,
|
|
1276
|
+
updatedAt: workspace.updatedAt,
|
|
1277
|
+
}));
|
|
1278
|
+
for (const workspace of workspaces) {
|
|
1279
|
+
if (defaults.model === undefined)
|
|
1280
|
+
delete workspace.defaultModel;
|
|
1281
|
+
else
|
|
1282
|
+
workspace.defaultModel = { ...defaults.model };
|
|
1283
|
+
if (defaults.thinkingLevel === undefined)
|
|
1284
|
+
delete workspace.defaultThinkingLevel;
|
|
1285
|
+
else
|
|
1286
|
+
workspace.defaultThinkingLevel = defaults.thinkingLevel;
|
|
1287
|
+
workspace.updatedAt = now();
|
|
1288
|
+
}
|
|
1289
|
+
try {
|
|
1290
|
+
await this.persist();
|
|
1291
|
+
}
|
|
1292
|
+
catch (error) {
|
|
1293
|
+
for (const saved of previous) {
|
|
1294
|
+
if (saved.defaultModel)
|
|
1295
|
+
saved.workspace.defaultModel = saved.defaultModel;
|
|
1296
|
+
else
|
|
1297
|
+
delete saved.workspace.defaultModel;
|
|
1298
|
+
if (saved.defaultThinkingLevel === undefined)
|
|
1299
|
+
delete saved.workspace.defaultThinkingLevel;
|
|
1300
|
+
else
|
|
1301
|
+
saved.workspace.defaultThinkingLevel = saved.defaultThinkingLevel;
|
|
1302
|
+
saved.workspace.updatedAt = saved.updatedAt;
|
|
1303
|
+
}
|
|
1304
|
+
throw error;
|
|
1305
|
+
}
|
|
1306
|
+
return workspaces.length;
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* TAKES A WORKSPACE OUT OF THE SIDEBAR. IT DOES NOT DELETE ANYTHING.
|
|
1310
|
+
*
|
|
1311
|
+
* This used to cascade: the workspace row AND every conversation that pointed at it were erased
|
|
1312
|
+
* from the state, in one persist. That made the most natural thing a user could do - remove a
|
|
1313
|
+
* workspace to tidy the sidebar, then add the same folder back - silently destroy the history of
|
|
1314
|
+
* that project, and there was no way to get it back.
|
|
1315
|
+
*
|
|
1316
|
+
* So the removal is a SOFT UNMOUNT, the same shape as a session's archive: the workspace row
|
|
1317
|
+
* stays (with `closedAt` on it), the conversations stay, the uploads stay, and nothing is
|
|
1318
|
+
* broadcast for either (see `clientState`). Adding the same folder again re-opens the very same
|
|
1319
|
+
* workspace - same id, same conversations - which is the whole point of the physical path being
|
|
1320
|
+
* the workspace's identity.
|
|
1321
|
+
*
|
|
1322
|
+
* The returned list is the conversations that were STOPPED, not deleted: a turn that was still
|
|
1323
|
+
* running under a workspace that just left the sidebar cannot keep burning a model session
|
|
1324
|
+
* behind the user's back, and a pending question would otherwise wait for an answer that the
|
|
1325
|
+
* sidebar can no longer reach.
|
|
1326
|
+
*/
|
|
1327
|
+
async deleteWorkspace(workspaceId) {
|
|
1328
|
+
const workspace = this.state.workspaces.find((item) => item.id === workspaceId);
|
|
1329
|
+
if (!workspace)
|
|
1330
|
+
throw new Error("找不到这个工作区。");
|
|
1331
|
+
if (workspace.closedAt)
|
|
1332
|
+
return [];
|
|
1333
|
+
workspace.closedAt = now();
|
|
1334
|
+
workspace.updatedAt = workspace.closedAt;
|
|
1335
|
+
await this.persist();
|
|
1336
|
+
return [];
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* THE STATE THE CLIENT IS ALLOWED TO SEE.
|
|
1340
|
+
*
|
|
1341
|
+
* `snapshot()` is the truth of what the store HOLDS; this is the truth of what is ON SCREEN. The
|
|
1342
|
+
* difference is the closed workspaces: one that was removed from the sidebar is still in the store
|
|
1343
|
+
* - that is exactly why re-adding the folder brings its history back - but it is not part of the
|
|
1344
|
+
* app any more, so neither it nor its conversations are broadcast.
|
|
1345
|
+
*
|
|
1346
|
+
* Filtering HERE, in one place, rather than in every reader, is what keeps the client dumb: the
|
|
1347
|
+
* sidebar renders `state.workspaces` and never has to know that a closed workspace exists.
|
|
1348
|
+
*/
|
|
1349
|
+
clientState(scope) {
|
|
1350
|
+
const { projects: _projects, ...publicState } = this.state;
|
|
1351
|
+
const closed = new Set(this.state.workspaces.filter((item) => item.closedAt).map((item) => item.id));
|
|
1352
|
+
const workspaces = this.state.workspaces.filter((item) => !closed.has(item.id));
|
|
1353
|
+
const visible = this.state.conversations.filter((item) => !closed.has(item.workspaceId) && !item.warmSession)
|
|
1354
|
+
.map(({ acceptedSendIds: _accepted, accountedPiUsageEntries: _piUsage, ...conversation }) => conversation);
|
|
1355
|
+
const warmSessions = workspaces.flatMap((workspace) => this.listWarmSessions(workspace.id));
|
|
1356
|
+
const presets = warmSessions.length ? { warmSessions } : {};
|
|
1357
|
+
const openEscalations = this.openEscalationAudiences();
|
|
1358
|
+
const pendingResults = this.pendingResultConversationIds();
|
|
1359
|
+
/* The projects themselves are not broadcast, but the archive confirmation needs to know
|
|
1360
|
+
「how many decisions does this archive throw away」. The server counts them; the client
|
|
1361
|
+
only adds them up - the predicate lives in `src/shared/archive-decisions.ts` and both ends
|
|
1362
|
+
call it. */
|
|
1363
|
+
const pendingDecisions = pendingUserDecisionsByOwner(this.state.projects ?? []);
|
|
1364
|
+
const pendingDecisionsField = Object.keys(pendingDecisions).length ? { pendingUserDecisionsByConversation: pendingDecisions } : {};
|
|
1365
|
+
// Legacy sockets still receive complete visible transcripts. Project before cloning so a closed
|
|
1366
|
+
// workspace's retained history is never copied just to discard it afterwards.
|
|
1367
|
+
if (scope === undefined) {
|
|
1368
|
+
return structuredClone({
|
|
1369
|
+
...publicState,
|
|
1370
|
+
...presets,
|
|
1371
|
+
...pendingDecisionsField,
|
|
1372
|
+
workspaces,
|
|
1373
|
+
conversations: visible.map((c) => {
|
|
1374
|
+
const escalationAudience = openEscalations.get(c.id);
|
|
1375
|
+
const hasPendingResult = pendingResults.has(c.id);
|
|
1376
|
+
if (!escalationAudience && !hasPendingResult)
|
|
1377
|
+
return c;
|
|
1378
|
+
return {
|
|
1379
|
+
...c,
|
|
1380
|
+
...(escalationAudience ? { hasOpenEscalation: true, escalationAudience } : {}),
|
|
1381
|
+
...(hasPendingResult ? { hasPendingResult: true } : {}),
|
|
1382
|
+
};
|
|
1383
|
+
}),
|
|
1384
|
+
serverTimeZone: serverTimeZone(),
|
|
1385
|
+
});
|
|
1386
|
+
}
|
|
1387
|
+
// A focused socket keeps every sidebar row, but owns only the selected transcript. An empty scope
|
|
1388
|
+
// deliberately loads none; a missing/closed selection must not expose retained workspace history.
|
|
1389
|
+
const selectedId = visible.find((item) => item.id === scope.conversationId)?.id;
|
|
1390
|
+
const conversations = visible.map(({ messages, ...metadata }) => ({
|
|
1391
|
+
...metadata,
|
|
1392
|
+
...(openEscalations.has(metadata.id)
|
|
1393
|
+
? { hasOpenEscalation: true, escalationAudience: openEscalations.get(metadata.id) }
|
|
1394
|
+
: {}),
|
|
1395
|
+
...(pendingResults.has(metadata.id) ? { hasPendingResult: true } : {}),
|
|
1396
|
+
messages: metadata.id === selectedId ? messages : [],
|
|
1397
|
+
messagesLoaded: metadata.id === selectedId,
|
|
1398
|
+
hasPendingQuestion: messages.some((message) => message.toolCalls?.some((call) => call.question?.status === "pending")),
|
|
1399
|
+
}));
|
|
1400
|
+
return structuredClone({
|
|
1401
|
+
...publicState,
|
|
1402
|
+
...presets,
|
|
1403
|
+
...pendingDecisionsField,
|
|
1404
|
+
workspaces,
|
|
1405
|
+
conversations,
|
|
1406
|
+
// THE CLOCK THE SERVER SCHEDULES BY, NAMED. The scheduled-task panel renders 「每天 09:00」 and
|
|
1407
|
+
// 「下次」 from two different sources - a configured string and an epoch millisecond - and a
|
|
1408
|
+
// browser on another machine renders the epoch in ITS timezone. Without this field the two
|
|
1409
|
+
// lines in one row mean two different wall clocks and nothing says so.
|
|
1410
|
+
serverTimeZone: serverTimeZone(),
|
|
1411
|
+
subagentRuns: this.state.subagentRuns.filter((run) => run.conversationId === selectedId),
|
|
1412
|
+
...(this.state.workflows ? { workflows: this.state.workflows.filter((run) => run.conversationId === selectedId) } : {}),
|
|
1413
|
+
...(this.state.todosByConversation ? { todosByConversation: selectedId && this.state.todosByConversation[selectedId]
|
|
1414
|
+
? { [selectedId]: this.state.todosByConversation[selectedId] } : {} } : {}),
|
|
1415
|
+
});
|
|
1416
|
+
}
|
|
1417
|
+
async createConversation(workspaceId, configuration) {
|
|
1418
|
+
const workspace = this.state.workspaces.find((item) => item.id === workspaceId);
|
|
1419
|
+
if (!workspace)
|
|
1420
|
+
throw new Error("找不到这个工作区。");
|
|
1421
|
+
const conversation = { id: id("conversation"), title: DEFAULT_CONVERSATION_TITLE, workspaceId, updatedAt: now(), status: "idle", messages: [] };
|
|
1422
|
+
// INHERITANCE, AS A COPY AT BIRTH. The workspace's defaults are stamped onto the new conversation
|
|
1423
|
+
// here and never consulted again: the session picker edits the conversation's own fields, so an
|
|
1424
|
+
// existing conversation is untouched by later workspace settings, and a workspace edit never
|
|
1425
|
+
// rewrites history. Field by field, never a spread, for the same reason setConversationModel
|
|
1426
|
+
// narrows: every inherited field has an explicit birth override, including null for Pi's default.
|
|
1427
|
+
if (workspace.defaultModel)
|
|
1428
|
+
conversation.model = { provider: workspace.defaultModel.provider, modelId: workspace.defaultModel.modelId, label: workspace.defaultModel.label };
|
|
1429
|
+
if (workspace.defaultThinkingLevel)
|
|
1430
|
+
conversation.thinkingLevel = workspace.defaultThinkingLevel;
|
|
1431
|
+
if (workspace.defaultAgentId)
|
|
1432
|
+
conversation.agentId = workspace.defaultAgentId;
|
|
1433
|
+
if (configuration) {
|
|
1434
|
+
// WHY THIS CONVERSATION IS NOT ON THE MODEL THE USER SET. Set once, at birth, and never
|
|
1435
|
+
// rewritten: it describes how this conversation came to be, not what is true right now.
|
|
1436
|
+
if (configuration.modelNotice !== undefined)
|
|
1437
|
+
conversation.modelNotice = configuration.modelNotice;
|
|
1438
|
+
if (configuration.agentNotice !== undefined)
|
|
1439
|
+
conversation.agentNotice = configuration.agentNotice;
|
|
1440
|
+
if (configuration.model !== undefined) {
|
|
1441
|
+
if (configuration.model)
|
|
1442
|
+
conversation.model = { ...configuration.model };
|
|
1443
|
+
else
|
|
1444
|
+
delete conversation.model;
|
|
1445
|
+
}
|
|
1446
|
+
if (configuration.thinkingLevel !== undefined) {
|
|
1447
|
+
if (configuration.thinkingLevel)
|
|
1448
|
+
conversation.thinkingLevel = configuration.thinkingLevel;
|
|
1449
|
+
else
|
|
1450
|
+
delete conversation.thinkingLevel;
|
|
1451
|
+
}
|
|
1452
|
+
if (configuration.agentId !== undefined) {
|
|
1453
|
+
if (configuration.agentId)
|
|
1454
|
+
conversation.agentId = configuration.agentId;
|
|
1455
|
+
else
|
|
1456
|
+
delete conversation.agentId;
|
|
1457
|
+
}
|
|
1458
|
+
// THE SESSION TREE'S EDGE, WRITTEN AT BIRTH. Both fields describe how this conversation CAME TO
|
|
1459
|
+
// BE, exactly like modelNotice above, so they are set once here and never rewritten: the tree
|
|
1460
|
+
// the sidebar draws after a restart is the tree that was true when each session was opened.
|
|
1461
|
+
// Written only when present, so a conversation created without them (the user's own "+") reads
|
|
1462
|
+
// as a top-level one on every code path, including every state.json from before this field.
|
|
1463
|
+
if (configuration.cwd)
|
|
1464
|
+
conversation.cwd = configuration.cwd;
|
|
1465
|
+
if (configuration.parentConversationId)
|
|
1466
|
+
conversation.parentConversationId = configuration.parentConversationId;
|
|
1467
|
+
if (configuration.origin)
|
|
1468
|
+
conversation.origin = configuration.origin;
|
|
1469
|
+
}
|
|
1470
|
+
try {
|
|
1471
|
+
// A PROJECT OPENS ITS OWN MEMORY TREE. Inheriting the parent's tree would put the project's
|
|
1472
|
+
// workers in the user's chat tree, where the tree-scoped memories of that conversation are
|
|
1473
|
+
// visible to them - a project is its own working context. The tree edge in the sidebar is a
|
|
1474
|
+
// different thing and stays exactly as it is.
|
|
1475
|
+
if (configuration?.separateMemoryTree)
|
|
1476
|
+
conversation.treeId = conversation.id;
|
|
1477
|
+
else
|
|
1478
|
+
conversation.treeId = memoryTreeId(conversation, this.state.conversations);
|
|
1479
|
+
}
|
|
1480
|
+
catch { /* Keep malformed legacy edges inspectable; memory authorization fails closed. */ }
|
|
1481
|
+
this.state.conversations.unshift(conversation);
|
|
1482
|
+
await this.persist();
|
|
1483
|
+
return structuredClone(conversation);
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* Records (or clears) one conversation as collapsed in the sidebar's session tree. The list is a
|
|
1487
|
+
* SET in array clothing - order means nothing, duplicates must not accumulate - and it follows the
|
|
1488
|
+
* assign -> persist -> rollback pattern `setTerminalShell` established: the in-memory value is the
|
|
1489
|
+
* previous value again the moment persistence fails, so a rejected write can never leave the
|
|
1490
|
+
* screen and the disk disagreeing.
|
|
1491
|
+
*/
|
|
1492
|
+
async setConversationCollapsed(conversationId, collapsed) {
|
|
1493
|
+
const previous = this.state.collapsedConversationIds;
|
|
1494
|
+
const next = new Set(previous ?? []);
|
|
1495
|
+
if (collapsed)
|
|
1496
|
+
next.add(conversationId);
|
|
1497
|
+
else
|
|
1498
|
+
next.delete(conversationId);
|
|
1499
|
+
if (next.size === 0)
|
|
1500
|
+
delete this.state.collapsedConversationIds;
|
|
1501
|
+
else
|
|
1502
|
+
this.state.collapsedConversationIds = [...next];
|
|
1503
|
+
try {
|
|
1504
|
+
await this.persist();
|
|
1505
|
+
}
|
|
1506
|
+
catch (error) {
|
|
1507
|
+
if (previous === undefined)
|
|
1508
|
+
delete this.state.collapsedConversationIds;
|
|
1509
|
+
else
|
|
1510
|
+
this.state.collapsedConversationIds = previous;
|
|
1511
|
+
throw error;
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* Whether the reader has opened one child session's composer.
|
|
1516
|
+
*
|
|
1517
|
+
* THE SERVER OWNS THIS FACT. The browser keeps a copy per conversation (so the choice survives a
|
|
1518
|
+
* reload), but the copy is a mirror: what the server says is what happens. A browser that owned
|
|
1519
|
+
* it could unlock a session the server still refuses, and the reader would be told 「发送失败」
|
|
1520
|
+
* for a message that was never allowed to be sent.
|
|
1521
|
+
*/
|
|
1522
|
+
childLockUnlocked(conversationId) {
|
|
1523
|
+
return Boolean(this.state.unlockedChildConversationIds?.includes(conversationId));
|
|
1524
|
+
}
|
|
1525
|
+
listWarmSessions(workspaceId) {
|
|
1526
|
+
return this.state.conversations.filter((item) => item.warmSession && item.workspaceId === workspaceId)
|
|
1527
|
+
.map(({ id, title, workspaceId, cwd, archivedAt, updatedAt }) => ({ id, title, workspaceId, cwd, savedAt: archivedAt ?? updatedAt }));
|
|
1528
|
+
}
|
|
1529
|
+
isWarmSession(conversationId) {
|
|
1530
|
+
return this.state.conversations.some((item) => item.id === conversationId && item.warmSession);
|
|
1531
|
+
}
|
|
1532
|
+
/**
|
|
1533
|
+
* Opens (or re-closes) one child session's composer, and persists it.
|
|
1534
|
+
*
|
|
1535
|
+
* The assign -> persist -> rollback pattern `setConversationCollapsed` established: the in-memory
|
|
1536
|
+
* value is the previous value again the moment persistence fails, so a rejected write can never
|
|
1537
|
+
* leave the screen and the disk disagreeing about whether the door is open.
|
|
1538
|
+
*/
|
|
1539
|
+
async setChildLockUnlocked(conversationId, unlocked) {
|
|
1540
|
+
const previous = this.state.unlockedChildConversationIds;
|
|
1541
|
+
const next = new Set(previous ?? []);
|
|
1542
|
+
if (unlocked)
|
|
1543
|
+
next.add(conversationId);
|
|
1544
|
+
else
|
|
1545
|
+
next.delete(conversationId);
|
|
1546
|
+
if (next.size === 0)
|
|
1547
|
+
delete this.state.unlockedChildConversationIds;
|
|
1548
|
+
else
|
|
1549
|
+
this.state.unlockedChildConversationIds = [...next];
|
|
1550
|
+
try {
|
|
1551
|
+
await this.persist();
|
|
1552
|
+
}
|
|
1553
|
+
catch (error) {
|
|
1554
|
+
if (previous === undefined)
|
|
1555
|
+
delete this.state.unlockedChildConversationIds;
|
|
1556
|
+
else
|
|
1557
|
+
this.state.unlockedChildConversationIds = previous;
|
|
1558
|
+
throw error;
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* THE CHILD-SESSION FACTS OF ONE CONVERSATION: its own parent edge, and the parent's row.
|
|
1563
|
+
*
|
|
1564
|
+
* Narrow on purpose: the send path asks this on EVERY message, and `store.conversation()` clones
|
|
1565
|
+
* the whole transcript - a long conversation would pay for its entire history to answer one
|
|
1566
|
+
* yes/no question. Two rows, read in place, and nothing copied.
|
|
1567
|
+
*/
|
|
1568
|
+
childSessionFacts(conversationId) {
|
|
1569
|
+
const conversation = this.state.conversations.find((item) => item.id === conversationId);
|
|
1570
|
+
const parentConversationId = conversation?.parentConversationId;
|
|
1571
|
+
if (!parentConversationId)
|
|
1572
|
+
return {};
|
|
1573
|
+
const parent = this.state.conversations.find((item) => item.id === parentConversationId);
|
|
1574
|
+
return { parentConversationId, ...(parent ? { parent: { id: parent.id, archivedAt: parent.archivedAt } } : {}) };
|
|
1575
|
+
}
|
|
1576
|
+
/**
|
|
1577
|
+
* Copies a conversation into a NEW one, under an id the caller has already minted.
|
|
1578
|
+
*
|
|
1579
|
+
* THE ID IS A PARAMETER, and that is the whole reason this method does not simply mint one: the caller had
|
|
1580
|
+
* to write Pi's copied transcript under that id first (see `ForkRequest.forkedConversationId`), so by the
|
|
1581
|
+
* time this runs the id is already the one on disk. Minting here as well would produce a conversation whose
|
|
1582
|
+
* Pi file belongs to a different, nonexistent conversation - the exact "Pi opens an empty session and the
|
|
1583
|
+
* history has vanished with no error anywhere" failure probe B was about.
|
|
1584
|
+
*
|
|
1585
|
+
* WHAT IS COPIED, FIELD BY FIELD AND NEVER BY A SPREAD, for the same reason `createConversation` writes out
|
|
1586
|
+
* three fields individually: the type declares exactly these, so a spread would quietly start persisting
|
|
1587
|
+
* whatever the next person adds to `Conversation`. The workspace, the model, the thinking level and the
|
|
1588
|
+
* agent are all copied, because a fork that came back on a different model or with no role would not be
|
|
1589
|
+
* the conversation the user forked.
|
|
1590
|
+
*
|
|
1591
|
+
* `title` is copied VERBATIM, unchanged. Not a reason, not a suffix: the fork IS this conversation, and
|
|
1592
|
+
* inventing a name is a product decision the request did not delegate. Renaming it is one click and always
|
|
1593
|
+
* available, which is better than a label nobody chose.
|
|
1594
|
+
*
|
|
1595
|
+
* MESSAGES ARE COPIED WITH FRESH `id`s AND THE ORIGINAL `piEntryId`s. Both halves matter:
|
|
1596
|
+
*
|
|
1597
|
+
* - Fresh ids, because `Message.id` is this store's own handle (`beginAssistantMessage`,
|
|
1598
|
+
* `appendToolCall` and `appendAssistantDelta` all find a message by it) and a forked conversation that
|
|
1599
|
+
* answered to its source's ids would be one object wearing two names. Fork the same conversation twice
|
|
1600
|
+
* and the two copies are distinct records.
|
|
1601
|
+
* - The ORIGINAL `piEntryId`, because that is the whole reason the fork is a fork. Pi's copied file is
|
|
1602
|
+
* byte-identical apart from two header fields (see `forkSessionFile`), so the source's entry ids are
|
|
1603
|
+
* present and valid in the fork - and a copied message keeps the ability to be a REVERT boundary in the
|
|
1604
|
+
* conversation it was copied into. Dropping the ids would produce a fork whose history cannot be
|
|
1605
|
+
* reverted at all, which is a silent loss of a feature rather than an honest absence.
|
|
1606
|
+
*
|
|
1607
|
+
* `status` is `"idle"` unconditionally, even when the source is running, because the caller refuses a
|
|
1608
|
+
* running source outright (`runtime.fork`) and a conversation that has never run a turn must not be born
|
|
1609
|
+
* claiming to be in one. `error` is NOT copied: it describes a run, and this conversation has had none.
|
|
1610
|
+
*
|
|
1611
|
+
* NOT COPIED, and both omissions are deliberate and both are the same judgement - they belong to a RUN,
|
|
1612
|
+
* and no run was copied: `subagentRuns` are filtered by `conversationId`, so a run dispatched by the source
|
|
1613
|
+
* stays with the source; a run dispatched by the FORK will be filed under the fork's own id and work as
|
|
1614
|
+
* usual. `queuedMessages` likewise, for the same reason (research pitfall 7): a message waiting for a turn
|
|
1615
|
+
* that was never copied must not be re-sent into a different conversation.
|
|
1616
|
+
*
|
|
1617
|
+
* POSITION IS NOT CHOSEN HERE. `unshift` plus the client rendering the sidebar by `updatedAt`
|
|
1618
|
+
* (`byRecency`) puts a fork at the TOP of its workspace group, because `updatedAt` is now - which is the
|
|
1619
|
+
* same position a newly created conversation takes, and the same reason.
|
|
1620
|
+
*/
|
|
1621
|
+
async forkConversation(sourceConversationId, forkedConversationId, options = {}) {
|
|
1622
|
+
const source = this.requireConversation(sourceConversationId);
|
|
1623
|
+
if (source.id === forkedConversationId)
|
|
1624
|
+
throw new Error("Cannot fork a conversation into itself");
|
|
1625
|
+
const parent = options.parentConversationId ? this.requireConversation(options.parentConversationId) : undefined;
|
|
1626
|
+
if (parent && (parent.workspaceId !== source.workspaceId || parent.archivedAt || (!source.warmSession && source.parentConversationId !== parent.id))) {
|
|
1627
|
+
throw new Error("分叉会话必须与来源保留同一个直属上级和工作区");
|
|
1628
|
+
}
|
|
1629
|
+
const conversation = {
|
|
1630
|
+
id: forkedConversationId,
|
|
1631
|
+
treeId: parent ? memoryTreeId(source.warmSession ? parent : source, this.state.conversations) : forkedConversationId,
|
|
1632
|
+
...(parent ? { parentConversationId: parent.id, origin: "orchestrator" } : {}),
|
|
1633
|
+
...(options.warmTitle ? { warmSession: true, archivedAt: now() } : {}),
|
|
1634
|
+
...(options.piSessionFile ? { piSessionFile: options.piSessionFile } : {}),
|
|
1635
|
+
...(options.inheritedUsageEntryIds?.length ? { accountedPiUsageEntries: [...new Set(options.inheritedUsageEntryIds)] } : {}),
|
|
1636
|
+
title: options.warmTitle ?? source.title,
|
|
1637
|
+
workspaceId: source.workspaceId,
|
|
1638
|
+
updatedAt: now(),
|
|
1639
|
+
status: "idle",
|
|
1640
|
+
// A WAITING MESSAGE IS NOT COPIED, and this filter is why the fork still answers "no queued
|
|
1641
|
+
// messages" after the waiting list stopped being a list of its own. Forking is refused while a turn
|
|
1642
|
+
// is running, but a conversation can still be holding messages that were sent during that run and
|
|
1643
|
+
// have not been started; they belong to the run that is in progress and to nothing else. Copying them
|
|
1644
|
+
// would put words in the fork's transcript that Pi's session file - which the fork copies separately -
|
|
1645
|
+
// has no record of, so the two halves of the new conversation would disagree from its first turn.
|
|
1646
|
+
messages: structuredClone(source.messages)
|
|
1647
|
+
.filter((message) => !message.delivery)
|
|
1648
|
+
.map((message) => ({ ...message, id: id("message") })),
|
|
1649
|
+
};
|
|
1650
|
+
if (source.model)
|
|
1651
|
+
conversation.model = { provider: source.model.provider, modelId: source.model.modelId, label: source.model.label };
|
|
1652
|
+
if (source.thinkingLevel)
|
|
1653
|
+
conversation.thinkingLevel = source.thinkingLevel;
|
|
1654
|
+
if (source.agentId)
|
|
1655
|
+
conversation.agentId = source.agentId;
|
|
1656
|
+
if (source.cwd)
|
|
1657
|
+
conversation.cwd = source.cwd;
|
|
1658
|
+
this.state.conversations.unshift(conversation);
|
|
1659
|
+
try {
|
|
1660
|
+
await this.persist();
|
|
1661
|
+
}
|
|
1662
|
+
catch (error) {
|
|
1663
|
+
this.state.conversations = this.state.conversations.filter((item) => item.id !== conversation.id);
|
|
1664
|
+
throw error;
|
|
1665
|
+
}
|
|
1666
|
+
return structuredClone(conversation);
|
|
1667
|
+
}
|
|
1668
|
+
/**
|
|
1669
|
+
* Archive is a marker, not a move: the conversation keeps its id, workspace, messages and position.
|
|
1670
|
+
* `updatedAt` is deliberately NOT touched, because it drives the sidebar's live timestamp and recency -
|
|
1671
|
+
* bumping it would teleport the row to the top of the list the instant it was archived.
|
|
1672
|
+
*
|
|
1673
|
+
* A running conversation is rejected rather than archived. An archived conversation cannot be opened,
|
|
1674
|
+
* so allowing one would leave a run streaming into a pane the user can no longer reach, along with any
|
|
1675
|
+
* Extension UI question it is blocked on. Refusing keeps the rule honest and leaves stop-then-archive
|
|
1676
|
+
* to the user, which is a visible choice instead of a silent one.
|
|
1677
|
+
*/
|
|
1678
|
+
async archiveConversation(conversationId) {
|
|
1679
|
+
const conversation = this.requireConversation(conversationId);
|
|
1680
|
+
if (conversation.archivedAt)
|
|
1681
|
+
return;
|
|
1682
|
+
if (conversation.status === "running" || conversation.status === "awaiting_background")
|
|
1683
|
+
throw new Error("运行中的会话无法归档,请先停止运行");
|
|
1684
|
+
conversation.archivedAt = now();
|
|
1685
|
+
await this.persistMetadata(conversationId);
|
|
1686
|
+
}
|
|
1687
|
+
/** Restoring deletes the key rather than setting it to null, so a fully restored conversation serializes
|
|
1688
|
+
* byte-identically to one that was never archived. `delete` is legal here because the field is optional. */
|
|
1689
|
+
async unarchiveConversation(conversationId) {
|
|
1690
|
+
const conversation = this.requireConversation(conversationId);
|
|
1691
|
+
if (conversation.warmSession)
|
|
1692
|
+
throw new Error("预热快照只能通过项目派发使用");
|
|
1693
|
+
if (!conversation.archivedAt)
|
|
1694
|
+
return;
|
|
1695
|
+
delete conversation.archivedAt;
|
|
1696
|
+
await this.persistMetadata(conversationId);
|
|
1697
|
+
}
|
|
1698
|
+
/**
|
|
1699
|
+
* Archives one whole tree as one state write. Only a conversation with no existing parent may
|
|
1700
|
+
* start it; an archived parent is still a parent, so its active descendants cannot be archived
|
|
1701
|
+
* independently. All running checks happen before the first mutation, making rejection all-or-none.
|
|
1702
|
+
*/
|
|
1703
|
+
async archiveConversationTree(conversationId) {
|
|
1704
|
+
const root = this.requireConversation(conversationId);
|
|
1705
|
+
if (root.parentConversationId && this.state.conversations.some(item => item.id === root.parentConversationId)) {
|
|
1706
|
+
throw new Error("子会话不能独立归档,请从根会话归档整棵树");
|
|
1707
|
+
}
|
|
1708
|
+
if (root.archivedAt)
|
|
1709
|
+
return;
|
|
1710
|
+
const active = this.conversationSubtree(root).filter(item => !item.archivedAt);
|
|
1711
|
+
const running = active.find(item => item.status === "running");
|
|
1712
|
+
if (running)
|
|
1713
|
+
throw new Error(`会话「${running.title}」正在运行,无法归档整棵树,请先停止运行`);
|
|
1714
|
+
const archivedAt = now();
|
|
1715
|
+
for (const conversation of active)
|
|
1716
|
+
conversation.archivedAt = archivedAt;
|
|
1717
|
+
await this.persist();
|
|
1718
|
+
}
|
|
1719
|
+
/** Restores one archived tree in one write; active descendants are already restored by definition. */
|
|
1720
|
+
async unarchiveConversationTree(conversationId) {
|
|
1721
|
+
const root = this.requireConversation(conversationId);
|
|
1722
|
+
if (root.warmSession)
|
|
1723
|
+
throw new Error("预热快照只能通过项目派发使用");
|
|
1724
|
+
const parent = root.parentConversationId
|
|
1725
|
+
? this.state.conversations.find(item => item.id === root.parentConversationId)
|
|
1726
|
+
: undefined;
|
|
1727
|
+
if (parent?.archivedAt)
|
|
1728
|
+
throw new Error("归档树中的子会话不能独立恢复,请从归档树的根会话恢复整棵树");
|
|
1729
|
+
if (!root.archivedAt)
|
|
1730
|
+
return;
|
|
1731
|
+
const archived = this.conversationSubtree(root).filter(item => item.archivedAt);
|
|
1732
|
+
for (const conversation of archived)
|
|
1733
|
+
delete conversation.archivedAt;
|
|
1734
|
+
await this.persist();
|
|
1735
|
+
}
|
|
1736
|
+
/**
|
|
1737
|
+
* Lists the conversation IDs in a session's subtree (root first, pre-order).
|
|
1738
|
+
* Returns `[]` when the conversation does not exist.
|
|
1739
|
+
*/
|
|
1740
|
+
conversationSubtreeIds(conversationId) {
|
|
1741
|
+
const root = this.state.conversations.find((item) => item.id === conversationId);
|
|
1742
|
+
if (!root)
|
|
1743
|
+
return [];
|
|
1744
|
+
return this.conversationSubtree(root).map((item) => item.id);
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* Permanently destroys a child conversation and its entire descendant subtree along with all
|
|
1748
|
+
* conversation-scoped store records (messages, tool calls, sub-agent runs, background tasks,
|
|
1749
|
+
* workflows, todos, UI locks/collapse markers, and open escalations raised by the destroyed
|
|
1750
|
+
* sessions). Refuses top-level sessions and refuses if any session in the subtree is running.
|
|
1751
|
+
*/
|
|
1752
|
+
async deleteConversationSubtree(conversationId) {
|
|
1753
|
+
const root = this.state.conversations.find((item) => item.id === conversationId);
|
|
1754
|
+
if (!root)
|
|
1755
|
+
return { destroyed: [] };
|
|
1756
|
+
if (!root.parentConversationId && !root.warmSession) {
|
|
1757
|
+
throw new Error("顶层会话不能销毁,只能由用户归档。");
|
|
1758
|
+
}
|
|
1759
|
+
const subtree = this.conversationSubtree(root);
|
|
1760
|
+
const running = subtree.find((item) => item.status === "running" || item.status === "awaiting_background");
|
|
1761
|
+
if (running) {
|
|
1762
|
+
throw new Error(`会话「${running.title}」仍在运行,无法销毁,请先停止运行。`);
|
|
1763
|
+
}
|
|
1764
|
+
const destroyed = subtree.map((item) => ({
|
|
1765
|
+
id: item.id,
|
|
1766
|
+
title: item.title,
|
|
1767
|
+
workspaceId: item.workspaceId,
|
|
1768
|
+
...(item.piSessionFile ? { piSessionFile: item.piSessionFile } : {}),
|
|
1769
|
+
messageIds: item.messages.map((message) => message.id),
|
|
1770
|
+
}));
|
|
1771
|
+
const destroyedIds = new Set(destroyed.map((item) => item.id));
|
|
1772
|
+
const previousConversations = this.state.conversations;
|
|
1773
|
+
const previousSubagentRuns = this.state.subagentRuns;
|
|
1774
|
+
const previousBackgroundTasks = this.state.backgroundTasks;
|
|
1775
|
+
const previousTodos = this.state.todosByConversation;
|
|
1776
|
+
const previousWorkflows = this.state.workflows;
|
|
1777
|
+
const previousScheduledTasks = this.state.scheduledTasks;
|
|
1778
|
+
const previousCollapsed = this.state.collapsedConversationIds;
|
|
1779
|
+
const previousUnlocked = this.state.unlockedChildConversationIds;
|
|
1780
|
+
const previousProjects = this.state.projects;
|
|
1781
|
+
this.state.conversations = this.state.conversations.filter((item) => !destroyedIds.has(item.id));
|
|
1782
|
+
this.state.subagentRuns = this.state.subagentRuns.filter((run) => !destroyedIds.has(run.conversationId));
|
|
1783
|
+
this.state.backgroundTasks = this.state.backgroundTasks.filter((task) => !destroyedIds.has(task.conversationId));
|
|
1784
|
+
if (this.state.todosByConversation) {
|
|
1785
|
+
const nextTodos = { ...this.state.todosByConversation };
|
|
1786
|
+
for (const id of destroyedIds)
|
|
1787
|
+
delete nextTodos[id];
|
|
1788
|
+
if (Object.keys(nextTodos).length === 0)
|
|
1789
|
+
delete this.state.todosByConversation;
|
|
1790
|
+
else
|
|
1791
|
+
this.state.todosByConversation = nextTodos;
|
|
1792
|
+
}
|
|
1793
|
+
if (this.state.workflows) {
|
|
1794
|
+
const nextWorkflows = this.state.workflows.filter((workflow) => !workflow?.conversationId || !destroyedIds.has(workflow.conversationId));
|
|
1795
|
+
if (nextWorkflows.length === 0)
|
|
1796
|
+
delete this.state.workflows;
|
|
1797
|
+
else
|
|
1798
|
+
this.state.workflows = nextWorkflows;
|
|
1799
|
+
}
|
|
1800
|
+
if (this.state.scheduledTasks) {
|
|
1801
|
+
this.state.scheduledTasks = this.state.scheduledTasks.map((task) => {
|
|
1802
|
+
if (!task?.conversationId || !destroyedIds.has(task.conversationId))
|
|
1803
|
+
return task;
|
|
1804
|
+
const copy = { ...task };
|
|
1805
|
+
delete copy.conversationId;
|
|
1806
|
+
return copy;
|
|
1807
|
+
});
|
|
1808
|
+
}
|
|
1809
|
+
if (this.state.collapsedConversationIds) {
|
|
1810
|
+
const nextCollapsed = this.state.collapsedConversationIds.filter((id) => !destroyedIds.has(id));
|
|
1811
|
+
if (nextCollapsed.length === 0)
|
|
1812
|
+
delete this.state.collapsedConversationIds;
|
|
1813
|
+
else
|
|
1814
|
+
this.state.collapsedConversationIds = nextCollapsed;
|
|
1815
|
+
}
|
|
1816
|
+
if (this.state.unlockedChildConversationIds) {
|
|
1817
|
+
const nextUnlocked = this.state.unlockedChildConversationIds.filter((id) => !destroyedIds.has(id));
|
|
1818
|
+
if (nextUnlocked.length === 0)
|
|
1819
|
+
delete this.state.unlockedChildConversationIds;
|
|
1820
|
+
else
|
|
1821
|
+
this.state.unlockedChildConversationIds = nextUnlocked;
|
|
1822
|
+
}
|
|
1823
|
+
if (this.state.projects) {
|
|
1824
|
+
this.state.projects = this.state.projects.map((project) => {
|
|
1825
|
+
if (!project.escalations?.length)
|
|
1826
|
+
return project;
|
|
1827
|
+
const nextEscalations = project.escalations.filter((escalation) => {
|
|
1828
|
+
const isOpen = escalation.status === "open" || escalation.status === "pending";
|
|
1829
|
+
if (!isOpen)
|
|
1830
|
+
return true;
|
|
1831
|
+
const requestedByDestroyed = Boolean(escalation.requestedByConversationId && destroyedIds.has(escalation.requestedByConversationId));
|
|
1832
|
+
const targetsDestroyed = Boolean(escalation.targetConversationId && destroyedIds.has(escalation.targetConversationId));
|
|
1833
|
+
return !requestedByDestroyed && !targetsDestroyed;
|
|
1834
|
+
});
|
|
1835
|
+
if (nextEscalations.length === project.escalations.length)
|
|
1836
|
+
return project;
|
|
1837
|
+
return { ...project, escalations: nextEscalations };
|
|
1838
|
+
});
|
|
1839
|
+
}
|
|
1840
|
+
try {
|
|
1841
|
+
await this.persist();
|
|
1842
|
+
}
|
|
1843
|
+
catch (error) {
|
|
1844
|
+
this.state.conversations = previousConversations;
|
|
1845
|
+
this.state.subagentRuns = previousSubagentRuns;
|
|
1846
|
+
this.state.backgroundTasks = previousBackgroundTasks;
|
|
1847
|
+
if (previousTodos === undefined)
|
|
1848
|
+
delete this.state.todosByConversation;
|
|
1849
|
+
else
|
|
1850
|
+
this.state.todosByConversation = previousTodos;
|
|
1851
|
+
if (previousWorkflows === undefined)
|
|
1852
|
+
delete this.state.workflows;
|
|
1853
|
+
else
|
|
1854
|
+
this.state.workflows = previousWorkflows;
|
|
1855
|
+
if (previousScheduledTasks === undefined)
|
|
1856
|
+
delete this.state.scheduledTasks;
|
|
1857
|
+
else
|
|
1858
|
+
this.state.scheduledTasks = previousScheduledTasks;
|
|
1859
|
+
if (previousCollapsed === undefined)
|
|
1860
|
+
delete this.state.collapsedConversationIds;
|
|
1861
|
+
else
|
|
1862
|
+
this.state.collapsedConversationIds = previousCollapsed;
|
|
1863
|
+
if (previousUnlocked === undefined)
|
|
1864
|
+
delete this.state.unlockedChildConversationIds;
|
|
1865
|
+
else
|
|
1866
|
+
this.state.unlockedChildConversationIds = previousUnlocked;
|
|
1867
|
+
if (previousProjects === undefined)
|
|
1868
|
+
delete this.state.projects;
|
|
1869
|
+
else
|
|
1870
|
+
this.state.projects = previousProjects;
|
|
1871
|
+
throw error;
|
|
1872
|
+
}
|
|
1873
|
+
return { destroyed };
|
|
1874
|
+
}
|
|
1875
|
+
/** Pre-order traversal with cycle protection; archived nodes are traversed, not treated as leaves. */
|
|
1876
|
+
conversationSubtree(root) {
|
|
1877
|
+
const byParent = new Map();
|
|
1878
|
+
for (const conversation of this.state.conversations) {
|
|
1879
|
+
if (conversation.workspaceId !== root.workspaceId || !conversation.parentConversationId)
|
|
1880
|
+
continue;
|
|
1881
|
+
const siblings = byParent.get(conversation.parentConversationId);
|
|
1882
|
+
if (siblings)
|
|
1883
|
+
siblings.push(conversation);
|
|
1884
|
+
else
|
|
1885
|
+
byParent.set(conversation.parentConversationId, [conversation]);
|
|
1886
|
+
}
|
|
1887
|
+
const result = [];
|
|
1888
|
+
const visited = new Set();
|
|
1889
|
+
const walk = (conversation) => {
|
|
1890
|
+
if (visited.has(conversation.id))
|
|
1891
|
+
return;
|
|
1892
|
+
visited.add(conversation.id);
|
|
1893
|
+
result.push(conversation);
|
|
1894
|
+
for (const child of byParent.get(conversation.id) ?? [])
|
|
1895
|
+
walk(child);
|
|
1896
|
+
};
|
|
1897
|
+
walk(root);
|
|
1898
|
+
return result;
|
|
1899
|
+
}
|
|
1900
|
+
/**
|
|
1901
|
+
* Rename edits the title and NOTHING else. In particular `updatedAt` is deliberately not touched,
|
|
1902
|
+
* for exactly the reason archive is: `updatedAt` is the sidebar's recency key, so bumping it would
|
|
1903
|
+
* teleport the row to the top of the live list because someone retitled it. Renaming is not activity.
|
|
1904
|
+
*
|
|
1905
|
+
* There is no uniqueness check, and there is no status check on purpose. `createWorkspace` does not
|
|
1906
|
+
* reject a duplicate name either, so rejecting one here would make the two paths disagree about the
|
|
1907
|
+
* same question; two rows reading "notes" is a cosmetic problem the user can see and fix. And a
|
|
1908
|
+
* RUNNING conversation stays renameable: the title is display-only, the run is unaffected, and
|
|
1909
|
+
* refusing would mean a conversation could be permanently un-renameable while the agent works.
|
|
1910
|
+
*
|
|
1911
|
+
* Archived conversations are renameable too - archiving folds a row away, it does not delete it, and
|
|
1912
|
+
* the Archived group renders the same name.
|
|
1913
|
+
*/
|
|
1914
|
+
async renameConversation(conversationId, name) {
|
|
1915
|
+
const cleanName = name.trim();
|
|
1916
|
+
if (!cleanName || cleanName.length > 80)
|
|
1917
|
+
throw new Error("会话名称需要 1-80 个字符。");
|
|
1918
|
+
const conversation = this.requireConversation(conversationId);
|
|
1919
|
+
conversation.title = cleanName;
|
|
1920
|
+
conversation.titleLocked = true;
|
|
1921
|
+
await this.persistMetadata(conversationId);
|
|
1922
|
+
return structuredClone(conversation);
|
|
1923
|
+
}
|
|
1924
|
+
async followConversationWorktree(conversationId, worktreeId) {
|
|
1925
|
+
const conversation = this.requireConversation(conversationId);
|
|
1926
|
+
if (conversation.followedWorktreeId === worktreeId)
|
|
1927
|
+
return;
|
|
1928
|
+
conversation.followedWorktreeId = worktreeId;
|
|
1929
|
+
await this.persistMetadata(conversationId);
|
|
1930
|
+
}
|
|
1931
|
+
/**
|
|
1932
|
+
* Writes ONE user message into the transcript - the single place a user utterance comes into being.
|
|
1933
|
+
*
|
|
1934
|
+
* Two callers exist and they differ only in `delivery`, because whether a send starts a turn or waits
|
|
1935
|
+
* for one is decided by the RUN GUARD in `run-service`, not here. This method records the words and,
|
|
1936
|
+
* if they are waiting, records that they are waiting. Deciding anything about turns would put a second,
|
|
1937
|
+
* contradictory answer next to the guard's.
|
|
1938
|
+
*
|
|
1939
|
+
* `clientId` is the browser's own id for the message it has already drawn. When it is well formed and
|
|
1940
|
+
* not already taken, the message IS that id - which is what lets the optimistic bubble and the stored
|
|
1941
|
+
* message be the same object rather than two that have to be matched up by content afterwards. A
|
|
1942
|
+
* collision falls back to a minted id rather than throwing: the browser is asking for its words to be
|
|
1943
|
+
* kept, and refusing the whole send because an id was already in use would lose them.
|
|
1944
|
+
*
|
|
1945
|
+
* `delivery: "waiting"` ALSO SKIPS EVERY SIDE EFFECT BELOW - no `running`, no title, no `updatedAt`,
|
|
1946
|
+
* no clearing of a failure reason. Those all describe a turn, and a message waiting for one has not
|
|
1947
|
+
* started anything. It is why a conversation holding only waiting messages still reads as idle in the
|
|
1948
|
+
* sidebar, and why the title comes from the first message that was actually asked rather than from
|
|
1949
|
+
* whatever was typed into a box that was not listening yet. `openTurnOnMessage` applies them at the
|
|
1950
|
+
* moment a turn genuinely begins.
|
|
1951
|
+
*/
|
|
1952
|
+
/**
|
|
1953
|
+
* Writes ONE INSTRUCTION INTO THE TRANSCRIPT AS SOMETHING THE SYSTEM SAID.
|
|
1954
|
+
*
|
|
1955
|
+
* `addUserMessage` above is the only way a person's words come into being, and everything written
|
|
1956
|
+
* through it wears the reader's own name and the reader's bubble. That is right for a person and
|
|
1957
|
+
* wrong for the orchestrator: when a primary agent dispatches a task to a child session, the
|
|
1958
|
+
* child receives an ORDER, not something the reader typed - and the child transcript showed it
|
|
1959
|
+
* under the reader's avatar, so the reader saw their own name on an instruction they never wrote.
|
|
1960
|
+
*
|
|
1961
|
+
* The role is `tool` for a reason that is not cosmetic: `tool` is already the product's word for
|
|
1962
|
+
* "the system delivered this", it renders as the 系统 side of the transcript rather than as a
|
|
1963
|
+
* person, and Pi's queue already knows how to hand a `tool` message to a model (see
|
|
1964
|
+
* `composePrompt` in the run service). So the instruction reaches the model the same way, and the
|
|
1965
|
+
* reader sees who spoke.
|
|
1966
|
+
*/
|
|
1967
|
+
async addAgentMessage(conversationId, content, options) {
|
|
1968
|
+
const conversation = this.requireConversation(conversationId);
|
|
1969
|
+
if (conversation.archivedAt)
|
|
1970
|
+
throw new Error("无法向已归档的会话下发指令,请先恢复该会话");
|
|
1971
|
+
const message = { id: id("message"), role: "tool", content, createdAt: now() };
|
|
1972
|
+
if (options?.source)
|
|
1973
|
+
message.source = options.source;
|
|
1974
|
+
if (options?.delivery)
|
|
1975
|
+
message.delivery = options.delivery;
|
|
1976
|
+
conversation.messages.push(message);
|
|
1977
|
+
if (message.source === "session-reminder" && !message.delivery)
|
|
1978
|
+
await this.persistIncomingTurn(conversation, message);
|
|
1979
|
+
else
|
|
1980
|
+
await this.persistMessages(conversation);
|
|
1981
|
+
return structuredClone(message);
|
|
1982
|
+
}
|
|
1983
|
+
async addUserMessage(conversationId, content, images, attachments, options) {
|
|
1984
|
+
const conversation = this.requireConversation(conversationId);
|
|
1985
|
+
// The browser cannot reach an archived conversation, so this guard exists for any other caller -
|
|
1986
|
+
// a direct WebSocket client, or a future code path. Archiving is the promise that a conversation is
|
|
1987
|
+
// closed, and a closed conversation must not accept a new turn.
|
|
1988
|
+
if (conversation.archivedAt)
|
|
1989
|
+
throw new Error("无法向已归档的会话发送消息,请先恢复该会话");
|
|
1990
|
+
const message = { id: this.claimClientMessageId(conversation, options?.clientId), role: "user", content, createdAt: now() };
|
|
1991
|
+
if (images && images.length > 0)
|
|
1992
|
+
message.images = structuredClone(images);
|
|
1993
|
+
if (attachments && attachments.length > 0)
|
|
1994
|
+
message.attachments = structuredClone(attachments);
|
|
1995
|
+
if (options?.delivery)
|
|
1996
|
+
message.delivery = options.delivery;
|
|
1997
|
+
conversation.messages.push(message);
|
|
1998
|
+
// Persisted as a transcript change and nothing more: this is the honest record of "the user said this
|
|
1999
|
+
// and nothing has picked it up yet", and a refresh has to show it in the same place it was sent from.
|
|
2000
|
+
const acceptedSendId = options?.clientId === message.id ? message.id : undefined;
|
|
2001
|
+
const previousMetadata = !message.delivery && acceptedSendId
|
|
2002
|
+
? { title: conversation.title, updatedAt: conversation.updatedAt, status: conversation.status, error: conversation.error, warning: conversation.warning }
|
|
2003
|
+
: undefined;
|
|
2004
|
+
if (acceptedSendId)
|
|
2005
|
+
(conversation.acceptedSendIds ??= []).push(acceptedSendId);
|
|
2006
|
+
try {
|
|
2007
|
+
if (message.delivery)
|
|
2008
|
+
await this.persistMessages(conversation, acceptedSendId);
|
|
2009
|
+
else
|
|
2010
|
+
await this.persistIncomingTurn(conversation, message, acceptedSendId);
|
|
2011
|
+
}
|
|
2012
|
+
catch (error) {
|
|
2013
|
+
if (acceptedSendId) {
|
|
2014
|
+
conversation.messages = conversation.messages.filter(item => item !== message);
|
|
2015
|
+
conversation.acceptedSendIds = conversation.acceptedSendIds?.filter(id => id !== acceptedSendId);
|
|
2016
|
+
if (previousMetadata && conversation.updatedAt === message.createdAt && conversation.status === "waiting")
|
|
2017
|
+
Object.assign(conversation, previousMetadata);
|
|
2018
|
+
}
|
|
2019
|
+
throw error;
|
|
2020
|
+
}
|
|
2021
|
+
return structuredClone(message);
|
|
2022
|
+
}
|
|
2023
|
+
async persistIncomingTurn(conversation, message, acceptedSendId) {
|
|
2024
|
+
const firstUser = conversation.messages.find((item) => item.role === "user");
|
|
2025
|
+
const autoTitle = firstUser?.content.trim()
|
|
2026
|
+
? firstUser.content.slice(0, 42)
|
|
2027
|
+
: (firstUser?.images?.length ? "【图片】" : DEFAULT_CONVERSATION_TITLE);
|
|
2028
|
+
if (!conversation.titleLocked)
|
|
2029
|
+
conversation.title = autoTitle || DEFAULT_CONVERSATION_TITLE;
|
|
2030
|
+
// A TURN STARTS IN `waiting`, NOT `running`. The first delta from the model is what flips the
|
|
2031
|
+
// conversation to `running` (see `RunService.streamTurn`); opening a turn only proves a prompt was
|
|
2032
|
+
// sent, and a prompt that was sent but never answered looks identical to one that is mid-stream
|
|
2033
|
+
// until something tells them apart. Holding the gap open is what makes a stuck LLM endpoint
|
|
2034
|
+
// visible to a person - the `waiting` mark on the sidebar row is the only honest signal.
|
|
2035
|
+
conversation.updatedAt = message.createdAt;
|
|
2036
|
+
conversation.status = "waiting";
|
|
2037
|
+
// The reason this conversation was failed - startup reconciliation's note that a previous run was cut
|
|
2038
|
+
// short - describes THAT run, and this line is the moment it stops being the current one. Deleting the
|
|
2039
|
+
// key rather than overwriting it keeps the file byte-identical to a conversation that was never
|
|
2040
|
+
// reconciled, and it is deleted here rather than at settle because the reason is wrong from the instant
|
|
2041
|
+
// the new turn starts: leaving it up would show "was interrupted, marked failed" above a conversation
|
|
2042
|
+
// that is visibly working again.
|
|
2043
|
+
delete conversation.error;
|
|
2044
|
+
// THE SAME IS TRUE OF THE TRUNCATION WARNING. It describes the answer that was cut short, and a
|
|
2045
|
+
// new turn is the reader answering that situation - so the notice belongs to the turn that just
|
|
2046
|
+
// ended, not to the conversation from now on.
|
|
2047
|
+
delete conversation.warning;
|
|
2048
|
+
// AN INCREMENTAL WRITE, NOT A FULL ONE. This line was the last full-state write on the hot path
|
|
2049
|
+
// of every message, and it was in front of the broadcast that tells the browser a turn has
|
|
2050
|
+
// started - so the size of the WHOLE state was the delay between clicking send and the stream
|
|
2051
|
+
// tail saying 「等待 LLM 返回」. Measured: a full write of a 12MB state costs 62ms on a fast
|
|
2052
|
+
// machine and seconds on a slow one, while the incremental write stays at 5ms regardless.
|
|
2053
|
+
//
|
|
2054
|
+
// The conversation's metadata (status, title, updatedAt) and its messages are exactly what
|
|
2055
|
+
// changed, and the repository has an incremental path for each. The base snapshot every other
|
|
2056
|
+
// conversation lives in is untouched by this call, so rewriting it buys nothing.
|
|
2057
|
+
const { messages: _messages, acceptedSendIds: _receipts, ...metadata } = conversation;
|
|
2058
|
+
await this.persistMessages(conversation, acceptedSendId, acceptedSendId ? metadata : undefined);
|
|
2059
|
+
if (!acceptedSendId)
|
|
2060
|
+
await this.persistMetadata(conversation.id);
|
|
2061
|
+
}
|
|
2062
|
+
/**
|
|
2063
|
+
* Takes the browser's id for its own optimistic message, when it is safe to.
|
|
2064
|
+
*
|
|
2065
|
+
* A client that names an id already in this conversation gets a minted one instead: two messages sharing
|
|
2066
|
+
* an id would break `updateToolCall`, `revertMessage` and every per-message write that follows, so
|
|
2067
|
+
* uniqueness within the conversation is worth more than the client getting its own id back in that case.
|
|
2068
|
+
* The `message_` prefix is required so a folded legacy id (which is `q_`-prefixed) can never be adopted.
|
|
2069
|
+
*/
|
|
2070
|
+
claimClientMessageId(conversation, clientId) {
|
|
2071
|
+
const usable = typeof clientId === "string" && /^message_[0-9a-f-]{36}$/.test(clientId);
|
|
2072
|
+
if (usable && !conversation.messages.some((message) => message.id === clientId))
|
|
2073
|
+
return clientId;
|
|
2074
|
+
return id("message");
|
|
2075
|
+
}
|
|
2076
|
+
/**
|
|
2077
|
+
* Appends one background-result message to a conversation. The render column is the same as before
|
|
2078
|
+
* (a `role: "tool"` row, never impersonating a user bubble) - what this method now ALSO supports is
|
|
2079
|
+
* putting the message straight into the dock by passing `delivery: "waiting"`, which is what exec and
|
|
2080
|
+
* sub-agent background completions do once a 后台回传 is treated as a queue item with steer priority
|
|
2081
|
+
* rather than a one-way notice the model never gets to read.
|
|
2082
|
+
*
|
|
2083
|
+
* NO `turnContext` claim, NO `status: "running"`. The message sits in the transcript; with a delivery
|
|
2084
|
+
* state it also enters `waitingMessages` and `runConversationTurns` will pick it up next.
|
|
2085
|
+
*/
|
|
2086
|
+
async addToolMessage(conversationId, content, options) {
|
|
2087
|
+
const conversation = this.requireConversation(conversationId);
|
|
2088
|
+
if (conversation.archivedAt)
|
|
2089
|
+
throw new Error("无法向已归档的会话追加后台回传,请先恢复该会话");
|
|
2090
|
+
const message = {
|
|
2091
|
+
id: id("message"),
|
|
2092
|
+
role: "tool",
|
|
2093
|
+
content,
|
|
2094
|
+
createdAt: now(),
|
|
2095
|
+
...(options?.delivery ? { delivery: options.delivery } : {}),
|
|
2096
|
+
};
|
|
2097
|
+
conversation.messages.push(message);
|
|
2098
|
+
if (options?.prioritizeWaiting && message.delivery === "waiting") {
|
|
2099
|
+
const waiting = this.waitingMessages(conversation);
|
|
2100
|
+
const lastSending = waiting.reduce((last, item, index) => item.delivery === "sending" ? index : last, -1);
|
|
2101
|
+
this.moveWaitingMessage(conversation, waiting, waiting.length - 1, lastSending + 1);
|
|
2102
|
+
}
|
|
2103
|
+
conversation.updatedAt = message.createdAt;
|
|
2104
|
+
await this.persist();
|
|
2105
|
+
return structuredClone(message);
|
|
2106
|
+
}
|
|
2107
|
+
/**
|
|
2108
|
+
* Records the model a conversation runs on. `updatedAt` is deliberately NOT touched, for the same
|
|
2109
|
+
* reason rename does not touch it: it is the sidebar's recency key, and switching model is not
|
|
2110
|
+
* activity in the conversation. No status check either - changing the model of a RUNNING
|
|
2111
|
+
* conversation is allowed, because the selection is read at the START of the next turn, so the
|
|
2112
|
+
* turn in flight is unaffected and refusing would strand a conversation on a model the user can
|
|
2113
|
+
* no longer change until it settles.
|
|
2114
|
+
*/
|
|
2115
|
+
async setConversationModel(conversationId, model) {
|
|
2116
|
+
const conversation = this.requireConversation(conversationId);
|
|
2117
|
+
// Built field by field, NEVER `{ ...model }`. A spread copies whatever it is handed, and the
|
|
2118
|
+
// caller in index.ts has a full `ModelOption` in hand (Pi's `detail`, `reasoning`,
|
|
2119
|
+
// `contextWindow` and `imageInput`), so a spread persisted every one of them into a field this
|
|
2120
|
+
// type declares as three: the declared shape would be a lie about the bytes on disk, and anything
|
|
2121
|
+
// reasoning from the type would be reasoning about a file that does not have that shape.
|
|
2122
|
+
//
|
|
2123
|
+
// Pi's capability metadata belongs to the CATALOG, which re-reads it from Pi on every fetch and
|
|
2124
|
+
// therefore cannot go stale. A copy frozen into a conversation would be wrong the moment Pi
|
|
2125
|
+
// changed a model, and nothing anywhere reads it: `sessionCommands` sends only provider and
|
|
2126
|
+
// modelId, and the client renders each option's detail from the catalog list rather than from
|
|
2127
|
+
// the stored selection. Narrowing is free and makes the type true.
|
|
2128
|
+
//
|
|
2129
|
+
// The field count is deliberately not written down here. It changed when `imageInput` landed, and
|
|
2130
|
+
// a comment naming the old number would have kept saying six while the object carried seven -
|
|
2131
|
+
// which is the exact failure this whole note is about, one level up. scripts/session-picker.test.mjs
|
|
2132
|
+
// pins the real key set instead, and re-breaks whenever a field is added.
|
|
2133
|
+
conversation.model = { provider: model.provider, modelId: model.modelId, label: model.label };
|
|
2134
|
+
await this.persistMetadata(conversationId);
|
|
2135
|
+
return structuredClone(conversation);
|
|
2136
|
+
}
|
|
2137
|
+
/**
|
|
2138
|
+
* Forgets the model a conversation runs on, so it follows Pi's own default again.
|
|
2139
|
+
*
|
|
2140
|
+
* FOR A MODEL THAT NO LONGER EXISTS. A conversation's model is copied at birth and never re-read
|
|
2141
|
+
* from the workspace - but the copied model can be removed from Pi, and leaving the field pointing
|
|
2142
|
+
* at it is worse than clearing it: Pi does not fail such a turn, it runs it on its own default, so
|
|
2143
|
+
* the picker names one model while another one answers. `undefined` DELETES the key rather than
|
|
2144
|
+
* storing "Pi's default" as this app's state, the same as `setConversationThinking` above.
|
|
2145
|
+
*
|
|
2146
|
+
* THE THINKING LEVEL GOES WITH IT. A level is a property of a model (`max` on a model with one
|
|
2147
|
+
* level means something different from `max` on another), so a level left behind by a model that
|
|
2148
|
+
* is gone describes nothing.
|
|
2149
|
+
*/
|
|
2150
|
+
async clearConversationModel(conversationId) {
|
|
2151
|
+
const conversation = this.requireConversation(conversationId);
|
|
2152
|
+
delete conversation.model;
|
|
2153
|
+
delete conversation.thinkingLevel;
|
|
2154
|
+
await this.persistMetadata(conversationId);
|
|
2155
|
+
return structuredClone(conversation);
|
|
2156
|
+
}
|
|
2157
|
+
/** Restoring Pi's own default deletes the key rather than storing Pi's default as this app's state. */
|
|
2158
|
+
async setConversationThinking(conversationId, level) {
|
|
2159
|
+
const conversation = this.requireConversation(conversationId);
|
|
2160
|
+
if (level === undefined)
|
|
2161
|
+
delete conversation.thinkingLevel;
|
|
2162
|
+
else
|
|
2163
|
+
conversation.thinkingLevel = level;
|
|
2164
|
+
await this.persistMetadata(conversationId);
|
|
2165
|
+
return structuredClone(conversation);
|
|
2166
|
+
}
|
|
2167
|
+
/**
|
|
2168
|
+
* Records the agent a conversation runs as. Same three rules as `setConversationModel`: `undefined`
|
|
2169
|
+
* DELETES the key rather than freezing "no agent" as a value, `updatedAt` is untouched because
|
|
2170
|
+
* changing role is not activity in the conversation, and no status check - the agent is read at the
|
|
2171
|
+
* START of the next turn, so the turn in flight is unaffected.
|
|
2172
|
+
*/
|
|
2173
|
+
async setConversationAgent(conversationId, agentId) {
|
|
2174
|
+
const conversation = this.requireConversation(conversationId);
|
|
2175
|
+
if (agentId === undefined)
|
|
2176
|
+
delete conversation.agentId;
|
|
2177
|
+
else
|
|
2178
|
+
conversation.agentId = agentId;
|
|
2179
|
+
await this.persistMetadata(conversationId);
|
|
2180
|
+
return structuredClone(conversation);
|
|
2181
|
+
}
|
|
2182
|
+
async setConversationConfiguration(conversationId, settings) {
|
|
2183
|
+
const conversation = this.requireConversation(conversationId);
|
|
2184
|
+
const previous = { agentId: conversation.agentId, model: conversation.model, thinkingLevel: conversation.thinkingLevel };
|
|
2185
|
+
const apply = (value) => {
|
|
2186
|
+
if (value.agentId === undefined)
|
|
2187
|
+
delete conversation.agentId;
|
|
2188
|
+
else
|
|
2189
|
+
conversation.agentId = value.agentId;
|
|
2190
|
+
if (value.model === undefined)
|
|
2191
|
+
delete conversation.model;
|
|
2192
|
+
else
|
|
2193
|
+
conversation.model = { provider: value.model.provider, modelId: value.model.modelId, label: value.model.label };
|
|
2194
|
+
if (value.thinkingLevel === undefined)
|
|
2195
|
+
delete conversation.thinkingLevel;
|
|
2196
|
+
else
|
|
2197
|
+
conversation.thinkingLevel = value.thinkingLevel;
|
|
2198
|
+
};
|
|
2199
|
+
apply(settings);
|
|
2200
|
+
try {
|
|
2201
|
+
await this.persist();
|
|
2202
|
+
}
|
|
2203
|
+
catch (error) {
|
|
2204
|
+
apply(previous);
|
|
2205
|
+
throw error;
|
|
2206
|
+
}
|
|
2207
|
+
return structuredClone(conversation);
|
|
2208
|
+
}
|
|
2209
|
+
async beginAssistantMessage(conversationId, agentIdentity) { const conversation = this.requireConversation(conversationId); const message = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) }; conversation.messages.push(message); await this.persist(); return structuredClone(message); }
|
|
2210
|
+
/**
|
|
2211
|
+
* Applies a streamed delta to the authoritative in-memory transcript without touching disk.
|
|
2212
|
+
*
|
|
2213
|
+
* The runtime must be able to drain Pi and publish the token before a disk transaction finishes.
|
|
2214
|
+
* `checkpointMessage` below makes the same object durable on a bounded cadence and at turn boundaries.
|
|
2215
|
+
*/
|
|
2216
|
+
appendAssistantDeltaLive(conversationId, messageId, delta) {
|
|
2217
|
+
const conversation = this.requireConversation(conversationId);
|
|
2218
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2219
|
+
if (!message)
|
|
2220
|
+
throw new Error("找不到对应的助手消息。");
|
|
2221
|
+
message.content += delta;
|
|
2222
|
+
conversation.updatedAt = now();
|
|
2223
|
+
}
|
|
2224
|
+
async appendAssistantDelta(conversationId, messageId, delta) {
|
|
2225
|
+
this.appendAssistantDeltaLive(conversationId, messageId, delta);
|
|
2226
|
+
await this.checkpointMessage(conversationId, messageId);
|
|
2227
|
+
}
|
|
2228
|
+
/**
|
|
2229
|
+
* THE MODEL'S REASONING, APPENDED TO THE MESSAGE IT BELONGS TO.
|
|
2230
|
+
*
|
|
2231
|
+
* It used to be broadcast and nothing more: the server emitted `message.thinking` on every delta and no
|
|
2232
|
+
* code anywhere read it, so the reasoning reached no one - not the screen while it streamed, and not
|
|
2233
|
+
* the transcript afterwards. The field, the event and the stylesheet were all already there; the two
|
|
2234
|
+
* halves that would have used them were missing, which is why a finished turn had no visible reasoning
|
|
2235
|
+
* to go back to. Persisting here rather than only in the browser is the point of its living on the
|
|
2236
|
+
* message: a reasoning stream that vanishes on reload was never a record of anything.
|
|
2237
|
+
*/
|
|
2238
|
+
appendThinkingDeltaLive(conversationId, messageId, delta, at, newBlock = false) {
|
|
2239
|
+
const conversation = this.requireConversation(conversationId);
|
|
2240
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2241
|
+
if (!message)
|
|
2242
|
+
throw new Error("找不到对应的助手消息。");
|
|
2243
|
+
message.thinking = `${message.thinking ?? ""}${delta}`;
|
|
2244
|
+
const blocks = (message.thinkingBlocks ??= []);
|
|
2245
|
+
// WHERE THE FRAGMENT BELONGS. The offset is where the block sits in the answer, and every block
|
|
2246
|
+
// keeps the offset it opened with, so the offset is what says which block a fragment continues.
|
|
2247
|
+
//
|
|
2248
|
+
// THE LAST SUCH BLOCK, because that is the one that was open. Two blocks can share an offset -
|
|
2249
|
+
// the answer does not move while a tool call happens, so the reasoning that comes back after the
|
|
2250
|
+
// call opens a second block at the same place - and the earlier of the two is a stretch of
|
|
2251
|
+
// reasoning the model has already left. The browser files the same fragment under the block the
|
|
2252
|
+
// server names, so the two sides have to pick the same one.
|
|
2253
|
+
const at0 = at ?? message.content.length;
|
|
2254
|
+
let same = -1;
|
|
2255
|
+
for (let index = blocks.length - 1; index >= 0; index -= 1)
|
|
2256
|
+
if (blocks[index].at === at0) {
|
|
2257
|
+
same = index;
|
|
2258
|
+
break;
|
|
2259
|
+
}
|
|
2260
|
+
if (!newBlock && same >= 0)
|
|
2261
|
+
blocks[same].text += delta;
|
|
2262
|
+
else
|
|
2263
|
+
blocks.push({ at: at0, text: delta });
|
|
2264
|
+
conversation.updatedAt = now();
|
|
2265
|
+
}
|
|
2266
|
+
setThinkingActiveLive(conversationId, messageId, active) {
|
|
2267
|
+
const message = this.requireConversation(conversationId).messages.find((item) => item.id === messageId);
|
|
2268
|
+
if (message)
|
|
2269
|
+
message.thinkingActive = active;
|
|
2270
|
+
}
|
|
2271
|
+
async appendThinkingDelta(conversationId, messageId, delta) {
|
|
2272
|
+
this.appendThinkingDeltaLive(conversationId, messageId, delta);
|
|
2273
|
+
await this.checkpointMessage(conversationId, messageId);
|
|
2274
|
+
}
|
|
2275
|
+
/** Persists the message exactly as it stands now, including any live text, thinking and tool updates. */
|
|
2276
|
+
async checkpointMessage(conversationId, messageId) {
|
|
2277
|
+
const conversation = this.requireConversation(conversationId);
|
|
2278
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2279
|
+
if (!message)
|
|
2280
|
+
throw new Error("找不到对应的助手消息。");
|
|
2281
|
+
await this.persistTransaction({ kind: "message.replace", conversationId, message: structuredClone(message), updatedAt: conversation.updatedAt });
|
|
2282
|
+
}
|
|
2283
|
+
/**
|
|
2284
|
+
* Appends one tool call to the message it belongs to, and returns the message's whole `toolCalls`
|
|
2285
|
+
* array so the caller can broadcast it as one snapshot.
|
|
2286
|
+
*
|
|
2287
|
+
* WHY AN APPEND AND NOT AN UPDATE, and why the returned array is the whole truth. A turn's calls arrive
|
|
2288
|
+
* one at a time and each one REWRITES a field on a row it has already broadcast - `status` and
|
|
2289
|
+
* `durationMs` land on `tool_execution_end`, minutes or seconds after the row was published by
|
|
2290
|
+
* `tool_execution_start`. So the only thing that can be cheap and correct is: the store owns the array,
|
|
2291
|
+
* the caller sends the array. Handing back the array rather than the one row is what stops the two from
|
|
2292
|
+
* drifting - the caller has nothing to merge, so there is no merge to get wrong, and the event it sends
|
|
2293
|
+
* is the same shape `state` carries on the next broadcast.
|
|
2294
|
+
*
|
|
2295
|
+
* PERSISTED ON EVERY CALL, for the same reason `appendAssistantDelta` is: a block that was on screen
|
|
2296
|
+
* when the browser reloaded has to come back, and a reload that showed a `read` but not the `bash` that
|
|
2297
|
+
* followed it would be worse than showing neither.
|
|
2298
|
+
*
|
|
2299
|
+
* `toolCalls` is CREATED LAZILY, so a message whose turn used no tools stores no empty array - which is
|
|
2300
|
+
* what makes a `state.json` written before call blocks existed read as "this turn used no tools"
|
|
2301
|
+
* instead of as a field it does not understand.
|
|
2302
|
+
*/
|
|
2303
|
+
async appendToolCall(conversationId, messageId, call) {
|
|
2304
|
+
const conversation = this.requireConversation(conversationId);
|
|
2305
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2306
|
+
if (!message)
|
|
2307
|
+
throw new Error("找不到对应的助手消息。");
|
|
2308
|
+
const calls = (message.toolCalls ??= []);
|
|
2309
|
+
// WHERE IN THE ANSWER THIS CALL HAPPENED, stamped here because this is the only place that knows both
|
|
2310
|
+
// halves: the call arrived, and the message already holds every character streamed before it. Without
|
|
2311
|
+
// it the browser can only render the blocks as one list beside the text, so a turn that read a file,
|
|
2312
|
+
// said something, then ran a test would show all three in the wrong order.
|
|
2313
|
+
//
|
|
2314
|
+
// AND WHERE IN THE REASONING, for the same reason and from the same place. `thinking` is the other
|
|
2315
|
+
// stream a turn has, and a call made while the model was still thinking has to be placeable inside it -
|
|
2316
|
+
// otherwise the transcript can only say "it reasoned, and then it called a tool", which is the one order
|
|
2317
|
+
// a `hmm → read → hmm → grep → answer` turn never had. Stamped as the thinking length BEFORE this call,
|
|
2318
|
+
// so a call that started before any reasoning anchors at 0 and renders first.
|
|
2319
|
+
//
|
|
2320
|
+
// The thinking read here is the message's own field, written synchronously as each delta arrives - not
|
|
2321
|
+
// a count of how much a queued disk write had managed to flush. That distinction is the same one `at`
|
|
2322
|
+
// was stamped for.
|
|
2323
|
+
const placed = {
|
|
2324
|
+
...call,
|
|
2325
|
+
...(call.at === undefined ? { at: message.content.length } : {}),
|
|
2326
|
+
...(call.thinkingAt === undefined ? { thinkingAt: (message.thinking ?? "").length } : {}),
|
|
2327
|
+
};
|
|
2328
|
+
calls.push(structuredClone(placed));
|
|
2329
|
+
conversation.updatedAt = now();
|
|
2330
|
+
await this.persistToolCallMessage(conversationId, messageId);
|
|
2331
|
+
return structuredClone(calls);
|
|
2332
|
+
}
|
|
2333
|
+
/**
|
|
2334
|
+
* Fills in the outcome of the call at `index`, or returns the array UNCHANGED when there is no such
|
|
2335
|
+
* index.
|
|
2336
|
+
*
|
|
2337
|
+
* ADDRESSED BY POSITION rather than by Pi's `toolCallId`, and that is the whole reason the caller has
|
|
2338
|
+
* to hold a map. `toolCallId` is an identity only Pi can resolve - it is never persisted on
|
|
2339
|
+
* `ToolCallBlock` - so the caller resolves each end back to the row it started, which is exactly what
|
|
2340
|
+
* `SubagentRunRecorder` does for a card.
|
|
2341
|
+
*
|
|
2342
|
+
* A MISMATCH IS NOT AN ERROR. `tool_execution_end` with no matching start, or one that arrives after the
|
|
2343
|
+
* turn ended, must not fail the turn: the alternative is a store method that throws inside a drain loop,
|
|
2344
|
+
* and the reader would lose the whole turn's transcript over one unresolvable id. Returning the array
|
|
2345
|
+
* unchanged keeps the caller broadcasting what it actually knows.
|
|
2346
|
+
*
|
|
2347
|
+
* Only `status` and `durationMs` are written, and only when they are present on the incoming block - a
|
|
2348
|
+
* second end for a row that already has an outcome must not erase it with an absent field.
|
|
2349
|
+
*/
|
|
2350
|
+
async settleToolCall(conversationId, messageId, index, outcome) {
|
|
2351
|
+
const conversation = this.requireConversation(conversationId);
|
|
2352
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2353
|
+
if (!message)
|
|
2354
|
+
throw new Error("找不到对应的助手消息。");
|
|
2355
|
+
const calls = message.toolCalls;
|
|
2356
|
+
const call = calls?.[index];
|
|
2357
|
+
if (!calls || !call)
|
|
2358
|
+
return structuredClone(calls ?? []);
|
|
2359
|
+
if (outcome.status !== undefined)
|
|
2360
|
+
call.status = outcome.status;
|
|
2361
|
+
if (outcome.durationMs !== undefined)
|
|
2362
|
+
call.durationMs = outcome.durationMs;
|
|
2363
|
+
// `!== undefined`, never a truthiness test: an absent result means "this call's output was never
|
|
2364
|
+
// recorded", which is a different fact from "recorded, and it was empty", and `""` would state the
|
|
2365
|
+
// second while meaning the first.
|
|
2366
|
+
if (outcome.result !== undefined)
|
|
2367
|
+
call.result = outcome.result;
|
|
2368
|
+
// The streaming `live` preview is KEPT, not deleted. It accumulated during execution and is the
|
|
2369
|
+
// full output a reader watched grow; the persisted `result` is a bounded 8KB tail of the same
|
|
2370
|
+
// stream. Deleting live would replace the watched text with a possibly-different 8KB slice, and a
|
|
2371
|
+
// finished tool block that vanishes the moment the call ends is a block that taught the reader
|
|
2372
|
+
// nothing. The client prefers `live` when both are present, falling back to `result`.
|
|
2373
|
+
conversation.updatedAt = now();
|
|
2374
|
+
await this.persistToolCallMessage(conversationId, messageId);
|
|
2375
|
+
return structuredClone(calls);
|
|
2376
|
+
}
|
|
2377
|
+
/**
|
|
2378
|
+
* REWRITE A CALL THAT IS STILL RUNNING - its arguments as they have grown, and whatever output has
|
|
2379
|
+
* arrived so far. Separate from `settleToolCall` because "settle" is the wrong word for a turn that is
|
|
2380
|
+
* still going: nothing here decides an outcome, and a method that could be mistaken for it is one a
|
|
2381
|
+
* future caller reaches for by mistake.
|
|
2382
|
+
*
|
|
2383
|
+
* Every field is `undefined`-tested for the same reason `settleToolCall` does it: `""` and `[]` are
|
|
2384
|
+
* values a tool can genuinely produce, and treating them as "not reported" would erase a real answer.
|
|
2385
|
+
*/
|
|
2386
|
+
/**
|
|
2387
|
+
* THE TOOL-CALL WRITES, PERSISTED AS ONE MESSAGE INSTEAD OF THE WHOLE APPLICATION.
|
|
2388
|
+
*
|
|
2389
|
+
* A tool call's lifecycle touches exactly ONE thing: the `toolCalls` array of ONE message. The
|
|
2390
|
+
* write used to be `this.persist()`, which hands the ENTIRE state to the repository - every
|
|
2391
|
+
* workspace, every conversation, every message of every conversation - to be serialized and
|
|
2392
|
+
* written. A turn that calls five tools therefore wrote the whole application ten to fifteen
|
|
2393
|
+
* times, and every one of those writes was proportional to the whole history rather than to the
|
|
2394
|
+
* one row that changed (LAT-020).
|
|
2395
|
+
*
|
|
2396
|
+
* `message.replace` is the transaction that means 「this one message now reads like this」, and it
|
|
2397
|
+
* is exactly the write this is: the row's content did not change, only its tool calls did.
|
|
2398
|
+
*/
|
|
2399
|
+
async persistToolCallMessage(conversationId, messageId) {
|
|
2400
|
+
const conversation = this.requireConversation(conversationId);
|
|
2401
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2402
|
+
if (!message)
|
|
2403
|
+
return;
|
|
2404
|
+
await this.persistTransaction({ kind: "message.replace", conversationId, message: structuredClone(message), updatedAt: conversation.updatedAt });
|
|
2405
|
+
}
|
|
2406
|
+
async updateToolCall(conversationId, messageId, index, patch) {
|
|
2407
|
+
const conversation = this.requireConversation(conversationId);
|
|
2408
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2409
|
+
if (!message)
|
|
2410
|
+
throw new Error("找不到对应的助手消息。");
|
|
2411
|
+
const calls = message.toolCalls;
|
|
2412
|
+
const call = calls?.[index];
|
|
2413
|
+
if (!calls || !call)
|
|
2414
|
+
return structuredClone(calls ?? []);
|
|
2415
|
+
// MERGED BY KEY, NOT REPLACED. An update carries the arguments as they stand at that moment, and while a
|
|
2416
|
+
// call is being prepared that list GROWS - one key, then two, then six. Replacing the row's list with
|
|
2417
|
+
// whatever the latest update happened to carry loses every key the update left out, which on the very
|
|
2418
|
+
// first update is all of them. Merging can only ever add, so a sparse update can no longer erase what
|
|
2419
|
+
// an earlier one already reported - and the cap is re-applied here rather than trusted from outside.
|
|
2420
|
+
if (patch.backgroundTask !== undefined)
|
|
2421
|
+
call.backgroundTask = structuredClone(patch.backgroundTask);
|
|
2422
|
+
if (patch.label !== undefined)
|
|
2423
|
+
call.label = patch.label;
|
|
2424
|
+
if (patch.detail !== undefined)
|
|
2425
|
+
call.detail = patch.detail;
|
|
2426
|
+
if (patch.preparing !== undefined)
|
|
2427
|
+
call.preparing = patch.preparing;
|
|
2428
|
+
if (patch.args !== undefined) {
|
|
2429
|
+
const merged = new Map((call.args ?? []).map((arg) => [arg.key, arg]));
|
|
2430
|
+
for (const arg of patch.args)
|
|
2431
|
+
merged.set(arg.key, arg);
|
|
2432
|
+
call.args = [...merged.values()].slice(0, TOOL_ARG_CAP);
|
|
2433
|
+
}
|
|
2434
|
+
// THE PREVIEW IS "THE TEXT SO FAR", SO IT REPLACES. Every writer sends the whole text: the runtime
|
|
2435
|
+
// accumulates the model's argument fragments before this is called, and Pi sends
|
|
2436
|
+
// `tool_execution_update.partialResult` already accumulated. Appending here would concatenate two
|
|
2437
|
+
// "so far"s - the reader would watch the output print itself twice. The clear at the preparing ->
|
|
2438
|
+
// running handoff (`live: ""`) is the same statement, once: the arguments that were on screen while
|
|
2439
|
+
// the call was being written are gone by the time it runs.
|
|
2440
|
+
if (patch.live !== undefined)
|
|
2441
|
+
call.live = patch.live;
|
|
2442
|
+
// WHERE THE CALL HAPPENED, corrected when the call is announced. The placeholder stamped the
|
|
2443
|
+
// offsets of the moment it was made, and that moment is not the moment the call belongs to
|
|
2444
|
+
// (UX-008).
|
|
2445
|
+
if (patch.at !== undefined)
|
|
2446
|
+
call.at = patch.at;
|
|
2447
|
+
if (patch.thinkingAt !== undefined)
|
|
2448
|
+
call.thinkingAt = patch.thinkingAt;
|
|
2449
|
+
// WHICH REASONING BLOCK THIS CALL BELONGS TO. It is written when the call is ANNOUNCED, not
|
|
2450
|
+
// when its placeholder was made, and it is written HERE because the placeholder row already
|
|
2451
|
+
// exists by then - a placeholder created while the model was still writing the arguments
|
|
2452
|
+
// cannot know whether the reasoning was over by the time the call was made (UX-008).
|
|
2453
|
+
//
|
|
2454
|
+
// `null` IS A VALUE, NOT AN ABSENCE: it says the call is outside every reasoning block, and
|
|
2455
|
+
// the browser needs to hear that difference from "not decided yet". So the check is
|
|
2456
|
+
// `!== undefined`, never a truthiness test.
|
|
2457
|
+
if (patch.thinkingBlock !== undefined)
|
|
2458
|
+
call.thinkingBlock = patch.thinkingBlock;
|
|
2459
|
+
// The question rides on the call rather than beside it, so this is the only write it needs.
|
|
2460
|
+
if (patch.question !== undefined && (!call.question || call.question.status === "pending")) {
|
|
2461
|
+
const previous = call.question;
|
|
2462
|
+
call.question = patch.question;
|
|
2463
|
+
if (patch.question.status !== "pending") {
|
|
2464
|
+
try {
|
|
2465
|
+
await this.persistToolCallMessage(conversationId, messageId);
|
|
2466
|
+
}
|
|
2467
|
+
catch (error) {
|
|
2468
|
+
if (call.question === patch.question)
|
|
2469
|
+
call.question = previous;
|
|
2470
|
+
throw error;
|
|
2471
|
+
}
|
|
2472
|
+
return structuredClone(calls);
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
conversation.updatedAt = now();
|
|
2476
|
+
await this.persistToolCallMessage(conversationId, messageId);
|
|
2477
|
+
return structuredClone(calls);
|
|
2478
|
+
}
|
|
2479
|
+
/**
|
|
2480
|
+
* STOPS SEVERAL ROWS FROM CLAIMING THE MODEL IS STILL WRITING THEM, in one write.
|
|
2481
|
+
*
|
|
2482
|
+
* A row is created by `toolcall_start` and filled in by `tool_execution_start`, so a call the turn cut
|
|
2483
|
+
* off between the two - an abort, a cancelled turn, an upstream error - kept `preparing` for the rest of
|
|
2484
|
+
* time. A finished turn showing 「生成参数中…」 is the same expensive lie as a settled tool still saying
|
|
2485
|
+
* 「正在生成参数…」: it says the agent is working on something it has already stopped doing, and it is
|
|
2486
|
+
* what a reader sees on every such row for the rest of the conversation.
|
|
2487
|
+
*
|
|
2488
|
+
* WHAT IS *NOT* WRITTEN HERE, and the omissions are the point. No `status`: Pi reported no outcome for
|
|
2489
|
+
* these calls, and `status` is the field that says an outcome was observed - writing `"error"` would
|
|
2490
|
+
* claim the tool failed, which is a different fact from "it never ran". No `result`, for the same
|
|
2491
|
+
* reason. `preparing: false` alone says exactly what is true, which is that the arguments stopped
|
|
2492
|
+
* arriving.
|
|
2493
|
+
*
|
|
2494
|
+
* `live` IS CLEARED, because during preparation that field holds the ARGUMENT TEXT and the transcript
|
|
2495
|
+
* would otherwise print a raw JSON fragment under a call that never ran. The parameters themselves are
|
|
2496
|
+
* not lost: `args` carries them from `toolcall_end`, and `detail` has named the target since the first
|
|
2497
|
+
* readable fragment.
|
|
2498
|
+
*
|
|
2499
|
+
* Addressed by position like every other row write, and one that is not there is skipped rather than
|
|
2500
|
+
* failing the turn - the same tolerance `settleToolCall` has for an id it cannot resolve.
|
|
2501
|
+
*/
|
|
2502
|
+
async clearPreparingToolCalls(conversationId, messageId, rows) {
|
|
2503
|
+
const conversation = this.requireConversation(conversationId);
|
|
2504
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2505
|
+
if (!message)
|
|
2506
|
+
throw new Error("找不到对应的助手消息。");
|
|
2507
|
+
const calls = message.toolCalls;
|
|
2508
|
+
if (!calls)
|
|
2509
|
+
return [];
|
|
2510
|
+
let touched = false;
|
|
2511
|
+
for (const index of rows) {
|
|
2512
|
+
const call = calls[index];
|
|
2513
|
+
if (!call || call.preparing !== true)
|
|
2514
|
+
continue;
|
|
2515
|
+
call.preparing = false;
|
|
2516
|
+
call.live = "";
|
|
2517
|
+
touched = true;
|
|
2518
|
+
}
|
|
2519
|
+
if (touched) {
|
|
2520
|
+
conversation.updatedAt = now();
|
|
2521
|
+
await this.persist();
|
|
2522
|
+
}
|
|
2523
|
+
return structuredClone(calls);
|
|
2524
|
+
}
|
|
2525
|
+
async setStatus(conversationId, status) { const conversation = this.requireConversation(conversationId); conversation.status = status; conversation.updatedAt = now(); await this.persistMetadata(conversationId); }
|
|
2526
|
+
/** Commit once at turn end; metadata transactions work for both JSON and SQLite repositories. */
|
|
2527
|
+
async recordConversationUsage(conversationId, readout) {
|
|
2528
|
+
const conversation = this.requireConversation(conversationId);
|
|
2529
|
+
if (readout.sourceEntryId) {
|
|
2530
|
+
if (conversation.accountedPiUsageEntries?.includes(readout.sourceEntryId))
|
|
2531
|
+
return;
|
|
2532
|
+
if (!readout.usage)
|
|
2533
|
+
return;
|
|
2534
|
+
(conversation.accountedPiUsageEntries ??= []).push(readout.sourceEntryId);
|
|
2535
|
+
}
|
|
2536
|
+
if (readout.usage) {
|
|
2537
|
+
const previous = conversation.usage;
|
|
2538
|
+
const total = { ...readout.usage };
|
|
2539
|
+
if (previous)
|
|
2540
|
+
for (const key of ["input", "output", "cacheRead", "cacheWrite", "cost", "turns"])
|
|
2541
|
+
total[key] += previous[key];
|
|
2542
|
+
conversation.usage = total;
|
|
2543
|
+
conversation.usageCostKnown = (conversation.usageCostKnown ?? true) && readout.costKnown;
|
|
2544
|
+
}
|
|
2545
|
+
if (readout.contextUsage)
|
|
2546
|
+
conversation.contextUsage = { ...readout.contextUsage };
|
|
2547
|
+
else if (!readout.sourceEntryId)
|
|
2548
|
+
delete conversation.contextUsage;
|
|
2549
|
+
if (readout.usage || readout.contextUsage)
|
|
2550
|
+
conversation.usageUpdatedAt = now();
|
|
2551
|
+
await this.persistMetadata(conversationId);
|
|
2552
|
+
}
|
|
2553
|
+
/**
|
|
2554
|
+
* Records WHY a turn failed in a way the reader can see. `Conversation.error` is rendered as a red
|
|
2555
|
+
* banner above the transcript (`App.tsx:conversation-error`), and it is the only field that survives
|
|
2556
|
+
* a status flip and a navigation away and back - so it is the only place a "Pi died without saying
|
|
2557
|
+
* anything" failure becomes visible to a person.
|
|
2558
|
+
*
|
|
2559
|
+
* Settled through `persistMetadata` rather than `persistState` so the message and tool deltas the
|
|
2560
|
+
* turn had already written are not re-validated against a partial read; a previous build took the
|
|
2561
|
+
* heavier path and an early failure mid-turn left the transcript rolled back to the last good
|
|
2562
|
+
* checkpoint, hiding exactly the deltas the reader would have wanted to see.
|
|
2563
|
+
*
|
|
2564
|
+
* Set to `undefined` to clear, which the next `addUserMessage` does anyway - so callers only need
|
|
2565
|
+
* this when they want the banner without a follow-up message (the turn did fail and the user is
|
|
2566
|
+
* going to act on it without sending another prompt first).
|
|
2567
|
+
*/
|
|
2568
|
+
async setFailureReason(conversationId, reason) {
|
|
2569
|
+
const conversation = this.requireConversation(conversationId);
|
|
2570
|
+
if (reason === undefined)
|
|
2571
|
+
delete conversation.error;
|
|
2572
|
+
else
|
|
2573
|
+
conversation.error = reason;
|
|
2574
|
+
conversation.updatedAt = now();
|
|
2575
|
+
await this.persistMetadata(conversationId);
|
|
2576
|
+
}
|
|
2577
|
+
/**
|
|
2578
|
+
* Records WHY THIS CONVERSATION'S LAST ANSWER IS INCOMPLETE, in a way the reader can see.
|
|
2579
|
+
*
|
|
2580
|
+
* `Conversation.warning` is a different fact from `Conversation.error`: the run did not break, the
|
|
2581
|
+
* answer was cut short by the model's output budget. The reader's next move is different too - a
|
|
2582
|
+
* failed turn asks them to retry, a truncated one asks them to let the model continue - so the two
|
|
2583
|
+
* are kept apart rather than sharing one field and one colour.
|
|
2584
|
+
*
|
|
2585
|
+
* Set to `undefined` to clear, which the next `addUserMessage` does anyway.
|
|
2586
|
+
*/
|
|
2587
|
+
async setWarningReason(conversationId, reason) {
|
|
2588
|
+
const conversation = this.requireConversation(conversationId);
|
|
2589
|
+
if (reason === undefined)
|
|
2590
|
+
delete conversation.warning;
|
|
2591
|
+
else
|
|
2592
|
+
conversation.warning = reason;
|
|
2593
|
+
conversation.updatedAt = now();
|
|
2594
|
+
await this.persistMetadata(conversationId);
|
|
2595
|
+
}
|
|
2596
|
+
/** The plan a revert would carry out, without carrying it out. The server reads this to stop children first. */
|
|
2597
|
+
planRevert(conversationId, messageId, withdraw = false) { return planRevert(this.state, conversationId, messageId, withdraw); }
|
|
2598
|
+
/**
|
|
2599
|
+
* Records which Pi entry a message became, as reported by Pi while it was still running.
|
|
2600
|
+
*
|
|
2601
|
+
* Only ever set, never cleared: a message that already has an id keeps the one Pi gave it for that
|
|
2602
|
+
* turn, and a second report for the same message is ignored rather than allowed to move the boundary -
|
|
2603
|
+
* a boundary that moved under a user who is looking at it is exactly the silent data loss revert must not
|
|
2604
|
+
* be able to cause. An unknown message id is refused for the same reason `appendAssistantDelta` refuses
|
|
2605
|
+
* one: it means the caller and the store disagree about the conversation, and guessing is worse.
|
|
2606
|
+
*/
|
|
2607
|
+
async setMessagePiEntryId(conversationId, messageId, piEntryId) {
|
|
2608
|
+
const conversation = this.requireConversation(conversationId);
|
|
2609
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2610
|
+
if (!message)
|
|
2611
|
+
throw new Error(`Message not found: ${messageId}`);
|
|
2612
|
+
if (message.piEntryId)
|
|
2613
|
+
return;
|
|
2614
|
+
message.piEntryId = piEntryId;
|
|
2615
|
+
await this.persist();
|
|
2616
|
+
}
|
|
2617
|
+
/** Cache a locator Pi itself resolved while serving this conversation; never trust it as authorization. */
|
|
2618
|
+
async setConversationPiSessionFile(conversationId, path) {
|
|
2619
|
+
const conversation = this.requireConversation(conversationId);
|
|
2620
|
+
if (conversation.piSessionFile === path)
|
|
2621
|
+
return;
|
|
2622
|
+
conversation.piSessionFile = path;
|
|
2623
|
+
await this.persistMetadata(conversationId);
|
|
2624
|
+
}
|
|
2625
|
+
/** Records that a child conversation has reported its result/progress to its parent. */
|
|
2626
|
+
async markConversationReported(conversationId, timestamp) {
|
|
2627
|
+
const target = this.state.conversations.find((c) => c.id === conversationId);
|
|
2628
|
+
if (!target)
|
|
2629
|
+
return undefined;
|
|
2630
|
+
target.reportedToParentAt = timestamp || now();
|
|
2631
|
+
await this.persistMetadata(conversationId);
|
|
2632
|
+
return target;
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Reverts the conversation to the state right after `messageId`, in `state.json` only.
|
|
2636
|
+
*
|
|
2637
|
+
* SCOPE, DELIBERATELY NARROW: this touches `messages` and `subagentRuns` and nothing else. It does not
|
|
2638
|
+
* touch the workspace (that is not this process's to touch), it does not create or modify a conversation
|
|
2639
|
+
* (the user's hard requirement: still the same session, same id, same row in the sidebar), and it does
|
|
2640
|
+
* not record a "revert happened" marker - there is no undo to restore one for.
|
|
2641
|
+
*
|
|
2642
|
+
* NOT `updatedAt`. For the same reason rename and archive leave it alone: it is the sidebar's recency key,
|
|
2643
|
+
* so bumping it would teleport the conversation to the top of the list as a side effect of editing its
|
|
2644
|
+
* history. What a person did to a transcript is not activity IN the conversation, and the timestamps of
|
|
2645
|
+
* the surviving messages are untouched, so the pane's own ordering does not move either.
|
|
2646
|
+
*
|
|
2647
|
+
* `planRevert` has already run by the time this is called (the server reads it to stop children), so the
|
|
2648
|
+
* plan is recomputed here rather than passed in - two callers cannot disagree about what a message id
|
|
2649
|
+
* means, and the recomputation is a pure scan of a small array.
|
|
2650
|
+
*/
|
|
2651
|
+
async revertMessages(conversationId, messageId, withdraw = false) {
|
|
2652
|
+
const plan = planRevert(this.state, conversationId, messageId, withdraw);
|
|
2653
|
+
const conversation = this.requireConversation(conversationId);
|
|
2654
|
+
conversation.messages.splice(plan.boundaryIndex + (withdraw ? 0 : 1));
|
|
2655
|
+
if (plan.doomedRunIds.length) {
|
|
2656
|
+
const doomed = new Set(plan.doomedRunIds);
|
|
2657
|
+
this.state.subagentRuns = this.state.subagentRuns.filter((run) => !doomed.has(run.id));
|
|
2658
|
+
}
|
|
2659
|
+
await this.persist();
|
|
2660
|
+
return plan;
|
|
2661
|
+
}
|
|
2662
|
+
requireConversation(conversationId) { const conversation = this.state.conversations.find((item) => item.id === conversationId); if (!conversation)
|
|
2663
|
+
throw new Error("找不到这个会话。"); return conversation; }
|
|
2664
|
+
// ------------------------------------------------------------- Waiting messages
|
|
2665
|
+
//
|
|
2666
|
+
// A message the user sent while the agent was working WAITS HERE, and "here" is a field on the message
|
|
2667
|
+
// (`MessageDelivery`) rather than a list beside the conversation. Nothing in this section copies text
|
|
2668
|
+
// anywhere, because there is no second copy: the words a user typed live in exactly one place, in the
|
|
2669
|
+
// transcript, from the frame they pressed send until long after the agent answered them.
|
|
2670
|
+
//
|
|
2671
|
+
// ORDER IS THE QUEUE. The waiting messages are the `role: "user"` messages carrying a `delivery`, and
|
|
2672
|
+
// their array order is the order they will be started in - so "put this one first" is a move within
|
|
2673
|
+
// that group, and there is no `priority` flag to disagree with it.
|
|
2674
|
+
//
|
|
2675
|
+
// Every method persists on every call, for the reason `setSubagentRun` does: what a browser reads and
|
|
2676
|
+
// what the file holds must never differ, and a message waiting for a turn that has not started is
|
|
2677
|
+
// exactly as durable as the conversation around it.
|
|
2678
|
+
/**
|
|
2679
|
+
* This conversation's waiting messages, in the order they will be started.
|
|
2680
|
+
*
|
|
2681
|
+
* Cloned like every other value this store hands out, because the caller broadcasts it straight to
|
|
2682
|
+
* browsers and the array is mutated in place by the very next send.
|
|
2683
|
+
*/
|
|
2684
|
+
listWaitingMessages(conversationId) {
|
|
2685
|
+
return structuredClone(this.waitingMessages(this.requireConversation(conversationId)));
|
|
2686
|
+
}
|
|
2687
|
+
/** The same list by reference, for callers that only read a field and must not pay for a clone.
|
|
2688
|
+
*
|
|
2689
|
+
* Includes `role: "tool"` messages now that a 后台回传 is a real queue item: same dock, same ordering,
|
|
2690
|
+
* same delivery state machine, same steer/claim semantics - the only thing different is the render
|
|
2691
|
+
* (kept as a 后台回传 block) and what the agent is told when its turn comes (see `composePrompt`). */
|
|
2692
|
+
waitingMessages(conversation) {
|
|
2693
|
+
return conversation.messages.filter((message) => (message.role === "user" || message.role === "tool") && message.delivery);
|
|
2694
|
+
}
|
|
2695
|
+
requireWaitingMessage(conversationId, messageId) {
|
|
2696
|
+
const conversation = this.requireConversation(conversationId);
|
|
2697
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2698
|
+
if (!message || !message.delivery || (message.role !== "user" && message.role !== "tool"))
|
|
2699
|
+
throw new Error(`等待中的消息不存在或已被处理:${messageId}`);
|
|
2700
|
+
return { conversation, message };
|
|
2701
|
+
}
|
|
2702
|
+
async persistMessages(conversation, acceptedSendId, metadata) {
|
|
2703
|
+
await this.persistTransaction({ kind: "conversation.messages", conversationId: conversation.id, messages: structuredClone(conversation.messages), updatedAt: conversation.updatedAt, ...(acceptedSendId ? { acceptedSendId } : {}), ...(metadata ? { metadata: structuredClone(metadata) } : {}) });
|
|
2704
|
+
}
|
|
2705
|
+
/**
|
|
2706
|
+
* Claims one waiting message for delivery to the live Pi process: `waiting` becomes `sending`, and the
|
|
2707
|
+
* message STAYS WHERE IT IS - still on screen, still in the transcript, still at the same index.
|
|
2708
|
+
*
|
|
2709
|
+
* The read and the write are adjacent statements with no `await` between them, which is what makes the
|
|
2710
|
+
* claim atomic here. This store has no mutex and does not need one: JavaScript runs this synchronous
|
|
2711
|
+
* run-to-completion, so a second caller arriving in the same tick observes the write above and cannot
|
|
2712
|
+
* claim the same message.
|
|
2713
|
+
*/
|
|
2714
|
+
async claimWaitingMessage(conversationId, messageId) {
|
|
2715
|
+
const { conversation, message } = this.requireWaitingMessage(conversationId, messageId);
|
|
2716
|
+
if (message.delivery === "sending")
|
|
2717
|
+
throw new Error("这条消息已经交给 Agent 了(Pi 没有撤回单条队列消息的能力)");
|
|
2718
|
+
message.delivery = "sending";
|
|
2719
|
+
await this.persistMessages(conversation);
|
|
2720
|
+
return structuredClone(message);
|
|
2721
|
+
}
|
|
2722
|
+
/**
|
|
2723
|
+
* Puts ONE message into `waiting` when it has no delivery state at all.
|
|
2724
|
+
*
|
|
2725
|
+
* `releaseWaitingMessage` above moves `sending` BACK to `waiting`, which is a claim being taken back.
|
|
2726
|
+
* This is the other direction: a message that was written as an ordinary sent message and has to join
|
|
2727
|
+
* the queue after the fact. There are exactly two reasons it happens, and both are consequences of the
|
|
2728
|
+
* decision being made before the write rather than after it (see `enqueueAndRun`):
|
|
2729
|
+
*
|
|
2730
|
+
* 1. Two sends raced. The second one read "idle", wrote itself as an ordinary message, and only then
|
|
2731
|
+
* found the run slot taken. Its words are unanswered, so it is a waiting message after all.
|
|
2732
|
+
* 2. The preflight that runs between the write and the turn refused (a model that cannot read images,
|
|
2733
|
+
* an @-mention that could not be expanded). Nothing reached a model, so the words are still owed an
|
|
2734
|
+
* answer and belong in the queue where the user can see them and send them again.
|
|
2735
|
+
*
|
|
2736
|
+
* Both are restorations of a state that was briefly wrong, never a way to re-queue a message Pi holds:
|
|
2737
|
+
* a `sending` message is refused here, which keeps this from becoming a back door around the one-way
|
|
2738
|
+
* door `claimWaitingMessage` puts up.
|
|
2739
|
+
*/
|
|
2740
|
+
async markMessageWaiting(conversationId, messageId) {
|
|
2741
|
+
const conversation = this.requireConversation(conversationId);
|
|
2742
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2743
|
+
if (!message || (message.role !== "user" && message.role !== "tool"))
|
|
2744
|
+
return undefined;
|
|
2745
|
+
if (message.delivery === "sending")
|
|
2746
|
+
throw new Error("这条消息已经交给 Agent 了");
|
|
2747
|
+
if (message.delivery === "waiting")
|
|
2748
|
+
return structuredClone(message);
|
|
2749
|
+
message.delivery = "waiting";
|
|
2750
|
+
await this.persistMessages(conversation);
|
|
2751
|
+
return structuredClone(message);
|
|
2752
|
+
}
|
|
2753
|
+
/**
|
|
2754
|
+
* Puts ONE `sending` message back to `waiting`, for the one case that proves Pi never took it.
|
|
2755
|
+
*
|
|
2756
|
+
* The one legal use, and it is narrow on purpose: this is called ONLY when we can prove the message
|
|
2757
|
+
* never reached a model - the turn ended while Pi still held it, or the write to Pi's stdin failed
|
|
2758
|
+
* before it left. Pi drains steering before its loop can end and announces the delivery before the turn
|
|
2759
|
+
* settles, so a message still `sending` when the child is gone provably was not delivered, and
|
|
2760
|
+
* returning it is a fact rather than a guess. It is deliberately NOT used for "Pi has not answered yet",
|
|
2761
|
+
* where the outcome is genuinely unknown and the honest state is still `sending`.
|
|
2762
|
+
*/
|
|
2763
|
+
async releaseWaitingMessage(conversationId, messageId) {
|
|
2764
|
+
const conversation = this.requireConversation(conversationId);
|
|
2765
|
+
const message = conversation.messages.find((item) => item.id === messageId);
|
|
2766
|
+
if (!message || message.delivery !== "sending")
|
|
2767
|
+
return;
|
|
2768
|
+
message.delivery = "waiting";
|
|
2769
|
+
await this.persistMessages(conversation);
|
|
2770
|
+
}
|
|
2771
|
+
/**
|
|
2772
|
+
* Returns every `sending` message of this conversation to `waiting`, for the end of a turn.
|
|
2773
|
+
*
|
|
2774
|
+
* See `releaseWaitingMessage` for why this is a fact and not a guess. Called both when a turn ends and
|
|
2775
|
+
* when the user stops it: in the stop case the child is killed mid-turn and a steer it was still holding
|
|
2776
|
+
* was never delivered either, so putting it back is what lets the user decide what to do with it instead
|
|
2777
|
+
* of silently dropping a message they typed - a message they can still see, because it never left the
|
|
2778
|
+
* transcript in the first place.
|
|
2779
|
+
*/
|
|
2780
|
+
async releaseSendingMessages(conversationId) {
|
|
2781
|
+
const conversation = this.requireConversation(conversationId);
|
|
2782
|
+
let changed = false;
|
|
2783
|
+
for (const message of this.waitingMessages(conversation)) {
|
|
2784
|
+
if (message.delivery !== "sending")
|
|
2785
|
+
continue;
|
|
2786
|
+
message.delivery = "waiting";
|
|
2787
|
+
changed = true;
|
|
2788
|
+
}
|
|
2789
|
+
if (changed)
|
|
2790
|
+
await this.persistMessages(conversation);
|
|
2791
|
+
}
|
|
2792
|
+
/**
|
|
2793
|
+
* Withdraws one waiting message, by id. Returns it, or `undefined` when it is already gone.
|
|
2794
|
+
*
|
|
2795
|
+
* "Already gone" is a no-op rather than an error, and the reason is the same as `SubagentRun.stop`: the
|
|
2796
|
+
* click that sent this was almost always triggered by a bubble the browser has not been told about
|
|
2797
|
+
* yet, so an id that has already been answered or cancelled is the ordinary case and must not surface
|
|
2798
|
+
* as a failure.
|
|
2799
|
+
*
|
|
2800
|
+
* A `sending` message REFUSES, because the text is already in a live Pi child's stdin and Pi has no way
|
|
2801
|
+
* to forget one item (its only queue command is `clear_queue`, which clears every one of them,
|
|
2802
|
+
* including follow-ups that have nothing to do with this click). Removing it here would not stop Pi from
|
|
2803
|
+
* delivering it - it would make the model act on a message the user believed they had withdrawn, while
|
|
2804
|
+
* their own transcript quietly lost the words.
|
|
2805
|
+
*/
|
|
2806
|
+
async cancelWaitingMessage(conversationId, messageId) {
|
|
2807
|
+
const conversation = this.requireConversation(conversationId);
|
|
2808
|
+
const index = conversation.messages.findIndex((item) => item.id === messageId);
|
|
2809
|
+
if (index < 0)
|
|
2810
|
+
return undefined;
|
|
2811
|
+
const message = conversation.messages[index];
|
|
2812
|
+
if ((message.role !== "user" && message.role !== "tool") || !message.delivery)
|
|
2813
|
+
return undefined;
|
|
2814
|
+
if (message.delivery === "sending")
|
|
2815
|
+
throw new Error("这条消息已经交给 Agent 了,取消不掉(Pi 没有撤回单条队列消息的能力)");
|
|
2816
|
+
const [removed] = conversation.messages.splice(index, 1);
|
|
2817
|
+
await this.persistMessages(conversation);
|
|
2818
|
+
return structuredClone(removed);
|
|
2819
|
+
}
|
|
2820
|
+
/**
|
|
2821
|
+
* Rewrites the words of one waiting message. User sends only - a 后台回传 carries a `<task>` envelope
|
|
2822
|
+
* the model parses for state, summary and body, and editing it would change a fact the agent has
|
|
2823
|
+
* already started reasoning from. The client dock shows no 「改字」 button for `role: "tool"` rows.
|
|
2824
|
+
*/
|
|
2825
|
+
async editWaitingMessage(conversationId, messageId, content) {
|
|
2826
|
+
const trimmed = content.trim();
|
|
2827
|
+
if (!trimmed)
|
|
2828
|
+
throw new Error("消息不能为空");
|
|
2829
|
+
const { conversation, message } = this.requireWaitingMessage(conversationId, messageId);
|
|
2830
|
+
if (message.source === "session-reminder")
|
|
2831
|
+
throw new Error("Agent 的定时提醒不能改字");
|
|
2832
|
+
if (message.role === "tool")
|
|
2833
|
+
throw new Error("后台任务结果不能改字");
|
|
2834
|
+
if (message.delivery !== "waiting")
|
|
2835
|
+
throw new Error("这条消息已经交给 Agent 了,改不了(Pi 已经收到了原文)");
|
|
2836
|
+
message.content = trimmed;
|
|
2837
|
+
await this.persistMessages(conversation);
|
|
2838
|
+
return structuredClone(message);
|
|
2839
|
+
}
|
|
2840
|
+
/**
|
|
2841
|
+
* Moves one waiting message to a new position among the waiting messages.
|
|
2842
|
+
*
|
|
2843
|
+
* `toIndex` is counted over the WAITING messages only, so `0` is the next one the agent will start and
|
|
2844
|
+
* the caller never has to know how many answered messages sit above it. Moving to the front and moving
|
|
2845
|
+
* back are the same operation, which is the point: the old arrangement had a `priority` boolean for the
|
|
2846
|
+
* first and no way at all to express the second, so undoing a priority meant cancelling the message and
|
|
2847
|
+
* retyping it.
|
|
2848
|
+
*
|
|
2849
|
+
* NOTHING CAN GO IN FRONT OF A `sending` MESSAGE. It is already in Pi's stdin and Pi's steering queue
|
|
2850
|
+
* is FIFO, so it will be delivered before anything this server could do about the order. Accepting the
|
|
2851
|
+
* move and then delivering the other one first would be the UI promising an outcome the transport has
|
|
2852
|
+
* already decided, so it is refused instead.
|
|
2853
|
+
*/
|
|
2854
|
+
async reorderWaitingMessage(conversationId, messageId, toIndex) {
|
|
2855
|
+
const { conversation, message } = this.requireWaitingMessage(conversationId, messageId);
|
|
2856
|
+
const waiting = this.waitingMessages(conversation);
|
|
2857
|
+
const from = waiting.indexOf(message);
|
|
2858
|
+
const target = Math.max(0, Math.min(Math.trunc(toIndex), waiting.length - 1));
|
|
2859
|
+
// NOTHING MAY OCCUPY THE `sending` MESSAGE'S SLOT, in either direction. It is already in Pi's stdin and
|
|
2860
|
+
// Pi's steering queue is FIFO, so it is delivered next whatever this method does - meaning a different
|
|
2861
|
+
// message landing in front of it would be a move the UI performed and the transport then ignored, and
|
|
2862
|
+
// moving the `sending` message itself off that spot would be a lie of the same kind.
|
|
2863
|
+
const lastSendingIndex = waiting.reduce((last, item, index) => item.delivery === "sending" ? index : last, -1);
|
|
2864
|
+
if (lastSendingIndex >= 0 && (message.delivery === "sending" || target <= lastSendingIndex)) {
|
|
2865
|
+
throw new Error(message.delivery === "sending"
|
|
2866
|
+
? "这条消息已经交给 Agent 了,挪不动(Pi 会先回答已经收到的那条)"
|
|
2867
|
+
: "前面那条消息已经交给 Agent 了,插不过去(Pi 按收到的顺序送达)");
|
|
2868
|
+
}
|
|
2869
|
+
if (target === from)
|
|
2870
|
+
return structuredClone(message);
|
|
2871
|
+
this.moveWaitingMessage(conversation, waiting, from, target);
|
|
2872
|
+
await this.persistMessages(conversation);
|
|
2873
|
+
return structuredClone(message);
|
|
2874
|
+
}
|
|
2875
|
+
moveWaitingMessage(conversation, waiting, from, target) {
|
|
2876
|
+
if (from === target)
|
|
2877
|
+
return;
|
|
2878
|
+
// Permute THE WAITING SLOTS rather than splicing a message to an index. The waiting messages are
|
|
2879
|
+
// usually a suffix of the array, but they are not guaranteed to be one - an assistant message sits
|
|
2880
|
+
// between two of them once a steer has been delivered mid-turn - and an offset derived from "where in
|
|
2881
|
+
// the waiting group am I" would then be computing a position that means nothing. Rewriting the slots in
|
|
2882
|
+
// place is total: it cannot land a message outside the group, and it moves nothing that is not waiting.
|
|
2883
|
+
const slots = waiting.map((item) => conversation.messages.indexOf(item));
|
|
2884
|
+
const reordered = [...waiting];
|
|
2885
|
+
const [message] = reordered.splice(from, 1);
|
|
2886
|
+
reordered.splice(target, 0, message);
|
|
2887
|
+
slots.forEach((slot, order) => { conversation.messages[slot] = reordered[order]; });
|
|
2888
|
+
}
|
|
2889
|
+
/**
|
|
2890
|
+
* Open the reply to a Pi steer and clear its delivery state in one write.
|
|
2891
|
+
* The text match and the FIFO fallback both require a claimed `sending` row.
|
|
2892
|
+
*/
|
|
2893
|
+
async deliverWaitingMessage(conversationId, agentIdentity, messageId) {
|
|
2894
|
+
const conversation = this.requireConversation(conversationId);
|
|
2895
|
+
// Looks for the single message Pi is currently answering. A `role: "tool"` 后台回传 that has been
|
|
2896
|
+
// steered or taken is on the same delivery state machine as a user message, so it is the answer
|
|
2897
|
+
// target too; the assistant placeholder still lands directly below it and the role/identity is read
|
|
2898
|
+
// from the conversation (not the message) when the turn opens.
|
|
2899
|
+
const index = messageId
|
|
2900
|
+
? conversation.messages.findIndex((item) => item.id === messageId)
|
|
2901
|
+
: conversation.messages.findIndex((item) => (item.role === "user" || item.role === "tool") && item.delivery === "sending");
|
|
2902
|
+
if (index < 0)
|
|
2903
|
+
return undefined;
|
|
2904
|
+
const user = conversation.messages[index];
|
|
2905
|
+
if ((user.role !== "user" && user.role !== "tool") || user.delivery !== "sending")
|
|
2906
|
+
return undefined;
|
|
2907
|
+
delete user.delivery;
|
|
2908
|
+
const assistant = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) };
|
|
2909
|
+
conversation.messages.splice(index + 1, 0, assistant);
|
|
2910
|
+
await this.persistMessages(conversation);
|
|
2911
|
+
return { user: structuredClone(user), assistant: structuredClone(assistant) };
|
|
2912
|
+
}
|
|
2913
|
+
/**
|
|
2914
|
+
* Opens a turn on a message that is ALREADY IN THE TRANSCRIPT: clears its delivery state, applies every
|
|
2915
|
+
* side effect that means "a turn started here", and splices the assistant placeholder in DIRECTLY AFTER
|
|
2916
|
+
* IT.
|
|
2917
|
+
*
|
|
2918
|
+
* THE INSERT POSITION IS THE WHOLE DESIGN. `push` was the old behaviour and it is only correct when the
|
|
2919
|
+
* message being answered is the last thing in the conversation. With two messages waiting, answering
|
|
2920
|
+
* the first by appending puts its reply BELOW the second one, so the reader sees the answer to a
|
|
2921
|
+
* question that is still waiting - a transcript lying about its own order. Splicing at
|
|
2922
|
+
* `indexOf(user) + 1` keeps every waiting message below the reply that belongs to the one above it.
|
|
2923
|
+
*
|
|
2924
|
+
* The side effects - title, `updatedAt`, `status: "waiting"`, clearing a stale failure - all describe a
|
|
2925
|
+
* TURN rather than a message, which is why `addUserMessage` skips them for a message that is only
|
|
2926
|
+
* waiting. They belong here, at the moment the turn genuinely begins - the model still has not
|
|
2927
|
+
* returned a token, and that is the shape the row carries until `streamTurn` sees the first delta.
|
|
2928
|
+
*/
|
|
2929
|
+
async openTurnOnMessage(conversationId, messageId, agentIdentity) {
|
|
2930
|
+
const conversation = this.requireConversation(conversationId);
|
|
2931
|
+
const index = conversation.messages.findIndex((item) => item.id === messageId);
|
|
2932
|
+
if (index < 0)
|
|
2933
|
+
throw new Error(`消息不存在或已被撤回:${messageId}`);
|
|
2934
|
+
const user = conversation.messages[index];
|
|
2935
|
+
delete user.delivery;
|
|
2936
|
+
const assistant = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) };
|
|
2937
|
+
conversation.messages.splice(index + 1, 0, assistant);
|
|
2938
|
+
const firstUser = conversation.messages.find((item) => item.role === "user");
|
|
2939
|
+
const autoTitle = firstUser?.content.trim()
|
|
2940
|
+
? firstUser.content.slice(0, 42)
|
|
2941
|
+
: (firstUser?.images?.length ? "【图片】" : DEFAULT_CONVERSATION_TITLE);
|
|
2942
|
+
if (!conversation.titleLocked)
|
|
2943
|
+
conversation.title = autoTitle || DEFAULT_CONVERSATION_TITLE;
|
|
2944
|
+
// Same `waiting` reasoning as `addUserMessage` above - the prompt was just handed off and no
|
|
2945
|
+
// token has come back yet, which is a different observable state from "we have data flowing".
|
|
2946
|
+
conversation.updatedAt = user.createdAt;
|
|
2947
|
+
conversation.status = "waiting";
|
|
2948
|
+
delete conversation.error;
|
|
2949
|
+
await this.persistMessages(conversation);
|
|
2950
|
+
return { user: structuredClone(user), assistant: structuredClone(assistant) };
|
|
2951
|
+
}
|
|
2952
|
+
/**
|
|
2953
|
+
* Takes the OLDEST still-`waiting` message of this conversation, clearing its delivery state, for the
|
|
2954
|
+
* next turn to send as its prompt.
|
|
2955
|
+
*
|
|
2956
|
+
* Clearing the state and taking the message are the same write on purpose: it bounds the follow-up loop
|
|
2957
|
+
* (every pass strictly shrinks the set of waiting messages, so the loop cannot run forever even if a turn
|
|
2958
|
+
* succeeds without consuming anything) and it is what makes the crash honest - a server that dies
|
|
2959
|
+
* mid-turn has already taken the message out of the waiting set, so startup does not put it back, because
|
|
2960
|
+
* it may well have been delivered.
|
|
2961
|
+
*/
|
|
2962
|
+
async takeNextWaitingMessage(conversationId) {
|
|
2963
|
+
const conversation = this.requireConversation(conversationId);
|
|
2964
|
+
const next = this.waitingMessages(conversation).find((item) => item.delivery === "waiting");
|
|
2965
|
+
if (!next)
|
|
2966
|
+
return undefined;
|
|
2967
|
+
delete next.delivery;
|
|
2968
|
+
await this.persistMessages(conversation);
|
|
2969
|
+
return structuredClone(next);
|
|
2970
|
+
}
|
|
2971
|
+
/** Takes one specific waiting message by id, so an explicit user action can start it as a new turn. */
|
|
2972
|
+
async takeWaitingMessage(conversationId, messageId) {
|
|
2973
|
+
const { conversation, message } = this.requireWaitingMessage(conversationId, messageId);
|
|
2974
|
+
if (message.delivery !== "waiting")
|
|
2975
|
+
throw new Error("当前轮还没有结束,这条消息已经交给 Agent 了(Pi 没有撤回单条队列消息的能力)");
|
|
2976
|
+
delete message.delivery;
|
|
2977
|
+
await this.persistMessages(conversation);
|
|
2978
|
+
return structuredClone(message);
|
|
2979
|
+
}
|
|
2980
|
+
/**
|
|
2981
|
+
* Opens a turn for a message the user chose to be answered now, when the conversation is idle.
|
|
2982
|
+
*
|
|
2983
|
+
* The one place that both claims a specific message and opens its turn, so there is no window between
|
|
2984
|
+
* "the message stopped waiting" and "the turn began" in which a crash would leave a message that is
|
|
2985
|
+
* neither waiting nor answered.
|
|
2986
|
+
*/
|
|
2987
|
+
async openTurnOnSpecificMessage(conversationId, messageId, agentIdentity) {
|
|
2988
|
+
await this.takeWaitingMessage(conversationId, messageId);
|
|
2989
|
+
return this.openTurnOnMessage(conversationId, messageId, agentIdentity);
|
|
2990
|
+
}
|
|
2991
|
+
/**
|
|
2992
|
+
* Records a sub-agent run as `running`, BEFORE the child is spawned.
|
|
2993
|
+
*
|
|
2994
|
+
* The ordering is the whole point of this method existing separately from the spawn. A record created
|
|
2995
|
+
* after the child starts cannot survive the child failing to start, and one created only at the end
|
|
2996
|
+
* leaves nothing behind when the SERVER dies - which is the orphan startup reconciliation exists to
|
|
2997
|
+
* clean up. Writing the claim first is what makes that orphan possible, and therefore recoverable.
|
|
2998
|
+
*
|
|
2999
|
+
* `unshift`, like `createConversation`: the newest run is the one a reader is looking for.
|
|
3000
|
+
*
|
|
3001
|
+
* Trimmed HERE rather than at read time, because the array in memory and the file on disk have to
|
|
3002
|
+
* be the same thing - a store that kept evicted rows until the next unrelated write would put them
|
|
3003
|
+
* back on disk, and one that trimmed on read would show a browser a roster the file still holds.
|
|
3004
|
+
*/
|
|
3005
|
+
async beginSubagentRun(run) {
|
|
3006
|
+
if (this.state.subagentRuns.some((item) => item.id === run.id))
|
|
3007
|
+
throw new Error(`Sub-agent run already recorded: ${run.id}`);
|
|
3008
|
+
this.state.subagentRuns.unshift(run);
|
|
3009
|
+
trimSubagentRuns(this.state.subagentRuns, this.state.conversations);
|
|
3010
|
+
await this.persist();
|
|
3011
|
+
// A clone, like every other return here: the caller must not hold a reference to the object this
|
|
3012
|
+
// store mutates in place on the next delta, or a run's "snapshot" would change under it.
|
|
3013
|
+
return structuredClone(run);
|
|
3014
|
+
}
|
|
3015
|
+
/**
|
|
3016
|
+
* Writes a whole plan BEFORE step one runs, and persists it.
|
|
3017
|
+
*
|
|
3018
|
+
* THE ORDER THIS EXISTS TO ENFORCE. A plan recorded only as it executes leaves a reload showing
|
|
3019
|
+
* nothing recoverable - which steps were intended, in what order, under which failure policy - because
|
|
3020
|
+
* a transcript of the model asking for a plan is not the plan. Writing it whole first makes the record
|
|
3021
|
+
* a CLAIM the engine then makes good, exactly the relationship a run has to its child process, and it
|
|
3022
|
+
* means an engine that dies mid-plan leaves a document a person can read instead of a gap.
|
|
3023
|
+
*
|
|
3024
|
+
* Steps arrive already in their pending form with empty `attempts`, rather than being built as the
|
|
3025
|
+
* engine reaches them, so what lands on disk before anything runs is the whole intention.
|
|
3026
|
+
*
|
|
3027
|
+
* `structuredClone` on the way out, like `beginSubagentRun`: the engine mutates its own copy on every
|
|
3028
|
+
* transition, and a caller holding a live reference would watch the record change under itself.
|
|
3029
|
+
*/
|
|
3030
|
+
async beginWorkflow(plan) {
|
|
3031
|
+
if (!this.state.workflows)
|
|
3032
|
+
this.state.workflows = [];
|
|
3033
|
+
if (this.state.workflows.some((item) => item?.id === plan.id))
|
|
3034
|
+
throw new Error(`Workflow already recorded: ${plan.id}`);
|
|
3035
|
+
this.state.workflows.unshift(plan);
|
|
3036
|
+
trimWorkflows(this.state.workflows);
|
|
3037
|
+
await this.persistCollections("workflows");
|
|
3038
|
+
return structuredClone(plan);
|
|
3039
|
+
}
|
|
3040
|
+
/**
|
|
3041
|
+
* Replaces a plan wholesale, and persists it.
|
|
3042
|
+
*
|
|
3043
|
+
* THE WHOLE PLAN RATHER THAN A FIELD PATCH, and the reason is that a plan's live state is three moving
|
|
3044
|
+
* parts at once - `currentIndex`, the status of one step, and an appended attempt - so a patch type
|
|
3045
|
+
* narrow enough to be safe for all three is a shape nothing could be typechecked against. Writing the
|
|
3046
|
+
* plan also cannot forget a field, which is the failure a hand-maintained patch list invites as the
|
|
3047
|
+
* plan grows new parts.
|
|
3048
|
+
*
|
|
3049
|
+
* The whole array is cloned before the write, for the same reason the recorder keeps its own copy of a
|
|
3050
|
+
* run (`subagent-runs.ts:170`): the caller mutates the object it is about to hand back here, and a store
|
|
3051
|
+
* that persisted by reference would write out those edits before they were ever announced.
|
|
3052
|
+
*/
|
|
3053
|
+
async setWorkflow(plan) {
|
|
3054
|
+
if (!this.state.workflows)
|
|
3055
|
+
this.state.workflows = [];
|
|
3056
|
+
const stored = structuredClone(plan);
|
|
3057
|
+
const index = this.state.workflows.findIndex((item) => item?.id === stored.id);
|
|
3058
|
+
if (index < 0)
|
|
3059
|
+
throw new Error(`Workflow not found: ${stored.id}`);
|
|
3060
|
+
this.state.workflows[index] = stored;
|
|
3061
|
+
trimWorkflows(this.state.workflows);
|
|
3062
|
+
await this.persistCollections("workflows");
|
|
3063
|
+
return structuredClone(stored);
|
|
3064
|
+
}
|
|
3065
|
+
async setBackgroundTask(summary) {
|
|
3066
|
+
const existing = this.state.backgroundTasks.find((item) => item.id === summary.id);
|
|
3067
|
+
if (existing)
|
|
3068
|
+
Object.assign(existing, summary);
|
|
3069
|
+
else
|
|
3070
|
+
this.state.backgroundTasks.unshift(summary);
|
|
3071
|
+
if (summary.conversationId && summary.status === "running") {
|
|
3072
|
+
const conv = this.state.conversations.find((c) => c.id === summary.conversationId);
|
|
3073
|
+
if (conv && conv.status !== "running" && conv.status !== "waiting") {
|
|
3074
|
+
conv.status = "awaiting_background";
|
|
3075
|
+
conv.updatedAt = now();
|
|
3076
|
+
await this.persistMetadata(conv.id);
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
await this.persistCollections("backgroundTasks");
|
|
3080
|
+
}
|
|
3081
|
+
backgroundTask(id) {
|
|
3082
|
+
const task = this.state.backgroundTasks.find(item => item.id === id);
|
|
3083
|
+
return task && structuredClone(task);
|
|
3084
|
+
}
|
|
3085
|
+
async checkpointBackgroundOutput(id, output, offset) {
|
|
3086
|
+
const task = this.state.backgroundTasks.find(item => item.id === id && item.status === "running");
|
|
3087
|
+
if (!task || (task.outputOffset ?? 0) >= offset)
|
|
3088
|
+
return;
|
|
3089
|
+
task.output = output.slice(-BACKGROUND_LOG_LIMIT);
|
|
3090
|
+
task.outputOffset = offset;
|
|
3091
|
+
task.outputTruncated = offset > task.output.length;
|
|
3092
|
+
await this.persistCollections("backgroundTasks");
|
|
3093
|
+
}
|
|
3094
|
+
async finishBackgroundTask(taskId, outcome, content, deliver) {
|
|
3095
|
+
const task = this.state.backgroundTasks.find(item => item.id === taskId);
|
|
3096
|
+
if (!task)
|
|
3097
|
+
return;
|
|
3098
|
+
const conversation = this.state.conversations.find(item => item.id === task.conversationId);
|
|
3099
|
+
this.state.backgroundTasks = this.state.backgroundTasks.filter(item => item.id !== taskId);
|
|
3100
|
+
const message = conversation && backgroundTaskMessage(conversation, task, outcome, content, deliver);
|
|
3101
|
+
if (message?.delivery === "waiting" && conversation) {
|
|
3102
|
+
const waiting = this.waitingMessages(conversation);
|
|
3103
|
+
const lastSending = waiting.reduce((last, item, index) => item.delivery === "sending" ? index : last, -1);
|
|
3104
|
+
this.moveWaitingMessage(conversation, waiting, waiting.length - 1, lastSending + 1);
|
|
3105
|
+
}
|
|
3106
|
+
await this.persist();
|
|
3107
|
+
return message && structuredClone(message);
|
|
3108
|
+
}
|
|
3109
|
+
async removeBackgroundTask(id) {
|
|
3110
|
+
this.state.backgroundTasks = this.state.backgroundTasks.filter((item) => item.id !== id);
|
|
3111
|
+
await this.persistCollections("backgroundTasks");
|
|
3112
|
+
}
|
|
3113
|
+
async clearBackgroundTasks() {
|
|
3114
|
+
if (!this.state.backgroundTasks.length)
|
|
3115
|
+
return;
|
|
3116
|
+
this.state.backgroundTasks = [];
|
|
3117
|
+
await this.persistCollections("backgroundTasks");
|
|
3118
|
+
}
|
|
3119
|
+
/**
|
|
3120
|
+
* Writes a scheduled task - new or changed - and persists it.
|
|
3121
|
+
*
|
|
3122
|
+
* ONE METHOD FOR BOTH, because the two are the same write. A task that has not run and a task that
|
|
3123
|
+
* has run are the same kind of thing with different field values, and splitting them into
|
|
3124
|
+
* "create" and "update" would leave the caller to decide which of two paths a given change takes -
|
|
3125
|
+
* which is exactly the kind of decision that ends up made twice, differently, in two places.
|
|
3126
|
+
*
|
|
3127
|
+
* The value is cloned on the way in and on the way out, like every other store method that hands a
|
|
3128
|
+
* record back: the caller mutates its own copy freely, and the copy on disk is the copy that was
|
|
3129
|
+
* written.
|
|
3130
|
+
*/
|
|
3131
|
+
async setScheduledTask(task) {
|
|
3132
|
+
if (!this.state.scheduledTasks)
|
|
3133
|
+
this.state.scheduledTasks = [];
|
|
3134
|
+
const stored = structuredClone(task);
|
|
3135
|
+
const index = this.state.scheduledTasks.findIndex((item) => item?.id === stored.id);
|
|
3136
|
+
if (index < 0)
|
|
3137
|
+
this.state.scheduledTasks.push(stored);
|
|
3138
|
+
else
|
|
3139
|
+
this.state.scheduledTasks[index] = stored;
|
|
3140
|
+
trimScheduledTasks(this.state.scheduledTasks);
|
|
3141
|
+
await this.persistCollections("scheduledTasks");
|
|
3142
|
+
return structuredClone(stored);
|
|
3143
|
+
}
|
|
3144
|
+
/**
|
|
3145
|
+
* Removes a scheduled task, and persists the removal.
|
|
3146
|
+
*
|
|
3147
|
+
* AN EMPTY LIST IS STORED AS ABSENCE, for the same reason `setTodos` stores an empty todo list as
|
|
3148
|
+
* the absence of the key: a state file that says "scheduledTasks: []" claims the user considered a
|
|
3149
|
+
* schedule and found none, and a fresh install has never considered anything.
|
|
3150
|
+
*/
|
|
3151
|
+
async removeScheduledTask(id) {
|
|
3152
|
+
if (!this.state.scheduledTasks)
|
|
3153
|
+
return;
|
|
3154
|
+
const remaining = this.state.scheduledTasks.filter((item) => item?.id !== id);
|
|
3155
|
+
if (remaining.length === this.state.scheduledTasks.length)
|
|
3156
|
+
return;
|
|
3157
|
+
if (remaining.length)
|
|
3158
|
+
this.state.scheduledTasks = remaining;
|
|
3159
|
+
else
|
|
3160
|
+
delete this.state.scheduledTasks;
|
|
3161
|
+
await this.persistCollections("scheduledTasks");
|
|
3162
|
+
}
|
|
3163
|
+
/**
|
|
3164
|
+
* Applies the fields a run's life can change, and nothing else.
|
|
3165
|
+
*
|
|
3166
|
+
* `Object.assign` is safe HERE in a way it is not in `setConversationModel`, and the difference is the
|
|
3167
|
+
* patch's own type: `SubagentRunUpdate` is a named list of six already-narrowed fields, so there is no
|
|
3168
|
+
* wider object for a spread to smuggle extra keys in from. `undefined` means "no such value" and is
|
|
3169
|
+
* dropped by JSON.stringify, which is how `output`/`error`/`outputTruncated` come to be absent rather
|
|
3170
|
+
* than stored as an empty or null one.
|
|
3171
|
+
*
|
|
3172
|
+
* PERSISTED ON EVERY CALL, exactly as `appendAssistantDelta` is: the record a reader sees in a
|
|
3173
|
+
* `state` broadcast and the record on disk are then never different, and a run that is in flight is
|
|
3174
|
+
* as durable as the conversation it belongs to.
|
|
3175
|
+
*/
|
|
3176
|
+
async setSubagentRun(runId, changes) {
|
|
3177
|
+
const run = this.state.subagentRuns.find((item) => item.id === runId);
|
|
3178
|
+
if (!run)
|
|
3179
|
+
throw new Error(`Sub-agent run not found: ${runId}`);
|
|
3180
|
+
Object.assign(run, changes);
|
|
3181
|
+
await this.persistTransaction({ kind: "subagent.replace", run: structuredClone(run) });
|
|
3182
|
+
return structuredClone(run);
|
|
3183
|
+
}
|
|
3184
|
+
updateSubagentProgress(runId, changes) {
|
|
3185
|
+
const run = this.state.subagentRuns.find(item => item.id === runId && item.status === "running");
|
|
3186
|
+
if (run)
|
|
3187
|
+
Object.assign(run, changes);
|
|
3188
|
+
}
|
|
3189
|
+
async checkpointSubagentProgress(runId) {
|
|
3190
|
+
const run = this.state.subagentRuns.find(item => item.id === runId && item.status === "running");
|
|
3191
|
+
if (run)
|
|
3192
|
+
await this.persistTransaction({ kind: "subagent.replace", run: structuredClone(run) });
|
|
3193
|
+
}
|
|
3194
|
+
/**
|
|
3195
|
+
* Adds ONE settled run's usage to the ledger of the conversation that dispatched it.
|
|
3196
|
+
*
|
|
3197
|
+
* CALLED AT THE SETTLE, ONCE PER RUN, and the run's FINAL accumulated usage is what it reads - the
|
|
3198
|
+
* run record already holds the total of every finished message the child produced, so nothing is
|
|
3199
|
+
* re-derived here and no message is counted twice.
|
|
3200
|
+
*
|
|
3201
|
+
* THE FLAG AND THE LEDGER ENTRY ARE WRITTEN IN ONE WRITE, and that is the whole crash-safety
|
|
3202
|
+
* argument: `foldRunUsage` mutates both in the same synchronous block and this persists the state
|
|
3203
|
+
* once, so a server that dies here cannot leave the money counted twice (flag written, entry not)
|
|
3204
|
+
* or not at all (entry written, flag not). A run that was folded already is left alone, so calling
|
|
3205
|
+
* this twice is a no-op rather than a second bill.
|
|
3206
|
+
*
|
|
3207
|
+
* IT PERSISTS THE WHOLE STATE rather than the two rows, because the two rows ARE one fact: the
|
|
3208
|
+
* run's flag and the conversation's ledger entry have to become true together or not at all.
|
|
3209
|
+
*/
|
|
3210
|
+
async accountSubagentUsage(runId) {
|
|
3211
|
+
const run = this.state.subagentRuns.find((item) => item.id === runId);
|
|
3212
|
+
if (!foldRunUsage(this.state, run))
|
|
3213
|
+
return false;
|
|
3214
|
+
await this.persist();
|
|
3215
|
+
return true;
|
|
3216
|
+
}
|
|
3217
|
+
/**
|
|
3218
|
+
* Replaces the model's task list, and persists it.
|
|
3219
|
+
*
|
|
3220
|
+
* WHY IT IS A FILE AND NOT PI'S MEMORY, stated once here because it is the whole justification: Pi is
|
|
3221
|
+
* killed unconditionally at the end of every turn (`runtime.ts`) and never writes a tool result it was
|
|
3222
|
+
* given by an extension anywhere durable except the session JSONL, so a list held only in the child
|
|
3223
|
+
* would be gone before a person could look at it - and the sidebar would empty itself at every turn
|
|
3224
|
+
* boundary. The list is therefore part of `state.json` and rides the existing broadcast, which is also
|
|
3225
|
+
* why the browser needs no channel of its own: it already repaints from `state` on every text delta.
|
|
3226
|
+
*
|
|
3227
|
+
* THE PARAMETER IS RE-NORMALIZED HERE, not trusted because the endpoint normalized it. Those are two
|
|
3228
|
+
* different things: `/api/todos` validates a request that crossed a socket, and this validates a value
|
|
3229
|
+
* handed to `setTodos` by any future caller inside this process. A method whose own contract is "call me
|
|
3230
|
+
* with anything" is the only version of this that cannot be broken by the next call site.
|
|
3231
|
+
*
|
|
3232
|
+
* AN EMPTY LIST IS STORED AS ABSENCE, not as `[]`. `normalizeTodos` returns `[]` for a list the model
|
|
3233
|
+
* emptied deliberately, and the two must not be distinguishable: the browser renders `todos: []` and
|
|
3234
|
+
* `todos: undefined` as the same empty state on purpose, and persisting `[]` for a store that has never
|
|
3235
|
+
* seen the tool would make a fresh install claim the model had considered a plan and found none. So the
|
|
3236
|
+
* key is deleted, which also keeps `state.json` free of a field no build before this one wrote.
|
|
3237
|
+
*/
|
|
3238
|
+
async setTodos(conversationId, raw) {
|
|
3239
|
+
const { todos, dropped } = normalizeTodos(raw);
|
|
3240
|
+
if (!this.state.todosByConversation)
|
|
3241
|
+
this.state.todosByConversation = {};
|
|
3242
|
+
if (todos.length)
|
|
3243
|
+
this.state.todosByConversation[conversationId] = todos;
|
|
3244
|
+
else
|
|
3245
|
+
delete this.state.todosByConversation[conversationId];
|
|
3246
|
+
if (!Object.keys(this.state.todosByConversation).length)
|
|
3247
|
+
delete this.state.todosByConversation;
|
|
3248
|
+
await this.persist();
|
|
3249
|
+
return { todos: structuredClone(todos), dropped };
|
|
3250
|
+
}
|
|
3251
|
+
/**
|
|
3252
|
+
* Updates user-configured custom agent discovery directories.
|
|
3253
|
+
* Empty/whitespace paths are ignored, and if no valid paths remain, the key is deleted
|
|
3254
|
+
* to keep state.json clean.
|
|
3255
|
+
*/
|
|
3256
|
+
async setCustomAgentDirs(dirs) {
|
|
3257
|
+
const cleaned = Array.from(new Set(dirs.map((d) => d.trim()).filter(Boolean)));
|
|
3258
|
+
if (cleaned.length) {
|
|
3259
|
+
this.state.customAgentDirs = cleaned;
|
|
3260
|
+
}
|
|
3261
|
+
else {
|
|
3262
|
+
delete this.state.customAgentDirs;
|
|
3263
|
+
}
|
|
3264
|
+
await this.persist();
|
|
3265
|
+
return structuredClone(cleaned);
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
3268
|
+
* Writes the whole state atomically: a temp file, then a rename over the real one.
|
|
3269
|
+
*
|
|
3270
|
+
* SERIALIZED, because two conversations can genuinely run at once (see workspace-cwd.test.mjs), and
|
|
3271
|
+
* this method was not safe for that: every write used the SAME `${filePath}.tmp`, so two overlapping
|
|
3272
|
+
* persists raced and the loser's rename failed with ENOENT on a file the winner had already moved.
|
|
3273
|
+
* A unique name per write would hide that ENOENT while leaving the real bug in place - whichever rename
|
|
3274
|
+
* landed last would win, and a rename of an OLDER snapshot last would silently discard a newer one.
|
|
3275
|
+
* Queueing keeps both properties: one writer at a time, and last write wins with the newest state.
|
|
3276
|
+
*
|
|
3277
|
+
* A rejected write must not poison the queue, or one failure would reject every later persist as well.
|
|
3278
|
+
*/
|
|
3279
|
+
async flush() { await this.repository.flush(); }
|
|
3280
|
+
/** Releases persistence resources after all accepted writes settle. */
|
|
3281
|
+
async close() { await this.flush(); this.repository.close?.(); }
|
|
3282
|
+
async persistTransaction(transaction) {
|
|
3283
|
+
if (this.repository.commit)
|
|
3284
|
+
await this.repository.commit(transaction);
|
|
3285
|
+
else
|
|
3286
|
+
await this.persist();
|
|
3287
|
+
}
|
|
3288
|
+
async persistCollections(key) {
|
|
3289
|
+
const value = this.state[key];
|
|
3290
|
+
// A collection that is EMPTY is absent from the state, and an absent collection has no row to
|
|
3291
|
+
// write. The row is removed instead, because a repository that can only write rows would have to
|
|
3292
|
+
// store `[]` - which is a different claim from "the user never made one".
|
|
3293
|
+
if (value === undefined) {
|
|
3294
|
+
await this.persistTransaction({ kind: "collections.remove", name: key });
|
|
3295
|
+
return;
|
|
3296
|
+
}
|
|
3297
|
+
await this.persistTransaction({ kind: "collections.replace", values: { [key]: structuredClone(value) } });
|
|
3298
|
+
}
|
|
3299
|
+
async persistMetadata(conversationId) {
|
|
3300
|
+
const { messages: _messages, acceptedSendIds: _receipts, ...metadata } = this.requireConversation(conversationId);
|
|
3301
|
+
await this.persistTransaction({ kind: "conversation.metadata", conversationId, metadata: structuredClone(metadata) });
|
|
3302
|
+
}
|
|
3303
|
+
async persist() { await this.repository.save(this.state); }
|
|
3304
|
+
}
|
|
3305
|
+
export const defaultStorePath = defaultJsonStatePath;
|