@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,72 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
export function captainStopAll(opts) {
|
|
4
|
+
const now = String((opts.nowFn ?? Date.now)());
|
|
5
|
+
const sent = [];
|
|
6
|
+
const failed = [];
|
|
7
|
+
for (const bot of opts.bots) {
|
|
8
|
+
const inflightCards = safeListInflightCards(opts.store, bot.botId);
|
|
9
|
+
for (const card of inflightCards) {
|
|
10
|
+
if (!card.runId)
|
|
11
|
+
continue;
|
|
12
|
+
const runDir = join(opts.dataDir, 'runs', bot.botId, card.runId);
|
|
13
|
+
const statusValue = safeReadFile(join(runDir, 'status'));
|
|
14
|
+
if (statusValue !== 'running')
|
|
15
|
+
continue;
|
|
16
|
+
try {
|
|
17
|
+
writeFileSync(join(runDir, 'stop.signal'), now);
|
|
18
|
+
sent.push({
|
|
19
|
+
botId: bot.botId,
|
|
20
|
+
runId: card.runId,
|
|
21
|
+
runIdShort: card.runId.slice(0, 12),
|
|
22
|
+
agentId: card.agentId ?? '(no agent)',
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
27
|
+
failed.push({ botId: bot.botId, runId: card.runId, reason });
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return { sent, failed };
|
|
32
|
+
}
|
|
33
|
+
export function renderCaptainStopAllCard(result) {
|
|
34
|
+
if (result.sent.length === 0 && result.failed.length === 0) {
|
|
35
|
+
return '✅ 当前没有 active run';
|
|
36
|
+
}
|
|
37
|
+
const lines = ['```'];
|
|
38
|
+
lines.push(`✅ 已向 ${result.sent.length} 个 active run 发送 stop 信号`);
|
|
39
|
+
lines.push('─────────────────────────────────────');
|
|
40
|
+
for (const item of result.sent) {
|
|
41
|
+
lines.push(`- ${item.botId} / ${item.runIdShort} : signal sent`);
|
|
42
|
+
}
|
|
43
|
+
if (result.failed.length > 0) {
|
|
44
|
+
lines.push('─────────────────────────────────────');
|
|
45
|
+
lines.push(`⚠️ ${result.failed.length} 个失败:`);
|
|
46
|
+
for (const item of result.failed) {
|
|
47
|
+
lines.push(`- ${item.botId} / ${item.runId.slice(0, 12)} : ${item.reason}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
lines.push('─────────────────────────────────────');
|
|
51
|
+
lines.push('signal 仅触发 graceful stop, 实际收敛是异步:');
|
|
52
|
+
lines.push('各 bot 的 wb-runner 读到 stop.signal 后会跑完手头的 tool,');
|
|
53
|
+
lines.push('完成后各自卡片更新为 "stopped". 用 /status 跟踪收敛进度.');
|
|
54
|
+
lines.push('```');
|
|
55
|
+
return lines.join('\n');
|
|
56
|
+
}
|
|
57
|
+
function safeListInflightCards(store, botId) {
|
|
58
|
+
try {
|
|
59
|
+
return store.listInflightCards(botId);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function safeReadFile(path) {
|
|
66
|
+
try {
|
|
67
|
+
return existsSync(path) ? readFileSync(path, 'utf8').trim() : null;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export function renderListBotsCard(bots, captainBotId, now) {
|
|
2
|
+
if (bots.length === 0) {
|
|
3
|
+
return ['```', '📋 已配置 bot', '─────────────────────────────────────', '(无)', '─────────────────────────────────────', '```'].join('\n');
|
|
4
|
+
}
|
|
5
|
+
const nowMs = now ?? Date.now();
|
|
6
|
+
const sorted = [...bots].sort((left, right) => {
|
|
7
|
+
if (left.botId === captainBotId)
|
|
8
|
+
return -1;
|
|
9
|
+
if (right.botId === captainBotId)
|
|
10
|
+
return 1;
|
|
11
|
+
return left.botId.localeCompare(right.botId);
|
|
12
|
+
});
|
|
13
|
+
const lines = ['```', '📋 已配置 bot', '─────────────────────────────────────'];
|
|
14
|
+
const width = Math.max(...sorted.map((bot) => (bot.botId === captainBotId ? `${bot.botId} (Captain)` : bot.botId).length), 10);
|
|
15
|
+
for (const bot of sorted) {
|
|
16
|
+
const isCaptain = bot.botId === captainBotId;
|
|
17
|
+
const name = isCaptain ? `${bot.botId} (Captain)` : bot.botId;
|
|
18
|
+
const namePadded = name.padEnd(width);
|
|
19
|
+
const agents = bot.agentAllowed && bot.agentAllowed.length > 0
|
|
20
|
+
? `agents=[${bot.agentAllowed.join(', ')}]`
|
|
21
|
+
: 'agents=[(unknown)]';
|
|
22
|
+
let status = '离线 ✗ (无 heartbeat)';
|
|
23
|
+
if (bot.online) {
|
|
24
|
+
status = '在线 ✓';
|
|
25
|
+
}
|
|
26
|
+
else if (bot.lastHeartbeatAt !== null) {
|
|
27
|
+
const ageSec = Math.floor((nowMs - bot.lastHeartbeatAt) / 1000);
|
|
28
|
+
const ageDisplay = ageSec < 60
|
|
29
|
+
? `${ageSec}s`
|
|
30
|
+
: ageSec < 3600
|
|
31
|
+
? `${Math.floor(ageSec / 60)}min`
|
|
32
|
+
: `${Math.floor(ageSec / 3600)}h`;
|
|
33
|
+
status = `离线 ✗ (${ageDisplay} 前)`;
|
|
34
|
+
}
|
|
35
|
+
lines.push(`${namePadded} · ${agents} · ${status}`);
|
|
36
|
+
}
|
|
37
|
+
lines.push('─────────────────────────────────────', '```');
|
|
38
|
+
return lines.join('\n');
|
|
39
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import * as Lark from '@larksuiteoapi/node-sdk';
|
|
4
|
+
import Database from 'better-sqlite3';
|
|
5
|
+
import { resolveDataDir } from '../../../../packages/core/src/paths.js';
|
|
6
|
+
import { commandExists, splitCommand } from '../agent-registry.js';
|
|
7
|
+
import { loadBotEnvFromFile } from '../config/bot-env.js';
|
|
8
|
+
import { botEnvPath } from '../config/config-paths.js';
|
|
9
|
+
import { createLarkBotIdentityFetcher } from '../feishu/bot-identity.js';
|
|
10
|
+
import { CWD_DENYLIST, validateCwd } from '../security/cwd-guard.js';
|
|
11
|
+
import { FEISHU_SETUP_CHECKLIST } from './setup-checklist.js';
|
|
12
|
+
const MIN_NODE_MAJOR = 22;
|
|
13
|
+
const IDENTITY_TIMEOUT_MS = 15_000;
|
|
14
|
+
function withTimeout(promise, ms) {
|
|
15
|
+
let timer;
|
|
16
|
+
const timeout = new Promise((_, reject) => {
|
|
17
|
+
timer = setTimeout(() => reject(new Error(`${ms / 1000}s 内没有响应 (网络或飞书开放平台不可达)`)), ms);
|
|
18
|
+
});
|
|
19
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
|
20
|
+
}
|
|
21
|
+
const AGENT_COMMANDS = {
|
|
22
|
+
'claude-code': (config) => config.claudeCommand,
|
|
23
|
+
codex: (config) => config.codexCommand,
|
|
24
|
+
};
|
|
25
|
+
function errorMessage(error) {
|
|
26
|
+
return error instanceof Error ? error.message : String(error);
|
|
27
|
+
}
|
|
28
|
+
function checkDataDir(dataDir, openSqlite) {
|
|
29
|
+
try {
|
|
30
|
+
mkdirSync(dataDir, { recursive: true });
|
|
31
|
+
const probe = join(dataDir, `.doctor-${process.pid}`);
|
|
32
|
+
writeFileSync(probe, 'ok');
|
|
33
|
+
rmSync(probe, { force: true });
|
|
34
|
+
openSqlite();
|
|
35
|
+
return { name: '数据目录', status: 'ok', detail: `${dataDir} 可写, better-sqlite3 可用` };
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
return { name: '数据目录', status: 'error', detail: `${dataDir}: ${errorMessage(error)}` };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function checkAgents(config, exists) {
|
|
42
|
+
const results = config.agentAllowed.filter((agent) => AGENT_COMMANDS[agent]).map((agent) => {
|
|
43
|
+
const command = AGENT_COMMANDS[agent](config);
|
|
44
|
+
const ok = exists(splitCommand(command).head);
|
|
45
|
+
return { name: `agent ${agent}`, status: ok ? 'ok' : 'warn', detail: ok ? `\`${command}\` 可用` : `\`${command}\` 不在 PATH 上` };
|
|
46
|
+
});
|
|
47
|
+
if (results.length > 0 && results.every((result) => result.status !== 'ok')) {
|
|
48
|
+
results.push({ name: 'agent', status: 'error', detail: '没有一个可用的 agent 命令, bot 收到消息只会回错误卡' });
|
|
49
|
+
}
|
|
50
|
+
return results;
|
|
51
|
+
}
|
|
52
|
+
export async function runDoctorChecks(botId, deps) {
|
|
53
|
+
const results = [];
|
|
54
|
+
const major = Number.parseInt(deps.nodeVersion.replace(/^v/, ''), 10);
|
|
55
|
+
results.push(major >= MIN_NODE_MAJOR
|
|
56
|
+
? { name: 'Node', status: 'ok', detail: deps.nodeVersion }
|
|
57
|
+
: { name: 'Node', status: 'error', detail: `${deps.nodeVersion}, 需要 ${MIN_NODE_MAJOR}+` });
|
|
58
|
+
const configPath = botEnvPath(deps.configDir, botId);
|
|
59
|
+
let config;
|
|
60
|
+
try {
|
|
61
|
+
config = loadBotEnvFromFile(configPath);
|
|
62
|
+
results.push({ name: '配置文件', status: 'ok', detail: configPath });
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
results.push({ name: '配置文件', status: 'error', detail: `${errorMessage(error)} (可以用 wb-bot init --bot ${botId} 生成)` });
|
|
66
|
+
}
|
|
67
|
+
if (config) {
|
|
68
|
+
try {
|
|
69
|
+
const identity = await deps.fetchBotIdentity(config.larkAppId, config.larkAppSecret);
|
|
70
|
+
results.push({ name: '飞书凭证', status: 'ok', detail: `应用「${identity.appName ?? '?'}」, bot open_id ${identity.openId}` });
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
results.push({ name: '飞书凭证', status: 'error', detail: `取 bot 信息失败: ${errorMessage(error)} (检查 App ID / Secret, 以及是否开启了机器人能力)` });
|
|
74
|
+
}
|
|
75
|
+
results.push(...checkAgents(config, deps.commandExists));
|
|
76
|
+
if (config.defaultCwd) {
|
|
77
|
+
const cwd = validateCwd(config.defaultCwd, [config.defaultCwd], CWD_DENYLIST);
|
|
78
|
+
results.push(cwd.ok
|
|
79
|
+
? { name: '默认工作目录', status: 'ok', detail: cwd.path }
|
|
80
|
+
: { name: '默认工作目录', status: 'error', detail: `${config.defaultCwd}: ${cwd.reason}` });
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
results.push({ name: '默认工作目录', status: 'warn', detail: '未设置 WB_DEFAULT_CWD, 会退回 bot 启动目录' });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
results.push(checkDataDir(deps.dataDir, deps.openSqlite));
|
|
87
|
+
return results;
|
|
88
|
+
}
|
|
89
|
+
const ICON = { ok: '✅', warn: '⚠️', error: '❌' };
|
|
90
|
+
export function renderDoctorReport(results) {
|
|
91
|
+
return results.map((result) => `${ICON[result.status]} ${result.name}: ${result.detail}`).join('\n');
|
|
92
|
+
}
|
|
93
|
+
export async function runDoctorCommand(botId, configDir) {
|
|
94
|
+
const results = await runDoctorChecks(botId, {
|
|
95
|
+
nodeVersion: process.version,
|
|
96
|
+
configDir,
|
|
97
|
+
dataDir: resolveDataDir(),
|
|
98
|
+
commandExists,
|
|
99
|
+
fetchBotIdentity: (appId, appSecret) => withTimeout(createLarkBotIdentityFetcher(new Lark.Client({ appId, appSecret, loggerLevel: Lark.LoggerLevel.error })).fetch(), IDENTITY_TIMEOUT_MS),
|
|
100
|
+
openSqlite: () => new Database(':memory:').close(),
|
|
101
|
+
});
|
|
102
|
+
console.log(renderDoctorReport(results));
|
|
103
|
+
console.log(`\n${FEISHU_SETUP_CHECKLIST}`);
|
|
104
|
+
return results.some((result) => result.status === 'error') ? 1 : 0;
|
|
105
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { Writable } from 'node:stream';
|
|
4
|
+
import { createInterface } from 'node:readline/promises';
|
|
5
|
+
import { commandExists, splitCommand } from '../agent-registry.js';
|
|
6
|
+
import { botEnvPath } from '../config/config-paths.js';
|
|
7
|
+
import { CWD_DENYLIST, validateCwd } from '../security/cwd-guard.js';
|
|
8
|
+
import { validateBotId } from '../security/bot-id-validator.js';
|
|
9
|
+
import { FEISHU_SETUP_CHECKLIST } from './setup-checklist.js';
|
|
10
|
+
const MAX_ATTEMPTS = 3;
|
|
11
|
+
function formatEnvValue(value) {
|
|
12
|
+
return /[\s#"'=]/.test(value) ? JSON.stringify(value) : value;
|
|
13
|
+
}
|
|
14
|
+
/** 生成 ~/.weaverbird/configs/.env.<botId>; 字段与 config/bot-env.ts 的 BotConfigSchema 对应. */
|
|
15
|
+
export function renderBotEnv(answers) {
|
|
16
|
+
const lines = [
|
|
17
|
+
'# Generated by `wb-bot init`. Start with: wb-bot --bot ' + answers.botId,
|
|
18
|
+
`BOT_ID=${answers.botId}`,
|
|
19
|
+
`LARK_APP_ID=${formatEnvValue(answers.appId)}`,
|
|
20
|
+
`LARK_APP_SECRET=${formatEnvValue(answers.appSecret)}`,
|
|
21
|
+
`AGENT_ALLOWED=${answers.agentAllowed.join(',')}`,
|
|
22
|
+
`WB_DEFAULT_CWD=${formatEnvValue(answers.defaultCwd)}`,
|
|
23
|
+
`WB_CLAUDE_COMMAND=${formatEnvValue(answers.claudeCommand)}`,
|
|
24
|
+
`WB_CODEX_COMMAND=${formatEnvValue(answers.codexCommand)}`,
|
|
25
|
+
];
|
|
26
|
+
return `${lines.join('\n')}\n`;
|
|
27
|
+
}
|
|
28
|
+
async function askValid(prompter, question, check, opts = {}, print) {
|
|
29
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
30
|
+
const value = (await prompter.ask(question, opts)).trim();
|
|
31
|
+
const problem = check(value);
|
|
32
|
+
if (!problem)
|
|
33
|
+
return value;
|
|
34
|
+
print(` ✗ ${problem}`);
|
|
35
|
+
}
|
|
36
|
+
throw new Error(`${question}: ${MAX_ATTEMPTS} 次输入都无效, 已放弃`);
|
|
37
|
+
}
|
|
38
|
+
function checkCwd(value) {
|
|
39
|
+
if (!value)
|
|
40
|
+
return '不能为空';
|
|
41
|
+
const result = validateCwd(value, [value], CWD_DENYLIST);
|
|
42
|
+
return result.ok ? null : `不能用作工作目录: ${result.reason}`;
|
|
43
|
+
}
|
|
44
|
+
/** 返回进程退出码. */
|
|
45
|
+
export async function runInit(opts, deps) {
|
|
46
|
+
const { prompter, print } = deps;
|
|
47
|
+
try {
|
|
48
|
+
print('生成 wb-bot 配置. 回车使用方括号里的默认值.\n');
|
|
49
|
+
const botId = await askValid(prompter, 'bot id', (v) => validateBotId(v).reason ?? null, { defaultValue: opts.botId ?? 'default' }, print);
|
|
50
|
+
const target = botEnvPath(deps.configDir, botId);
|
|
51
|
+
if (existsSync(target) && !opts.force) {
|
|
52
|
+
print(`${target} 已存在; 要覆盖请加 --force.`);
|
|
53
|
+
return 1;
|
|
54
|
+
}
|
|
55
|
+
const appId = await askValid(prompter, '飞书 App ID (cli_ 开头)', (v) => (v.startsWith('cli_') ? null : '应以 cli_ 开头'), {}, print);
|
|
56
|
+
const appSecret = await askValid(prompter, '飞书 App Secret (输入不回显)', (v) => (v ? null : '不能为空'), { secret: true }, print);
|
|
57
|
+
const defaultCwd = await askValid(prompter, 'agent 默认工作目录', checkCwd, { defaultValue: process.cwd() }, print);
|
|
58
|
+
const claudeCommand = await askValid(prompter, 'claude 命令', (v) => (v ? null : '不能为空'), { defaultValue: 'claude' }, print);
|
|
59
|
+
const codexCommand = await askValid(prompter, 'codex 命令', (v) => (v ? null : '不能为空'), { defaultValue: 'codex' }, print);
|
|
60
|
+
const found = {
|
|
61
|
+
'claude-code': deps.commandExists(splitCommand(claudeCommand).head),
|
|
62
|
+
codex: deps.commandExists(splitCommand(codexCommand).head),
|
|
63
|
+
};
|
|
64
|
+
for (const [agent, ok] of Object.entries(found)) {
|
|
65
|
+
print(` ${ok ? '✅' : '⚠️'} ${agent}: ${ok ? '命令可用' : '没有在 PATH 上找到, 装好之前这个 agent 不可用'}`);
|
|
66
|
+
}
|
|
67
|
+
const available = Object.entries(found).filter(([, ok]) => ok).map(([agent]) => agent);
|
|
68
|
+
const agentAllowed = available.length > 0 ? available : ['claude-code', 'codex'];
|
|
69
|
+
mkdirSync(deps.configDir, { recursive: true, mode: 0o700 });
|
|
70
|
+
writeFileSync(target, renderBotEnv({ botId, appId, appSecret, defaultCwd, claudeCommand, codexCommand, agentAllowed }), { mode: 0o600 });
|
|
71
|
+
chmodSync(target, 0o600);
|
|
72
|
+
print(`\n已写入 ${target.replace(homedir(), '~')} (权限 600).\n`);
|
|
73
|
+
print(FEISHU_SETUP_CHECKLIST);
|
|
74
|
+
print(`\n下一步:\n wb-bot doctor --bot ${botId}\n wb-bot --bot ${botId}`);
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
print(error instanceof Error ? error.message : String(error));
|
|
79
|
+
return 1;
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
prompter.close();
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** 终端问答; secret 输入时静音回显. */
|
|
86
|
+
export function createTerminalPrompter() {
|
|
87
|
+
let muted = false;
|
|
88
|
+
const output = new Writable({
|
|
89
|
+
write(chunk, encoding, callback) {
|
|
90
|
+
if (!muted)
|
|
91
|
+
process.stdout.write(chunk, encoding);
|
|
92
|
+
callback();
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
const rl = createInterface({ input: process.stdin, output, terminal: true });
|
|
96
|
+
return {
|
|
97
|
+
async ask(question, opts = {}) {
|
|
98
|
+
process.stdout.write(`${question}${opts.defaultValue ? ` [${opts.defaultValue}]` : ''}: `);
|
|
99
|
+
muted = opts.secret === true;
|
|
100
|
+
const answer = await rl.question('');
|
|
101
|
+
if (muted)
|
|
102
|
+
process.stdout.write('\n');
|
|
103
|
+
muted = false;
|
|
104
|
+
return answer.trim() || opts.defaultValue || '';
|
|
105
|
+
},
|
|
106
|
+
close() {
|
|
107
|
+
rl.close();
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
export async function runInitCommand(opts, configDir) {
|
|
112
|
+
if (process.stdin.isTTY !== true) {
|
|
113
|
+
console.error('wb-bot init 需要在交互式终端里运行.');
|
|
114
|
+
return 1;
|
|
115
|
+
}
|
|
116
|
+
return runInit(opts, {
|
|
117
|
+
prompter: createTerminalPrompter(),
|
|
118
|
+
configDir,
|
|
119
|
+
commandExists,
|
|
120
|
+
print: (line) => console.log(line),
|
|
121
|
+
});
|
|
122
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const COMMANDS = ['init', 'doctor'];
|
|
2
|
+
export const USAGE = [
|
|
3
|
+
'Usage:',
|
|
4
|
+
' wb-bot [--bot <botId>] 启动 bot (--bot 读取 ~/.weaverbird/configs/.env.<botId>)',
|
|
5
|
+
' wb-bot init [--bot <botId>] [--force] 交互式生成上面的配置文件',
|
|
6
|
+
' wb-bot doctor [--bot <botId>] 检查配置、飞书凭证、agent 命令和数据目录',
|
|
7
|
+
].join('\n');
|
|
8
|
+
export function parseArgs(argv) {
|
|
9
|
+
const out = {};
|
|
10
|
+
if (argv[0] && COMMANDS.includes(argv[0]))
|
|
11
|
+
out.command = argv[0];
|
|
12
|
+
for (let i = out.command ? 1 : 0; i < argv.length; i++) {
|
|
13
|
+
const a = argv[i];
|
|
14
|
+
if (a === '--help' || a === '-h') {
|
|
15
|
+
out.help = true;
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (a === '--force') {
|
|
19
|
+
out.force = true;
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
if (a === '--bot') {
|
|
23
|
+
const v = argv[++i];
|
|
24
|
+
if (!v || v.startsWith('-'))
|
|
25
|
+
throw new Error('--bot requires a value');
|
|
26
|
+
out.botId = v;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return out;
|
|
31
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** 单 bot 模式下进程环境里一个飞书凭证都没有: 多半是 npm 全局安装后还没生成配置. */
|
|
2
|
+
export const MISSING_CREDENTIALS_HINT = [
|
|
3
|
+
'没有找到飞书凭证 (LARK_APP_ID / LARK_APP_SECRET).',
|
|
4
|
+
'先运行 `wb-bot init` 生成配置, 再用 `wb-bot --bot <id>` 启动;',
|
|
5
|
+
'从源码仓库运行时也可以把凭证写进 apps/wb-bot/.env.',
|
|
6
|
+
].join('\n');
|
|
7
|
+
export function lacksLarkCredentials(env) {
|
|
8
|
+
return !env['LARK_APP_ID']?.trim() && !env['LARK_APP_SECRET']?.trim();
|
|
9
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** 飞书开放平台上必须手工完成的配置; 接口查不到, init / doctor 只能列出来让人核对. 与 apps/wb-bot/README.md 的权限表一致. */
|
|
2
|
+
export const FEISHU_SETUP_CHECKLIST = [
|
|
3
|
+
'飞书开放平台 (open.feishu.cn) 上需要确认:',
|
|
4
|
+
' - 已开启「机器人」能力',
|
|
5
|
+
' - 权限: im:message、im:message.group_at_msg、im:resource',
|
|
6
|
+
' - 事件订阅方式: 使用长连接接收事件',
|
|
7
|
+
' - 事件: im.message.receive_v1 (接收消息)、card.action.trigger (卡片回调)',
|
|
8
|
+
' - 改完权限 / 事件后发布一个新版本',
|
|
9
|
+
' 可选能力 (流式卡片、话题回复、撤回、云文档评论) 的权限见 apps/wb-bot/README.md.',
|
|
10
|
+
].join('\n');
|