@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,312 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { parseArgs } from 'node:util';
|
|
4
|
+
import { createDefaultAgentRegistry } from '../../../packages/core/src/index.js';
|
|
5
|
+
import { logsCommand } from './commands/logs.js';
|
|
6
|
+
import { runsCommand } from './commands/runs.js';
|
|
7
|
+
import { debugCommand } from './commands/debug.js';
|
|
8
|
+
import { historyCommand } from './commands/history.js';
|
|
9
|
+
import { statusCommand } from './commands/status.js';
|
|
10
|
+
import { captainCommand } from './commands/captain.js';
|
|
11
|
+
import { attachCommand } from './commands/attach.js';
|
|
12
|
+
import { resumeInheritCommand } from './commands/resume.js';
|
|
13
|
+
import { listCommand } from './commands/list.js';
|
|
14
|
+
import { auditCommand } from './commands/audit.js';
|
|
15
|
+
import { approvalCommand } from './commands/approval.js';
|
|
16
|
+
import { watchCommand } from './commands/watch.js';
|
|
17
|
+
import { COMMAND_CATALOG } from '../../../packages/core/src/captain/index.js';
|
|
18
|
+
import { isEntryModule } from '../../../packages/core/src/util/entry-module.js';
|
|
19
|
+
// M12-B (2026-08-04 owner-authorized): wb-cli 的命令面应该来自 COMMAND_CATALOG
|
|
20
|
+
// 单源 (bot/cli/both 三态)。resolveCommand 当 catalog 条目可见时直接通道;
|
|
21
|
+
// run / debug / list-agents 是 non-catalog 特例 (不属于 catalog 维度) 走原路径。
|
|
22
|
+
const CLI_CATALOG_KEYS = Object.keys(COMMAND_CATALOG).filter((name) => COMMAND_CATALOG[name]?.cli_visible);
|
|
23
|
+
function catalogLookup(command) {
|
|
24
|
+
if (CLI_CATALOG_KEYS.includes(command))
|
|
25
|
+
return COMMAND_CATALOG[command] ?? null;
|
|
26
|
+
for (const [name, entry] of Object.entries(COMMAND_CATALOG)) {
|
|
27
|
+
if (name === 'resume-im' || name === 'pause-im' || name === 'cancel-im')
|
|
28
|
+
continue;
|
|
29
|
+
if (entry.cli_visible && entry.aliases.some((alias) => alias === command || alias.startsWith(`${command} `))) {
|
|
30
|
+
return entry;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
function printHelp() {
|
|
36
|
+
const cliCommands = Object.entries(COMMAND_CATALOG)
|
|
37
|
+
.filter(([, entry]) => entry.cli_visible)
|
|
38
|
+
.map(([name, entry]) => ` ${name.padEnd(12)} ${entry.description}`)
|
|
39
|
+
.join('\n');
|
|
40
|
+
process.stdout.write(`Usage: wb-cli <command> [options]
|
|
41
|
+
|
|
42
|
+
Commands (catalog-driven):
|
|
43
|
+
${cliCommands}
|
|
44
|
+
run Run an agent with the given prompt
|
|
45
|
+
resume Resume from an inherited run: wb-cli resume --inherit <run_id>
|
|
46
|
+
--help, -h Show this help
|
|
47
|
+
--version Show CLI version
|
|
48
|
+
|
|
49
|
+
Options for 'run':
|
|
50
|
+
--agent <id> Agent id (default: claude-code)
|
|
51
|
+
--consent-level <l> Permission level (default: normal)
|
|
52
|
+
Values: plan-only, strict, normal, relaxed, auto
|
|
53
|
+
--resume <token> Resume previous session (token from prior [done] line)
|
|
54
|
+
--cwd <path> Working directory for agent (default: current dir)
|
|
55
|
+
--model <id> Model id (agent-specific, e.g. claude-sonnet-4-20250514)
|
|
56
|
+
|
|
57
|
+
Options for 'history':
|
|
58
|
+
--all-captains Aggregate view across captains
|
|
59
|
+
--json NDJSON per run
|
|
60
|
+
--keyword / --agent / --status / --after / --before / --limit / --cursor
|
|
61
|
+
|
|
62
|
+
Examples:
|
|
63
|
+
wb-cli run "explain this file"
|
|
64
|
+
wb-cli run --consent-level plan-only "review code in src/"
|
|
65
|
+
wb-cli resume --inherit run-abc123
|
|
66
|
+
wb-cli list --all-captains
|
|
67
|
+
wb-cli history --all-captains --limit 20
|
|
68
|
+
`);
|
|
69
|
+
}
|
|
70
|
+
function readVersion() {
|
|
71
|
+
// 源码运行时 package.json 在上三层; 编译后多一层 dist/.
|
|
72
|
+
const candidates = ['../../../package.json', '../../../../package.json'].map((rel) => new URL(rel, import.meta.url));
|
|
73
|
+
const pkgUrl = candidates.find((url) => existsSync(url)) ?? candidates[0];
|
|
74
|
+
const raw = readFileSync(pkgUrl, 'utf8');
|
|
75
|
+
const parsed = JSON.parse(raw);
|
|
76
|
+
return parsed.version ?? '0.0.0';
|
|
77
|
+
}
|
|
78
|
+
export function resolveCommand(argv) {
|
|
79
|
+
const command = argv[0];
|
|
80
|
+
if (!command || command === '--help' || command === '-h')
|
|
81
|
+
return '--help';
|
|
82
|
+
if (command === '--version')
|
|
83
|
+
return '--version';
|
|
84
|
+
if (command === 'run')
|
|
85
|
+
return 'run';
|
|
86
|
+
if (command === 'debug')
|
|
87
|
+
return 'debug';
|
|
88
|
+
// catalog-driven path: any cli_visible entry routes directly, no hard-coded switch.
|
|
89
|
+
if (catalogLookup(command) !== null)
|
|
90
|
+
return command;
|
|
91
|
+
return 'run';
|
|
92
|
+
}
|
|
93
|
+
export function resolveRunArgv(argv) {
|
|
94
|
+
return argv[0] === 'run' ? argv.slice(1) : argv;
|
|
95
|
+
}
|
|
96
|
+
function parseConsentLevel(value) {
|
|
97
|
+
if (value === 'plan-only' || value === 'strict' || value === 'normal' || value === 'relaxed' || value === 'auto') {
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
throw new Error(`invalid consent level: "${value ?? ''}"\nValid values: plan-only, strict, normal, relaxed, auto`);
|
|
101
|
+
}
|
|
102
|
+
function parseRunArgs(argv) {
|
|
103
|
+
const values = parseArgs({
|
|
104
|
+
args: argv,
|
|
105
|
+
allowPositionals: true,
|
|
106
|
+
options: {
|
|
107
|
+
agent: { type: 'string', default: 'claude-code' },
|
|
108
|
+
'consent-level': { type: 'string', default: 'normal' },
|
|
109
|
+
resume: { type: 'string' },
|
|
110
|
+
cwd: { type: 'string' },
|
|
111
|
+
model: { type: 'string' },
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
const prompt = values.positionals.join(' ').trim();
|
|
115
|
+
if (!prompt) {
|
|
116
|
+
throw new Error('prompt is required\nUsage: wb-cli run [options] <prompt>\nExample: wb-cli run "explain this file"');
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
prompt,
|
|
120
|
+
options: {
|
|
121
|
+
agent: values.values.agent,
|
|
122
|
+
consentLevel: parseConsentLevel(values.values['consent-level']),
|
|
123
|
+
resume: values.values.resume,
|
|
124
|
+
cwd: values.values.cwd,
|
|
125
|
+
model: values.values.model,
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function formatToolResult(event) {
|
|
130
|
+
const prefix = event.isError ? 'ERROR ' : '';
|
|
131
|
+
return `${prefix}${event.output.slice(0, 200)}`;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Per-agent unavailable hint (W2.5-Hotfix-batch-C P1-8).
|
|
135
|
+
*
|
|
136
|
+
* R2 review M3: wb-cli 的 unavailable 分支不区分 agent, 统一提示
|
|
137
|
+
* "Install claude CLI" — 用户跑 `--agent codex` 时这个提示是错误的, 影响工具可信度.
|
|
138
|
+
*
|
|
139
|
+
* 这里按 agent.id 给出对应的安装/验证指引. 新加 agent 时也需在此补一条.
|
|
140
|
+
*/
|
|
141
|
+
export function unavailableHint(agentId) {
|
|
142
|
+
if (agentId === 'claude-code') {
|
|
143
|
+
return [
|
|
144
|
+
'Install claude CLI: npm install -g @anthropic-ai/claude-code',
|
|
145
|
+
'Then verify: claude --version',
|
|
146
|
+
].join('\n');
|
|
147
|
+
}
|
|
148
|
+
if (agentId === 'codex') {
|
|
149
|
+
return [
|
|
150
|
+
'Install codex CLI: see https://github.com/openai/codex',
|
|
151
|
+
'Then verify: codex --version',
|
|
152
|
+
].join('\n');
|
|
153
|
+
}
|
|
154
|
+
return [
|
|
155
|
+
`No install hint registered for agent: ${agentId}`,
|
|
156
|
+
"Run 'wb-cli list-agents' to see registered agents and availability.",
|
|
157
|
+
].join('\n');
|
|
158
|
+
}
|
|
159
|
+
function writeMeta(event) {
|
|
160
|
+
if (event.type === 'system')
|
|
161
|
+
process.stderr.write(`[session] ${event.continuationToken ?? '-'}\n`);
|
|
162
|
+
else if (event.type === 'tool_use')
|
|
163
|
+
process.stderr.write(`[tool] ${event.name}\n`);
|
|
164
|
+
else if (event.type === 'tool_result')
|
|
165
|
+
process.stderr.write(`[tool result] ${formatToolResult(event)}\n`);
|
|
166
|
+
else if (event.type === 'usage')
|
|
167
|
+
process.stderr.write(`[usage] in=${event.inputTokens ?? '-'} out=${event.outputTokens ?? '-'} cost=$${event.costUsd ?? '-'}\n`);
|
|
168
|
+
else if (event.type === 'done')
|
|
169
|
+
process.stderr.write(`[done] ${event.continuationToken ?? '-'}\n`);
|
|
170
|
+
else if (event.type === 'error')
|
|
171
|
+
process.stderr.write(`[error] ${event.message}\n`);
|
|
172
|
+
}
|
|
173
|
+
async function runCommand(argv) {
|
|
174
|
+
const { options, prompt } = parseRunArgs(argv);
|
|
175
|
+
const registry = createDefaultAgentRegistry();
|
|
176
|
+
const adapter = registry.lookup(options.agent);
|
|
177
|
+
if (!adapter) {
|
|
178
|
+
const registered = registry.list().map((a) => a.id).join(', ') || '(none)';
|
|
179
|
+
process.stderr.write(`agent not registered: ${options.agent}\nRegistered agents: ${registered}\nRun 'wb-cli list-agents' to see availability.\n`);
|
|
180
|
+
return 1;
|
|
181
|
+
}
|
|
182
|
+
const available = await registry.isAvailable(options.agent);
|
|
183
|
+
if (!available) {
|
|
184
|
+
process.stderr.write(`agent not available: ${options.agent}\n${unavailableHint(options.agent)}\n`);
|
|
185
|
+
return 2;
|
|
186
|
+
}
|
|
187
|
+
const run = adapter.run({
|
|
188
|
+
prompt,
|
|
189
|
+
cwd: options.cwd ?? process.cwd(),
|
|
190
|
+
consentLevel: options.consentLevel,
|
|
191
|
+
continuationToken: options.resume,
|
|
192
|
+
model: options.model,
|
|
193
|
+
});
|
|
194
|
+
let exitCode = 0;
|
|
195
|
+
let interrupted = false;
|
|
196
|
+
const onSigint = () => {
|
|
197
|
+
interrupted = true;
|
|
198
|
+
void run.stop().then(() => run.waitForExit(2000)).finally(() => process.exit(130));
|
|
199
|
+
};
|
|
200
|
+
process.once('SIGINT', onSigint);
|
|
201
|
+
for await (const event of run.events) {
|
|
202
|
+
if (event.type === 'text' || event.type === 'thinking')
|
|
203
|
+
process.stdout.write(event.delta);
|
|
204
|
+
else
|
|
205
|
+
writeMeta(event);
|
|
206
|
+
if (event.type === 'error')
|
|
207
|
+
exitCode = 1;
|
|
208
|
+
if (event.type === 'done' || event.type === 'error')
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
process.removeListener('SIGINT', onSigint);
|
|
212
|
+
if (!interrupted)
|
|
213
|
+
await run.waitForExit(2000);
|
|
214
|
+
return exitCode;
|
|
215
|
+
}
|
|
216
|
+
async function listAgents() {
|
|
217
|
+
const registry = createDefaultAgentRegistry();
|
|
218
|
+
for (const agent of registry.list()) {
|
|
219
|
+
const available = await registry.isAvailable(agent.id);
|
|
220
|
+
process.stdout.write(`${agent.id}\t${agent.displayName}\t${available ? 'available' : 'unavailable'}\n`);
|
|
221
|
+
}
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* M12-B (2026-08-04 owner-authorized): catalog-driven dispatch. `resolveCommand`
|
|
226
|
+
* 命中一个 cli_visible 的 catalog 条目时由这张表执行;新增 catalog 条目不必改 main.ts,
|
|
227
|
+
* 只需在这里登记一个 handler (或先用 default handler 报 "not yet implemented")。
|
|
228
|
+
* 特例:`run` / `debug` / `--help` / `--version` 不是 catalog 条目,保留 hard-coded 分支。
|
|
229
|
+
*/
|
|
230
|
+
const CATALOG_HANDLERS = {
|
|
231
|
+
history: historyCommand,
|
|
232
|
+
status: () => statusCommand(),
|
|
233
|
+
captain: (argv) => captainCommand(argv),
|
|
234
|
+
attach: attachCommand,
|
|
235
|
+
resume: resumeInheritCommand,
|
|
236
|
+
list: listCommand,
|
|
237
|
+
'list-agents': listAgents,
|
|
238
|
+
help: () => { printHelp(); return 0; },
|
|
239
|
+
use: () => 2,
|
|
240
|
+
audit: auditCommand,
|
|
241
|
+
approval: approvalCommand,
|
|
242
|
+
watch: watchCommand,
|
|
243
|
+
logs: () => 2,
|
|
244
|
+
runs: () => runsCommand(),
|
|
245
|
+
'captain-use': () => 2,
|
|
246
|
+
};
|
|
247
|
+
async function dispatchCatalogCommand(command, argv) {
|
|
248
|
+
const handler = CATALOG_HANDLERS[command];
|
|
249
|
+
if (!handler) {
|
|
250
|
+
process.stderr.write(`wb-cli: catalog entry "${command}" not yet implemented (cli)\n`);
|
|
251
|
+
return 2;
|
|
252
|
+
}
|
|
253
|
+
return await handler(argv);
|
|
254
|
+
}
|
|
255
|
+
async function main() {
|
|
256
|
+
const argv = process.argv.slice(2);
|
|
257
|
+
const command = resolveCommand(argv);
|
|
258
|
+
if (command === '--help') {
|
|
259
|
+
printHelp();
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
if (command === '--version') {
|
|
263
|
+
process.stdout.write(`${readVersion()}\n`);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (command === 'logs') {
|
|
267
|
+
const logsArgv = argv.slice(1);
|
|
268
|
+
const follow = logsArgv.includes('-f') || logsArgv.includes('--follow');
|
|
269
|
+
let tail = 0;
|
|
270
|
+
const tailIdx = logsArgv.indexOf('--tail');
|
|
271
|
+
if (tailIdx >= 0 && logsArgv[tailIdx + 1])
|
|
272
|
+
tail = parseInt(logsArgv[tailIdx + 1], 10) || 0;
|
|
273
|
+
let runId;
|
|
274
|
+
const runIdIdx = logsArgv.indexOf('--run-id');
|
|
275
|
+
if (runIdIdx >= 0 && logsArgv[runIdIdx + 1])
|
|
276
|
+
runId = logsArgv[runIdIdx + 1];
|
|
277
|
+
const code = logsCommand({ follow, tail, runId });
|
|
278
|
+
if (!follow)
|
|
279
|
+
process.exit(code);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
if (command === 'debug') {
|
|
283
|
+
const parsed = debugCommand(argv.slice(1));
|
|
284
|
+
if (!parsed) {
|
|
285
|
+
process.stderr.write('Usage: wb-cli debug [agentId] -- <prompt>\n');
|
|
286
|
+
process.exit(1);
|
|
287
|
+
}
|
|
288
|
+
const code = await runCommand(['--agent', parsed.agentId, parsed.prompt]);
|
|
289
|
+
process.exit(code);
|
|
290
|
+
}
|
|
291
|
+
// catalog-driven path: any command that has been registered under COMMAND_CATALOG
|
|
292
|
+
// with cli_visible=true is routed here. Special argv order for `captain use <id>`
|
|
293
|
+
// hands straight to captainCommand.
|
|
294
|
+
if (command === 'captain' && argv[1] === 'use') {
|
|
295
|
+
process.exit(captainCommand(argv.slice(1)));
|
|
296
|
+
}
|
|
297
|
+
if (command === 'captain-use') {
|
|
298
|
+
process.exit(captainCommand(['use', ...argv.slice(1)]));
|
|
299
|
+
}
|
|
300
|
+
if (catalogLookup(command) !== null) {
|
|
301
|
+
process.exit(await dispatchCatalogCommand(command, argv.slice(1)));
|
|
302
|
+
}
|
|
303
|
+
const exitCode = command === 'list-agents' ? await listAgents() : await runCommand(resolveRunArgv(argv));
|
|
304
|
+
process.exit(exitCode);
|
|
305
|
+
}
|
|
306
|
+
const isEntry = isEntryModule(import.meta.url);
|
|
307
|
+
if (isEntry) {
|
|
308
|
+
void main().catch((error) => {
|
|
309
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
310
|
+
process.exit(1);
|
|
311
|
+
});
|
|
312
|
+
}
|
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { CLISubprocessAgent } from './cli-subprocess.js';
|
|
3
|
+
const CLAUDE_PASSTHROUGH_KEYS = [
|
|
4
|
+
'ANTHROPIC_API_KEY',
|
|
5
|
+
'ANTHROPIC_BASE_URL',
|
|
6
|
+
'ANTHROPIC_MODEL',
|
|
7
|
+
'CLAUDE_MD_PATH',
|
|
8
|
+
'CLAUDE_CONFIG_DIR',
|
|
9
|
+
'XDG_CONFIG_HOME',
|
|
10
|
+
'XDG_DATA_HOME',
|
|
11
|
+
'XDG_CACHE_HOME',
|
|
12
|
+
'PATH',
|
|
13
|
+
'HOME',
|
|
14
|
+
'USER',
|
|
15
|
+
'LOGNAME',
|
|
16
|
+
'SHELL',
|
|
17
|
+
'PWD',
|
|
18
|
+
'LANG',
|
|
19
|
+
'LC_ALL',
|
|
20
|
+
'TERM',
|
|
21
|
+
'TMPDIR',
|
|
22
|
+
'NO_COLOR',
|
|
23
|
+
'FORCE_COLOR',
|
|
24
|
+
'SSL_CERT_FILE',
|
|
25
|
+
'NODE_EXTRA_CA_CERTS',
|
|
26
|
+
];
|
|
27
|
+
const CAPABILITIES = {
|
|
28
|
+
type: 'cli',
|
|
29
|
+
input: { images: true, attachments: true },
|
|
30
|
+
output: { streaming: true, thinking: true, toolUse: true, citations: false },
|
|
31
|
+
context: { window: 200000, costClass: 'premium' },
|
|
32
|
+
skills: { code: 'A+', review: 'A', plan: 'A', research: 'A', ops: 'B' },
|
|
33
|
+
tools: {
|
|
34
|
+
builtin: ['Read', 'Write', 'Bash', 'Edit', 'Glob', 'Grep', 'Task', 'WebSearch'],
|
|
35
|
+
canExtend: true,
|
|
36
|
+
},
|
|
37
|
+
session: { resumable: true, tokenKind: 'opaque' },
|
|
38
|
+
tokenRotation: 'rotating',
|
|
39
|
+
};
|
|
40
|
+
function pickEnv(source, keys) {
|
|
41
|
+
const env = {};
|
|
42
|
+
for (const key of keys) {
|
|
43
|
+
const value = source[key];
|
|
44
|
+
if (value !== undefined)
|
|
45
|
+
env[key] = value;
|
|
46
|
+
}
|
|
47
|
+
return env;
|
|
48
|
+
}
|
|
49
|
+
function asRecord(value) {
|
|
50
|
+
return value !== null && typeof value === 'object' ? value : null;
|
|
51
|
+
}
|
|
52
|
+
function readString(value) {
|
|
53
|
+
return typeof value === 'string' ? value : undefined;
|
|
54
|
+
}
|
|
55
|
+
function readErrorMessage(payload) {
|
|
56
|
+
const error = asRecord(payload['error']);
|
|
57
|
+
return readString(error?.['message']) ?? readString(payload['result']) ?? 'claude run failed';
|
|
58
|
+
}
|
|
59
|
+
function inferRecoverable(code) {
|
|
60
|
+
return code === 'rate_limit' || code === 'network' || code === 'context_length';
|
|
61
|
+
}
|
|
62
|
+
function inferErrorCode(message) {
|
|
63
|
+
const text = message.toLowerCase();
|
|
64
|
+
if (text.includes('auth'))
|
|
65
|
+
return 'auth';
|
|
66
|
+
if (text.includes('rate limit'))
|
|
67
|
+
return 'rate_limit';
|
|
68
|
+
if (text.includes('context'))
|
|
69
|
+
return 'context_length';
|
|
70
|
+
if (text.includes('network'))
|
|
71
|
+
return 'network';
|
|
72
|
+
return 'crashed';
|
|
73
|
+
}
|
|
74
|
+
function stringifyToolResult(value) {
|
|
75
|
+
if (typeof value === 'string')
|
|
76
|
+
return value;
|
|
77
|
+
if (!Array.isArray(value))
|
|
78
|
+
return JSON.stringify(value ?? '');
|
|
79
|
+
return value
|
|
80
|
+
.map((item) => (typeof item === 'string' ? item : readString(asRecord(item)?.['text']) ?? JSON.stringify(item)))
|
|
81
|
+
.join('\n');
|
|
82
|
+
}
|
|
83
|
+
function extractSubagentId(event) {
|
|
84
|
+
if (event['isSidechain'] === true) {
|
|
85
|
+
const rawAgentId = readString(event['agentId']);
|
|
86
|
+
if (rawAgentId)
|
|
87
|
+
return rawAgentId;
|
|
88
|
+
}
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
function mapAssistantContent(item, subagentId) {
|
|
92
|
+
const type = readString(item['type']);
|
|
93
|
+
if (type === 'text')
|
|
94
|
+
return [{ type: 'text', delta: readString(item['text']) ?? '' }];
|
|
95
|
+
if (type === 'thinking')
|
|
96
|
+
return [{ type: 'thinking', delta: readString(item['thinking']) ?? '' }];
|
|
97
|
+
if (type === 'tool_use') {
|
|
98
|
+
const event = { type: 'tool_use', id: readString(item['id']) ?? '', name: readString(item['name']) ?? '', input: item['input'] };
|
|
99
|
+
if (subagentId)
|
|
100
|
+
event.subagentId = subagentId;
|
|
101
|
+
return [event];
|
|
102
|
+
}
|
|
103
|
+
return [];
|
|
104
|
+
}
|
|
105
|
+
function mapToolResult(item, subagentId) {
|
|
106
|
+
if (readString(item['type']) !== 'tool_result')
|
|
107
|
+
return [];
|
|
108
|
+
const event = {
|
|
109
|
+
type: 'tool_result',
|
|
110
|
+
id: readString(item['tool_use_id']) ?? '',
|
|
111
|
+
output: stringifyToolResult(item['content']),
|
|
112
|
+
isError: Boolean(item['is_error']),
|
|
113
|
+
};
|
|
114
|
+
if (subagentId)
|
|
115
|
+
event.subagentId = subagentId;
|
|
116
|
+
return [event];
|
|
117
|
+
}
|
|
118
|
+
function mapMessage(payload) {
|
|
119
|
+
const message = asRecord(payload['message']);
|
|
120
|
+
const rawContent = message?.['content'];
|
|
121
|
+
const content = Array.isArray(rawContent) ? rawContent : [];
|
|
122
|
+
const subagentId = extractSubagentId(payload);
|
|
123
|
+
if (readString(payload['type']) === 'assistant')
|
|
124
|
+
return content.flatMap((item) => mapAssistantContent(asRecord(item) ?? {}, subagentId));
|
|
125
|
+
if (readString(payload['type']) === 'user')
|
|
126
|
+
return content.flatMap((item) => mapToolResult(asRecord(item) ?? {}, subagentId));
|
|
127
|
+
return [];
|
|
128
|
+
}
|
|
129
|
+
export function mapConsentLevelToPermissionMode(level = 'normal') {
|
|
130
|
+
if (level === 'plan-only')
|
|
131
|
+
return 'plan';
|
|
132
|
+
if (level === 'relaxed')
|
|
133
|
+
return 'acceptEdits';
|
|
134
|
+
if (level === 'auto')
|
|
135
|
+
return 'bypassPermissions';
|
|
136
|
+
return 'default';
|
|
137
|
+
}
|
|
138
|
+
export function mapClaudeStreamEvent(payload) {
|
|
139
|
+
const event = asRecord(payload);
|
|
140
|
+
if (!event)
|
|
141
|
+
return [];
|
|
142
|
+
if (readString(event['type']) === 'system' && readString(event['subtype']) === 'init') {
|
|
143
|
+
return [{
|
|
144
|
+
type: 'system',
|
|
145
|
+
continuationToken: readString(event['session_id']),
|
|
146
|
+
cwd: readString(event['cwd']),
|
|
147
|
+
model: readString(event['model']),
|
|
148
|
+
}];
|
|
149
|
+
}
|
|
150
|
+
if (readString(event['type']) === 'assistant' || readString(event['type']) === 'user')
|
|
151
|
+
return mapMessage(event);
|
|
152
|
+
// 鉴权 / API 错误时 claude 仍报 subtype=success, 只在 is_error 上标出失败.
|
|
153
|
+
if (readString(event['type']) === 'result' && readString(event['subtype']) === 'success' && event['is_error'] !== true) {
|
|
154
|
+
const usage = asRecord(event['usage']);
|
|
155
|
+
return [
|
|
156
|
+
{
|
|
157
|
+
type: 'usage',
|
|
158
|
+
inputTokens: typeof usage?.['input_tokens'] === 'number' ? usage['input_tokens'] : undefined,
|
|
159
|
+
outputTokens: typeof usage?.['output_tokens'] === 'number' ? usage['output_tokens'] : undefined,
|
|
160
|
+
costUsd: typeof event['total_cost_usd'] === 'number' ? event['total_cost_usd'] : undefined,
|
|
161
|
+
},
|
|
162
|
+
{ type: 'done', continuationToken: readString(event['session_id']) },
|
|
163
|
+
];
|
|
164
|
+
}
|
|
165
|
+
if (readString(event['type']) === 'result' && (readString(event['subtype'])?.startsWith('error') || event['is_error'] === true)) {
|
|
166
|
+
const message = readErrorMessage(event);
|
|
167
|
+
const code = inferErrorCode(message);
|
|
168
|
+
return [{ type: 'error', message, code, recoverable: inferRecoverable(code) }];
|
|
169
|
+
}
|
|
170
|
+
return [];
|
|
171
|
+
}
|
|
172
|
+
/** 让 claude 输出 stream_event 增量, 卡片才能边生成边显示; 不加时正文要等整段生成完才一次出现. */
|
|
173
|
+
export const CLAUDE_PARTIAL_MESSAGES_FLAG = '--include-partial-messages';
|
|
174
|
+
/**
|
|
175
|
+
* 带 `--include-partial-messages` 时, claude 先发 stream_event 增量 (text_delta / thinking_delta),
|
|
176
|
+
* 每个内容块结束后再发一条同 message.id 的完整 assistant 消息. 已经按增量推过的 text / thinking
|
|
177
|
+
* 不再从完整消息里重复; tool_use 等仍以完整消息为准. 子 agent (parent_tool_use_id 非空) 的增量不进正文.
|
|
178
|
+
* 有状态, 每个 run 一个.
|
|
179
|
+
*/
|
|
180
|
+
export function createClaudeStreamMapper() {
|
|
181
|
+
let streamingMessageId;
|
|
182
|
+
const streamedKinds = new Set();
|
|
183
|
+
return (payload) => {
|
|
184
|
+
const event = asRecord(payload);
|
|
185
|
+
if (!event)
|
|
186
|
+
return [];
|
|
187
|
+
if (readString(event['type']) === 'stream_event') {
|
|
188
|
+
if (event['parent_tool_use_id'])
|
|
189
|
+
return [];
|
|
190
|
+
const inner = asRecord(event['event']);
|
|
191
|
+
const innerType = readString(inner?.['type']);
|
|
192
|
+
if (innerType === 'message_start') {
|
|
193
|
+
streamingMessageId = readString(asRecord(inner?.['message'])?.['id']);
|
|
194
|
+
streamedKinds.clear();
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
if (innerType !== 'content_block_delta')
|
|
198
|
+
return [];
|
|
199
|
+
const delta = asRecord(inner?.['delta']);
|
|
200
|
+
const deltaType = readString(delta?.['type']);
|
|
201
|
+
if (deltaType !== 'text_delta' && deltaType !== 'thinking_delta')
|
|
202
|
+
return [];
|
|
203
|
+
const kind = deltaType === 'text_delta' ? 'text' : 'thinking';
|
|
204
|
+
const text = readString(delta?.[kind]) ?? '';
|
|
205
|
+
if (!text)
|
|
206
|
+
return [];
|
|
207
|
+
if (streamingMessageId)
|
|
208
|
+
streamedKinds.add(kind);
|
|
209
|
+
return [{ type: kind, delta: text }];
|
|
210
|
+
}
|
|
211
|
+
if (readString(event['type']) === 'assistant' && streamedKinds.size > 0) {
|
|
212
|
+
const message = asRecord(event['message']);
|
|
213
|
+
if (message && readString(message['id']) === streamingMessageId && Array.isArray(message['content'])) {
|
|
214
|
+
const content = message['content'].filter((item) => !streamedKinds.has(readString(asRecord(item)?.['type'])));
|
|
215
|
+
return mapClaudeStreamEvent({ ...event, message: { ...message, content } });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return mapClaudeStreamEvent(payload);
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
const TOOL_PROGRESS_DEFAULT_MS = 2000;
|
|
222
|
+
const TOOL_PROGRESS_MIN_MS = 100;
|
|
223
|
+
const TOOL_PROGRESS_MAX_MS = 60000;
|
|
224
|
+
export function parseToolProgressInterval(envValue) {
|
|
225
|
+
if (envValue === undefined)
|
|
226
|
+
return TOOL_PROGRESS_DEFAULT_MS;
|
|
227
|
+
const parsed = Number.parseInt(envValue, 10);
|
|
228
|
+
if (Number.isNaN(parsed) || parsed < TOOL_PROGRESS_MIN_MS || parsed > TOOL_PROGRESS_MAX_MS)
|
|
229
|
+
return TOOL_PROGRESS_DEFAULT_MS;
|
|
230
|
+
return parsed;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* claude CLI has no image / attachment flag; it reads local files with its own
|
|
234
|
+
* Read tool. Paths the caller already wrote into the prompt are left alone, the
|
|
235
|
+
* rest are listed after the prompt so `images` / `attachments` are never dropped.
|
|
236
|
+
*/
|
|
237
|
+
export function promptWithLocalFiles(req) {
|
|
238
|
+
const missing = [...(req.images ?? []), ...(req.attachments ?? [])].filter((path) => !req.prompt.includes(path));
|
|
239
|
+
if (missing.length === 0)
|
|
240
|
+
return req.prompt;
|
|
241
|
+
return `${req.prompt}\n\n${missing.map((path) => `附件: ${path}`).join('\n')}`;
|
|
242
|
+
}
|
|
243
|
+
export class ClaudeCodeAgent extends CLISubprocessAgent {
|
|
244
|
+
id = 'claude-code';
|
|
245
|
+
displayName = 'Claude Code';
|
|
246
|
+
availability;
|
|
247
|
+
capabilities;
|
|
248
|
+
/** 增量去重是有状态的, 按 run (同一个 req 对象) 各用一个. */
|
|
249
|
+
streamMappers = new WeakMap();
|
|
250
|
+
run(req) {
|
|
251
|
+
const baseRun = super.run(req);
|
|
252
|
+
const intervalMs = parseToolProgressInterval(process.env['WB_TOOL_PROGRESS_INTERVAL_MS']);
|
|
253
|
+
return new ToolProgressWrappedRun(baseRun, intervalMs);
|
|
254
|
+
}
|
|
255
|
+
async isAvailable() {
|
|
256
|
+
this.availability ??= Promise.resolve(this.checkAvailability());
|
|
257
|
+
return this.availability;
|
|
258
|
+
}
|
|
259
|
+
async getCapabilities() {
|
|
260
|
+
this.capabilities ??= Promise.resolve(CAPABILITIES);
|
|
261
|
+
return this.capabilities;
|
|
262
|
+
}
|
|
263
|
+
buildProcessSpec(req) {
|
|
264
|
+
const args = ['--print', '--output-format', 'stream-json', '--verbose', CLAUDE_PARTIAL_MESSAGES_FLAG];
|
|
265
|
+
if (req.continuationToken)
|
|
266
|
+
args.push('--resume', req.continuationToken);
|
|
267
|
+
if (req.model)
|
|
268
|
+
args.push('--model', req.model);
|
|
269
|
+
args.push('--permission-mode', mapConsentLevelToPermissionMode(req.consentLevel), promptWithLocalFiles(req));
|
|
270
|
+
return { command: 'claude', args, cwd: req.cwd, env: pickEnv(process.env, CLAUDE_PASSTHROUGH_KEYS) };
|
|
271
|
+
}
|
|
272
|
+
mapOutput(payload, req) {
|
|
273
|
+
let mapper = this.streamMappers.get(req);
|
|
274
|
+
if (!mapper) {
|
|
275
|
+
mapper = createClaudeStreamMapper();
|
|
276
|
+
this.streamMappers.set(req, mapper);
|
|
277
|
+
}
|
|
278
|
+
return mapper(payload);
|
|
279
|
+
}
|
|
280
|
+
checkAvailability() {
|
|
281
|
+
const result = spawnSync('claude', ['--version'], { encoding: 'utf8' });
|
|
282
|
+
return result.status === 0 && result.stdout.includes('Claude Code');
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
class ToolProgressWrappedRun {
|
|
286
|
+
baseRun;
|
|
287
|
+
intervalMs;
|
|
288
|
+
events;
|
|
289
|
+
timer = null;
|
|
290
|
+
buffer = null;
|
|
291
|
+
pending = [];
|
|
292
|
+
done = false;
|
|
293
|
+
constructor(baseRun, intervalMs) {
|
|
294
|
+
this.baseRun = baseRun;
|
|
295
|
+
this.intervalMs = intervalMs;
|
|
296
|
+
this.events = this.wrapEvents();
|
|
297
|
+
}
|
|
298
|
+
async stop() {
|
|
299
|
+
return this.baseRun.stop();
|
|
300
|
+
}
|
|
301
|
+
async waitForExit(timeoutMs) {
|
|
302
|
+
return this.baseRun.waitForExit(timeoutMs);
|
|
303
|
+
}
|
|
304
|
+
async *wrapEvents() {
|
|
305
|
+
this.timer = setInterval(() => this.tick(), this.intervalMs);
|
|
306
|
+
try {
|
|
307
|
+
for await (const event of this.baseRun.events) {
|
|
308
|
+
this.trackDelta(event);
|
|
309
|
+
yield event;
|
|
310
|
+
yield* this.drainPending();
|
|
311
|
+
if (event.type === 'done' || event.type === 'error') {
|
|
312
|
+
this.done = true;
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
finally {
|
|
318
|
+
this.cleanup();
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
trackDelta(event) {
|
|
322
|
+
if (event.type === 'tool_use') {
|
|
323
|
+
const snippet = typeof event.input === 'string' ? event.input.slice(0, 200) : undefined;
|
|
324
|
+
this.buffer = { id: event.id, message: snippet, subagentId: event.subagentId, updated: true };
|
|
325
|
+
}
|
|
326
|
+
else if (event.type === 'text' || event.type === 'thinking') {
|
|
327
|
+
const id = this.buffer?.id ?? '_text';
|
|
328
|
+
this.buffer = { id, message: event.delta.slice(0, 200), subagentId: this.buffer?.subagentId, updated: true };
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
tick() {
|
|
332
|
+
if (this.done || !this.buffer?.updated)
|
|
333
|
+
return;
|
|
334
|
+
const progress = { type: 'tool_progress', id: this.buffer.id };
|
|
335
|
+
if (this.buffer.message)
|
|
336
|
+
progress.message = this.buffer.message;
|
|
337
|
+
if (this.buffer.subagentId)
|
|
338
|
+
progress.subagentId = this.buffer.subagentId;
|
|
339
|
+
this.pending.push(progress);
|
|
340
|
+
this.buffer.updated = false;
|
|
341
|
+
}
|
|
342
|
+
*drainPending() {
|
|
343
|
+
while (this.pending.length > 0) {
|
|
344
|
+
yield this.pending.shift();
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
cleanup() {
|
|
348
|
+
if (this.timer) {
|
|
349
|
+
clearInterval(this.timer);
|
|
350
|
+
this.timer = null;
|
|
351
|
+
}
|
|
352
|
+
this.buffer = null;
|
|
353
|
+
}
|
|
354
|
+
}
|