@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,75 @@
1
+ import { createRunRegistryWriter, RunQuerySchema } from '../../../../packages/core/src/run-registry/index.js';
2
+ export function parseHistoryArgs(argv) {
3
+ const query = {};
4
+ let json = false;
5
+ let allCaptains = false;
6
+ for (let index = 0; index < argv.length; index += 1) {
7
+ const arg = argv[index] ?? '';
8
+ const next = argv[index + 1];
9
+ if (arg === '--json') {
10
+ json = true;
11
+ continue;
12
+ }
13
+ if (arg === '--all-captains') {
14
+ allCaptains = true;
15
+ continue;
16
+ }
17
+ if (arg === '--keyword' && next) {
18
+ query['keyword'] = next;
19
+ index += 1;
20
+ continue;
21
+ }
22
+ if (arg === '--status' && next) {
23
+ query['status'] = next;
24
+ index += 1;
25
+ continue;
26
+ }
27
+ if (arg === '--agent' && next) {
28
+ query['agent'] = next;
29
+ index += 1;
30
+ continue;
31
+ }
32
+ if (arg === '--after' && next) {
33
+ query['after'] = next;
34
+ index += 1;
35
+ continue;
36
+ }
37
+ if (arg === '--before' && next) {
38
+ query['before'] = next;
39
+ index += 1;
40
+ continue;
41
+ }
42
+ if (arg === '--limit' && next) {
43
+ query['limit'] = Number.parseInt(next, 10);
44
+ index += 1;
45
+ continue;
46
+ }
47
+ if (arg === '--cursor' && next) {
48
+ query['cursor'] = next;
49
+ index += 1;
50
+ }
51
+ }
52
+ return { query: RunQuerySchema.parse(query), json, allCaptains };
53
+ }
54
+ function renderTable(runs) {
55
+ if (runs.length === 0)
56
+ return '(no runs)\n';
57
+ return runs.map((run) => `${run.run_id}\t${run.status}\t${run.agent}\t${run.cwd}\t${run.created_at}`).join('\n') + '\n';
58
+ }
59
+ export async function historyCommand(argv) {
60
+ const { query, json, allCaptains } = parseHistoryArgs(argv);
61
+ const writer = createRunRegistryWriter();
62
+ const result = await writer.queryRuns(query);
63
+ if (json) {
64
+ for (const run of result.runs) {
65
+ process.stdout.write(`${JSON.stringify({ ...run, _aggregate: allCaptains ? 'all-captains' : 'current' })}\n`);
66
+ }
67
+ return 0;
68
+ }
69
+ process.stdout.write(renderTable(result.runs));
70
+ if (allCaptains)
71
+ process.stderr.write('view=all-captains\n');
72
+ if (result.next_cursor)
73
+ process.stderr.write(`next_cursor=${result.next_cursor}\n`);
74
+ return 0;
75
+ }
@@ -0,0 +1,24 @@
1
+ import { createRunRegistryWriter } from '../../../../packages/core/src/run-registry/index.js';
2
+ // Reads all runs (across every captain) from the Run Registry and prints a compact
3
+ // captain-oriented digest. This is the cli-side aggregate view the PRD anchors to
4
+ // `wb list --all-captains`; we do not do a per-captain split yet — just a newest-first
5
+ // cross-captain run listing so the author can spot drift across bots in one pulse.
6
+ export async function listCommand(_argv, _opts = {}) {
7
+ const writer = createRunRegistryWriter();
8
+ let result;
9
+ try {
10
+ result = await writer.queryRuns({ limit: 50 });
11
+ }
12
+ catch (error) {
13
+ process.stderr.write(`list --all-captains query failed: ${error instanceof Error ? error.message : String(error)}\n`);
14
+ return 2;
15
+ }
16
+ const runs = result.runs;
17
+ if (runs.length === 0) {
18
+ process.stdout.write('(no runs across captains)\n');
19
+ return 0;
20
+ }
21
+ const lines = runs.map((run) => `${run.run_id}\t${run.status}\t${run.agent}\t${run.cwd}\t${run.created_at}`);
22
+ process.stdout.write(`${lines.join('\n')}\n`);
23
+ return 0;
24
+ }
@@ -0,0 +1,122 @@
1
+ import { existsSync, readFileSync, statSync, openSync, readSync, closeSync, watch } from 'node:fs';
2
+ import { readdirSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { runHeartbeatPath, runDir as runPath, runsRootDir, resolveDataDir } from '../../../../packages/core/src/paths.js';
5
+ function getDataDir() {
6
+ return resolveDataDir({ dataDir: process.env['WB_DATA_DIR'] });
7
+ }
8
+ function findLastActiveRunDir() {
9
+ const dataDir = getDataDir();
10
+ const runsDir = runsRootDir(dataDir);
11
+ if (!existsSync(runsDir))
12
+ return null;
13
+ let best = null;
14
+ try {
15
+ for (const botId of readdirSync(runsDir)) {
16
+ const botDir = join(runsDir, botId);
17
+ if (!statSync(botDir).isDirectory())
18
+ continue;
19
+ for (const runId of readdirSync(botDir)) {
20
+ const runDir = join(botDir, runId);
21
+ if (!statSync(runDir).isDirectory())
22
+ continue;
23
+ const hbPath = runHeartbeatPath(dataDir, runId, botId);
24
+ let mtime = 0;
25
+ try {
26
+ mtime = parseInt(readFileSync(hbPath, 'utf8').trim(), 10) * 1000;
27
+ }
28
+ catch {
29
+ try {
30
+ mtime = statSync(runDir).mtimeMs;
31
+ }
32
+ catch { /* ok */ }
33
+ }
34
+ if (!best || mtime > best.mtime)
35
+ best = { dir: runDir, mtime };
36
+ }
37
+ }
38
+ }
39
+ catch { /* ok */ }
40
+ return best?.dir ?? null;
41
+ }
42
+ function resolveLogFile(runDir) {
43
+ const typescript = join(runDir, 'typescript.log');
44
+ if (existsSync(typescript))
45
+ return typescript;
46
+ const output = join(runDir, 'output.log');
47
+ if (existsSync(output))
48
+ return output;
49
+ return null;
50
+ }
51
+ export function logsCommand(args) {
52
+ let runDir;
53
+ if (args.runId) {
54
+ const dataDir = getDataDir();
55
+ const runsDir = runsRootDir(dataDir);
56
+ // search across botIds
57
+ runDir = null;
58
+ try {
59
+ for (const botId of readdirSync(runsDir)) {
60
+ const candidate = runPath(dataDir, args.runId, botId);
61
+ if (existsSync(candidate) && statSync(candidate).isDirectory()) {
62
+ runDir = candidate;
63
+ break;
64
+ }
65
+ }
66
+ }
67
+ catch { /* ok */ }
68
+ }
69
+ else {
70
+ runDir = findLastActiveRunDir();
71
+ }
72
+ if (!runDir) {
73
+ process.stderr.write('No run directory found. Use --run-id or ensure WB_DATA_DIR is set.\n');
74
+ return 1;
75
+ }
76
+ const logFile = resolveLogFile(runDir);
77
+ if (!logFile) {
78
+ process.stderr.write(`No log file in ${runDir}\n`);
79
+ return 1;
80
+ }
81
+ if (args.follow) {
82
+ return followFile(logFile);
83
+ }
84
+ const content = readFileSync(logFile, 'utf8');
85
+ const lines = content.split('\n');
86
+ const start = args.tail > 0 ? Math.max(0, lines.length - args.tail) : 0;
87
+ process.stdout.write(lines.slice(start).join('\n'));
88
+ if (!content.endsWith('\n'))
89
+ process.stdout.write('\n');
90
+ return 0;
91
+ }
92
+ function followFile(path) {
93
+ let offset = 0;
94
+ try {
95
+ offset = statSync(path).size;
96
+ }
97
+ catch { /* start from 0 */ }
98
+ const read = () => {
99
+ try {
100
+ const size = statSync(path).size;
101
+ if (size <= offset)
102
+ return;
103
+ const fd = openSync(path, 'r');
104
+ const buf = Buffer.alloc(size - offset);
105
+ readSync(fd, buf, 0, buf.length, offset);
106
+ closeSync(fd);
107
+ offset = size;
108
+ process.stdout.write(buf);
109
+ }
110
+ catch { /* file may not exist yet */ }
111
+ };
112
+ read();
113
+ const watcher = watch(path, { persistent: true }, () => read());
114
+ const timer = setInterval(read, 1000);
115
+ process.on('SIGINT', () => {
116
+ watcher.close();
117
+ clearInterval(timer);
118
+ process.exit(0);
119
+ });
120
+ // Keep process alive
121
+ return 0;
122
+ }
@@ -0,0 +1,50 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createRunRegistryWriter, RUN_REGISTRY_ERROR_CODES } from '../../../../packages/core/src/run-registry/index.js';
3
+ export const CLI_INHERIT_FIELDS = ['project', 'cwd', 'scope', 'agent', 'home_group_id', 'entry_form'];
4
+ export function buildCliInheritedRun(fromRun, newRunId = randomUUID()) {
5
+ return {
6
+ fromRunId: fromRun.run_id,
7
+ newRunId,
8
+ inherited: {
9
+ project: fromRun.project,
10
+ cwd: fromRun.cwd,
11
+ scope: fromRun.scope,
12
+ agent: fromRun.agent,
13
+ home_group_id: fromRun.home_group_id,
14
+ entry_form: fromRun.entry_form,
15
+ },
16
+ };
17
+ }
18
+ export async function resumeInheritCommand(argv) {
19
+ const inheritIdx = argv.indexOf('--inherit');
20
+ const runId = inheritIdx >= 0 ? argv[inheritIdx + 1] : undefined;
21
+ if (inheritIdx < 0 || !runId) {
22
+ process.stderr.write('Usage: wb-cli resume --inherit <run_id>\n');
23
+ return 1;
24
+ }
25
+ const writer = createRunRegistryWriter();
26
+ let fromRun;
27
+ try {
28
+ fromRun = await writer.findByRunId(runId);
29
+ }
30
+ catch (error) {
31
+ process.stderr.write(`resume --inherit lookup failed: ${error instanceof Error ? error.message : String(error)}\n`);
32
+ return 2;
33
+ }
34
+ if (!fromRun) {
35
+ process.stderr.write(`${RUN_REGISTRY_ERROR_CODES.E_INHERIT_NOT_FOUND}: run ${runId} not found in registry\n`);
36
+ return 2;
37
+ }
38
+ const inherited = buildCliInheritedRun(fromRun);
39
+ process.stdout.write([
40
+ `♻️ Inherited run ${runId}`,
41
+ `new_run_id=${inherited.newRunId}`,
42
+ `agent=${inherited.inherited.agent}`,
43
+ `cwd=${inherited.inherited.cwd}`,
44
+ `scope=${inherited.inherited.scope}`,
45
+ `project=${inherited.inherited.project ?? '-'}`,
46
+ `home_group_id=${inherited.inherited.home_group_id ?? '-'}`,
47
+ `entry_form=${inherited.inherited.entry_form}`,
48
+ ].join('\n') + '\n');
49
+ return 0;
50
+ }
@@ -0,0 +1,75 @@
1
+ import { readdirSync, readFileSync, statSync, existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { runHeartbeatPath, runSpecPath, runStatusPath, runsRootDir, resolveDataDir } from '../../../../packages/core/src/paths.js';
4
+ function getDataDir() {
5
+ return resolveDataDir({ dataDir: process.env['WB_DATA_DIR'] });
6
+ }
7
+ export function listRuns() {
8
+ const dataDir = getDataDir();
9
+ const runsDir = runsRootDir(dataDir);
10
+ if (!existsSync(runsDir))
11
+ return [];
12
+ const entries = [];
13
+ const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
14
+ try {
15
+ for (const botId of readdirSync(runsDir)) {
16
+ const botDir = join(runsDir, botId);
17
+ if (!statSync(botDir).isDirectory())
18
+ continue;
19
+ for (const runId of readdirSync(botDir)) {
20
+ const runDir = join(botDir, runId);
21
+ if (!statSync(runDir).isDirectory())
22
+ continue;
23
+ const specPath = runSpecPath(dataDir, runId, botId);
24
+ const statusPath = runStatusPath(dataDir, runId, botId);
25
+ const hbPath = runHeartbeatPath(dataDir, runId, botId);
26
+ let agentId = 'unknown';
27
+ let startedAt = '';
28
+ try {
29
+ const spec = JSON.parse(readFileSync(specPath, 'utf8'));
30
+ agentId = spec.agentId ?? 'unknown';
31
+ startedAt = spec.startedAt ?? '';
32
+ }
33
+ catch { /* spec may not exist */ }
34
+ let status = 'unknown';
35
+ try {
36
+ status = readFileSync(statusPath, 'utf8').trim();
37
+ }
38
+ catch { /* ok */ }
39
+ let lastActive = 0;
40
+ try {
41
+ const hb = parseInt(readFileSync(hbPath, 'utf8').trim(), 10) * 1000;
42
+ if (!isNaN(hb))
43
+ lastActive = hb;
44
+ }
45
+ catch { /* ok */ }
46
+ if (!lastActive) {
47
+ try {
48
+ lastActive = statSync(runDir).mtimeMs;
49
+ }
50
+ catch { /* ok */ }
51
+ }
52
+ if (lastActive < sevenDaysAgo)
53
+ continue;
54
+ entries.push({ runId, botId, agentId, status, startedAt, lastActive });
55
+ }
56
+ }
57
+ }
58
+ catch { /* top-level read failure */ }
59
+ entries.sort((a, b) => b.lastActive - a.lastActive);
60
+ return entries;
61
+ }
62
+ export function runsCommand() {
63
+ const entries = listRuns();
64
+ if (entries.length === 0) {
65
+ process.stderr.write('No runs found in the last 7 days.\n');
66
+ return 0;
67
+ }
68
+ const mostActive = entries[0].runId;
69
+ for (const e of entries) {
70
+ const marker = e.runId === mostActive ? ' ★' : '';
71
+ const short = e.runId.length > 20 ? e.runId.slice(0, 20) : e.runId;
72
+ process.stdout.write(`${short}\t${e.botId}\t${e.agentId}\t${e.status}\t${e.startedAt || '-'}${marker}\n`);
73
+ }
74
+ return 0;
75
+ }
@@ -0,0 +1,35 @@
1
+ import { existsSync } from 'node:fs';
2
+ import BetterSqlite3 from 'better-sqlite3';
3
+ import { botDbPath, resolveDataDir } from '../../../../packages/core/src/paths.js';
4
+ function readThreadBinding(dbPath, botId, userOpenId, threadId) {
5
+ if (!existsSync(dbPath))
6
+ return null;
7
+ let db = null;
8
+ try {
9
+ db = new BetterSqlite3(dbPath);
10
+ // PRAGMA query_only prevents accidental writes; no schema migration is triggered
11
+ db.pragma('query_only = ON');
12
+ const row = db
13
+ .prepare('SELECT agent_id, cwd FROM thread_binding WHERE bot_id = ? AND user_open_id = ? AND thread_id = ?')
14
+ .get(botId, userOpenId, threadId);
15
+ return row ? { agentId: row.agent_id, cwd: row.cwd } : null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ finally {
21
+ db?.close();
22
+ }
23
+ }
24
+ export function statusCommand(opts = {}) {
25
+ const dataDir = resolveDataDir({ dataDir: opts.dataDir });
26
+ const botId = opts.botId ?? process.env['BOT_ID'] ?? 'default';
27
+ const userOpenId = opts.userOpenId ?? process.env['WB_USER_OPEN_ID'] ?? 'cli';
28
+ const threadId = opts.threadId ?? process.env['WB_THREAD_ID'] ?? 'cli';
29
+ const binding = readThreadBinding(botDbPath(dataDir), botId, userOpenId, threadId);
30
+ const agent = binding?.agentId ?? 'claude-code';
31
+ const cwd = binding?.cwd ?? '-';
32
+ const status = binding ? 'bound' : 'unknown';
33
+ process.stdout.write(`cwd=${cwd}\nagent=${agent}\nstatus=${status}\n`);
34
+ return 0;
35
+ }
@@ -0,0 +1,73 @@
1
+ import { IpcClient, ReverseChannelError } from '../../../../packages/core/src/index.js';
2
+ export function parseWatchArgs(argv) {
3
+ const options = {};
4
+ for (let i = 0; i < argv.length; i += 1) {
5
+ const arg = argv[i] ?? '';
6
+ const next = argv[i + 1];
7
+ if (arg === '--session' && next) {
8
+ options.sessionId = next;
9
+ i += 1;
10
+ continue;
11
+ }
12
+ if ((arg === '-t' || arg === '--timeout') && next) {
13
+ options.durationMs = Number.parseInt(next, 10) * 1000;
14
+ i += 1;
15
+ continue;
16
+ }
17
+ if (!options.sessionId && arg && !arg.startsWith('-')) {
18
+ options.sessionId = arg;
19
+ }
20
+ }
21
+ return options;
22
+ }
23
+ /**
24
+ * M12-D (2026-08-04 owner-authorized, PRD §4.2 "wb-cli watch" 平价):
25
+ * 长连 reverse-channel IPC socket,把 server 推过来的事件回显到 stdout。
26
+ * 这条命令不动卡片、不推桌面通知 (D' 边界:不接 osascript/notify-send);
27
+ * 真正把 stderr 送到用户端的通知工具包是 wrapper 的事, wb-cli 只保证数据流。
28
+ *
29
+ * 若 socket 不存在 => 返回 3,表示 "没有正在跑的 bot"; 调用 wrapper 应解读成
30
+ * "bot offline"。
31
+ */
32
+ export async function watchCommand(argv) {
33
+ const options = parseWatchArgs(argv);
34
+ const client = new IpcClient();
35
+ let connection = null;
36
+ const close = async () => {
37
+ if (!connection)
38
+ return;
39
+ try {
40
+ await connection.close();
41
+ }
42
+ catch {
43
+ // swallow close errors - process is shutting down
44
+ }
45
+ connection = null;
46
+ };
47
+ process.once('SIGINT', () => { void close().then(() => process.exit(130)); });
48
+ try {
49
+ connection = await client.openSession(options.sessionId ? { runId: options.sessionId } : {});
50
+ }
51
+ catch (error) {
52
+ if (error instanceof ReverseChannelError) {
53
+ process.stderr.write(`watch connect failed: ${error.message}\n`);
54
+ return 3;
55
+ }
56
+ process.stderr.write(`watch connect failed: ${error instanceof Error ? error.message : String(error)}\n`);
57
+ return 3;
58
+ }
59
+ const deadline = options.durationMs ? Date.now() + options.durationMs : Number.POSITIVE_INFINITY;
60
+ process.stdout.write(`watching session=${options.sessionId ?? '(all)'}\n`);
61
+ while (Date.now() < deadline) {
62
+ await new Promise((resolvePromise) => {
63
+ const timeout = setTimeout(() => resolvePromise(), 1000);
64
+ connection?.on('push', (message) => {
65
+ clearTimeout(timeout);
66
+ process.stdout.write(`${JSON.stringify(message)}\n`);
67
+ resolvePromise();
68
+ });
69
+ });
70
+ }
71
+ await close();
72
+ return 0;
73
+ }