@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,84 @@
|
|
|
1
|
+
import { MuteRegistry, defaultMuteRegistryPath } from '../../../../packages/core/src/reverse-channel/index.js';
|
|
2
|
+
import { parseCommand } from './parser.js';
|
|
3
|
+
/**
|
|
4
|
+
* /wb mute — session 维度静音 (PRD §2.7 反向 @ 礼仪第 4 条)
|
|
5
|
+
*
|
|
6
|
+
* 用法:
|
|
7
|
+
* /wb mute <sid> <duration> — <sid> 为 sessionId 或 shortId (前 12 字符);
|
|
8
|
+
* <duration> 支持 30s / 15m / 2h / 7d
|
|
9
|
+
* /wb mute list — 列出当前 session 维度的有效静音
|
|
10
|
+
* /wb unmute <sid> — 解除静音
|
|
11
|
+
*
|
|
12
|
+
* sessionId 解析规则:
|
|
13
|
+
* - 如果参数正好 12 位且是当前 thread 的 shortId, 自动扩展为 full sessionId
|
|
14
|
+
* (`${botId}:${userOpenId}:${threadId}`)
|
|
15
|
+
* - 否则按字面 sessionId 寻找 (允许跨 thread, owner 特权场景)
|
|
16
|
+
*
|
|
17
|
+
* 解析不到 sid 时 (用户没传 / 当前 thread 没 active session):
|
|
18
|
+
* 返回提示, 不抛错.
|
|
19
|
+
*/
|
|
20
|
+
function resolveSessionId(sidArg, ctx) {
|
|
21
|
+
if (sidArg.length === 0)
|
|
22
|
+
return null;
|
|
23
|
+
// 当前 thread 的 sessionId 是权威解析
|
|
24
|
+
const ownThreadSid = `${ctx.botId}:${ctx.userOpenId}:${ctx.threadId}`;
|
|
25
|
+
if (sidArg === ownThreadSid)
|
|
26
|
+
return ownThreadSid;
|
|
27
|
+
// 支持 sid 前缀短写 (前 12 字符)
|
|
28
|
+
if (sidArg.length === 12 && ownThreadSid.startsWith(sidArg))
|
|
29
|
+
return ownThreadSid;
|
|
30
|
+
// 未匹配当前 thread 时仍按字面 sid 用 (owner 跨 thread mute 也需要)
|
|
31
|
+
return sidArg;
|
|
32
|
+
}
|
|
33
|
+
export async function handleWbMute(args, ctx, registry) {
|
|
34
|
+
const [sub, ...rest] = args;
|
|
35
|
+
if (sub === 'list') {
|
|
36
|
+
const items = registry.list();
|
|
37
|
+
if (items.length === 0)
|
|
38
|
+
return '当前没有静音中的 session';
|
|
39
|
+
const lines = ['静音中的 session:'];
|
|
40
|
+
for (const item of items) {
|
|
41
|
+
const sidShort = item.sessionId.length > 24 ? `${item.sessionId.slice(0, 24)}…` : item.sessionId;
|
|
42
|
+
const reasonSuffix = item.reason ? ` (${item.reason})` : '';
|
|
43
|
+
lines.push(`- ${sidShort} · till ${item.expiresAtIso}${reasonSuffix}`);
|
|
44
|
+
}
|
|
45
|
+
return lines.join('\n');
|
|
46
|
+
}
|
|
47
|
+
if (sub === undefined) {
|
|
48
|
+
return [
|
|
49
|
+
'用法:',
|
|
50
|
+
' /wb mute <sid> <duration> (30s/15m/2h/7d)',
|
|
51
|
+
' /wb mute list',
|
|
52
|
+
' /wb unmute <sid>',
|
|
53
|
+
].join('\n');
|
|
54
|
+
}
|
|
55
|
+
const sidArg = sub;
|
|
56
|
+
const duration = rest[0];
|
|
57
|
+
if (!duration)
|
|
58
|
+
return '缺 duration: /wb mute <sid> <duration>';
|
|
59
|
+
const sessionId = resolveSessionId(sidArg, ctx);
|
|
60
|
+
if (!sessionId)
|
|
61
|
+
return `未解析到 sessionId: ${sidArg}`;
|
|
62
|
+
const result = registry.mute(sessionId, duration, { reason: `im /wb mute by ${ctx.userOpenId}` });
|
|
63
|
+
if (!result.ok)
|
|
64
|
+
return `❌ ${result.error}`;
|
|
65
|
+
const sidShort = sessionId.length > 24 ? `${sessionId.slice(0, 24)}…` : sessionId;
|
|
66
|
+
return `✅ 已静音 ${sidShort} 至 ${result.expiresAtIso}`;
|
|
67
|
+
}
|
|
68
|
+
export async function handleWbUnmute(args, ctx, registry) {
|
|
69
|
+
const [sidArg] = args;
|
|
70
|
+
if (!sidArg)
|
|
71
|
+
return '用法: /wb unmute <sid>';
|
|
72
|
+
const sessionId = resolveSessionId(sidArg, ctx);
|
|
73
|
+
if (!sessionId)
|
|
74
|
+
return `未解析到 sessionId: ${sidArg}`;
|
|
75
|
+
const result = registry.unmute(sessionId);
|
|
76
|
+
if (!result.ok)
|
|
77
|
+
return `未找到 ${sessionId} 的静音记录`;
|
|
78
|
+
return `✅ 已解除 ${sessionId.slice(0, 24)}${sessionId.length > 24 ? '…' : ''} 的静音`;
|
|
79
|
+
}
|
|
80
|
+
export function createMuteRegistry(dataDir) {
|
|
81
|
+
return new MuteRegistry(defaultMuteRegistryPath(dataDir));
|
|
82
|
+
}
|
|
83
|
+
// parseCommand re-export to keep parity with router (single source).
|
|
84
|
+
export { parseCommand };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { loadGroupSyncConfig, syncGroupCommand, createMockGroupSyncTransport, } from '../../../../packages/core/src/group-sync/index.js';
|
|
3
|
+
/**
|
|
4
|
+
* `/wb sync` 命令 handler(M11-C C3)。
|
|
5
|
+
* PRD §5.1 中 F8-F12 触发面在 IM;这里把 group-sync 已有 service 接到 IM slash:
|
|
6
|
+
*
|
|
7
|
+
* /wb sync — 手动触发一次 sync
|
|
8
|
+
* /wb sync dry — run sync 但不真正写 mock transport 状态(留接口)
|
|
9
|
+
*
|
|
10
|
+
* 当前用 mock transport 兜底 (没有真正的 IM 群转发通道,不引入新 dispatch surface)。
|
|
11
|
+
* 后续如需真实 sendCard 到其他群,在 `transport` 里换 guarded / 新建 Lark transport。
|
|
12
|
+
*/
|
|
13
|
+
export async function handleWbSync(args, ctx) {
|
|
14
|
+
// 必需的 controlPlane.dataDir 是 group-sync state 的落点.
|
|
15
|
+
const dataDir = ctx.controlPlane?.dataDir;
|
|
16
|
+
if (!dataDir) {
|
|
17
|
+
return '⚠️ /wb sync 不可用 (control plane 未启动)';
|
|
18
|
+
}
|
|
19
|
+
const config = loadGroupSyncConfig({ env: { WB_DATA_DIR: dataDir } });
|
|
20
|
+
if (!config.enabled) {
|
|
21
|
+
return [
|
|
22
|
+
'⚠️ group-sync 未启用',
|
|
23
|
+
`当前 transport=${config.transport}`,
|
|
24
|
+
'要开启,在 `config/group-sync.json` 或 legacy `config.json` 里把 `group_sync.enabled` 设为 true',
|
|
25
|
+
].join('\n');
|
|
26
|
+
}
|
|
27
|
+
const sub = args[1] ?? 'run';
|
|
28
|
+
if (sub !== 'run') {
|
|
29
|
+
return 'Usage: /wb sync run';
|
|
30
|
+
}
|
|
31
|
+
const runId = `run-wb-sync-${randomUUID().slice(0, 8)}`;
|
|
32
|
+
const command = {
|
|
33
|
+
request_id: `req-${randomUUID()}`,
|
|
34
|
+
session_id: `${ctx.botId}:${ctx.userOpenId}:${ctx.threadId}`,
|
|
35
|
+
run_id: runId,
|
|
36
|
+
revision: 0,
|
|
37
|
+
text: `/wb sync ${sub}`,
|
|
38
|
+
scheduled_at: new Date().toISOString(),
|
|
39
|
+
user_open_id: ctx.userOpenId,
|
|
40
|
+
thread_id: ctx.threadId,
|
|
41
|
+
message_id: runId,
|
|
42
|
+
};
|
|
43
|
+
const result = await syncGroupCommand({
|
|
44
|
+
dataDir,
|
|
45
|
+
botId: ctx.botId,
|
|
46
|
+
command,
|
|
47
|
+
config,
|
|
48
|
+
transport: createMockGroupSyncTransport(dataDir),
|
|
49
|
+
});
|
|
50
|
+
if (result.sync_failed) {
|
|
51
|
+
return `❌ sync 失败: ${result.state.last_error ?? 'unknown'}`;
|
|
52
|
+
}
|
|
53
|
+
return [
|
|
54
|
+
`✅ sync 已开始 (run_id=${runId})`,
|
|
55
|
+
`session=${command.session_id}`,
|
|
56
|
+
`state.last_synced_at=${result.state.last_synced_at ?? '-'}`,
|
|
57
|
+
].join('\n');
|
|
58
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
const OPEN_ID_PATTERN = /^ou_[A-Za-z0-9_-]+$/;
|
|
5
|
+
const RuleSchema = z.object({
|
|
6
|
+
paths: z.array(z.string().min(1)).min(1),
|
|
7
|
+
codeOwnerOpenIds: z.array(z.string().regex(OPEN_ID_PATTERN)).min(1),
|
|
8
|
+
});
|
|
9
|
+
const BranchSchema = z.object({
|
|
10
|
+
name: z.string().min(1),
|
|
11
|
+
rules: z.array(RuleSchema).min(1),
|
|
12
|
+
});
|
|
13
|
+
const RepositorySchema = z.object({
|
|
14
|
+
repoRoot: z.string().min(1),
|
|
15
|
+
branches: z.array(BranchSchema).min(1),
|
|
16
|
+
});
|
|
17
|
+
export const ApprovalCodeOwnerConfigSchema = z.object({
|
|
18
|
+
version: z.literal(1),
|
|
19
|
+
repositories: z.array(RepositorySchema).min(1),
|
|
20
|
+
});
|
|
21
|
+
export class ApprovalCodeOwnerConfigError extends Error {
|
|
22
|
+
cause;
|
|
23
|
+
constructor(message, cause) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.cause = cause;
|
|
26
|
+
this.name = 'ApprovalCodeOwnerConfigError';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function validateMode(path) {
|
|
30
|
+
const stat = statSync(path);
|
|
31
|
+
if ((stat.mode & 0o077) !== 0) {
|
|
32
|
+
throw new ApprovalCodeOwnerConfigError(`${path} permissions are too open (${(stat.mode & 0o777).toString(8)}), expected 600`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function resolveApprovalCodeOwnerConfigPath(env = process.env) {
|
|
36
|
+
const raw = env['WB_APPROVAL_CODE_OWNER_CONFIG_PATH'];
|
|
37
|
+
return raw && raw.trim() ? resolve(raw.trim()) : undefined;
|
|
38
|
+
}
|
|
39
|
+
export function loadApprovalCodeOwnerConfig(options = {}) {
|
|
40
|
+
const env = options.env ?? process.env;
|
|
41
|
+
const rawPath = options.configPath ?? resolveApprovalCodeOwnerConfigPath(env);
|
|
42
|
+
if (!rawPath) {
|
|
43
|
+
throw new ApprovalCodeOwnerConfigError('approval code owner config path is missing');
|
|
44
|
+
}
|
|
45
|
+
const path = resolve(rawPath);
|
|
46
|
+
if (!existsSync(path)) {
|
|
47
|
+
throw new ApprovalCodeOwnerConfigError(`approval code owner config not found: ${path}`);
|
|
48
|
+
}
|
|
49
|
+
validateMode(path);
|
|
50
|
+
let parsed;
|
|
51
|
+
try {
|
|
52
|
+
parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
throw new ApprovalCodeOwnerConfigError(`failed to parse ${path}: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
return ApprovalCodeOwnerConfigSchema.parse(parsed);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
throw new ApprovalCodeOwnerConfigError('approval code owner config is invalid', error);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function globToRegex(pattern) {
|
|
65
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
66
|
+
const withGlob = escaped
|
|
67
|
+
.replace(/\*\*/g, '§§DOUBLESTAR§§')
|
|
68
|
+
.replace(/\*/g, '[^/]*')
|
|
69
|
+
.replace(/§§DOUBLESTAR§§/g, '.*');
|
|
70
|
+
return new RegExp(`^${withGlob}$`);
|
|
71
|
+
}
|
|
72
|
+
export function resolveConfiguredCodeOwners(config, input) {
|
|
73
|
+
const repository = config.repositories.find((entry) => resolve(entry.repoRoot) === resolve(input.repoRoot));
|
|
74
|
+
if (!repository) {
|
|
75
|
+
throw new ApprovalCodeOwnerConfigError(`no approval repository config for ${input.repoRoot}`);
|
|
76
|
+
}
|
|
77
|
+
const branch = repository.branches.find((entry) => entry.name === input.branch);
|
|
78
|
+
if (!branch) {
|
|
79
|
+
throw new ApprovalCodeOwnerConfigError(`no approval branch config for ${input.branch}`);
|
|
80
|
+
}
|
|
81
|
+
const owners = new Set();
|
|
82
|
+
for (const changedPath of input.changedPaths) {
|
|
83
|
+
const normalizedPath = changedPath.replace(/^\.\//, '');
|
|
84
|
+
const matchingRule = branch.rules.find((rule) => rule.paths.some((pattern) => globToRegex(pattern).test(normalizedPath)));
|
|
85
|
+
if (!matchingRule) {
|
|
86
|
+
throw new ApprovalCodeOwnerConfigError(`no approval rule matched path ${normalizedPath}`);
|
|
87
|
+
}
|
|
88
|
+
for (const openId of matchingRule.codeOwnerOpenIds)
|
|
89
|
+
owners.add(openId);
|
|
90
|
+
}
|
|
91
|
+
if (owners.size === 0) {
|
|
92
|
+
throw new ApprovalCodeOwnerConfigError('resolved code owner set is empty');
|
|
93
|
+
}
|
|
94
|
+
return [...owners].sort();
|
|
95
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { parse as dotenvParse } from 'dotenv';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { assertValidBotId } from '../security/bot-id-validator.js';
|
|
5
|
+
import { basename } from 'node:path';
|
|
6
|
+
import { botEnvPath, resolveBotConfigDir } from './config-paths.js';
|
|
7
|
+
import { assertNoPlaceholderLarkCredentials } from './lark-credentials.js';
|
|
8
|
+
const BotConfigSchema = z.object({
|
|
9
|
+
BOT_ID: z.string().min(1),
|
|
10
|
+
LARK_APP_ID: z.string().min(1),
|
|
11
|
+
LARK_APP_SECRET: z.string().min(1),
|
|
12
|
+
LARK_ENCRYPT_KEY: z.string().optional().default(''),
|
|
13
|
+
LARK_VERIFICATION_TOKEN: z.string().optional().default(''),
|
|
14
|
+
AGENT_ALLOWED: z.string().optional().default('claude-code,codex'),
|
|
15
|
+
WB_DEFAULT_CWD: z.string().optional(),
|
|
16
|
+
WB_APPROVAL_CODE_OWNER_CONFIG_PATH: z.string().optional(),
|
|
17
|
+
WB_CLAUDE_COMMAND: z.string().optional(),
|
|
18
|
+
WB_CODEX_COMMAND: z.string().optional(),
|
|
19
|
+
// `strict` 接受输入但由 wb-bot 内部 alias 为 `plan-only` (见 §下方 normalize).
|
|
20
|
+
// 见 docs/product-strategy.md "Consent contract in wb-bot (no-TTY invariant)".
|
|
21
|
+
WB_CLAUDE_CONSENT_LEVEL: z.enum(['normal', 'relaxed', 'auto', 'plan-only', 'strict']).optional().default('auto'),
|
|
22
|
+
LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace']).optional().default('info'),
|
|
23
|
+
});
|
|
24
|
+
/**
|
|
25
|
+
* wb-bot consent normalize (W2.5-Hotfix-batch-C P1-4):
|
|
26
|
+
*
|
|
27
|
+
* wb-bot 永远以 backend 进程 `spawn` agent CLI, 无 TTY 无 stdin.
|
|
28
|
+
* 任何 startup-phase interactive prompt 都会 hang 子进程 → 卡片冻在 running.
|
|
29
|
+
* 因此 wb-bot 对 `claude-code` 路径除 `plan-only` 之外一律附加
|
|
30
|
+
* `--dangerously-skip-permissions` 短路底层 CLI permission UI.
|
|
31
|
+
*
|
|
32
|
+
* `strict` consent 在 core/CLI 语义里 = "ask me for everything", 在 no-TTY
|
|
33
|
+
* 环境无法兑现. 这里把它 alias 为 `plan-only` (功能等价于 wb-bot 能保证的最严
|
|
34
|
+
* 模式: 只产 plan 不执行 tool, trust 风险 = 0).
|
|
35
|
+
*
|
|
36
|
+
* 这不是把 contract 收窄, 而是把 wb-bot 在 contract 上的真实可兑现集明文化.
|
|
37
|
+
* 完整漂移说明: docs/product-strategy.md "Consent contract in wb-bot".
|
|
38
|
+
*/
|
|
39
|
+
export function normalizeBotConsentLevel(level) {
|
|
40
|
+
if (level === 'strict')
|
|
41
|
+
return 'plan-only';
|
|
42
|
+
return level;
|
|
43
|
+
}
|
|
44
|
+
export function resolveBotEnvPath(botId, opts = {}) {
|
|
45
|
+
return botEnvPath(resolveBotConfigDir(opts), botId);
|
|
46
|
+
}
|
|
47
|
+
export function loadBotEnvFromFile(filePath) {
|
|
48
|
+
if (!existsSync(filePath)) {
|
|
49
|
+
throw new Error(`Bot env file not found: ${filePath} — check \${WB_CONFIG_DIR} and ensure the file exists`);
|
|
50
|
+
}
|
|
51
|
+
const raw = readFileSync(filePath, 'utf8');
|
|
52
|
+
const parsed = dotenvParse(raw);
|
|
53
|
+
const validated = BotConfigSchema.parse(parsed);
|
|
54
|
+
assertNoPlaceholderLarkCredentials({
|
|
55
|
+
appId: validated.LARK_APP_ID,
|
|
56
|
+
appSecret: validated.LARK_APP_SECRET,
|
|
57
|
+
sourceLabel: filePath,
|
|
58
|
+
});
|
|
59
|
+
const botId = assertValidBotId(validated.BOT_ID, `BOT_ID in ${filePath}`);
|
|
60
|
+
// verify BOT_ID matches filename convention (.env.<botId>)
|
|
61
|
+
const fileName = basename(filePath);
|
|
62
|
+
const expectedPrefix = `.env.${botId}`;
|
|
63
|
+
if (fileName !== expectedPrefix) {
|
|
64
|
+
throw new Error(`BOT_ID mismatch: file "${fileName}" contains BOT_ID="${botId}", expected file ".env.${botId}" — path: ${filePath}`);
|
|
65
|
+
}
|
|
66
|
+
return {
|
|
67
|
+
botId,
|
|
68
|
+
larkAppId: validated.LARK_APP_ID,
|
|
69
|
+
larkAppSecret: validated.LARK_APP_SECRET,
|
|
70
|
+
larkEncryptKey: validated.LARK_ENCRYPT_KEY,
|
|
71
|
+
larkVerificationToken: validated.LARK_VERIFICATION_TOKEN,
|
|
72
|
+
agentAllowed: validated.AGENT_ALLOWED.split(',').map((s) => s.trim()).filter(Boolean),
|
|
73
|
+
defaultCwd: validated.WB_DEFAULT_CWD?.trim() || undefined,
|
|
74
|
+
approvalCodeOwnerConfigPath: validated.WB_APPROVAL_CODE_OWNER_CONFIG_PATH?.trim() || undefined,
|
|
75
|
+
claudeCommand: validated.WB_CLAUDE_COMMAND?.trim() || 'claude',
|
|
76
|
+
codexCommand: validated.WB_CODEX_COMMAND?.trim() || 'codex',
|
|
77
|
+
consentLevel: normalizeBotConsentLevel(validated.WB_CLAUDE_CONSENT_LEVEL),
|
|
78
|
+
logLevel: validated.LOG_LEVEL,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
export function resolveBotConfigDir(opts = {}) {
|
|
4
|
+
if (opts.configDir && opts.configDir.trim())
|
|
5
|
+
return opts.configDir.trim();
|
|
6
|
+
const envDir = process.env['WB_CONFIG_DIR'];
|
|
7
|
+
if (envDir && envDir.trim())
|
|
8
|
+
return envDir.trim();
|
|
9
|
+
return join(homedir(), '.weaverbird', 'configs');
|
|
10
|
+
}
|
|
11
|
+
export function resolveConfigDir() {
|
|
12
|
+
return resolveBotConfigDir();
|
|
13
|
+
}
|
|
14
|
+
export function botEnvPath(configDir, botId) {
|
|
15
|
+
return join(configDir, `.env.${botId}`);
|
|
16
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { config as loadDotenv } from 'dotenv';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { resolveDataDir } from '../../../../packages/core/src/paths.js';
|
|
4
|
+
import { assertValidBotId } from '../security/bot-id-validator.js';
|
|
5
|
+
import { normalizeBotConsentLevel } from './bot-env.js';
|
|
6
|
+
import { assertNoPlaceholderLarkCredentials } from './lark-credentials.js';
|
|
7
|
+
loadDotenv({ path: new URL('../../.env', import.meta.url).pathname, override: false });
|
|
8
|
+
loadDotenv({ override: false });
|
|
9
|
+
const EnvSchema = z.object({
|
|
10
|
+
LARK_APP_ID: z.string().min(1),
|
|
11
|
+
LARK_APP_SECRET: z.string().min(1),
|
|
12
|
+
LARK_ENCRYPT_KEY: z.string().optional().default(''),
|
|
13
|
+
LARK_VERIFICATION_TOKEN: z.string().optional().default(''),
|
|
14
|
+
WB_DATA_DIR: z.string().optional(),
|
|
15
|
+
WB_CLAUDE_COMMAND: z.string().optional(),
|
|
16
|
+
WB_CODEX_COMMAND: z.string().optional(),
|
|
17
|
+
WB_DEFAULT_CWD: z.string().optional(),
|
|
18
|
+
WB_REVERSE_AT_ADMIN_OPEN_IDS: z.string().optional(),
|
|
19
|
+
WB_APPROVAL_CODE_OWNER_CONFIG_PATH: z.string().optional(),
|
|
20
|
+
// `strict` 接受输入但 alias 为 `plan-only` (no-TTY invariant, 见 bot-env.ts normalizeBotConsentLevel).
|
|
21
|
+
WB_CLAUDE_CONSENT_LEVEL: z.enum(['normal', 'relaxed', 'auto', 'plan-only', 'strict']).optional().default('auto'),
|
|
22
|
+
LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace']).optional().default('info'),
|
|
23
|
+
BOT_ID: z.string().optional(),
|
|
24
|
+
WB_MODE: z.enum(['single', 'multi-bot']).optional().default('single'),
|
|
25
|
+
});
|
|
26
|
+
export function readEnv(input = process.env) {
|
|
27
|
+
const env = EnvSchema.parse(input);
|
|
28
|
+
assertNoPlaceholderLarkCredentials({
|
|
29
|
+
appId: env.LARK_APP_ID,
|
|
30
|
+
appSecret: env.LARK_APP_SECRET,
|
|
31
|
+
sourceLabel: 'process env / apps/wb-bot/.env',
|
|
32
|
+
});
|
|
33
|
+
return {
|
|
34
|
+
...env,
|
|
35
|
+
WB_CLAUDE_CONSENT_LEVEL: normalizeBotConsentLevel(env.WB_CLAUDE_CONSENT_LEVEL),
|
|
36
|
+
dataDir: resolveDataDir({ dataDir: env.WB_DATA_DIR && env.WB_DATA_DIR.trim() ? env.WB_DATA_DIR : undefined }),
|
|
37
|
+
claudeCommand: env.WB_CLAUDE_COMMAND && env.WB_CLAUDE_COMMAND.trim() ? env.WB_CLAUDE_COMMAND.trim() : 'claude',
|
|
38
|
+
codexCommand: env.WB_CODEX_COMMAND && env.WB_CODEX_COMMAND.trim() ? env.WB_CODEX_COMMAND.trim() : 'codex',
|
|
39
|
+
defaultCwd: env.WB_DEFAULT_CWD && env.WB_DEFAULT_CWD.trim() ? env.WB_DEFAULT_CWD.trim() : undefined,
|
|
40
|
+
botId: assertValidBotId(env.BOT_ID ?? 'default', 'BOT_ID env'),
|
|
41
|
+
mode: env.WB_MODE,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const LARK_CREDENTIAL_PLACEHOLDERS = {
|
|
2
|
+
LARK_APP_ID: new Set(['your_lark_app_id_here']),
|
|
3
|
+
LARK_APP_SECRET: new Set(['your_lark_app_secret_here']),
|
|
4
|
+
};
|
|
5
|
+
function assertNotPlaceholder(key, value, sourceLabel) {
|
|
6
|
+
const trimmed = value.trim();
|
|
7
|
+
if (!LARK_CREDENTIAL_PLACEHOLDERS[key].has(trimmed))
|
|
8
|
+
return;
|
|
9
|
+
throw new Error(`${key} in ${sourceLabel} still uses the shipped placeholder; replace it with a real Feishu app credential before starting wb-bot`);
|
|
10
|
+
}
|
|
11
|
+
export function assertNoPlaceholderLarkCredentials(input) {
|
|
12
|
+
assertNotPlaceholder('LARK_APP_ID', input.appId, input.sourceLabel);
|
|
13
|
+
assertNotPlaceholder('LARK_APP_SECRET', input.appSecret, input.sourceLabel);
|
|
14
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import * as Lark from '@larksuiteoapi/node-sdk';
|
|
2
|
+
import { resolveDataDir } from '../../../../packages/core/src/paths.js';
|
|
3
|
+
import { readEnv } from '../config/env.js';
|
|
4
|
+
import { botEnvPath, resolveBotConfigDir } from '../config/config-paths.js';
|
|
5
|
+
import { loadBotEnvFromFile } from '../config/bot-env.js';
|
|
6
|
+
import { createLarkBotIdentityFetcher } from '../feishu/bot-identity.js';
|
|
7
|
+
import { createLarkReverseAtAdminRoleResolver } from '../feishu/reverse-at-im-handler.js';
|
|
8
|
+
import { allocateSessionShortId } from '../feishu/stream-state.js';
|
|
9
|
+
import { resolveReverseAtCancelTargetFromSession } from '../feishu/session-short-id.js';
|
|
10
|
+
function ok(label, detail) {
|
|
11
|
+
return { status: 'ok', label, detail };
|
|
12
|
+
}
|
|
13
|
+
function warn(label, detail) {
|
|
14
|
+
return { status: 'warn', label, detail };
|
|
15
|
+
}
|
|
16
|
+
function errorCheck(label, detail) {
|
|
17
|
+
return { status: 'error', label, detail };
|
|
18
|
+
}
|
|
19
|
+
function trimOrUndefined(value) {
|
|
20
|
+
if (!value)
|
|
21
|
+
return undefined;
|
|
22
|
+
const trimmed = value.trim();
|
|
23
|
+
return trimmed ? trimmed : undefined;
|
|
24
|
+
}
|
|
25
|
+
function detectPreflightChatId(input) {
|
|
26
|
+
return trimOrUndefined(input['WB_E2E_PREFLIGHT_CHAT_ID']) ?? trimOrUndefined(input['WB_ADMIN_THREAD_ID']);
|
|
27
|
+
}
|
|
28
|
+
function resolvePreflightDataDir(input) {
|
|
29
|
+
const configured = trimOrUndefined(input['WB_DATA_DIR']);
|
|
30
|
+
return resolveDataDir({ dataDir: configured });
|
|
31
|
+
}
|
|
32
|
+
function loadMultiBotConfig(input) {
|
|
33
|
+
const rawBotId = trimOrUndefined(input['BOT_ID']);
|
|
34
|
+
if (!rawBotId) {
|
|
35
|
+
throw new Error('multi-bot preflight requires BOT_ID env');
|
|
36
|
+
}
|
|
37
|
+
const configDir = resolveBotConfigDir({ configDir: trimOrUndefined(input['WB_CONFIG_DIR']) });
|
|
38
|
+
const configPath = botEnvPath(configDir, rawBotId);
|
|
39
|
+
const botCfg = loadBotEnvFromFile(configPath);
|
|
40
|
+
const dataDir = resolvePreflightDataDir(input);
|
|
41
|
+
return {
|
|
42
|
+
botId: botCfg.botId,
|
|
43
|
+
dataDir,
|
|
44
|
+
larkAppId: botCfg.larkAppId,
|
|
45
|
+
larkAppSecret: botCfg.larkAppSecret,
|
|
46
|
+
mode: 'multi-bot',
|
|
47
|
+
source: 'bot-env-file',
|
|
48
|
+
configPath,
|
|
49
|
+
preflightChatId: detectPreflightChatId(input),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function loadSingleBotConfig(input) {
|
|
53
|
+
const env = readEnv(input);
|
|
54
|
+
return {
|
|
55
|
+
botId: env.botId,
|
|
56
|
+
dataDir: env.dataDir,
|
|
57
|
+
larkAppId: env.LARK_APP_ID,
|
|
58
|
+
larkAppSecret: env.LARK_APP_SECRET,
|
|
59
|
+
mode: 'single',
|
|
60
|
+
source: 'env',
|
|
61
|
+
preflightChatId: detectPreflightChatId(input),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export function loadReadonlyPreflightConfig(input = process.env) {
|
|
65
|
+
return input['WB_MODE'] === 'multi-bot'
|
|
66
|
+
? loadMultiBotConfig(input)
|
|
67
|
+
: loadSingleBotConfig(input);
|
|
68
|
+
}
|
|
69
|
+
export function createReadonlyPreflightClient(config) {
|
|
70
|
+
return new Lark.Client({ appId: config.larkAppId, appSecret: config.larkAppSecret });
|
|
71
|
+
}
|
|
72
|
+
export async function checkBotIdentityReadable(client) {
|
|
73
|
+
try {
|
|
74
|
+
const identity = await createLarkBotIdentityFetcher(client).fetch();
|
|
75
|
+
return ok('bot online', `bot identity readable · open_id=${identity.openId}${identity.appName ? ` · app=${identity.appName}` : ''}`);
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
return errorCheck('bot online', err instanceof Error ? err.message : String(err));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export async function checkRoleApiReadable(client, chatId, probeOpenId) {
|
|
82
|
+
if (!chatId) {
|
|
83
|
+
return warn('group role API', 'skipped (set WB_E2E_PREFLIGHT_CHAT_ID or WB_ADMIN_THREAD_ID for readonly chat.get probe)');
|
|
84
|
+
}
|
|
85
|
+
const resolver = createLarkReverseAtAdminRoleResolver(client, new Set());
|
|
86
|
+
try {
|
|
87
|
+
const role = await resolver({
|
|
88
|
+
messageId: 'readonly-preflight',
|
|
89
|
+
threadId: chatId,
|
|
90
|
+
userOpenId: probeOpenId,
|
|
91
|
+
});
|
|
92
|
+
return ok('group role API', `chat.get readable · chat_id=${chatId} · resolved_role=${role ?? 'none'}`);
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
return errorCheck('group role API', err instanceof Error ? err.message : String(err));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
export function checkShortIdParseability() {
|
|
99
|
+
const runId = 'syntheticrun0001';
|
|
100
|
+
const shortId = allocateSessionShortId(runId, []);
|
|
101
|
+
const target = resolveReverseAtCancelTargetFromSession({
|
|
102
|
+
agentId: 'claude-code',
|
|
103
|
+
runId,
|
|
104
|
+
sessionShortId: shortId,
|
|
105
|
+
});
|
|
106
|
+
if (!target) {
|
|
107
|
+
return errorCheck('shortId parse', 'failed to resolve synthetic shortId target');
|
|
108
|
+
}
|
|
109
|
+
return ok('shortId parse', `synthetic shortId resolves · ${target.shortId} -> ${target.runId}`);
|
|
110
|
+
}
|
|
111
|
+
export function checkReadonlyEnvCompleteness(config) {
|
|
112
|
+
const source = config.source === 'env' ? 'process env' : config.configPath ?? 'bot env file';
|
|
113
|
+
const roleProbe = config.preflightChatId ? `chat probe configured (${config.preflightChatId})` : 'chat probe not configured';
|
|
114
|
+
return ok('env completeness', `mode=${config.mode} · bot=${config.botId} · source=${source} · dataDir=${config.dataDir} · ${roleProbe}`);
|
|
115
|
+
}
|
|
116
|
+
export async function runReadonlyPreflight(input = process.env, deps = {}) {
|
|
117
|
+
const config = loadReadonlyPreflightConfig(input);
|
|
118
|
+
const client = (deps.createClient ?? createReadonlyPreflightClient)(config);
|
|
119
|
+
const envCheck = checkReadonlyEnvCompleteness(config);
|
|
120
|
+
const botCheck = await checkBotIdentityReadable(client);
|
|
121
|
+
const probeOpenId = botCheck.status === 'ok'
|
|
122
|
+
? botCheck.detail.match(/open_id=([^\s]+)/)?.[1] ?? 'readonly-preflight-open-id'
|
|
123
|
+
: 'readonly-preflight-open-id';
|
|
124
|
+
const roleCheck = await checkRoleApiReadable(client, config.preflightChatId, probeOpenId);
|
|
125
|
+
const shortIdCheck = checkShortIdParseability();
|
|
126
|
+
return {
|
|
127
|
+
mode: config.mode,
|
|
128
|
+
botId: config.botId,
|
|
129
|
+
checks: [envCheck, botCheck, roleCheck, shortIdCheck],
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function emoji(status) {
|
|
133
|
+
return status === 'ok' ? '✅' : status === 'warn' ? '⚠️' : '❌';
|
|
134
|
+
}
|
|
135
|
+
function overallStatus(checks) {
|
|
136
|
+
if (checks.some((check) => check.status === 'error'))
|
|
137
|
+
return 'error';
|
|
138
|
+
if (checks.some((check) => check.status === 'warn'))
|
|
139
|
+
return 'warn';
|
|
140
|
+
return 'ok';
|
|
141
|
+
}
|
|
142
|
+
export function formatReadonlyPreflightReport(report) {
|
|
143
|
+
const overall = overallStatus(report.checks);
|
|
144
|
+
const header = `${emoji(overall)} W13 readonly preflight (${report.mode}) · bot=${report.botId}`;
|
|
145
|
+
const body = report.checks.map((check) => `${emoji(check.status)} ${check.label}: ${check.detail}`);
|
|
146
|
+
return [header, ...body].join('\n');
|
|
147
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { formatReadonlyPreflightReport, runReadonlyPreflight } from './preflight-env.js';
|
|
2
|
+
async function main() {
|
|
3
|
+
const report = await runReadonlyPreflight(process.env);
|
|
4
|
+
console.log(formatReadonlyPreflightReport(report));
|
|
5
|
+
const hasError = report.checks.some((check) => check.status === 'error');
|
|
6
|
+
process.exit(hasError ? 1 : 0);
|
|
7
|
+
}
|
|
8
|
+
void main().catch((error) => {
|
|
9
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
10
|
+
console.error(`❌ W13 readonly preflight failed before checks: ${message}`);
|
|
11
|
+
process.exit(1);
|
|
12
|
+
});
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import pino from 'pino';
|
|
3
|
+
import { adminAlertsPath } from '../../../../packages/core/src/paths.js';
|
|
4
|
+
import { appendNdjsonLine, listNdjsonSegments, readNdjsonSegments } from '../../../../packages/core/src/util/ndjson-rotation.js';
|
|
5
|
+
const logger = pino({ level: process.env['LOG_LEVEL'] ?? 'info' });
|
|
6
|
+
const SEVERITY_EMOJI = {
|
|
7
|
+
warn: '⚠️',
|
|
8
|
+
error: '⛔',
|
|
9
|
+
fatal: '🔥',
|
|
10
|
+
};
|
|
11
|
+
const OPEN_ID_PATTERN = /^ou_[A-Za-z0-9_-]+$/;
|
|
12
|
+
// Lark chat_id 形态: oc_ + 数字小写字母加下划线 / 中划线 (例 oc_a1b2c3_xxx).
|
|
13
|
+
// 旧的 /^oc_[a-zA-Z0-9]+$/ 不含 "_" 把"oc_cluster_1" 这类合法 id 判否, M13-C 修掉.
|
|
14
|
+
const CHAT_ID_PATTERN = /^oc_[a-zA-Z0-9_-]+$/;
|
|
15
|
+
/**
|
|
16
|
+
* M13-C (2026-08-04 owner-authorized): owner DM 兜底通道。
|
|
17
|
+
* 优先用 `WB_OWNER_OPEN_ID` (ou_*) DM 到 owner,失败 → 原 `WB_ADMIN_THREAD_ID`
|
|
18
|
+
* 群回退,仍失败 → 落 admin-alerts.ndjson。失败不抛 — 告警通道不能反过来砸主流程。
|
|
19
|
+
*/
|
|
20
|
+
export async function sendAdminAlert(sink, dataDir, message, severity = 'error') {
|
|
21
|
+
const ownerOpenId = (process.env['WB_OWNER_OPEN_ID'] ?? '').trim();
|
|
22
|
+
const threadId = (process.env['WB_ADMIN_THREAD_ID'] ?? '').trim();
|
|
23
|
+
const emoji = SEVERITY_EMOJI[severity];
|
|
24
|
+
const fullMessage = `${emoji} [wb-bot] ${message}`;
|
|
25
|
+
if (sink?.sendDm && ownerOpenId && OPEN_ID_PATTERN.test(ownerOpenId)) {
|
|
26
|
+
try {
|
|
27
|
+
await sink.sendDm(ownerOpenId, fullMessage);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
catch (err) {
|
|
31
|
+
logger.warn({ err, ownerOpenId, message }, 'admin alert DM to owner failed, falling back to cluster channel');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (sink && threadId && CHAT_ID_PATTERN.test(threadId)) {
|
|
35
|
+
try {
|
|
36
|
+
await sink.sendText(threadId, fullMessage);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
catch (textErr) {
|
|
40
|
+
// M13-H A3: sendText 失败时改走 sendCard 同 chatId (rich card 也能在 group 里
|
|
41
|
+
// 呈现,不会因为 text pipe 坏掉就完全静默).
|
|
42
|
+
if (sink.sendCard) {
|
|
43
|
+
try {
|
|
44
|
+
await sink.sendCard(threadId, {
|
|
45
|
+
schema: '2.0',
|
|
46
|
+
config: { wide_screen_mode: true },
|
|
47
|
+
header: { title: { tag: 'plain_text', content: emoji + ' Admin alert' } },
|
|
48
|
+
body: { elements: [{ tag: 'markdown', content: fullMessage }] },
|
|
49
|
+
});
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
catch (cardErr) {
|
|
53
|
+
logger.error({ textErr, cardErr, threadId, message }, 'admin alert cluster channel failed both text and card');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
logger.error({ err: textErr, threadId, message }, 'admin alert feishu send failed, falling back to file');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
appendAlertToFile(dataDir, fullMessage, severity);
|
|
62
|
+
}
|
|
63
|
+
function emitLastResortAlert(message, severity, err) {
|
|
64
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
65
|
+
const line = `[wb-bot][admin-alert][last-resort][${severity}] ${message} :: ${detail}\n`;
|
|
66
|
+
try {
|
|
67
|
+
process.stderr.write(line);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
// stderr itself may be unavailable; keep fail-open
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function appendAlertToFile(dataDir, message, severity) {
|
|
74
|
+
try {
|
|
75
|
+
const alertFile = adminAlertsPath(dataDir);
|
|
76
|
+
const entry = JSON.stringify({ ts: new Date().toISOString(), severity, message });
|
|
77
|
+
appendNdjsonLine(alertFile, entry);
|
|
78
|
+
}
|
|
79
|
+
catch (err) {
|
|
80
|
+
logger.error({ err, message }, 'admin alert file write failed');
|
|
81
|
+
emitLastResortAlert(message, severity, err);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export function getPendingAlertCount(dataDir) {
|
|
85
|
+
try {
|
|
86
|
+
const alertFile = adminAlertsPath(dataDir);
|
|
87
|
+
if (!existsSync(alertFile) && listNdjsonSegments(alertFile).length === 0)
|
|
88
|
+
return 0;
|
|
89
|
+
return readNdjsonSegments(alertFile).length;
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
}
|