@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.
- package/LICENSE +21 -0
- package/README.en.md +418 -0
- package/README.md +418 -2
- package/apps/wb-bot/README.md +118 -0
- package/dist/apps/wb-bot/src/agent-display.js +24 -0
- package/dist/apps/wb-bot/src/agent-registry.js +188 -0
- package/dist/apps/wb-bot/src/approval-gate/audit.js +37 -0
- package/dist/apps/wb-bot/src/approval-gate/cards.js +94 -0
- package/dist/apps/wb-bot/src/approval-gate/hook-env.js +15 -0
- package/dist/apps/wb-bot/src/approval-gate/hook-files.js +311 -0
- package/dist/apps/wb-bot/src/approval-gate/hook-main.js +147 -0
- package/dist/apps/wb-bot/src/approval-gate/notifier.js +29 -0
- package/dist/apps/wb-bot/src/approval-gate/store.js +157 -0
- package/dist/apps/wb-bot/src/binding/migration-runner.js +35 -0
- package/dist/apps/wb-bot/src/binding/migrations/001-add-run-id-agent-id.js +8 -0
- package/dist/apps/wb-bot/src/binding/migrations/002-add-bot-id.js +34 -0
- package/dist/apps/wb-bot/src/binding/migrations/003-inflight-card-agent-id-pk.js +31 -0
- package/dist/apps/wb-bot/src/binding/migrations/004-thread-alias-topic-key.js +31 -0
- package/dist/apps/wb-bot/src/binding/migrations/005-card-entity.js +21 -0
- package/dist/apps/wb-bot/src/binding/migrations/006-group-setting.js +17 -0
- package/dist/apps/wb-bot/src/binding/schema.js +58 -0
- package/dist/apps/wb-bot/src/binding/sleep-sync.js +5 -0
- package/dist/apps/wb-bot/src/binding/store.js +270 -0
- package/dist/apps/wb-bot/src/binding/task-index.js +127 -0
- package/dist/apps/wb-bot/src/boot/entry-path.js +9 -0
- package/dist/apps/wb-bot/src/boot/integrity.js +47 -0
- package/dist/apps/wb-bot/src/boot/logger.js +44 -0
- package/dist/apps/wb-bot/src/captain/bot-discovery.js +42 -0
- package/dist/apps/wb-bot/src/captain/captain-context.js +26 -0
- package/dist/apps/wb-bot/src/captain/captain-gate.js +9 -0
- package/dist/apps/wb-bot/src/captain/captain-status.js +101 -0
- package/dist/apps/wb-bot/src/captain/captain-stop-all.js +72 -0
- package/dist/apps/wb-bot/src/captain/list-bots.js +39 -0
- package/dist/apps/wb-bot/src/cli/doctor.js +105 -0
- package/dist/apps/wb-bot/src/cli/init.js +122 -0
- package/dist/apps/wb-bot/src/cli/parse-args.js +31 -0
- package/dist/apps/wb-bot/src/cli/preflight.js +9 -0
- package/dist/apps/wb-bot/src/cli/setup-checklist.js +10 -0
- package/dist/apps/wb-bot/src/commands/health.js +328 -0
- package/dist/apps/wb-bot/src/commands/history.js +100 -0
- package/dist/apps/wb-bot/src/commands/logs.js +91 -0
- package/dist/apps/wb-bot/src/commands/parser.js +43 -0
- package/dist/apps/wb-bot/src/commands/queue-metrics.js +24 -0
- package/dist/apps/wb-bot/src/commands/resume.js +48 -0
- package/dist/apps/wb-bot/src/commands/router.js +299 -0
- package/dist/apps/wb-bot/src/commands/status.js +77 -0
- package/dist/apps/wb-bot/src/commands/tasks.js +106 -0
- package/dist/apps/wb-bot/src/commands/wb-approval.js +86 -0
- package/dist/apps/wb-bot/src/commands/wb-audit.js +46 -0
- package/dist/apps/wb-bot/src/commands/wb-mute.js +84 -0
- package/dist/apps/wb-bot/src/commands/wb-sync.js +58 -0
- package/dist/apps/wb-bot/src/config/approval-code-owners.js +95 -0
- package/dist/apps/wb-bot/src/config/bot-env.js +80 -0
- package/dist/apps/wb-bot/src/config/config-paths.js +16 -0
- package/dist/apps/wb-bot/src/config/env.js +43 -0
- package/dist/apps/wb-bot/src/config/lark-credentials.js +14 -0
- package/dist/apps/wb-bot/src/e2e/preflight-env.js +147 -0
- package/dist/apps/wb-bot/src/e2e/preflight-main.js +12 -0
- package/dist/apps/wb-bot/src/feishu/admin-alert.js +94 -0
- package/dist/apps/wb-bot/src/feishu/artifacts.js +95 -0
- package/dist/apps/wb-bot/src/feishu/bot-identity.js +38 -0
- package/dist/apps/wb-bot/src/feishu/card-pipeline.js +121 -0
- package/dist/apps/wb-bot/src/feishu/card-renderer.js +360 -0
- package/dist/apps/wb-bot/src/feishu/card-transport.js +294 -0
- package/dist/apps/wb-bot/src/feishu/chat-mode-cache.js +47 -0
- package/dist/apps/wb-bot/src/feishu/completion-push.js +30 -0
- package/dist/apps/wb-bot/src/feishu/doc-comment.js +183 -0
- package/dist/apps/wb-bot/src/feishu/event-handler.js +2634 -0
- package/dist/apps/wb-bot/src/feishu/events-file-reader.js +162 -0
- package/dist/apps/wb-bot/src/feishu/inbound-context.js +53 -0
- package/dist/apps/wb-bot/src/feishu/keepalive.js +85 -0
- package/dist/apps/wb-bot/src/feishu/log-redact.js +20 -0
- package/dist/apps/wb-bot/src/feishu/markdown-style.js +95 -0
- package/dist/apps/wb-bot/src/feishu/media-cache.js +92 -0
- package/dist/apps/wb-bot/src/feishu/message-parser.js +126 -0
- package/dist/apps/wb-bot/src/feishu/pending-queue.js +133 -0
- package/dist/apps/wb-bot/src/feishu/reaction.js +44 -0
- package/dist/apps/wb-bot/src/feishu/reverse-at-im-handler.js +345 -0
- package/dist/apps/wb-bot/src/feishu/run-state.js +30 -0
- package/dist/apps/wb-bot/src/feishu/session-short-id.js +9 -0
- package/dist/apps/wb-bot/src/feishu/stream-state.js +72 -0
- package/dist/apps/wb-bot/src/feishu/topic-key.js +34 -0
- package/dist/apps/wb-bot/src/feishu/transport.js +768 -0
- package/dist/apps/wb-bot/src/feishu/wb-runner-spawner.js +84 -0
- package/dist/apps/wb-bot/src/heartbeat/bot-heartbeat.js +20 -0
- package/dist/apps/wb-bot/src/main.js +144 -0
- package/dist/apps/wb-bot/src/multi/discovery.js +53 -0
- package/dist/apps/wb-bot/src/multi/main.js +57 -0
- package/dist/apps/wb-bot/src/multi/parse-args.js +17 -0
- package/dist/apps/wb-bot/src/multi/supervisor.js +288 -0
- package/dist/apps/wb-bot/src/run-observability/orchestrator.js +61 -0
- package/dist/apps/wb-bot/src/security/bot-id-validator.js +18 -0
- package/dist/apps/wb-bot/src/security/cwd-guard.js +72 -0
- package/dist/apps/wb-bot/src/security/env-whitelist.js +94 -0
- package/dist/apps/wb-bot/src/server/wire-up.js +125 -0
- package/dist/apps/wb-cli/src/commands/approval.js +101 -0
- package/dist/apps/wb-cli/src/commands/attach.js +31 -0
- package/dist/apps/wb-cli/src/commands/audit.js +71 -0
- package/dist/apps/wb-cli/src/commands/captain.js +72 -0
- package/dist/apps/wb-cli/src/commands/debug.js +22 -0
- package/dist/apps/wb-cli/src/commands/history.js +75 -0
- package/dist/apps/wb-cli/src/commands/list.js +24 -0
- package/dist/apps/wb-cli/src/commands/logs.js +122 -0
- package/dist/apps/wb-cli/src/commands/resume.js +50 -0
- package/dist/apps/wb-cli/src/commands/runs.js +75 -0
- package/dist/apps/wb-cli/src/commands/status.js +35 -0
- package/dist/apps/wb-cli/src/commands/watch.js +73 -0
- package/dist/apps/wb-cli/src/main.js +312 -0
- package/dist/packages/core/src/agent/claude-code.js +354 -0
- package/dist/packages/core/src/agent/cli-subprocess.js +244 -0
- package/dist/packages/core/src/agent/codex.js +231 -0
- package/dist/packages/core/src/agent/index.js +5 -0
- package/dist/packages/core/src/agent/registry.js +47 -0
- package/dist/packages/core/src/agent/types.js +1 -0
- package/dist/packages/core/src/approval-gate/audit.js +16 -0
- package/dist/packages/core/src/approval-gate/contracts.js +26 -0
- package/dist/packages/core/src/approval-gate/matcher.js +112 -0
- package/dist/packages/core/src/audit-pipe/audit-pipe-main.js +38 -0
- package/dist/packages/core/src/audit-pipe/bitable-sink.js +156 -0
- package/dist/packages/core/src/audit-pipe/config.js +105 -0
- package/dist/packages/core/src/audit-pipe/contracts.js +33 -0
- package/dist/packages/core/src/audit-pipe/index.js +2 -0
- package/dist/packages/core/src/audit-pipe/mirror-sink.js +21 -0
- package/dist/packages/core/src/audit-pipe/normalizer.js +129 -0
- package/dist/packages/core/src/audit-pipe/orchestrator.js +252 -0
- package/dist/packages/core/src/audit-pipe/parser.js +24 -0
- package/dist/packages/core/src/audit-pipe/tailer.js +46 -0
- package/dist/packages/core/src/audit-pipe/wal.js +71 -0
- package/dist/packages/core/src/calendar-hook/config.js +45 -0
- package/dist/packages/core/src/calendar-hook/contracts.js +66 -0
- package/dist/packages/core/src/calendar-hook/index.js +5 -0
- package/dist/packages/core/src/calendar-hook/scheduler.js +169 -0
- package/dist/packages/core/src/calendar-hook/service.js +189 -0
- package/dist/packages/core/src/calendar-hook/transport.js +66 -0
- package/dist/packages/core/src/captain/captain-service.js +160 -0
- package/dist/packages/core/src/captain/command-catalog.js +41 -0
- package/dist/packages/core/src/captain/concurrency-config.js +10 -0
- package/dist/packages/core/src/captain/concurrency-queue-index.js +94 -0
- package/dist/packages/core/src/captain/concurrency-queue-store.js +43 -0
- package/dist/packages/core/src/captain/contracts.js +102 -0
- package/dist/packages/core/src/captain/cwd-inference.js +29 -0
- package/dist/packages/core/src/captain/enqueue-or-spawn.js +63 -0
- package/dist/packages/core/src/captain/index.js +27 -0
- package/dist/packages/core/src/captain/queue-metrics/aggregator.js +98 -0
- package/dist/packages/core/src/captain/queue-metrics/contracts.js +42 -0
- package/dist/packages/core/src/captain/queue-metrics/event-store.js +26 -0
- package/dist/packages/core/src/captain/session-store.js +429 -0
- package/dist/packages/core/src/captain/toml-loader.js +86 -0
- package/dist/packages/core/src/config/errors.js +15 -0
- package/dist/packages/core/src/config/registry.js +34 -0
- package/dist/packages/core/src/errors/codes.js +98 -0
- package/dist/packages/core/src/group-sync/autodoc.js +166 -0
- package/dist/packages/core/src/group-sync/config.js +45 -0
- package/dist/packages/core/src/group-sync/contracts.js +126 -0
- package/dist/packages/core/src/group-sync/dispatch.js +163 -0
- package/dist/packages/core/src/group-sync/index.js +9 -0
- package/dist/packages/core/src/group-sync/revdiff.js +138 -0
- package/dist/packages/core/src/group-sync/scheduler.js +93 -0
- package/dist/packages/core/src/group-sync/service.js +79 -0
- package/dist/packages/core/src/group-sync/transport.js +97 -0
- package/dist/packages/core/src/group-sync/xref.js +139 -0
- package/dist/packages/core/src/index.js +23 -0
- package/dist/packages/core/src/minutes/adapter.js +187 -0
- package/dist/packages/core/src/minutes/client.js +46 -0
- package/dist/packages/core/src/minutes/contracts.js +36 -0
- package/dist/packages/core/src/minutes/index.js +3 -0
- package/dist/packages/core/src/paths.js +158 -0
- package/dist/packages/core/src/periodic-tasks/config.js +45 -0
- package/dist/packages/core/src/periodic-tasks/contracts.js +75 -0
- package/dist/packages/core/src/periodic-tasks/index.js +4 -0
- package/dist/packages/core/src/periodic-tasks/orchestrator.js +249 -0
- package/dist/packages/core/src/periodic-tasks/state.js +29 -0
- package/dist/packages/core/src/reverse-channel/attach-handler.js +108 -0
- package/dist/packages/core/src/reverse-channel/audit-encoder.js +61 -0
- package/dist/packages/core/src/reverse-channel/contracts.js +136 -0
- package/dist/packages/core/src/reverse-channel/echo-tailer.js +36 -0
- package/dist/packages/core/src/reverse-channel/handoff.js +238 -0
- package/dist/packages/core/src/reverse-channel/index.js +5 -0
- package/dist/packages/core/src/reverse-channel/ipc-client.js +110 -0
- package/dist/packages/core/src/reverse-channel/ipc-control-handler.js +27 -0
- package/dist/packages/core/src/reverse-channel/ipc-server.js +127 -0
- package/dist/packages/core/src/reverse-channel/mute-registry.js +113 -0
- package/dist/packages/core/src/reverse-channel/pid-resolver.js +41 -0
- package/dist/packages/core/src/reverse-channel/reverse-at-handler.js +19 -0
- package/dist/packages/core/src/reverse-channel/sla-tracker.js +51 -0
- package/dist/packages/core/src/run-observability/alert-card-renderer.js +24 -0
- package/dist/packages/core/src/run-observability/alert-pusher.js +47 -0
- package/dist/packages/core/src/run-observability/card-refresher.js +31 -0
- package/dist/packages/core/src/run-observability/card-renderer-progress.js +33 -0
- package/dist/packages/core/src/run-observability/config-loader.js +23 -0
- package/dist/packages/core/src/run-observability/contracts.js +107 -0
- package/dist/packages/core/src/run-observability/exit-code-detector.js +16 -0
- package/dist/packages/core/src/run-observability/finalizer.js +114 -0
- package/dist/packages/core/src/run-observability/index.js +12 -0
- package/dist/packages/core/src/run-observability/obs-toggle-handler.js +29 -0
- package/dist/packages/core/src/run-observability/progress-collector.js +53 -0
- package/dist/packages/core/src/run-observability/progress-store.js +100 -0
- package/dist/packages/core/src/run-observability/silent-timeout-detector.js +12 -0
- package/dist/packages/core/src/run-registry/bitable-writer.js +308 -0
- package/dist/packages/core/src/run-registry/config.js +77 -0
- package/dist/packages/core/src/run-registry/contracts.js +114 -0
- package/dist/packages/core/src/run-registry/doc-sink-classifier.js +0 -0
- package/dist/packages/core/src/run-registry/doc-sink-transport.js +63 -0
- package/dist/packages/core/src/run-registry/doc-sink.js +200 -0
- package/dist/packages/core/src/run-registry/extractor.js +40 -0
- package/dist/packages/core/src/run-registry/index.js +11 -0
- package/dist/packages/core/src/run-registry/inherit.js +11 -0
- package/dist/packages/core/src/run-registry/orchestrator.js +86 -0
- package/dist/packages/core/src/run-registry/run-registry-main.js +38 -0
- package/dist/packages/core/src/run-registry/tailer.js +390 -0
- package/dist/packages/core/src/run-registry/wal.js +106 -0
- package/dist/packages/core/src/runner/event-replay.js +65 -0
- package/dist/packages/core/src/runner/wb-runner-main.js +27 -0
- package/dist/packages/core/src/runner/wb-runner.js +237 -0
- package/dist/packages/core/src/util/entry-module.js +21 -0
- package/dist/packages/core/src/util/ndjson-rotation.js +99 -0
- package/package.json +76 -4
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync, createReadStream } from 'node:fs';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
import { EventEmitter } from 'node:events';
|
|
4
|
+
import { createClaudeStreamMapper } from '../../../../packages/core/src/agent/claude-code.js';
|
|
5
|
+
import { mapCodexStreamEvent } from '../../../../packages/core/src/agent/codex.js';
|
|
6
|
+
export const EVENTS_SUPPORTED_SCHEMA_VERSION = 1;
|
|
7
|
+
/** wb-runner 自己补写的终态行, 以及已经是 AgentEvent 形状的行. */
|
|
8
|
+
const AGENT_EVENT_TYPES = new Set(['text', 'thinking', 'tool_use', 'tool_result', 'usage', 'done']);
|
|
9
|
+
/**
|
|
10
|
+
* wb-runner 把 agent CLI 的原始 stdout (claude stream-json / codex exec --json) 逐行写进
|
|
11
|
+
* events.ndjson, 只有终态 done / error 是它自己补的 AgentEvent. 读的一侧按 agent 翻译成
|
|
12
|
+
* AgentEvent, 否则正文 / 思考 / 工具 / 用量 / continuationToken 都到不了卡片和绑定.
|
|
13
|
+
*/
|
|
14
|
+
export function runnerEventMapper(agentId, req) {
|
|
15
|
+
const mapClaude = createClaudeStreamMapper();
|
|
16
|
+
return (raw) => {
|
|
17
|
+
const type = typeof raw['type'] === 'string' ? raw['type'] : '';
|
|
18
|
+
if (AGENT_EVENT_TYPES.has(type))
|
|
19
|
+
return [raw];
|
|
20
|
+
if (agentId === 'claude-code') {
|
|
21
|
+
// claude 原始流没有顶层 error, 这里的 error 只可能是 wb-runner 补的.
|
|
22
|
+
return type === 'error' ? [raw] : mapClaude(raw);
|
|
23
|
+
}
|
|
24
|
+
if (agentId === 'codex')
|
|
25
|
+
return mapCodexStreamEvent(raw, { prompt: '', ...req });
|
|
26
|
+
return [raw];
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export function extractLatestContinuationToken(events) {
|
|
30
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
31
|
+
const ev = events[i];
|
|
32
|
+
if ((ev['type'] === 'done' || ev['type'] === 'system') && typeof ev['continuationToken'] === 'string') {
|
|
33
|
+
return ev['continuationToken'];
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
export function checkSchemaVersion(specOrHeader) {
|
|
39
|
+
if (!specOrHeader || specOrHeader['schemaVersion'] === undefined) {
|
|
40
|
+
return { ok: true, version: 1 };
|
|
41
|
+
}
|
|
42
|
+
const version = typeof specOrHeader['schemaVersion'] === 'number' ? specOrHeader['schemaVersion'] : 1;
|
|
43
|
+
if (version > EVENTS_SUPPORTED_SCHEMA_VERSION) {
|
|
44
|
+
return { ok: false, version, message: `schemaVersion ${version} > supported ${EVENTS_SUPPORTED_SCHEMA_VERSION}` };
|
|
45
|
+
}
|
|
46
|
+
return { ok: true, version };
|
|
47
|
+
}
|
|
48
|
+
export function parseEventLine(line) {
|
|
49
|
+
try {
|
|
50
|
+
const parsed = JSON.parse(line);
|
|
51
|
+
if (typeof parsed === 'object' && parsed !== null && typeof parsed.type === 'string') {
|
|
52
|
+
return parsed;
|
|
53
|
+
}
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export function readEventsSync(ndjsonPath) {
|
|
61
|
+
if (!existsSync(ndjsonPath))
|
|
62
|
+
return [];
|
|
63
|
+
try {
|
|
64
|
+
const raw = readFileSync(ndjsonPath, 'utf8');
|
|
65
|
+
const lines = raw.split('\n');
|
|
66
|
+
const events = [];
|
|
67
|
+
for (const line of lines) {
|
|
68
|
+
const parsed = parseEventLine(line);
|
|
69
|
+
if (parsed)
|
|
70
|
+
events.push(parsed);
|
|
71
|
+
}
|
|
72
|
+
return events;
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
export class EventsFileReader extends EventEmitter {
|
|
79
|
+
ndjsonPath;
|
|
80
|
+
mapEvent;
|
|
81
|
+
offset = 0;
|
|
82
|
+
timer = null;
|
|
83
|
+
closed = false;
|
|
84
|
+
constructor(ndjsonPath, startOffset = 0, mapEvent) {
|
|
85
|
+
super();
|
|
86
|
+
this.ndjsonPath = ndjsonPath;
|
|
87
|
+
this.mapEvent = mapEvent;
|
|
88
|
+
this.offset = startOffset;
|
|
89
|
+
}
|
|
90
|
+
start() {
|
|
91
|
+
this.timer = setInterval(() => this.poll(), 200);
|
|
92
|
+
}
|
|
93
|
+
stop() {
|
|
94
|
+
this.closed = true;
|
|
95
|
+
if (this.timer) {
|
|
96
|
+
clearInterval(this.timer);
|
|
97
|
+
this.timer = null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
poll() {
|
|
101
|
+
if (this.closed)
|
|
102
|
+
return;
|
|
103
|
+
if (!existsSync(this.ndjsonPath))
|
|
104
|
+
return;
|
|
105
|
+
try {
|
|
106
|
+
const { size } = statSync(this.ndjsonPath);
|
|
107
|
+
if (size <= this.offset)
|
|
108
|
+
return;
|
|
109
|
+
const stream = createReadStream(this.ndjsonPath, { start: this.offset, encoding: 'utf8' });
|
|
110
|
+
const rl = createInterface({ input: stream });
|
|
111
|
+
rl.on('line', (line) => {
|
|
112
|
+
if (this.closed)
|
|
113
|
+
return;
|
|
114
|
+
try {
|
|
115
|
+
const parsed = JSON.parse(line);
|
|
116
|
+
if (typeof parsed === 'object' && parsed !== null && parsed.type) {
|
|
117
|
+
const events = this.mapEvent ? this.mapEvent(parsed) : [parsed];
|
|
118
|
+
for (const event of events)
|
|
119
|
+
this.emit('event', event);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
// skip non-JSON lines
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
rl.once('close', () => {
|
|
127
|
+
this.offset = size;
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
// file access error, retry next poll
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
async *events() {
|
|
135
|
+
const queue = [];
|
|
136
|
+
let resolve = null;
|
|
137
|
+
const onEvent = (event) => {
|
|
138
|
+
queue.push(event);
|
|
139
|
+
if (resolve) {
|
|
140
|
+
resolve();
|
|
141
|
+
resolve = null;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
this.on('event', onEvent);
|
|
145
|
+
try {
|
|
146
|
+
while (!this.closed) {
|
|
147
|
+
if (queue.length > 0) {
|
|
148
|
+
yield queue.shift();
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
await new Promise((r) => { resolve = r; });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
while (queue.length > 0) {
|
|
155
|
+
yield queue.shift();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
finally {
|
|
159
|
+
this.removeListener('event', onEvent);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { parseApiMessageItem } from './message-parser.js';
|
|
2
|
+
function quoteBlock(text) {
|
|
3
|
+
return text.split('\n').map((line) => `> ${line}`).join('\n');
|
|
4
|
+
}
|
|
5
|
+
export async function buildAgentInput(event, deps) {
|
|
6
|
+
const notices = [];
|
|
7
|
+
let quoted = null;
|
|
8
|
+
if (event.parentId) {
|
|
9
|
+
if (!deps.fetchMessage) {
|
|
10
|
+
notices.push('引用的消息未读取: 当前通道不支持拉取消息');
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
try {
|
|
14
|
+
const items = await deps.fetchMessage(event.parentId);
|
|
15
|
+
const parent = items.find((item) => item.message_id === event.parentId) ?? items[0];
|
|
16
|
+
if (!parent)
|
|
17
|
+
throw new Error('消息不存在或无权限');
|
|
18
|
+
const parsed = await parseApiMessageItem(parent, { botOpenId: deps.botOpenId, fetchSubMessages: deps.fetchMessage });
|
|
19
|
+
quoted = { text: parsed.text, messageId: event.parentId, resources: parsed.resources };
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
notices.push(`引用的消息读取失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
let body = event.text;
|
|
27
|
+
let quotedText = quoted?.text ?? '';
|
|
28
|
+
const images = [];
|
|
29
|
+
const attachments = [];
|
|
30
|
+
const groups = [
|
|
31
|
+
{ messageId: event.messageId, resources: event.resources ?? [], apply: (from, to) => { body = body.split(from).join(to); } },
|
|
32
|
+
...(quoted ? [{ messageId: quoted.messageId, resources: quoted.resources, apply: (from, to) => { quotedText = quotedText.split(from).join(to); } }] : []),
|
|
33
|
+
];
|
|
34
|
+
for (const group of groups) {
|
|
35
|
+
if (group.resources.length === 0)
|
|
36
|
+
continue;
|
|
37
|
+
if (!deps.media) {
|
|
38
|
+
notices.push(`${group.resources.length} 个附件未下载: 当前通道不支持下载资源`);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const { resolved, failures } = await deps.media.resolve(group.messageId, group.resources);
|
|
42
|
+
for (const item of resolved) {
|
|
43
|
+
group.apply(`key="${item.resource.fileKey}"`, `path="${item.path}"`);
|
|
44
|
+
group.apply(item.resource.fileKey, item.path);
|
|
45
|
+
(item.resource.type === 'image' ? images : attachments).push(item.path);
|
|
46
|
+
}
|
|
47
|
+
for (const failure of failures) {
|
|
48
|
+
notices.push(`附件 ${failure.resource.fileName ?? failure.resource.fileKey} ${failure.reason}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const text = quoted ? `${quoteBlock(`引用消息:\n${quotedText}`)}\n\n${body}` : body;
|
|
52
|
+
return { text, images, attachments, notices };
|
|
53
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 长连接保活. SDK 自己会断线重连, 但遇到过两类它兜不住的情况:
|
|
3
|
+
* - 笔记本合盖 / 进程被挂起后醒来, socket 早死了, SDK 状态还停在 connected 或卡在 reconnecting
|
|
4
|
+
* - 重连循环用尽次数后进入 failed, 不再尝试
|
|
5
|
+
*
|
|
6
|
+
* 做法 (参照 notebook bot 的 auto_reconnect):
|
|
7
|
+
* - 15s 独立定时器读 `getConnectionStatus()`
|
|
8
|
+
* - 两次 tick 间隔远超 15s → 判定刚从睡眠醒来, 本轮只重置计数 (睡前的状态不可信)
|
|
9
|
+
* - 连续 3 次不是 connected, 且 HTTP 能连到飞书 (排除整机断网) → 重建 WSClient
|
|
10
|
+
*/
|
|
11
|
+
export const KEEPALIVE_INTERVAL_MS = 15_000;
|
|
12
|
+
const SLEEP_DETECT_MS = 30_000;
|
|
13
|
+
const TIMER_STORM_GUARD_MS = 5_000;
|
|
14
|
+
const DEAD_THRESHOLD = 3;
|
|
15
|
+
export class Keepalive {
|
|
16
|
+
deps;
|
|
17
|
+
lastTick = 0;
|
|
18
|
+
consecutiveDown = 0;
|
|
19
|
+
networkDown = false;
|
|
20
|
+
timer = null;
|
|
21
|
+
forcedReconnects = 0;
|
|
22
|
+
lastForcedReconnectAt = null;
|
|
23
|
+
constructor(deps) {
|
|
24
|
+
this.deps = deps;
|
|
25
|
+
}
|
|
26
|
+
start(intervalMs = KEEPALIVE_INTERVAL_MS) {
|
|
27
|
+
this.timer = setInterval(() => {
|
|
28
|
+
void this.tick().catch((error) => this.deps.logger.warn({ error }, 'keepalive tick failed'));
|
|
29
|
+
}, intervalMs);
|
|
30
|
+
this.timer.unref?.();
|
|
31
|
+
}
|
|
32
|
+
stop() {
|
|
33
|
+
if (this.timer)
|
|
34
|
+
clearInterval(this.timer);
|
|
35
|
+
this.timer = null;
|
|
36
|
+
}
|
|
37
|
+
async tick() {
|
|
38
|
+
const now = (this.deps.now ?? Date.now)();
|
|
39
|
+
const sinceLast = this.lastTick > 0 ? now - this.lastTick : 0;
|
|
40
|
+
// 醒来时积压的 interval 会背靠背触发, 只认第一个.
|
|
41
|
+
if (sinceLast > 0 && sinceLast < TIMER_STORM_GUARD_MS)
|
|
42
|
+
return;
|
|
43
|
+
this.lastTick = now;
|
|
44
|
+
if (sinceLast > SLEEP_DETECT_MS) {
|
|
45
|
+
this.deps.logger.info({ sleptMs: sinceLast }, 'keepalive detected wake-up, resetting counters');
|
|
46
|
+
this.consecutiveDown = 0;
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const state = this.deps.connectionState();
|
|
50
|
+
if (!state || state === 'idle' || state === 'connected') {
|
|
51
|
+
if (this.consecutiveDown > 0)
|
|
52
|
+
this.deps.logger.info({ afterTicks: this.consecutiveDown }, 'feishu ws recovered');
|
|
53
|
+
this.consecutiveDown = 0;
|
|
54
|
+
this.networkDown = false;
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (!(await this.deps.probe())) {
|
|
58
|
+
if (!this.networkDown)
|
|
59
|
+
this.deps.logger.warn({ state }, 'feishu unreachable over http, waiting for network');
|
|
60
|
+
this.networkDown = true;
|
|
61
|
+
this.consecutiveDown = 0;
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
this.networkDown = false;
|
|
65
|
+
this.consecutiveDown += 1;
|
|
66
|
+
this.deps.logger.warn({ state, consecutiveDown: this.consecutiveDown }, 'feishu ws not connected');
|
|
67
|
+
if (this.consecutiveDown < DEAD_THRESHOLD)
|
|
68
|
+
return;
|
|
69
|
+
this.consecutiveDown = 0;
|
|
70
|
+
this.forcedReconnects += 1;
|
|
71
|
+
this.lastForcedReconnectAt = now;
|
|
72
|
+
this.deps.logger.warn({ state }, 'feishu ws stuck, rebuilding client');
|
|
73
|
+
await this.deps.forceReconnect();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export async function httpProbe(url, timeoutMs = 5_000) {
|
|
77
|
+
try {
|
|
78
|
+
const response = await fetch(url, { method: 'HEAD', signal: AbortSignal.timeout(timeoutMs) });
|
|
79
|
+
return response.status > 0;
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
// 超时 / DNS / 连接拒绝都按不可达处理, 由调用方记日志.
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pino 的 err / error 序列化: SDK 抛出的 AxiosError 自带 config.headers.Authorization (tenant token),
|
|
3
|
+
* 原样打进日志就泄露了 token. 只保留排障需要的字段.
|
|
4
|
+
*/
|
|
5
|
+
export function serializeError(value) {
|
|
6
|
+
if (!(value instanceof Error))
|
|
7
|
+
return value;
|
|
8
|
+
const record = value;
|
|
9
|
+
return {
|
|
10
|
+
type: record.name,
|
|
11
|
+
message: record.message,
|
|
12
|
+
code: record.code,
|
|
13
|
+
status: record.response?.status ?? record.status,
|
|
14
|
+
data: record.response?.data,
|
|
15
|
+
url: record.config?.url,
|
|
16
|
+
method: record.config?.method,
|
|
17
|
+
stack: record.stack,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export const errorSerializers = { err: serializeError, error: serializeError };
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agent 输出的 Markdown → 飞书卡片 markdown 组件能稳定渲染的形态.
|
|
3
|
+
*
|
|
4
|
+
* 飞书卡片 markdown 与 GitHub 风格的差异里, 会直接让卡片更新失败或难看的几处:
|
|
5
|
+
* - 图片只认 `img_` 开头的飞书 image_key; 本地路径 / http 图片会让整次 CardKit 更新报错
|
|
6
|
+
* → 改写成链接或行内代码, 不丢信息
|
|
7
|
+
* - 单卡表格数量有上限 → 超出的表格转成代码块原样保留
|
|
8
|
+
* - H1~H3 在卡片里过大 → 统一降到 H4/H5
|
|
9
|
+
* 代码块内部一律不动.
|
|
10
|
+
*/
|
|
11
|
+
const TABLE_LIMIT = 5;
|
|
12
|
+
const FENCE_RE = /```[\s\S]*?(?:```|$)/g;
|
|
13
|
+
const IMAGE_RE = /!\[([^\]]*)\]\(([^)\s]+)\)/g;
|
|
14
|
+
function protectFences(text) {
|
|
15
|
+
const blocks = [];
|
|
16
|
+
const body = text.replace(FENCE_RE, (block) => `\u0000F${blocks.push(block) - 1}\u0000`);
|
|
17
|
+
return { body, restore: (s) => s.replace(/\u0000F(\d+)\u0000/g, (_m, i) => blocks[Number(i)] ?? '') };
|
|
18
|
+
}
|
|
19
|
+
function rewriteImages(text) {
|
|
20
|
+
return text.replace(IMAGE_RE, (full, alt, target) => {
|
|
21
|
+
if (target.startsWith('img_'))
|
|
22
|
+
return full;
|
|
23
|
+
if (/^https?:\/\//.test(target))
|
|
24
|
+
return `[${alt || '图片'}](${target})`;
|
|
25
|
+
return `\`${target}\``;
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function demoteHeadings(text) {
|
|
29
|
+
if (!/^#{1,3} /m.test(text))
|
|
30
|
+
return text;
|
|
31
|
+
return text.replace(/^(#{1,6}) (.+)$/gm, (_m, hashes, title) => (hashes.length === 1 ? `#### ${title}` : `##### ${title}`));
|
|
32
|
+
}
|
|
33
|
+
function limitTables(text) {
|
|
34
|
+
const lines = text.split('\n');
|
|
35
|
+
const out = [];
|
|
36
|
+
let tables = 0;
|
|
37
|
+
for (let i = 0; i < lines.length; i++) {
|
|
38
|
+
const isHeader = /^\s*\|.*\|\s*$/.test(lines[i] ?? '') && /^\s*\|?\s*:?-{3,}/.test(lines[i + 1] ?? '');
|
|
39
|
+
if (!isHeader) {
|
|
40
|
+
out.push(lines[i]);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
let end = i;
|
|
44
|
+
while (end + 1 < lines.length && /^\s*\|.*\|\s*$/.test(lines[end + 1]))
|
|
45
|
+
end++;
|
|
46
|
+
const block = lines.slice(i, end + 1);
|
|
47
|
+
tables++;
|
|
48
|
+
if (tables > TABLE_LIMIT)
|
|
49
|
+
out.push('```', ...block, '```');
|
|
50
|
+
else
|
|
51
|
+
out.push(...block);
|
|
52
|
+
i = end;
|
|
53
|
+
}
|
|
54
|
+
return out.join('\n');
|
|
55
|
+
}
|
|
56
|
+
export function toFeishuMarkdown(text) {
|
|
57
|
+
if (!text)
|
|
58
|
+
return text;
|
|
59
|
+
const { body, restore } = protectFences(text);
|
|
60
|
+
const styled = limitTables(demoteHeadings(rewriteImages(body))).replace(/\n{3,}/g, '\n\n');
|
|
61
|
+
return restore(styled);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 按长度切分, 不切在代码块中间: 切点落在 ``` 内时, 当前段补一个闭合 fence,
|
|
65
|
+
* 下一段以同样的开 fence 续上, 两段各自都是合法 markdown.
|
|
66
|
+
*/
|
|
67
|
+
export function splitMarkdown(text, maxChars) {
|
|
68
|
+
if (text.length <= maxChars)
|
|
69
|
+
return [text];
|
|
70
|
+
const chunks = [];
|
|
71
|
+
let rest = text;
|
|
72
|
+
let carryFence = '';
|
|
73
|
+
while (rest.length > 0) {
|
|
74
|
+
const budget = Math.max(1, maxChars - carryFence.length - 4);
|
|
75
|
+
let piece = rest.slice(0, budget);
|
|
76
|
+
if (rest.length > budget) {
|
|
77
|
+
const cut = piece.lastIndexOf('\n');
|
|
78
|
+
if (cut > budget * 0.5)
|
|
79
|
+
piece = piece.slice(0, cut + 1);
|
|
80
|
+
}
|
|
81
|
+
rest = rest.slice(piece.length);
|
|
82
|
+
let chunk = carryFence ? `${carryFence}\n${piece}` : piece;
|
|
83
|
+
const fences = chunk.match(/^```.*$/gm) ?? [];
|
|
84
|
+
if (fences.length % 2 === 1 && rest.length > 0) {
|
|
85
|
+
// 奇数个 fence 行 → 最后一行是还没闭合的开 fence (带语言标记就一起续上)
|
|
86
|
+
carryFence = fences[fences.length - 1];
|
|
87
|
+
chunk = `${chunk.replace(/\n?$/, '\n')}\`\`\``;
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
carryFence = '';
|
|
91
|
+
}
|
|
92
|
+
chunks.push(chunk);
|
|
93
|
+
}
|
|
94
|
+
return chunks;
|
|
95
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { extname, join } from 'node:path';
|
|
4
|
+
const MB = 1024 * 1024;
|
|
5
|
+
export function mediaLimitsFromEnv(env = process.env) {
|
|
6
|
+
const fileMb = Number(env['WB_MEDIA_MAX_MB']);
|
|
7
|
+
const totalMb = Number(env['WB_MEDIA_CACHE_MAX_MB']);
|
|
8
|
+
return {
|
|
9
|
+
maxFileBytes: (Number.isFinite(fileMb) && fileMb > 0 ? fileMb : 20) * MB,
|
|
10
|
+
maxTotalBytes: (Number.isFinite(totalMb) && totalMb > 0 ? totalMb : 1024) * MB,
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function sniffImageExt(buf) {
|
|
14
|
+
if (buf.length >= 8 && buf.readUInt32BE(0) === 0x89504e47)
|
|
15
|
+
return '.png';
|
|
16
|
+
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff)
|
|
17
|
+
return '.jpg';
|
|
18
|
+
if (buf.length >= 6 && buf.subarray(0, 3).toString('ascii') === 'GIF')
|
|
19
|
+
return '.gif';
|
|
20
|
+
if (buf.length >= 12 && buf.subarray(0, 4).toString('ascii') === 'RIFF' && buf.subarray(8, 12).toString('ascii') === 'WEBP')
|
|
21
|
+
return '.webp';
|
|
22
|
+
return '.png';
|
|
23
|
+
}
|
|
24
|
+
function extFor(resource, buf) {
|
|
25
|
+
if (resource.type === 'image')
|
|
26
|
+
return sniffImageExt(buf);
|
|
27
|
+
if (resource.type === 'audio')
|
|
28
|
+
return '.opus';
|
|
29
|
+
if (resource.type === 'video')
|
|
30
|
+
return '.mp4';
|
|
31
|
+
const fromName = resource.fileName ? extname(resource.fileName).toLowerCase() : '';
|
|
32
|
+
return /^\.[a-z0-9]{1,10}$/.test(fromName) ? fromName : '.bin';
|
|
33
|
+
}
|
|
34
|
+
export class MediaCache {
|
|
35
|
+
opts;
|
|
36
|
+
maxFileBytes;
|
|
37
|
+
maxTotalBytes;
|
|
38
|
+
constructor(opts) {
|
|
39
|
+
this.opts = opts;
|
|
40
|
+
const defaults = mediaLimitsFromEnv();
|
|
41
|
+
this.maxFileBytes = opts.maxFileBytes ?? defaults.maxFileBytes;
|
|
42
|
+
this.maxTotalBytes = opts.maxTotalBytes ?? defaults.maxTotalBytes;
|
|
43
|
+
}
|
|
44
|
+
async resolve(messageId, resources) {
|
|
45
|
+
const resolved = [];
|
|
46
|
+
const failures = [];
|
|
47
|
+
if (resources.length === 0)
|
|
48
|
+
return { resolved, failures };
|
|
49
|
+
mkdirSync(this.opts.rootDir, { recursive: true });
|
|
50
|
+
for (const resource of resources) {
|
|
51
|
+
if (resource.type === 'sticker')
|
|
52
|
+
continue;
|
|
53
|
+
let buf;
|
|
54
|
+
try {
|
|
55
|
+
buf = await this.opts.download(messageId, resource.fileKey, resource.type === 'image' ? 'image' : 'file');
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
failures.push({ resource, reason: `下载失败: ${error instanceof Error ? error.message : String(error)}` });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if (buf.length > this.maxFileBytes) {
|
|
62
|
+
failures.push({ resource, reason: `超过 ${Math.round(this.maxFileBytes / MB)}MB 上限 (${(buf.length / MB).toFixed(1)}MB)` });
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const hash = createHash('sha256').update(buf).digest('hex').slice(0, 32);
|
|
66
|
+
const path = join(this.opts.rootDir, `${hash}${extFor(resource, buf)}`);
|
|
67
|
+
if (!existsSync(path))
|
|
68
|
+
writeFileSync(path, buf);
|
|
69
|
+
resolved.push({ resource, path });
|
|
70
|
+
}
|
|
71
|
+
this.evict(new Set(resolved.map((item) => item.path)));
|
|
72
|
+
return { resolved, failures };
|
|
73
|
+
}
|
|
74
|
+
evict(keep) {
|
|
75
|
+
const entries = readdirSync(this.opts.rootDir)
|
|
76
|
+
.map((name) => join(this.opts.rootDir, name))
|
|
77
|
+
.map((path) => ({ path, stat: statSync(path) }))
|
|
78
|
+
.filter((entry) => entry.stat.isFile());
|
|
79
|
+
let total = entries.reduce((sum, entry) => sum + entry.stat.size, 0);
|
|
80
|
+
if (total <= this.maxTotalBytes)
|
|
81
|
+
return;
|
|
82
|
+
entries.sort((a, b) => a.stat.mtimeMs - b.stat.mtimeMs);
|
|
83
|
+
for (const entry of entries) {
|
|
84
|
+
if (total <= this.maxTotalBytes)
|
|
85
|
+
break;
|
|
86
|
+
if (keep.has(entry.path))
|
|
87
|
+
continue;
|
|
88
|
+
unlinkSync(entry.path);
|
|
89
|
+
total -= entry.stat.size;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { normalize } from '@larksuiteoapi/node-sdk';
|
|
2
|
+
function legacyText(content) {
|
|
3
|
+
try {
|
|
4
|
+
const parsed = JSON.parse(content);
|
|
5
|
+
return typeof parsed.text === 'string' ? parsed.text : '';
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return content;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
const INTERACTIVE_PLACEHOLDER = '[interactive card]';
|
|
12
|
+
/**
|
|
13
|
+
* 飞书推给 bot 的卡片消息 (含转发来的告警卡) 是简化格式 `{ title, elements: [[{tag,text,href}]] }`,
|
|
14
|
+
* SDK 只给 `[interactive card]` 占位; 这里按行拼出标题和文字, 链接保留地址.
|
|
15
|
+
*/
|
|
16
|
+
export function interactiveText(content) {
|
|
17
|
+
let parsed;
|
|
18
|
+
try {
|
|
19
|
+
parsed = JSON.parse(content);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return '';
|
|
23
|
+
}
|
|
24
|
+
const lines = [];
|
|
25
|
+
if (typeof parsed.title === 'string' && parsed.title.trim())
|
|
26
|
+
lines.push(parsed.title.trim());
|
|
27
|
+
for (const row of Array.isArray(parsed.elements) ? parsed.elements : []) {
|
|
28
|
+
if (!Array.isArray(row))
|
|
29
|
+
continue;
|
|
30
|
+
const line = row.map((item) => {
|
|
31
|
+
if (item.tag === 'a')
|
|
32
|
+
return item.href ? `${item.text ?? ''} (${item.href})` : item.text ?? '';
|
|
33
|
+
if (item.tag === 'at')
|
|
34
|
+
return `@${item.user_name ?? item.text ?? ''}`;
|
|
35
|
+
return item.tag === 'text' ? item.text ?? '' : '';
|
|
36
|
+
}).join('').trim();
|
|
37
|
+
if (line)
|
|
38
|
+
lines.push(line);
|
|
39
|
+
}
|
|
40
|
+
return lines.join('\n');
|
|
41
|
+
}
|
|
42
|
+
/** 新版客户端的部分文本消息整段包在 `<p>…</p>` 里 (例如引用回复), 去掉段落标签. */
|
|
43
|
+
export function stripParagraphTags(text) {
|
|
44
|
+
if (!/^\s*<p>[\s\S]*<\/p>\s*$/.test(text))
|
|
45
|
+
return text;
|
|
46
|
+
return text.replace(/<\/p>\s*<p>/g, '\n').replace(/^\s*<p>/, '').replace(/<\/p>\s*$/, '').trim();
|
|
47
|
+
}
|
|
48
|
+
function toRawEvent(message, senderOpenId) {
|
|
49
|
+
return {
|
|
50
|
+
sender: { sender_id: { open_id: senderOpenId } },
|
|
51
|
+
message: {
|
|
52
|
+
message_id: message.message_id ?? '',
|
|
53
|
+
root_id: message.root_id,
|
|
54
|
+
parent_id: message.parent_id,
|
|
55
|
+
create_time: message.create_time,
|
|
56
|
+
chat_id: message.chat_id ?? '',
|
|
57
|
+
thread_id: message.thread_id,
|
|
58
|
+
chat_type: message.chat_type === 'p2p' ? 'p2p' : 'group',
|
|
59
|
+
message_type: message.message_type ?? 'text',
|
|
60
|
+
content: message.content ?? '',
|
|
61
|
+
mentions: (message.mentions ?? []).map((mention) => ({
|
|
62
|
+
key: mention.key ?? '',
|
|
63
|
+
id: {
|
|
64
|
+
open_id: mention.id?.open_id,
|
|
65
|
+
user_id: mention.id?.user_id ?? undefined,
|
|
66
|
+
union_id: mention.id?.union_id,
|
|
67
|
+
},
|
|
68
|
+
name: mention.name,
|
|
69
|
+
})),
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** 正文里的 @ 只剩名字; 附上 open_id, agent 才能用飞书工具查到是谁. bot 自己不算. */
|
|
74
|
+
function mentionedPeople(mentions, botOpenId) {
|
|
75
|
+
const seen = new Set();
|
|
76
|
+
const lines = [];
|
|
77
|
+
for (const mention of mentions) {
|
|
78
|
+
if (!mention.openId || mention.isBot || mention.openId === botOpenId || seen.has(mention.openId))
|
|
79
|
+
continue;
|
|
80
|
+
seen.add(mention.openId);
|
|
81
|
+
lines.push(`- ${mention.name ?? '?'} (open_id: ${mention.openId})`);
|
|
82
|
+
}
|
|
83
|
+
return lines.length > 0 ? `提到的人:\n${lines.join('\n')}` : '';
|
|
84
|
+
}
|
|
85
|
+
export async function parseInboundMessage(message, opts) {
|
|
86
|
+
const msgType = message.message_type ?? 'text';
|
|
87
|
+
const content = message.content ?? '';
|
|
88
|
+
const parentId = message.parent_id || undefined;
|
|
89
|
+
// 老 payload / 测试桩可能缺 message_type: 只有 text 一种形态, 走原解析, 不进 SDK.
|
|
90
|
+
if (!message.message_type) {
|
|
91
|
+
return { text: legacyText(content), msgType, resources: [], parentId, mentionAll: false };
|
|
92
|
+
}
|
|
93
|
+
const normalized = await normalize(toRawEvent(message, opts.senderOpenId), {
|
|
94
|
+
botIdentity: { openId: opts.botOpenId, name: '' },
|
|
95
|
+
stripBotMentions: true,
|
|
96
|
+
fetchSubMessages: opts.fetchSubMessages,
|
|
97
|
+
});
|
|
98
|
+
let text = normalized.content;
|
|
99
|
+
if (msgType === 'text')
|
|
100
|
+
text = stripParagraphTags(text);
|
|
101
|
+
if (msgType === 'interactive' && (!text.trim() || text.trim() === INTERACTIVE_PLACEHOLDER))
|
|
102
|
+
text = interactiveText(content) || text;
|
|
103
|
+
const people = mentionedPeople(normalized.mentions, opts.botOpenId);
|
|
104
|
+
// `/` 命令按整段文本解析参数, 不追加.
|
|
105
|
+
if (people && !text.trimStart().startsWith('/'))
|
|
106
|
+
text = `${text}\n\n${people}`;
|
|
107
|
+
return {
|
|
108
|
+
text,
|
|
109
|
+
msgType,
|
|
110
|
+
resources: normalized.resources,
|
|
111
|
+
parentId,
|
|
112
|
+
mentionAll: normalized.mentionAll,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* 把父消息 (引用回复的对象) 的 ApiMessageItem 转成可读文本.
|
|
117
|
+
* merge_forward 的子消息展开同样走 fetchSubMessages.
|
|
118
|
+
*/
|
|
119
|
+
export async function parseApiMessageItem(item, opts) {
|
|
120
|
+
return parseInboundMessage({
|
|
121
|
+
message_id: item.message_id,
|
|
122
|
+
message_type: item.msg_type ?? 'text',
|
|
123
|
+
content: item.body?.content ?? '',
|
|
124
|
+
mentions: (item.mentions ?? []).map((mention) => ({ key: mention.key, name: mention.name, id: mention.id })),
|
|
125
|
+
}, opts);
|
|
126
|
+
}
|