agent-bridge-service 0.2.2 → 1.0.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +112 -140
  2. package/README.md +508 -35
  3. package/README.zh-CN.md +443 -33
  4. package/assets/agent-icons/agy.svg +27 -0
  5. package/dist/adapters/acp-auth.js +51 -0
  6. package/dist/adapters/acp-codebuddy.js +507 -0
  7. package/dist/adapters/agent-adapters.js +466 -46
  8. package/dist/adapters/claude-stream.js +159 -0
  9. package/dist/adapters/codex-app-server.js +310 -0
  10. package/dist/adapters/host-env.js +48 -0
  11. package/dist/adapters/mcp-elicitation.js +148 -0
  12. package/dist/adapters/mcp-host.js +70 -0
  13. package/dist/adapters/step-parsers.js +583 -0
  14. package/dist/app/bootstrap.js +163 -74
  15. package/dist/app/claude-resident.js +204 -0
  16. package/dist/app/conversation.js +639 -0
  17. package/dist/app/service-gate.js +1 -1
  18. package/dist/app/session.js +425 -14
  19. package/dist/app/task-dispatch.js +883 -7
  20. package/dist/app/task-registry.js +168 -0
  21. package/dist/cli/dispatch.js +4 -0
  22. package/dist/cli/flags.js +11 -0
  23. package/dist/cli/help.js +25 -7
  24. package/dist/cli/panel.js +334 -0
  25. package/dist/cli/render.js +2 -0
  26. package/dist/commands/approvals.js +80 -0
  27. package/dist/commands/connect.js +122 -4
  28. package/dist/commands/daemon-service.js +81 -0
  29. package/dist/commands/daemon.js +269 -6
  30. package/dist/commands/logout.js +13 -10
  31. package/dist/commands/serve.js +98 -12
  32. package/dist/commands/sessions.js +106 -0
  33. package/dist/core/ansi.js +5 -0
  34. package/dist/core/artifact-extract.js +158 -0
  35. package/dist/core/artifact-transfer.js +583 -0
  36. package/dist/core/device-identity.js +22 -0
  37. package/dist/core/emitter.js +50 -8
  38. package/dist/core/errors.js +43 -0
  39. package/dist/core/form-schema.js +72 -0
  40. package/dist/core/interaction-broker.js +440 -0
  41. package/dist/core/interaction-url.js +63 -0
  42. package/dist/core/partial-messages.js +99 -0
  43. package/dist/core/permission-ledger.js +146 -0
  44. package/dist/core/permission-policy.js +88 -0
  45. package/dist/core/port-fallback.js +22 -0
  46. package/dist/core/redact.js +13 -0
  47. package/dist/core/scan.js +12 -7
  48. package/dist/core/session-store.js +1632 -0
  49. package/dist/core/task-supervisor.js +955 -30
  50. package/dist/infra/atomic-file.js +111 -0
  51. package/dist/infra/audit.js +7 -0
  52. package/dist/infra/auth.js +167 -42
  53. package/dist/infra/config.js +511 -72
  54. package/dist/infra/device-identity-store.js +87 -0
  55. package/dist/infra/jwt.js +149 -0
  56. package/dist/infra/profile-lock.js +295 -0
  57. package/dist/infra/proxy-env.js +60 -0
  58. package/dist/infra/service-token.js +25 -4
  59. package/dist/protocol.js +298 -2
  60. package/dist/transport/a2a-mapping.js +206 -0
  61. package/dist/transport/acp-gateway-mapping.js +186 -0
  62. package/dist/transport/bridge-client.js +31 -22
  63. package/dist/transport/control-plane-page.js +820 -0
  64. package/dist/transport/control-plane-sessions-page.js +90 -0
  65. package/dist/transport/control-plane.js +923 -71
  66. package/dist/transport/gateway.js +1005 -0
  67. package/dist/transport/office-preview.js +154 -0
  68. package/package.json +6 -3
  69. package/assets/agent-icons/gemini.svg +0 -1
