@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,147 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { matchApprovalGate } from '../../../../packages/core/src/approval-gate/matcher.js';
4
+ import { APPROVAL_REQUEST_STATUS } from '../../../../packages/core/src/approval-gate/contracts.js';
5
+ import { ApprovalRequestStore, readApprovalResolution } from './store.js';
6
+ import { writeApprovalAudit } from './audit.js';
7
+ import { loadApprovalCodeOwnerConfig, resolveConfiguredCodeOwners } from '../config/approval-code-owners.js';
8
+ import { isEntryModule } from '../../../../packages/core/src/util/entry-module.js';
9
+ const OPEN_ID_PATTERN = /^ou_[A-Za-z0-9_-]+$/;
10
+ export function shellCommand(input) {
11
+ const command = input?.command;
12
+ return typeof command === 'string' ? command : '';
13
+ }
14
+ /**
15
+ * M12-F (2026-08-04 owner-authorized): envVarChange / externalDepUpgrade 的 approver
16
+ * 不应该是触发者本身 (userOpenId), 应该是 config 表里的 owner/admin。
17
+ * 通过 env `WB_APPROVAL_ADMIN_OPEN_IDS` (逗号分隔 ou_*) 读;为空时回退到 [userOpenId]
18
+ * 并在 stderr 留 warn 提示配置缺失 (不 deny,以免 block 合法流程)。
19
+ */
20
+ export function resolveAdminApproverOpenIds(env, fallbackUserOpenId) {
21
+ const raw = env['WB_APPROVAL_ADMIN_OPEN_IDS'] ?? '';
22
+ const ids = raw.split(',').map((value) => value.trim()).filter((value) => value && OPEN_ID_PATTERN.test(value));
23
+ if (ids.length === 0) {
24
+ return {
25
+ approvers: [fallbackUserOpenId],
26
+ fallbackNote: 'WB_APPROVAL_ADMIN_OPEN_IDS missing/unset — falling back to [userOpenId]; approval from the requester is a degenerate case, configure the owner set before production.',
27
+ };
28
+ }
29
+ return { approvers: [...new Set(ids)].sort(), fallbackNote: null };
30
+ }
31
+ export function gitStdout(args, cwd) {
32
+ const result = spawnSync('git', args, { cwd, encoding: 'utf8' });
33
+ if (result.status !== 0) {
34
+ throw new Error((result.stderr || result.stdout || `git ${args.join(' ')} failed`).trim());
35
+ }
36
+ return result.stdout.trim();
37
+ }
38
+ export function resolveWriteToMainBranchApprovers(cwd, userOpenId, env = process.env, gitRunner = gitStdout) {
39
+ const configPath = env['WB_APPROVAL_CODE_OWNER_CONFIG_PATH'];
40
+ if (!configPath)
41
+ throw new Error('approval code owner config path is missing');
42
+ const config = loadApprovalCodeOwnerConfig({ configPath, env });
43
+ const repoRoot = gitRunner(['rev-parse', '--show-toplevel'], cwd);
44
+ const changedRaw = gitRunner(['diff', '--name-only', 'HEAD^', 'HEAD'], cwd);
45
+ const changedPaths = changedRaw.split('\n').map((line) => line.trim()).filter(Boolean);
46
+ if (changedPaths.length === 0) {
47
+ throw new Error('unable to determine changed paths for writeToMainBranch');
48
+ }
49
+ const codeOwners = resolveConfiguredCodeOwners(config, {
50
+ repoRoot,
51
+ branch: 'main',
52
+ changedPaths,
53
+ });
54
+ return [...new Set([userOpenId, ...codeOwners])].sort();
55
+ }
56
+ export function readPayload(raw = readFileSync(0, 'utf8')) {
57
+ return JSON.parse(raw);
58
+ }
59
+ function deny(reason) {
60
+ process.stdout.write(JSON.stringify({
61
+ hookSpecificOutput: {
62
+ hookEventName: 'PreToolUse',
63
+ permissionDecision: 'deny',
64
+ permissionDecisionReason: reason,
65
+ },
66
+ }));
67
+ process.exit(0);
68
+ }
69
+ export function runApprovalHook(env = process.env, payload = readPayload(), options = {}) {
70
+ const dataDir = env['WB_DATA_DIR'];
71
+ const runId = env['WB_APPROVAL_RUN_ID'];
72
+ const botId = env['WB_APPROVAL_BOT_ID'];
73
+ const sessionId = env['WB_APPROVAL_SESSION_ID'];
74
+ const userOpenId = env['WB_APPROVAL_USER_OPEN_ID'];
75
+ const threadId = env['WB_APPROVAL_THREAD_ID'];
76
+ const sourceMessageId = env['WB_APPROVAL_SOURCE_MESSAGE_ID'];
77
+ const replyMessageId = env['WB_APPROVAL_REPLY_MESSAGE_ID'];
78
+ const agentId = env['WB_APPROVAL_AGENT_ID'];
79
+ if (!dataDir || !runId || !botId || !sessionId || !userOpenId || !threadId || !sourceMessageId || !replyMessageId || !agentId) {
80
+ deny('approval gate misconfigured');
81
+ }
82
+ const toolName = payload.tool_name ?? '';
83
+ const toolInput = payload.tool_input;
84
+ const match = matchApprovalGate(toolName, toolInput);
85
+ if (!match) {
86
+ process.exit(0);
87
+ }
88
+ let allowedApproverOpenIds = [userOpenId];
89
+ if (match.anchor === 'writeToMainBranch') {
90
+ try {
91
+ allowedApproverOpenIds = resolveWriteToMainBranchApprovers(payload.cwd ?? process.cwd(), userOpenId, env, options.gitRunner);
92
+ }
93
+ catch (error) {
94
+ deny(error instanceof Error ? error.message : String(error));
95
+ }
96
+ }
97
+ else if (match.anchor === 'envVarChange' || match.anchor === 'externalDepUpgrade') {
98
+ const resolved = resolveAdminApproverOpenIds(env, userOpenId);
99
+ allowedApproverOpenIds = resolved.approvers;
100
+ if (resolved.fallbackNote) {
101
+ process.stderr.write(`[approval-gate] ${resolved.fallbackNote}\n`);
102
+ }
103
+ }
104
+ const store = new ApprovalRequestStore(dataDir);
105
+ const request = store.create({
106
+ runId,
107
+ botId,
108
+ sessionId,
109
+ userOpenId,
110
+ threadId,
111
+ sourceMessageId,
112
+ replyMessageId,
113
+ agentId,
114
+ cwd: payload.cwd ?? process.cwd(),
115
+ match,
116
+ allowedApproverOpenIds,
117
+ });
118
+ writeApprovalAudit({ dataDir, request, phase: 'created' });
119
+ const dispatched = store.markDispatched(request.requestId, 'group_card');
120
+ writeApprovalAudit({ dataDir, request: dispatched, phase: 'dispatched' });
121
+ if (options.skipWait) {
122
+ return;
123
+ }
124
+ while (true) {
125
+ const resolution = readApprovalResolution(dataDir, request.requestId);
126
+ if (!resolution) {
127
+ const expired = store.expireOverdue();
128
+ const matching = expired.find((entry) => entry.requestId === request.requestId);
129
+ if (matching) {
130
+ writeApprovalAudit({ dataDir, request: matching, phase: 'resolved' });
131
+ deny(matching.resolutionReason ?? 'approval timeout');
132
+ }
133
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
134
+ continue;
135
+ }
136
+ const resolved = store.get(request.requestId);
137
+ if (resolved)
138
+ writeApprovalAudit({ dataDir, request: resolved, phase: 'resolved', nowIso: resolution.resolvedAt });
139
+ if (resolution.status === APPROVAL_REQUEST_STATUS.APPROVED) {
140
+ process.exit(0);
141
+ }
142
+ deny(resolution.reason);
143
+ }
144
+ }
145
+ if (isEntryModule(import.meta.url)) {
146
+ runApprovalHook();
147
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Card-driven notifier: the actual @通知 is embedded in the approval card itself
3
+ * via `<at user_id=... />` markup, so dispatch 只走 `renderApprovalRequestCard`
4
+ * 的 patch/reply 路径;这里保留一个 hook 让上层 (wb-bot event-handler) 可以
5
+ * 在不改 cards.ts 的情况下追加额外通道 (例如 IM 私聊 owner / dm),并统一做
6
+ * "只 @ 一次" 节流。
7
+ *
8
+ * 启用 muteRegistry 时: 命中 session 静音 → skip sendCard, 卡片已由主流程先 reply,
9
+ * 后续状态推进走 patch. 这样实现 PRD §2.7(4) 礼仪第 4 条.
10
+ */
11
+ export function createCardApprovalNotifier(opts) {
12
+ const seen = new Set();
13
+ return {
14
+ async notifyApprovers(request) {
15
+ if (opts.notifyOncePerRequest !== false && seen.has(request.requestId))
16
+ return;
17
+ seen.add(request.requestId);
18
+ const sessionId = opts.sessionIdOf ? opts.sessionIdOf(request) : request.sessionId;
19
+ if (opts.muteRegistry && sessionId) {
20
+ const record = opts.muteRegistry.isMuted({ sessionId });
21
+ if (record.muted) {
22
+ // 静音 → 只让卡片由后续流程 patch, 不再发一次独立通知
23
+ return;
24
+ }
25
+ }
26
+ await opts.sendCard(opts.resolveChatId(request), opts.cardFor(request));
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,157 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { appendNdjsonLine, readNdjsonSegments } from '../../../../packages/core/src/util/ndjson-rotation.js';
5
+ import { approvalRequestsPath, approvalResolutionPath } from '../../../../packages/core/src/paths.js';
6
+ import { APPROVAL_CARRIER, APPROVAL_REQUEST_STATUS, } from '../../../../packages/core/src/approval-gate/contracts.js';
7
+ export class ApprovalRequestStore {
8
+ dataDir;
9
+ nowFn;
10
+ requests = new Map();
11
+ constructor(dataDir, nowFn = () => new Date().toISOString()) {
12
+ this.dataDir = dataDir;
13
+ this.nowFn = nowFn;
14
+ this.replay();
15
+ }
16
+ create(input) {
17
+ const createdAt = input.nowIso ?? this.nowFn();
18
+ const deadlineAt = new Date(Date.parse(createdAt) + input.match.timeoutMs).toISOString();
19
+ const request = {
20
+ requestId: randomUUID(),
21
+ runId: input.runId,
22
+ botId: input.botId,
23
+ sessionId: input.sessionId,
24
+ userOpenId: input.userOpenId,
25
+ threadId: input.threadId,
26
+ sourceMessageId: input.sourceMessageId,
27
+ replyMessageId: input.replyMessageId,
28
+ agentId: input.agentId,
29
+ cwd: input.cwd,
30
+ createdAt,
31
+ deadlineAt,
32
+ status: APPROVAL_REQUEST_STATUS.PENDING_DISPATCH,
33
+ anchor: input.match.anchor,
34
+ approverPolicy: input.match.approverPolicy,
35
+ timeoutMs: input.match.timeoutMs,
36
+ toolName: input.match.toolName,
37
+ toolInput: input.match.toolInput,
38
+ resource: input.match.resource,
39
+ summary: input.match.summary,
40
+ allowedApproverOpenIds: [...new Set(input.allowedApproverOpenIds ?? [input.userOpenId])].sort(),
41
+ carrier: input.carrier,
42
+ };
43
+ this.requests.set(request.requestId, request);
44
+ this.writeMirror({ ts: createdAt, op: 'request_created', request });
45
+ return request;
46
+ }
47
+ markDispatched(requestId, carrier, carrierMessageId, nowIso = this.nowFn()) {
48
+ const request = this.requireRequest(requestId);
49
+ const next = {
50
+ ...request,
51
+ status: APPROVAL_REQUEST_STATUS.PENDING_APPROVAL,
52
+ carrier,
53
+ carrierMessageId,
54
+ };
55
+ this.requests.set(requestId, next);
56
+ this.writeMirror({ ts: nowIso, op: 'request_dispatched', request: next });
57
+ return next;
58
+ }
59
+ resolve(requestId, resolution) {
60
+ const request = this.requireRequest(requestId);
61
+ const next = {
62
+ ...request,
63
+ status: resolution.status,
64
+ resolutionReason: resolution.reason,
65
+ resolvedAt: resolution.resolvedAt,
66
+ resolvedBy: resolution.resolvedBy,
67
+ };
68
+ this.requests.set(requestId, next);
69
+ this.writeResolution({
70
+ requestId,
71
+ runId: request.runId,
72
+ status: resolution.status,
73
+ reason: resolution.reason,
74
+ resolvedAt: resolution.resolvedAt,
75
+ resolvedBy: resolution.resolvedBy,
76
+ });
77
+ this.writeMirror({ ts: resolution.resolvedAt, op: 'request_resolved', request: next });
78
+ return next;
79
+ }
80
+ /**
81
+ * M13-B (2026-08-04 owner-authorized): 真正的 transfer 语义 = 保留原 request,
82
+ * 把 allowedApproverOpenIds 整表替换为新的 pending 名单。**不** DENIED 原
83
+ * record,也**不**新建行。后续的 approve/deny/expire 走的都是原 requestId,
84
+ * audit 上以一次"request_dispatched (re-targeted)" 镜像登记 (含 approver 列表 diff).
85
+ */
86
+ transferInPlace(requestId, newApproverOpenIds, nowIso = this.nowFn()) {
87
+ const previous = this.requireRequest(requestId);
88
+ if (previous.status !== APPROVAL_REQUEST_STATUS.PENDING_DISPATCH && previous.status !== APPROVAL_REQUEST_STATUS.PENDING_APPROVAL) {
89
+ throw new Error(`approval request ${requestId} is not pending (status=${previous.status})`);
90
+ }
91
+ const next = {
92
+ ...previous,
93
+ allowedApproverOpenIds: [...new Set(newApproverOpenIds)].sort(),
94
+ };
95
+ this.requests.set(requestId, next);
96
+ this.writeMirror({ ts: nowIso, op: 'request_dispatched', request: next });
97
+ return next;
98
+ }
99
+ get(requestId) {
100
+ this.replay();
101
+ const request = this.requests.get(requestId);
102
+ return request ? { ...request } : undefined;
103
+ }
104
+ listPending() {
105
+ this.replay();
106
+ return [...this.requests.values()]
107
+ .filter((request) => request.status === APPROVAL_REQUEST_STATUS.PENDING_DISPATCH || request.status === APPROVAL_REQUEST_STATUS.PENDING_APPROVAL)
108
+ .map((request) => ({ ...request }));
109
+ }
110
+ expireOverdue(nowIso = this.nowFn()) {
111
+ const expired = [];
112
+ for (const request of this.requests.values()) {
113
+ if (request.status !== APPROVAL_REQUEST_STATUS.PENDING_DISPATCH && request.status !== APPROVAL_REQUEST_STATUS.PENDING_APPROVAL)
114
+ continue;
115
+ if (Date.parse(request.deadlineAt) > Date.parse(nowIso))
116
+ continue;
117
+ expired.push(this.resolve(request.requestId, {
118
+ status: APPROVAL_REQUEST_STATUS.EXPIRED,
119
+ reason: 'approval timeout',
120
+ resolvedAt: nowIso,
121
+ }));
122
+ }
123
+ return expired;
124
+ }
125
+ requireRequest(requestId) {
126
+ const request = this.requests.get(requestId);
127
+ if (!request)
128
+ throw new Error(`approval request not found: ${requestId}`);
129
+ return request;
130
+ }
131
+ replay() {
132
+ const path = approvalRequestsPath(this.dataDir);
133
+ if (!existsSync(path))
134
+ return;
135
+ for (const line of readNdjsonSegments(path)) {
136
+ const entry = JSON.parse(line);
137
+ this.requests.set(entry.request.requestId, entry.request);
138
+ }
139
+ }
140
+ writeMirror(entry) {
141
+ appendNdjsonLine(approvalRequestsPath(this.dataDir), JSON.stringify(entry), { fsync: true });
142
+ }
143
+ writeResolution(entry) {
144
+ const path = approvalResolutionPath(this.dataDir, entry.requestId);
145
+ mkdirSync(dirname(path), { recursive: true });
146
+ writeFileSync(path, JSON.stringify(entry, null, 2));
147
+ }
148
+ }
149
+ export function defaultApprovalCarrier(isApprovalAppAvailable) {
150
+ return isApprovalAppAvailable ? APPROVAL_CARRIER.APPROVAL_APP : APPROVAL_CARRIER.GROUP_CARD;
151
+ }
152
+ export function readApprovalResolution(dataDir, requestId) {
153
+ const path = approvalResolutionPath(dataDir, requestId);
154
+ if (!existsSync(path))
155
+ return null;
156
+ return JSON.parse(readFileSync(path, 'utf8'));
157
+ }
@@ -0,0 +1,35 @@
1
+ import { migration001 } from './migrations/001-add-run-id-agent-id.js';
2
+ import { migration002 } from './migrations/002-add-bot-id.js';
3
+ import { migration003 } from './migrations/003-inflight-card-agent-id-pk.js';
4
+ import { migration004 } from './migrations/004-thread-alias-topic-key.js';
5
+ import { migration005 } from './migrations/005-card-entity.js';
6
+ import { migration006 } from './migrations/006-group-setting.js';
7
+ const ALL_MIGRATIONS = [migration001, migration002, migration003, migration004, migration005, migration006];
8
+ export const CURRENT_SCHEMA_VERSION = ALL_MIGRATIONS.length;
9
+ export function runMigrations(db) {
10
+ const rows = db.pragma('user_version');
11
+ const currentVersion = rows[0]?.user_version ?? 0;
12
+ if (currentVersion >= CURRENT_SCHEMA_VERSION) {
13
+ return { success: true, fromVersion: currentVersion, toVersion: currentVersion };
14
+ }
15
+ const pending = ALL_MIGRATIONS.filter((m) => m.version > currentVersion);
16
+ try {
17
+ db.exec('BEGIN IMMEDIATE');
18
+ try {
19
+ for (const migration of pending) {
20
+ migration.up(db);
21
+ }
22
+ db.pragma(`user_version = ${CURRENT_SCHEMA_VERSION}`);
23
+ db.exec('COMMIT');
24
+ }
25
+ catch (err) {
26
+ db.exec('ROLLBACK');
27
+ throw err;
28
+ }
29
+ return { success: true, fromVersion: currentVersion, toVersion: CURRENT_SCHEMA_VERSION };
30
+ }
31
+ catch (err) {
32
+ const message = err instanceof Error ? err.message : String(err);
33
+ return { success: false, fromVersion: currentVersion, toVersion: currentVersion, error: message };
34
+ }
35
+ }
@@ -0,0 +1,8 @@
1
+ export const migration001 = {
2
+ version: 1,
3
+ description: 'add run_id and agent_id columns to inflight_card',
4
+ up(db) {
5
+ db.exec(`ALTER TABLE inflight_card ADD COLUMN run_id TEXT`);
6
+ db.exec(`ALTER TABLE inflight_card ADD COLUMN agent_id TEXT`);
7
+ },
8
+ };
@@ -0,0 +1,34 @@
1
+ function rebuildTable(db, table, columns, selectCols, newPk) {
2
+ db.exec(`CREATE TABLE ${table}_new (${columns}, PRIMARY KEY (${newPk}))`);
3
+ db.exec(`INSERT INTO ${table}_new (${selectCols}, bot_id) SELECT ${selectCols}, 'default' FROM ${table}`);
4
+ db.exec(`DROP TABLE ${table}`);
5
+ db.exec(`ALTER TABLE ${table}_new RENAME TO ${table}`);
6
+ }
7
+ export const migration002 = {
8
+ version: 2,
9
+ description: 'add bot_id column + PK upgrade to thread_binding, agent_continuation, inflight_card',
10
+ up(db) {
11
+ rebuildTable(db, 'thread_binding', 'user_open_id TEXT NOT NULL, thread_id TEXT NOT NULL, agent_id TEXT NOT NULL, cwd TEXT, bot_id TEXT NOT NULL DEFAULT \'default\'', 'user_open_id, thread_id, agent_id, cwd', 'bot_id, user_open_id, thread_id');
12
+ rebuildTable(db, 'agent_continuation', 'user_open_id TEXT NOT NULL, thread_id TEXT NOT NULL, agent_id TEXT NOT NULL, continuation_token TEXT NOT NULL, bot_id TEXT NOT NULL DEFAULT \'default\'', 'user_open_id, thread_id, agent_id, continuation_token', 'bot_id, user_open_id, thread_id, agent_id');
13
+ // inflight_card has run_id + agent_id from migration 001
14
+ const cols = db.prepare("PRAGMA table_info('inflight_card')").all();
15
+ const colNames = cols.map((c) => c.name);
16
+ const hasRunId = colNames.includes('run_id');
17
+ const hasAgentId = colNames.includes('agent_id');
18
+ let inflightCols = 'user_open_id TEXT NOT NULL, thread_id TEXT NOT NULL, source_message_id TEXT NOT NULL, reply_message_id TEXT NOT NULL';
19
+ let selectList = 'user_open_id, thread_id, source_message_id, reply_message_id';
20
+ if (hasRunId) {
21
+ inflightCols += ', run_id TEXT';
22
+ selectList += ', run_id';
23
+ }
24
+ if (hasAgentId) {
25
+ inflightCols += ', agent_id TEXT';
26
+ selectList += ', agent_id';
27
+ }
28
+ inflightCols += ", bot_id TEXT NOT NULL DEFAULT 'default'";
29
+ db.exec(`CREATE TABLE inflight_card_new (${inflightCols}, PRIMARY KEY (bot_id, user_open_id, thread_id))`);
30
+ db.exec(`INSERT INTO inflight_card_new (${selectList}, bot_id) SELECT ${selectList}, 'default' FROM inflight_card`);
31
+ db.exec('DROP TABLE inflight_card');
32
+ db.exec('ALTER TABLE inflight_card_new RENAME TO inflight_card');
33
+ },
34
+ };
@@ -0,0 +1,31 @@
1
+ export const migration003 = {
2
+ version: 3,
3
+ description: 'inflight_card PK include agent_id · 解 multi-agent concurrent inflight 互相覆盖 / cleanupSession 连带删除 bug',
4
+ up(db) {
5
+ db.exec(`UPDATE inflight_card SET agent_id = 'claude-code' WHERE agent_id IS NULL`);
6
+ db.exec(`
7
+ CREATE TABLE inflight_card_new (
8
+ user_open_id TEXT NOT NULL,
9
+ thread_id TEXT NOT NULL,
10
+ source_message_id TEXT NOT NULL,
11
+ reply_message_id TEXT NOT NULL,
12
+ run_id TEXT,
13
+ agent_id TEXT NOT NULL DEFAULT 'claude-code',
14
+ bot_id TEXT NOT NULL DEFAULT 'default',
15
+ PRIMARY KEY (bot_id, user_open_id, thread_id, agent_id)
16
+ )
17
+ `);
18
+ db.exec(`
19
+ INSERT INTO inflight_card_new (
20
+ user_open_id, thread_id, source_message_id, reply_message_id, run_id, agent_id, bot_id
21
+ )
22
+ SELECT
23
+ user_open_id, thread_id, source_message_id, reply_message_id, run_id,
24
+ COALESCE(agent_id, 'claude-code'),
25
+ bot_id
26
+ FROM inflight_card
27
+ `);
28
+ db.exec(`DROP TABLE inflight_card`);
29
+ db.exec(`ALTER TABLE inflight_card_new RENAME TO inflight_card`);
30
+ },
31
+ };
@@ -0,0 +1,31 @@
1
+ function insertLegacyChatAliases(db, table) {
2
+ db.exec(`
3
+ INSERT OR IGNORE INTO thread_alias (bot_id, user_open_id, alias_thread_id, target_thread_id)
4
+ SELECT DISTINCT
5
+ bot_id,
6
+ user_open_id,
7
+ 'chat:' || thread_id,
8
+ thread_id
9
+ FROM ${table}
10
+ WHERE thread_id NOT LIKE 'chat:%'
11
+ AND thread_id NOT LIKE 'root:%'
12
+ `);
13
+ }
14
+ export const migration004 = {
15
+ version: 4,
16
+ description: 'add thread_alias table for canonical topic-key fallback to legacy chat_id rows',
17
+ up(db) {
18
+ db.exec(`
19
+ CREATE TABLE IF NOT EXISTS thread_alias (
20
+ bot_id TEXT NOT NULL DEFAULT 'default',
21
+ user_open_id TEXT NOT NULL,
22
+ alias_thread_id TEXT NOT NULL,
23
+ target_thread_id TEXT NOT NULL,
24
+ PRIMARY KEY (bot_id, user_open_id, alias_thread_id)
25
+ )
26
+ `);
27
+ insertLegacyChatAliases(db, 'thread_binding');
28
+ insertLegacyChatAliases(db, 'agent_continuation');
29
+ insertLegacyChatAliases(db, 'inflight_card');
30
+ },
31
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * CardKit 卡片实体: 消息只引用 card_id, 之后的更新必须走 cardkit 接口且 sequence 严格递增.
3
+ * 重启后 restart-recovery 要改写残留的运行卡, 所以 card_id 与最近用过的 sequence 落库.
4
+ */
5
+ export const migration005 = {
6
+ version: 5,
7
+ description: 'add card_entity table mapping Feishu message ids to CardKit card ids and sequences',
8
+ up(db) {
9
+ db.exec(`
10
+ CREATE TABLE IF NOT EXISTS card_entity (
11
+ bot_id TEXT NOT NULL DEFAULT 'default',
12
+ message_id TEXT NOT NULL,
13
+ card_id TEXT NOT NULL,
14
+ sequence INTEGER NOT NULL DEFAULT 0,
15
+ streaming INTEGER NOT NULL DEFAULT 0,
16
+ updated_at INTEGER NOT NULL,
17
+ PRIMARY KEY (bot_id, message_id)
18
+ )
19
+ `);
20
+ },
21
+ };
@@ -0,0 +1,17 @@
1
+ /** 每个群的 bot 行为开关; 目前只有 require_mention (群里是否必须 @bot 才响应). */
2
+ export const migration006 = {
3
+ version: 6,
4
+ description: 'add group_setting table for per-chat bot switches',
5
+ up(db) {
6
+ db.exec(`
7
+ CREATE TABLE IF NOT EXISTS group_setting (
8
+ bot_id TEXT NOT NULL DEFAULT 'default',
9
+ chat_id TEXT NOT NULL,
10
+ require_mention INTEGER NOT NULL DEFAULT 1,
11
+ updated_by TEXT,
12
+ updated_at INTEGER NOT NULL,
13
+ PRIMARY KEY (bot_id, chat_id)
14
+ )
15
+ `);
16
+ },
17
+ };
@@ -0,0 +1,58 @@
1
+ export const CREATE_THREAD_BINDING_SQL = `
2
+ CREATE TABLE IF NOT EXISTS thread_binding (
3
+ user_open_id TEXT NOT NULL,
4
+ thread_id TEXT NOT NULL,
5
+ agent_id TEXT NOT NULL,
6
+ cwd TEXT,
7
+ bot_id TEXT NOT NULL DEFAULT 'default',
8
+ PRIMARY KEY (bot_id, user_open_id, thread_id)
9
+ );
10
+ `;
11
+ export const CREATE_AGENT_CONTINUATION_SQL = `
12
+ CREATE TABLE IF NOT EXISTS agent_continuation (
13
+ user_open_id TEXT NOT NULL,
14
+ thread_id TEXT NOT NULL,
15
+ agent_id TEXT NOT NULL,
16
+ continuation_token TEXT NOT NULL,
17
+ bot_id TEXT NOT NULL DEFAULT 'default',
18
+ PRIMARY KEY (bot_id, user_open_id, thread_id, agent_id)
19
+ );
20
+ `;
21
+ export const CREATE_CWD_ALIAS_SQL = `
22
+ CREATE TABLE IF NOT EXISTS cwd_alias (
23
+ user_open_id TEXT NOT NULL,
24
+ name TEXT NOT NULL,
25
+ path TEXT NOT NULL,
26
+ PRIMARY KEY (user_open_id, name)
27
+ );
28
+ `;
29
+ export const CREATE_THREAD_ALIAS_SQL = `
30
+ CREATE TABLE IF NOT EXISTS thread_alias (
31
+ bot_id TEXT NOT NULL DEFAULT 'default',
32
+ user_open_id TEXT NOT NULL,
33
+ alias_thread_id TEXT NOT NULL,
34
+ target_thread_id TEXT NOT NULL,
35
+ PRIMARY KEY (bot_id, user_open_id, alias_thread_id)
36
+ );
37
+ `;
38
+ // NOTE: SCHEMA_SQL 是 "v0 早期 form", 由 migrations 001/002/003 增量升到 final form.
39
+ // 不要把 run_id / agent_id / 4-tuple PK 写在这里, 否则 m001 ADD COLUMN 会撞重复列.
40
+ // 最终 form 见 migration 003 (PK = (bot_id, user_open_id, thread_id, agent_id),
41
+ // agent_id NOT NULL DEFAULT 'claude-code').
42
+ export const CREATE_INFLIGHT_CARD_SQL = `
43
+ CREATE TABLE IF NOT EXISTS inflight_card (
44
+ user_open_id TEXT NOT NULL,
45
+ thread_id TEXT NOT NULL,
46
+ source_message_id TEXT NOT NULL,
47
+ reply_message_id TEXT NOT NULL,
48
+ bot_id TEXT NOT NULL DEFAULT 'default',
49
+ PRIMARY KEY (bot_id, user_open_id, thread_id)
50
+ );
51
+ `;
52
+ export const SCHEMA_SQL = [
53
+ CREATE_THREAD_BINDING_SQL,
54
+ CREATE_AGENT_CONTINUATION_SQL,
55
+ CREATE_CWD_ALIAS_SQL,
56
+ CREATE_THREAD_ALIAS_SQL,
57
+ CREATE_INFLIGHT_CARD_SQL,
58
+ ];
@@ -0,0 +1,5 @@
1
+ export function sleepSync(ms) {
2
+ const buffer = new SharedArrayBuffer(4);
3
+ const view = new Int32Array(buffer);
4
+ Atomics.wait(view, 0, 0, ms);
5
+ }