@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,188 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { ClaudeCodeAgent, CodexAgent, DefaultAgentRegistry, } from '../../../packages/core/src/index.js';
|
|
6
|
+
import { isCommandOnPath } from '../../../packages/core/src/agent/registry.js';
|
|
7
|
+
import { buildClaudeAgentEnv, shouldPreferClaudeOAuth } from './security/env-whitelist.js';
|
|
8
|
+
import { extractModelFromArgs, stripModelArgs } from './feishu/event-handler.js';
|
|
9
|
+
/**
|
|
10
|
+
* `WB_CLAUDE_COMMAND="claude-w --model X"` 这类带参数的写法: 第一个词是可执行文件, 其余前置到 argv.
|
|
11
|
+
* 与 wb-runner 路径 (event-handler) 的拆分规则一致; 不拆的话可用性检查找不到 `claude-w --model X`
|
|
12
|
+
* 这个文件, 所有 agent 都被判为不可用.
|
|
13
|
+
*/
|
|
14
|
+
export function splitCommand(command) {
|
|
15
|
+
const [head, ...prepend] = command.trim().split(/\s+/);
|
|
16
|
+
return { head: head ?? command, prepend };
|
|
17
|
+
}
|
|
18
|
+
export function commandExists(command) {
|
|
19
|
+
return command.includes('/') ? existsSync(command) : isCommandOnPath(command);
|
|
20
|
+
}
|
|
21
|
+
function supportsAuthStatus(command) {
|
|
22
|
+
const result = spawnSync(command, ['auth', 'status', '--json'], {
|
|
23
|
+
encoding: 'utf8',
|
|
24
|
+
timeout: 3000,
|
|
25
|
+
env: buildClaudeAgentEnv(process.env, false),
|
|
26
|
+
});
|
|
27
|
+
return result.status === 0 && result.stdout.trim().startsWith('{');
|
|
28
|
+
}
|
|
29
|
+
function readClaudeAuthStatus(command, env) {
|
|
30
|
+
const result = spawnSync(command, ['auth', 'status', '--json'], {
|
|
31
|
+
encoding: 'utf8',
|
|
32
|
+
timeout: 3000,
|
|
33
|
+
env: buildClaudeAgentEnv(env, false),
|
|
34
|
+
});
|
|
35
|
+
if (result.status !== 0 || !result.stdout.trim())
|
|
36
|
+
return null;
|
|
37
|
+
try {
|
|
38
|
+
return JSON.parse(result.stdout);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const DEFAULT_CODEX_HOME = join(homedir(), '.codex');
|
|
45
|
+
const DEPRECATED_CODEX_HOOKS_PATTERN = /^\s*codex_hooks\s*=.*$/m;
|
|
46
|
+
function resolveCodexHome(env) {
|
|
47
|
+
const override = env['CODEX_HOME'];
|
|
48
|
+
return override && override.trim() ? override : DEFAULT_CODEX_HOME;
|
|
49
|
+
}
|
|
50
|
+
function hasDeprecatedCodexHooksConfig(codexHome) {
|
|
51
|
+
const configPath = join(codexHome, 'config.toml');
|
|
52
|
+
if (!existsSync(configPath))
|
|
53
|
+
return false;
|
|
54
|
+
return DEPRECATED_CODEX_HOOKS_PATTERN.test(readFileSync(configPath, 'utf8'));
|
|
55
|
+
}
|
|
56
|
+
function sanitizeCodexConfig(content) {
|
|
57
|
+
const lines = content.split(/\r?\n/);
|
|
58
|
+
const filtered = lines.filter((line, index, source) => {
|
|
59
|
+
if (DEPRECATED_CODEX_HOOKS_PATTERN.test(line))
|
|
60
|
+
return false;
|
|
61
|
+
return !(index === source.length - 1 && line === '');
|
|
62
|
+
});
|
|
63
|
+
return `${filtered.join('\n')}${content.endsWith('\n') ? '\n' : ''}`;
|
|
64
|
+
}
|
|
65
|
+
function getSymlinkType(path) {
|
|
66
|
+
const stat = lstatSync(path);
|
|
67
|
+
if (stat.isDirectory())
|
|
68
|
+
return 'dir';
|
|
69
|
+
if (stat.isFile() || stat.isSymbolicLink())
|
|
70
|
+
return 'file';
|
|
71
|
+
return 'other';
|
|
72
|
+
}
|
|
73
|
+
function syncCodexHome(sourceDir, targetDir) {
|
|
74
|
+
mkdirSync(targetDir, { recursive: true });
|
|
75
|
+
if (!existsSync(sourceDir))
|
|
76
|
+
return;
|
|
77
|
+
for (const entry of readdirSync(targetDir)) {
|
|
78
|
+
const targetPath = join(targetDir, entry);
|
|
79
|
+
if (!existsSync(join(sourceDir, entry)))
|
|
80
|
+
rmSync(targetPath, { recursive: true, force: true });
|
|
81
|
+
}
|
|
82
|
+
for (const entry of readdirSync(sourceDir)) {
|
|
83
|
+
const sourcePath = join(sourceDir, entry);
|
|
84
|
+
const targetPath = join(targetDir, entry);
|
|
85
|
+
if (entry === 'config.toml') {
|
|
86
|
+
const sanitized = sanitizeCodexConfig(readFileSync(sourcePath, 'utf8'));
|
|
87
|
+
writeFileSync(targetPath, sanitized);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
const sourceType = getSymlinkType(sourcePath);
|
|
91
|
+
if (sourceType === 'other')
|
|
92
|
+
continue;
|
|
93
|
+
if (existsSync(targetPath)) {
|
|
94
|
+
const targetType = getSymlinkType(targetPath);
|
|
95
|
+
if (targetType === 'file' && sourceType === 'file')
|
|
96
|
+
continue;
|
|
97
|
+
if (targetType === 'dir' && sourceType === 'dir')
|
|
98
|
+
continue;
|
|
99
|
+
rmSync(targetPath, { recursive: true, force: true });
|
|
100
|
+
}
|
|
101
|
+
symlinkSync(sourcePath, targetPath, sourceType);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
class OAuthFirstClaudeCodeAgent extends ClaudeCodeAgent {
|
|
105
|
+
authStatusSupported;
|
|
106
|
+
preferOAuth;
|
|
107
|
+
command;
|
|
108
|
+
prepend;
|
|
109
|
+
constructor(command, authStatusSupported) {
|
|
110
|
+
super();
|
|
111
|
+
this.authStatusSupported = authStatusSupported;
|
|
112
|
+
({ head: this.command, prepend: this.prepend } = splitCommand(command));
|
|
113
|
+
}
|
|
114
|
+
async isAvailable() {
|
|
115
|
+
if (!commandExists(this.command))
|
|
116
|
+
return false;
|
|
117
|
+
if (!this.authStatusSupported)
|
|
118
|
+
return true;
|
|
119
|
+
const result = spawnSync(this.command, ['--version'], { encoding: 'utf8', timeout: 3000 });
|
|
120
|
+
return result.status === 0;
|
|
121
|
+
}
|
|
122
|
+
buildProcessSpec(req) {
|
|
123
|
+
// claude-w skips interactive model selection only when --model is in $@.
|
|
124
|
+
// If ANTHROPIC_MODEL env is set and no explicit model was requested,
|
|
125
|
+
// inject it so the wrapper sees the flag and skips the TTY picker.
|
|
126
|
+
// A model written into the command itself is moved into the single --model slot.
|
|
127
|
+
const commandModel = extractModelFromArgs(this.prepend);
|
|
128
|
+
const prepend = commandModel ? stripModelArgs(this.prepend) : this.prepend;
|
|
129
|
+
const effectiveModel = req.model ?? commandModel ?? process.env['ANTHROPIC_MODEL'];
|
|
130
|
+
const spec = super.buildProcessSpec({ ...req, model: effectiveModel });
|
|
131
|
+
return { ...spec, command: this.command, args: [...prepend, ...spec.args] };
|
|
132
|
+
}
|
|
133
|
+
envFilter(env) {
|
|
134
|
+
if (!this.authStatusSupported)
|
|
135
|
+
return buildClaudeAgentEnv(env, false);
|
|
136
|
+
this.preferOAuth ??= shouldPreferClaudeOAuth(readClaudeAuthStatus(this.command, env));
|
|
137
|
+
return buildClaudeAgentEnv(env, this.preferOAuth);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
class ConfigurableCodexAgent extends CodexAgent {
|
|
141
|
+
isolatedCodexHome;
|
|
142
|
+
command;
|
|
143
|
+
prepend;
|
|
144
|
+
constructor(command, dataDir) {
|
|
145
|
+
super();
|
|
146
|
+
({ head: this.command, prepend: this.prepend } = splitCommand(command));
|
|
147
|
+
this.isolatedCodexHome = join(dataDir, 'wb-bot-codex-home');
|
|
148
|
+
}
|
|
149
|
+
async isAvailable() {
|
|
150
|
+
if (!commandExists(this.command))
|
|
151
|
+
return false;
|
|
152
|
+
if (this.command !== 'codex')
|
|
153
|
+
return true;
|
|
154
|
+
const result = spawnSync(this.command, ['--version'], { encoding: 'utf8', timeout: 3000 });
|
|
155
|
+
return result.status === 0 && result.stdout.toLowerCase().includes('codex');
|
|
156
|
+
}
|
|
157
|
+
buildProcessSpec(req) {
|
|
158
|
+
// codex-w skips interactive model selection only when -c model=... is in $@.
|
|
159
|
+
// Fall back to CODEX_MODEL env so the wrapper sees the flag and skips the TTY picker.
|
|
160
|
+
// `--model X` written into the command goes through the same slot; `-c model=X` stays in prepend.
|
|
161
|
+
const commandModel = extractModelFromArgs(this.prepend);
|
|
162
|
+
const prepend = commandModel ? stripModelArgs(this.prepend) : this.prepend;
|
|
163
|
+
const effectiveModel = req.model ?? commandModel ?? (this.command !== 'codex' ? process.env['CODEX_MODEL'] : undefined);
|
|
164
|
+
const spec = super.buildProcessSpec({ ...req, model: effectiveModel });
|
|
165
|
+
if (!effectiveModel || this.command === 'codex')
|
|
166
|
+
return { ...spec, command: this.command, args: [...prepend, ...spec.args] };
|
|
167
|
+
const args = spec.args.filter((arg, index, source) => arg !== '--model' && source[index - 1] !== '--model');
|
|
168
|
+
return { ...spec, command: this.command, args: [...prepend, '-c', `model=${effectiveModel}`, ...args] };
|
|
169
|
+
}
|
|
170
|
+
envFilter(env) {
|
|
171
|
+
const filtered = { ...env };
|
|
172
|
+
const sourceCodexHome = resolveCodexHome(filtered);
|
|
173
|
+
if (!hasDeprecatedCodexHooksConfig(sourceCodexHome))
|
|
174
|
+
return filtered;
|
|
175
|
+
syncCodexHome(sourceCodexHome, this.isolatedCodexHome);
|
|
176
|
+
filtered['CODEX_HOME'] = this.isolatedCodexHome;
|
|
177
|
+
delete filtered['CODEX_CONFIG_DIR'];
|
|
178
|
+
return filtered;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
export function createBotAgentRegistry(options) {
|
|
182
|
+
return new DefaultAgentRegistry([
|
|
183
|
+
{
|
|
184
|
+
agent: new OAuthFirstClaudeCodeAgent(options.claudeCommand, supportsAuthStatus(splitCommand(options.claudeCommand).head)),
|
|
185
|
+
},
|
|
186
|
+
{ agent: new ConfigurableCodexAgent(options.codexCommand, options.dataDir) },
|
|
187
|
+
]);
|
|
188
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { createMirrorSink } from '../../../../packages/core/src/audit-pipe/mirror-sink.js';
|
|
3
|
+
function entryDetail(request) {
|
|
4
|
+
return {
|
|
5
|
+
source_message_id: request.sourceMessageId,
|
|
6
|
+
user_open_id: request.userOpenId,
|
|
7
|
+
thread_id: request.threadId,
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
function buildResource(request, phase) {
|
|
11
|
+
const result = request.status;
|
|
12
|
+
const reason = request.resolutionReason ? `:reason=${request.resolutionReason.replace(/[:\s]/g, '_')}` : '';
|
|
13
|
+
const carrier = request.carrier ? `:carrier=${request.carrier}` : '';
|
|
14
|
+
return `approval-gate:${phase}:anchor=${request.anchor}:request=${request.requestId}:result=${result}${carrier}${reason}`.slice(0, 256);
|
|
15
|
+
}
|
|
16
|
+
export function writeApprovalAudit(options) {
|
|
17
|
+
const sink = createMirrorSink({ dataDir: options.dataDir });
|
|
18
|
+
const record = {
|
|
19
|
+
audit_record_id: randomUUID(),
|
|
20
|
+
session_id: requestSessionId(options.request),
|
|
21
|
+
run_id: options.request.runId,
|
|
22
|
+
revision: 0,
|
|
23
|
+
actor: options.request.userOpenId,
|
|
24
|
+
action: 'other',
|
|
25
|
+
resource: buildResource(options.request, options.phase),
|
|
26
|
+
ts: options.nowIso ?? new Date().toISOString(),
|
|
27
|
+
entry_form: 'im',
|
|
28
|
+
entry_detail: entryDetail(options.request),
|
|
29
|
+
agent_id: 'claude-code',
|
|
30
|
+
raw_tool_use_id: `approval-gate:${options.request.requestId}:${options.phase}`,
|
|
31
|
+
raw_tool_name: 'approval-gate',
|
|
32
|
+
};
|
|
33
|
+
sink.write(record);
|
|
34
|
+
}
|
|
35
|
+
function requestSessionId(request) {
|
|
36
|
+
return request.sessionId;
|
|
37
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
function mentionApproversContent(request) {
|
|
2
|
+
if (!request.allowedApproverOpenIds.length)
|
|
3
|
+
return null;
|
|
4
|
+
return request.allowedApproverOpenIds.map((openId) => `<at user_id="${openId}" />`).join(' ');
|
|
5
|
+
}
|
|
6
|
+
export function renderApprovalCountdownText(request, nowMs) {
|
|
7
|
+
const remainingMs = Date.parse(request.deadlineAt) - nowMs;
|
|
8
|
+
if (remainingMs <= 0)
|
|
9
|
+
return '⏱️ 已超时,默认拒绝';
|
|
10
|
+
const totalSeconds = Math.max(0, Math.floor(remainingMs / 1000));
|
|
11
|
+
const minutes = Math.floor(totalSeconds / 60);
|
|
12
|
+
const seconds = totalSeconds % 60;
|
|
13
|
+
return `⏱️ 剩余 ${minutes}m${String(seconds).padStart(2, '0')}s`;
|
|
14
|
+
}
|
|
15
|
+
// M13-E: PRD §2.7 "@ 必带 '为什么 @ 你 + 下一步动作'" — 卡头中文化、动词短句
|
|
16
|
+
// 明确告诉被 @ 审批人"这是什么、下一步该怎么做"。
|
|
17
|
+
const ANCHOR_HEADLINE = {
|
|
18
|
+
writeToMainBranch: { emoji: '🚀', verb: '准备往 main 提交代码', explanation: '批准 = 放行这次 push · 拒绝 = 终止这个 run' },
|
|
19
|
+
envVarChange: { emoji: '🔧', verb: '准备修改 / 读取环境变量', explanation: '批准 = 放行这次 env 变更 · 拒绝 = 终止这个 run' },
|
|
20
|
+
externalDepUpgrade: { emoji: '📦', verb: '准备升级外部依赖', explanation: '批准 = 放行升级 · 拒绝 = 终止这个 run' },
|
|
21
|
+
};
|
|
22
|
+
function anchorCallout(request) {
|
|
23
|
+
return ANCHOR_HEADLINE[request.anchor] ?? { emoji: '⚠️', verb: '准备动敏感操作', explanation: '批准或拒绝即可, 可以转派' };
|
|
24
|
+
}
|
|
25
|
+
export function renderApprovalRequestCard(request) {
|
|
26
|
+
const mentions = mentionApproversContent(request);
|
|
27
|
+
const nowMs = Date.now();
|
|
28
|
+
const headline = anchorCallout(request);
|
|
29
|
+
return {
|
|
30
|
+
schema: '2.0',
|
|
31
|
+
config: { wide_screen_mode: true },
|
|
32
|
+
header: { title: { tag: 'plain_text', content: `${headline.emoji} ${headline.verb} — 需要审批` } },
|
|
33
|
+
body: {
|
|
34
|
+
elements: [
|
|
35
|
+
// 为什么 @ 你 + 下一步: PRD §2.7。
|
|
36
|
+
...(mentions ? [{ tag: 'markdown', content: `${mentions} ${headline.explanation}` }] : [{ tag: 'markdown', content: `${headline.explanation}` }]),
|
|
37
|
+
{ tag: 'markdown', content: `**触发的 run** ${request.agentId}\n*${request.cwd}*\n${request.summary}` },
|
|
38
|
+
{ tag: 'markdown', content: `${renderApprovalCountdownText(request, nowMs)}\nrequest_id: ${request.requestId}` },
|
|
39
|
+
{
|
|
40
|
+
tag: 'column_set',
|
|
41
|
+
columns: [
|
|
42
|
+
{
|
|
43
|
+
tag: 'column',
|
|
44
|
+
width: 'weighted',
|
|
45
|
+
weight: 1,
|
|
46
|
+
elements: [{
|
|
47
|
+
tag: 'button',
|
|
48
|
+
text: { tag: 'plain_text', content: '批准' },
|
|
49
|
+
type: 'primary_filled',
|
|
50
|
+
behaviors: [{ type: 'callback', value: { action: 'approval_gate_approve', requestId: request.requestId } }],
|
|
51
|
+
}],
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
tag: 'column',
|
|
55
|
+
width: 'weighted',
|
|
56
|
+
weight: 1,
|
|
57
|
+
elements: [{
|
|
58
|
+
tag: 'button',
|
|
59
|
+
text: { tag: 'plain_text', content: '拒绝' },
|
|
60
|
+
type: 'default',
|
|
61
|
+
behaviors: [{ type: 'callback', value: { action: 'approval_gate_deny', requestId: request.requestId } }],
|
|
62
|
+
}],
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
tag: 'column',
|
|
66
|
+
width: 'weighted',
|
|
67
|
+
weight: 1,
|
|
68
|
+
elements: [{
|
|
69
|
+
tag: 'button',
|
|
70
|
+
text: { tag: 'plain_text', content: '转派' },
|
|
71
|
+
type: 'default',
|
|
72
|
+
behaviors: [{ type: 'callback', value: { action: 'approval_gate_transfer', requestId: request.requestId } }],
|
|
73
|
+
}],
|
|
74
|
+
},
|
|
75
|
+
],
|
|
76
|
+
},
|
|
77
|
+
],
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
export function renderApprovalResolvedCard(request) {
|
|
82
|
+
const statusLabel = request.status === 'approved' ? '✅ 已批准' : request.status === 'denied' ? '❌ 已拒绝' : '⌛ 已超时';
|
|
83
|
+
return {
|
|
84
|
+
schema: '2.0',
|
|
85
|
+
config: { wide_screen_mode: true },
|
|
86
|
+
header: { title: { tag: 'plain_text', content: `${statusLabel} · ${request.anchor}` } },
|
|
87
|
+
body: {
|
|
88
|
+
elements: [
|
|
89
|
+
{ tag: 'markdown', content: `agent: ${request.agentId}\ncwd: ${request.cwd}\nsummary: ${request.summary}` },
|
|
90
|
+
{ tag: 'markdown', content: `resolution: ${request.resolutionReason ?? '-'}\nresolved_by: ${request.resolvedBy ?? '-'}\nrequest: ${request.requestId}` },
|
|
91
|
+
],
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function buildApprovalHookEnv(baseEnv, options) {
|
|
2
|
+
return {
|
|
3
|
+
...baseEnv,
|
|
4
|
+
WB_DATA_DIR: options.dataDir,
|
|
5
|
+
WB_APPROVAL_RUN_ID: options.runId,
|
|
6
|
+
WB_APPROVAL_BOT_ID: options.botId,
|
|
7
|
+
WB_APPROVAL_SESSION_ID: options.sessionId,
|
|
8
|
+
WB_APPROVAL_USER_OPEN_ID: options.userOpenId,
|
|
9
|
+
WB_APPROVAL_THREAD_ID: options.threadId,
|
|
10
|
+
WB_APPROVAL_SOURCE_MESSAGE_ID: options.sourceMessageId,
|
|
11
|
+
WB_APPROVAL_REPLY_MESSAGE_ID: options.replyMessageId,
|
|
12
|
+
WB_APPROVAL_AGENT_ID: options.agentId,
|
|
13
|
+
...(options.codeOwnerConfigPath ? { WB_APPROVAL_CODE_OWNER_CONFIG_PATH: options.codeOwnerConfigPath } : {}),
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { approvalGateDir } from '../../../../packages/core/src/paths.js';
|
|
5
|
+
const DEFAULT_CODEX_HOME = join(homedir(), '.codex');
|
|
6
|
+
const DEPRECATED_CODEX_HOOKS_PATTERN = /^\s*codex_hooks\s*=.*$/m;
|
|
7
|
+
const CODEX_HOME_EXCLUDED_ENTRIES = new Set(['config.toml', 'hooks.json']);
|
|
8
|
+
function isTomlTableHeader(trimmed) {
|
|
9
|
+
return /^\[\[?.+\]\]?(?:\s+#.*)?$/.test(trimmed);
|
|
10
|
+
}
|
|
11
|
+
function isHookTableHeader(trimmed) {
|
|
12
|
+
return /^\[\[?hooks(?:\.|\])/.test(trimmed);
|
|
13
|
+
}
|
|
14
|
+
function buildNodeInvocation(scriptPath) {
|
|
15
|
+
const absScriptPath = resolve(scriptPath);
|
|
16
|
+
if (absScriptPath.endsWith('.js')) {
|
|
17
|
+
return `${JSON.stringify(process.execPath)} ${JSON.stringify(absScriptPath)}`;
|
|
18
|
+
}
|
|
19
|
+
let dir = dirname(absScriptPath);
|
|
20
|
+
let tsxLoader;
|
|
21
|
+
while (true) {
|
|
22
|
+
const candidate = join(dir, 'node_modules/tsx/dist/esm/index.mjs');
|
|
23
|
+
if (existsSync(candidate)) {
|
|
24
|
+
tsxLoader = candidate;
|
|
25
|
+
break;
|
|
26
|
+
}
|
|
27
|
+
const parent = dirname(dir);
|
|
28
|
+
if (parent === dir)
|
|
29
|
+
break;
|
|
30
|
+
dir = parent;
|
|
31
|
+
}
|
|
32
|
+
if (tsxLoader) {
|
|
33
|
+
return `${JSON.stringify(process.execPath)} --import ${JSON.stringify(tsxLoader)} ${JSON.stringify(absScriptPath)}`;
|
|
34
|
+
}
|
|
35
|
+
return `${JSON.stringify(process.execPath)} --import tsx ${JSON.stringify(absScriptPath)}`;
|
|
36
|
+
}
|
|
37
|
+
function resolveSourceCodexHome() {
|
|
38
|
+
const override = process.env['CODEX_HOME'];
|
|
39
|
+
return override && override.trim() ? override.trim() : DEFAULT_CODEX_HOME;
|
|
40
|
+
}
|
|
41
|
+
function sanitizeCodexConfig(content) {
|
|
42
|
+
const lines = content.split(/\r?\n/);
|
|
43
|
+
const filtered = [];
|
|
44
|
+
let skippingHookTable = false;
|
|
45
|
+
for (const line of lines) {
|
|
46
|
+
const trimmed = line.trim();
|
|
47
|
+
if (isHookTableHeader(trimmed)) {
|
|
48
|
+
skippingHookTable = true;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (skippingHookTable && isTomlTableHeader(trimmed)) {
|
|
52
|
+
skippingHookTable = false;
|
|
53
|
+
}
|
|
54
|
+
if (skippingHookTable)
|
|
55
|
+
continue;
|
|
56
|
+
if (DEPRECATED_CODEX_HOOKS_PATTERN.test(line))
|
|
57
|
+
continue;
|
|
58
|
+
filtered.push(line);
|
|
59
|
+
}
|
|
60
|
+
while (filtered.length > 0 && filtered.at(-1) === '')
|
|
61
|
+
filtered.pop();
|
|
62
|
+
return filtered.join('\n');
|
|
63
|
+
}
|
|
64
|
+
function withHooksEnabled(content) {
|
|
65
|
+
const sanitized = sanitizeCodexConfig(content).trimEnd();
|
|
66
|
+
if (!sanitized)
|
|
67
|
+
return '[features]\nhooks = true\n';
|
|
68
|
+
const lines = sanitized.split('\n');
|
|
69
|
+
const out = [];
|
|
70
|
+
let insideFeatures = false;
|
|
71
|
+
let featureHooksPatched = false;
|
|
72
|
+
for (const line of lines) {
|
|
73
|
+
const trimmed = line.trim();
|
|
74
|
+
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
|
|
75
|
+
if (insideFeatures && !featureHooksPatched)
|
|
76
|
+
out.push('hooks = true');
|
|
77
|
+
insideFeatures = trimmed === '[features]';
|
|
78
|
+
featureHooksPatched = false;
|
|
79
|
+
out.push(line);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (insideFeatures && /^\s*hooks\s*=/.test(line)) {
|
|
83
|
+
out.push('hooks = true');
|
|
84
|
+
featureHooksPatched = true;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
out.push(line);
|
|
88
|
+
}
|
|
89
|
+
if (insideFeatures && !featureHooksPatched)
|
|
90
|
+
out.push('hooks = true');
|
|
91
|
+
if (out.some((line) => line.trim() === '[features]'))
|
|
92
|
+
return `${out.join('\n')}\n`;
|
|
93
|
+
return `${out.join('\n')}\n\n[features]\nhooks = true\n`;
|
|
94
|
+
}
|
|
95
|
+
function stripTomlInlineComment(value) {
|
|
96
|
+
let quote = null;
|
|
97
|
+
let escaped = false;
|
|
98
|
+
let out = '';
|
|
99
|
+
for (const ch of value) {
|
|
100
|
+
if (quote === '"' && escaped) {
|
|
101
|
+
out += ch;
|
|
102
|
+
escaped = false;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (quote === '"' && ch === '\\') {
|
|
106
|
+
out += ch;
|
|
107
|
+
escaped = true;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (quote) {
|
|
111
|
+
out += ch;
|
|
112
|
+
if (ch === quote)
|
|
113
|
+
quote = null;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (ch === '#')
|
|
117
|
+
break;
|
|
118
|
+
if (ch === '"' || ch === '\'') {
|
|
119
|
+
quote = ch;
|
|
120
|
+
out += ch;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
out += ch;
|
|
124
|
+
}
|
|
125
|
+
return out.trim();
|
|
126
|
+
}
|
|
127
|
+
function parseCodexConfig(content) {
|
|
128
|
+
const root = new Map();
|
|
129
|
+
const modelProviders = new Map();
|
|
130
|
+
let currentProvider = null;
|
|
131
|
+
let currentIsRoot = true;
|
|
132
|
+
for (const line of content.split(/\r?\n/)) {
|
|
133
|
+
const trimmed = line.trim();
|
|
134
|
+
if (!trimmed || trimmed.startsWith('#'))
|
|
135
|
+
continue;
|
|
136
|
+
const tableMatch = trimmed.match(/^\[([^\]]+)\]$/);
|
|
137
|
+
if (tableMatch) {
|
|
138
|
+
const tableName = tableMatch[1].trim();
|
|
139
|
+
const providerMatch = tableName.match(/^model_providers\.([^\.]+)$/);
|
|
140
|
+
if (providerMatch) {
|
|
141
|
+
currentProvider = providerMatch[1];
|
|
142
|
+
currentIsRoot = false;
|
|
143
|
+
if (!modelProviders.has(currentProvider))
|
|
144
|
+
modelProviders.set(currentProvider, new Map());
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
currentProvider = null;
|
|
148
|
+
currentIsRoot = false;
|
|
149
|
+
}
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (trimmed.startsWith('[[')) {
|
|
153
|
+
currentProvider = null;
|
|
154
|
+
currentIsRoot = false;
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const kvMatch = line.match(/^\s*([A-Za-z0-9_.-]+)\s*=\s*(.+)$/);
|
|
158
|
+
if (!kvMatch)
|
|
159
|
+
continue;
|
|
160
|
+
const key = kvMatch[1];
|
|
161
|
+
const value = stripTomlInlineComment(kvMatch[2]);
|
|
162
|
+
if (!value)
|
|
163
|
+
continue;
|
|
164
|
+
if (currentProvider) {
|
|
165
|
+
modelProviders.get(currentProvider).set(key, value);
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (currentIsRoot) {
|
|
169
|
+
const dottedProviderMatch = key.match(/^model_providers\.([^\.]+)\.(.+)$/);
|
|
170
|
+
if (dottedProviderMatch) {
|
|
171
|
+
const providerName = dottedProviderMatch[1];
|
|
172
|
+
const providerKey = dottedProviderMatch[2];
|
|
173
|
+
if (!modelProviders.has(providerName))
|
|
174
|
+
modelProviders.set(providerName, new Map());
|
|
175
|
+
modelProviders.get(providerName).set(providerKey, value);
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
root.set(key, value);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return { root, modelProviders };
|
|
182
|
+
}
|
|
183
|
+
function buildCodexPreToolUseOverride(wrapperScriptPath) {
|
|
184
|
+
return `hooks.PreToolUse=[{matcher="*",hooks=[{type="command",command=${JSON.stringify(wrapperScriptPath)},timeout=3605,statusMessage="Checking approval gate"}]}]`;
|
|
185
|
+
}
|
|
186
|
+
// Runtime argv that carries codex config under the approval-gate path.
|
|
187
|
+
//
|
|
188
|
+
// Why `-c` and not config.toml: codex runs with `--ignore-user-config`, which
|
|
189
|
+
// makes `$CODEX_HOME/config.toml` a no-op for runtime config (auth still uses
|
|
190
|
+
// CODEX_HOME). The config.toml written by buildCodexConfig is therefore
|
|
191
|
+
// inert at runtime; hooks / model / model_providers survive only because they
|
|
192
|
+
// are re-injected here as `-c key=value`. codex parses each `-c` value as TOML,
|
|
193
|
+
// so values must be TOML literals (quoted strings stay quoted; booleans bare).
|
|
194
|
+
//
|
|
195
|
+
// model_provider has two sources: an explicit `model_provider` root key (its
|
|
196
|
+
// value is already a TOML literal, e.g. `"llmgw"`, so it is passed through
|
|
197
|
+
// verbatim) or, when absent and exactly one provider is defined, the provider
|
|
198
|
+
// table name (a bare TOML key, so JSON.stringify wraps it into a string
|
|
199
|
+
// literal). Both paths yield a valid `model_provider=<toml-string>` form.
|
|
200
|
+
function buildCodexRuntimeArgs(wrapperScriptPath, sourceConfigRaw) {
|
|
201
|
+
const parsed = parseCodexConfig(sourceConfigRaw);
|
|
202
|
+
const args = ['--ignore-user-config', '--dangerously-bypass-hook-trust'];
|
|
203
|
+
for (const key of ['model_catalog_json', 'model', 'model_reasoning_effort']) {
|
|
204
|
+
const value = parsed.root.get(key);
|
|
205
|
+
if (value)
|
|
206
|
+
args.push('-c', `${key}=${value}`);
|
|
207
|
+
}
|
|
208
|
+
for (const [providerName, entries] of parsed.modelProviders) {
|
|
209
|
+
for (const [key, value] of entries) {
|
|
210
|
+
args.push('-c', `model_providers.${providerName}.${key}=${value}`);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const explicitProvider = parsed.root.get('model_provider');
|
|
214
|
+
if (explicitProvider) {
|
|
215
|
+
args.push('-c', `model_provider=${explicitProvider}`);
|
|
216
|
+
}
|
|
217
|
+
else if (parsed.modelProviders.size === 1) {
|
|
218
|
+
const inferredProvider = parsed.modelProviders.keys().next().value;
|
|
219
|
+
if (inferredProvider)
|
|
220
|
+
args.push('-c', `model_provider=${JSON.stringify(inferredProvider)}`);
|
|
221
|
+
}
|
|
222
|
+
args.push('-c', 'features.hooks=true');
|
|
223
|
+
args.push('-c', buildCodexPreToolUseOverride(wrapperScriptPath));
|
|
224
|
+
return args;
|
|
225
|
+
}
|
|
226
|
+
function getEntryKind(path) {
|
|
227
|
+
const stat = lstatSync(path);
|
|
228
|
+
if (stat.isDirectory())
|
|
229
|
+
return 'dir';
|
|
230
|
+
if (stat.isFile() || stat.isSymbolicLink())
|
|
231
|
+
return 'file';
|
|
232
|
+
return 'other';
|
|
233
|
+
}
|
|
234
|
+
function syncCodexHome(sourceDir, targetDir) {
|
|
235
|
+
mkdirSync(targetDir, { recursive: true });
|
|
236
|
+
if (!existsSync(sourceDir))
|
|
237
|
+
return;
|
|
238
|
+
for (const entry of readdirSync(targetDir)) {
|
|
239
|
+
if (CODEX_HOME_EXCLUDED_ENTRIES.has(entry))
|
|
240
|
+
continue;
|
|
241
|
+
const targetPath = join(targetDir, entry);
|
|
242
|
+
if (!existsSync(join(sourceDir, entry)))
|
|
243
|
+
rmSync(targetPath, { recursive: true, force: true });
|
|
244
|
+
}
|
|
245
|
+
for (const entry of CODEX_HOME_EXCLUDED_ENTRIES) {
|
|
246
|
+
rmSync(join(targetDir, entry), { recursive: true, force: true });
|
|
247
|
+
}
|
|
248
|
+
for (const entry of readdirSync(sourceDir)) {
|
|
249
|
+
if (CODEX_HOME_EXCLUDED_ENTRIES.has(entry))
|
|
250
|
+
continue;
|
|
251
|
+
const sourcePath = join(sourceDir, entry);
|
|
252
|
+
const targetPath = join(targetDir, entry);
|
|
253
|
+
const sourceKind = getEntryKind(sourcePath);
|
|
254
|
+
if (sourceKind === 'other')
|
|
255
|
+
continue;
|
|
256
|
+
if (existsSync(targetPath)) {
|
|
257
|
+
const targetKind = getEntryKind(targetPath);
|
|
258
|
+
if (targetKind === sourceKind)
|
|
259
|
+
continue;
|
|
260
|
+
rmSync(targetPath, { recursive: true, force: true });
|
|
261
|
+
}
|
|
262
|
+
if (!existsSync(targetPath))
|
|
263
|
+
symlinkSync(sourcePath, targetPath, sourceKind);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function buildCodexConfig(wrapperScriptPath, sourceConfigRaw) {
|
|
267
|
+
const base = withHooksEnabled(sourceConfigRaw).trimEnd();
|
|
268
|
+
return `${base}\n\n[[hooks.PreToolUse]]\nmatcher = "*"\n\n[[hooks.PreToolUse.hooks]]\ntype = "command"\ncommand = ${JSON.stringify(wrapperScriptPath)}\ntimeout = 3605\nstatusMessage = "Checking approval gate"\n`;
|
|
269
|
+
}
|
|
270
|
+
export function prepareApprovalHookFiles(options) {
|
|
271
|
+
const root = approvalGateDir(options.dataDir);
|
|
272
|
+
const hooksDir = join(root, 'hooks');
|
|
273
|
+
const claudeDir = join(root, 'claude');
|
|
274
|
+
const codexHome = join(root, 'codex-home');
|
|
275
|
+
mkdirSync(hooksDir, { recursive: true });
|
|
276
|
+
mkdirSync(claudeDir, { recursive: true });
|
|
277
|
+
mkdirSync(codexHome, { recursive: true });
|
|
278
|
+
const wrapperScriptPath = join(hooksDir, 'approval-gate-hook.sh');
|
|
279
|
+
const invocation = buildNodeInvocation(options.hookScriptPath);
|
|
280
|
+
writeFileSync(wrapperScriptPath, `#!/bin/sh\nexec ${invocation} "$@"\n`, { mode: 0o755 });
|
|
281
|
+
chmodSync(wrapperScriptPath, 0o755);
|
|
282
|
+
const claudeSettingsPath = join(claudeDir, 'settings.json');
|
|
283
|
+
writeFileSync(claudeSettingsPath, JSON.stringify({
|
|
284
|
+
hooks: {
|
|
285
|
+
PreToolUse: [
|
|
286
|
+
{
|
|
287
|
+
matcher: '*',
|
|
288
|
+
hooks: [
|
|
289
|
+
{
|
|
290
|
+
type: 'command',
|
|
291
|
+
command: wrapperScriptPath,
|
|
292
|
+
timeout: 3605,
|
|
293
|
+
statusMessage: 'Checking approval gate',
|
|
294
|
+
},
|
|
295
|
+
],
|
|
296
|
+
},
|
|
297
|
+
],
|
|
298
|
+
},
|
|
299
|
+
}, null, 2));
|
|
300
|
+
const sourceCodexHome = resolveSourceCodexHome();
|
|
301
|
+
syncCodexHome(sourceCodexHome, codexHome);
|
|
302
|
+
const codexConfigPath = join(codexHome, 'config.toml');
|
|
303
|
+
const sourceConfigPath = join(sourceCodexHome, 'config.toml');
|
|
304
|
+
const sourceConfigRaw = existsSync(sourceConfigPath) ? readFileSync(sourceConfigPath, 'utf8') : '';
|
|
305
|
+
// config.toml is written for completeness/debuggability, but at runtime it is
|
|
306
|
+
// inert: codex runs with --ignore-user-config (see buildCodexRuntimeArgs), so
|
|
307
|
+
// the live hooks/model/model_providers come from the `-c` argv, not this file.
|
|
308
|
+
writeFileSync(codexConfigPath, buildCodexConfig(wrapperScriptPath, sourceConfigRaw));
|
|
309
|
+
const codexRuntimeArgs = buildCodexRuntimeArgs(wrapperScriptPath, sourceConfigRaw);
|
|
310
|
+
return { wrapperScriptPath, claudeSettingsPath, codexHome, codexRuntimeArgs };
|
|
311
|
+
}
|