@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,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 连发合并. 飞书里人习惯把一件事拆成几条发 (先贴报错、再补一句"帮我看下"),
|
|
3
|
+
* 或者长文本被客户端自动切成多条. 逐条起 run 会让第一条在信息不全时就开跑.
|
|
4
|
+
*
|
|
5
|
+
* 两层:
|
|
6
|
+
* - InboundDebouncer (transport 用): 同一 user+thread 在静默窗口内的连发合并成一条再交给 handler.
|
|
7
|
+
* slash 命令不进窗口, 但会先把同 scope 已攒的消息冲出去, 保证先后顺序.
|
|
8
|
+
* - mergeMessageEvents (handler 用): run 进行中收到的消息排队, run 结束后合并成下一轮.
|
|
9
|
+
*/
|
|
10
|
+
export const DEFAULT_DEBOUNCE_MS = 600;
|
|
11
|
+
const MAX_BATCH = 10;
|
|
12
|
+
export function debounceMsFromEnv(env = process.env) {
|
|
13
|
+
const raw = env['WB_MESSAGE_DEBOUNCE_MS'];
|
|
14
|
+
if (raw === undefined || raw.trim() === '')
|
|
15
|
+
return DEFAULT_DEBOUNCE_MS;
|
|
16
|
+
const value = Number(raw);
|
|
17
|
+
return Number.isFinite(value) && value >= 0 ? value : DEFAULT_DEBOUNCE_MS;
|
|
18
|
+
}
|
|
19
|
+
function concat(events, pick) {
|
|
20
|
+
const all = events.flatMap((event) => pick(event) ?? []);
|
|
21
|
+
return all.length > 0 ? all : undefined;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* 合并多条消息: 正文按顺序空行拼接, 资源 / 附件 / 告警拼接; 回复挂在最后一条下面,
|
|
25
|
+
* 其余消息 id 进 mergedMessageIds (用于撤 Typing 表情). 引用取第一条带引用的.
|
|
26
|
+
*/
|
|
27
|
+
export function mergeMessageEvents(events) {
|
|
28
|
+
if (events.length === 0)
|
|
29
|
+
throw new Error('mergeMessageEvents: empty batch');
|
|
30
|
+
if (events.length === 1)
|
|
31
|
+
return events[0];
|
|
32
|
+
const first = events[0];
|
|
33
|
+
const last = events[events.length - 1];
|
|
34
|
+
const merged = {
|
|
35
|
+
...last,
|
|
36
|
+
eventId: `${first.eventId}+${events.length - 1}`,
|
|
37
|
+
text: events.map((event) => event.text).filter((text) => text.trim()).join('\n\n'),
|
|
38
|
+
mergedMessageIds: events.flatMap((event) => [...(event.mergedMessageIds ?? []), event.messageId]).filter((id) => id !== last.messageId),
|
|
39
|
+
};
|
|
40
|
+
const resources = concat(events, (event) => event.resources);
|
|
41
|
+
const images = concat(events, (event) => event.images);
|
|
42
|
+
const attachments = concat(events, (event) => event.attachments);
|
|
43
|
+
const notices = concat(events, (event) => event.notices);
|
|
44
|
+
const parentId = events.find((event) => event.parentId)?.parentId;
|
|
45
|
+
delete merged.resources;
|
|
46
|
+
delete merged.images;
|
|
47
|
+
delete merged.attachments;
|
|
48
|
+
delete merged.notices;
|
|
49
|
+
delete merged.parentId;
|
|
50
|
+
return {
|
|
51
|
+
...merged,
|
|
52
|
+
...(resources ? { resources } : {}),
|
|
53
|
+
...(images ? { images } : {}),
|
|
54
|
+
...(attachments ? { attachments } : {}),
|
|
55
|
+
...(notices ? { notices } : {}),
|
|
56
|
+
...(parentId ? { parentId } : {}),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const SEEN_EVENT_IDS = 1000;
|
|
60
|
+
export class InboundDebouncer {
|
|
61
|
+
delayMs;
|
|
62
|
+
dispatch;
|
|
63
|
+
entries = new Map();
|
|
64
|
+
// 合并后 handler 只看到合并 eventId, 原始 eventId 的重投递要在这里挡掉.
|
|
65
|
+
seenEventIds = new Set();
|
|
66
|
+
constructor(delayMs, dispatch) {
|
|
67
|
+
this.delayMs = delayMs;
|
|
68
|
+
this.dispatch = dispatch;
|
|
69
|
+
}
|
|
70
|
+
push(event) {
|
|
71
|
+
if (event.eventId) {
|
|
72
|
+
if (this.seenEventIds.has(event.eventId))
|
|
73
|
+
return;
|
|
74
|
+
this.seenEventIds.add(event.eventId);
|
|
75
|
+
if (this.seenEventIds.size > SEEN_EVENT_IDS) {
|
|
76
|
+
const oldest = this.seenEventIds.values().next().value;
|
|
77
|
+
if (oldest !== undefined)
|
|
78
|
+
this.seenEventIds.delete(oldest);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const scope = `${event.userOpenId}:${event.threadId}`;
|
|
82
|
+
if (this.delayMs <= 0) {
|
|
83
|
+
this.dispatch(event);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (event.text.trimStart().startsWith('/')) {
|
|
87
|
+
this.flush(scope);
|
|
88
|
+
this.dispatch(event);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const entry = this.entries.get(scope) ?? { events: [], timer: null };
|
|
92
|
+
if (entry.timer)
|
|
93
|
+
clearTimeout(entry.timer);
|
|
94
|
+
entry.events.push(event);
|
|
95
|
+
this.entries.set(scope, entry);
|
|
96
|
+
if (entry.events.length >= MAX_BATCH) {
|
|
97
|
+
this.flush(scope);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
entry.timer = setTimeout(() => this.flush(scope), this.delayMs);
|
|
101
|
+
entry.timer.unref?.();
|
|
102
|
+
}
|
|
103
|
+
flush(scope) {
|
|
104
|
+
const entry = this.entries.get(scope);
|
|
105
|
+
if (!entry)
|
|
106
|
+
return;
|
|
107
|
+
this.entries.delete(scope);
|
|
108
|
+
if (entry.timer)
|
|
109
|
+
clearTimeout(entry.timer);
|
|
110
|
+
if (entry.events.length > 0)
|
|
111
|
+
this.dispatch(mergeMessageEvents(entry.events));
|
|
112
|
+
}
|
|
113
|
+
/** 撤回: 还在静默窗口里的消息直接丢掉. 返回是否命中. */
|
|
114
|
+
drop(messageId) {
|
|
115
|
+
for (const [scope, entry] of this.entries) {
|
|
116
|
+
const index = entry.events.findIndex((event) => event.messageId === messageId);
|
|
117
|
+
if (index === -1)
|
|
118
|
+
continue;
|
|
119
|
+
entry.events.splice(index, 1);
|
|
120
|
+
if (entry.events.length === 0) {
|
|
121
|
+
if (entry.timer)
|
|
122
|
+
clearTimeout(entry.timer);
|
|
123
|
+
this.entries.delete(scope);
|
|
124
|
+
}
|
|
125
|
+
return true;
|
|
126
|
+
}
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
flushAll() {
|
|
130
|
+
for (const scope of [...this.entries.keys()])
|
|
131
|
+
this.flush(scope);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import pino from 'pino';
|
|
2
|
+
import { errorSerializers } from './log-redact.js';
|
|
3
|
+
/**
|
|
4
|
+
* 收到消息即在原消息上打一个「敲键盘」(Typing) 表情, run 结束后撤掉.
|
|
5
|
+
* 运行卡要等 reply 回来才出现, 表情是更早、手机通知里也看得到的"我收到了".
|
|
6
|
+
*
|
|
7
|
+
* 纯装饰: add / remove 失败只 warn, 不影响主流程. 只能撤 bot 自己打的表情, 所以要记 reaction_id.
|
|
8
|
+
*/
|
|
9
|
+
export const ACK_EMOJI = 'Typing';
|
|
10
|
+
const logger = pino({ level: process.env['LOG_LEVEL'] ?? 'info', serializers: errorSerializers });
|
|
11
|
+
export class AckReactions {
|
|
12
|
+
client;
|
|
13
|
+
pending = new Map();
|
|
14
|
+
constructor(client) {
|
|
15
|
+
this.client = client;
|
|
16
|
+
}
|
|
17
|
+
add(messageId) {
|
|
18
|
+
if (!this.client.addReaction || !messageId || this.pending.has(messageId))
|
|
19
|
+
return;
|
|
20
|
+
const added = this.client.addReaction(messageId, ACK_EMOJI).catch((error) => {
|
|
21
|
+
logger.warn({ messageId, error: error instanceof Error ? error.message : String(error) }, 'ack reaction add failed');
|
|
22
|
+
return undefined;
|
|
23
|
+
});
|
|
24
|
+
this.pending.set(messageId, added);
|
|
25
|
+
}
|
|
26
|
+
async clear(messageId) {
|
|
27
|
+
const added = this.pending.get(messageId);
|
|
28
|
+
if (!added)
|
|
29
|
+
return;
|
|
30
|
+
this.pending.delete(messageId);
|
|
31
|
+
const reactionId = await added;
|
|
32
|
+
if (!reactionId || !this.client.removeReaction)
|
|
33
|
+
return;
|
|
34
|
+
try {
|
|
35
|
+
await this.client.removeReaction(messageId, reactionId);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
logger.warn({ messageId, reactionId, error: error instanceof Error ? error.message : String(error) }, 'ack reaction remove failed');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
has(messageId) {
|
|
42
|
+
return this.pending.has(messageId);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import * as Lark from '@larksuiteoapi/node-sdk';
|
|
3
|
+
import { captainSocketPath } from '../../../../packages/core/src/paths.js';
|
|
4
|
+
import { ConcurrencyQueueEntryStatus } from '../../../../packages/core/src/captain/concurrency-queue-store.js';
|
|
5
|
+
import { createMirrorSink } from '../../../../packages/core/src/audit-pipe/mirror-sink.js';
|
|
6
|
+
import { IpcClient } from '../../../../packages/core/src/reverse-channel/ipc-client.js';
|
|
7
|
+
import { REVERSE_CHANNEL_ERROR_CODES, ReverseChannelError, } from '../../../../packages/core/src/reverse-channel/contracts.js';
|
|
8
|
+
import { validateReverseAtRun } from '../../../../packages/core/src/reverse-channel/reverse-at-handler.js';
|
|
9
|
+
import { renderCard } from './card-renderer.js';
|
|
10
|
+
import { createInitialState } from './stream-state.js';
|
|
11
|
+
function findSessionByRunId(captainService, runId) {
|
|
12
|
+
return captainService.listActiveSessions().find((entry) => entry.run_ids.includes(runId));
|
|
13
|
+
}
|
|
14
|
+
function sessionIdFor(botId, userOpenId, threadId) {
|
|
15
|
+
return `${botId}:${userOpenId}:${threadId}`;
|
|
16
|
+
}
|
|
17
|
+
function renderSystemCard(text, terminalState) {
|
|
18
|
+
return renderCard({
|
|
19
|
+
...createInitialState('system', 'Weaverbird', 'bot'),
|
|
20
|
+
text,
|
|
21
|
+
includeMeta: false,
|
|
22
|
+
terminalState,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
function formatCancelableList(items) {
|
|
26
|
+
return items.length > 0
|
|
27
|
+
? `可叫停列表:\n${items.map((item) => `- ${item}`).join('\n')}`
|
|
28
|
+
: '当前没有可叫停的运行';
|
|
29
|
+
}
|
|
30
|
+
export function parseReverseAtAdminWhitelist(value) {
|
|
31
|
+
return new Set((value ?? '').split(',').map((item) => item.trim()).filter(Boolean));
|
|
32
|
+
}
|
|
33
|
+
export function createLarkReverseAtAdminRoleResolver(client, whitelistOpenIds = new Set()) {
|
|
34
|
+
return async (context) => {
|
|
35
|
+
if (whitelistOpenIds.has(context.userOpenId))
|
|
36
|
+
return 'whitelist';
|
|
37
|
+
const response = await client.im.v1.chat.get({
|
|
38
|
+
path: { chat_id: context.threadId },
|
|
39
|
+
params: { user_id_type: 'open_id' },
|
|
40
|
+
});
|
|
41
|
+
const ownerId = response.data?.owner_id;
|
|
42
|
+
if (ownerId === context.userOpenId)
|
|
43
|
+
return 'owner';
|
|
44
|
+
if ((response.data?.user_manager_id_list ?? []).includes(context.userOpenId))
|
|
45
|
+
return 'group_admin';
|
|
46
|
+
return null;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
async function replyPlainText(feishu, messageId, text) {
|
|
50
|
+
if (feishu.replyText) {
|
|
51
|
+
await feishu.replyText(messageId, text);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
await feishu.replyCard(messageId, renderSystemCard(text, 'done'));
|
|
55
|
+
}
|
|
56
|
+
function formatQueueList(title, items) {
|
|
57
|
+
if (items.length === 0)
|
|
58
|
+
return `${title}\n- (empty)`;
|
|
59
|
+
return `${title}\n${items.map((item) => `- ${item}`).join('\n')}`;
|
|
60
|
+
}
|
|
61
|
+
function recordQueueCommandMetric(metrics, sessionId, command) {
|
|
62
|
+
metrics?.record({
|
|
63
|
+
metric: 'captain_queue_commands_total',
|
|
64
|
+
value: 1,
|
|
65
|
+
labels: { session_id: sessionId, command },
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
async function handleConcurrencyCommand(cmd, context, options) {
|
|
69
|
+
const now = options.captainConcurrency.now ?? (() => new Date().toISOString());
|
|
70
|
+
const sessionId = options.captainConcurrency.sessionId ?? context.threadId;
|
|
71
|
+
const index = options.captainConcurrency.index;
|
|
72
|
+
const store = options.captainConcurrency.store;
|
|
73
|
+
const metrics = options.captainConcurrency.metrics;
|
|
74
|
+
if (cmd === '/queue') {
|
|
75
|
+
const running = index.listRunning(sessionId);
|
|
76
|
+
const queued = index.listQueued(sessionId);
|
|
77
|
+
await replyPlainText(options.feishu, context.messageId, `${formatQueueList('running', running)}\n${formatQueueList('queued', queued)}`);
|
|
78
|
+
recordQueueCommandMetric(metrics, sessionId, 'queue');
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
if (cmd === '/cancel-all') {
|
|
82
|
+
const queued = index.listQueuedEntries(sessionId);
|
|
83
|
+
for (const entry of queued) {
|
|
84
|
+
const ts = now();
|
|
85
|
+
store.append({
|
|
86
|
+
session_id: sessionId,
|
|
87
|
+
run_id: entry.run_id,
|
|
88
|
+
status: ConcurrencyQueueEntryStatus.ENDED,
|
|
89
|
+
ts,
|
|
90
|
+
reason: 'cancelled',
|
|
91
|
+
});
|
|
92
|
+
index.markEnded(sessionId, entry.run_id, ts);
|
|
93
|
+
}
|
|
94
|
+
await replyPlainText(options.feishu, context.messageId, `cancelled ${queued.length} queued run(s)`);
|
|
95
|
+
recordQueueCommandMetric(metrics, sessionId, 'cancel_all');
|
|
96
|
+
if (queued.length > 0) {
|
|
97
|
+
metrics?.record({
|
|
98
|
+
metric: 'captain_queue_cancelled_runs_total',
|
|
99
|
+
value: queued.length,
|
|
100
|
+
labels: { session_id: sessionId },
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
if (cmd === '/preempt') {
|
|
106
|
+
const running = index.listRunningEntries(sessionId);
|
|
107
|
+
for (const entry of running) {
|
|
108
|
+
const ts = now();
|
|
109
|
+
store.append({
|
|
110
|
+
session_id: sessionId,
|
|
111
|
+
run_id: entry.run_id,
|
|
112
|
+
status: ConcurrencyQueueEntryStatus.ENDED,
|
|
113
|
+
ts,
|
|
114
|
+
reason: 'preempted',
|
|
115
|
+
});
|
|
116
|
+
index.markEnded(sessionId, entry.run_id, ts);
|
|
117
|
+
}
|
|
118
|
+
const nextQueued = index.listQueuedEntries(sessionId)[0];
|
|
119
|
+
if (nextQueued) {
|
|
120
|
+
const ts = now();
|
|
121
|
+
store.append({
|
|
122
|
+
session_id: sessionId,
|
|
123
|
+
run_id: nextQueued.run_id,
|
|
124
|
+
status: ConcurrencyQueueEntryStatus.RUNNING,
|
|
125
|
+
ts,
|
|
126
|
+
});
|
|
127
|
+
index.markRunning(sessionId, nextQueued.run_id, ts);
|
|
128
|
+
await replyPlainText(options.feishu, context.messageId, `preempted ${running.length} running run(s)\n- promoted ${nextQueued.run_id}`);
|
|
129
|
+
recordQueueCommandMetric(metrics, sessionId, 'preempt');
|
|
130
|
+
if (running.length > 0) {
|
|
131
|
+
metrics?.record({
|
|
132
|
+
metric: 'captain_queue_preempted_runs_total',
|
|
133
|
+
value: running.length,
|
|
134
|
+
labels: { session_id: sessionId },
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
metrics?.record({
|
|
138
|
+
metric: 'captain_queue_promoted_by_preempt_total',
|
|
139
|
+
value: 1,
|
|
140
|
+
labels: { session_id: sessionId },
|
|
141
|
+
});
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
await replyPlainText(options.feishu, context.messageId, `preempted ${running.length} running run(s)`);
|
|
145
|
+
recordQueueCommandMetric(metrics, sessionId, 'preempt');
|
|
146
|
+
if (running.length > 0) {
|
|
147
|
+
metrics?.record({
|
|
148
|
+
metric: 'captain_queue_preempted_runs_total',
|
|
149
|
+
value: running.length,
|
|
150
|
+
labels: { session_id: sessionId },
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
return false;
|
|
156
|
+
}
|
|
157
|
+
function writeReverseAtAudit(dataDir, session, command, context, resource) {
|
|
158
|
+
const sink = createMirrorSink({ dataDir });
|
|
159
|
+
const record = {
|
|
160
|
+
audit_record_id: randomUUID(),
|
|
161
|
+
session_id: session.record.session_id,
|
|
162
|
+
run_id: session.record.latest_run_id ?? command,
|
|
163
|
+
revision: 0,
|
|
164
|
+
actor: context.userOpenId,
|
|
165
|
+
action: 'other',
|
|
166
|
+
resource,
|
|
167
|
+
ts: new Date().toISOString(),
|
|
168
|
+
entry_form: 'im',
|
|
169
|
+
entry_detail: {
|
|
170
|
+
source_message_id: context.messageId,
|
|
171
|
+
user_open_id: context.userOpenId,
|
|
172
|
+
thread_id: context.threadId,
|
|
173
|
+
},
|
|
174
|
+
agent_id: 'claude-code',
|
|
175
|
+
raw_tool_use_id: `reverse-at:${context.messageId}:${command}`,
|
|
176
|
+
raw_tool_name: `reverse-at:${command}`,
|
|
177
|
+
};
|
|
178
|
+
sink.write(record);
|
|
179
|
+
}
|
|
180
|
+
function writeAdminCancelAudit(dataDir, session, context, payload) {
|
|
181
|
+
const sink = createMirrorSink({ dataDir });
|
|
182
|
+
const record = {
|
|
183
|
+
audit_record_id: randomUUID(),
|
|
184
|
+
session_id: session.record.session_id,
|
|
185
|
+
run_id: session.record.latest_run_id ?? payload.shortId,
|
|
186
|
+
revision: 0,
|
|
187
|
+
actor: context.userOpenId,
|
|
188
|
+
action: 'other',
|
|
189
|
+
resource: `event=admin_cancel:actor_role=${payload.actorRole}:target_session=${payload.shortId}:result=${payload.result}`,
|
|
190
|
+
ts: new Date().toISOString(),
|
|
191
|
+
entry_form: 'im',
|
|
192
|
+
entry_detail: {
|
|
193
|
+
source_message_id: context.messageId,
|
|
194
|
+
user_open_id: context.userOpenId,
|
|
195
|
+
thread_id: context.threadId,
|
|
196
|
+
},
|
|
197
|
+
agent_id: 'claude-code',
|
|
198
|
+
raw_tool_use_id: `admin_cancel:${context.messageId}:${payload.shortId}`,
|
|
199
|
+
raw_tool_name: 'admin_cancel',
|
|
200
|
+
};
|
|
201
|
+
sink.write(record);
|
|
202
|
+
}
|
|
203
|
+
async function authorizeReverseAtCommand(session, context, resolveAdminRole) {
|
|
204
|
+
if (session.record.operator === context.userOpenId) {
|
|
205
|
+
return { role: 'operator' };
|
|
206
|
+
}
|
|
207
|
+
if (!resolveAdminRole) {
|
|
208
|
+
return { role: 'denied', reason: 'not_authorized' };
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
const role = await resolveAdminRole(context);
|
|
212
|
+
if (role)
|
|
213
|
+
return { role };
|
|
214
|
+
return { role: 'denied', reason: 'not_authorized' };
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
return { role: 'denied', reason: 'fail_closed' };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
async function executeAdminCancel(identifier, context, options) {
|
|
221
|
+
if (!identifier)
|
|
222
|
+
return false;
|
|
223
|
+
if (!options.resolveCancelTarget || !options.executeCancel) {
|
|
224
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ /cancel ${identifier}: 未配置叫停解析器`, 'error'));
|
|
225
|
+
return true;
|
|
226
|
+
}
|
|
227
|
+
const target = options.resolveCancelTarget(identifier);
|
|
228
|
+
if (!target) {
|
|
229
|
+
const list = options.listCancelableTargets?.() ?? [];
|
|
230
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ /cancel ${identifier}: 未找到目标\n${formatCancelableList(list)}`, 'error'));
|
|
231
|
+
return true;
|
|
232
|
+
}
|
|
233
|
+
const result = await options.executeCancel(target.runId);
|
|
234
|
+
const text = result === 'cancelled'
|
|
235
|
+
? `✅ /cancel ${target.shortId}: 已叫停 ${target.label}`
|
|
236
|
+
: `✅ /cancel ${target.shortId}: ${target.label} 已结束,无需再叫停`;
|
|
237
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(text, 'done'));
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
export async function handleReverseAtImCommand(cmd, context, options) {
|
|
241
|
+
const createIpcClient = options.createIpcClient ?? ((socketPath) => new IpcClient(socketPath));
|
|
242
|
+
if ((cmd.command === '/queue' || cmd.command === '/cancel-all' || cmd.command === '/preempt') && options.captainConcurrency) {
|
|
243
|
+
const handled = await handleConcurrencyCommand(cmd.command, context, {
|
|
244
|
+
captainConcurrency: options.captainConcurrency,
|
|
245
|
+
feishu: options.feishu,
|
|
246
|
+
});
|
|
247
|
+
if (handled)
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (cmd.command === '/cancel') {
|
|
251
|
+
const cancelTarget = options.resolveCancelTarget?.(cmd.run_id);
|
|
252
|
+
if (!cancelTarget) {
|
|
253
|
+
const list = options.listCancelableTargets?.() ?? [];
|
|
254
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ /cancel ${cmd.run_id}: 未找到目标\n${formatCancelableList(list)}`, 'error'));
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
try {
|
|
258
|
+
validateReverseAtRun(options.captainService, cancelTarget.runId);
|
|
259
|
+
}
|
|
260
|
+
catch (error) {
|
|
261
|
+
const reason = error instanceof ReverseChannelError
|
|
262
|
+
? error.code
|
|
263
|
+
: REVERSE_CHANNEL_ERROR_CODES.E_REVERSE_AT_RUN_GONE;
|
|
264
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ /cancel ${cancelTarget.shortId}: ${reason}`, 'error'));
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const session = findSessionByRunId(options.captainService, cancelTarget.runId);
|
|
268
|
+
if (!session) {
|
|
269
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ /cancel ${cancelTarget.shortId}: ${REVERSE_CHANNEL_ERROR_CODES.E_REVERSE_AT_RUN_GONE}`, 'error'));
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (session.record.operator === context.userOpenId) {
|
|
273
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ /cancel ${cancelTarget.shortId}: 该入口仅用于 admin 止损,请使用现有 operator 控制路径`, 'error'));
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
const auth = await authorizeReverseAtCommand(session, context, options.resolveAdminRole);
|
|
277
|
+
if (auth.role === 'denied') {
|
|
278
|
+
writeReverseAtAudit(options.dataDir, session, 'denied', context, auth.reason === 'fail_closed'
|
|
279
|
+
? 'reverse-channel:reverse-at:denied_fail_closed'
|
|
280
|
+
: 'reverse-channel:reverse-at:denied');
|
|
281
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(auth.reason === 'fail_closed'
|
|
282
|
+
? `❌ 无权操作 ${cancelTarget.shortId} (群角色查询失败,已按 fail-closed 拒绝)`
|
|
283
|
+
: `❌ 无权操作 ${cancelTarget.shortId} (非发起人/管理员)`, 'error'));
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
if (auth.role === 'operator') {
|
|
287
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ /cancel ${cancelTarget.shortId}: operator 不应进入 admin cancel 分支`, 'error'));
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const result = options.executeCancel ? await options.executeCancel(cancelTarget.runId) : 'cancelled';
|
|
291
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(result === 'cancelled'
|
|
292
|
+
? `✅ /cancel ${cancelTarget.shortId}: 已叫停 ${cancelTarget.label}`
|
|
293
|
+
: `✅ /cancel ${cancelTarget.shortId}: ${cancelTarget.label} 已结束,无需再叫停`, 'done'));
|
|
294
|
+
writeAdminCancelAudit(options.dataDir, session, context, {
|
|
295
|
+
actorRole: auth.role,
|
|
296
|
+
shortId: cancelTarget.shortId,
|
|
297
|
+
result,
|
|
298
|
+
});
|
|
299
|
+
await options.notifyOperator?.({
|
|
300
|
+
runId: cancelTarget.runId,
|
|
301
|
+
shortId: cancelTarget.shortId,
|
|
302
|
+
actorOpenId: context.userOpenId,
|
|
303
|
+
actorRole: auth.role,
|
|
304
|
+
operatorOpenId: session.record.operator,
|
|
305
|
+
result,
|
|
306
|
+
});
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const session = findSessionByRunId(options.captainService, cmd.run_id);
|
|
310
|
+
if (!session) {
|
|
311
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ ${cmd.command} ${cmd.run_id}: ${REVERSE_CHANNEL_ERROR_CODES.E_REVERSE_AT_RUN_GONE}`, 'error'));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
const auth = await authorizeReverseAtCommand(session, context, options.resolveAdminRole);
|
|
315
|
+
if (auth.role === 'denied') {
|
|
316
|
+
writeReverseAtAudit(options.dataDir, session, 'denied', context, auth.reason === 'fail_closed'
|
|
317
|
+
? 'reverse-channel:reverse-at:denied_fail_closed'
|
|
318
|
+
: 'reverse-channel:reverse-at:denied');
|
|
319
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(auth.reason === 'fail_closed'
|
|
320
|
+
? `❌ 无权操作 ${cmd.run_id} (群角色查询失败,已按 fail-closed 拒绝)`
|
|
321
|
+
: `❌ 无权操作 ${cmd.run_id} (非发起人/管理员)`, 'error'));
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const client = createIpcClient(captainSocketPath(options.dataDir));
|
|
325
|
+
const connection = await client.openSession({ runId: cmd.run_id });
|
|
326
|
+
try {
|
|
327
|
+
const ack = await connection.send({ kind: 'control', command: cmd.command, run_id: cmd.run_id });
|
|
328
|
+
writeReverseAtAudit(options.dataDir, session, cmd.command, context, `reverse-channel:reverse-at:${cmd.command}`);
|
|
329
|
+
if (ack.kind === 'ack' && ack.ok) {
|
|
330
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`✅ ${cmd.command} ${cmd.run_id}`, 'done'));
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
const reason = ack.kind === 'ack' ? (ack.reason ?? 'unknown') : 'non-ack response';
|
|
334
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(`❌ ${cmd.command} ${cmd.run_id}: ${reason}`, 'error'));
|
|
335
|
+
}
|
|
336
|
+
catch (error) {
|
|
337
|
+
const text = error instanceof ReverseChannelError && error.code === REVERSE_CHANNEL_ERROR_CODES.E_IPC_SEND_TIMEOUT
|
|
338
|
+
? `⏱ ${cmd.command} ${cmd.run_id}: ipc timeout`
|
|
339
|
+
: `❌ ${cmd.command} ${cmd.run_id}: ${error instanceof Error ? error.message : String(error)}`;
|
|
340
|
+
await options.feishu.replyCard(context.messageId, renderSystemCard(text, 'error'));
|
|
341
|
+
}
|
|
342
|
+
finally {
|
|
343
|
+
await connection.close();
|
|
344
|
+
}
|
|
345
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { runEventsPath, runHeartbeatPath, runStatusPath } from '../../../../packages/core/src/paths.js';
|
|
3
|
+
export function judgeRunState(botId, runId, opts) {
|
|
4
|
+
if (botId.includes('..'))
|
|
5
|
+
return 'lost';
|
|
6
|
+
const statusPath = runStatusPath(opts.dataDir, runId, botId);
|
|
7
|
+
if (!existsSync(statusPath))
|
|
8
|
+
return 'lost';
|
|
9
|
+
const status = readFileSync(statusPath, 'utf8').trim();
|
|
10
|
+
if (status !== 'running')
|
|
11
|
+
return 'lost';
|
|
12
|
+
const now = opts.now ?? Date.now();
|
|
13
|
+
const l1Fresh = isHeartbeatFresh(runHeartbeatPath(opts.dataDir, runId, botId), now, opts.staleMs, 'file');
|
|
14
|
+
const l2Fresh = isHeartbeatFresh(runEventsPath(opts.dataDir, runId, botId), now, opts.staleMs, 'mtime');
|
|
15
|
+
return l1Fresh || l2Fresh ? 'resumed' : 'lost';
|
|
16
|
+
}
|
|
17
|
+
function isHeartbeatFresh(path, now, staleMs, mode) {
|
|
18
|
+
if (!existsSync(path))
|
|
19
|
+
return false;
|
|
20
|
+
try {
|
|
21
|
+
if (mode === 'file') {
|
|
22
|
+
const ts = parseInt(readFileSync(path, 'utf8').trim(), 10) * 1000;
|
|
23
|
+
return (now - ts) < staleMs;
|
|
24
|
+
}
|
|
25
|
+
return (now - statSync(path).mtimeMs) < staleMs;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function resolveReverseAtCancelTargetFromSession(session) {
|
|
2
|
+
if (!session?.runId || !session.sessionShortId)
|
|
3
|
+
return null;
|
|
4
|
+
return {
|
|
5
|
+
runId: session.runId,
|
|
6
|
+
shortId: session.sessionShortId,
|
|
7
|
+
label: `${session.agentId} · ${session.sessionShortId}`,
|
|
8
|
+
};
|
|
9
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
export function createInitialState(agentId, agentDisplayName, agentPersona) {
|
|
2
|
+
return {
|
|
3
|
+
agentId,
|
|
4
|
+
agentDisplayName,
|
|
5
|
+
agentPersona,
|
|
6
|
+
text: '',
|
|
7
|
+
thinking: '',
|
|
8
|
+
tools: [],
|
|
9
|
+
hasContext: false,
|
|
10
|
+
includeMeta: true,
|
|
11
|
+
stopState: 'running',
|
|
12
|
+
terminalState: 'running',
|
|
13
|
+
startedAt: Date.now(),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export const SESSION_SHORT_ID_MIN_LEN = 8;
|
|
17
|
+
export function allocateSessionShortId(runId, existing, minLength = SESSION_SHORT_ID_MIN_LEN) {
|
|
18
|
+
const used = new Set(existing);
|
|
19
|
+
for (let length = minLength; length <= runId.length; length += 1) {
|
|
20
|
+
const candidate = runId.slice(0, length);
|
|
21
|
+
if (!used.has(candidate))
|
|
22
|
+
return candidate;
|
|
23
|
+
}
|
|
24
|
+
return runId;
|
|
25
|
+
}
|
|
26
|
+
export function reduceStreamState(state, event) {
|
|
27
|
+
if (event.type === 'text')
|
|
28
|
+
return { ...state, text: `${state.text}${event.delta}` };
|
|
29
|
+
if (event.type === 'thinking')
|
|
30
|
+
return { ...state, thinking: `${state.thinking}${event.delta}` };
|
|
31
|
+
if (event.type === 'system') {
|
|
32
|
+
return {
|
|
33
|
+
...state,
|
|
34
|
+
cwd: event.cwd ?? state.cwd,
|
|
35
|
+
model: event.model ?? state.model,
|
|
36
|
+
continuationToken: event.continuationToken ?? state.continuationToken,
|
|
37
|
+
hasContext: Boolean(event.continuationToken ?? state.continuationToken),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
if (event.type === 'tool_use') {
|
|
41
|
+
return { ...state, tools: [...state.tools, { id: event.id, name: event.name, input: event.input }] };
|
|
42
|
+
}
|
|
43
|
+
if (event.type === 'tool_result') {
|
|
44
|
+
return {
|
|
45
|
+
...state,
|
|
46
|
+
tools: state.tools.map((tool) => (tool.id === event.id ? { ...tool, output: event.output, isError: event.isError } : tool)),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (event.type === 'usage')
|
|
50
|
+
return { ...state, usage: { inputTokens: event.inputTokens, outputTokens: event.outputTokens, costUsd: event.costUsd } };
|
|
51
|
+
if (event.type === 'done') {
|
|
52
|
+
return {
|
|
53
|
+
...state,
|
|
54
|
+
terminalState: 'done',
|
|
55
|
+
stopState: state.stopState === 'stopping' ? 'stopped' : state.stopState,
|
|
56
|
+
continuationToken: event.continuationToken ?? state.continuationToken,
|
|
57
|
+
hasContext: Boolean(event.continuationToken ?? state.continuationToken),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
if (event.type === 'error') {
|
|
61
|
+
if (state.stopState === 'stopping') {
|
|
62
|
+
return {
|
|
63
|
+
...state,
|
|
64
|
+
terminalState: 'done',
|
|
65
|
+
stopState: 'stopped',
|
|
66
|
+
errorMessage: undefined,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
return { ...state, terminalState: 'error', errorMessage: event.message };
|
|
70
|
+
}
|
|
71
|
+
return state;
|
|
72
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
function readToken(value) {
|
|
2
|
+
if (typeof value !== 'string')
|
|
3
|
+
return null;
|
|
4
|
+
const trimmed = value.trim();
|
|
5
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
6
|
+
}
|
|
7
|
+
export function toChatTopicKey(chatId) {
|
|
8
|
+
const value = readToken(chatId);
|
|
9
|
+
if (!value)
|
|
10
|
+
return null;
|
|
11
|
+
return value.startsWith('chat:') ? value : `chat:${value}`;
|
|
12
|
+
}
|
|
13
|
+
export function toRootTopicKey(rootId) {
|
|
14
|
+
const value = readToken(rootId);
|
|
15
|
+
if (!value)
|
|
16
|
+
return null;
|
|
17
|
+
return value.startsWith('root:') ? value : `root:${value}`;
|
|
18
|
+
}
|
|
19
|
+
export function normalizeTopic(input) {
|
|
20
|
+
const rootKey = toRootTopicKey(input.rootId);
|
|
21
|
+
if (rootKey)
|
|
22
|
+
return rootKey;
|
|
23
|
+
const chatKey = toChatTopicKey(input.chatId);
|
|
24
|
+
const messageToken = readToken(input.messageId);
|
|
25
|
+
const groupLikeMessage = input.chatType != null && input.chatType !== 'p2p';
|
|
26
|
+
if (groupLikeMessage && messageToken) {
|
|
27
|
+
return messageToken.startsWith('root:') ? messageToken : `root:${messageToken}`;
|
|
28
|
+
}
|
|
29
|
+
if (chatKey)
|
|
30
|
+
return chatKey;
|
|
31
|
+
if (messageToken)
|
|
32
|
+
return messageToken.startsWith('root:') ? messageToken : `root:${messageToken}`;
|
|
33
|
+
return 'chat:';
|
|
34
|
+
}
|