@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,390 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { closeSync, existsSync, openSync, readFileSync, readdirSync, readSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { auditMirrorPath, runCalendarHookStatePath, runDir as resolveRunDir, runsRootDir } from '../paths.js';
5
+ import { RUN_STATUS } from './contracts.js';
6
+ import { extractShas, extractUrls } from './extractor.js';
7
+ import { ensureRunDoc } from './doc-sink.js';
8
+ import { loadRunRegistryConfig } from './config.js';
9
+ import { CalendarHookStateSchema } from '../calendar-hook/contracts.js';
10
+ function isRecord(value) {
11
+ return typeof value === 'object' && value !== null;
12
+ }
13
+ function parseMirrorLine(line) {
14
+ if (!line.trim())
15
+ return null;
16
+ let parsed;
17
+ try {
18
+ parsed = JSON.parse(line);
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ if (!isRecord(parsed))
24
+ return null;
25
+ if (parsed['status'] === 'rejected')
26
+ return parsed;
27
+ if (typeof parsed['run_id'] === 'string'
28
+ && typeof parsed['session_id'] === 'string'
29
+ && typeof parsed['revision'] === 'number'
30
+ && typeof parsed['ts'] === 'string') {
31
+ return parsed;
32
+ }
33
+ return null;
34
+ }
35
+ function parseTs(ts, fallback) {
36
+ const parsed = Date.parse(ts);
37
+ return Number.isFinite(parsed) ? parsed : fallback;
38
+ }
39
+ function isTerminalStatus(value) {
40
+ return value === 'done' || value === 'error' || value === 'cancelled' || value === 'failed' || value === 'stopped';
41
+ }
42
+ function mapTerminalStatus(value) {
43
+ if (value === 'done')
44
+ return RUN_STATUS.SUCCEEDED;
45
+ if (value === 'cancelled' || value === 'stopped')
46
+ return RUN_STATUS.CANCELLED;
47
+ return RUN_STATUS.FAILED;
48
+ }
49
+ export class RunTailer {
50
+ dataDir;
51
+ mirrorPath;
52
+ batchFlushIntervalMs;
53
+ pollIntervalMs;
54
+ finalizeIntervalMs;
55
+ runFinalizeGraceMs;
56
+ nowFn;
57
+ config;
58
+ docSinkTransport;
59
+ env;
60
+ onRunUpserted;
61
+ entries = new Map();
62
+ runDirByRunId = new Map();
63
+ finalizingRuns = new Set();
64
+ finalizerPromises = new Map();
65
+ offset = 0;
66
+ remainder = '';
67
+ pollTimer = null;
68
+ flushTimer = null;
69
+ finalizeTimer = null;
70
+ constructor(options) {
71
+ this.dataDir = options.dataDir;
72
+ this.mirrorPath = options.mirrorPath ?? auditMirrorPath(options.dataDir);
73
+ this.batchFlushIntervalMs = options.batchFlushIntervalMs ?? 5_000;
74
+ this.pollIntervalMs = options.pollIntervalMs ?? 200;
75
+ this.finalizeIntervalMs = options.finalizeIntervalMs ?? Math.min(options.runFinalizeGraceMs ?? 30_000, 200);
76
+ this.runFinalizeGraceMs = options.runFinalizeGraceMs ?? 30_000;
77
+ this.nowFn = options.nowFn ?? Date.now;
78
+ this.config = options.config ?? this.loadConfigOrNull(options.env);
79
+ this.docSinkTransport = options.docSinkTransport;
80
+ this.env = options.env;
81
+ this.onRunUpserted = options.onRunUpserted;
82
+ }
83
+ get size() {
84
+ return this.entries.size;
85
+ }
86
+ getEntry(runId) {
87
+ const entry = this.entries.get(runId);
88
+ if (!entry)
89
+ return undefined;
90
+ return {
91
+ run_id: entry.run_id,
92
+ state: entry.state,
93
+ first_event_ts: entry.first_event_ts,
94
+ last_event_ts: entry.last_event_ts,
95
+ event_count: entry.event_count,
96
+ produced_doc_urls: [...entry.produced_doc_urls],
97
+ commit_shas: [...entry.commit_shas],
98
+ doc_sink_failed: entry.doc_sink_failed,
99
+ calendar_block_id: entry.calendar_block_id,
100
+ calendar_hook_failed: entry.calendar_hook_failed,
101
+ spec: entry.spec,
102
+ };
103
+ }
104
+ start() {
105
+ if (this.pollTimer)
106
+ return;
107
+ this.pollTimer = setInterval(() => this.pollMirror(), this.pollIntervalMs);
108
+ this.flushTimer = setInterval(() => this.flushDirtyEntries(), this.batchFlushIntervalMs);
109
+ this.finalizeTimer = setInterval(() => this.finalizeEligibleEntries(), this.finalizeIntervalMs);
110
+ this.pollMirror();
111
+ }
112
+ stop() {
113
+ if (this.pollTimer)
114
+ clearInterval(this.pollTimer);
115
+ if (this.flushTimer)
116
+ clearInterval(this.flushTimer);
117
+ if (this.finalizeTimer)
118
+ clearInterval(this.finalizeTimer);
119
+ this.pollTimer = null;
120
+ this.flushTimer = null;
121
+ this.finalizeTimer = null;
122
+ }
123
+ async waitForIdle() {
124
+ await Promise.all([...this.finalizerPromises.values()]);
125
+ }
126
+ pollMirror() {
127
+ if (!existsSync(this.mirrorPath))
128
+ return;
129
+ const { size } = statSync(this.mirrorPath);
130
+ if (size < this.offset) {
131
+ this.offset = 0;
132
+ this.remainder = '';
133
+ }
134
+ if (size === this.offset)
135
+ return;
136
+ const chunk = Buffer.alloc(size - this.offset);
137
+ const fd = openSync(this.mirrorPath, 'r');
138
+ try {
139
+ readSync(fd, chunk, 0, chunk.length, this.offset);
140
+ }
141
+ finally {
142
+ closeSync(fd);
143
+ }
144
+ this.offset = size;
145
+ const text = this.remainder + chunk.toString('utf8');
146
+ const lines = text.split('\n');
147
+ this.remainder = lines.pop() ?? '';
148
+ for (const line of lines)
149
+ this.processLine(line);
150
+ }
151
+ processLine(line) {
152
+ const parsed = parseMirrorLine(line);
153
+ if (!parsed || 'status' in parsed)
154
+ return;
155
+ const recordTs = parseTs(parsed.ts, this.nowFn());
156
+ const runId = parsed.run_id || parsed.session_id || randomUUID();
157
+ const entry = this.entries.get(runId) ?? this.createEntry(runId, parsed.session_id, recordTs);
158
+ entry.last_event_ts = Math.max(entry.last_event_ts, recordTs);
159
+ entry.event_count += 1;
160
+ entry.session_id = parsed.session_id;
161
+ entry.dirty = true;
162
+ if (!entry.run_dir)
163
+ entry.run_dir = this.findRunDir(runId, { allowRetry: true });
164
+ if (!entry.spec)
165
+ entry.spec = this.readRunSpec(runId);
166
+ this.entries.set(runId, entry);
167
+ }
168
+ loadConfigOrNull(env) {
169
+ try {
170
+ return loadRunRegistryConfig({ env });
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ }
176
+ createEntry(runId, sessionId, recordTs) {
177
+ return {
178
+ run_id: runId,
179
+ state: 'ACTIVE',
180
+ first_event_ts: recordTs,
181
+ last_event_ts: recordTs,
182
+ event_count: 0,
183
+ produced_doc_urls: [],
184
+ commit_shas: [],
185
+ doc_sink_failed: false,
186
+ calendar_block_id: null,
187
+ calendar_hook_failed: false,
188
+ spec: this.readRunSpec(runId),
189
+ session_id: sessionId,
190
+ next_revision: 0,
191
+ pending_initial: true,
192
+ dirty: false,
193
+ run_dir: this.findRunDir(runId, { allowRetry: true }),
194
+ };
195
+ }
196
+ flushDirtyEntries() {
197
+ for (const entry of this.entries.values()) {
198
+ if (entry.state !== 'ACTIVE')
199
+ continue;
200
+ if (entry.pending_initial) {
201
+ this.emitUpsert(entry, RUN_STATUS.PENDING);
202
+ entry.pending_initial = false;
203
+ entry.dirty = false;
204
+ continue;
205
+ }
206
+ if (!entry.dirty)
207
+ continue;
208
+ this.emitUpsert(entry, RUN_STATUS.ACTIVE);
209
+ entry.dirty = false;
210
+ }
211
+ }
212
+ finalizeEligibleEntries() {
213
+ const now = this.nowFn();
214
+ for (const entry of this.entries.values()) {
215
+ if (entry.state !== 'ACTIVE')
216
+ continue;
217
+ const signalA = this.readTerminalStatus(entry);
218
+ if (signalA) {
219
+ this.finalizeEntry(entry, signalA);
220
+ continue;
221
+ }
222
+ if (now - entry.last_event_ts > this.runFinalizeGraceMs) {
223
+ this.finalizeEntry(entry, RUN_STATUS.SUCCEEDED);
224
+ }
225
+ }
226
+ }
227
+ finalizeEntry(entry, status) {
228
+ if (this.finalizingRuns.has(entry.run_id))
229
+ return;
230
+ this.finalizingRuns.add(entry.run_id);
231
+ entry.state = 'FINALIZING';
232
+ if (entry.pending_initial) {
233
+ this.emitUpsert(entry, RUN_STATUS.PENDING);
234
+ entry.pending_initial = false;
235
+ }
236
+ if (!entry.spec)
237
+ entry.spec = this.readRunSpec(entry.run_id);
238
+ this.refreshArtifacts(entry);
239
+ this.emitUpsert(entry, status);
240
+ entry.dirty = false;
241
+ entry.state = 'DONE';
242
+ const finalizer = this.runDocSink(entry, status).finally(() => {
243
+ this.finalizingRuns.delete(entry.run_id);
244
+ this.finalizerPromises.delete(entry.run_id);
245
+ });
246
+ this.finalizerPromises.set(entry.run_id, finalizer);
247
+ void finalizer;
248
+ }
249
+ refreshArtifacts(entry) {
250
+ const records = this.readRunRecords(entry.run_id);
251
+ entry.commit_shas = extractShas(records);
252
+ if (this.config) {
253
+ entry.produced_doc_urls = extractUrls(records, this.config.doc_url_allowlist);
254
+ }
255
+ const calendarState = this.readCalendarHookState(entry.run_id, entry.spec?.botId);
256
+ entry.calendar_block_id = calendarState?.calendar_block_id ?? null;
257
+ entry.calendar_hook_failed = calendarState?.calendar_hook_failed ?? false;
258
+ }
259
+ readCalendarHookState(runId, botId = 'default') {
260
+ const path = runCalendarHookStatePath(this.dataDir, runId, botId);
261
+ if (!existsSync(path))
262
+ return null;
263
+ try {
264
+ return CalendarHookStateSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
265
+ }
266
+ catch {
267
+ return null;
268
+ }
269
+ }
270
+ async runDocSink(entry, status) {
271
+ if (!this.config)
272
+ return;
273
+ const docResult = await ensureRunDoc({
274
+ dataDir: this.dataDir,
275
+ runId: entry.run_id,
276
+ botId: entry.spec?.botId,
277
+ status,
278
+ existingDocUrls: entry.produced_doc_urls,
279
+ config: this.config,
280
+ transport: this.docSinkTransport,
281
+ env: this.env,
282
+ });
283
+ if (docResult.reason === 'created' || docResult.reason === 'already_succeeded' || docResult.reason === 'existing_registry_url' || docResult.reason === 'failed') {
284
+ entry.produced_doc_urls = docResult.produced_doc_urls;
285
+ entry.doc_sink_failed = docResult.doc_sink_failed;
286
+ this.emitUpsert(entry, status);
287
+ }
288
+ }
289
+ emitUpsert(entry, status) {
290
+ const event = {
291
+ event: 'RunUpserted',
292
+ run_id: entry.run_id,
293
+ session_id: entry.session_id,
294
+ revision: entry.next_revision,
295
+ status,
296
+ cost_tokens: null,
297
+ cost_minutes: this.computeCostMinutes(entry),
298
+ produced_doc_urls: [...entry.produced_doc_urls],
299
+ commit_shas: [...entry.commit_shas],
300
+ doc_sink_failed: entry.doc_sink_failed,
301
+ calendar_block_id: entry.calendar_block_id,
302
+ calendar_hook_failed: entry.calendar_hook_failed,
303
+ updated_at: new Date(this.nowFn()).toISOString(),
304
+ };
305
+ entry.next_revision += 1;
306
+ if (this.onRunUpserted)
307
+ void Promise.resolve(this.onRunUpserted(event, this.getEntry(entry.run_id)));
308
+ }
309
+ readRunRecords(runId) {
310
+ if (!existsSync(this.mirrorPath))
311
+ return [];
312
+ try {
313
+ return readFileSync(this.mirrorPath, 'utf8')
314
+ .split('\n')
315
+ .map((line) => parseMirrorLine(line))
316
+ .filter((record) => record !== null && !('status' in record) && record.run_id === runId);
317
+ }
318
+ catch {
319
+ return [];
320
+ }
321
+ }
322
+ computeCostMinutes(entry) {
323
+ const startedAt = entry.spec?.startedAt ? Date.parse(entry.spec.startedAt) : entry.first_event_ts;
324
+ if (!Number.isFinite(startedAt))
325
+ return null;
326
+ return Math.max(0, Math.floor((entry.last_event_ts - startedAt) / 60_000));
327
+ }
328
+ readTerminalStatus(entry) {
329
+ const runDir = entry.run_dir ?? this.findRunDir(entry.run_id, { allowRetry: true });
330
+ if (!runDir)
331
+ return null;
332
+ entry.run_dir = runDir;
333
+ const statusPath = join(runDir, 'status');
334
+ if (!existsSync(statusPath))
335
+ return null;
336
+ try {
337
+ const status = readFileSync(statusPath, 'utf8').trim();
338
+ return isTerminalStatus(status) ? mapTerminalStatus(status) : null;
339
+ }
340
+ catch {
341
+ return null;
342
+ }
343
+ }
344
+ readRunSpec(runId) {
345
+ const runDir = this.findRunDir(runId, { allowRetry: true });
346
+ if (!runDir)
347
+ return null;
348
+ const specPath = join(runDir, 'spec.json');
349
+ if (!existsSync(specPath))
350
+ return null;
351
+ try {
352
+ return JSON.parse(readFileSync(specPath, 'utf8'));
353
+ }
354
+ catch {
355
+ return null;
356
+ }
357
+ }
358
+ findRunDir(runId, options = { allowRetry: false }) {
359
+ const cached = this.runDirByRunId.get(runId);
360
+ if (cached)
361
+ return cached;
362
+ if (cached === null && !options.allowRetry)
363
+ return null;
364
+ const runsRoot = runsRootDir(this.dataDir);
365
+ if (!existsSync(runsRoot)) {
366
+ if (!options.allowRetry)
367
+ this.runDirByRunId.set(runId, null);
368
+ return null;
369
+ }
370
+ try {
371
+ for (const botEntry of readdirSync(runsRoot, { withFileTypes: true })) {
372
+ if (!botEntry.isDirectory())
373
+ continue;
374
+ const candidate = resolveRunDir(this.dataDir, runId, botEntry.name);
375
+ if (existsSync(candidate)) {
376
+ this.runDirByRunId.set(runId, candidate);
377
+ return candidate;
378
+ }
379
+ }
380
+ }
381
+ catch {
382
+ if (!options.allowRetry)
383
+ this.runDirByRunId.set(runId, null);
384
+ return null;
385
+ }
386
+ if (!options.allowRetry)
387
+ this.runDirByRunId.set(runId, null);
388
+ return null;
389
+ }
390
+ }
@@ -0,0 +1,106 @@
1
+ import { mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { runRegistryWalDir } from '../paths.js';
4
+ function atomicWrite(path, content) {
5
+ const tmp = `${path}.tmp`;
6
+ writeFileSync(tmp, content);
7
+ renameSync(tmp, path);
8
+ }
9
+ function serializeSeq(seq) {
10
+ return `${seq}`.padStart(16, '0');
11
+ }
12
+ function parseEntry(path) {
13
+ try {
14
+ return JSON.parse(readFileSync(path, 'utf8'));
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ export function createRunRegistryWal({ dataDir, walPath }) {
21
+ const walDir = walPath ?? runRegistryWalDir(dataDir);
22
+ mkdirSync(walDir, { recursive: true });
23
+ let counter = 0;
24
+ let lastSeq = 0;
25
+ for (const file of readdirSync(walDir)) {
26
+ const match = file.match(/_(\d+)\.jsonl$/);
27
+ const seq = match ? Number.parseInt(match[1], 10) : Number.NaN;
28
+ if (Number.isFinite(seq))
29
+ lastSeq = Math.max(lastSeq, seq);
30
+ }
31
+ function filePathFor(entry) {
32
+ return join(walDir, `${entry.run_id}_${serializeSeq(entry.seq)}.jsonl`);
33
+ }
34
+ function findEntryPath(seq) {
35
+ const suffix = `_${serializeSeq(seq)}.jsonl`;
36
+ try {
37
+ const file = readdirSync(walDir).find((name) => name.endsWith(suffix));
38
+ return file ? join(walDir, file) : null;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ function writeEntry(entry) {
45
+ atomicWrite(filePathFor(entry), JSON.stringify(entry));
46
+ }
47
+ function nextSeq() {
48
+ counter += 1;
49
+ lastSeq = Math.max(lastSeq + 1, Date.now() * 1000 + counter);
50
+ return lastSeq;
51
+ }
52
+ return {
53
+ append(runId, record) {
54
+ const seq = nextSeq();
55
+ writeEntry({ seq, run_id: runId, record, attempts: 0, state: 'queued', enqueued_at: new Date().toISOString() });
56
+ return seq;
57
+ },
58
+ async *replay() {
59
+ let files = [];
60
+ try {
61
+ files = readdirSync(walDir).filter((file) => file.endsWith('.jsonl')).sort();
62
+ }
63
+ catch {
64
+ files = [];
65
+ }
66
+ for (const file of files) {
67
+ const entry = parseEntry(join(walDir, file));
68
+ if (entry)
69
+ yield entry;
70
+ }
71
+ },
72
+ ack(seq) {
73
+ const path = findEntryPath(seq);
74
+ if (path)
75
+ unlinkSync(path);
76
+ },
77
+ markPendingSync(seq) {
78
+ const path = findEntryPath(seq);
79
+ if (!path)
80
+ return;
81
+ const entry = parseEntry(path);
82
+ if (!entry)
83
+ return;
84
+ unlinkSync(path);
85
+ writeEntry({ ...entry, attempts: Math.max(entry.attempts, 5), state: 'pending-sync' });
86
+ },
87
+ bumpAttempts(seq) {
88
+ const path = findEntryPath(seq);
89
+ if (!path)
90
+ return;
91
+ const entry = parseEntry(path);
92
+ if (!entry)
93
+ return;
94
+ unlinkSync(path);
95
+ writeEntry({ ...entry, attempts: entry.attempts + 1 });
96
+ },
97
+ listFiles() {
98
+ try {
99
+ return readdirSync(walDir).filter((file) => file.endsWith('.jsonl')).sort();
100
+ }
101
+ catch {
102
+ return [];
103
+ }
104
+ },
105
+ };
106
+ }
@@ -0,0 +1,65 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ export const SUPPORTED_SCHEMA_VERSION = 1;
3
+ function isAgentEventType(type) {
4
+ return typeof type === 'string' && [
5
+ 'system', 'text', 'thinking', 'tool_use', 'tool_progress',
6
+ 'tool_result', 'usage', 'consent_required', 'done', 'error',
7
+ ].includes(type);
8
+ }
9
+ function parseEventLine(line) {
10
+ let parsed;
11
+ try {
12
+ parsed = JSON.parse(line);
13
+ }
14
+ catch {
15
+ return { event: null, schemaVersion: 0, error: `JSON parse failed: ${line.slice(0, 100)}` };
16
+ }
17
+ if (typeof parsed !== 'object' || parsed === null) {
18
+ return { event: null, schemaVersion: 0, error: 'parsed value is not an object' };
19
+ }
20
+ const schemaVersion = typeof parsed['schemaVersion'] === 'number' ? parsed['schemaVersion'] : 0;
21
+ if (schemaVersion > SUPPORTED_SCHEMA_VERSION) {
22
+ return { event: null, schemaVersion, error: `schemaVersion ${schemaVersion} > supported ${SUPPORTED_SCHEMA_VERSION}` };
23
+ }
24
+ const type = parsed['type'];
25
+ if (!isAgentEventType(type)) {
26
+ if (type === 'heartbeat') {
27
+ return { event: null, schemaVersion, error: undefined };
28
+ }
29
+ return { event: null, schemaVersion, error: undefined };
30
+ }
31
+ return { event: parsed, schemaVersion, error: undefined };
32
+ }
33
+ export function replayEventsFromNdjson(ndjsonPath) {
34
+ if (!existsSync(ndjsonPath)) {
35
+ return { events: [], errors: [], skipped: false };
36
+ }
37
+ const content = readFileSync(ndjsonPath, 'utf8');
38
+ const lines = content.split('\n').filter((l) => l.trim().length > 0);
39
+ const events = [];
40
+ const errors = [];
41
+ let latestContinuationToken;
42
+ let skipped = false;
43
+ for (const line of lines) {
44
+ const { event, schemaVersion, error } = parseEventLine(line);
45
+ if (schemaVersion > SUPPORTED_SCHEMA_VERSION) {
46
+ errors.push(error ?? `unsupported schemaVersion ${schemaVersion}`);
47
+ skipped = true;
48
+ return { events: [], latestContinuationToken: undefined, errors, skipped };
49
+ }
50
+ if (error) {
51
+ errors.push(error);
52
+ continue;
53
+ }
54
+ if (!event)
55
+ continue;
56
+ events.push(event);
57
+ if (event.type === 'system' && event.continuationToken) {
58
+ latestContinuationToken = event.continuationToken;
59
+ }
60
+ if (event.type === 'done' && event.continuationToken) {
61
+ latestContinuationToken = event.continuationToken;
62
+ }
63
+ }
64
+ return { events, latestContinuationToken, errors, skipped };
65
+ }
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { resolve, dirname } from 'node:path';
4
+ import { WbRunner } from './wb-runner.js';
5
+ const specJsonPath = process.argv[2];
6
+ if (!specJsonPath) {
7
+ process.stderr.write('usage: wb-runner-main <specJsonPath>\n');
8
+ process.exit(1);
9
+ }
10
+ let spec;
11
+ try {
12
+ const raw = readFileSync(resolve(specJsonPath), 'utf8');
13
+ spec = JSON.parse(raw);
14
+ }
15
+ catch (err) {
16
+ process.stderr.write(`failed to read spec: ${err.message}\n`);
17
+ process.exit(1);
18
+ }
19
+ // specJsonPath = <dataDir>/runs/<botId>/<runId>/spec.json → dataDir is 3 levels up from spec.json dir
20
+ const dataDir = dirname(dirname(dirname(dirname(resolve(specJsonPath)))));
21
+ const runner = new WbRunner(dataDir, spec);
22
+ runner.start().then(() => {
23
+ process.exit(0);
24
+ }).catch((err) => {
25
+ process.stderr.write(`wb-runner fatal: ${err.message}\n`);
26
+ process.exit(1);
27
+ });