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.
- package/CHANGELOG.md +112 -140
- package/README.md +508 -35
- package/README.zh-CN.md +443 -33
- package/assets/agent-icons/agy.svg +27 -0
- package/dist/adapters/acp-auth.js +51 -0
- package/dist/adapters/acp-codebuddy.js +507 -0
- package/dist/adapters/agent-adapters.js +466 -46
- package/dist/adapters/claude-stream.js +159 -0
- package/dist/adapters/codex-app-server.js +310 -0
- package/dist/adapters/host-env.js +48 -0
- package/dist/adapters/mcp-elicitation.js +148 -0
- package/dist/adapters/mcp-host.js +70 -0
- package/dist/adapters/step-parsers.js +583 -0
- package/dist/app/bootstrap.js +163 -74
- package/dist/app/claude-resident.js +204 -0
- package/dist/app/conversation.js +639 -0
- package/dist/app/service-gate.js +1 -1
- package/dist/app/session.js +425 -14
- package/dist/app/task-dispatch.js +883 -7
- package/dist/app/task-registry.js +168 -0
- package/dist/cli/dispatch.js +4 -0
- package/dist/cli/flags.js +11 -0
- package/dist/cli/help.js +25 -7
- package/dist/cli/panel.js +334 -0
- package/dist/cli/render.js +2 -0
- package/dist/commands/approvals.js +80 -0
- package/dist/commands/connect.js +122 -4
- package/dist/commands/daemon-service.js +81 -0
- package/dist/commands/daemon.js +269 -6
- package/dist/commands/logout.js +13 -10
- package/dist/commands/serve.js +98 -12
- package/dist/commands/sessions.js +106 -0
- package/dist/core/ansi.js +5 -0
- package/dist/core/artifact-extract.js +158 -0
- package/dist/core/artifact-transfer.js +583 -0
- package/dist/core/device-identity.js +22 -0
- package/dist/core/emitter.js +50 -8
- package/dist/core/errors.js +43 -0
- package/dist/core/form-schema.js +72 -0
- package/dist/core/interaction-broker.js +440 -0
- package/dist/core/interaction-url.js +63 -0
- package/dist/core/partial-messages.js +99 -0
- package/dist/core/permission-ledger.js +146 -0
- package/dist/core/permission-policy.js +88 -0
- package/dist/core/port-fallback.js +22 -0
- package/dist/core/redact.js +13 -0
- package/dist/core/scan.js +12 -7
- package/dist/core/session-store.js +1632 -0
- package/dist/core/task-supervisor.js +955 -30
- package/dist/infra/atomic-file.js +111 -0
- package/dist/infra/audit.js +7 -0
- package/dist/infra/auth.js +167 -42
- package/dist/infra/config.js +511 -72
- package/dist/infra/device-identity-store.js +87 -0
- package/dist/infra/jwt.js +149 -0
- package/dist/infra/profile-lock.js +295 -0
- package/dist/infra/proxy-env.js +60 -0
- package/dist/infra/service-token.js +25 -4
- package/dist/protocol.js +298 -2
- package/dist/transport/a2a-mapping.js +206 -0
- package/dist/transport/acp-gateway-mapping.js +186 -0
- package/dist/transport/bridge-client.js +31 -22
- package/dist/transport/control-plane-page.js +820 -0
- package/dist/transport/control-plane-sessions-page.js +90 -0
- package/dist/transport/control-plane.js +923 -71
- package/dist/transport/gateway.js +1005 -0
- package/dist/transport/office-preview.js +154 -0
- package/package.json +6 -3
- package/assets/agent-icons/gemini.svg +0 -1
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"><title>Antigravity CLI</title><g transform="translate(-1.3209 -1.6007) scale(0.238806)"><path d="M89.6992 93.695C94.3659 97.195 101.366 94.8617 94.9492 88.445C75.6992 69.7783 79.7825 18.445 55.8659 18.445C31.9492 18.445 36.0325 69.7783 16.7825 88.445C9.78251 95.445 17.3658 97.195 22.0325 93.695C40.1159 81.445 38.9492 59.8617 55.8659 59.8617C72.7825 59.8617 71.6159 81.445 89.6992 93.695Z" fill="#3186FF"/>
|
|
2
|
+
<mask id="ag_fav_m" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="13" y="18" width="85" height="78">
|
|
3
|
+
<path d="M89.6992 93.695C94.3659 97.195 101.366 94.8617 94.9492 88.445C75.6992 69.7783 79.7825 18.445 55.8659 18.445C31.9492 18.445 36.0325 69.7783 16.7825 88.445C9.78251 95.445 17.3658 97.195 22.0325 93.695C40.1159 81.445 38.9492 59.8617 55.8659 59.8617C72.7825 59.8617 71.6159 81.445 89.6992 93.695Z" fill="black"/>
|
|
4
|
+
</mask>
|
|
5
|
+
<g mask="url(#ag_fav_m)">
|
|
6
|
+
<g filter="url(#ag_fav_f0)"><ellipse cx="22.7873" cy="26.8098" rx="22.7873" ry="26.8098" transform="matrix(-0.112784 0.99362 -0.99362 -0.112781 66.2473 -15.5344)" fill="#FFE432"/></g>
|
|
7
|
+
<g filter="url(#ag_fav_f1)"><ellipse cx="96.491" cy="35.1231" rx="29.5007" ry="30.1492" transform="rotate(76.9243 96.491 35.1231)" fill="#FC413D"/></g>
|
|
8
|
+
<g filter="url(#ag_fav_f2)"><ellipse cx="9.02988" cy="41.6647" rx="30.832" ry="39.9417" transform="rotate(74.1257 9.02988 41.6647)" fill="#00B95C"/></g>
|
|
9
|
+
<g filter="url(#ag_fav_f3)"><ellipse cx="11.2212" cy="42.8915" rx="30.22" ry="33.2695" transform="rotate(45.6065 11.2212 42.8915)" fill="#00B95C"/></g>
|
|
10
|
+
<g filter="url(#ag_fav_f4)"><ellipse cx="75.7546" cy="104.822" rx="29.0177" ry="27.943" transform="rotate(76.9243 75.7546 104.822)" fill="#3186FF"/></g>
|
|
11
|
+
<g filter="url(#ag_fav_f5)"><ellipse cx="33.5661" cy="35.4043" rx="33.5661" ry="35.4043" transform="matrix(-0.409539 0.912293 -0.912294 -0.409537 101.25 -15.1674)" fill="#FBBC04"/></g>
|
|
12
|
+
<g filter="url(#ag_fav_f6)"><path d="M2.56802 149.695C-15.8116 142.48 15.5987 83.1163 23.4093 63.2203C31.22 43.3244 52.4514 33.0447 70.831 40.26C89.2107 47.4753 110.996 87.2162 103.185 107.112C95.3742 127.008 20.9477 156.91 2.56802 149.695Z" fill="#3186FF"/></g>
|
|
13
|
+
<g filter="url(#ag_fav_f7)"><path d="M113.934 75.8079C109.013 81.5509 96.1724 78.6224 85.253 69.2667C74.3335 59.911 69.4704 47.6711 74.391 41.928C79.3116 36.185 92.1525 39.1136 103.072 48.4692C113.991 57.8249 118.855 70.0648 113.934 75.8079Z" fill="#749BFF"/></g>
|
|
14
|
+
<g filter="url(#ag_fav_f8)"><ellipse cx="92.611" cy="23.7962" rx="44.2411" ry="27.5016" transform="rotate(34.0763 92.611 23.7962)" fill="#FC413D"/></g>
|
|
15
|
+
<g filter="url(#ag_fav_f9)"><ellipse cx="23.4949" cy="29.5887" rx="23.7071" ry="13.7869" transform="rotate(112.516 23.4949 29.5887)" fill="#FFEE48"/></g>
|
|
16
|
+
</g></g><defs>
|
|
17
|
+
<filter id="ag_fav_f0" x="2.49348" y="-26.5423" width="69.0899" height="61.2525" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="3.89034"/></filter>
|
|
18
|
+
<filter id="ag_fav_f1" x="28.7524" y="-32.0333" width="135.477" height="134.313" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="18.8078"/></filter>
|
|
19
|
+
<filter id="ag_fav_f2" x="-62.2884" y="-21.9253" width="142.637" height="127.18" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="15.9884"/></filter>
|
|
20
|
+
<filter id="ag_fav_f3" x="-52.5697" y="-20.8346" width="127.582" height="127.452" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="15.9884"/></filter>
|
|
21
|
+
<filter id="ag_fav_f4" x="17.3619" y="45.4646" width="116.786" height="118.715" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="15.1937"/></filter>
|
|
22
|
+
<filter id="ag_fav_f5" x="-7.44765" y="-60.4737" width="125.303" height="122.858" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="13.7698"/></filter>
|
|
23
|
+
<filter id="ag_fav_f6" x="-27.7086" y="13.3597" width="157.119" height="162.029" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="12.297"/></filter>
|
|
24
|
+
<filter id="ag_fav_f7" x="50.4638" y="16.981" width="87.3973" height="83.7738" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="11.0036"/></filter>
|
|
25
|
+
<filter id="ag_fav_f8" x="34.2604" y="-28.457" width="116.701" height="104.506" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="9.29385"/></filter>
|
|
26
|
+
<filter id="ag_fav_f9" x="-15.1522" y="-15.9493" width="77.2941" height="91.076" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="11.5027"/></filter>
|
|
27
|
+
</defs></svg>
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CodeBuddy ACP 认证继承。
|
|
3
|
+
*
|
|
4
|
+
* WorkBuddy 桌面把 CodeBuddy 的登录态放在 CodeBuddyExtension 的 auth/*.info:
|
|
5
|
+
* - workbuddy-desktop.info 的 token 是 WorkBuddy 加密信封(本进程无法解密)
|
|
6
|
+
* - Tencent-Cloud.coding-copilot.info 是明文 JWT,可直接作为 CODEBUDDY_AUTH_TOKEN
|
|
7
|
+
*
|
|
8
|
+
* ACP 子进程必须显式拿到 CODEBUDDY_AUTH_TOKEN;仅继承父进程环境不足(桌面进程的
|
|
9
|
+
* token 不落在可读环境里)。这里只负责“找到可用明文 token”,环境清理在适配器里做。
|
|
10
|
+
*/
|
|
11
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
12
|
+
import { homedir } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
export function codeBuddyAuthDir() {
|
|
15
|
+
if (process.env['CODEBUDDY_AUTH_DIR'])
|
|
16
|
+
return process.env['CODEBUDDY_AUTH_DIR'];
|
|
17
|
+
if (process.platform === 'win32') {
|
|
18
|
+
return join(process.env['LOCALAPPDATA'] ?? join(homedir(), 'AppData', 'Local'), 'CodeBuddyExtension', 'Data', 'Public', 'auth');
|
|
19
|
+
}
|
|
20
|
+
if (process.platform === 'darwin') {
|
|
21
|
+
return join(homedir(), 'Library', 'Application Support', 'CodeBuddyExtension', 'Data', 'Public', 'auth');
|
|
22
|
+
}
|
|
23
|
+
return join(homedir(), '.local', 'share', 'CodeBuddyExtension', 'Data', 'Public', 'auth');
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* 找可用明文 token。只接受字符串 token;加密信封($wbEncrypted)直接跳过。
|
|
27
|
+
* 不读日志、不返回文件内容。
|
|
28
|
+
*/
|
|
29
|
+
export function resolveCodeBuddyAuthToken(dir = codeBuddyAuthDir(), now = Date.now()) {
|
|
30
|
+
if (!existsSync(dir))
|
|
31
|
+
return undefined;
|
|
32
|
+
const files = readdirSync(dir)
|
|
33
|
+
.filter((name) => name.endsWith('.info'))
|
|
34
|
+
.sort((a, b) => a.includes('coding-copilot') ? -1 : b.includes('coding-copilot') ? 1 : 0);
|
|
35
|
+
for (const name of files) {
|
|
36
|
+
try {
|
|
37
|
+
const parsed = JSON.parse(readFileSync(join(dir, name), 'utf8'));
|
|
38
|
+
const token = parsed.auth?.accessToken;
|
|
39
|
+
if (typeof token !== 'string' || token.length < 20)
|
|
40
|
+
continue;
|
|
41
|
+
const expiresAt = parsed.auth?.expiresAt;
|
|
42
|
+
if (typeof expiresAt === 'number' && expiresAt <= now)
|
|
43
|
+
continue;
|
|
44
|
+
return token;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
/* 跳过损坏/非 JSON 文件 */
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CodeBuddy ACP (v1) adapter.
|
|
3
|
+
*
|
|
4
|
+
* Verified against CodeBuddy 2.174.0:
|
|
5
|
+
* codebuddy --serve --acp --port 0
|
|
6
|
+
* -> initialize / session/new / session/prompt over NDJSON stdio.
|
|
7
|
+
*
|
|
8
|
+
* Important: WorkBuddy's own CodeBuddy process sets SERVER__PORT (e.g. 61899).
|
|
9
|
+
* If inherited, the ACP child tries to bind the same port and dies with EADDRINUSE.
|
|
10
|
+
* The adapter therefore always starts from a sanitized env and requires an explicit
|
|
11
|
+
* CODEBUDDY_AUTH_TOKEN; encrypted host credentials are never read or decrypted.
|
|
12
|
+
*/
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import { resolve } from 'node:path';
|
|
15
|
+
import { resolveCodeBuddyAuthToken } from './acp-auth.js';
|
|
16
|
+
import { killCliProcess, spawnCliProcess } from './agent-adapters.js';
|
|
17
|
+
import { withoutHostEnv } from './host-env.js';
|
|
18
|
+
import { redactDiagnostic } from '../core/redact.js';
|
|
19
|
+
import { externalProxyEnv } from '../infra/proxy-env.js';
|
|
20
|
+
export class AcpAuthRequiredError extends Error {
|
|
21
|
+
constructor(message = 'CodeBuddy ACP 需要 CODEBUDDY_AUTH_TOKEN(宿主未注入登录态)') {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'AcpAuthRequiredError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export function codebuddyAcpArgs() {
|
|
27
|
+
return ['--serve', '--acp', '--port', '0'];
|
|
28
|
+
}
|
|
29
|
+
export const CODEBUDDY_ACP_SPEC = {
|
|
30
|
+
command: 'codebuddy',
|
|
31
|
+
args: codebuddyAcpArgs(),
|
|
32
|
+
label: 'CodeBuddy',
|
|
33
|
+
authEnv: 'CODEBUDDY_AUTH_TOKEN',
|
|
34
|
+
sanitizeHostEnv: true,
|
|
35
|
+
};
|
|
36
|
+
export function canRunAcp(spec, env = process.env) {
|
|
37
|
+
if (!spec)
|
|
38
|
+
return false;
|
|
39
|
+
if (!spec.authEnv)
|
|
40
|
+
return true;
|
|
41
|
+
if (spec.authEnv === 'CODEBUDDY_AUTH_TOKEN')
|
|
42
|
+
return hasCodebuddyAcpAuth(env);
|
|
43
|
+
const token = env[spec.authEnv];
|
|
44
|
+
return typeof token === 'string' && token.trim() !== '';
|
|
45
|
+
}
|
|
46
|
+
export function codebuddyAcpEnv(source = process.env) {
|
|
47
|
+
// 清宿主注入变量(清单见 adapters/host-env.ts,与 headless 通道共用同一张表),再补认证令牌
|
|
48
|
+
const env = withoutHostEnv(source);
|
|
49
|
+
const token = env['CODEBUDDY_AUTH_TOKEN'] || resolveCodeBuddyAuthToken();
|
|
50
|
+
if (token)
|
|
51
|
+
env['CODEBUDDY_AUTH_TOKEN'] = token;
|
|
52
|
+
return env;
|
|
53
|
+
}
|
|
54
|
+
export function hasCodebuddyAcpAuth(env = process.env) {
|
|
55
|
+
const token = env['CODEBUDDY_AUTH_TOKEN'];
|
|
56
|
+
if (typeof token === 'string' && token.trim() !== '')
|
|
57
|
+
return true;
|
|
58
|
+
return resolveCodeBuddyAuthToken() !== undefined;
|
|
59
|
+
}
|
|
60
|
+
/** stderr 尾部保留上限:够看清最后一条错误栈,又不至于把整份日志塞进错误消息 */
|
|
61
|
+
export const ACP_STDERR_TAIL_LIMIT = 4 * 1024;
|
|
62
|
+
/**
|
|
63
|
+
* ACP 帧的行长上限(接收侧,tasks.md 5.2 / design「有界解析防 DoS」):
|
|
64
|
+
* readline 没有行长限制 —— 恶意/异常 agent 发一条永不换行的超长流会把缓冲撑到无界。
|
|
65
|
+
* 超限帧整帧丢弃并计数,后续正常行不受影响;上限取 1 MiB(交互 wire 上限 64 KiB 的
|
|
66
|
+
* 同量级放宽,容纳 transcript 重放类大 prompt 帧)。
|
|
67
|
+
*/
|
|
68
|
+
export const ACP_MAX_LINE_BYTES = 1024 * 1024;
|
|
69
|
+
export function createBoundedLineReader(limit = ACP_MAX_LINE_BYTES) {
|
|
70
|
+
let buf = '';
|
|
71
|
+
let dropped = 0;
|
|
72
|
+
let dropping = false;
|
|
73
|
+
return {
|
|
74
|
+
feed(chunk) {
|
|
75
|
+
const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
|
|
76
|
+
const out = [];
|
|
77
|
+
let data = buf + text;
|
|
78
|
+
let nl;
|
|
79
|
+
while ((nl = data.indexOf('\n')) >= 0) {
|
|
80
|
+
const line = data.slice(0, nl);
|
|
81
|
+
data = data.slice(nl + 1);
|
|
82
|
+
if (dropping) {
|
|
83
|
+
// 上一帧超限被丢弃:这个换行是它的结束,本身不产出
|
|
84
|
+
dropping = false;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (line.length > limit) {
|
|
88
|
+
dropped += 1;
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
out.push(line);
|
|
92
|
+
}
|
|
93
|
+
buf = data;
|
|
94
|
+
if (buf.length > limit) {
|
|
95
|
+
// 未终止帧已超限(无换行的持续流):丢弃累积并进入丢弃态直到换行
|
|
96
|
+
if (!dropping)
|
|
97
|
+
dropped += 1;
|
|
98
|
+
dropping = true;
|
|
99
|
+
buf = '';
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
},
|
|
103
|
+
flush() {
|
|
104
|
+
if (dropping || !buf) {
|
|
105
|
+
buf = '';
|
|
106
|
+
return [];
|
|
107
|
+
}
|
|
108
|
+
const rest = buf.length > limit ? [] : [buf];
|
|
109
|
+
buf = '';
|
|
110
|
+
return rest;
|
|
111
|
+
},
|
|
112
|
+
droppedFrames() {
|
|
113
|
+
return dropped;
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
/** 只保留末尾 limit 个字符(纯函数,便于单测) */
|
|
118
|
+
export function tailOf(text, limit = ACP_STDERR_TAIL_LIMIT) {
|
|
119
|
+
return text.length > limit ? text.slice(text.length - limit) : text;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* 子进程 stderr 尾部缓冲。
|
|
123
|
+
*
|
|
124
|
+
* 为什么必须读而不是 destroy:ACP agent(尤其 opencode/mimo 这类 Bun 编译的二进制)
|
|
125
|
+
* 会往 stderr 打配置错误、认证提示、模型缺失等**唯一可解释失败原因**的信息。
|
|
126
|
+
* 不读有两个后果:①失败只剩一个退出码,用户无法自查;②pipe 缓冲写满后子进程会阻塞在
|
|
127
|
+
* write 上,表现为「挂住不动」——这比报错难查得多。
|
|
128
|
+
*/
|
|
129
|
+
function deliveryFuture() {
|
|
130
|
+
let settle;
|
|
131
|
+
const promise = new Promise((resolvePromise) => {
|
|
132
|
+
settle = resolvePromise;
|
|
133
|
+
});
|
|
134
|
+
return { promise, settle };
|
|
135
|
+
}
|
|
136
|
+
export function createStderrTail(limit = ACP_STDERR_TAIL_LIMIT) {
|
|
137
|
+
let tail = '';
|
|
138
|
+
return {
|
|
139
|
+
push: (chunk) => {
|
|
140
|
+
tail = tailOf(tail + (typeof chunk === 'string' ? chunk : chunk.toString('utf8')), limit);
|
|
141
|
+
},
|
|
142
|
+
text: () => tail,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
export async function runAcpPrompt(opts) {
|
|
146
|
+
const spec = opts.spec ?? CODEBUDDY_ACP_SPEC;
|
|
147
|
+
const baseEnv = spec.sanitizeHostEnv ? codebuddyAcpEnv(opts.env) : { ...(opts.env ?? process.env) };
|
|
148
|
+
const env = spec.preferSystemProxy ? externalProxyEnv(baseEnv) : baseEnv;
|
|
149
|
+
if (spec.authEnv && !canRunAcp(spec, env)) {
|
|
150
|
+
throw new AcpAuthRequiredError(`ACP 需要 ${spec.authEnv},未设置时不会启动无认证子进程`);
|
|
151
|
+
}
|
|
152
|
+
// Windows 的 npm 垫片(.cmd/.bat)不能直接 spawn(CreateProcess 报 EINVAL);
|
|
153
|
+
// 垫片处理统一收敛在 agent-adapters 的 spawnCliProcess(唯一被门禁放行的位置)。
|
|
154
|
+
const child = spawnCliProcess(spec.command, spec.args, { cwd: opts.cwd, env });
|
|
155
|
+
const label = opts.label ?? spec.label ?? 'ACP';
|
|
156
|
+
const stderrTail = createStderrTail();
|
|
157
|
+
child.stderr?.on('data', (chunk) => stderrTail.push(chunk));
|
|
158
|
+
/** 是否成功走过 authenticate;initialize 之后才有结论 */
|
|
159
|
+
let authenticated = false;
|
|
160
|
+
/** 需要登录但没登录的提示,只在失败时追加 */
|
|
161
|
+
let authHint = '';
|
|
162
|
+
/** 错误消息的「为什么」后缀:有 stderr 就带上尾部,没有就不加噪音 */
|
|
163
|
+
const why = () => {
|
|
164
|
+
const tail = redactDiagnostic(stderrTail.text().trim());
|
|
165
|
+
return `${tail ? `:${tail}` : ''}${authHint}`;
|
|
166
|
+
};
|
|
167
|
+
let nextId = 1;
|
|
168
|
+
const pending = new Map();
|
|
169
|
+
let sessionId = '';
|
|
170
|
+
let text = '';
|
|
171
|
+
// session/load 可重放历史 chunk(agy 1.5.9 实测);只有本轮 prompt 发出后才收集结果文本。
|
|
172
|
+
let collectAgentText = false;
|
|
173
|
+
let stopReason = 'unknown';
|
|
174
|
+
let closed = false;
|
|
175
|
+
let timedOut = false;
|
|
176
|
+
let aborted = false;
|
|
177
|
+
/** 已调用 write、等待 callback 的响应;进程关闭/错误必须立即以失败唤醒。 */
|
|
178
|
+
const responseWaiters = new Set();
|
|
179
|
+
const settleResponseWaiters = () => {
|
|
180
|
+
for (const finish of responseWaiters)
|
|
181
|
+
finish(false);
|
|
182
|
+
responseWaiters.clear();
|
|
183
|
+
};
|
|
184
|
+
const send = (message) => {
|
|
185
|
+
if (closed || !child.stdin.writable || child.stdin.destroyed)
|
|
186
|
+
return false;
|
|
187
|
+
try {
|
|
188
|
+
child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
189
|
+
// write() 的 false 只是背压(数据已进入缓冲区),不是交付失败;异常/关闭才是不确定。
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
const request = (method, params, timeoutMs = 15_000) => new Promise((resolvePromise, reject) => {
|
|
197
|
+
const id = nextId++;
|
|
198
|
+
const timer = setTimeout(() => {
|
|
199
|
+
pending.delete(id);
|
|
200
|
+
reject(new Error(`${label} ${method} 超时(${timeoutMs}ms)${why()}`));
|
|
201
|
+
}, timeoutMs);
|
|
202
|
+
pending.set(id, { resolve: resolvePromise, reject, timer });
|
|
203
|
+
send({ jsonrpc: '2.0', id, method, params });
|
|
204
|
+
});
|
|
205
|
+
const respond = (id, result) => {
|
|
206
|
+
if ((typeof id !== 'number' && typeof id !== 'string') || closed || !child.stdin.writable) {
|
|
207
|
+
return Promise.resolve(false);
|
|
208
|
+
}
|
|
209
|
+
return new Promise((resolvePromise) => {
|
|
210
|
+
let finished = false;
|
|
211
|
+
const finish = (delivered) => {
|
|
212
|
+
if (finished)
|
|
213
|
+
return;
|
|
214
|
+
finished = true;
|
|
215
|
+
responseWaiters.delete(finish);
|
|
216
|
+
resolvePromise(delivered);
|
|
217
|
+
};
|
|
218
|
+
responseWaiters.add(finish);
|
|
219
|
+
try {
|
|
220
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, result })}\n`, (error) => {
|
|
221
|
+
finish(!error);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
finish(false);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
};
|
|
229
|
+
const respondError = (id, code, message) => {
|
|
230
|
+
if (typeof id !== 'number' && typeof id !== 'string')
|
|
231
|
+
return;
|
|
232
|
+
send({ jsonrpc: '2.0', id, error: { code, message } });
|
|
233
|
+
};
|
|
234
|
+
const handleAgentRequest = async (message) => {
|
|
235
|
+
const method = String(message['method'] ?? '');
|
|
236
|
+
const params = (message['params'] ?? {});
|
|
237
|
+
if (method === 'session/request_permission') {
|
|
238
|
+
const delivery = deliveryFuture();
|
|
239
|
+
const options = Array.isArray(params['options']) ? params['options'] : [];
|
|
240
|
+
try {
|
|
241
|
+
const selected = opts.onPermission
|
|
242
|
+
? await opts.onPermission({
|
|
243
|
+
sessionId: String(params['sessionId'] ?? sessionId),
|
|
244
|
+
toolCall: params['toolCall'],
|
|
245
|
+
options,
|
|
246
|
+
delivery: delivery.promise,
|
|
247
|
+
})
|
|
248
|
+
: undefined;
|
|
249
|
+
delivery.settle(await (selected
|
|
250
|
+
? respond(message['id'], { outcome: { outcome: 'selected', optionId: selected } })
|
|
251
|
+
: respond(message['id'], { outcome: { outcome: 'cancelled' } })));
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
delivery.settle(false);
|
|
255
|
+
await respond(message['id'], { outcome: { outcome: 'cancelled' } });
|
|
256
|
+
}
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
// 表单有两个入口,语义一致(accept/decline/cancel + content),只是来源不同:
|
|
260
|
+
// - `session/request_form`:CodeBuddy 扩展方法,可能带 expiresAt 与自带 requestId;
|
|
261
|
+
// - `elicitation/create`:标准 ACP elicitation,requestId 只能由我们生成。
|
|
262
|
+
// 之前只认前者,等于把「标准 ACP 的工具能弹表单」这件事说成了已支持 —— 现在两条都收。
|
|
263
|
+
if (method === 'session/request_form' || method === 'elicitation/create') {
|
|
264
|
+
const delivery = deliveryFuture();
|
|
265
|
+
const requestId = typeof params['requestId'] === 'string' && params['requestId']
|
|
266
|
+
? params['requestId']
|
|
267
|
+
: `ir_${randomUUID().replace(/-/g, '').slice(0, 20)}`;
|
|
268
|
+
const requestedSchema = typeof params['requestedSchema'] === 'object' && params['requestedSchema'] !== null
|
|
269
|
+
? params['requestedSchema']
|
|
270
|
+
: {};
|
|
271
|
+
try {
|
|
272
|
+
const response = opts.onForm
|
|
273
|
+
? await opts.onForm({
|
|
274
|
+
sessionId: String(params['sessionId'] ?? sessionId),
|
|
275
|
+
requestId,
|
|
276
|
+
message: String(params['message'] ?? ''),
|
|
277
|
+
requestedSchema,
|
|
278
|
+
...(typeof params['expiresAt'] === 'string' ? { expiresAt: params['expiresAt'] } : {}),
|
|
279
|
+
delivery: delivery.promise,
|
|
280
|
+
})
|
|
281
|
+
: { action: 'cancel' };
|
|
282
|
+
delivery.settle(await respond(message['id'], response));
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
delivery.settle(false);
|
|
286
|
+
await respond(message['id'], { action: 'cancel' });
|
|
287
|
+
}
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
// fs/terminal 等 client 能力默认不开放;即使 agent 忽略 initialize 声明直接调用,
|
|
291
|
+
// 也统一返回 UnsupportedOperation,绝不能在这里绕过任务权限策略读写文件或执行命令。
|
|
292
|
+
if (message['id'] !== undefined) {
|
|
293
|
+
respondError(message['id'], -32601, `UnsupportedOperation: ${method}`);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
const handleMessage = (message) => {
|
|
297
|
+
const id = message['id'];
|
|
298
|
+
if (typeof id === 'number' && pending.has(id) && (message['result'] !== undefined || message['error'])) {
|
|
299
|
+
const p = pending.get(id);
|
|
300
|
+
if (!p)
|
|
301
|
+
return;
|
|
302
|
+
pending.delete(id);
|
|
303
|
+
clearTimeout(p.timer);
|
|
304
|
+
if (message['error']) {
|
|
305
|
+
// agent 用 JSON-RPC error 表达「未登录 / 模型缺失 / 配置非法」这类**唯一可解释**的原因,
|
|
306
|
+
// 原样 JSON.stringify 会把 message 埋进结构里;这里取 message 并补上 label。
|
|
307
|
+
const err = message['error'];
|
|
308
|
+
const detail = typeof err.message === 'string' ? err.message : JSON.stringify(err);
|
|
309
|
+
const code = typeof err.code === 'number' ? err.code : '?';
|
|
310
|
+
p.reject(new Error(`${label} 返回错误(${code}):${detail}${why()}`));
|
|
311
|
+
}
|
|
312
|
+
else
|
|
313
|
+
p.resolve(message['result']);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (message['method']) {
|
|
317
|
+
if (id !== undefined)
|
|
318
|
+
void handleAgentRequest(message);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
if (id !== undefined) {
|
|
322
|
+
// Unexpected response shape: never leave the peer waiting.
|
|
323
|
+
send({ jsonrpc: '2.0', id, result: {} });
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
// 有界行读取(5.2 帧上限):跨 chunk 半行重组 + 超限帧整帧丢弃(防无换行超长流的内存 DoS)
|
|
327
|
+
const lineReader = createBoundedLineReader();
|
|
328
|
+
const onLine = (line) => {
|
|
329
|
+
const trimmed = line.trim();
|
|
330
|
+
if (!trimmed.startsWith('{'))
|
|
331
|
+
return; // HTTP server banner / logs
|
|
332
|
+
try {
|
|
333
|
+
const message = JSON.parse(trimmed);
|
|
334
|
+
if (message['method'] === 'session/update') {
|
|
335
|
+
const params = (message['params'] ?? {});
|
|
336
|
+
const update = (params['update'] ?? {});
|
|
337
|
+
opts.onUpdate?.(update);
|
|
338
|
+
if (collectAgentText && update['sessionUpdate'] === 'agent_message_chunk') {
|
|
339
|
+
const content = update['content'];
|
|
340
|
+
if (content?.['type'] === 'text' && typeof content['text'] === 'string')
|
|
341
|
+
text += content['text'];
|
|
342
|
+
}
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
handleMessage(message);
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
/* non-JSON line */
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
child.stdout?.on('data', (chunk) => {
|
|
352
|
+
for (const line of lineReader.feed(chunk))
|
|
353
|
+
onLine(line);
|
|
354
|
+
});
|
|
355
|
+
child.stdout?.on('close', () => {
|
|
356
|
+
for (const line of lineReader.flush())
|
|
357
|
+
onLine(line);
|
|
358
|
+
});
|
|
359
|
+
const failAll = (error) => {
|
|
360
|
+
for (const p of pending.values()) {
|
|
361
|
+
clearTimeout(p.timer);
|
|
362
|
+
p.reject(error);
|
|
363
|
+
}
|
|
364
|
+
pending.clear();
|
|
365
|
+
};
|
|
366
|
+
child.on('error', (error) => {
|
|
367
|
+
settleResponseWaiters();
|
|
368
|
+
failAll(error);
|
|
369
|
+
});
|
|
370
|
+
child.on('close', (code) => {
|
|
371
|
+
closed = true;
|
|
372
|
+
settleResponseWaiters();
|
|
373
|
+
// 三条文案都必须带 label:这是 9 个工具共用的 runner,
|
|
374
|
+
// 写死成 CodeBuddy 会让 opencode/trae/grok 的失败被误判成另一个产品的问题。
|
|
375
|
+
failAll(new Error(timedOut
|
|
376
|
+
? `${label} 超时,进程已终止${why()}`
|
|
377
|
+
: aborted
|
|
378
|
+
? `${label} 已取消${why()}`
|
|
379
|
+
: `${label} 进程退出(code ${code ?? 'null'})${why()}`));
|
|
380
|
+
});
|
|
381
|
+
const timeoutMs = opts.timeoutMs ?? 10 * 60_000;
|
|
382
|
+
const cancel = () => {
|
|
383
|
+
if (sessionId)
|
|
384
|
+
send({ jsonrpc: '2.0', method: 'session/cancel', params: { sessionId } });
|
|
385
|
+
killCliProcess(child, spec.command);
|
|
386
|
+
};
|
|
387
|
+
const timer = setTimeout(() => {
|
|
388
|
+
timedOut = true;
|
|
389
|
+
cancel();
|
|
390
|
+
}, timeoutMs);
|
|
391
|
+
const onAbort = () => {
|
|
392
|
+
aborted = true;
|
|
393
|
+
cancel();
|
|
394
|
+
};
|
|
395
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
396
|
+
try {
|
|
397
|
+
const initialized = (await request('initialize', {
|
|
398
|
+
protocolVersion: 1,
|
|
399
|
+
clientInfo: { name: 'agent-bridge', version: '1.0.0' },
|
|
400
|
+
clientCapabilities: {
|
|
401
|
+
fs: { readTextFile: false, writeTextFile: false },
|
|
402
|
+
// 只有真正接了表单回调(= 本机交互开关打开且任务允许交互)才声明 elicitation。
|
|
403
|
+
// 声明了却回不了,agent 会发出 elicitation 然后拿到 cancel —— 不如一开始不声明。
|
|
404
|
+
...(opts.onForm ? { elicitation: {} } : {}),
|
|
405
|
+
},
|
|
406
|
+
}));
|
|
407
|
+
const methods = new Set((initialized.authMethods ?? [])
|
|
408
|
+
.map((method) => method.id)
|
|
409
|
+
.filter((id) => typeof id === 'string'));
|
|
410
|
+
// authMethod 不再按产品名硬编码:spec 里写明,或按「环境变量有值才用」的映射挑一个。
|
|
411
|
+
// 顺序上先试显式配置,不在列表里才看环境变量映射 —— 实测 grok 只声明 grok.com,
|
|
412
|
+
// 而写死 cached_token 时永远匹配不到,authenticate 就被静默跳过了。
|
|
413
|
+
const candidates = [
|
|
414
|
+
spec.authMethod,
|
|
415
|
+
...Object.entries(spec.authEnvMethods ?? {})
|
|
416
|
+
.filter(([key]) => (env[key] ?? '').trim() !== '')
|
|
417
|
+
.map(([, methodId]) => methodId),
|
|
418
|
+
].filter((methodId) => typeof methodId === 'string' && methodId !== '');
|
|
419
|
+
const authMethod = candidates.find((methodId) => methods.has(methodId));
|
|
420
|
+
if (authMethod) {
|
|
421
|
+
try {
|
|
422
|
+
// 认证给短超时:有的 agent 把 authenticate 当**交互登录入口**(grok.com 要开浏览器),
|
|
423
|
+
// headless 下不响应。原来用 15s 全局超时会白等,且失败就等于整个任务失败。
|
|
424
|
+
await request('authenticate', { methodId: authMethod, _meta: { headless: true } }, 5_000);
|
|
425
|
+
authenticated = true;
|
|
426
|
+
}
|
|
427
|
+
catch (error) {
|
|
428
|
+
// 认证没走通 ≠ 不能跑:很多 agent 靠自身已登录态照样能工作。
|
|
429
|
+
// 这里只记下原因、继续 session/new,让 agent 自己给出更准的错误。
|
|
430
|
+
const how = spec.loginCommand ? `,请先运行 \`${spec.loginCommand}\`` : '';
|
|
431
|
+
authHint = `(认证 ${authMethod} 未完成${how}:${error.message})`;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
// 声明了认证方式却没走成(未配 method / 配的 method 不在列表里):记下来,
|
|
435
|
+
// 失败时追加到错误文案。**不在这里抛错** —— mimo 这类工具会列 opencode-login,
|
|
436
|
+
// 但它靠自身已登录态照样能跑,硬失败会把能用的工具判死。
|
|
437
|
+
if (methods.size > 0 && !authenticated && !authHint) {
|
|
438
|
+
// 同时给「跑哪条命令」和「agent 声明的认证方式」:前者可操作,后者是证据。
|
|
439
|
+
const how = spec.loginCommand ? `请先运行 \`${spec.loginCommand}\` 完成登录;` : '';
|
|
440
|
+
authHint = `(${how}该工具声明了认证方式 ${[...methods].join(' / ')})`;
|
|
441
|
+
}
|
|
442
|
+
if (opts.nativeSessionId) {
|
|
443
|
+
// 续会话有两条路,且不是所有 agent 两条都认(实测):
|
|
444
|
+
// - ACP 标准 `session/load`(codebuddy/opencode/mimo/grok/kimi/minimax/trae 认);
|
|
445
|
+
// - `dsh` 自家 `session/resume`,标准 load 回 -32601 Method not found。
|
|
446
|
+
// 先试标准再试 resume:否则 dsh 会「静默退化成全新会话」——历史丢了却看不出来。
|
|
447
|
+
const attempts = [
|
|
448
|
+
{ method: 'session/load', params: { sessionId: opts.nativeSessionId, cwd: resolve(opts.cwd), mcpServers: [] } },
|
|
449
|
+
{ method: 'session/resume', params: { sessionId: opts.nativeSessionId, cwd: resolve(opts.cwd), mcpServers: [] } },
|
|
450
|
+
];
|
|
451
|
+
for (const attempt of attempts) {
|
|
452
|
+
try {
|
|
453
|
+
const resumed = (await request(attempt.method, attempt.params));
|
|
454
|
+
sessionId = resumed?.sessionId ?? opts.nativeSessionId;
|
|
455
|
+
break;
|
|
456
|
+
}
|
|
457
|
+
catch {
|
|
458
|
+
// 这个方法不被支持(或会话已过期):试下一条,最后退回新会话
|
|
459
|
+
sessionId = '';
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
// 续上了的会话用「本轮新说的话」;**试过续但没续上**就必须把完整历史塞进首轮 prompt,
|
|
464
|
+
// 否则新会话看着像正常回合,实际把之前所有上下文丢了 —— 这种失败看不出来。
|
|
465
|
+
const attemptedResume = Boolean(opts.nativeSessionId);
|
|
466
|
+
const resumedOk = Boolean(sessionId);
|
|
467
|
+
if (!sessionId) {
|
|
468
|
+
const newSession = (await request('session/new', {
|
|
469
|
+
cwd: resolve(opts.cwd),
|
|
470
|
+
mcpServers: [],
|
|
471
|
+
}));
|
|
472
|
+
sessionId = newSession.sessionId ?? '';
|
|
473
|
+
}
|
|
474
|
+
if (!sessionId)
|
|
475
|
+
throw new Error('ACP session/new 未返回 sessionId');
|
|
476
|
+
const promptText = !attemptedResume || resumedOk ? opts.prompt : (opts.replayPrompt ?? opts.prompt);
|
|
477
|
+
collectAgentText = true;
|
|
478
|
+
const result = (await request('session/prompt', { sessionId, prompt: [{ type: 'text', text: promptText }] }, timeoutMs));
|
|
479
|
+
stopReason = result.stopReason ?? 'end_turn';
|
|
480
|
+
const errorMessage = result._meta?.['codebuddy.ai/errorMessage'];
|
|
481
|
+
if (typeof errorMessage === 'string' && /authentication required/i.test(errorMessage)) {
|
|
482
|
+
throw new AcpAuthRequiredError(`${label} 登录态失效,请重新登录或注入 CODEBUDDY_AUTH_TOKEN`);
|
|
483
|
+
}
|
|
484
|
+
return { sessionId, text, stopReason };
|
|
485
|
+
}
|
|
486
|
+
finally {
|
|
487
|
+
clearTimeout(timer);
|
|
488
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
489
|
+
try {
|
|
490
|
+
if (sessionId && !closed)
|
|
491
|
+
send({ jsonrpc: '2.0', method: 'session/cancel', params: { sessionId } });
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
/* closing */
|
|
495
|
+
}
|
|
496
|
+
killCliProcess(child, spec.command);
|
|
497
|
+
// ACP 子进程常年驻留(--serve);必须主动断开三条管道,否则调用方进程会被句柄拖住。
|
|
498
|
+
child.stdin.destroy();
|
|
499
|
+
child.stdout?.destroy();
|
|
500
|
+
child.stderr?.destroy();
|
|
501
|
+
child.unref();
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
/** 向后兼容入口:CodeBuddy 固定启动参数与认证门禁 */
|
|
505
|
+
export function runCodeBuddyAcpPrompt(opts) {
|
|
506
|
+
return runAcpPrompt({ ...opts, spec: CODEBUDDY_ACP_SPEC });
|
|
507
|
+
}
|