@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,252 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { basename, dirname, join, resolve } from 'node:path';
3
+ import { auditMirrorPath, auditRejectedPath, auditWalDir, configFile, runAuditOffsetPath, runDir as resolveRunDir, runsRootDir, } from '../paths.js';
4
+ import { appendNdjsonLine, readNdjsonSegments } from '../util/ndjson-rotation.js';
5
+ import { loadAuditPipeConfig, resolveAuditDataDir } from './config.js';
6
+ import { DEFAULT_RETRY_POLICY } from './contracts.js';
7
+ import { createMirrorSink } from './mirror-sink.js';
8
+ import { normalize, hydrateNormalizer, resetNormalizerState } from './normalizer.js';
9
+ import { parseEventLine } from './parser.js';
10
+ import { createTailer } from './tailer.js';
11
+ import { createWal } from './wal.js';
12
+ import { createBitableSink } from './bitable-sink.js';
13
+ function readRunSpec(runDir) {
14
+ const specPath = join(runDir, 'spec.json');
15
+ if (!existsSync(specPath))
16
+ return null;
17
+ try {
18
+ return JSON.parse(readFileSync(specPath, 'utf8'));
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ function listRunDirs(dataDir) {
25
+ const runsRoot = runsRootDir(dataDir);
26
+ if (!existsSync(runsRoot))
27
+ return [];
28
+ const runDirs = [];
29
+ for (const botEntry of readdirSync(runsRoot, { withFileTypes: true })) {
30
+ if (!botEntry.isDirectory())
31
+ continue;
32
+ const botDir = join(runsRoot, botEntry.name);
33
+ for (const runEntry of readdirSync(botDir, { withFileTypes: true })) {
34
+ if (runEntry.isDirectory())
35
+ runDirs.push(resolveRunDir(dataDir, runEntry.name, botEntry.name));
36
+ }
37
+ }
38
+ return runDirs.sort();
39
+ }
40
+ function readAuditMirrorRecords(dataDir) {
41
+ const path = auditMirrorPath(dataDir);
42
+ const records = [];
43
+ for (const line of readNdjsonSegments(path)) {
44
+ if (!line.trim())
45
+ continue;
46
+ try {
47
+ const parsed = JSON.parse(line);
48
+ if (parsed['status'] !== 'rejected' && typeof parsed['run_id'] === 'string' && typeof parsed['raw_tool_use_id'] === 'string' && typeof parsed['revision'] === 'number' && typeof parsed['audit_record_id'] === 'string') {
49
+ records.push(parsed);
50
+ }
51
+ }
52
+ catch {
53
+ continue;
54
+ }
55
+ }
56
+ return records;
57
+ }
58
+ function appendRejected(dataDir, line) {
59
+ appendNdjsonLine(auditRejectedPath(dataDir), line);
60
+ }
61
+ function countWalPending(dataDir) {
62
+ const walDir = auditWalDir(dataDir);
63
+ if (!existsSync(walDir))
64
+ return 0;
65
+ return readdirSync(walDir).filter((file) => file.endsWith('.jsonl')).length;
66
+ }
67
+ function queueFlush(state) {
68
+ if (!state.bitableSink)
69
+ return Promise.resolve();
70
+ state.flushChain = state.flushChain.then(async () => {
71
+ const result = await state.bitableSink?.flush();
72
+ if (result?.ok)
73
+ state.lastBitableOk = new Date().toISOString();
74
+ }).catch(() => undefined);
75
+ return state.flushChain;
76
+ }
77
+ function clearTailers(state) {
78
+ for (const entry of state.tailers.values())
79
+ clearInterval(entry.timer);
80
+ state.tailers.clear();
81
+ }
82
+ function clearRuntimeTimers(state) {
83
+ if (state.scanTimer) {
84
+ clearInterval(state.scanTimer);
85
+ state.scanTimer = null;
86
+ }
87
+ if (state.flushTimer) {
88
+ clearInterval(state.flushTimer);
89
+ state.flushTimer = null;
90
+ }
91
+ }
92
+ async function drainRun(state, runDir, tailer) {
93
+ const spec = readRunSpec(runDir);
94
+ for await (const line of tailer.tick()) {
95
+ const event = parseEventLine(line);
96
+ if (!event)
97
+ continue;
98
+ const result = normalize(event, spec, new Date().toISOString(), line);
99
+ if (result.kind === 'rejected') {
100
+ if (state.config)
101
+ createMirrorSink({ dataDir: state.dataDir }).write(result.record);
102
+ appendRejected(state.dataDir, JSON.stringify(result.record));
103
+ continue;
104
+ }
105
+ if (state.config)
106
+ createMirrorSink({ dataDir: state.dataDir }).write(result.record);
107
+ state.wal?.append(result.record);
108
+ await queueFlush(state);
109
+ }
110
+ }
111
+ function attachRun(state, runDir) {
112
+ if (state.tailers.has(runDir) || !existsSync(join(runDir, 'spec.json')))
113
+ return;
114
+ const runId = basename(runDir);
115
+ const botId = basename(dirname(runDir));
116
+ const tailer = createTailer({
117
+ eventsPath: join(runDir, 'events.ndjson'),
118
+ offsetPath: runAuditOffsetPath(state.dataDir, runId, botId),
119
+ });
120
+ const entry = {
121
+ runDir,
122
+ tailer,
123
+ timer: setInterval(() => undefined, state.drainIntervalMs),
124
+ draining: false,
125
+ };
126
+ const tick = () => {
127
+ if (state.stopped || entry.draining)
128
+ return;
129
+ entry.draining = true;
130
+ void drainRun(state, runDir, tailer).finally(() => {
131
+ entry.draining = false;
132
+ });
133
+ };
134
+ clearInterval(entry.timer);
135
+ entry.timer = setInterval(tick, state.drainIntervalMs);
136
+ state.tailers.set(runDir, entry);
137
+ tick();
138
+ }
139
+ function scanAndAttachMissingRuns(state) {
140
+ if (state.stopped || state.scanning || !state.config?.audit.enabled)
141
+ return;
142
+ state.scanning = true;
143
+ try {
144
+ for (const runDir of listRunDirs(state.dataDir)) {
145
+ attachRun(state, runDir);
146
+ }
147
+ }
148
+ finally {
149
+ state.scanning = false;
150
+ }
151
+ }
152
+ function buildBitableSink(state, config) {
153
+ if (!config.audit.enabled)
154
+ return null;
155
+ return createBitableSink({
156
+ dataDir: state.dataDir,
157
+ baseId: config.audit.bitable_base_id,
158
+ tableId: config.audit.bitable_table_id,
159
+ appId: config.audit.app_id,
160
+ appSecret: config.audit.app_secret,
161
+ larkDomain: config.audit.lark_domain,
162
+ retry: state.retryOverride ?? DEFAULT_RETRY_POLICY,
163
+ wal: state.wal ?? createWal({ dataDir: state.dataDir }),
164
+ _client: state.bitableClient,
165
+ });
166
+ }
167
+ async function startRuntime(state) {
168
+ const config = loadAuditPipeConfig({ configPath: state.configPath, env: state.env });
169
+ state.config = config;
170
+ clearTailers(state);
171
+ clearRuntimeTimers(state);
172
+ state.scanning = false;
173
+ if (!config.audit.enabled) {
174
+ state.wal = null;
175
+ state.bitableSink = null;
176
+ return;
177
+ }
178
+ mkdirSync(state.dataDir, { recursive: true });
179
+ resetNormalizerState();
180
+ hydrateNormalizer(readAuditMirrorRecords(state.dataDir));
181
+ state.wal = createWal({ dataDir: state.dataDir });
182
+ state.bitableSink = buildBitableSink(state, config);
183
+ scanAndAttachMissingRuns(state);
184
+ state.scanTimer = setInterval(() => {
185
+ scanAndAttachMissingRuns(state);
186
+ }, state.scanIntervalMs);
187
+ state.flushTimer = setInterval(() => {
188
+ void queueFlush(state);
189
+ }, 60_000);
190
+ await queueFlush(state);
191
+ }
192
+ export async function startAuditPipe(options = {}) {
193
+ const env = options.env ?? process.env;
194
+ const dataDir = resolveAuditDataDir(env);
195
+ const state = {
196
+ configPath: options.configPath ?? resolve(configFile(dataDir, 'audit-pipe')),
197
+ dataDir,
198
+ env,
199
+ config: null,
200
+ wal: null,
201
+ bitableSink: null,
202
+ tailers: new Map(),
203
+ scanTimer: null,
204
+ flushTimer: null,
205
+ lastBitableOk: null,
206
+ stopped: false,
207
+ scanning: false,
208
+ flushChain: Promise.resolve(),
209
+ onSighup: null,
210
+ onSigterm: null,
211
+ bitableClient: options._bitableClient,
212
+ retryOverride: options._retryOverride,
213
+ scanIntervalMs: options._scanIntervalMs ?? 500,
214
+ drainIntervalMs: options._drainIntervalMs ?? 200,
215
+ };
216
+ await startRuntime(state);
217
+ const controller = {
218
+ async reload() {
219
+ if (state.stopped)
220
+ return;
221
+ await startRuntime(state);
222
+ },
223
+ async stop() {
224
+ if (state.stopped)
225
+ return;
226
+ state.stopped = true;
227
+ clearTailers(state);
228
+ clearRuntimeTimers(state);
229
+ if (state.onSighup)
230
+ process.removeListener('SIGHUP', state.onSighup);
231
+ if (state.onSigterm)
232
+ process.removeListener('SIGTERM', state.onSigterm);
233
+ await Promise.race([state.flushChain, new Promise((resolve) => setTimeout(resolve, 30_000))]);
234
+ },
235
+ status() {
236
+ return {
237
+ tailers: state.tailers.size,
238
+ walPending: countWalPending(state.dataDir),
239
+ lastBitableOk: state.lastBitableOk,
240
+ };
241
+ },
242
+ };
243
+ state.onSighup = () => {
244
+ void controller.reload();
245
+ };
246
+ state.onSigterm = () => {
247
+ void controller.stop();
248
+ };
249
+ process.on('SIGHUP', state.onSighup);
250
+ process.on('SIGTERM', state.onSigterm);
251
+ return controller;
252
+ }
@@ -0,0 +1,24 @@
1
+ function isRecord(value) {
2
+ return typeof value === 'object' && value !== null;
3
+ }
4
+ export function parseEventLine(line) {
5
+ if (!line.trim())
6
+ return null;
7
+ let parsed;
8
+ try {
9
+ parsed = JSON.parse(line);
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ if (!isRecord(parsed))
15
+ return null;
16
+ if (parsed['type'] !== 'tool_use')
17
+ return null;
18
+ if (typeof parsed['id'] !== 'string' || typeof parsed['name'] !== 'string' || !('input' in parsed))
19
+ return null;
20
+ const event = { type: 'tool_use', id: parsed['id'], name: parsed['name'], input: parsed['input'] };
21
+ if (typeof parsed['subagentId'] === 'string')
22
+ event.subagentId = parsed['subagentId'];
23
+ return event;
24
+ }
@@ -0,0 +1,46 @@
1
+ import { closeSync, existsSync, openSync, readFileSync, readSync, renameSync, statSync, writeFileSync } from 'node:fs';
2
+ function atomicWrite(path, content) {
3
+ const tmp = `${path}.tmp`;
4
+ writeFileSync(tmp, content);
5
+ renameSync(tmp, path);
6
+ }
7
+ function readOffset(path) {
8
+ if (!existsSync(path))
9
+ return 0;
10
+ const value = Number.parseInt(readFileSync(path, 'utf8').trim(), 10);
11
+ return Number.isFinite(value) && value >= 0 ? value : 0;
12
+ }
13
+ export function createTailer({ eventsPath, offsetPath }) {
14
+ let offset = readOffset(offsetPath);
15
+ return {
16
+ async *tick() {
17
+ if (!existsSync(eventsPath))
18
+ return;
19
+ const size = statSync(eventsPath).size;
20
+ if (size < offset)
21
+ offset = 0;
22
+ if (size <= offset)
23
+ return;
24
+ const length = size - offset;
25
+ const buffer = Buffer.alloc(length);
26
+ const fd = openSync(eventsPath, 'r');
27
+ try {
28
+ readSync(fd, buffer, 0, buffer.length, offset);
29
+ }
30
+ finally {
31
+ closeSync(fd);
32
+ }
33
+ const chunk = buffer.toString('utf8');
34
+ const lastNewline = chunk.lastIndexOf('\n');
35
+ if (lastNewline < 0)
36
+ return;
37
+ const complete = chunk.slice(0, lastNewline + 1);
38
+ offset += Buffer.byteLength(complete, 'utf8');
39
+ atomicWrite(offsetPath, String(offset));
40
+ for (const line of complete.split('\n')) {
41
+ if (line.trim())
42
+ yield line;
43
+ }
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,71 @@
1
+ import { mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { auditWalDir } 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 createWal({ dataDir }) {
21
+ const walDir = auditWalDir(dataDir);
22
+ mkdirSync(walDir, { recursive: true });
23
+ let counter = 0;
24
+ let lastSeq = readdirSync(walDir).map((file) => Number.parseInt(file.replace(/\.jsonl$/, ''), 10)).filter(Number.isFinite).reduce((max, value) => Math.max(max, value), 0);
25
+ function filePathFor(seq) {
26
+ return join(walDir, `${serializeSeq(seq)}.jsonl`);
27
+ }
28
+ function writeEntry(entry) {
29
+ atomicWrite(filePathFor(entry.seq), JSON.stringify(entry));
30
+ }
31
+ function nextSeq() {
32
+ counter += 1;
33
+ lastSeq = Math.max(lastSeq + 1, Date.now() * 1000 + counter);
34
+ return lastSeq;
35
+ }
36
+ return {
37
+ append(record) {
38
+ const seq = nextSeq();
39
+ writeEntry({ seq, record, attempts: 0, state: 'queued', enqueued_at: new Date().toISOString() });
40
+ return seq;
41
+ },
42
+ async *replay() {
43
+ const files = readdirSync(walDir).filter((file) => file.endsWith('.jsonl')).sort();
44
+ for (const file of files) {
45
+ const entry = parseEntry(join(walDir, file));
46
+ if (entry)
47
+ yield entry;
48
+ }
49
+ },
50
+ ack(seq) {
51
+ unlinkSync(filePathFor(seq));
52
+ },
53
+ markPendingSync(seq) {
54
+ const path = filePathFor(seq);
55
+ const entry = parseEntry(path);
56
+ if (!entry)
57
+ return;
58
+ writeEntry({ ...entry, attempts: Math.max(entry.attempts, 5), state: 'pending-sync' });
59
+ },
60
+ bumpAttempts(seq) {
61
+ const path = filePathFor(seq);
62
+ const entry = parseEntry(path);
63
+ if (!entry)
64
+ return;
65
+ writeEntry({ ...entry, attempts: entry.attempts + 1 });
66
+ },
67
+ listFiles() {
68
+ return readdirSync(walDir).filter((file) => file.endsWith('.jsonl')).sort();
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,45 @@
1
+ import { existsSync, readFileSync, statSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { loadConfig } from '../config/registry.js';
4
+ import { configFile, legacyConfigJsonPath, resolveDataDir } from '../paths.js';
5
+ import { CalendarHookConfigSchema } from './contracts.js';
6
+ function validateMode(path) {
7
+ const stat = statSync(path);
8
+ if ((stat.mode & 0o077) !== 0) {
9
+ throw new Error(`${path} permissions are too open (${(stat.mode & 0o777).toString(8)}), expected 600`);
10
+ }
11
+ }
12
+ function readJson(path) {
13
+ return JSON.parse(readFileSync(path, 'utf8'));
14
+ }
15
+ function isRecord(value) {
16
+ return typeof value === 'object' && value !== null;
17
+ }
18
+ function parseLegacyConfig(path) {
19
+ const parsed = readJson(path);
20
+ if (!isRecord(parsed) || !isRecord(parsed['calendar_hook'])) {
21
+ throw new Error('config.json must contain a calendar_hook object');
22
+ }
23
+ return CalendarHookConfigSchema.parse(parsed['calendar_hook']);
24
+ }
25
+ export function resolveCalendarHookDataDir(env = process.env) {
26
+ return resolveDataDir({ dataDir: env['WB_DATA_DIR'] });
27
+ }
28
+ export function resolveCalendarHookConfigPath(env = process.env) {
29
+ return resolve(configFile(resolveCalendarHookDataDir(env), 'calendar-hook'));
30
+ }
31
+ export function loadCalendarHookConfig(options = {}) {
32
+ const env = options.env ?? process.env;
33
+ const dataDir = resolveCalendarHookDataDir(env);
34
+ const configPath = resolve(options.configPath ?? resolveCalendarHookConfigPath(env));
35
+ const legacyPath = resolve(legacyConfigJsonPath(dataDir));
36
+ if (existsSync(configPath)) {
37
+ validateMode(configPath);
38
+ return CalendarHookConfigSchema.parse(loadConfig(dataDir, 'calendar-hook', CalendarHookConfigSchema, {}));
39
+ }
40
+ if (existsSync(legacyPath)) {
41
+ validateMode(legacyPath);
42
+ return parseLegacyConfig(legacyPath);
43
+ }
44
+ return CalendarHookConfigSchema.parse({});
45
+ }
@@ -0,0 +1,66 @@
1
+ import { z } from 'zod';
2
+ export const CALENDAR_TRIGGER_SOURCES = ['calendar'];
3
+ export const CalendarHookConfigSchema = z.object({
4
+ enabled: z.boolean().default(false),
5
+ transport: z.enum(['disabled', 'mock', 'cli']).default('mock'),
6
+ calendar_id: z.string().min(1).optional(),
7
+ rpc_timeout_ms: z.number().int().positive().default(15_000),
8
+ overdue_after_ms: z.number().int().positive().default(60 * 60 * 1000),
9
+ sweep_interval_ms: z.number().int().positive().default(15_000),
10
+ });
11
+ export const CalendarHookStateSchema = z.object({
12
+ run_id: z.string().min(1),
13
+ session_id: z.string().min(1).nullable().default(null),
14
+ open_revision_applied: z.number().int().min(0).nullable(),
15
+ close_revision_applied: z.number().int().min(0).nullable(),
16
+ calendar_block_id: z.string().nullable(),
17
+ calendar_hook_failed: z.boolean().default(false),
18
+ desired_state: z.enum(['open', 'closed']).default('open'),
19
+ due_at: z.string().datetime().nullable(),
20
+ overdue_escalated_at: z.string().datetime().nullable(),
21
+ last_error: z.string().nullable(),
22
+ updated_at: z.string().datetime(),
23
+ });
24
+ export const CalendarBlockRequestSchema = z.object({
25
+ run_id: z.string().min(1),
26
+ session_id: z.string().min(1),
27
+ revision: z.number().int().min(0),
28
+ title: z.string().min(1),
29
+ starts_at: z.string().datetime(),
30
+ ends_at: z.string().datetime(),
31
+ });
32
+ export const CalendarBlockResultSchema = z.object({
33
+ calendar_block_id: z.string().min(1),
34
+ });
35
+ export const CalendarCommandReceivedSchema = z.object({
36
+ source: z.enum(['calendar', 'periodic']),
37
+ request_id: z.string().min(1),
38
+ session_id: z.string().min(1),
39
+ run_id: z.string().min(1),
40
+ revision: z.number().int().min(0),
41
+ text: z.string().min(1),
42
+ scheduled_at: z.string().datetime(),
43
+ user_open_id: z.string().optional(),
44
+ thread_id: z.string().optional(),
45
+ message_id: z.string().optional(),
46
+ });
47
+ export const CalendarTriggerRecordSchema = z.object({
48
+ request_id: z.string().min(1),
49
+ session_id: z.string().min(1),
50
+ run_id: z.string().min(1),
51
+ revision: z.number().int().min(0),
52
+ text: z.string().min(1),
53
+ scheduled_at: z.string().datetime(),
54
+ user_open_id: z.string().optional(),
55
+ thread_id: z.string().optional(),
56
+ message_id: z.string().optional(),
57
+ fired_at: z.string().datetime().nullable().default(null),
58
+ });
59
+ export const CalendarRunStateChangedSchema = z.object({
60
+ event: z.literal('RunStateChanged'),
61
+ reason: z.literal('calendar_overdue'),
62
+ run_id: z.string().min(1),
63
+ session_id: z.string().min(1),
64
+ revision: z.number().int().min(0),
65
+ ts: z.string().datetime(),
66
+ });
@@ -0,0 +1,5 @@
1
+ export * from './contracts.js';
2
+ export { loadCalendarHookConfig, resolveCalendarHookConfigPath, resolveCalendarHookDataDir } from './config.js';
3
+ export { openCalendarBlock, closeCalendarBlock } from './service.js';
4
+ export { createMockCalendarTransport, createGuardedCliCalendarTransport, withTimeout } from './transport.js';
5
+ export { startCalendarScheduler } from './scheduler.js';
@@ -0,0 +1,169 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { calendarMockTriggersPath, calendarRunStateChangedPath, calendarTriggerStatePath, runCalendarHookStatePath, runsRootDir } from '../paths.js';
4
+ import { appendNdjsonLine } from '../util/ndjson-rotation.js';
5
+ import { runPeriodicPhase } from '../periodic-tasks/orchestrator.js';
6
+ import { CalendarCommandReceivedSchema, CalendarHookStateSchema, CalendarRunStateChangedSchema, CalendarTriggerRecordSchema, } from './contracts.js';
7
+ function atomicWrite(path, content) {
8
+ mkdirSync(dirname(path), { recursive: true });
9
+ const temp = `${path}.tmp`;
10
+ writeFileSync(temp, content);
11
+ renameSync(temp, path);
12
+ }
13
+ function readTriggerRecords(path) {
14
+ if (!existsSync(path))
15
+ return [];
16
+ try {
17
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
18
+ return Array.isArray(parsed) ? parsed.map((item) => CalendarTriggerRecordSchema.parse(item)) : [];
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ }
24
+ function readTriggerState(path) {
25
+ if (!existsSync(path))
26
+ return {};
27
+ try {
28
+ return JSON.parse(readFileSync(path, 'utf8'));
29
+ }
30
+ catch {
31
+ return {};
32
+ }
33
+ }
34
+ function writeTriggerState(path, state) {
35
+ atomicWrite(path, JSON.stringify(state, null, 2));
36
+ }
37
+ function readDirNames(path) {
38
+ try {
39
+ return readdirSync(path, { withFileTypes: true })
40
+ .filter((entry) => entry.isDirectory())
41
+ .map((entry) => entry.name);
42
+ }
43
+ catch {
44
+ return [];
45
+ }
46
+ }
47
+ function listCalendarStateFiles(dataDir) {
48
+ const runsRoot = runsRootDir(dataDir);
49
+ if (!existsSync(runsRoot))
50
+ return [];
51
+ const files = [];
52
+ for (const botId of readDirNames(runsRoot)) {
53
+ const botDir = join(runsRoot, botId);
54
+ for (const runId of readDirNames(botDir)) {
55
+ const statePath = runCalendarHookStatePath(dataDir, runId, botId);
56
+ if (existsSync(statePath))
57
+ files.push(statePath);
58
+ }
59
+ }
60
+ return files;
61
+ }
62
+ function readCalendarState(path) {
63
+ if (!existsSync(path))
64
+ return null;
65
+ try {
66
+ return CalendarHookStateSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
72
+ function writeCalendarState(path, state) {
73
+ atomicWrite(path, JSON.stringify(state, null, 2));
74
+ }
75
+ export function startCalendarScheduler(options) {
76
+ const nowFn = options.nowFn ?? Date.now;
77
+ const triggerFile = calendarMockTriggersPath(options.dataDir);
78
+ const triggerStateFile = calendarTriggerStatePath(options.dataDir);
79
+ let timer = null;
80
+ let inFlight = false;
81
+ async function tick() {
82
+ if (inFlight)
83
+ return;
84
+ inFlight = true;
85
+ try {
86
+ const triggerState = readTriggerState(triggerStateFile);
87
+ const now = nowFn();
88
+ const nowIso = new Date(now).toISOString();
89
+ for (const record of readTriggerRecords(triggerFile)) {
90
+ if (Date.parse(record.scheduled_at) > now)
91
+ continue;
92
+ if (triggerState[record.request_id])
93
+ continue;
94
+ triggerState[record.request_id] = nowIso;
95
+ writeTriggerState(triggerStateFile, triggerState);
96
+ await options.onCommand(CalendarCommandReceivedSchema.parse({
97
+ source: 'calendar',
98
+ request_id: record.request_id,
99
+ session_id: record.session_id,
100
+ run_id: record.run_id,
101
+ revision: record.revision,
102
+ text: record.text,
103
+ scheduled_at: record.scheduled_at,
104
+ user_open_id: record.user_open_id,
105
+ thread_id: record.thread_id,
106
+ message_id: record.message_id,
107
+ }));
108
+ }
109
+ await runPeriodicPhase({
110
+ dataDir: options.dataDir,
111
+ nowFn,
112
+ onCommand: options.onCommand,
113
+ });
114
+ for (const statePath of listCalendarStateFiles(options.dataDir)) {
115
+ const state = readCalendarState(statePath);
116
+ if (!state || !state.due_at || state.desired_state !== 'open' || state.overdue_escalated_at)
117
+ continue;
118
+ if (Date.parse(state.due_at) > now)
119
+ continue;
120
+ appendNdjsonLine(calendarRunStateChangedPath(options.dataDir), JSON.stringify(CalendarRunStateChangedSchema.parse({
121
+ event: 'RunStateChanged',
122
+ reason: 'calendar_overdue',
123
+ run_id: state.run_id,
124
+ session_id: state.session_id ?? state.run_id,
125
+ revision: state.open_revision_applied ?? 0,
126
+ ts: nowIso,
127
+ })));
128
+ writeCalendarState(statePath, CalendarHookStateSchema.parse({
129
+ ...state,
130
+ overdue_escalated_at: nowIso,
131
+ updated_at: nowIso,
132
+ }));
133
+ if (options.onOverdueEscalated) {
134
+ try {
135
+ await options.onOverdueEscalated({
136
+ run_id: state.run_id,
137
+ session_id: state.session_id ?? state.run_id,
138
+ revision: state.open_revision_applied ?? 0,
139
+ due_at: state.due_at,
140
+ escalated_at: nowIso,
141
+ });
142
+ }
143
+ catch (notifyError) {
144
+ // Do not surface IM/notification failure back to the sweep loop; the
145
+ // escalation has already been recorded in the RunStateChanged queue.
146
+ void notifyError;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ finally {
152
+ inFlight = false;
153
+ }
154
+ }
155
+ if (options.config.enabled) {
156
+ timer = setInterval(() => {
157
+ void tick();
158
+ }, options.config.sweep_interval_ms);
159
+ timer.unref?.();
160
+ }
161
+ return {
162
+ tick,
163
+ stop() {
164
+ if (timer)
165
+ clearInterval(timer);
166
+ timer = null;
167
+ },
168
+ };
169
+ }