agent-gear 2.5.0 → 2.7.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/AGENTS.md +53 -5
- package/dist/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
- package/dist/acp/bridge.d.ts +23 -1
- package/dist/acp/bridge.d.ts.map +1 -1
- package/dist/acp/bridge.js +152 -17
- package/dist/acp/bridge.js.map +1 -1
- package/dist/acp/bridge.test.js +366 -1
- package/dist/acp/bridge.test.js.map +1 -1
- package/dist/acp/capabilities.d.ts +81 -0
- package/dist/acp/capabilities.d.ts.map +1 -0
- package/dist/acp/capabilities.js +211 -0
- package/dist/acp/capabilities.js.map +1 -0
- package/dist/acp/capabilities.test.d.ts +2 -0
- package/dist/acp/capabilities.test.d.ts.map +1 -0
- package/dist/acp/capabilities.test.js +156 -0
- package/dist/acp/capabilities.test.js.map +1 -0
- package/dist/acp/elicitation.integration.test.d.ts +2 -0
- package/dist/acp/elicitation.integration.test.d.ts.map +1 -0
- package/dist/acp/elicitation.integration.test.js +98 -0
- package/dist/acp/elicitation.integration.test.js.map +1 -0
- package/dist/acp/prober.d.ts +4 -0
- package/dist/acp/prober.d.ts.map +1 -1
- package/dist/acp/prober.js +1 -0
- package/dist/acp/prober.js.map +1 -1
- package/dist/acp/spawner.d.ts.map +1 -1
- package/dist/acp/spawner.js +3 -0
- package/dist/acp/spawner.js.map +1 -1
- package/dist/acp/sync-bridge.d.ts.map +1 -1
- package/dist/acp/sync-bridge.js +5 -1
- package/dist/acp/sync-bridge.js.map +1 -1
- package/dist/cloud-host/supervisor.d.ts +13 -0
- package/dist/cloud-host/supervisor.d.ts.map +1 -1
- package/dist/cloud-host/supervisor.js +21 -0
- package/dist/cloud-host/supervisor.js.map +1 -1
- package/dist/cloud-host/supervisor.test.js +71 -0
- package/dist/cloud-host/supervisor.test.js.map +1 -1
- package/dist/github/credential-manager.d.ts +70 -0
- package/dist/github/credential-manager.d.ts.map +1 -0
- package/dist/github/credential-manager.js +205 -0
- package/dist/github/credential-manager.js.map +1 -0
- package/dist/github/credential-manager.test.d.ts +2 -0
- package/dist/github/credential-manager.test.d.ts.map +1 -0
- package/dist/github/credential-manager.test.js +215 -0
- package/dist/github/credential-manager.test.js.map +1 -0
- package/dist/github/gh-config.d.ts +17 -0
- package/dist/github/gh-config.d.ts.map +1 -0
- package/dist/github/gh-config.js +68 -0
- package/dist/github/gh-config.js.map +1 -0
- package/dist/github/gh-config.test.d.ts +2 -0
- package/dist/github/gh-config.test.d.ts.map +1 -0
- package/dist/github/gh-config.test.js +90 -0
- package/dist/github/gh-config.test.js.map +1 -0
- package/dist/harness/env.d.ts +8 -0
- package/dist/harness/env.d.ts.map +1 -1
- package/dist/harness/env.js +30 -0
- package/dist/harness/env.js.map +1 -1
- package/dist/harness/env.test.js +40 -1
- package/dist/harness/env.test.js.map +1 -1
- package/dist/harness/opencode-config.d.ts +6 -3
- package/dist/harness/opencode-config.d.ts.map +1 -1
- package/dist/harness/opencode-config.js +6 -2
- package/dist/harness/opencode-config.js.map +1 -1
- package/dist/harness/opencode-config.test.js +12 -0
- package/dist/harness/opencode-config.test.js.map +1 -1
- package/dist/harness/prepare.test.js +19 -0
- package/dist/harness/prepare.test.js.map +1 -1
- package/dist/socketio-client.d.ts +12 -0
- package/dist/socketio-client.d.ts.map +1 -1
- package/dist/socketio-client.github.test.d.ts +2 -0
- package/dist/socketio-client.github.test.d.ts.map +1 -0
- package/dist/socketio-client.github.test.js +66 -0
- package/dist/socketio-client.github.test.js.map +1 -0
- package/dist/socketio-client.js +115 -65
- package/dist/socketio-client.js.map +1 -1
- package/dist/socketio-client.test.js +251 -1
- package/dist/socketio-client.test.js.map +1 -1
- package/dist/workload-executor.d.ts +14 -1
- package/dist/workload-executor.d.ts.map +1 -1
- package/dist/workload-executor.js +33 -3
- package/dist/workload-executor.js.map +1 -1
- package/dist/workload-executor.test.js +106 -2
- package/dist/workload-executor.test.js.map +1 -1
- package/package.json +1 -1
- package/src/acp/__fixtures__/fake-elicitation-agent.mjs +113 -0
- package/src/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
- package/src/acp/bridge.test.ts +480 -1
- package/src/acp/bridge.ts +163 -18
- package/src/acp/capabilities.test.ts +200 -0
- package/src/acp/capabilities.ts +274 -0
- package/src/acp/elicitation.integration.test.ts +126 -0
- package/src/acp/prober.ts +4 -0
- package/src/acp/spawner.ts +3 -0
- package/src/acp/sync-bridge.ts +5 -1
- package/src/cloud-host/supervisor.test.ts +96 -1
- package/src/cloud-host/supervisor.ts +37 -0
- package/src/github/credential-manager.test.ts +268 -0
- package/src/github/credential-manager.ts +251 -0
- package/src/github/gh-config.test.ts +103 -0
- package/src/github/gh-config.ts +76 -0
- package/src/harness/env.test.ts +44 -1
- package/src/harness/env.ts +32 -0
- package/src/harness/opencode-config.test.ts +13 -0
- package/src/harness/opencode-config.ts +12 -6
- package/src/harness/prepare.test.ts +22 -0
- package/src/socketio-client.github.test.ts +76 -0
- package/src/socketio-client.test.ts +306 -1
- package/src/socketio-client.ts +113 -53
- package/src/workload-executor.test.ts +144 -2
- package/src/workload-executor.ts +48 -2
- package/tests/acp-sync-bridge.test.ts +5 -1
- package/tests/socketio-client.test.ts +2 -2
- package/vitest.config.ts +5 -1
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP 能力快照归一化(纯函数模块)。
|
|
3
|
+
*
|
|
4
|
+
* 设计要点(见实现计划裁决 R1/R2):
|
|
5
|
+
* - FeatureId 全集与平台支持矩阵集中在本文件,禁止在其他位置复制;
|
|
6
|
+
* - 状态 = Agent 声明 × 平台支持 的二维合并:
|
|
7
|
+
* declared=false → unsupported
|
|
8
|
+
* declared=true + platform full → supported
|
|
9
|
+
* declared=true + platform partial/none → partial(界面无入口或仅动态下发)
|
|
10
|
+
* - `elicitation.*` / `config.boolean` 是 Client 能力,declared 取自本端声明;
|
|
11
|
+
* - 未知 `_meta` 扩展键不产生 feature,只在 raw 中保留原文。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export type AgentFeatureStatus = 'supported' | 'partial' | 'unsupported';
|
|
15
|
+
|
|
16
|
+
export interface AgentFeatureSupport {
|
|
17
|
+
id: string;
|
|
18
|
+
status: AgentFeatureStatus;
|
|
19
|
+
detail: string | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface AgentCapabilitySnapshot {
|
|
23
|
+
protocolVersion: number | null;
|
|
24
|
+
agentInfo: { name: string; version: string | null } | null;
|
|
25
|
+
features: AgentFeatureSupport[];
|
|
26
|
+
raw: {
|
|
27
|
+
agentCapabilities: unknown;
|
|
28
|
+
authMethods: unknown;
|
|
29
|
+
clientCapabilities: unknown;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 本端 initialize 声明的 Client 能力(bridge 与 sync-bridge 共用,禁止重复字面量) */
|
|
34
|
+
export const CLIENT_CAPABILITIES = {
|
|
35
|
+
session: { configOptions: { boolean: {} } },
|
|
36
|
+
elicitation: { form: {}, url: {} },
|
|
37
|
+
} as const;
|
|
38
|
+
|
|
39
|
+
type PlatformSupport = 'full' | 'partial' | 'none';
|
|
40
|
+
|
|
41
|
+
/** 平台侧支持矩阵:full=有入口且可用,partial=仅动态/受限,none=无入口 */
|
|
42
|
+
const PLATFORM_SUPPORT: Record<string, PlatformSupport> = {
|
|
43
|
+
'session.load': 'full',
|
|
44
|
+
'session.resume': 'full',
|
|
45
|
+
'session.close': 'full',
|
|
46
|
+
'session.list': 'full',
|
|
47
|
+
'session.delete': 'full',
|
|
48
|
+
'session.fork': 'none',
|
|
49
|
+
'session.additionalDirectories': 'none',
|
|
50
|
+
'prompt.image': 'none',
|
|
51
|
+
'prompt.audio': 'none',
|
|
52
|
+
'prompt.embeddedContext': 'none',
|
|
53
|
+
'auth.login': 'none',
|
|
54
|
+
'auth.logout': 'none',
|
|
55
|
+
'mcp.http': 'full',
|
|
56
|
+
'mcp.sse': 'none',
|
|
57
|
+
'config.boolean': 'full',
|
|
58
|
+
'config.model': 'full',
|
|
59
|
+
'config.mode': 'full',
|
|
60
|
+
commands: 'partial',
|
|
61
|
+
'elicitation.form': 'full',
|
|
62
|
+
'elicitation.url': 'full',
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** 固定展示顺序(与实现计划裁决 R1 表格逐项一致) */
|
|
66
|
+
export const FEATURE_IDS = [
|
|
67
|
+
'session.load',
|
|
68
|
+
'session.resume',
|
|
69
|
+
'session.close',
|
|
70
|
+
'session.list',
|
|
71
|
+
'session.delete',
|
|
72
|
+
'session.fork',
|
|
73
|
+
'session.additionalDirectories',
|
|
74
|
+
'prompt.image',
|
|
75
|
+
'prompt.audio',
|
|
76
|
+
'prompt.embeddedContext',
|
|
77
|
+
'auth.login',
|
|
78
|
+
'auth.logout',
|
|
79
|
+
'mcp.http',
|
|
80
|
+
'mcp.sse',
|
|
81
|
+
'config.boolean',
|
|
82
|
+
'config.model',
|
|
83
|
+
'config.mode',
|
|
84
|
+
'commands',
|
|
85
|
+
'elicitation.form',
|
|
86
|
+
'elicitation.url',
|
|
87
|
+
] as const;
|
|
88
|
+
|
|
89
|
+
/** Agent 未声明时展示的字段路径 */
|
|
90
|
+
const SOURCE_FIELD: Record<string, string> = {
|
|
91
|
+
'session.load': 'agentCapabilities.loadSession',
|
|
92
|
+
'session.resume': 'agentCapabilities.sessionCapabilities.resume',
|
|
93
|
+
'session.close': 'agentCapabilities.sessionCapabilities.close',
|
|
94
|
+
'session.list': 'agentCapabilities.sessionCapabilities.list',
|
|
95
|
+
'session.delete': 'agentCapabilities.sessionCapabilities.delete',
|
|
96
|
+
'session.fork': 'agentCapabilities.sessionCapabilities.fork',
|
|
97
|
+
'session.additionalDirectories': 'agentCapabilities.sessionCapabilities.additionalDirectories',
|
|
98
|
+
'prompt.image': 'agentCapabilities.promptCapabilities.image',
|
|
99
|
+
'prompt.audio': 'agentCapabilities.promptCapabilities.audio',
|
|
100
|
+
'prompt.embeddedContext': 'agentCapabilities.promptCapabilities.embeddedContext',
|
|
101
|
+
'auth.login': 'authMethods',
|
|
102
|
+
'auth.logout': 'agentCapabilities.auth.logout',
|
|
103
|
+
'mcp.http': 'agentCapabilities.mcpCapabilities.http',
|
|
104
|
+
'mcp.sse': 'agentCapabilities.mcpCapabilities.sse',
|
|
105
|
+
'config.boolean': 'clientCapabilities.session.configOptions.boolean',
|
|
106
|
+
'config.model': 'configOptions(category=model)',
|
|
107
|
+
'config.mode': 'configOptions(category=mode)/modes',
|
|
108
|
+
commands: 'available_commands_update',
|
|
109
|
+
'elicitation.form': 'clientCapabilities.elicitation.form',
|
|
110
|
+
'elicitation.url': 'clientCapabilities.elicitation.url',
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const PLATFORM_LIMITATION: Partial<Record<string, string>> = {
|
|
114
|
+
'session.fork': '平台暂未提供入口',
|
|
115
|
+
'session.additionalDirectories': '平台暂未提供入口',
|
|
116
|
+
'prompt.image': '平台暂未提供附件入口',
|
|
117
|
+
'prompt.audio': '平台暂未提供附件入口',
|
|
118
|
+
'prompt.embeddedContext': '平台暂未提供附件入口',
|
|
119
|
+
'auth.login': '平台暂未提供认证入口',
|
|
120
|
+
'auth.logout': '平台暂未提供认证入口',
|
|
121
|
+
'mcp.sse': '平台不支持 SSE 传输',
|
|
122
|
+
commands: '平台仅动态下发(available_commands_update)',
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
const AGENT_NOTE: Partial<Record<string, string>> = {
|
|
126
|
+
commands: '命令集由 available_commands_update 动态下发,平台已支持命令列表与 / 补全',
|
|
127
|
+
'elicitation.form': 'Agent 是否发起取决于其触发条件',
|
|
128
|
+
'elicitation.url': 'Agent 是否发起取决于其触发条件',
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
type CapabilityField = { readonly [key: string]: unknown } | null | undefined;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* ACP 能力布尔判定:`true` 或非 null 对象(`{}` 表示「已通告」)均视为已声明;
|
|
135
|
+
* `null`/`undefined`/`false` 为未声明。
|
|
136
|
+
*/
|
|
137
|
+
export function isTruthyCapability(value: unknown): boolean {
|
|
138
|
+
if (value === true) return true;
|
|
139
|
+
return typeof value === 'object' && value !== null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export interface NormalizeCapabilitiesInput {
|
|
143
|
+
protocolVersion: number | null;
|
|
144
|
+
agentInfo: { name: string; version: string | null } | null;
|
|
145
|
+
/** initialize 返回的 agentCapabilities 原文(含 _meta) */
|
|
146
|
+
agentCapabilities: unknown;
|
|
147
|
+
/** initialize 返回的 authMethods 原文 */
|
|
148
|
+
authMethods: unknown;
|
|
149
|
+
/** 本端 initialize 发送的 clientCapabilities 原文 */
|
|
150
|
+
clientCapabilities: unknown;
|
|
151
|
+
/** 已归一化的会话配置项(session/new 响应) */
|
|
152
|
+
configOptions: Array<{ id: string; type: string; category?: string | null }>;
|
|
153
|
+
/** session/new 的 modes[](旧 Agent 回退通道) */
|
|
154
|
+
modes: Array<{ id: string; name: string }>;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface DeclaredFeature {
|
|
158
|
+
declared: boolean;
|
|
159
|
+
/** Agent 侧补充说明(可选) */
|
|
160
|
+
note?: string;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function asRecord(value: unknown): CapabilityField {
|
|
164
|
+
return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function declaredMap(input: NormalizeCapabilitiesInput): Record<string, DeclaredFeature> {
|
|
168
|
+
const caps = asRecord(input.agentCapabilities);
|
|
169
|
+
const sessionCaps = asRecord(caps?.sessionCapabilities);
|
|
170
|
+
const promptCaps = asRecord(caps?.promptCapabilities);
|
|
171
|
+
const mcpCaps = asRecord(caps?.mcpCapabilities);
|
|
172
|
+
const authCaps = asRecord(caps?.auth);
|
|
173
|
+
const clientCaps = asRecord(input.clientCapabilities);
|
|
174
|
+
const clientSession = asRecord(clientCaps?.session);
|
|
175
|
+
const clientConfigOptions = asRecord(clientSession?.configOptions);
|
|
176
|
+
const clientElicitation = asRecord(clientCaps?.elicitation);
|
|
177
|
+
|
|
178
|
+
const authMethods = Array.isArray(input.authMethods) ? input.authMethods : [];
|
|
179
|
+
const hasSelectConfig = (category: string): boolean =>
|
|
180
|
+
input.configOptions.some((opt) => opt.category === category && opt.type === 'select');
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
'session.load': { declared: caps?.loadSession === true },
|
|
184
|
+
'session.resume': { declared: isTruthyCapability(sessionCaps?.resume) },
|
|
185
|
+
'session.close': { declared: isTruthyCapability(sessionCaps?.close) },
|
|
186
|
+
'session.list': { declared: isTruthyCapability(sessionCaps?.list) },
|
|
187
|
+
'session.delete': { declared: isTruthyCapability(sessionCaps?.delete) },
|
|
188
|
+
'session.fork': { declared: isTruthyCapability(sessionCaps?.fork) },
|
|
189
|
+
'session.additionalDirectories': { declared: isTruthyCapability(sessionCaps?.additionalDirectories) },
|
|
190
|
+
'prompt.image': { declared: promptCaps?.image === true },
|
|
191
|
+
'prompt.audio': { declared: promptCaps?.audio === true },
|
|
192
|
+
'prompt.embeddedContext': { declared: promptCaps?.embeddedContext === true },
|
|
193
|
+
'auth.login': { declared: authMethods.length > 0 },
|
|
194
|
+
'auth.logout': { declared: isTruthyCapability(authCaps?.logout) },
|
|
195
|
+
'mcp.http': { declared: mcpCaps?.http === true },
|
|
196
|
+
'mcp.sse': { declared: mcpCaps?.sse === true },
|
|
197
|
+
'config.boolean': { declared: isTruthyCapability(clientConfigOptions?.boolean) },
|
|
198
|
+
'config.model': { declared: hasSelectConfig('model') },
|
|
199
|
+
'config.mode': { declared: hasSelectConfig('mode') || input.modes.length > 0 },
|
|
200
|
+
commands: { declared: true },
|
|
201
|
+
'elicitation.form': { declared: isTruthyCapability(clientElicitation?.form) },
|
|
202
|
+
'elicitation.url': { declared: isTruthyCapability(clientElicitation?.url) },
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function mergeStatus(
|
|
207
|
+
id: string,
|
|
208
|
+
declared: boolean,
|
|
209
|
+
note: string | undefined,
|
|
210
|
+
): AgentFeatureSupport {
|
|
211
|
+
const platform = PLATFORM_SUPPORT[id] ?? 'none';
|
|
212
|
+
|
|
213
|
+
if (!declared) {
|
|
214
|
+
return {
|
|
215
|
+
id,
|
|
216
|
+
status: 'unsupported',
|
|
217
|
+
detail: `未声明 ${SOURCE_FIELD[id] ?? 'unknown'}`,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (platform === 'full') {
|
|
222
|
+
return { id, status: 'supported', detail: note ?? null };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const limitation = PLATFORM_LIMITATION[id] ?? '平台暂未提供入口';
|
|
226
|
+
const detail = [note, limitation].filter((part): part is string => Boolean(part)).join(';');
|
|
227
|
+
return { id, status: 'partial', detail };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** 快照 raw 体积上限:`_meta` 等扩展字段由 Agent 任意控制,避免放大 WS/Mongo 写入 */
|
|
231
|
+
export const RAW_SNAPSHOT_MAX_BYTES = 16 * 1024;
|
|
232
|
+
|
|
233
|
+
/** 原文留存带体积上限:超限时只保留可诊断摘要,不原样外露/落库 */
|
|
234
|
+
function capRaw(value: unknown): unknown {
|
|
235
|
+
if (value == null) return null;
|
|
236
|
+
try {
|
|
237
|
+
const json = JSON.stringify(value);
|
|
238
|
+
if (json === undefined) return null;
|
|
239
|
+
// UTF-8 字节口径(TextEncoder 在 Node/浏览器一致;避免依赖 Buffer 类型)
|
|
240
|
+
const bytes = new TextEncoder().encode(json).length;
|
|
241
|
+
if (bytes <= RAW_SNAPSHOT_MAX_BYTES) return value;
|
|
242
|
+
return {
|
|
243
|
+
truncated: true,
|
|
244
|
+
originalBytes: bytes,
|
|
245
|
+
preview: json.slice(0, 512),
|
|
246
|
+
};
|
|
247
|
+
} catch {
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* 归一化能力快照。输出固定 20 项(FEATURE_IDS 顺序),与 Agent 是否广播无关。
|
|
254
|
+
*/
|
|
255
|
+
export function normalizeCapabilities(input: NormalizeCapabilitiesInput): AgentCapabilitySnapshot {
|
|
256
|
+
const declared = declaredMap(input);
|
|
257
|
+
|
|
258
|
+
const features = FEATURE_IDS.map((id) => {
|
|
259
|
+
const entry = declared[id] ?? { declared: false };
|
|
260
|
+
const note = entry.note ?? AGENT_NOTE[id];
|
|
261
|
+
return mergeStatus(id, entry.declared, note);
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
protocolVersion: input.protocolVersion ?? null,
|
|
266
|
+
agentInfo: input.agentInfo ?? null,
|
|
267
|
+
features,
|
|
268
|
+
raw: {
|
|
269
|
+
agentCapabilities: capRaw(input.agentCapabilities),
|
|
270
|
+
authMethods: capRaw(input.authMethods),
|
|
271
|
+
clientCapabilities: capRaw(input.clientCapabilities),
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { describe, it, expect, afterEach } from 'vitest';
|
|
2
|
+
import { mkdtempSync, readFileSync, existsSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join, dirname } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { AcpSessionBridge } from './bridge.js';
|
|
7
|
+
import { AcpSpawner } from './spawner.js';
|
|
8
|
+
|
|
9
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const FAKE_AGENT = join(here, '__fixtures__', 'fake-elicitation-agent.mjs');
|
|
11
|
+
|
|
12
|
+
interface EmittedEvent {
|
|
13
|
+
event: string;
|
|
14
|
+
payload: Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function createRecordingSocket() {
|
|
18
|
+
const emitted: EmittedEvent[] = [];
|
|
19
|
+
const socket = {
|
|
20
|
+
emit: (event: string, payload: Record<string, unknown>) => {
|
|
21
|
+
emitted.push({ event, payload });
|
|
22
|
+
return true;
|
|
23
|
+
},
|
|
24
|
+
on: () => socket,
|
|
25
|
+
off: () => socket,
|
|
26
|
+
};
|
|
27
|
+
return { socket, emitted };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function waitFor<T>(
|
|
31
|
+
fn: () => T | undefined,
|
|
32
|
+
timeoutMs = 6000,
|
|
33
|
+
intervalMs = 20,
|
|
34
|
+
): Promise<T> {
|
|
35
|
+
const deadline = Date.now() + timeoutMs;
|
|
36
|
+
while (Date.now() < deadline) {
|
|
37
|
+
const value = fn();
|
|
38
|
+
if (value !== undefined) return value;
|
|
39
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
40
|
+
}
|
|
41
|
+
throw new Error(`waitFor timed out after ${timeoutMs}ms`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const cleanupFns: Array<() => Promise<void> | void> = [];
|
|
45
|
+
|
|
46
|
+
afterEach(async () => {
|
|
47
|
+
while (cleanupFns.length > 0) {
|
|
48
|
+
await cleanupFns.pop()?.();
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
function createBridge(mode: string) {
|
|
53
|
+
const dir = mkdtempSync(join(tmpdir(), 'acp-fake-agent-'));
|
|
54
|
+
const resultFile = join(dir, 'result.jsonl');
|
|
55
|
+
const spawner = new AcpSpawner({
|
|
56
|
+
sessionId: `it-${Date.now()}`,
|
|
57
|
+
cwd: dir,
|
|
58
|
+
command: process.execPath,
|
|
59
|
+
args: [FAKE_AGENT, mode, resultFile],
|
|
60
|
+
});
|
|
61
|
+
const { socket, emitted } = createRecordingSocket();
|
|
62
|
+
const bridge = new AcpSessionBridge(
|
|
63
|
+
socket as never,
|
|
64
|
+
{ sessionId: `it-${Date.now()}`, cwd: dir },
|
|
65
|
+
spawner,
|
|
66
|
+
);
|
|
67
|
+
cleanupFns.push(async () => {
|
|
68
|
+
await bridge.stop().catch(() => {});
|
|
69
|
+
spawner.stop();
|
|
70
|
+
});
|
|
71
|
+
return { bridge, emitted, resultFile };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function readRecords(resultFile: string): Array<Record<string, unknown>> {
|
|
75
|
+
if (!existsSync(resultFile)) return [];
|
|
76
|
+
return readFileSync(resultFile, 'utf8')
|
|
77
|
+
.split('\n')
|
|
78
|
+
.filter(Boolean)
|
|
79
|
+
.map((line) => JSON.parse(line) as Record<string, unknown>);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
describe('elicitation 真实 SDK + 假 Agent 进程', () => {
|
|
83
|
+
it('T-BI1: form 模式问询被路由到 unstable_createElicitation,响应回传 Agent', async () => {
|
|
84
|
+
const { bridge, emitted, resultFile } = createBridge('form');
|
|
85
|
+
|
|
86
|
+
await bridge.start();
|
|
87
|
+
|
|
88
|
+
const elicitation = await waitFor(() =>
|
|
89
|
+
emitted.find((e) => e.event === 'acp:elicitation'),
|
|
90
|
+
);
|
|
91
|
+
expect(elicitation.payload).toMatchObject({
|
|
92
|
+
mode: 'form',
|
|
93
|
+
message: 'Fake agent needs input',
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const requestId = elicitation.payload.requestId as string;
|
|
97
|
+
bridge.handleElicitationResponse(requestId, 'accept', { answer: 'x' });
|
|
98
|
+
|
|
99
|
+
const records = await waitFor(() => {
|
|
100
|
+
const current = readRecords(resultFile);
|
|
101
|
+
return current.length > 0 ? current : undefined;
|
|
102
|
+
});
|
|
103
|
+
expect(records[0].elicitationResponse).toEqual({ action: 'accept', content: { answer: 'x' } });
|
|
104
|
+
expect(emitted.some((e) => e.event === 'acp:elicitation:resolved')).toBe(false);
|
|
105
|
+
}, 15000);
|
|
106
|
+
|
|
107
|
+
it('T-BI2: 平台未声明模式(custom)返回 cancel 并发出 resolved(unsupported_mode)', async () => {
|
|
108
|
+
const { bridge, emitted, resultFile } = createBridge('custom');
|
|
109
|
+
|
|
110
|
+
await bridge.start();
|
|
111
|
+
|
|
112
|
+
const records = await waitFor(() => {
|
|
113
|
+
const current = readRecords(resultFile);
|
|
114
|
+
return current.length > 0 ? current : undefined;
|
|
115
|
+
});
|
|
116
|
+
// 未知模式在到达用户前被取消:Agent 收到 cancel
|
|
117
|
+
expect(records[0].elicitationResponse).toEqual({ action: 'cancel' });
|
|
118
|
+
|
|
119
|
+
const resolved = emitted.find((e) => e.event === 'acp:elicitation:resolved');
|
|
120
|
+
expect(resolved?.payload).toMatchObject({
|
|
121
|
+
reason: 'unsupported_mode',
|
|
122
|
+
detail: 'custom',
|
|
123
|
+
});
|
|
124
|
+
expect(emitted.some((e) => e.event === 'acp:elicitation')).toBe(false);
|
|
125
|
+
}, 15000);
|
|
126
|
+
});
|
package/src/acp/prober.ts
CHANGED
|
@@ -9,6 +9,9 @@ export interface AcpServerOptionsProbeResult {
|
|
|
9
9
|
availableModels: Array<{ id: string; name: string; provider?: string }>;
|
|
10
10
|
currentModeId: string | null;
|
|
11
11
|
currentModelId: string | null;
|
|
12
|
+
/** 能力快照(供 API 测试与后续回归复用;旧调用方忽略该字段即可)。
|
|
13
|
+
* 旧版 controller 可能不上报,故运行时允许缺省(类型保持可选,消费方须判空)。 */
|
|
14
|
+
capabilities?: AcpInitializedPayload['capabilities'];
|
|
12
15
|
}
|
|
13
16
|
|
|
14
17
|
/**
|
|
@@ -56,6 +59,7 @@ export async function probeAcpServerOptions(
|
|
|
56
59
|
availableModels: payload.availableModels ?? [],
|
|
57
60
|
currentModeId: payload.currentModeId ?? null,
|
|
58
61
|
currentModelId: payload.currentModelId ?? null,
|
|
62
|
+
...(payload.capabilities ? { capabilities: payload.capabilities } : {}),
|
|
59
63
|
}),
|
|
60
64
|
);
|
|
61
65
|
});
|
package/src/acp/spawner.ts
CHANGED
|
@@ -61,6 +61,9 @@ export class AcpSpawner {
|
|
|
61
61
|
|
|
62
62
|
this.process.on('error', (error) => {
|
|
63
63
|
console.error(`ACP process error (session=${this.sessionId}, cmd=${cmd}):`, error);
|
|
64
|
+
// spawn 失败同样视为进程终止:必须 resolve closed,让 bridge 收敛 pending,避免 65s 迟到 timeout
|
|
65
|
+
this.process = null;
|
|
66
|
+
this.resolveClosed?.();
|
|
64
67
|
});
|
|
65
68
|
}
|
|
66
69
|
|
package/src/acp/sync-bridge.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as acp from '@agentclientprotocol/sdk';
|
|
2
2
|
import { AcpSpawner } from './spawner.js';
|
|
3
|
+
import { CLIENT_CAPABILITIES } from './capabilities.js';
|
|
3
4
|
|
|
4
5
|
const ACP_PROTOCOL_VERSION = 1;
|
|
5
6
|
const CONNECT_TIMEOUT_MS = 30_000;
|
|
@@ -50,7 +51,7 @@ export class AcpSyncBridge implements acp.Client {
|
|
|
50
51
|
|
|
51
52
|
const initPromise = this.connection.initialize({
|
|
52
53
|
protocolVersion: ACP_PROTOCOL_VERSION,
|
|
53
|
-
clientCapabilities:
|
|
54
|
+
clientCapabilities: CLIENT_CAPABILITIES,
|
|
54
55
|
clientInfo: { name: 'agent-gear', version: '1.0.0' },
|
|
55
56
|
});
|
|
56
57
|
|
|
@@ -126,6 +127,9 @@ export class AcpSyncBridge implements acp.Client {
|
|
|
126
127
|
}
|
|
127
128
|
|
|
128
129
|
async unstable_createElicitation(): Promise<acp.CreateElicitationResponse> {
|
|
130
|
+
// 同步链路无用户交互通道:声明了 elicitation 能力后 Agent 可能发起问询,
|
|
131
|
+
// 这里显式取消并留日志(声明 + 立即取消是合法降级,不引入交互链路)。
|
|
132
|
+
console.warn('[ACP sync-bridge] elicitation request auto-cancelled: no user channel');
|
|
129
133
|
return { action: 'cancel' };
|
|
130
134
|
}
|
|
131
135
|
|
|
@@ -12,8 +12,10 @@ import {
|
|
|
12
12
|
readCloudHostEnv,
|
|
13
13
|
resolveShutdownExitCode,
|
|
14
14
|
startCloudHostSupervisor,
|
|
15
|
+
type CredentialManagerLike,
|
|
15
16
|
} from './supervisor.js';
|
|
16
17
|
import type { ConnectToServerOptions } from '../socketio-client.js';
|
|
18
|
+
import type { GithubCredentialRefreshResult } from '../github/credential-manager.js';
|
|
17
19
|
|
|
18
20
|
const TMP_BASE = '/tmp/opencode';
|
|
19
21
|
|
|
@@ -35,7 +37,11 @@ function fakeSocket(): FakeSocket {
|
|
|
35
37
|
return { disconnect: vi.fn(), emit: vi.fn() };
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
function setup(overrides: {
|
|
40
|
+
function setup(overrides: {
|
|
41
|
+
env?: NodeJS.ProcessEnv;
|
|
42
|
+
makeDir?: (path: string) => Promise<void>;
|
|
43
|
+
credentialManager?: CredentialManagerLike;
|
|
44
|
+
} = {}) {
|
|
39
45
|
const worker = fakeSocket();
|
|
40
46
|
const controller = fakeSocket();
|
|
41
47
|
const connect = vi.fn((endpoint: string, key: string, options?: ConnectToServerOptions) => {
|
|
@@ -59,10 +65,21 @@ function setup(overrides: { env?: NodeJS.ProcessEnv; makeDir?: (path: string) =>
|
|
|
59
65
|
exit,
|
|
60
66
|
log: (message: string) => logs.push(message),
|
|
61
67
|
installSignalHandlers: false,
|
|
68
|
+
credentialManager: overrides.credentialManager,
|
|
62
69
|
},
|
|
63
70
|
};
|
|
64
71
|
}
|
|
65
72
|
|
|
73
|
+
function fakeCredentialManager(
|
|
74
|
+
result: GithubCredentialRefreshResult = { ok: true, expiresAt: new Date('2026-10-22T12:00:00Z') },
|
|
75
|
+
): CredentialManagerLike {
|
|
76
|
+
return {
|
|
77
|
+
start: vi.fn(),
|
|
78
|
+
stop: vi.fn(),
|
|
79
|
+
refreshNow: vi.fn(async () => result),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
|
|
66
83
|
describe('cloud host mode detection (T-AG2)', () => {
|
|
67
84
|
it('requires all three cloud-host env variables to be non-empty', () => {
|
|
68
85
|
expect(isCloudHostMode(BASE_ENV)).toBe(true);
|
|
@@ -365,3 +382,81 @@ describe('startCloudHostSupervisor', () => {
|
|
|
365
382
|
expect(context.exit).not.toHaveBeenCalled();
|
|
366
383
|
});
|
|
367
384
|
});
|
|
385
|
+
|
|
386
|
+
describe('cloud host github credential manager (T-SUP-G)', () => {
|
|
387
|
+
it('T-SUP-G1: starts the credential manager and wires githubAuth batches to refreshNow', async () => {
|
|
388
|
+
const credentials = fakeCredentialManager();
|
|
389
|
+
const context = setup({
|
|
390
|
+
env: { ...BASE_ENV, ZAG_AGENT_API_ENDPOINT: 'http://agent-api:8002', ZAG_CONTROLLER_ID: 'c-1' },
|
|
391
|
+
credentialManager: credentials,
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
await startCloudHostSupervisor(context.deps);
|
|
395
|
+
|
|
396
|
+
expect(credentials.start).toHaveBeenCalledTimes(1);
|
|
397
|
+
|
|
398
|
+
const workerOptions = context.connect.mock.calls[0][2] as ConnectToServerOptions;
|
|
399
|
+
expect(workerOptions.onBeforeWorkloadBatch).toBeTypeOf('function');
|
|
400
|
+
|
|
401
|
+
await workerOptions.onBeforeWorkloadBatch?.({
|
|
402
|
+
phase: 'init',
|
|
403
|
+
githubAuth: true,
|
|
404
|
+
items: [{ logId: 'x', workloadName: 'Git 项目设置', script: 'echo', timeoutMs: 1000 }],
|
|
405
|
+
});
|
|
406
|
+
expect(credentials.refreshNow).toHaveBeenCalledTimes(1);
|
|
407
|
+
|
|
408
|
+
// 非 githubAuth 批次不触发凭据申请
|
|
409
|
+
await workerOptions.onBeforeWorkloadBatch?.({
|
|
410
|
+
phase: 'init',
|
|
411
|
+
items: [{ logId: 'y', workloadName: 'Other', script: 'echo', timeoutMs: 1000 }],
|
|
412
|
+
});
|
|
413
|
+
expect(credentials.refreshNow).toHaveBeenCalledTimes(1);
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
it('T-SUP-G1b: no-binding and other failures surface readable errors to the executor', async () => {
|
|
417
|
+
const noBinding = fakeCredentialManager({ ok: false, error: 'no-binding' });
|
|
418
|
+
const context = setup({ credentialManager: noBinding });
|
|
419
|
+
await startCloudHostSupervisor(context.deps);
|
|
420
|
+
const options = context.connect.mock.calls[0][2] as ConnectToServerOptions;
|
|
421
|
+
const payload = {
|
|
422
|
+
phase: 'init' as const,
|
|
423
|
+
githubAuth: true,
|
|
424
|
+
items: [{ logId: 'x', workloadName: 'Git 项目设置', script: 'echo', timeoutMs: 1000 }],
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
await expect(options.onBeforeWorkloadBatch?.(payload)).rejects.toThrow('未设置 Github 项目');
|
|
428
|
+
|
|
429
|
+
const invalid = fakeCredentialManager({ ok: false, error: 'Github 凭据无效(HTTP 401)' });
|
|
430
|
+
const context2 = setup({ credentialManager: invalid });
|
|
431
|
+
await startCloudHostSupervisor(context2.deps);
|
|
432
|
+
const options2 = context2.connect.mock.calls[0][2] as ConnectToServerOptions;
|
|
433
|
+
await expect(options2.onBeforeWorkloadBatch?.(payload)).rejects.toThrow('Github 凭据无效');
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
it('T-SUP-G2: shutdown stops the credential manager (idempotently)', async () => {
|
|
437
|
+
const credentials = fakeCredentialManager();
|
|
438
|
+
const context = setup({ credentialManager: credentials });
|
|
439
|
+
const handle = await startCloudHostSupervisor(context.deps);
|
|
440
|
+
|
|
441
|
+
handle.shutdown('test');
|
|
442
|
+
handle.shutdown('again');
|
|
443
|
+
|
|
444
|
+
expect(credentials.stop).toHaveBeenCalledTimes(1);
|
|
445
|
+
expect(context.exit).toHaveBeenCalledWith(0);
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it('T-SUP-G3: missing credential env does not block the supervisor, only warns', async () => {
|
|
449
|
+
const context = setup({ env: { ...BASE_ENV } });
|
|
450
|
+
|
|
451
|
+
const handle = await startCloudHostSupervisor(context.deps);
|
|
452
|
+
|
|
453
|
+
expect(handle.workerSocket).toBe(context.worker);
|
|
454
|
+
expect(context.connect).toHaveBeenCalledTimes(1);
|
|
455
|
+
expect(context.exit).not.toHaveBeenCalled();
|
|
456
|
+
const output = context.logs.join('\n');
|
|
457
|
+
expect(output).toContain('disabled');
|
|
458
|
+
expect(output).toContain('ZAG_AGENT_API_ENDPOINT');
|
|
459
|
+
expect(output).toContain('ZAG_CONTROLLER_ID');
|
|
460
|
+
expect(output).not.toContain(BASE_ENV.ZAG_HOST_KEY);
|
|
461
|
+
});
|
|
462
|
+
});
|
|
@@ -6,6 +6,11 @@ import {
|
|
|
6
6
|
parseEndpoint,
|
|
7
7
|
type ConnectToServerOptions,
|
|
8
8
|
} from '../socketio-client.js';
|
|
9
|
+
import {
|
|
10
|
+
GithubCredentialManager,
|
|
11
|
+
type GithubCredentialRefreshResult,
|
|
12
|
+
} from '../github/credential-manager.js';
|
|
13
|
+
import type { WorkloadRunPayload } from '../workload-executor.js';
|
|
9
14
|
|
|
10
15
|
/** 未设置 `HARNESS_INIT_WAIT_MS` 时的初始化等待上限(10 分钟)。 */
|
|
11
16
|
export const DEFAULT_HARNESS_INIT_WAIT_MS = 600_000;
|
|
@@ -32,6 +37,10 @@ export interface CloudHostEnv {
|
|
|
32
37
|
workspace: string;
|
|
33
38
|
/** 初始化等待超时(env `HARNESS_INIT_WAIT_MS`,缺省 10 分钟)。 */
|
|
34
39
|
initWaitMs: number;
|
|
40
|
+
/** agent-api 内部地址(env `ZAG_AGENT_API_ENDPOINT`;缺失时凭据管理器禁用)。 */
|
|
41
|
+
agentApiEndpoint?: string;
|
|
42
|
+
/** 云主机 controllerId(env `ZAG_CONTROLLER_ID`;缺失时凭据管理器禁用)。 */
|
|
43
|
+
controllerId?: string;
|
|
35
44
|
}
|
|
36
45
|
|
|
37
46
|
/** 云电脑 env 校验失败(消息只含变量名,不含任何值)。 */
|
|
@@ -87,9 +96,18 @@ export function readCloudHostEnv(env: NodeJS.ProcessEnv = process.env): CloudHos
|
|
|
87
96
|
hostName: nonEmpty(env.ZAG_HOST_NAME) || hostname(),
|
|
88
97
|
workspace: nonEmpty(env.ZAG_DEFAULT_WORKSPACE) || DEFAULT_WORKSPACE,
|
|
89
98
|
initWaitMs: parseInitWaitMs(env.HARNESS_INIT_WAIT_MS),
|
|
99
|
+
agentApiEndpoint: nonEmpty(env.ZAG_AGENT_API_ENDPOINT) || undefined,
|
|
100
|
+
controllerId: nonEmpty(env.ZAG_CONTROLLER_ID) || undefined,
|
|
90
101
|
};
|
|
91
102
|
}
|
|
92
103
|
|
|
104
|
+
/** 凭据管理器最小接口(supervisor 只依赖生命周期与 refreshNow,便于测试注入)。 */
|
|
105
|
+
export interface CredentialManagerLike {
|
|
106
|
+
start(): void;
|
|
107
|
+
stop(): void;
|
|
108
|
+
refreshNow(): Promise<GithubCredentialRefreshResult>;
|
|
109
|
+
}
|
|
110
|
+
|
|
93
111
|
/** 依赖注入(测试锚定时序与副作用;生产使用默认实现)。 */
|
|
94
112
|
export interface CloudHostSupervisorDeps {
|
|
95
113
|
env?: NodeJS.ProcessEnv;
|
|
@@ -99,6 +117,8 @@ export interface CloudHostSupervisorDeps {
|
|
|
99
117
|
log?: (message: string) => void;
|
|
100
118
|
/** 是否接管 SIGINT/SIGTERM(默认 true;测试关闭以免污染进程)。 */
|
|
101
119
|
installSignalHandlers?: boolean;
|
|
120
|
+
/** 注入 Github 凭据管理器(测试用);缺省按容器 env 创建。 */
|
|
121
|
+
credentialManager?: CredentialManagerLike;
|
|
102
122
|
}
|
|
103
123
|
|
|
104
124
|
export interface CloudHostSupervisorHandle {
|
|
@@ -174,6 +194,21 @@ export async function startCloudHostSupervisor(
|
|
|
174
194
|
await makeDir(env.workspace);
|
|
175
195
|
log(`[CloudHost] workspace ready: ${env.workspace}`);
|
|
176
196
|
|
|
197
|
+
// Github 凭据管理器:env 缺失时自身只 warn 并禁用,绝不阻塞云主机上线。
|
|
198
|
+
const credentialManager =
|
|
199
|
+
deps.credentialManager ??
|
|
200
|
+
new GithubCredentialManager({ env: deps.env ?? process.env, log });
|
|
201
|
+
credentialManager.start();
|
|
202
|
+
|
|
203
|
+
const beforeWorkloadBatch = async (payload: WorkloadRunPayload): Promise<void> => {
|
|
204
|
+
if (payload.githubAuth !== true) return;
|
|
205
|
+
const result = await credentialManager.refreshNow();
|
|
206
|
+
if (result.ok) return;
|
|
207
|
+
if (result.error === 'no-binding') throw new Error('未设置 Github 项目');
|
|
208
|
+
if (result.error === 'disabled') throw new Error('云主机未配置 Github 凭据申请环境');
|
|
209
|
+
throw new Error(result.error || 'Github 凭据申请失败');
|
|
210
|
+
};
|
|
211
|
+
|
|
177
212
|
let controllerSocket: Socket | null = null;
|
|
178
213
|
let initWaitTimer: ReturnType<typeof setTimeout> | null = null;
|
|
179
214
|
let waitingForInit = false;
|
|
@@ -193,6 +228,7 @@ export async function startCloudHostSupervisor(
|
|
|
193
228
|
clearInitTimer();
|
|
194
229
|
const exitCode = code ?? resolveShutdownExitCode(reason);
|
|
195
230
|
log(`[CloudHost] shutting down: ${reason} (exit ${exitCode})`);
|
|
231
|
+
credentialManager.stop();
|
|
196
232
|
try {
|
|
197
233
|
workerSocket.disconnect();
|
|
198
234
|
} catch {
|
|
@@ -246,6 +282,7 @@ export async function startCloudHostSupervisor(
|
|
|
246
282
|
handleWorkload: true,
|
|
247
283
|
skipLocalMcpStart: true,
|
|
248
284
|
persistConfig: false,
|
|
285
|
+
onBeforeWorkloadBatch: beforeWorkloadBatch,
|
|
249
286
|
onRegistered: (payload) => {
|
|
250
287
|
log(`[CloudHost] worker registered: ${payload.controllerId}${payload.initializing ? ' (initializing)' : ''}`);
|
|
251
288
|
if (payload.initializing) {
|