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,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话启动(应用编排层)
|
|
3
|
+
*
|
|
4
|
+
* `connect` 与 `serve` 共用同一段"取凭证 → 建会话"的流程:
|
|
5
|
+
* 抽出来是为了不复制一份授权交互(复制品的必然结局是两边慢慢不一致)。
|
|
6
|
+
*
|
|
7
|
+
* 这里只负责**把会话建起来**,不负责"建完之后要一直活着还是顺便开个控制面"—— 那是命令层的事。
|
|
8
|
+
*/
|
|
9
|
+
import { hostname } from 'node:os';
|
|
10
|
+
import { version } from '../cli/meta.js';
|
|
11
|
+
import { boolFlag, posFlag, strFlag } from '../cli/flags.js';
|
|
12
|
+
import { createSession } from './session.js';
|
|
13
|
+
import { AuthError, authorizeWithBrowser, authorizeWithDeviceCode } from '../infra/auth.js';
|
|
14
|
+
import { configPath, loadConfig, resolveDiffMaxBytes, resolveMaxQueued, resolveMaxTasks, saveConfig, tokenTail, } from '../infra/config.js';
|
|
15
|
+
import { resolveDeviceId } from '../transport/bridge-client.js';
|
|
16
|
+
export async function startBridge(flags, log) {
|
|
17
|
+
const platformUrl = posFlag(flags, 1);
|
|
18
|
+
if (!platformUrl) {
|
|
19
|
+
log('error', '用法:agent-bridge connect <platformUrl> [--token=xxx] [--no-browser]');
|
|
20
|
+
process.exit(2);
|
|
21
|
+
}
|
|
22
|
+
const saved = loadConfig();
|
|
23
|
+
let deviceToken = strFlag(flags, 'token');
|
|
24
|
+
// 只在授权/复用配置时被赋值;--token 模式下由下面的 resolveDeviceId 解析
|
|
25
|
+
let deviceId = '';
|
|
26
|
+
let boundUrl = saved?.platformUrl ?? '';
|
|
27
|
+
if (!deviceToken) {
|
|
28
|
+
if (saved?.platformUrl === platformUrl.replace(/\/+$/, '') && saved.deviceToken) {
|
|
29
|
+
deviceToken = saved.deviceToken;
|
|
30
|
+
deviceId = saved.deviceId;
|
|
31
|
+
boundUrl = saved.platformUrl;
|
|
32
|
+
log('info', `复用已保存的设备凭证(${deviceId},token ${tokenTail(deviceToken)})`);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
log('info', '[agent-bridge] 开始设备授权…');
|
|
36
|
+
const useBrowser = !boolFlag(flags, 'no-browser');
|
|
37
|
+
try {
|
|
38
|
+
const res = useBrowser
|
|
39
|
+
? await authorizeWithBrowser(platformUrl, {
|
|
40
|
+
onPrompt: (url) => log('info', `[agent-bridge] 已打开浏览器,若无反应请手动访问:\n ${url}`),
|
|
41
|
+
})
|
|
42
|
+
: await authorizeWithDeviceCode(platformUrl, {
|
|
43
|
+
onPrompt: (uri, code) => log('info', `[agent-bridge] 请在浏览器打开 ${uri} 并输入验证码:${code}`),
|
|
44
|
+
});
|
|
45
|
+
deviceToken = res.deviceToken;
|
|
46
|
+
deviceId = res.deviceId;
|
|
47
|
+
boundUrl = res.platformUrl;
|
|
48
|
+
saveConfig({
|
|
49
|
+
platformUrl: res.platformUrl,
|
|
50
|
+
deviceId: res.deviceId,
|
|
51
|
+
deviceToken: res.deviceToken,
|
|
52
|
+
refreshToken: res.refreshToken,
|
|
53
|
+
label: strFlag(flags, 'label') ?? hostname(),
|
|
54
|
+
boundAt: new Date().toISOString(),
|
|
55
|
+
});
|
|
56
|
+
log('info', `✅ 设备绑定成功(${res.deviceId}),配置已写入 ${configPath()}`);
|
|
57
|
+
}
|
|
58
|
+
catch (e) {
|
|
59
|
+
if (e instanceof AuthError) {
|
|
60
|
+
log('error', `❌ 授权失败:${e.message}`);
|
|
61
|
+
process.exit(1);
|
|
62
|
+
}
|
|
63
|
+
throw e;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
// deviceId 解析优先级:授权响应 > --device-id > AGENT_BRIDGE_DEVICE_ID > 已保存配置(同平台)
|
|
68
|
+
const targetUrl = (boundUrl || platformUrl).replace(/\/+$/, '');
|
|
69
|
+
const savedId = saved && saved.platformUrl === targetUrl ? saved.deviceId : '';
|
|
70
|
+
deviceId = resolveDeviceId({
|
|
71
|
+
fromAuth: deviceId,
|
|
72
|
+
flag: strFlag(flags, 'device-id') ?? '',
|
|
73
|
+
env: process.env['AGENT_BRIDGE_DEVICE_ID'] ?? '',
|
|
74
|
+
saved: savedId,
|
|
75
|
+
});
|
|
76
|
+
if (!deviceId) {
|
|
77
|
+
log('warn', '[agent-bridge] 未提供 deviceId(--device-id / AGENT_BRIDGE_DEVICE_ID):' +
|
|
78
|
+
'连接将不带 deviceId 参数,平台需按 Bearer token 反查设备');
|
|
79
|
+
}
|
|
80
|
+
if (saved?.allowedCwd?.length) {
|
|
81
|
+
log('info', `[agent-bridge] 目录白名单已启用(${saved.allowedCwd.length} 个条目),越界任务将被拒绝`);
|
|
82
|
+
}
|
|
83
|
+
if (saved?.requireServiceToken) {
|
|
84
|
+
log('info', '[agent-bridge] 已开启 require_service_token:无有效服务令牌的任务将被拒绝');
|
|
85
|
+
}
|
|
86
|
+
const session = createSession({
|
|
87
|
+
platformUrl: boundUrl || platformUrl,
|
|
88
|
+
deviceToken,
|
|
89
|
+
deviceId,
|
|
90
|
+
cliVersion: version(),
|
|
91
|
+
hostname: hostname(),
|
|
92
|
+
allowedCwd: saved?.allowedCwd,
|
|
93
|
+
maxConcurrent: resolveMaxTasks(saved?.maxTasks),
|
|
94
|
+
maxQueued: resolveMaxQueued(saved?.maxQueued),
|
|
95
|
+
diffMaxBytes: resolveDiffMaxBytes(saved?.diffMaxBytes),
|
|
96
|
+
captureDiffByDefault: saved?.diffDefault === true,
|
|
97
|
+
requireServiceToken: saved?.requireServiceToken === true,
|
|
98
|
+
log,
|
|
99
|
+
});
|
|
100
|
+
return { session, config: saved };
|
|
101
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 服务身份校验(P0-8)—— 应用编排层
|
|
3
|
+
*
|
|
4
|
+
* 兼容策略(不能变,平台靠它平滑升级):
|
|
5
|
+
* - 本地没登记任何令牌、且未开启 `require_service_token` → 放行,与 v1 行为**完全一致**;
|
|
6
|
+
* - 一旦报文带了令牌 → **必须**校验通过,不存在"带了也跳过"的口子。
|
|
7
|
+
*
|
|
8
|
+
* 校验结果一律落审计(成功与失败都落),失败再映射成受控错误码回给平台。
|
|
9
|
+
*/
|
|
10
|
+
import { tokenDenyCode } from '../core/errors.js';
|
|
11
|
+
import { writeAudit } from '../infra/audit.js';
|
|
12
|
+
import { verifyServiceToken } from '../infra/service-token.js';
|
|
13
|
+
export function authorizeService(msg, action, taskId, scope, requireToken) {
|
|
14
|
+
if (!msg.serviceToken && !requireToken)
|
|
15
|
+
return { ok: true };
|
|
16
|
+
const res = verifyServiceToken(msg.serviceToken, scope);
|
|
17
|
+
const at = new Date().toISOString();
|
|
18
|
+
if (res.ok) {
|
|
19
|
+
writeAudit({
|
|
20
|
+
at,
|
|
21
|
+
action,
|
|
22
|
+
outcome: 'allowed',
|
|
23
|
+
taskId,
|
|
24
|
+
requestedBy: msg.requestedBy,
|
|
25
|
+
purpose: msg.purpose,
|
|
26
|
+
serviceId: res.record?.id,
|
|
27
|
+
scopes: res.record?.scopes,
|
|
28
|
+
});
|
|
29
|
+
return { ok: true, serviceId: res.record?.id };
|
|
30
|
+
}
|
|
31
|
+
writeAudit({
|
|
32
|
+
at,
|
|
33
|
+
action,
|
|
34
|
+
outcome: 'denied',
|
|
35
|
+
taskId,
|
|
36
|
+
requestedBy: msg.requestedBy,
|
|
37
|
+
purpose: msg.purpose,
|
|
38
|
+
serviceId: res.record?.id,
|
|
39
|
+
scopes: res.record?.scopes,
|
|
40
|
+
reason: res.message,
|
|
41
|
+
});
|
|
42
|
+
return { ok: false, message: res.message ?? '服务令牌校验失败', code: tokenDenyCode(res.reason) };
|
|
43
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 平台会话(应用编排层)
|
|
3
|
+
*
|
|
4
|
+
* 职责:一条出站长连接的生命周期 —— 上报初值、路由平台指令、维护在跑任务表。
|
|
5
|
+
* 它**不知道**自己在 CLI 里还是被控制面板驱动:输出全走注入的 `log`,上行全走 `Emitter`。
|
|
6
|
+
*
|
|
7
|
+
* 指令路由只做分发,具体动作在 `task-dispatch.ts`;扫描/取消这类短逻辑就地处理(不值得再开文件)。
|
|
8
|
+
*/
|
|
9
|
+
import { Emitter } from '../core/emitter.js';
|
|
10
|
+
import { scanAgents } from '../core/scan.js';
|
|
11
|
+
import { assertServerMessage, ProtocolError } from '../protocol.js';
|
|
12
|
+
import { createBridgeClient } from '../transport/bridge-client.js';
|
|
13
|
+
import { dispatchCancelTask, dispatchRunTask } from './task-dispatch.js';
|
|
14
|
+
export function createSession(opts) {
|
|
15
|
+
const tasks = new Map();
|
|
16
|
+
// client 的 onOpen/onMessage 里要用到 emitter,而 emitter 又要用到 client.send ——
|
|
17
|
+
// 互相依赖只能在"连接建立后才会回调"这个前提下用后赋值解决(与实现顺序无关,回调天然晚于同步构造)
|
|
18
|
+
let emitter;
|
|
19
|
+
const now = () => new Date().toISOString();
|
|
20
|
+
const client = createBridgeClient({
|
|
21
|
+
platformUrl: opts.platformUrl,
|
|
22
|
+
deviceToken: opts.deviceToken,
|
|
23
|
+
deviceId: opts.deviceId,
|
|
24
|
+
cliVersion: opts.cliVersion,
|
|
25
|
+
hostname: opts.hostname,
|
|
26
|
+
log: (line) => opts.log('info', line),
|
|
27
|
+
onOpen: async () => {
|
|
28
|
+
// 流式上报:每完成一个工具就推一条 scan_progress,平台可以边收边亮卡片
|
|
29
|
+
const items = await scanAgents({
|
|
30
|
+
fresh: true,
|
|
31
|
+
onItem: (item) => emitter?.emit({ type: 'scan_progress', items: [item], scannedAt: now(), done: false }),
|
|
32
|
+
});
|
|
33
|
+
emitter?.emit({ type: 'scan_progress', items: [], scannedAt: now(), done: true });
|
|
34
|
+
emitter?.emit({ type: 'agent_list', agents: items, scannedAt: now() });
|
|
35
|
+
opts.log('info', `[agent-bridge] 已上报 ${items.length} 个工具状态,等待平台任务…`);
|
|
36
|
+
},
|
|
37
|
+
onMessage: (raw) => {
|
|
38
|
+
let msg;
|
|
39
|
+
try {
|
|
40
|
+
msg = assertServerMessage(raw);
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
if (e instanceof ProtocolError) {
|
|
44
|
+
opts.log('error', `[agent-bridge] 指令非法:${e.message}`);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
throw e;
|
|
48
|
+
}
|
|
49
|
+
if (!emitter)
|
|
50
|
+
return;
|
|
51
|
+
if (msg.type === 'ping') {
|
|
52
|
+
emitter.emit({ type: 'pong', at: Date.now() });
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (msg.type === 'scan') {
|
|
56
|
+
const requestId = msg.requestId;
|
|
57
|
+
void scanAgents({
|
|
58
|
+
fresh: true,
|
|
59
|
+
onItem: (item) => emitter?.emit({
|
|
60
|
+
type: 'scan_progress',
|
|
61
|
+
requestId,
|
|
62
|
+
items: [item],
|
|
63
|
+
scannedAt: new Date().toISOString(),
|
|
64
|
+
done: false,
|
|
65
|
+
}),
|
|
66
|
+
}).then((agents) => {
|
|
67
|
+
const scannedAt = new Date().toISOString();
|
|
68
|
+
emitter?.emit({ type: 'scan_progress', requestId, items: [], scannedAt, done: true });
|
|
69
|
+
emitter?.emit({ type: 'scan_result', requestId, agents, scannedAt });
|
|
70
|
+
});
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const dispatchOpts = {
|
|
74
|
+
emitter,
|
|
75
|
+
tasks,
|
|
76
|
+
allowedCwd: opts.allowedCwd,
|
|
77
|
+
maxConcurrent: opts.maxConcurrent,
|
|
78
|
+
maxQueued: opts.maxQueued,
|
|
79
|
+
diffMaxBytes: opts.diffMaxBytes,
|
|
80
|
+
captureDiffByDefault: opts.captureDiffByDefault,
|
|
81
|
+
requireServiceToken: opts.requireServiceToken,
|
|
82
|
+
log: opts.log,
|
|
83
|
+
};
|
|
84
|
+
if (msg.type === 'cancel_task')
|
|
85
|
+
return dispatchCancelTask(msg, dispatchOpts);
|
|
86
|
+
dispatchRunTask(msg, dispatchOpts);
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
emitter = new Emitter({
|
|
90
|
+
// 信封暂不由本地单方开启:平台在 hello 协商到 cloud-events 后再启用,默认保持 v1 扁平报文
|
|
91
|
+
sink: (msg) => client.send(msg),
|
|
92
|
+
});
|
|
93
|
+
return {
|
|
94
|
+
// 循环依赖的解法:client 的回调只在连接建立后触发,此时 emitter 必然已赋值
|
|
95
|
+
emitter,
|
|
96
|
+
close: () => client.close(),
|
|
97
|
+
isConnected: () => client.isOpen(),
|
|
98
|
+
activeTasks: () => tasks.size,
|
|
99
|
+
cancelTask: (taskId) => {
|
|
100
|
+
const h = tasks.get(taskId);
|
|
101
|
+
if (!h)
|
|
102
|
+
return false;
|
|
103
|
+
h.cancel();
|
|
104
|
+
return true;
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 任务指令编排(应用编排层)
|
|
3
|
+
*
|
|
4
|
+
* 把「平台下发 run_task / cancel_task」到「本地起进程 + 回传状态」这一段从入口文件里搬出来。
|
|
5
|
+
* 这里**不碰终端**:所有输出走注入的 `log`,所以控制面板复用同一段逻辑时不会污染 stdout。
|
|
6
|
+
*
|
|
7
|
+
* 上行一律经 `Emitter.emit()`(终态幂等 / 日志脱敏 / 审计 / 信封收口都在这条路上)。
|
|
8
|
+
*/
|
|
9
|
+
import { startTask } from '../runner.js';
|
|
10
|
+
import { authorizeService } from './service-gate.js';
|
|
11
|
+
/** 取消同样要鉴权:拿到 task:create 的令牌不等于能杀别人的任务 */
|
|
12
|
+
export function dispatchCancelTask(msg, o) {
|
|
13
|
+
const gate = authorizeService(msg, 'cancel_task', msg.taskId, 'task:cancel', o.requireServiceToken);
|
|
14
|
+
if (!gate.ok) {
|
|
15
|
+
o.log('error', `[agent-bridge] 拒绝取消 ${msg.taskId}:${gate.message}`);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
o.tasks.get(msg.taskId)?.cancel();
|
|
19
|
+
}
|
|
20
|
+
export function dispatchRunTask(msg, o) {
|
|
21
|
+
const gate = authorizeService(msg, 'run_task', msg.taskId, 'task:create', o.requireServiceToken);
|
|
22
|
+
if (!gate.ok) {
|
|
23
|
+
o.log('error', `[agent-bridge] 拒绝执行 ${msg.taskId}:${gate.message}`);
|
|
24
|
+
o.emitter.emit({
|
|
25
|
+
type: 'task_status',
|
|
26
|
+
taskId: msg.taskId,
|
|
27
|
+
status: 'failed',
|
|
28
|
+
error: `服务身份校验失败:${gate.message}`,
|
|
29
|
+
errorCode: gate.code,
|
|
30
|
+
requestedBy: msg.requestedBy,
|
|
31
|
+
});
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const who = msg.requestedBy ? `(${msg.requestedBy}${msg.purpose ? ` / ${msg.purpose}` : ''})` : '';
|
|
35
|
+
o.log('info', `\n▶ 执行任务 ${msg.taskId}:${msg.agentType}${who}`);
|
|
36
|
+
const handle = startTask({
|
|
37
|
+
taskId: msg.taskId,
|
|
38
|
+
agentType: msg.agentType,
|
|
39
|
+
cwd: msg.cwd,
|
|
40
|
+
args: msg.args,
|
|
41
|
+
prompt: msg.prompt,
|
|
42
|
+
timeoutMs: msg.timeoutMs,
|
|
43
|
+
allowedCwd: o.allowedCwd,
|
|
44
|
+
maxConcurrent: o.maxConcurrent,
|
|
45
|
+
maxQueued: o.maxQueued,
|
|
46
|
+
captureDiff: msg.captureDiff === true || o.captureDiffByDefault,
|
|
47
|
+
diffMaxBytes: o.diffMaxBytes,
|
|
48
|
+
}, {
|
|
49
|
+
onLog: (stream, data) => {
|
|
50
|
+
const text = data.replace(/\x1b\[[0-9;]*m/g, '');
|
|
51
|
+
if (text.trim())
|
|
52
|
+
o.log('info', `[${stream}] ${text.trimEnd()}`);
|
|
53
|
+
o.emitter.emit({ type: 'task_log', taskId: msg.taskId, stream, data, isAnsi: true });
|
|
54
|
+
},
|
|
55
|
+
onStatus: (status, info) => {
|
|
56
|
+
if (info?.changedFiles?.length) {
|
|
57
|
+
o.log('info', `[agent-bridge] 变更 ${info.changedFiles.length} 个文件:${info.changedFiles.slice(0, 8).join(', ')}`);
|
|
58
|
+
}
|
|
59
|
+
o.emitter.emit({
|
|
60
|
+
type: 'task_status',
|
|
61
|
+
taskId: msg.taskId,
|
|
62
|
+
status,
|
|
63
|
+
exitCode: info?.exitCode,
|
|
64
|
+
error: info?.error,
|
|
65
|
+
// 受控错误码:给平台做程序化分支(error 仍是可直接展示的人类可读串)
|
|
66
|
+
errorCode: info?.errorCode,
|
|
67
|
+
// 排队语义:status 恒为 running,phase/queuePosition 供新平台区分(v1 兼容)
|
|
68
|
+
phase: info?.phase,
|
|
69
|
+
queuePosition: info?.queuePosition,
|
|
70
|
+
// P0-6:终态带 diff(未开启 captureDiff 时这些字段都是 undefined,不会出现在 JSON 里)
|
|
71
|
+
diff: info?.diff,
|
|
72
|
+
changedFiles: info?.changedFiles,
|
|
73
|
+
diffTruncated: info?.diffTruncated,
|
|
74
|
+
// P0-8:回显服务身份,供平台落 requested_by 审计
|
|
75
|
+
requestedBy: msg.requestedBy,
|
|
76
|
+
});
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
o.tasks.set(msg.taskId, handle);
|
|
80
|
+
void handle.done.then(() => o.tasks.delete(msg.taskId));
|
|
81
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 命令注册表与分发(CLI 支撑件)
|
|
3
|
+
*
|
|
4
|
+
* `src/cli.ts` 只做一件事:把 argv 交给 `dispatch()`。命令表在这里,
|
|
5
|
+
* 新增命令 = 在 `src/commands/` 加一个文件 + 在这里加一行,入口文件零改动。
|
|
6
|
+
*/
|
|
7
|
+
import { cmdConnect } from '../commands/connect.js';
|
|
8
|
+
import { cmdDaemon } from '../commands/daemon.js';
|
|
9
|
+
import { cmdLogout } from '../commands/logout.js';
|
|
10
|
+
import { cmdServe } from '../commands/serve.js';
|
|
11
|
+
import { cmdServices } from '../commands/services.js';
|
|
12
|
+
import { cmdStatus } from '../commands/status.js';
|
|
13
|
+
import { parseFlags } from './flags.js';
|
|
14
|
+
import { help } from './help.js';
|
|
15
|
+
import { version } from './meta.js';
|
|
16
|
+
import { C } from './render.js';
|
|
17
|
+
/** 命令表:`doc:check` 会核对这里与两份 README 的命令清单是否一致 */
|
|
18
|
+
export const COMMANDS = {
|
|
19
|
+
connect: cmdConnect,
|
|
20
|
+
serve: cmdServe,
|
|
21
|
+
status: cmdStatus,
|
|
22
|
+
logout: cmdLogout,
|
|
23
|
+
services: cmdServices,
|
|
24
|
+
daemon: cmdDaemon,
|
|
25
|
+
};
|
|
26
|
+
export async function dispatch(argv) {
|
|
27
|
+
const cmd = argv[0];
|
|
28
|
+
const flags = parseFlags(argv);
|
|
29
|
+
if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h')
|
|
30
|
+
return help();
|
|
31
|
+
if (cmd === '--version' || cmd === '-v' || cmd === 'version') {
|
|
32
|
+
console.log(version());
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const fn = COMMANDS[cmd];
|
|
36
|
+
if (!fn) {
|
|
37
|
+
console.error(C.red(`未知命令:${cmd}`));
|
|
38
|
+
help();
|
|
39
|
+
process.exit(2);
|
|
40
|
+
}
|
|
41
|
+
await fn(flags);
|
|
42
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 命令行参数解析(CLI 支撑件)
|
|
3
|
+
*
|
|
4
|
+
* 极简解析:只支持 `--key=value`、`--flag` 与位置参数。
|
|
5
|
+
* 不引入 commander/yargs —— 本包刻意的"零运行时依赖"约束(package.json 只有 ws + smol-toml)。
|
|
6
|
+
*/
|
|
7
|
+
export function parseFlags(argv) {
|
|
8
|
+
const out = { _: [] };
|
|
9
|
+
for (const a of argv) {
|
|
10
|
+
if (a.startsWith('--')) {
|
|
11
|
+
const eq = a.indexOf('=');
|
|
12
|
+
if (eq > 0)
|
|
13
|
+
out[a.slice(2, eq)] = a.slice(eq + 1);
|
|
14
|
+
else
|
|
15
|
+
out[a.slice(2)] = true;
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
out._.push(a);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
/** 取字符串型 flag(非字符串一律视为未给) */
|
|
24
|
+
export function strFlag(flags, key) {
|
|
25
|
+
const v = flags[key];
|
|
26
|
+
return typeof v === 'string' ? v : undefined;
|
|
27
|
+
}
|
|
28
|
+
/** 取布尔型 flag */
|
|
29
|
+
export function boolFlag(flags, key) {
|
|
30
|
+
return flags[key] === true;
|
|
31
|
+
}
|
|
32
|
+
/** 取数值型 flag:非法或非正一律回落默认值 */
|
|
33
|
+
export function numFlag(flags, key, fallback) {
|
|
34
|
+
const raw = Number(strFlag(flags, key) ?? '');
|
|
35
|
+
return Number.isFinite(raw) && raw > 0 ? raw : fallback;
|
|
36
|
+
}
|
|
37
|
+
/** 位置参数:`agent-bridge services revoke <id>` 里 pos(flags,2) 即 `<id>` */
|
|
38
|
+
export function posFlag(flags, index) {
|
|
39
|
+
return flags._[index] ?? '';
|
|
40
|
+
}
|
package/dist/cli/help.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 帮助文本(CLI 支撑件)
|
|
3
|
+
*
|
|
4
|
+
* 命令清单与 `dispatch.ts` 的注册表必须一致 —— README 由 `doc:check` 机检,
|
|
5
|
+
* 这里则是给人看的第一份说明,未实现的能力必须当场写清(daemon 是 stub)。
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync } from 'node:fs';
|
|
8
|
+
import { configPath } from '../infra/config.js';
|
|
9
|
+
import { version } from './meta.js';
|
|
10
|
+
import { C } from './render.js';
|
|
11
|
+
export function help() {
|
|
12
|
+
console.log(`
|
|
13
|
+
${C.bold('agent-bridge')} ${version()} —— 把本机 AI 编码 CLI 接入你的编排平台
|
|
14
|
+
|
|
15
|
+
用法:
|
|
16
|
+
agent-bridge connect <platformUrl> [--token=xxx] [--device-id=bd_xxx] [--no-browser] [--label=name]
|
|
17
|
+
绑定本机设备并保持长连接(浏览器授权;SSH 场景加 --no-browser 走设备码)
|
|
18
|
+
--token 模式建议同时给 --device-id(或设 AGENT_BRIDGE_DEVICE_ID),否则平台需按 token 反查设备
|
|
19
|
+
agent-bridge status [--json] [--fresh]
|
|
20
|
+
扫描并打印本机 12 个 AI 编码 CLI 的安装/凭据状态
|
|
21
|
+
agent-bridge serve <platformUrl> [--port=8787]
|
|
22
|
+
与 connect 相同的主流程,额外开一个**本地回环控制面**(默认关闭;带 --port 本次启用)
|
|
23
|
+
服务对象是本机其它程序(IDE 插件 / 脚本 / MCP server / CI),远程平台仍走出站 WebSocket
|
|
24
|
+
agent-bridge logout
|
|
25
|
+
清除本地设备凭证
|
|
26
|
+
agent-bridge services issue|list|revoke|rotate
|
|
27
|
+
服务令牌(scoped service token):给外部系统/后端服务签发可轮换的最小权限身份
|
|
28
|
+
--label=<name> --scopes=task:create,task:cancel,task:read,device:read [--ttl-days=90]
|
|
29
|
+
rotate 可带 --grace-hours=24(旧令牌宽限期,期间仍然有效)
|
|
30
|
+
agent-bridge daemon start|stop|install|uninstall
|
|
31
|
+
后台常驻(Phase 3,尚未实现)
|
|
32
|
+
agent-bridge --version | help
|
|
33
|
+
|
|
34
|
+
配置文件:${configPath()}${existsSync(configPath()) ? '' : C.dim('(尚未创建)')}
|
|
35
|
+
`);
|
|
36
|
+
}
|
package/dist/cli/hold.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 前台保活(CLI 支撑件)
|
|
3
|
+
*
|
|
4
|
+
* 长驻命令(`connect` / `serve`)最后都要:注册退出信号 → 优雅关闭 → 永不 resolve。
|
|
5
|
+
* 抽出来是因为两个命令都要,写两遍必然慢慢写歪。
|
|
6
|
+
*/
|
|
7
|
+
export function hold(close) {
|
|
8
|
+
const bye = () => {
|
|
9
|
+
close();
|
|
10
|
+
process.exit(0);
|
|
11
|
+
};
|
|
12
|
+
process.on('SIGINT', bye);
|
|
13
|
+
process.on('SIGTERM', bye);
|
|
14
|
+
return new Promise(() => undefined);
|
|
15
|
+
}
|
package/dist/cli/meta.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 包元信息(CLI 支撑件)
|
|
3
|
+
*
|
|
4
|
+
* 从 package.json 读版本,而不是在代码里硬编码 —— 避免发版忘了改。
|
|
5
|
+
* 读不到(例如被单包打包)时回落 0.0.0,绝不因此崩溃。
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
export function version() {
|
|
9
|
+
try {
|
|
10
|
+
const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
11
|
+
return pkg.version ?? '0.0.0';
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return '0.0.0';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 终端渲染(CLI 支撑件)
|
|
3
|
+
*
|
|
4
|
+
* 只有 `cli/` 与 `commands/` 依赖它;`app/` 层**不许**直接碰终端 ——
|
|
5
|
+
* 否则「本地控制面板」「单元测试」想复用同一段逻辑时会被 stdout 绑死。
|
|
6
|
+
*/
|
|
7
|
+
const tty = () => process.stdout.isTTY === true;
|
|
8
|
+
const paint = (code, s) => (tty() ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
9
|
+
export const C = {
|
|
10
|
+
dim: (s) => paint('2', s),
|
|
11
|
+
green: (s) => paint('32', s),
|
|
12
|
+
yellow: (s) => paint('33', s),
|
|
13
|
+
red: (s) => paint('31', s),
|
|
14
|
+
bold: (s) => paint('1', s),
|
|
15
|
+
};
|
|
16
|
+
export const STATUS_LABEL = {
|
|
17
|
+
ready: '就绪',
|
|
18
|
+
installed_no_cred: '缺凭据',
|
|
19
|
+
not_installed: '未装',
|
|
20
|
+
};
|
|
21
|
+
export const out = {
|
|
22
|
+
line: (s = '') => console.log(s),
|
|
23
|
+
info: (s) => console.log(C.dim(s)),
|
|
24
|
+
ok: (s) => console.log(C.green(s)),
|
|
25
|
+
warn: (s) => console.log(C.yellow(s)),
|
|
26
|
+
error: (s) => console.error(C.red(s)),
|
|
27
|
+
fatal: (s) => {
|
|
28
|
+
console.error(C.red(s));
|
|
29
|
+
process.exit(2);
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
export function printAgents(items) {
|
|
33
|
+
const rows = items.map((a) => {
|
|
34
|
+
const name = a.display.padEnd(18);
|
|
35
|
+
const ver = (a.version ?? (a.path?.startsWith('npx ') ? 'npx 免安装' : '-')).padEnd(20);
|
|
36
|
+
// 找到二进制但执行失败时,「就绪」是假象,直接标「装坏」
|
|
37
|
+
const label = a.installedButBroken ? '装坏' : STATUS_LABEL[a.status];
|
|
38
|
+
const painted = a.installedButBroken
|
|
39
|
+
? C.red(label)
|
|
40
|
+
: a.status === 'ready'
|
|
41
|
+
? C.green(label)
|
|
42
|
+
: a.status === 'installed_no_cred'
|
|
43
|
+
? C.yellow(label)
|
|
44
|
+
: C.dim(label);
|
|
45
|
+
return `${name} ${ver} ${painted}`;
|
|
46
|
+
});
|
|
47
|
+
console.log(C.bold('\n工具 版本 状态'));
|
|
48
|
+
console.log(C.dim('─'.repeat(58)));
|
|
49
|
+
for (const r of rows)
|
|
50
|
+
console.log(r);
|
|
51
|
+
const ready = items.filter((a) => a.status === 'ready' && !a.installedButBroken).length;
|
|
52
|
+
console.log(C.dim(`\n共 ${items.length} 个工具,可用 ${ready} 个\n`));
|
|
53
|
+
}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* agent-bridge 入口
|
|
4
|
+
*
|
|
5
|
+
* 这个文件**只做分发**:argv → `cli/dispatch.ts` → `commands/<name>` → `app/`。
|
|
6
|
+
* 任何业务逻辑都不许写在这里 —— 之前它同时承担了参数解析、终端渲染、授权交互、
|
|
7
|
+
* 平台指令编排和任务回传,548 行里塞了五个职责,改一处要读完全文。
|
|
8
|
+
*
|
|
9
|
+
* 现在的分层(依赖单向,无环):
|
|
10
|
+
*
|
|
11
|
+
* cli.ts ─▶ cli/(参数·渲染·帮助·分发) ─▶ commands/(命令实现) ─▶ app/(用例编排)
|
|
12
|
+
* ─▶ core / transport / adapters / infra
|
|
13
|
+
*
|
|
14
|
+
* agent-bridge connect <platformUrl> [--token=xxx] [--label=name] [--no-browser]
|
|
15
|
+
* agent-bridge status [--json] [--fresh]
|
|
16
|
+
* agent-bridge logout
|
|
17
|
+
* agent-bridge services issue|list|revoke|rotate
|
|
18
|
+
* agent-bridge daemon start|stop|install|uninstall
|
|
19
|
+
* agent-bridge --version
|
|
20
|
+
*/
|
|
21
|
+
import { dispatch } from './cli/dispatch.js';
|
|
22
|
+
import { C } from './cli/render.js';
|
|
23
|
+
void dispatch(process.argv.slice(2)).catch((e) => {
|
|
24
|
+
console.error(C.red(`❌ ${e.message}`));
|
|
25
|
+
process.exit(1);
|
|
26
|
+
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `agent-bridge connect` —— 绑定设备并保持出站长连接
|
|
3
|
+
*
|
|
4
|
+
* 命令层只做两件事:把凭证与配置交给 `app/bootstrap.ts` 起会话,然后注册退出信号并保活。
|
|
5
|
+
* 「连上平台之后干什么」在 `app/session.ts`,与 `serve` 共用同一份(不复制一份授权流程)。
|
|
6
|
+
*/
|
|
7
|
+
import { startBridge } from '../app/bootstrap.js';
|
|
8
|
+
import { hold } from '../cli/hold.js';
|
|
9
|
+
import { C, out } from '../cli/render.js';
|
|
10
|
+
export async function cmdConnect(flags) {
|
|
11
|
+
const log = (level, line) => {
|
|
12
|
+
if (level === 'info')
|
|
13
|
+
console.log(C.dim(line));
|
|
14
|
+
else
|
|
15
|
+
console.error(level === 'error' ? C.red(line) : C.yellow(line));
|
|
16
|
+
};
|
|
17
|
+
const { session } = await startBridge(flags, log);
|
|
18
|
+
out.info('[agent-bridge] 已就绪(Ctrl+C 退出)');
|
|
19
|
+
await hold(() => session.close());
|
|
20
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `agent-bridge daemon` —— 后台常驻(Phase 3,**尚未实现**)
|
|
3
|
+
*
|
|
4
|
+
* 保留 stub 而不是删命令:README 与 `doc:check` 都声明了它,
|
|
5
|
+
* 且用户按习惯敲 `daemon start` 时应该得到明确说明而不是「未知命令」。
|
|
6
|
+
*/
|
|
7
|
+
import { posFlag } from '../cli/flags.js';
|
|
8
|
+
import { out } from '../cli/render.js';
|
|
9
|
+
export function cmdDaemon(flags) {
|
|
10
|
+
const sub = posFlag(flags, 1) || 'status';
|
|
11
|
+
out.warn(`[agent-bridge] daemon ${sub} 尚未实现(Phase 3:systemd/launchd/Windows 服务)`);
|
|
12
|
+
out.info('当前请用前台模式:agent-bridge connect <platformUrl>');
|
|
13
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `agent-bridge logout` —— 清除本地设备凭证
|
|
3
|
+
*
|
|
4
|
+
* 只清本地:平台侧的"设备下线"是对端动作,必须提示用户去平台吊销(否则会出现
|
|
5
|
+
* 「本地已登出但平台还挂着这台设备」的错配)。
|
|
6
|
+
*/
|
|
7
|
+
import { out } from '../cli/render.js';
|
|
8
|
+
import { clearConfig, loadConfig } from '../infra/config.js';
|
|
9
|
+
export function cmdLogout() {
|
|
10
|
+
const cfg = loadConfig();
|
|
11
|
+
if (!cfg) {
|
|
12
|
+
out.info('[agent-bridge] 未绑定任何平台');
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
clearConfig();
|
|
16
|
+
out.ok(`✅ 已清除本地设备凭证(${cfg.deviceId})`);
|
|
17
|
+
out.info('提示:如需让平台侧同步下线,请到「设备管理」里吊销该设备。');
|
|
18
|
+
}
|