@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,237 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync, mkdirSync, writeFileSync, renameSync, appendFileSync, openSync, statSync, readSync, closeSync, readFileSync, } from 'node:fs';
3
+ import { runDir, runErrorLogPath, runEventsPath, runHeartbeatPath, runOutputLogPath, runPidPath, runSpecPath, runStatusPath, runStopSignalPath, } from '../paths.js';
4
+ export const CURRENT_SCHEMA_VERSION = 1;
5
+ export const HEARTBEAT_INTERVAL_MS = 5_000;
6
+ export const STOP_POLL_INTERVAL_MS = 500;
7
+ export const STOP_GRACE_MS = 500;
8
+ function atomicWrite(path, content) {
9
+ const tmp = `${path}.tmp`;
10
+ writeFileSync(tmp, content);
11
+ renameSync(tmp, path);
12
+ }
13
+ const VALID_ID_PATTERN = /^[a-zA-Z0-9._-]{1,64}$/;
14
+ export function validateSpecId(id, field) {
15
+ if (!VALID_ID_PATTERN.test(id)) {
16
+ throw new Error(`invalid ${field}: must match /^[a-zA-Z0-9._-]{1,64}$/, got "${id}"`);
17
+ }
18
+ }
19
+ export class WbRunner {
20
+ dataDir;
21
+ spec;
22
+ runDir;
23
+ child = null;
24
+ heartbeatTimer = null;
25
+ stopPollTimer = null;
26
+ eventTailTimer = null;
27
+ handlingStop = false;
28
+ constructor(dataDir, spec) {
29
+ this.dataDir = dataDir;
30
+ this.spec = spec;
31
+ validateSpecId(spec.runId, 'runId');
32
+ validateSpecId(spec.botId, 'botId');
33
+ this.runDir = runDir(dataDir, spec.runId, spec.botId);
34
+ }
35
+ get runDirectory() {
36
+ return this.runDir;
37
+ }
38
+ async start() {
39
+ mkdirSync(this.runDir, { recursive: true });
40
+ const specToWrite = {
41
+ runId: this.spec.runId,
42
+ botId: this.spec.botId,
43
+ agentId: this.spec.agentId,
44
+ model: this.spec.model ?? null,
45
+ cwd: this.spec.cwd,
46
+ userOpenId: this.spec.userOpenId,
47
+ threadId: this.spec.threadId,
48
+ sourceMessageId: this.spec.sourceMessageId,
49
+ replyMessageId: this.spec.replyMessageId,
50
+ continuationToken: this.spec.continuationToken ?? null,
51
+ consentLevel: this.spec.consentLevel ?? 'normal',
52
+ startedAt: new Date().toISOString(),
53
+ schemaVersion: this.spec.schemaVersion ?? CURRENT_SCHEMA_VERSION,
54
+ host: this.spec.host ?? 'local',
55
+ };
56
+ writeFileSync(runSpecPath(this.dataDir, this.spec.runId, this.spec.botId), JSON.stringify(specToWrite, null, 2));
57
+ this.writeStatus('running');
58
+ this.writeHeartbeat();
59
+ const outputFd = openSync(runOutputLogPath(this.dataDir, this.spec.runId, this.spec.botId), 'a');
60
+ const errFd = openSync(runErrorLogPath(this.dataDir, this.spec.runId, this.spec.botId), 'a');
61
+ // D1: codex 等 stdin-only CLI 需要把 prompt 通过 stdin 写给 grandchild,
62
+ // 默认 claude-code 路径仍走 stdio[0]='ignore' (no TTY, no stdin, contract 不变).
63
+ const stdinSpec = this.spec.stdinInput !== undefined ? 'pipe' : 'ignore';
64
+ this.child = spawn(this.spec.agentCommand, this.spec.agentArgs, {
65
+ cwd: this.spec.cwd,
66
+ env: this.spec.env,
67
+ stdio: [stdinSpec, outputFd, errFd],
68
+ detached: true,
69
+ });
70
+ if (stdinSpec === 'pipe' && this.child.stdin) {
71
+ // .end() 在 unref 之前调用, Node 会先 flush stdin buffer 再让 fd close, 然后才允许 parent exit.
72
+ this.child.stdin.end(this.spec.stdinInput);
73
+ }
74
+ this.child.unref();
75
+ writeFileSync(runPidPath(this.dataDir, this.spec.runId, this.spec.botId), String(this.child.pid ?? ''));
76
+ this.heartbeatTimer = setInterval(() => this.writeHeartbeat(), HEARTBEAT_INTERVAL_MS);
77
+ this.stopPollTimer = setInterval(() => this.checkStopSignal(), STOP_POLL_INTERVAL_MS);
78
+ const tailState = this.startEventTailer();
79
+ return new Promise((resolve) => {
80
+ this.child.once('close', (code) => {
81
+ this.flushEventTailer(tailState);
82
+ this.cleanup();
83
+ if (this.handlingStop) {
84
+ if (!this.hasTerminalEvent()) {
85
+ this.appendErrorEvent('stopped by user');
86
+ }
87
+ this.writeStatus('stopped');
88
+ }
89
+ else if (code === 0) {
90
+ if (!this.hasTerminalEvent()) {
91
+ this.appendDoneEvent();
92
+ }
93
+ this.writeStatus('done');
94
+ }
95
+ else {
96
+ if (!this.hasTerminalEvent()) {
97
+ this.appendErrorEvent(`child exited with code ${code}`);
98
+ }
99
+ this.writeStatus('error');
100
+ }
101
+ resolve();
102
+ });
103
+ this.child.once('error', (err) => {
104
+ this.flushEventTailer(tailState);
105
+ this.cleanup();
106
+ appendFileSync(runErrorLogPath(this.dataDir, this.spec.runId, this.spec.botId), `spawn error: ${err.message}\n`);
107
+ if (!this.hasTerminalEvent()) {
108
+ this.appendErrorEvent(`spawn failed: ${err.message}`);
109
+ }
110
+ this.writeStatus('error');
111
+ resolve();
112
+ });
113
+ });
114
+ }
115
+ startEventTailer() {
116
+ const state = { offset: 0 };
117
+ const outputLog = runOutputLogPath(this.dataDir, this.spec.runId, this.spec.botId);
118
+ this.eventTailTimer = setInterval(() => {
119
+ this.tailOutputLog(outputLog, state);
120
+ }, 200);
121
+ return state;
122
+ }
123
+ flushEventTailer(state) {
124
+ const outputLog = runOutputLogPath(this.dataDir, this.spec.runId, this.spec.botId);
125
+ this.tailOutputLog(outputLog, state);
126
+ }
127
+ tailOutputLog(outputLog, state) {
128
+ try {
129
+ const { size } = statSync(outputLog);
130
+ if (size <= state.offset)
131
+ return;
132
+ const buf = Buffer.alloc(size - state.offset);
133
+ const fd = openSync(outputLog, 'r');
134
+ readSync(fd, buf, 0, buf.length, state.offset);
135
+ closeSync(fd);
136
+ state.offset = size;
137
+ const lines = buf.toString('utf8').split('\n');
138
+ for (const line of lines) {
139
+ if (line.trim())
140
+ this.appendEvent(line);
141
+ }
142
+ }
143
+ catch {
144
+ // file may not exist yet
145
+ }
146
+ }
147
+ appendEvent(line) {
148
+ try {
149
+ const parsed = JSON.parse(line);
150
+ if (typeof parsed === 'object' && parsed !== null) {
151
+ const event = ('schemaVersion' in parsed) ? parsed : { ...parsed, schemaVersion: CURRENT_SCHEMA_VERSION };
152
+ appendFileSync(runEventsPath(this.dataDir, this.spec.runId, this.spec.botId), `${JSON.stringify(event)}\n`);
153
+ }
154
+ }
155
+ catch {
156
+ // non-JSON stdout lines are not events, skip
157
+ }
158
+ }
159
+ appendErrorEvent(message) {
160
+ const event = { type: 'error', message, schemaVersion: CURRENT_SCHEMA_VERSION };
161
+ appendFileSync(runEventsPath(this.dataDir, this.spec.runId, this.spec.botId), `${JSON.stringify(event)}\n`);
162
+ }
163
+ appendDoneEvent() {
164
+ const event = { type: 'done', schemaVersion: CURRENT_SCHEMA_VERSION };
165
+ appendFileSync(runEventsPath(this.dataDir, this.spec.runId, this.spec.botId), `${JSON.stringify(event)}\n`);
166
+ }
167
+ // D0 hotfix idempotency guard: skip terminal-event fallback when child 已写过 done/error.
168
+ // 读 events.ndjson 最后非空行, 判断 type ∈ {done, error}.
169
+ hasTerminalEvent() {
170
+ const ndjsonPath = runEventsPath(this.dataDir, this.spec.runId, this.spec.botId);
171
+ if (!existsSync(ndjsonPath))
172
+ return false;
173
+ try {
174
+ const raw = readFileSync(ndjsonPath, 'utf8');
175
+ const lines = raw.split('\n');
176
+ for (let i = lines.length - 1; i >= 0; i--) {
177
+ const line = lines[i];
178
+ if (!line || !line.trim())
179
+ continue;
180
+ try {
181
+ const parsed = JSON.parse(line);
182
+ if (parsed && typeof parsed === 'object' &&
183
+ (parsed.type === 'done' || parsed.type === 'error')) {
184
+ return true;
185
+ }
186
+ }
187
+ catch {
188
+ // last non-empty line corrupt — treat as no terminal event
189
+ }
190
+ return false;
191
+ }
192
+ return false;
193
+ }
194
+ catch {
195
+ return false;
196
+ }
197
+ }
198
+ writeStatus(status) {
199
+ atomicWrite(runStatusPath(this.dataDir, this.spec.runId, this.spec.botId), status);
200
+ }
201
+ writeHeartbeat() {
202
+ atomicWrite(runHeartbeatPath(this.dataDir, this.spec.runId, this.spec.botId), String(Math.floor(Date.now() / 1000)));
203
+ }
204
+ checkStopSignal() {
205
+ if (this.handlingStop)
206
+ return;
207
+ const signalPath = runStopSignalPath(this.dataDir, this.spec.runId, this.spec.botId);
208
+ if (!existsSync(signalPath))
209
+ return;
210
+ this.handlingStop = true;
211
+ if (this.child && this.child.exitCode === null) {
212
+ this.child.kill('SIGTERM');
213
+ setTimeout(() => {
214
+ if (this.child && this.child.exitCode === null) {
215
+ this.child.kill('SIGKILL');
216
+ }
217
+ }, STOP_GRACE_MS);
218
+ }
219
+ }
220
+ cleanup() {
221
+ if (this.heartbeatTimer) {
222
+ clearInterval(this.heartbeatTimer);
223
+ this.heartbeatTimer = null;
224
+ }
225
+ if (this.stopPollTimer) {
226
+ clearInterval(this.stopPollTimer);
227
+ this.stopPollTimer = null;
228
+ }
229
+ if (this.eventTailTimer) {
230
+ clearInterval(this.eventTailTimer);
231
+ this.eventTailTimer = null;
232
+ }
233
+ }
234
+ }
235
+ export function validateRunCwd(specCwd) {
236
+ return existsSync(specCwd);
237
+ }
@@ -0,0 +1,21 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ /**
4
+ * True when the module is the process entry point. npm installs bins as symlinks, so argv[1]
5
+ * is the symlink while import.meta.url is the resolved file; compare real paths.
6
+ */
7
+ export function isEntryModule(importMetaUrl, argv1 = process.argv[1]) {
8
+ if (argv1 === undefined)
9
+ return false;
10
+ const self = fileURLToPath(importMetaUrl);
11
+ if (argv1 === self)
12
+ return true;
13
+ try {
14
+ return realpathSync(argv1) === realpathSync(self);
15
+ }
16
+ catch (error) {
17
+ if (error.code === 'ENOENT')
18
+ return false;
19
+ throw error;
20
+ }
21
+ }
@@ -0,0 +1,99 @@
1
+ import * as fs from 'node:fs';
2
+ import { basename, dirname, join } from 'node:path';
3
+ export const NDJSON_ROTATION_DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
4
+ export const NDJSON_ROTATION_DEFAULT_MAX_FILES = 5;
5
+ function normalizeLine(line) {
6
+ return line.endsWith('\n') ? line : `${line}\n`;
7
+ }
8
+ function overflowSegmentPath(path, maxFiles) {
9
+ return `${path}.${maxFiles}`;
10
+ }
11
+ function rotatedSegmentPath(path, index) {
12
+ return `${path}.${index}`;
13
+ }
14
+ function appendAndMaybeSync(path, line, options) {
15
+ options.fsImpl.appendFileSync(path, line, 'utf8');
16
+ if (!options.fsync)
17
+ return;
18
+ const fd = options.fsImpl.openSync(path, 'a');
19
+ try {
20
+ options.fsImpl.fsyncSync(fd);
21
+ }
22
+ finally {
23
+ options.fsImpl.closeSync(fd);
24
+ }
25
+ }
26
+ function rotateSegments(path, options) {
27
+ const completed = [];
28
+ try {
29
+ for (let index = options.maxFiles - 1; index >= 1; index -= 1) {
30
+ const from = rotatedSegmentPath(path, index);
31
+ if (!options.fsImpl.existsSync(from))
32
+ continue;
33
+ const to = rotatedSegmentPath(path, index + 1);
34
+ options.fsImpl.renameSync(from, to);
35
+ completed.push({ from, to });
36
+ }
37
+ options.fsImpl.renameSync(path, rotatedSegmentPath(path, 1));
38
+ completed.push({ from: path, to: rotatedSegmentPath(path, 1) });
39
+ const overflowPath = overflowSegmentPath(path, options.maxFiles);
40
+ if (options.fsImpl.existsSync(overflowPath)) {
41
+ options.fsImpl.unlinkSync(overflowPath);
42
+ }
43
+ }
44
+ catch (error) {
45
+ for (let index = completed.length - 1; index >= 0; index -= 1) {
46
+ const rename = completed[index];
47
+ if (!rename || !options.fsImpl.existsSync(rename.to))
48
+ continue;
49
+ options.fsImpl.renameSync(rename.to, rename.from);
50
+ }
51
+ throw error;
52
+ }
53
+ }
54
+ export function appendNdjsonLine(path, line, options = {}) {
55
+ const fsImpl = options.fsImpl ?? fs;
56
+ const maxBytes = options.maxBytes ?? NDJSON_ROTATION_DEFAULT_MAX_BYTES;
57
+ const maxFiles = options.maxFiles ?? NDJSON_ROTATION_DEFAULT_MAX_FILES;
58
+ const normalizedLine = normalizeLine(line);
59
+ fsImpl.mkdirSync(dirname(path), { recursive: true });
60
+ const currentSize = fsImpl.existsSync(path) ? fsImpl.statSync(path).size : 0;
61
+ if (currentSize + Buffer.byteLength(normalizedLine) > maxBytes && fsImpl.existsSync(path)) {
62
+ rotateSegments(path, { fsImpl, maxFiles });
63
+ }
64
+ appendAndMaybeSync(path, normalizedLine, { fsImpl, fsync: options.fsync ?? false });
65
+ }
66
+ export function listNdjsonSegments(path, options = {}) {
67
+ const fsImpl = options.fsImpl ?? fs;
68
+ const dir = dirname(path);
69
+ if (!fsImpl.existsSync(dir))
70
+ return [];
71
+ const name = basename(path);
72
+ const entries = fsImpl.readdirSync(dir)
73
+ .map((entry) => entry.toString())
74
+ .filter((entry) => entry === name || entry.startsWith(`${name}.`));
75
+ const rotated = entries
76
+ .filter((entry) => entry !== name)
77
+ .map((entry) => ({
78
+ entry,
79
+ suffix: Number.parseInt(entry.slice(name.length + 1), 10),
80
+ }))
81
+ .filter((entry) => Number.isFinite(entry.suffix))
82
+ .sort((a, b) => b.suffix - a.suffix)
83
+ .map((entry) => join(dir, entry.entry));
84
+ const active = entries.includes(name) ? [path] : [];
85
+ return [...rotated, ...active];
86
+ }
87
+ export function readNdjsonSegments(path, options = {}) {
88
+ const fsImpl = options.fsImpl ?? fs;
89
+ const lines = [];
90
+ for (const segment of listNdjsonSegments(path, { fsImpl })) {
91
+ const raw = fsImpl.readFileSync(segment, 'utf8');
92
+ for (const line of raw.split('\n')) {
93
+ if (!line)
94
+ continue;
95
+ lines.push(line);
96
+ }
97
+ }
98
+ return lines;
99
+ }
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@zyaochen/weaverbird",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Feishu (Lark) bot that runs Claude Code / Codex CLI on your own machine",
5
+ "license": "MIT",
6
+ "author": "Ziyao Chen",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/zyaochen/weaverbird.git"
10
+ },
11
+ "homepage": "https://github.com/zyaochen/weaverbird#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/zyaochen/weaverbird/issues"
14
+ },
15
+ "keywords": [
16
+ "feishu",
17
+ "lark",
18
+ "bot",
19
+ "claude-code",
20
+ "codex",
21
+ "agent"
22
+ ],
23
+ "type": "module",
24
+ "workspaces": [
25
+ "packages/*",
26
+ "apps/*"
27
+ ],
28
+ "bin": {
29
+ "wb-bot": "./dist/apps/wb-bot/src/main.js",
30
+ "wb-bot-multi": "./dist/apps/wb-bot/src/multi/main.js",
31
+ "wb-cli": "./dist/apps/wb-cli/src/main.js"
32
+ },
33
+ "files": [
34
+ "dist/apps/**/*.js",
35
+ "dist/packages/**/*.js",
36
+ "README.md",
37
+ "README.en.md",
38
+ "LICENSE",
39
+ "apps/wb-bot/README.md"
40
+ ],
41
+ "scripts": {
42
+ "build": "tsc -p tsconfig.json",
43
+ "build:pkg": "node -e \"import('node:fs').then((fs) => fs.rmSync('dist', { recursive: true, force: true }))\" && tsc -p tsconfig.build.json",
44
+ "prepack": "npm run build:pkg",
45
+ "typecheck": "tsc --noEmit -p tsconfig.json",
46
+ "test": "vitest run",
47
+ "test:e2e": "vitest run --config vitest.e2e.config.ts",
48
+ "test:all": "vitest run --config vitest.all.config.ts",
49
+ "dev": "tsx apps/wb-cli/src/main.ts",
50
+ "wb-bot:dev": "tsx apps/wb-bot/src/main.ts",
51
+ "e2e:preflight:env": "tsx apps/wb-bot/src/e2e/preflight-main.ts",
52
+ "audit-pipe": "tsx packages/core/src/audit-pipe/audit-pipe-main.ts",
53
+ "run-registry": "tsx packages/core/src/run-registry/run-registry-main.ts",
54
+ "lint:codes": "tsx scripts/lint-error-codes.ts"
55
+ },
56
+ "dependencies": {
57
+ "@larksuiteoapi/node-sdk": "^1.65.0",
58
+ "better-sqlite3": "^11.0.0",
59
+ "dotenv": "^16.4.0",
60
+ "pino": "^9.0.0",
61
+ "pino-pretty": "^13.1.3",
62
+ "pino-roll": "^4.0.0",
63
+ "zod": "^3.23.0"
64
+ },
65
+ "devDependencies": {
66
+ "@types/node": "^22.0.0",
67
+ "tsx": "^4.19.1",
68
+ "typescript": "^5.6.3",
69
+ "vitest": "^2.1.4"
70
+ },
71
+ "engines": {
72
+ "node": ">=22.0.0"
73
+ },
74
+ "publishConfig": {
75
+ "access": "public",
76
+ "provenance": true
77
+ }
78
+ }