agent-bridge-service 0.0.0-stage → 0.2.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/CHANGELOG.md +200 -0
- package/LICENSE +21 -0
- package/README.md +519 -2
- package/README.zh-CN.md +496 -0
- package/assets/agent-icons/claude-code.svg +1 -0
- package/assets/agent-icons/codebuddy-cli.svg +35 -0
- package/assets/agent-icons/codex.svg +1 -0
- package/assets/agent-icons/ds-harness.svg +1 -0
- package/assets/agent-icons/gemini.svg +1 -0
- package/assets/agent-icons/grok-cli.svg +1 -0
- package/assets/agent-icons/kimi-code.svg +1 -0
- package/assets/agent-icons/mimo-code.svg +1 -0
- package/assets/agent-icons/minimax-code.svg +1 -0
- package/assets/agent-icons/opencode.svg +1 -0
- package/assets/agent-icons/qoder-cli-light.svg +1 -0
- package/assets/agent-icons/qoder-cli.svg +1 -0
- package/assets/agent-icons/trae-cli.svg +1 -0
- package/dist/adapters/agent-adapters.js +437 -0
- package/dist/adapters/agent-logos.js +40 -0
- package/dist/adapters/win-exec.js +25 -0
- package/dist/app/bootstrap.js +101 -0
- package/dist/app/service-gate.js +43 -0
- package/dist/app/session-log.js +7 -0
- package/dist/app/session.js +107 -0
- package/dist/app/task-dispatch.js +81 -0
- package/dist/cli/dispatch.js +42 -0
- package/dist/cli/flags.js +40 -0
- package/dist/cli/help.js +36 -0
- package/dist/cli/hold.js +15 -0
- package/dist/cli/meta.js +16 -0
- package/dist/cli/render.js +53 -0
- package/dist/cli.js +26 -0
- package/dist/commands/connect.js +20 -0
- package/dist/commands/daemon.js +13 -0
- package/dist/commands/logout.js +18 -0
- package/dist/commands/serve.js +65 -0
- package/dist/commands/services.js +89 -0
- package/dist/commands/status.js +16 -0
- package/dist/core/emitter.js +119 -0
- package/dist/core/errors.js +89 -0
- package/dist/core/redact.js +34 -0
- package/dist/core/scan.js +55 -0
- package/dist/core/task-supervisor.js +277 -0
- package/dist/infra/audit.js +54 -0
- package/dist/infra/auth.js +174 -0
- package/dist/infra/config.js +191 -0
- package/dist/infra/git.js +141 -0
- package/dist/infra/service-token.js +198 -0
- package/dist/protocol.js +144 -0
- package/dist/runner.js +37 -0
- package/dist/transport/bridge-client.js +139 -0
- package/dist/transport/control-plane.js +482 -0
- package/dist/transport/outbox.js +95 -0
- package/package.json +80 -4
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本地配置:`~/.agent-bridge/config.toml`(Windows 为 `%APPDATA%\agent-bridge\config.toml`)
|
|
3
|
+
*
|
|
4
|
+
* 安全:文件权限 0600(仅当前用户可读写);终端输出**永不打印** device_token 明文,
|
|
5
|
+
* 只显示尾号与设备 id。
|
|
6
|
+
*/
|
|
7
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { dirname, join, resolve } from 'node:path';
|
|
10
|
+
import { parse as parseToml, stringify as stringifyToml } from 'smol-toml';
|
|
11
|
+
/**
|
|
12
|
+
* 并发上限解析:`AGENT_BRIDGE_MAX_TASKS`(临时/CI 覆盖)> config.toml 的 `max_tasks` > 默认 3。
|
|
13
|
+
* 夹在 1~32:0 或负数会让 bridge 一个任务都跑不了,过大则回到"并发打爆开发机"的老问题。
|
|
14
|
+
*/
|
|
15
|
+
export const DEFAULT_MAX_TASKS = 3;
|
|
16
|
+
const MAX_TASKS_CEILING = 32;
|
|
17
|
+
export function resolveMaxTasks(fromConfig) {
|
|
18
|
+
const envRaw = Number(process.env['AGENT_BRIDGE_MAX_TASKS'] ?? '');
|
|
19
|
+
const chosen = Number.isFinite(envRaw) && envRaw > 0 ? envRaw : fromConfig;
|
|
20
|
+
if (!Number.isFinite(chosen ?? NaN) || (chosen ?? 0) <= 0)
|
|
21
|
+
return DEFAULT_MAX_TASKS;
|
|
22
|
+
return Math.min(MAX_TASKS_CEILING, Math.max(1, Math.floor(chosen)));
|
|
23
|
+
}
|
|
24
|
+
/** 队列上限:默认 32,夹在 0~1024(0 = 不允许排队,超限直接失败) */
|
|
25
|
+
export const DEFAULT_MAX_QUEUED = 32;
|
|
26
|
+
const MAX_QUEUED_CEILING = 1024;
|
|
27
|
+
export function resolveMaxQueued(fromConfig) {
|
|
28
|
+
const rawEnv = process.env['AGENT_BRIDGE_MAX_QUEUE'];
|
|
29
|
+
const envValue = rawEnv === undefined || rawEnv.trim() === '' ? undefined : Number(rawEnv);
|
|
30
|
+
const chosen = envValue !== undefined && Number.isFinite(envValue) && envValue >= 0 ? envValue : fromConfig;
|
|
31
|
+
if (chosen === undefined || !Number.isFinite(chosen) || chosen < 0)
|
|
32
|
+
return DEFAULT_MAX_QUEUED;
|
|
33
|
+
return Math.min(MAX_QUEUED_CEILING, Math.floor(chosen));
|
|
34
|
+
}
|
|
35
|
+
/** diff 上限:默认 256 KB,夹在 1 KB ~ 8 MB(人工审核看不了几 MB,也别让报文失控) */
|
|
36
|
+
export const DEFAULT_DIFF_MAX_BYTES = 256 * 1024;
|
|
37
|
+
const DIFF_MIN_BYTES = 1024;
|
|
38
|
+
const DIFF_MAX_CEILING = 8 * 1024 * 1024;
|
|
39
|
+
/** 解析顺序:`AGENT_BRIDGE_DIFF_MAX_BYTES` > config.toml 的 `diff_max_bytes` > 默认 256 KB */
|
|
40
|
+
export function resolveDiffMaxBytes(fromConfig) {
|
|
41
|
+
const rawEnv = process.env['AGENT_BRIDGE_DIFF_MAX_BYTES'];
|
|
42
|
+
const envValue = rawEnv === undefined || rawEnv.trim() === '' ? undefined : Number(rawEnv);
|
|
43
|
+
const chosen = envValue !== undefined && Number.isFinite(envValue) && envValue > 0 ? envValue : fromConfig;
|
|
44
|
+
if (chosen === undefined || !Number.isFinite(chosen) || chosen <= 0)
|
|
45
|
+
return DEFAULT_DIFF_MAX_BYTES;
|
|
46
|
+
return Math.min(DIFF_MAX_CEILING, Math.max(DIFF_MIN_BYTES, Math.floor(chosen)));
|
|
47
|
+
}
|
|
48
|
+
/** 控制面默认端口(显式写在配置里即可改;端口 0 = 由系统分配) */
|
|
49
|
+
export const DEFAULT_CONTROL_PLANE_PORT = 8787;
|
|
50
|
+
/** 控制面只允许绑回环:非回环一律回落,不报错也不放行(护栏另有一道硬校验) */
|
|
51
|
+
const LOOPBACK_HOSTS = ['127.0.0.1', '::1', 'localhost'];
|
|
52
|
+
/**
|
|
53
|
+
* 控制面设置解析:`AGENT_BRIDGE_CONTROL_PLANE`(1/0,CI 临时开)> config.toml 的 `[control_plane]` > 默认(**关闭**)。
|
|
54
|
+
*
|
|
55
|
+
* 默认关闭是红线:不开就一个端口都不监听,"零入站"卖点不受影响。
|
|
56
|
+
* host 只允许回环值,其它值静默回落 127.0.0.1。
|
|
57
|
+
*/
|
|
58
|
+
export function resolveControlPlane(fromConfig) {
|
|
59
|
+
const envOn = process.env['AGENT_BRIDGE_CONTROL_PLANE'];
|
|
60
|
+
const envEnabled = envOn === '1' || envOn === 'true' ? true : envOn === '0' || envOn === 'false' ? false : undefined;
|
|
61
|
+
const rawHost = (fromConfig?.host ?? '').trim();
|
|
62
|
+
const host = LOOPBACK_HOSTS.includes(rawHost) ? rawHost : '127.0.0.1';
|
|
63
|
+
const rawPort = Number(fromConfig?.port ?? '');
|
|
64
|
+
const envPort = Number(process.env['AGENT_BRIDGE_CONTROL_PORT'] ?? '');
|
|
65
|
+
const port = Number.isFinite(envPort) && envPort >= 0
|
|
66
|
+
? Math.floor(envPort)
|
|
67
|
+
: Number.isFinite(rawPort) && rawPort >= 0
|
|
68
|
+
? Math.floor(rawPort)
|
|
69
|
+
: DEFAULT_CONTROL_PLANE_PORT;
|
|
70
|
+
return {
|
|
71
|
+
enabled: envEnabled ?? fromConfig?.enabled === true,
|
|
72
|
+
host,
|
|
73
|
+
port,
|
|
74
|
+
// 默认必须带令牌:本机控制面一旦免鉴权,等于给机器上任何程序下发任务的权限
|
|
75
|
+
requireToken: fromConfig?.requireToken !== false,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** 白名单条目规范化:`resolve()` 成绝对路径、丢弃空项、去重;空数组等价于「未配置」。
|
|
79
|
+
* 配置里写相对路径(如 `"./"`)时以启动 bridge 时的 cwd 为基准 —— 规范化一次,避免每次任务都算。
|
|
80
|
+
*/
|
|
81
|
+
export function normalizeAllowedCwd(value) {
|
|
82
|
+
if (!Array.isArray(value))
|
|
83
|
+
return undefined;
|
|
84
|
+
const dirs = value
|
|
85
|
+
.filter((v) => typeof v === 'string' && v.trim().length > 0)
|
|
86
|
+
.map((v) => resolve(v.trim()));
|
|
87
|
+
return dirs.length ? [...new Set(dirs)] : undefined;
|
|
88
|
+
}
|
|
89
|
+
/** 本地状态目录(`~/.agent-bridge/`)。config.toml / services.toml / audit.jsonl 都在这里 */
|
|
90
|
+
export function stateDir() {
|
|
91
|
+
return dirname(configPath());
|
|
92
|
+
}
|
|
93
|
+
export function configPath() {
|
|
94
|
+
if (process.env.AGENT_BRIDGE_CONFIG)
|
|
95
|
+
return process.env.AGENT_BRIDGE_CONFIG;
|
|
96
|
+
// 三处口径必须一致(README / CHANGELOG / 本文件):目录名统一 `.agent-bridge`
|
|
97
|
+
const base = process.platform === 'win32'
|
|
98
|
+
? (process.env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'))
|
|
99
|
+
: homedir();
|
|
100
|
+
return join(base, '.agent-bridge', 'config.toml');
|
|
101
|
+
}
|
|
102
|
+
export function loadConfig() {
|
|
103
|
+
const file = configPath();
|
|
104
|
+
if (!existsSync(file))
|
|
105
|
+
return null;
|
|
106
|
+
try {
|
|
107
|
+
const raw = parseToml(readFileSync(file, 'utf8'));
|
|
108
|
+
if (!raw['platformUrl'] || !raw['deviceId'])
|
|
109
|
+
return null;
|
|
110
|
+
// 白名单:文档口径是 snake_case(allowed_cwd),同时兼容早期手写的 camelCase
|
|
111
|
+
const allowedCwd = normalizeAllowedCwd(raw['allowed_cwd'] ?? raw['allowedCwd']);
|
|
112
|
+
const maxTasksRaw = Number(raw['max_tasks'] ?? raw['maxTasks'] ?? '');
|
|
113
|
+
const maxTasks = Number.isFinite(maxTasksRaw) && maxTasksRaw > 0 ? Math.floor(maxTasksRaw) : undefined;
|
|
114
|
+
const maxQueuedRaw = Number(raw['max_queue'] ?? raw['maxQueued'] ?? '');
|
|
115
|
+
const maxQueued = Number.isFinite(maxQueuedRaw) && maxQueuedRaw >= 0 ? Math.floor(maxQueuedRaw) : undefined;
|
|
116
|
+
const diffRaw = Number(raw['diff_max_bytes'] ?? raw['diffMaxBytes'] ?? '');
|
|
117
|
+
const diffMaxBytes = Number.isFinite(diffRaw) && diffRaw > 0 ? Math.floor(diffRaw) : undefined;
|
|
118
|
+
const diffDefault = raw['diff_default'] === true || raw['diffDefault'] === true;
|
|
119
|
+
const requireServiceToken = raw['require_service_token'] === true || raw['requireServiceToken'] === true;
|
|
120
|
+
// 控制面:[control_plane] 表;也兼容 `control_plane_enabled = true` 这种扁平写法
|
|
121
|
+
const cpRaw = (raw['control_plane'] ?? {});
|
|
122
|
+
const cpEnabled = cpRaw['enabled'] === true || raw['control_plane_enabled'] === true;
|
|
123
|
+
const controlPlane = {
|
|
124
|
+
enabled: cpEnabled,
|
|
125
|
+
host: typeof cpRaw['host'] === 'string' ? cpRaw['host'] : undefined,
|
|
126
|
+
port: Number.isFinite(Number(cpRaw['port'])) ? Math.floor(Number(cpRaw['port'])) : undefined,
|
|
127
|
+
requireToken: cpRaw['require_token'] !== false,
|
|
128
|
+
};
|
|
129
|
+
return {
|
|
130
|
+
...raw,
|
|
131
|
+
allowedCwd,
|
|
132
|
+
maxTasks,
|
|
133
|
+
maxQueued,
|
|
134
|
+
diffMaxBytes,
|
|
135
|
+
diffDefault,
|
|
136
|
+
requireServiceToken,
|
|
137
|
+
controlPlane,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
export function saveConfig(cfg) {
|
|
145
|
+
const file = configPath();
|
|
146
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
147
|
+
// 显式构造输出对象:避免写入 undefined 字段,且白名单统一落 snake_case(与 README 一致)
|
|
148
|
+
const out = {
|
|
149
|
+
platformUrl: cfg.platformUrl,
|
|
150
|
+
deviceId: cfg.deviceId,
|
|
151
|
+
deviceToken: cfg.deviceToken,
|
|
152
|
+
};
|
|
153
|
+
if (cfg.refreshToken)
|
|
154
|
+
out['refreshToken'] = cfg.refreshToken;
|
|
155
|
+
if (cfg.allowedCwd?.length)
|
|
156
|
+
out['allowed_cwd'] = cfg.allowedCwd;
|
|
157
|
+
if (cfg.maxTasks)
|
|
158
|
+
out['max_tasks'] = cfg.maxTasks;
|
|
159
|
+
if (cfg.maxQueued !== undefined)
|
|
160
|
+
out['max_queue'] = cfg.maxQueued;
|
|
161
|
+
if (cfg.diffMaxBytes)
|
|
162
|
+
out['diff_max_bytes'] = cfg.diffMaxBytes;
|
|
163
|
+
if (cfg.diffDefault)
|
|
164
|
+
out['diff_default'] = true;
|
|
165
|
+
if (cfg.requireServiceToken)
|
|
166
|
+
out['require_service_token'] = true;
|
|
167
|
+
if (cfg.label)
|
|
168
|
+
out['label'] = cfg.label;
|
|
169
|
+
if (cfg.boundAt)
|
|
170
|
+
out['boundAt'] = cfg.boundAt;
|
|
171
|
+
const body = stringifyToml(out);
|
|
172
|
+
writeFileSync(file, `${body}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
173
|
+
try {
|
|
174
|
+
chmodSync(file, 0o600);
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
// Windows 上 chmod 只改只读位;文件仍在用户目录内,属可接受范围
|
|
178
|
+
}
|
|
179
|
+
return file;
|
|
180
|
+
}
|
|
181
|
+
export function clearConfig() {
|
|
182
|
+
const file = configPath();
|
|
183
|
+
if (!existsSync(file))
|
|
184
|
+
return false;
|
|
185
|
+
writeFileSync(file, '', { encoding: 'utf8', mode: 0o600 });
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
/** 只回尾号,用于终端展示 */
|
|
189
|
+
export function tokenTail(token) {
|
|
190
|
+
return token.length <= 8 ? '****' : `…${token.slice(-6)}`;
|
|
191
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工作区差异捕获(P0-6)
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一块:diff 是"任务产物"级别的通用能力 —— 人工审核、变更清单、未来的隔离工作区
|
|
5
|
+
* (prepare_workspace)都要用同一份实现。放在 runner 里只会变成一堆内联 git 调用,且无法单测。
|
|
6
|
+
*
|
|
7
|
+
* 三条硬边界:
|
|
8
|
+
* 1. 非 git 目录 → 返回空结果,**不报错**(平台不该因为用户没用 git 就看到任务失败);
|
|
9
|
+
* 2. 实际上只读:未跟踪文件先 `git add -N` 才能进 diff,取完立刻 `git reset -q -- <paths>`
|
|
10
|
+
* 把 intent-to-add 还原掉,索引不留副作用(失败也在 finally 里还原);
|
|
11
|
+
* 3. 永不经过 shell:一律 `spawnSync('git', [...])` 参数数组;任何异常都降级成空 diff。
|
|
12
|
+
*/
|
|
13
|
+
import { spawnSync } from 'node:child_process';
|
|
14
|
+
/** diff 文本上限(字节):人工审核看不了几 MB,超了截断并置 truncated */
|
|
15
|
+
export const DEFAULT_DIFF_MAX_BYTES = 256 * 1024;
|
|
16
|
+
/** changedFiles 上限(条):清单要完整可见,但也要防极端仓库把报文撑爆 */
|
|
17
|
+
export const DEFAULT_MAX_CHANGED_FILES = 500;
|
|
18
|
+
/** 唯一 git 调用入口:参数数组、无 shell、超时即杀、永不抛异常 */
|
|
19
|
+
function git(cwd, args, timeoutMs) {
|
|
20
|
+
try {
|
|
21
|
+
const r = spawnSync('git', ['-C', cwd, ...args], {
|
|
22
|
+
encoding: 'utf8',
|
|
23
|
+
timeout: timeoutMs,
|
|
24
|
+
windowsHide: true,
|
|
25
|
+
// 输出可能很大(大仓库 diff),但受 diff_max_bytes 约束;这里给 32MB 兜底
|
|
26
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
27
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
28
|
+
});
|
|
29
|
+
if (r.error)
|
|
30
|
+
return { ok: false, stdout: '', timedOut: false };
|
|
31
|
+
if (r.signal || r.status === null)
|
|
32
|
+
return { ok: false, stdout: r.stdout ?? '', timedOut: true };
|
|
33
|
+
return { ok: r.status === 0, stdout: r.stdout ?? '', timedOut: false };
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return { ok: false, stdout: '', timedOut: false };
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export function isGitWorkTree(cwd, timeoutMs = 5000) {
|
|
40
|
+
const r = git(cwd, ['rev-parse', '--is-inside-work-tree'], timeoutMs);
|
|
41
|
+
return r.ok && r.stdout.trim() === 'true';
|
|
42
|
+
}
|
|
43
|
+
/** 未跟踪(且未被 .gitignore 排除)的文件清单,NUL 分隔,空格路径也安全 */
|
|
44
|
+
function listUntracked(cwd, timeoutMs) {
|
|
45
|
+
const r = git(cwd, ['ls-files', '--others', '--exclude-standard', '-z'], timeoutMs);
|
|
46
|
+
if (!r.ok)
|
|
47
|
+
return [];
|
|
48
|
+
return r.stdout.split('\0').map((s) => s.trim()).filter(Boolean);
|
|
49
|
+
}
|
|
50
|
+
function chunk(items, size) {
|
|
51
|
+
const out = [];
|
|
52
|
+
for (let i = 0; i < items.length; i += size)
|
|
53
|
+
out.push(items.slice(i, i + size));
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* 按**行边界**截断,保证截断后仍是合法 unified diff 的前缀(不切半行、不切多字节字符)。
|
|
58
|
+
* 单行就超过上限时退化为按码点切(复用 protocol 的 chunkLog,避免重复实现"不切断多字节")。
|
|
59
|
+
*/
|
|
60
|
+
export function truncateDiff(text, maxBytes) {
|
|
61
|
+
if (Buffer.byteLength(text, 'utf8') <= maxBytes)
|
|
62
|
+
return { text, truncated: false };
|
|
63
|
+
const lines = text.split('\n');
|
|
64
|
+
const kept = [];
|
|
65
|
+
let used = 0;
|
|
66
|
+
for (const line of lines) {
|
|
67
|
+
const size = Buffer.byteLength(line, 'utf8') + 1;
|
|
68
|
+
if (used + size > maxBytes)
|
|
69
|
+
break;
|
|
70
|
+
kept.push(line);
|
|
71
|
+
used += size;
|
|
72
|
+
}
|
|
73
|
+
if (kept.length === 0) {
|
|
74
|
+
const first = lines[0] ?? '';
|
|
75
|
+
const head = chunkLogHead(first, maxBytes);
|
|
76
|
+
return { text: head, truncated: true };
|
|
77
|
+
}
|
|
78
|
+
return { text: `${kept.join('\n')}\n`, truncated: true };
|
|
79
|
+
}
|
|
80
|
+
/** 单行的兜底截断:按码点累加,绝不切断多字节字符 */
|
|
81
|
+
function chunkLogHead(line, maxBytes) {
|
|
82
|
+
let buf = '';
|
|
83
|
+
for (const ch of line) {
|
|
84
|
+
const next = buf + ch;
|
|
85
|
+
if (Buffer.byteLength(next, 'utf8') > maxBytes)
|
|
86
|
+
break;
|
|
87
|
+
buf = next;
|
|
88
|
+
}
|
|
89
|
+
return buf;
|
|
90
|
+
}
|
|
91
|
+
function emptyCapture(reason) {
|
|
92
|
+
return { diff: '', changedFiles: [], truncated: false, reason };
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* 捕获 `cwd` 下的工作区差异。
|
|
96
|
+
*
|
|
97
|
+
* 调用方(runner)只在任务终态调用一次;本函数对异常零容忍 —— 任何失败都返回空 diff,
|
|
98
|
+
* 绝不改变任务本身的终态。
|
|
99
|
+
*/
|
|
100
|
+
export function captureWorktreeDiff(cwd, opts = {}) {
|
|
101
|
+
const maxBytes = opts.maxBytes && opts.maxBytes > 0 ? Math.floor(opts.maxBytes) : DEFAULT_DIFF_MAX_BYTES;
|
|
102
|
+
const maxFiles = opts.maxFiles && opts.maxFiles > 0 ? Math.floor(opts.maxFiles) : DEFAULT_MAX_CHANGED_FILES;
|
|
103
|
+
const t = opts.timeoutMs && opts.timeoutMs > 0 ? Math.floor(opts.timeoutMs) : 8000;
|
|
104
|
+
if (!isGitWorkTree(cwd, t))
|
|
105
|
+
return emptyCapture('not-a-git-repo');
|
|
106
|
+
const untracked = listUntracked(cwd, t);
|
|
107
|
+
// 已 add -N 成功的路径,finally 里要逐个还原
|
|
108
|
+
const staged = [];
|
|
109
|
+
try {
|
|
110
|
+
if (untracked.length > 0) {
|
|
111
|
+
for (const batch of chunk(untracked, 64)) {
|
|
112
|
+
const r = git(cwd, ['add', '-N', '--', ...batch], Math.max(t, 15_000));
|
|
113
|
+
if (r.ok)
|
|
114
|
+
staged.push(...batch);
|
|
115
|
+
else if (r.timedOut)
|
|
116
|
+
return emptyCapture('timeout');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const diffRes = git(cwd, ['diff', '--no-color'], Math.max(t, 30_000));
|
|
120
|
+
if (diffRes.timedOut)
|
|
121
|
+
return emptyCapture('timeout');
|
|
122
|
+
if (!diffRes.ok)
|
|
123
|
+
return emptyCapture('git-error');
|
|
124
|
+
const names = git(cwd, ['diff', '--name-only'], Math.max(t, 15_000)).stdout
|
|
125
|
+
.split('\n')
|
|
126
|
+
.map((s) => s.trim())
|
|
127
|
+
.filter(Boolean);
|
|
128
|
+
const changedFiles = [...new Set(names)].slice(0, maxFiles);
|
|
129
|
+
const cut = truncateDiff(diffRes.stdout, maxBytes);
|
|
130
|
+
return { diff: cut.text, changedFiles, truncated: cut.truncated };
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
return emptyCapture('git-error');
|
|
134
|
+
}
|
|
135
|
+
finally {
|
|
136
|
+
// 还原 intent-to-add:只 reset 我们刚加进去、且本来就是未跟踪的路径(不影响用户已暂存的内容)
|
|
137
|
+
for (const batch of chunk(staged, 64)) {
|
|
138
|
+
git(cwd, ['reset', '-q', '--', ...batch], Math.max(t, 15_000));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scoped service token(P0-8:服务间调用身份)
|
|
3
|
+
*
|
|
4
|
+
* 定位:给**任何外部系统**(编排平台后端、CI、IDE 插件、本地脚本)一个标准的服务身份 ——
|
|
5
|
+
* 最小权限(scope)、可轮换、可吊销、带审计。不是为某一个平台做的单点功能。
|
|
6
|
+
*
|
|
7
|
+
* 形态:`abs_<kid>_<secret>`
|
|
8
|
+
* - `kid`:8 位十六进制,用于定位记录并支持**轮换宽限期**(新旧并存);
|
|
9
|
+
* - `secret`:32 字节 base64url 随机串,本地**只存 SHA-256**,比对用 `timingSafeEqual`。
|
|
10
|
+
*
|
|
11
|
+
* 兼容策略(重要):`require_service_token` 默认 false —— 本地没登记任何令牌时,
|
|
12
|
+
* 平台不带令牌也能跑(v1 行为零破坏);但**只要报文带了令牌就必须校验通过**,
|
|
13
|
+
* 不存在"带了也跳过"的口子。
|
|
14
|
+
*/
|
|
15
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
16
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
17
|
+
import { dirname, join } from 'node:path';
|
|
18
|
+
import { parse as parseToml, stringify as stringifyToml } from 'smol-toml';
|
|
19
|
+
import { stateDir, tokenTail } from './config.js';
|
|
20
|
+
/** 受控 scope 集合(新增 scope = 新增能力,必须同步文档) */
|
|
21
|
+
export const SERVICE_SCOPES = ['task:create', 'task:cancel', 'task:read', 'device:read'];
|
|
22
|
+
const TOKEN_PREFIX = 'abs';
|
|
23
|
+
const SECRET_BYTES = 32;
|
|
24
|
+
const KID_HEX = 8;
|
|
25
|
+
const ID_HEX = 6;
|
|
26
|
+
export function servicesPath() {
|
|
27
|
+
return join(stateDir(), 'services.toml');
|
|
28
|
+
}
|
|
29
|
+
export function loadServices() {
|
|
30
|
+
const file = servicesPath();
|
|
31
|
+
if (!existsSync(file))
|
|
32
|
+
return [];
|
|
33
|
+
try {
|
|
34
|
+
const raw = parseToml(readFileSync(file, 'utf8'));
|
|
35
|
+
if (!Array.isArray(raw.services))
|
|
36
|
+
return [];
|
|
37
|
+
return raw.services.filter((s) => typeof s?.id === 'string' && typeof s?.sha256 === 'string');
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function saveServices(list) {
|
|
44
|
+
const file = servicesPath();
|
|
45
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
46
|
+
writeFileSync(file, `${stringifyToml({ services: list })}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
47
|
+
try {
|
|
48
|
+
chmodSync(file, 0o600);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
// Windows 上 chmod 语义有限;文件在用户目录内,可接受
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 随机串一律用 **hex**(不能用 base64url):base64url 字母表里含 `_`,
|
|
56
|
+
* 而 `_` 是令牌的分隔符,会让 `abs_<kid>_<secret>` 解析错位。
|
|
57
|
+
*/
|
|
58
|
+
function hex(bytes) {
|
|
59
|
+
return randomBytes(bytes).toString('hex');
|
|
60
|
+
}
|
|
61
|
+
function sha256Hex(secret) {
|
|
62
|
+
return createHash('sha256').update(secret, 'utf8').digest('hex');
|
|
63
|
+
}
|
|
64
|
+
/** 归一化 scope:去重、只保留受控集合内的项;空集合视为 `task:create` */
|
|
65
|
+
export function normalizeScopes(input) {
|
|
66
|
+
const cleaned = (input ?? [])
|
|
67
|
+
.map((s) => s.trim())
|
|
68
|
+
.filter((s) => SERVICE_SCOPES.includes(s));
|
|
69
|
+
const uniq = [...new Set(cleaned)];
|
|
70
|
+
return uniq.length > 0 ? uniq : ['task:create'];
|
|
71
|
+
}
|
|
72
|
+
export function issueServiceToken(opts) {
|
|
73
|
+
const kid = hex(KID_HEX / 2);
|
|
74
|
+
const secret = hex(SECRET_BYTES);
|
|
75
|
+
const now = new Date();
|
|
76
|
+
const record = {
|
|
77
|
+
id: `svc_${hex(ID_HEX / 2)}`,
|
|
78
|
+
kid,
|
|
79
|
+
label: opts.label.trim().slice(0, 64) || 'service',
|
|
80
|
+
scopes: normalizeScopes(opts.scopes),
|
|
81
|
+
sha256: sha256Hex(secret),
|
|
82
|
+
createdAt: now.toISOString(),
|
|
83
|
+
...(opts.ttlDays && opts.ttlDays > 0
|
|
84
|
+
? { expiresAt: new Date(now.getTime() + opts.ttlDays * 86_400_000).toISOString() }
|
|
85
|
+
: {}),
|
|
86
|
+
...(opts.rotatedFrom ? { rotatedFrom: opts.rotatedFrom } : {}),
|
|
87
|
+
};
|
|
88
|
+
const list = loadServices();
|
|
89
|
+
list.push(record);
|
|
90
|
+
saveServices(list);
|
|
91
|
+
return { record, token: `${TOKEN_PREFIX}_${kid}_${secret}` };
|
|
92
|
+
}
|
|
93
|
+
/** 解析令牌正文;格式不对返回 undefined(不抛) */
|
|
94
|
+
function parseToken(token) {
|
|
95
|
+
const t = token.trim();
|
|
96
|
+
const parts = t.split('_');
|
|
97
|
+
if (parts.length !== 3 || parts[0] !== TOKEN_PREFIX)
|
|
98
|
+
return undefined;
|
|
99
|
+
const kid = parts[1] ?? '';
|
|
100
|
+
const secret = parts[2] ?? '';
|
|
101
|
+
if (!/^[0-9a-f]{8}$/.test(kid) || secret.length < 16)
|
|
102
|
+
return undefined;
|
|
103
|
+
return { kid, secret };
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* 校验服务令牌 + scope。
|
|
107
|
+
* 「没有令牌」与「令牌无效」是两件事:前者由调用方按 `requireServiceToken` 决定,后者一律拒绝。
|
|
108
|
+
*/
|
|
109
|
+
export function verifyServiceToken(token, requiredScope, now = new Date()) {
|
|
110
|
+
if (!token || !token.trim())
|
|
111
|
+
return { ok: false, reason: 'missing', message: '未提供服务令牌' };
|
|
112
|
+
const parsed = parseToken(token);
|
|
113
|
+
if (!parsed)
|
|
114
|
+
return { ok: false, reason: 'malformed', message: '服务令牌格式非法' };
|
|
115
|
+
const list = loadServices();
|
|
116
|
+
const rec = list.find((s) => s.kid === parsed.kid);
|
|
117
|
+
if (!rec)
|
|
118
|
+
return { ok: false, reason: 'unknown-kid', message: '服务令牌未登记(kid 未知)' };
|
|
119
|
+
const expected = Buffer.from(rec.sha256, 'hex');
|
|
120
|
+
const actual = Buffer.from(sha256Hex(parsed.secret), 'hex');
|
|
121
|
+
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) {
|
|
122
|
+
return { ok: false, reason: 'mismatch', message: '服务令牌不匹配' };
|
|
123
|
+
}
|
|
124
|
+
if (rec.expiresAt && Date.parse(rec.expiresAt) <= now.getTime()) {
|
|
125
|
+
return { ok: false, reason: 'expired', message: '服务令牌已过期' };
|
|
126
|
+
}
|
|
127
|
+
if (rec.revokedAt) {
|
|
128
|
+
const grace = rec.graceEndsAt ? Date.parse(rec.graceEndsAt) : Date.parse(rec.revokedAt);
|
|
129
|
+
if (!(grace > now.getTime())) {
|
|
130
|
+
return { ok: false, reason: 'revoked', message: '服务令牌已吊销' };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (!rec.scopes.includes(requiredScope)) {
|
|
134
|
+
return { ok: false, reason: 'scope', message: `服务令牌缺少 scope:${requiredScope}` };
|
|
135
|
+
}
|
|
136
|
+
// 记录最近使用(best-effort:写失败不影响本次判定)
|
|
137
|
+
try {
|
|
138
|
+
const idx = list.findIndex((s) => s.id === rec.id);
|
|
139
|
+
if (idx >= 0) {
|
|
140
|
+
list[idx] = { ...rec, lastUsedAt: now.toISOString() };
|
|
141
|
+
saveServices(list);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
/* 旁路 */
|
|
146
|
+
}
|
|
147
|
+
return { ok: true, record: rec };
|
|
148
|
+
}
|
|
149
|
+
/** 本地是否已登记过任何服务令牌(决定"默认不强校验"是否成立) */
|
|
150
|
+
export function hasAnyService() {
|
|
151
|
+
return loadServices().length > 0;
|
|
152
|
+
}
|
|
153
|
+
export function revokeServiceToken(id) {
|
|
154
|
+
const list = loadServices();
|
|
155
|
+
const idx = list.findIndex((s) => s.id === id || s.kid === id);
|
|
156
|
+
if (idx < 0)
|
|
157
|
+
return false;
|
|
158
|
+
const rec = list[idx];
|
|
159
|
+
if (!rec)
|
|
160
|
+
return false;
|
|
161
|
+
list[idx] = { ...rec, revokedAt: new Date().toISOString(), graceEndsAt: undefined };
|
|
162
|
+
saveServices(list);
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* 轮换:签发新令牌,旧令牌进入宽限期(期间仍然有效),宽限期后自动失效。
|
|
167
|
+
* 这样平台可以"先换后撤",不必停服。
|
|
168
|
+
*/
|
|
169
|
+
export function rotateServiceToken(id, graceHours = 24) {
|
|
170
|
+
const list = loadServices();
|
|
171
|
+
const idx = list.findIndex((s) => (s.id === id || s.kid === id) && !s.revokedAt);
|
|
172
|
+
if (idx < 0)
|
|
173
|
+
return undefined;
|
|
174
|
+
const old = list[idx];
|
|
175
|
+
if (!old)
|
|
176
|
+
return undefined;
|
|
177
|
+
const now = new Date();
|
|
178
|
+
const issued = issueServiceToken({
|
|
179
|
+
label: old.label,
|
|
180
|
+
scopes: old.scopes,
|
|
181
|
+
rotatedFrom: old.id,
|
|
182
|
+
});
|
|
183
|
+
const after = loadServices();
|
|
184
|
+
const oldIdx = after.findIndex((s) => s.id === old.id);
|
|
185
|
+
if (oldIdx >= 0 && after[oldIdx]) {
|
|
186
|
+
after[oldIdx] = {
|
|
187
|
+
...after[oldIdx],
|
|
188
|
+
revokedAt: now.toISOString(),
|
|
189
|
+
graceEndsAt: new Date(now.getTime() + Math.max(0, graceHours) * 3_600_000).toISOString(),
|
|
190
|
+
};
|
|
191
|
+
saveServices(after);
|
|
192
|
+
}
|
|
193
|
+
return issued;
|
|
194
|
+
}
|
|
195
|
+
/** 展示用:令牌只打尾号(明文永不进终端/日志/审计) */
|
|
196
|
+
export function serviceTokenTail(token) {
|
|
197
|
+
return tokenTail(token);
|
|
198
|
+
}
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire protocol between the bridge and the orchestration platform.
|
|
3
|
+
*
|
|
4
|
+
* The bridge is an external client: it does not import platform code, it only relies on this JSON
|
|
5
|
+
* contract plus runtime validation (`assertServerMessage`) so the two sides cannot drift silently.
|
|
6
|
+
*
|
|
7
|
+
* Direction: bridge → platform uses `ClientMessage`; platform → bridge uses `ServerMessage`.
|
|
8
|
+
*/
|
|
9
|
+
export const PROTOCOL_VERSION = 1;
|
|
10
|
+
/**
|
|
11
|
+
* 能力协商清单(hello.capabilities)
|
|
12
|
+
*
|
|
13
|
+
* 平台(可能是任意第三方系统)据此判断本机支持哪些**可选**能力,而不是靠 CLI 版本号猜。
|
|
14
|
+
* 规则:新增能力 = 加一个字符串 + 保持 PROTOCOL_VERSION 不变;语义变更/必填字段才 +1。
|
|
15
|
+
*/
|
|
16
|
+
export const PROTOCOL_CAPABILITIES = [
|
|
17
|
+
'diff',
|
|
18
|
+
'service-token',
|
|
19
|
+
'queue',
|
|
20
|
+
'scan-progress',
|
|
21
|
+
'cloud-events',
|
|
22
|
+
];
|
|
23
|
+
/** 平台下发的字符串字段长度上限(防畸形报文,也防日志/审计被撑爆) */
|
|
24
|
+
const MAX_META_LEN = 128;
|
|
25
|
+
const MAX_PURPOSE_LEN = 64;
|
|
26
|
+
const MAX_TOKEN_LEN = 256;
|
|
27
|
+
/** 取字符串字段:类型不对或超长一律忽略(前向兼容,不因为新字段拒帧) */
|
|
28
|
+
function strField(msg, key, max) {
|
|
29
|
+
const v = msg[key];
|
|
30
|
+
if (typeof v !== 'string')
|
|
31
|
+
return undefined;
|
|
32
|
+
const t = v.trim();
|
|
33
|
+
return t.length > 0 && t.length <= max ? t : undefined;
|
|
34
|
+
}
|
|
35
|
+
export class ProtocolError extends Error {
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* 运行时校验平台指令(不信任平台下发的任意结构)。
|
|
39
|
+
* 只做形状校验;**指令白名单**(agentType / cwd)在 runner 里另行校验。
|
|
40
|
+
*/
|
|
41
|
+
export function assertServerMessage(raw) {
|
|
42
|
+
if (!raw || typeof raw !== 'object')
|
|
43
|
+
throw new ProtocolError('报文不是对象');
|
|
44
|
+
const msg = raw;
|
|
45
|
+
const type = msg['type'];
|
|
46
|
+
if (type === 'run_task') {
|
|
47
|
+
for (const key of ['taskId', 'agentType', 'cwd']) {
|
|
48
|
+
if (typeof msg[key] !== 'string' || !msg[key].length) {
|
|
49
|
+
throw new ProtocolError(`run_task 缺少 ${key}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (!Array.isArray(msg['args']) || msg['args'].some((a) => typeof a !== 'string')) {
|
|
53
|
+
throw new ProtocolError('run_task.args 必须是字符串数组');
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
type: 'run_task',
|
|
57
|
+
taskId: String(msg['taskId']),
|
|
58
|
+
agentType: String(msg['agentType']),
|
|
59
|
+
cwd: String(msg['cwd']),
|
|
60
|
+
args: msg['args'],
|
|
61
|
+
prompt: typeof msg['prompt'] === 'string' ? msg['prompt'] : undefined,
|
|
62
|
+
// 注意:平台**不得**下发 env(2026-10-22 移除)。这里刻意不透传,
|
|
63
|
+
// 未知字段一律忽略 —— 子进程只用 bridge 自身进程的环境。
|
|
64
|
+
timeoutMs: typeof msg['timeoutMs'] === 'number' ? msg['timeoutMs'] : undefined,
|
|
65
|
+
allowInteractive: msg['allowInteractive'] === true,
|
|
66
|
+
// P0-6:只有显式 true 才捕获 diff(本地 diff_default 可在 cli 层兜底)
|
|
67
|
+
captureDiff: msg['captureDiff'] === true,
|
|
68
|
+
// P0-8:服务身份三件套,形状不对就忽略(不因为新字段拒帧)
|
|
69
|
+
requestedBy: strField(msg, 'requestedBy', MAX_META_LEN),
|
|
70
|
+
purpose: strField(msg, 'purpose', MAX_PURPOSE_LEN),
|
|
71
|
+
serviceToken: strField(msg, 'serviceToken', MAX_TOKEN_LEN),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
if (type === 'cancel_task') {
|
|
75
|
+
if (typeof msg['taskId'] !== 'string')
|
|
76
|
+
throw new ProtocolError('cancel_task 缺少 taskId');
|
|
77
|
+
return {
|
|
78
|
+
type: 'cancel_task',
|
|
79
|
+
taskId: String(msg['taskId']),
|
|
80
|
+
requestedBy: strField(msg, 'requestedBy', MAX_META_LEN),
|
|
81
|
+
purpose: strField(msg, 'purpose', MAX_PURPOSE_LEN),
|
|
82
|
+
serviceToken: strField(msg, 'serviceToken', MAX_TOKEN_LEN),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
if (type === 'scan') {
|
|
86
|
+
return {
|
|
87
|
+
type: 'scan',
|
|
88
|
+
requestId: typeof msg['requestId'] === 'string' ? msg['requestId'] : undefined,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (type === 'ping') {
|
|
92
|
+
return { type: 'ping', at: typeof msg['at'] === 'number' ? msg['at'] : undefined };
|
|
93
|
+
}
|
|
94
|
+
throw new ProtocolError(`未知指令类型: ${String(type)}`);
|
|
95
|
+
}
|
|
96
|
+
// ---------- CloudEvents 1.0 信封(可选,由 capabilities 协商) ----------
|
|
97
|
+
/**
|
|
98
|
+
* 上行事件的 **CloudEvents 1.0** 信封(CNCF 标准)。
|
|
99
|
+
*
|
|
100
|
+
* 为什么提供:默认报文是扁平的自研结构,第三方要接必须读文档。给一条"标准信封"开关后,
|
|
101
|
+
* 任何支持 CloudEvents 的事件系统(Kafka / Knative / 各类网关)可以直接消费,
|
|
102
|
+
* 不必为 bridge 单独写解析器。
|
|
103
|
+
*
|
|
104
|
+
* 默认关闭(保持 v1 扁平报文);平台在 `hello` 协商到 `cloud-events` 后请求启用。
|
|
105
|
+
*/
|
|
106
|
+
export const CLOUD_EVENTS_SPECVERSION = '1.0';
|
|
107
|
+
/** 把一条上行报文包成 CloudEvents 1.0 信封(纯函数,便于单测) */
|
|
108
|
+
export function toCloudEvent(msg, source, seq, at = new Date()) {
|
|
109
|
+
const type = `dev.agent-bridge.${msg.type}.v1`;
|
|
110
|
+
const subject = 'taskId' in msg ? String(msg['taskId']) : undefined;
|
|
111
|
+
return {
|
|
112
|
+
specversion: CLOUD_EVENTS_SPECVERSION,
|
|
113
|
+
id: `${seq}-${at.getTime()}`,
|
|
114
|
+
source,
|
|
115
|
+
type,
|
|
116
|
+
time: at.toISOString(),
|
|
117
|
+
datacontenttype: 'application/json',
|
|
118
|
+
...(subject ? { subject } : {}),
|
|
119
|
+
seq,
|
|
120
|
+
data: msg,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/** 日志分片上限:平台侧按 4KB 收,避免单帧过大 */
|
|
124
|
+
export const LOG_CHUNK_BYTES = 4096;
|
|
125
|
+
/** 把一段输出切成 ≤4KB 的分片(按 UTF-8 字节切,且不切断多字节字符) */
|
|
126
|
+
export function chunkLog(data, maxBytes = LOG_CHUNK_BYTES) {
|
|
127
|
+
if (!data)
|
|
128
|
+
return [];
|
|
129
|
+
const out = [];
|
|
130
|
+
let buf = '';
|
|
131
|
+
for (const ch of data) {
|
|
132
|
+
const next = buf + ch;
|
|
133
|
+
if (Buffer.byteLength(next, 'utf8') > maxBytes) {
|
|
134
|
+
out.push(buf);
|
|
135
|
+
buf = ch;
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
buf = next;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (buf)
|
|
142
|
+
out.push(buf);
|
|
143
|
+
return out;
|
|
144
|
+
}
|