@zyaochen/weaverbird 0.0.0-stage → 0.1.0

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.
Files changed (217) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +418 -0
  3. package/README.md +418 -2
  4. package/apps/wb-bot/README.md +118 -0
  5. package/dist/apps/wb-bot/src/agent-display.js +24 -0
  6. package/dist/apps/wb-bot/src/agent-registry.js +188 -0
  7. package/dist/apps/wb-bot/src/approval-gate/audit.js +37 -0
  8. package/dist/apps/wb-bot/src/approval-gate/cards.js +94 -0
  9. package/dist/apps/wb-bot/src/approval-gate/hook-env.js +15 -0
  10. package/dist/apps/wb-bot/src/approval-gate/hook-files.js +311 -0
  11. package/dist/apps/wb-bot/src/approval-gate/hook-main.js +147 -0
  12. package/dist/apps/wb-bot/src/approval-gate/notifier.js +29 -0
  13. package/dist/apps/wb-bot/src/approval-gate/store.js +157 -0
  14. package/dist/apps/wb-bot/src/binding/migration-runner.js +35 -0
  15. package/dist/apps/wb-bot/src/binding/migrations/001-add-run-id-agent-id.js +8 -0
  16. package/dist/apps/wb-bot/src/binding/migrations/002-add-bot-id.js +34 -0
  17. package/dist/apps/wb-bot/src/binding/migrations/003-inflight-card-agent-id-pk.js +31 -0
  18. package/dist/apps/wb-bot/src/binding/migrations/004-thread-alias-topic-key.js +31 -0
  19. package/dist/apps/wb-bot/src/binding/migrations/005-card-entity.js +21 -0
  20. package/dist/apps/wb-bot/src/binding/migrations/006-group-setting.js +17 -0
  21. package/dist/apps/wb-bot/src/binding/schema.js +58 -0
  22. package/dist/apps/wb-bot/src/binding/sleep-sync.js +5 -0
  23. package/dist/apps/wb-bot/src/binding/store.js +270 -0
  24. package/dist/apps/wb-bot/src/binding/task-index.js +127 -0
  25. package/dist/apps/wb-bot/src/boot/entry-path.js +9 -0
  26. package/dist/apps/wb-bot/src/boot/integrity.js +47 -0
  27. package/dist/apps/wb-bot/src/boot/logger.js +44 -0
  28. package/dist/apps/wb-bot/src/captain/bot-discovery.js +42 -0
  29. package/dist/apps/wb-bot/src/captain/captain-context.js +26 -0
  30. package/dist/apps/wb-bot/src/captain/captain-gate.js +9 -0
  31. package/dist/apps/wb-bot/src/captain/captain-status.js +101 -0
  32. package/dist/apps/wb-bot/src/captain/captain-stop-all.js +72 -0
  33. package/dist/apps/wb-bot/src/captain/list-bots.js +39 -0
  34. package/dist/apps/wb-bot/src/cli/doctor.js +105 -0
  35. package/dist/apps/wb-bot/src/cli/init.js +122 -0
  36. package/dist/apps/wb-bot/src/cli/parse-args.js +31 -0
  37. package/dist/apps/wb-bot/src/cli/preflight.js +9 -0
  38. package/dist/apps/wb-bot/src/cli/setup-checklist.js +10 -0
  39. package/dist/apps/wb-bot/src/commands/health.js +328 -0
  40. package/dist/apps/wb-bot/src/commands/history.js +100 -0
  41. package/dist/apps/wb-bot/src/commands/logs.js +91 -0
  42. package/dist/apps/wb-bot/src/commands/parser.js +43 -0
  43. package/dist/apps/wb-bot/src/commands/queue-metrics.js +24 -0
  44. package/dist/apps/wb-bot/src/commands/resume.js +48 -0
  45. package/dist/apps/wb-bot/src/commands/router.js +299 -0
  46. package/dist/apps/wb-bot/src/commands/status.js +77 -0
  47. package/dist/apps/wb-bot/src/commands/tasks.js +106 -0
  48. package/dist/apps/wb-bot/src/commands/wb-approval.js +86 -0
  49. package/dist/apps/wb-bot/src/commands/wb-audit.js +46 -0
  50. package/dist/apps/wb-bot/src/commands/wb-mute.js +84 -0
  51. package/dist/apps/wb-bot/src/commands/wb-sync.js +58 -0
  52. package/dist/apps/wb-bot/src/config/approval-code-owners.js +95 -0
  53. package/dist/apps/wb-bot/src/config/bot-env.js +80 -0
  54. package/dist/apps/wb-bot/src/config/config-paths.js +16 -0
  55. package/dist/apps/wb-bot/src/config/env.js +43 -0
  56. package/dist/apps/wb-bot/src/config/lark-credentials.js +14 -0
  57. package/dist/apps/wb-bot/src/e2e/preflight-env.js +147 -0
  58. package/dist/apps/wb-bot/src/e2e/preflight-main.js +12 -0
  59. package/dist/apps/wb-bot/src/feishu/admin-alert.js +94 -0
  60. package/dist/apps/wb-bot/src/feishu/artifacts.js +95 -0
  61. package/dist/apps/wb-bot/src/feishu/bot-identity.js +38 -0
  62. package/dist/apps/wb-bot/src/feishu/card-pipeline.js +121 -0
  63. package/dist/apps/wb-bot/src/feishu/card-renderer.js +360 -0
  64. package/dist/apps/wb-bot/src/feishu/card-transport.js +294 -0
  65. package/dist/apps/wb-bot/src/feishu/chat-mode-cache.js +47 -0
  66. package/dist/apps/wb-bot/src/feishu/completion-push.js +30 -0
  67. package/dist/apps/wb-bot/src/feishu/doc-comment.js +183 -0
  68. package/dist/apps/wb-bot/src/feishu/event-handler.js +2634 -0
  69. package/dist/apps/wb-bot/src/feishu/events-file-reader.js +162 -0
  70. package/dist/apps/wb-bot/src/feishu/inbound-context.js +53 -0
  71. package/dist/apps/wb-bot/src/feishu/keepalive.js +85 -0
  72. package/dist/apps/wb-bot/src/feishu/log-redact.js +20 -0
  73. package/dist/apps/wb-bot/src/feishu/markdown-style.js +95 -0
  74. package/dist/apps/wb-bot/src/feishu/media-cache.js +92 -0
  75. package/dist/apps/wb-bot/src/feishu/message-parser.js +126 -0
  76. package/dist/apps/wb-bot/src/feishu/pending-queue.js +133 -0
  77. package/dist/apps/wb-bot/src/feishu/reaction.js +44 -0
  78. package/dist/apps/wb-bot/src/feishu/reverse-at-im-handler.js +345 -0
  79. package/dist/apps/wb-bot/src/feishu/run-state.js +30 -0
  80. package/dist/apps/wb-bot/src/feishu/session-short-id.js +9 -0
  81. package/dist/apps/wb-bot/src/feishu/stream-state.js +72 -0
  82. package/dist/apps/wb-bot/src/feishu/topic-key.js +34 -0
  83. package/dist/apps/wb-bot/src/feishu/transport.js +768 -0
  84. package/dist/apps/wb-bot/src/feishu/wb-runner-spawner.js +84 -0
  85. package/dist/apps/wb-bot/src/heartbeat/bot-heartbeat.js +20 -0
  86. package/dist/apps/wb-bot/src/main.js +144 -0
  87. package/dist/apps/wb-bot/src/multi/discovery.js +53 -0
  88. package/dist/apps/wb-bot/src/multi/main.js +57 -0
  89. package/dist/apps/wb-bot/src/multi/parse-args.js +17 -0
  90. package/dist/apps/wb-bot/src/multi/supervisor.js +288 -0
  91. package/dist/apps/wb-bot/src/run-observability/orchestrator.js +61 -0
  92. package/dist/apps/wb-bot/src/security/bot-id-validator.js +18 -0
  93. package/dist/apps/wb-bot/src/security/cwd-guard.js +72 -0
  94. package/dist/apps/wb-bot/src/security/env-whitelist.js +94 -0
  95. package/dist/apps/wb-bot/src/server/wire-up.js +125 -0
  96. package/dist/apps/wb-cli/src/commands/approval.js +101 -0
  97. package/dist/apps/wb-cli/src/commands/attach.js +31 -0
  98. package/dist/apps/wb-cli/src/commands/audit.js +71 -0
  99. package/dist/apps/wb-cli/src/commands/captain.js +72 -0
  100. package/dist/apps/wb-cli/src/commands/debug.js +22 -0
  101. package/dist/apps/wb-cli/src/commands/history.js +75 -0
  102. package/dist/apps/wb-cli/src/commands/list.js +24 -0
  103. package/dist/apps/wb-cli/src/commands/logs.js +122 -0
  104. package/dist/apps/wb-cli/src/commands/resume.js +50 -0
  105. package/dist/apps/wb-cli/src/commands/runs.js +75 -0
  106. package/dist/apps/wb-cli/src/commands/status.js +35 -0
  107. package/dist/apps/wb-cli/src/commands/watch.js +73 -0
  108. package/dist/apps/wb-cli/src/main.js +312 -0
  109. package/dist/packages/core/src/agent/claude-code.js +354 -0
  110. package/dist/packages/core/src/agent/cli-subprocess.js +244 -0
  111. package/dist/packages/core/src/agent/codex.js +231 -0
  112. package/dist/packages/core/src/agent/index.js +5 -0
  113. package/dist/packages/core/src/agent/registry.js +47 -0
  114. package/dist/packages/core/src/agent/types.js +1 -0
  115. package/dist/packages/core/src/approval-gate/audit.js +16 -0
  116. package/dist/packages/core/src/approval-gate/contracts.js +26 -0
  117. package/dist/packages/core/src/approval-gate/matcher.js +112 -0
  118. package/dist/packages/core/src/audit-pipe/audit-pipe-main.js +38 -0
  119. package/dist/packages/core/src/audit-pipe/bitable-sink.js +156 -0
  120. package/dist/packages/core/src/audit-pipe/config.js +105 -0
  121. package/dist/packages/core/src/audit-pipe/contracts.js +33 -0
  122. package/dist/packages/core/src/audit-pipe/index.js +2 -0
  123. package/dist/packages/core/src/audit-pipe/mirror-sink.js +21 -0
  124. package/dist/packages/core/src/audit-pipe/normalizer.js +129 -0
  125. package/dist/packages/core/src/audit-pipe/orchestrator.js +252 -0
  126. package/dist/packages/core/src/audit-pipe/parser.js +24 -0
  127. package/dist/packages/core/src/audit-pipe/tailer.js +46 -0
  128. package/dist/packages/core/src/audit-pipe/wal.js +71 -0
  129. package/dist/packages/core/src/calendar-hook/config.js +45 -0
  130. package/dist/packages/core/src/calendar-hook/contracts.js +66 -0
  131. package/dist/packages/core/src/calendar-hook/index.js +5 -0
  132. package/dist/packages/core/src/calendar-hook/scheduler.js +169 -0
  133. package/dist/packages/core/src/calendar-hook/service.js +189 -0
  134. package/dist/packages/core/src/calendar-hook/transport.js +66 -0
  135. package/dist/packages/core/src/captain/captain-service.js +160 -0
  136. package/dist/packages/core/src/captain/command-catalog.js +41 -0
  137. package/dist/packages/core/src/captain/concurrency-config.js +10 -0
  138. package/dist/packages/core/src/captain/concurrency-queue-index.js +94 -0
  139. package/dist/packages/core/src/captain/concurrency-queue-store.js +43 -0
  140. package/dist/packages/core/src/captain/contracts.js +102 -0
  141. package/dist/packages/core/src/captain/cwd-inference.js +29 -0
  142. package/dist/packages/core/src/captain/enqueue-or-spawn.js +63 -0
  143. package/dist/packages/core/src/captain/index.js +27 -0
  144. package/dist/packages/core/src/captain/queue-metrics/aggregator.js +98 -0
  145. package/dist/packages/core/src/captain/queue-metrics/contracts.js +42 -0
  146. package/dist/packages/core/src/captain/queue-metrics/event-store.js +26 -0
  147. package/dist/packages/core/src/captain/session-store.js +429 -0
  148. package/dist/packages/core/src/captain/toml-loader.js +86 -0
  149. package/dist/packages/core/src/config/errors.js +15 -0
  150. package/dist/packages/core/src/config/registry.js +34 -0
  151. package/dist/packages/core/src/errors/codes.js +98 -0
  152. package/dist/packages/core/src/group-sync/autodoc.js +166 -0
  153. package/dist/packages/core/src/group-sync/config.js +45 -0
  154. package/dist/packages/core/src/group-sync/contracts.js +126 -0
  155. package/dist/packages/core/src/group-sync/dispatch.js +163 -0
  156. package/dist/packages/core/src/group-sync/index.js +9 -0
  157. package/dist/packages/core/src/group-sync/revdiff.js +138 -0
  158. package/dist/packages/core/src/group-sync/scheduler.js +93 -0
  159. package/dist/packages/core/src/group-sync/service.js +79 -0
  160. package/dist/packages/core/src/group-sync/transport.js +97 -0
  161. package/dist/packages/core/src/group-sync/xref.js +139 -0
  162. package/dist/packages/core/src/index.js +23 -0
  163. package/dist/packages/core/src/minutes/adapter.js +187 -0
  164. package/dist/packages/core/src/minutes/client.js +46 -0
  165. package/dist/packages/core/src/minutes/contracts.js +36 -0
  166. package/dist/packages/core/src/minutes/index.js +3 -0
  167. package/dist/packages/core/src/paths.js +158 -0
  168. package/dist/packages/core/src/periodic-tasks/config.js +45 -0
  169. package/dist/packages/core/src/periodic-tasks/contracts.js +75 -0
  170. package/dist/packages/core/src/periodic-tasks/index.js +4 -0
  171. package/dist/packages/core/src/periodic-tasks/orchestrator.js +249 -0
  172. package/dist/packages/core/src/periodic-tasks/state.js +29 -0
  173. package/dist/packages/core/src/reverse-channel/attach-handler.js +108 -0
  174. package/dist/packages/core/src/reverse-channel/audit-encoder.js +61 -0
  175. package/dist/packages/core/src/reverse-channel/contracts.js +136 -0
  176. package/dist/packages/core/src/reverse-channel/echo-tailer.js +36 -0
  177. package/dist/packages/core/src/reverse-channel/handoff.js +238 -0
  178. package/dist/packages/core/src/reverse-channel/index.js +5 -0
  179. package/dist/packages/core/src/reverse-channel/ipc-client.js +110 -0
  180. package/dist/packages/core/src/reverse-channel/ipc-control-handler.js +27 -0
  181. package/dist/packages/core/src/reverse-channel/ipc-server.js +127 -0
  182. package/dist/packages/core/src/reverse-channel/mute-registry.js +113 -0
  183. package/dist/packages/core/src/reverse-channel/pid-resolver.js +41 -0
  184. package/dist/packages/core/src/reverse-channel/reverse-at-handler.js +19 -0
  185. package/dist/packages/core/src/reverse-channel/sla-tracker.js +51 -0
  186. package/dist/packages/core/src/run-observability/alert-card-renderer.js +24 -0
  187. package/dist/packages/core/src/run-observability/alert-pusher.js +47 -0
  188. package/dist/packages/core/src/run-observability/card-refresher.js +31 -0
  189. package/dist/packages/core/src/run-observability/card-renderer-progress.js +33 -0
  190. package/dist/packages/core/src/run-observability/config-loader.js +23 -0
  191. package/dist/packages/core/src/run-observability/contracts.js +107 -0
  192. package/dist/packages/core/src/run-observability/exit-code-detector.js +16 -0
  193. package/dist/packages/core/src/run-observability/finalizer.js +114 -0
  194. package/dist/packages/core/src/run-observability/index.js +12 -0
  195. package/dist/packages/core/src/run-observability/obs-toggle-handler.js +29 -0
  196. package/dist/packages/core/src/run-observability/progress-collector.js +53 -0
  197. package/dist/packages/core/src/run-observability/progress-store.js +100 -0
  198. package/dist/packages/core/src/run-observability/silent-timeout-detector.js +12 -0
  199. package/dist/packages/core/src/run-registry/bitable-writer.js +308 -0
  200. package/dist/packages/core/src/run-registry/config.js +77 -0
  201. package/dist/packages/core/src/run-registry/contracts.js +114 -0
  202. package/dist/packages/core/src/run-registry/doc-sink-classifier.js +0 -0
  203. package/dist/packages/core/src/run-registry/doc-sink-transport.js +63 -0
  204. package/dist/packages/core/src/run-registry/doc-sink.js +200 -0
  205. package/dist/packages/core/src/run-registry/extractor.js +40 -0
  206. package/dist/packages/core/src/run-registry/index.js +11 -0
  207. package/dist/packages/core/src/run-registry/inherit.js +11 -0
  208. package/dist/packages/core/src/run-registry/orchestrator.js +86 -0
  209. package/dist/packages/core/src/run-registry/run-registry-main.js +38 -0
  210. package/dist/packages/core/src/run-registry/tailer.js +390 -0
  211. package/dist/packages/core/src/run-registry/wal.js +106 -0
  212. package/dist/packages/core/src/runner/event-replay.js +65 -0
  213. package/dist/packages/core/src/runner/wb-runner-main.js +27 -0
  214. package/dist/packages/core/src/runner/wb-runner.js +237 -0
  215. package/dist/packages/core/src/util/entry-module.js +21 -0
  216. package/dist/packages/core/src/util/ndjson-rotation.js +99 -0
  217. package/package.json +76 -4
