agent-gear 2.4.0 → 2.6.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 (159) hide show
  1. package/AGENTS.md +108 -5
  2. package/dist/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
  3. package/dist/acp/bridge.d.ts +23 -1
  4. package/dist/acp/bridge.d.ts.map +1 -1
  5. package/dist/acp/bridge.js +152 -17
  6. package/dist/acp/bridge.js.map +1 -1
  7. package/dist/acp/bridge.test.js +366 -1
  8. package/dist/acp/bridge.test.js.map +1 -1
  9. package/dist/acp/capabilities.d.ts +81 -0
  10. package/dist/acp/capabilities.d.ts.map +1 -0
  11. package/dist/acp/capabilities.js +211 -0
  12. package/dist/acp/capabilities.js.map +1 -0
  13. package/dist/acp/capabilities.test.d.ts +2 -0
  14. package/dist/acp/capabilities.test.d.ts.map +1 -0
  15. package/dist/acp/capabilities.test.js +156 -0
  16. package/dist/acp/capabilities.test.js.map +1 -0
  17. package/dist/acp/elicitation.integration.test.d.ts +2 -0
  18. package/dist/acp/elicitation.integration.test.d.ts.map +1 -0
  19. package/dist/acp/elicitation.integration.test.js +98 -0
  20. package/dist/acp/elicitation.integration.test.js.map +1 -0
  21. package/dist/acp/prober.d.ts +4 -0
  22. package/dist/acp/prober.d.ts.map +1 -1
  23. package/dist/acp/prober.js +1 -0
  24. package/dist/acp/prober.js.map +1 -1
  25. package/dist/acp/spawner.d.ts.map +1 -1
  26. package/dist/acp/spawner.js +3 -0
  27. package/dist/acp/spawner.js.map +1 -1
  28. package/dist/acp/sync-bridge.d.ts.map +1 -1
  29. package/dist/acp/sync-bridge.js +5 -1
  30. package/dist/acp/sync-bridge.js.map +1 -1
  31. package/dist/cloud-host/supervisor.d.ts +105 -0
  32. package/dist/cloud-host/supervisor.d.ts.map +1 -0
  33. package/dist/cloud-host/supervisor.js +237 -0
  34. package/dist/cloud-host/supervisor.js.map +1 -0
  35. package/dist/cloud-host/supervisor.test.d.ts +2 -0
  36. package/dist/cloud-host/supervisor.test.d.ts.map +1 -0
  37. package/dist/cloud-host/supervisor.test.js +367 -0
  38. package/dist/cloud-host/supervisor.test.js.map +1 -0
  39. package/dist/commands/harness.d.ts +17 -0
  40. package/dist/commands/harness.d.ts.map +1 -0
  41. package/dist/commands/harness.js +35 -0
  42. package/dist/commands/harness.js.map +1 -0
  43. package/dist/config.d.ts.map +1 -1
  44. package/dist/config.js +10 -3
  45. package/dist/config.js.map +1 -1
  46. package/dist/github/credential-manager.d.ts +70 -0
  47. package/dist/github/credential-manager.d.ts.map +1 -0
  48. package/dist/github/credential-manager.js +205 -0
  49. package/dist/github/credential-manager.js.map +1 -0
  50. package/dist/github/credential-manager.test.d.ts +2 -0
  51. package/dist/github/credential-manager.test.d.ts.map +1 -0
  52. package/dist/github/credential-manager.test.js +215 -0
  53. package/dist/github/credential-manager.test.js.map +1 -0
  54. package/dist/github/gh-config.d.ts +17 -0
  55. package/dist/github/gh-config.d.ts.map +1 -0
  56. package/dist/github/gh-config.js +68 -0
  57. package/dist/github/gh-config.js.map +1 -0
  58. package/dist/github/gh-config.test.d.ts +2 -0
  59. package/dist/github/gh-config.test.d.ts.map +1 -0
  60. package/dist/github/gh-config.test.js +90 -0
  61. package/dist/github/gh-config.test.js.map +1 -0
  62. package/dist/harness/env.d.ts +36 -0
  63. package/dist/harness/env.d.ts.map +1 -0
  64. package/dist/harness/env.js +78 -0
  65. package/dist/harness/env.js.map +1 -0
  66. package/dist/harness/env.test.d.ts +2 -0
  67. package/dist/harness/env.test.d.ts.map +1 -0
  68. package/dist/harness/env.test.js +70 -0
  69. package/dist/harness/env.test.js.map +1 -0
  70. package/dist/harness/opencode-cli.d.ts +24 -0
  71. package/dist/harness/opencode-cli.d.ts.map +1 -0
  72. package/dist/harness/opencode-cli.js +74 -0
  73. package/dist/harness/opencode-cli.js.map +1 -0
  74. package/dist/harness/opencode-cli.test.d.ts +2 -0
  75. package/dist/harness/opencode-cli.test.d.ts.map +1 -0
  76. package/dist/harness/opencode-cli.test.js +62 -0
  77. package/dist/harness/opencode-cli.test.js.map +1 -0
  78. package/dist/harness/opencode-config.atomic-failure.test.d.ts +2 -0
  79. package/dist/harness/opencode-config.atomic-failure.test.d.ts.map +1 -0
  80. package/dist/harness/opencode-config.atomic-failure.test.js +35 -0
  81. package/dist/harness/opencode-config.atomic-failure.test.js.map +1 -0
  82. package/dist/harness/opencode-config.d.ts +54 -0
  83. package/dist/harness/opencode-config.d.ts.map +1 -0
  84. package/dist/harness/opencode-config.js +130 -0
  85. package/dist/harness/opencode-config.js.map +1 -0
  86. package/dist/harness/opencode-config.test.d.ts +2 -0
  87. package/dist/harness/opencode-config.test.d.ts.map +1 -0
  88. package/dist/harness/opencode-config.test.js +183 -0
  89. package/dist/harness/opencode-config.test.js.map +1 -0
  90. package/dist/harness/prepare.d.ts +34 -0
  91. package/dist/harness/prepare.d.ts.map +1 -0
  92. package/dist/harness/prepare.js +46 -0
  93. package/dist/harness/prepare.js.map +1 -0
  94. package/dist/harness/prepare.test.d.ts +2 -0
  95. package/dist/harness/prepare.test.d.ts.map +1 -0
  96. package/dist/harness/prepare.test.js +96 -0
  97. package/dist/harness/prepare.test.js.map +1 -0
  98. package/dist/heartbeat.d.ts.map +1 -1
  99. package/dist/heartbeat.js +2 -0
  100. package/dist/heartbeat.js.map +1 -1
  101. package/dist/index.js +21 -0
  102. package/dist/index.js.map +1 -1
  103. package/dist/socketio-client.d.ts +74 -3
  104. package/dist/socketio-client.d.ts.map +1 -1
  105. package/dist/socketio-client.github.test.d.ts +2 -0
  106. package/dist/socketio-client.github.test.d.ts.map +1 -0
  107. package/dist/socketio-client.github.test.js +66 -0
  108. package/dist/socketio-client.github.test.js.map +1 -0
  109. package/dist/socketio-client.js +267 -78
  110. package/dist/socketio-client.js.map +1 -1
  111. package/dist/socketio-client.test.d.ts +2 -0
  112. package/dist/socketio-client.test.d.ts.map +1 -0
  113. package/dist/socketio-client.test.js +382 -0
  114. package/dist/socketio-client.test.js.map +1 -0
  115. package/dist/workload-executor.d.ts +37 -1
  116. package/dist/workload-executor.d.ts.map +1 -1
  117. package/dist/workload-executor.js +111 -19
  118. package/dist/workload-executor.js.map +1 -1
  119. package/dist/workload-executor.test.js +205 -3
  120. package/dist/workload-executor.test.js.map +1 -1
  121. package/package.json +2 -1
  122. package/src/acp/__fixtures__/fake-elicitation-agent.mjs +113 -0
  123. package/src/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
  124. package/src/acp/bridge.test.ts +480 -1
  125. package/src/acp/bridge.ts +163 -18
  126. package/src/acp/capabilities.test.ts +200 -0
  127. package/src/acp/capabilities.ts +274 -0
  128. package/src/acp/elicitation.integration.test.ts +126 -0
  129. package/src/acp/prober.ts +4 -0
  130. package/src/acp/spawner.ts +3 -0
  131. package/src/acp/sync-bridge.ts +5 -1
  132. package/src/cloud-host/supervisor.test.ts +462 -0
  133. package/src/cloud-host/supervisor.ts +326 -0
  134. package/src/commands/harness.ts +44 -0
  135. package/src/config.ts +9 -3
  136. package/src/github/credential-manager.test.ts +268 -0
  137. package/src/github/credential-manager.ts +251 -0
  138. package/src/github/gh-config.test.ts +103 -0
  139. package/src/github/gh-config.ts +76 -0
  140. package/src/harness/env.test.ts +79 -0
  141. package/src/harness/env.ts +89 -0
  142. package/src/harness/opencode-cli.test.ts +82 -0
  143. package/src/harness/opencode-cli.ts +99 -0
  144. package/src/harness/opencode-config.atomic-failure.test.ts +51 -0
  145. package/src/harness/opencode-config.test.ts +238 -0
  146. package/src/harness/opencode-config.ts +176 -0
  147. package/src/harness/prepare.test.ts +117 -0
  148. package/src/harness/prepare.ts +69 -0
  149. package/src/heartbeat.ts +2 -0
  150. package/src/index.ts +22 -0
  151. package/src/socketio-client.github.test.ts +76 -0
  152. package/src/socketio-client.test.ts +460 -0
  153. package/src/socketio-client.ts +314 -68
  154. package/src/workload-executor.test.ts +264 -2
  155. package/src/workload-executor.ts +147 -18
  156. package/tests/acp-sync-bridge.test.ts +5 -1
  157. package/tests/commands/harness.test.ts +90 -0
  158. package/tests/socketio-client.test.ts +140 -2
  159. package/vitest.config.ts +5 -1