@@ -0,0 +1,80 @@
1
+ /**
2
+ * `agent-bridge approvals` —— 持久授权账本的查看与撤销(1.0)
3
+ *
4
+ * 账本只由人工在交互里选「永久允许」时写入;这里补上**撤销**这一半 ——
5
+ * 没有撤销入口的持久授权等于永久后门,所以它和写入在同一批交付。
6
+ *
7
+ * 存储是本地 SQLite(与 session/event 同一个库),命令层只做打印与调用,语义在
8
+ * `core/permission-ledger.ts`(判定)与 `core/session-store.ts`(持久化)。
9
+ */
10
+ import { posFlag, strFlag } from '../cli/flags.js';
11
+ import { C, out } from '../cli/render.js';
12
+ import { DEFAULT_TENANT, SessionStore } from '../core/session-store.js';
13
+ import { stateDbPath } from '../infra/config.js';
14
+ import { writeAudit } from '../infra/audit.js';
15
+ export function cmdApprovals(flags) {
16
+ const sub = posFlag(flags, 1) || 'list';
17
+ const tenantId = strFlag(flags, 'tenant') ?? DEFAULT_TENANT;
18
+ const withRevoked = flags['all'] === true || flags['all'] === 'true';
19
+ let store;
20
+ const open = () => {
21
+ store = new SessionStore(stateDbPath());
22
+ return store;
23
+ };
24
+ try {
25
+ if (sub === 'list') {
26
+ const rows = open().listApprovals(tenantId, withRevoked);
27
+ if (!rows.length) {
28
+ out.info('账本为空。开启方式:config.toml 设 approval_ledger_enabled = true(或 connect --approval-ledger),' +
29
+ '之后交互里选择「永久允许」才会记录。');
30
+ return;
31
+ }
32
+ console.log(C.bold('\nID AGENT TOOL 资源 到期时间'));
33
+ console.log(C.dim('─'.repeat(96)));
34
+ const now = Date.now();
35
+ for (const row of rows) {
36
+ const expired = row.expiresAt !== undefined && Date.parse(row.expiresAt) <= now;
37
+ const state = row.revokedAt ? C.red('已撤销 ') : expired ? C.yellow('已过期 ') : '';
38
+ console.log(`${row.approvalId.padEnd(24)}${row.agentType.padEnd(18)}${row.tool.padEnd(10)}` +
39
+ `${row.resource.slice(0, 14).padEnd(16)}${row.expiresAt ?? '-'} ${state}`);
40
+ }
41
+ console.log('');
42
+ out.info(`共 ${rows.length} 条${withRevoked ? '' : '(不含已撤销;加 --all 可看)'}`);
43
+ return;
44
+ }
45
+ if (sub === 'revoke') {
46
+ const id = strFlag(flags, 'id') ?? posFlag(flags, 2);
47
+ if (!id)
48
+ return out.fatal('用法:agent-bridge approvals revoke <approvalId>');
49
+ const ok = open().revokeApproval(tenantId, id);
50
+ if (!ok) {
51
+ out.error(`未找到可撤销的授权:${id}`);
52
+ process.exit(1);
53
+ }
54
+ out.ok(`✅ 已撤销 ${id}(后续任务不会再自动命中)`);
55
+ writeAudit({
56
+ at: new Date().toISOString(),
57
+ action: 'approval_revoke',
58
+ outcome: 'allowed',
59
+ approvalId: id,
60
+ reason: 'cli',
61
+ });
62
+ return;
63
+ }
64
+ if (sub === 'purge') {
65
+ const removed = open().purgeExpiredApprovals(tenantId);
66
+ out.ok(`✅ 已清理 ${removed} 条过期授权`);
67
+ writeAudit({
68
+ at: new Date().toISOString(),
69
+ action: 'approval_purge',
70
+ outcome: 'allowed',
71
+ reason: `removed=${removed}`,
72
+ });
73
+ return;
74
+ }
75
+ return out.fatal(`未知子命令:approvals ${sub}\n可用:list / revoke / purge`);
76
+ }
77
+ finally {
78
+ store?.close();
79
+ }
80
+ }
@@ -3,18 +3,136 @@
3
3
  *
