@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,2523 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { deriveProjectActivity, deriveTaskActivity } from "../../shared/project-presentation.js";
|
|
3
|
+
import { deliveryCoversTasks, latestProjectDelivery, projectInView } from "../../shared/project-overview.js";
|
|
4
|
+
import { buildTeamHandoff, discoverTeamFiles, parseTeamContext, pathsOverlap, publishTeamContext, teamPaths } from "../team-context.js";
|
|
5
|
+
import { deriveReportingState, deriveSessionState, sessionStateWord, } from "../../shared/session-reporting.js";
|
|
6
|
+
const stamp = () => new Date().toISOString();
|
|
7
|
+
/**
|
|
8
|
+
* WHAT THE PROJECT LEADER IS TOLD WHEN IT STARTS.
|
|
9
|
+
*
|
|
10
|
+
* The two prompts are kept apart on purpose. The standard one is the shape the project flow has
|
|
11
|
+
* always had - decompose, delegate, review. The lightweight one is a different set of
|
|
12
|
+
* instructions about a different shape: one session, no decomposition, no reviewer. Writing one
|
|
13
|
+
* prompt with holes in it would mean every sentence had to carry a condition, and the model would
|
|
14
|
+
* have to work out which shape it was in.
|
|
15
|
+
*
|
|
16
|
+
* THE ESCALATION RULE IS SAID ONCE, IN ONE VOICE. The standard leader used to be told two
|
|
17
|
+
* opposite things about the same event - "your subordinates' escalations come to you first, you
|
|
18
|
+
* decide whether to handle them yourself or report them up" AND "you must not resolve escalations
|
|
19
|
+
* yourself" - and a model reading both has no way to pick, so it hesitates between them. The
|
|
20
|
+
* rule is now one sentence with three parts: handle it at your own level, escalate only what
|
|
21
|
+
* really needs the Boss, and never decide for the Boss or drop an escalation. The lightweight
|
|
22
|
+
* leader has no subordinates at all, so it is told the second half only - it must not decide
|
|
23
|
+
* alone either - and is never told about subordinates it does not have.
|
|
24
|
+
*/
|
|
25
|
+
export const STANDARD_LEADER_PROMPT = "你是负责项目协调的 Leader,负责敏捷开发与小步交付。用户是顶层决策者,你自行处理内部协调,沿汇报线汇总进展、成果与必要决策。开篇上下文已给出项目目标、模式、分工与当前任务清单,不必先调用 project(action=get) 就能直接拆解、派活或推进。小项目只拆最少必要任务,大项目按交付边界分工。用 add_task 登记任务(明确目标、交付物、验收标准、依赖);add_task / update_task 时可以带 executorProfile 与 reviewerProfile(支持指定 agentId、cwd、model、thinkingLevel、watchdogTimeoutSeconds),按任务性质将执行与复核委派给最合适的员工,不指定则继承项目默认;需要继续拆解的工作设 role=leader,叶子执行任务设 role=executor,子 Leader 用 parentTaskId 登记自己的子任务,dispatch 立即启动执行子会话;不要用 session_spawn/session_dispatch 或 task/workflow 绕开项目分工与汇报线。收到交付后用 request_review 启动独立复核。派发后子会话会立即开始执行并在完成后自动回报给你,届时继续派发 ready 任务、复核待验收任务或按 review.summary 返工;不要轮询等待,不要反复无进展重试,等待回报时直接结束当前回复。用 report 登记关键进展。你的下属的升级先到你这里:你在自己这一层处理,能自己解决的自己解决;本层解决不了的问题才用 escalate:有父会话就交给直属父会话,由它判断和转述;只有顶层会话才把确需用户决定的问题交给用户。你不能替 Boss 做决定,也不要把没处理的升级压下去不理。所有任务验收后,用 deliver 记录带证据的阶段交付,后续可继续派发。上下文有限,明确假设,主动寻找反证。只在本次触发范围内工作。";
|
|
26
|
+
export const LIGHTWEIGHT_LEADER_PROMPT = "你是负责项目协调的 Leader,这是一个轻量项目:这个项目由你亲自完成,不要拆子任务、不要派发给别人、也没有独立复核。开篇上下文已给出项目目标、模式与当前任务清单,不必先调用 project(action=get) 就能直接动手。用 add_task 登记任务(明确目标、交付物、验收标准、依赖),任务一律登记为执行任务:role=leader 或带 parentTaskId 都会被拒绝。dispatch 会把任务交回给你自己,你亲自做完;做完后调用 project(action=submit, projectId, taskId, output, evidenceRefs) 提交交付,提交即完成,不会有人回来复核,证据必须附上。不要用 session_spawn/session_dispatch 或 task/workflow 绕开项目职责与汇报线。不要轮询等待,不要反复无进展重试。用 report 汇总关键进展。普通技术决策、阻塞与返工由你自行处理;本层解决不了的事才用 escalate:有父会话就交给直属父会话,由它判断和转述;只有顶层会话才把确需用户决定的问题交给用户,不得替 Boss 决定这些事项。所有任务交付后,用 deliver 记录带证据的阶段交付,后续可继续派发。上下文有限,明确假设,主动寻找反证。只在本次触发范围内工作。";
|
|
27
|
+
const text = (value, label) => {
|
|
28
|
+
if (typeof value !== "string" || !value.trim())
|
|
29
|
+
throw new Error(`${label} 不能为空`);
|
|
30
|
+
if (value.length > 32_000)
|
|
31
|
+
throw new Error(`${label} 过长`);
|
|
32
|
+
return value.trim();
|
|
33
|
+
};
|
|
34
|
+
const optional = (value, label) => value === undefined ? undefined : text(value, label);
|
|
35
|
+
const strings = (value, label) => {
|
|
36
|
+
if (value === undefined || value === null)
|
|
37
|
+
return [];
|
|
38
|
+
if (!Array.isArray(value) || value.length > 100)
|
|
39
|
+
throw new Error(`${label} 必须是最多 100 项的字符串数组`);
|
|
40
|
+
return [...new Set(value.map((item) => text(item, label)))];
|
|
41
|
+
};
|
|
42
|
+
export const profile = (value, label) => {
|
|
43
|
+
if (value === undefined || value === null)
|
|
44
|
+
return undefined;
|
|
45
|
+
if (typeof value !== "object" || Array.isArray(value))
|
|
46
|
+
throw new Error(`${label} 格式不合法`);
|
|
47
|
+
const record = value;
|
|
48
|
+
const result = {};
|
|
49
|
+
let hasValidKey = false;
|
|
50
|
+
if (record.agentId !== undefined) {
|
|
51
|
+
if (typeof record.agentId !== "string" || !record.agentId.trim())
|
|
52
|
+
throw new Error(`${label}.agentId 必须为非空字符串`);
|
|
53
|
+
result.agentId = record.agentId.trim();
|
|
54
|
+
hasValidKey = true;
|
|
55
|
+
}
|
|
56
|
+
if (record.cwd !== undefined) {
|
|
57
|
+
if (typeof record.cwd !== "string")
|
|
58
|
+
throw new Error(`${label}.cwd 必须为字符串`);
|
|
59
|
+
result.cwd = record.cwd.trim();
|
|
60
|
+
hasValidKey = true;
|
|
61
|
+
}
|
|
62
|
+
if (record.model !== undefined) {
|
|
63
|
+
if (typeof record.model !== "object" || !record.model || Array.isArray(record.model)) {
|
|
64
|
+
throw new Error(`${label}.model 必须包含非空的 provider 与 modelId`);
|
|
65
|
+
}
|
|
66
|
+
const m = record.model;
|
|
67
|
+
if (typeof m.provider !== "string" || !m.provider.trim() || typeof m.modelId !== "string" || !m.modelId.trim()) {
|
|
68
|
+
throw new Error(`${label}.model 必须包含非空的 provider 与 modelId`);
|
|
69
|
+
}
|
|
70
|
+
result.model = {
|
|
71
|
+
provider: m.provider.trim(),
|
|
72
|
+
modelId: m.modelId.trim(),
|
|
73
|
+
};
|
|
74
|
+
hasValidKey = true;
|
|
75
|
+
}
|
|
76
|
+
if (record.thinkingLevel !== undefined) {
|
|
77
|
+
if (typeof record.thinkingLevel !== "string")
|
|
78
|
+
throw new Error(`${label}.thinkingLevel 必须为字符串`);
|
|
79
|
+
result.thinkingLevel = record.thinkingLevel.trim();
|
|
80
|
+
hasValidKey = true;
|
|
81
|
+
}
|
|
82
|
+
if (record.watchdogTimeoutSeconds !== undefined) {
|
|
83
|
+
const v = record.watchdogTimeoutSeconds;
|
|
84
|
+
if (typeof v !== "number" || !Number.isSafeInteger(v) || v <= 0) {
|
|
85
|
+
throw new Error(`${label}.watchdogTimeoutSeconds 必须为正整数`);
|
|
86
|
+
}
|
|
87
|
+
result.watchdogTimeoutSeconds = v;
|
|
88
|
+
hasValidKey = true;
|
|
89
|
+
}
|
|
90
|
+
return hasValidKey ? result : undefined;
|
|
91
|
+
};
|
|
92
|
+
export const mergeProfile = (taskProfile, projectDefault) => {
|
|
93
|
+
if (!taskProfile && !projectDefault)
|
|
94
|
+
return undefined;
|
|
95
|
+
const merged = {};
|
|
96
|
+
const agentId = taskProfile?.agentId ?? projectDefault?.agentId;
|
|
97
|
+
const cwd = taskProfile?.cwd ?? projectDefault?.cwd;
|
|
98
|
+
const model = taskProfile?.model ?? projectDefault?.model;
|
|
99
|
+
const thinkingLevel = taskProfile?.thinkingLevel ?? projectDefault?.thinkingLevel;
|
|
100
|
+
const watchdogTimeoutSeconds = taskProfile?.watchdogTimeoutSeconds ?? projectDefault?.watchdogTimeoutSeconds;
|
|
101
|
+
let hasKey = false;
|
|
102
|
+
if (agentId !== undefined) {
|
|
103
|
+
merged.agentId = agentId;
|
|
104
|
+
hasKey = true;
|
|
105
|
+
}
|
|
106
|
+
if (cwd !== undefined) {
|
|
107
|
+
merged.cwd = cwd;
|
|
108
|
+
hasKey = true;
|
|
109
|
+
}
|
|
110
|
+
if (model !== undefined) {
|
|
111
|
+
merged.model = model;
|
|
112
|
+
hasKey = true;
|
|
113
|
+
}
|
|
114
|
+
if (thinkingLevel !== undefined) {
|
|
115
|
+
merged.thinkingLevel = thinkingLevel;
|
|
116
|
+
hasKey = true;
|
|
117
|
+
}
|
|
118
|
+
if (watchdogTimeoutSeconds !== undefined) {
|
|
119
|
+
merged.watchdogTimeoutSeconds = watchdogTimeoutSeconds;
|
|
120
|
+
hasKey = true;
|
|
121
|
+
}
|
|
122
|
+
return hasKey ? merged : undefined;
|
|
123
|
+
};
|
|
124
|
+
const closed = (p) => ["cancelled", "failed"].includes(p.status);
|
|
125
|
+
const busy = (status) => ["running", "waiting", "awaiting_background"].includes(status ?? "");
|
|
126
|
+
const dependenciesComplete = (p, t) => t.dependencies.every((id) => p.tasks.find((candidate) => candidate.id === id)?.status === "completed");
|
|
127
|
+
// Usage accounting uses billing-equivalent tokens so the panel and report match provider bills,
|
|
128
|
+
// alongside the raw 1:1 components. There is no budget cap or admission gate.
|
|
129
|
+
const CACHE_READ_WEIGHT = 0.1;
|
|
130
|
+
const CACHE_WRITE_WEIGHT = 1.25;
|
|
131
|
+
const tokens = (usage) => usage ? Math.round(usage.input + usage.output + usage.cacheWrite * CACHE_WRITE_WEIGHT + usage.cacheRead * CACHE_READ_WEIGHT) : 0;
|
|
132
|
+
/**
|
|
133
|
+
* HOW MANY PROJECTS ONE LIST CALL MAY CARRY.
|
|
134
|
+
*
|
|
135
|
+
* The list goes into an agent's context, and a workspace that has been alive for a year has
|
|
136
|
+
* hundreds of finished projects. Twenty is enough to answer "how are my projects doing" - the
|
|
137
|
+
* running ones and the ones that just finished are all in there - and small enough that the
|
|
138
|
+
* answer does not arrive wrapped in a year of history. The count that was cut is NOT hidden:
|
|
139
|
+
* the list carries the real total next to the truncated one.
|
|
140
|
+
*/
|
|
141
|
+
const PROJECT_LIST_LIMIT = 20;
|
|
142
|
+
/**
|
|
143
|
+
* HOW MANY EVENTS THE REPORT'S TIMELINE PRINTS.
|
|
144
|
+
*
|
|
145
|
+
* A project that ran for weeks has thousands of events, and a timeline that lists all of them
|
|
146
|
+
* is not a document - it is a wall of text nobody reads, and it makes the report too big to
|
|
147
|
+
* paste into a weekly note. So the timeline prints the MOST RECENT 200 events and says, in
|
|
148
|
+
* front of the list, how many there were in total: a reader then knows that the list is the
|
|
149
|
+
* tail of a longer story rather than the whole of it.
|
|
150
|
+
*
|
|
151
|
+
* ONLY THE EVENT STREAM IS CONVERGED. The tasks, the deliveries, the acceptances, the
|
|
152
|
+
* exceptions and the recent reports are the report itself - they are all still printed, one by
|
|
153
|
+
* one, because dropping any of them would drop the answer to "what did this project do".
|
|
154
|
+
*/
|
|
155
|
+
const REPORT_EVENT_LIMIT = 200;
|
|
156
|
+
/**
|
|
157
|
+
* HOW LONG A CELL MAY BE. The table is read down a column, so a cell has to stay short enough to
|
|
158
|
+
* be read without scrolling sideways - and when a cell is cut, the cut says so, because a silent
|
|
159
|
+
* cut reads as the whole truth. The full text is never lost: it is printed below the table.
|
|
160
|
+
*/
|
|
161
|
+
const DECISION_CELL_LIMIT = 40;
|
|
162
|
+
// THE WORDS THE REPORT SPEAKS IN. A reader of the report is a person, not a console, so every
|
|
163
|
+
// state and every role is written the way a person would say it out loud.
|
|
164
|
+
const PROJECT_STATUS_TEXT = {
|
|
165
|
+
planning: "草稿", awaiting_start: "待启动", active: "进行中", blocked: "已阻塞", awaiting_approval: "等待审批",
|
|
166
|
+
awaiting_review: "等待复核", cancelled: "已取消", failed: "失败",
|
|
167
|
+
};
|
|
168
|
+
const TASK_STATUS_TEXT = {
|
|
169
|
+
pending: "等待依赖", ready: "待派发", in_progress: "执行阶段", interrupted: "已中断", blocked: "已阻塞",
|
|
170
|
+
awaiting_review: "待复核", completed: "已完成", failed: "失败", cancelled: "已取消",
|
|
171
|
+
};
|
|
172
|
+
const EVENT_TEXT = {
|
|
173
|
+
created: "创建项目", started: "启动执行", task_created: "登记任务", dispatched: "派发执行",
|
|
174
|
+
submitted: "提交交付", reviewed: "复核", review_requested: "启动复核", task_updated: "任务更新", status: "状态变更",
|
|
175
|
+
budget: "预算变更", report: "进展汇报", escalated: "例外升级", decision: "决定",
|
|
176
|
+
delivery: "阶段交付", completed: "历史交付", ready: "依赖就绪", unreachable: "转述对象不可达",
|
|
177
|
+
// THE REPORT IS READ BY PEOPLE. Every other line of the timeline is printed in Chinese, so the
|
|
178
|
+
// one warning that says "your leader landed on the workspace default agent" must not be the
|
|
179
|
+
// only line a reader meets as an English identifier.
|
|
180
|
+
"leader-profile-missing": "负责人配置缺失",
|
|
181
|
+
};
|
|
182
|
+
const ESCALATION_STATUS_TEXT = { open: "未决", resolved: "已解决", dismissed: "已忽略", returned: "已退回补充材料" };
|
|
183
|
+
const SEVERITY_TEXT = { low: "低", medium: "中", high: "高" };
|
|
184
|
+
const REPORT_KIND_TEXT = {
|
|
185
|
+
progress: "进展", blocked: "阻塞", delivery: "交付", decision_request: "决策请求", review: "复核",
|
|
186
|
+
};
|
|
187
|
+
/** ONE LINE, ONE MEANING: a value that carries newlines must not break the layout of the report. */
|
|
188
|
+
const oneLine = (value) => value.replace(/\r?\n+/g, " ").trim();
|
|
189
|
+
/**
|
|
190
|
+
* A NUMBER A PERSON READS AT A GLANCE, AND THE SAME WAY ON EVERY MACHINE.
|
|
191
|
+
*
|
|
192
|
+
* `toLocaleString` follows the machine's locale, so the same budget is printed as "378,424" in
|
|
193
|
+
* one place and "378424" in another. Two spellings of one number is a number nobody can check
|
|
194
|
+
* against the one on the panel, so the separator is written here instead of asked for.
|
|
195
|
+
*/
|
|
196
|
+
const grouped = (value) => Math.round(value).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
197
|
+
/** A table cell must not carry a pipe of its own, or the row it sits in falls apart. */
|
|
198
|
+
const cell = (value) => oneLine(value).replace(/\|/g, "\\|");
|
|
199
|
+
/** A long delivery is trimmed, and the trim says so - a silent cut would read as the whole truth. */
|
|
200
|
+
const truncate = (value, limit) => value.length > limit ? `${value.slice(0, limit)}…(已截断)` : value;
|
|
201
|
+
/** A timestamp a person can read at a glance, and a missing one that says so. */
|
|
202
|
+
const moment = (value) => value ? value.replace("T", " ").replace(/\.\d+Z$/, "") : "无";
|
|
203
|
+
/**
|
|
204
|
+
* THE FIRST SENTENCE OF A PROSE.
|
|
205
|
+
*
|
|
206
|
+
* The sentence boundary is where a Chinese reader's eye stops, so the first sentence is the part
|
|
207
|
+
* that can stand alone in a table cell. A case with no sentence mark at all is returned whole -
|
|
208
|
+
* there is nothing to cut it at, and cutting it anywhere else would be guessing.
|
|
209
|
+
*/
|
|
210
|
+
const firstSentence = (value) => {
|
|
211
|
+
const text = oneLine(value).trim();
|
|
212
|
+
const index = text.search(/[。!?!?]/);
|
|
213
|
+
if (index < 0)
|
|
214
|
+
return text;
|
|
215
|
+
return text.slice(0, index + 1).trim();
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* THE QUESTION AN EXCEPTION ASKS, in one line.
|
|
219
|
+
*
|
|
220
|
+
* The reader decides on the question, and the case for it is a paragraph - so the table carries
|
|
221
|
+
* the question and the paragraph goes below the table. An exception raised before the title
|
|
222
|
+
* existed falls back to the first sentence of its case, which is the closest thing it has.
|
|
223
|
+
*/
|
|
224
|
+
const exceptionTitle = (exception) => {
|
|
225
|
+
const title = exception.title?.trim();
|
|
226
|
+
if (title)
|
|
227
|
+
return oneLine(title);
|
|
228
|
+
return firstSentence(exception.reason ?? "") || "(未命名)";
|
|
229
|
+
};
|
|
230
|
+
/**
|
|
231
|
+
* THE DECISION IN ONE LINE - OR THE WORD THAT SAYS THERE IS NONE.
|
|
232
|
+
*
|
|
233
|
+
* A decision is the Boss's own words about an exception, and his words are a paragraph: why he
|
|
234
|
+
* decided that, what he accepts, what happens next. The cell in the table is a column to read
|
|
235
|
+
* DOWN, not a paragraph to read - a paragraph in a cell makes the row as tall as the longest
|
|
236
|
+
* case, and a table whose rows are all tall is a list with borders. So the cell carries the FIRST
|
|
237
|
+
* SENTENCE of the decision - the part that stands on its own - and the whole decision is printed
|
|
238
|
+
* below the table, where a paragraph belongs.
|
|
239
|
+
*
|
|
240
|
+
* An exception nobody has answered yet says 「无」, and keeps saying it until somebody answers.
|
|
241
|
+
*/
|
|
242
|
+
const decisionCell = (decision) => {
|
|
243
|
+
const text = (decision ?? "").trim();
|
|
244
|
+
if (!text)
|
|
245
|
+
return "无";
|
|
246
|
+
return truncate(firstSentence(text), DECISION_CELL_LIMIT);
|
|
247
|
+
};
|
|
248
|
+
/**
|
|
249
|
+
* A PROSE, PRINTED AS THE PROSE IS.
|
|
250
|
+
*
|
|
251
|
+
* The complaint this answers: a case that arrived with its line breaks in it was printed as ONE
|
|
252
|
+
* line - the newline was flattened into a space. Not one word was lost, but the SHAPE was: three
|
|
253
|
+
* sentences the writer had deliberately put on three lines came out as one long string, and a
|
|
254
|
+
* reader could no longer see where one thought ended and the next began. That is the "报告文学
|
|
255
|
+
* 有点混乱" the exported report was blamed for.
|
|
256
|
+
*
|
|
257
|
+
* So the line breaks are kept, and they are kept as MARKDOWN line breaks: a blank line in the
|
|
258
|
+
* source stays a blank line - a paragraph of its own - and a single line break inside a paragraph
|
|
259
|
+
* is written as a HARD break (two trailing spaces). A soft break is a space in half the Markdown
|
|
260
|
+
* readers in the world, and this report is read by people.
|
|
261
|
+
*
|
|
262
|
+
* The lines are indented, because they sit inside a list item, and a list item's content that is
|
|
263
|
+
* not indented has already left the item.
|
|
264
|
+
*/
|
|
265
|
+
const proseBlock = (value, indent) => {
|
|
266
|
+
const normalized = value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
267
|
+
const out = [];
|
|
268
|
+
for (const paragraph of normalized.split(/\n{2,}/)) {
|
|
269
|
+
const lines = paragraph.split("\n");
|
|
270
|
+
if (!lines.some((line) => line.trim()))
|
|
271
|
+
continue;
|
|
272
|
+
if (out.length)
|
|
273
|
+
out.push("");
|
|
274
|
+
lines.forEach((line, index) => {
|
|
275
|
+
if (!line.trim()) {
|
|
276
|
+
out.push("");
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
/* THE HARD BREAK goes on the line BEFORE the break, because that is where Markdown looks
|
|
280
|
+
for it: two spaces at the end of a line mean "the next line starts a new line". */
|
|
281
|
+
const next = lines[index + 1];
|
|
282
|
+
const hard = next !== undefined && next.trim() ? " " : "";
|
|
283
|
+
out.push(`${indent}${line.replace(/\s+$/, "")}${hard}`);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
while (out.length && !out[0].trim())
|
|
287
|
+
out.shift();
|
|
288
|
+
return out;
|
|
289
|
+
};
|
|
290
|
+
/**
|
|
291
|
+
* ONE DETAIL ITEM: THE QUESTION ON THE BULLET, THE CASE UNDER IT.
|
|
292
|
+
*
|
|
293
|
+
* The bullet carries the question - one line, the thing the reader decides on - and the case,
|
|
294
|
+
* which is a paragraph, is printed under it with its own paragraphs. The blank line between the
|
|
295
|
+
* two is what makes them two paragraphs instead of one run-on line.
|
|
296
|
+
*
|
|
297
|
+
* AN EXCEPTION WITHOUT A TITLE has no question to put on the bullet, so the case starts on the
|
|
298
|
+
* bullet itself - the way it has always been printed - and the rest of it is indented under it.
|
|
299
|
+
* Nothing is said twice: an exception is not labelled with the first sentence of its own case and
|
|
300
|
+
* then printed with that case all over again.
|
|
301
|
+
*/
|
|
302
|
+
const detailItem = (label, prose) => {
|
|
303
|
+
/* THE NAME IS NOT `body` ON PURPOSE: a local called `body` reads like a read off the request
|
|
304
|
+
body, and the tool-surface gate reads it as one. */
|
|
305
|
+
const block = proseBlock(prose, " ");
|
|
306
|
+
if (label === undefined) {
|
|
307
|
+
if (!block.length)
|
|
308
|
+
return [];
|
|
309
|
+
const [first, ...rest] = block;
|
|
310
|
+
return [`- ${first.replace(/^\s+/, "")}`, ...rest];
|
|
311
|
+
}
|
|
312
|
+
return ["- " + label, "", ...block];
|
|
313
|
+
};
|
|
314
|
+
/**
|
|
315
|
+
* THE TWO SHAPES A PROJECT CAN HAVE.
|
|
316
|
+
*
|
|
317
|
+
* A standard project spends three sessions on every piece of work - the leader, the worker, and
|
|
318
|
+
* the reviewer - and pays two handovers for it. That is the right shape when the work needs an
|
|
319
|
+
* independent check, and it is too expensive for a project with one small task in it: the cost of
|
|
320
|
+
* the project flow then exceeds the cost of the work.
|
|
321
|
+
*
|
|
322
|
+
* A lightweight project collapses the flow to the leader session: it IS the worker, and a
|
|
323
|
+
* delivery is accepted on the executor's own evidence. Mandatory evidence, the escalation path,
|
|
324
|
+
* and the event timeline stay the same.
|
|
325
|
+
*/
|
|
326
|
+
const lightweight = (p) => p.mode === "lightweight";
|
|
327
|
+
/** Persist explicit domain fields only; transport credentials never enter project records. */
|
|
328
|
+
export class ProjectService {
|
|
329
|
+
store;
|
|
330
|
+
orchestrator;
|
|
331
|
+
agents;
|
|
332
|
+
queues = new Map();
|
|
333
|
+
constructor(store, orchestrator,
|
|
334
|
+
/**
|
|
335
|
+
* Optional on purpose: a service built without an agent directory cannot tell a subagent from a
|
|
336
|
+
* custom agent, and it then behaves exactly as it did before this check existed. The real
|
|
337
|
+
* server always passes one.
|
|
338
|
+
*/
|
|
339
|
+
agents) {
|
|
340
|
+
this.store = store;
|
|
341
|
+
this.orchestrator = orchestrator;
|
|
342
|
+
this.agents = agents;
|
|
343
|
+
}
|
|
344
|
+
publishContext(p, value, actor) {
|
|
345
|
+
const inputs = parseTeamContext(value);
|
|
346
|
+
if (!inputs.length)
|
|
347
|
+
return;
|
|
348
|
+
this.member(p, actor);
|
|
349
|
+
const canEdit = (entry) => !actor || actor === entry.authorConversationId || actor === p.ownerConversationId || actor === p.initiatorConversationId
|
|
350
|
+
|| p.tasks.some(task => [task.ownerConversationId, task.reviewerConversationId].includes(entry.authorConversationId)
|
|
351
|
+
&& (task.parentTaskId ? p.tasks.find(parent => parent.id === task.parentTaskId)?.ownerConversationId : p.ownerConversationId) === actor);
|
|
352
|
+
const before = p.contextRevision ?? 0;
|
|
353
|
+
const revisions = new Map((p.sharedContext ?? []).map(entry => [entry.id, entry.revision]));
|
|
354
|
+
const previousRefs = new Map((p.sharedContext ?? []).map(entry => [entry.id, { refs: JSON.stringify(entry.evidenceRefs), cwd: entry.sourceCwd }]));
|
|
355
|
+
publishTeamContext(p, inputs, actor ?? "user", canEdit);
|
|
356
|
+
for (const entry of p.sharedContext ?? [])
|
|
357
|
+
if (entry.revision !== revisions.get(entry.id)) {
|
|
358
|
+
const author = actor ? this.store.conversation(actor) : undefined;
|
|
359
|
+
const previous = previousRefs.get(entry.id);
|
|
360
|
+
entry.sourceCwd = previous?.refs === JSON.stringify(entry.evidenceRefs) ? previous.cwd : author?.cwd;
|
|
361
|
+
if (!revisions.has(entry.id))
|
|
362
|
+
entry.sourceMessageId = author?.messages?.at(-1)?.id;
|
|
363
|
+
entry.updatedFromMessageId = author?.messages?.at(-1)?.id;
|
|
364
|
+
}
|
|
365
|
+
if (before !== (p.contextRevision ?? 0))
|
|
366
|
+
this.event(p, "context_published", `共享上下文更新到第 ${p.contextRevision} 版`, undefined, actor);
|
|
367
|
+
}
|
|
368
|
+
async shareContext(id, value, workspaceId, actor) {
|
|
369
|
+
return this.change(id, workspaceId, p => {
|
|
370
|
+
this.live(p);
|
|
371
|
+
this.publishContext(p, value, actor);
|
|
372
|
+
return { revision: p.contextRevision ?? 0, entries: p.sharedContext ?? [] };
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
async messageTask(id, taskId, content, workspaceId, actor, targetConversationId, deliveryMode = "queue") {
|
|
376
|
+
return this.change(id, workspaceId, async (p) => {
|
|
377
|
+
this.live(p);
|
|
378
|
+
const task = this.task(p, taskId);
|
|
379
|
+
this.manager(p, task, actor);
|
|
380
|
+
if (!["in_progress", "awaiting_review", "blocked", "completed"].includes(task.status))
|
|
381
|
+
throw new Error("补充指令只能发送到已有执行或复核记录的任务;新的交付请登记任务");
|
|
382
|
+
if (!["queue", "steer"].includes(deliveryMode))
|
|
383
|
+
throw new Error("deliveryMode 只能是 queue 或 steer");
|
|
384
|
+
const target = targetConversationId ?? task.ownerConversationId;
|
|
385
|
+
if (!target || ![task.ownerConversationId, task.reviewerConversationId].includes(target))
|
|
386
|
+
throw new Error("补充指令只能发送给本任务已有的执行或复核会话");
|
|
387
|
+
const session = this.store.conversation(target);
|
|
388
|
+
if (!session || session.archivedAt || session.workspaceId !== workspaceId)
|
|
389
|
+
throw new Error("目标会话已归档或不存在");
|
|
390
|
+
if (target === task.ownerConversationId)
|
|
391
|
+
this.assertWriteScope(p, task);
|
|
392
|
+
if (!busy(session.status))
|
|
393
|
+
this.admission(p);
|
|
394
|
+
const result = await this.dispatchContext(target, text(content, "补充指令"), { wait: false, mode: deliveryMode }, task.id);
|
|
395
|
+
this.event(p, "task_message", `向「${task.title}」发送补充指令(${deliveryMode === "steer" ? "下一工具边界" : "排队"}),附带当前共享上下文`, task.id, actor);
|
|
396
|
+
/* THE REPLY IS THE ANSWER. The case was raised against this supervisor, and the supervisor
|
|
397
|
+
has just written to the member - so the case is answered, and the member's session must
|
|
398
|
+
stop saying that it is waiting for a decision. */
|
|
399
|
+
this.settleEscalationsByMessage(p, actor, target, text(content, "补充指令"));
|
|
400
|
+
return result;
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* A SUPERVISOR'S MESSAGE IS THE ANSWER TO THE EXCEPTION - NOT A FORMAL RULING.
|
|
405
|
+
*
|
|
406
|
+
* The reader's complaint was that a session kept saying 「等上面拍板」 long after the question
|
|
407
|
+
* had been settled in a real conversation: the supervisor had talked it through with the member
|
|
408
|
+
* and sent the follow-up instruction, and the platform was still waiting for a ceremony nobody
|
|
409
|
+
* had asked for. Communication is higher than protocol - when the supervisor the case is
|
|
410
|
+
* addressed to writes back to the member who raised it, the case IS answered.
|
|
411
|
+
*
|
|
412
|
+
* TWO THINGS ARE KEPT APART ON PURPOSE.
|
|
413
|
+
* - THE RECORD STAYS. The exception keeps its place in `p.escalations` with the answer, who
|
|
414
|
+
* answered and when. A decision record must not disappear when the project is cancelled.
|
|
415
|
+
* - THE STATE CHANGES. The session no longer says 「等上面拍板」, because nobody is waiting for
|
|
416
|
+
* anything any more: the answer is already on the member's desk.
|
|
417
|
+
*
|
|
418
|
+
* WHAT IS NOT SETTLED HERE, AND WHY:
|
|
419
|
+
* - A BOSS-LEVEL EXCEPTION IS NEVER SETTLED BY A MESSAGE. That case asks the Boss himself, and
|
|
420
|
+
* no team member has the authority to answer it - `resolveEscalation` enforces the very same
|
|
421
|
+
* rule for the panel and the tool, and it must hold for a message too.
|
|
422
|
+
* - A RETURNED EXCEPTION IS NOT REVIVED BY A MESSAGE. A returned case means the member was
|
|
423
|
+
* asked for more material; that material comes back as a NEW exception, not as the old one
|
|
424
|
+
* coming back to life.
|
|
425
|
+
* - ONLY THE DESIGNATED DIRECT SUPERVISOR ANSWERS. `targetConversationId` is the supervisor
|
|
426
|
+
* the case is addressed to, so a message from anybody else is somebody else's business.
|
|
427
|
+
* - AND THE REPLY HAS TO REACH THE MEMBER WHO RAISED IT. A supervisor who writes to somebody
|
|
428
|
+
* else has not answered this case, and settling it would repeat the mistake this project
|
|
429
|
+
* already made once: one answer closing every case of that member at once.
|
|
430
|
+
*/
|
|
431
|
+
settleEscalationsByMessage(p, actor, target, content, existingIds) {
|
|
432
|
+
if (!actor)
|
|
433
|
+
return;
|
|
434
|
+
const answer = truncate(oneLine(content), 200);
|
|
435
|
+
let settled = 0;
|
|
436
|
+
for (const e of p.escalations ?? []) {
|
|
437
|
+
if (existingIds && !existingIds.has(e.id))
|
|
438
|
+
continue;
|
|
439
|
+
if (e.status !== "open")
|
|
440
|
+
continue;
|
|
441
|
+
if ((e.audience ?? "boss") !== "supervisor")
|
|
442
|
+
continue;
|
|
443
|
+
if (e.targetConversationId !== actor)
|
|
444
|
+
continue;
|
|
445
|
+
if (e.requestedByConversationId !== target)
|
|
446
|
+
continue;
|
|
447
|
+
e.status = "resolved";
|
|
448
|
+
e.decision = answer;
|
|
449
|
+
e.resolvedAt = stamp();
|
|
450
|
+
e.resolvedByConversationId = actor;
|
|
451
|
+
this.event(p, "decision", `直接上级已答复例外(ID:${e.id}):${e.decision}`, e.taskId, actor);
|
|
452
|
+
settled += 1;
|
|
453
|
+
}
|
|
454
|
+
if (settled)
|
|
455
|
+
this.reconcile(p);
|
|
456
|
+
}
|
|
457
|
+
getContext(id, workspaceId, actor, taskId, contextIds) {
|
|
458
|
+
const p = id ? this.raw(id, workspaceId) : actor ? this.projectForSession(actor) : undefined;
|
|
459
|
+
if (!p)
|
|
460
|
+
return { notes: "", entries: [], revision: 0 };
|
|
461
|
+
if (p.workspaceId !== workspaceId)
|
|
462
|
+
throw new Error("项目不属于当前工作区");
|
|
463
|
+
this.member(p, actor);
|
|
464
|
+
this.reconcileInterrupted(p);
|
|
465
|
+
const assigned = taskId ? this.task(p, taskId) : actor === p.ownerConversationId ? undefined : p.tasks.filter(item => item.ownerConversationId === actor || item.reviewerConversationId === actor)
|
|
466
|
+
.sort((a, b) => Number(b.status === "in_progress" || b.status === "awaiting_review") - Number(a.status === "in_progress" || a.status === "awaiting_review") || (b.dispatchedAt ?? b.updatedAt).localeCompare(a.dispatchedAt ?? a.updatedAt))[0];
|
|
467
|
+
const task = assigned && actor && assigned.reviewerConversationId === actor ? { ...assigned, readOnly: true, ownedPaths: [] } : assigned;
|
|
468
|
+
if (contextIds !== undefined) {
|
|
469
|
+
if (!Array.isArray(contextIds) || contextIds.length > 32 || contextIds.some(item => typeof item !== "string"))
|
|
470
|
+
throw new Error("contextIds 须为最多 32 项的条目 id 数组");
|
|
471
|
+
return { projectId: p.id, revision: p.contextRevision ?? 0, entries: (p.sharedContext ?? []).filter(entry => contextIds.includes(entry.id)), notes: "" };
|
|
472
|
+
}
|
|
473
|
+
const workspace = this.store.workspace(workspaceId);
|
|
474
|
+
const source = assigned && actor && assigned.reviewerConversationId === actor ? assigned.ownerConversationId
|
|
475
|
+
: task?.parentTaskId ? p.tasks.find(parent => parent.id === task.parentTaskId)?.ownerConversationId : p.ownerConversationId;
|
|
476
|
+
const files = workspace && source ? discoverTeamFiles(this.store.conversation(source), workspace.path) : [];
|
|
477
|
+
const coordination = actor ? this.coordinationHints(p, actor) : [];
|
|
478
|
+
const handoff = buildTeamHandoff(p, task, source, files, actor ? this.store.conversation(actor)?.cwd : undefined, coordination);
|
|
479
|
+
return { projectId: p.id, revision: p.contextRevision ?? 0, ...handoff, coordination, navigationFiles: files };
|
|
480
|
+
}
|
|
481
|
+
coordinationHints(p, actor) {
|
|
482
|
+
if (closed(p))
|
|
483
|
+
return [];
|
|
484
|
+
const direct = p.tasks.filter(task => (task.parentTaskId ? p.tasks.find(parent => parent.id === task.parentTaskId)?.ownerConversationId : p.ownerConversationId) === actor);
|
|
485
|
+
const internal = p.escalations.filter(item => item.status === "open" && item.audience === "supervisor" && item.targetConversationId === actor);
|
|
486
|
+
const hints = internal.map(item => ({ action: "resolve_escalation", escalationId: item.id, taskId: item.taskId, reason: "先判断并处理直属成员的问题;普通技术决策由你解决,不转成用户待办" }));
|
|
487
|
+
for (const task of direct) {
|
|
488
|
+
if (["ready", "interrupted"].includes(task.status))
|
|
489
|
+
hints.push({ action: "dispatch", taskId: task.id, reason: task.status === "interrupted" ? "恢复原任务并派回原会话,先自行处理执行中断" : "已具备执行条件,可直接派发" });
|
|
490
|
+
else if (task.status === "awaiting_review") {
|
|
491
|
+
if (!task.reviewerConversationId)
|
|
492
|
+
hints.push({ action: "request_review", taskId: task.id, reason: "交付已提交,由你安排独立复核,不要求用户调度" });
|
|
493
|
+
else if (["completed", "idle", "failed", "stopped"].includes(this.store.conversation(task.reviewerConversationId)?.status ?? ""))
|
|
494
|
+
hints.push({ action: "message", taskId: task.id, targetConversationId: task.reviewerConversationId, reason: "继续原复核会话并要求给出结论" });
|
|
495
|
+
}
|
|
496
|
+
else if (task.ownerConversationId && (task.status === "in_progress" && ["completed", "idle"].includes(this.store.conversation(task.ownerConversationId)?.status ?? "") || task.status === "blocked" && !internal.some(item => item.taskId === task.id))) {
|
|
497
|
+
hints.push({ action: "message", taskId: task.id, reason: task.status === "blocked" ? "先排查并协调阻塞,给原执行者明确下一步;仅确需用户提供取舍或权限时才上收" : "本轮已结束但尚未交付,继续原会话或要求提交,不等待用户安排" });
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
const required = this.deliveryTasks(p);
|
|
501
|
+
if (actor === p.ownerConversationId && required.length && required.every(task => this.taskAccepted(task))
|
|
502
|
+
&& !deliveryCoversTasks(latestProjectDelivery(p), required) && !p.escalations.some(item => item.status === "open")) {
|
|
503
|
+
hints.push({ action: "deliver", reason: "本阶段必需任务已验收,汇总成果与证据后继续安排工作" });
|
|
504
|
+
}
|
|
505
|
+
return hints;
|
|
506
|
+
}
|
|
507
|
+
assertWriteScope(p, task) {
|
|
508
|
+
if (task.readOnly || !task.ownedPaths?.length)
|
|
509
|
+
return;
|
|
510
|
+
const conflicts = p.tasks.filter(other => other.id !== task.id && !other.readOnly
|
|
511
|
+
&& other.ownerConversationId && busy(this.store.conversation(other.ownerConversationId)?.status)
|
|
512
|
+
&& other.ownedPaths?.some(path => task.ownedPaths.some(own => pathsOverlap(path, own))));
|
|
513
|
+
if (conflicts.length)
|
|
514
|
+
throw new Error(`并行写入范围冲突:${conflicts.map(other => `${other.title}(${other.ownedPaths?.join("、")})`).join(";")}。请调整分工范围或等待这些任务完成;只读任务可并行。`);
|
|
515
|
+
}
|
|
516
|
+
taskCoordination(input) {
|
|
517
|
+
if (input.readOnly !== undefined && typeof input.readOnly !== "boolean")
|
|
518
|
+
throw new Error("readOnly 必须为布尔值");
|
|
519
|
+
if (input.handoffNote !== undefined && (typeof input.handoffNote !== "string" || input.handoffNote.length > 8000))
|
|
520
|
+
throw new Error("handoffNote 须为最多 8000 字符的交接说明");
|
|
521
|
+
return {
|
|
522
|
+
...(input.ownedPaths === undefined ? {} : { ownedPaths: teamPaths(input.ownedPaths) }),
|
|
523
|
+
...(input.readOnly === undefined ? {} : { readOnly: input.readOnly }),
|
|
524
|
+
...(input.handoffNote === undefined ? {} : { handoffNote: input.handoffNote.trim() }),
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
captureHandoff(p, task, source) {
|
|
528
|
+
const workspace = this.store.workspace(p.workspaceId);
|
|
529
|
+
const files = workspace && source ? discoverTeamFiles(this.store.conversation(source), workspace.path) : [];
|
|
530
|
+
task.handoff = buildTeamHandoff(p, task, source, files, this.store.conversation(task.ownerConversationId ?? "")?.cwd);
|
|
531
|
+
}
|
|
532
|
+
async dispatchContext(conversationId, content, options = {}, taskId, receipt) {
|
|
533
|
+
if (!this.orchestrator)
|
|
534
|
+
throw new Error("会话编排服务未就绪");
|
|
535
|
+
const project = this.store.projects().find(p => p.ownerConversationId === conversationId
|
|
536
|
+
|| p.tasks.some(task => task.ownerConversationId === conversationId || task.reviewerConversationId === conversationId));
|
|
537
|
+
if (receipt)
|
|
538
|
+
content += `\n${receipt.notes}`;
|
|
539
|
+
else if (project) {
|
|
540
|
+
const snapshot = this.getContext(project.id, project.workspaceId, conversationId, taskId);
|
|
541
|
+
if (snapshot.notes)
|
|
542
|
+
content += `\n${snapshot.notes}`;
|
|
543
|
+
}
|
|
544
|
+
return this.orchestrator.dispatch(conversationId, content, options);
|
|
545
|
+
}
|
|
546
|
+
syncDeliveryContext(p, task, actor) {
|
|
547
|
+
if (!task.output || !task.evidenceRefs?.length)
|
|
548
|
+
return;
|
|
549
|
+
const current = p.sharedContext?.find(entry => entry.deliveryTaskId === task.id);
|
|
550
|
+
const accepted = this.taskAccepted(task);
|
|
551
|
+
try {
|
|
552
|
+
publishTeamContext(p, [{
|
|
553
|
+
...(current ? { id: current.id, expectedRevision: current.revision } : {}),
|
|
554
|
+
title: `${accepted ? "已验收交付" : "待验证交付"}:${task.title}`.slice(0, 160),
|
|
555
|
+
content: task.output.slice(0, 8000), kind: accepted ? "finding" : "hypothesis", status: "active",
|
|
556
|
+
taskIds: [task.id], paths: task.ownedPaths ?? [], evidenceRefs: task.evidenceRefs,
|
|
557
|
+
}], actor ?? task.ownerConversationId ?? "user", () => true);
|
|
558
|
+
}
|
|
559
|
+
catch (error) {
|
|
560
|
+
if (error instanceof Error && error.message.includes("超过 1 MB")) {
|
|
561
|
+
this.event(p, "context_capacity", "交付已保留,自动共享摘要未写入:请将旧记录整理为文件摘要", task.id, actor);
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
throw error;
|
|
565
|
+
}
|
|
566
|
+
const entry = current ? p.sharedContext?.find(entry => entry.id === current.id) : p.sharedContext?.at(-1);
|
|
567
|
+
if (entry) {
|
|
568
|
+
const owner = this.store.conversation(task.ownerConversationId ?? "");
|
|
569
|
+
entry.deliveryTaskId = task.id;
|
|
570
|
+
entry.sourceCwd = owner?.cwd;
|
|
571
|
+
entry.sourceMessageId ??= owner?.messages?.at(-1)?.id;
|
|
572
|
+
entry.updatedFromMessageId = actor ? this.store.conversation(actor)?.messages?.at(-1)?.id : undefined;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
dispatchReceipt(task) {
|
|
576
|
+
if (!task.handoff)
|
|
577
|
+
return task;
|
|
578
|
+
const { notes: _notes, discoveryFiles: _files, ...handoff } = task.handoff;
|
|
579
|
+
return { ...task, handoff };
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* A PROJECT EMPLOYEE MUST BE A PRIMARY AGENT.
|
|
583
|
+
*
|
|
584
|
+
* §1 says a subagent cannot be a project employee: a subagent is a tool-level, one-shot,
|
|
585
|
+
* invisible call, and a project that leans on one leans on a role the user can never see and
|
|
586
|
+
* never interrupt. The client only offers primary agents in the candidate list, but a candidate
|
|
587
|
+
* list is a SUGGESTION - the server is the constraint, and the refusal belongs at the moment the
|
|
588
|
+
* profile is written, while the reader is still looking at the form. Refusing later (when the
|
|
589
|
+
* task is dispatched) teaches the reader that the panel accepted something the project cannot
|
|
590
|
+
* use.
|
|
591
|
+
*
|
|
592
|
+
* WHAT IS REFUSED, AND WHAT IS NOT. An agent that EXISTS and is a subagent is refused, and the
|
|
593
|
+
* message names the slot and the agent, so the reader knows WHICH employee to change. An id that
|
|
594
|
+
* is in NO directory is a custom agent, and §3 keeps custom agents legal - so it is accepted here,
|
|
595
|
+
* exactly as it was before this check existed.
|
|
596
|
+
*/
|
|
597
|
+
async assertEmployee(profile, label) {
|
|
598
|
+
const agentId = profile?.agentId;
|
|
599
|
+
if (!agentId || !this.agents)
|
|
600
|
+
return;
|
|
601
|
+
const mode = await this.agents.agentModeOf(agentId);
|
|
602
|
+
if (mode === "subagent") {
|
|
603
|
+
throw new Error(`${label}.agentId 指向的是 subagent(${agentId}),项目员工必须是 primary:subagent 是一次性的工具级调用,用户在侧栏看不到它的中间步骤,也插不上话。`);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
static taskView(task, project) {
|
|
607
|
+
const t = { ...task };
|
|
608
|
+
const effectiveExec = mergeProfile(t.executorProfile, project.defaultExecutorProfile);
|
|
609
|
+
if (effectiveExec)
|
|
610
|
+
t.effectiveExecutorProfile = effectiveExec;
|
|
611
|
+
else
|
|
612
|
+
delete t.effectiveExecutorProfile;
|
|
613
|
+
const effectiveRev = mergeProfile(t.reviewerProfile, project.defaultReviewerProfile);
|
|
614
|
+
if (effectiveRev)
|
|
615
|
+
t.effectiveReviewerProfile = effectiveRev;
|
|
616
|
+
else
|
|
617
|
+
delete t.effectiveReviewerProfile;
|
|
618
|
+
return t;
|
|
619
|
+
}
|
|
620
|
+
filterEscalations(escalations, actor) {
|
|
621
|
+
return escalations.filter((e) => {
|
|
622
|
+
const audience = e.audience ?? "boss";
|
|
623
|
+
if (audience === "boss")
|
|
624
|
+
return true;
|
|
625
|
+
if (!actor)
|
|
626
|
+
return false;
|
|
627
|
+
return actor === e.targetConversationId || actor === e.requestedByConversationId;
|
|
628
|
+
});
|
|
629
|
+
}
|
|
630
|
+
projectView(p, actor) {
|
|
631
|
+
/* THE PROJECT IS READ AS IT REALLY IS. The reconciliation runs on the way out, so a task
|
|
632
|
+
whose execution session is gone says 「已中断」 in the payload - the panel, the agent tool
|
|
633
|
+
and the exported report all read the same corrected project, and none of them has to know
|
|
634
|
+
that the correction happened at all. */
|
|
635
|
+
this.reconcileInterrupted(p);
|
|
636
|
+
if (p.status === "awaiting_approval" && !p.escalations.some(item => item.status === "open" && item.severity === "high" && item.audience !== "supervisor"))
|
|
637
|
+
this.reconcile(p);
|
|
638
|
+
const resources = this.resources(p);
|
|
639
|
+
return {
|
|
640
|
+
...p,
|
|
641
|
+
status: this.statusWithInterruptions(p),
|
|
642
|
+
/* THE CLIENT MIRRORS THE VIEW RULE, so it needs the same fact: is the owner session in the
|
|
643
|
+
archive? The server computes it (it is the one that knows), and the client re-applies the
|
|
644
|
+
rule rather than guessing. */
|
|
645
|
+
ownerArchived: this.ownerArchived(p),
|
|
646
|
+
resources,
|
|
647
|
+
activity: deriveProjectActivity({ ...p, status: this.statusWithInterruptions(p), resources }),
|
|
648
|
+
tasks: p.tasks.map((t) => ({ ...ProjectService.taskView(t, p), activity: deriveTaskActivity(t, resources.sessions, p.mode, p.tasks) })),
|
|
649
|
+
escalations: this.filterEscalations(p.escalations ?? [], actor),
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
raw(id, workspaceId) {
|
|
653
|
+
const scope = this.workspace(workspaceId);
|
|
654
|
+
const p = this.store.project(id);
|
|
655
|
+
if (!p || p.workspaceId !== scope)
|
|
656
|
+
throw new Error("项目不存在或不属于当前工作区");
|
|
657
|
+
return p;
|
|
658
|
+
}
|
|
659
|
+
workspace(workspaceId) {
|
|
660
|
+
const value = text(workspaceId, "workspaceId");
|
|
661
|
+
if (!this.store.workspace(value))
|
|
662
|
+
throw new Error("工作区不存在");
|
|
663
|
+
return value;
|
|
664
|
+
}
|
|
665
|
+
event(p, kind, summary, taskId, actorConversationId) {
|
|
666
|
+
p.updatedAt = stamp();
|
|
667
|
+
(p.events ??= []).push({ id: randomUUID(), kind, summary, taskId, actorConversationId, createdAt: p.updatedAt });
|
|
668
|
+
}
|
|
669
|
+
async change(id, workspaceId, work, actor) {
|
|
670
|
+
this.workspace(workspaceId);
|
|
671
|
+
const previous = this.queues.get(id) ?? Promise.resolve();
|
|
672
|
+
const pending = previous.catch(() => { }).then(async () => {
|
|
673
|
+
const p = this.raw(id, workspaceId);
|
|
674
|
+
/* THE PROJECT REPAIRS ITSELF ON THE NEXT WRITE. The reconciliation runs before the work, so
|
|
675
|
+
a write of any kind leaves the record saying 「已中断」 instead of 「执行中」 for a task
|
|
676
|
+
whose execution session is gone - and the event says it happened, so the timeline explains
|
|
677
|
+
the change instead of the status quietly moving under the reader. */
|
|
678
|
+
this.reconcileInterrupted(p, true);
|
|
679
|
+
const result = await work(p);
|
|
680
|
+
for (const t of p.tasks) {
|
|
681
|
+
delete t.effectiveExecutorProfile;
|
|
682
|
+
delete t.effectiveReviewerProfile;
|
|
683
|
+
}
|
|
684
|
+
await this.store.setProject(p);
|
|
685
|
+
if (result && typeof result === "object" && "tasks" in result && Array.isArray(result.tasks)) {
|
|
686
|
+
return structuredClone(this.projectView(result, actor));
|
|
687
|
+
}
|
|
688
|
+
return structuredClone(result);
|
|
689
|
+
});
|
|
690
|
+
this.queues.set(id, pending);
|
|
691
|
+
try {
|
|
692
|
+
return await pending;
|
|
693
|
+
}
|
|
694
|
+
finally {
|
|
695
|
+
if (this.queues.get(id) === pending)
|
|
696
|
+
this.queues.delete(id);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
live(p) { if (closed(p))
|
|
700
|
+
throw new Error("项目已结束,不能继续修改或派发"); }
|
|
701
|
+
/**
|
|
702
|
+
* WAKING THE OTHER SIDE MUST NOT TAKE THE REPORT DOWN WITH IT.
|
|
703
|
+
*
|
|
704
|
+
* The report, the escalation or the decision is already written to the store by the time the
|
|
705
|
+
* other side is woken, so a dispatch that fails - a session that was archived, stopped or never
|
|
706
|
+
* existed - must NOT fail the request. It would: the caller would be told the whole thing
|
|
707
|
+
* failed although it succeeded, it would try again, and the same report would be written twice.
|
|
708
|
+
*
|
|
709
|
+
* So the wake is wrapped, the failure is written down, and the record is returned as the
|
|
710
|
+
* success it is.
|
|
711
|
+
*
|
|
712
|
+
* AND THE FAILURE IS NOT SILENT. A report nobody was told about is a report nobody will ever
|
|
713
|
+
* handle, so the project's own timeline gets an event saying exactly that, and the log line
|
|
714
|
+
* names the project and the escalation so the case can be found again later.
|
|
715
|
+
*/
|
|
716
|
+
async wake(target, prompt, what, projectId, workspaceId, actor) {
|
|
717
|
+
if (!this.orchestrator)
|
|
718
|
+
return;
|
|
719
|
+
try {
|
|
720
|
+
await this.dispatchContext(target, prompt, { wait: false });
|
|
721
|
+
}
|
|
722
|
+
catch (error) {
|
|
723
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
724
|
+
console.warn(`Super Pi: 项目 ${projectId} 的${what}已保存,但叫不醒会话 ${target}:${message}`);
|
|
725
|
+
await this.noteUnreachable(projectId, workspaceId, `${what}已保存,但转述对象会话不可达(${target}):${message}`, actor);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/** THE TIMELINE SAYS THAT NOBODY COULD BE TOLD. Written after the fact, so it never loses the
|
|
729
|
+
* record that was already saved. */
|
|
730
|
+
async noteUnreachable(projectId, workspaceId, summary, actor) {
|
|
731
|
+
if (workspaceId === undefined)
|
|
732
|
+
return;
|
|
733
|
+
try {
|
|
734
|
+
await this.change(projectId, workspaceId, (p) => { this.event(p, "unreachable", summary, undefined, actor); });
|
|
735
|
+
}
|
|
736
|
+
catch (error) {
|
|
737
|
+
console.warn(`Super Pi: 项目 ${projectId} 记录「转述对象不可达」事件失败:${error instanceof Error ? error.message : String(error)}`);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
leader(p, actor) { if (actor && actor !== p.ownerConversationId)
|
|
741
|
+
throw new Error("仅项目负责人可以执行此操作"); }
|
|
742
|
+
/**
|
|
743
|
+
* IS THE SESSION THAT WAS SUPPOSED TO BE RUNNING A TASK STILL THERE?
|
|
744
|
+
*
|
|
745
|
+
* "Still there" means three things, and all three are checked against the SESSION'S OWN RECORD,
|
|
746
|
+
* never against a message the project service was handed:
|
|
747
|
+
*
|
|
748
|
+
* - the record is gone: the session was deleted, or it never existed;
|
|
749
|
+
* - the record says `failed`: the turn died (an unhandled error, or the server was killed
|
|
750
|
+
* mid-turn and the startup sweep marked the record failed);
|
|
751
|
+
* - the record says `stopped`: the session was stopped.
|
|
752
|
+
*
|
|
753
|
+
* WHAT IS NOT "GONE" IS AS IMPORTANT. A session that is `idle` or `completed` is ALIVE: it
|
|
754
|
+
* finished its turn and it can be dispatched again, and in the project flow the leader is woken
|
|
755
|
+
* by exactly that report. Calling an alive session "gone" would light up the whole panel for a
|
|
756
|
+
* worker that is simply between turns.
|
|
757
|
+
*
|
|
758
|
+
* The moment the session died is returned with the verdict, because that moment is what tells a
|
|
759
|
+
* death BEFORE the task was dispatched from a death AFTER it. Only the second one interrupted
|
|
760
|
+
* the task.
|
|
761
|
+
*/
|
|
762
|
+
goneSession(conversationId) {
|
|
763
|
+
if (!conversationId)
|
|
764
|
+
return { gone: false };
|
|
765
|
+
const conversation = this.store.conversation(conversationId);
|
|
766
|
+
if (!conversation)
|
|
767
|
+
return { gone: true, why: "会话记录已经不存在" };
|
|
768
|
+
if (conversation.status === "failed")
|
|
769
|
+
return { gone: true, since: conversation.updatedAt, title: conversation.title, why: "会话已失败", error: conversation.error };
|
|
770
|
+
if (conversation.status === "stopped")
|
|
771
|
+
return { gone: true, since: conversation.updatedAt, title: conversation.title, why: "会话已被停止", error: conversation.error };
|
|
772
|
+
return { gone: false };
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* ONE SENTENCE THAT SAYS WHAT HAPPENED, for the reader of the panel.
|
|
776
|
+
*
|
|
777
|
+
* The session's own failure reason is the most specific thing there is - the startup sweep
|
|
778
|
+
* writes "the server died while this task was running, it has been marked failed" into it - so
|
|
779
|
+
* the first sentence of that reason is used when there is one. Otherwise the verdict alone is
|
|
780
|
+
* said, in the same words the reader has seen everywhere else.
|
|
781
|
+
*/
|
|
782
|
+
interruptedReason(session) {
|
|
783
|
+
const who = session.title ? `执行会话「${session.title}」` : "执行会话";
|
|
784
|
+
/* THE SESSION'S OWN REASON IS THE MOST SPECIFIC THING THERE IS - the startup sweep writes
|
|
785
|
+
"the server died while this task was running, it has been marked failed" into it - so its
|
|
786
|
+
first sentence is used when there is one, with the sentence mark taken off: the reason
|
|
787
|
+
continues after it. */
|
|
788
|
+
const detail = (session.error ? firstSentence(session.error) : "").replace(/[。..!!??]+$/, "");
|
|
789
|
+
const why = detail || session.why || "会话记录已经不存在";
|
|
790
|
+
return `${who}已经不在了(${why}),这个任务不会自己继续了。`;
|
|
791
|
+
}
|
|
792
|
+
/**
|
|
793
|
+
* THE PROJECT IS TOLD THE TRUTH ABOUT ITS OWN TASKS.
|
|
794
|
+
*
|
|
795
|
+
* A task says 「执行中」 only while there is something running for it. When the execution session
|
|
796
|
+
* is gone - the process was killed, the session failed, the session was stopped - the task can
|
|
797
|
+
* never advance on its own, and nobody will ever report back on it. So the task is marked
|
|
798
|
+
* `interrupted`, with the reason attached, and the Boss is handed a way to send it out again.
|
|
799
|
+
*
|
|
800
|
+
* WHY THIS IS DONE WHILE READING, AND NOT WHEN THE SESSION DIES. The runtime could tell the
|
|
801
|
+
* project service that a session ended - but only for the deaths it witnessed. The console was
|
|
802
|
+
* killed by the OS at 05:41 with no shutdown log at all: there was no event to receive, no
|
|
803
|
+
* callback to fire, no chance to be told. Reconciling on READ covers EVERY cause of death -
|
|
804
|
+
* the kill, the network cut, the watchdog, the crash - because it asks the one question that is
|
|
805
|
+
* still answerable afterwards: is the session that was running this task still there?
|
|
806
|
+
*
|
|
807
|
+
* THE DEATH HAS TO HAVE HAPPENED AFTER THE DISPATCH. The moment a task is dispatched, its
|
|
808
|
+
* session is restarted - it goes from `failed` back to `running` a moment later. A task
|
|
809
|
+
* dispatched at T2 while its session died at T1 is a task whose session is on its way back, not
|
|
810
|
+
* a task that was interrupted, so the two moments are compared before the task is marked. The
|
|
811
|
+
* session's own record carries the moment it died; the task carries the moment it was sent out.
|
|
812
|
+
*/
|
|
813
|
+
reconcileInterrupted(p, record = false) {
|
|
814
|
+
for (const t of p.tasks) {
|
|
815
|
+
if (t.status !== "in_progress")
|
|
816
|
+
continue;
|
|
817
|
+
const session = this.goneSession(t.ownerConversationId);
|
|
818
|
+
if (!session.gone)
|
|
819
|
+
continue;
|
|
820
|
+
const dispatchedAt = t.dispatchedAt ?? t.updatedAt;
|
|
821
|
+
if (session.since && dispatchedAt && Date.parse(session.since) < Date.parse(dispatchedAt))
|
|
822
|
+
continue;
|
|
823
|
+
t.status = "interrupted";
|
|
824
|
+
t.interruptedReason = this.interruptedReason(session);
|
|
825
|
+
t.updatedAt = stamp();
|
|
826
|
+
if (record)
|
|
827
|
+
this.event(p, "task_updated", `执行会话已中断:${t.title}`, t.id);
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* THE STATUS A PROJECT SHOWS WHEN ONE OF ITS TASKS HAS BEEN INTERRUPTED.
|
|
832
|
+
*
|
|
833
|
+
* A project with an interrupted task is not "running": the work that is not finished there is
|
|
834
|
+
* work nobody is doing, and it will stay that way until somebody restarts it. So the project
|
|
835
|
+
* says 「已阻塞」 - the word the panel already uses for "this needs a decision from you" - instead
|
|
836
|
+
* of 「执行中」, which would be a claim that something is running.
|
|
837
|
+
*
|
|
838
|
+
* Only a project that says 「执行中」 is moved: a project that has already been closed, or that is
|
|
839
|
+
* waiting for a review, is saying something else and stays truthful.
|
|
840
|
+
*/
|
|
841
|
+
statusWithInterruptions(p) {
|
|
842
|
+
if (p.status === "active" && p.tasks.some((t) => t.status === "interrupted"))
|
|
843
|
+
return "blocked";
|
|
844
|
+
return p.status;
|
|
845
|
+
}
|
|
846
|
+
topLevelAuthor(p, actor) {
|
|
847
|
+
if (!actor)
|
|
848
|
+
return;
|
|
849
|
+
if (actor === p.ownerConversationId)
|
|
850
|
+
return;
|
|
851
|
+
if (actor === p.initiatorConversationId)
|
|
852
|
+
return;
|
|
853
|
+
throw new Error("只有项目负责人或发起人可以登记顶层任务");
|
|
854
|
+
}
|
|
855
|
+
manager(p, t, actor) {
|
|
856
|
+
const manager = t.parentTaskId ? this.task(p, t.parentTaskId).ownerConversationId : p.ownerConversationId;
|
|
857
|
+
if (actor && actor !== manager)
|
|
858
|
+
throw new Error("仅直属 Leader 可以管理此任务");
|
|
859
|
+
return manager;
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* DOES THIS TASK COUNT AS ACCEPTED?
|
|
863
|
+
*
|
|
864
|
+
* In a STANDARD project, acceptance means another session reviewed this delivery: the reviewer
|
|
865
|
+
* of the review must be the session that was spawned to review, and it must NOT be the session
|
|
866
|
+
* that did the work. Those conditions are the whole point of an independent review, so they
|
|
867
|
+
* stand exactly as they were.
|
|
868
|
+
*
|
|
869
|
+
* In a LIGHTWEIGHT project there is no reviewer session at all - the leader session does the
|
|
870
|
+
* work itself - so a delivery is accepted on the executor's own evidence. The flag that says so
|
|
871
|
+
* is written by `submit` and nowhere else, and it names the session that made the call, so a
|
|
872
|
+
* task with no accepted review at all still counts for nothing.
|
|
873
|
+
*/
|
|
874
|
+
taskAccepted(t) {
|
|
875
|
+
if (t.status !== "completed")
|
|
876
|
+
return false;
|
|
877
|
+
if (t.review?.lightweight === true)
|
|
878
|
+
return Boolean(t.review.reviewerConversationId);
|
|
879
|
+
return t.review?.verdict === "accepted" && t.review.reviewerConversationId === t.reviewerConversationId
|
|
880
|
+
&& Boolean(t.reviewerConversationId) && t.reviewerConversationId !== t.ownerConversationId;
|
|
881
|
+
}
|
|
882
|
+
requiredComplete(p, parentTaskId) {
|
|
883
|
+
const required = p.tasks.filter((t) => t.parentTaskId === parentTaskId && (t.status !== "cancelled" || !t.blockedReason));
|
|
884
|
+
return required.length > 0 && required.every((t) => this.taskAccepted(t));
|
|
885
|
+
}
|
|
886
|
+
task(p, taskId) {
|
|
887
|
+
const t = p.tasks.find((item) => item.id === taskId);
|
|
888
|
+
if (!t)
|
|
889
|
+
throw new Error("任务不存在");
|
|
890
|
+
return t;
|
|
891
|
+
}
|
|
892
|
+
member(p, actor) {
|
|
893
|
+
if (actor && actor !== p.ownerConversationId && actor !== p.initiatorConversationId && !p.tasks.some((t) => t.ownerConversationId === actor || t.reviewerConversationId === actor))
|
|
894
|
+
throw new Error("调用会话不属于项目执行团队");
|
|
895
|
+
}
|
|
896
|
+
canAddressUser(p, actor) {
|
|
897
|
+
return !actor || ((actor === p.ownerConversationId || actor === p.initiatorConversationId)
|
|
898
|
+
&& !this.store.conversation(actor)?.parentConversationId);
|
|
899
|
+
}
|
|
900
|
+
isMember(p, actor) {
|
|
901
|
+
if (!actor)
|
|
902
|
+
return false;
|
|
903
|
+
if (actor === p.initiatorConversationId)
|
|
904
|
+
return true;
|
|
905
|
+
if (actor === p.ownerConversationId)
|
|
906
|
+
return true;
|
|
907
|
+
if (p.tasks?.some((t) => t.ownerConversationId === actor || t.reviewerConversationId === actor))
|
|
908
|
+
return true;
|
|
909
|
+
if (this.projectForSession(actor)?.id === p.id)
|
|
910
|
+
return true;
|
|
911
|
+
return false;
|
|
912
|
+
}
|
|
913
|
+
directSupervisor(p, actor, taskId) {
|
|
914
|
+
if (!actor)
|
|
915
|
+
return undefined;
|
|
916
|
+
const session = this.store.conversation(actor);
|
|
917
|
+
const parent = session?.parentConversationId ? this.store.conversation(session.parentConversationId) : undefined;
|
|
918
|
+
if (parent && !parent.archivedAt && parent.workspaceId === p.workspaceId && this.isMember(p, parent.id))
|
|
919
|
+
return parent.id;
|
|
920
|
+
if (actor === p.ownerConversationId || actor === p.initiatorConversationId)
|
|
921
|
+
return undefined;
|
|
922
|
+
const assigned = p.tasks.filter(item => item.ownerConversationId === actor || item.reviewerConversationId === actor);
|
|
923
|
+
const t = assigned.find(item => item.id === taskId) ?? assigned[0];
|
|
924
|
+
const manager = t ? this.manager(p, t) : undefined;
|
|
925
|
+
if (manager && this.isMember(p, manager))
|
|
926
|
+
return manager;
|
|
927
|
+
return undefined;
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* THE PROJECT A SESSION BELONGS TO RIGHT NOW.
|
|
931
|
+
*
|
|
932
|
+
* `projectForSession` answers a different question - "which project is this session part of" -
|
|
933
|
+
* and it counts the finished projects too, because the history of a project has to stay visible
|
|
934
|
+
* to the people who worked on it. This method answers the narrower question the QUESTION path
|
|
935
|
+
* needs: "is this session inside a project that is still running".
|
|
936
|
+
*
|
|
937
|
+
* WHY THAT DISTINCTION MATTERS. A conversation that took part in a project which has since been
|
|
938
|
+
* completed is not a project member any more - it is a conversation that happens to have a
|
|
939
|
+
* finished project in its history. The old lookup mixed the two, so asking the Boss a question
|
|
940
|
+
* from such a conversation was refused with "a project member may not ask the Boss directly",
|
|
941
|
+
* which is not what was true: the project was over, and nobody was being bypassed. The finished
|
|
942
|
+
* project is still found and still visible in the history; it just does not block the question.
|
|
943
|
+
*
|
|
944
|
+
* A session that is in a running project AND in a finished one belongs to the running one - it
|
|
945
|
+
* is the one that is still in charge of it.
|
|
946
|
+
*/
|
|
947
|
+
liveProjectForSession(conversationId) {
|
|
948
|
+
let c = this.store.conversation(conversationId);
|
|
949
|
+
const seen = new Set();
|
|
950
|
+
while (c && !seen.has(c.id)) {
|
|
951
|
+
seen.add(c.id);
|
|
952
|
+
const projects = this.store.projects().filter((p) => p.workspaceId === c.workspaceId
|
|
953
|
+
&& (p.ownerConversationId === c.id || p.tasks.some((t) => t.ownerConversationId === c.id || t.reviewerConversationId === c.id)));
|
|
954
|
+
const live = projects.find((p) => !closed(p));
|
|
955
|
+
if (live)
|
|
956
|
+
return live;
|
|
957
|
+
c = c.parentConversationId ? this.store.conversation(c.parentConversationId) : undefined;
|
|
958
|
+
}
|
|
959
|
+
return undefined;
|
|
960
|
+
}
|
|
961
|
+
canAskQuestion(conversationId) {
|
|
962
|
+
const project = this.liveProjectForSession(conversationId);
|
|
963
|
+
if (!project)
|
|
964
|
+
return { ok: true };
|
|
965
|
+
if (this.canAddressUser(project, conversationId))
|
|
966
|
+
return { ok: true };
|
|
967
|
+
return {
|
|
968
|
+
ok: false,
|
|
969
|
+
reason: "项目成员不能直接向 Boss 提问:请通过直接上级上报,由负责人代为转述",
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
reconcile(p) {
|
|
973
|
+
if (closed(p))
|
|
974
|
+
return;
|
|
975
|
+
for (const t of p.tasks)
|
|
976
|
+
if (t.status === "pending" && dependenciesComplete(p, t)) {
|
|
977
|
+
t.status = "ready";
|
|
978
|
+
t.updatedAt = stamp();
|
|
979
|
+
this.event(p, "ready", `前置交付已验收:${t.title}`, t.id);
|
|
980
|
+
}
|
|
981
|
+
const openBoss = p.escalations.filter((e) => e.status === "open" && (e.audience === "boss" || !e.audience));
|
|
982
|
+
const hasLeaderBlockedTask = p.tasks.some((t) => t.status === "blocked" && this.canAddressUser(p, t.blockedReportedByConversationId));
|
|
983
|
+
const lastLeaderProjectReport = [...p.reports].reverse().find((r) => !r.taskId && this.canAddressUser(p, r.authorConversationId));
|
|
984
|
+
const leaderProjectBlocked = lastLeaderProjectReport?.kind === "blocked";
|
|
985
|
+
/* AN INTERRUPTED TASK BLOCKS THE PROJECT. Its execution session is gone, so nobody is working
|
|
986
|
+
on it and nobody will report back on it: the project is not "running", it is waiting for a
|
|
987
|
+
person to put that task back out. Saying 「执行中」 here would be the same lie one level up
|
|
988
|
+
from the task row - the row says 「已中断」 and the card says 「执行中」, and the reader has
|
|
989
|
+
no way to tell which one to believe. */
|
|
990
|
+
const hasInterruptedTask = p.tasks.some((t) => t.status === "interrupted");
|
|
991
|
+
const openRequesters = new Set((p.escalations ?? [])
|
|
992
|
+
.filter((e) => e.status === "open" && e.requestedByConversationId)
|
|
993
|
+
.map((e) => e.requestedByConversationId));
|
|
994
|
+
const memberIds = new Set([
|
|
995
|
+
p.ownerConversationId,
|
|
996
|
+
...p.tasks.flatMap((t) => [t.ownerConversationId, t.reviewerConversationId]),
|
|
997
|
+
...(p.escalations ?? []).map((e) => e.requestedByConversationId),
|
|
998
|
+
].filter(Boolean));
|
|
999
|
+
for (const memberId of memberIds) {
|
|
1000
|
+
const conv = this.store.conversation(memberId);
|
|
1001
|
+
if (conv) {
|
|
1002
|
+
conv.hasOpenEscalation = openRequesters.has(memberId);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
/* A PROJECT THAT HAS WORK REGISTERED BUT NO LEADER SESSION YET IS NOT RUNNING.
|
|
1006
|
+
"active" used to mean "there is at least one task", so a project whose tasks were only
|
|
1007
|
+
REGISTERED - nobody had started it, nobody was working on it - claimed on its card to be
|
|
1008
|
+
running while the panel's own team section said there were no sessions at all. The card
|
|
1009
|
+
and the team list contradicted each other, and the card was the one that lied: the
|
|
1010
|
+
project's own status has to say what is true about the project, not what the client
|
|
1011
|
+
happens to translate it into. So the state is split:
|
|
1012
|
+
planning - nothing has been broken down yet,
|
|
1013
|
+
awaiting_start - the work is registered and the project has NOT been started,
|
|
1014
|
+
active - the project is started and a leader session exists.
|
|
1015
|
+
A project has a leader session only after `start`, so the leader is the signal - not the
|
|
1016
|
+
task count, and not anything the client sends. */
|
|
1017
|
+
p.status = openBoss.some((e) => e.severity === "high") ? "awaiting_approval"
|
|
1018
|
+
: openBoss.length || hasLeaderBlockedTask || leaderProjectBlocked || hasInterruptedTask ? "blocked"
|
|
1019
|
+
: p.tasks.some((t) => t.status === "awaiting_review") ? "awaiting_review"
|
|
1020
|
+
: p.tasks.length ? (p.ownerConversationId ? "active" : "awaiting_start") : "planning";
|
|
1021
|
+
}
|
|
1022
|
+
resources(p) {
|
|
1023
|
+
const state = this.store.snapshot();
|
|
1024
|
+
const members = new Set([p.ownerConversationId, ...p.tasks.flatMap((t) => [t.ownerConversationId, t.reviewerConversationId])].filter(Boolean));
|
|
1025
|
+
for (let changed = true; changed;) {
|
|
1026
|
+
changed = false;
|
|
1027
|
+
for (const c of state.conversations)
|
|
1028
|
+
if (c.workspaceId === p.workspaceId && c.parentConversationId && members.has(c.parentConversationId) && !members.has(c.id)) {
|
|
1029
|
+
members.add(c.id);
|
|
1030
|
+
changed = true;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
const coordinatorIds = new Set([p.ownerConversationId, ...p.tasks.filter((t) => t.role === "leader").map((t) => t.ownerConversationId)].filter(Boolean));
|
|
1034
|
+
/* THE MEMORY TREE OF THE PROJECT, AND OF EVERY SESSION IN IT.
|
|
1035
|
+
*
|
|
1036
|
+
* Since 0.1.161 a project opens its OWN memory tree: the leader session is the root of it and
|
|
1037
|
+
* the workers inherit it, so the project's memories never mix with the Boss's chat. That is
|
|
1038
|
+
* invisible from the outside - the client draws a tree of sessions and cannot tell which
|
|
1039
|
+
* memories are behind it. So the server says it outright: the tree each session belongs to,
|
|
1040
|
+
* and whether that tree is the project's own ("project") or the one it shares with the
|
|
1041
|
+
* initiator's conversation ("shared"). The leader is the root of the project's tree, so it is
|
|
1042
|
+
* "project" by the same rule as everybody else - there is no special case for it. */
|
|
1043
|
+
const projectTreeId = p.ownerConversationId ? this.store.conversation(p.ownerConversationId)?.treeId : undefined;
|
|
1044
|
+
const memberConversations = state.conversations.filter((c) => c.workspaceId === p.workspaceId && members.has(c.id));
|
|
1045
|
+
// Match the sidebar's archive marker without removing historical usage.
|
|
1046
|
+
const visibleMemberConversations = memberConversations.filter((c) => !c.archivedAt);
|
|
1047
|
+
const openEscalationRequesters = new Set((p.escalations ?? [])
|
|
1048
|
+
.filter((e) => e.status === "open" && e.requestedByConversationId)
|
|
1049
|
+
.map((e) => e.requestedByConversationId));
|
|
1050
|
+
const snapshotMap = new Map();
|
|
1051
|
+
for (const c of visibleMemberConversations) {
|
|
1052
|
+
snapshotMap.set(c.id, {
|
|
1053
|
+
id: c.id,
|
|
1054
|
+
parentConversationId: c.parentConversationId,
|
|
1055
|
+
status: c.status,
|
|
1056
|
+
reportedToParentAt: c.reportedToParentAt,
|
|
1057
|
+
archivedAt: c.archivedAt,
|
|
1058
|
+
hasOpenEscalation: openEscalationRequesters.has(c.id),
|
|
1059
|
+
...(c.hasPendingResult ? { hasPendingResult: true } : {}),
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
const sessions = visibleMemberConversations.map((c) => {
|
|
1063
|
+
const parent = c.parentConversationId ? this.store.conversation(c.parentConversationId) : undefined;
|
|
1064
|
+
const directChildren = visibleMemberConversations
|
|
1065
|
+
.filter((child) => child.parentConversationId === c.id)
|
|
1066
|
+
.map((child) => snapshotMap.get(child.id));
|
|
1067
|
+
const snapshot = snapshotMap.get(c.id);
|
|
1068
|
+
const reportingState = deriveReportingState({
|
|
1069
|
+
conversation: snapshot,
|
|
1070
|
+
parent,
|
|
1071
|
+
directChildren,
|
|
1072
|
+
isTopLevelUnread: false,
|
|
1073
|
+
});
|
|
1074
|
+
const displayStatus = deriveSessionState({
|
|
1075
|
+
status: c.status,
|
|
1076
|
+
reportingState,
|
|
1077
|
+
});
|
|
1078
|
+
const displayWord = sessionStateWord(displayStatus);
|
|
1079
|
+
return {
|
|
1080
|
+
id: c.id,
|
|
1081
|
+
title: c.title,
|
|
1082
|
+
status: c.status,
|
|
1083
|
+
displayStatus,
|
|
1084
|
+
displayWord,
|
|
1085
|
+
reportingState,
|
|
1086
|
+
hasOpenEscalation: snapshot.hasOpenEscalation,
|
|
1087
|
+
reportedToParentAt: c.reportedToParentAt,
|
|
1088
|
+
tokens: tokens(c.usage),
|
|
1089
|
+
contextPercent: c.contextUsage?.percent,
|
|
1090
|
+
// THE TREE SKELETON. The client draws the agents of a project as a tree, and the only
|
|
1091
|
+
// thing that knows who spawned whom is the conversation's own parent link. It is sent
|
|
1092
|
+
// verbatim (including the undefined case, which means "this session has no parent in
|
|
1093
|
+
// this collection" - i.e. it is a root of the tree).
|
|
1094
|
+
parentConversationId: c.parentConversationId,
|
|
1095
|
+
// WHOSE MEMORY THIS SESSION WORKS FROM. The project's own tree is the one the leader
|
|
1096
|
+
// opened; anything else is a session that still shares the initiator's chat memory.
|
|
1097
|
+
memoryTreeId: c.treeId,
|
|
1098
|
+
cwd: c.cwd,
|
|
1099
|
+
memoryScope: projectTreeId && c.treeId === projectTreeId ? "project" : "shared",
|
|
1100
|
+
role: c.id === p.ownerConversationId ? "项目负责人" : coordinatorIds.has(c.id) ? "分支 Leader" : p.tasks.some((t) => t.reviewerConversationId === c.id) ? "独立复核" : "执行者",
|
|
1101
|
+
};
|
|
1102
|
+
});
|
|
1103
|
+
const runs = state.subagentRuns.filter((r) => members.has(r.conversationId));
|
|
1104
|
+
/* A COORDINATOR IS NOT A WORKER - EXCEPT IN A LIGHTWEIGHT PROJECT, WHERE THE LEADER IS THE
|
|
1105
|
+
WORKER. There the leader session does the work itself, so a project that is running must not
|
|
1106
|
+
report zero running agents. The concurrency guard is not touched by this: the in-flight task
|
|
1107
|
+
it counts (`reserved`) already covers the busy leader, so the cap behaves exactly as before. */
|
|
1108
|
+
const leaderIsWorker = lightweight(p) && p.ownerConversationId !== undefined;
|
|
1109
|
+
/* ONE ACCOUNTING PATH, AND IT IS THE SESSION TREE.
|
|
1110
|
+
The number below is the sum of the member sessions' usage, and NOTHING ELSE. A one-shot call
|
|
1111
|
+
(a sub-agent) used to be added here from the run records on top of that sum, which was a
|
|
1112
|
+
SECOND path to the same money: the run's usage was already inside the conversation's usage
|
|
1113
|
+
(the store folds it in when the run settles), so the same tokens were counted twice.
|
|
1114
|
+
Now it is counted once - through the session - and a project's budget therefore includes what
|
|
1115
|
+
its one-shot calls cost, which is the whole point of a budget a person can predict.
|
|
1116
|
+
See `Store.accountSubagentUsage`. */
|
|
1117
|
+
/* THE SAME USAGE, TWICE: ONCE IN THE BILLING-EQUIVALENT UNITS THE BUDGET IS SPENT IN, AND
|
|
1118
|
+
ONCE IN THE RAW 1:1 UNITS THE READER'S OWN TOOLING COUNTS IN.
|
|
1119
|
+
The panel used to show only the equivalent number, and the two differ by a factor of
|
|
1120
|
+
two and a half on a real run - so a reader who compared the project's cost with their
|
|
1121
|
+
own dashboard saw two different numbers and no way to tell which one the panel meant.
|
|
1122
|
+
So the raw components are sent as well: 输入 + 输出 + 缓存写入 + 缓存读取, which the reader
|
|
1123
|
+
can add up, and can also feed into the published formula themselves.
|
|
1124
|
+
The equivalent number is computed from the SUMMED components and rounded ONCE, not by
|
|
1125
|
+
adding up each session's own rounded number: that way the formula printed next to the
|
|
1126
|
+
number reproduces the number exactly, instead of being off by a token per session. */
|
|
1127
|
+
const usage = memberConversations.reduce((acc, c) => {
|
|
1128
|
+
if (!c.usage)
|
|
1129
|
+
return acc;
|
|
1130
|
+
acc.input += c.usage.input;
|
|
1131
|
+
acc.output += c.usage.output;
|
|
1132
|
+
acc.cacheRead += c.usage.cacheRead;
|
|
1133
|
+
acc.cacheWrite += c.usage.cacheWrite;
|
|
1134
|
+
return acc;
|
|
1135
|
+
}, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 });
|
|
1136
|
+
return { tokens: tokens(usage),
|
|
1137
|
+
usageKnown: memberConversations.length > 0 && memberConversations.every((c) => Boolean(c.usage)) && runs.every((r) => Boolean(r.usage)),
|
|
1138
|
+
activeWorkers: sessions.filter((s) => (!coordinatorIds.has(s.id) || (leaderIsWorker && s.id === p.ownerConversationId)) && busy(s.status)).length + runs.filter((r) => r.status === "running" && visibleMemberConversations.some((c) => c.id === r.conversationId)).length,
|
|
1139
|
+
// THE PROJECT'S OWN MEMORY TREE, named once so the client does not have to infer it from
|
|
1140
|
+
// the sessions. Absent only when the project has no leader session yet.
|
|
1141
|
+
memoryTreeId: projectTreeId, sessions,
|
|
1142
|
+
// Evidence keeps its original base directory even when the owner is archived.
|
|
1143
|
+
ownerCwd: memberConversations.find((c) => c.id === p.ownerConversationId)?.cwd,
|
|
1144
|
+
// THE RAW 1:1 PICTURE OF THE SAME MONEY, next to the equivalent number it is spent in.
|
|
1145
|
+
usage, rawTokens: usage.input + usage.output + usage.cacheRead + usage.cacheWrite };
|
|
1146
|
+
}
|
|
1147
|
+
list(workspaceId, view = "current") {
|
|
1148
|
+
const scope = this.workspace(workspaceId);
|
|
1149
|
+
return this.store.projects()
|
|
1150
|
+
.filter((p) => p.workspaceId === scope && projectInView(p, this.ownerArchived(p), view))
|
|
1151
|
+
.map((p) => this.projectView(p));
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* IS THE OWNER SESSION IN THE ARCHIVE? A project whose leader was archived has nobody left to
|
|
1155
|
+
* run it. The server is the one that knows what is archived, so it computes the answer and
|
|
1156
|
+
* hands the client the same fact in the project payload (`ownerArchived`).
|
|
1157
|
+
*/
|
|
1158
|
+
ownerArchived(p) {
|
|
1159
|
+
if (!p.ownerConversationId)
|
|
1160
|
+
return false;
|
|
1161
|
+
return Boolean(this.store.conversation(p.ownerConversationId)?.archivedAt);
|
|
1162
|
+
}
|
|
1163
|
+
headline(p, actor, resources) {
|
|
1164
|
+
const total = p.tasks.length;
|
|
1165
|
+
const completed = p.tasks.filter((t) => t.status === "completed").length;
|
|
1166
|
+
if (p.status === "cancelled")
|
|
1167
|
+
return "项目已取消";
|
|
1168
|
+
if (p.status === "failed")
|
|
1169
|
+
return "项目失败";
|
|
1170
|
+
const visibleEscalations = this.filterEscalations(p.escalations ?? [], actor);
|
|
1171
|
+
const openEscalation = visibleEscalations.find((e) => e.status === "open");
|
|
1172
|
+
if (openEscalation) {
|
|
1173
|
+
return (openEscalation.audience === "boss" || !openEscalation.audience) && p.status === "awaiting_approval"
|
|
1174
|
+
? `等待审批:${openEscalation.reason}`
|
|
1175
|
+
: `项目已阻塞:${openEscalation.reason}`;
|
|
1176
|
+
}
|
|
1177
|
+
const blockedTask = p.tasks.find((t) => t.status === "blocked");
|
|
1178
|
+
if (blockedTask && p.status === "blocked") {
|
|
1179
|
+
const reason = blockedTask.blockedReason ? `(${blockedTask.blockedReason})` : "";
|
|
1180
|
+
return `项目已阻塞:${blockedTask.title}${reason}`;
|
|
1181
|
+
}
|
|
1182
|
+
/* THE WORK IS REGISTERED AND THE PROJECT HAS NOT BEEN STARTED. The task is "ready to
|
|
1183
|
+
dispatch", but dispatching needs a leader and there is no leader until the project is
|
|
1184
|
+
started - so "waiting to dispatch" would point the reader at something nobody can do.
|
|
1185
|
+
The headline says what is true, in the same words the card uses. */
|
|
1186
|
+
if (total > 0 && !p.ownerConversationId)
|
|
1187
|
+
return `已登记 ${total} 个任务,项目待启动`;
|
|
1188
|
+
/* A TASK WHOSE EXECUTION SESSION IS GONE. Nothing is running for it and nobody will report
|
|
1189
|
+
back on it, so the headline must not say 「正在执行」 - the reader would wait for a turn that
|
|
1190
|
+
is never coming. It says the task is interrupted and needs to be put back out. */
|
|
1191
|
+
const interruptedTask = p.tasks.find((t) => t.status === "interrupted");
|
|
1192
|
+
if (interruptedTask) {
|
|
1193
|
+
return `${completed}/${total} 任务完成,${interruptedTask.title} 已中断(执行会话不在了),等待恢复`;
|
|
1194
|
+
}
|
|
1195
|
+
const sessions = this.activitySessions(p);
|
|
1196
|
+
const current = deriveProjectActivity({ ...p, resources: resources ?? this.resources(p) });
|
|
1197
|
+
const task = p.tasks.find(item => deriveTaskActivity(item, sessions, p.mode, p.tasks).kind === current.kind) ?? blockedTask;
|
|
1198
|
+
const label = current.kind === "executing" ? "正在执行" : current.kind === "reviewing" ? "正在复核" : current.label;
|
|
1199
|
+
return total > 0 ? `${completed}/${total} 任务完成,${label}${task ? `:${task.title}` : ""}` : "项目规划中,尚未拆解任务";
|
|
1200
|
+
}
|
|
1201
|
+
activitySessions(p) {
|
|
1202
|
+
const ids = new Set([p.ownerConversationId, ...p.tasks.flatMap(task => [task.ownerConversationId, task.reviewerConversationId])].filter(Boolean));
|
|
1203
|
+
return [...ids].flatMap(id => { const session = this.store.conversation(id); return session && !session.archivedAt ? [{ id, status: session.status }] : []; });
|
|
1204
|
+
}
|
|
1205
|
+
isActorRelated(p, actor) {
|
|
1206
|
+
return this.isMember(p, actor);
|
|
1207
|
+
}
|
|
1208
|
+
projectSummary(p, actor) {
|
|
1209
|
+
/* THE AGENT'S OWN LIST IS CORRECTED TOO. An agent that reads 「执行中」 for a task whose
|
|
1210
|
+
session is gone will wait for a report that is never coming, and it has no way to tell the
|
|
1211
|
+
difference - so the summary counts the interrupted tasks separately instead. */
|
|
1212
|
+
this.reconcileInterrupted(p);
|
|
1213
|
+
const resources = this.resources(p);
|
|
1214
|
+
return {
|
|
1215
|
+
id: p.id,
|
|
1216
|
+
name: p.title,
|
|
1217
|
+
status: this.statusWithInterruptions(p),
|
|
1218
|
+
mode: p.mode ?? "standard",
|
|
1219
|
+
headline: this.headline(p, actor, resources),
|
|
1220
|
+
activity: deriveProjectActivity({ ...p, status: this.statusWithInterruptions(p), resources }),
|
|
1221
|
+
tasks: {
|
|
1222
|
+
total: p.tasks.length,
|
|
1223
|
+
completed: p.tasks.filter((t) => t.status === "completed").length,
|
|
1224
|
+
inProgress: p.tasks.filter((t) => t.status === "in_progress").length,
|
|
1225
|
+
blocked: p.tasks.filter((t) => t.status === "blocked").length,
|
|
1226
|
+
interrupted: p.tasks.filter((t) => t.status === "interrupted").length,
|
|
1227
|
+
},
|
|
1228
|
+
activeWorkers: resources.activeWorkers,
|
|
1229
|
+
tokens: resources.tokens,
|
|
1230
|
+
updatedAt: p.updatedAt,
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* THE PROJECTS AN ACTOR IS PART OF, AND HOW MANY OF THEM THERE ARE.
|
|
1235
|
+
*
|
|
1236
|
+
* The list is capped, because the list is what goes into an agent's context: a workspace that
|
|
1237
|
+
* has been alive for a year has hundreds of finished projects, and handing all of them over
|
|
1238
|
+
* answers the question "how are my projects doing" with a wall of history. The cap is on the
|
|
1239
|
+
* RECENT ones - the same order the list has always had, newest update first - so what the
|
|
1240
|
+
* agent reads first is what actually changed.
|
|
1241
|
+
*
|
|
1242
|
+
* AND THE COUNT IS TOLD, NOT IMPLIED. `total` is how many projects the session is really
|
|
1243
|
+
* related to, counted BEFORE the cut, and `returned` is how many came back. An agent that sees
|
|
1244
|
+
* total 57 and returned 20 knows the workspace has more history than it was shown, and says so
|
|
1245
|
+
* instead of telling the Boss the workspace only has 20 projects. A silently truncated list
|
|
1246
|
+
* would be a lie the agent could not see through.
|
|
1247
|
+
*/
|
|
1248
|
+
listForActor(workspaceId, actor, limit = PROJECT_LIST_LIMIT) {
|
|
1249
|
+
const scope = this.workspace(workspaceId);
|
|
1250
|
+
const related = this.store.projects()
|
|
1251
|
+
.filter((p) => p.workspaceId === scope && this.isActorRelated(p, actor))
|
|
1252
|
+
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
1253
|
+
const total = related.length;
|
|
1254
|
+
const projects = related.slice(0, limit).map((p) => this.projectSummary(p, actor));
|
|
1255
|
+
return { projects, total, returned: projects.length };
|
|
1256
|
+
}
|
|
1257
|
+
get(id, workspaceId, actor) {
|
|
1258
|
+
return this.projectView(this.raw(id, workspaceId), actor);
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* THE PROJECT AS A REPORT A HUMAN CAN READ.
|
|
1262
|
+
*
|
|
1263
|
+
* Everything the panel shows in pieces - the objective, the tasks and who did them, the
|
|
1264
|
+
* deliveries and their evidence, the reviews that accepted them, the exceptions and how they
|
|
1265
|
+
* were decided - in one piece of Markdown, in reading order.
|
|
1266
|
+
*
|
|
1267
|
+
* TWO THINGS THIS REPORT REFUSES TO DO. It prints no session handle: a conversation id is a
|
|
1268
|
+
* machine address, and a report full of addresses is not something a person can read or paste
|
|
1269
|
+
* into a weekly note - the session's own title is used instead. And it prints no credential of
|
|
1270
|
+
* any kind: the CONTENT of the tasks, events, reports and exceptions is the report, and a
|
|
1271
|
+
* capability or a token that happens to live in a session profile is not content.
|
|
1272
|
+
*/
|
|
1273
|
+
async exportReport(id, workspaceId) {
|
|
1274
|
+
const p = workspaceId === undefined ? this.store.project(id) : this.raw(id, workspaceId);
|
|
1275
|
+
if (!p)
|
|
1276
|
+
throw new Error("项目不存在或不属于当前工作区");
|
|
1277
|
+
/* THE REPORT READS THE CORRECTED PROJECT. A report that called an interrupted task
|
|
1278
|
+
「执行中」 would be a document of lies - and the report is the thing that gets pasted into
|
|
1279
|
+
a weekly note, so it has to survive being read by somebody who was not there. */
|
|
1280
|
+
this.reconcileInterrupted(p);
|
|
1281
|
+
const store = this.store;
|
|
1282
|
+
/** THE TITLE A PERSON CALLS A SESSION BY. The handle stays out of the report. */
|
|
1283
|
+
const session = (conversationId) => {
|
|
1284
|
+
if (!conversationId)
|
|
1285
|
+
return "系统";
|
|
1286
|
+
return store.conversation(conversationId)?.title ?? "未知会话";
|
|
1287
|
+
};
|
|
1288
|
+
/** THE ROLE A TASK PLAYS, in the words the report uses. */
|
|
1289
|
+
const role = (t) => t.role === "leader" ? "负责人" : t.parentTaskId ? "执行者" : "负责人直属";
|
|
1290
|
+
/** THE ACCEPTANCE OF A TASK, told the truth about what is behind it. */
|
|
1291
|
+
const acceptance = (t) => {
|
|
1292
|
+
if (t.review?.lightweight === true)
|
|
1293
|
+
return "自评交付(轻量项目,无独立复核)";
|
|
1294
|
+
if (!t.review)
|
|
1295
|
+
return "未验收";
|
|
1296
|
+
return oneLine(t.review.summary);
|
|
1297
|
+
};
|
|
1298
|
+
/** THE TIMES A DELIVERY WAS SENT BACK. The current review only holds the last word, so the
|
|
1299
|
+
* earlier rejections are read back out of the timeline - the event summary carries the exact
|
|
1300
|
+
* text the reviewer wrote that day. */
|
|
1301
|
+
const reworkNotes = (t) => {
|
|
1302
|
+
const prefix = `退回返工:${t.title};`;
|
|
1303
|
+
return (p.events ?? []).filter((e) => e.kind === "reviewed" && e.taskId === t.id && e.summary.startsWith(prefix))
|
|
1304
|
+
.map((e) => e.summary.slice(prefix.length).trim());
|
|
1305
|
+
};
|
|
1306
|
+
const lines = [];
|
|
1307
|
+
lines.push(`# ${oneLine(p.title)}`, "", `> ${oneLine(p.objective)}`);
|
|
1308
|
+
if (p.deliverables.length)
|
|
1309
|
+
lines.push(`> 交付物:${p.deliverables.map(oneLine).join(";")}`);
|
|
1310
|
+
if (p.acceptanceCriteria.length)
|
|
1311
|
+
lines.push(`> 验收标准:${p.acceptanceCriteria.map(oneLine).join(";")}`);
|
|
1312
|
+
lines.push("", "## 概览", "");
|
|
1313
|
+
lines.push(`- 状态:${PROJECT_STATUS_TEXT[p.status] ?? p.status}`);
|
|
1314
|
+
const activitySessions = this.activitySessions(p);
|
|
1315
|
+
const projectActivity = deriveProjectActivity({ ...p, resources: { sessions: activitySessions } });
|
|
1316
|
+
lines.push(`- 当前活动:${projectActivity.label}`);
|
|
1317
|
+
lines.push(`- 下一步:${projectActivity.nextStep}`);
|
|
1318
|
+
lines.push(`- 模式:${lightweight(p) ? "轻量" : "标准"}`);
|
|
1319
|
+
lines.push(`- 风险:${SEVERITY_TEXT[p.risk] ?? p.risk}`);
|
|
1320
|
+
lines.push(`- 创建时间:${moment(p.createdAt)}`);
|
|
1321
|
+
lines.push(`- 最后更新时间:${moment(p.updatedAt)}`);
|
|
1322
|
+
if (p.closedAt)
|
|
1323
|
+
lines.push(`- 停止时间:${moment(p.closedAt)}`);
|
|
1324
|
+
const usage = this.resources(p);
|
|
1325
|
+
lines.push(`- 已用等效 Token:${usage.tokens}(口径:输入 + 输出 + 缓存写入×${CACHE_WRITE_WEIGHT} + 缓存读取×${CACHE_READ_WEIGHT},取整;含项目内的一次性调用(subagent))`);
|
|
1326
|
+
lines.push(`- 原始口径(1:1):${usage.rawTokens}(输入 ${usage.usage?.input ?? 0} + 输出 ${usage.usage?.output ?? 0} + 缓存写入 ${usage.usage?.cacheWrite ?? 0} + 缓存读取 ${usage.usage?.cacheRead ?? 0})`);
|
|
1327
|
+
lines.push(`- 任务:共 ${p.tasks.length} 个,已完成 ${p.tasks.filter((t) => t.status === "completed").length} 个`);
|
|
1328
|
+
lines.push("", "## 交付与验收", "");
|
|
1329
|
+
if (!p.tasks.length)
|
|
1330
|
+
lines.push("无");
|
|
1331
|
+
p.tasks.forEach((t, index) => {
|
|
1332
|
+
lines.push(`### ${index + 1}. ${oneLine(t.title)}`, "");
|
|
1333
|
+
lines.push(`- 角色:${role(t)}`);
|
|
1334
|
+
lines.push(`- 状态:${TASK_STATUS_TEXT[t.status] ?? t.status}`);
|
|
1335
|
+
const taskActivity = deriveTaskActivity(t, activitySessions, p.mode, p.tasks);
|
|
1336
|
+
lines.push(`- 当前活动:${taskActivity.label}`);
|
|
1337
|
+
lines.push(`- 下一步:${taskActivity.nextStep}`);
|
|
1338
|
+
if (t.status === "interrupted")
|
|
1339
|
+
lines.push(`- 中断原因:${oneLine(t.interruptedReason ?? "执行会话不在了")}`);
|
|
1340
|
+
lines.push(`- 负责人:${t.ownerConversationId ? session(t.ownerConversationId) : "未派发"}`);
|
|
1341
|
+
lines.push(`- 复核者:${t.reviewerConversationId ? session(t.reviewerConversationId) : "无"}`);
|
|
1342
|
+
lines.push(`- 交付内容:${t.output ? truncate(oneLine(t.output), 200) : "无"}`);
|
|
1343
|
+
lines.push(`- 证据:${t.evidenceRefs?.length ? t.evidenceRefs.map(oneLine).join("、") : "无"}`);
|
|
1344
|
+
lines.push(`- 验收结论:${acceptance(t)}`);
|
|
1345
|
+
if (t.review?.evidenceRefs?.length)
|
|
1346
|
+
lines.push(`- 复核证据:${t.review.evidenceRefs.map(oneLine).join("、")}`);
|
|
1347
|
+
const notes = reworkNotes(t);
|
|
1348
|
+
if (notes.length)
|
|
1349
|
+
lines.push(`- 退回意见:${notes.join(";")}`);
|
|
1350
|
+
lines.push("");
|
|
1351
|
+
});
|
|
1352
|
+
lines.push("## 例外与决定", "");
|
|
1353
|
+
if (!p.escalations.length)
|
|
1354
|
+
lines.push("无");
|
|
1355
|
+
else {
|
|
1356
|
+
/* THE TABLE IS FOR COMPARING, so the cell is a TITLE - the question the reader decides on -
|
|
1357
|
+
and the case goes under the table. A whole paragraph in one cell makes the table
|
|
1358
|
+
unreadable, and a table that cannot be scanned is not a table any more. THE SAME RULE
|
|
1359
|
+
GOVERNS THE DECISION COLUMN: a decision is the Boss's paragraph, so the cell carries its
|
|
1360
|
+
first sentence and the paragraph itself is printed below the table. */
|
|
1361
|
+
lines.push("| 例外 | 严重程度 | 状态 | 决定 | 解决时间 |", "| --- | --- | --- | --- | --- |");
|
|
1362
|
+
for (const e of p.escalations) {
|
|
1363
|
+
lines.push(`| ${cell(exceptionTitle(e))} | ${SEVERITY_TEXT[e.severity] ?? e.severity} | ${ESCALATION_STATUS_TEXT[e.status] ?? e.status} | ${cell(decisionCell(e.decision))} | ${e.resolvedAt ? moment(e.resolvedAt) : "无"} |`);
|
|
1364
|
+
}
|
|
1365
|
+
/* AND THE CASE IS NOT LOST. The title is what the reader compares; the reason is WHY, and it
|
|
1366
|
+
is a paragraph - so it is printed in full below the table, where a paragraph belongs. AND
|
|
1367
|
+
IT KEEPS ITS PARAGRAPHS: the line breaks the writer put in it are line breaks here too,
|
|
1368
|
+
because a case flattened into one long line is the "报告文学有点混乱" the report was
|
|
1369
|
+
blamed for. */
|
|
1370
|
+
const cases = p.escalations.filter((e) => (e.reason ?? "").trim());
|
|
1371
|
+
if (cases.length) {
|
|
1372
|
+
lines.push("", "例外详情:", "");
|
|
1373
|
+
for (const e of cases) {
|
|
1374
|
+
/* AN EXCEPTION WITH A TITLE is named by it; one without has only its case, and the case
|
|
1375
|
+
starts on the bullet itself - so the case is not printed twice under a label that is
|
|
1376
|
+
its own first sentence. */
|
|
1377
|
+
const label = e.title?.trim();
|
|
1378
|
+
lines.push(...detailItem(label ? label : undefined, e.reason ?? ""));
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
/* AND NEITHER IS THE DECISION. The column carries the first sentence; the Boss's whole
|
|
1382
|
+
paragraph - why he decided that, and what he accepts - is printed here, below the table,
|
|
1383
|
+
next to the case it answers. */
|
|
1384
|
+
const decided = p.escalations.filter((e) => (e.decision ?? "").trim());
|
|
1385
|
+
if (decided.length) {
|
|
1386
|
+
lines.push("", "决定详情:", "");
|
|
1387
|
+
for (const e of decided)
|
|
1388
|
+
lines.push(...detailItem(exceptionTitle(e), e.decision ?? ""));
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
lines.push("", "## 时间线", "");
|
|
1392
|
+
const events = [...(p.events ?? [])].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
|
|
1393
|
+
if (!events.length)
|
|
1394
|
+
lines.push("无");
|
|
1395
|
+
else {
|
|
1396
|
+
/* THE TIMELINE IS CONVERGED, AND SAYS SO. The list is the tail of the project's story -
|
|
1397
|
+
the most recent events, still in time order - and the number in front of it is how
|
|
1398
|
+
long the whole story was, so a reader never mistakes the tail for the whole. */
|
|
1399
|
+
const shown = events.length > REPORT_EVENT_LIMIT ? events.slice(-REPORT_EVENT_LIMIT) : events;
|
|
1400
|
+
lines.push(events.length > REPORT_EVENT_LIMIT
|
|
1401
|
+
? `共 ${events.length} 条事件,以下是最近 ${REPORT_EVENT_LIMIT} 条(更早的省略)`
|
|
1402
|
+
: `共 ${events.length} 条事件`);
|
|
1403
|
+
for (const e of shown)
|
|
1404
|
+
lines.push(`- ${moment(e.createdAt)} · ${EVENT_TEXT[e.kind] ?? e.kind} · ${oneLine(e.summary)} · ${session(e.actorConversationId)}`);
|
|
1405
|
+
}
|
|
1406
|
+
lines.push("", "## 最近汇报", "");
|
|
1407
|
+
if (!p.reports.length)
|
|
1408
|
+
lines.push("无");
|
|
1409
|
+
for (const r of p.reports) {
|
|
1410
|
+
lines.push(`- ${REPORT_KIND_TEXT[r.kind] ?? r.kind}:${oneLine(r.progress)} | 偏差:${r.variance ? oneLine(r.variance) : "无"} | 下一步:${r.nextStep ? oneLine(r.nextStep) : "无"} | 风险:${r.risks?.length ? r.risks.map(oneLine).join("、") : "无"}`);
|
|
1411
|
+
}
|
|
1412
|
+
return `${lines.join("\n")}\n`;
|
|
1413
|
+
}
|
|
1414
|
+
projectForSession(conversationId) {
|
|
1415
|
+
let c = this.store.conversation(conversationId);
|
|
1416
|
+
const seen = new Set();
|
|
1417
|
+
while (c && !seen.has(c.id)) {
|
|
1418
|
+
seen.add(c.id);
|
|
1419
|
+
const p = this.store.projects().find((p) => p.workspaceId === c.workspaceId && (p.ownerConversationId === c.id || p.tasks.some((t) => t.ownerConversationId === c.id || t.reviewerConversationId === c.id)));
|
|
1420
|
+
if (p)
|
|
1421
|
+
return p;
|
|
1422
|
+
c = c.parentConversationId ? this.store.conversation(c.parentConversationId) : undefined;
|
|
1423
|
+
}
|
|
1424
|
+
return undefined;
|
|
1425
|
+
}
|
|
1426
|
+
async create(input, initiatorConversationId) {
|
|
1427
|
+
const workspaceId = this.workspace(input.workspaceId);
|
|
1428
|
+
if (input.ownerConversationId !== undefined)
|
|
1429
|
+
throw new Error("项目负责人由启动操作创建独立会话");
|
|
1430
|
+
const rawRisk = typeof input.risk === "string" ? input.risk.trim().toLowerCase() : "";
|
|
1431
|
+
const risk = rawRisk === "medium" || rawRisk === "high" ? rawRisk : "low";
|
|
1432
|
+
// THE MODE IS CHOSEN ONCE, AT BIRTH, AND IT IS A CLOSED SET. A typo must not silently buy a
|
|
1433
|
+
// project the standard shape, because the standard shape is the one with the reviewer.
|
|
1434
|
+
if (input.mode !== undefined && input.mode !== "standard" && input.mode !== "lightweight")
|
|
1435
|
+
throw new Error("项目模式不合法:只能是 standard 或 lightweight");
|
|
1436
|
+
const defaultLeaderProfile = profile(input.defaultLeaderProfile, "默认 Leader 配置");
|
|
1437
|
+
const defaultExecutorProfile = profile(input.defaultExecutorProfile, "默认执行配置");
|
|
1438
|
+
const defaultReviewerProfile = profile(input.defaultReviewerProfile, "默认复核配置");
|
|
1439
|
+
// THE PROJECT'S OWN EMPLOYEE DEFAULTS ARE EMPLOYEES TOO. They are the profiles every task
|
|
1440
|
+
// inherits when it names no one, so a subagent written here would become the employee of the
|
|
1441
|
+
// whole project - and it would be refused at every task that inherited it, one by one, long
|
|
1442
|
+
// after the person who wrote it had walked away.
|
|
1443
|
+
await this.assertEmployee(defaultExecutorProfile, "defaultExecutorProfile");
|
|
1444
|
+
await this.assertEmployee(defaultReviewerProfile, "defaultReviewerProfile");
|
|
1445
|
+
const initiator = (initiatorConversationId ?? (typeof input.initiatorConversationId === "string" ? input.initiatorConversationId : undefined))?.trim() || undefined;
|
|
1446
|
+
const now = stamp();
|
|
1447
|
+
const p = { id: `project_${randomUUID()}`, workspaceId, title: text(input.title, "项目标题"), objective: text(input.objective, "项目目标"),
|
|
1448
|
+
deliverables: strings(input.deliverables, "交付物"), acceptanceCriteria: strings(input.acceptanceCriteria, "验收标准"), constraints: strings(input.constraints, "约束"),
|
|
1449
|
+
risk, status: "planning",
|
|
1450
|
+
// A project without a mode is a standard project: the mode is written down only when it was
|
|
1451
|
+
// asked for, so every project that existed before the mode existed reads as standard.
|
|
1452
|
+
...(input.mode ? { mode: input.mode } : {}),
|
|
1453
|
+
...(defaultLeaderProfile ? { defaultLeaderProfile } : {}),
|
|
1454
|
+
...(defaultExecutorProfile ? { defaultExecutorProfile } : {}),
|
|
1455
|
+
...(defaultReviewerProfile ? { defaultReviewerProfile } : {}),
|
|
1456
|
+
...(initiator ? { initiatorConversationId: initiator } : {}),
|
|
1457
|
+
tasks: [], reports: [], escalations: [], events: [], createdAt: now, updatedAt: now };
|
|
1458
|
+
if (initiator) {
|
|
1459
|
+
this.event(p, "created", "Agent 触发项目", undefined, initiator);
|
|
1460
|
+
}
|
|
1461
|
+
else {
|
|
1462
|
+
this.event(p, "created", "Boss 触发项目");
|
|
1463
|
+
}
|
|
1464
|
+
this.publishContext(p, input.sharedContext, initiator);
|
|
1465
|
+
const saved = await this.store.setProject(p);
|
|
1466
|
+
return this.projectView(saved);
|
|
1467
|
+
}
|
|
1468
|
+
admission(p) {
|
|
1469
|
+
this.live(p);
|
|
1470
|
+
if (p.escalations.some((e) => e.status === "open" && e.severity === "high" && (e.audience === "boss" || !e.audience)))
|
|
1471
|
+
throw new Error("等待 Boss 处理升级决策后才能继续派发");
|
|
1472
|
+
}
|
|
1473
|
+
context(p) {
|
|
1474
|
+
const modeLabel = lightweight(p) ? "轻量(由你亲自完成,提交即完成,无独立复核)" : "标准(任务分工 + 独立复核 + 逐级汇报)";
|
|
1475
|
+
const taskLines = p.tasks.length
|
|
1476
|
+
? p.tasks.map((t) => {
|
|
1477
|
+
const deps = t.dependencies.length ? `,依赖:${t.dependencies.join("、")}` : "";
|
|
1478
|
+
const owner = t.ownerConversationId ? `,执行会话:${t.ownerConversationId}` : "";
|
|
1479
|
+
const reviewer = t.reviewerConversationId ? `,复核会话:${t.reviewerConversationId}` : "";
|
|
1480
|
+
return `- ${t.id}|${t.title}|role=${t.role}|status=${t.status}${deps}${owner}${reviewer}`;
|
|
1481
|
+
}).join("\n")
|
|
1482
|
+
: "(暂无已登记任务,可直接用 add_task 拆解登记)";
|
|
1483
|
+
return `项目 ${p.id}:${p.title}\n模式:${modeLabel}\n目标:${p.objective}\n交付物:${p.deliverables.join(";")}\n验收标准:${p.acceptanceCriteria.join(";")}\n约束:${p.constraints.join(";")}\n当前任务分工:\n${taskLines}`;
|
|
1484
|
+
}
|
|
1485
|
+
async start(id, workspaceId, actor) {
|
|
1486
|
+
return this.change(id, workspaceId, async (p) => {
|
|
1487
|
+
this.topLevelAuthor(p, actor);
|
|
1488
|
+
this.admission(p);
|
|
1489
|
+
if (!this.orchestrator)
|
|
1490
|
+
throw new Error("会话编排服务未就绪");
|
|
1491
|
+
/* STARTING A PROJECT THAT IS ALREADY RUNNING IS NOT AN ERROR. `create` starts the project in
|
|
1492
|
+
one call - that is what the ceremony-free project is for - so the natural next call is
|
|
1493
|
+
`start`, and it used to answer 「项目负责人正在执行,请勿重复启动」. A model that created a
|
|
1494
|
+
project and then started it was doing exactly what the tool's own contract says it may do,
|
|
1495
|
+
and the refusal taught it nothing except that the tool lies. So the project is returned as
|
|
1496
|
+
it is: no second leader is spawned (the spawn below only happens when there is no owner),
|
|
1497
|
+
and the caller learns the state it asked about. */
|
|
1498
|
+
if (p.ownerConversationId && busy(this.store.conversation(p.ownerConversationId)?.status)) {
|
|
1499
|
+
this.event(p, "start_skipped", "项目已经在执行中,重复启动被忽略", undefined, actor);
|
|
1500
|
+
return p;
|
|
1501
|
+
}
|
|
1502
|
+
if (!p.ownerConversationId) {
|
|
1503
|
+
const effective = p.defaultLeaderProfile;
|
|
1504
|
+
p.ownerConversationId = (await this.orchestrator.spawn({
|
|
1505
|
+
workspaceId,
|
|
1506
|
+
// A PROJECT'S SESSIONS HANG UNDER THE CONVERSATION THAT CREATED IT. The leader session is
|
|
1507
|
+
// spawned without a parent today, so it lands at the TOP of the session tree and drags the
|
|
1508
|
+
// whole project subtree up with it. The initiator is the conversation that created the
|
|
1509
|
+
// project, so it is where the project belongs in the tree. A project the Boss started from
|
|
1510
|
+
// the panel has no initiator, and stays a root session exactly as before.
|
|
1511
|
+
...(p.initiatorConversationId ? { parentConversationId: p.initiatorConversationId } : {}),
|
|
1512
|
+
// A PROJECT IS ITS OWN WORKING CONTEXT. The leader hangs under the conversation that
|
|
1513
|
+
// asked for the project, but it must NOT share that conversation's memory tree: a tree
|
|
1514
|
+
// is what makes the memories of a chat visible to the sessions below it, and the
|
|
1515
|
+
// project's workers are not part of the user's chat. The tree edge is for the SIDEBAR
|
|
1516
|
+
// and the memory tree is for the WORK - they are two different things.
|
|
1517
|
+
separateMemoryTree: true,
|
|
1518
|
+
title: `项目负责人 · ${p.title}`,
|
|
1519
|
+
task: p.objective,
|
|
1520
|
+
initialPrompt: "",
|
|
1521
|
+
...(effective?.agentId ? { agentId: effective.agentId } : {}),
|
|
1522
|
+
...(effective?.cwd !== undefined ? { cwd: effective.cwd } : {}),
|
|
1523
|
+
...(effective?.model ? { model: effective.model } : {}),
|
|
1524
|
+
...(effective?.thinkingLevel ? { thinkingLevel: effective.thinkingLevel } : {}),
|
|
1525
|
+
...(effective?.watchdogTimeoutSeconds ? { watchdogTimeoutSeconds: effective.watchdogTimeoutSeconds } : {}),
|
|
1526
|
+
})).conversationId;
|
|
1527
|
+
// A LEADER WITHOUT A PROFILE LANDS ON THE WORKSPACE DEFAULT, AND THAT IS NOT A DECISION.
|
|
1528
|
+
// The default agent is whatever the workspace happens to run - it may well be another PMO,
|
|
1529
|
+
// which is how a project's leader became "one more pmo" once. The silent part was the
|
|
1530
|
+
// problem: the project looked started and the timeline never said what the leader is.
|
|
1531
|
+
// So the fallback is written down, where the people reading the project can see it.
|
|
1532
|
+
if (!effective?.agentId) {
|
|
1533
|
+
this.event(p, "leader-profile-missing", "未指定 Leader 的 agentId,负责人会话落在工作区默认 agent 上;请用 defaultLeaderProfile 明确指定", undefined, actor);
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
1536
|
+
for (const task of p.tasks) {
|
|
1537
|
+
if (!task.parentTaskId && (!task.accountableConversationId || task.accountableConversationId === p.initiatorConversationId)) {
|
|
1538
|
+
task.accountableConversationId = p.ownerConversationId;
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
this.event(p, "started", "项目负责人开始组织执行", undefined, actor);
|
|
1542
|
+
p.status = "active";
|
|
1543
|
+
await this.store.setProject(p);
|
|
1544
|
+
await this.dispatchContext(p.ownerConversationId, `${this.context(p)}\n${lightweight(p) ? LIGHTWEIGHT_LEADER_PROMPT : STANDARD_LEADER_PROMPT}`, { wait: false });
|
|
1545
|
+
return p;
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
async addTask(id, input, workspaceId, actor) {
|
|
1549
|
+
return this.change(id, workspaceId, async (p) => {
|
|
1550
|
+
this.live(p);
|
|
1551
|
+
const parentTaskId = optional(input.parentTaskId, "父任务 id");
|
|
1552
|
+
// A LIGHTWEIGHT PROJECT HAS ONE SESSION, SO IT HAS NO TREE OF TASKS. Decomposing the work
|
|
1553
|
+
// would mean spawning the worker sessions the mode exists to avoid, and a branch leader
|
|
1554
|
+
// would mean a second one. Both are refused here, in words the caller can act on.
|
|
1555
|
+
if (lightweight(p)) {
|
|
1556
|
+
if (parentTaskId)
|
|
1557
|
+
throw new Error("轻量项目不再拆子任务:整个项目由负责人会话自己完成");
|
|
1558
|
+
if (input.role === "leader")
|
|
1559
|
+
throw new Error("轻量项目没有分支 Leader:请登记为执行任务,由负责人亲自完成");
|
|
1560
|
+
}
|
|
1561
|
+
// A top-level task is accountable to whoever owns the project: the leader once it runs, and
|
|
1562
|
+
// before that the initiator who registered it - a task nobody answers for cannot be closed.
|
|
1563
|
+
let manager = p.ownerConversationId ?? p.initiatorConversationId;
|
|
1564
|
+
if (parentTaskId) {
|
|
1565
|
+
const parent = this.task(p, parentTaskId);
|
|
1566
|
+
if (parent.role !== "leader" || parent.status !== "in_progress" || !parent.ownerConversationId)
|
|
1567
|
+
throw new Error("父任务必须是执行中的 Leader 任务");
|
|
1568
|
+
if (actor && actor !== parent.ownerConversationId)
|
|
1569
|
+
throw new Error("仅父任务 Leader 可以拆解子任务");
|
|
1570
|
+
manager = parent.ownerConversationId;
|
|
1571
|
+
let depth = 1;
|
|
1572
|
+
let ancestor = parent;
|
|
1573
|
+
while (ancestor?.parentTaskId) {
|
|
1574
|
+
depth++;
|
|
1575
|
+
ancestor = this.task(p, ancestor.parentTaskId);
|
|
1576
|
+
}
|
|
1577
|
+
if (depth >= 3 && input.role === "leader")
|
|
1578
|
+
throw new Error("Leader 最多 3 层,请改为执行任务");
|
|
1579
|
+
}
|
|
1580
|
+
else
|
|
1581
|
+
this.topLevelAuthor(p, actor);
|
|
1582
|
+
if (input.role !== undefined && input.role !== "leader" && input.role !== "executor")
|
|
1583
|
+
throw new Error("任务角色必须是 leader 或 executor");
|
|
1584
|
+
const dependencies = strings(input.dependencies, "任务依赖");
|
|
1585
|
+
for (const dependency of dependencies)
|
|
1586
|
+
if (!p.tasks.some((t) => t.id === dependency))
|
|
1587
|
+
throw new Error(`任务依赖不存在:${dependency}`);
|
|
1588
|
+
for (const dependency of dependencies)
|
|
1589
|
+
if (this.task(p, dependency).parentTaskId !== parentTaskId)
|
|
1590
|
+
throw new Error("任务依赖只能指向同级任务,避免层级死锁");
|
|
1591
|
+
if (input.status !== undefined && input.status !== "pending" && input.status !== "ready")
|
|
1592
|
+
throw new Error("新任务必须从待派发或等待依赖开始");
|
|
1593
|
+
if (input.ownerConversationId || input.reviewerConversationId)
|
|
1594
|
+
throw new Error("执行和复核会话由派发操作创建");
|
|
1595
|
+
if (input.priority !== undefined && !["low", "medium", "high", "urgent"].includes(input.priority))
|
|
1596
|
+
throw new Error("任务优先级不合法");
|
|
1597
|
+
if (p.tasks.length >= 100)
|
|
1598
|
+
throw new Error("项目最多 100 个任务,请收敛分工范围");
|
|
1599
|
+
const executorProfile = profile(input.executorProfile, "执行配置");
|
|
1600
|
+
const reviewerProfile = profile(input.reviewerProfile, "复核配置");
|
|
1601
|
+
// THE EMPLOYEE IS CHECKED BEFORE THE TASK EXISTS. The refusal happens in the write itself,
|
|
1602
|
+
// so a project never carries a task whose employee is a subagent - not even for the moment
|
|
1603
|
+
// between the write and the next read.
|
|
1604
|
+
await this.assertEmployee(executorProfile, "executorProfile");
|
|
1605
|
+
await this.assertEmployee(reviewerProfile, "reviewerProfile");
|
|
1606
|
+
const now = stamp();
|
|
1607
|
+
const t = { id: `task_${randomUUID()}`, projectId: id, title: text(input.title, "任务标题"), objective: text(input.objective, "任务目标"),
|
|
1608
|
+
status: dependencies.length ? "pending" : "ready", accountableConversationId: manager, parentTaskId, role: input.role ?? "executor", dependencies,
|
|
1609
|
+
deliverables: strings(input.deliverables, "任务交付物"), acceptanceCriteria: strings(input.acceptanceCriteria, "任务验收标准"), priority: input.priority ?? "medium",
|
|
1610
|
+
...(executorProfile ? { executorProfile } : {}),
|
|
1611
|
+
...(reviewerProfile ? { reviewerProfile } : {}),
|
|
1612
|
+
dueAt: optional(input.dueAt, "截止时间"), createdAt: now, updatedAt: now };
|
|
1613
|
+
Object.assign(t, this.taskCoordination(input));
|
|
1614
|
+
p.tasks.push(t);
|
|
1615
|
+
this.publishContext(p, input.sharedContext, actor);
|
|
1616
|
+
this.reconcile(p);
|
|
1617
|
+
this.event(p, "task_created", `登记任务:${t.title}`, t.id, actor);
|
|
1618
|
+
return ProjectService.taskView(t, p);
|
|
1619
|
+
});
|
|
1620
|
+
}
|
|
1621
|
+
async dispatchTask(id, taskId, workspaceId, actor, sourceContext) {
|
|
1622
|
+
return this.change(id, workspaceId, async (p) => {
|
|
1623
|
+
const t = this.task(p, taskId);
|
|
1624
|
+
const manager = this.manager(p, t, actor);
|
|
1625
|
+
this.assertWriteScope(p, t);
|
|
1626
|
+
/* WAS THIS TASK INTERRUPTED? It is remembered before the status moves on, because both the
|
|
1627
|
+
worker and the reader need to know that this is a task coming back from a dead session,
|
|
1628
|
+
not a task that is being started for the first time. */
|
|
1629
|
+
const wasInterrupted = t.status === "interrupted";
|
|
1630
|
+
const interruptedNote = t.interruptedReason;
|
|
1631
|
+
if (!dependenciesComplete(p, t))
|
|
1632
|
+
throw new Error("任务的前置依赖尚未全部完成,不能开始执行");
|
|
1633
|
+
/* AN INTERRUPTED TASK CAN BE SENT OUT AGAIN. It used to be impossible: the task was stuck
|
|
1634
|
+
at `in_progress` with a session that no longer existed, and `dispatchTask` refused
|
|
1635
|
+
anything that was not `ready` - so a task whose execution session had died could never be
|
|
1636
|
+
dispatched again, and the only way out was two buttons in the wrong order. `interrupted` is
|
|
1637
|
+
the state that says "the execution is gone, put it back out", so it is a state this
|
|
1638
|
+
operation accepts. */
|
|
1639
|
+
if (t.status !== "ready" && t.status !== "interrupted")
|
|
1640
|
+
throw new Error("仅待派发或已中断的任务可以启动");
|
|
1641
|
+
this.admission(p);
|
|
1642
|
+
if (t.role === "leader" && !t.ownerConversationId && p.tasks.filter((t) => t.role === "leader" && t.ownerConversationId).length >= 8)
|
|
1643
|
+
throw new Error("分支 Leader 最多 8 个,请收敛组织层级");
|
|
1644
|
+
if (!this.orchestrator || !p.ownerConversationId)
|
|
1645
|
+
throw new Error("请先启动项目负责人");
|
|
1646
|
+
if (t.parentTaskId && this.task(p, t.parentTaskId).status !== "in_progress")
|
|
1647
|
+
throw new Error("父任务未处于执行中");
|
|
1648
|
+
const effective = mergeProfile(t.executorProfile, p.defaultExecutorProfile);
|
|
1649
|
+
if (sourceContext) {
|
|
1650
|
+
if (lightweight(p) || t.ownerConversationId || wasInterrupted || !manager)
|
|
1651
|
+
throw new Error("分叉只用于标准项目中首次派发的任务");
|
|
1652
|
+
const source = this.store.conversation(sourceContext.id);
|
|
1653
|
+
if (sourceContext.warm) {
|
|
1654
|
+
if (!source?.warmSession || source.workspaceId !== workspaceId)
|
|
1655
|
+
throw new Error("预热会话不在此工作区或已移除");
|
|
1656
|
+
}
|
|
1657
|
+
else if (!source || source.warmSession || source.parentConversationId !== manager || source.workspaceId !== workspaceId
|
|
1658
|
+
|| !p.tasks.some((task) => task.ownerConversationId === source.id)) {
|
|
1659
|
+
throw new Error("分叉来源必须是本项目下由你管理的执行会话");
|
|
1660
|
+
}
|
|
1661
|
+
else if (source.archivedAt || busy(source.status)) {
|
|
1662
|
+
throw new Error("请等待来源会话结束当前一轮后再分叉");
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
if (!t.ownerConversationId) {
|
|
1666
|
+
if (lightweight(p)) {
|
|
1667
|
+
// THE LEADER IS THE WORKER. A lightweight project spawns no worker session, so the task's
|
|
1668
|
+
// executor IS the project leader session - the very session that is asking for this
|
|
1669
|
+
// dispatch. There is nothing to hand the work to otherwise.
|
|
1670
|
+
if (!p.ownerConversationId)
|
|
1671
|
+
throw new Error("轻量项目还没有负责人会话:请先启动项目负责人");
|
|
1672
|
+
t.ownerConversationId = p.ownerConversationId;
|
|
1673
|
+
}
|
|
1674
|
+
else {
|
|
1675
|
+
t.ownerConversationId = (await this.orchestrator.spawn({
|
|
1676
|
+
workspaceId, parentConversationId: manager, title: `${t.role === "leader" ? "Leader" : "执行"} · ${t.title}`, task: t.objective, initialPrompt: "",
|
|
1677
|
+
...(sourceContext ? { forkFromConversationId: sourceContext.id } : {}),
|
|
1678
|
+
...(effective?.agentId ? { agentId: effective.agentId } : {}),
|
|
1679
|
+
...(effective?.cwd !== undefined ? { cwd: effective.cwd } : {}),
|
|
1680
|
+
...(effective?.model ? { model: effective.model } : {}),
|
|
1681
|
+
...(effective?.thinkingLevel ? { thinkingLevel: effective.thinkingLevel } : {}),
|
|
1682
|
+
...(effective?.watchdogTimeoutSeconds ? { watchdogTimeoutSeconds: effective.watchdogTimeoutSeconds } : {}),
|
|
1683
|
+
})).conversationId;
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
// THE BUSY CHECK IS ABOUT A SECOND WORKER SESSION, AND THERE IS NONE HERE. It stops a
|
|
1687
|
+
// worker from being handed a second task while it is still running the first one. In a
|
|
1688
|
+
// lightweight project the executor is the leader, which is busy by definition - it is the
|
|
1689
|
+
// session that asked for this dispatch - and the leader's own queue serializes the tasks
|
|
1690
|
+
// it has taken on.
|
|
1691
|
+
if (!lightweight(p) && busy(this.store.conversation(t.ownerConversationId)?.status))
|
|
1692
|
+
throw new Error("执行会话尚未结束,请等待完成回报后派发");
|
|
1693
|
+
/* THE MOMENT THE TASK WENT OUT IS WRITTEN DOWN. It is what tells a session that died BEFORE
|
|
1694
|
+
this dispatch from one that died AFTER it: only the second one interrupted the task, and
|
|
1695
|
+
only the second one may turn it into 「已中断」. */
|
|
1696
|
+
/* THE STATUS IS CHECKED AGAIN AT THE MOMENT OF THE WRITE, and it is checked against the
|
|
1697
|
+
STORE, not against the snapshot this operation started with. The spawn above is an await:
|
|
1698
|
+
while it was in flight the project could have been closed - every task delivered, the
|
|
1699
|
+
reconcile marked it done - and a dispatch that writes into a closed project is a duplicate
|
|
1700
|
+
delivery, not a delivery. The door check is not enough, because the door and the write are
|
|
1701
|
+
separated by exactly the length of a spawn, and the object in hand is the state from the
|
|
1702
|
+
door. So the fresh copy is read here, and the refusal happens before anything is written. */
|
|
1703
|
+
this.live(this.raw(id, workspaceId));
|
|
1704
|
+
t.status = "in_progress";
|
|
1705
|
+
t.updatedAt = stamp();
|
|
1706
|
+
t.dispatchedAt = t.updatedAt;
|
|
1707
|
+
delete t.blockedReason;
|
|
1708
|
+
delete t.blockedReportedByConversationId;
|
|
1709
|
+
delete t.interruptedReason;
|
|
1710
|
+
this.captureHandoff(p, t, sourceContext?.id ?? manager);
|
|
1711
|
+
this.event(p, "dispatched", `派发执行:${t.title};交接 ${t.handoff?.entries.length ?? 0} 条共享记录`, t.id, actor);
|
|
1712
|
+
this.reconcile(p);
|
|
1713
|
+
await this.store.setProject(p);
|
|
1714
|
+
const delegation = t.role === "leader" ? `你是分支 Leader,负责这项任务的拆解、委派、集成交付。用 project add_task 时必须带 parentTaskId="${t.id}";可按必要性指定 role="leader" 或 "executor";add_task / update_task 时可以带 executorProfile 与 reviewerProfile(支持指定 agentId、cwd、model、thinkingLevel、watchdogTimeoutSeconds),按任务性质将执行与复核委派给最合适的员工,不指定则继承项目默认。用 project dispatch / request_review 管理直属子任务,派发后子会话立即开始执行并在完成后自动回报给你,不要轮询;等待回报时结束本轮即可。所有必需子任务独立验收后才能 submit 聚合交付,上级还会独立复核你的集成结果。最多 3 层 Leader、8 个分支 Leader;小任务不要继续拆层。你的下属的升级先到你这里;你决定是自己解决还是再向上级转述。` : `你是执行者,直接上级会话是 ${manager},不得自行拆解子任务。`;
|
|
1715
|
+
/* THE LIGHTWEIGHT TASK SAYS WHAT IS DIFFERENT, because the difference is the point: there is
|
|
1716
|
+
no reviewer coming back, so the evidence that the reviewer would have demanded is the only
|
|
1717
|
+
thing that stands behind the delivery. */
|
|
1718
|
+
const modeNote = lightweight(p) ? "本项目是轻量项目:你就是唯一的执行会话,不会有独立复核人回来,完成后调用 project(action=submit, …) 提交即完成,交付证据必须附上。"
|
|
1719
|
+
: sourceContext ? "\n复用已复制的历史背景,立即推进本条消息指定的新任务;历史里的任务、成员身份及验收均属于原会话。\n" : "";
|
|
1720
|
+
/* THE TASK THAT WAS INTERRUPTED IS TOLD WHAT HAPPENED. A worker that comes back to a task
|
|
1721
|
+
it was working on has no idea whether the work it half did is still wanted, and the
|
|
1722
|
+
default - carry on as if nothing happened - is the wrong one after a crash. */
|
|
1723
|
+
const recoveryNote = wasInterrupted
|
|
1724
|
+
? `\n注意:这个任务上一次执行被中断了(${oneLine(interruptedNote ?? "执行会话不在了")})。请先确认当前状态,再继续完成交付;不要假设上一次的工作已经完成。`
|
|
1725
|
+
: "";
|
|
1726
|
+
try {
|
|
1727
|
+
await this.dispatchContext(t.ownerConversationId, `${this.context(p)}\n${delegation}\n你负责执行任务 ${t.id}:${t.title}\n目标:${t.objective}\n交付物:${t.deliverables.join(";")}\n验收:${t.acceptanceCriteria.join(";")}\n上次复核意见与验证证据:${JSON.stringify(t.review ?? null)}\n已验收前置产物:${JSON.stringify(p.tasks.filter((d) => t.dependencies.includes(d.id)).map((d) => ({ title: d.title, output: d.output, evidenceRefs: d.evidenceRefs })))}\n你不是唯一执行者,遵守分工边界。${modeNote}${recoveryNote}完成后必须调用 project(action=submit, projectId="${p.id}", taskId="${t.id}", output="交付总结", evidenceRefs=["产物路径或验证记录"]),不能自行标记已完成。复核退回时修复后重新 submit。遇到阻塞用 report(阻塞) 或 escalate 上报给你的直接上级,不要直接找 Boss,保留证据、假设和未解决问题。不要自行创建其他执行会话或 task/workflow。`, { wait: false }, t.id, t.handoff);
|
|
1728
|
+
}
|
|
1729
|
+
catch (error) {
|
|
1730
|
+
/* A DISPATCH THAT DID NOT HAPPEN MUST NOT LEAVE THE TASK SAYING 「执行中」. The status was
|
|
1731
|
+
already written down before the dispatch - that ordering is deliberate, so a reader can
|
|
1732
|
+
never see a task that is executing while the session was never told to run - but it means
|
|
1733
|
+
a failed dispatch has to correct the record itself. The task goes back to 「已中断」 with
|
|
1734
|
+
the reason, because that is exactly what it is: the work is not running, and nobody is
|
|
1735
|
+
going to report back on it. */
|
|
1736
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1737
|
+
t.status = "interrupted";
|
|
1738
|
+
t.interruptedReason = `重新派发没有成功:${message}`;
|
|
1739
|
+
t.updatedAt = stamp();
|
|
1740
|
+
this.event(p, "task_updated", `重新派发失败,任务已中断:${t.title}`, t.id, actor);
|
|
1741
|
+
await this.store.setProject(p);
|
|
1742
|
+
throw error;
|
|
1743
|
+
}
|
|
1744
|
+
return ProjectService.taskView(t, p);
|
|
1745
|
+
});
|
|
1746
|
+
}
|
|
1747
|
+
async submit(id, taskId, input, workspaceId, actor) {
|
|
1748
|
+
let completedOwner;
|
|
1749
|
+
const task = await this.change(id, workspaceId, (p) => {
|
|
1750
|
+
this.live(p);
|
|
1751
|
+
const t = this.task(p, taskId);
|
|
1752
|
+
if (actor && actor !== t.ownerConversationId)
|
|
1753
|
+
throw new Error("仅任务执行者可以提交交付");
|
|
1754
|
+
if (t.status !== "in_progress")
|
|
1755
|
+
throw new Error("仅执行中的任务可以提交交付");
|
|
1756
|
+
if (t.role === "leader" && !this.requiredComplete(p, t.id))
|
|
1757
|
+
throw new Error("Leader 的必需子任务尚未全部独立验收");
|
|
1758
|
+
t.output = text(input.output, "交付结果");
|
|
1759
|
+
const evidenceRefs = strings(input.evidenceRefs, "交付证据");
|
|
1760
|
+
t.evidenceRefs = evidenceRefs;
|
|
1761
|
+
// THE EVIDENCE IS REQUIRED IN BOTH SHAPES. The reviewer is gone in a lightweight project,
|
|
1762
|
+
// and the evidence is exactly what the reviewer would have checked - so it is the one thing
|
|
1763
|
+
// that does not get lighter.
|
|
1764
|
+
if (!t.evidenceRefs.length)
|
|
1765
|
+
throw new Error("交付必须附上产物或验证证据");
|
|
1766
|
+
this.publishContext(p, input.sharedContext, actor);
|
|
1767
|
+
if (lightweight(p)) {
|
|
1768
|
+
/* THE DELIVERY IS ACCEPTED ON THE EXECUTOR'S OWN EVIDENCE. There is no reviewer session to
|
|
1769
|
+
send it to, so the acceptance is written down here - with the flag that says there was
|
|
1770
|
+
no independent review, and with the session that made the call, so the record is not a
|
|
1771
|
+
claim that somebody else checked it. */
|
|
1772
|
+
t.status = "completed";
|
|
1773
|
+
t.updatedAt = stamp();
|
|
1774
|
+
completedOwner = t.ownerConversationId;
|
|
1775
|
+
t.review = { verdict: "accepted", summary: "轻量项目:执行者自评交付,未做独立复核", evidenceRefs,
|
|
1776
|
+
reviewerConversationId: t.ownerConversationId, createdAt: stamp(), lightweight: true };
|
|
1777
|
+
this.syncDeliveryContext(p, t, actor);
|
|
1778
|
+
this.event(p, "submitted", `轻量交付完成:${t.title}`, t.id, actor);
|
|
1779
|
+
this.reconcile(p);
|
|
1780
|
+
return ProjectService.taskView(t, p);
|
|
1781
|
+
}
|
|
1782
|
+
t.status = "awaiting_review";
|
|
1783
|
+
t.updatedAt = stamp();
|
|
1784
|
+
delete t.review;
|
|
1785
|
+
this.syncDeliveryContext(p, t, actor);
|
|
1786
|
+
this.event(p, "submitted", `交付待独立复核:${t.title}`, t.id, actor);
|
|
1787
|
+
this.reconcile(p);
|
|
1788
|
+
return ProjectService.taskView(t, p);
|
|
1789
|
+
});
|
|
1790
|
+
await this.notifyTaskCompleted(completedOwner, taskId);
|
|
1791
|
+
return task;
|
|
1792
|
+
}
|
|
1793
|
+
async requestReview(id, taskId, workspaceId, actor) {
|
|
1794
|
+
return this.change(id, workspaceId, async (p) => {
|
|
1795
|
+
/* THERE IS NO REVIEWER TO ASK FOR. A lightweight project's delivery is accepted when it is
|
|
1796
|
+
submitted, so asking for a review is asking for a session that will never exist. */
|
|
1797
|
+
if (lightweight(p))
|
|
1798
|
+
throw new Error("轻量项目不做独立复核:提交即完成");
|
|
1799
|
+
this.admission(p);
|
|
1800
|
+
const t = this.task(p, taskId);
|
|
1801
|
+
const manager = this.manager(p, t, actor);
|
|
1802
|
+
if (t.status !== "awaiting_review")
|
|
1803
|
+
throw new Error("任务尚未提交交付");
|
|
1804
|
+
if (!this.orchestrator || !p.ownerConversationId)
|
|
1805
|
+
throw new Error("请先启动项目负责人");
|
|
1806
|
+
const effective = mergeProfile(t.reviewerProfile, p.defaultReviewerProfile);
|
|
1807
|
+
if (!t.reviewerConversationId) {
|
|
1808
|
+
t.reviewerConversationId = (await this.orchestrator.spawn({
|
|
1809
|
+
workspaceId, parentConversationId: manager, title: `复核 · ${t.title}`, task: `独立复核 ${t.title}`, initialPrompt: "",
|
|
1810
|
+
...(effective?.agentId ? { agentId: effective.agentId } : {}),
|
|
1811
|
+
...(effective?.cwd !== undefined ? { cwd: effective.cwd } : {}),
|
|
1812
|
+
...(effective?.model ? { model: effective.model } : {}),
|
|
1813
|
+
...(effective?.thinkingLevel ? { thinkingLevel: effective.thinkingLevel } : {}),
|
|
1814
|
+
...(effective?.watchdogTimeoutSeconds ? { watchdogTimeoutSeconds: effective.watchdogTimeoutSeconds } : {}),
|
|
1815
|
+
})).conversationId;
|
|
1816
|
+
}
|
|
1817
|
+
if (busy(this.store.conversation(t.reviewerConversationId)?.status))
|
|
1818
|
+
throw new Error("复核会话正在执行");
|
|
1819
|
+
this.event(p, "review_requested", `启动独立复核:${t.title}`, t.id, actor);
|
|
1820
|
+
await this.store.setProject(p);
|
|
1821
|
+
await this.dispatchContext(t.reviewerConversationId, `${this.context(p)}\n你是独立复核人,只读检查,不修改执行者产物。任务 ${t.id}:${t.title}\n目标:${t.objective}\n验收标准:${t.acceptanceCriteria.join(";")}\n交付:${t.output}\n证据:${JSON.stringify(t.evidenceRefs)}\n主动寻找反例,核对真实产物、测试与证据,不能只复述作者结论。调用 project(action=review, projectId="${p.id}", taskId="${t.id}", verdict="accepted" 或 "changes_requested", summary="验收理由或具体返工项", evidenceRefs=["独立验证记录"])。完成后结束本轮,由上级安排后续。不创建额外会话。`, { wait: false }, t.id);
|
|
1822
|
+
return ProjectService.taskView(t, p);
|
|
1823
|
+
});
|
|
1824
|
+
}
|
|
1825
|
+
async review(id, taskId, input, workspaceId, actor) {
|
|
1826
|
+
let completedOwner;
|
|
1827
|
+
const task = await this.change(id, workspaceId, (p) => {
|
|
1828
|
+
this.live(p);
|
|
1829
|
+
const t = this.task(p, taskId);
|
|
1830
|
+
if (!actor || actor !== t.reviewerConversationId || actor === t.ownerConversationId)
|
|
1831
|
+
throw new Error("仅指定的独立复核人可以验收,禁止自审");
|
|
1832
|
+
if (t.status !== "awaiting_review")
|
|
1833
|
+
throw new Error("任务不处于待复核状态");
|
|
1834
|
+
if (input.verdict !== "accepted" && input.verdict !== "changes_requested")
|
|
1835
|
+
throw new Error("复核结论不合法");
|
|
1836
|
+
const evidenceRefs = strings(input.evidenceRefs, "复核证据");
|
|
1837
|
+
if (!evidenceRefs.length)
|
|
1838
|
+
throw new Error("复核必须附独立验证证据");
|
|
1839
|
+
t.review = { verdict: input.verdict, summary: text(input.summary, "复核意见"), evidenceRefs, reviewerConversationId: actor, createdAt: stamp() };
|
|
1840
|
+
t.status = input.verdict === "accepted" ? "completed" : "ready";
|
|
1841
|
+
t.updatedAt = stamp();
|
|
1842
|
+
if (t.status === "completed")
|
|
1843
|
+
completedOwner = t.ownerConversationId;
|
|
1844
|
+
this.syncDeliveryContext(p, t, actor);
|
|
1845
|
+
this.event(p, "reviewed", `${input.verdict === "accepted" ? "验收通过" : "退回返工"}:${t.title};${t.review.summary}`, t.id, actor);
|
|
1846
|
+
this.reconcile(p);
|
|
1847
|
+
return ProjectService.taskView(t, p);
|
|
1848
|
+
});
|
|
1849
|
+
await this.notifyTaskCompleted(completedOwner, taskId);
|
|
1850
|
+
return task;
|
|
1851
|
+
}
|
|
1852
|
+
/**
|
|
1853
|
+
* THE TASK IS DONE, SO THE LEADER IS WOKEN - AND IT IS NOT TOLD WHAT WAS DONE.
|
|
1854
|
+
*
|
|
1855
|
+
* The member's work is finished, and the member's direct parent - the Leader - has to hear
|
|
1856
|
+
* about it: a Leader that is not told is a Leader that sits there with a finished employee.
|
|
1857
|
+
*
|
|
1858
|
+
* WHAT THE WAKE CARRIES IS THE TASK'S IDENTITY AND NOTHING ELSE. The delivery, the evidence and
|
|
1859
|
+
* the review verdict stay where they are: in the project record and in the member's own
|
|
1860
|
+
* session. A platform that wrote the summary here would be writing a report nobody checked, and
|
|
1861
|
+
* the Leader is the one who is supposed to look and judge.
|
|
1862
|
+
*
|
|
1863
|
+
* THE COMPLETION IS THE UNIT, SO THE KNOCK HAPPENS ONCE. A task that is marked complete twice -
|
|
1864
|
+
* a retried acceptance - is one piece of work, and the Leader is woken once for it.
|
|
1865
|
+
*/
|
|
1866
|
+
async notifyTaskCompleted(ownerConversationId, taskId) {
|
|
1867
|
+
if (!ownerConversationId || !this.orchestrator)
|
|
1868
|
+
return;
|
|
1869
|
+
try {
|
|
1870
|
+
await this.orchestrator.notifyChildCompleted(ownerConversationId, { unit: `task:${taskId}` });
|
|
1871
|
+
}
|
|
1872
|
+
catch (error) {
|
|
1873
|
+
console.warn(`Super Pi: 任务 ${taskId} 已完成,但叫不醒直属上级:${error instanceof Error ? error.message : String(error)}`);
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
async updateTask(id, taskId, patch, actor) {
|
|
1877
|
+
const result = await this.change(id, patch.workspaceId, async (p) => {
|
|
1878
|
+
this.live(p);
|
|
1879
|
+
const t = this.task(p, taskId);
|
|
1880
|
+
this.member(p, actor);
|
|
1881
|
+
const manager = this.manager(p, t);
|
|
1882
|
+
if (actor && actor !== manager && actor !== t.ownerConversationId)
|
|
1883
|
+
throw new Error("无权更新此任务");
|
|
1884
|
+
if (patch.ownedPaths !== undefined || patch.readOnly !== undefined || patch.handoffNote !== undefined) {
|
|
1885
|
+
if (t.status === "in_progress" || t.status === "awaiting_review")
|
|
1886
|
+
throw new Error("执行或复核期间不能修改分工范围,请通过共享条目补充发现");
|
|
1887
|
+
Object.assign(t, this.taskCoordination({ ownedPaths: patch.ownedPaths, readOnly: patch.readOnly, handoffNote: patch.handoffNote }));
|
|
1888
|
+
}
|
|
1889
|
+
if (patch.status !== undefined) {
|
|
1890
|
+
if (patch.status === "in_progress" && !dependenciesComplete(p, t))
|
|
1891
|
+
throw new Error("任务的前置依赖尚未全部完成,不能开始执行");
|
|
1892
|
+
if (!["blocked", "failed", "cancelled", "ready"].includes(String(patch.status)))
|
|
1893
|
+
throw new Error("请使用派发、交付或独立复核操作流转任务");
|
|
1894
|
+
if (t.status === "completed" || t.status === "cancelled")
|
|
1895
|
+
throw new Error("任务已结束");
|
|
1896
|
+
if (patch.status === "ready" && !dependenciesComplete(p, t))
|
|
1897
|
+
throw new Error("前置依赖尚未完成");
|
|
1898
|
+
if (patch.status === "cancelled" && actor)
|
|
1899
|
+
throw new Error("取消交付范围必须由 Boss 决策");
|
|
1900
|
+
if (patch.status === "cancelled" && !patch.blockedReason)
|
|
1901
|
+
throw new Error("取消任务必须记录 Boss 的范围变更理由");
|
|
1902
|
+
if (patch.status === "ready" && actor && actor !== manager)
|
|
1903
|
+
throw new Error("仅直属 Leader 可以重新派发任务");
|
|
1904
|
+
t.status = patch.status;
|
|
1905
|
+
if (t.status === "blocked") {
|
|
1906
|
+
t.blockedReportedByConversationId = actor;
|
|
1907
|
+
}
|
|
1908
|
+
else {
|
|
1909
|
+
delete t.blockedReportedByConversationId;
|
|
1910
|
+
}
|
|
1911
|
+
}
|
|
1912
|
+
if (patch.executorProfile !== undefined) {
|
|
1913
|
+
if (t.ownerConversationId)
|
|
1914
|
+
throw new Error("执行会话已创建,禁止修改执行配置");
|
|
1915
|
+
const ep = profile(patch.executorProfile, "执行配置");
|
|
1916
|
+
// THE CHECK COMES BEFORE THE ASSIGNMENT. The task keeps the employee it had; what it must
|
|
1917
|
+
// not do is end up holding an employee the project is not allowed to have.
|
|
1918
|
+
await this.assertEmployee(ep, "executorProfile");
|
|
1919
|
+
if (ep)
|
|
1920
|
+
t.executorProfile = ep;
|
|
1921
|
+
else
|
|
1922
|
+
delete t.executorProfile;
|
|
1923
|
+
}
|
|
1924
|
+
if (patch.reviewerProfile !== undefined) {
|
|
1925
|
+
if (t.reviewerConversationId)
|
|
1926
|
+
throw new Error("复核会话已创建,禁止修改复核配置");
|
|
1927
|
+
const rp = profile(patch.reviewerProfile, "复核配置");
|
|
1928
|
+
await this.assertEmployee(rp, "reviewerProfile");
|
|
1929
|
+
if (rp)
|
|
1930
|
+
t.reviewerProfile = rp;
|
|
1931
|
+
else
|
|
1932
|
+
delete t.reviewerProfile;
|
|
1933
|
+
}
|
|
1934
|
+
if (patch.blockedReason !== undefined)
|
|
1935
|
+
t.blockedReason = text(patch.blockedReason, "阻塞原因");
|
|
1936
|
+
if (t.status === "blocked" && !t.blockedReason)
|
|
1937
|
+
throw new Error("阻塞任务必须说明原因");
|
|
1938
|
+
if (patch.dueAt !== undefined)
|
|
1939
|
+
t.dueAt = text(patch.dueAt, "截止时间");
|
|
1940
|
+
if (patch.output !== undefined)
|
|
1941
|
+
t.output = text(patch.output, "任务产出");
|
|
1942
|
+
if (patch.evidenceRefs !== undefined)
|
|
1943
|
+
t.evidenceRefs = strings(patch.evidenceRefs, "交付证据");
|
|
1944
|
+
if (patch.review !== undefined && !actor) {
|
|
1945
|
+
const rev = patch.review;
|
|
1946
|
+
if (rev === null) {
|
|
1947
|
+
delete t.review;
|
|
1948
|
+
}
|
|
1949
|
+
else if (typeof rev === "object") {
|
|
1950
|
+
t.review = {
|
|
1951
|
+
verdict: rev.verdict === "accepted" ? "accepted" : "changes_requested",
|
|
1952
|
+
summary: text(rev.summary, "复核意见"),
|
|
1953
|
+
evidenceRefs: strings(rev.evidenceRefs ?? ["verify.md"], "复核证据"),
|
|
1954
|
+
reviewerConversationId: typeof rev.reviewerConversationId === "string" ? rev.reviewerConversationId : (p.ownerConversationId ?? "boss"),
|
|
1955
|
+
createdAt: stamp(),
|
|
1956
|
+
};
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
if (patch.status === "cancelled") {
|
|
1960
|
+
const descendants = new Set([t.id]);
|
|
1961
|
+
for (let changed = true; changed;) {
|
|
1962
|
+
changed = false;
|
|
1963
|
+
for (const child of p.tasks)
|
|
1964
|
+
if (child.parentTaskId && descendants.has(child.parentTaskId) && !descendants.has(child.id)) {
|
|
1965
|
+
descendants.add(child.id);
|
|
1966
|
+
changed = true;
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
for (const child of p.tasks)
|
|
1970
|
+
if (child.id !== t.id && descendants.has(child.id) && child.status !== "completed") {
|
|
1971
|
+
child.status = "cancelled";
|
|
1972
|
+
child.blockedReason = t.blockedReason;
|
|
1973
|
+
child.updatedAt = stamp();
|
|
1974
|
+
this.event(p, "task_updated", `范围变更取消子任务:${child.title}`, child.id);
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
t.updatedAt = stamp();
|
|
1978
|
+
this.event(p, "task_updated", `${t.title}:${t.status}`, t.id, actor);
|
|
1979
|
+
this.reconcile(p);
|
|
1980
|
+
return ProjectService.taskView(t, p);
|
|
1981
|
+
});
|
|
1982
|
+
if (patch.status === "cancelled") {
|
|
1983
|
+
if (result.ownerConversationId)
|
|
1984
|
+
await this.orchestrator?.stopSubtree?.(result.ownerConversationId);
|
|
1985
|
+
if (result.reviewerConversationId)
|
|
1986
|
+
await this.orchestrator?.stopSubtree?.(result.reviewerConversationId);
|
|
1987
|
+
}
|
|
1988
|
+
return result;
|
|
1989
|
+
}
|
|
1990
|
+
async updateStatus(id, status, workspaceId) {
|
|
1991
|
+
const result = await this.change(id, workspaceId, (p) => {
|
|
1992
|
+
this.live(p);
|
|
1993
|
+
if (!["active", "cancelled", "failed"].includes(status))
|
|
1994
|
+
throw new Error("阶段交付请使用 deliver,项目状态由任务和例外推导");
|
|
1995
|
+
if (status === "active" && p.escalations.some((e) => e.status === "open"))
|
|
1996
|
+
throw new Error("请先处理未解决的例外");
|
|
1997
|
+
/* A PROJECT WITH NO LEADER SESSION HAS NOTHING RUNNING IN IT. The status is derived from
|
|
1998
|
+
the project's own state, and the API may not push it back into the contradiction that
|
|
1999
|
+
derivation exists to prevent: a project whose tasks were only registered is 待启动, and
|
|
2000
|
+
no caller - the panel included - may call it 执行中 until it has actually been started. */
|
|
2001
|
+
if (status === "active" && !p.ownerConversationId)
|
|
2002
|
+
throw new Error("项目尚未启动,请先启动项目负责人");
|
|
2003
|
+
p.status = status;
|
|
2004
|
+
if (closed(p))
|
|
2005
|
+
p.closedAt = stamp();
|
|
2006
|
+
this.event(p, "status", `项目状态:${status}`);
|
|
2007
|
+
return p;
|
|
2008
|
+
});
|
|
2009
|
+
// Stop after releasing the write lock: an interrupted tool may itself be waiting for it.
|
|
2010
|
+
if ((status === "cancelled" || status === "failed") && result.ownerConversationId)
|
|
2011
|
+
await this.orchestrator?.stopSubtree?.(result.ownerConversationId);
|
|
2012
|
+
return result;
|
|
2013
|
+
}
|
|
2014
|
+
/**
|
|
2015
|
+
* THE SESSION THAT OPENED THE PROJECT MAY CANCEL IT.
|
|
2016
|
+
*
|
|
2017
|
+
* There is no delete here, and that is deliberate. The project record, its tasks, its events and
|
|
2018
|
+
* its evidence references are the trail of what was tried; a project that went nowhere is
|
|
2019
|
+
* evidence too. Cancelling stops the work and marks the project cancelled - the record stays,
|
|
2020
|
+
* readable, with the reason attached.
|
|
2021
|
+
*
|
|
2022
|
+
* Only the session that opened the project may do this. A worker or a reviewer that could
|
|
2023
|
+
* cancel the project it belongs to would have a way to make its own budget and concurrency
|
|
2024
|
+
* guards disappear, and those guards are the only thing between a runaway agent and an
|
|
2025
|
+
* unbounded bill. The human path - the panel's stop button - is unchanged and stays the Boss's.
|
|
2026
|
+
*
|
|
2027
|
+
* A reason is required: "we changed our minds" and "the customer shipped it last night" are
|
|
2028
|
+
* different decisions, and the timeline is where that difference has to show up.
|
|
2029
|
+
*/
|
|
2030
|
+
async cancel(id, body, workspaceId, actor) {
|
|
2031
|
+
const reason = typeof body.reason === "string" ? body.reason.trim() : "";
|
|
2032
|
+
if (!reason)
|
|
2033
|
+
throw new Error("取消项目必须说明理由:理由会进入项目的事件时间线。");
|
|
2034
|
+
const found = this.get(id, workspaceId);
|
|
2035
|
+
if (!found.initiatorConversationId || found.initiatorConversationId !== actor)
|
|
2036
|
+
throw new Error("只有项目的发起人可以取消它。");
|
|
2037
|
+
const result = await this.change(id, workspaceId, (p) => {
|
|
2038
|
+
this.live(p);
|
|
2039
|
+
p.status = "cancelled";
|
|
2040
|
+
if (closed(p))
|
|
2041
|
+
p.closedAt = stamp();
|
|
2042
|
+
for (const t of p.tasks) {
|
|
2043
|
+
if (["completed", "cancelled", "failed"].includes(t.status))
|
|
2044
|
+
continue;
|
|
2045
|
+
t.status = "cancelled";
|
|
2046
|
+
t.updatedAt = stamp();
|
|
2047
|
+
}
|
|
2048
|
+
this.event(p, "status", `项目发起人取消项目:${reason}`, undefined, actor);
|
|
2049
|
+
return p;
|
|
2050
|
+
});
|
|
2051
|
+
// Stop after releasing the write lock: an interrupted tool may itself be waiting for it.
|
|
2052
|
+
if (result.ownerConversationId)
|
|
2053
|
+
await this.orchestrator?.stopSubtree?.(result.ownerConversationId);
|
|
2054
|
+
return result;
|
|
2055
|
+
}
|
|
2056
|
+
async addReport(id, input, workspaceId, actor) {
|
|
2057
|
+
let supervisorToWake;
|
|
2058
|
+
let taskForWake;
|
|
2059
|
+
let memberBlockedReport = false;
|
|
2060
|
+
const report = await this.change(id, workspaceId, (p) => {
|
|
2061
|
+
this.live(p);
|
|
2062
|
+
this.member(p, actor);
|
|
2063
|
+
if (!["progress", "blocked", "delivery", "decision_request", "review"].includes(input.kind))
|
|
2064
|
+
throw new Error("汇报类型不合法");
|
|
2065
|
+
const t = input.taskId ? this.task(p, text(input.taskId, "任务 id")) : undefined;
|
|
2066
|
+
if (t && ["completed", "cancelled"].includes(t.status) && input.kind === "blocked")
|
|
2067
|
+
throw new Error("已结束的任务不能标记阻塞");
|
|
2068
|
+
const projectContact = actor === p.ownerConversationId || (!t && actor === p.initiatorConversationId);
|
|
2069
|
+
if (actor && !projectContact && (!t || ![t.ownerConversationId, t.reviewerConversationId, this.manager(p, t)].includes(actor)))
|
|
2070
|
+
throw new Error("仅可汇报本人负责的任务");
|
|
2071
|
+
const report = { id: randomUUID(), projectId: id, taskId: t?.id, authorConversationId: actor, kind: input.kind,
|
|
2072
|
+
progress: text(input.progress, "汇报进展"), summary: typeof input.summary === "string" && input.summary.trim() ? text(input.summary, "汇报标题") : undefined, variance: optional(input.variance, "偏差"), nextStep: optional(input.nextStep, "下一步"), risks: strings(input.risks, "风险"),
|
|
2073
|
+
decisionNeeded: optional(input.decisionNeeded, "所需决策"), evidenceRefs: strings(input.evidenceRefs, "证据"), createdAt: stamp() };
|
|
2074
|
+
this.publishContext(p, input.sharedContext, actor);
|
|
2075
|
+
p.reports.push(report);
|
|
2076
|
+
if (report.kind === "blocked") {
|
|
2077
|
+
if (t) {
|
|
2078
|
+
t.status = "blocked";
|
|
2079
|
+
t.blockedReason = report.progress;
|
|
2080
|
+
t.blockedReportedByConversationId = actor;
|
|
2081
|
+
t.updatedAt = stamp();
|
|
2082
|
+
}
|
|
2083
|
+
if (actor && !this.canAddressUser(p, actor)) {
|
|
2084
|
+
memberBlockedReport = true;
|
|
2085
|
+
supervisorToWake = this.directSupervisor(p, actor, t?.id);
|
|
2086
|
+
taskForWake = t;
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
this.event(p, "report", report.progress, t?.id, actor);
|
|
2090
|
+
this.reconcile(p);
|
|
2091
|
+
return report;
|
|
2092
|
+
}, actor);
|
|
2093
|
+
if (supervisorToWake) {
|
|
2094
|
+
const taskInfo = taskForWake ? `任务 ${taskForWake.id}(${taskForWake.title})` : "所属任务";
|
|
2095
|
+
await this.wake(supervisorToWake, `下级成员(会话:${actor})汇报阻塞:${taskInfo}\n原因:${report.progress}\n请先在本层处理;仍需上级协助时,收敛后沿汇报线转述。`, "阻塞上报", id, workspaceId, actor);
|
|
2096
|
+
}
|
|
2097
|
+
else if (memberBlockedReport) {
|
|
2098
|
+
/* A MEMBER REPORTED A BLOCK AND NO SUPERVISOR COULD BE FOUND. The report is saved either
|
|
2099
|
+
* way, but nobody has been told, so the case is written down instead of vanishing. */
|
|
2100
|
+
const summary = "阻塞上报已保存,但找不到直接上级会话,上报没有被转述";
|
|
2101
|
+
console.warn(`Super Pi: 项目 ${id} 的${summary}`);
|
|
2102
|
+
await this.noteUnreachable(id, workspaceId, summary, actor);
|
|
2103
|
+
}
|
|
2104
|
+
return report;
|
|
2105
|
+
}
|
|
2106
|
+
async addEscalation(id, input, workspaceId, actor) {
|
|
2107
|
+
let supervisorToWake;
|
|
2108
|
+
let wakeMemberRole;
|
|
2109
|
+
const result = await this.change(id, workspaceId, (p) => {
|
|
2110
|
+
this.live(p);
|
|
2111
|
+
this.member(p, actor);
|
|
2112
|
+
if (!["low", "medium", "high"].includes(input.severity))
|
|
2113
|
+
throw new Error("升级风险等级不合法");
|
|
2114
|
+
const t = input.taskId
|
|
2115
|
+
? this.task(p, text(input.taskId, "任务 id"))
|
|
2116
|
+
: p.tasks.find((task) => task.ownerConversationId === actor || task.reviewerConversationId === actor);
|
|
2117
|
+
const isBossAudience = this.canAddressUser(p, actor);
|
|
2118
|
+
const audience = isBossAudience ? "boss" : "supervisor";
|
|
2119
|
+
let targetConversationId;
|
|
2120
|
+
if (!isBossAudience) {
|
|
2121
|
+
targetConversationId = this.directSupervisor(p, actor, t?.id);
|
|
2122
|
+
if (!targetConversationId) {
|
|
2123
|
+
throw new Error("无法确定直接上级会话:上级不在项目执行团队内且无法定位所属任务 Leader,升级已拒绝。");
|
|
2124
|
+
}
|
|
2125
|
+
supervisorToWake = targetConversationId;
|
|
2126
|
+
wakeMemberRole = p.tasks.some((task) => task.role === "leader" && task.ownerConversationId === actor)
|
|
2127
|
+
? "分支 Leader"
|
|
2128
|
+
: p.tasks.some((task) => task.reviewerConversationId === actor)
|
|
2129
|
+
? "独立复核"
|
|
2130
|
+
: "执行者";
|
|
2131
|
+
}
|
|
2132
|
+
const reason = text(input.reason, "升级原因");
|
|
2133
|
+
const e = {
|
|
2134
|
+
id: randomUUID(),
|
|
2135
|
+
projectId: id,
|
|
2136
|
+
taskId: t?.id,
|
|
2137
|
+
reason,
|
|
2138
|
+
/* THE QUESTION IS KEPT BESIDE THE CASE. The title is what the reader decides ON - one
|
|
2139
|
+
sentence, in the reader's terms - and the reason is the case for it. An escalation
|
|
2140
|
+
* without a title is still a valid escalation; it simply has to be read in full. */
|
|
2141
|
+
...(typeof input.title === "string" && input.title.trim() ? { title: text(input.title, "升级标题") } : {}),
|
|
2142
|
+
severity: input.severity,
|
|
2143
|
+
status: "open",
|
|
2144
|
+
requestedByConversationId: actor,
|
|
2145
|
+
audience,
|
|
2146
|
+
...(targetConversationId ? { targetConversationId } : {}),
|
|
2147
|
+
createdAt: stamp(),
|
|
2148
|
+
};
|
|
2149
|
+
p.escalations.push(e);
|
|
2150
|
+
this.event(p, "escalated", e.title ? `${e.title}:${e.reason}` : e.reason, t?.id, actor);
|
|
2151
|
+
this.reconcile(p);
|
|
2152
|
+
return e;
|
|
2153
|
+
}, actor);
|
|
2154
|
+
if (supervisorToWake) {
|
|
2155
|
+
await this.wake(supervisorToWake, `下级成员(会话:${actor},身份:${wakeMemberRole ?? "执行者"})发起例外升级(ID:${result.id}):\n${result.title ? `待决问题:${result.title}\n` : ""}原因:${result.reason}\n严重级别:${result.severity}\n请先在本层处理。若仍需上级或用户作决定,由你收敛问题并发起新的升级。`, `例外升级(ID:${result.id})`, id, workspaceId, actor);
|
|
2156
|
+
}
|
|
2157
|
+
return result;
|
|
2158
|
+
}
|
|
2159
|
+
/**
|
|
2160
|
+
* A DECISION ON A CLOSED PROJECT IS STILL A RECORD - AND A CLOSED PROJECT HAS NOBODY TO WAKE.
|
|
2161
|
+
*
|
|
2162
|
+
* THE TO-DO MUST NOT BE A DEAD END. `live()` refuses every write on a project that is
|
|
2163
|
+
* completed, cancelled or failed, and that guard is right for the paths it protects - it stops
|
|
2164
|
+
* a finished project from being quietly worked on again. But a decision is not a change to the
|
|
2165
|
+
* work: it is the RECORD of what the reader decided ABOUT the work. The exception is still
|
|
2166
|
+
* open, the question it asks is still unanswered, and the answer is worth keeping even when
|
|
2167
|
+
* the project itself is over - the reader's own words ("授权我以现有两份独立实测记录结案")
|
|
2168
|
+
* are exactly the thing the record is missing.
|
|
2169
|
+
*
|
|
2170
|
+
* So this path tells the two cases apart EXPLICITLY instead of bumping into the general guard:
|
|
2171
|
+
*
|
|
2172
|
+
* - the project is over: the decision is written into the exception (status, decision,
|
|
2173
|
+
* resolvedAt) and into the timeline, and NOBODY is woken - the whole session tree has
|
|
2174
|
+
* stopped, so waking is a gesture at an empty room;
|
|
2175
|
+
* - the project is live: everything happens as it always did, including the wake.
|
|
2176
|
+
*
|
|
2177
|
+
* THE TIMELINE SAYS WHY NOBODY WAS WOKEN. A record that silently skips a step is a record the
|
|
2178
|
+
* next reader has to guess about.
|
|
2179
|
+
*/
|
|
2180
|
+
async resolveEscalation(id, escalationId, decision, status, workspaceId, actor) {
|
|
2181
|
+
/* Whether the project was over when the decision was made. It is read inside the write, and
|
|
2182
|
+
read again afterwards - because the wake happens after the write is released. */
|
|
2183
|
+
let projectEnded = false;
|
|
2184
|
+
const result = await this.change(id, workspaceId, (p) => {
|
|
2185
|
+
projectEnded = closed(p);
|
|
2186
|
+
/* `live()` IS NOT CALLED HERE, AND THAT IS THE POINT. It protects the paths that change a
|
|
2187
|
+
project's work; this path changes the record of a decision, and on a closed project the
|
|
2188
|
+
decision is precisely what is still missing. Every OTHER reason to refuse stays: an
|
|
2189
|
+
unknown exception, one that has been handled already, a status that is not one of the
|
|
2190
|
+
three, and an actor who is not the one the exception is addressed to. */
|
|
2191
|
+
if (status !== "resolved" && status !== "dismissed" && status !== "returned")
|
|
2192
|
+
throw new Error("升级处理状态不合法");
|
|
2193
|
+
const e = p.escalations.find((e) => e.id === escalationId);
|
|
2194
|
+
if (!e)
|
|
2195
|
+
throw new Error("升级事项不存在");
|
|
2196
|
+
if (e.status !== "open")
|
|
2197
|
+
throw new Error("升级事项已处理");
|
|
2198
|
+
const audience = e.audience ?? "boss";
|
|
2199
|
+
if (audience === "boss") {
|
|
2200
|
+
if (actor)
|
|
2201
|
+
throw new Error("此例外需由 Boss 决策,团队成员无权处理");
|
|
2202
|
+
}
|
|
2203
|
+
else if (audience === "supervisor") {
|
|
2204
|
+
if (!actor)
|
|
2205
|
+
throw new Error("该例外属于直接上级处理范围,Boss 不能直接处理 supervisor 级别的例外");
|
|
2206
|
+
if (actor !== e.targetConversationId)
|
|
2207
|
+
throw new Error("只有指定的直接上级可以处理此例外");
|
|
2208
|
+
e.resolvedByConversationId = actor;
|
|
2209
|
+
}
|
|
2210
|
+
e.status = status;
|
|
2211
|
+
e.decision = text(decision, "处理意见");
|
|
2212
|
+
e.resolvedAt = stamp();
|
|
2213
|
+
const decider = audience === "boss" ? "Boss" : "直接上级";
|
|
2214
|
+
/* A RETURN IS NOT A DECISION. It says the case was not ready - the reader is being asked
|
|
2215
|
+
* for more material, not for a ruling - so the timeline says so in those words. */
|
|
2216
|
+
/* AND ON A CLOSED PROJECT THE TIMELINE ALSO SAYS THAT NOBODY WAS WOKEN. The decision is
|
|
2217
|
+
* recorded, but the session tree has stopped: a reader who comes back to this project
|
|
2218
|
+
* later must be able to tell "the answer was written down" from "the answer was sent to
|
|
2219
|
+
* somebody", and on a cancelled project those are two different things. */
|
|
2220
|
+
const endedNote = status === "returned"
|
|
2221
|
+
? "(项目已结束:退回意见已记入项目记录;项目已结束,没人可叫醒,未唤醒提出人)"
|
|
2222
|
+
: "(项目已结束:处理意见已记入项目记录,未唤醒任何人——没人可叫醒)";
|
|
2223
|
+
this.event(p, "decision", status === "returned"
|
|
2224
|
+
? `${decider}退回例外,等待补充材料:${e.decision}${projectEnded ? endedNote : ""}`
|
|
2225
|
+
: `${decider}决策:${e.decision}${projectEnded ? endedNote : ""}`, e.taskId, actor);
|
|
2226
|
+
this.reconcile(p);
|
|
2227
|
+
return e;
|
|
2228
|
+
}, actor);
|
|
2229
|
+
/* A CLOSED PROJECT HAS NO SESSION TREE TO WAKE. Every session under it has stopped, so a
|
|
2230
|
+
wake would be a gesture at an empty room - and the failure it would produce (a dispatch to
|
|
2231
|
+
a session that is not running) would be noise on a decision that was recorded perfectly
|
|
2232
|
+
well. The timeline already says that nobody was woken, so the silence is explained. */
|
|
2233
|
+
if (projectEnded)
|
|
2234
|
+
return result;
|
|
2235
|
+
/* THE CASE GOES BACK TO WHO RAISED IT. A returned escalation leaves the inbox without being
|
|
2236
|
+
* answered, so nobody would ever know it was still open - unless the person who raised it is
|
|
2237
|
+
* woken up and told to bring the missing material. This is the one wake that is NOT about a
|
|
2238
|
+
* decision: it is about work coming back. */
|
|
2239
|
+
if (status === "returned") {
|
|
2240
|
+
if (result.requestedByConversationId) {
|
|
2241
|
+
await this.wake(result.requestedByConversationId, `例外已退回,等待对方补充材料(ID:${result.id}):${result.title ?? result.reason}\n退回意见:${result.decision}\n请补充材料后重新发起升级。`, `例外已退回(ID:${result.id})`, id, workspaceId, actor);
|
|
2242
|
+
}
|
|
2243
|
+
return result;
|
|
2244
|
+
}
|
|
2245
|
+
const p = this.raw(id, workspaceId);
|
|
2246
|
+
if (result.audience === "supervisor") {
|
|
2247
|
+
if (result.requestedByConversationId) {
|
|
2248
|
+
await this.wake(result.requestedByConversationId, `直接上级已处理例外(ID:${result.id}):${result.reason}\n处理意见:${result.decision}\n请按处理意见继续工作。`, `例外处理结果(ID:${result.id})`, id, workspaceId, actor);
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
else {
|
|
2252
|
+
const recipientId = result.requestedByConversationId ?? p.initiatorConversationId ?? p.ownerConversationId;
|
|
2253
|
+
if (recipientId) {
|
|
2254
|
+
await this.wake(recipientId, `Boss 已处理项目 ${p.id} 的例外:${result.reason}\n决策:${result.decision}\n先读取 project 最新状态,按决策继续范围内的工作。`, `例外处理结果(ID:${result.id})`, id, workspaceId, actor);
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
return result;
|
|
2258
|
+
}
|
|
2259
|
+
deliveryTasks(p) {
|
|
2260
|
+
return p.tasks.filter((task) => task.status !== "cancelled" || !task.blockedReason);
|
|
2261
|
+
}
|
|
2262
|
+
async deliver(id, summary, evidenceRefs, workspaceId, actor) {
|
|
2263
|
+
return this.change(id, workspaceId, (p) => {
|
|
2264
|
+
this.live(p);
|
|
2265
|
+
this.leader(p, actor);
|
|
2266
|
+
const required = this.deliveryTasks(p);
|
|
2267
|
+
if (!required.length || required.some((t) => !this.taskAccepted(t))) {
|
|
2268
|
+
throw new Error(lightweight(p) ? "所有必需任务须先完成交付" : "所有必需任务须先经独立复核验收");
|
|
2269
|
+
}
|
|
2270
|
+
if (p.escalations.some((e) => e.status === "open"))
|
|
2271
|
+
throw new Error("尚有未处理例外");
|
|
2272
|
+
const evidence = strings(evidenceRefs, "阶段交付证据");
|
|
2273
|
+
if (!evidence.length)
|
|
2274
|
+
throw new Error("阶段交付必须附证据");
|
|
2275
|
+
const progress = text(summary, "阶段交付总结");
|
|
2276
|
+
p.reports.push({ id: randomUUID(), projectId: id, kind: "delivery", progress, evidenceRefs: evidence,
|
|
2277
|
+
acceptedTaskIds: required.map(task => task.id), authorConversationId: actor ?? p.ownerConversationId, createdAt: stamp() });
|
|
2278
|
+
this.event(p, "delivery", progress, undefined, actor);
|
|
2279
|
+
this.reconcile(p);
|
|
2280
|
+
return p;
|
|
2281
|
+
});
|
|
2282
|
+
}
|
|
2283
|
+
/**
|
|
2284
|
+
* The tasks an initiator hands over with create. A dependency names the TITLE of another task in
|
|
2285
|
+
* the same batch, because the batch carries no task IDs yet - the service assigns them while it
|
|
2286
|
+
* registers the batch. The plan comes back in dependency order, so the plain add_task rules
|
|
2287
|
+
* (title, objective, priority, sibling dependencies) can be reused unchanged.
|
|
2288
|
+
*/
|
|
2289
|
+
planTopLevelTasks(batch) {
|
|
2290
|
+
if (batch === undefined || batch === null)
|
|
2291
|
+
return [];
|
|
2292
|
+
if (!Array.isArray(batch))
|
|
2293
|
+
throw new Error("tasks 必须是任务数组");
|
|
2294
|
+
if (batch.length > 100)
|
|
2295
|
+
throw new Error("项目最多 100 个任务,请收敛分工范围");
|
|
2296
|
+
const items = batch.map((raw) => {
|
|
2297
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
2298
|
+
throw new Error("tasks 的每一项必须是任务对象");
|
|
2299
|
+
const record = raw;
|
|
2300
|
+
const priority = record.priority;
|
|
2301
|
+
if (priority !== undefined && !["low", "medium", "high", "urgent"].includes(String(priority)))
|
|
2302
|
+
throw new Error("任务优先级不合法");
|
|
2303
|
+
return {
|
|
2304
|
+
title: text(record.title, "任务标题"),
|
|
2305
|
+
objective: text(record.objective, "任务目标"),
|
|
2306
|
+
deliverables: record.deliverables === undefined ? undefined : strings(record.deliverables, "任务交付物"),
|
|
2307
|
+
acceptanceCriteria: record.acceptanceCriteria === undefined ? undefined : strings(record.acceptanceCriteria, "任务验收标准"),
|
|
2308
|
+
priority: priority,
|
|
2309
|
+
dependencies: record.dependencies === undefined ? [] : strings(record.dependencies, "任务依赖"),
|
|
2310
|
+
...this.taskCoordination(record),
|
|
2311
|
+
};
|
|
2312
|
+
});
|
|
2313
|
+
const index = new Map();
|
|
2314
|
+
items.forEach((item, at) => {
|
|
2315
|
+
if (index.has(item.title))
|
|
2316
|
+
throw new Error(`任务标题重复:${item.title}`);
|
|
2317
|
+
index.set(item.title, at);
|
|
2318
|
+
});
|
|
2319
|
+
const edges = items.map((item) => item.dependencies.map((dependency) => {
|
|
2320
|
+
const at = index.get(dependency);
|
|
2321
|
+
if (at === undefined)
|
|
2322
|
+
throw new Error(`任务依赖不存在:${dependency}`);
|
|
2323
|
+
return at;
|
|
2324
|
+
}));
|
|
2325
|
+
const ordered = [];
|
|
2326
|
+
const done = new Set();
|
|
2327
|
+
while (ordered.length < items.length) {
|
|
2328
|
+
let progressed = false;
|
|
2329
|
+
for (let at = 0; at < items.length; at += 1) {
|
|
2330
|
+
if (done.has(at))
|
|
2331
|
+
continue;
|
|
2332
|
+
if (!edges[at].every((dependency) => done.has(dependency)))
|
|
2333
|
+
continue;
|
|
2334
|
+
ordered.push(items[at]);
|
|
2335
|
+
done.add(at);
|
|
2336
|
+
progressed = true;
|
|
2337
|
+
}
|
|
2338
|
+
if (!progressed)
|
|
2339
|
+
throw new Error("任务依赖存在循环,无法登记顶层任务");
|
|
2340
|
+
}
|
|
2341
|
+
return ordered;
|
|
2342
|
+
}
|
|
2343
|
+
async registerTopLevelTasks(projectId, plan, workspaceId, actor) {
|
|
2344
|
+
const ids = new Map();
|
|
2345
|
+
for (const item of plan) {
|
|
2346
|
+
const dependencies = item.dependencies.map((dependency) => ids.get(dependency));
|
|
2347
|
+
const task = await this.addTask(projectId, {
|
|
2348
|
+
title: item.title, objective: item.objective,
|
|
2349
|
+
...this.taskCoordination(item),
|
|
2350
|
+
...(item.deliverables ? { deliverables: item.deliverables } : {}),
|
|
2351
|
+
...(item.acceptanceCriteria ? { acceptanceCriteria: item.acceptanceCriteria } : {}),
|
|
2352
|
+
...(item.priority !== undefined ? { priority: item.priority } : {}),
|
|
2353
|
+
dependencies,
|
|
2354
|
+
}, workspaceId, actor);
|
|
2355
|
+
ids.set(item.title, task.id);
|
|
2356
|
+
}
|
|
2357
|
+
}
|
|
2358
|
+
/**
|
|
2359
|
+
* THE INITIATOR'S LIMITED CORRECTION RIGHT.
|
|
2360
|
+
*
|
|
2361
|
+
* The person who opened the project gets exactly two things the Leader's chain does not give
|
|
2362
|
+
* them: READ-ONLY SUPERVISION of the whole project (the project's own read surface already
|
|
2363
|
+
* shows every member's status to every member), and ONE message to any session inside the
|
|
2364
|
+
* project tree - a single correction, delivered to that session directly, without having to go
|
|
2365
|
+
* through the Leader and wait for it to be relayed.
|
|
2366
|
+
*
|
|
2367
|
+
* WHY IT IS BOUNDED BY THREE RULES, AND NOT BY "THE INITIATOR CAN DO WHATEVER":
|
|
2368
|
+
*
|
|
2369
|
+
* 1. ONLY THE INITIATOR. Every other session in the project keeps the reporting line: a member
|
|
2370
|
+
* still reaches its direct supervisor, and the Leader still answers to the initiator. If every
|
|
2371
|
+
* member could correct every other member, the tree would stop being a tree.
|
|
2372
|
+
* 2. ONLY INSIDE THE PROJECT TREE. The target must be one of this project's sessions - the
|
|
2373
|
+
* Leader, a branch Leader, a worker, a reviewer. A session that is not in this project is
|
|
2374
|
+
* somebody else's department, and this right says nothing about it.
|
|
2375
|
+
* 3. ONE MESSAGE, NOT A CHANNEL. This sends a message; it does not open a line. The reporting
|
|
2376
|
+
* line, the escalation path and the parent's dispatch rules are untouched by it.
|
|
2377
|
+
*/
|
|
2378
|
+
async correctMember(id, targetConversationId, content, workspaceId, actor) {
|
|
2379
|
+
const p = this.raw(id, workspaceId);
|
|
2380
|
+
if (!actor)
|
|
2381
|
+
throw new Error("纠偏需要发起会话的身份。");
|
|
2382
|
+
// THE INITIATOR, AND ONLY THE INITIATOR.
|
|
2383
|
+
if (actor !== p.initiatorConversationId) {
|
|
2384
|
+
throw new Error("只有项目发起会话可以直接纠偏:其它会话请通过直接上级转述,汇报线不变。");
|
|
2385
|
+
}
|
|
2386
|
+
const target = text(targetConversationId, "targetConversationId");
|
|
2387
|
+
if (target === actor)
|
|
2388
|
+
throw new Error("不能给自己的会话发纠偏消息。");
|
|
2389
|
+
const message = text(content, "content");
|
|
2390
|
+
// INSIDE THIS PROJECT'S TREE, AND ONLY INSIDE IT.
|
|
2391
|
+
const members = new Set([
|
|
2392
|
+
p.ownerConversationId,
|
|
2393
|
+
...p.tasks.flatMap((t) => [t.ownerConversationId, t.reviewerConversationId]),
|
|
2394
|
+
].filter(Boolean));
|
|
2395
|
+
if (!members.has(target)) {
|
|
2396
|
+
throw new Error(`会话 ${target} 不在这个项目的会话树里,纠偏只能发给项目树内的会话。`);
|
|
2397
|
+
}
|
|
2398
|
+
if (!this.orchestrator)
|
|
2399
|
+
throw new Error("会话编排服务未就绪");
|
|
2400
|
+
const existingIds = new Set(p.escalations.filter(item => item.status === "open" && item.audience === "supervisor"
|
|
2401
|
+
&& item.targetConversationId === actor && item.requestedByConversationId === target).map(item => item.id));
|
|
2402
|
+
await this.dispatchContext(target, message, { wait: false });
|
|
2403
|
+
if (existingIds.size)
|
|
2404
|
+
await this.change(id, workspaceId, current => this.settleEscalationsByMessage(current, actor, target, message, existingIds));
|
|
2405
|
+
return { ok: true, conversationId: target, delivered: true };
|
|
2406
|
+
}
|
|
2407
|
+
async tool(body, workspaceId, actor) {
|
|
2408
|
+
if (body.action === "create") {
|
|
2409
|
+
// ONLY A ROOT CONVERSATION MAY OPEN A PROJECT. Every dispatched session - the leader, its
|
|
2410
|
+
// reviewers, the workers - holds the same tool, and a project opened from one of them would
|
|
2411
|
+
// escape the parent project's delegation and reporting chain.
|
|
2412
|
+
const conversation = this.store.conversation(actor);
|
|
2413
|
+
if (!conversation)
|
|
2414
|
+
throw new Error("找不到这个会话。");
|
|
2415
|
+
// AND A SESSION THAT IS ALREADY IN A PROJECT MAY NOT OPEN ANOTHER ONE. This gate is checked
|
|
2416
|
+
// FIRST, before the root-conversation gate, because it is the more precise of the two: the
|
|
2417
|
+
// leader, its reviewers and its workers all live INSIDE a project, and "you are already in a
|
|
2418
|
+
// project" is the reason that stops them. The leader is now spawned UNDER its initiator, so
|
|
2419
|
+
// the root gate would catch it too - but it would blame the tree shape instead of the project
|
|
2420
|
+
// membership, and the membership is the real reason. The set of sessions that may open a
|
|
2421
|
+
// project is the same either way: a session is refused if it is in a project OR has a parent.
|
|
2422
|
+
if (this.projectForSession(actor))
|
|
2423
|
+
throw new Error("已经在项目里的会话不能另起项目:请专注当前项目分工。");
|
|
2424
|
+
if (conversation.parentConversationId)
|
|
2425
|
+
throw new Error("只有主对话可以创建项目:派发出来的会话不能另起项目。");
|
|
2426
|
+
const running = this.store.projects().filter((p) => p.initiatorConversationId === actor && !closed(p)
|
|
2427
|
+
&& (!deliveryCoversTasks(latestProjectDelivery(p), this.deliveryTasks(p))
|
|
2428
|
+
|| this.deliveryTasks(p).some(task => !this.taskAccepted(task))
|
|
2429
|
+
|| p.escalations.some(item => item.status === "open")
|
|
2430
|
+
|| this.activitySessions(p).some(session => busy(session.status))));
|
|
2431
|
+
if (running.length >= 3)
|
|
2432
|
+
throw new Error("你同时进行的项目超过上限(3 个),先完成或停止一个再新建。");
|
|
2433
|
+
// ONLY TWO FIELDS ARE ASKED FOR, AND SAYING SO IS PART OF THE CONTRACT. The schema marks
|
|
2434
|
+
// `title` and `objective` optional - they are optional for the other actions of this tool -
|
|
2435
|
+
// so a model that reads the schema alone can send a project with neither, and then it meets
|
|
2436
|
+
// a bare "项目标题 不能为空". That message names a field the model never sent. So the
|
|
2437
|
+
// refusal names what IS needed, in one sentence, the first time.
|
|
2438
|
+
const missing = [];
|
|
2439
|
+
if (typeof body.title !== "string" || !body.title.trim())
|
|
2440
|
+
missing.push("title(项目标题)");
|
|
2441
|
+
if (typeof body.objective !== "string" || !body.objective.trim())
|
|
2442
|
+
missing.push("objective(项目目标)");
|
|
2443
|
+
if (missing.length) {
|
|
2444
|
+
throw new Error(`起项目只需要 title 和 objective,缺 ${missing.join(" 和 ")}。其余参数(risk、mode、deliverables 等)都可以不填。`);
|
|
2445
|
+
}
|
|
2446
|
+
const { tasks: batch, ...input } = body;
|
|
2447
|
+
const plan = this.planTopLevelTasks(batch);
|
|
2448
|
+
const project = await this.create({ ...input, workspaceId }, actor);
|
|
2449
|
+
await this.registerTopLevelTasks(project.id, plan, workspaceId, actor);
|
|
2450
|
+
if (this.orchestrator)
|
|
2451
|
+
await this.start(project.id, workspaceId, actor);
|
|
2452
|
+
return this.get(project.id, workspaceId);
|
|
2453
|
+
}
|
|
2454
|
+
if (body.action === "list") {
|
|
2455
|
+
// THE LIST IS CAPPED, AND IT SAYS SO. `total` and `returned` travel with it, so an agent
|
|
2456
|
+
// that sees a short list can tell the difference between "the workspace has three projects"
|
|
2457
|
+
// and "the workspace has fifty and I was shown twenty".
|
|
2458
|
+
return this.listForActor(workspaceId, actor);
|
|
2459
|
+
}
|
|
2460
|
+
if (body.action === "get_context")
|
|
2461
|
+
return this.getContext(typeof body.projectId === "string" ? body.projectId : undefined, workspaceId, actor, typeof body.taskId === "string" ? body.taskId : undefined, body.contextIds);
|
|
2462
|
+
const id = text(body.projectId, "projectId");
|
|
2463
|
+
const rawProject = this.raw(id, workspaceId);
|
|
2464
|
+
this.member(rawProject, actor);
|
|
2465
|
+
switch (body.action) {
|
|
2466
|
+
case "get": return this.get(id, workspaceId, actor);
|
|
2467
|
+
case "list_warm_sessions": return { sessions: this.store.listWarmSessions(workspaceId) };
|
|
2468
|
+
case "export": return this.exportReport(id, workspaceId);
|
|
2469
|
+
case "start": return this.start(id, workspaceId, actor);
|
|
2470
|
+
case "add_task": return this.addTask(id, body, workspaceId, actor);
|
|
2471
|
+
case "share_context": return this.shareContext(id, body.sharedContext, workspaceId, actor);
|
|
2472
|
+
case "message": {
|
|
2473
|
+
this.manager(rawProject, this.task(rawProject, text(body.taskId, "taskId")), actor);
|
|
2474
|
+
if (body.sharedContext !== undefined)
|
|
2475
|
+
await this.shareContext(id, body.sharedContext, workspaceId, actor);
|
|
2476
|
+
return this.messageTask(id, text(body.taskId, "taskId"), text(body.content, "content"), workspaceId, actor, typeof body.targetConversationId === "string" ? body.targetConversationId : undefined, body.deliveryMode);
|
|
2477
|
+
}
|
|
2478
|
+
case "dispatch": {
|
|
2479
|
+
const forkFromConversationId = body.forkFromConversationId === undefined
|
|
2480
|
+
? undefined : text(body.forkFromConversationId, "forkFromConversationId");
|
|
2481
|
+
const warmSessionId = body.warmSessionId === undefined ? undefined : text(body.warmSessionId, "warmSessionId");
|
|
2482
|
+
if (forkFromConversationId && warmSessionId)
|
|
2483
|
+
throw new Error("请选择一个会话上下文来源");
|
|
2484
|
+
const sourceContext = warmSessionId ? { id: warmSessionId, warm: true }
|
|
2485
|
+
: forkFromConversationId ? { id: forkFromConversationId, warm: false } : undefined;
|
|
2486
|
+
if (body.sharedContext !== undefined)
|
|
2487
|
+
await this.shareContext(id, body.sharedContext, workspaceId, actor);
|
|
2488
|
+
if (body.taskIds === undefined) {
|
|
2489
|
+
const taskId = text(body.taskId, "taskId");
|
|
2490
|
+
if (body.handoffNote !== undefined)
|
|
2491
|
+
await this.updateTask(id, taskId, { workspaceId, handoffNote: body.handoffNote }, actor);
|
|
2492
|
+
return this.dispatchReceipt(await this.dispatchTask(id, taskId, workspaceId, actor, sourceContext));
|
|
2493
|
+
}
|
|
2494
|
+
if (!Array.isArray(body.taskIds) || !body.taskIds.length || body.taskIds.length > 32 || body.taskIds.some(taskId => typeof taskId !== "string"))
|
|
2495
|
+
throw new Error("taskIds 须为 1–32 项任务 id 数组");
|
|
2496
|
+
const started = [], failed = [];
|
|
2497
|
+
for (const taskId of [...new Set(body.taskIds)]) {
|
|
2498
|
+
try {
|
|
2499
|
+
started.push(await this.dispatchTask(id, taskId, workspaceId, actor, sourceContext));
|
|
2500
|
+
}
|
|
2501
|
+
catch (error) {
|
|
2502
|
+
failed.push({ taskId, error: error instanceof Error ? error.message : String(error) });
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
return { ok: failed.length === 0, partial: failed.length > 0 && started.length > 0, started: started.map(task => this.dispatchReceipt(task)), failed };
|
|
2506
|
+
}
|
|
2507
|
+
case "submit": return this.submit(id, text(body.taskId, "taskId"), body, workspaceId, actor);
|
|
2508
|
+
case "request_review": return this.requestReview(id, text(body.taskId, "taskId"), workspaceId, actor);
|
|
2509
|
+
case "review": return this.review(id, text(body.taskId, "taskId"), body, workspaceId, actor);
|
|
2510
|
+
case "update_task": return this.updateTask(id, text(body.taskId, "taskId"), { ...body, workspaceId }, actor);
|
|
2511
|
+
case "report": return this.addReport(id, body, workspaceId, actor);
|
|
2512
|
+
case "escalate": return this.addEscalation(id, body, workspaceId, actor);
|
|
2513
|
+
case "resolve_escalation":
|
|
2514
|
+
case "resolveEscalation":
|
|
2515
|
+
return this.resolveEscalation(id, text(body.escalationId, "escalationId"), text(body.decision, "decision"), body.status ?? "resolved", workspaceId, actor);
|
|
2516
|
+
case "correct": return this.correctMember(id, text(body.targetConversationId, "targetConversationId"), text(body.content, "content"), workspaceId, actor);
|
|
2517
|
+
case "deliver":
|
|
2518
|
+
case "complete": return this.deliver(id, body.summary, body.evidenceRefs, workspaceId, actor);
|
|
2519
|
+
case "cancel": return this.cancel(id, body, workspaceId, actor);
|
|
2520
|
+
default: throw new Error("未知的项目工具操作");
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
}
|