@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,270 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import BetterSqlite3 from 'better-sqlite3';
4
+ import { runMigrations } from './migration-runner.js';
5
+ import { SCHEMA_SQL } from './schema.js';
6
+ import { sleepSync } from './sleep-sync.js';
7
+ import { toChatTopicKey } from '../feishu/topic-key.js';
8
+ const ALIAS_CHAIN_LIMIT = 8;
9
+ export class BindingStore {
10
+ db;
11
+ readOnly;
12
+ migrationResult;
13
+ constructor(dbPath) {
14
+ mkdirSync(dirname(dbPath), { recursive: true });
15
+ this.db = new BetterSqlite3(dbPath, { timeout: 5000 });
16
+ this.ensureWalMode();
17
+ this.db.pragma('foreign_keys = ON');
18
+ for (const sql of SCHEMA_SQL)
19
+ this.db.exec(sql);
20
+ this.migrationResult = runMigrations(this.db);
21
+ this.readOnly = !this.migrationResult.success;
22
+ }
23
+ ensureWalMode() {
24
+ const db = this.db;
25
+ const current = String(db.pragma('journal_mode', { simple: true }) ?? '').toLowerCase();
26
+ if (current === 'wal')
27
+ return;
28
+ const delays = [50, 100, 200, 400, 800, 1600];
29
+ let lastError;
30
+ for (let i = 0; i <= delays.length; i++) {
31
+ try {
32
+ this.db.pragma('journal_mode = WAL');
33
+ return;
34
+ }
35
+ catch (error) {
36
+ lastError = error;
37
+ const code = error instanceof Error && 'code' in error
38
+ ? error.code
39
+ : undefined;
40
+ if (code !== 'SQLITE_BUSY' && code !== 'SQLITE_LOCKED')
41
+ throw error;
42
+ if (i === delays.length)
43
+ break;
44
+ sleepSync(delays[i]);
45
+ const recheck = String(db.pragma('journal_mode', { simple: true }) ?? '').toLowerCase();
46
+ if (recheck === 'wal')
47
+ return;
48
+ }
49
+ }
50
+ throw lastError;
51
+ }
52
+ initialThreadIdCandidates(threadId) {
53
+ const normalized = threadId.trim();
54
+ if (!normalized)
55
+ return [];
56
+ const out = [normalized];
57
+ if (normalized.startsWith('chat:')) {
58
+ out.push(normalized.slice('chat:'.length));
59
+ return out;
60
+ }
61
+ if (normalized.startsWith('root:'))
62
+ return out;
63
+ const chatKey = toChatTopicKey(normalized);
64
+ if (chatKey && chatKey !== normalized)
65
+ out.push(chatKey);
66
+ return out;
67
+ }
68
+ listThreadIdCandidates(botId, userOpenId, threadId) {
69
+ const queue = this.initialThreadIdCandidates(threadId);
70
+ const seen = new Set(queue);
71
+ const readAlias = this.db.prepare('SELECT target_thread_id FROM thread_alias WHERE bot_id = ? AND user_open_id = ? AND alias_thread_id = ?');
72
+ for (let i = 0; i < queue.length && i < ALIAS_CHAIN_LIMIT; i += 1) {
73
+ const key = queue[i];
74
+ const row = readAlias.get(botId, userOpenId, key);
75
+ const target = typeof row?.target_thread_id === 'string' ? row.target_thread_id : null;
76
+ if (!target || seen.has(target))
77
+ continue;
78
+ seen.add(target);
79
+ queue.push(target);
80
+ for (const fallback of this.initialThreadIdCandidates(target)) {
81
+ if (seen.has(fallback))
82
+ continue;
83
+ seen.add(fallback);
84
+ queue.push(fallback);
85
+ }
86
+ }
87
+ return queue;
88
+ }
89
+ findThreadBindingRow(botId, userOpenId, threadId) {
90
+ const stmt = this.db.prepare('SELECT user_open_id, thread_id, agent_id, cwd FROM thread_binding WHERE bot_id = ? AND user_open_id = ? AND thread_id = ?');
91
+ for (const candidate of this.listThreadIdCandidates(botId, userOpenId, threadId)) {
92
+ const row = stmt.get(botId, userOpenId, candidate);
93
+ if (row)
94
+ return row;
95
+ }
96
+ return undefined;
97
+ }
98
+ findContinuationRow(botId, userOpenId, threadId, agentId) {
99
+ const stmt = this.db.prepare('SELECT thread_id, continuation_token FROM agent_continuation WHERE bot_id = ? AND user_open_id = ? AND thread_id = ? AND agent_id = ?');
100
+ for (const candidate of this.listThreadIdCandidates(botId, userOpenId, threadId)) {
101
+ const row = stmt.get(botId, userOpenId, candidate, agentId);
102
+ if (row)
103
+ return row;
104
+ }
105
+ return undefined;
106
+ }
107
+ findInflightCardRow(botId, userOpenId, threadId, agentId) {
108
+ const stmt = this.db.prepare('SELECT * FROM inflight_card WHERE bot_id = ? AND user_open_id = ? AND thread_id = ? AND agent_id = ?');
109
+ for (const candidate of this.listThreadIdCandidates(botId, userOpenId, threadId)) {
110
+ const row = stmt.get(botId, userOpenId, candidate, agentId);
111
+ if (row)
112
+ return row;
113
+ }
114
+ return undefined;
115
+ }
116
+ toInflightCard(row) {
117
+ return {
118
+ userOpenId: row['user_open_id'],
119
+ threadId: row['thread_id'],
120
+ sourceMessageId: row['source_message_id'],
121
+ replyMessageId: row['reply_message_id'],
122
+ agentId: row['agent_id'],
123
+ runId: row['run_id'] ?? undefined,
124
+ };
125
+ }
126
+ get isReadOnly() {
127
+ return this.readOnly;
128
+ }
129
+ /**
130
+ * SQLite integrity quick check (lightweight, not full PRAGMA integrity_check).
131
+ * Block E E6 + plan v1.5 §2 Block E (A.M-7): chosen over BEGIN IMMEDIATE
132
+ * to avoid contending the write lock in W2.5 multi-bot scenarios.
133
+ */
134
+ quickCheck() {
135
+ try {
136
+ const row = this.db.prepare('PRAGMA quick_check').get();
137
+ const value = row?.quick_check ?? '';
138
+ if (value === 'ok')
139
+ return { ok: true };
140
+ return { ok: false, error: value };
141
+ }
142
+ catch (err) {
143
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
144
+ }
145
+ }
146
+ close() {
147
+ this.db.close();
148
+ }
149
+ upsertThreadAlias(botId, userOpenId, aliasThreadId, targetThreadId) {
150
+ if (this.readOnly)
151
+ return;
152
+ if (!aliasThreadId || !targetThreadId)
153
+ return;
154
+ this.db.prepare(`INSERT INTO thread_alias (bot_id, user_open_id, alias_thread_id, target_thread_id)
155
+ VALUES (?, ?, ?, ?)
156
+ ON CONFLICT(bot_id, user_open_id, alias_thread_id)
157
+ DO UPDATE SET target_thread_id = excluded.target_thread_id`).run(botId, userOpenId, aliasThreadId, targetThreadId);
158
+ }
159
+ getThreadBinding(botId, userOpenId, threadId) {
160
+ const row = this.findThreadBindingRow(botId, userOpenId, threadId);
161
+ if (!row)
162
+ return null;
163
+ return { userOpenId: row.user_open_id, threadId: row.thread_id, agentId: row.agent_id, cwd: row.cwd };
164
+ }
165
+ upsertThreadBinding(botId, binding) {
166
+ const existing = this.findThreadBindingRow(botId, binding.userOpenId, binding.threadId);
167
+ const threadId = existing?.thread_id ?? binding.threadId;
168
+ this.db.prepare(`INSERT INTO thread_binding (bot_id, user_open_id, thread_id, agent_id, cwd)
169
+ VALUES (?, ?, ?, ?, ?)
170
+ ON CONFLICT(bot_id, user_open_id, thread_id)
171
+ DO UPDATE SET agent_id = excluded.agent_id, cwd = excluded.cwd`).run(botId, binding.userOpenId, threadId, binding.agentId, binding.cwd);
172
+ }
173
+ setCurrentAgent(botId, userOpenId, threadId, agentId) {
174
+ const existing = this.getThreadBinding(botId, userOpenId, threadId);
175
+ this.upsertThreadBinding(botId, { userOpenId, threadId: existing?.threadId ?? threadId, agentId, cwd: existing?.cwd ?? null });
176
+ }
177
+ setCurrentCwd(botId, userOpenId, threadId, cwd) {
178
+ const existing = this.getThreadBinding(botId, userOpenId, threadId);
179
+ this.upsertThreadBinding(botId, { userOpenId, threadId: existing?.threadId ?? threadId, agentId: existing?.agentId ?? 'claude-code', cwd });
180
+ }
181
+ getContinuation(botId, userOpenId, threadId, agentId) {
182
+ const row = this.findContinuationRow(botId, userOpenId, threadId, agentId);
183
+ return row?.continuation_token ?? null;
184
+ }
185
+ upsertContinuation(botId, userOpenId, threadId, agentId, token) {
186
+ const existing = this.findContinuationRow(botId, userOpenId, threadId, agentId);
187
+ const storageThreadId = existing?.thread_id ?? threadId;
188
+ this.db.prepare(`INSERT INTO agent_continuation (bot_id, user_open_id, thread_id, agent_id, continuation_token)
189
+ VALUES (?, ?, ?, ?, ?)
190
+ ON CONFLICT(bot_id, user_open_id, thread_id, agent_id)
191
+ DO UPDATE SET continuation_token = excluded.continuation_token`).run(botId, userOpenId, storageThreadId, agentId, token);
192
+ }
193
+ clearContinuation(botId, userOpenId, threadId, agentId) {
194
+ const existing = this.findContinuationRow(botId, userOpenId, threadId, agentId);
195
+ if (!existing)
196
+ return false;
197
+ const result = this.db.prepare('DELETE FROM agent_continuation WHERE bot_id = ? AND user_open_id = ? AND thread_id = ? AND agent_id = ?').run(botId, userOpenId, existing.thread_id, agentId);
198
+ return result.changes > 0;
199
+ }
200
+ upsertInflightCard(botId, card) {
201
+ if (this.readOnly)
202
+ return;
203
+ const existing = this.findInflightCardRow(botId, card.userOpenId, card.threadId, card.agentId);
204
+ const storageThreadId = existing?.['thread_id'] ?? card.threadId;
205
+ this.db.prepare(`INSERT INTO inflight_card (bot_id, user_open_id, thread_id, agent_id, source_message_id, reply_message_id, run_id)
206
+ VALUES (?, ?, ?, ?, ?, ?, ?)
207
+ ON CONFLICT(bot_id, user_open_id, thread_id, agent_id)
208
+ DO UPDATE SET source_message_id = excluded.source_message_id, reply_message_id = excluded.reply_message_id, run_id = excluded.run_id`).run(botId, card.userOpenId, storageThreadId, card.agentId, card.sourceMessageId, card.replyMessageId, card.runId ?? null);
209
+ }
210
+ getInflightCard(botId, userOpenId, threadId, agentId) {
211
+ const row = this.findInflightCardRow(botId, userOpenId, threadId, agentId);
212
+ return row ? this.toInflightCard(row) : null;
213
+ }
214
+ listInflightCards(botId) {
215
+ const rows = this.db.prepare('SELECT * FROM inflight_card WHERE bot_id = ? ORDER BY user_open_id ASC, thread_id ASC, agent_id ASC').all(botId);
216
+ return rows.map((row) => this.toInflightCard(row));
217
+ }
218
+ clearInflightCard(botId, userOpenId, threadId, agentId) {
219
+ const existing = this.findInflightCardRow(botId, userOpenId, threadId, agentId);
220
+ if (!existing)
221
+ return false;
222
+ const result = this.db.prepare('DELETE FROM inflight_card WHERE bot_id = ? AND user_open_id = ? AND thread_id = ? AND agent_id = ?').run(botId, userOpenId, existing['thread_id'], agentId);
223
+ return result.changes > 0;
224
+ }
225
+ setAlias(userOpenId, name, path) {
226
+ this.db.prepare(`INSERT INTO cwd_alias (user_open_id, name, path)
227
+ VALUES (?, ?, ?)
228
+ ON CONFLICT(user_open_id, name)
229
+ DO UPDATE SET path = excluded.path`).run(userOpenId, name, path);
230
+ }
231
+ listAliases(userOpenId) {
232
+ const rows = this.db.prepare('SELECT name, path FROM cwd_alias WHERE user_open_id = ? ORDER BY name ASC').all(userOpenId);
233
+ return rows.map((row) => ({ name: row.name, path: row.path }));
234
+ }
235
+ removeAlias(userOpenId, name) {
236
+ const result = this.db.prepare('DELETE FROM cwd_alias WHERE user_open_id = ? AND name = ?').run(userOpenId, name);
237
+ return result.changes > 0;
238
+ }
239
+ getCardEntity(botId, messageId) {
240
+ const row = this.db.prepare('SELECT card_id, sequence, streaming FROM card_entity WHERE bot_id = ? AND message_id = ?').get(botId, messageId);
241
+ return row ? { cardId: row.card_id, sequence: row.sequence, streaming: row.streaming === 1 } : null;
242
+ }
243
+ saveCardEntity(botId, messageId, entity) {
244
+ if (this.readOnly)
245
+ return;
246
+ this.db.prepare(`INSERT INTO card_entity (bot_id, message_id, card_id, sequence, streaming, updated_at)
247
+ VALUES (?, ?, ?, ?, ?, ?)
248
+ ON CONFLICT(bot_id, message_id)
249
+ DO UPDATE SET card_id = excluded.card_id, sequence = excluded.sequence, streaming = excluded.streaming, updated_at = excluded.updated_at`).run(botId, messageId, entity.cardId, entity.sequence, entity.streaming ? 1 : 0, Date.now());
250
+ }
251
+ /** 卡片实体只在运行期和重启恢复时有用; 清掉长时间没动过的. */
252
+ pruneCardEntities(olderThanMs) {
253
+ if (this.readOnly)
254
+ return 0;
255
+ return this.db.prepare('DELETE FROM card_entity WHERE updated_at < ?').run(Date.now() - olderThanMs).changes;
256
+ }
257
+ /** 群里是否必须 @bot 才响应; 没设置过默认 true. */
258
+ getRequireMention(botId, chatId) {
259
+ const row = this.db.prepare('SELECT require_mention FROM group_setting WHERE bot_id = ? AND chat_id = ?').get(botId, chatId);
260
+ return row ? row.require_mention === 1 : true;
261
+ }
262
+ setRequireMention(botId, chatId, requireMention, updatedBy) {
263
+ if (this.readOnly)
264
+ throw new Error('binding store is read-only (migration failed); cannot change group settings');
265
+ this.db.prepare(`INSERT INTO group_setting (bot_id, chat_id, require_mention, updated_by, updated_at)
266
+ VALUES (?, ?, ?, ?, ?)
267
+ ON CONFLICT(bot_id, chat_id)
268
+ DO UPDATE SET require_mention = excluded.require_mention, updated_by = excluded.updated_by, updated_at = excluded.updated_at`).run(botId, chatId, requireMention ? 1 : 0, updatedBy, Date.now());
269
+ }
270
+ }
@@ -0,0 +1,127 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const MAX_ENTRIES = 700;
4
+ const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;
5
+ class SimpleLRU {
6
+ max;
7
+ map = new Map();
8
+ constructor(max) {
9
+ this.max = max;
10
+ }
11
+ get size() { return this.map.size; }
12
+ get(key) {
13
+ const value = this.map.get(key);
14
+ if (value !== undefined) {
15
+ this.map.delete(key);
16
+ this.map.set(key, value);
17
+ }
18
+ return value;
19
+ }
20
+ set(key, value) {
21
+ if (this.map.has(key))
22
+ this.map.delete(key);
23
+ this.map.set(key, value);
24
+ if (this.map.size > this.max) {
25
+ const oldest = this.map.keys().next().value;
26
+ if (oldest !== undefined)
27
+ this.map.delete(oldest);
28
+ }
29
+ }
30
+ entries() { return this.map.entries(); }
31
+ }
32
+ /**
33
+ * TaskIndex: in-memory LRU (max 700 entries) of recent runs.
34
+ *
35
+ * Scope (W2): single wb-bot process, default botId; 7-day window.
36
+ * Out-of-scope: no search / tag / retry / scheduled / cross-bot aggregation (W2.5+).
37
+ * Source of truth: runs/<botId>/<runId>/{spec.json, status} filesystem;
38
+ * SQLite binding only holds inflight_card table, not TaskIndex state.
39
+ */
40
+ export class TaskIndex {
41
+ dataDir;
42
+ botId;
43
+ cache;
44
+ scanning = false;
45
+ constructor(dataDir, botId = 'default') {
46
+ this.dataDir = dataDir;
47
+ this.botId = botId;
48
+ this.cache = new SimpleLRU(MAX_ENTRIES);
49
+ }
50
+ get size() {
51
+ return this.cache.size;
52
+ }
53
+ get(runId) {
54
+ return this.cache.get(runId);
55
+ }
56
+ list(limit) {
57
+ const entries = [];
58
+ for (const [, entry] of this.cache.entries()) {
59
+ entries.push(entry);
60
+ }
61
+ entries.sort((a, b) => b.lastModified - a.lastModified);
62
+ return limit ? entries.slice(0, limit) : entries;
63
+ }
64
+ scheduleScan() {
65
+ if (this.scanning)
66
+ return;
67
+ this.scanning = true;
68
+ setImmediate(() => {
69
+ try {
70
+ this.scan();
71
+ }
72
+ finally {
73
+ this.scanning = false;
74
+ }
75
+ });
76
+ }
77
+ scan() {
78
+ const runsDir = join(this.dataDir, 'runs', this.botId);
79
+ if (!existsSync(runsDir))
80
+ return;
81
+ const cutoff = Date.now() - SEVEN_DAYS_MS;
82
+ let dirs;
83
+ try {
84
+ dirs = readdirSync(runsDir);
85
+ }
86
+ catch {
87
+ return;
88
+ }
89
+ for (const runId of dirs) {
90
+ const runDir = join(runsDir, runId);
91
+ const specPath = join(runDir, 'spec.json');
92
+ const statusPath = join(runDir, 'status');
93
+ if (!existsSync(specPath))
94
+ continue;
95
+ let lastModified;
96
+ try {
97
+ const stat = statSync(runDir);
98
+ lastModified = stat.mtimeMs;
99
+ }
100
+ catch {
101
+ continue;
102
+ }
103
+ if (lastModified < cutoff)
104
+ continue;
105
+ try {
106
+ const specRaw = readFileSync(specPath, 'utf8');
107
+ const spec = JSON.parse(specRaw);
108
+ const status = existsSync(statusPath)
109
+ ? readFileSync(statusPath, 'utf8').trim()
110
+ : 'running';
111
+ this.cache.set(runId, {
112
+ runId,
113
+ agentId: spec['agentId'] ?? 'unknown',
114
+ status,
115
+ cwd: spec['cwd'] ?? '',
116
+ startedAt: spec['startedAt'] ?? '',
117
+ lastModified,
118
+ userOpenId: spec['userOpenId'] ?? '',
119
+ threadId: spec['threadId'] ?? '',
120
+ });
121
+ }
122
+ catch {
123
+ continue;
124
+ }
125
+ }
126
+ }
127
+ }
@@ -0,0 +1,9 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ /**
3
+ * 同一棵目录树里的兄弟入口. 源码运行 (tsx) 时调用方是 .ts, 编译运行 (仓库 dist/ 或 npm 安装) 时是 .js;
4
+ * 子进程入口要跟调用方用同一种扩展名, 否则装好的包里会去找不存在的 .ts.
5
+ */
6
+ export function siblingEntry(importMetaUrl, relativePathWithoutExt) {
7
+ const ext = importMetaUrl.endsWith('.ts') ? '.ts' : '.js';
8
+ return fileURLToPath(new URL(`${relativePathWithoutExt}${ext}`, importMetaUrl));
9
+ }
@@ -0,0 +1,47 @@
1
+ import { chmodSync, existsSync, mkdirSync, statSync, accessSync, constants } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const REQUIRED_MODE = 0o700;
4
+ const REQUIRED_SUBDIRS = ['data', 'runs', 'logs'];
5
+ function ensureDir(dir, logger) {
6
+ if (!existsSync(dir)) {
7
+ mkdirSync(dir, { recursive: true, mode: REQUIRED_MODE });
8
+ logger.info({ dir }, 'created directory with mode 0700');
9
+ return;
10
+ }
11
+ const stat = statSync(dir);
12
+ const currentMode = stat.mode & 0o777;
13
+ if (currentMode !== REQUIRED_MODE) {
14
+ logger.warn({ dir, currentMode: `0${currentMode.toString(8)}`, requiredMode: '0700' }, 'directory mode incorrect, fixing');
15
+ chmodSync(dir, REQUIRED_MODE);
16
+ }
17
+ }
18
+ function isWritable(dir) {
19
+ try {
20
+ accessSync(dir, constants.W_OK);
21
+ return true;
22
+ }
23
+ catch {
24
+ return false;
25
+ }
26
+ }
27
+ export function ensureDataDirIntegrity(dataDir, logger) {
28
+ ensureDir(dataDir, logger);
29
+ for (const sub of REQUIRED_SUBDIRS) {
30
+ const subDir = join(dataDir, sub);
31
+ ensureDir(subDir, logger);
32
+ }
33
+ const unwritable = [];
34
+ for (const sub of REQUIRED_SUBDIRS) {
35
+ const subDir = join(dataDir, sub);
36
+ if (!isWritable(subDir)) {
37
+ unwritable.push(subDir);
38
+ }
39
+ }
40
+ if (!isWritable(dataDir)) {
41
+ unwritable.push(dataDir);
42
+ }
43
+ if (unwritable.length > 0) {
44
+ logger.warn({ unwritable }, 'some directories are not writable after chmod attempt; wb-bot may not function correctly');
45
+ }
46
+ return { unwritable };
47
+ }
@@ -0,0 +1,44 @@
1
+ import pino from 'pino';
2
+ import pinoPretty from 'pino-pretty';
3
+ import pinoRoll from 'pino-roll';
4
+ import { mkdirSync } from 'node:fs';
5
+ import { dirname } from 'node:path';
6
+ import { botLogPath } from '../../../../packages/core/src/paths.js';
7
+ /**
8
+ * Two-stream pino logger (HP-W2-2 + Block E E0):
9
+ *
10
+ * stdout (raw JSON) → launchd captures, /var/log diagnostics path
11
+ * file → pino-pretty (colorize=false) → pino-roll
12
+ * path: <dataDir>/logs/<botId>/wb-bot.log
13
+ * rotation: daily, keep 7 (limit.count=7)
14
+ *
15
+ * Both streams receive every record at the same level. Stdout vs file are
16
+ * not mutually exclusive (A.M-5): launchd / stdout redirection still works,
17
+ * and /logs can read the pretty-formatted file (C.M-4).
18
+ *
19
+ * The function is async because pino-roll initialization needs to detect
20
+ * the current rotation file. main.ts awaits this before booting transport.
21
+ */
22
+ export async function createLogger(opts) {
23
+ const logFilePath = botLogPath(opts.dataDir, opts.botId);
24
+ mkdirSync(dirname(logFilePath), { recursive: true, mode: 0o700 });
25
+ const rollStream = await pinoRoll({
26
+ file: logFilePath,
27
+ frequency: 'daily',
28
+ mkdir: true,
29
+ limit: { count: 7 },
30
+ });
31
+ const prettyStream = pinoPretty({
32
+ colorize: false,
33
+ destination: rollStream,
34
+ sync: true,
35
+ translateTime: 'yyyy-mm-dd HH:MM:ss.l',
36
+ ignore: 'pid,hostname',
37
+ });
38
+ const stdoutStream = pino.destination(1);
39
+ const logger = pino({ level: opts.level }, pino.multistream([
40
+ { stream: stdoutStream, level: opts.level },
41
+ { stream: prettyStream, level: opts.level },
42
+ ]));
43
+ return { logger, logFilePath };
44
+ }
@@ -0,0 +1,42 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { botHeartbeatPath } from '../../../../packages/core/src/paths.js';
3
+ import { loadBotEnvFromFile } from '../config/bot-env.js';
4
+ import { discoverBots } from '../multi/discovery.js';
5
+ export function discoverBotsWithStatus(opts) {
6
+ const discovered = discoverBots(opts.configDir, opts.logger);
7
+ const staleMs = opts.staleMs ?? 30_000;
8
+ const now = (opts.nowFn ?? Date.now)();
9
+ const bots = discovered.bots.map((bot) => probeBotStatus(bot, opts.dataDir, now, staleMs, opts.logger));
10
+ return { bots, warnings: discovered.warnings };
11
+ }
12
+ function probeBotStatus(bot, dataDir, now, staleMs, logger) {
13
+ const heartbeatPath = botHeartbeatPath(dataDir, bot.botId);
14
+ let lastHeartbeatAt = null;
15
+ let online = false;
16
+ if (existsSync(heartbeatPath)) {
17
+ try {
18
+ const tsSec = parseInt(readFileSync(heartbeatPath, 'utf8').trim(), 10);
19
+ if (!Number.isNaN(tsSec)) {
20
+ lastHeartbeatAt = tsSec * 1000;
21
+ online = (now - lastHeartbeatAt) < staleMs;
22
+ }
23
+ }
24
+ catch (error) {
25
+ logger?.warn?.({ botId: bot.botId, heartbeatPath, error }, 'failed to read bot heartbeat');
26
+ }
27
+ }
28
+ let agentAllowed;
29
+ try {
30
+ agentAllowed = loadBotEnvFromFile(bot.configPath).agentAllowed;
31
+ }
32
+ catch (error) {
33
+ logger?.warn?.({ botId: bot.botId, configPath: bot.configPath, error }, 'failed to load bot env during captain discovery');
34
+ }
35
+ return {
36
+ botId: bot.botId,
37
+ configPath: bot.configPath,
38
+ online,
39
+ lastHeartbeatAt,
40
+ agentAllowed,
41
+ };
42
+ }
@@ -0,0 +1,26 @@
1
+ import { resolveConfigDir } from '../config/config-paths.js';
2
+ import { resolveDataDir } from '../../../../packages/core/src/paths.js';
3
+ import { isCaptainEnabled } from './captain-gate.js';
4
+ import { discoverBotsWithStatus } from './bot-discovery.js';
5
+ /**
6
+ * 统一 Captain 上下文解析: 把 router.ts 里 4+ 处重复展开 (gate +
7
+ * resolveConfigDir + dataDir + discoverBotsWithStatus) 合到一处.
8
+ * 副作用: 仅 file IO (bot discovery), 不写状态, 不持久化.
9
+ * 不变量: enabled=false 时不会调 discover (省 file IO).
10
+ *
11
+ * Pure refactor (W2.5-Hotfix-batch-C P1-6): 不改变 Captain 启用判定 / discovery
12
+ * 行为, 只把 4 个 router.ts 命令分支的重复逻辑提到一处.
13
+ */
14
+ export function resolveCaptainContext(input) {
15
+ const enabled = isCaptainEnabled({
16
+ mode: process.env['WB_MODE'] === 'multi-bot' ? 'multi-bot' : 'single',
17
+ botId: input.botId,
18
+ disableCaptainEnv: process.env['WB_DISABLE_CAPTAIN'],
19
+ });
20
+ if (!enabled)
21
+ return { enabled: false };
22
+ const configDir = resolveConfigDir();
23
+ const dataDir = resolveDataDir();
24
+ const { bots } = discoverBotsWithStatus({ configDir, dataDir });
25
+ return { enabled: true, configDir, dataDir, bots };
26
+ }
@@ -0,0 +1,9 @@
1
+ export function isCaptainEnabled(inputs) {
2
+ if (inputs.mode !== 'multi-bot')
3
+ return false;
4
+ if (inputs.botId !== 'default')
5
+ return false;
6
+ if (inputs.disableCaptainEnv === 'true' || inputs.disableCaptainEnv === '1')
7
+ return false;
8
+ return true;
9
+ }
@@ -0,0 +1,101 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ export function renderCaptainStatusCard(opts) {
4
+ const now = (opts.nowFn ?? Date.now)();
5
+ const tsLine = new Date(now).toISOString().replace('T', ' ').slice(0, 19);
6
+ const sorted = sortBots(opts.bots, opts.captainBotId);
7
+ const lines = ['```', `📊 Weaverbird Status (${tsLine})`, '─────────────────────────────────────'];
8
+ if (sorted.length === 0) {
9
+ lines.push('(无 worker)');
10
+ }
11
+ else {
12
+ for (const bot of sorted) {
13
+ lines.push(renderBotLine(bot, opts.store, opts.dataDir, opts.captainBotId, now));
14
+ }
15
+ }
16
+ lines.push('─────────────────────────────────────');
17
+ lines.push('per-bot 摘要视图 · 单 bot 多 run 时显示最早 run + 数量');
18
+ lines.push('完整 run 列表视图待 W3 (snapshot protocol)');
19
+ lines.push('```');
20
+ return lines.join('\n');
21
+ }
22
+ function sortBots(bots, captainBotId) {
23
+ return [...bots].sort((left, right) => {
24
+ if (left.botId === captainBotId)
25
+ return -1;
26
+ if (right.botId === captainBotId)
27
+ return 1;
28
+ return left.botId.localeCompare(right.botId);
29
+ });
30
+ }
31
+ function renderBotLine(bot, store, dataDir, captainBotId, now) {
32
+ const name = bot.botId === captainBotId ? `${bot.botId} (Captain)` : bot.botId;
33
+ const inflightCards = safeListInflightCards(store, bot.botId);
34
+ const stats = collectActiveRunStats(inflightCards, dataDir, bot.botId, now);
35
+ if (!bot.online && bot.lastHeartbeatAt !== null) {
36
+ const ageDisplay = formatAge(now - bot.lastHeartbeatAt);
37
+ return `🤖 ${name.padEnd(20)} : ⚠️ 离线 (最后心跳 ${ageDisplay} 前)`;
38
+ }
39
+ if (!bot.online) {
40
+ return `🤖 ${name.padEnd(20)} : ⚠️ 离线 (无 heartbeat)`;
41
+ }
42
+ if (stats) {
43
+ const age = formatAge(now - stats.earliest.startedAt);
44
+ if (stats.count === 1) {
45
+ return `🤖 ${name.padEnd(20)} : 跑中 1 · ${age} · run ${stats.earliest.runIdShort}`;
46
+ }
47
+ return `🤖 ${name.padEnd(20)} : 跑中 ${stats.count} · 最早 ${age} · run ${stats.earliest.runIdShort} (+${stats.count - 1} 更多)`;
48
+ }
49
+ const hbAge = bot.lastHeartbeatAt !== null ? formatAge(now - bot.lastHeartbeatAt) : '?';
50
+ return `🤖 ${name.padEnd(20)} : 空闲 · 最后心跳 ${hbAge} 前`;
51
+ }
52
+ function collectActiveRunStats(cards, dataDir, botId, now) {
53
+ let earliest = null;
54
+ let count = 0;
55
+ for (const card of cards) {
56
+ if (!card.runId)
57
+ continue;
58
+ const runDir = join(dataDir, 'runs', botId, card.runId);
59
+ const statusValue = safeReadFile(join(runDir, 'status'));
60
+ if (statusValue && statusValue !== 'running')
61
+ continue;
62
+ count += 1;
63
+ const hbTs = safeReadHeartbeat(join(runDir, 'heartbeat'));
64
+ const startedAt = hbTs ?? now;
65
+ if (!earliest || startedAt < earliest.startedAt) {
66
+ earliest = { runId: card.runId, runIdShort: card.runId.slice(0, 12), startedAt };
67
+ }
68
+ }
69
+ return earliest ? { earliest, count } : null;
70
+ }
71
+ function safeListInflightCards(store, botId) {
72
+ try {
73
+ return store.listInflightCards(botId);
74
+ }
75
+ catch {
76
+ return [];
77
+ }
78
+ }
79
+ function safeReadFile(path) {
80
+ try {
81
+ return existsSync(path) ? readFileSync(path, 'utf8').trim() : null;
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
87
+ function safeReadHeartbeat(path) {
88
+ const raw = safeReadFile(path);
89
+ if (!raw)
90
+ return null;
91
+ const tsSec = parseInt(raw, 10);
92
+ return Number.isNaN(tsSec) ? null : tsSec * 1000;
93
+ }
94
+ function formatAge(ms) {
95
+ const sec = Math.max(0, Math.floor(ms / 1000));
96
+ if (sec < 60)
97
+ return `${sec}s`;
98
+ if (sec < 3600)
99
+ return `${Math.floor(sec / 60)}min`;
100
+ return `${Math.floor(sec / 3600)}h`;
101
+ }