agent-gear 2.8.0 → 2.10.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 (116) hide show
  1. package/AGENTS.md +35 -5
  2. package/dist/acp/bridge.d.ts +29 -1
  3. package/dist/acp/bridge.d.ts.map +1 -1
  4. package/dist/acp/bridge.js +171 -27
  5. package/dist/acp/bridge.js.map +1 -1
  6. package/dist/acp/bridge.test.js +198 -15
  7. package/dist/acp/bridge.test.js.map +1 -1
  8. package/dist/acp/detector.d.ts +2 -0
  9. package/dist/acp/detector.d.ts.map +1 -1
  10. package/dist/acp/detector.js +18 -3
  11. package/dist/acp/detector.js.map +1 -1
  12. package/dist/acp/detector.test.d.ts +2 -0
  13. package/dist/acp/detector.test.d.ts.map +1 -0
  14. package/dist/acp/detector.test.js +50 -0
  15. package/dist/acp/detector.test.js.map +1 -0
  16. package/dist/acp/initial-config.integration.test.d.ts +2 -0
  17. package/dist/acp/initial-config.integration.test.d.ts.map +1 -0
  18. package/dist/acp/initial-config.integration.test.js +95 -0
  19. package/dist/acp/initial-config.integration.test.js.map +1 -0
  20. package/dist/cloud-host/supervisor.d.ts +8 -19
  21. package/dist/cloud-host/supervisor.d.ts.map +1 -1
  22. package/dist/cloud-host/supervisor.js +7 -27
  23. package/dist/cloud-host/supervisor.js.map +1 -1
  24. package/dist/cloud-host/supervisor.test.js +12 -6
  25. package/dist/cloud-host/supervisor.test.js.map +1 -1
  26. package/dist/commands/harness.d.ts +5 -1
  27. package/dist/commands/harness.d.ts.map +1 -1
  28. package/dist/commands/harness.js +7 -3
  29. package/dist/commands/harness.js.map +1 -1
  30. package/dist/exit-codes.d.ts +30 -0
  31. package/dist/exit-codes.d.ts.map +1 -0
  32. package/dist/exit-codes.js +52 -0
  33. package/dist/exit-codes.js.map +1 -0
  34. package/dist/exit-codes.test.d.ts +2 -0
  35. package/dist/exit-codes.test.d.ts.map +1 -0
  36. package/dist/exit-codes.test.js +61 -0
  37. package/dist/exit-codes.test.js.map +1 -0
  38. package/dist/harness/dsh-cli.d.ts +17 -0
  39. package/dist/harness/dsh-cli.d.ts.map +1 -0
  40. package/dist/harness/dsh-cli.js +51 -0
  41. package/dist/harness/dsh-cli.js.map +1 -0
  42. package/dist/harness/dsh-cli.test.d.ts +2 -0
  43. package/dist/harness/dsh-cli.test.d.ts.map +1 -0
  44. package/dist/harness/dsh-cli.test.js +51 -0
  45. package/dist/harness/dsh-cli.test.js.map +1 -0
  46. package/dist/harness/dsh-config.atomic-failure.test.d.ts +2 -0
  47. package/dist/harness/dsh-config.atomic-failure.test.d.ts.map +1 -0
  48. package/dist/harness/dsh-config.atomic-failure.test.js +35 -0
  49. package/dist/harness/dsh-config.atomic-failure.test.js.map +1 -0
  50. package/dist/harness/dsh-config.d.ts +46 -0
  51. package/dist/harness/dsh-config.d.ts.map +1 -0
  52. package/dist/harness/dsh-config.js +228 -0
  53. package/dist/harness/dsh-config.js.map +1 -0
  54. package/dist/harness/dsh-config.test.d.ts +2 -0
  55. package/dist/harness/dsh-config.test.d.ts.map +1 -0
  56. package/dist/harness/dsh-config.test.js +229 -0
  57. package/dist/harness/dsh-config.test.js.map +1 -0
  58. package/dist/harness/env.d.ts +11 -0
  59. package/dist/harness/env.d.ts.map +1 -1
  60. package/dist/harness/env.js +23 -0
  61. package/dist/harness/env.js.map +1 -1
  62. package/dist/harness/env.test.js +25 -3
  63. package/dist/harness/env.test.js.map +1 -1
  64. package/dist/harness/opencode-cli.d.ts +5 -0
  65. package/dist/harness/opencode-cli.d.ts.map +1 -1
  66. package/dist/harness/opencode-cli.js +8 -1
  67. package/dist/harness/opencode-cli.js.map +1 -1
  68. package/dist/harness/prepare.d.ts +27 -9
  69. package/dist/harness/prepare.d.ts.map +1 -1
  70. package/dist/harness/prepare.js +67 -23
  71. package/dist/harness/prepare.js.map +1 -1
  72. package/dist/harness/prepare.test.js +112 -5
  73. package/dist/harness/prepare.test.js.map +1 -1
  74. package/dist/index.d.ts +1 -1
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +1 -0
  77. package/dist/index.js.map +1 -1
  78. package/dist/socketio-client.auth-gate.test.js +3 -3
  79. package/dist/socketio-client.auth-gate.test.js.map +1 -1
  80. package/dist/socketio-client.d.ts.map +1 -1
  81. package/dist/socketio-client.js +27 -3
  82. package/dist/socketio-client.js.map +1 -1
  83. package/dist/socketio-client.test.js +37 -0
  84. package/dist/socketio-client.test.js.map +1 -1
  85. package/dist/workload-executor.test.js +2 -2
  86. package/dist/workload-executor.test.js.map +1 -1
  87. package/package.json +3 -2
  88. package/src/acp/__fixtures__/fake-initial-config-agent.mjs +113 -0
  89. package/src/acp/bridge.test.ts +223 -15
  90. package/src/acp/bridge.ts +188 -27
  91. package/src/acp/detector.test.ts +64 -0
  92. package/src/acp/detector.ts +18 -3
  93. package/src/acp/initial-config.integration.test.ts +120 -0
  94. package/src/cloud-host/supervisor.test.ts +15 -6
  95. package/src/cloud-host/supervisor.ts +22 -35
  96. package/src/commands/harness.ts +9 -3
  97. package/src/exit-codes.test.ts +73 -0
  98. package/src/exit-codes.ts +59 -0
  99. package/src/harness/dsh-cli.test.ts +58 -0
  100. package/src/harness/dsh-cli.ts +67 -0
  101. package/src/harness/dsh-config.atomic-failure.test.ts +51 -0
  102. package/src/harness/dsh-config.test.ts +275 -0
  103. package/src/harness/dsh-config.ts +280 -0
  104. package/src/harness/env.test.ts +34 -3
  105. package/src/harness/env.ts +26 -0
  106. package/src/harness/opencode-cli.ts +9 -2
  107. package/src/harness/prepare.test.ts +131 -5
  108. package/src/harness/prepare.ts +103 -27
  109. package/src/index.ts +7 -0
  110. package/src/socketio-client.auth-gate.test.ts +3 -3
  111. package/src/socketio-client.test.ts +44 -0
  112. package/src/socketio-client.ts +27 -3
  113. package/src/workload-executor.test.ts +2 -2
  114. package/tests/acp-detector.test.ts +28 -8
  115. package/tests/commands/harness.test.ts +18 -8
  116. package/tests/socketio-client.test.ts +4 -4
