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
@@ -4,6 +4,7 @@ import { join } from 'node:path';
4
4
  import { parse } from 'jsonc-parser';
5
5
  import { formatPrepareSummary, prepareHarness } from './prepare.js';
6
6
  import { HarnessEnvError } from './env.js';
7
+ import { DshCliError } from './dsh-cli.js';
7
8
  import { OpencodeCliError } from './opencode-cli.js';
8
9
  import type { CommandRunner } from './opencode-cli.js';
9
10
 
@@ -13,7 +14,7 @@ const VALID_ENV: NodeJS.ProcessEnv = {
13
14
  ZAG_MODEL_BASE_URL: 'http://admin-api:8002/v1',
14
15
  ZAG_MODEL_API_KEY: 'zag_sk_super_secret',
15
16
  ZAG_MODEL_IDS: '["model-a","model-a"," model-b ",""]',
16
- ZAG_DEFAULT_WORKSPACE: '/root/workspace',
17
+ ZAG_DEFAULT_WORKSPACE: '/home/worker/workspace',
17
18
  };
18
19
 
19
20
  async function makeDir(): Promise<string> {
@@ -45,11 +46,13 @@ describe('prepareHarness (T-AG7..T-AG12)', () => {
45
46
  });
46
47
 
47
48
  expect(runner).toHaveBeenCalledWith('opencode', ['--version']);
48
- expect(result.opencodeVersion).toBe('1.2.3');
49
+ expect(result.items).toHaveLength(1);
50
+ expect(result.items[0]).toMatchObject({ type: 'opencode', version: '1.2.3', modelCount: 2 });
49
51
  expect(result.env).toMatchObject({
50
52
  modelBaseUrl: 'http://admin-api:8002/v1',
51
53
  defaultWorkspace: workspace,
52
54
  modelCount: 2,
55
+ types: ['opencode'],
53
56
  });
54
57
  expect((await stat(workspace)).isDirectory()).toBe(true);
55
58
 
@@ -129,11 +132,134 @@ describe('prepareHarness (T-AG7..T-AG12)', () => {
129
132
  });
130
133
 
131
134
  const summary = formatPrepareSummary(result);
132
- expect(summary).toContain('OpenCode harness prepared');
133
- expect(summary).toContain('version=1.2.3');
135
+ expect(summary).toContain('Harness prepared: types=opencode');
136
+ expect(summary).toContain('- opencode: version=1.2.3');
134
137
  expect(summary).toContain('models=2');
135
- expect(summary).toContain('workspace=/root/workspace');
138
+ expect(summary).toContain('workspace=/home/worker/workspace');
136
139
  expect(summary).not.toContain('zag_sk_super_secret');
137
140
  expect(summary).not.toContain('admin-api');
138
141
  });
