agent-gear 2.9.0 → 2.10.1
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 +25 -5
- package/dist/acp/bridge.d.ts +29 -1
- package/dist/acp/bridge.d.ts.map +1 -1
- package/dist/acp/bridge.js +171 -27
- package/dist/acp/bridge.js.map +1 -1
- package/dist/acp/bridge.test.js +198 -15
- package/dist/acp/bridge.test.js.map +1 -1
- package/dist/acp/initial-config.integration.test.d.ts +2 -0
- package/dist/acp/initial-config.integration.test.d.ts.map +1 -0
- package/dist/acp/initial-config.integration.test.js +95 -0
- package/dist/acp/initial-config.integration.test.js.map +1 -0
- package/dist/cloud-host/supervisor.d.ts +8 -19
- package/dist/cloud-host/supervisor.d.ts.map +1 -1
- package/dist/cloud-host/supervisor.js +7 -27
- package/dist/cloud-host/supervisor.js.map +1 -1
- package/dist/cloud-host/supervisor.test.js +12 -6
- package/dist/cloud-host/supervisor.test.js.map +1 -1
- package/dist/exit-codes.d.ts +30 -0
- package/dist/exit-codes.d.ts.map +1 -0
- package/dist/exit-codes.js +52 -0
- package/dist/exit-codes.js.map +1 -0
- package/dist/exit-codes.test.d.ts +2 -0
- package/dist/exit-codes.test.d.ts.map +1 -0
- package/dist/exit-codes.test.js +61 -0
- package/dist/exit-codes.test.js.map +1 -0
- package/dist/harness/env.test.js +2 -2
- package/dist/harness/env.test.js.map +1 -1
- package/dist/harness/prepare.test.js +2 -2
- package/dist/harness/prepare.test.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/socketio-client.auth-gate.test.js +3 -3
- package/dist/socketio-client.auth-gate.test.js.map +1 -1
- package/dist/socketio-client.d.ts.map +1 -1
- package/dist/socketio-client.js +27 -3
- package/dist/socketio-client.js.map +1 -1
- package/dist/socketio-client.test.js +37 -0
- package/dist/socketio-client.test.js.map +1 -1
- package/dist/workload-executor.test.js +2 -2
- package/dist/workload-executor.test.js.map +1 -1
- package/package.json +1 -1
- package/src/acp/__fixtures__/fake-initial-config-agent.mjs +113 -0
- package/src/acp/bridge.test.ts +223 -15
- package/src/acp/bridge.ts +188 -27
- package/src/acp/initial-config.integration.test.ts +120 -0
- package/src/cloud-host/supervisor.test.ts +15 -6
- package/src/cloud-host/supervisor.ts +22 -35
- package/src/exit-codes.test.ts +73 -0
- package/src/exit-codes.ts +59 -0
- package/src/harness/env.test.ts +2 -2
- package/src/harness/prepare.test.ts +2 -2
- package/src/index.ts +7 -0
- package/src/socketio-client.auth-gate.test.ts +3 -3
- package/src/socketio-client.test.ts +44 -0
- package/src/socketio-client.ts +27 -3
- package/src/workload-executor.test.ts +2 -2
- package/tests/commands/harness.test.ts +1 -1
- package/tests/socketio-client.test.ts +5 -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
|
-
|
|
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',
|
|
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
|
-
|
|
440
|
-
|
|
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.
|
|
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
|
-
/**
|
|
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
|
-
|
|
472
|
-
|
|
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.
|
|
482
|
-
|
|
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
|
-
|
|
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
|
-
|
|
643
|
-
|
|
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,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: '/
|
|
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
|
|
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(
|
|
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(
|
|
351
|
+
expect(resolveShutdownExitCode('controller-api shutdown: server requested')).toBe(42);
|
|
343
352
|
expect(resolveShutdownExitCode('SIGINT')).toBe(0);
|
|
344
|
-
expect(resolveShutdownExitCode('unregistered')).toBe(
|
|
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(
|
|
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 () => {
|
|
@@ -11,12 +11,26 @@ import {
|
|
|
11
11
|
type GithubCredentialRefreshResult,
|
|
12
12
|
} from '../github/credential-manager.js';
|
|
13
13
|
import type { WorkloadRunPayload } from '../workload-executor.js';
|
|
14
|
+
import {
|
|
15
|
+
EXIT_SERVER_SHUTDOWN,
|
|
16
|
+
isFailureShutdownReason,
|
|
17
|
+
isServerTerminationReason,
|
|
18
|
+
resolveShutdownExitCode,
|
|
19
|
+
} from '../exit-codes.js';
|
|
20
|
+
|
|
21
|
+
// 既有导入路径(`cloud-host/supervisor.js`)继续可用;实现统一在 `exit-codes.ts`。
|
|
22
|
+
export {
|
|
23
|
+
EXIT_SERVER_SHUTDOWN,
|
|
24
|
+
isFailureShutdownReason,
|
|
25
|
+
isServerTerminationReason,
|
|
26
|
+
resolveShutdownExitCode,
|
|
27
|
+
} from '../exit-codes.js';
|
|
14
28
|
|
|
15
29
|
/** 未设置 `HARNESS_INIT_WAIT_MS` 时的初始化等待上限(10 分钟)。 */
|
|
16
30
|
export const DEFAULT_HARNESS_INIT_WAIT_MS = 600_000;
|
|
17
31
|
|
|
18
|
-
/** 未设置 `ZAG_DEFAULT_WORKSPACE`
|
|
19
|
-
export const DEFAULT_WORKSPACE = '/
|
|
32
|
+
/** 未设置 `ZAG_DEFAULT_WORKSPACE` 时的默认工作区(容器以 worker 用户运行)。 */
|
|
33
|
+
export const DEFAULT_WORKSPACE = '/home/worker/workspace';
|
|
20
34
|
|
|
21
35
|
/** 云电脑模式必需的环境变量(三者同时非空才进入 supervisor)。 */
|
|
22
36
|
export const CLOUD_HOST_MODE_KEYS = ['ZAG_HOST_ENDPOINT', 'ZAG_HOST_KEY', 'ZAG_CONTROLLER_KEY'] as const;
|
|
@@ -33,7 +47,7 @@ export interface CloudHostEnv {
|
|
|
33
47
|
serverEndpoint: string;
|
|
34
48
|
/** 注册上报的主机名(env `ZAG_HOST_NAME`,缺省 `os.hostname()`)。 */
|
|
35
49
|
hostName: string;
|
|
36
|
-
/** 默认工作区(env `ZAG_DEFAULT_WORKSPACE`,缺省 `/
|
|
50
|
+
/** 默认工作区(env `ZAG_DEFAULT_WORKSPACE`,缺省 `/home/worker/workspace`)。 */
|
|
37
51
|
workspace: string;
|
|
38
52
|
/** 初始化等待超时(env `HARNESS_INIT_WAIT_MS`,缺省 10 分钟)。 */
|
|
39
53
|
initWaitMs: number;
|
|
@@ -131,40 +145,13 @@ export interface CloudHostSupervisorHandle {
|
|
|
131
145
|
/**
|
|
132
146
|
* 关闭两端并退出(不发送 `unregister`)。
|
|
133
147
|
*
|
|
134
|
-
* `code` 缺省按 `reason`
|
|
135
|
-
*
|
|
136
|
-
*
|
|
148
|
+
* `code` 缺省按 `reason` 分类(见 `exit-codes.ts`):信号退出 → 0(入口保活重启);
|
|
149
|
+
* 服务端终止(非失败类 shutdown / `unregistered` / `INVALID_TOKEN`)→ 42(入口不重启);
|
|
150
|
+
* `version_mismatch:*` / 其它 `error:*` / 初始化失败类 → 1(入口退避自更新后重启,C-2)。
|
|
137
151
|
*/
|
|
138
152
|
shutdown: (reason: string, code?: number) => void;
|
|
139
153
|
}
|
|
140
154
|
|
|
141
|
-
/**
|
|
142
|
-
* 错误/失败类 shutdown reason 判定(C-2):
|
|
143
|
-
*
|
|
144
|
-
* - `socketio-client` 把 `VERSION_MISMATCH` / 其它 `error` 事件转成
|
|
145
|
-
* `version_mismatch:*` / `error:<code>` 前缀;
|
|
146
|
-
* - cloud-controller 的必须工作负载失败 reason 形如「必须工作负载「x」初始化失败」
|
|
147
|
-
* (经 `worker shutdown: ...` 包装后仍需识别);
|
|
148
|
-
* - 其余(服务端主动 shutdown、`unregistered`、SIGINT/SIGTERM)视为正常退出。
|
|
149
|
-
*/
|
|
150
|
-
export function isFailureShutdownReason(reason: string): boolean {
|
|
151
|
-
const normalized = reason.trim().toLowerCase();
|
|
152
|
-
// reason 可能被 `worker shutdown:` / `controller-api shutdown:` 包装,用 includes 判定前缀。
|
|
153
|
-
if (normalized.includes('version_mismatch:') || /(^|[\s:])error:/.test(normalized)) {
|
|
154
|
-
return true;
|
|
155
|
-
}
|
|
156
|
-
return (
|
|
157
|
-
reason.includes('初始化失败') ||
|
|
158
|
-
normalized.includes('init failed') ||
|
|
159
|
-
normalized.includes('initialization failed')
|
|
160
|
-
);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/** 由 shutdown reason 推导退出码:失败路径 1、正常退出 0。 */
|
|
164
|
-
export function resolveShutdownExitCode(reason: string): number {
|
|
165
|
-
return isFailureShutdownReason(reason) ? 1 : 0;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
155
|
/** 日志中的连接目标:仅 origin + namespace,绝不包含 query/token。 */
|
|
169
156
|
function describeEndpoint(endpoint: string): string {
|
|
170
157
|
const { origin, namespace } = parseEndpoint(endpoint);
|
|
@@ -178,7 +165,7 @@ function describeEndpoint(endpoint: string): string {
|
|
|
178
165
|
* 2. 先连 cloud-controller `/worker`(`ZAG_SERVER_ENDPOINT` + `ZAG_CONTROLLER_KEY`);
|
|
179
166
|
* 3. `registered.initializing=true` → 等待首个 `workload:run` 批次结束(成功/失败/超时)后
|
|
180
167
|
* 再连 controller-api(`ZAG_HOST_ENDPOINT` + `ZAG_HOST_KEY`);`false`/缺省立即连接;
|
|
181
|
-
* 4. 任一端 `shutdown` →
|
|
168
|
+
* 4. 任一端 `shutdown` → 关闭两端并退出(服务端终止 42 / 信号 0 / 失败 1);**始终不发送 `unregister`**;
|
|
182
169
|
* 5. 仅 controller-api 标准连接启动本地 MCP 回环服务(worker 连接跳过,避免端口冲突)。
|
|
183
170
|
*/
|
|
184
171
|
export async function startCloudHostSupervisor(
|
|
@@ -240,7 +227,7 @@ export async function startCloudHostSupervisor(
|
|
|
240
227
|
/* socket may already be closed */
|
|
241
228
|
}
|
|
242
229
|
// 不发送 unregister:容器销毁由 agent-api 编排(stopCloudHost / TTL / 失败回调)。
|
|
243
|
-
//
|
|
230
|
+
// 退出码三分见 exit-codes.ts:42 服务端终止 / 0 信号 / 1 失败(入口据此保活或收敛)。
|
|
244
231
|
exit(exitCode);
|
|
245
232
|
};
|
|
246
233
|
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
EXIT_SERVER_SHUTDOWN,
|
|
4
|
+
isFailureShutdownReason,
|
|
5
|
+
isServerTerminationReason,
|
|
6
|
+
isSignalShutdownReason,
|
|
7
|
+
resolveShutdownExitCode,
|
|
8
|
+
} from './exit-codes.js';
|
|
9
|
+
|
|
10
|
+
describe('exit codes (contract §3.7)', () => {
|
|
11
|
+
it('T-EC1: EXIT_SERVER_SHUTDOWN is 42', () => {
|
|
12
|
+
expect(EXIT_SERVER_SHUTDOWN).toBe(42);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('T-EC2: signals exit 0 (keepalive restarts after accidental kill)', () => {
|
|
16
|
+
for (const reason of ['SIGINT', 'SIGTERM', 'signal: SIGTERM', ' worker shutdown: sigterm ']) {
|
|
17
|
+
expect(isSignalShutdownReason(reason)).toBe(true);
|
|
18
|
+
expect(resolveShutdownExitCode(reason)).toBe(0);
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('T-EC3: server termination reasons exit 42', () => {
|
|
23
|
+
const reasons = [
|
|
24
|
+
'unregistered',
|
|
25
|
+
'worker shutdown: unregistered',
|
|
26
|
+
'controller-api shutdown: unregistered',
|
|
27
|
+
'error: INVALID_TOKEN',
|
|
28
|
+
'worker shutdown: error: INVALID_TOKEN',
|
|
29
|
+
'worker shutdown: error:invalid_token',
|
|
30
|
+
];
|
|
31
|
+
for (const reason of reasons) {
|
|
32
|
+
expect(isServerTerminationReason(reason)).toBe(true);
|
|
33
|
+
expect(resolveShutdownExitCode(reason)).toBe(42);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('T-EC4: failure reasons exit 1', () => {
|
|
38
|
+
const reasons = [
|
|
39
|
+
'version_mismatch: agent-gear 版本不兼容',
|
|
40
|
+
'worker shutdown: version_mismatch: too old',
|
|
41
|
+
'error: REGISTER_FAILED',
|
|
42
|
+
'controller-api shutdown: error: UNKNOWN',
|
|
43
|
+
'必须工作负载「OpenCode(Harness)」初始化失败',
|
|
44
|
+
'worker shutdown: 必须工作负载「x」初始化失败',
|
|
45
|
+
'required init failed',
|
|
46
|
+
'required initialization failed',
|
|
47
|
+
];
|
|
48
|
+
for (const reason of reasons) {
|
|
49
|
+
expect(isFailureShutdownReason(reason)).toBe(true);
|
|
50
|
+
expect(resolveShutdownExitCode(reason)).toBe(1);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('T-EC5: plain server shutdown falls through to 42', () => {
|
|
55
|
+
expect(resolveShutdownExitCode('server requested shutdown')).toBe(42);
|
|
56
|
+
expect(resolveShutdownExitCode('worker shutdown: 强制销毁')).toBe(42);
|
|
57
|
+
expect(resolveShutdownExitCode('controller-api shutdown: key_revoked')).toBe(42);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('T-EC6: INVALID_TOKEN overrides the generic error: failure prefix', () => {
|
|
61
|
+
expect(isFailureShutdownReason('error: INVALID_TOKEN')).toBe(true);
|
|
62
|
+
expect(resolveShutdownExitCode('error: INVALID_TOKEN')).toBe(42);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
describe('contract anchor', () => {
|
|
67
|
+
it('T-EC7: contract documents exit code 42', async () => {
|
|
68
|
+
const { readFileSync } = await import('node:fs');
|
|
69
|
+
const contract = readFileSync(new URL('../../../contracts/agent-controller-websocket.md', import.meta.url), 'utf8');
|
|
70
|
+
expect(contract).toContain('`42`');
|
|
71
|
+
expect(contract).toContain('EXIT_SERVER_SHUTDOWN');
|
|
72
|
+
});
|
|
73
|
+
});
|