@@ -0,0 +1,2634 @@
1
+ import pino from 'pino';
2
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { CODEX_PASSTHROUGH_KEYS } from '../../../../packages/core/src/index.js';
5
+ import { CLAUDE_PARTIAL_MESSAGES_FLAG } from '../../../../packages/core/src/agent/claude-code.js';
6
+ import { resolveDataDir, runDir as resolveRunDir, runEventsPath, runSpecPath, runStopSignalPath, } from '../../../../packages/core/src/paths.js';
7
+ import { createCaptainConcurrencyContainer } from '../../../../packages/core/src/captain/index.js';
8
+ import { ConcurrencyQueueEntryStatus } from '../../../../packages/core/src/captain/concurrency-queue-store.js';
9
+ import { enqueueOrSpawn } from '../../../../packages/core/src/captain/enqueue-or-spawn.js';
10
+ import { isCaptainEnabled } from '../captain/captain-gate.js';
11
+ import { BindingStore } from '../binding/store.js';
12
+ import { runCommand } from '../commands/router.js';
13
+ import { allocateSessionShortId, createInitialState, reduceStreamState } from './stream-state.js';
14
+ import { RUN_FOLLOW_UP_ACTIONS, SEND_ARTIFACT_ACTION, answerChunks, renderCard, renderContinuationCard } from './card-renderer.js';
15
+ import { ARTIFACT_MAX_BYTES, artifactLabel, findArtifacts } from './artifacts.js';
16
+ import { CardPipeline } from './card-pipeline.js';
17
+ import { validateCwd } from '../security/cwd-guard.js';
18
+ import { replayEventsFromNdjson } from '../../../../packages/core/src/runner/event-replay.js';
19
+ import { EventsFileReader } from './events-file-reader.js';
20
+ import { readEventsSync, extractLatestContinuationToken, runnerEventMapper } from './events-file-reader.js';
21
+ import { spawnWbRunner, generateRunId, buildRunSpec } from './wb-runner-spawner.js';
22
+ import { buildFilteredEnv } from '../security/env-whitelist.js';
23
+ import { buildApprovalHookEnv } from '../approval-gate/hook-env.js';
24
+ import { sendAdminAlert } from './admin-alert.js';
25
+ import { shouldPushOnDone, parsePushThresholdMs, formatCompletionMessage } from './completion-push.js';
26
+ import { judgeRunState as judgeRunStatePure } from './run-state.js';
27
+ import { handleReverseAtImCommand, } from './reverse-at-im-handler.js';
28
+ import { resolveReverseAtCancelTargetFromSession } from './session-short-id.js';
29
+ import { parseReverseAt } from '../../../../packages/core/src/reverse-channel/reverse-at-handler.js';
30
+ import { resolveCliPid } from '../../../../packages/core/src/reverse-channel/pid-resolver.js';
31
+ import { sendControlSignal } from '../../../../packages/core/src/reverse-channel/ipc-control-handler.js';
32
+ import { ProgressStore, ProgressCollector } from '../../../../packages/core/src/run-observability/index.js';
33
+ import { wireRunObservability } from '../run-observability/orchestrator.js';
34
+ import { closeCalendarBlock, openCalendarBlock } from '../../../../packages/core/src/calendar-hook/service.js';
35
+ import { ApprovalRequestStore } from '../approval-gate/store.js';
36
+ import { renderApprovalRequestCard, renderApprovalResolvedCard, renderApprovalCountdownText } from '../approval-gate/cards.js';
37
+ import { createCardApprovalNotifier } from '../approval-gate/notifier.js';
38
+ import { writeApprovalAudit } from '../approval-gate/audit.js';
39
+ import { APPROVAL_REQUEST_STATUS } from '../../../../packages/core/src/approval-gate/contracts.js';
40
+ import { prepareApprovalHookFiles } from '../approval-gate/hook-files.js';
41
+ import { toChatTopicKey } from './topic-key.js';
42
+ import { MediaCache } from './media-cache.js';
43
+ import { buildAgentInput } from './inbound-context.js';
44
+ import { AckReactions } from './reaction.js';
45
+ import { mergeMessageEvents } from './pending-queue.js';
46
+ import { MuteRegistry, defaultMuteRegistryPath, } from '../../../../packages/core/src/reverse-channel/index.js';
47
+ import { errorSerializers } from './log-redact.js';
48
+ import { siblingEntry } from '../boot/entry-path.js';
49
+ import { feishuErrorCode } from './card-transport.js';
50
+ const PREFERRED_AGENT_ORDER = ['claude-code', 'codex'];
51
+ const STALE_SELF_HEAL_MAX_ATTEMPTS = 1;
52
+ const RUNNER_STARTUP_GRACE_MS = 5_000;
53
+ /**
54
+ * 飞书 mention 占位符正则: `@_user_<n>` 单个用户 mention, `@_all` 全员 mention.
55
+ * 当用户在群里 `@bot` 时, 飞书 message content 会用这种占位符表示 mention.
56
+ *
57
+ * 实测形态 (主设计师 lark log 2026-06-03):
58
+ * raw content: {"text":"@_user_1"} # 只 @bot 没附文字
59
+ * raw content: {"text":"@_user_1 hello"} # @bot + 文字
60
+ */
61
+ const LARK_MENTION_PLACEHOLDER_RE = /@_user_\d+|@_all/g;
62
+ /**
63
+ * Strip 所有飞书 mention 占位符. 仅做 placeholder replace, **不 trim 不 collapse 空白**:
64
+ * - 不 trim: 保留 trailing whitespace 让 caller 内部 regex (例如 `AGENT_PREFIX` 的
65
+ * `\s+(.+)$`) 仍能解析 user 的 trailing-whitespace + empty prompt body 这种边界
66
+ * - 不 collapse: prompt body 内的多空白让 caller 决定怎么处理
67
+ *
68
+ * 用途:
69
+ * - 用户只 `@bot` 不附文字: helper 返回 '', caller 用 `.trim() === ''` 判 empty
70
+ * - 用户 `@bot + 文字`: helper 返回 ' 文字...' (含 leading space), caller 内的
71
+ * `.trimStart()` 已经处理
72
+ *
73
+ * 背景: 不 strip placeholder 直接把 `@_user_1` 当 prompt 传 claude code, claude 会
74
+ * 把 `@<id>` 解释成 file ref / sigil, 在 --print 模式报 "Input must be provided
75
+ * either through stdin or as a prompt argument".
76
+ *
77
+ * 测试见 `tests/wb-bot/lark-mention-strip.test.ts`.
78
+ */
79
+ export function stripLarkMentionPlaceholders(text) {
80
+ return text.replace(LARK_MENTION_PLACEHOLDER_RE, '');
81
+ }
82
+ /**
83
+ * 从 args 数组里抽 `--model` 的值. 支持 4 种 form:
84
+ * --model gpt-5.4 (separated)
85
+ * --model=gpt-5.4 (equal-sign)
86
+ * -m gpt-5.4 (short)
87
+ * -mgpt-5.4 (short concat)
88
+ *
89
+ * 用于把用户在 `WB_CLAUDE_COMMAND` 里写的 model 自动 propagate 到 child env
90
+ * 作 `ANTHROPIC_MODEL`. 背景: claude-code `--print --output-format stream-json`
91
+ * mode 某些版本不 honor CLI `--model` flag, 需要 env var 兜底. 同时 wrapper
92
+ * `claude-w` wrapper 在 has_model_flag=1 path 下不 export ANTHROPIC_MODEL,
93
+ * 所以 wb-bot 必须自己补这一步, 让用户单一 source of truth (WB_CLAUDE_COMMAND).
94
+ *
95
+ * 测试见 `tests/wb-bot/build-agent-args.test.ts`.
96
+ */
97
+ export function extractModelFromArgs(args) {
98
+ for (let i = 0; i < args.length; i++) {
99
+ const a = args[i];
100
+ if (!a)
101
+ continue;
102
+ if (a === '--model' || a === '-m') {
103
+ const next = args[i + 1];
104
+ if (next && !next.startsWith('-'))
105
+ return next;
106
+ }
107
+ if (a.startsWith('--model='))
108
+ return a.slice('--model='.length) || undefined;
109
+ if (a.startsWith('-m') && a.length > 2 && !a.startsWith('--'))
110
+ return a.slice(2);
111
+ }
112
+ return undefined;
113
+ }
114
+ /**
115
+ * 从 args 数组里把 `--model` / `-m` (含 4 种 form) 移除. 用于 codex 路径:
116
+ * `WB_CODEX_COMMAND="codex --model X"` 时, head=`codex`, prepend=[`--model`,`X`].
117
+ * core CodexAgent 把 `--model` splice 进 `exec` 子命令的固定位置, prepend 里再带一份就
118
+ * 重复且位置错. 抽出 model 到 buildAgentArgs 的 6th 参数后, 必须把 prepend 里的剥掉.
119
+ *
120
+ * 与 `extractModelFromArgs` 解析规则保持对称. 测试见 `tests/wb-bot/codex-argv-alignment.test.ts`.
121
+ */
122
+ export function stripModelArgs(args) {
123
+ const out = [];
124
+ for (let i = 0; i < args.length; i++) {
125
+ const a = args[i];
126
+ if (!a) {
127
+ out.push(a);
128
+ continue;
129
+ }
130
+ if (a === '--model' || a === '-m') {
131
+ const next = args[i + 1];
132
+ if (next && !next.startsWith('-')) {
133
+ i++;
134
+ continue;
135
+ }
136
+ continue;
137
+ }
138
+ if (a.startsWith('--model='))
139
+ continue;
140
+ if (a.startsWith('-m') && a.length > 2 && !a.startsWith('--'))
141
+ continue;
142
+ out.push(a);
143
+ }
144
+ return out;
145
+ }
146
+ /**
147
+ * 构造传给 claude-code / codex CLI 的 argv.
148
+ *
149
+ * **wb-bot invariant**: wb-bot 永远 backend 进程, 通过 `spawn` + `stdio: ['ignore', file, file]`
150
+ * + `detached: true` 起 agent CLI 子进程, **永远无 TTY 无 stdin**. 任何 claude / codex 自身的
151
+ * startup-phase interactive prompt (workspace trust / model picker / etc) 都会 hang 子进程,
152
+ * 导致主进程 `for await events.ndjson` 永远阻塞 → 飞书卡片冻在 "running · 00:00".
153
+ *
154
+ * 因此 claude-code 路径下, 除 `consentLevel === 'plan-only'` 之外, 一律附加
155
+ * `--dangerously-skip-permissions` 屏蔽所有 startup-phase prompt. consent gating
156
+ * 由 wb-bot 自身的 `ConsentLevel` contract 统一管 (per `AgentAdapter`), 不依赖
157
+ * claude 自身的 trust/permission UI.
158
+ *
159
+ * 例外 `plan-only`: 该模式 claude 仅产 plan 不执行任何工具, trust 风险 = 0, 保留
160
+ * `--permission-mode plan` 即足够.
161
+ *
162
+ * `strict` consent (core ConsentLevel 5 档之一) 在 wb-bot 入口 (config/bot-env.ts
163
+ * normalizeBotConsentLevel) 已 alias 为 `plan-only` — 因为 strict 语义 = "ask me
164
+ * for everything" 在无 TTY 环境无法兑现. 这里 buildAgentArgs 只看到 4 档,
165
+ * 不需要单独处理 strict. 完整 contract 说明: docs/product-strategy.md
166
+ * "Consent contract in wb-bot (no-TTY invariant)".
167
+ *
168
+ * 测试见 `tests/wb-bot/build-agent-args.test.ts`.
169
+ */
170
+ export function buildAgentArgs(agentId, prompt, cwd, continuationToken, consentLevel, model, images = []) {
171
+ void cwd;
172
+ if (agentId === 'claude-code') {
173
+ const args = ['--print', '--output-format', 'stream-json', '--verbose', CLAUDE_PARTIAL_MESSAGES_FLAG];
174
+ if (continuationToken)
175
+ args.push('--resume', continuationToken);
176
+ const claudeModel = process.env['ANTHROPIC_MODEL'];
177
+ if (claudeModel)
178
+ args.push('--model', claudeModel);
179
+ args.push('--permission-mode', consentLevel === 'auto'
180
+ ? 'bypassPermissions'
181
+ : consentLevel === 'relaxed'
182
+ ? 'acceptEdits'
183
+ : consentLevel === 'plan-only'
184
+ ? 'plan'
185
+ : 'default');
186
+ if (consentLevel !== 'plan-only') {
187
+ args.push('--dangerously-skip-permissions');
188
+ }
189
+ // Append optional system prompt from env (e.g. fail-fast guidance for
190
+ // internal-auth tools 这类). 不动 contract (RunRequest/ConsentLevel), pure
191
+ // claude CLI passthrough. 多行 prompt 用 dotenv multi-line 语法或 \\n escape.
192
+ const appendSysPrompt = process.env['WB_CLAUDE_APPEND_SYSTEM_PROMPT'];
193
+ if (appendSysPrompt && appendSysPrompt.trim()) {
194
+ args.push('--append-system-prompt', appendSysPrompt);
195
+ }
196
+ args.push(prompt);
197
+ return args;
198
+ }
199
+ // codex: mirror core CodexAgent.buildProcessSpec (packages/core/src/agent/codex.ts:186-196).
200
+ // 1. argv 形态: `exec [--model M] --json --skip-git-repo-check -`
201
+ // 或 resume: `exec resume --json [--model M] --skip-git-repo-check <token> -`
202
+ // 2. prompt **不在 argv**, 由 caller 通过 stdin pipe 写给 grandchild
203
+ // (RunSpec.stdinInput → wb-runner stdio[0]='pipe' + child.stdin.end(prompt+'\n')).
204
+ // 3. trailing `-` 是 codex 约定: read prompt from stdin.
205
+ // 之前 `--quiet -p <prompt>` argv 是 latent bug — codex 在该模式不吐 JSON stream,
206
+ // wb-runner 的 events.ndjson 永远拿不到 done event, 卡片冻在 running.
207
+ // 不要在此 build prompt; prompt 由 handleMessageViaWbRunner 走 stdinInput.
208
+ void prompt;
209
+ if (agentId === 'codex') {
210
+ const args = continuationToken
211
+ ? ['exec', 'resume', '--json', '--skip-git-repo-check', continuationToken, '-']
212
+ : ['exec', '--json', '--skip-git-repo-check', '-'];
213
+ if (model)
214
+ args.splice(continuationToken ? 3 : 2, 0, '--model', model);
215
+ // `--image <FILE>...` 是变长参数, 必须紧跟子命令、后面接 `--json` 之类的 flag 截断,
216
+ // 否则会吞掉末尾的 `-`. 图片路径同时已写进 prompt 正文.
217
+ if (images.length > 0)
218
+ args.splice(continuationToken ? 2 : 1, 0, ...images.flatMap((path) => ['--image', path]));
219
+ return args;
220
+ }
221
+ // unknown agent: fallback to legacy form so 测试/未来 agents 不会无 args 卡住
222
+ return ['--quiet', '-p', prompt];
223
+ }
224
+ function injectCodexExecArgs(args, extraArgs) {
225
+ if (extraArgs.length === 0)
226
+ return args;
227
+ if (args[0] !== 'exec')
228
+ return [...extraArgs, ...args];
229
+ return [args[0], ...extraArgs, ...args.slice(1)];
230
+ }
231
+ async function resolveDefaultAgent(registry) {
232
+ for (const id of PREFERRED_AGENT_ORDER) {
233
+ const agent = registry.lookup(id);
234
+ if (agent && await agent.isAvailable())
235
+ return agent;
236
+ }
237
+ for (const agent of registry.list()) {
238
+ if (await agent.isAvailable())
239
+ return agent;
240
+ }
241
+ return null;
242
+ }
243
+ const FOLLOW_UP_MEMORY = 200;
244
+ /** 无卡片运行 (云文档评论) 没有停止按钮, 超过这个时长自动停. */
245
+ const HEADLESS_RUN_TIMEOUT_MS = 15 * 60 * 1000;
246
+ function rememberBounded(map, key, value) {
247
+ map.delete(key);
248
+ map.set(key, value);
249
+ if (map.size > FOLLOW_UP_MEMORY) {
250
+ const oldest = map.keys().next().value;
251
+ if (oldest !== undefined)
252
+ map.delete(oldest);
253
+ }
254
+ }
255
+ const logger = pino({ level: process.env['LOG_LEVEL'] ?? 'info', serializers: errorSerializers });
256
+ /** 回复 / 引用的消息已被撤回. */
257
+ const MESSAGE_WITHDRAWN = 230011;
258
+ function summarizeState(state) {
259
+ return {
260
+ agentId: state.agentId,
261
+ cwd: state.cwd ?? '-',
262
+ hasContext: state.hasContext,
263
+ stopState: state.stopState,
264
+ terminalState: state.terminalState,
265
+ model: state.model ?? '-',
266
+ toolCount: state.tools.length,
267
+ textLength: state.text.length,
268
+ errorMessage: state.errorMessage,
269
+ };
270
+ }
271
+ function renderRestartedCard(mode, runIdShort, agentId, displayName) {
272
+ if (mode === 'resumed') {
273
+ const name = displayName ?? agentId ?? 'Weaverbird';
274
+ const text = `⏳ 服务重启, ${name} 任务 ${runIdShort ?? ''} 仍在运行中, 请稍候`;
275
+ return renderCard({
276
+ ...createInitialState(agentId ?? 'system', name, name),
277
+ text,
278
+ stopState: 'running',
279
+ terminalState: 'running',
280
+ });
281
+ }
282
+ // M13-I: "lost" 卡也带 dismiss, 避免"请重发"死胡同.
283
+ const text = '⚠️ 服务重启了, 这次卡已经断了。\n把你刚才的 prompt 再发一次, 我会当新任务跑。';
284
+ return renderCardWithButtons({
285
+ ...createInitialState('system', 'Weaverbird', 'bot'),
286
+ text,
287
+ stopState: 'running',
288
+ terminalState: 'error',
289
+ errorMessage: '服务重启',
290
+ }, [
291
+ { action: 'watchdog_dismiss', label: '知道了', value: runIdShort ? { runId: runIdShort } : {} },
292
+ ]);
293
+ }
294
+ // M13-D (2026-08-04): watchdog/restart 卡带"下一步"按钮 — PRD §2.7 礼仪 "@ 必
295
+ // 带'下一步动作'"。按钮 callback 由 handleCardAction 处理:
296
+ // - action='watchdog_dismiss': 关卡片
297
+ // - action='watchdog_retry': 重发原 prompt(当前版本 toast 提示重发;未来接
298
+ // session/operator 壳回到 handleMessage).
299
+ function renderActionButtons(actions) {
300
+ return {
301
+ tag: 'column_set',
302
+ columns: actions.map((button) => ({
303
+ tag: 'column',
304
+ width: 'weighted',
305
+ weight: 1,
306
+ elements: [{
307
+ tag: 'button',
308
+ text: { tag: 'plain_text', content: button.label },
309
+ type: button.primary ? 'primary_filled' : 'default',
310
+ behaviors: [{ type: 'callback', value: { action: button.action, ...button.value } }],
311
+ }],
312
+ })),
313
+ };
314
+ }
315
+ function renderCardWithButtons(state, actions) {
316
+ const base = renderCard(state);
317
+ const baseBody = base['body'] ?? { elements: [] };
318
+ baseBody.elements = [...(baseBody.elements ?? []), renderActionButtons(actions)];
319
+ return base;
320
+ }
321
+ function renderWatchdogRecoveredCard(runIdShort, runId) {
322
+ const text = `⚠️ 任务 ${runIdShort ?? ''} 卡死了, 我帮你把它停了。\n如果想重跑, 直接再发一次 prompt 即可, 不用手动清现场。`;
323
+ return renderCardWithButtons({
324
+ ...createInitialState('system', 'Weaverbird', 'bot'),
325
+ text,
326
+ stopState: 'stopped',
327
+ terminalState: 'error',
328
+ errorMessage: 'watchdog auto-recovered stale run',
329
+ }, [
330
+ { action: 'watchdog_dismiss', label: '知道了', value: runId ? { runId } : {} },
331
+ ]);
332
+ }
333
+ function renderWatchdogEscalatedCard(runIdShort, runId) {
334
+ const text = `⛔ 任务 ${runIdShort ?? ''} 这个人反复卡死, 我已停了自动重试并通知 bot 拥有者。\n需要的话你点下面重试, 或者等 owner 看一下后台。`;
335
+ return renderCardWithButtons({
336
+ ...createInitialState('system', 'Weaverbird', 'bot'),
337
+ text,
338
+ stopState: 'stopped',
339
+ terminalState: 'error',
340
+ errorMessage: 'watchdog auto-recovery disabled after repeated stale detection',
341
+ }, [
342
+ { action: 'watchdog_retry', label: '重试', primary: true, value: runId ? { runId } : {} },
343
+ { action: 'watchdog_dismiss', label: '先这样', value: runId ? { runId } : {} },
344
+ ]);
345
+ }
346
+ export class EventHandler {
347
+ registry;
348
+ store;
349
+ feishu;
350
+ defaultCwd;
351
+ claudeConsentLevel;
352
+ runnerConfig;
353
+ controlPlane;
354
+ captainService;
355
+ captainConcurrency;
356
+ reverseAtAdminRoleResolver;
357
+ reverseAtOperatorNotifier;
358
+ seen = new Map();
359
+ activeSessions = new Map();
360
+ activeSessionsByMessageId = new Map();
361
+ activeSessionsByShortId = new Map();
362
+ reservedSessionShortIds = new Set();
363
+ pendingCaptainRuns = new Map();
364
+ injectedRunIds = new Map();
365
+ pushThresholdMs;
366
+ followFlags = new Set();
367
+ staleRunSweepMs;
368
+ approvalRequests;
369
+ approvalNotifier;
370
+ approvalHookFiles;
371
+ calendarHookConfig;
372
+ calendarTransport;
373
+ muteRegistry;
374
+ mediaCache = null;
375
+ ackReactions;
376
+ followUps = new Map();
377
+ /** 已进入 startAgentRun、session 还没注册的 scope; 值是起跑标记, 防止前一轮的收尾误清后一轮. */
378
+ startingScopes = new Map();
379
+ mergedAckIds = new Map();
380
+ /** 结束卡按钮要用: 最近处理过的原始消息 (重试) 与运行卡 → 发起上下文 (校验发起人 / 定位 scope). */
381
+ recentInputs = new Map();
382
+ runCards = new Map();
383
+ runArtifacts = new Map();
384
+ headlessScopes = new Set();
385
+ staleRunSweepTimer = null;
386
+ staleRunSweepInFlight = false;
387
+ draining = false;
388
+ constructor(registry, store, feishu, defaultCwd, claudeConsentLevel, runnerConfig, controlPlane, captainService, captainConcurrency, reverseAtAdminRoleResolver, reverseAtOperatorNotifier, calendarHook) {
389
+ this.registry = registry;
390
+ this.store = store;
391
+ this.feishu = feishu;
392
+ this.defaultCwd = defaultCwd;
393
+ this.claudeConsentLevel = claudeConsentLevel;
394
+ this.runnerConfig = runnerConfig;
395
+ this.controlPlane = controlPlane;
396
+ this.captainService = captainService;
397
+ this.captainConcurrency = captainConcurrency;
398
+ this.reverseAtAdminRoleResolver = reverseAtAdminRoleResolver;
399
+ this.reverseAtOperatorNotifier = reverseAtOperatorNotifier;
400
+ this.ackReactions = new AckReactions(this.feishu);
401
+ this.pushThresholdMs = parsePushThresholdMs(process.env['WB_PUSH_THRESHOLD_MS']);
402
+ this.staleRunSweepMs = 5_000;
403
+ this.approvalRequests = new ApprovalRequestStore(this.alertDataDir);
404
+ this.muteRegistry = new MuteRegistry(defaultMuteRegistryPath(this.alertDataDir));
405
+ this.calendarHookConfig = calendarHook?.config;
406
+ this.calendarTransport = calendarHook?.transport;
407
+ this.approvalNotifier = createCardApprovalNotifier({
408
+ sendCard: async (chatId, card) => {
409
+ if (!this.feishu.sendCard)
410
+ return;
411
+ await this.feishu.sendCard(chatId, card);
412
+ },
413
+ cardFor: (request) => renderApprovalRequestCard(request),
414
+ resolveChatId: (request) => request.threadId,
415
+ muteRegistry: this.muteRegistry,
416
+ });
417
+ this.approvalHookFiles = this.runnerConfig ? prepareApprovalHookFiles({
418
+ dataDir: this.alertDataDir,
419
+ hookScriptPath: siblingEntry(import.meta.url, '../approval-gate/hook-main'),
420
+ }) : undefined;
421
+ if (this.runnerConfig) {
422
+ this.staleRunSweepTimer = setInterval(() => {
423
+ void this.sweepStaleRuns();
424
+ }, this.staleRunSweepMs);
425
+ this.staleRunSweepTimer.unref?.();
426
+ }
427
+ }
428
+ get botId() {
429
+ return this.runnerConfig?.botId ?? this.controlPlane?.botId ?? 'default';
430
+ }
431
+ /**
432
+ * M12-E (2026-08-04 owner-authorized): echo 首卡回写 home group。
433
+ * sendCard 缺失时本机 EchoDaemon 不应 throw;所以这里 fallback 成 warn,让上层
434
+ * EchoTailer 的 try 有机会记录失败但是不打断 daemon tick。
435
+ */
436
+ async sendHomeGroupCard(chatId, card) {
437
+ if (!chatId)
438
+ return;
439
+ if (this.feishu.sendCard) {
440
+ await this.feishu.sendCard(chatId, card);
441
+ return;
442
+ }
443
+ logger.warn({ chatId, card }, 'sendHomeGroupCard skipped: feishu.sendCard unavailable on this surface');
444
+ }
445
+ getControlPlane() {
446
+ return this.controlPlane;
447
+ }
448
+ /**
449
+ * M11-C C2 (2026-08-04 owner-authorized): calendar overdue escalation 回流
450
+ * 到 home group。发一张简单的"超时"提卡,让群成员知道这个 run 的时间块没关;
451
+ * 卡片同时被 audit mirror 记录,后续调度去重靠 `overdue_escalated_at` 或一次性
452
+ * sweep。
453
+ */
454
+ async notifyCalendarOverdue(payload) {
455
+ // session_id 前缀结构是 `${botId}:${userOpenId}:${threadId}`;拆出 threadId
456
+ // 告诉 home-group 标签;没 home group => 整段静音失败 (不打扰 owner).
457
+ const parts = payload.sessionId.split(':');
458
+ const threadId = parts.length >= 3 ? parts.slice(2).join(':') : payload.sessionId;
459
+ const homeGroupId = this.homeGroupIdFor({ threadId });
460
+ if (!homeGroupId) {
461
+ logger.warn({ payload }, 'calendar overdue notify skipped: no home group');
462
+ return;
463
+ }
464
+ const card = renderCard({
465
+ ...createInitialState('system', 'Weaverbird', 'bot'),
466
+ text: `⏰ run ${payload.runId.slice(0, 12)} 超过 ${payload.dueAt} 仍未结束`,
467
+ stopState: 'running',
468
+ terminalState: 'running',
469
+ errorMessage: undefined,
470
+ });
471
+ try {
472
+ await this.feishu.sendCard?.(homeGroupId, card);
473
+ }
474
+ catch (error) {
475
+ logger.warn({ payload, error }, 'calendar overdue sendCard failed');
476
+ throw error;
477
+ }
478
+ }
479
+ dispose() {
480
+ if (this.staleRunSweepTimer) {
481
+ clearInterval(this.staleRunSweepTimer);
482
+ this.staleRunSweepTimer = null;
483
+ }
484
+ }
485
+ reserveVisibleSessionShortId(value) {
486
+ const shortId = allocateSessionShortId(value, this.reservedSessionShortIds);
487
+ this.reservedSessionShortIds.add(shortId);
488
+ return shortId;
489
+ }
490
+ activeSessionsSnapshot() {
491
+ const out = [];
492
+ for (const session of this.activeSessions.values()) {
493
+ out.push({
494
+ scopeKey: session.scopeKey,
495
+ agentId: session.agentId,
496
+ runId: session.runId,
497
+ sessionShortId: session.state.sessionShortId,
498
+ startedAt: session.startedAt,
499
+ stopState: session.state.stopState,
500
+ terminalState: session.state.terminalState,
501
+ replyMessageId: session.replyMessageId,
502
+ });
503
+ }
504
+ return out;
505
+ }
506
+ activeSessionSnapshotByShortId(shortId) {
507
+ const session = this.activeSessionsByShortId.get(shortId);
508
+ if (!session)
509
+ return undefined;
510
+ return {
511
+ scopeKey: session.scopeKey,
512
+ agentId: session.agentId,
513
+ runId: session.runId,
514
+ sessionShortId: session.state.sessionShortId,
515
+ startedAt: session.startedAt,
516
+ stopState: session.state.stopState,
517
+ terminalState: session.state.terminalState,
518
+ replyMessageId: session.replyMessageId,
519
+ };
520
+ }
521
+ resolveReverseAtCancelTarget = (identifier) => {
522
+ const session = this.activeSessionsByShortId.get(identifier);
523
+ return resolveReverseAtCancelTargetFromSession(session ? {
524
+ agentId: session.agentId,
525
+ runId: session.runId,
526
+ sessionShortId: session.state.sessionShortId,
527
+ } : undefined);
528
+ };
529
+ buildCaptainConcurrencyDeps(context) {
530
+ if (!this.captainConcurrency)
531
+ return undefined;
532
+ return {
533
+ index: this.captainConcurrency.index,
534
+ store: this.captainConcurrency.store,
535
+ metrics: this.captainConcurrency.metrics,
536
+ now: this.captainConcurrency.now,
537
+ sessionId: this.sessionIdFor(context.userOpenId, context.threadId),
538
+ };
539
+ }
540
+ listReverseAtCancelableTargets = () => {
541
+ return this.activeSessionsSnapshot()
542
+ .filter((session) => session.sessionShortId)
543
+ .map((session) => `${session.sessionShortId} · ${session.agentId}`)
544
+ .sort();
545
+ };
546
+ get alertSink() {
547
+ return {
548
+ sendText: async (chatId, text) => {
549
+ await this.feishu.replyCard(chatId, renderCard({
550
+ ...createInitialState('system', '系统通知', 'bot'),
551
+ text,
552
+ terminalState: 'error',
553
+ includeMeta: false,
554
+ }));
555
+ },
556
+ sendDm: async (openId, text) => {
557
+ // M13-C: DM owner 通道. FeishuClient surface 上 sendDm 是可选的;缺时让
558
+ // admin-alert 走 cluster-fallback,避免踩到不支持 DM 的 bot。
559
+ if (this.feishu.sendDm) {
560
+ await this.feishu.sendDm(openId, text);
561
+ return;
562
+ }
563
+ throw new Error('feishu.sendDm unavailable on this surface');
564
+ },
565
+ };
566
+ }
567
+ /** CardKit 元素流式更新便宜且有打字机缓冲, 刷得勤一些; 消息 patch 维持 800ms 以免频控. */
568
+ cardIntervalMs(replyMessageId) {
569
+ return this.feishu.isStreamingCard?.(replyMessageId) ? 300 : 800;
570
+ }
571
+ resolveMediaCache() {
572
+ if (!this.feishu.downloadResource)
573
+ return undefined;
574
+ if (!this.mediaCache) {
575
+ const download = this.feishu.downloadResource.bind(this.feishu);
576
+ this.mediaCache = new MediaCache({ rootDir: join(this.alertDataDir, 'media'), download });
577
+ }
578
+ return this.mediaCache;
579
+ }
580
+ get alertDataDir() {
581
+ return resolveDataDir({ dataDir: this.runnerConfig?.dataDir ?? this.controlPlane?.dataDir });
582
+ }
583
+ sessionIdFor(userOpenId, threadId) {
584
+ return `${this.botId}:${userOpenId}:${threadId}`;
585
+ }
586
+ homeGroupIdFor(event) {
587
+ if (event.chatId && event.chatId.trim())
588
+ return event.chatId;
589
+ if (!event.threadId)
590
+ return null;
591
+ if (event.threadId.startsWith('chat:'))
592
+ return event.threadId.slice('chat:'.length) || null;
593
+ if (event.threadId.startsWith('root:'))
594
+ return null;
595
+ return event.threadId.trim() || null;
596
+ }
597
+ reverseAtThreadIdFor(event) {
598
+ return this.homeGroupIdFor(event) ?? event.threadId;
599
+ }
600
+ linkThreadTopicAlias(event) {
601
+ if (!event.rootId)
602
+ return;
603
+ const chatKey = toChatTopicKey(event.chatId);
604
+ if (!chatKey || chatKey === event.threadId)
605
+ return;
606
+ this.store.upsertThreadAlias(this.botId, event.userOpenId, event.threadId, chatKey);
607
+ }
608
+ async replyCardInThread(messageId, card) {
609
+ if (this.feishu.replyCardInThread) {
610
+ await this.feishu.replyCardInThread(messageId, card);
611
+ return;
612
+ }
613
+ await this.feishu.replyCard(messageId, card).then(() => undefined);
614
+ }
615
+ async sendCard(chatId, card) {
616
+ if (!chatId)
617
+ return;
618
+ if (this.feishu.sendCard) {
619
+ await this.feishu.sendCard(chatId, card);
620
+ return;
621
+ }
622
+ await this.feishu.replyCard(chatId, card).then(() => undefined);
623
+ }
624
+ async dispatchCommandReceived(command) {
625
+ if (this.isDuplicate(`${command.source}:${command.requestId}:${command.revision}`))
626
+ return;
627
+ this.injectedRunIds.set(command.requestId, command.runId);
628
+ const text = command.text.trimStart();
629
+ const commandResult = await runCommand(text, {
630
+ userOpenId: command.userOpenId,
631
+ threadId: command.threadId,
632
+ registry: this.registry,
633
+ store: this.store,
634
+ botId: this.botId,
635
+ controlPlane: this.controlPlane,
636
+ activeSessions: () => this.activeSessionsSnapshot(),
637
+ stopAllSessions: () => this.stopAllSessions(),
638
+ activeSessionsForThread: (uid, tid) => this.activeSessionsForThread(uid, tid).map((s) => ({ agentId: s.agentId })),
639
+ setFollowFlag: (tid) => this.followFlags.add(tid),
640
+ queueMetricsSnapshot: this.captainConcurrency
641
+ ? () => this.captainConcurrency.metrics.snapshot({ session_id: `${this.botId}:${command.userOpenId}:${command.threadId}` })
642
+ : undefined,
643
+ muteRegistry: this.muteRegistry,
644
+ });
645
+ if (commandResult !== null) {
646
+ await this.feishu.replyCard(command.messageId, renderCard({
647
+ ...createInitialState('system', 'Weaverbird', 'bot'),
648
+ text: commandResult,
649
+ includeMeta: false,
650
+ terminalState: 'done',
651
+ }));
652
+ return;
653
+ }
654
+ await this.handleMessage({
655
+ eventId: command.requestId,
656
+ userOpenId: command.userOpenId,
657
+ threadId: command.threadId,
658
+ messageId: command.messageId,
659
+ text: command.text,
660
+ });
661
+ }
662
+ async handleMessage(rawEvent) {
663
+ if (this.isDuplicate(this.messageDedupKey(rawEvent)))
664
+ return;
665
+ rememberBounded(this.recentInputs, rawEvent.messageId, rawEvent);
666
+ if (this.draining) {
667
+ await this.feishu.replyCard(rawEvent.messageId, renderCard({
668
+ ...createInitialState('system', 'Weaverbird', 'bot'),
669
+ text: '⚠️ bot 正在 shutdown drain,当前不接收新请求,请稍后重试',
670
+ includeMeta: false,
671
+ terminalState: 'done',
672
+ }));
673
+ return;
674
+ }
675
+ // Strip 飞书 mention 占位符 (@_user_<n>, @_all) + empty-prompt guard.
676
+ // 用户只 `@bot` 不附文字时, cleanedText.trim() === '', friendly reply 不 spawn agent.
677
+ // 不 strip 直接把 `@_user_1` 当 prompt 传给 claude --print 会报
678
+ // "Input must be provided either through stdin or as a prompt argument".
679
+ // helper 不 trim 不 collapse, 保 trailing whitespace 给后续 AGENT_PREFIX 解析.
680
+ const cleanedText = stripLarkMentionPlaceholders(rawEvent.text);
681
+ if (!cleanedText.trim()) {
682
+ await this.feishu.replyCard(rawEvent.messageId, renderCard({
683
+ ...createInitialState('system', 'Weaverbird', 'bot'),
684
+ text: '请在 `@bot` 后面写要执行的指令, 例如:\n• `@bot 帮我看一下这段代码`\n• `@bot /help` 看支持的命令',
685
+ includeMeta: false,
686
+ terminalState: 'done',
687
+ }));
688
+ return;
689
+ }
690
+ const event = { ...rawEvent, text: cleanedText };
691
+ this.linkThreadTopicAlias(event);
692
+ const trimmedText = event.text.trimStart();
693
+ const reverseAtThreadId = this.reverseAtThreadIdFor(event);
694
+ const captainEnabled = isCaptainEnabled({
695
+ mode: process.env['WB_MODE'] === 'multi-bot' ? 'multi-bot' : 'single',
696
+ botId: this.botId,
697
+ disableCaptainEnv: process.env['WB_DISABLE_CAPTAIN'],
698
+ });
699
+ if (captainEnabled && this.captainService) {
700
+ const cancelMatch = trimmedText.match(/^\/cancel\s+([a-zA-Z0-9._-]{1,64})$/);
701
+ if (cancelMatch) {
702
+ await handleReverseAtImCommand({
703
+ command: '/cancel',
704
+ run_id: cancelMatch[1],
705
+ requester_open_id: event.userOpenId,
706
+ requested_at: new Date().toISOString(),
707
+ message_id: event.messageId,
708
+ }, {
709
+ messageId: event.messageId,
710
+ threadId: reverseAtThreadId,
711
+ userOpenId: event.userOpenId,
712
+ }, {
713
+ captainService: this.captainService,
714
+ dataDir: this.alertDataDir,
715
+ feishu: this.feishu,
716
+ resolveAdminRole: this.reverseAtAdminRoleResolver,
717
+ resolveCancelTarget: this.resolveReverseAtCancelTarget,
718
+ executeCancel: this.executeReverseAtCancel,
719
+ listCancelableTargets: this.listReverseAtCancelableTargets,
720
+ captainConcurrency: this.buildCaptainConcurrencyDeps(event),
721
+ notifyOperator: this.reverseAtOperatorNotifier,
722
+ });
723
+ return;
724
+ }
725
+ const reverseAt = parseReverseAt(trimmedText, event.userOpenId, event.messageId);
726
+ if (reverseAt) {
727
+ await handleReverseAtImCommand(reverseAt, {
728
+ messageId: event.messageId,
729
+ threadId: reverseAtThreadId,
730
+ userOpenId: event.userOpenId,
731
+ }, {
732
+ captainService: this.captainService,
733
+ dataDir: this.alertDataDir,
734
+ feishu: this.feishu,
735
+ resolveAdminRole: this.reverseAtAdminRoleResolver,
736
+ resolveCancelTarget: this.resolveReverseAtCancelTarget,
737
+ executeCancel: this.executeReverseAtCancel,
738
+ listCancelableTargets: this.listReverseAtCancelableTargets,
739
+ captainConcurrency: this.buildCaptainConcurrencyDeps(event),
740
+ notifyOperator: this.reverseAtOperatorNotifier,
741
+ });
742
+ return;
743
+ }
744
+ }
745
+ // C5.1: typed /stop handling (before agent resolution, operates on thread-level sessions)
746
+ if (trimmedText === '/stop') {
747
+ const matching = this.activeSessionsForThread(event.userOpenId, event.threadId);
748
+ if (matching.length === 0) {
749
+ // fall through to router (returns "当前没有可停止的运行")
750
+ }
751
+ else if (matching.length === 1) {
752
+ matching[0].state = { ...matching[0].state, stopState: 'stopping' };
753
+ await this.stopSession(matching[0]);
754
+ return;
755
+ }
756
+ else {
757
+ const names = matching.map((s) => s.agentId).join(' / ');
758
+ for (const s of matching)
759
+ s.state = { ...s.state, stopState: 'stopping' };
760
+ await Promise.allSettled(matching.map((s) => this.stopSession(s)));
761
+ await this.feishu.replyCard(event.messageId, renderCard({
762
+ ...createInitialState('system', 'Weaverbird', 'bot'),
763
+ text: `已停止 ${matching.length} 个任务: ${names}`,
764
+ includeMeta: false,
765
+ terminalState: 'done',
766
+ }));
767
+ return;
768
+ }
769
+ }
770
+ // C5.1: typed /stop <id> (stop specific agent)
771
+ const stopMatch = trimmedText.match(/^\/stop\s+([a-z][a-z0-9_-]{0,31})$/);
772
+ if (stopMatch) {
773
+ const targetAgentId = stopMatch[1];
774
+ const targetScopeKey = this.scopeKey(event.userOpenId, event.threadId, targetAgentId);
775
+ const session = this.activeSessions.get(targetScopeKey);
776
+ if (session) {
777
+ session.state = { ...session.state, stopState: 'stopping' };
778
+ await this.stopSession(session);
779
+ return;
780
+ }
781
+ await this.feishu.replyCard(event.messageId, renderCard({
782
+ ...createInitialState('system', 'Weaverbird', 'bot'),
783
+ text: `${targetAgentId} 未在运行`,
784
+ includeMeta: false,
785
+ terminalState: 'done',
786
+ }));
787
+ return;
788
+ }
789
+ const requireMentionMatch = trimmedText.match(/^\/require-mention(?:\s+(on|off))?\s*$/);
790
+ if (requireMentionMatch) {
791
+ await this.replySystemCard(event.messageId, await this.handleRequireMention(event, requireMentionMatch[1]));
792
+ return;
793
+ }
794
+ // C5: /agent <id> <prompt> parsing (must be BEFORE command router, AFTER /stop)
795
+ const AGENT_PREFIX = /^\/agent\s+([a-z][a-z0-9_-]{0,31})\s+(.+)$/s;
796
+ const agentMatch = trimmedText.match(AGENT_PREFIX);
797
+ let agentOverride = null;
798
+ let promptText = event.text;
799
+ if (agentMatch) {
800
+ const requestedAgentId = agentMatch[1];
801
+ const promptBody = agentMatch[2];
802
+ const candidate = this.registry.lookup(requestedAgentId);
803
+ if (!candidate) {
804
+ const registered = this.registry.list().map((a) => a.id).join(' / ');
805
+ await this.feishu.replyCard(event.messageId, renderCard({
806
+ ...createInitialState('system', 'Weaverbird', 'bot'),
807
+ text: `❌ 未注册 agent: ${requestedAgentId}; 已注册: ${registered}`,
808
+ includeMeta: false,
809
+ terminalState: 'error',
810
+ }));
811
+ return;
812
+ }
813
+ if (!promptBody.trim()) {
814
+ await this.feishu.replyCard(event.messageId, renderCard({
815
+ ...createInitialState('system', 'Weaverbird', 'bot'),
816
+ text: '请在 /agent <id> 后面写要执行的指令',
817
+ includeMeta: false,
818
+ terminalState: 'error',
819
+ }));
820
+ return;
821
+ }
822
+ agentOverride = candidate;
823
+ promptText = promptBody;
824
+ }
825
+ // Route through command router (Batch-W2-E commands: /status, /stop-all, /logs, etc.)
826
+ // Skip router if /agent was matched (it starts with /, but it's weaverbird syntax, not a router command)
827
+ if (!agentOverride) {
828
+ const commandResult = await runCommand(event.text, {
829
+ userOpenId: event.userOpenId,
830
+ threadId: event.threadId,
831
+ registry: this.registry,
832
+ store: this.store,
833
+ botId: this.botId,
834
+ controlPlane: this.controlPlane,
835
+ activeSessions: () => this.activeSessionsSnapshot(),
836
+ stopAllSessions: () => this.stopAllSessions(),
837
+ activeSessionsForThread: (uid, tid) => this.activeSessionsForThread(uid, tid).map((s) => ({ agentId: s.agentId })),
838
+ setFollowFlag: (tid) => this.followFlags.add(tid),
839
+ queueMetricsSnapshot: this.captainConcurrency
840
+ ? () => this.captainConcurrency.metrics.snapshot({ session_id: `${this.botId}:${event.userOpenId}:${event.threadId}` })
841
+ : undefined,
842
+ muteRegistry: this.muteRegistry,
843
+ });
844
+ if (commandResult !== null) {
845
+ await this.feishu.replyCard(event.messageId, renderCard({
846
+ ...createInitialState('system', 'Weaverbird', 'bot'),
847
+ text: commandResult,
848
+ includeMeta: false,
849
+ terminalState: 'done',
850
+ }));
851
+ return;
852
+ }
853
+ }
854
+ // Resolve agent (override from /agent or binding/default)
855
+ let agent;
856
+ if (agentOverride) {
857
+ agent = agentOverride;
858
+ }
859
+ else {
860
+ const binding = this.store.getThreadBinding(this.botId, event.userOpenId, event.threadId);
861
+ agent = binding?.agentId
862
+ ? (this.registry.lookup(binding.agentId) ?? await resolveDefaultAgent(this.registry))
863
+ : await resolveDefaultAgent(this.registry);
864
+ }
865
+ if (!agent) {
866
+ logger.warn({ messageId: event.messageId, agents: this.registry.list().map((a) => a.id) }, 'no available agent');
867
+ await this.replySystemCard(event.messageId, '❌ 没有可用的 agent: 检测不到 claude / codex 命令。检查 `WB_CLAUDE_COMMAND` / `WB_CODEX_COMMAND` 指向的命令是否在 PATH 上。');
868
+ return;
869
+ }
870
+ // Now that agent is resolved, compute scopeKey (C1: contains agentId)
871
+ const scopeKey = this.scopeKey(event.userOpenId, event.threadId, agent.id);
872
+ // Resolve cwd
873
+ const binding = this.store.getThreadBinding(this.botId, event.userOpenId, event.threadId);
874
+ let cwd;
875
+ if (binding?.cwd) {
876
+ cwd = binding.cwd;
877
+ }
878
+ else if (this.defaultCwd) {
879
+ cwd = this.defaultCwd;
880
+ }
881
+ else {
882
+ const fallback = process.cwd();
883
+ const cwdResult = validateCwd(fallback);
884
+ if (!cwdResult.ok) {
885
+ await this.feishu.replyCard(event.messageId, renderCard({
886
+ ...createInitialState('system', 'Weaverbird', 'bot'),
887
+ text: '⚠️ bot 当前工作目录不在允许范围, 请先 `/cwd <dir>` 设置',
888
+ includeMeta: false,
889
+ terminalState: 'error',
890
+ errorMessage: cwdResult.reason,
891
+ }));
892
+ return;
893
+ }
894
+ cwd = cwdResult.path;
895
+ }
896
+ let inputExtras = {};
897
+ if ((event.resources && event.resources.length > 0) || event.parentId) {
898
+ const input = await buildAgentInput({
899
+ messageId: event.messageId,
900
+ text: promptText,
901
+ resources: event.resources,
902
+ parentId: event.parentId,
903
+ }, {
904
+ botOpenId: '',
905
+ fetchMessage: this.feishu.fetchMessage?.bind(this.feishu),
906
+ media: this.resolveMediaCache(),
907
+ });
908
+ promptText = input.text;
909
+ inputExtras = { images: input.images, attachments: input.attachments, notices: input.notices };
910
+ if (input.notices.length > 0)
911
+ logger.warn({ messageId: event.messageId, notices: input.notices }, 'agent input assembled with notices');
912
+ }
913
+ if (captainEnabled && this.captainService) {
914
+ const sessionId = this.sessionIdFor(event.userOpenId, event.threadId);
915
+ const homeGroupId = this.homeGroupIdFor(event);
916
+ const existingSession = this.captainService.getSession(sessionId);
917
+ const normalizedAgent = agent.id === 'claude-code' || agent.id === 'codex' ? agent.id : 'other';
918
+ const record = {
919
+ session_id: sessionId,
920
+ captain_id: this.botId,
921
+ created_at: new Date().toISOString(),
922
+ last_active_at: new Date().toISOString(),
923
+ cwd,
924
+ scope: 'dev',
925
+ project: 'weaverbird',
926
+ home_group_id: homeGroupId,
927
+ agent: normalizedAgent,
928
+ latest_run_id: null,
929
+ operator: event.userOpenId,
930
+ entry_form: 'im',
931
+ };
932
+ if (existingSession) {
933
+ this.captainService.updateSession(sessionId, {
934
+ cwd,
935
+ last_active_at: new Date().toISOString(),
936
+ agent: record.agent,
937
+ operator: event.userOpenId,
938
+ home_group_id: homeGroupId,
939
+ entry_form: 'im',
940
+ });
941
+ }
942
+ else {
943
+ this.captainService.createSession(record);
944
+ }
945
+ }
946
+ const captainSessionId = this.sessionIdFor(event.userOpenId, event.threadId);
947
+ let forcedRunId = this.injectedRunIds.get(rawEvent.eventId);
948
+ if (captainEnabled && this.captainConcurrency) {
949
+ const decision = await enqueueOrSpawn({
950
+ config: this.captainConcurrency.config,
951
+ index: this.captainConcurrency.index,
952
+ store: this.captainConcurrency.store,
953
+ metrics: this.captainConcurrency.metrics,
954
+ now: this.captainConcurrency.now ?? (() => new Date().toISOString()),
955
+ genRunId: this.captainConcurrency.genRunId ?? generateRunId,
956
+ }, {
957
+ session_id: captainSessionId,
958
+ });
959
+ if (decision.kind === 'queued') {
960
+ this.pendingCaptainRuns.set(decision.run_id, {
961
+ event: { ...event, ...inputExtras, text: promptText },
962
+ agent,
963
+ cwd,
964
+ scopeKey,
965
+ skipBindingUpdate: agentOverride !== null,
966
+ runId: decision.run_id,
967
+ });
968
+ this.ackReactions.add(event.messageId);
969
+ await this.feishu.replyText(event.messageId, `queued at position ${decision.position}`);
970
+ return;
971
+ }
972
+ if (decision.kind === 'rejected') {
973
+ await this.feishu.replyText(event.messageId, 'queue full');
974
+ return;
975
+ }
976
+ forcedRunId = decision.run_id;
977
+ }
978
+ else {
979
+ // C3: busy check per (user, thread, agent). 进行中就排队, 本轮结束后合并成下一轮.
980
+ // 起跑中 (卡片还在创建、session 还没注册) 和等待接续排队消息的 scope 同样算忙, 否则会并发起两轮.
981
+ if (this.activeSessions.has(scopeKey) || this.startingScopes.has(scopeKey) || this.followUps.has(scopeKey)) {
982
+ await this.enqueueFollowUp(scopeKey, {
983
+ event: { ...event, ...inputExtras, text: promptText },
984
+ agent,
985
+ cwd,
986
+ isAgentOverride: agentOverride !== null,
987
+ });
988
+ return;
989
+ }
990
+ }
991
+ // Use promptText (may be overridden by /agent) via modified event
992
+ const effectiveEvent = { ...event, ...inputExtras, text: promptText };
993
+ await this.startAgentRun(effectiveEvent, agent, cwd, scopeKey, agentOverride !== null, forcedRunId);
994
+ }
995
+ async startAgentRun(effectiveEvent, agent, cwd, scopeKey, isAgentOverride, forcedRunId) {
996
+ const startToken = Symbol(scopeKey);
997
+ this.startingScopes.set(scopeKey, startToken);
998
+ try {
999
+ this.ackReactions.add(effectiveEvent.messageId);
1000
+ if (effectiveEvent.mergedMessageIds && effectiveEvent.mergedMessageIds.length > 0) {
1001
+ this.mergedAckIds.set(effectiveEvent.messageId, effectiveEvent.mergedMessageIds);
1002
+ }
1003
+ const replyMessageId = await this.feishu.replyCard(effectiveEvent.messageId, renderCard(createInitialState(agent.id, agent.displayName, agent.displayName)));
1004
+ rememberBounded(this.runCards, replyMessageId, {
1005
+ sourceMessageId: effectiveEvent.messageId,
1006
+ userOpenId: effectiveEvent.userOpenId,
1007
+ threadId: effectiveEvent.threadId,
1008
+ agentId: agent.id,
1009
+ cwd,
1010
+ });
1011
+ if (this.runnerConfig) {
1012
+ await this.handleMessageViaWbRunner(effectiveEvent, agent, cwd, replyMessageId, scopeKey, isAgentOverride, forcedRunId);
1013
+ }
1014
+ else {
1015
+ await this.handleMessageViaPipe(effectiveEvent, agent, cwd, replyMessageId, scopeKey, isAgentOverride, forcedRunId);
1016
+ }
1017
+ }
1018
+ catch (error) {
1019
+ // 起跑就失败 (没注册 session, 不会走 cleanupSession): 起跑窗口里排进来的消息要接着处理, 不能一直挂着.
1020
+ if (!this.activeSessions.has(scopeKey) && this.followUps.has(scopeKey)) {
1021
+ setImmediate(() => {
1022
+ this.drainFollowUps(scopeKey).catch((drainError) => logger.error({ scopeKey, error: drainError }, 'follow-up drain failed'));
1023
+ });
1024
+ }
1025
+ throw error;
1026
+ }
1027
+ finally {
1028
+ // 排队消息的下一轮可能已经在本调用返回前起跑, 只清自己设的标记.
1029
+ if (this.startingScopes.get(scopeKey) === startToken)
1030
+ this.startingScopes.delete(scopeKey);
1031
+ }
1032
+ }
1033
+ /** 注册运行中的 session, 并接上起跑窗口里已经排进来的消息 (排队数 + 排队提示卡). */
1034
+ registerSession(scopeKey, session) {
1035
+ this.activeSessions.set(scopeKey, session);
1036
+ const queue = this.followUps.get(scopeKey);
1037
+ if (!queue || queue.length === 0)
1038
+ return;
1039
+ session.state = { ...session.state, queuedCount: queue.length };
1040
+ for (const item of queue) {
1041
+ if (!item.noticeMessageId)
1042
+ continue;
1043
+ session.extraMessageIds.push(item.noticeMessageId);
1044
+ this.activeSessionsByMessageId.set(item.noticeMessageId, session);
1045
+ }
1046
+ }
1047
+ async enqueueFollowUp(scopeKey, item) {
1048
+ const queue = this.followUps.get(scopeKey) ?? [];
1049
+ queue.push(item);
1050
+ this.followUps.set(scopeKey, queue);
1051
+ this.ackReactions.add(item.event.messageId);
1052
+ // 起跑中还没有 session: 运行卡上的排队数在 session 注册时补上.
1053
+ const activeSession = this.activeSessions.get(scopeKey);
1054
+ if (activeSession) {
1055
+ activeSession.state = { ...activeSession.state, queuedCount: queue.length };
1056
+ void activeSession.pipeline.flush(renderCard(activeSession.state));
1057
+ }
1058
+ const noticeId = await this.feishu.replyCard(item.event.messageId, renderCard({
1059
+ ...createInitialState('system', 'Weaverbird', 'bot'),
1060
+ text: `⏳ ${item.agent.id} 正在处理上一条, 这条已排队 (第 ${queue.length} 条), 结束后自动接着处理`,
1061
+ includeMeta: false,
1062
+ stopState: 'running',
1063
+ terminalState: 'running',
1064
+ }));
1065
+ item.noticeMessageId = noticeId;
1066
+ const current = this.activeSessions.get(scopeKey);
1067
+ if (current) {
1068
+ current.extraMessageIds.push(noticeId);
1069
+ this.activeSessionsByMessageId.set(noticeId, current);
1070
+ }
1071
+ }
1072
+ /**
1073
+ * 用户撤回消息. 只处理还没开始跑的排队消息: 从队列移除并改写它的排队提示卡;
1074
+ * 已经在跑的 run 不动 (撤回不等于叫停, 要停请点停止).
1075
+ */
1076
+ async handleMessageRecalled(messageId) {
1077
+ for (const [scopeKey, queue] of this.followUps) {
1078
+ const index = queue.findIndex((item) => item.event.messageId === messageId);
1079
+ if (index === -1)
1080
+ continue;
1081
+ const [item] = queue.splice(index, 1);
1082
+ if (queue.length === 0)
1083
+ this.followUps.delete(scopeKey);
1084
+ void this.ackReactions.clear(messageId);
1085
+ const active = this.activeSessions.get(scopeKey);
1086
+ if (active) {
1087
+ active.state = { ...active.state, queuedCount: queue.length };
1088
+ void active.pipeline.flush(renderCard(active.state));
1089
+ }
1090
+ if (item?.noticeMessageId) {
1091
+ await this.feishu.updateCard(item.noticeMessageId, renderCard({
1092
+ ...createInitialState('system', 'Weaverbird', 'bot'),
1093
+ text: '↩️ 消息已撤回, 不再处理',
1094
+ includeMeta: false,
1095
+ terminalState: 'done',
1096
+ }));
1097
+ }
1098
+ logger.info({ scopeKey, messageId }, 'dropped recalled follow-up');
1099
+ return true;
1100
+ }
1101
+ return false;
1102
+ }
1103
+ /** 停止 = 这个 scope 不再处理: 排队消息一起丢弃, 不在停止后自动起新 run. */
1104
+ dropFollowUps(scopeKey) {
1105
+ const queue = this.followUps.get(scopeKey);
1106
+ if (!queue)
1107
+ return;
1108
+ this.followUps.delete(scopeKey);
1109
+ for (const item of queue) {
1110
+ void this.ackReactions.clear(item.event.messageId);
1111
+ if (!item.noticeMessageId)
1112
+ continue;
1113
+ void this.feishu.updateCard(item.noticeMessageId, renderCard({
1114
+ ...createInitialState('system', 'Weaverbird', 'bot'),
1115
+ text: '⏹ 已随上一条一起停止, 需要的话重新发送',
1116
+ includeMeta: false,
1117
+ terminalState: 'done',
1118
+ })).catch((error) => logger.warn({ noticeId: item.noticeMessageId, error }, 'follow-up notice update failed'));
1119
+ }
1120
+ }
1121
+ /** 本轮结束后把排队的消息合并成下一轮. 关停 drain 中则丢弃并撤回执. */
1122
+ async drainFollowUps(scopeKey) {
1123
+ const queue = this.followUps.get(scopeKey);
1124
+ if (!queue || queue.length === 0)
1125
+ return;
1126
+ if (this.activeSessions.has(scopeKey))
1127
+ return;
1128
+ this.followUps.delete(scopeKey);
1129
+ const notices = queue.map((item) => item.noticeMessageId).filter((id) => Boolean(id));
1130
+ if (this.draining) {
1131
+ for (const item of queue)
1132
+ void this.ackReactions.clear(item.event.messageId);
1133
+ return;
1134
+ }
1135
+ for (const noticeId of notices) {
1136
+ void this.feishu.updateCard(noticeId, renderCard({
1137
+ ...createInitialState('system', 'Weaverbird', 'bot'),
1138
+ text: queue.length > 1 ? `▶️ 已合并 ${queue.length} 条排队消息开始处理` : '▶️ 已开始处理这条',
1139
+ includeMeta: false,
1140
+ terminalState: 'done',
1141
+ })).catch((error) => logger.warn({ noticeId, error }, 'follow-up notice update failed'));
1142
+ }
1143
+ // 运行卡回复在最后一条上. 它已被撤回 (没订阅撤回事件, 或事件晚到) 时回复会报 230011:
1144
+ // 去掉这条, 用剩下的重来.
1145
+ let items = queue;
1146
+ while (items.length > 0) {
1147
+ const last = items[items.length - 1];
1148
+ try {
1149
+ await this.startAgentRun(mergeMessageEvents(items.map((item) => item.event)), last.agent, last.cwd, scopeKey, last.isAgentOverride);
1150
+ return;
1151
+ }
1152
+ catch (error) {
1153
+ if (feishuErrorCode(error) !== MESSAGE_WITHDRAWN)
1154
+ throw error;
1155
+ logger.info({ scopeKey, messageId: last.event.messageId }, 'queued message was withdrawn before its turn, skipping');
1156
+ void this.ackReactions.clear(last.event.messageId);
1157
+ if (last.noticeMessageId) {
1158
+ void this.feishu.updateCard(last.noticeMessageId, renderCard({
1159
+ ...createInitialState('system', 'Weaverbird', 'bot'),
1160
+ text: '↩️ 消息已撤回, 不再处理',
1161
+ includeMeta: false,
1162
+ terminalState: 'done',
1163
+ })).catch((noticeError) => logger.warn({ noticeId: last.noticeMessageId, error: noticeError }, 'follow-up notice update failed'));
1164
+ }
1165
+ items = items.slice(0, -1);
1166
+ }
1167
+ }
1168
+ }
1169
+ async handleMessageViaWbRunner(event, agent, cwd, replyMessageId, scopeKey, skipBindingUpdate = false, forcedRunId) {
1170
+ const captainEnabled = isCaptainEnabled({
1171
+ mode: process.env['WB_MODE'] === 'multi-bot' ? 'multi-bot' : 'single',
1172
+ botId: this.botId,
1173
+ disableCaptainEnv: process.env['WB_DISABLE_CAPTAIN'],
1174
+ });
1175
+ const config = this.runnerConfig;
1176
+ const runId = forcedRunId ?? generateRunId();
1177
+ const sessionId = this.sessionIdFor(event.userOpenId, event.threadId);
1178
+ const homeGroupId = this.homeGroupIdFor(event);
1179
+ const botId = config.botId ?? 'default';
1180
+ const continuationToken = this.store.getContinuation(this.botId, event.userOpenId, event.threadId, agent.id) ?? undefined;
1181
+ const consentLevel = (this.claudeConsentLevel && agent.id === 'claude-code') ? this.claudeConsentLevel : undefined;
1182
+ // D1: codex 路径 env passthrough 复用 core CodexAgent 的 CODEX_PASSTHROUGH_KEYS,
1183
+ // 不在此重复 keys 列表 (单一 source of truth). claude-code 路径维持原 ANTHROPIC_* 透传.
1184
+ const passthroughKeys = agent.id === 'claude-code'
1185
+ ? ['ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL', 'ANTHROPIC_MODEL']
1186
+ : agent.id === 'codex'
1187
+ ? CODEX_PASSTHROUGH_KEYS
1188
+ : [];
1189
+ let agentEnv = buildFilteredEnv('agent-cli', process.env, passthroughKeys);
1190
+ const claudeRaw = (process.env['WB_CLAUDE_COMMAND'] ?? '').trim();
1191
+ const codexRaw = (process.env['WB_CODEX_COMMAND'] ?? '').trim();
1192
+ const [claudeHead, ...claudePrepend] = claudeRaw ? claudeRaw.split(/\s+/) : ['claude'];
1193
+ const [codexHead, ...codexPrepend] = codexRaw ? codexRaw.split(/\s+/) : ['codex'];
1194
+ const agentCommand = agent.id === 'claude-code' ? claudeHead : codexHead;
1195
+ const prependArgs = agent.id === 'claude-code' ? claudePrepend : codexPrepend;
1196
+ // Single source of truth for model: 如果 WB_CLAUDE_COMMAND 写了 `--model X`,
1197
+ // 自动 propagate 到 child env 作 ANTHROPIC_MODEL (claude --print stream-json
1198
+ // mode 不 honor CLI --model flag, 必须 env var; wrapper 在
1199
+ // has_model_flag=1 path 下不 export 该 env, 所以 wb-bot 必须补).
1200
+ // 父进程已显式 set ANTHROPIC_MODEL 时优先尊重父进程.
1201
+ if (agent.id === 'claude-code' && !agentEnv['ANTHROPIC_MODEL']) {
1202
+ const modelFromCommand = extractModelFromArgs(claudePrepend);
1203
+ if (modelFromCommand) {
1204
+ agentEnv['ANTHROPIC_MODEL'] = modelFromCommand;
1205
+ }
1206
+ }
1207
+ // D1: 对称 claude 的 model 抽取. WB_CODEX_COMMAND="codex --model X" 时
1208
+ // `--model X` 必须以 `exec --model X` 形式 splice 进 codex argv (core CodexAgent
1209
+ // 同位置), 不能放到 codex 子命令前. 这里把它从 prepend 抽出, 由 buildAgentArgs splice 进位.
1210
+ const codexModel = agent.id === 'codex' ? extractModelFromArgs(codexPrepend) : undefined;
1211
+ const codexPrependWithoutModel = agent.id === 'codex' && codexModel
1212
+ ? stripModelArgs(codexPrepend)
1213
+ : codexPrepend;
1214
+ const effectivePrepend = agent.id === 'codex' ? codexPrependWithoutModel : prependArgs;
1215
+ const builtArgs = this.buildAgentArgs(agent.id, event.text, cwd, continuationToken, consentLevel, codexModel, event.images);
1216
+ const codexApprovalArgs = agent.id === 'codex' && this.approvalHookFiles
1217
+ ? this.approvalHookFiles.codexRuntimeArgs
1218
+ : [];
1219
+ const agentArgs = agent.id === 'codex'
1220
+ ? [...effectivePrepend, ...injectCodexExecArgs(builtArgs, codexApprovalArgs)]
1221
+ : [...effectivePrepend, ...builtArgs];
1222
+ // D1: codex 走 stdin (codex `exec --json ... -` 约定从 stdin 读 prompt).
1223
+ // claude-code 维持原 argv 末尾 prompt + stdio[0]='ignore' 不变.
1224
+ const stdinInput = agent.id === 'codex' ? `${event.text}\n` : undefined;
1225
+ if (agent.id === 'claude-code' && this.approvalHookFiles) {
1226
+ agentEnv['CLAUDE_CONFIG_DIR'] = dirname(this.approvalHookFiles.claudeSettingsPath);
1227
+ agentArgs.unshift('--settings', this.approvalHookFiles.claudeSettingsPath);
1228
+ agentArgs.unshift('--bare');
1229
+ }
1230
+ if (agent.id === 'codex' && this.approvalHookFiles) {
1231
+ agentEnv['CODEX_HOME'] = this.approvalHookFiles.codexHome;
1232
+ }
1233
+ agentEnv = buildApprovalHookEnv(agentEnv, {
1234
+ dataDir: config.dataDir,
1235
+ runId,
1236
+ botId,
1237
+ sessionId,
1238
+ userOpenId: event.userOpenId,
1239
+ threadId: event.threadId,
1240
+ sourceMessageId: event.messageId,
1241
+ replyMessageId,
1242
+ agentId: agent.id,
1243
+ codeOwnerConfigPath: process.env['WB_APPROVAL_CODE_OWNER_CONFIG_PATH'],
1244
+ });
1245
+ const spec = buildRunSpec({
1246
+ runId,
1247
+ botId,
1248
+ agentId: agent.id,
1249
+ agentCommand,
1250
+ agentArgs,
1251
+ cwd,
1252
+ env: agentEnv,
1253
+ userOpenId: event.userOpenId,
1254
+ threadId: event.threadId,
1255
+ sourceMessageId: event.messageId,
1256
+ replyMessageId,
1257
+ continuationToken,
1258
+ consentLevel,
1259
+ ...(stdinInput !== undefined ? { stdinInput } : {}),
1260
+ });
1261
+ let runDir;
1262
+ try {
1263
+ ({ runDir } = spawnWbRunner({
1264
+ dataDir: config.dataDir,
1265
+ spec,
1266
+ wbRunnerMainPath: config.wbRunnerMainPath,
1267
+ }));
1268
+ if (captainEnabled && this.captainService) {
1269
+ this.captainService.bindRun(sessionId, runId);
1270
+ }
1271
+ if (captainEnabled && this.captainConcurrency) {
1272
+ this.captainConcurrency.index.markRunning(sessionId, runId, new Date().toISOString());
1273
+ }
1274
+ if (this.calendarHookConfig?.enabled && this.calendarTransport) {
1275
+ void openCalendarBlock({
1276
+ dataDir: config.dataDir,
1277
+ botId,
1278
+ runId,
1279
+ sessionId,
1280
+ revision: 0,
1281
+ title: `Weaverbird Run ${runId}`,
1282
+ startsAt: new Date().toISOString(),
1283
+ endsAt: new Date(Date.now() + this.calendarHookConfig.overdue_after_ms).toISOString(),
1284
+ config: this.calendarHookConfig,
1285
+ transport: this.calendarTransport,
1286
+ });
1287
+ }
1288
+ }
1289
+ catch (err) {
1290
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `wb-runner spawn failed for ${agent.id}: ${err}`, 'fatal');
1291
+ throw err;
1292
+ }
1293
+ const pipeline = new CardPipeline((card) => this.feishu.updateCard(replyMessageId, card), {
1294
+ logger,
1295
+ label: `reply:${replyMessageId}`,
1296
+ minIntervalMs: this.cardIntervalMs(replyMessageId),
1297
+ });
1298
+ const progressStore = new ProgressStore({
1299
+ dataDir: config.dataDir,
1300
+ botId,
1301
+ runId,
1302
+ sessionId,
1303
+ originMessageId: event.messageId,
1304
+ cardMessageId: replyMessageId,
1305
+ homeGroupId,
1306
+ });
1307
+ const progressCollector = new ProgressCollector(progressStore);
1308
+ // 运行卡只有一个写者: 下面按 AgentEvent 渲染的 renderCard(state).
1309
+ // run-observability 仍负责 progress.ndjson / store / 告警 / doc-sink, 但不再往同一张卡上
1310
+ // 刷 "Run Progress" 进度卡, 也不在结束时用 "Run Finalized" 原始输出覆盖答案并重复回一张卡.
1311
+ const silentCards = { updateCard: async () => { }, replyCard: async () => { }, sendCard: async () => { } };
1312
+ const observability = wireRunObservability(runDir, {
1313
+ collector: progressCollector,
1314
+ store: progressStore,
1315
+ finalizerClient: silentCards,
1316
+ dataDir: config.dataDir,
1317
+ alertContext: {
1318
+ session: {
1319
+ session_id: sessionId,
1320
+ home_group_id: homeGroupId,
1321
+ operator: event.userOpenId,
1322
+ agent: 'claude-code',
1323
+ },
1324
+ dataDir: config.dataDir,
1325
+ client: {
1326
+ sendMessage: (chatId, card) => this.sendCard(chatId, card),
1327
+ },
1328
+ alertEnabled: true,
1329
+ alreadyAlerted: false,
1330
+ },
1331
+ });
1332
+ const shortId = this.reserveVisibleSessionShortId(runId);
1333
+ let state = {
1334
+ ...createInitialState(agent.id, agent.displayName, agent.displayName),
1335
+ sessionShortId: shortId,
1336
+ adminCancelEnabled: captainEnabled,
1337
+ ...(event.notices && event.notices.length > 0 ? { notices: event.notices } : {}),
1338
+ };
1339
+ const eventsReader = new EventsFileReader(join(runDir, 'events.ndjson'), 0, runnerEventMapper(agent.id, { cwd, model: codexModel }));
1340
+ const activeSession = {
1341
+ scopeKey,
1342
+ threadId: event.threadId,
1343
+ homeGroupId,
1344
+ sourceMessageId: event.messageId,
1345
+ replyMessageId,
1346
+ run: null,
1347
+ runId,
1348
+ pipeline,
1349
+ state,
1350
+ extraMessageIds: [],
1351
+ eventsReader,
1352
+ startedAt: Date.now(),
1353
+ agentId: agent.id,
1354
+ sessionId,
1355
+ };
1356
+ this.registerSession(scopeKey, activeSession);
1357
+ this.activeSessionsByMessageId.set(event.messageId, activeSession);
1358
+ this.activeSessionsByMessageId.set(replyMessageId, activeSession);
1359
+ this.activeSessionsByShortId.set(shortId, activeSession);
1360
+ this.store.upsertInflightCard(this.botId, {
1361
+ userOpenId: event.userOpenId,
1362
+ threadId: event.threadId,
1363
+ sourceMessageId: event.messageId,
1364
+ replyMessageId,
1365
+ runId,
1366
+ agentId: agent.id,
1367
+ });
1368
+ logger.info({ scopeKey, runId, agentId: agent.id, replyMessageId }, 'spawned wb-runner session');
1369
+ eventsReader.start();
1370
+ try {
1371
+ const outputLogPath = join(runDir, 'output.log');
1372
+ const outputErrPath = join(runDir, 'output.err');
1373
+ let stdoutOffset = 0;
1374
+ let stderrOffset = 0;
1375
+ let lastLogReadAt = 0;
1376
+ for await (const output of eventsReader.events()) {
1377
+ // 流式下每个 delta 都是一个事件, 每次整读 output.log 会退化成 O(n²); 节流到 1s, 终态必读.
1378
+ const isTerminal = output.type === 'done' || output.type === 'error';
1379
+ if (isTerminal || Date.now() - lastLogReadAt >= 1000) {
1380
+ lastLogReadAt = Date.now();
1381
+ try {
1382
+ const stdoutRaw = readFileSync(outputLogPath, 'utf8');
1383
+ const stderrRaw = readFileSync(outputErrPath, 'utf8');
1384
+ const nextStdout = stdoutRaw.slice(stdoutOffset);
1385
+ const nextStderr = stderrRaw.slice(stderrOffset);
1386
+ if (nextStdout)
1387
+ observability.onStdout(nextStdout);
1388
+ if (nextStderr)
1389
+ observability.onStderr(nextStderr);
1390
+ stdoutOffset = stdoutRaw.length;
1391
+ stderrOffset = stderrRaw.length;
1392
+ }
1393
+ catch {
1394
+ // logs may not exist yet
1395
+ }
1396
+ }
1397
+ state = reduceStreamState(activeSession.state, output);
1398
+ activeSession.state = state;
1399
+ if ((output.type === 'done' || output.type === 'system') && output.continuationToken) {
1400
+ this.store.upsertContinuation(this.botId, event.userOpenId, event.threadId, agent.id, output.continuationToken);
1401
+ }
1402
+ await (output.type === 'tool_use' || output.type === 'tool_result' || output.type === 'done' || output.type === 'error'
1403
+ ? pipeline.force(renderCard(state))
1404
+ : pipeline.flush(renderCard(state)));
1405
+ if (output.type === 'done') {
1406
+ await observability.onExit({
1407
+ status: 'succeeded',
1408
+ cancelled: false,
1409
+ elapsedS: Math.max(0, Math.floor((Date.now() - activeSession.startedAt) / 1000)),
1410
+ });
1411
+ if (captainEnabled && this.captainService) {
1412
+ this.captainService.closeSession(sessionId);
1413
+ }
1414
+ if (this.calendarHookConfig?.enabled && this.calendarTransport) {
1415
+ void closeCalendarBlock({
1416
+ dataDir: config.dataDir,
1417
+ botId,
1418
+ runId,
1419
+ revision: 1,
1420
+ config: this.calendarHookConfig,
1421
+ transport: this.calendarTransport,
1422
+ });
1423
+ }
1424
+ await this.onCaptainRunEnded(event.userOpenId, event.threadId, runId, 'succeeded');
1425
+ await this.handleCompletionPush(activeSession, agent, event.userOpenId, event.threadId);
1426
+ break;
1427
+ }
1428
+ if (output.type === 'error') {
1429
+ const reason = activeSession.state.stopState === 'stopping' ? 'cancelled' : 'failed';
1430
+ await observability.onExit({
1431
+ status: reason,
1432
+ cancelled: activeSession.state.stopState === 'stopping',
1433
+ elapsedS: Math.max(0, Math.floor((Date.now() - activeSession.startedAt) / 1000)),
1434
+ exitMeta: /^child exited with code (?<exitCode>-?\d+)$/.test(output.message)
1435
+ ? { exit_code: Number(/^child exited with code (?<exitCode>-?\d+)$/.exec(output.message)?.groups?.['exitCode'] ?? null), signal: null }
1436
+ : undefined,
1437
+ });
1438
+ if (captainEnabled && this.captainService) {
1439
+ this.captainService.closeSession(sessionId);
1440
+ }
1441
+ if (this.calendarHookConfig?.enabled && this.calendarTransport) {
1442
+ void closeCalendarBlock({
1443
+ dataDir: config.dataDir,
1444
+ botId,
1445
+ runId,
1446
+ revision: 1,
1447
+ config: this.calendarHookConfig,
1448
+ transport: this.calendarTransport,
1449
+ });
1450
+ }
1451
+ await this.onCaptainRunEnded(event.userOpenId, event.threadId, runId, reason);
1452
+ break;
1453
+ }
1454
+ }
1455
+ if (!skipBindingUpdate) {
1456
+ this.store.upsertThreadBinding(this.botId, {
1457
+ userOpenId: event.userOpenId,
1458
+ threadId: event.threadId,
1459
+ agentId: agent.id,
1460
+ cwd,
1461
+ });
1462
+ }
1463
+ }
1464
+ finally {
1465
+ eventsReader.stop();
1466
+ this.cleanupSession(activeSession, event.userOpenId, event.threadId);
1467
+ }
1468
+ }
1469
+ async handleMessageViaPipe(event, agent, cwd, replyMessageId, scopeKey, skipBindingUpdate = false, forcedRunId) {
1470
+ const captainEnabled = isCaptainEnabled({
1471
+ mode: process.env['WB_MODE'] === 'multi-bot' ? 'multi-bot' : 'single',
1472
+ botId: this.botId,
1473
+ disableCaptainEnv: process.env['WB_DISABLE_CAPTAIN'],
1474
+ });
1475
+ const runId = forcedRunId ?? generateRunId();
1476
+ const sessionId = this.sessionIdFor(event.userOpenId, event.threadId);
1477
+ const homeGroupId = this.homeGroupIdFor(event);
1478
+ const run = agent.run({
1479
+ prompt: event.text,
1480
+ cwd,
1481
+ ...(event.images && event.images.length > 0 ? { images: event.images } : {}),
1482
+ ...(event.attachments && event.attachments.length > 0 ? { attachments: event.attachments } : {}),
1483
+ continuationToken: this.store.getContinuation(this.botId, event.userOpenId, event.threadId, agent.id) ?? undefined,
1484
+ ...(this.claudeConsentLevel && agent.id === 'claude-code' ? { consentLevel: this.claudeConsentLevel } : {}),
1485
+ });
1486
+ const pipeline = new CardPipeline((card) => this.feishu.updateCard(replyMessageId, card), {
1487
+ logger,
1488
+ label: `reply:${replyMessageId}`,
1489
+ minIntervalMs: this.cardIntervalMs(replyMessageId),
1490
+ });
1491
+ const shortId = this.reserveVisibleSessionShortId(forcedRunId ?? event.messageId);
1492
+ let state = {
1493
+ ...createInitialState(agent.id, agent.displayName, agent.displayName),
1494
+ sessionShortId: shortId,
1495
+ adminCancelEnabled: captainEnabled,
1496
+ ...(event.notices && event.notices.length > 0 ? { notices: event.notices } : {}),
1497
+ };
1498
+ const activeSession = {
1499
+ scopeKey,
1500
+ threadId: event.threadId,
1501
+ homeGroupId,
1502
+ sourceMessageId: event.messageId,
1503
+ replyMessageId,
1504
+ run,
1505
+ runId,
1506
+ pipeline,
1507
+ state,
1508
+ extraMessageIds: [],
1509
+ startedAt: Date.now(),
1510
+ agentId: agent.id,
1511
+ sessionId: captainEnabled ? sessionId : undefined,
1512
+ };
1513
+ this.registerSession(scopeKey, activeSession);
1514
+ this.activeSessionsByMessageId.set(event.messageId, activeSession);
1515
+ this.activeSessionsByMessageId.set(replyMessageId, activeSession);
1516
+ if (shortId)
1517
+ this.activeSessionsByShortId.set(shortId, activeSession);
1518
+ this.store.upsertInflightCard(this.botId, {
1519
+ userOpenId: event.userOpenId,
1520
+ threadId: event.threadId,
1521
+ sourceMessageId: event.messageId,
1522
+ replyMessageId,
1523
+ runId,
1524
+ agentId: agent.id,
1525
+ });
1526
+ if (this.calendarHookConfig?.enabled && this.calendarTransport) {
1527
+ void openCalendarBlock({
1528
+ dataDir: this.alertDataDir,
1529
+ botId: this.botId,
1530
+ runId,
1531
+ sessionId,
1532
+ revision: 0,
1533
+ title: `Weaverbird Run ${runId}`,
1534
+ startsAt: new Date().toISOString(),
1535
+ endsAt: new Date(Date.now() + this.calendarHookConfig.overdue_after_ms).toISOString(),
1536
+ config: this.calendarHookConfig,
1537
+ transport: this.calendarTransport,
1538
+ });
1539
+ }
1540
+ logger.info({
1541
+ scopeKey,
1542
+ sourceMessageId: event.messageId,
1543
+ replyMessageId,
1544
+ activeSessionKeys: Array.from(this.activeSessionsByMessageId.keys()),
1545
+ state: summarizeState(state),
1546
+ }, 'registered active session');
1547
+ try {
1548
+ for await (const output of run.events) {
1549
+ state = reduceStreamState(activeSession.state, output);
1550
+ activeSession.state = state;
1551
+ logger.info({
1552
+ scopeKey,
1553
+ outputType: output.type,
1554
+ sourceMessageId: activeSession.sourceMessageId,
1555
+ replyMessageId: activeSession.replyMessageId,
1556
+ state: summarizeState(state),
1557
+ }, 'updated active session state');
1558
+ if ((output.type === 'done' || output.type === 'system') && output.continuationToken) {
1559
+ this.store.upsertContinuation(this.botId, event.userOpenId, event.threadId, agent.id, output.continuationToken);
1560
+ }
1561
+ await (output.type === 'tool_use' || output.type === 'tool_result' || output.type === 'done' || output.type === 'error'
1562
+ ? pipeline.force(renderCard(state))
1563
+ : pipeline.flush(renderCard(state)));
1564
+ if (output.type === 'done') {
1565
+ if (captainEnabled && this.captainService) {
1566
+ this.captainService.closeSession(sessionId);
1567
+ }
1568
+ if (this.calendarHookConfig?.enabled && this.calendarTransport) {
1569
+ void closeCalendarBlock({
1570
+ dataDir: this.alertDataDir,
1571
+ botId: this.botId,
1572
+ runId,
1573
+ revision: 1,
1574
+ config: this.calendarHookConfig,
1575
+ transport: this.calendarTransport,
1576
+ });
1577
+ }
1578
+ await this.onCaptainRunEnded(event.userOpenId, event.threadId, runId, 'succeeded');
1579
+ await this.handleCompletionPush(activeSession, agent, event.userOpenId, event.threadId);
1580
+ break;
1581
+ }
1582
+ if (output.type === 'error') {
1583
+ if (captainEnabled && this.captainService) {
1584
+ this.captainService.closeSession(sessionId);
1585
+ }
1586
+ if (this.calendarHookConfig?.enabled && this.calendarTransport) {
1587
+ void closeCalendarBlock({
1588
+ dataDir: this.alertDataDir,
1589
+ botId: this.botId,
1590
+ runId,
1591
+ revision: 1,
1592
+ config: this.calendarHookConfig,
1593
+ transport: this.calendarTransport,
1594
+ });
1595
+ }
1596
+ await this.onCaptainRunEnded(event.userOpenId, event.threadId, runId, activeSession.state.stopState === 'stopping' ? 'cancelled' : 'failed');
1597
+ break;
1598
+ }
1599
+ }
1600
+ if (!skipBindingUpdate) {
1601
+ this.store.upsertThreadBinding(this.botId, {
1602
+ userOpenId: event.userOpenId,
1603
+ threadId: event.threadId,
1604
+ agentId: agent.id,
1605
+ cwd: cwd,
1606
+ });
1607
+ }
1608
+ }
1609
+ finally {
1610
+ logger.info({
1611
+ scopeKey,
1612
+ sourceMessageId: activeSession.sourceMessageId,
1613
+ replyMessageId: activeSession.replyMessageId,
1614
+ state: summarizeState(activeSession.state),
1615
+ }, 'cleaning up active session');
1616
+ this.cleanupSession(activeSession, event.userOpenId, event.threadId);
1617
+ }
1618
+ }
1619
+ buildAgentArgs(agentId, prompt, cwd, continuationToken, consentLevel, model, images) {
1620
+ return buildAgentArgs(agentId, prompt, cwd, continuationToken, consentLevel, model, images);
1621
+ }
1622
+ reconcileLostCaptainRun(userOpenId, threadId, runId) {
1623
+ if (!this.captainConcurrency)
1624
+ return;
1625
+ const sessionId = `${this.botId}:${userOpenId}:${threadId}`;
1626
+ if (!this.captainConcurrency.index.listRunning(sessionId).includes(runId))
1627
+ return;
1628
+ try {
1629
+ const session = this.captainService?.getSession(sessionId);
1630
+ if (session && (session.record.status === 'active' || session.record.status === 'suspended')) {
1631
+ this.captainService?.closeSession(sessionId);
1632
+ }
1633
+ }
1634
+ catch (error) {
1635
+ logger.error({ sessionId, runId, error }, 'failed to close captain session during lost-run recovery');
1636
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `lost-run session close failed: ${runId}`, 'warn');
1637
+ }
1638
+ try {
1639
+ const ts = new Date().toISOString();
1640
+ this.captainConcurrency.store.append({
1641
+ session_id: sessionId,
1642
+ run_id: runId,
1643
+ status: ConcurrencyQueueEntryStatus.ENDED,
1644
+ ts,
1645
+ reason: 'cancelled',
1646
+ });
1647
+ this.captainConcurrency.index.markEnded(sessionId, runId, ts);
1648
+ }
1649
+ catch (error) {
1650
+ logger.error({ sessionId, runId, error }, 'failed to reconcile lost captain run');
1651
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `lost-run queue reconcile failed: ${runId}`, 'warn');
1652
+ }
1653
+ }
1654
+ async onCaptainRunEnded(userOpenId, threadId, endedRunId, reason) {
1655
+ if (!this.captainConcurrency)
1656
+ return;
1657
+ const sessionId = `${this.botId}:${userOpenId}:${threadId}`;
1658
+ const ts = new Date().toISOString();
1659
+ this.captainConcurrency.metrics.record({
1660
+ metric: 'captain_run_ended_total',
1661
+ value: 1,
1662
+ labels: { session_id: sessionId, reason },
1663
+ });
1664
+ this.captainConcurrency.store.append({
1665
+ session_id: sessionId,
1666
+ run_id: endedRunId,
1667
+ status: ConcurrencyQueueEntryStatus.ENDED,
1668
+ ts,
1669
+ ...(reason === 'cancelled' || reason === 'preempted' ? { reason } : {}),
1670
+ });
1671
+ this.captainConcurrency.index.markEnded(sessionId, endedRunId, ts);
1672
+ const nextQueued = this.captainConcurrency.index.listQueuedEntries(sessionId)[0];
1673
+ if (!nextQueued)
1674
+ return;
1675
+ const waitDurationSeconds = Math.max(0, (Date.parse(ts) - Date.parse(nextQueued.ts)) / 1000);
1676
+ this.captainConcurrency.metrics.record({
1677
+ metric: 'captain_queue_wait_duration_seconds',
1678
+ value: waitDurationSeconds,
1679
+ labels: { session_id: sessionId },
1680
+ });
1681
+ this.captainConcurrency.metrics.record({
1682
+ metric: 'captain_queue_promotions_total',
1683
+ value: 1,
1684
+ labels: { session_id: sessionId, trigger_reason: reason },
1685
+ });
1686
+ this.captainConcurrency.store.append({
1687
+ session_id: sessionId,
1688
+ run_id: nextQueued.run_id,
1689
+ status: ConcurrencyQueueEntryStatus.RUNNING,
1690
+ ts,
1691
+ });
1692
+ this.captainConcurrency.index.markRunning(sessionId, nextQueued.run_id, ts);
1693
+ const pending = this.pendingCaptainRuns.get(nextQueued.run_id);
1694
+ if (!pending) {
1695
+ this.captainConcurrency.metrics.record({
1696
+ metric: 'captain_queue_promotion_failures_total',
1697
+ value: 1,
1698
+ labels: { session_id: sessionId },
1699
+ });
1700
+ return;
1701
+ }
1702
+ this.pendingCaptainRuns.delete(nextQueued.run_id);
1703
+ const replyMessageId = await this.feishu.replyCard(pending.event.messageId, renderCard(createInitialState(pending.agent.id, pending.agent.displayName, pending.agent.displayName)));
1704
+ if (this.runnerConfig) {
1705
+ await this.handleMessageViaWbRunner(pending.event, pending.agent, pending.cwd, replyMessageId, pending.scopeKey, pending.skipBindingUpdate, pending.runId);
1706
+ return;
1707
+ }
1708
+ await this.handleMessageViaPipe(pending.event, pending.agent, pending.cwd, replyMessageId, pending.scopeKey, pending.skipBindingUpdate, pending.runId);
1709
+ }
1710
+ // Waits for the sweep to settle, then confirms the runner process actually stopped before
1711
+ // clearing state. If the CLI subprocess is still alive (e.g. it ignored the cancel signal or
1712
+ // the heartbeat writer stalled while the agent kept running), keep the session/card so the
1713
+ // busy check blocks duplicate runs and the next sweep can retry instead of orphaning them.
1714
+ finalizeLostRun(activeSession, card, stopResult) {
1715
+ if (!this.isRunnerProcessStopped(stopResult.pid)) {
1716
+ logger.warn({ runId: card.runId, pid: stopResult.pid }, 'watchdog keeping state: runner process still alive after cancel signal');
1717
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `watchdog retained stale-run state, runner ${stopResult.pid ?? 'unknown'} still alive: ${card.runId}`, 'warn');
1718
+ return 'still-running';
1719
+ }
1720
+ if (activeSession) {
1721
+ this.cleanupSession(activeSession, card.userOpenId, card.threadId);
1722
+ }
1723
+ else {
1724
+ this.store.clearInflightCard(this.botId, card.userOpenId, card.threadId, card.agentId);
1725
+ }
1726
+ return 'cleared';
1727
+ }
1728
+ isRunnerProcessStopped(pid) {
1729
+ if (!pid)
1730
+ return true;
1731
+ try {
1732
+ process.kill(pid, 0);
1733
+ return false;
1734
+ }
1735
+ catch (error) {
1736
+ // ESRCH = no such process -> stopped; EPERM = exists but not ours -> still alive.
1737
+ return error.code === 'ESRCH';
1738
+ }
1739
+ }
1740
+ cleanupSession(session, userOpenId, threadId) {
1741
+ void this.ackReactions.clear(session.sourceMessageId);
1742
+ for (const id of this.mergedAckIds.get(session.sourceMessageId) ?? [])
1743
+ void this.ackReactions.clear(id);
1744
+ this.mergedAckIds.delete(session.sourceMessageId);
1745
+ this.store.clearInflightCard(this.botId, userOpenId, threadId, session.agentId);
1746
+ this.activeSessions.delete(session.scopeKey);
1747
+ this.activeSessionsByMessageId.delete(session.sourceMessageId);
1748
+ this.activeSessionsByMessageId.delete(session.replyMessageId);
1749
+ if (session.state.sessionShortId) {
1750
+ this.activeSessionsByShortId.delete(session.state.sessionShortId);
1751
+ this.reservedSessionShortIds.delete(session.state.sessionShortId);
1752
+ }
1753
+ for (const id of session.extraMessageIds) {
1754
+ this.activeSessionsByMessageId.delete(id);
1755
+ }
1756
+ // 续卡发完再接排队消息, 保证话题里先看到完整答案再看到下一轮.
1757
+ void this.finishRunCard(session).finally(() => {
1758
+ if (!this.followUps.has(session.scopeKey))
1759
+ return;
1760
+ setImmediate(() => {
1761
+ this.drainFollowUps(session.scopeKey).catch((error) => {
1762
+ logger.error({ scopeKey: session.scopeKey, error }, 'follow-up drain failed');
1763
+ });
1764
+ });
1765
+ });
1766
+ }
1767
+ async finishRunCard(session) {
1768
+ const origin = this.runCards.get(session.replyMessageId);
1769
+ const { state } = session;
1770
+ if (origin && this.feishu.sendLocalFile && state.agentId !== 'system' && state.terminalState !== 'running' && state.stopState === 'running') {
1771
+ const cwd = state.cwd ?? origin.cwd;
1772
+ const found = findArtifacts({ tools: state.tools, text: state.text, cwd, startedAt: session.startedAt });
1773
+ if (found.length > 0) {
1774
+ rememberBounded(this.runArtifacts, session.replyMessageId, found);
1775
+ session.state = { ...state, artifacts: found.map((path) => ({ path, label: artifactLabel(path, cwd) })) };
1776
+ try {
1777
+ await session.pipeline.force(renderCard(session.state));
1778
+ }
1779
+ catch (error) {
1780
+ logger.error({ scopeKey: session.scopeKey, error }, 'artifact card update failed');
1781
+ }
1782
+ }
1783
+ }
1784
+ await this.sendContinuationCards(session);
1785
+ }
1786
+ /** 产物按钮: 只有发起人能发, 每个文件只发一次; 点击时再检查一遍文件仍在且没超限. */
1787
+ async handleSendArtifact(event) {
1788
+ const origin = this.runCards.get(event.messageId);
1789
+ const path = event.artifactIndex === undefined ? undefined : this.runArtifacts.get(event.messageId)?.[event.artifactIndex];
1790
+ if (!origin || !path || !this.feishu.sendLocalFile)
1791
+ return { toast: { type: 'info', content: '这张卡的产物已失效 (bot 重启过)' } };
1792
+ if (origin.userOpenId !== event.userOpenId)
1793
+ return { toast: { type: 'error', content: '只有发起人可以发送产物' } };
1794
+ let size;
1795
+ try {
1796
+ size = statSync(path).size;
1797
+ }
1798
+ catch {
1799
+ return { toast: { type: 'error', content: '文件已不存在' } };
1800
+ }
1801
+ if (size > ARTIFACT_MAX_BYTES)
1802
+ return { toast: { type: 'error', content: '文件超过 20MB, 不发送' } };
1803
+ if (this.isDuplicate(`send-artifact:${event.messageId}:${path}`))
1804
+ return { toast: { type: 'info', content: '已经发送过了' } };
1805
+ const send = this.feishu.sendLocalFile.bind(this.feishu);
1806
+ setImmediate(() => {
1807
+ send(origin.sourceMessageId, path).catch(async (error) => {
1808
+ logger.error({ path, error }, 'send artifact failed');
1809
+ await this.feishu.replyText(origin.sourceMessageId, `发送 ${basename(path)} 失败: ${error instanceof Error ? error.message : String(error)}`)
1810
+ .catch((replyError) => logger.error({ replyError }, 'send artifact failure notice failed'));
1811
+ });
1812
+ });
1813
+ return { toast: { type: 'success', content: `正在发送 ${basename(path)}` } };
1814
+ }
1815
+ async sendContinuationCards(session) {
1816
+ if (session.state.terminalState === 'running')
1817
+ return;
1818
+ const chunks = answerChunks(session.state);
1819
+ for (let index = 1; index < chunks.length; index++) {
1820
+ try {
1821
+ const messageId = await this.feishu.replyCard(session.sourceMessageId, renderContinuationCard(session.state, chunks[index], index + 1, chunks.length));
1822
+ session.extraMessageIds.push(messageId);
1823
+ }
1824
+ catch (error) {
1825
+ logger.error({ scopeKey: session.scopeKey, index, total: chunks.length, error }, 'continuation card failed');
1826
+ return;
1827
+ }
1828
+ }
1829
+ }
1830
+ findActiveSessionByRunId(runId) {
1831
+ for (const session of this.activeSessions.values()) {
1832
+ if (session.runId === runId)
1833
+ return session;
1834
+ }
1835
+ return undefined;
1836
+ }
1837
+ isFreshRunnerStartupSession(session, now = Date.now()) {
1838
+ // wb-runner sessions persist the inflight card before the detached runner process finishes
1839
+ // writing spec/status/heartbeat. Skip the first watchdog window so a new run is not
1840
+ // misclassified as lost during this startup race.
1841
+ if (session.run !== null)
1842
+ return false;
1843
+ if (session.state.terminalState !== 'running')
1844
+ return false;
1845
+ return (now - session.startedAt) < RUNNER_STARTUP_GRACE_MS;
1846
+ }
1847
+ isFreshRunnerStartupRun(runId, botId, now = Date.now()) {
1848
+ try {
1849
+ const specRaw = readFileSync(runSpecPath(this.alertDataDir, runId, botId), 'utf8');
1850
+ const spec = JSON.parse(specRaw);
1851
+ if (!spec.startedAt)
1852
+ return false;
1853
+ const startedAt = Date.parse(spec.startedAt);
1854
+ if (!Number.isFinite(startedAt))
1855
+ return false;
1856
+ return (now - startedAt) < RUNNER_STARTUP_GRACE_MS;
1857
+ }
1858
+ catch {
1859
+ return false;
1860
+ }
1861
+ }
1862
+ staleSelfHealStore(card) {
1863
+ if (!card.runId)
1864
+ return null;
1865
+ return new ProgressStore({
1866
+ dataDir: this.alertDataDir,
1867
+ botId: this.botId,
1868
+ runId: card.runId,
1869
+ sessionId: `${this.botId}:${card.userOpenId}:${card.threadId}`,
1870
+ originMessageId: card.sourceMessageId,
1871
+ cardMessageId: card.replyMessageId,
1872
+ });
1873
+ }
1874
+ reserveStaleSelfHeal(card) {
1875
+ const store = this.staleSelfHealStore(card);
1876
+ const now = new Date().toISOString();
1877
+ if (!store)
1878
+ return { kind: 'allowed', attempts: 0 };
1879
+ const entry = store.readOrInitEntry(now);
1880
+ if (entry.stale_self_heal_attempts >= STALE_SELF_HEAL_MAX_ATTEMPTS) {
1881
+ const shouldEscalate = entry.stale_self_heal_escalated_at == null;
1882
+ if (shouldEscalate) {
1883
+ entry.stale_self_heal_escalated_at = now;
1884
+ store.saveEntry(entry);
1885
+ }
1886
+ return {
1887
+ kind: 'blocked',
1888
+ attempts: entry.stale_self_heal_attempts,
1889
+ shouldEscalate,
1890
+ };
1891
+ }
1892
+ entry.stale_self_heal_attempts += 1;
1893
+ entry.stale_self_heal_last_attempt_at = now;
1894
+ store.saveEntry(entry);
1895
+ return {
1896
+ kind: 'allowed',
1897
+ attempts: entry.stale_self_heal_attempts,
1898
+ };
1899
+ }
1900
+ async handleBlockedStaleSelfHeal(card, source, attempts, shouldEscalate) {
1901
+ if (!card.runId)
1902
+ return;
1903
+ await this.feishu.updateCard(card.replyMessageId, renderWatchdogEscalatedCard(card.runId.slice(0, 12), card.runId));
1904
+ if (!shouldEscalate)
1905
+ return;
1906
+ const sourceLabel = source === 'watchdog' ? 'watchdog' : 'restart recovery';
1907
+ await sendAdminAlert(this.alertSink, this.alertDataDir, `${sourceLabel} stale-run auto-recovery disabled after limit: ${card.runId} (attempts=${attempts}/${STALE_SELF_HEAL_MAX_ATTEMPTS})`, 'error');
1908
+ }
1909
+ async bestEffortStopLostRun(runId) {
1910
+ const botId = this.botId;
1911
+ const stopSignalPath = runStopSignalPath(this.alertDataDir, runId, botId);
1912
+ let stopSignalWritten = false;
1913
+ if (!existsSync(stopSignalPath)) {
1914
+ writeFileSync(stopSignalPath, String(Date.now()));
1915
+ stopSignalWritten = true;
1916
+ }
1917
+ const pid = resolveCliPid(this.alertDataDir, runId);
1918
+ let signalSent = false;
1919
+ if (pid) {
1920
+ try {
1921
+ await sendControlSignal('cancel', pid);
1922
+ signalSent = true;
1923
+ }
1924
+ catch (error) {
1925
+ logger.warn({ runId, pid, error }, 'watchdog cancel signal failed');
1926
+ }
1927
+ }
1928
+ return { pid, stopSignalWritten, signalSent };
1929
+ }
1930
+ async sweepApprovalRequests() {
1931
+ for (const request of this.approvalRequests.listPending()) {
1932
+ if (request.status !== APPROVAL_REQUEST_STATUS.PENDING_DISPATCH)
1933
+ continue;
1934
+ try {
1935
+ const approvalMessageId = await this.feishu.replyCard(request.replyMessageId, renderApprovalRequestCard(request));
1936
+ const dispatched = this.approvalRequests.markDispatched(request.requestId, request.carrier ?? 'group_card', approvalMessageId);
1937
+ writeApprovalAudit({ dataDir: this.alertDataDir, request: dispatched, phase: 'dispatched', nowIso: dispatched.createdAt });
1938
+ // F22: 通知所有 allowed approvers。卡片本身已经渲染了 <at user_id=...>,
1939
+ // 但 approval card 挂在 replyMessageId 下,只有 requester 会被 ping;让 notifier
1940
+ // 用 home-group sendCard 再发一条让其他审批人真收到 @。
1941
+ await this.approvalNotifier.notifyApprovers(dispatched).catch((notifyError) => {
1942
+ logger.warn({ requestId: dispatched.requestId, notifyError }, 'approval approver notify failed');
1943
+ });
1944
+ }
1945
+ catch (approvalError) {
1946
+ const failed = this.approvalRequests.resolve(request.requestId, {
1947
+ status: APPROVAL_REQUEST_STATUS.FAILED_CLOSED,
1948
+ reason: 'approval dispatch failed',
1949
+ resolvedAt: new Date().toISOString(),
1950
+ });
1951
+ writeApprovalAudit({ dataDir: this.alertDataDir, request: failed, phase: 'resolved', nowIso: failed.resolvedAt });
1952
+ logger.error({ requestId: request.requestId, approvalError }, 'approval gate card dispatch failed');
1953
+ }
1954
+ }
1955
+ // F22 countdown self-update: 对所有还在 PENDING_APPROVAL 的卡,每一次 sweep
1956
+ // 都 patch 一次倒计时,让卡片始终显示剩余秒数,到点显示默认拒绝文案。失败不阻塞。
1957
+ for (const request of this.approvalRequests.listPending()) {
1958
+ if (request.status !== APPROVAL_REQUEST_STATUS.PENDING_APPROVAL)
1959
+ continue;
1960
+ if (!request.carrierMessageId)
1961
+ continue;
1962
+ try {
1963
+ await this.feishu.updateCard(request.carrierMessageId, renderApprovalRequestCard(request));
1964
+ }
1965
+ catch (countdownError) {
1966
+ logger.warn({ requestId: request.requestId, countdownError }, 'approval countdown card refresh failed');
1967
+ }
1968
+ }
1969
+ for (const request of this.approvalRequests.expireOverdue()) {
1970
+ writeApprovalAudit({ dataDir: this.alertDataDir, request, phase: 'resolved', nowIso: request.resolvedAt });
1971
+ const session = this.findActiveSessionByRunId(request.runId);
1972
+ if (request.carrierMessageId) {
1973
+ // 超时卡翻新为 resolved 文案,让审批人看到"已默认拒绝",而不是一直 pending。
1974
+ try {
1975
+ await this.feishu.updateCard(request.carrierMessageId, renderApprovalResolvedCard(request));
1976
+ }
1977
+ catch (patchError) {
1978
+ logger.warn({ requestId: request.requestId, patchError }, 'approval expiry card refresh failed');
1979
+ }
1980
+ }
1981
+ if (!session)
1982
+ continue;
1983
+ session.state = {
1984
+ ...session.state,
1985
+ terminalState: 'error',
1986
+ errorMessage: request.resolutionReason ?? 'approval timeout',
1987
+ };
1988
+ await session.pipeline.force(renderCard(session.state));
1989
+ // Expire = fail-closed deny: the run must not linger as a zombie holding the scopeKey
1990
+ // busy check. Signal the runner to stop; the events-stream finally cleans the session up
1991
+ // once the runner drains its terminal event.
1992
+ await this.stopSession(session);
1993
+ }
1994
+ }
1995
+ async sweepStaleRuns() {
1996
+ if (!this.runnerConfig || this.draining || this.staleRunSweepInFlight)
1997
+ return;
1998
+ await this.sweepApprovalRequests();
1999
+ this.staleRunSweepInFlight = true;
2000
+ try {
2001
+ const botId = this.botId;
2002
+ const now = Date.now();
2003
+ const cards = this.store.listInflightCards(botId);
2004
+ for (const card of cards) {
2005
+ if (!card.runId)
2006
+ continue;
2007
+ const activeSession = this.findActiveSessionByRunId(card.runId);
2008
+ if (activeSession && activeSession.state.terminalState !== 'running')
2009
+ continue;
2010
+ if ((activeSession && this.isFreshRunnerStartupSession(activeSession, now)) || this.isFreshRunnerStartupRun(card.runId, botId, now))
2011
+ continue;
2012
+ if (this.judgeRunState(card.runId, botId) !== 'lost')
2013
+ continue;
2014
+ activeSession?.eventsReader?.stop();
2015
+ try {
2016
+ const gate = this.reserveStaleSelfHeal(card);
2017
+ if (gate.kind === 'blocked') {
2018
+ await this.handleBlockedStaleSelfHeal(card, 'watchdog', gate.attempts, gate.shouldEscalate);
2019
+ logger.warn({ runId: card.runId, attempts: gate.attempts, replyMessageId: card.replyMessageId }, 'watchdog stale-run auto-recovery disabled after attempt limit');
2020
+ // Blocked escalation still tears the run down. If the runner is actually gone,
2021
+ // drop the card now; if it is alive beyond the attempt limit, leave state so a
2022
+ // human-approved retry has something to act on.
2023
+ this.finalizeLostRun(activeSession, card, { pid: resolveCliPid(this.alertDataDir, card.runId) });
2024
+ continue;
2025
+ }
2026
+ const stopResult = await this.bestEffortStopLostRun(card.runId);
2027
+ this.reconcileLostCaptainRun(card.userOpenId, card.threadId, card.runId);
2028
+ await this.feishu.updateCard(card.replyMessageId, renderWatchdogRecoveredCard(card.runId.slice(0, 12), card.runId));
2029
+ await sendAdminAlert(this.alertSink, this.alertDataDir, `watchdog auto-recovered stale run: ${card.runId} (attempt=${gate.attempts}/${STALE_SELF_HEAL_MAX_ATTEMPTS} signalSent=${stopResult.signalSent} stopSignalWritten=${stopResult.stopSignalWritten}${stopResult.pid ? ` pid=${stopResult.pid}` : ''})`, 'warn');
2030
+ logger.info({ runId: card.runId, stopResult, replyMessageId: card.replyMessageId, attempts: gate.attempts }, 'watchdog auto-recovered stale run');
2031
+ this.finalizeLostRun(activeSession, card, stopResult);
2032
+ }
2033
+ catch (error) {
2034
+ logger.error({ runId: card.runId, replyMessageId: card.replyMessageId, error }, 'watchdog stale-run recovery failed');
2035
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `watchdog stale-run recovery failed: ${card.runId}`, 'warn');
2036
+ // Best-effort stop already ran (or pid-file lookup failed). Only drop the card once
2037
+ // the runner is actually gone; a live runner must keep state so the scope stays armed.
2038
+ const pid = resolveCliPid(this.alertDataDir, card.runId);
2039
+ this.finalizeLostRun(activeSession, card, { pid });
2040
+ }
2041
+ }
2042
+ }
2043
+ finally {
2044
+ this.staleRunSweepInFlight = false;
2045
+ }
2046
+ }
2047
+ async stopSession(session) {
2048
+ this.dropFollowUps(session.scopeKey);
2049
+ if (session.run) {
2050
+ await session.run.stop();
2051
+ }
2052
+ else if (session.runId && this.runnerConfig) {
2053
+ const botId = this.runnerConfig.botId ?? 'default';
2054
+ const stopSignalPath = runStopSignalPath(this.runnerConfig.dataDir, session.runId, botId);
2055
+ writeFileSync(stopSignalPath, String(Date.now()));
2056
+ }
2057
+ }
2058
+ executeReverseAtCancel = async (runId) => {
2059
+ const session = this.findActiveSessionByRunId(runId);
2060
+ if (!session)
2061
+ return 'noop_already_ended';
2062
+ if (session.state.stopState === 'stopping' || session.state.stopState === 'stopped' || session.state.terminalState !== 'running') {
2063
+ return 'noop_already_ended';
2064
+ }
2065
+ session.state = {
2066
+ ...session.state,
2067
+ stopState: 'stopping',
2068
+ };
2069
+ await session.pipeline.force(renderCard(session.state));
2070
+ await this.stopSession(session);
2071
+ return 'cancelled';
2072
+ };
2073
+ async handleCompletionPush(session, agent, userOpenId, threadId) {
2074
+ if (session.state.stopState === 'stopped' || session.state.stopState === 'stopping')
2075
+ return;
2076
+ const durationMs = Date.now() - session.startedAt;
2077
+ const hasFollow = this.followFlags.has(threadId);
2078
+ if (!shouldPushOnDone({ durationMs, thresholdMs: this.pushThresholdMs, hasFollow }))
2079
+ return;
2080
+ const cwd = session.state.cwd ?? '-';
2081
+ const message = formatCompletionMessage(agent.displayName, cwd, durationMs);
2082
+ try {
2083
+ await this.feishu.replyText(session.replyMessageId, message);
2084
+ }
2085
+ catch (err) {
2086
+ logger.error({ err, threadId, message }, 'completion push replyText failed');
2087
+ }
2088
+ if (hasFollow && this.activeSessionsForThread(userOpenId, threadId).length <= 1) {
2089
+ this.followFlags.delete(threadId);
2090
+ }
2091
+ }
2092
+ /**
2093
+ * 没有卡片的运行 (云文档评论): 按 (用户, threadId) 解析 agent / cwd / 上下文, 跑完返回纯文本.
2094
+ * 同一 scope 同时只跑一个; 没有停止按钮, 超时自动停.
2095
+ */
2096
+ async runHeadless(input) {
2097
+ if (this.draining)
2098
+ return { text: '', error: 'bot 正在重启, 请稍后再试' };
2099
+ const binding = this.store.getThreadBinding(this.botId, input.userOpenId, input.threadId);
2100
+ const agent = (binding?.agentId ? this.registry.lookup(binding.agentId) : null) ?? await resolveDefaultAgent(this.registry);
2101
+ if (!agent)
2102
+ return { text: '', error: '没有可用的 agent' };
2103
+ const scopeKey = this.scopeKey(input.userOpenId, input.threadId, agent.id);
2104
+ if (this.headlessScopes.has(scopeKey) || this.activeSessions.has(scopeKey)) {
2105
+ return { text: '', error: '上一条还在处理, 请稍后再 @ 我' };
2106
+ }
2107
+ let cwd = binding?.cwd ?? this.defaultCwd;
2108
+ if (!cwd) {
2109
+ const fallback = validateCwd(process.cwd());
2110
+ if (!fallback.ok)
2111
+ return { text: '', error: `bot 工作目录不在允许范围: ${fallback.reason}` };
2112
+ cwd = fallback.path;
2113
+ }
2114
+ this.headlessScopes.add(scopeKey);
2115
+ const run = agent.run({
2116
+ prompt: input.prompt,
2117
+ cwd,
2118
+ continuationToken: this.store.getContinuation(this.botId, input.userOpenId, input.threadId, agent.id) ?? undefined,
2119
+ ...(this.claudeConsentLevel && agent.id === 'claude-code' ? { consentLevel: this.claudeConsentLevel } : {}),
2120
+ });
2121
+ const timer = setTimeout(() => { void run.stop(); }, HEADLESS_RUN_TIMEOUT_MS);
2122
+ timer.unref?.();
2123
+ let state = createInitialState(agent.id, agent.displayName, agent.displayName);
2124
+ try {
2125
+ for await (const output of run.events) {
2126
+ state = reduceStreamState(state, output);
2127
+ if (output.type === 'done' && output.continuationToken) {
2128
+ this.store.upsertContinuation(this.botId, input.userOpenId, input.threadId, agent.id, output.continuationToken);
2129
+ }
2130
+ if (output.type === 'done' || output.type === 'error')
2131
+ break;
2132
+ }
2133
+ }
2134
+ finally {
2135
+ clearTimeout(timer);
2136
+ this.headlessScopes.delete(scopeKey);
2137
+ }
2138
+ return state.terminalState === 'error' ? { text: state.text, error: state.errorMessage ?? 'agent 出错' } : { text: state.text };
2139
+ }
2140
+ async replySystemCard(messageId, text) {
2141
+ await this.feishu.replyCard(messageId, renderCard({
2142
+ ...createInitialState('system', 'Weaverbird', 'bot'),
2143
+ text,
2144
+ includeMeta: false,
2145
+ terminalState: 'done',
2146
+ }));
2147
+ }
2148
+ /** 群级开关; 关掉 @ 要求会让 bot 响应群里所有人, 所以只允许群主 / 群管理员 / 白名单改. */
2149
+ async handleRequireMention(event, value) {
2150
+ if (!event.chatId || !event.chatType || event.chatType === 'p2p')
2151
+ return '私聊不需要 @bot, 这个设置只在群里有效';
2152
+ const current = this.store.getRequireMention(this.botId, event.chatId);
2153
+ if (!value)
2154
+ return `本群当前${current ? '需要' : '不需要'} @bot 才响应。修改: /require-mention on|off`;
2155
+ if (!this.reverseAtAdminRoleResolver)
2156
+ return '当前环境无法校验群管理员身份, 不能修改群设置';
2157
+ let role;
2158
+ try {
2159
+ role = await this.reverseAtAdminRoleResolver({ messageId: event.messageId, userOpenId: event.userOpenId, threadId: event.chatId });
2160
+ }
2161
+ catch (error) {
2162
+ logger.warn({ chatId: event.chatId, error }, 'require-mention role lookup failed');
2163
+ return '查询群管理员身份失败, 请稍后再试';
2164
+ }
2165
+ if (!role)
2166
+ return '只有群主 / 群管理员可以修改这个设置';
2167
+ this.store.setRequireMention(this.botId, event.chatId, value === 'on', event.userOpenId);
2168
+ return value === 'on'
2169
+ ? '已开启: 本群需要 @bot 才响应'
2170
+ : '已关闭 @ 要求: 本群所有人的消息都会被处理 (机器人消息和只 @ 了别人的消息除外)。需要应用开通 im:message.group_msg 权限, 否则飞书只推送 @bot 的消息。恢复: /require-mention on';
2171
+ }
2172
+ /**
2173
+ * 结束卡上的 继续 / 重试 / 新会话. 只有发起人能点; 生成的消息照常走 handleMessage,
2174
+ * 所以排队、绑定、上下文续接都和手动发消息一致.
2175
+ */
2176
+ async handleRunFollowUpAction(event) {
2177
+ const origin = this.runCards.get(event.messageId);
2178
+ if (!origin)
2179
+ return { toast: { type: 'info', content: '这张卡的上下文已失效 (bot 重启过), 请直接发消息' } };
2180
+ if (origin.userOpenId !== event.userOpenId)
2181
+ return { toast: { type: 'error', content: '只有发起人可以操作这张卡' } };
2182
+ // 连点只认第一次; 卡片回调的 event_id 每次点击都不同, 不能用来去重.
2183
+ if (this.isDuplicate(`run-follow-up:${event.messageId}:${event.action}`)) {
2184
+ return { toast: { type: 'info', content: '已经处理过了' } };
2185
+ }
2186
+ if (event.action === RUN_FOLLOW_UP_ACTIONS.reset) {
2187
+ const cleared = this.store.clearContinuation(this.botId, origin.userOpenId, origin.threadId, origin.agentId);
2188
+ return { toast: { type: 'success', content: cleared ? `已清空 ${origin.agentId} 上下文, 下一条消息开新会话` : `${origin.agentId} 当前没有上下文` } };
2189
+ }
2190
+ const base = {
2191
+ eventId: `card:${event.action}:${event.messageId}`,
2192
+ userOpenId: origin.userOpenId,
2193
+ threadId: origin.threadId,
2194
+ messageId: origin.sourceMessageId,
2195
+ };
2196
+ let next;
2197
+ if (event.action === RUN_FOLLOW_UP_ACTIONS.retry) {
2198
+ const input = this.recentInputs.get(origin.sourceMessageId);
2199
+ if (!input)
2200
+ return { toast: { type: 'info', content: '原消息已不在缓存里, 请重新发送' } };
2201
+ next = { ...input, eventId: base.eventId };
2202
+ }
2203
+ else {
2204
+ next = { ...base, text: `/agent ${origin.agentId} 继续` };
2205
+ }
2206
+ // 回调要在 3 秒内返回, run 放到后台.
2207
+ setImmediate(() => {
2208
+ this.handleMessage(next).catch((error) => {
2209
+ logger.error({ action: event.action, messageId: event.messageId, error }, 'run follow-up action failed');
2210
+ });
2211
+ });
2212
+ return { toast: { type: 'success', content: event.action === RUN_FOLLOW_UP_ACTIONS.retry ? '重新执行中' : '继续执行中' } };
2213
+ }
2214
+ async handleCardAction(event) {
2215
+ // Use messageId+action as dedup key when eventId is empty (Feishu omits it for card callbacks).
2216
+ // 同一张卡上的多个「发送」按钮 action 相同, 要带上序号, 否则第二个文件会被当成重复点击.
2217
+ const artifactSuffix = event.artifactIndex === undefined ? '' : `:${event.artifactIndex}`;
2218
+ const dedupKey = event.eventId || `card-action:${event.messageId}:${event.action}${artifactSuffix}`;
2219
+ if (this.isDuplicate(dedupKey)) {
2220
+ logger.info({ dedupKey, action: event.action }, 'duplicate card action ignored');
2221
+ return { toast: { type: 'info', content: 'duplicate' } };
2222
+ }
2223
+ // M13-H: 未知 action 提前动手, 给用户真话不是 "duplicate".
2224
+ const KNOWN_ACTIONS = new Set(['stop', 'admin_cancel', 'approval_gate_approve', 'approval_gate_deny', 'approval_gate_transfer', 'watchdog_retry', 'watchdog_dismiss', SEND_ARTIFACT_ACTION, ...Object.values(RUN_FOLLOW_UP_ACTIONS)]);
2225
+ if (!KNOWN_ACTIONS.has(event.action)) {
2226
+ logger.warn({ action: event.action, messageId: event.messageId }, 'unknown card action');
2227
+ return { toast: { type: 'error', content: `未知操作: ${event.action}, 请联系 owner` } };
2228
+ }
2229
+ if (Object.values(RUN_FOLLOW_UP_ACTIONS).includes(event.action)) {
2230
+ return this.handleRunFollowUpAction(event);
2231
+ }
2232
+ if (event.action === SEND_ARTIFACT_ACTION)
2233
+ return this.handleSendArtifact(event);
2234
+ const reverseAtThreadId = this.reverseAtThreadIdFor(event);
2235
+ const clickedSession = this.activeSessionsByMessageId.get(event.messageId);
2236
+ logger.info({
2237
+ eventId: event.eventId,
2238
+ userOpenId: event.userOpenId,
2239
+ threadId: event.threadId,
2240
+ messageId: event.messageId,
2241
+ action: event.action,
2242
+ activeSessionKeys: Array.from(this.activeSessionsByMessageId.keys()),
2243
+ }, 'handling card action');
2244
+ // M13-D: watchdog 卡按钮. dismiss= 消化提示即可, retry= 给出重发提示让 owner
2245
+ // 决定 (跨 run 拿不到原 prompt 是常态, 当前版本只返 toast, 不重发 run).
2246
+ if (event.action === 'watchdog_dismiss') {
2247
+ return { toast: { type: 'success', content: '知道了' } };
2248
+ }
2249
+ if (event.action === 'watchdog_retry') {
2250
+ return { toast: { type: 'info', content: '请把原 prompt 再发一次, 我会当新任务跑' } };
2251
+ }
2252
+ if (event.action === 'approval_gate_approve' || event.action === 'approval_gate_deny') {
2253
+ if (!event.requestId)
2254
+ return { toast: { type: 'info', content: '当前没有可处理的审批' } };
2255
+ const request = this.approvalRequests.get(event.requestId);
2256
+ if (!request)
2257
+ return { toast: { type: 'info', content: '当前没有可处理的审批' } };
2258
+ if (!request.allowedApproverOpenIds.includes(event.userOpenId)) {
2259
+ return { toast: { type: 'error', content: '你无权处理该审批' } };
2260
+ }
2261
+ const resolved = this.approvalRequests.resolve(event.requestId, {
2262
+ status: event.action === 'approval_gate_approve' ? APPROVAL_REQUEST_STATUS.APPROVED : APPROVAL_REQUEST_STATUS.DENIED,
2263
+ reason: event.action === 'approval_gate_approve' ? 'approved by configured approver' : 'denied by configured approver',
2264
+ resolvedAt: new Date().toISOString(),
2265
+ resolvedBy: event.userOpenId,
2266
+ });
2267
+ writeApprovalAudit({ dataDir: this.alertDataDir, request: resolved, phase: 'resolved', nowIso: resolved.resolvedAt });
2268
+ if (resolved.carrierMessageId) {
2269
+ try {
2270
+ await this.feishu.updateCard(resolved.carrierMessageId, renderApprovalResolvedCard(resolved));
2271
+ }
2272
+ catch (patchError) {
2273
+ logger.warn({ requestId: resolved.requestId, patchError }, 'approval resolved card patch failed');
2274
+ }
2275
+ }
2276
+ return { toast: { type: 'success', content: event.action === 'approval_gate_approve' ? '已批准' : '已拒绝' } };
2277
+ }
2278
+ if (event.action === 'approval_gate_transfer') {
2279
+ if (!event.requestId)
2280
+ return { toast: { type: 'info', content: '没有可转派的审批' } };
2281
+ const request = this.approvalRequests.get(event.requestId);
2282
+ if (!request)
2283
+ return { toast: { type: 'info', content: '没有可转派的审批' } };
2284
+ if (!request.allowedApproverOpenIds.includes(event.userOpenId)) {
2285
+ return { toast: { type: 'error', content: '你无权转派该审批' } };
2286
+ }
2287
+ // 选择面板未落(W3.4 范围之外); 让 transfer 退化为 @全员重发 (发起者被本轮排除,
2288
+ // 其他审批人会被 allow-list 重新编辑).
2289
+ const remaining = request.allowedApproverOpenIds.filter((id) => id !== event.userOpenId);
2290
+ if (remaining.length === 0) {
2291
+ return { toast: { type: 'error', content: '没有其他审批人可接收转派' } };
2292
+ }
2293
+ // M13-B: transfer 保留原 request pending, 不 DENIED 重建. 原卡 patch 一次以
2294
+ // 更新 @ 提及集合; audit 用 'dispatched' (re-targeted)。
2295
+ const next = this.approvalRequests.transferInPlace(event.requestId, remaining);
2296
+ writeApprovalAudit({ dataDir: this.alertDataDir, request: next, phase: 'dispatched' });
2297
+ if (next.carrierMessageId) {
2298
+ try {
2299
+ await this.feishu.updateCard(next.carrierMessageId, renderApprovalRequestCard(next));
2300
+ }
2301
+ catch (patchError) {
2302
+ logger.warn({ requestId: next.requestId, patchError }, 'approval transfer card patch failed');
2303
+ }
2304
+ }
2305
+ try {
2306
+ await this.approvalNotifier.notifyApprovers(next);
2307
+ }
2308
+ catch (notifyError) {
2309
+ logger.warn({ requestId: next.requestId, notifyError }, 'approval transfer notify failed');
2310
+ }
2311
+ return { toast: { type: 'success', content: '已转派,等待新审批人处理' } };
2312
+ }
2313
+ if (event.action === 'admin_cancel') {
2314
+ if (!event.shortId || !this.captainService) {
2315
+ return { toast: { type: 'info', content: '当前没有可叫停的目标' } };
2316
+ }
2317
+ const target = this.resolveReverseAtCancelTarget(event.shortId);
2318
+ if (!target) {
2319
+ return { toast: { type: 'info', content: '当前没有可叫停的目标' } };
2320
+ }
2321
+ const session = this.findActiveSessionByRunId(target.runId);
2322
+ if (!session) {
2323
+ return { toast: { type: 'info', content: '当前没有可叫停的目标' } };
2324
+ }
2325
+ const operatorOwnsSession = session.sessionId
2326
+ ? this.captainService.getSession(session.sessionId)?.record.operator === event.userOpenId
2327
+ : false;
2328
+ if (clickedSession?.runId === session.runId && operatorOwnsSession) {
2329
+ session.state = { ...session.state, stopState: 'stopping' };
2330
+ await session.pipeline.force(renderCard(session.state));
2331
+ void this.stopSession(session).then(() => {
2332
+ logger.info({
2333
+ scopeKey: session.scopeKey,
2334
+ state: summarizeState(session.state),
2335
+ }, 'operator short-circuit stop request resolved');
2336
+ }).catch((error) => {
2337
+ logger.error({ scopeKey: session.scopeKey, error }, 'operator short-circuit stop failed');
2338
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `operator stop failed for ${session.scopeKey}`, 'warn');
2339
+ });
2340
+ return { toast: { type: 'success', content: '停止中...' } };
2341
+ }
2342
+ await handleReverseAtImCommand({
2343
+ command: '/cancel',
2344
+ run_id: event.shortId,
2345
+ requester_open_id: event.userOpenId,
2346
+ requested_at: new Date().toISOString(),
2347
+ message_id: event.messageId,
2348
+ }, {
2349
+ messageId: event.messageId,
2350
+ threadId: reverseAtThreadId,
2351
+ userOpenId: event.userOpenId,
2352
+ }, {
2353
+ captainService: this.captainService,
2354
+ dataDir: this.alertDataDir,
2355
+ feishu: this.feishu,
2356
+ resolveAdminRole: this.reverseAtAdminRoleResolver,
2357
+ resolveCancelTarget: this.resolveReverseAtCancelTarget,
2358
+ executeCancel: this.executeReverseAtCancel,
2359
+ listCancelableTargets: this.listReverseAtCancelableTargets,
2360
+ captainConcurrency: this.buildCaptainConcurrencyDeps({
2361
+ userOpenId: event.userOpenId,
2362
+ threadId: clickedSession?.threadId ?? event.threadId,
2363
+ }),
2364
+ notifyOperator: this.reverseAtOperatorNotifier,
2365
+ });
2366
+ return { toast: { type: 'info', content: '已提交' } };
2367
+ }
2368
+ if (event.action === 'stop') {
2369
+ // Only match by the specific card's message ID — do NOT fall back to scopeKey.
2370
+ // A stale STOP from an old card must not stop a newly started session.
2371
+ const session = this.activeSessionsByMessageId.get(event.messageId);
2372
+ if (!session) {
2373
+ logger.warn({
2374
+ eventId: event.eventId,
2375
+ userOpenId: event.userOpenId,
2376
+ threadId: event.threadId,
2377
+ messageId: event.messageId,
2378
+ activeSessionKeys: Array.from(this.activeSessionsByMessageId.keys()),
2379
+ }, 'stop action ignored because no active session matched');
2380
+ return { toast: { type: 'info', content: '当前没有可停止的运行' } };
2381
+ }
2382
+ session.state = { ...session.state, stopState: 'stopping' };
2383
+ logger.info({
2384
+ scopeKey: session.scopeKey,
2385
+ sourceMessageId: session.sourceMessageId,
2386
+ replyMessageId: session.replyMessageId,
2387
+ state: summarizeState(session.state),
2388
+ }, 'marked active session as stopping');
2389
+ await session.pipeline.force(renderCard(session.state));
2390
+ void this.stopSession(session).then(() => {
2391
+ logger.info({
2392
+ scopeKey: session.scopeKey,
2393
+ sourceMessageId: session.sourceMessageId,
2394
+ replyMessageId: session.replyMessageId,
2395
+ state: summarizeState(session.state),
2396
+ }, 'stop request resolved');
2397
+ }).catch((error) => {
2398
+ logger.error({
2399
+ scopeKey: session.scopeKey,
2400
+ sourceMessageId: session.sourceMessageId,
2401
+ replyMessageId: session.replyMessageId,
2402
+ state: summarizeState(session.state),
2403
+ error,
2404
+ }, 'stop request failed');
2405
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `stop request failed for ${session.scopeKey}`, 'warn');
2406
+ });
2407
+ return { toast: { type: 'success', content: '停止中...' } };
2408
+ }
2409
+ return { toast: { type: 'info', content: 'ignored' } };
2410
+ }
2411
+ async markRestarted(messageId) {
2412
+ return this.feishu.replyCard(messageId, renderRestartedCard('lost'));
2413
+ }
2414
+ beginDraining() {
2415
+ this.draining = true;
2416
+ }
2417
+ async stopAllSessions(deadlineMs) {
2418
+ const sessions = Array.from(this.activeSessions.values());
2419
+ await Promise.allSettled(sessions.map((session) => this.stopSession(session).catch((err) => {
2420
+ logger.error({ scopeKey: session.scopeKey, err }, 'stop failed during shutdown');
2421
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `stop failed during shutdown: ${session.scopeKey}`, 'error');
2422
+ })));
2423
+ const waitUntil = Date.now() + (deadlineMs ?? 0);
2424
+ while (this.activeSessions.size > 0 && Date.now() < waitUntil) {
2425
+ await new Promise((resolve) => setTimeout(resolve, 50));
2426
+ }
2427
+ }
2428
+ async recoverInflightCards() {
2429
+ const cards = this.store.listInflightCards(this.botId);
2430
+ for (const card of cards) {
2431
+ try {
2432
+ if (card.runId) {
2433
+ const dataDir = resolveDataDir({ dataDir: this.runnerConfig?.dataDir });
2434
+ const botId = this.runnerConfig?.botId ?? 'default';
2435
+ const runDir = resolveRunDir(dataDir, card.runId, botId);
2436
+ const recovered = this.judgeRunState(card.runId, botId);
2437
+ let agentId = card.agentId;
2438
+ let displayName;
2439
+ let runStartedAt;
2440
+ try {
2441
+ const specRaw = readFileSync(runSpecPath(dataDir, card.runId, botId), 'utf8');
2442
+ const spec = JSON.parse(specRaw);
2443
+ agentId = spec['agentId'] ?? agentId;
2444
+ const specStartedAt = typeof spec['startedAt'] === 'string' ? Date.parse(spec['startedAt']) : Number.NaN;
2445
+ if (Number.isFinite(specStartedAt))
2446
+ runStartedAt = specStartedAt;
2447
+ const agent = agentId ? this.registry.lookup(agentId) : null;
2448
+ displayName = agent?.displayName;
2449
+ }
2450
+ catch { /* spec.json may not exist */ }
2451
+ if (recovered === 'resumed') {
2452
+ const shortId = card.runId.slice(0, 12);
2453
+ await this.feishu.updateCard(card.replyMessageId, renderRestartedCard('resumed', shortId, agentId, displayName));
2454
+ logger.info({ runId: card.runId, agentId, replyMessageId: card.replyMessageId }, 'run resumed after restart (heartbeat fresh)');
2455
+ if (this.runnerConfig) {
2456
+ const agent = agentId ? this.registry.lookup(agentId) : null;
2457
+ const caps = agent ? await agent.getCapabilities() : null;
2458
+ if (caps?.tokenRotation === 'rotating' && agentId) {
2459
+ const mapEvent = runnerEventMapper(agentId, { cwd: dataDir });
2460
+ const historicalEvents = readEventsSync(runEventsPath(dataDir, card.runId, botId))
2461
+ .flatMap((raw) => mapEvent(raw));
2462
+ const latestToken = extractLatestContinuationToken(historicalEvents);
2463
+ if (latestToken) {
2464
+ this.store.upsertContinuation(this.botId, card.userOpenId, card.threadId, agentId, latestToken);
2465
+ logger.info({
2466
+ runId: card.runId,
2467
+ agentId,
2468
+ tokenSuffix: latestToken.slice(-8),
2469
+ }, 'F6 backfill: updated store with latest continuationToken from events.ndjson');
2470
+ }
2471
+ }
2472
+ this.reattachEventsStream(card, runDir, agentId, runStartedAt);
2473
+ }
2474
+ }
2475
+ else {
2476
+ const gate = this.reserveStaleSelfHeal(card);
2477
+ if (gate.kind === 'blocked') {
2478
+ await this.handleBlockedStaleSelfHeal(card, 'restart', gate.attempts, gate.shouldEscalate);
2479
+ logger.warn({ runId: card.runId, attempts: gate.attempts, replyMessageId: card.replyMessageId }, 'restart recovery stale-run auto-recovery disabled after attempt limit');
2480
+ }
2481
+ else {
2482
+ writeFileSync(runStopSignalPath(dataDir, card.runId, botId), String(Date.now()));
2483
+ this.reconcileLostCaptainRun(card.userOpenId, card.threadId, card.runId);
2484
+ await this.feishu.updateCard(card.replyMessageId, renderRestartedCard('lost'));
2485
+ await sendAdminAlert(this.alertSink, this.alertDataDir, `restart recovery auto-stopped stale run: ${card.runId} (attempt=${gate.attempts}/${STALE_SELF_HEAL_MAX_ATTEMPTS})`, 'warn');
2486
+ logger.info({ runId: card.runId, replyMessageId: card.replyMessageId, attempts: gate.attempts }, 'run lost after restart (heartbeat stale), stop.signal written');
2487
+ }
2488
+ }
2489
+ }
2490
+ else {
2491
+ await this.feishu.updateCard(card.replyMessageId, renderRestartedCard('lost'));
2492
+ logger.info({
2493
+ sourceMessageId: card.sourceMessageId,
2494
+ replyMessageId: card.replyMessageId,
2495
+ threadId: card.threadId,
2496
+ }, 'patched pre-W2 stale in-flight card after restart');
2497
+ }
2498
+ }
2499
+ catch (error) {
2500
+ logger.error({
2501
+ sourceMessageId: card.sourceMessageId,
2502
+ replyMessageId: card.replyMessageId,
2503
+ threadId: card.threadId,
2504
+ error,
2505
+ }, 'failed to patch stale in-flight card after restart');
2506
+ void sendAdminAlert(this.alertSink, this.alertDataDir, `recover inflight card failed: ${card.replyMessageId}`, 'error');
2507
+ }
2508
+ finally {
2509
+ if (this.activeSessionsForThread(card.userOpenId, card.threadId).length === 0) {
2510
+ this.store.clearInflightCard(this.botId, card.userOpenId, card.threadId, card.agentId);
2511
+ }
2512
+ }
2513
+ }
2514
+ }
2515
+ reattachEventsStream(card, runDir, agentId, runStartedAt) {
2516
+ const ndjsonPath = join(runDir, 'events.ndjson');
2517
+ const eventsReader = new EventsFileReader(ndjsonPath, 0, runnerEventMapper(agentId, { cwd: runDir }));
2518
+ const scopeKey = this.scopeKey(card.userOpenId, card.threadId, agentId ?? 'system');
2519
+ const pipeline = new CardPipeline((c) => this.feishu.updateCard(card.replyMessageId, c), {
2520
+ logger,
2521
+ label: `reply:${card.replyMessageId}`,
2522
+ minIntervalMs: this.cardIntervalMs(card.replyMessageId),
2523
+ });
2524
+ const agent = agentId ? this.registry.lookup(agentId) : null;
2525
+ // 耗时和完成推送门槛按 run 真正的开始时间算, 不从 bot 重启那一刻重新计.
2526
+ const startedAt = runStartedAt ?? Date.now();
2527
+ const state = {
2528
+ ...createInitialState(agentId ?? 'system', agent?.displayName ?? 'Weaverbird', agent?.displayName ?? 'Weaverbird'),
2529
+ startedAt,
2530
+ };
2531
+ const activeSession = {
2532
+ scopeKey,
2533
+ threadId: card.threadId,
2534
+ homeGroupId: null,
2535
+ sourceMessageId: card.replyMessageId,
2536
+ replyMessageId: card.replyMessageId,
2537
+ run: null,
2538
+ runId: card.runId ?? undefined,
2539
+ pipeline,
2540
+ state,
2541
+ extraMessageIds: [],
2542
+ eventsReader,
2543
+ startedAt,
2544
+ agentId: agentId ?? 'system',
2545
+ sessionId: this.sessionIdFor(card.userOpenId, card.threadId),
2546
+ };
2547
+ this.activeSessions.set(scopeKey, activeSession);
2548
+ this.activeSessionsByMessageId.set(card.replyMessageId, activeSession);
2549
+ eventsReader.start();
2550
+ void (async () => {
2551
+ try {
2552
+ for await (const output of eventsReader.events()) {
2553
+ const newState = reduceStreamState(activeSession.state, output);
2554
+ activeSession.state = newState;
2555
+ if ((output.type === 'done' || output.type === 'system') && output.continuationToken && agentId) {
2556
+ this.store.upsertContinuation(this.botId, card.userOpenId, card.threadId, agentId, output.continuationToken);
2557
+ }
2558
+ await (output.type === 'tool_use' || output.type === 'tool_result' || output.type === 'done' || output.type === 'error'
2559
+ ? pipeline.force(renderCard(newState))
2560
+ : pipeline.flush(renderCard(newState)));
2561
+ if (output.type === 'done') {
2562
+ const recoveryAgent = agentId ? this.registry.lookup(agentId) : null;
2563
+ if (recoveryAgent) {
2564
+ await this.handleCompletionPush(activeSession, recoveryAgent, card.userOpenId, card.threadId);
2565
+ }
2566
+ break;
2567
+ }
2568
+ if (output.type === 'error')
2569
+ break;
2570
+ }
2571
+ }
2572
+ finally {
2573
+ eventsReader.stop();
2574
+ this.cleanupSession(activeSession, card.userOpenId, card.threadId);
2575
+ }
2576
+ })();
2577
+ }
2578
+ judgeRunState(runId, botId) {
2579
+ const staleMs = parseInt(process.env['WB_HEARTBEAT_STALE_MS'] ?? '240000', 10);
2580
+ return judgeRunStatePure(botId, runId, { dataDir: this.alertDataDir, staleMs });
2581
+ }
2582
+ isL1HeartbeatFresh(runDir, now, staleMs) {
2583
+ const hbPath = join(runDir, 'heartbeat');
2584
+ if (!existsSync(hbPath))
2585
+ return false;
2586
+ try {
2587
+ const ts = parseInt(readFileSync(hbPath, 'utf8').trim(), 10) * 1000;
2588
+ return (now - ts) < staleMs;
2589
+ }
2590
+ catch {
2591
+ return false;
2592
+ }
2593
+ }
2594
+ isL2HeartbeatFresh(runDir, now, staleMs) {
2595
+ const ndjsonPath = join(runDir, 'events.ndjson');
2596
+ if (!existsSync(ndjsonPath))
2597
+ return false;
2598
+ try {
2599
+ const stat = statSync(ndjsonPath);
2600
+ return (now - stat.mtimeMs) < staleMs;
2601
+ }
2602
+ catch {
2603
+ return false;
2604
+ }
2605
+ }
2606
+ isDuplicate(key) {
2607
+ if (!key)
2608
+ return false;
2609
+ if (this.seen.has(key))
2610
+ return true;
2611
+ this.seen.set(key, Date.now());
2612
+ if (this.seen.size > 2000) {
2613
+ const oldest = this.seen.keys().next().value;
2614
+ if (oldest)
2615
+ this.seen.delete(oldest);
2616
+ }
2617
+ return false;
2618
+ }
2619
+ messageDedupKey(event) {
2620
+ return event.eventId || `${event.threadId}:${event.messageId}`;
2621
+ }
2622
+ scopeKey(userOpenId, threadId, agentId) {
2623
+ return `${userOpenId}:${threadId}:${agentId}`;
2624
+ }
2625
+ activeSessionsForThread(userOpenId, threadId) {
2626
+ const prefix = `${userOpenId}:${threadId}:`;
2627
+ const result = [];
2628
+ for (const [key, session] of this.activeSessions) {
2629
+ if (key.startsWith(prefix))
2630
+ result.push(session);
2631
+ }
2632
+ return result;
2633
+ }
2634
+ }