@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,244 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
const STDERR_RING_MAX_BYTES = 8 * 1024;
|
|
4
|
+
function isCLIEvent(event) {
|
|
5
|
+
return event.type !== 'consent_required';
|
|
6
|
+
}
|
|
7
|
+
function hasExited(child) {
|
|
8
|
+
return child.exitCode !== null || child.signalCode !== null;
|
|
9
|
+
}
|
|
10
|
+
function getErrorMessage(error) {
|
|
11
|
+
return error instanceof Error ? error.message : String(error);
|
|
12
|
+
}
|
|
13
|
+
function inferErrorCode(stderr) {
|
|
14
|
+
const message = stderr.toLowerCase();
|
|
15
|
+
if (message.includes('auth'))
|
|
16
|
+
return 'auth';
|
|
17
|
+
if (message.includes('rate limit'))
|
|
18
|
+
return 'rate_limit';
|
|
19
|
+
if (message.includes('context'))
|
|
20
|
+
return 'context_length';
|
|
21
|
+
if (message.includes('network'))
|
|
22
|
+
return 'network';
|
|
23
|
+
return 'crashed';
|
|
24
|
+
}
|
|
25
|
+
function buildExitMessage(stderr, code, signal) {
|
|
26
|
+
const trimmed = stderr.trim();
|
|
27
|
+
if (trimmed)
|
|
28
|
+
return trimmed.split('\n').at(-1) ?? trimmed;
|
|
29
|
+
if (signal)
|
|
30
|
+
return `process exited with signal ${signal}`;
|
|
31
|
+
return `process exited with code ${code ?? -1}`;
|
|
32
|
+
}
|
|
33
|
+
function buildCrashEvent(message, code = 'crashed') {
|
|
34
|
+
return { type: 'error', message, code, recoverable: false };
|
|
35
|
+
}
|
|
36
|
+
function raceExit(exitPromise, timeoutMs) {
|
|
37
|
+
return new Promise((resolve) => {
|
|
38
|
+
const timer = setTimeout(() => resolve(false), timeoutMs);
|
|
39
|
+
void exitPromise.then(() => {
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
resolve(true);
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function trimToMaxBytes(value, maxBytes) {
|
|
46
|
+
const buffer = Buffer.from(value);
|
|
47
|
+
if (buffer.length <= maxBytes)
|
|
48
|
+
return value;
|
|
49
|
+
let start = buffer.length - maxBytes;
|
|
50
|
+
while (start < buffer.length) {
|
|
51
|
+
const byte = buffer.at(start);
|
|
52
|
+
if (byte === undefined || (byte & 0b1100_0000) !== 0b1000_0000)
|
|
53
|
+
break;
|
|
54
|
+
start += 1;
|
|
55
|
+
}
|
|
56
|
+
return buffer.subarray(start).toString('utf8');
|
|
57
|
+
}
|
|
58
|
+
function appendStderr(buffer, line) {
|
|
59
|
+
const next = buffer.text ? `${buffer.text}\n${line}` : line;
|
|
60
|
+
buffer.text = trimToMaxBytes(next, STDERR_RING_MAX_BYTES);
|
|
61
|
+
}
|
|
62
|
+
class AsyncEventQueue {
|
|
63
|
+
items = [];
|
|
64
|
+
waiters = [];
|
|
65
|
+
closed = false;
|
|
66
|
+
failure;
|
|
67
|
+
push(value) {
|
|
68
|
+
if (this.closed || this.failure !== undefined)
|
|
69
|
+
return;
|
|
70
|
+
const waiter = this.waiters.shift();
|
|
71
|
+
if (waiter)
|
|
72
|
+
waiter.resolve({ value, done: false });
|
|
73
|
+
else
|
|
74
|
+
this.items.push(value);
|
|
75
|
+
}
|
|
76
|
+
close() {
|
|
77
|
+
if (this.closed)
|
|
78
|
+
return;
|
|
79
|
+
this.closed = true;
|
|
80
|
+
for (const waiter of this.waiters.splice(0)) {
|
|
81
|
+
waiter.resolve({ value: undefined, done: true });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
fail(error) {
|
|
85
|
+
if (this.closed)
|
|
86
|
+
return;
|
|
87
|
+
this.failure = error;
|
|
88
|
+
this.closed = true;
|
|
89
|
+
this.items.length = 0;
|
|
90
|
+
for (const waiter of this.waiters.splice(0)) {
|
|
91
|
+
waiter.reject(error);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
[Symbol.asyncIterator]() {
|
|
95
|
+
return {
|
|
96
|
+
next: async () => {
|
|
97
|
+
if (this.items.length > 0)
|
|
98
|
+
return { value: this.items.shift(), done: false };
|
|
99
|
+
if (this.failure !== undefined)
|
|
100
|
+
throw this.failure;
|
|
101
|
+
if (this.closed)
|
|
102
|
+
return { value: undefined, done: true };
|
|
103
|
+
return new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
|
|
104
|
+
},
|
|
105
|
+
return: async () => {
|
|
106
|
+
this.close();
|
|
107
|
+
return { value: undefined, done: true };
|
|
108
|
+
},
|
|
109
|
+
throw: async (error) => {
|
|
110
|
+
this.fail(error);
|
|
111
|
+
throw error;
|
|
112
|
+
},
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
class ImmediateAgentRun {
|
|
117
|
+
immediateEvents;
|
|
118
|
+
constructor(immediateEvents) {
|
|
119
|
+
this.immediateEvents = immediateEvents;
|
|
120
|
+
}
|
|
121
|
+
get events() {
|
|
122
|
+
const events = this.immediateEvents;
|
|
123
|
+
return { [Symbol.asyncIterator]: async function* () { yield* events; } };
|
|
124
|
+
}
|
|
125
|
+
async stop() { }
|
|
126
|
+
async waitForExit() { return true; }
|
|
127
|
+
}
|
|
128
|
+
class SubprocessAgentRun {
|
|
129
|
+
child;
|
|
130
|
+
exitPromise;
|
|
131
|
+
stopGraceMs;
|
|
132
|
+
events;
|
|
133
|
+
stopping = false;
|
|
134
|
+
constructor(queue, child, exitPromise, stopGraceMs) {
|
|
135
|
+
this.child = child;
|
|
136
|
+
this.exitPromise = exitPromise;
|
|
137
|
+
this.stopGraceMs = stopGraceMs;
|
|
138
|
+
this.events = queue;
|
|
139
|
+
}
|
|
140
|
+
async stop() {
|
|
141
|
+
if (this.stopping || hasExited(this.child))
|
|
142
|
+
return this.exitPromise;
|
|
143
|
+
this.stopping = true;
|
|
144
|
+
this.child.kill('SIGTERM');
|
|
145
|
+
if (!(await this.waitForExit(this.stopGraceMs)) && !hasExited(this.child)) {
|
|
146
|
+
this.child.kill('SIGKILL');
|
|
147
|
+
}
|
|
148
|
+
await this.exitPromise;
|
|
149
|
+
}
|
|
150
|
+
async waitForExit(timeoutMs) {
|
|
151
|
+
if (timeoutMs === undefined) {
|
|
152
|
+
await this.exitPromise;
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
if (timeoutMs <= 0)
|
|
156
|
+
return hasExited(this.child);
|
|
157
|
+
return raceExit(this.exitPromise, timeoutMs);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
export class CLISubprocessAgent {
|
|
161
|
+
run(req) {
|
|
162
|
+
try {
|
|
163
|
+
const spec = this.buildProcessSpec(req);
|
|
164
|
+
const child = spawn(spec.command, spec.args, this.buildSpawnOptions(spec, req));
|
|
165
|
+
const queue = new AsyncEventQueue();
|
|
166
|
+
const exitPromise = this.bindProcess(req, child, queue, { sawError: false });
|
|
167
|
+
return new SubprocessAgentRun(queue, child, exitPromise, req.stopGraceMs ?? 500);
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
return new ImmediateAgentRun(this.mapSpawnError(error));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
mapSpawnError(error) {
|
|
174
|
+
return [buildCrashEvent(getErrorMessage(error))];
|
|
175
|
+
}
|
|
176
|
+
mapExitError(stderr, code, signal) {
|
|
177
|
+
return buildCrashEvent(buildExitMessage(stderr, code, signal), inferErrorCode(stderr));
|
|
178
|
+
}
|
|
179
|
+
buildSpawnOptions(spec, req) {
|
|
180
|
+
const cwd = this.cwdGuard ? this.cwdGuard(spec.cwd, req) : spec.cwd;
|
|
181
|
+
const env = this.envFilter ? this.envFilter(spec.env ?? process.env, req) : (spec.env ?? process.env);
|
|
182
|
+
return { cwd, env };
|
|
183
|
+
}
|
|
184
|
+
bindProcess(req, child, queue, state) {
|
|
185
|
+
const stderr = { text: '' };
|
|
186
|
+
this.bindStdout(req, child, queue, state);
|
|
187
|
+
this.bindStderr(child, stderr);
|
|
188
|
+
this.bindStdin(req, child, queue, state);
|
|
189
|
+
return new Promise((resolve) => {
|
|
190
|
+
let settled = false;
|
|
191
|
+
const finish = (events) => {
|
|
192
|
+
if (settled)
|
|
193
|
+
return;
|
|
194
|
+
settled = true;
|
|
195
|
+
this.pushEvents(queue, state, events);
|
|
196
|
+
queue.close();
|
|
197
|
+
resolve();
|
|
198
|
+
};
|
|
199
|
+
child.once('error', (error) => finish(this.mapSpawnError(error)));
|
|
200
|
+
child.once('close', (code, signal) => {
|
|
201
|
+
const events = code === 0 || state.sawError ? [] : [this.mapExitError(stderr.text, code, signal)];
|
|
202
|
+
finish(events);
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
bindStdout(req, child, queue, state) {
|
|
207
|
+
const stdout = child.stdout;
|
|
208
|
+
if (!stdout)
|
|
209
|
+
return;
|
|
210
|
+
const reader = createInterface({ input: stdout });
|
|
211
|
+
reader.on('line', (line) => this.pushEvents(queue, state, this.parseOutputLine(line, req)));
|
|
212
|
+
}
|
|
213
|
+
bindStderr(child, stderr) {
|
|
214
|
+
const stream = child.stderr;
|
|
215
|
+
if (!stream)
|
|
216
|
+
return;
|
|
217
|
+
const reader = createInterface({ input: stream });
|
|
218
|
+
reader.on('line', (line) => appendStderr(stderr, line));
|
|
219
|
+
}
|
|
220
|
+
bindStdin(req, child, queue, state) {
|
|
221
|
+
if (!this.writeStdin)
|
|
222
|
+
return;
|
|
223
|
+
void this.writeStdin(child, req).catch((error) => {
|
|
224
|
+
this.pushEvents(queue, state, this.mapSpawnError(error));
|
|
225
|
+
child.stdin?.destroy(error instanceof Error ? error : undefined);
|
|
226
|
+
if (!hasExited(child))
|
|
227
|
+
child.kill('SIGTERM');
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
parseOutputLine(line, req) {
|
|
231
|
+
try {
|
|
232
|
+
return this.mapOutput(JSON.parse(line), req).filter(isCLIEvent);
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
return [buildCrashEvent(getErrorMessage(error))];
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
pushEvents(queue, state, events) {
|
|
239
|
+
for (const event of events) {
|
|
240
|
+
state.sawError ||= event.type === 'error';
|
|
241
|
+
queue.push(event);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { CLISubprocessAgent } from './cli-subprocess.js';
|
|
3
|
+
/**
|
|
4
|
+
* Codex CLI 子进程允许透传的 env keys. wb-bot 也需要这份名单 (handleMessageViaWbRunner),
|
|
5
|
+
* 防止两边漂移. 单一 source of truth. 不要复制 keys 数组到别处.
|
|
6
|
+
*/
|
|
7
|
+
export const CODEX_PASSTHROUGH_KEYS = [
|
|
8
|
+
'OPENAI_API_KEY',
|
|
9
|
+
'OPENAI_BASE_URL',
|
|
10
|
+
'CODEX_HOME',
|
|
11
|
+
'CODEX_CONFIG_DIR',
|
|
12
|
+
'XDG_CONFIG_HOME',
|
|
13
|
+
'XDG_DATA_HOME',
|
|
14
|
+
'XDG_CACHE_HOME',
|
|
15
|
+
'PATH',
|
|
16
|
+
'HOME',
|
|
17
|
+
'USER',
|
|
18
|
+
'LOGNAME',
|
|
19
|
+
'SHELL',
|
|
20
|
+
'PWD',
|
|
21
|
+
'LANG',
|
|
22
|
+
'LC_ALL',
|
|
23
|
+
'TERM',
|
|
24
|
+
'TMPDIR',
|
|
25
|
+
'NO_COLOR',
|
|
26
|
+
'FORCE_COLOR',
|
|
27
|
+
'SSL_CERT_FILE',
|
|
28
|
+
'NODE_EXTRA_CA_CERTS',
|
|
29
|
+
];
|
|
30
|
+
const CAPABILITIES = {
|
|
31
|
+
type: 'cli',
|
|
32
|
+
input: { images: true, attachments: false },
|
|
33
|
+
output: { streaming: true, thinking: false, toolUse: true, citations: false },
|
|
34
|
+
context: { window: 200000, costClass: 'standard' },
|
|
35
|
+
skills: { code: 'A', review: 'A', plan: 'B', research: 'B', ops: 'B' },
|
|
36
|
+
tools: {
|
|
37
|
+
builtin: ['read_file', 'write_file', 'apply_patch', 'shell'],
|
|
38
|
+
canExtend: true,
|
|
39
|
+
},
|
|
40
|
+
session: { resumable: true, tokenKind: 'opaque' },
|
|
41
|
+
tokenRotation: 'static',
|
|
42
|
+
};
|
|
43
|
+
function asRecord(value) {
|
|
44
|
+
return value !== null && typeof value === 'object' ? value : null;
|
|
45
|
+
}
|
|
46
|
+
function readString(value) {
|
|
47
|
+
return typeof value === 'string' ? value : undefined;
|
|
48
|
+
}
|
|
49
|
+
function pickEnv(source, keys) {
|
|
50
|
+
const env = {};
|
|
51
|
+
for (const key of keys) {
|
|
52
|
+
const value = source[key];
|
|
53
|
+
if (value !== undefined)
|
|
54
|
+
env[key] = value;
|
|
55
|
+
}
|
|
56
|
+
return env;
|
|
57
|
+
}
|
|
58
|
+
function readUsage(payload) {
|
|
59
|
+
const usage = asRecord(payload['usage']);
|
|
60
|
+
return {
|
|
61
|
+
inputTokens: typeof usage?.['input_tokens'] === 'number' ? usage['input_tokens'] : undefined,
|
|
62
|
+
outputTokens: typeof usage?.['output_tokens'] === 'number' ? usage['output_tokens'] : undefined,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function joinTextParts(content) {
|
|
66
|
+
if (typeof content === 'string')
|
|
67
|
+
return content;
|
|
68
|
+
if (!Array.isArray(content))
|
|
69
|
+
return '';
|
|
70
|
+
return content
|
|
71
|
+
.map((item) => {
|
|
72
|
+
const record = asRecord(item);
|
|
73
|
+
return readString(record?.['text']) ?? readString(record?.['content']) ?? '';
|
|
74
|
+
})
|
|
75
|
+
.filter(Boolean)
|
|
76
|
+
.join('\n');
|
|
77
|
+
}
|
|
78
|
+
function mapItemEvent(eventType, payload) {
|
|
79
|
+
const item = asRecord(payload['item']);
|
|
80
|
+
if (!item)
|
|
81
|
+
return [];
|
|
82
|
+
const itemType = readString(item['type']);
|
|
83
|
+
if (eventType === 'item.started' && itemType === 'command_execution') {
|
|
84
|
+
return [{
|
|
85
|
+
type: 'tool_use',
|
|
86
|
+
id: readString(item['id']) ?? '',
|
|
87
|
+
name: 'shell',
|
|
88
|
+
input: { command: readString(item['command']) ?? '' },
|
|
89
|
+
}];
|
|
90
|
+
}
|
|
91
|
+
if (eventType === 'item.completed' && itemType === 'command_execution') {
|
|
92
|
+
const output = readString(item['aggregated_output']) ?? '';
|
|
93
|
+
const status = readString(item['status']) ?? '';
|
|
94
|
+
const exitCode = item['exit_code'];
|
|
95
|
+
return [{
|
|
96
|
+
type: 'tool_result',
|
|
97
|
+
id: readString(item['id']) ?? '',
|
|
98
|
+
output: output || `status=${status} exit_code=${typeof exitCode === 'number' ? exitCode : '-'}`,
|
|
99
|
+
isError: status === 'failed' || (typeof exitCode === 'number' && exitCode !== 0),
|
|
100
|
+
}];
|
|
101
|
+
}
|
|
102
|
+
// item 级 error 是 codex 的非致命告警 (模型元数据缺失、skill 描述被截断等), run 会照常继续;
|
|
103
|
+
// 当成 error 会让卡片提前进入失败态. 致命错误走顶层 error / turn.failed.
|
|
104
|
+
if (eventType === 'item.completed' && itemType === 'error')
|
|
105
|
+
return [];
|
|
106
|
+
if (eventType === 'item.completed' && itemType === 'agent_message') {
|
|
107
|
+
const text = readString(item['text']) ?? joinTextParts(item['content']);
|
|
108
|
+
return text ? [{ type: 'text', delta: text }] : [];
|
|
109
|
+
}
|
|
110
|
+
return [];
|
|
111
|
+
}
|
|
112
|
+
function inferRecoverable(message) {
|
|
113
|
+
const text = message.toLowerCase();
|
|
114
|
+
return text.includes('rate limit') || text.includes('network') || text.includes('timed out');
|
|
115
|
+
}
|
|
116
|
+
function inferErrorCode(message) {
|
|
117
|
+
const text = message.toLowerCase();
|
|
118
|
+
if (text.includes('401') || text.includes('unauthorized') || text.includes('auth'))
|
|
119
|
+
return 'auth';
|
|
120
|
+
if (text.includes('rate limit'))
|
|
121
|
+
return 'rate_limit';
|
|
122
|
+
if (text.includes('context'))
|
|
123
|
+
return 'context_length';
|
|
124
|
+
if (text.includes('network') || text.includes('connect') || text.includes('timeout'))
|
|
125
|
+
return 'network';
|
|
126
|
+
return 'crashed';
|
|
127
|
+
}
|
|
128
|
+
export function mapCodexStreamEvent(payload, req) {
|
|
129
|
+
const event = asRecord(payload);
|
|
130
|
+
if (!event)
|
|
131
|
+
return [];
|
|
132
|
+
const eventType = readString(event['type']) ?? '';
|
|
133
|
+
if (eventType === 'thread.started') {
|
|
134
|
+
const continuationToken = readString(event['thread_id']) ?? readString(event['session_id']);
|
|
135
|
+
return [{ type: 'system', continuationToken, cwd: req.cwd, model: req.model }];
|
|
136
|
+
}
|
|
137
|
+
if (eventType === 'turn.completed') {
|
|
138
|
+
const usage = readUsage(event);
|
|
139
|
+
return [
|
|
140
|
+
{
|
|
141
|
+
type: 'usage',
|
|
142
|
+
inputTokens: usage.inputTokens,
|
|
143
|
+
outputTokens: usage.outputTokens,
|
|
144
|
+
},
|
|
145
|
+
{ type: 'done', continuationToken: readString(event['thread_id']) ?? readString(event['session_id']) },
|
|
146
|
+
];
|
|
147
|
+
}
|
|
148
|
+
if (eventType === 'agent_message' || eventType === 'assistant_message') {
|
|
149
|
+
const text = readString(event['message']) ?? readString(event['text']) ?? '';
|
|
150
|
+
return text ? [{ type: 'text', delta: text }] : [];
|
|
151
|
+
}
|
|
152
|
+
if (eventType === 'message' || eventType === 'response.output_text.done') {
|
|
153
|
+
const text = readString(event['text']) ?? readString(event['delta']) ?? '';
|
|
154
|
+
return text ? [{ type: 'text', delta: text }] : [];
|
|
155
|
+
}
|
|
156
|
+
if (eventType === 'error' || eventType === 'turn.failed') {
|
|
157
|
+
const detail = readString(asRecord(event['error'])?.['message']) ?? readString(event['message']) ?? 'codex exec failed';
|
|
158
|
+
return [{ type: 'error', message: detail, code: inferErrorCode(detail), recoverable: inferRecoverable(detail) }];
|
|
159
|
+
}
|
|
160
|
+
const itemEvents = mapItemEvent(eventType, event);
|
|
161
|
+
if (itemEvents.length > 0)
|
|
162
|
+
return itemEvents;
|
|
163
|
+
const item = asRecord(event['item']);
|
|
164
|
+
const assistantText = item ? joinTextParts(item['content']) : '';
|
|
165
|
+
if (assistantText)
|
|
166
|
+
return [{ type: 'text', delta: assistantText }];
|
|
167
|
+
return [];
|
|
168
|
+
}
|
|
169
|
+
export class CodexAgent extends CLISubprocessAgent {
|
|
170
|
+
id = 'codex';
|
|
171
|
+
displayName = 'Codex';
|
|
172
|
+
availability;
|
|
173
|
+
capabilities;
|
|
174
|
+
run(req) {
|
|
175
|
+
const baseRun = super.run(req);
|
|
176
|
+
const prefixEvent = {
|
|
177
|
+
type: 'system',
|
|
178
|
+
continuationToken: req.continuationToken,
|
|
179
|
+
cwd: req.cwd,
|
|
180
|
+
model: req.model,
|
|
181
|
+
};
|
|
182
|
+
return {
|
|
183
|
+
events: {
|
|
184
|
+
async *[Symbol.asyncIterator]() {
|
|
185
|
+
yield prefixEvent;
|
|
186
|
+
for await (const event of baseRun.events) {
|
|
187
|
+
yield event;
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
stop: () => baseRun.stop(),
|
|
192
|
+
waitForExit: (timeoutMs) => baseRun.waitForExit(timeoutMs),
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
async isAvailable() {
|
|
196
|
+
this.availability ??= Promise.resolve(this.checkAvailability());
|
|
197
|
+
return this.availability;
|
|
198
|
+
}
|
|
199
|
+
async getCapabilities() {
|
|
200
|
+
this.capabilities ??= Promise.resolve(CAPABILITIES);
|
|
201
|
+
return this.capabilities;
|
|
202
|
+
}
|
|
203
|
+
buildProcessSpec(req) {
|
|
204
|
+
const args = req.continuationToken
|
|
205
|
+
? ['exec', 'resume', '--json', '--skip-git-repo-check', req.continuationToken, '-']
|
|
206
|
+
: ['exec', '--json', '--skip-git-repo-check', '-'];
|
|
207
|
+
if (req.model)
|
|
208
|
+
args.splice(req.continuationToken ? 3 : 2, 0, '--model', req.model);
|
|
209
|
+
// `--image <FILE>...` is variadic: keep it right after the subcommand so the
|
|
210
|
+
// following `--json` flag terminates it instead of swallowing the trailing `-`.
|
|
211
|
+
const images = req.images ?? [];
|
|
212
|
+
if (images.length > 0)
|
|
213
|
+
args.splice(req.continuationToken ? 2 : 1, 0, ...images.flatMap((path) => ['--image', path]));
|
|
214
|
+
return {
|
|
215
|
+
command: 'codex',
|
|
216
|
+
args,
|
|
217
|
+
cwd: req.cwd,
|
|
218
|
+
env: pickEnv(process.env, CODEX_PASSTHROUGH_KEYS),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
async writeStdin(child, req) {
|
|
222
|
+
child.stdin?.end(`${req.prompt}\n`);
|
|
223
|
+
}
|
|
224
|
+
mapOutput(payload, req) {
|
|
225
|
+
return mapCodexStreamEvent(payload, req);
|
|
226
|
+
}
|
|
227
|
+
checkAvailability() {
|
|
228
|
+
const result = spawnSync('codex', ['--version'], { encoding: 'utf8' });
|
|
229
|
+
return result.status === 0 && result.stdout.toLowerCase().includes('codex');
|
|
230
|
+
}
|
|
231
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { ClaudeCodeAgent } from './claude-code.js';
|
|
4
|
+
import { CodexAgent } from './codex.js';
|
|
5
|
+
function isCommandOnPath(command) {
|
|
6
|
+
const pathEnv = process.env['PATH'] ?? '';
|
|
7
|
+
const sep = process.platform === 'win32' ? ';' : ':';
|
|
8
|
+
const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
|
|
9
|
+
for (const dir of pathEnv.split(sep).filter(Boolean)) {
|
|
10
|
+
for (const ext of exts) {
|
|
11
|
+
if (existsSync(join(dir, command + ext)))
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
export class DefaultAgentRegistry {
|
|
18
|
+
entries = new Map();
|
|
19
|
+
constructor(initial = []) {
|
|
20
|
+
for (const entry of initial)
|
|
21
|
+
this.register(entry.agent, entry.command);
|
|
22
|
+
}
|
|
23
|
+
register(agent, command) {
|
|
24
|
+
this.entries.set(agent.id, { agent, command });
|
|
25
|
+
}
|
|
26
|
+
lookup(id) {
|
|
27
|
+
return this.entries.get(id)?.agent ?? null;
|
|
28
|
+
}
|
|
29
|
+
list() {
|
|
30
|
+
return Array.from(this.entries.values(), (entry) => entry.agent);
|
|
31
|
+
}
|
|
32
|
+
async isAvailable(id) {
|
|
33
|
+
const entry = this.entries.get(id);
|
|
34
|
+
if (!entry)
|
|
35
|
+
return null;
|
|
36
|
+
if (entry.command && !isCommandOnPath(entry.command))
|
|
37
|
+
return false;
|
|
38
|
+
return entry.agent.isAvailable();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export function createDefaultAgentRegistry() {
|
|
42
|
+
return new DefaultAgentRegistry([
|
|
43
|
+
{ agent: new ClaudeCodeAgent(), command: 'claude' },
|
|
44
|
+
{ agent: new CodexAgent(), command: 'codex' },
|
|
45
|
+
]);
|
|
46
|
+
}
|
|
47
|
+
export { isCommandOnPath };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { APPROVAL_GATE_ANCHORS } from './contracts.js';
|
|
2
|
+
export function deriveApprovalRiskLevel(records) {
|
|
3
|
+
for (const record of records) {
|
|
4
|
+
if (record.action !== 'other')
|
|
5
|
+
continue;
|
|
6
|
+
if (!record.resource.startsWith('approval-gate:'))
|
|
7
|
+
continue;
|
|
8
|
+
if (record.resource.includes(`anchor=${APPROVAL_GATE_ANCHORS.ENV_VAR_CHANGE}`))
|
|
9
|
+
return 'high';
|
|
10
|
+
if (record.resource.includes(`anchor=${APPROVAL_GATE_ANCHORS.EXTERNAL_DEP_UPGRADE}`))
|
|
11
|
+
return 'high';
|
|
12
|
+
if (record.resource.includes(`anchor=${APPROVAL_GATE_ANCHORS.WRITE_TO_MAIN_BRANCH}`))
|
|
13
|
+
return 'high';
|
|
14
|
+
}
|
|
15
|
+
return 'unknown';
|
|
16
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export const APPROVAL_GATE_ANCHORS = {
|
|
2
|
+
WRITE_TO_MAIN_BRANCH: 'writeToMainBranch',
|
|
3
|
+
ENV_VAR_CHANGE: 'envVarChange',
|
|
4
|
+
EXTERNAL_DEP_UPGRADE: 'externalDepUpgrade',
|
|
5
|
+
};
|
|
6
|
+
export const APPROVAL_GATE_APPROVER_POLICY = {
|
|
7
|
+
OWNER: 'owner',
|
|
8
|
+
OWNER_AND_CODE_OWNER: 'owner_and_code_owner',
|
|
9
|
+
};
|
|
10
|
+
export const APPROVAL_GATE_TIMEOUT_MS = {
|
|
11
|
+
writeToMainBranch: 10 * 60 * 1000,
|
|
12
|
+
envVarChange: 30 * 60 * 1000,
|
|
13
|
+
externalDepUpgrade: 60 * 60 * 1000,
|
|
14
|
+
};
|
|
15
|
+
export const APPROVAL_REQUEST_STATUS = {
|
|
16
|
+
PENDING_DISPATCH: 'pending_dispatch',
|
|
17
|
+
PENDING_APPROVAL: 'pending_approval',
|
|
18
|
+
APPROVED: 'approved',
|
|
19
|
+
DENIED: 'denied',
|
|
20
|
+
EXPIRED: 'expired',
|
|
21
|
+
FAILED_CLOSED: 'failed_closed',
|
|
22
|
+
};
|
|
23
|
+
export const APPROVAL_CARRIER = {
|
|
24
|
+
APPROVAL_APP: 'approval_app',
|
|
25
|
+
GROUP_CARD: 'group_card',
|
|
26
|
+
};
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { APPROVAL_GATE_ANCHORS, APPROVAL_GATE_APPROVER_POLICY, APPROVAL_GATE_TIMEOUT_MS, } from './contracts.js';
|
|
2
|
+
function asRecord(value) {
|
|
3
|
+
return value !== null && typeof value === 'object' ? value : null;
|
|
4
|
+
}
|
|
5
|
+
function readString(value) {
|
|
6
|
+
return typeof value === 'string' ? value : undefined;
|
|
7
|
+
}
|
|
8
|
+
function normalizeWhitespace(value) {
|
|
9
|
+
return value.replace(/\s+/g, ' ').trim();
|
|
10
|
+
}
|
|
11
|
+
function shellCommand(input) {
|
|
12
|
+
return normalizeWhitespace(readString(asRecord(input)?.['command']) ?? '');
|
|
13
|
+
}
|
|
14
|
+
function filePath(input) {
|
|
15
|
+
return normalizeWhitespace(readString(asRecord(input)?.['file_path']) ?? '');
|
|
16
|
+
}
|
|
17
|
+
function lower(value) {
|
|
18
|
+
return (value ?? '').toLowerCase();
|
|
19
|
+
}
|
|
20
|
+
function looksLikeMainBranchWrite(command) {
|
|
21
|
+
const normalized = lower(command);
|
|
22
|
+
if (!normalized.startsWith('git push'))
|
|
23
|
+
return false;
|
|
24
|
+
return [
|
|
25
|
+
/\bmain\b/,
|
|
26
|
+
/head:main\b/,
|
|
27
|
+
/refs\/heads\/main\b/,
|
|
28
|
+
/origin\/main\b/,
|
|
29
|
+
].some((pattern) => pattern.test(normalized));
|
|
30
|
+
}
|
|
31
|
+
function looksLikeEnvVarChange(toolName, input) {
|
|
32
|
+
if (toolName === 'Write' || toolName === 'Edit') {
|
|
33
|
+
const path = lower(filePath(input));
|
|
34
|
+
return /(^|\/)\.env(\.|$)|\.env$/.test(path);
|
|
35
|
+
}
|
|
36
|
+
if (toolName !== 'Bash')
|
|
37
|
+
return false;
|
|
38
|
+
const command = lower(shellCommand(input));
|
|
39
|
+
return /(^| )(export|unset) [a-z_][a-z0-9_]*=?/i.test(command)
|
|
40
|
+
|| /(^| )env [a-z_][a-z0-9_]*=/i.test(command);
|
|
41
|
+
}
|
|
42
|
+
function looksLikeDependencyManifest(path) {
|
|
43
|
+
return /(^|\/)(package\.json|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|uv\.lock|pyproject\.toml|requirements(\.[a-z0-9_-]+)?\.txt)$/i.test(path);
|
|
44
|
+
}
|
|
45
|
+
function looksLikeExternalDepUpgrade(toolName, input) {
|
|
46
|
+
if (toolName === 'Write' || toolName === 'Edit') {
|
|
47
|
+
return looksLikeDependencyManifest(lower(filePath(input)));
|
|
48
|
+
}
|
|
49
|
+
if (toolName !== 'Bash')
|
|
50
|
+
return false;
|
|
51
|
+
const command = lower(shellCommand(input));
|
|
52
|
+
return /(npm|pnpm|yarn|uv|pip) (install|add|update|upgrade)\b/.test(command);
|
|
53
|
+
}
|
|
54
|
+
function summarize(toolName, input) {
|
|
55
|
+
const record = asRecord(input) ?? {};
|
|
56
|
+
const command = readString(record['command']);
|
|
57
|
+
if (command)
|
|
58
|
+
return normalizeWhitespace(command).slice(0, 200);
|
|
59
|
+
const path = readString(record['file_path']) ?? readString(record['pattern']);
|
|
60
|
+
if (path)
|
|
61
|
+
return normalizeWhitespace(path).slice(0, 200);
|
|
62
|
+
return JSON.stringify(input).slice(0, 200);
|
|
63
|
+
}
|
|
64
|
+
function resource(toolName, input) {
|
|
65
|
+
const record = asRecord(input) ?? {};
|
|
66
|
+
const command = readString(record['command']);
|
|
67
|
+
if (command)
|
|
68
|
+
return normalizeWhitespace(command).slice(0, 500);
|
|
69
|
+
const path = readString(record['file_path']) ?? readString(record['pattern']);
|
|
70
|
+
if (path)
|
|
71
|
+
return normalizeWhitespace(path).slice(0, 500);
|
|
72
|
+
return `${toolName}:${JSON.stringify(input).slice(0, 400)}`;
|
|
73
|
+
}
|
|
74
|
+
export function matchApprovalGate(toolName, input) {
|
|
75
|
+
if (toolName === 'Bash') {
|
|
76
|
+
const command = shellCommand(input);
|
|
77
|
+
if (command && looksLikeMainBranchWrite(command)) {
|
|
78
|
+
return {
|
|
79
|
+
anchor: APPROVAL_GATE_ANCHORS.WRITE_TO_MAIN_BRANCH,
|
|
80
|
+
approverPolicy: APPROVAL_GATE_APPROVER_POLICY.OWNER_AND_CODE_OWNER,
|
|
81
|
+
timeoutMs: APPROVAL_GATE_TIMEOUT_MS.writeToMainBranch,
|
|
82
|
+
toolName,
|
|
83
|
+
toolInput: input,
|
|
84
|
+
summary: summarize(toolName, input),
|
|
85
|
+
resource: resource(toolName, input),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (looksLikeEnvVarChange(toolName, input)) {
|
|
90
|
+
return {
|
|
91
|
+
anchor: APPROVAL_GATE_ANCHORS.ENV_VAR_CHANGE,
|
|
92
|
+
approverPolicy: APPROVAL_GATE_APPROVER_POLICY.OWNER,
|
|
93
|
+
timeoutMs: APPROVAL_GATE_TIMEOUT_MS.envVarChange,
|
|
94
|
+
toolName,
|
|
95
|
+
toolInput: input,
|
|
96
|
+
summary: summarize(toolName, input),
|
|
97
|
+
resource: resource(toolName, input),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
if (looksLikeExternalDepUpgrade(toolName, input)) {
|
|
101
|
+
return {
|
|
102
|
+
anchor: APPROVAL_GATE_ANCHORS.EXTERNAL_DEP_UPGRADE,
|
|
103
|
+
approverPolicy: APPROVAL_GATE_APPROVER_POLICY.OWNER,
|
|
104
|
+
timeoutMs: APPROVAL_GATE_TIMEOUT_MS.externalDepUpgrade,
|
|
105
|
+
toolName,
|
|
106
|
+
toolInput: input,
|
|
107
|
+
summary: summarize(toolName, input),
|
|
108
|
+
resource: resource(toolName, input),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|