@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,61 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { finalizeRun } from '../../../../packages/core/src/run-observability/finalizer.js';
4
+ import { detectExitError } from '../../../../packages/core/src/run-observability/exit-code-detector.js';
5
+ import { pushAlert } from '../../../../packages/core/src/run-observability/alert-pusher.js';
6
+ export function wireRunObservability(runDir, deps) {
7
+ const refreshLatest = async () => {
8
+ if (!deps.refresher)
9
+ return;
10
+ const entry = deps.store.readEntry();
11
+ if (!entry)
12
+ return;
13
+ const lines = readFileSync(deps.store.progressPath, 'utf8').trim().split('\n').filter(Boolean);
14
+ const latest = lines.length > 0 ? JSON.parse(lines.at(-1)).text : null;
15
+ await deps.refresher.refresh(entry, latest);
16
+ };
17
+ return {
18
+ onStdout(chunk) {
19
+ deps.collector.push('stdout', chunk);
20
+ void refreshLatest();
21
+ },
22
+ onStderr(chunk) {
23
+ deps.collector.push('stderr', chunk);
24
+ void refreshLatest();
25
+ },
26
+ async onExit(input) {
27
+ deps.collector.flush();
28
+ const entry = deps.store.readEntry();
29
+ if (!entry)
30
+ return;
31
+ const nowIso = new Date().toISOString();
32
+ const finalizedEntry = {
33
+ ...entry,
34
+ status: input.status,
35
+ updated_at: nowIso,
36
+ finalized: true,
37
+ cancelled: input.cancelled,
38
+ };
39
+ const lines = readFileSync(join(runDir, 'progress.ndjson'), 'utf8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line).text);
40
+ const alert = detectExitError({
41
+ runId: entry.run_id,
42
+ sessionId: entry.session_id,
43
+ status: input.status,
44
+ cancelled: input.cancelled,
45
+ elapsedS: input.elapsedS,
46
+ exitMeta: input.exitMeta,
47
+ });
48
+ if (alert) {
49
+ await pushAlert(alert, deps.alertContext);
50
+ }
51
+ await finalizeRun(finalizedEntry, lines, {
52
+ client: deps.finalizerClient,
53
+ dataDir: deps.dataDir,
54
+ nowIso,
55
+ onFinalized: () => {
56
+ deps.store.saveEntry(finalizedEntry);
57
+ },
58
+ });
59
+ },
60
+ };
61
+ }
@@ -0,0 +1,18 @@
1
+ const BOT_ID_PATTERN = /^[a-z][a-z0-9_-]{0,31}$/;
2
+ export function validateBotId(input) {
3
+ if (typeof input !== 'string')
4
+ return { ok: false, reason: 'botId 必须是 string' };
5
+ if (input.length === 0)
6
+ return { ok: false, reason: 'botId 不能为空' };
7
+ if (input.length > 32)
8
+ return { ok: false, reason: `botId 长度超过 32 (got ${input.length})` };
9
+ if (!BOT_ID_PATTERN.test(input))
10
+ return { ok: false, reason: 'botId 必须匹配 /^[a-z][a-z0-9_-]{0,31}$/ (lowercase, 字母开头, 含字母数字 _ -)' };
11
+ return { ok: true };
12
+ }
13
+ export function assertValidBotId(input, context) {
14
+ const result = validateBotId(input);
15
+ if (!result.ok)
16
+ throw new Error(`invalid botId at ${context}: ${result.reason}`);
17
+ return input;
18
+ }
@@ -0,0 +1,72 @@
1
+ import { existsSync, realpathSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { relative, resolve, sep } from 'node:path';
4
+ export const DEFAULT_CWD_ALLOWLIST = [
5
+ '$HOME/projects',
6
+ '$HOME/code',
7
+ '$HOME/work',
8
+ '/tmp',
9
+ '/private/tmp',
10
+ ];
11
+ export const CWD_DENYLIST = [
12
+ '/etc',
13
+ '/proc',
14
+ '/sys',
15
+ '/dev',
16
+ '/root',
17
+ '$HOME/.ssh',
18
+ '$HOME/.gnupg',
19
+ '$HOME/.aws',
20
+ '$HOME/.docker',
21
+ '$HOME/.kube',
22
+ '$HOME/.netrc',
23
+ '$HOME/.config/gh',
24
+ '$HOME/.weaverbird',
25
+ '$HOME/Library/Keychains',
26
+ '/Library/Keychains',
27
+ '$HOME/Library/Cookies',
28
+ ];
29
+ function expandHome(path, home) {
30
+ if (path === '~')
31
+ return home;
32
+ if (path.startsWith('~/'))
33
+ return `${home}${path.slice(1)}`;
34
+ return path.replace('$HOME', home);
35
+ }
36
+ function normalizePath(path) {
37
+ return process.platform === 'darwin' || process.platform === 'win32' ? path.toLowerCase() : path;
38
+ }
39
+ function canonicalizePath(path) {
40
+ return existsSync(path) ? realpathSync(path) : resolve(path);
41
+ }
42
+ function isWithin(base, target) {
43
+ const rel = relative(base, target);
44
+ return rel === '' || (!rel.startsWith('..') && !rel.startsWith(sep));
45
+ }
46
+ export function validateCwd(input, allowlist = DEFAULT_CWD_ALLOWLIST, denylist = CWD_DENYLIST) {
47
+ if (!input || input.trim() === '')
48
+ return { ok: false, reason: 'empty path' };
49
+ const home = homedir();
50
+ const resolved = resolve(expandHome(input.trim(), home));
51
+ if (!existsSync(resolved))
52
+ return { ok: false, reason: 'path does not exist' };
53
+ let canonical = '';
54
+ try {
55
+ canonical = realpathSync(resolved);
56
+ }
57
+ catch {
58
+ return { ok: false, reason: 'cannot resolve realpath' };
59
+ }
60
+ const target = normalizePath(canonical);
61
+ for (const entry of denylist) {
62
+ const denied = normalizePath(canonicalizePath(expandHome(entry, home)));
63
+ if (isWithin(denied, target))
64
+ return { ok: false, reason: `denied (protected): ${entry}` };
65
+ }
66
+ for (const entry of allowlist) {
67
+ const allowed = normalizePath(canonicalizePath(expandHome(entry, home)));
68
+ if (isWithin(allowed, target))
69
+ return { ok: true, path: canonical };
70
+ }
71
+ return { ok: false, reason: 'not in allowlist; use /cwd-add to allow a prefix' };
72
+ }
@@ -0,0 +1,94 @@
1
+ const SECRET_PATTERNS = [
2
+ /_TOKEN$/,
3
+ /_SECRET$/,
4
+ /_KEY$/,
5
+ /_PASSWORD$/,
6
+ /^LARK_/,
7
+ /^FEISHU_/,
8
+ /^AWS_/,
9
+ /^GITHUB_TOKEN$/,
10
+ /^SSH_/,
11
+ /^GPG_/,
12
+ /^GCP_/,
13
+ /^WB_/,
14
+ /^BOT_ID$/,
15
+ ];
16
+ const DEFAULT_BASE_ENV = [
17
+ 'PATH',
18
+ 'HOME',
19
+ 'USER',
20
+ 'LOGNAME',
21
+ 'SHELL',
22
+ 'PWD',
23
+ 'LANG',
24
+ 'LC_ALL',
25
+ 'TERM',
26
+ 'TMPDIR',
27
+ 'NO_COLOR',
28
+ 'FORCE_COLOR',
29
+ 'SSL_CERT_FILE',
30
+ 'NODE_EXTRA_CA_CERTS',
31
+ 'CLAUDE_CONFIG_DIR',
32
+ 'XDG_CONFIG_HOME',
33
+ 'XDG_DATA_HOME',
34
+ 'XDG_CACHE_HOME',
35
+ ];
36
+ const WB_RUNNER_ALLOW = [
37
+ 'WB_DATA_DIR',
38
+ 'WB_HEARTBEAT_STALE_MS',
39
+ 'WB_PUSH_THRESHOLD_MS',
40
+ 'WB_TOOL_PROGRESS_INTERVAL_MS',
41
+ ];
42
+ export function filterBaseEnv(input) {
43
+ const output = {};
44
+ for (const [key, value] of Object.entries(input)) {
45
+ if (value === undefined)
46
+ continue;
47
+ if (SECRET_PATTERNS.some((pattern) => pattern.test(key)))
48
+ continue;
49
+ if (DEFAULT_BASE_ENV.includes(key) || key.startsWith('LC_')) {
50
+ output[key] = value;
51
+ }
52
+ }
53
+ return output;
54
+ }
55
+ export function buildFilteredEnv(target, input, passthrough) {
56
+ const env = filterBaseEnv(input);
57
+ if (target === 'wb-runner') {
58
+ for (const key of WB_RUNNER_ALLOW) {
59
+ const value = input[key];
60
+ if (value !== undefined)
61
+ env[key] = value;
62
+ }
63
+ }
64
+ if (passthrough) {
65
+ for (const key of passthrough) {
66
+ const value = input[key];
67
+ if (value !== undefined)
68
+ env[key] = value;
69
+ }
70
+ }
71
+ return env;
72
+ }
73
+ export function buildAgentEnv(input, passthrough) {
74
+ const env = filterBaseEnv(input);
75
+ for (const key of passthrough) {
76
+ const value = input[key];
77
+ if (value !== undefined)
78
+ env[key] = value;
79
+ }
80
+ return env;
81
+ }
82
+ const CLAUDE_OAUTH_KEYS = ['ANTHROPIC_API_KEY', 'ANTHROPIC_BASE_URL'];
83
+ const CLAUDE_MODEL_KEYS = ['ANTHROPIC_MODEL'];
84
+ export function shouldPreferClaudeOAuth(status) {
85
+ return status?.loggedIn === true && status.authMethod === 'oauth_token';
86
+ }
87
+ export function buildClaudeAgentEnv(input, preferOAuth) {
88
+ const passthrough = preferOAuth ? CLAUDE_MODEL_KEYS : [...CLAUDE_OAUTH_KEYS, ...CLAUDE_MODEL_KEYS];
89
+ return buildAgentEnv(input, passthrough);
90
+ }
91
+ export function attachEnvFilter(agent, passthrough) {
92
+ agent.envFilter = (env) => buildAgentEnv(env, passthrough);
93
+ return agent;
94
+ }
@@ -0,0 +1,125 @@
1
+ import { handleAttachRequest } from '../../../../packages/core/src/reverse-channel/attach-handler.js';
2
+ import { REVERSE_CHANNEL_ERROR_CODES, ReverseChannelError, } from '../../../../packages/core/src/reverse-channel/contracts.js';
3
+ import { sendControlSignal } from '../../../../packages/core/src/reverse-channel/ipc-control-handler.js';
4
+ import { resolveCliPid } from '../../../../packages/core/src/reverse-channel/pid-resolver.js';
5
+ const OUTCOME_REASON = {
6
+ attached: undefined,
7
+ mutex_conflict: REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_MUTEX,
8
+ not_found: REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_NOT_FOUND,
9
+ timed_out: REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_TIMEOUT,
10
+ revision_mismatch: REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_MUTEX,
11
+ };
12
+ function attachResultToAck(result, runId) {
13
+ return {
14
+ kind: 'ack',
15
+ command: 'attach',
16
+ run_id: runId,
17
+ ok: result.outcome === 'attached',
18
+ reason: OUTCOME_REASON[result.outcome],
19
+ payload: result,
20
+ };
21
+ }
22
+ function attachThrowToAck(err, runId) {
23
+ if (err instanceof ReverseChannelError) {
24
+ const code = err.code;
25
+ const reason = code === REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_TIMEOUT
26
+ ? REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_TIMEOUT
27
+ : REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_FLUSH_FAILED;
28
+ return {
29
+ kind: 'ack',
30
+ command: 'attach',
31
+ run_id: runId,
32
+ ok: false,
33
+ reason,
34
+ payload: { outcome: 'error', code },
35
+ };
36
+ }
37
+ return {
38
+ kind: 'ack',
39
+ command: 'attach',
40
+ run_id: runId,
41
+ ok: false,
42
+ reason: REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_FLUSH_FAILED,
43
+ payload: {
44
+ outcome: 'error',
45
+ code: 'E_UNKNOWN',
46
+ message: err instanceof Error ? err.message : String(err),
47
+ },
48
+ };
49
+ }
50
+ export function wireUpReverseChannel(ipcServer, captainService, dataDir, selfCaptainId) {
51
+ ipcServer.on('attach', async (msg) => {
52
+ try {
53
+ const result = await handleAttachRequest(captainService, {
54
+ session_id: msg.session_id,
55
+ requester_captain_id: msg.requester_captain_id,
56
+ force: msg.force ?? false,
57
+ requested_at: new Date().toISOString(),
58
+ });
59
+ const sent = ipcServer.send(msg.run_id, attachResultToAck(result, msg.run_id));
60
+ if (!sent) {
61
+ console.warn(`[wire-up] attach ack lost: no connection registered for run_id=${msg.run_id}`);
62
+ }
63
+ }
64
+ catch (err) {
65
+ const sent = ipcServer.send(msg.run_id, attachThrowToAck(err, msg.run_id));
66
+ if (!sent) {
67
+ console.warn(`[wire-up] attach ack lost: no connection registered for run_id=${msg.run_id}`);
68
+ }
69
+ }
70
+ });
71
+ ipcServer.on('control', async (msg) => {
72
+ const session = captainService.listActiveSessions().find((entry) => entry.run_ids.includes(msg.run_id));
73
+ if (session && session.record.captain_id !== selfCaptainId) {
74
+ const sent = ipcServer.send(msg.run_id, {
75
+ kind: 'ack',
76
+ command: msg.command,
77
+ run_id: msg.run_id,
78
+ ok: false,
79
+ reason: REVERSE_CHANNEL_ERROR_CODES.E_CAPTAIN_HANDED_OVER,
80
+ });
81
+ if (!sent) {
82
+ console.warn(`[wire-up] control ack lost: no connection registered for run_id=${msg.run_id}`);
83
+ }
84
+ return;
85
+ }
86
+ const pid = resolveCliPid(dataDir, msg.run_id);
87
+ if (!pid) {
88
+ const sent = ipcServer.send(msg.run_id, {
89
+ kind: 'ack',
90
+ command: msg.command,
91
+ run_id: msg.run_id,
92
+ ok: false,
93
+ reason: REVERSE_CHANNEL_ERROR_CODES.E_REVERSE_AT_RUN_GONE,
94
+ });
95
+ if (!sent) {
96
+ console.warn(`[wire-up] control ack lost: no connection registered for run_id=${msg.run_id}`);
97
+ }
98
+ return;
99
+ }
100
+ try {
101
+ await sendControlSignal(msg.command, pid);
102
+ const sent = ipcServer.send(msg.run_id, {
103
+ kind: 'ack',
104
+ command: msg.command,
105
+ run_id: msg.run_id,
106
+ ok: true,
107
+ });
108
+ if (!sent) {
109
+ console.warn(`[wire-up] control ack lost: no connection registered for run_id=${msg.run_id}`);
110
+ }
111
+ }
112
+ catch {
113
+ const sent = ipcServer.send(msg.run_id, {
114
+ kind: 'ack',
115
+ command: msg.command,
116
+ run_id: msg.run_id,
117
+ ok: false,
118
+ reason: REVERSE_CHANNEL_ERROR_CODES.E_SIGNAL_FAILED,
119
+ });
120
+ if (!sent) {
121
+ console.warn(`[wire-up] control ack lost: no connection registered for run_id=${msg.run_id}`);
122
+ }
123
+ }
124
+ });
125
+ }
@@ -0,0 +1,101 @@
1
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { approvalGateDir, approvalRequestsPath, approvalResolutionPath, resolveDataDir } from '../../../../packages/core/src/index.js';
4
+ export function parseApprovalArgs(argv) {
5
+ const filter = {};
6
+ for (const arg of argv) {
7
+ if (arg === '--all')
8
+ filter.all = true;
9
+ else if (arg === '--pending')
10
+ filter.pending = true;
11
+ else if (arg === '--resolved')
12
+ filter.resolved = true;
13
+ else if (arg === '--expired')
14
+ filter.expired = true;
15
+ else if (arg === '--limit')
16
+ filter.limit = Number.parseInt(argv[argv.indexOf(arg) + 1] ?? '', 10);
17
+ }
18
+ return filter;
19
+ }
20
+ function loadRequests(dataDir) {
21
+ const path = approvalRequestsPath(dataDir);
22
+ if (!existsSync(path))
23
+ return [];
24
+ const lines = readFileSync(path, 'utf8').split('\n').filter(Boolean);
25
+ const out = [];
26
+ for (const line of lines) {
27
+ try {
28
+ const entry = JSON.parse(line);
29
+ if (entry.op === 'request_created' || entry.op === 'request_resolved') {
30
+ if (entry.request)
31
+ out.push(entry.request);
32
+ }
33
+ }
34
+ catch {
35
+ continue;
36
+ }
37
+ }
38
+ return out;
39
+ }
40
+ function loadResolutions(dataDir, requestIds) {
41
+ const dir = approvalGateDir(dataDir);
42
+ if (!existsSync(dir))
43
+ return new Map();
44
+ const out = new Map();
45
+ for (const id of requestIds) {
46
+ const path = approvalResolutionPath(dataDir, id);
47
+ if (!existsSync(path))
48
+ continue;
49
+ try {
50
+ const resolution = JSON.parse(readFileSync(path, 'utf8'));
51
+ out.set(id, resolution);
52
+ }
53
+ catch {
54
+ continue;
55
+ }
56
+ }
57
+ return out;
58
+ }
59
+ /**
60
+ * M12-D (2026-08-04 owner-authorized, PRD §4.2 "wb-cli approval" 平价):
61
+ * 本机 Approval 队列视图:读 approval-requests.ndjson + resolutions/。只做查询,
62
+ * 不做远端审批 API 调用,也不动飞书审批 决策(还是卡片按钮决定)。
63
+ */
64
+ export function approvalCommand(argv) {
65
+ const filter = parseApprovalArgs(argv);
66
+ const dataDir = resolveDataDir({});
67
+ const requests = loadRequests(dataDir);
68
+ if (requests.length === 0) {
69
+ process.stdout.write('(no approval requests)\n');
70
+ return Promise.resolve(0);
71
+ }
72
+ const deduped = new Map();
73
+ for (const request of requests)
74
+ deduped.set(request.requestId, request);
75
+ const resolutions = loadResolutions(dataDir, [...deduped.keys()]);
76
+ const rows = [...deduped.values()]
77
+ .map((request) => ({ ...request, resolved: resolutions.get(request.requestId) }))
78
+ .filter((row) => {
79
+ if (filter.all)
80
+ return true;
81
+ if (filter.pending)
82
+ return row.status === 'pending_dispatch' || row.status === 'pending_approval';
83
+ if (filter.resolved)
84
+ return Boolean(row.resolved);
85
+ if (filter.expired)
86
+ return row.status === 'expired';
87
+ return true;
88
+ })
89
+ .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt))
90
+ .slice(0, filter.limit ?? 50);
91
+ const lines = rows.map((row) => [
92
+ row.createdAt,
93
+ row.requestId.slice(0, 8),
94
+ row.anchor,
95
+ row.status,
96
+ row.resolved?.resolutionReason ?? '-',
97
+ row.userOpenId,
98
+ ].join('\t'));
99
+ process.stdout.write(lines.join('\n') + '\n');
100
+ return Promise.resolve(0);
101
+ }
@@ -0,0 +1,31 @@
1
+ import { IpcClient } from '../../../../packages/core/src/reverse-channel/index.js';
2
+ export async function attachCommand(argv) {
3
+ const sessionId = argv[0];
4
+ if (!sessionId) {
5
+ process.stderr.write('Usage: wb-cli attach <session_id>\n');
6
+ return 1;
7
+ }
8
+ const client = new IpcClient();
9
+ const connection = await client.openSession();
10
+ try {
11
+ await connection.send({ kind: 'hello', run_id: sessionId, pid: process.pid });
12
+ const request = {
13
+ session_id: sessionId,
14
+ requester_captain_id: process.env['BOT_ID'] ?? 'default',
15
+ requested_at: new Date().toISOString(),
16
+ force: argv.includes('--force'),
17
+ };
18
+ const ack = await connection.send({
19
+ kind: 'attach',
20
+ run_id: request.session_id,
21
+ session_id: request.session_id,
22
+ requester_captain_id: request.requester_captain_id,
23
+ force: request.force,
24
+ });
25
+ process.stdout.write(`${JSON.stringify({ session_id: sessionId, ack })}\n`);
26
+ return 0;
27
+ }
28
+ finally {
29
+ await connection.close();
30
+ }
31
+ }
@@ -0,0 +1,71 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { auditMirrorPath, resolveDataDir } from '../../../../packages/core/src/index.js';
3
+ export function parseAuditArgs(argv) {
4
+ const options = {};
5
+ for (let i = 0; i < argv.length; i += 1) {
6
+ const arg = argv[i] ?? '';
7
+ const next = argv[i + 1];
8
+ if (arg === '--limit' && next) {
9
+ options.limit = Number.parseInt(next, 10);
10
+ i += 1;
11
+ continue;
12
+ }
13
+ if (arg === '--since' && next) {
14
+ options.since = next;
15
+ i += 1;
16
+ continue;
17
+ }
18
+ if (arg === '--session-id' && next) {
19
+ options.sessionId = next;
20
+ i += 1;
21
+ continue;
22
+ }
23
+ }
24
+ return options;
25
+ }
26
+ /**
27
+ * M12-D (2026-08-04 owner-authorized, PRD §4.2 "wb-cli audit" 平价):
28
+ * Reads the local audit-mirror.ndjson (W3.1 audit-pipe 持久化层) and prints a
29
+ * tabular summary. 不动远端审计 OpenAPI (红线 specs/w3.1-f17-audit-pipe §20);
30
+ * 远端查询 PRD-要求的"90 天企业审计" 是留 v2, 本命令只看本机镜像。
31
+ */
32
+ export function auditCommand(argv) {
33
+ const opts = parseAuditArgs(argv);
34
+ const dataDir = resolveDataDir({});
35
+ const mirrorPath = auditMirrorPath(dataDir);
36
+ if (!existsSync(mirrorPath)) {
37
+ process.stderr.write(`audit mirror not found at ${mirrorPath}; run a cycle first or check WB_DATA_DIR\n`);
38
+ return Promise.resolve(1);
39
+ }
40
+ const since = opts.since ? Date.parse(opts.since) : null;
41
+ const limit = opts.limit ?? 50;
42
+ const lines = readFileSync(mirrorPath, 'utf8').split('\n').filter((line) => line.trim()).slice(-5000);
43
+ const kept = [];
44
+ for (const line of lines) {
45
+ try {
46
+ const record = JSON.parse(line);
47
+ if (since !== null && Date.parse(String(record['ts'] ?? '')) < since)
48
+ continue;
49
+ if (opts.sessionId && record['session_id'] !== opts.sessionId)
50
+ continue;
51
+ kept.push(record);
52
+ }
53
+ catch {
54
+ continue;
55
+ }
56
+ }
57
+ const out = kept
58
+ .reverse()
59
+ .slice(0, limit)
60
+ .map((record) => [
61
+ record['ts'],
62
+ record['session_id'],
63
+ record['agent_id'],
64
+ record['action'],
65
+ record['env_filter_hit'] ? 'env_hit=1' : 'env_hit=0',
66
+ record['resource'],
67
+ record['run_id'],
68
+ ].join('\t'));
69
+ process.stdout.write(out.length ? out.join('\n') + '\n' : '(no audit entries)\n');
70
+ return Promise.resolve(0);
71
+ }
@@ -0,0 +1,72 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { loadCaptainConfig } from '../../../../packages/core/src/captain/index.js';
5
+ import { SlaTracker } from '../../../../packages/core/src/reverse-channel/sla-tracker.js';
6
+ function metricsPath(homeDir = homedir()) {
7
+ return join(homeDir, '.weaverbird', 'sla-metrics.ndjson');
8
+ }
9
+ function readMetrics(homeDir = homedir()) {
10
+ const path = metricsPath(homeDir);
11
+ if (!existsSync(path))
12
+ return [];
13
+ return readFileSync(path, 'utf8')
14
+ .split('\n')
15
+ .filter((line) => line.trim())
16
+ .map((line) => JSON.parse(line));
17
+ }
18
+ function resolveCaptainBindingPath(homeDir = homedir()) {
19
+ return join(homeDir, '.weaverbird', 'captain-binding.json');
20
+ }
21
+ function readCaptainBinding(homeDir = homedir()) {
22
+ const path = resolveCaptainBindingPath(homeDir);
23
+ if (!existsSync(path))
24
+ return null;
25
+ try {
26
+ return JSON.parse(readFileSync(path, 'utf8'));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ function writeCaptainBinding(captainId, homeDir = homedir()) {
33
+ const path = resolveCaptainBindingPath(homeDir);
34
+ mkdirSync(dirname(path), { recursive: true });
35
+ writeFileSync(path, JSON.stringify({ captain_id: captainId, updated_at: new Date().toISOString() }, null, 2));
36
+ }
37
+ export function captainCommand(argv, opts = {}) {
38
+ if (argv[0] === 'sla') {
39
+ const entries = readMetrics(opts.homeDir);
40
+ const tracker = new SlaTracker(metricsPath(opts.homeDir));
41
+ const summary = tracker.summarize(entries.slice(-100));
42
+ if (argv.includes('--json')) {
43
+ process.stdout.write(`${JSON.stringify(summary)}\n`);
44
+ return 0;
45
+ }
46
+ process.stdout.write([
47
+ `F18 attach P95: ${summary.attach_p95_ms}ms`,
48
+ `F19 echo P95: ${summary.echo_p95_ms}ms`,
49
+ `F21 hit rate: ${Math.round(summary.reverse_at_hit_rate * 100)}%`,
50
+ ].join('\n') + '\n');
51
+ return 0;
52
+ }
53
+ if (argv[0] === 'use') {
54
+ const captainId = argv[1];
55
+ if (!captainId) {
56
+ process.stderr.write('Usage: wb-cli captain use <captain_id>\n');
57
+ return 1;
58
+ }
59
+ writeCaptainBinding(captainId, opts.homeDir);
60
+ process.stdout.write(`captain=${captainId}\n`);
61
+ return 0;
62
+ }
63
+ const config = loadCaptainConfig({ cwd: opts.cwd, homeDir: opts.homeDir });
64
+ const binding = readCaptainBinding(opts.homeDir);
65
+ const lines = ['Known captains:'];
66
+ for (const mapping of config.mapping) {
67
+ const current = binding?.captain_id === mapping.captain_id ? ' (current)' : '';
68
+ lines.push(`- ${mapping.captain_id}${current}`);
69
+ }
70
+ process.stdout.write(`${lines.join('\n')}\n`);
71
+ return 0;
72
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `wb-cli debug [agentId] -- <prompt>`
3
+ * Foreground alias — runs agent with stdio inherited (TTY passthrough).
4
+ * Equivalent to `wb-cli run` but with stderr visible inline.
5
+ */
6
+ export function debugCommand(argv) {
7
+ const dashDash = argv.indexOf('--');
8
+ let agentId = 'claude-code';
9
+ let promptParts;
10
+ if (dashDash >= 0) {
11
+ if (dashDash > 0)
12
+ agentId = argv[0];
13
+ promptParts = argv.slice(dashDash + 1);
14
+ }
15
+ else {
16
+ promptParts = argv;
17
+ }
18
+ const prompt = promptParts.join(' ').trim();
19
+ if (!prompt)
20
+ return null;
21
+ return { agentId, prompt };
22
+ }