@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,107 @@
1
+ /**
2
+ * W3.4 Run Observability & Intervention Loop — contracts
3
+ * ≤ 200 lines · zod schemas + derived TS types
4
+ * No runtime imports except zod and frozen contract re-exports.
5
+ *
6
+ * Frozen imports (read-only, do NOT modify):
7
+ * RUN_STATUS ← packages/core/src/run-registry/contracts
8
+ * ENTRY_FORMS ← packages/core/src/audit-pipe/contracts
9
+ */
10
+ import { z } from 'zod';
11
+ import { RUN_STATUS } from '../run-registry/contracts.js';
12
+ import { ENTRY_FORMS } from '../audit-pipe/contracts.js';
13
+ import { EchoPayloadSchema } from '../reverse-channel/contracts.js';
14
+ export { RUN_STATUS, ENTRY_FORMS, EchoPayloadSchema };
15
+ const RUN_STATUS_VALUES = Object.values(RUN_STATUS);
16
+ const ALERT_REASON = ['silent_timeout', 'exit_nonzero'];
17
+ export const PROGRESS_STORE_MAX_BYTES = 10 * 1024 * 1024;
18
+ export const ALERT_POLL_INTERVAL_MS = 60_000;
19
+ export const SILENT_TIMEOUT_S_DEFAULT = 300;
20
+ export const SILENT_TIMEOUT_S_MIN = 60;
21
+ export const SILENT_TIMEOUT_S_MAX = 1800;
22
+ export const OBSERVE_AT_PATTERN = /^@wb\s+obs\s+(on|off)$/i;
23
+ export const FINALIZE_OUTPUT_MAX_BYTES = 4 * 1024;
24
+ export const FINALIZE_HEAD_LINES = 10;
25
+ export const FINALIZE_TAIL_LINES = 10;
26
+ export const CARD_LINE_MAX_CHARS = 120; // 经验值;impl 阶段允许 ±20% 调整
27
+ export const RATE_LIMIT_BUCKET_CAPACITY = 1; // deprecated: C3 reuses CardPipeline(minIntervalMs=800)
28
+ export const RATE_LIMIT_REFILL_MS = 1_000; // deprecated: retained for cleanup follow-up
29
+ export const RunObservabilityEventSchema = z.object({
30
+ run_id: z.string().min(1).describe('对应 RunRecord.run_id'),
31
+ ts: z.string().datetime().describe('事件时间戳,ISO8601'),
32
+ line_index: z.number().int().nonnegative().describe('行序号,从 0 起,双流共享计数'),
33
+ text: z.string().max(65_536).describe('stdout/stderr 原始行文本,64 KB hard cap'),
34
+ source: z.enum(['stdout', 'stderr']).describe('事件来源流'),
35
+ truncated: z.boolean().default(false).describe('文本是否被截断'),
36
+ });
37
+ export const ObservabilityStoreEntrySchema = z.object({
38
+ run_id: z.string().min(1).describe('对应 RunRecord.run_id'),
39
+ session_id: z.string().min(1).describe('对应 SessionRecord.session_id'),
40
+ step_index: z.number().int().min(0).default(0).describe('当前步骤序号,从 0 起'),
41
+ token_usage: z.number().int().min(0).default(0).describe('累计 token 消耗'),
42
+ status: z.enum(RUN_STATUS_VALUES).describe('与 RunRecord.status 同步'),
43
+ updated_at: z.string().datetime().describe('最近写入时间,ISO8601'),
44
+ last_stdout_at: z.string().datetime().nullable().describe('静默检测基准时间'),
45
+ origin_message_id: z.string().nullable().describe('E1/E3 原始卡片锚点'),
46
+ card_message_id: z.string().nullable().describe('E1 patch 目标 Lark message_id'),
47
+ home_group_id: z.string().nullable().default(null).describe('E3/F24 顶层发送目标 chat_id;缺失时跳过非 reply send'),
48
+ created_at: z.string().datetime().describe('run 观测开始时间'),
49
+ alerted: z.boolean().default(false).describe('F26 幂等标记'),
50
+ alert_reason: z.enum(ALERT_REASON).nullable().describe('最近一次告警原因'),
51
+ finalized: z.boolean().default(false).describe('F27 幂等标记'),
52
+ cancelled: z.boolean().default(false).describe('cancel 路径标记'),
53
+ alert_enabled: z.boolean().default(true).describe('F29 per-session 推送开关'),
54
+ store_truncated: z.boolean().default(false).describe('progress.ndjson 已达 10MB 上限'),
55
+ stale_self_heal_attempts: z.number().int().min(0).default(0).describe('watchdog stale self-heal 已占用次数'),
56
+ stale_self_heal_last_attempt_at: z.string().datetime().nullable().default(null).describe('最近一次 watchdog stale self-heal 尝试时间'),
57
+ stale_self_heal_escalated_at: z.string().datetime().nullable().default(null).describe('超出 stale self-heal 次数后首次升级 admin alert 时间'),
58
+ // M11-C C1 (2026-08-04, owner-authorized): additive fields to surface auto-doc-sink
59
+ // behaviour on finalize runs. Defaults preserve prior behaviour for rows without these keys.
60
+ produced_doc_urls: z.array(z.string()).default([]).describe('auto doc-sink 写出的 doc/wiki URL 列表(含历史与本次)'),
61
+ doc_sink_attempted_at: z.string().datetime().nullable().default(null).describe('最近一次 ensureRunDoc 尝试时间'),
62
+ doc_sink_last_reason: z.string().nullable().default(null).describe('ensureRunDoc 最近一次的 reason 字段(created/already_succeeded/failed/locked/not_longform/not_terminal)'),
63
+ });
64
+ export const AlertPayloadSchema = z.object({
65
+ run_id: z.string().min(1).describe('对应 RunRecord.run_id'),
66
+ session_id: z.string().min(1).describe('对应 SessionRecord.session_id'),
67
+ reason: z.enum(ALERT_REASON).describe('告警类型'),
68
+ last_output_at: z.string().datetime().nullable().describe('最后一条输出时间'),
69
+ elapsed_s: z.number().nonnegative().describe('run 已运行秒数'),
70
+ exit_code: z.number().int().nullable().describe('exit_nonzero 时的退出码'),
71
+ signal: z.string().nullable().describe('进程终止信号,如 SIGKILL'),
72
+ });
73
+ export const FinalizePayloadSchema = z.object({
74
+ run_id: z.string().min(1).describe('对应 RunRecord.run_id'),
75
+ session_id: z.string().min(1).describe('对应 SessionRecord.session_id'),
76
+ status: z.enum(RUN_STATUS_VALUES).describe('RUN_STATUS 终态值'),
77
+ elapsed_s: z.number().nonnegative().describe('run 总运行秒数'),
78
+ origin_message_id: z.string().nullable().describe('reply 锚点;缺失时降级顶层发送'),
79
+ head_lines: z.array(z.string()).describe('output 前 N 行'),
80
+ tail_lines: z.array(z.string()).describe('output 后 N 行'),
81
+ output_truncated: z.boolean().default(false).describe('head+tail 合并后是否超 4KB'),
82
+ });
83
+ export const ObservabilityConfigSchema = z.object({
84
+ enabled: z.boolean().default(true).describe('全局开关;false 时跳过所有 F22-F29'),
85
+ alert_enabled: z.boolean().default(true).describe('默认推送开关;F29 per-session 可覆盖'),
86
+ silent_timeout_s: z.number().int().min(SILENT_TIMEOUT_S_MIN).max(SILENT_TIMEOUT_S_MAX).default(SILENT_TIMEOUT_S_DEFAULT).describe('F24 静默超时秒数'),
87
+ finalize_head_lines: z.number().int().positive().default(FINALIZE_HEAD_LINES).describe('E3 摘要头部行数'),
88
+ finalize_tail_lines: z.number().int().positive().default(FINALIZE_TAIL_LINES).describe('E3 摘要尾部行数'),
89
+ }).default({});
90
+ export const RUN_OBSERVABILITY_ERROR_CODES = {
91
+ E_STORE_WRITE: 'run-observability.store.write_failed',
92
+ E_STORE_TRUNCATED: 'run-observability.store.truncated',
93
+ E_IM_SEND_FAILED: 'run-observability.im.send_failed',
94
+ E_IM_PATCH_FAILED: 'run-observability.im.patch_failed',
95
+ E_RUN_STALE_NOOP: 'run-observability.alert.stale_noop',
96
+ E_NO_ACTIVE_SESSION: 'run-observability.session.not_found',
97
+ };
98
+ export class RunObservabilityError extends Error {
99
+ code;
100
+ cause;
101
+ constructor(code, message, cause) {
102
+ super(`[${code}] ${message}`);
103
+ this.code = code;
104
+ this.cause = cause;
105
+ this.name = 'RunObservabilityError';
106
+ }
107
+ }
@@ -0,0 +1,16 @@
1
+ import { AlertPayloadSchema } from './contracts.js';
2
+ export function detectExitError(input) {
3
+ if (input.cancelled)
4
+ return null;
5
+ if (input.status !== 'failed')
6
+ return null;
7
+ return AlertPayloadSchema.parse({
8
+ run_id: input.runId,
9
+ session_id: input.sessionId,
10
+ reason: 'exit_nonzero',
11
+ last_output_at: null,
12
+ elapsed_s: input.elapsedS,
13
+ exit_code: input.exitMeta?.exit_code ?? null,
14
+ signal: input.exitMeta?.signal ?? null,
15
+ });
16
+ }
@@ -0,0 +1,114 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createMirrorSink } from '../audit-pipe/mirror-sink.js';
3
+ import { FINALIZE_HEAD_LINES, FINALIZE_OUTPUT_MAX_BYTES, FINALIZE_TAIL_LINES } from './contracts.js';
4
+ import { ensureRunDoc } from '../run-registry/doc-sink.js';
5
+ import { loadRunRegistryConfig } from '../run-registry/config.js';
6
+ function truncateLines(lines) {
7
+ const raw = lines.join('\n');
8
+ if (Buffer.byteLength(raw, 'utf8') <= FINALIZE_OUTPUT_MAX_BYTES) {
9
+ return { lines, outputTruncated: false };
10
+ }
11
+ const prefix = '...(已截断)';
12
+ let working = [...lines];
13
+ while (working.length > 1 && Buffer.byteLength([prefix, ...working].join('\n'), 'utf8') > FINALIZE_OUTPUT_MAX_BYTES) {
14
+ working.pop();
15
+ }
16
+ return { lines: [prefix, ...working], outputTruncated: true };
17
+ }
18
+ function summarizeOutput(lines) {
19
+ if (lines.length === 0)
20
+ return { headLines: ['(no output)'], tailLines: [], outputTruncated: false };
21
+ const headLines = lines.slice(0, FINALIZE_HEAD_LINES);
22
+ const tailLines = lines.slice(-FINALIZE_TAIL_LINES);
23
+ const deduped = [...headLines, ...tailLines.slice(Math.max(0, headLines.length + tailLines.length - lines.length))];
24
+ const truncated = truncateLines(deduped);
25
+ return {
26
+ headLines: truncated.lines.slice(0, Math.min(headLines.length, truncated.lines.length)),
27
+ tailLines: truncated.lines.slice(Math.min(headLines.length, truncated.lines.length)),
28
+ outputTruncated: truncated.outputTruncated,
29
+ };
30
+ }
31
+ function renderFinalizeCard(entry, lines, nowIso) {
32
+ const summary = summarizeOutput(lines);
33
+ return {
34
+ schema: '2.0',
35
+ config: { wide_screen_mode: true },
36
+ header: { title: { tag: 'plain_text', content: `✅ Run Finalized · ${entry.run_id}` } },
37
+ body: {
38
+ elements: [
39
+ { tag: 'markdown', content: `status: ${entry.status}` },
40
+ { tag: 'markdown', content: `elapsed_at: ${nowIso}` },
41
+ { tag: 'markdown', content: summary.headLines.join('\n') },
42
+ { tag: 'markdown', content: summary.tailLines.join('\n') },
43
+ ],
44
+ },
45
+ };
46
+ }
47
+ export async function finalizeRun(entry, lines, options) {
48
+ const nowIso = options.nowIso ?? new Date().toISOString();
49
+ const finalCard = renderFinalizeCard(entry, lines, nowIso);
50
+ if (entry.card_message_id) {
51
+ try {
52
+ await options.client.updateCard(entry.card_message_id, finalCard);
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ if (entry.origin_message_id) {
59
+ await options.client.replyCard(entry.origin_message_id, finalCard);
60
+ }
61
+ else if (entry.home_group_id) {
62
+ await options.client.sendCard(entry.home_group_id, finalCard);
63
+ }
64
+ options.onFinalized?.();
65
+ // C1 (2026-08-04 owner-authorized): finalize 完成后触发 auto doc-sink (prereq: status terminal)
66
+ // reason 'not_terminal' 直接 passthrough, 不打扰已 finalized 的卡; succeeded/created 写入
67
+ // produced_doc_urls 并回写 store (caller 已持久化 entry, via onFinalized).
68
+ if (!options.skipDocSink) {
69
+ try {
70
+ // Read the registry config from the same dataDir the doc-sink writes to.
71
+ const config = loadRunRegistryConfig({ env: { ...(options.larkEnv ?? process.env), WB_DATA_DIR: options.dataDir } });
72
+ const sinkStatus = entry.status;
73
+ const result = await ensureRunDoc({
74
+ dataDir: options.dataDir,
75
+ runId: entry.run_id,
76
+ botId: options.botId ?? 'default',
77
+ status: sinkStatus,
78
+ existingDocUrls: entry.produced_doc_urls ?? [],
79
+ config,
80
+ env: options.larkEnv,
81
+ });
82
+ entry.produced_doc_urls = result.produced_doc_urls;
83
+ entry.doc_sink_attempted_at = nowIso;
84
+ entry.doc_sink_last_reason = result.reason;
85
+ }
86
+ catch (error) {
87
+ // doc-sink 失败不阻塞 finalize 主路径, 但记录上次原因便于排障.
88
+ entry.doc_sink_attempted_at = nowIso;
89
+ entry.doc_sink_last_reason = `error:${error instanceof Error ? error.message : String(error)}`;
90
+ }
91
+ }
92
+ const sink = createMirrorSink({ dataDir: options.dataDir });
93
+ const record = {
94
+ audit_record_id: randomUUID(),
95
+ session_id: entry.session_id,
96
+ run_id: entry.run_id,
97
+ revision: 0,
98
+ actor: entry.session_id,
99
+ action: 'network_call',
100
+ resource: `run-observability:finalize:${entry.run_id}`,
101
+ ts: nowIso,
102
+ entry_form: 'im',
103
+ entry_detail: {
104
+ source_message_id: entry.origin_message_id ?? entry.run_id,
105
+ user_open_id: entry.session_id,
106
+ thread_id: entry.home_group_id ?? entry.card_message_id ?? '',
107
+ },
108
+ agent_id: 'claude-code',
109
+ raw_tool_use_id: `${entry.run_id}:finalize`,
110
+ raw_tool_name: 'finalizer',
111
+ };
112
+ sink.write(record);
113
+ return true;
114
+ }
@@ -0,0 +1,12 @@
1
+ export * from './contracts.js';
2
+ export * from './progress-store.js';
3
+ export * from './progress-collector.js';
4
+ export * from './card-renderer-progress.js';
5
+ export * from './card-refresher.js';
6
+ export * from './silent-timeout-detector.js';
7
+ export * from './exit-code-detector.js';
8
+ export * from './alert-card-renderer.js';
9
+ export * from './alert-pusher.js';
10
+ export * from './finalizer.js';
11
+ export * from './config-loader.js';
12
+ export * from './obs-toggle-handler.js';
@@ -0,0 +1,29 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createMirrorSink } from '../audit-pipe/mirror-sink.js';
3
+ import {} from './contracts.js';
4
+ export function toggleAlert(entry, enabled) {
5
+ return { ...entry, alert_enabled: enabled };
6
+ }
7
+ export function writeToggleAudit(dataDir, entry, enabled) {
8
+ const sink = createMirrorSink({ dataDir });
9
+ const record = {
10
+ audit_record_id: randomUUID(),
11
+ session_id: entry.session_id,
12
+ run_id: entry.run_id,
13
+ revision: 0,
14
+ actor: entry.session_id,
15
+ action: 'network_call',
16
+ resource: `run-observability:toggle:${entry.run_id}:alert:${enabled}`,
17
+ ts: new Date().toISOString(),
18
+ entry_form: 'im',
19
+ entry_detail: {
20
+ source_message_id: entry.origin_message_id ?? entry.run_id,
21
+ user_open_id: entry.session_id,
22
+ thread_id: entry.home_group_id ?? entry.card_message_id ?? '',
23
+ },
24
+ agent_id: 'claude-code',
25
+ raw_tool_use_id: `${entry.run_id}:toggle:${enabled}`,
26
+ raw_tool_name: 'obs-toggle',
27
+ };
28
+ sink.write(record);
29
+ }
@@ -0,0 +1,53 @@
1
+ import { ProgressStore } from './progress-store.js';
2
+ export class ProgressCollector {
3
+ store;
4
+ nowFn;
5
+ buffers = {
6
+ stdout: '',
7
+ stderr: '',
8
+ };
9
+ lineIndex = 0;
10
+ constructor(store, nowFn = () => new Date().toISOString()) {
11
+ this.store = store;
12
+ this.nowFn = nowFn;
13
+ }
14
+ attach(streams) {
15
+ const listeners = [];
16
+ for (const [source, stream] of Object.entries(streams)) {
17
+ if (!stream)
18
+ continue;
19
+ const onData = (chunk) => {
20
+ this.push(source, typeof chunk === 'string' ? chunk : chunk.toString('utf8'));
21
+ };
22
+ stream.on('data', onData);
23
+ listeners.push(() => stream.off('data', onData));
24
+ }
25
+ return () => listeners.forEach((off) => off());
26
+ }
27
+ push(source, chunk) {
28
+ this.buffers[source] += chunk;
29
+ const lines = this.buffers[source].split('\n');
30
+ this.buffers[source] = lines.pop() ?? '';
31
+ return lines.filter((line) => line.length > 0).map((line) => this.appendLine(source, line));
32
+ }
33
+ flush() {
34
+ const results = [];
35
+ for (const source of ['stdout', 'stderr']) {
36
+ if (!this.buffers[source])
37
+ continue;
38
+ results.push(this.appendLine(source, this.buffers[source]));
39
+ this.buffers[source] = '';
40
+ }
41
+ return results;
42
+ }
43
+ appendLine(source, text) {
44
+ const result = this.store.append({
45
+ lineIndex: this.lineIndex,
46
+ source,
47
+ text,
48
+ ts: this.nowFn(),
49
+ });
50
+ this.lineIndex += 1;
51
+ return result;
52
+ }
53
+ }
@@ -0,0 +1,100 @@
1
+ import * as fs from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { runDir } from '../paths.js';
4
+ import { ObservabilityStoreEntrySchema, PROGRESS_STORE_MAX_BYTES, RUN_OBSERVABILITY_ERROR_CODES, RunObservabilityEventSchema, } from './contracts.js';
5
+ export class ProgressStore {
6
+ options;
7
+ runDir;
8
+ progressPath;
9
+ metaPath;
10
+ fsImpl;
11
+ constructor(options) {
12
+ this.options = options;
13
+ this.fsImpl = options.fsImpl ?? fs;
14
+ this.runDir = runDir(options.dataDir, options.runId, options.botId);
15
+ this.progressPath = join(this.runDir, 'progress.ndjson');
16
+ this.metaPath = join(this.runDir, 'meta.json');
17
+ this.fsImpl.mkdirSync(this.runDir, { recursive: true });
18
+ }
19
+ append(input) {
20
+ const entry = this.readEntry() ?? this.defaultEntry(input.ts);
21
+ entry.step_index = input.lineIndex;
22
+ entry.updated_at = input.ts;
23
+ if (input.source === 'stdout')
24
+ entry.last_stdout_at = input.ts;
25
+ if (entry.store_truncated) {
26
+ this.writeEntry(entry);
27
+ return { ok: true, wroteLine: false, storeTruncated: true };
28
+ }
29
+ const event = this.normalizeEvent(input);
30
+ const line = `${JSON.stringify(event)}\n`;
31
+ const maxBytes = this.options.maxBytes ?? PROGRESS_STORE_MAX_BYTES;
32
+ const currentSize = this.fsImpl.existsSync(this.progressPath) ? this.fsImpl.statSync(this.progressPath).size : 0;
33
+ if (currentSize + Buffer.byteLength(line) > maxBytes) {
34
+ entry.store_truncated = true;
35
+ this.writeEntry(entry);
36
+ return { ok: true, wroteLine: false, storeTruncated: true };
37
+ }
38
+ const wroteLine = this.writeProgressLine(line);
39
+ this.writeEntry(entry);
40
+ return { ok: wroteLine, wroteLine, storeTruncated: entry.store_truncated };
41
+ }
42
+ readEntry() {
43
+ if (!this.fsImpl.existsSync(this.metaPath))
44
+ return null;
45
+ const raw = this.fsImpl.readFileSync(this.metaPath, 'utf8');
46
+ return ObservabilityStoreEntrySchema.parse(JSON.parse(raw));
47
+ }
48
+ readOrInitEntry(ts = this.now()) {
49
+ return this.readEntry() ?? this.defaultEntry(ts);
50
+ }
51
+ saveEntry(entry) {
52
+ this.writeEntry(entry);
53
+ }
54
+ defaultEntry(ts) {
55
+ return ObservabilityStoreEntrySchema.parse({
56
+ run_id: this.options.runId,
57
+ session_id: this.options.sessionId,
58
+ status: 'active',
59
+ updated_at: ts,
60
+ last_stdout_at: null,
61
+ origin_message_id: this.options.originMessageId ?? null,
62
+ card_message_id: this.options.cardMessageId ?? null,
63
+ home_group_id: this.options.homeGroupId ?? null,
64
+ created_at: ts,
65
+ alert_reason: null,
66
+ });
67
+ }
68
+ now() {
69
+ return this.options.nowFn?.() ?? new Date().toISOString();
70
+ }
71
+ normalizeEvent(input) {
72
+ const text = input.text.length > 65_536 ? input.text.slice(0, 65_536) : input.text;
73
+ return RunObservabilityEventSchema.parse({
74
+ run_id: this.options.runId,
75
+ ts: input.ts,
76
+ line_index: input.lineIndex,
77
+ text,
78
+ source: input.source,
79
+ truncated: text !== input.text,
80
+ });
81
+ }
82
+ writeProgressLine(line) {
83
+ for (let attempt = 0; attempt < 2; attempt += 1) {
84
+ try {
85
+ this.fsImpl.appendFileSync(this.progressPath, line, 'utf8');
86
+ return true;
87
+ }
88
+ catch {
89
+ if (attempt === 1)
90
+ return false;
91
+ }
92
+ }
93
+ return false;
94
+ }
95
+ writeEntry(entry) {
96
+ const parsed = ObservabilityStoreEntrySchema.parse(entry);
97
+ this.fsImpl.writeFileSync(this.metaPath, JSON.stringify(parsed, null, 2));
98
+ }
99
+ }
100
+ export { RUN_OBSERVABILITY_ERROR_CODES };
@@ -0,0 +1,12 @@
1
+ import {} from './contracts.js';
2
+ export function shouldAlertSilentTimeout(entry, options) {
3
+ if (entry.alerted)
4
+ return false;
5
+ if (entry.cancelled)
6
+ return false;
7
+ if (entry.finalized)
8
+ return false;
9
+ const baseline = entry.last_stdout_at ?? (options.storeExists ? entry.updated_at : entry.created_at);
10
+ const elapsedMs = Date.parse(options.nowIso) - Date.parse(baseline);
11
+ return elapsedMs > options.silentTimeoutS * 1000;
12
+ }