4
4
  * 命令层只做两件事:把凭证与配置交给 `app/bootstrap.ts` 起会话,然后注册退出信号并保活。
5
5
  * 「连上平台之后干什么」在 `app/session.ts`,与 `serve` 共用同一份(不复制一份授权流程)。
6
+ *
7
+ * TTY 下挂常驻任务面板(C 批次):主窗口只留状态表,任务日志不滚动
8
+ * (上行走 task_log,本机查看走 Web 面板)。非 TTY 退化为逐行日志。
6
9
  */
10
+ import { randomBytes } from 'node:crypto';
11
+ import { hostname } from 'node:os';
7
12
  import { startBridge } from '../app/bootstrap.js';
13
+ import { boolFlag, numFlagMin, strFlag } from '../cli/flags.js';
8
14
  import { hold } from '../cli/hold.js';
15
+ import { version } from '../cli/meta.js';
16
+ import { panelLog, startPanel } from '../cli/panel.js';
9
17
  import { C, out } from '../cli/render.js';
18
+ import { withPortFallback } from '../core/port-fallback.js';
19
+ import { scanAgents } from '../core/scan.js';
20
+ import { defaultSupervisor } from '../core/task-supervisor.js';
21
+ import { resolveControlPlane, resolveDiffMaxBytes, resolveExternalSandbox, resolveGateway, resolvePermissionPolicy, resolveMaxQueued, resolveMaxTasks, } from '../infra/config.js';
22
+ import { AGENTS } from '../adapters/agent-adapters.js';
23
+ import { JwtVerifier } from '../infra/jwt.js';
24
+ import { acquireBridgeRuntimeLock } from '../infra/profile-lock.js';
25
+ import { stateDir } from '../infra/config.js';
26
+ import { verifyServiceToken } from '../infra/service-token.js';
27
+ import { PROTOCOL_CAPABILITIES } from '../protocol.js';
28
+ import { startTask } from '../runner.js';
29
+ import { startControlPlane } from '../transport/control-plane.js';
10
30
  export async function cmdConnect(flags) {
11
- const log = (level, line) => {
31
+ const runtime = await acquireBridgeRuntimeLock(stateDir());
32
+ try {
33
+ await runConnect(flags);
34
+ }
35
+ finally {
36
+ await runtime.release().catch(() => undefined);
37
+ }
38
+ }
39
+ async function runConnect(flags) {
40
+ // 两阶段:授权/建连期逐行日志;会话起来后(TTY)切面板模式
41
+ let log = (level, line) => {
12
42
  if (level === 'info')
13
43
  console.log(C.dim(line));
14
44
  else
15
45
  console.error(level === 'error' ? C.red(line) : C.yellow(line));
16
46
  };
17
- const { session } = await startBridge(flags, log);
18
- out.info('[agent-bridge] 已就绪(Ctrl+C 退出)');
19
- await hold(() => session.close());
47
+ const { session, config } = await startBridge(flags, (level, line) => log(level, line));
48
+ // connect 默认自带本机 Web 面板:不进 serve、不额外加参数,也能直接打开看任务。
49
+ // 只绑回环、必须带令牌;端口占用时从 8787 起顺延,全部失败才降级为无 Web 面板。
50
+ const settings = resolveControlPlane(config?.controlPlane);
51
+ const uiToken = `abs_ui_${randomBytes(16).toString('hex')}`;
52
+ const verifyWithUi = (token, scope) => {
53
+ const required = Array.isArray(scope) ? scope : [scope];
54
+ // 面板令牌是只读的:允许读会话/任务/设备;写操作仍必须用 services issue 签发的令牌
55
+ const readOnly = ['task:read', 'session:read', 'device:read'];
56
+ if (token === uiToken && required.every((s) => readOnly.includes(s)))
57
+ return { ok: true };
58
+ return verifyServiceToken(token, scope);
59
+ };
60
+ let plane;
61
+ let webUrl;
62
+ const basePort = settings.port > 0 ? settings.port : 8787;
63
+ try {
64
+ plane = await withPortFallback(basePort, 20, (port) => startControlPlane({
65
+ enabled: true,
66
+ host: settings.host,
67
+ port,
68
+ requireToken: settings.requireToken,
69
+ // A2A/ACP 网关(默认关闭):resolveGateway 读 [gateway] 配置与环境变量
70
+ gateway: resolveGateway(config?.gateway),
71
+ }, {
72
+ emitter: session.emitter,
73
+ registry: session.registry,
74
+ store: session.store,
75
+ artifacts: session.artifacts,
76
+ artifactsForTenant: (tenantId) => session.artifactsForTenant(tenantId),
77
+ startTask: (req, hooks) => startTask(req, hooks),
78
+ respondInteraction: (msg) => session.respondInteraction(msg),
79
+ // conversation 编排(add-acp-session-memory):与 WS 通道同一份 dispatchOptions
80
+ conversation: session.conversation,
81
+ partialMessages: (taskId) => session.partialMessages(taskId),
82
+ scan: (opts) => scanAgents(opts),
83
+ log,
84
+ verify: verifyWithUi,
85
+ ...(config?.jwt
86
+ ? {
87
+ jwt: new JwtVerifier({
88
+ jwks: config.jwt.jwksUrl,
89
+ issuer: config.jwt.issuer,
90
+ audience: config.jwt.audience,
91
+ tenantClaim: config.jwt.tenantClaim,
92
+ cacheMs: config.jwt.cacheMs,
93
+ }),
94
+ }
95
+ : {}),
96
+ capabilities: PROTOCOL_CAPABILITIES,
97
+ version: version(),
98
+ // 网关 agent card 的 skills 数据源:静态适配器表(不触发扫描)
99
+ gatewayAgents: AGENTS.map((a) => ({ id: a.kind, name: a.display })),
100
+ defaults: {
101
+ allowedCwd: config?.allowedCwd,
102
+ maxConcurrent: resolveMaxTasks(config?.maxTasks, numFlagMin(flags, 'max-tasks', 1)),
103
+ maxQueued: resolveMaxQueued(config?.maxQueued, numFlagMin(flags, 'max-queue', 0)),
104
+ diffMaxBytes: resolveDiffMaxBytes(config?.diffMaxBytes),
105
+ captureDiffByDefault: config?.diffDefault === true,
106
+ // 控制面与 WS 共用同一套权限策略,不能被本地通道绕过
107
+ permissionPolicy: resolvePermissionPolicy(config?.permissionPolicy, strFlag(flags, 'permission-policy')),
108
+ externalSandbox: resolveExternalSandbox(config?.externalSandbox, boolFlag(flags, 'external-sandbox')),
109
+ },
110
+ }));
111
+ if (plane)
112
+ webUrl = `${plane.url}/?token=${uiToken}`;
113
+ }
114
+ catch (error) {
115
+ log('warn', `[agent-bridge] 本机 Web 面板启动失败:${error.message}`);
116
+ }
117
+ if (!plane) {
118
+ log('warn', `[agent-bridge] ${basePort} 起连续 20 个端口均不可用,本次不提供 Web 面板`);
119
+ }
120
+ if (!process.stdout.isTTY && webUrl) {
121
+ out.ok(`📊 Web 任务面板 ${webUrl}`);
122
+ }
123
+ const panel = startPanel({
124
+ registry: session.registry,
125
+ capacity: () => defaultSupervisor.capacitySnapshot(),
126
+ platformUrl: config?.platformUrl ?? '',
127
+ deviceName: config?.label ?? hostname(),
128
+ ...(webUrl ? { webUrl } : {}),
129
+ });
130
+ if (panel)
131
+ log = panelLog(panel);
132
+ log('info', '[agent-bridge] 已就绪(Ctrl+C 退出)');
133
+ await hold(() => {
134
+ panel?.stop();
135
+ plane?.close();
136
+ session.close();
137
+ });
20
138
  }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * daemon 系统服务定义(纯函数,便于测试与 --dry-run)。
3
+ *
4
+ * 范围(2026-10-26 决策):
5
+ * - Linux: systemd --user(不要求 root)
6
+ * - macOS: LaunchAgent(当前用户)
7
+ * - Windows: 当前用户计划任务(ONLOGON;Windows Service 需要管理员,先不选)
8
+ */
9
+ export const SERVICE_NAME = 'agent-bridge';
10
+ function quoted(value) {
11
+ return `"${value.replace(/(["\\])/g, '\\$1')}"`;
12
+ }
13
+ export function serviceArgs(cmd) {
14
+ return [cmd.nodePath, cmd.cliPath, 'connect', cmd.platformUrl];
15
+ }
16
+ export function renderSystemdUnit(cmd) {
17
+ return [
18
+ '[Unit]',
19
+ 'Description=Agent Bridge Service',
20
+ 'After=network-online.target',
21
+ '',
22
+ '[Service]',
23
+ 'Type=simple',
24
+ `ExecStart=${serviceArgs(cmd).map(quoted).join(' ')}`,
25
+ 'Restart=on-failure',
26
+ 'RestartSec=3',
27
+ '',
28
+ '[Install]',
29
+ 'WantedBy=default.target',
30
+ '',
31
+ ].join('\n');
32
+ }
33
+ function xml(value) {
34
+ return value
35
+ .replace(/&/g, '&amp;')
36
+ .replace(/</g, '&lt;')
37
+ .replace(/>/g, '&gt;')
38
+ .replace(/"/g, '&quot;');
39
+ }
40
+ export function renderLaunchdPlist(cmd) {
41
+ const args = serviceArgs(cmd)
42
+ .map((arg) => ` <string>${xml(arg)}</string>`)
43
+ .join('\n');
44
+ return [
45
+ '<?xml version="1.0" encoding="UTF-8"?>',
46
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
47
+ '<plist version="1.0">',
48
+ '<dict>',
49
+ ' <key>Label</key>',
50
+ ` <string>com.${SERVICE_NAME}</string>`,
51
+ ' <key>ProgramArguments</key>',
52
+ ' <array>',
53
+ args,
54
+ ' </array>',
55
+ ' <key>RunAtLoad</key>',
56
+ ' <true/>',
57
+ ' <key>KeepAlive</key>',
58
+ ' <true/>',
59
+ '</dict>',
60
+ '</plist>',
61
+ '',
62
+ ].join('\n');
63
+ }
64
+ /** schtasks /TR 需要的是“一条命令行字符串”,不是 argv 数组 */
65
+ export function windowsTaskCommand(cmd) {
66
+ return serviceArgs(cmd).map(quoted).join(' ');
67
+ }
68
+ export function schtasksCreateArgs(cmd) {
69
+ return [
70
+ '/Create',
71
+ '/TN',
72
+ SERVICE_NAME,
73
+ '/TR',
74
+ windowsTaskCommand(cmd),
75
+ '/SC',
76
+ 'ONLOGON',
77
+ '/RL',
78
+ 'LIMITED',
79
+ '/F',
80
+ ];
81
+ }
@@ -1,13 +1,276 @@
1
1
  /**
2
- * `agent-bridge daemon` —— 后台常驻(Phase 3,**尚未实现**)
2
+ * `agent-bridge daemon` —— 轻量后台进程管理(不依赖 systemd/launchd)。
3
3
  *
4
- * 保留 stub 而不是删命令:README 与 `doc:check` 都声明了它,
5
- * 且用户按习惯敲 `daemon start` 时应该得到明确说明而不是「未知命令」。
4
+ * start/stop/status 是真实实现:detached 子进程 + PID 文件 + 日志文件。
5
+ * install/uninstall(注册系统服务)仍明确提示未实现,避免冒充平台服务管理器。
6
6
  */
7
- import { posFlag } from '../cli/flags.js';
7
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { execFileSync, spawn } from 'node:child_process';
9
+ import { homedir } from 'node:os';
10
+ import { dirname, join } from 'node:path';
11
+ import { boolFlag, posFlag, strFlag } from '../cli/flags.js';
8
12
  import { out } from '../cli/render.js';
13
+ import { stateDir } from '../infra/config.js';
14
+ import { renderLaunchdPlist, renderSystemdUnit, schtasksCreateArgs, SERVICE_NAME, } from './daemon-service.js';
15
+ function pidPath() {
16
+ return join(stateDir(), 'daemon.pid');
17
+ }
18
+ function logPath() {
19
+ return join(stateDir(), 'daemon.log');
20
+ }
21
+ export function readDaemonPid(path = pidPath()) {
22
+ try {
23
+ const raw = readFileSync(path, 'utf8').trim();
24
+ const pid = Number(raw);
25
+ return Number.isInteger(pid) && pid > 0 ? pid : undefined;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ export function isPidAlive(pid) {
32
+ try {
33
+ process.kill(pid, 0);
34
+ return true;
35
+ }
36
+ catch (error) {
37
+ return error.code === 'EPERM';
38
+ }
39
+ }
40
+ function forwardFlags(flags) {
41
+ const keys = ['token', 'label', 'max-tasks', 'max-queue', 'diff-max-bytes', 'allowed-cwd'];
42
+ const args = [];
43
+ for (const key of keys) {
44
+ const value = strFlag(flags, key);
45
+ if (value !== undefined)
46
+ args.push(`--${key}=${value}`);
47
+ }
48
+ if (boolFlag(flags, 'no-browser'))
49
+ args.push('--no-browser');
50
+ return args;
51
+ }
52
+ function start(flags) {
53
+ const existing = readDaemonPid();
54
+ if (existing && isPidAlive(existing)) {
55
+ out.warn(`[agent-bridge] daemon 已在运行(pid ${existing})`);
56
+ return;
57
+ }
58
+ if (existsSync(pidPath()))
59
+ rmSync(pidPath(), { force: true });
60
+ const platformUrl = posFlag(flags, 2);
61
+ if (!platformUrl) {
62
+ out.error('[agent-bridge] daemon start 需要 platformUrl(或先在配置中写入 platformUrl)');
63
+ process.exitCode = 2;
64
+ return;
65
+ }
66
+ mkdirSync(stateDir(), { recursive: true });
67
+ const logFd = openSync(logPath(), 'a');
68
+ const argv = [process.argv[1] ?? '', 'connect', platformUrl, ...forwardFlags(flags)];
69
+ const child = spawn(process.execPath, argv, {
70
+ detached: true,
71
+ stdio: ['ignore', logFd, logFd],
72
+ windowsHide: true,
73
+ env: process.env,
74
+ });
75
+ closeSync(logFd);
76
+ child.unref();
77
+ if (!child.pid) {
78
+ out.error('[agent-bridge] daemon 启动失败:没有拿到 pid');
79
+ process.exitCode = 1;
80
+ return;
81
+ }
82
+ writeFileSync(pidPath(), `${child.pid}\n`, 'utf8');
83
+ out.ok(`[agent-bridge] daemon 已启动(pid ${child.pid})`);
84
+ out.info(`日志:${logPath()}`);
85
+ }
86
+ function stop() {
87
+ const pid = readDaemonPid();
88
+ if (!pid) {
89
+ out.warn('[agent-bridge] daemon 未运行(没有 pid 文件)');
90
+ return;
91
+ }
92
+ if (!isPidAlive(pid)) {
93
+ rmSync(pidPath(), { force: true });
94
+ out.warn(`[agent-bridge] daemon 已不在运行(陈旧 pid ${pid},已清理)`);
95
+ return;
96
+ }
97
+ try {
98
+ process.kill(pid, 'SIGTERM');
99
+ out.ok(`[agent-bridge] 已发送停止信号(pid ${pid})`);
100
+ }
101
+ catch (error) {
102
+ out.error(`[agent-bridge] 停止失败:${error.message}`);
103
+ process.exitCode = 1;
104
+ return;
105
+ }
106
+ rmSync(pidPath(), { force: true });
107
+ }
108
+ function status() {
109
+ const pid = readDaemonPid();
110
+ if (!pid) {
111
+ out.info('[agent-bridge] daemon 未运行');
112
+ return;
113
+ }
114
+ if (isPidAlive(pid)) {
115
+ out.ok(`[agent-bridge] daemon 运行中(pid ${pid})`);
116
+ out.info(`日志:${logPath()}`);
117
+ }
118
+ else {
119
+ out.warn(`[agent-bridge] pid ${pid} 已失效(陈旧 pid 文件)`);
120
+ process.exitCode = 1;
121
+ }
122
+ }
123
+ function serviceCommand(flags) {
124
+ const platformUrl = posFlag(flags, 2);
125
+ if (!platformUrl) {
126
+ out.error(`[agent-bridge] daemon ${posFlag(flags, 1)} 需要 platformUrl`);
127
+ process.exitCode = 2;
128
+ return undefined;
129
+ }
130
+ const cliPath = process.argv[1];
131
+ if (!cliPath) {
132
+ out.error('[agent-bridge] 无法确定 CLI 路径(process.argv[1] 为空)');
133
+ process.exitCode = 1;
134
+ return undefined;
135
+ }
136
+ return { nodePath: process.execPath, cliPath, platformUrl };
137
+ }
138
+ function systemdPath() {
139
+ return join(homedir(), '.config', 'systemd', 'user', `${SERVICE_NAME}.service`);
140
+ }
141
+ function launchdPath() {
142
+ return join(homedir(), 'Library', 'LaunchAgents', `com.${SERVICE_NAME}.plist`);
143
+ }
144
+ function install(flags) {
145
+ const cmd = serviceCommand(flags);
146
+ if (!cmd)
147
+ return;
148
+ const dryRun = boolFlag(flags, 'dry-run');
149
+ if (process.platform === 'win32') {
150
+ const args = schtasksCreateArgs(cmd);
151
+ if (dryRun) {
152
+ out.info(`schtasks ${args.join(' ')}`);
153
+ return;
154
+ }
155
+ try {
156
+ execFileSync('schtasks', args, { stdio: 'inherit' });
157
+ out.ok(`[agent-bridge] 已注册当前用户登录任务:${SERVICE_NAME}`);
158
+ out.info('卸载:agent-bridge daemon uninstall');
159
+ }
160
+ catch (error) {
161
+ out.error(`[agent-bridge] 计划任务注册失败:${error.message}`);
162
+ process.exitCode = 1;
163
+ }
164
+ return;
165
+ }
166
+ if (process.platform === 'darwin') {
167
+ const content = renderLaunchdPlist(cmd);
168
+ const target = launchdPath();
169
+ if (dryRun) {
170
+ out.info(`# ${target}\n${content}`);
171
+ return;
172
+ }
173
+ mkdirSync(dirname(target), { recursive: true });
174
+ writeFileSync(target, content, 'utf8');
175
+ try {
176
+ execFileSync('launchctl', ['load', '-w', target], { stdio: 'inherit' });
177
+ out.ok(`[agent-bridge] 已注册 LaunchAgent:${target}`);
178
+ }
179
+ catch (error) {
180
+ out.error(`[agent-bridge] LaunchAgent 注册失败:${error.message}`);
181
+ process.exitCode = 1;
182
+ }
183
+ return;
184
+ }
185
+ const content = renderSystemdUnit(cmd);
186
+ const target = systemdPath();
187
+ if (dryRun) {
188
+ out.info(`# ${target}\n${content}`);
189
+ return;
190
+ }
191
+ mkdirSync(dirname(target), { recursive: true });
192
+ writeFileSync(target, content, 'utf8');
193
+ try {
194
+ execFileSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'inherit' });
195
+ execFileSync('systemctl', ['--user', 'enable', '--now', `${SERVICE_NAME}.service`], {
196
+ stdio: 'inherit',
197
+ });
198
+ out.ok(`[agent-bridge] 已注册 systemd user 服务:${target}`);
199
+ }
200
+ catch (error) {
201
+ out.error(`[agent-bridge] systemd 服务注册失败:${error.message}`);
202
+ process.exitCode = 1;
203
+ }
204
+ }
205
+ function uninstall(flags) {
206
+ const dryRun = boolFlag(flags, 'dry-run');
207
+ if (process.platform === 'win32') {
208
+ const args = ['/Delete', '/TN', SERVICE_NAME, '/F'];
209
+ if (dryRun) {
210
+ out.info(`schtasks ${args.join(' ')}`);
211
+ return;
212
+ }
213
+ try {
214
+ execFileSync('schtasks', args, { stdio: 'inherit' });
215
+ out.ok(`[agent-bridge] 已删除计划任务:${SERVICE_NAME}`);
216
+ }
217
+ catch (error) {
218
+ out.error(`[agent-bridge] 计划任务删除失败:${error.message}`);
219
+ process.exitCode = 1;
220
+ }
221
+ return;
222
+ }
223
+ if (process.platform === 'darwin') {
224
+ const target = launchdPath();
225
+ if (dryRun) {
226
+ out.info(`launchctl unload -w ${target}\nrm ${target}`);
227
+ return;
228
+ }
229
+ try {
230
+ execFileSync('launchctl', ['unload', '-w', target], { stdio: 'inherit' });
231
+ }
232
+ catch {
233
+ /* 未加载时继续删文件 */
234
+ }
235
+ rmSync(target, { force: true });
236
+ out.ok(`[agent-bridge] 已移除 LaunchAgent:${target}`);
237
+ return;
238
+ }
239
+ const target = systemdPath();
240
+ if (dryRun) {
241
+ out.info(`systemctl --user disable --now ${SERVICE_NAME}.service\nrm ${target}`);
242
+ return;
243
+ }
244
+ try {
245
+ execFileSync('systemctl', ['--user', 'disable', '--now', `${SERVICE_NAME}.service`], {
246
+ stdio: 'inherit',
247
+ });
248
+ }
249
+ catch {
250
+ /* 未启用时继续删文件 */
251
+ }
252
+ rmSync(target, { force: true });
253
+ try {
254
+ execFileSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'inherit' });
255
+ }
256
+ catch {
257
+ /* daemon-reload 失败不阻塞卸载 */
258
+ }
259
+ out.ok(`[agent-bridge] 已移除 systemd user 服务:${target}`);
260
+ }
9
261
  export function cmdDaemon(flags) {
10
262
  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>');
263
+ if (sub === 'start')
264
+ return start(flags);
265
+ if (sub === 'stop')
266
+ return stop();
267
+ if (sub === 'status')
268
+ return status();
269
+ if (sub === 'install')
270
+ return install(flags);
271
+ if (sub === 'uninstall')
272
+ return uninstall(flags);
273
+ out.warn(`[agent-bridge] 未知 daemon 子命令:${sub}`);
274
+ out.info('用法:agent-bridge daemon start <platformUrl> | stop | status | install <platformUrl> | uninstall');
275
+ process.exitCode = 2;
13
276
  }
@@ -5,14 +5,17 @@
5
5
  * 「本地已登出但平台还挂着这台设备」的错配)。
6
6
  */
7
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('提示:如需让平台侧同步下线,请到「设备管理」里吊销该设备。');
8
+ import { clearConfig, loadConfig, stateDir } from '../infra/config.js';
9
+ import { withProfileLock } from '../infra/profile-lock.js';
10
+ export async function cmdLogout() {
11
+ await withProfileLock(stateDir(), async () => {
12
+ const cfg = loadConfig();
13
+ if (!cfg) {
14
+ out.info('[agent-bridge] 未绑定任何平台');
15
+ return;
16
+ }
17
+ await clearConfig();
18
+ out.ok(`✅ 已清除本地设备凭证(${cfg.deviceId}),设备身份与业务设置已保留`);
19
+ out.info('提示:如需让平台侧同步下线,请到「设备管理」里吊销该设备。');
20
+ });
18
21
  }