@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,95 @@
1
+ import { realpathSync, statSync } from 'node:fs';
2
+ import { basename, extname, isAbsolute, relative, resolve, sep } from 'node:path';
3
+ /**
4
+ * 产物回传: run 结束时找出这一轮在 cwd 里新生成 / 改过的文件, 在结束卡上给出「发送」按钮.
5
+ * 只在点击时上传, 不自动外发; 只认 cwd 内的普通文件, 避免把别处的文件发进群.
6
+ */
7
+ export const ARTIFACT_MAX_BYTES = 20 * 1024 * 1024;
8
+ const MAX_ARTIFACTS = 3;
9
+ /** mtime 与 run 开始时间比较时容忍的时钟误差. */
10
+ const MTIME_SLACK_MS = 2_000;
11
+ const PATH_KEYS = ['file_path', 'path', 'filename', 'output_path', 'target_file'];
12
+ // 文本里的绝对路径或 ./ 开头的相对路径, 要求带扩展名, 免得把目录当成产物.
13
+ const TEXT_PATH_RE = /(?:^|[\s`'"((])((?:\/|\.\/)[^\s`'"()<>()]+\.[A-Za-z0-9]{1,8})(?=$|[\s`'"),.;:!?))。,;:])/gm;
14
+ // agent 用 Bash 生成文件时常只在正文里写 `chart.png` 这样的裸文件名; 只认反引号里的, 仍须在 cwd 内且本轮新生成.
15
+ const CODE_SPAN_PATH_RE = /`([^`\s/][^`\s]*\.[A-Za-z0-9]{1,8})`/g;
16
+ function toolPaths(tools) {
17
+ const paths = [];
18
+ for (const tool of tools) {
19
+ if (tool.isError || !tool.input || typeof tool.input !== 'object')
20
+ continue;
21
+ const input = tool.input;
22
+ for (const key of PATH_KEYS) {
23
+ if (typeof input[key] === 'string')
24
+ paths.push(input[key]);
25
+ }
26
+ }
27
+ return paths;
28
+ }
29
+ function textPaths(text) {
30
+ return [...text.matchAll(TEXT_PATH_RE), ...text.matchAll(CODE_SPAN_PATH_RE)].map((match) => match[1]);
31
+ }
32
+ function realCwd(cwd) {
33
+ try {
34
+ return realpathSync(cwd);
35
+ }
36
+ catch {
37
+ return null; // cwd 已被删除: 没有可回传的产物
38
+ }
39
+ }
40
+ export function findArtifacts(input) {
41
+ if (!input.cwd)
42
+ return [];
43
+ const root = realCwd(input.cwd);
44
+ if (!root)
45
+ return [];
46
+ const found = [];
47
+ for (const candidate of [...toolPaths(input.tools), ...textPaths(input.text)]) {
48
+ const absolute = isAbsolute(candidate) ? candidate : resolve(input.cwd, candidate);
49
+ let real;
50
+ try {
51
+ real = realpathSync(absolute);
52
+ }
53
+ catch {
54
+ continue; // agent 提到但不存在 (或已删除) 的路径
55
+ }
56
+ if (found.includes(real) || !(real === root || real.startsWith(`${root}${sep}`)))
57
+ continue;
58
+ const stat = statSync(real);
59
+ if (!stat.isFile() || stat.size === 0 || stat.size > ARTIFACT_MAX_BYTES)
60
+ continue;
61
+ if (stat.mtimeMs < input.startedAt - MTIME_SLACK_MS)
62
+ continue;
63
+ found.push(real);
64
+ if (found.length >= MAX_ARTIFACTS)
65
+ break;
66
+ }
67
+ return found;
68
+ }
69
+ export function artifactLabel(path, cwd) {
70
+ if (!cwd)
71
+ return basename(path);
72
+ const rel = relative(realCwd(cwd) ?? cwd, path);
73
+ return rel && !rel.startsWith('..') ? rel : basename(path);
74
+ }
75
+ const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.tiff', '.ico']);
76
+ /** im.v1.image.create 的上限; 更大的图片按普通文件发. */
77
+ const IMAGE_MAX_BYTES = 10 * 1024 * 1024;
78
+ export function uploadKind(path, size) {
79
+ const ext = extname(path).toLowerCase();
80
+ if (IMAGE_EXTS.has(ext) && size <= IMAGE_MAX_BYTES)
81
+ return { kind: 'image' };
82
+ if (ext === '.pdf')
83
+ return { kind: 'file', fileType: 'pdf' };
84
+ if (ext === '.mp4')
85
+ return { kind: 'file', fileType: 'mp4' };
86
+ if (ext === '.opus')
87
+ return { kind: 'file', fileType: 'opus' };
88
+ if (ext === '.doc' || ext === '.docx')
89
+ return { kind: 'file', fileType: 'doc' };
90
+ if (ext === '.xls' || ext === '.xlsx' || ext === '.csv')
91
+ return { kind: 'file', fileType: 'xls' };
92
+ if (ext === '.ppt' || ext === '.pptx')
93
+ return { kind: 'file', fileType: 'ppt' };
94
+ return { kind: 'file', fileType: 'stream' };
95
+ }
@@ -0,0 +1,38 @@
1
+ import * as Lark from '@larksuiteoapi/node-sdk';
2
+ function asNonEmptyString(value) {
3
+ if (typeof value !== 'string')
4
+ return undefined;
5
+ const trimmed = value.trim();
6
+ return trimmed ? trimmed : undefined;
7
+ }
8
+ function extractOpenId(payload) {
9
+ return (asNonEmptyString(payload.bot?.open_id) ??
10
+ asNonEmptyString(payload.open_id) ??
11
+ asNonEmptyString(payload.data?.bot?.open_id) ??
12
+ asNonEmptyString(payload.data?.open_id));
13
+ }
14
+ function extractAppName(payload) {
15
+ return (asNonEmptyString(payload.bot?.app_name) ??
16
+ asNonEmptyString(payload.app_name) ??
17
+ asNonEmptyString(payload.data?.bot?.app_name) ??
18
+ asNonEmptyString(payload.data?.app_name));
19
+ }
20
+ export function createLarkBotIdentityFetcher(client) {
21
+ return {
22
+ async fetch() {
23
+ const result = await client.request({
24
+ method: 'GET',
25
+ url: '/open-apis/bot/v3/info',
26
+ });
27
+ const payload = result;
28
+ const openId = extractOpenId(payload);
29
+ if (!openId) {
30
+ throw new Error('bot identity fetch returned no open_id');
31
+ }
32
+ return {
33
+ openId,
34
+ appName: extractAppName(payload),
35
+ };
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,121 @@
1
+ import pino, {} from 'pino';
2
+ import { errorSerializers } from './log-redact.js';
3
+ const defaultLogger = pino({ level: process.env['LOG_LEVEL'] ?? 'info', serializers: errorSerializers });
4
+ function extractPatchErrorDetails(error) {
5
+ const message = error instanceof Error ? error.message : String(error);
6
+ const response = typeof error === 'object' && error !== null && 'response' in error
7
+ ? error.response
8
+ : undefined;
9
+ return {
10
+ message,
11
+ code: response?.data?.code,
12
+ detail: response?.data?.msg ?? '',
13
+ };
14
+ }
15
+ function isRetryablePatchError(details) {
16
+ return details.message.includes('230020')
17
+ || details.message.includes('230099')
18
+ || details.message.includes('card action is lock')
19
+ || details.code === 230020
20
+ || details.code === 230099
21
+ || details.code === 99991400
22
+ || details.detail.includes('card action is lock');
23
+ }
24
+ export class CardPipeline {
25
+ patch;
26
+ pending = null;
27
+ timer = null;
28
+ backoffMs;
29
+ minIntervalMs;
30
+ logger;
31
+ label;
32
+ isPatching = false;
33
+ constructor(patch, minIntervalOrOptions = 800) {
34
+ this.patch = patch;
35
+ const options = typeof minIntervalOrOptions === 'number'
36
+ ? { minIntervalMs: minIntervalOrOptions }
37
+ : minIntervalOrOptions;
38
+ this.minIntervalMs = options.minIntervalMs ?? 800;
39
+ this.backoffMs = this.minIntervalMs;
40
+ this.logger = options.logger ?? defaultLogger;
41
+ this.label = options.label ?? 'card-pipeline';
42
+ }
43
+ async flush(card) {
44
+ this.pending = card;
45
+ if (this.timer) {
46
+ this.logger.debug({ label: this.label, hasPending: true }, 'card patch already scheduled');
47
+ return;
48
+ }
49
+ // If a patch is already in-flight, just leave the payload in pending —
50
+ // drain() will re-schedule when the current patch settles.
51
+ if (this.isPatching) {
52
+ this.logger.debug({ label: this.label, hasPending: true }, 'card patch in-flight, queued flush');
53
+ return;
54
+ }
55
+ this.logger.debug({ label: this.label, delayMs: this.minIntervalMs }, 'scheduled card patch flush');
56
+ this.timer = setTimeout(() => {
57
+ this.timer = null;
58
+ void this.drain('flush-timer');
59
+ }, this.minIntervalMs);
60
+ }
61
+ async force(card) {
62
+ this.pending = card;
63
+ if (this.timer) {
64
+ clearTimeout(this.timer);
65
+ this.timer = null;
66
+ this.logger.info({ label: this.label }, 'cleared pending card patch timer before force');
67
+ }
68
+ if (this.isPatching) {
69
+ // A patch is in-flight; the updated pending will be drained when it settles.
70
+ this.logger.info({ label: this.label }, 'card patch in-flight, force queued for after current patch');
71
+ return;
72
+ }
73
+ await this.drain('force');
74
+ }
75
+ async drain(trigger) {
76
+ const card = this.pending;
77
+ this.pending = null;
78
+ if (!card) {
79
+ this.logger.info({ label: this.label, trigger }, 'skipped card patch drain with no pending payload');
80
+ return;
81
+ }
82
+ this.isPatching = true;
83
+ try {
84
+ this.logger.info({ label: this.label, trigger, payloadSize: JSON.stringify(card).length }, 'patching card');
85
+ await this.patch(card);
86
+ this.backoffMs = this.minIntervalMs;
87
+ this.logger.info({ label: this.label, trigger }, 'patched card successfully');
88
+ // Drain any payload that arrived while we were in-flight.
89
+ if (this.pending && !this.timer) {
90
+ this.timer = setTimeout(() => {
91
+ this.timer = null;
92
+ void this.drain('flush-timer');
93
+ }, this.minIntervalMs);
94
+ }
95
+ }
96
+ catch (error) {
97
+ const details = extractPatchErrorDetails(error);
98
+ if (!isRetryablePatchError(details)) {
99
+ this.logger.error({ label: this.label, trigger, ...details, error }, 'card patch failed without retry');
100
+ throw error;
101
+ }
102
+ this.pending = card;
103
+ const retryMs = this.backoffMs;
104
+ this.backoffMs = Math.min(this.backoffMs * 2, 3200);
105
+ this.logger.warn({
106
+ label: this.label,
107
+ trigger,
108
+ retryMs,
109
+ nextBackoffMs: this.backoffMs,
110
+ ...details,
111
+ }, 'card patch failed with retryable error');
112
+ this.timer = setTimeout(() => {
113
+ this.timer = null;
114
+ void this.drain('retry-timer');
115
+ }, retryMs);
116
+ }
117
+ finally {
118
+ this.isPatching = false;
119
+ }
120
+ }
121
+ }
@@ -0,0 +1,360 @@
1
+ import { getAgentDisplay } from '../agent-display.js';
2
+ import { splitMarkdown, toFeishuMarkdown } from './markdown-style.js';
3
+ /**
4
+ * 运行卡两种形态:
5
+ *
6
+ * - 进行中 (live): 结构固定、带 element_id 槽位 + `config.streaming_mode`. 传输层
7
+ * (card-transport.ts) 发现结构没变就只把槽位文本推给 `cardElement.content`,
8
+ * 正文得到飞书原生打字机效果; 所以 live 卡里会变的内容 (耗时、阶段、工具) 都只能放在槽位里,
9
+ * header 与按钮在进行中保持不变.
10
+ * - 结束 / 停止中 / 系统卡 (static): 完整重排, 思考与工具收进折叠面板, 页脚带用量.
11
+ */
12
+ export const CARD_ELEMENT_IDS = {
13
+ process: 'wb_process',
14
+ main: 'wb_main',
15
+ status: 'wb_status',
16
+ };
17
+ export const STREAMING_CONFIG = {
18
+ print_frequency_ms: { default: 30, android: 25, ios: 40, pc: 50 },
19
+ print_step: { default: 2, android: 3, ios: 4, pc: 5 },
20
+ print_strategy: 'fast',
21
+ };
22
+ /** 单个 markdown 组件的安全长度; 超出部分由续卡接着发. */
23
+ export const MAIN_TEXT_MAX = 12000;
24
+ const THINKING_LIVE_TAIL = 300;
25
+ const THINKING_FINAL_MAX = 1500;
26
+ const LIVE_TOOL_LINES = 3;
27
+ const TOOL_SUMMARY_MAX = 80;
28
+ const CARD_SIZE_LIMIT = 28 * 1024;
29
+ function formatElapsed(startedAt) {
30
+ const elapsed = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
31
+ const mins = Math.floor(elapsed / 60);
32
+ const secs = elapsed % 60;
33
+ return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
34
+ }
35
+ function shortCwd(cwd) {
36
+ if (!cwd)
37
+ return '-';
38
+ const home = process.env['HOME'] ?? '';
39
+ if (home && cwd.startsWith(home))
40
+ return `~${cwd.slice(home.length)}`;
41
+ return cwd;
42
+ }
43
+ function statusBadge(state) {
44
+ if (state.stopState === 'stopped')
45
+ return '⏹ stopped';
46
+ if (state.stopState === 'stopping')
47
+ return '🟡 stopping';
48
+ if (state.terminalState === 'error')
49
+ return '🔴 error';
50
+ if (state.terminalState === 'done')
51
+ return '✅ 完成';
52
+ return '🟢 running';
53
+ }
54
+ function agentLine(state) {
55
+ return `${getAgentDisplay(state.agentId).emoji} ${state.agentDisplayName} · ${state.agentId}`;
56
+ }
57
+ function buildHeader(state, withElapsed) {
58
+ const sessionLine = state.sessionShortId ? ` · #${state.sessionShortId}` : '';
59
+ const elapsed = withElapsed ? ` · ${formatElapsed(state.startedAt)}` : '';
60
+ return `${agentLine(state)}\n${statusBadge(state)}${sessionLine}${elapsed} · ${shortCwd(state.cwd)}`;
61
+ }
62
+ function truncate(text, maxChars) {
63
+ return text.length <= maxChars ? text : `${text.slice(0, maxChars)}\n…`;
64
+ }
65
+ function tail(text, maxChars) {
66
+ return text.length <= maxChars ? text : `…${text.slice(text.length - maxChars)}`;
67
+ }
68
+ function showThinking() {
69
+ return process.env['WB_CARD_SHOW_THINKING'] !== '0';
70
+ }
71
+ /** 进行中的 agent 卡走流式形态; 系统提示卡 / 停止中 / 已结束都走完整卡. */
72
+ export function isLiveState(state) {
73
+ return state.agentId !== 'system' && state.terminalState === 'running' && state.stopState === 'running';
74
+ }
75
+ const INPUT_SUMMARY_KEYS = ['command', 'cmd', 'file_path', 'path', 'pattern', 'query', 'url', 'description', 'prompt'];
76
+ /** 工具参数的一句话摘要: 优先取常见的语义字段, 否则退回 JSON. */
77
+ export function toolSummary(tool) {
78
+ const input = tool.input;
79
+ let summary = '';
80
+ if (typeof input === 'string') {
81
+ summary = input;
82
+ }
83
+ else if (input && typeof input === 'object') {
84
+ const record = input;
85
+ const key = INPUT_SUMMARY_KEYS.find((candidate) => typeof record[candidate] === 'string' && record[candidate] !== '');
86
+ summary = key ? String(record[key]) : JSON.stringify(record);
87
+ }
88
+ summary = summary.replace(/\s+/g, ' ').trim();
89
+ if (summary === '{}')
90
+ return '';
91
+ return summary.length > TOOL_SUMMARY_MAX ? `${summary.slice(0, TOOL_SUMMARY_MAX)}…` : summary;
92
+ }
93
+ function toolLine(tool, finished) {
94
+ const icon = tool.isError ? '❌' : tool.output !== undefined || finished ? '✅' : '⏳';
95
+ const summary = toolSummary(tool).replace(/`/g, "'");
96
+ return `${icon} **${tool.name}**${summary ? ` \`${summary}\`` : ''}`;
97
+ }
98
+ function liveProcessText(state) {
99
+ const lines = [];
100
+ const thinking = state.thinking.trim();
101
+ if (thinking && showThinking())
102
+ lines.push(`🧠 ${tail(thinking, THINKING_LIVE_TAIL).replace(/\s*\n+\s*/g, ' ')}`);
103
+ if (state.tools.length > LIVE_TOOL_LINES)
104
+ lines.push(`☕ 已调用 ${state.tools.length} 个工具, 最近 ${LIVE_TOOL_LINES} 个:`);
105
+ for (const tool of state.tools.slice(-LIVE_TOOL_LINES))
106
+ lines.push(toolLine(tool, false));
107
+ return lines.join('\n');
108
+ }
109
+ function livePhase(state) {
110
+ const lastTool = state.tools.at(-1);
111
+ if (lastTool && lastTool.output === undefined && !lastTool.isError)
112
+ return '🧰 调用工具中';
113
+ if (state.text.trim())
114
+ return '✍️ 输出中';
115
+ return '🧠 思考中';
116
+ }
117
+ function noticeLines(state) {
118
+ const lines = (state.notices ?? []).map((notice) => `⚠️ ${notice}`);
119
+ if (state.queuedCount && state.terminalState === 'running') {
120
+ lines.push(`📥 已排队 ${state.queuedCount} 条, 本轮结束后自动接着处理`);
121
+ }
122
+ return lines;
123
+ }
124
+ function liveStatusText(state) {
125
+ const lines = [`${livePhase(state)} · ${formatElapsed(state.startedAt)}`, ...noticeLines(state)];
126
+ if (state.text.trim().length > MAIN_TEXT_MAX)
127
+ lines.push('📄 输出较长, 结束后分卡发送全文');
128
+ return lines.join('\n');
129
+ }
130
+ /** 结束卡正文按长度切块 (不切在代码块中间); 第一块留在运行卡里, 其余作为续卡发出. */
131
+ export function answerChunks(state) {
132
+ const text = state.text.trim();
133
+ if (!text)
134
+ return [];
135
+ if (state.agentId === 'system')
136
+ return [toFeishuMarkdown(text)];
137
+ return splitMarkdown(toFeishuMarkdown(text), MAIN_TEXT_MAX);
138
+ }
139
+ export function renderContinuationCard(state, chunk, index, total) {
140
+ return {
141
+ schema: '2.0',
142
+ config: { wide_screen_mode: true, summary: { content: `续 ${index}/${total}` } },
143
+ header: { title: { tag: 'plain_text', content: `${agentLine(state)} · 续 ${index}/${total}` } },
144
+ body: { elements: [{ tag: 'markdown', content: chunk }] },
145
+ };
146
+ }
147
+ function formatTokens(n) {
148
+ return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n);
149
+ }
150
+ function usageText(state) {
151
+ const usage = state.usage;
152
+ if (!usage)
153
+ return '';
154
+ const parts = [];
155
+ if (usage.inputTokens !== undefined || usage.outputTokens !== undefined) {
156
+ parts.push(`tokens ${formatTokens(usage.inputTokens ?? 0)} in / ${formatTokens(usage.outputTokens ?? 0)} out`);
157
+ }
158
+ if (usage.costUsd !== undefined)
159
+ parts.push(`$${usage.costUsd.toFixed(usage.costUsd < 1 ? 3 : 2)}`);
160
+ return parts.join(' · ');
161
+ }
162
+ function stopButtonText(state) {
163
+ if (state.stopState === 'stopped')
164
+ return '已停止';
165
+ if (state.stopState === 'stopping')
166
+ return '停止中...';
167
+ return '停止';
168
+ }
169
+ function buttonRow(buttons) {
170
+ return {
171
+ tag: 'column_set',
172
+ columns: buttons.map((button) => ({
173
+ tag: 'column',
174
+ width: 'weighted',
175
+ weight: 1,
176
+ elements: [button],
177
+ })),
178
+ };
179
+ }
180
+ function callbackButton(label, action, type = 'default') {
181
+ return { tag: 'button', text: { tag: 'plain_text', content: label }, type, behaviors: [{ type: 'callback', value: { action } }] };
182
+ }
183
+ /** 结束卡的后续操作; 回调里校验发起人, 见 EventHandler.handleRunFollowUpAction. */
184
+ export const RUN_FOLLOW_UP_ACTIONS = { retry: 'run_retry', continue: 'run_continue', reset: 'run_reset' };
185
+ export const SEND_ARTIFACT_ACTION = 'send_artifact';
186
+ function artifactElements(state) {
187
+ const artifacts = state.artifacts ?? [];
188
+ if (artifacts.length === 0)
189
+ return [];
190
+ return [
191
+ { tag: 'markdown', content: `📎 本轮产物: ${artifacts.map((artifact) => `\`${artifact.label}\``).join(' ')}`, text_size: 'notation' },
192
+ buttonRow(artifacts.map((artifact, index) => ({
193
+ tag: 'button',
194
+ text: { tag: 'plain_text', content: `发送 ${artifact.label.split('/').pop()}` },
195
+ type: 'default',
196
+ behaviors: [{ type: 'callback', value: { action: SEND_ARTIFACT_ACTION, index } }],
197
+ }))),
198
+ ];
199
+ }
200
+ function buildActionElements(state) {
201
+ if (state.terminalState !== 'running' && state.stopState === 'running') {
202
+ if (state.agentId === 'system')
203
+ return [];
204
+ return [buttonRow([
205
+ callbackButton('继续', RUN_FOLLOW_UP_ACTIONS.continue, 'primary_filled'),
206
+ callbackButton('重试', RUN_FOLLOW_UP_ACTIONS.retry),
207
+ callbackButton('新会话', RUN_FOLLOW_UP_ACTIONS.reset),
208
+ ])];
209
+ }
210
+ if (state.stopState !== 'running') {
211
+ return [{
212
+ tag: 'markdown',
213
+ content: `操作: ${stopButtonText(state)}`,
214
+ }];
215
+ }
216
+ const buttons = [
217
+ {
218
+ tag: 'button',
219
+ text: { tag: 'plain_text', content: stopButtonText(state) },
220
+ type: 'primary_filled',
221
+ behaviors: [{ type: 'callback', value: { action: 'stop' } }],
222
+ },
223
+ ];
224
+ if (state.adminCancelEnabled && state.sessionShortId) {
225
+ buttons.push({
226
+ tag: 'button',
227
+ text: { tag: 'plain_text', content: '叫停' },
228
+ type: 'default',
229
+ behaviors: [{ type: 'callback', value: { action: 'admin_cancel', shortId: state.sessionShortId } }],
230
+ });
231
+ }
232
+ return [buttonRow(buttons)];
233
+ }
234
+ function collapsiblePanel(title, content, border = 'grey') {
235
+ return {
236
+ tag: 'collapsible_panel',
237
+ expanded: false,
238
+ header: {
239
+ title: { tag: 'markdown', content: title },
240
+ vertical_align: 'center',
241
+ icon: { tag: 'standard_icon', token: 'down-small-ccm_outlined', size: '16px 16px' },
242
+ icon_position: 'follow_text',
243
+ icon_expanded_angle: -180,
244
+ },
245
+ border: { color: border, corner_radius: '5px' },
246
+ vertical_spacing: '8px',
247
+ padding: '8px 8px 8px 8px',
248
+ elements: [{ tag: 'markdown', content, text_size: 'notation' }],
249
+ };
250
+ }
251
+ /** 会话列表 / 通知里的预览文字. */
252
+ function summaryText(state) {
253
+ if (isLiveState(state))
254
+ return `${state.agentDisplayName} 处理中…`;
255
+ if (state.stopState === 'stopping')
256
+ return '停止中…';
257
+ if (state.stopState === 'stopped')
258
+ return '已停止';
259
+ if (state.terminalState === 'error')
260
+ return `出错: ${(state.errorMessage ?? '').slice(0, 50)}`;
261
+ const firstLine = state.text.split('\n').find((line) => line.trim()) ?? '';
262
+ return firstLine.replace(/[#*`>|]/g, '').trim().slice(0, 60) || '已完成';
263
+ }
264
+ function renderLiveCard(state) {
265
+ return {
266
+ schema: '2.0',
267
+ config: {
268
+ wide_screen_mode: true,
269
+ streaming_mode: true,
270
+ streaming_config: STREAMING_CONFIG,
271
+ summary: { content: summaryText(state) },
272
+ },
273
+ header: { title: { tag: 'plain_text', content: buildHeader(state, false) } },
274
+ body: {
275
+ elements: [
276
+ { tag: 'markdown', element_id: CARD_ELEMENT_IDS.process, content: liveProcessText(state), text_size: 'notation' },
277
+ { tag: 'markdown', element_id: CARD_ELEMENT_IDS.main, content: toFeishuMarkdown(truncate(state.text.trim(), MAIN_TEXT_MAX)) },
278
+ { tag: 'markdown', element_id: CARD_ELEMENT_IDS.status, content: liveStatusText(state), text_size: 'notation' },
279
+ ...buildActionElements(state),
280
+ ],
281
+ },
282
+ };
283
+ }
284
+ function toolsPanel(state) {
285
+ const finished = state.terminalState !== 'running' || state.stopState !== 'running';
286
+ const failed = state.tools.filter((tool) => tool.isError).length;
287
+ const title = `🧰 **${state.tools.length} 个工具调用**${failed > 0 ? ` · ${failed} 个失败` : ''}`;
288
+ const body = state.tools.map((tool) => {
289
+ const line = `- ${toolLine(tool, finished)}`;
290
+ return tool.isError && tool.output ? `${line}\n ${truncate(tool.output.replace(/\s*\n+\s*/g, ' '), 200)}` : line;
291
+ }).join('\n');
292
+ return collapsiblePanel(title, body, failed > 0 ? 'red' : 'grey');
293
+ }
294
+ function renderStaticCard(state) {
295
+ const sections = [];
296
+ const text = state.text.trim();
297
+ const isAgentCard = state.agentId !== 'system';
298
+ const notices = noticeLines(state);
299
+ if (notices.length > 0)
300
+ sections.push({ tag: 'markdown', content: notices.join('\n'), text_size: 'notation' });
301
+ const thinking = state.thinking.trim();
302
+ if (isAgentCard && thinking && showThinking()) {
303
+ sections.push(collapsiblePanel('🧠 **思考过程**', truncate(thinking, THINKING_FINAL_MAX)));
304
+ }
305
+ // 被停止的 run 工具记录没有参考价值, 只留结论.
306
+ if (isAgentCard && state.tools.length > 0 && state.stopState === 'running')
307
+ sections.push(toolsPanel(state));
308
+ const chunks = answerChunks(state);
309
+ if (chunks.length > 0)
310
+ sections.push({ tag: 'markdown', content: truncate(chunks[0], MAIN_TEXT_MAX) });
311
+ if (chunks.length > 1)
312
+ sections.push({ tag: 'markdown', content: `📄 输出较长, 共 ${chunks.length} 张卡, 后续见下方「续」卡`, text_size: 'notation' });
313
+ // claude 遇到 API 错误时会把同一句错误也作为正文输出, 正文已经以它结尾就不再重复一遍.
314
+ const errorMessage = state.errorMessage?.trim();
315
+ if (errorMessage && !text.endsWith(errorMessage))
316
+ sections.push({ tag: 'markdown', content: `**Error**\n${truncate(errorMessage, 2000)}` });
317
+ if (state.includeMeta) {
318
+ const meta = [
319
+ `agent: ${state.agentId}`,
320
+ `cwd: ${state.cwd ?? '-'}`,
321
+ `context: ${state.hasContext ? '有' : '无'}`,
322
+ `model: ${state.model ?? '-'}`,
323
+ ];
324
+ const usage = usageText(state);
325
+ if (usage)
326
+ meta.push(`usage: ${usage}`);
327
+ sections.push({ tag: 'markdown', content: meta.join('\n'), text_size: 'notation' });
328
+ }
329
+ const card = {
330
+ schema: '2.0',
331
+ config: { wide_screen_mode: true, summary: { content: summaryText(state) } },
332
+ header: { title: { tag: 'plain_text', content: buildHeader(state, true) } },
333
+ body: {
334
+ elements: [...sections, ...artifactElements(state), ...buildActionElements(state)],
335
+ },
336
+ };
337
+ if (JSON.stringify(card).length <= CARD_SIZE_LIMIT)
338
+ return card;
339
+ return {
340
+ ...card,
341
+ body: {
342
+ elements: [
343
+ { tag: 'markdown', content: toFeishuMarkdown(truncate(text || state.errorMessage || '结果过长,已降级显示。', 6000)) },
344
+ { tag: 'markdown', content: '完整结果过长,当前卡片已降级显示。' },
345
+ ...buildActionElements(state),
346
+ ],
347
+ },
348
+ };
349
+ }
350
+ /** 走 im.message 接口 (非 CardKit 实体) 时去掉流式配置; 消息卡片不认 streaming_mode. */
351
+ export function withoutStreaming(card) {
352
+ const config = card['config'];
353
+ if (!config || typeof config !== 'object' || !('streaming_mode' in config))
354
+ return card;
355
+ const { streaming_mode: _mode, streaming_config: _config, ...rest } = config;
356
+ return { ...card, config: rest };
357
+ }
358
+ export function renderCard(state) {
359
+ return isLiveState(state) ? renderLiveCard(state) : renderStaticCard(state);
360
+ }