142
+
143
+ it('T-PREP1: ZAG_HARNESS_TYPES=deepseek_harness 只跑 dsh 校验与写入,不触碰 opencode', async () => {
144
+ const dir = await makeDir();
145
+ dirs.push(dir);
146
+ const configDir = join(dir, 'opencode-config');
147
+ const dshHome = join(dir, 'dsh-home');
148
+ const runner = vi.fn<CommandRunner>(async () => ({ stdout: '0.1.2-alpha.2\n', stderr: '' }));
149
+
150
+ const result = await prepareHarness({
151
+ env: {
152
+ ...VALID_ENV,
153
+ ZAG_HARNESS_TYPES: 'deepseek_harness',
154
+ ZAG_DEFAULT_WORKSPACE: join(dir, 'workspace'),
155
+ },
156
+ runner,
157
+ configDir,
158
+ dshHome,
159
+ makeDir: async (path: string) => {
160
+ await mkdir(path, { recursive: true });
161
+ },
162
+ });
163
+
164
+ expect(runner).toHaveBeenCalledTimes(1);
165
+ expect(runner).toHaveBeenCalledWith('dsh', ['--version']);
166
+ expect(result.env.types).toEqual(['deepseek_harness']);
167
+ expect(result.items).toHaveLength(1);
168
+ expect(result.items[0]).toMatchObject({
169
+ type: 'deepseek_harness',
170
+ version: '0.1.2-alpha.2',
171
+ modelCount: 2,
172
+ });
173
+ await expect(stat(configDir)).rejects.toThrow();
174
+ expect((await stat(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'))).isFile()).toBe(true);
175
+ expect((await stat(join(dshHome, '.credentials.yaml'))).isFile()).toBe(true);
176
+ });
177
+
178
+ it('T-PREP2: 未设置/空串/全部非法 → 回退 opencode;kimi_code 被过滤', async () => {
179
+ const dir = await makeDir();
180
+ dirs.push(dir);
181
+ const runner = vi.fn<CommandRunner>(async () => ({ stdout: '1.2.3', stderr: '' }));
182
+
183
+ for (const ZAG_HARNESS_TYPES of [undefined, '', 'kimi_code', 'kimi_code,bogus']) {
184
+ const result = await prepareHarness({
185
+ env: { ...VALID_ENV, ZAG_HARNESS_TYPES } as NodeJS.ProcessEnv,
186
+ runner,
187
+ configDir: join(dir, `config-${String(ZAG_HARNESS_TYPES)}`),
188
+ makeDir: async () => {},
189
+ });
190
+ expect(result.env.types).toEqual(['opencode']);
191
+ }
192
+ expect(runner).toHaveBeenCalledWith('opencode', ['--version']);
193
+ });
194
+
195
+ it('T-PREP3: opencode,deepseek_harness 两类各执行一次,顺序稳定、摘要两行', async () => {
196
+ const dir = await makeDir();
197
+ dirs.push(dir);
198
+ const runner = vi.fn<CommandRunner>(async (command: string) =>
199
+ command === 'dsh'
200
+ ? { stdout: '0.1.2-alpha.2\n', stderr: '' }
201
+ : { stdout: '1.2.3\n', stderr: '' },
202
+ );
203
+
204
+ const result = await prepareHarness({
205
+ env: {
206
+ ...VALID_ENV,
207
+ ZAG_HARNESS_TYPES: 'opencode, deepseek_harness,kimi_code,opencode',
208
+ },
209
+ runner,
210
+ configDir: join(dir, 'config'),
211
+ dshHome: join(dir, 'dsh-home'),
212
+ makeDir: async () => {},
213
+ });
214
+
215
+ expect(result.env.types).toEqual(['opencode', 'deepseek_harness']);
216
+ expect(result.items.map((item) => item.type)).toEqual(['opencode', 'deepseek_harness']);
217
+ expect(runner).toHaveBeenNthCalledWith(1, 'opencode', ['--version']);
218
+ expect(runner).toHaveBeenNthCalledWith(2, 'dsh', ['--version']);
219
+
220
+ const summary = formatPrepareSummary(result);
221
+ expect(summary.split('\n')).toHaveLength(3);
222
+ expect(summary).toContain('- opencode: version=1.2.3');
223
+ expect(summary).toContain('- deepseek_harness: version=0.1.2-alpha.2');
224
+ });
225
+
226
+ it('T-PREP4: 重复执行 deepseek_harness 幂等(文件内容一致)', async () => {
227
+ const dir = await makeDir();
228
+ dirs.push(dir);
229
+ const dshHome = join(dir, 'dsh-home');
230
+ const options = {
231
+ env: { ...VALID_ENV, ZAG_HARNESS_TYPES: 'deepseek_harness' },
232
+ runner: async () => ({ stdout: '0.1.2-alpha.2\n', stderr: '' }),
233
+ dshHome,
234
+ makeDir: async () => {},
235
+ };
236
+
237
+ await prepareHarness(options);
238
+ const firstPatch = await readFile(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'), 'utf-8');
239
+ await prepareHarness(options);
240
+ const secondPatch = await readFile(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'), 'utf-8');
241
+
242
+ expect(secondPatch).toBe(firstPatch);
243
+ });
244
+
245
+ it('T-PREP5: dsh 校验失败 → 整体抛错且不写配置(opencode 未执行)', async () => {
246
+ const dir = await makeDir();
247
+ dirs.push(dir);
248
+ const dshHome = join(dir, 'dsh-home');
249
+ const runner = vi.fn<CommandRunner>(async () => {
250
+ throw new Error('spawn dsh ENOENT');
251
+ });
252
+
253
+ await expect(
254
+ prepareHarness({
255
+ env: { ...VALID_ENV, ZAG_HARNESS_TYPES: 'deepseek_harness' },
256
+ runner,
257
+ dshHome,
258
+ makeDir: async () => {},
259
+ }),
260
+ ).rejects.toBeInstanceOf(DshCliError);
261
+
262
+ expect(runner).toHaveBeenCalledTimes(1);
263
+ await expect(stat(join(dshHome, 'profiles'))).rejects.toThrow();
264
+ });
139
265
  });
@@ -1,13 +1,30 @@
1
1
  import { mkdir } from 'node:fs/promises';
2
- import { readHarnessEnv, type HarnessEnv } from './env.js';
2
+ import { readHarnessEnv, resolvePrepareTypes, type HarnessEnv, type PrepareHarnessType } from './env.js';
3
+ import { verifyDshCli } from './dsh-cli.js';
4
+ import { writeDshConfig, defaultDshHome, type WriteDshConfigResult } from './dsh-config.js';
3
5
  import { verifyOpencodeCli, type CommandRunner } from './opencode-cli.js';
4
6
  import { writeOpencodeConfig, type WriteOpencodeConfigResult } from './opencode-config.js';
5
7
 
8
+ /** 逐类型的 prepare 结果(摘要不含任何 secret)。 */
9
+ export interface HarnessPrepareItemResult {
10
+ type: PrepareHarnessType;
11
+ ok: boolean;
12
+ /** 实际 CLI 版本(opencode / dsh)。 */
13
+ version: string;
14
+ /** 写入的模型数量。 */
15
+ modelCount: number;
16
+ /** 一行摘要(用于 `harness prepare` 输出)。 */
17
+ summary: string;
18
+ config: WriteOpencodeConfigResult | WriteDshConfigResult;
19
+ }
20
+
6
21
  /** `harness prepare` 结果摘要(不含任何 secret)。 */
7
22
  export interface HarnessPrepareResult {
8
- opencodeVersion: string;
9
- env: Pick<HarnessEnv, 'modelBaseUrl' | 'defaultWorkspace'> & { modelCount: number };
10
- config: WriteOpencodeConfigResult;
23
+ env: Pick<HarnessEnv, 'modelBaseUrl' | 'defaultWorkspace'> & {
24
+ modelCount: number;
25
+ types: PrepareHarnessType[];
26
+ };
27
+ items: HarnessPrepareItemResult[];
11
28
  }
12
29
 
13
30
  export interface PrepareHarnessOptions {
@@ -16,54 +33,113 @@ export interface PrepareHarnessOptions {
16
33
  runner?: CommandRunner;
17
34
  /** 覆盖 OpenCode 配置目录(测试/定制场景)。 */
18
35
  configDir?: string;
36
+ /** 覆盖 dsh home(测试/定制场景;缺省 `$DSH_HOME` 或 `~/.dsh`)。 */
37
+ dshHome?: string;
19
38
  /** 创建工作区的实现(测试注入)。 */
20
39
  makeDir?: (path: string) => Promise<void>;
21
40
  }
22
41
 
42
+ function formatOpencodeSummary(
43
+ version: string,
44
+ config: WriteOpencodeConfigResult,
45
+ ): string {
46
+ return `opencode: version=${version} models=${config.modelCount} config=${config.path} (${config.created ? 'created' : 'updated'})`;
47
+ }
48
+
49
+ function formatDeepseekSummary(
50
+ version: string,
51
+ config: WriteDshConfigResult,
52
+ ): string {
53
+ return [
54
+ `deepseek_harness: version=${version}`,
55
+ `models=${config.modelCount}`,
56
+ `patch=${config.patchPath} (${config.patchCreated ? 'created' : 'updated'})`,
57
+ `credentials=${config.credentialsPath} (${config.credentialsCreated ? 'created' : 'updated'})`,
58
+ ].join(' ');
59
+ }
60
+
23
61
  /**
24
- * 准备 OpenCode harness 环境(契约/计划 Phase 6):
62
+ * 准备 harness 环境(契约/计划 Phase 4):
25
63
  *
26
- * 1. 校验 harness env(缺失项明确报错);
27
- * 2. `opencode --version` 硬校验(不通过即失败);
28
- * 3. `mkdir -p ZAG_DEFAULT_WORKSPACE`(幂等);
29
- * 4. 写入/合并 `opencode.jsonc` 的 `providers.zag`(权限 0600)。
64
+ * 1. 校验 harness env(缺失项明确报错,只执行一次);
65
+ * 2. 按 `ZAG_HARNESS_TYPES` 分流(缺省/空/全非法 → `['opencode']`)逐类型 CLI 硬校验
66
+ * (`opencode --version` / `dsh --version`),全部通过前不触碰文件系统;
67
+ * 3. `mkdir -p ZAG_DEFAULT_WORKSPACE`(幂等,只执行一次);
68
+ * 4. 逐类型写入:`opencode` → 合并 `opencode.jsonc`;`deepseek_harness` → 合并
69
+ * `cordis.patch.yml` / `.credentials.yaml`。任一类型失败整体抛错,已成功部分不回滚(幂等重跑)。
30
70
  *
71
+ * 只对所选类型做 CLI 校验与写入:`deepseek_harness` 单选时不触碰 opencode(反之亦然)。
31
72
  * secret 只写入配置文件,不进入日志/错误/返回值。
32
73
  */
33
74
  export async function prepareHarness(
34
75
  options: PrepareHarnessOptions = {},
35
76
  ): Promise<HarnessPrepareResult> {
36
- const env = readHarnessEnv(options.env ?? process.env);
37
- // init 脚本 export OPENCODE_CLI_VERSION:agent-gear 侧做二次硬校验(C-5,缺省不启用)。
38
- const expectedOpencodeVersion = (options.env ?? process.env).OPENCODE_CLI_VERSION;
39
- const opencodeVersion = await verifyOpencodeCli(options.runner, expectedOpencodeVersion);
77
+ const sourceEnv = options.env ?? process.env;
78
+ const env = readHarnessEnv(sourceEnv);
79
+ const types = resolvePrepareTypes(sourceEnv);
80
+
81
+ const makeDir =
82
+ options.makeDir ?? ((path: string) => mkdir(path, { recursive: true }).then(() => undefined));
83
+
84
+ const versions = new Map<PrepareHarnessType, string>();
85
+ for (const type of types) {
86
+ // init 脚本 export OPENCODE_CLI_VERSION / DSH_CLI_VERSION:agent-gear 侧做二次硬校验
87
+ //(opencode C-5 缺省不启用;dsh 预发布段精确比较)。
88
+ versions.set(
89
+ type,
90
+ type === 'opencode'
91
+ ? await verifyOpencodeCli(options.runner, sourceEnv.OPENCODE_CLI_VERSION)
92
+ : await verifyDshCli(options.runner, sourceEnv.DSH_CLI_VERSION),
93
+ );
94
+ }
40
95
 
41
- const makeDir = options.makeDir ?? ((path: string) => mkdir(path, { recursive: true }).then(() => undefined));
42
96
  await makeDir(env.defaultWorkspace);
43
97
 
44
- const config = await writeOpencodeConfig({
45
- env,
46
- configDir: options.configDir,
47
- });
98
+ const items: HarnessPrepareItemResult[] = [];
99
+ for (const type of types) {
100
+ const version = versions.get(type)!;
101
+ if (type === 'opencode') {
102
+ const config = await writeOpencodeConfig({ env, configDir: options.configDir });
103
+ items.push({
104
+ type,
105
+ ok: true,
106
+ version,
107
+ modelCount: config.modelCount,
108
+ summary: formatOpencodeSummary(version, config),
109
+ config,
110
+ });
111
+ continue;
112
+ }
113
+
114
+ const config = await writeDshConfig({
115
+ env,
116
+ dshHome: options.dshHome ?? defaultDshHome(sourceEnv),
117
+ });
118
+ items.push({
119
+ type,
120
+ ok: true,
121
+ version,
122
+ modelCount: config.modelCount,
123
+ summary: formatDeepseekSummary(version, config),
124
+ config,
125
+ });
126
+ }
48
127
 
49
128
  return {
50
- opencodeVersion,
51
129
  env: {
52
130
  modelBaseUrl: env.modelBaseUrl,
53
131
  defaultWorkspace: env.defaultWorkspace,
54
132
  modelCount: env.modelIds.length,
133
+ types,
55
134
  },
56
- config,
135
+ items,
57
136
  };
58
137
  }
59
138
 
60
- /** 输出一行摘要(不含 `ZAG_MODEL_API_KEY` / provider apiKey)。 */
139
+ /** 输出摘要(首行汇总,随后逐类型一行;不含 `ZAG_MODEL_API_KEY` / provider apiKey)。 */
61
140
  export function formatPrepareSummary(result: HarnessPrepareResult): string {
62
- const created = result.config.created ? 'created' : 'updated';
63
141
  return [
64
- `OpenCode harness prepared: version=${result.opencodeVersion}`,
65
- `models=${result.env.modelCount}`,
66
- `workspace=${result.env.defaultWorkspace}`,
67
- `config=${result.config.path} (${created})`,
68
- ].join(' ');
142
+ `Harness prepared: types=${result.env.types.join(',')} models=${result.env.modelCount} workspace=${result.env.defaultWorkspace}`,
143
+ ...result.items.map((item) => `- ${item.summary}`),
144
+ ].join('\n');
69
145
  }
package/src/index.ts CHANGED
@@ -10,6 +10,13 @@ import { startMcpProxy } from './commands/mcp.js';
10
10
  import { registerHarnessCommands } from './commands/harness.js';
11
11
  import { isCloudHostMode, startCloudHostSupervisor } from './cloud-host/supervisor.js';
12
12
  import { processRegistry, isProcessAlive } from './acp/process-registry.js';
13
+ export {
14
+ EXIT_SERVER_SHUTDOWN,
15
+ isFailureShutdownReason,
16
+ isServerTerminationReason,
17
+ isSignalShutdownReason,
18
+ resolveShutdownExitCode,
19
+ } from './exit-codes.js';
13
20
 
14
21
  // 版本号唯一事实源为 package.json(`--version` 与 npm 发布版本保持一致,避免手工同步漂移)。
15
22
  const { version: CLI_VERSION } = createRequire(import.meta.url)('../package.json') as {
@@ -75,11 +75,11 @@ function emitted(event: string) {
75
75
  }
76
76
 
77
77
  describe('CONTROLLER_VERSION', () => {
78
- it('register 上报版本取自 package.json(2.8.0,无第二处常量)', () => {
78
+ it('register 上报版本取自 package.json(2.10.0,无第二处常量)', () => {
79
79
  setup();
80
80
  fake.handlers.get('connect')?.();
81
- expect(PACKAGE_VERSION).toBe('2.8.0');
82
- expect(emitted('register')[0]).toMatchObject({ version: '2.8.0' });
81
+ expect(PACKAGE_VERSION).toBe('2.10.0');
82
+ expect(emitted('register')[0]).toMatchObject({ version: '2.10.0' });
83
83
  });
84
84
  });
85
85
 
@@ -184,6 +184,50 @@ describe('cloud-host reconnect backoff (C-3)', () => {
184
184
  });
185
185
  });
186
186
 
187
+ describe('idle-path exit codes (contract §3.7)', () => {
188
+ beforeEach(() => {
189
+ fake.handlers.clear();
190
+ fake.socket.on.mockClear();
191
+ fake.socket.emit.mockClear();
192
+ fake.socket.disconnect.mockClear();
193
+ fake.socket.close.mockClear();
194
+ vi.spyOn(console, 'log').mockImplementation(() => {});
195
+ vi.spyOn(console, 'error').mockImplementation(() => {});
196
+ vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
197
+ throw new Error(`exit:${code}`);
198
+ }) as never);
199
+ });
200
+
201
+ afterEach(() => {
202
+ vi.restoreAllMocks();
203
+ });
204
+
205
+ it('unregistered exits 42 (server termination)', () => {
206
+ setup(false);
207
+ expect(() => fake.handlers.get('unregistered')?.()).toThrow('exit:42');
208
+ });
209
+
210
+ it('server shutdown exits 42, failure shutdown exits 1', () => {
211
+ setup(false);
212
+ expect(() => shutdownHandler()({ reason: 'server requested shutdown' })).toThrow('exit:42');
213
+
214
+ fake.handlers.clear();
215
+ setup(false);
216
+ expect(() => shutdownHandler()({ reason: 'error: REGISTER_FAILED' })).toThrow('exit:1');
217
+ });
218
+
219
+ it('error INVALID_TOKEN exits 42 instead of the generic failure code', () => {
220
+ setup(false);
221
+ expect(() => errorHandler()({ code: 'INVALID_TOKEN', message: 'token expired' })).toThrow('exit:42');
222
+ });
223
+
224
+ it('connect_error INVALID_TOKEN exits 42', () => {
225
+ setup(false);
226
+ const error = Object.assign(new Error('INVALID_TOKEN'), { data: { code: 'INVALID_TOKEN' } });
227
+ expect(() => fake.handlers.get('connect_error')?.(error)).toThrow('exit:42');
228
+ });
229
+ });
230
+
187
231
  describe('buildAcpInitResult', () => {
188
232
  it('T-SC1: payload 带 capabilities 时透传,既有字段一个不少', () => {
189
233
  const capabilities = {
@@ -21,10 +21,11 @@ import { processRegistry, isProcessAlive } from './acp/process-registry.js';
21
21
  import { McpRelay } from './mcp/relay.js';
22
22
  import { LocalMcpServer } from './mcp/local-server.js';
23
23
  import { WorkloadExecutor, type WorkloadRunPayload, collectSecretValues, redactSecrets } from './workload-executor.js';
24
+ import { EXIT_SERVER_SHUTDOWN, resolveShutdownExitCode } from './exit-codes.js';
24
25
 
25
26
  // 版本号唯一事实源为 package.json(register 上报的完整版本;服务端按 MIN_WORKER_VERSION=2.2.0 门禁)。
26
27
  // 2.8.0 起 `kimi_code` 使用前登录闸门(`kimi login` stdio 判定 + `harness:login:*` 事件族);
27
- // 2.6.0 起支持 `workload:run.githubAuth` 与云电脑 Github 凭据管理器(MIN_HARNESS_WORKER_VERSION=2.6.0);
28
+ // 2.6.0 起支持 `workload:run.githubAuth` 与云电脑 Github 凭据管理器(MIN_HARNESS_WORKER_VERSION=2.10.0);
28
29
  // 2.5.0 起支持云电脑双连接(`/worker` + controller-api)与 `harness prepare`。
29
30
  const { version: CONTROLLER_VERSION } = createRequire(import.meta.url)('../package.json') as {
30
31
  version: string;
@@ -527,6 +528,17 @@ export function connectToServer(
527
528
 
528
529
  socket.on('error', (data: ErrorPayload) => {
529
530
  console.error(`Server error: ${data.code} - ${data.message}`);
531
+ if (data.code === 'INVALID_TOKEN') {
532
+ // token 已失效 = 已被服务端注销:服务端终止语义(退出码 42,入口不保活重启)。
533
+ console.error('Handshake token is no longer valid; the container has been deregistered.');
534
+ socket.disconnect();
535
+ if (options?.onShutdown) {
536
+ notifyShutdown({ reason: `error: ${data.code}` });
537
+ return;
538
+ }
539
+ process.exit(EXIT_SERVER_SHUTDOWN);
540
+ return;
541
+ }
530
542
  if (data.code === 'VERSION_MISMATCH') {
531
543
  console.error('The agent-controller version is not supported by the server.');
532
544
  console.error('Please upgrade agent-controller to 2.x (npm i -g agent-gear@2 or the matching release).');
@@ -569,7 +581,7 @@ export function connectToServer(
569
581
  return;
570
582
  }
571
583
  socket.close();
572
- process.exit(0);
584
+ process.exit(EXIT_SERVER_SHUTDOWN);
573
585
  });
574
586
 
575
587
  socket.on('shutdown', (data: ShutdownPayload) => {
@@ -585,7 +597,8 @@ export function connectToServer(
585
597
  }
586
598
  if (persistConfig) clearConfigKey();
587
599
  socket.close();
588
- process.exit(0);
600
+ // idle / 单连接:服务端终止 42、失败类 1(与云电脑 supervisor 同一分类)。
601
+ process.exit(resolveShutdownExitCode(data.reason));
589
602
  };
590
603
  // post 批次仍在执行时,等待其结束(≤5s)后再退出,避免清理脚本被中途打断。
591
604
  // 无批次在跑时保持同步退出,行为与现状完全一致。
@@ -1477,6 +1490,17 @@ export function connectToServer(
1477
1490
  // 传输层失败时 err.message 往往只有笼统的 "websocket error",真实原因在 description/context
1478
1491
  // (如 HTTP 404/502、TLS 失败、协议错误)里——一并打印,避免"看不出为何连不上"。
1479
1492
  console.error(`Connection error: ${err.message}${describeConnectError(err)}`);
1493
+ // 握手鉴权失败(cloud-controller 一次性 token 已失效):服务端终止语义,退出码 42。
1494
+ const code = (err as Error & { data?: { code?: string } }).data?.code;
1495
+ if (code === 'INVALID_TOKEN' || err.message.includes('INVALID_TOKEN')) {
1496
+ console.error('Handshake token is no longer valid; the container has been deregistered.');
1497
+ socket.disconnect();
1498
+ if (options?.onShutdown) {
1499
+ notifyShutdown({ reason: 'error: INVALID_TOKEN' });
1500
+ return;
1501
+ }
1502
+ process.exit(EXIT_SERVER_SHUTDOWN);
1503
+ }
1480
1504
  });
1481
1505
 
1482
1506
  return socket;
@@ -570,7 +570,7 @@ describe('WorkloadExecutor container env + secret redaction (T-AG13/T-AG14)', ()
570
570
  phase: 'init',
571
571
  env: {
572
572
  ZAG_MODEL_IDS: '["model-a","model-b"]',
573
- ZAG_DEFAULT_WORKSPACE: '/root/workspace',
573
+ ZAG_DEFAULT_WORKSPACE: '/home/worker/workspace',
574
574
  ZAG_USER_ID: 'user-1',
575
575
  WORKLOAD_PARAM_VERSION: 'from-container-env',
576
576
  },
@@ -595,7 +595,7 @@ describe('WorkloadExecutor container env + secret redaction (T-AG13/T-AG14)', ()
595
595
 
596
596
  expect(results.map((r) => r.logId)).toEqual(['first', 'second']);
597
597
  expect(results[0].log).toContain('IDS=["model-a","model-b"]');
598
- expect(results[0].log).toContain('WS=/root/workspace');
598
+ expect(results[0].log).toContain('WS=/home/worker/workspace');
599
599
  expect(results[0].log).toContain('USER=user-1');
600
600
  // item 参数优先于容器 env 的同名 WORKLOAD_PARAM_*
601
601
  expect(results[0].log).toContain('V=from-item-param');
@@ -28,11 +28,17 @@ describe('AcpDetector', () => {
28
28
 
29
29
  beforeEach(() => {
30
30
  vi.clearAllMocks();
31
+ // 默认按「命令不可用」兜底:个别用例未显式 mock 的探测不会挂起。
32
+ vi.mocked(exec).mockImplementation(((...args: unknown[]) => {
33
+ const cb = args.find((a) => typeof a === 'function') as ((err: Error) => void) | undefined;
34
+ if (cb) cb(new Error('command not found'));
35
+ return {} as any;
36
+ }) as never);
31
37
  detector = new AcpDetector();
32
38
  });
33
39
 
34
40
  describe('detect', () => {
35
- it('should detect all 7 servers when all available', async () => {
41
+ it('should detect all 8 servers when all available', async () => {
36
42
  mockExecSuccessOnce('opencode v1.2.3\n');
37
43
  mockExecSuccessOnce('copilot 1.0.0\n');
38
44
  mockExecSuccessOnce('claude-agent-acp 0.1.0\n');
@@ -40,10 +46,11 @@ describe('AcpDetector', () => {
40
46
  mockExecSuccessOnce('codex-acp 0.5.0\n');
41
47
  mockExecSuccessOnce('mimo 0.1.0\n');
42
48
  mockExecSuccessOnce('kimi 1.0.0\n');
49
+ mockExecSuccessOnce('0.1.2-alpha.2\n');
43
50
 
44
51
  const result = await detector.detect();
45
52
 
46
- expect(result).toHaveLength(7);
53
+ expect(result).toHaveLength(8);
47
54
  expect(result[0]).toEqual({ type: 'opencode', available: true, version: '1.2.3' });
48
55
  expect(result[1]).toEqual({ type: 'github_copilot', available: true, version: '1.0.0' });
49
56
  expect(result[2]).toEqual({ type: 'claude_code', available: true, version: '0.1.0' });
@@ -51,6 +58,11 @@ describe('AcpDetector', () => {
51
58
  expect(result[4]).toEqual({ type: 'codex', available: true, version: '0.5.0' });
52
59
  expect(result[5]).toEqual({ type: 'mimo_code', available: true, version: '0.1.0' });
53
60
  expect(result[6]).toEqual({ type: 'kimi_code', available: true, version: '1.0.0' });
61
+ expect(result[7]).toEqual({
62
+ type: 'deepseek_harness',
63
+ available: true,
64
+ version: '0.1.2-alpha.2',
65
+ });
54
66
  });
55
67
 
56
68
  it('should detect as unavailable when command fails', async () => {
@@ -64,7 +76,7 @@ describe('AcpDetector', () => {
64
76
 
65
77
  const result = await detector.detect();
66
78
 
67
- expect(result).toHaveLength(7);
79
+ expect(result).toHaveLength(8);
68
80
  expect(result[0]).toEqual({ type: 'opencode', available: false });
69
81
  expect(result[1]).toEqual({ type: 'github_copilot', available: false });
70
82
  expect(result[2]).toEqual({ type: 'claude_code', available: false });
@@ -72,6 +84,7 @@ describe('AcpDetector', () => {
72
84
  expect(result[4]).toEqual({ type: 'codex', available: false });
73
85
  expect(result[5]).toEqual({ type: 'mimo_code', available: false });
74
86
  expect(result[6]).toEqual({ type: 'kimi_code', available: false });
87
+ expect(result[7]).toEqual({ type: 'deepseek_harness', available: false });
75
88
  });
76
89
 
77
90
  it('should detect claude_code only when other servers fail', async () => {
@@ -85,7 +98,7 @@ describe('AcpDetector', () => {
85
98
 
86
99
  const result = await detector.detect();
87
100
 
88
- expect(result).toHaveLength(7);
101
+ expect(result).toHaveLength(8);
89
102
  expect(result[0]).toEqual({ type: 'opencode', available: false });
90
103
  expect(result[1]).toEqual({ type: 'github_copilot', available: false });
91
104
  expect(result[2]).toEqual({ type: 'claude_code', available: true, version: '0.1.0' });
@@ -106,7 +119,7 @@ describe('AcpDetector', () => {
106
119
 
107
120
  const result = await detector.detect();
108
121
 
109
- expect(result).toHaveLength(7);
122
+ expect(result).toHaveLength(8);
110
123
  expect(result[3]).toEqual({ type: 'gemini_cli', available: true, version: '2.0.0' });
111
124
  });
112
125
 
@@ -121,7 +134,7 @@ describe('AcpDetector', () => {
121
134
 
122
135
  const result = await detector.detect();
123
136
 
124
- expect(result).toHaveLength(7);
137
+ expect(result).toHaveLength(8);
125
138
  expect(result[4]).toEqual({ type: 'codex', available: true, version: '0.5.0' });
126
139
  });
127
140
 
@@ -136,7 +149,7 @@ describe('AcpDetector', () => {
136
149
 
137
150
  const result = await detector.detect();
138
151
 
139
- expect(result).toHaveLength(7);
152
+ expect(result).toHaveLength(8);
140
153
  expect(result[5]).toEqual({ type: 'mimo_code', available: true, version: '0.1.0' });
141
154
  });
142
155
 
@@ -151,7 +164,7 @@ describe('AcpDetector', () => {
151
164
 
152
165
  const result = await detector.detect();
153
166
 
154
- expect(result).toHaveLength(7);
167
+ expect(result).toHaveLength(8);
155
168
  expect(result[6]).toEqual({ type: 'kimi_code', available: true, version: '2.0.0' });
156
169
  });
157
170
 
@@ -163,6 +176,7 @@ describe('AcpDetector', () => {
163
176
  mockExecSuccessOnce('codex-acp version 0.5.0\n');
164
177
  mockExecSuccessOnce('MiMo CLI v1.0.0\n');
165
178
  mockExecSuccessOnce('kimi 2.0.0\n');
179
+ mockExecSuccessOnce('0.1.2-alpha.2\n');
166
180
 
167
181
  const result = await detector.detect();
168
182
 
@@ -173,6 +187,7 @@ describe('AcpDetector', () => {
173
187
  expect(result[4].version).toBe('0.5.0');
174
188
  expect(result[5].version).toBe('1.0.0');
175
189
  expect(result[6].version).toBe('2.0.0');
190
+ expect(result[7].version).toBe('0.1.2-alpha.2');
176
191
  });
177
192
  });
178
193
 
@@ -212,6 +227,11 @@ describe('AcpDetector', () => {
212
227
  expect(config).toEqual({ command: 'kimi', args: ['acp'] });
213
228
  });
214
229
 
230
+ it('should return deepseek_harness spawner config', () => {
231
+ const config = detector.getSpawnerConfig('deepseek_harness');
232
+ expect(config).toEqual({ command: 'dsh', args: ['--profile', 'acp'] });
233
+ });
234
+
215
235
  it('should return opencode as default for unknown serverType', () => {
216
236
  const config = detector.getSpawnerConfig('unknown_server');
217
237
  expect(config).toEqual({ command: 'opencode', args: ['acp'] });