package/src/acp/bridge.ts CHANGED
@@ -2,6 +2,11 @@ import * as acp from '@agentclientprotocol/sdk';
2
2
  import { EventEmitter } from 'events';
3
3
  import type { Socket } from 'socket.io-client';
4
4
  import { AcpSpawner } from './spawner.js';
5
+ import {
6
+ CLIENT_CAPABILITIES,
7
+ normalizeCapabilities,
8
+ type AgentCapabilitySnapshot,
9
+ } from './capabilities.js';
5
10
 
6
11
  const ACP_PROTOCOL_VERSION = 1;
7
12
 
@@ -54,6 +59,8 @@ export interface AcpInitializedPayload {
54
59
  authMethods: AcpAuthMethodData[];
55
60
  supportsAdditionalDirectories: boolean;
56
61
  protocolVersion?: number | null;
62
+ /** 能力快照(Agent 声明 × 平台支持归一化结果) */
63
+ capabilities: AgentCapabilitySnapshot;
57
64
  }
58
65
 
59
66
  function toMcpServers(servers: AcpBridgeOptions['mcpServers']): acp.McpServer[] {
@@ -214,6 +221,9 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
214
221
  private textChunkTimer: ReturnType<typeof setTimeout> | null = null;
215
222
  private initializing = false;
216
223
  private stopped = false;
224
+ private processExitSubscribed = false;
225
+ /** silent stop(同 sessionId 替换/对账):后续迟到的 handleError 不得再向服务端发 stopped */
226
+ private silentStop = false;
217
227
  private pendingPermissions = new Map<string, {
218
228
  resolve: (response: acp.RequestPermissionResponse) => void;
219
229
  timeout: NodeJS.Timeout;
@@ -221,6 +231,8 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
221
231
  private pendingElicitations = new Map<string, {
222
232
  resolve: (response: acp.CreateElicitationResponse) => void;
223
233
  timeout: NodeJS.Timeout;
234
+ /** url 模式的 elicitationId:用于 Agent 自发 complete 时精确定位 pending 请求 */
235
+ elicitationId?: string;
224
236
  }>();
225
237
 
226
238
  // Capability snapshot from initialize / session/new / resume
@@ -228,9 +240,13 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
228
240
  private promptCapabilities: AcpInitializedPayload['promptCapabilities'] = null;
229
241
  private agentInfo: AcpInitializedPayload['agentInfo'] = null;
230
242
  private authMethods: AcpAuthMethodData[] = [];
243
+ /** initialize 返回的 authMethods 原文(契约要求快照 raw 保留对端声明原文,不能存转换后产物) */
244
+ private authMethodsRaw: unknown = null;
231
245
  private supportsAdditionalDirectories = false;
232
246
  private agentProtocolVersion: number | null = null;
233
247
  private agentMcpCapabilities: { http?: boolean | null; sse?: boolean | null } | null = null;
248
+ private agentCapabilitiesRaw: unknown = null;
249
+ private clientCapabilitiesRaw: unknown = CLIENT_CAPABILITIES;
234
250
 
235
251
  constructor(socket: Socket, options: AcpBridgeOptions, spawner?: AcpSpawner) {
236
252
  super();
@@ -272,6 +288,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
272
288
  this.initializing = true;
273
289
 
274
290
  this.spawner.start();
291
+ this.subscribeToProcessExit();
275
292
  try {
276
293
  await this.initConnection();
277
294
  const mcpServers = this.resolveMcpServers();
@@ -300,6 +317,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
300
317
  this.initializing = true;
301
318
 
302
319
  this.spawner.start();
320
+ this.subscribeToProcessExit();
303
321
  try {
304
322
  await this.initConnection();
305
323
  const mcpServers = this.resolveMcpServers();
@@ -337,23 +355,74 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
337
355
  }
338
356
  }
339
357
 
340
- async stop(): Promise<void> {
358
+ async stop(options: { silent?: boolean } = {}): Promise<void> {
359
+ if (options.silent) this.silentStop = true;
360
+ this.activePrompt = null;
361
+ this.inputQueue = [];
362
+ // 会话关闭:所有在途问询/授权必须先同步收敛(在 cancel/closeSession 的 5s race 之前),
363
+ // 否则 race 窗口内 65s timer 仍可能迟到发 timeout。
364
+ this.settlePendingRequests('session stopped by user');
365
+ let stopTimer: ReturnType<typeof setTimeout> | undefined;
341
366
  try {
342
367
  if (this.acpSessionId && this.connection) {
343
- // 5s timeout for cancel/closeSession to prevent hanging
368
+ // 5s timeout for cancel/closeSession to prevent hanging(结束后清理 timer,避免拖住事件循环)
344
369
  await Promise.race([
345
370
  (async () => {
346
371
  await this.connection!.cancel({ sessionId: this.acpSessionId! });
347
372
  await this.connection!.closeSession({ sessionId: this.acpSessionId! });
348
373
  })(),
349
- new Promise<void>((resolve) => setTimeout(resolve, 5000)),
374
+ new Promise<void>((resolve) => { stopTimer = setTimeout(resolve, 5000); }),
350
375
  ]);
351
376
  }
352
- } catch { /* ignore */ }
353
- this.activePrompt = null;
354
- this.inputQueue = [];
377
+ } catch { /* ignore */ } finally {
378
+ if (stopTimer) clearTimeout(stopTimer);
379
+ }
355
380
  this.spawner.stop();
356
- this.emitStopped('user_close');
381
+ this.emitStopped('user_close', undefined, options.silent);
382
+ }
383
+
384
+ /**
385
+ * 清空 pending 请求:clearTimeout + resolve(cancel) + delete。
386
+ * 问询额外回发 resolved(cancelled),让服务端待办收敛为 cancelled 而不是等 65s 超时误标 expired。
387
+ * 同时发出 settled 事件,供 socketio-client 清理 requestId → bridge 映射(避免 Map 单调增长/阻止 GC)。
388
+ */
389
+ private settlePendingRequests(detail: string): void {
390
+ for (const [requestId, pending] of this.pendingElicitations) {
391
+ clearTimeout(pending.timeout);
392
+ this.pendingElicitations.delete(requestId);
393
+ pending.resolve({ action: 'cancel' });
394
+ this.emit('elicitation:settled', requestId);
395
+ this.socket.emit('acp:elicitation:resolved', {
396
+ requestId,
397
+ sessionId: this.sessionId,
398
+ reason: 'cancelled',
399
+ detail: detail.slice(0, 100),
400
+ });
401
+ }
402
+
403
+ for (const [requestId, pending] of this.pendingPermissions) {
404
+ clearTimeout(pending.timeout);
405
+ this.pendingPermissions.delete(requestId);
406
+ pending.resolve({ outcome: { outcome: 'cancelled' } });
407
+ this.emit('permission:settled', requestId);
408
+ }
409
+ }
410
+
411
+ /** 进程退出(不可恢复):收敛所有 pending;socket 仍连接时服务端据 cancelled 收敛待办 */
412
+ private subscribeToProcessExit(): void {
413
+ if (this.processExitSubscribed) return;
414
+ this.processExitSubscribed = true;
415
+ this.spawner.closed.then(() => {
416
+ if (this.stopped) return;
417
+ console.warn(`[ACP bridge] session ${this.sessionId}: process exited, settling pending requests`);
418
+ this.settlePendingRequests('process exited');
419
+ }).catch(() => { /* ignore */ });
420
+ }
421
+
422
+ /** 连接断开(可能自动重连):只收敛 pending,不停止会话进程;重连后可继续使用 */
423
+ settlePendingOnDisconnect(): void {
424
+ if (this.stopped) return;
425
+ this.settlePendingRequests('connection lost');
357
426
  }
358
427
 
359
428
  cancel(): void {
@@ -517,12 +586,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
517
586
  this.connection = new acp.ClientSideConnection(() => this, stream);
518
587
  const result = await this.connection.initialize({
519
588
  protocolVersion: ACP_PROTOCOL_VERSION,
520
- clientCapabilities: {
521
- session: {
522
- configOptions: { boolean: {} },
523
- },
524
- elicitation: { form: {}, url: {} },
525
- },
589
+ clientCapabilities: CLIENT_CAPABILITIES,
526
590
  clientInfo: {
527
591
  name: 'agent-gear',
528
592
  version: '1.1.5',
@@ -530,6 +594,8 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
530
594
  });
531
595
 
532
596
  this.agentProtocolVersion = result.protocolVersion ?? null;
597
+ this.agentCapabilitiesRaw = result.agentCapabilities ?? null;
598
+ this.clientCapabilitiesRaw = CLIENT_CAPABILITIES;
533
599
  if (result.protocolVersion != null && result.protocolVersion !== ACP_PROTOCOL_VERSION) {
534
600
  // 版本不兼容:不断连,由上层提示用户
535
601
  this.socket.emit('acp:protocol-version-mismatch', {
@@ -549,6 +615,8 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
549
615
  this.agentInfo = result.agentInfo
550
616
  ? { name: result.agentInfo.name, version: result.agentInfo.version ?? null }
551
617
  : null;
618
+ // 原文留存与归一化分离:authMethods 用于下发/展示,authMethodsRaw 只进能力快照 raw
619
+ this.authMethodsRaw = result.authMethods ?? null;
552
620
  this.authMethods = toAuthMethods(result.authMethods);
553
621
  this.agentMcpCapabilities = result.agentCapabilities?.mcpCapabilities ?? null;
554
622
  console.log(
@@ -615,6 +683,17 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
615
683
  authMethods: this.authMethods,
616
684
  supportsAdditionalDirectories: this.supportsAdditionalDirectories,
617
685
  protocolVersion: this.agentProtocolVersion,
686
+ capabilities: normalizeCapabilities({
687
+ protocolVersion: this.agentProtocolVersion,
688
+ agentInfo: this.agentInfo
689
+ ? { name: this.agentInfo.name, version: this.agentInfo.version ?? null }
690
+ : null,
691
+ agentCapabilities: this.agentCapabilitiesRaw,
692
+ authMethods: this.authMethodsRaw,
693
+ clientCapabilities: this.clientCapabilitiesRaw,
694
+ configOptions: this.configOptions,
695
+ modes,
696
+ }),
618
697
  };
619
698
  }
620
699
 
@@ -681,6 +760,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
681
760
  return new Promise((resolve) => {
682
761
  const timeout = setTimeout(() => {
683
762
  this.pendingPermissions.delete(requestId);
763
+ this.emit('permission:settled', requestId);
684
764
  resolve({ outcome: { outcome: 'cancelled' } });
685
765
  }, 65_000);
686
766
 
@@ -706,27 +786,59 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
706
786
 
707
787
  clearTimeout(pending.timeout);
708
788
  this.pendingPermissions.delete(requestId);
789
+ this.emit('permission:settled', requestId);
709
790
  pending.resolve({ outcome });
710
791
  }
711
792
 
712
793
  async unstable_createElicitation(
713
794
  params: acp.CreateElicitationRequest,
714
795
  ): Promise<acp.CreateElicitationResponse> {
715
- // custom/未知模式不支持:立即取消,避免挂起 Agent
796
+ // 先分配 requestId:unsupported_mode 事件同样需要可定位的请求 id,
797
+ // 否则接收端只能按 sessionId 兜底或静默丢弃。
798
+ const requestId = `elic_${Date.now()}_${Math.random().toString(36).slice(2)}`;
799
+
800
+ // custom/未知模式不支持:立即取消,避免挂起 Agent。必须留下日志与 resolved 事件,
801
+ // 否则「Agent 发起问询但用户从未看到弹窗」无法从日志/待办侧定位。
716
802
  if (!acp.CreateElicitationRequest.isForm(params) && !acp.CreateElicitationRequest.isUrl(params)) {
803
+ const mode = (params as { mode?: unknown }).mode ?? 'unknown';
804
+ console.warn('[ACP bridge] session %s: unsupported elicitation mode=%j', this.sessionId, mode);
805
+ this.socket.emit('acp:elicitation:resolved', {
806
+ requestId,
807
+ sessionId: this.sessionId,
808
+ reason: 'unsupported_mode',
809
+ // Agent 可控字符串:截断后再入事件/日志,避免无限放大
810
+ detail: String(mode).slice(0, 100),
811
+ });
717
812
  return { action: 'cancel' };
718
813
  }
719
814
 
720
- const requestId = `elic_${Date.now()}_${Math.random().toString(36).slice(2)}`;
721
815
  const toolCallId = 'toolCallId' in params ? params.toolCallId : undefined;
722
816
 
723
817
  return new Promise((resolve) => {
724
818
  const timeout = setTimeout(() => {
725
819
  this.pendingElicitations.delete(requestId);
820
+ this.emit('elicitation:settled', requestId);
821
+ console.warn(
822
+ '[ACP bridge] session %s: elicitation %s timed out after 65s, auto-cancelling',
823
+ this.sessionId,
824
+ requestId,
825
+ );
826
+ this.socket.emit('acp:elicitation:resolved', {
827
+ requestId,
828
+ sessionId: this.sessionId,
829
+ reason: 'timeout',
830
+ detail: 'bridge timeout (65s)',
831
+ });
726
832
  resolve({ action: 'cancel' });
727
833
  }, 65_000);
728
834
 
729
- this.pendingElicitations.set(requestId, { resolve, timeout });
835
+ this.pendingElicitations.set(requestId, {
836
+ resolve,
837
+ timeout,
838
+ ...('elicitationId' in params && params.elicitationId
839
+ ? { elicitationId: String(params.elicitationId) }
840
+ : {}),
841
+ });
730
842
 
731
843
  if (acp.CreateElicitationRequest.isForm(params)) {
732
844
  this.socket.emit('acp:elicitation', {
@@ -766,6 +878,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
766
878
 
767
879
  clearTimeout(pending.timeout);
768
880
  this.pendingElicitations.delete(requestId);
881
+ this.emit('elicitation:settled', requestId);
769
882
  pending.resolve({
770
883
  action,
771
884
  ...(action === 'accept' && content
@@ -779,6 +892,24 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
779
892
  sessionId: this.sessionId,
780
893
  elicitationId: params.elicitationId,
781
894
  });
895
+
896
+ // Agent 自行完成/取消:对匹配的 pending 就地收敛,避免悬挂到 65s 被误标 expired。
897
+ // 契约 reason:'cancelled' 的产生路径之一(另一处为会话关闭 settle)。
898
+ const entry = [...this.pendingElicitations.entries()]
899
+ .find(([, pending]) => pending.elicitationId === params.elicitationId);
900
+ if (!entry) return;
901
+
902
+ const [requestId, pending] = entry;
903
+ clearTimeout(pending.timeout);
904
+ this.pendingElicitations.delete(requestId);
905
+ this.emit('elicitation:settled', requestId);
906
+ pending.resolve({ action: 'cancel' });
907
+ this.socket.emit('acp:elicitation:resolved', {
908
+ requestId,
909
+ sessionId: this.sessionId,
910
+ reason: 'cancelled',
911
+ detail: 'agent completed elicitation',
912
+ });
782
913
  }
783
914
 
784
915
  // ── text buffering ──
@@ -813,9 +944,17 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
813
944
  });
814
945
  }
815
946
 
816
- private emitStopped(reason: string, exitCode?: number): void {
817
- console.log(`[ACP bridge] session ${this.sessionId} stopped: reason=${reason} exitCode=${exitCode ?? 'n/a'}`);
947
+ private emitStopped(reason: string, exitCode?: number, silent = false): void {
948
+ console.log(`[ACP bridge] session ${this.sessionId} stopped: reason=${reason} exitCode=${exitCode ?? 'n/a'}${silent ? ' (silent)' : ''}`);
818
949
  this.stopped = true;
950
+ if (this.textChunkTimer) {
951
+ clearTimeout(this.textChunkTimer);
952
+ this.textChunkTimer = null;
953
+ }
954
+ // silent:同 sessionId 被替换/对账杀掉时,旧 bridge 的迟到 stopped 不得删除新会话映射。
955
+ // silentStop 为 once-silent-always-silent:非 silent stop 在 5s race 在途时被替换路径
956
+ // 的 stop({silent:true}) 接管,迟到的 emitStopped 同样必须抑制(R6a)。
957
+ if (silent || this.silentStop) return;
819
958
  this.socket.emit('acp:stopped', { sessionId: this.sessionId, reason, exitCode });
820
959
  this.emit('acp:stopped', { sessionId: this.sessionId, reason, exitCode });
821
960
  }
@@ -824,7 +963,13 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
824
963
  const msg = error instanceof Error ? error.message : String(error);
825
964
  const stack = error instanceof Error ? error.stack : undefined;
826
965
  console.error(`[ACP bridge] session ${this.sessionId} failed: ${msg}${stack ? `\n${stack}` : ''}`);
966
+ const wasStopped = this.stopped || this.silentStop;
827
967
  this.stopped = true;
968
+ // 进程崩溃同样必须收敛 pending:否则 65s timer 泄漏且迟发 timeout 事件
969
+ this.settlePendingRequests('session failed');
970
+ // 已停止(含 silent 替换/对账)后迟到的初始化失败:不得再发 stopped,
971
+ // 否则内联监听器/服务端会按 sessionId 删除新会话的注册与映射。
972
+ if (wasStopped) return;
828
973
  this.socket.emit('acp:stopped', {
829
974
  sessionId: this.sessionId,
830
975
  reason: 'error',
@@ -0,0 +1,200 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import {
3
+ CLIENT_CAPABILITIES,
4
+ FEATURE_IDS,
5
+ normalizeCapabilities,
6
+ RAW_SNAPSHOT_MAX_BYTES,
7
+ type AgentCapabilitySnapshot,
8
+ } from './capabilities.js';
9
+ import opencodeFixture from './__fixtures__/opencode-2.0.31-capabilities.json' with { type: 'json' };
10
+
11
+ type Fixture = {
12
+ protocolVersion: number;
13
+ agentCapabilities: Record<string, unknown>;
14
+ authMethods: unknown[];
15
+ agentInfo: { name: string; version: string };
16
+ };
17
+
18
+ const fixture = opencodeFixture as Fixture;
19
+
20
+ const MODEL_CONFIG = [
21
+ { id: 'model', type: 'select', category: 'model' },
22
+ { id: 'mode', type: 'select', category: 'mode' },
23
+ ];
24
+
25
+ function normalizeWith(overrides: {
26
+ agentCapabilities?: unknown;
27
+ authMethods?: unknown;
28
+ clientCapabilities?: unknown;
29
+ configOptions?: Array<{ id: string; type: string; category?: string | null }>;
30
+ modes?: Array<{ id: string; name: string }>;
31
+ } = {}): AgentCapabilitySnapshot {
32
+ return normalizeCapabilities({
33
+ protocolVersion: fixture.protocolVersion,
34
+ agentInfo: fixture.agentInfo,
35
+ agentCapabilities: overrides.agentCapabilities === undefined
36
+ ? fixture.agentCapabilities
37
+ : overrides.agentCapabilities,
38
+ authMethods: overrides.authMethods === undefined ? fixture.authMethods : overrides.authMethods,
39
+ clientCapabilities: overrides.clientCapabilities === undefined
40
+ ? CLIENT_CAPABILITIES
41
+ : overrides.clientCapabilities,
42
+ configOptions: overrides.configOptions ?? MODEL_CONFIG,
43
+ modes: overrides.modes ?? [],
44
+ });
45
+ }
46
+
47
+ function statusOf(snapshot: AgentCapabilitySnapshot, id: string) {
48
+ return snapshot.features.find((f) => f.id === id);
49
+ }
50
+
51
+ describe('normalizeCapabilities', () => {
52
+ it('T-C1: OpenCode 2.0.31 fixture 全量归一化', () => {
53
+ const snapshot = normalizeWith();
54
+ const fixtureFeatures = fixture.agentCapabilities as {
55
+ promptCapabilities: { image: boolean };
56
+ sessionCapabilities: Record<string, unknown>;
57
+ };
58
+ expect(fixtureFeatures.promptCapabilities.image).toBe(true);
59
+ expect(fixtureFeatures.sessionCapabilities.fork).toEqual({});
60
+
61
+ expect(snapshot.features.map((f) => f.id)).toEqual([...FEATURE_IDS]);
62
+
63
+ for (const id of ['session.load', 'session.resume', 'session.close', 'session.list', 'session.delete']) {
64
+ expect(statusOf(snapshot, id)?.status).toBe('supported');
65
+ }
66
+ expect(statusOf(snapshot, 'prompt.image')?.status).toBe('partial');
67
+ expect(statusOf(snapshot, 'prompt.embeddedContext')?.status).toBe('partial');
68
+ expect(statusOf(snapshot, 'prompt.audio')?.status).toBe('unsupported');
69
+ expect(statusOf(snapshot, 'session.fork')?.status).toBe('partial');
70
+ expect(statusOf(snapshot, 'session.additionalDirectories')?.status).toBe('partial');
71
+ expect(statusOf(snapshot, 'config.model')?.status).toBe('supported');
72
+ expect(statusOf(snapshot, 'config.mode')?.status).toBe('supported');
73
+ expect(statusOf(snapshot, 'mcp.http')?.status).toBe('supported');
74
+ expect(statusOf(snapshot, 'mcp.sse')?.status).toBe('unsupported');
75
+ expect(statusOf(snapshot, 'commands')?.status).toBe('partial');
76
+ expect(statusOf(snapshot, 'elicitation.form')?.status).toBe('supported');
77
+ expect(statusOf(snapshot, 'elicitation.url')?.status).toBe('supported');
78
+ });
79
+
80
+ it('T-C2: agentCapabilities 为 null(旧 Agent)时仍返回全集,声明类全部 unsupported', () => {
81
+ const snapshot = normalizeWith({ agentCapabilities: null, authMethods: [], configOptions: [], modes: [] });
82
+
83
+ expect(snapshot.features).toHaveLength(FEATURE_IDS.length);
84
+ for (const id of [
85
+ 'session.load',
86
+ 'session.resume',
87
+ 'session.close',
88
+ 'session.list',
89
+ 'session.delete',
90
+ 'session.fork',
91
+ 'session.additionalDirectories',
92
+ 'prompt.image',
93
+ 'prompt.audio',
94
+ 'prompt.embeddedContext',
95
+ 'auth.login',
96
+ 'auth.logout',
97
+ 'mcp.http',
98
+ 'mcp.sse',
99
+ 'config.model',
100
+ 'config.mode',
101
+ ]) {
102
+ const feature = statusOf(snapshot, id);
103
+ expect(feature?.status, id).toBe('unsupported');
104
+ expect(feature?.detail, id).toMatch(/^未声明 /);
105
+ }
106
+ // 本端声明的能力仍为 supported
107
+ expect(statusOf(snapshot, 'elicitation.form')?.status).toBe('supported');
108
+ expect(statusOf(snapshot, 'elicitation.url')?.status).toBe('supported');
109
+ expect(statusOf(snapshot, 'config.boolean')?.status).toBe('supported');
110
+ });
111
+
112
+ it('T-C3: {} 与 false 区分', () => {
113
+ const snapshot = normalizeWith({
114
+ agentCapabilities: { sessionCapabilities: { resume: {}, close: false } },
115
+ });
116
+
117
+ expect(statusOf(snapshot, 'session.resume')?.status).toBe('supported');
118
+ expect(statusOf(snapshot, 'session.close')?.status).toBe('unsupported');
119
+ expect(statusOf(snapshot, 'session.close')?.detail).toContain('sessionCapabilities.close');
120
+ });
121
+
122
+ it('T-C4: authMethods 非空时 auth.login=partial,auth.logout=unsupported', () => {
123
+ const snapshot = normalizeWith({
124
+ authMethods: [{ id: 'login' }],
125
+ agentCapabilities: {},
126
+ });
127
+
128
+ expect(statusOf(snapshot, 'auth.login')?.status).toBe('partial');
129
+ expect(statusOf(snapshot, 'auth.login')?.detail).toContain('平台');
130
+ expect(statusOf(snapshot, 'auth.logout')?.status).toBe('unsupported');
131
+ expect(statusOf(snapshot, 'auth.logout')?.detail).toMatch(/^未声明 /);
132
+ });
133
+
134
+ it('T-C5: 无 mode 配置项但 modes[] 非空时 config.mode=supported', () => {
135
+ const snapshot = normalizeWith({
136
+ configOptions: [{ id: 'model', type: 'select', category: 'model' }],
137
+ modes: [{ id: 'build', name: 'Build' }],
138
+ });
139
+
140
+ expect(statusOf(snapshot, 'config.mode')?.status).toBe('supported');
141
+ });
142
+
143
+ it('T-C6: _meta 扩展键原样进入 raw,不产生 feature', () => {
144
+ const snapshot = normalizeWith();
145
+
146
+ expect(snapshot.features).toHaveLength(FEATURE_IDS.length);
147
+ expect(snapshot.features.some((f) => f.id.includes('_meta'))).toBe(false);
148
+ expect((snapshot.raw.agentCapabilities as { _meta?: unknown })._meta).toEqual({
149
+ 'opencode/child-session-updates': true,
150
+ });
151
+ });
152
+
153
+ it('T-C7: raw 保真(三份声明与入参深相等)', () => {
154
+ const snapshot = normalizeWith();
155
+
156
+ expect(snapshot.raw.agentCapabilities).toEqual(fixture.agentCapabilities);
157
+ expect(snapshot.raw.authMethods).toEqual(fixture.authMethods);
158
+ // 显式值断言(非自引用常量),防止常量被改空后测试恒绿
159
+ expect(snapshot.raw.clientCapabilities).toEqual({
160
+ session: { configOptions: { boolean: {} } },
161
+ elicitation: { form: {}, url: {} },
162
+ });
163
+ expect(snapshot.protocolVersion).toBe(1);
164
+ expect(snapshot.agentInfo).toEqual({ name: 'OpenCode', version: '2.0.31' });
165
+ });
166
+
167
+ it('T-C9: 超限 raw 只保留截断摘要,不原样外露', () => {
168
+ const hugeKey = 'x'.repeat(64);
169
+ const huge = { [hugeKey]: 'y'.repeat(RAW_SNAPSHOT_MAX_BYTES * 2) };
170
+ const snapshot = normalizeCapabilities({
171
+ protocolVersion: 1,
172
+ agentInfo: { name: 'A', version: null },
173
+ agentCapabilities: huge,
174
+ authMethods: [],
175
+ clientCapabilities: CLIENT_CAPABILITIES,
176
+ configOptions: [],
177
+ modes: [],
178
+ });
179
+
180
+ const raw = snapshot.raw.agentCapabilities as { truncated?: boolean; originalBytes?: number; preview?: string };
181
+ expect(raw).toMatchObject({ truncated: true });
182
+ expect(raw.originalBytes).toBeGreaterThan(RAW_SNAPSHOT_MAX_BYTES);
183
+ expect(raw.preview?.length).toBeLessThanOrEqual(512);
184
+ // 超限时不得保留原文键
185
+ expect(raw).not.toHaveProperty(hugeKey);
186
+ });
187
+
188
+ it('T-C8: detail 文案(unsupported 以「未声明 <字段>」开头;partial 含「平台」)', () => {
189
+ const snapshot = normalizeWith();
190
+
191
+ for (const feature of snapshot.features) {
192
+ if (feature.status === 'unsupported') {
193
+ expect(feature.detail, feature.id).toMatch(/^未声明 /);
194
+ }
195
+ if (feature.status === 'partial') {
196
+ expect(feature.detail, feature.id).toContain('平台');
197
+ }
198
+ }
199
+ });
200
+ });