package/src/acp/bridge.ts CHANGED
@@ -10,6 +10,14 @@ import {
10
10
 
11
11
  const ACP_PROTOCOL_VERSION = 1;
12
12
 
13
+ /** 初始 mode/model 应用后回读确认失败时的重试间隔 */
14
+ const INITIAL_CONFIG_RETRY_DELAY_MS = 300;
15
+
16
+ function initialConfigPendingTimeoutMs(): number {
17
+ const raw = Number(process.env.INITIAL_CONFIG_PENDING_TIMEOUT_MS);
18
+ return Number.isFinite(raw) && raw > 0 ? raw : 10_000;
19
+ }
20
+
13
21
  export interface AcpBridgeOptions {
14
22
  sessionId: string;
15
23
  cwd: string;
@@ -234,6 +242,19 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
234
242
  /** url 模式的 elicitationId:用于 Agent 自发 complete 时精确定位 pending 请求 */
235
243
  elicitationId?: string;
236
244
  }>();
245
+ /** 初始 mode/model 应用确认结果(契约 §2.39;仅请求过 modeId/modelId 时非空) */
246
+ private initialConfigResult: {
247
+ modeId?: string;
248
+ modelId?: string;
249
+ modeStatus?: 'applied' | 'failed';
250
+ modelStatus?: 'applied' | 'failed';
251
+ error?: string;
252
+ } | null = null;
253
+ /** apply 时缺少可用通道(configOptions 未随 session/new 到达)而挂起等待 config_option_update 的类目 */
254
+ private pendingInitialConfigKinds: Array<'mode' | 'model'> = [];
255
+ private initialConfigPendingTimer: ReturnType<typeof setTimeout> | null = null;
256
+ private initialConfigRetrying = false;
257
+ private initialConfigEmitted = false;
237
258
 
238
259
  // Capability snapshot from initialize / session/new / resume
239
260
  private configOptions: SessionConfigOptionData[] = [];
@@ -301,10 +322,11 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
301
322
  this.acpSessionId = result.sessionId;
302
323
  this.initializing = false;
303
324
 
304
- const initialized = this.buildInitializedPayload(result);
305
- // 工作流节点配置的初始 mode/model:在首条 prompt 前应用,而非使用 harness 默认设置
325
+ this.absorbSessionConfigOptions(result);
326
+ // 工作流节点配置的初始 mode/model:在首条 prompt 前应用,而非使用 harness 默认设置;
327
+ // initialized payload 须在应用之后构造,携带确认后的生效值而非默认值
306
328
  await this.applyInitialModeModel();
307
- this.emit('acp:initialized', initialized);
329
+ this.emit('acp:initialized', this.buildInitializedPayload(result));
308
330
  this.flushInputQueue();
309
331
  } catch (error) {
310
332
  this.initializing = false;
@@ -331,6 +353,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
331
353
  this.acpSessionId = externalSessionId;
332
354
  this.initializing = false;
333
355
 
356
+ this.absorbSessionConfigOptions(result);
334
357
  // 初始 mode/model 在 acp:initialized 之前应用(时序同 start:initialized → resume:result → prompt 补发)
335
358
  await this.applyInitialModeModel();
336
359
  this.emit('acp:initialized', this.buildInitializedPayload(result));
@@ -346,6 +369,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
346
369
  this.acpSessionId = result.sessionId;
347
370
  this.initializing = false;
348
371
 
372
+ this.absorbSessionConfigOptions(result);
349
373
  await this.applyInitialModeModel();
350
374
  this.emit('acp:initialized', this.buildInitializedPayload(result));
351
375
  } catch (fallbackError) {
@@ -362,6 +386,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
362
386
  // 会话关闭:所有在途问询/授权必须先同步收敛(在 cancel/closeSession 的 5s race 之前),
363
387
  // 否则 race 窗口内 65s timer 仍可能迟到发 timeout。
364
388
  this.settlePendingRequests('session stopped by user');
389
+ this.clearPendingInitialConfig();
365
390
  let stopTimer: ReturnType<typeof setTimeout> | undefined;
366
391
  try {
367
392
  if (this.acpSessionId && this.connection) {
@@ -435,12 +460,9 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
435
460
  if (!this.connection || !this.acpSessionId) return;
436
461
  const modeConfig = findConfigByCategory(this.configOptions, 'mode');
437
462
  if (modeConfig) {
438
- // 配置项通道:Agent 提供 configOptions 时以配置项为准
439
- await this.connection.setSessionConfigOption({
440
- sessionId: this.acpSessionId,
441
- configId: modeConfig.id,
442
- value: modeId,
443
- });
463
+ // 配置项通道:Agent 提供 configOptions 时以配置项为准;复用 setConfigOption
464
+ // 以获得响应快照刷新 + acp:config-options 回发(与 acp:set-config-option 行为一致)
465
+ await this.setConfigOption(modeConfig.id, modeId);
444
466
  return;
445
467
  }
446
468
  await this.connection.setSessionMode({
@@ -453,11 +475,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
453
475
  if (!this.connection || !this.acpSessionId) return;
454
476
  const modelConfig = findConfigByCategory(this.configOptions, 'model');
455
477
  if (modelConfig) {
456
- await this.connection.setSessionConfigOption({
457
- sessionId: this.acpSessionId,
458
- configId: modelConfig.id,
459
- value: modelId,
460
- });
478
+ await this.setConfigOption(modelConfig.id, modelId);
461
479
  return;
462
480
  }
463
481
  // SDK 1.x 已移除 unstable_setSessionModel:无 configOptions 的旧 Agent 无法走配置项通道。
@@ -465,25 +483,157 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
465
483
  throw new Error('Model switching is not supported: agent does not expose a model config option');
466
484
  }
467
485
 
468
- /** 会话初始化(session/new 之后、首条 prompt 之前)应用工作流节点配置的初始 mode/model */
486
+ /**
487
+ * 会话初始化(session/new 之后、首条 prompt 之前)应用工作流节点配置的初始 mode/model。
488
+ * 契约 §2.4「初始模式/模型应用确认」:应用 → 回读确认 → 重试一次 → 结果上报;
489
+ * apply 时缺少可用通道(configOptions 未随响应到达)则挂起,待 config_option_update 补应用。
490
+ */
469
491
  private async applyInitialModeModel(): Promise<void> {
492
+ if (!this.initialModeId && !this.initialModelId) return;
493
+ this.initialConfigResult = {
494
+ ...(this.initialModeId ? { modeId: this.initialModeId } : {}),
495
+ ...(this.initialModelId ? { modelId: this.initialModelId } : {}),
496
+ };
497
+
470
498
  if (this.initialModeId) {
471
- try {
472
- await this.setMode(this.initialModeId);
473
- console.log(`[ACP bridge] session ${this.sessionId}: applied initial mode=${this.initialModeId}`);
474
- } catch (err) {
475
- // 应用初始 mode 失败不阻断会话:回退 harness 默认,仅记录日志
476
- console.warn(`[ACP bridge] session ${this.sessionId}: failed to apply initial mode: ${(err as Error).message}`);
477
- }
499
+ const error = await this.confirmInitialConfig('mode', this.initialModeId);
500
+ this.recordInitialConfigStatus('mode', error ? 'failed' : 'applied', error);
478
501
  }
479
502
  if (this.initialModelId) {
503
+ if (findConfigByCategory(this.configOptions, 'model')) {
504
+ const error = await this.confirmInitialConfig('model', this.initialModelId);
505
+ this.recordInitialConfigStatus('model', error ? 'failed' : 'applied', error);
506
+ } else {
507
+ // model 无旧通道可走:不判失败,挂起等待 config_option_update 补应用
508
+ this.pendingInitialConfigKinds.push('model');
509
+ }
510
+ }
511
+
512
+ if (this.pendingInitialConfigKinds.length > 0) {
513
+ // 挂起不阻塞会话:initialized 照常发出,结果事件在补确认/超时收敛后补发
514
+ this.armInitialConfigPendingTimeout();
515
+ return;
516
+ }
517
+ this.emitInitialConfigResult();
518
+ }
519
+
520
+ /**
521
+ * 应用并回读确认单个初始配置项,失败重试一次;返回 null 表示 confirmed,否则为失败原因。
522
+ * config-option 通道以 set_config_option 响应快照回读(currentValue === 请求值);
523
+ * 旧 session/setMode 通道(无 config-option)无协议级回读,不抛错即视为 applied。
524
+ */
525
+ private async confirmInitialConfig(kind: 'mode' | 'model', requested: string): Promise<string | null> {
526
+ let lastError = '';
527
+ for (let attempt = 0; attempt < 2; attempt++) {
528
+ if (attempt > 0) {
529
+ await new Promise((resolve) => setTimeout(resolve, INITIAL_CONFIG_RETRY_DELAY_MS));
530
+ }
480
531
  try {
481
- await this.setModel(this.initialModelId);
482
- console.log(`[ACP bridge] session ${this.sessionId}: applied initial model=${this.initialModelId}`);
532
+ if (kind === 'mode') await this.setMode(requested);
533
+ else await this.setModel(requested);
534
+ const config = findConfigByCategory(this.configOptions, kind);
535
+ if (!config || config.currentValue === requested) {
536
+ console.log(`[ACP bridge] session ${this.sessionId}: applied initial ${kind}=${requested}`);
537
+ return null;
538
+ }
539
+ lastError = `agent confirmed "${config.currentValue ?? 'null'}" instead of "${requested}"`;
483
540
  } catch (err) {
484
- console.warn(`[ACP bridge] session ${this.sessionId}: failed to apply initial model: ${(err as Error).message}`);
541
+ lastError = (err as Error).message;
485
542
  }
486
543
  }
544
+ console.warn(
545
+ `[ACP bridge] session ${this.sessionId}: failed to apply initial ${kind}: ` +
546
+ `requested=${requested}, ${lastError}`,
547
+ );
548
+ return `requested "${requested}": ${lastError}`;
549
+ }
550
+
551
+ private recordInitialConfigStatus(
552
+ kind: 'mode' | 'model',
553
+ status: 'applied' | 'failed',
554
+ error?: string | null,
555
+ ): void {
556
+ if (!this.initialConfigResult) return;
557
+ if (kind === 'mode') this.initialConfigResult.modeStatus = status;
558
+ else this.initialConfigResult.modelStatus = status;
559
+ if (status === 'failed' && error) {
560
+ this.initialConfigResult.error = this.initialConfigResult.error
561
+ ? `${this.initialConfigResult.error}; ${kind}: ${error}`
562
+ : `${kind}: ${error}`;
563
+ }
564
+ }
565
+
566
+ /** 挂起等待上限:超时后未确认的类目按 failed 收敛(契约 §2.4) */
567
+ private armInitialConfigPendingTimeout(): void {
568
+ if (this.initialConfigPendingTimer) return;
569
+ const timeoutMs = initialConfigPendingTimeoutMs();
570
+ this.initialConfigPendingTimer = setTimeout(() => {
571
+ this.initialConfigPendingTimer = null;
572
+ for (const kind of this.pendingInitialConfigKinds.splice(0)) {
573
+ const requested = kind === 'mode' ? this.initialModeId : this.initialModelId;
574
+ const error = `agent did not expose a ${kind} config option within ${timeoutMs}ms`;
575
+ console.warn(
576
+ `[ACP bridge] session ${this.sessionId}: failed to apply initial ${kind}: ` +
577
+ `requested=${requested}, ${error}`,
578
+ );
579
+ this.recordInitialConfigStatus(kind, 'failed', `requested "${requested}": ${error}`);
580
+ }
581
+ this.emitInitialConfigResult();
582
+ }, timeoutMs);
583
+ }
584
+
585
+ /** config_option_update 到达后对挂起的类目补应用 + 回读确认;全部收敛时上报结果 */
586
+ private async retryPendingInitialConfig(): Promise<void> {
587
+ if (
588
+ this.initialConfigEmitted ||
589
+ this.initialConfigRetrying ||
590
+ this.pendingInitialConfigKinds.length === 0
591
+ ) return;
592
+ this.initialConfigRetrying = true;
593
+ try {
594
+ for (const kind of this.pendingInitialConfigKinds.splice(0)) {
595
+ const requested = kind === 'mode' ? this.initialModeId : this.initialModelId;
596
+ if (!requested) continue;
597
+ if (!findConfigByCategory(this.configOptions, kind)) {
598
+ // 本次通知仍未暴露对应 category:继续挂起,等待后续通知或超时收敛
599
+ this.pendingInitialConfigKinds.push(kind);
600
+ continue;
601
+ }
602
+ const error = await this.confirmInitialConfig(kind, requested);
603
+ this.recordInitialConfigStatus(kind, error ? 'failed' : 'applied', error);
604
+ }
605
+ if (this.pendingInitialConfigKinds.length === 0) {
606
+ this.emitInitialConfigResult();
607
+ }
608
+ } finally {
609
+ this.initialConfigRetrying = false;
610
+ }
611
+ }
612
+
613
+ /** 确认收敛时恰好发送一次 acp:initial-config:result(契约 §2.39) */
614
+ private emitInitialConfigResult(): void {
615
+ if (this.initialConfigEmitted || !this.initialConfigResult) return;
616
+ this.initialConfigEmitted = true;
617
+ if (this.initialConfigPendingTimer) {
618
+ clearTimeout(this.initialConfigPendingTimer);
619
+ this.initialConfigPendingTimer = null;
620
+ }
621
+ const result = this.initialConfigResult;
622
+ this.socket.emit('acp:initial-config:result', {
623
+ sessionId: this.sessionId,
624
+ ...(result.modeId ? { modeId: result.modeId, modeStatus: result.modeStatus } : {}),
625
+ ...(result.modelId ? { modelId: result.modelId, modelStatus: result.modelStatus } : {}),
626
+ ...(result.error ? { error: result.error.slice(0, 200) } : {}),
627
+ });
628
+ }
629
+
630
+ /** 会话关闭/初始化失败后不再补发确认结果(语义同 settlePendingRequests) */
631
+ private clearPendingInitialConfig(): void {
632
+ if (this.initialConfigPendingTimer) {
633
+ clearTimeout(this.initialConfigPendingTimer);
634
+ this.initialConfigPendingTimer = null;
635
+ }
636
+ this.pendingInitialConfigKinds = [];
487
637
  }
488
638
 
489
639
  async setConfigOption(configId: string, value: string | boolean): Promise<acp.SetSessionConfigOptionResponse> {
@@ -636,11 +786,19 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
636
786
  }
637
787
  }
638
788
 
789
+ /** session/new 与 session/resume 响应携带的 configOptions 是全量快照:非空时以其刷新本地状态 */
790
+ private absorbSessionConfigOptions(
791
+ result: acp.NewSessionResponse | acp.ResumeSessionResponse,
792
+ ): void {
793
+ const configOptions = extractConfigOptions(result.configOptions);
794
+ if (configOptions.length > 0) this.configOptions = configOptions;
795
+ }
796
+
639
797
  private buildInitializedPayload(
640
798
  result: acp.NewSessionResponse | acp.ResumeSessionResponse,
641
799
  ): AcpInitializedPayload {
642
- const configOptions = extractConfigOptions(result.configOptions);
643
- this.configOptions = configOptions.length > 0 ? configOptions : this.configOptions;
800
+ // this.configOptions 已由 absorbSessionConfigOptions(start/resume 在 apply 前)装载,
801
+ // apply 阶段的 set_config_option 响应快照也已刷新,此处不得再用 session/new 旧快照覆盖
644
802
 
645
803
  // 协议要求:响应含 configOptions 时以其为准(忽略 modes)
646
804
  const configModes = extractConfigModes(this.configOptions);
@@ -742,6 +900,8 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
742
900
  sessionId: this.sessionId,
743
901
  configOptions: this.configOptions,
744
902
  });
903
+ // session/new 未携带 configOptions 时挂起的初始 mode/model 在此补应用(契约 §2.4)
904
+ await this.retryPendingInitialConfig();
745
905
  break;
746
906
  case 'user_message_chunk':
747
907
  break;
@@ -967,6 +1127,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
967
1127
  this.stopped = true;
968
1128
  // 进程崩溃同样必须收敛 pending:否则 65s timer 泄漏且迟发 timeout 事件
969
1129
  this.settlePendingRequests('session failed');
1130
+ this.clearPendingInitialConfig();
970
1131
  // 已停止(含 silent 替换/对账)后迟到的初始化失败:不得再发 stopped,
971
1132
  // 否则内联监听器/服务端会按 sessionId 删除新会话的注册与映射。
972
1133
  if (wasStopped) return;
@@ -0,0 +1,64 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ const childProcess = vi.hoisted(() => ({ exec: vi.fn() }));
4
+
5
+ vi.mock('child_process', () => childProcess);
6
+
7
+ import { AcpDetector } from './detector.js';
8
+
9
+ type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void;
10
+
11
+ function mockExec(handler: (command: string, callback: ExecCallback) => void): void {
12
+ childProcess.exec.mockImplementation(handler);
13
+ }
14
+
15
+ function mockOnlyDsh(stdout: string): void {
16
+ mockExec((command: string, callback: ExecCallback) => {
17
+ if (command === 'dsh --version') {
18
+ callback(null, { stdout, stderr: '' });
19
+ return;
20
+ }
21
+ callback(new Error('not available'));
22
+ });
23
+ }
24
+
25
+ describe('AcpDetector deepseek_harness (T-DET*)', () => {
26
+ beforeEach(() => {
27
+ vi.clearAllMocks();
28
+ });
29
+
30
+ it('T-DET1: dsh --version 成功时 deepseek_harness 可用', async () => {
31
+ mockOnlyDsh('0.1.2-alpha.2\n');
32
+
33
+ const result = await new AcpDetector().detect();
34
+ expect(result.find((item) => item.type === 'deepseek_harness')).toEqual({
35
+ type: 'deepseek_harness',
36
+ available: true,
37
+ version: '0.1.2-alpha.2',
38
+ });
39
+ });
40
+
41
+ it('T-DET1b: 缺命令时 deepseek_harness 不可用(不抛错)', async () => {
42
+ mockExec((_command: string, callback: ExecCallback) => callback(new Error('spawn dsh ENOENT')));
43
+
44
+ const result = await new AcpDetector().detect();
45
+ expect(result.find((item) => item.type === 'deepseek_harness')).toEqual({
46
+ type: 'deepseek_harness',
47
+ available: false,
48
+ });
49
+ });
50
+
51
+ it('T-DET2: 预发布段保留', async () => {
52
+ mockOnlyDsh('0.1.2-alpha.2\n');
53
+
54
+ const result = await new AcpDetector().detect();
55
+ expect(result.find((item) => item.type === 'deepseek_harness')?.version).toBe('0.1.2-alpha.2');
56
+ });
57
+
58
+ it('T-DET3: spawner 为 dsh --profile acp', () => {
59
+ expect(new AcpDetector().getSpawnerConfig('deepseek_harness')).toEqual({
60
+ command: 'dsh',
61
+ args: ['--profile', 'acp'],
62
+ });
63
+ });
64
+ });
@@ -11,7 +11,7 @@ interface AcpServerInfo {
11
11
 
12
12
  export class AcpDetector {
13
13
  async detect(): Promise<AcpServerInfo[]> {
14
- const [opencode, copilot, claudeCode, geminiCli, codex, mimoCode, kimiCode] = await Promise.all([
14
+ const [opencode, copilot, claudeCode, geminiCli, codex, mimoCode, kimiCode, deepseekHarness] = await Promise.all([
15
15
  this.detectOpenCode(),
16
16
  this.detectGitHubCopilot(),
17
17
  this.detectClaudeCode(),
@@ -19,8 +19,9 @@ export class AcpDetector {
19
19
  this.detectCodex(),
20
20
  this.detectMiMoCode(),
21
21
  this.detectKimiCode(),
22
+ this.detectDeepseekHarness(),
22
23
  ]);
23
- return [opencode, copilot, claudeCode, geminiCli, codex, mimoCode, kimiCode];
24
+ return [opencode, copilot, claudeCode, geminiCli, codex, mimoCode, kimiCode, deepseekHarness];
24
25
  }
25
26
 
26
27
  private async detectOpenCode(): Promise<AcpServerInfo> {
@@ -93,6 +94,17 @@ export class AcpDetector {
93
94
  }
94
95
  }
95
96
 
97
+ /** DeepSeek Harness:`dsh --version` 输出纯版本号(预发布段如 `0.1.2-alpha.2` 保留)。 */
98
+ private async detectDeepseekHarness(): Promise<AcpServerInfo> {
99
+ try {
100
+ const { stdout } = await execAsync('dsh --version');
101
+ const version = this.parseVersion(stdout);
102
+ return { type: 'deepseek_harness', available: true, version };
103
+ } catch {
104
+ return { type: 'deepseek_harness', available: false };
105
+ }
106
+ }
107
+
96
108
  getSpawnerConfig(serverType: string): { command: string; args: string[] } {
97
109
  switch (serverType) {
98
110
  case 'github_copilot':
@@ -107,6 +119,8 @@ export class AcpDetector {
107
119
  return { command: 'mimo', args: ['acp'] };
108
120
  case 'kimi_code':
109
121
  return { command: 'kimi', args: ['acp'] };
122
+ case 'deepseek_harness':
123
+ return { command: 'dsh', args: ['--profile', 'acp'] };
110
124
  case 'opencode':
111
125
  default:
112
126
  return { command: 'opencode', args: ['acp'] };
@@ -114,7 +128,8 @@ export class AcpDetector {
114
128
  }
115
129
 
116
130
  private parseVersion(output: string): string {
117
- const match = output.match(/(\d+\.\d+\.\d+)/);
131
+ // 预发布段保留(如 dsh 的 `0.1.2-alpha.2`)。
132
+ const match = output.match(/(\d+\.\d+\.\d+(?:-[\w.]+)?)/);
118
133
  return match ? match[1] : 'unknown';
119
134
  }
120
135
  }
@@ -0,0 +1,120 @@
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-initial-config-agent.mjs');
11
+ const SESSION_ID = 'it-initial-config';
12
+
13
+ interface EmittedEvent {
14
+ event: string;
15
+ payload: Record<string, unknown>;
16
+ }
17
+
18
+ function createRecordingSocket() {
19
+ const emitted: EmittedEvent[] = [];
20
+ const socket = {
21
+ emit: (event: string, payload: Record<string, unknown>) => {
22
+ emitted.push({ event, payload });
23
+ return true;
24
+ },
25
+ on: () => socket,
26
+ off: () => socket,
27
+ };
28
+ return { socket, emitted };
29
+ }
30
+
31
+ async function waitFor<T>(
32
+ fn: () => T | undefined,
33
+ timeoutMs = 6000,
34
+ intervalMs = 20,
35
+ ): Promise<T> {
36
+ const deadline = Date.now() + timeoutMs;
37
+ while (Date.now() < deadline) {
38
+ const value = fn();
39
+ if (value !== undefined) return value;
40
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
41
+ }
42
+ throw new Error(`waitFor timed out after ${timeoutMs}ms`);
43
+ }
44
+
45
+ const cleanupFns: Array<() => Promise<void> | void> = [];
46
+
47
+ afterEach(async () => {
48
+ while (cleanupFns.length > 0) {
49
+ await cleanupFns.pop()?.();
50
+ }
51
+ });
52
+
53
+ function readRecords(resultFile: string): Array<Record<string, unknown>> {
54
+ if (!existsSync(resultFile)) return [];
55
+ return readFileSync(resultFile, 'utf8')
56
+ .split('\n')
57
+ .filter(Boolean)
58
+ .map((line) => JSON.parse(line) as Record<string, unknown>);
59
+ }
60
+
61
+ describe('初始 mode/model 应用确认:真实 SDK + 假 Agent 进程', () => {
62
+ it('T-IC1: session/new 无 configOptions → 异步 config_option_update → 补应用生效 → 结果事件 applied', async () => {
63
+ const dir = mkdtempSync(join(tmpdir(), 'acp-initial-config-'));
64
+ const resultFile = join(dir, 'result.jsonl');
65
+ const spawner = new AcpSpawner({
66
+ sessionId: SESSION_ID,
67
+ cwd: dir,
68
+ command: process.execPath,
69
+ args: [FAKE_AGENT, resultFile],
70
+ });
71
+ const { socket, emitted } = createRecordingSocket();
72
+ const bridge = new AcpSessionBridge(
73
+ socket as never,
74
+ { sessionId: SESSION_ID, cwd: dir, initialModelId: 'requested-model' },
75
+ spawner,
76
+ );
77
+ cleanupFns.push(async () => {
78
+ await bridge.stop().catch(() => {});
79
+ spawner.stop();
80
+ });
81
+ const initialized: unknown[] = [];
82
+ bridge.on('acp:initialized', (payload) => initialized.push(payload));
83
+
84
+ await bridge.start();
85
+
86
+ // 挂起阶段不阻断会话:initialized 照常发出,结果事件尚未收敛
87
+ expect(initialized).toHaveLength(1);
88
+ expect(emitted.some((e) => e.event === 'acp:initial-config:result')).toBe(false);
89
+
90
+ const result = await waitFor(() =>
91
+ emitted.find((e) => e.event === 'acp:initial-config:result'),
92
+ );
93
+ expect(result.payload).toEqual({
94
+ sessionId: SESSION_ID,
95
+ modelId: 'requested-model',
96
+ modelStatus: 'applied',
97
+ });
98
+
99
+ // Agent 侧确实收到了补应用的 set_config_option(请求值经真实协议到达对端)
100
+ const records = await waitFor(() => {
101
+ const current = readRecords(resultFile);
102
+ return current.length > 0 ? current : undefined;
103
+ });
104
+ expect(records[0].setConfigOption).toMatchObject({
105
+ sessionId: 'fake-session-1',
106
+ configId: 'model',
107
+ value: 'requested-model',
108
+ });
109
+
110
+ // 响应快照刷新后回发 acp:config-options,末次快照 currentValue 为生效值
111
+ const configOptionsEvents = emitted.filter((e) => e.event === 'acp:config-options');
112
+ const last = configOptionsEvents[configOptionsEvents.length - 1];
113
+ expect(last).toBeDefined();
114
+ const options = last.payload.configOptions as Array<{ category: string; currentValue: string }>;
115
+ expect(options.find((o) => o.category === 'model')?.currentValue).toBe('requested-model');
116
+
117
+ // 收敛恰好一次
118
+ expect(emitted.filter((e) => e.event === 'acp:initial-config:result')).toHaveLength(1);
119
+ }, 15000);
120
+ });
@@ -25,7 +25,7 @@ const BASE_ENV: NodeJS.ProcessEnv = {
25
25
  ZAG_CONTROLLER_KEY: 'controller-token-secret',
26
26
  ZAG_SERVER_ENDPOINT: 'wss://cloud-controller.example.com/worker',
27
27
  ZAG_HOST_NAME: 'my-cloud-host',
28
- ZAG_DEFAULT_WORKSPACE: '/root/workspace',
28
+ ZAG_DEFAULT_WORKSPACE: '/home/worker/workspace',
29
29
  };
30
30
 
31
31
  interface FakeSocket {
@@ -298,7 +298,7 @@ describe('startCloudHostSupervisor', () => {
298
298
  expect(context.connect).toHaveBeenCalledTimes(2);
299
299
  });
300
300
 
301
- it('T-AG17: shutdown from either side closes both sockets and exits 0 without unregister', async () => {
301
+ it('T-AG17: server shutdown from either side closes both sockets and exits 42 without unregister', async () => {
302
302
  const context = setup();
303
303
  const handle = await startCloudHostSupervisor(context.deps);
304
304
  const workerOptions = context.connect.mock.calls[0][2] as ConnectToServerOptions;
@@ -309,7 +309,7 @@ describe('startCloudHostSupervisor', () => {
309
309
 
310
310
  expect(context.worker.disconnect).toHaveBeenCalled();
311
311
  expect(context.controller.disconnect).toHaveBeenCalled();
312
- expect(context.exit).toHaveBeenCalledWith(0);
312
+ expect(context.exit).toHaveBeenCalledWith(42);
313
313
  expect(context.worker.emit).not.toHaveBeenCalledWith('unregister', expect.anything());
314
314
  expect(context.controller.emit).not.toHaveBeenCalledWith('unregister', expect.anything());
315
315
 
@@ -328,6 +328,15 @@ describe('startCloudHostSupervisor', () => {
328
328
 
329
329
  expect(context.worker.disconnect).toHaveBeenCalled();
330
330
  expect(context.controller.disconnect).not.toHaveBeenCalled();
331
+ expect(context.exit).toHaveBeenCalledWith(42);
332
+ });
333
+
334
+ it('C-2: signal shutdown exits 0 (keepalive restarts after accidental kill)', async () => {
335
+ const context = setup();
336
+ const handle = await startCloudHostSupervisor(context.deps);
337
+
338
+ handle.shutdown('SIGTERM');
339
+
331
340
  expect(context.exit).toHaveBeenCalledWith(0);
332
341
  });
333
342
 
@@ -339,9 +348,9 @@ describe('startCloudHostSupervisor', () => {
339
348
  expect(resolveShutdownExitCode('worker shutdown: 必须工作负载「OpenCode(Harness)」初始化失败')).toBe(1);
340
349
  expect(resolveShutdownExitCode('required init failed')).toBe(1);
341
350
  // 正常路径
342
- expect(resolveShutdownExitCode('controller-api shutdown: server requested')).toBe(0);
351
+ expect(resolveShutdownExitCode('controller-api shutdown: server requested')).toBe(42);
343
352
  expect(resolveShutdownExitCode('SIGINT')).toBe(0);
344
- expect(resolveShutdownExitCode('unregistered')).toBe(0);
353
+ expect(resolveShutdownExitCode('unregistered')).toBe(42);
345
354
  });
346
355
 
347
356
  it('C-2: required init failure closes both sockets and exits 1', async () => {
@@ -442,7 +451,7 @@ describe('cloud host github credential manager (T-SUP-G)', () => {
442
451
  handle.shutdown('again');
443
452
 
444
453
  expect(credentials.stop).toHaveBeenCalledTimes(1);
445
- expect(context.exit).toHaveBeenCalledWith(0);
454
+ expect(context.exit).toHaveBeenCalledWith(42);
446
455
  });
447
456
 
448
457
  it('T-SUP-G3: missing credential env does not block the supervisor, only warns', async () => {