@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,84 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { writeFileSync, mkdirSync, openSync, existsSync } from 'node:fs';
3
+ import { join, resolve, dirname } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { runDir as resolveRunDir, runSpecPath } from '../../../../packages/core/src/paths.js';
6
+ import { buildFilteredEnv } from '../security/env-whitelist.js';
7
+ /**
8
+ * 决定如何 spawn wb-runner subprocess.
9
+ *
10
+ * - `.js` (dist build output): 直接 `node <path>` (production / npm run build 后跑)
11
+ * - `.ts` (src source): 用 tsx loader `node --import tsx <path>` (dev mode, 无需 build)
12
+ *
13
+ * 背景: child 是 fresh Node 进程, 不继承父进程 tsx loader hook. 直接 `node foo.ts`
14
+ * 会 ERR_MODULE_NOT_FOUND (.ts source 用 `.js` import suffix 给 TS 的 bundle target).
15
+ * 必须 (a) 跑 build 后的 .js, 或 (b) 显式加 tsx loader.
16
+ *
17
+ * tsx 的 loader 模块: `node_modules/tsx/dist/esm/index.mjs`. 用 `--import` flag (Node 20+)
18
+ * 把 loader 在 user code 跑前 register.
19
+ */
20
+ export function buildRunnerSpawnArgs(wbRunnerMainPath, specJsonPath) {
21
+ const absRunnerPath = resolve(wbRunnerMainPath);
22
+ if (absRunnerPath.endsWith('.js')) {
23
+ return { cmd: process.execPath, args: [absRunnerPath, specJsonPath] };
24
+ }
25
+ // .ts source mode: locate tsx ESM loader (walk up from runner path 找 node_modules/tsx)
26
+ let dir = dirname(absRunnerPath);
27
+ let tsxLoader;
28
+ while (true) {
29
+ const candidate = join(dir, 'node_modules/tsx/dist/esm/index.mjs');
30
+ if (existsSync(candidate)) {
31
+ tsxLoader = candidate;
32
+ break;
33
+ }
34
+ const parent = dirname(dir);
35
+ if (parent === dir)
36
+ break;
37
+ dir = parent;
38
+ }
39
+ if (!tsxLoader) {
40
+ // 兜底: 依赖 child 进程能从 cwd resolve tsx (大多 dev 路径 OK)
41
+ return { cmd: process.execPath, args: ['--import', 'tsx', absRunnerPath, specJsonPath] };
42
+ }
43
+ return { cmd: process.execPath, args: ['--import', tsxLoader, absRunnerPath, specJsonPath] };
44
+ }
45
+ export function generateRunId() {
46
+ return randomUUID();
47
+ }
48
+ export function buildRunSpec(opts) {
49
+ return {
50
+ runId: opts.runId,
51
+ botId: opts.botId,
52
+ agentId: opts.agentId,
53
+ agentCommand: opts.agentCommand,
54
+ agentArgs: opts.agentArgs,
55
+ cwd: opts.cwd,
56
+ env: opts.env,
57
+ userOpenId: opts.userOpenId,
58
+ threadId: opts.threadId,
59
+ sourceMessageId: opts.sourceMessageId,
60
+ replyMessageId: opts.replyMessageId,
61
+ continuationToken: opts.continuationToken,
62
+ consentLevel: opts.consentLevel,
63
+ model: opts.model,
64
+ ...(opts.stdinInput !== undefined ? { stdinInput: opts.stdinInput } : {}),
65
+ };
66
+ }
67
+ export function spawnWbRunner(opts) {
68
+ const { dataDir, spec, wbRunnerMainPath } = opts;
69
+ const runDir = resolveRunDir(dataDir, spec.runId, spec.botId);
70
+ mkdirSync(runDir, { recursive: true });
71
+ const specJsonPath = runSpecPath(dataDir, spec.runId, spec.botId);
72
+ writeFileSync(specJsonPath, JSON.stringify(spec, null, 2));
73
+ const outputFd = openSync(join(runDir, 'wb-runner.stdout'), 'a');
74
+ const errFd = openSync(join(runDir, 'wb-runner.stderr'), 'a');
75
+ const wbRunnerEnv = buildFilteredEnv('wb-runner', process.env);
76
+ const { cmd, args } = buildRunnerSpawnArgs(wbRunnerMainPath, specJsonPath);
77
+ const child = spawn(cmd, args, {
78
+ detached: true,
79
+ stdio: ['ignore', outputFd, errFd],
80
+ env: wbRunnerEnv,
81
+ });
82
+ child.unref();
83
+ return { runId: spec.runId, runDir, specJsonPath, child };
84
+ }
@@ -0,0 +1,20 @@
1
+ import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { botHeartbeatPath, botHeartbeatTempPath, runsDir } from '../../../../packages/core/src/paths.js';
3
+ export function startBotHeartbeat(opts) {
4
+ const intervalMs = opts.intervalMs ?? 10_000;
5
+ const heartbeatDir = runsDir(opts.dataDir, opts.botId);
6
+ const heartbeatPath = botHeartbeatPath(opts.dataDir, opts.botId);
7
+ const tmpPath = botHeartbeatTempPath(opts.dataDir, opts.botId);
8
+ const now = opts.nowFn ?? Date.now;
9
+ function writeOnce() {
10
+ mkdirSync(heartbeatDir, { recursive: true });
11
+ writeFileSync(tmpPath, String(Math.floor(now() / 1000)));
12
+ renameSync(tmpPath, heartbeatPath);
13
+ }
14
+ writeOnce();
15
+ const timer = setInterval(writeOnce, intervalMs);
16
+ return {
17
+ stop: () => clearInterval(timer),
18
+ writeOnce,
19
+ };
20
+ }
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env node
2
+ import pino from 'pino';
3
+ import { botDbPath, resolveDataDir } from '../../../packages/core/src/paths.js';
4
+ import { BindingStore } from './binding/store.js';
5
+ import { readEnv } from './config/env.js';
6
+ import { startTransport } from './feishu/transport.js';
7
+ import { createBotAgentRegistry } from './agent-registry.js';
8
+ import { validateCwd, CWD_DENYLIST } from './security/cwd-guard.js';
9
+ import { ensureDataDirIntegrity } from './boot/integrity.js';
10
+ import { createLogger } from './boot/logger.js';
11
+ import { TaskIndex } from './binding/task-index.js';
12
+ import { sendAdminAlert } from './feishu/admin-alert.js';
13
+ import { USAGE, parseArgs } from './cli/parse-args.js';
14
+ import { runInitCommand } from './cli/init.js';
15
+ import { runDoctorCommand } from './cli/doctor.js';
16
+ import { MISSING_CREDENTIALS_HINT, lacksLarkCredentials } from './cli/preflight.js';
17
+ import { assertValidBotId } from './security/bot-id-validator.js';
18
+ import { resolveConfigDir, botEnvPath } from './config/config-paths.js';
19
+ import { loadBotEnvFromFile } from './config/bot-env.js';
20
+ import { loadApprovalCodeOwnerConfig } from './config/approval-code-owners.js';
21
+ import { startBotHeartbeat } from './heartbeat/bot-heartbeat.js';
22
+ import { COMMAND_CATALOG, validateCatalog } from '../../../packages/core/src/captain/index.js';
23
+ const TASK_INDEX_SCAN_INTERVAL_MS = 5 * 60 * 1000;
24
+ const SHUTDOWN_GRACE_MS = 15_000;
25
+ const DRAIN_MARKER = '__WB_DRAINED__';
26
+ async function main() {
27
+ const cliArgs = parseArgs(process.argv.slice(2));
28
+ if (cliArgs.help) {
29
+ console.log(USAGE);
30
+ process.exit(0);
31
+ }
32
+ if (cliArgs.command === 'init') {
33
+ process.exit(await runInitCommand({ ...(cliArgs.botId ? { botId: cliArgs.botId } : {}), force: cliArgs.force === true }, resolveConfigDir()));
34
+ }
35
+ if (cliArgs.command === 'doctor') {
36
+ process.exit(await runDoctorCommand(assertValidBotId(cliArgs.botId ?? 'default', 'CLI --bot'), resolveConfigDir()));
37
+ }
38
+ const isMultiBot = cliArgs.botId !== undefined || process.env['WB_MODE'] === 'multi-bot';
39
+ if (isMultiBot) {
40
+ const raw = cliArgs.botId ?? process.env['BOT_ID'];
41
+ if (!raw) {
42
+ console.error('multi-bot mode requires --bot <botId> or BOT_ID env');
43
+ process.exit(1);
44
+ }
45
+ const botId = assertValidBotId(raw, 'CLI --bot or BOT_ID env');
46
+ const configDir = resolveConfigDir();
47
+ const filePath = botEnvPath(configDir, botId);
48
+ const botCfg = loadBotEnvFromFile(filePath);
49
+ process.env['BOT_ID'] = botCfg.botId;
50
+ process.env['LARK_APP_ID'] = botCfg.larkAppId;
51
+ process.env['LARK_APP_SECRET'] = botCfg.larkAppSecret;
52
+ process.env['LARK_ENCRYPT_KEY'] = botCfg.larkEncryptKey;
53
+ process.env['LARK_VERIFICATION_TOKEN'] = botCfg.larkVerificationToken;
54
+ process.env['AGENT_ALLOWED'] = botCfg.agentAllowed.join(',');
55
+ if (botCfg.defaultCwd)
56
+ process.env['WB_DEFAULT_CWD'] = botCfg.defaultCwd;
57
+ if (botCfg.approvalCodeOwnerConfigPath) {
58
+ process.env['WB_APPROVAL_CODE_OWNER_CONFIG_PATH'] = botCfg.approvalCodeOwnerConfigPath;
59
+ }
60
+ process.env['WB_CLAUDE_COMMAND'] = botCfg.claudeCommand;
61
+ process.env['WB_CODEX_COMMAND'] = botCfg.codexCommand;
62
+ process.env['WB_CLAUDE_CONSENT_LEVEL'] = botCfg.consentLevel;
63
+ process.env['LOG_LEVEL'] = botCfg.logLevel;
64
+ process.env['WB_MODE'] = 'multi-bot';
65
+ }
66
+ if (!isMultiBot && lacksLarkCredentials(process.env)) {
67
+ console.error(MISSING_CREDENTIALS_HINT);
68
+ process.exit(1);
69
+ }
70
+ const env = readEnv();
71
+ if (env.WB_APPROVAL_CODE_OWNER_CONFIG_PATH) {
72
+ loadApprovalCodeOwnerConfig({ configPath: env.WB_APPROVAL_CODE_OWNER_CONFIG_PATH });
73
+ }
74
+ const bootLogger = pino({ level: env.LOG_LEVEL });
75
+ validateCatalog(Object.keys(COMMAND_CATALOG));
76
+ const integrity = ensureDataDirIntegrity(env.dataDir, bootLogger);
77
+ if (integrity.unwritable.length > 0) {
78
+ void sendAdminAlert(null, env.dataDir, `boot integrity: ${integrity.unwritable.length} directories not writable: ${integrity.unwritable.join(', ')}`, 'error');
79
+ }
80
+ const { logger, logFilePath } = await createLogger({
81
+ dataDir: env.dataDir,
82
+ botId: env.botId,
83
+ level: env.LOG_LEVEL,
84
+ });
85
+ logger.info({ logFilePath, botId: env.botId, mode: env.mode }, '📝 logger multi-stream ready (stdout + pino-pretty file, daily rotation, retain 7)');
86
+ const store = new BindingStore(botDbPath(env.dataDir));
87
+ if (store.isReadOnly) {
88
+ logger.error({ error: store.migrationResult.error }, '⛔ database migration failed, wb-bot starting in read-only mode');
89
+ void sendAdminAlert(null, env.dataDir, `database migration failed: ${store.migrationResult.error ?? 'unknown'}; wb-bot started in read-only mode`, 'error');
90
+ }
91
+ else {
92
+ logger.info({ migration: store.migrationResult }, '✅ database migrations completed');
93
+ }
94
+ let defaultCwd;
95
+ if (env.defaultCwd) {
96
+ // WB_DEFAULT_CWD is operator-controlled startup config; only check denylist
97
+ const result = validateCwd(env.defaultCwd, [env.defaultCwd], CWD_DENYLIST);
98
+ if (!result.ok) {
99
+ logger.error({ WB_DEFAULT_CWD: env.defaultCwd, reason: result.reason }, '⛔ WB_DEFAULT_CWD is not valid, ignoring');
100
+ void sendAdminAlert(null, env.dataDir, `WB_DEFAULT_CWD invalid (${env.defaultCwd}): ${result.reason}; falling back to per-message cwd`, 'warn');
101
+ }
102
+ else {
103
+ defaultCwd = result.path;
104
+ logger.info({ defaultCwd }, '✅ using WB_DEFAULT_CWD as fallback cwd');
105
+ }
106
+ }
107
+ const taskIndex = new TaskIndex(env.dataDir, env.botId);
108
+ taskIndex.scan();
109
+ const taskIndexInterval = setInterval(() => taskIndex.scheduleScan(), TASK_INDEX_SCAN_INTERVAL_MS);
110
+ logger.info({ taskIndexSize: taskIndex.size }, '📚 TaskIndex initialized + scheduled');
111
+ const botHeartbeat = startBotHeartbeat({ dataDir: env.dataDir, botId: env.botId });
112
+ logger.info({ botId: env.botId }, '💓 bot self-heartbeat started');
113
+ logger.info({ dataDir: env.dataDir, claudeCommand: env.claudeCommand, codexCommand: env.codexCommand }, '🚀 starting wb-bot');
114
+ const { handler, close } = await startTransport(createBotAgentRegistry({ dataDir: env.dataDir, claudeCommand: env.claudeCommand, codexCommand: env.codexCommand }), store, defaultCwd, env.WB_CLAUDE_CONSENT_LEVEL, env.dataDir, { botId: env.botId, taskIndex, logFilePath });
115
+ logger.info('✅ wb-bot transport started');
116
+ let shuttingDown = false;
117
+ async function shutdown(signal) {
118
+ if (shuttingDown)
119
+ return;
120
+ shuttingDown = true;
121
+ logger.info({ signal }, '🛑 shutting down');
122
+ clearInterval(taskIndexInterval);
123
+ botHeartbeat.stop();
124
+ handler.beginDraining();
125
+ await handler.stopAllSessions(SHUTDOWN_GRACE_MS);
126
+ process.stdout.write(`${DRAIN_MARKER}\n`);
127
+ await close();
128
+ store.close();
129
+ process.exit(0);
130
+ }
131
+ process.on('SIGINT', () => { void shutdown('SIGINT'); });
132
+ process.on('SIGTERM', () => { void shutdown('SIGTERM'); });
133
+ }
134
+ void main().catch((error) => {
135
+ const logger = pino({ level: process.env['LOG_LEVEL'] ?? 'info' });
136
+ logger.error({ err: error }, '🔥 wb-bot failed');
137
+ // Best-effort fatal admin alert; readEnv() may itself have failed, so fall back to env or default
138
+ const dataDir = resolveDataDir();
139
+ const message = error instanceof Error ? error.message : String(error);
140
+ void sendAdminAlert(null, dataDir, `wb-bot fatal startup failure: ${message}`, 'fatal').catch(() => {
141
+ // file write may also fail (e.g. dataDir missing); nothing more we can do
142
+ });
143
+ process.exit(1);
144
+ });
@@ -0,0 +1,53 @@
1
+ import { existsSync, readdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { loadBotEnvFromFile } from '../config/bot-env.js';
4
+ import { validateBotId } from '../security/bot-id-validator.js';
5
+ const IGNORED_ENV_SUFFIXES = new Set([
6
+ 'local',
7
+ 'example',
8
+ 'test',
9
+ 'development',
10
+ 'production',
11
+ 'staging',
12
+ ]);
13
+ export function discoverBots(configDir, logger) {
14
+ if (!existsSync(configDir)) {
15
+ throw new Error(`configDir not found: ${configDir}`);
16
+ }
17
+ const bots = [];
18
+ const warnings = [];
19
+ for (const entry of readdirSync(configDir, { withFileTypes: true })) {
20
+ if (!entry.isFile())
21
+ continue;
22
+ if (!entry.name.startsWith('.env.'))
23
+ continue;
24
+ const match = entry.name.match(/^\.env\.(.+)$/);
25
+ if (!match)
26
+ continue;
27
+ const botId = match[1];
28
+ if (IGNORED_ENV_SUFFIXES.has(botId)) {
29
+ logger?.info?.({ file: entry.name, configDir }, 'skipping reserved env suffix');
30
+ continue;
31
+ }
32
+ const validation = validateBotId(botId);
33
+ if (!validation.ok) {
34
+ const warning = { file: entry.name, reason: validation.reason ?? 'invalid botId' };
35
+ warnings.push(warning);
36
+ logger?.warn({ ...warning, configDir }, 'skipping invalid bot env filename');
37
+ continue;
38
+ }
39
+ const configPath = join(configDir, entry.name);
40
+ try {
41
+ loadBotEnvFromFile(configPath);
42
+ bots.push({ botId, configPath });
43
+ }
44
+ catch (error) {
45
+ const reason = error instanceof Error ? error.message : String(error);
46
+ const warning = { file: entry.name, reason };
47
+ warnings.push(warning);
48
+ logger?.warn({ ...warning, configDir }, 'skipping invalid bot env file');
49
+ }
50
+ }
51
+ bots.sort((left, right) => left.botId.localeCompare(right.botId));
52
+ return { bots, warnings };
53
+ }
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env node
2
+ import { fileURLToPath } from 'node:url';
3
+ import pino from 'pino';
4
+ import { resolveConfigDir } from '../config/config-paths.js';
5
+ import { discoverBots } from './discovery.js';
6
+ import { parseMultiArgs } from './parse-args.js';
7
+ import { Supervisor } from './supervisor.js';
8
+ const DEFAULT_SHUTDOWN_GRACE_MS = 15_000;
9
+ async function main() {
10
+ const logger = pino({ level: process.env['LOG_LEVEL'] ?? 'info' });
11
+ const cliArgs = parseMultiArgs(process.argv.slice(2));
12
+ if (cliArgs.help) {
13
+ console.log('Usage: wb-bot-multi [--config <path>] [--help]');
14
+ process.exit(0);
15
+ }
16
+ const configDir = cliArgs.configDir ?? resolveConfigDir();
17
+ const discovery = discoverBots(configDir);
18
+ for (const warning of discovery.warnings) {
19
+ logger.warn({ configDir, file: warning.file, reason: warning.reason }, 'skipping invalid bot config');
20
+ }
21
+ if (discovery.bots.length === 0) {
22
+ logger.error({ configDir }, 'no valid bot configs discovered');
23
+ process.exit(1);
24
+ }
25
+ const mainJs = fileURLToPath(new URL('../main.js', import.meta.url));
26
+ const supervisor = new Supervisor(discovery.bots, {
27
+ bin: process.execPath,
28
+ mainJs,
29
+ baseEnv: process.env,
30
+ logger,
31
+ });
32
+ logger.info({ configDir, botIds: discovery.bots.map((bot) => bot.botId) }, 'starting multi-bot orchestrator');
33
+ supervisor.startAll();
34
+ let shuttingDown = false;
35
+ async function handleSignal(signal) {
36
+ if (shuttingDown)
37
+ return;
38
+ shuttingDown = true;
39
+ logger.info({ signal }, 'shutting down multi-bot orchestrator');
40
+ await supervisor.shutdown(signal, DEFAULT_SHUTDOWN_GRACE_MS);
41
+ process.exit(0);
42
+ }
43
+ process.on('SIGINT', () => {
44
+ void handleSignal('SIGINT');
45
+ });
46
+ process.on('SIGTERM', () => {
47
+ void handleSignal('SIGTERM');
48
+ });
49
+ await supervisor.untilAllExited();
50
+ logger.info('all supervised bots exited');
51
+ process.exit(0);
52
+ }
53
+ void main().catch((error) => {
54
+ const logger = pino({ level: process.env['LOG_LEVEL'] ?? 'info' });
55
+ logger.error({ err: error }, 'wb-bot-multi failed');
56
+ process.exit(1);
57
+ });
@@ -0,0 +1,17 @@
1
+ export function parseMultiArgs(argv) {
2
+ const out = {};
3
+ for (let i = 0; i < argv.length; i++) {
4
+ const arg = argv[i];
5
+ if (arg === '--help' || arg === '-h') {
6
+ out.help = true;
7
+ continue;
8
+ }
9
+ if (arg === '--config') {
10
+ const value = argv[++i];
11
+ if (!value || value.startsWith('-'))
12
+ throw new Error('--config requires a value');
13
+ out.configDir = value;
14
+ }
15
+ }
16
+ return out;
17
+ }
@@ -0,0 +1,288 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createInterface } from 'node:readline';
3
+ const HEALTHY_UPTIME_MS = 5 * 60 * 1000;
4
+ const HEALTH_CHECK_INTERVAL_MS = 60 * 1000;
5
+ const CRASH_WINDOW_MS = 10 * 60 * 1000;
6
+ const MAX_CRASHES_PER_WINDOW = 10;
7
+ const DRAIN_MARKER = '__WB_DRAINED__';
8
+ export function nextBackoffMs(restartCount) {
9
+ return Math.min(1000 * Math.pow(2, restartCount), 30_000);
10
+ }
11
+ export function shouldGiveUp(crashWindow, now) {
12
+ const recent = crashWindow.filter((timestamp) => timestamp > now - CRASH_WINDOW_MS);
13
+ return recent.length >= MAX_CRASHES_PER_WINDOW;
14
+ }
15
+ export function isHealthyUptime(startedAt, now) {
16
+ return now - startedAt > HEALTHY_UPTIME_MS;
17
+ }
18
+ export class Supervisor {
19
+ opts;
20
+ states = new Map();
21
+ spawnFn;
22
+ nowFn;
23
+ waiters = new Set();
24
+ changeWaiters = new Set();
25
+ healthyTimer = null;
26
+ shuttingDown = false;
27
+ started = false;
28
+ constructor(bots, opts) {
29
+ this.opts = opts;
30
+ this.spawnFn = opts.spawnFn ?? spawn;
31
+ this.nowFn = opts.nowFn ?? Date.now;
32
+ for (const bot of bots) {
33
+ this.states.set(bot.botId, {
34
+ botId: bot.botId,
35
+ configPath: bot.configPath,
36
+ child: null,
37
+ startedAt: null,
38
+ restartCount: 0,
39
+ crashWindow: [],
40
+ status: 'stopped',
41
+ restartTimer: null,
42
+ drainSeen: false,
43
+ drainReader: null,
44
+ canObserveDrain: false,
45
+ signalSent: false,
46
+ });
47
+ }
48
+ }
49
+ startAll() {
50
+ if (this.started)
51
+ return;
52
+ this.started = true;
53
+ this.healthyTimer = setInterval(() => this.checkHealthy(), HEALTH_CHECK_INTERVAL_MS);
54
+ for (const state of this.states.values()) {
55
+ this.spawnOne(state);
56
+ }
57
+ this.checkTerminal();
58
+ }
59
+ async shutdown(signal, gracePeriodMs) {
60
+ this.shuttingDown = true;
61
+ if (this.healthyTimer) {
62
+ clearInterval(this.healthyTimer);
63
+ this.healthyTimer = null;
64
+ }
65
+ const deadline = this.nowFn() + gracePeriodMs;
66
+ for (const state of this.states.values()) {
67
+ if (state.restartTimer) {
68
+ clearTimeout(state.restartTimer);
69
+ state.restartTimer = null;
70
+ }
71
+ if (state.status === 'failed' || state.status === 'stopped')
72
+ continue;
73
+ if (!state.child) {
74
+ state.status = 'stopped';
75
+ continue;
76
+ }
77
+ if (!state.canObserveDrain) {
78
+ state.status = 'stopping';
79
+ state.signalSent = true;
80
+ this.killChild(state, signal);
81
+ }
82
+ }
83
+ this.checkTerminal();
84
+ if (!this.areAllExited() && this.hasDrainAwareChildren()) {
85
+ await this.waitForDrainOrExit(deadline);
86
+ }
87
+ if (this.areAllExited())
88
+ return;
89
+ for (const state of this.states.values()) {
90
+ if (!state.child || state.status === 'failed' || state.status === 'stopped' || state.signalSent)
91
+ continue;
92
+ state.status = 'stopping';
93
+ state.signalSent = true;
94
+ this.killChild(state, signal);
95
+ }
96
+ const remainingMs = Math.max(0, deadline - this.nowFn());
97
+ await Promise.race([
98
+ this.untilAllExited(),
99
+ new Promise((resolve) => setTimeout(resolve, remainingMs)),
100
+ ]);
101
+ if (this.areAllExited())
102
+ return;
103
+ for (const state of this.states.values()) {
104
+ if (!state.child)
105
+ continue;
106
+ state.status = 'stopping';
107
+ this.killChild(state, 'SIGKILL');
108
+ }
109
+ }
110
+ untilAllExited() {
111
+ if (this.areAllExited())
112
+ return Promise.resolve();
113
+ return new Promise((resolve) => {
114
+ this.waiters.add(resolve);
115
+ });
116
+ }
117
+ getStates() {
118
+ return Array.from(this.states.values(), (state) => ({
119
+ botId: state.botId,
120
+ configPath: state.configPath,
121
+ child: state.child,
122
+ startedAt: state.startedAt,
123
+ restartCount: state.restartCount,
124
+ crashWindow: [...state.crashWindow],
125
+ status: state.status,
126
+ failureReason: state.failureReason,
127
+ }));
128
+ }
129
+ spawnOne(state) {
130
+ if (this.shuttingDown) {
131
+ state.status = 'stopped';
132
+ this.checkTerminal();
133
+ return;
134
+ }
135
+ state.restartTimer = null;
136
+ state.failureReason = undefined;
137
+ state.status = 'starting';
138
+ state.drainSeen = false;
139
+ state.canObserveDrain = false;
140
+ state.signalSent = false;
141
+ state.drainReader?.close();
142
+ state.drainReader = null;
143
+ const child = this.spawnFn(this.opts.bin, [this.opts.mainJs, '--bot', state.botId], {
144
+ env: { ...this.opts.baseEnv, BOT_ID: state.botId, WB_MODE: 'multi-bot' },
145
+ stdio: ['ignore', 'pipe', 'inherit'],
146
+ detached: false,
147
+ });
148
+ state.child = child;
149
+ state.startedAt = this.nowFn();
150
+ state.status = 'running';
151
+ this.attachDrainReader(state, child);
152
+ this.opts.logger.info({ botId: state.botId, pid: child.pid, configPath: state.configPath }, 'started wb-bot child');
153
+ let handled = false;
154
+ const finalize = (code, signal, error) => {
155
+ if (handled)
156
+ return;
157
+ handled = true;
158
+ state.child = null;
159
+ state.startedAt = null;
160
+ state.drainReader?.close();
161
+ state.drainReader = null;
162
+ state.drainSeen = false;
163
+ state.canObserveDrain = false;
164
+ state.signalSent = false;
165
+ this.notifyChange();
166
+ if (this.shuttingDown || state.status === 'stopping') {
167
+ state.status = 'stopped';
168
+ this.opts.logger.info({ botId: state.botId, code, signal }, 'wb-bot child stopped');
169
+ this.checkTerminal();
170
+ return;
171
+ }
172
+ const now = this.nowFn();
173
+ state.crashWindow = state.crashWindow.filter((timestamp) => timestamp > now - CRASH_WINDOW_MS);
174
+ state.crashWindow.push(now);
175
+ if (shouldGiveUp(state.crashWindow, now)) {
176
+ state.status = 'failed';
177
+ state.failureReason = error?.message ?? `crashed ${state.crashWindow.length} times in 10 min`;
178
+ this.opts.logger.error({ botId: state.botId, code, signal, failureReason: state.failureReason }, 'bot give-up, no more restart');
179
+ this.checkTerminal();
180
+ return;
181
+ }
182
+ const backoffMs = nextBackoffMs(state.restartCount);
183
+ state.restartCount += 1;
184
+ state.status = 'restarting';
185
+ this.opts.logger.warn({ botId: state.botId, code, signal, restartCount: state.restartCount, backoffMs }, 'bot crashed, scheduling restart');
186
+ state.restartTimer = setTimeout(() => {
187
+ state.restartTimer = null;
188
+ if (state.status !== 'restarting') {
189
+ this.checkTerminal();
190
+ return;
191
+ }
192
+ this.spawnOne(state);
193
+ }, backoffMs);
194
+ this.checkTerminal();
195
+ };
196
+ child.once('exit', (code, signal) => finalize(code, signal));
197
+ child.once('error', (error) => finalize(null, null, error instanceof Error ? error : new Error(String(error))));
198
+ }
199
+ attachDrainReader(state, child) {
200
+ if (!child.stdout)
201
+ return;
202
+ state.canObserveDrain = true;
203
+ const reader = createInterface({ input: child.stdout });
204
+ state.drainReader = reader;
205
+ let buffered = '';
206
+ child.stdout.on('data', (chunk) => {
207
+ const text = chunk.toString();
208
+ buffered += text;
209
+ process.stdout.write(chunk);
210
+ if (buffered.includes(`${DRAIN_MARKER}\n`)) {
211
+ state.drainSeen = true;
212
+ this.notifyChange();
213
+ }
214
+ if (buffered.length > DRAIN_MARKER.length * 4) {
215
+ buffered = buffered.slice(-DRAIN_MARKER.length * 2);
216
+ }
217
+ });
218
+ reader.on('line', (line) => {
219
+ if (line !== DRAIN_MARKER)
220
+ return;
221
+ state.drainSeen = true;
222
+ this.notifyChange();
223
+ });
224
+ }
225
+ hasDrainAwareChildren() {
226
+ return Array.from(this.states.values()).some((state) => state.child && state.canObserveDrain && !state.drainSeen);
227
+ }
228
+ async waitForDrainOrExit(deadline) {
229
+ while (this.nowFn() < deadline) {
230
+ if (this.areAllExited())
231
+ return;
232
+ const waiting = Array.from(this.states.values()).filter((state) => state.child && state.canObserveDrain && !state.drainSeen);
233
+ if (waiting.length === 0)
234
+ return;
235
+ const remainingMs = Math.max(0, deadline - this.nowFn());
236
+ await Promise.race([
237
+ this.untilChanged(),
238
+ new Promise((resolve) => setTimeout(resolve, remainingMs)),
239
+ ]);
240
+ }
241
+ }
242
+ untilChanged() {
243
+ return new Promise((resolve) => {
244
+ this.changeWaiters.add(resolve);
245
+ });
246
+ }
247
+ notifyChange() {
248
+ for (const resolve of this.changeWaiters)
249
+ resolve();
250
+ this.changeWaiters.clear();
251
+ }
252
+ checkHealthy() {
253
+ const now = this.nowFn();
254
+ for (const state of this.states.values()) {
255
+ if (state.status !== 'running' || state.startedAt === null)
256
+ continue;
257
+ if (!isHealthyUptime(state.startedAt, now))
258
+ continue;
259
+ if (state.restartCount === 0 && state.crashWindow.length === 0)
260
+ continue;
261
+ state.restartCount = 0;
262
+ state.crashWindow = [];
263
+ this.opts.logger.info({ botId: state.botId }, 'wb-bot child healthy, reset restart window');
264
+ }
265
+ }
266
+ killChild(state, signal) {
267
+ try {
268
+ state.child?.kill(signal);
269
+ }
270
+ catch (error) {
271
+ this.opts.logger.warn({ botId: state.botId, signal, err: error }, 'failed to signal wb-bot child');
272
+ }
273
+ }
274
+ areAllExited() {
275
+ return Array.from(this.states.values()).every((state) => state.status === 'stopped' || state.status === 'failed');
276
+ }
277
+ checkTerminal() {
278
+ if (!this.areAllExited())
279
+ return;
280
+ if (this.healthyTimer) {
281
+ clearInterval(this.healthyTimer);
282
+ this.healthyTimer = null;
283
+ }
284
+ for (const resolve of this.waiters)
285
+ resolve();
286
+ this.waiters.clear();
287
+ }
288
+ }