agent-gear 2.8.0 → 2.9.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 (68) hide show
  1. package/AGENTS.md +11 -1
  2. package/dist/acp/detector.d.ts +2 -0
  3. package/dist/acp/detector.d.ts.map +1 -1
  4. package/dist/acp/detector.js +18 -3
  5. package/dist/acp/detector.js.map +1 -1
  6. package/dist/acp/detector.test.d.ts +2 -0
  7. package/dist/acp/detector.test.d.ts.map +1 -0
  8. package/dist/acp/detector.test.js +50 -0
  9. package/dist/acp/detector.test.js.map +1 -0
  10. package/dist/commands/harness.d.ts +5 -1
  11. package/dist/commands/harness.d.ts.map +1 -1
  12. package/dist/commands/harness.js +7 -3
  13. package/dist/commands/harness.js.map +1 -1
  14. package/dist/harness/dsh-cli.d.ts +17 -0
  15. package/dist/harness/dsh-cli.d.ts.map +1 -0
  16. package/dist/harness/dsh-cli.js +51 -0
  17. package/dist/harness/dsh-cli.js.map +1 -0
  18. package/dist/harness/dsh-cli.test.d.ts +2 -0
  19. package/dist/harness/dsh-cli.test.d.ts.map +1 -0
  20. package/dist/harness/dsh-cli.test.js +51 -0
  21. package/dist/harness/dsh-cli.test.js.map +1 -0
  22. package/dist/harness/dsh-config.atomic-failure.test.d.ts +2 -0
  23. package/dist/harness/dsh-config.atomic-failure.test.d.ts.map +1 -0
  24. package/dist/harness/dsh-config.atomic-failure.test.js +35 -0
  25. package/dist/harness/dsh-config.atomic-failure.test.js.map +1 -0
  26. package/dist/harness/dsh-config.d.ts +46 -0
  27. package/dist/harness/dsh-config.d.ts.map +1 -0
  28. package/dist/harness/dsh-config.js +228 -0
  29. package/dist/harness/dsh-config.js.map +1 -0
  30. package/dist/harness/dsh-config.test.d.ts +2 -0
  31. package/dist/harness/dsh-config.test.d.ts.map +1 -0
  32. package/dist/harness/dsh-config.test.js +229 -0
  33. package/dist/harness/dsh-config.test.js.map +1 -0
  34. package/dist/harness/env.d.ts +11 -0
  35. package/dist/harness/env.d.ts.map +1 -1
  36. package/dist/harness/env.js +23 -0
  37. package/dist/harness/env.js.map +1 -1
  38. package/dist/harness/env.test.js +23 -1
  39. package/dist/harness/env.test.js.map +1 -1
  40. package/dist/harness/opencode-cli.d.ts +5 -0
  41. package/dist/harness/opencode-cli.d.ts.map +1 -1
  42. package/dist/harness/opencode-cli.js +8 -1
  43. package/dist/harness/opencode-cli.js.map +1 -1
  44. package/dist/harness/prepare.d.ts +27 -9
  45. package/dist/harness/prepare.d.ts.map +1 -1
  46. package/dist/harness/prepare.js +67 -23
  47. package/dist/harness/prepare.js.map +1 -1
  48. package/dist/harness/prepare.test.js +110 -3
  49. package/dist/harness/prepare.test.js.map +1 -1
  50. package/dist/socketio-client.auth-gate.test.js +3 -3
  51. package/package.json +3 -2
  52. package/src/acp/detector.test.ts +64 -0
  53. package/src/acp/detector.ts +18 -3
  54. package/src/commands/harness.ts +9 -3
  55. package/src/harness/dsh-cli.test.ts +58 -0
  56. package/src/harness/dsh-cli.ts +67 -0
  57. package/src/harness/dsh-config.atomic-failure.test.ts +51 -0
  58. package/src/harness/dsh-config.test.ts +275 -0
  59. package/src/harness/dsh-config.ts +280 -0
  60. package/src/harness/env.test.ts +32 -1
  61. package/src/harness/env.ts +26 -0
  62. package/src/harness/opencode-cli.ts +9 -2
  63. package/src/harness/prepare.test.ts +129 -3
  64. package/src/harness/prepare.ts +103 -27
  65. package/src/socketio-client.auth-gate.test.ts +3 -3
  66. package/tests/acp-detector.test.ts +28 -8
  67. package/tests/commands/harness.test.ts +17 -7
  68. package/tests/socketio-client.test.ts +2 -2
@@ -0,0 +1,280 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { Document, isMap, isSeq, parseDocument, type YAMLMap, type YAMLSeq } from 'yaml';
6
+ import type { HarnessEnv } from './env.js';
7
+
8
+ /** dsh 凭据 env 引用名(值只写 `.credentials.yaml` 的 `refs`)。 */
9
+ export const ZAG_API_KEY_ENV = 'ZAG_MODEL_API_KEY';
10
+
11
+ /** dsh ACP profile 名(`dsh --profile acp`)。 */
12
+ export const DSH_ACP_PROFILE = 'acp';
13
+
14
+ /** dsh ACP profile 组合包名(写入 patch 的 `acp` 条目)。 */
15
+ export const DSH_ACP_APP_NAME = '@deepseek-ai/dsh-acp';
16
+
17
+ /** 我方在 `cordis.patch.yml` 中维护的 4 个条目(按此顺序写入,按 id 替换)。 */
18
+ export const DSH_PATCH_ENTRY_IDS = [
19
+ 'llm-deepseek',
20
+ 'llm-pi-ai',
21
+ 'agent-default-model',
22
+ 'acp',
23
+ ] as const;
24
+
25
+ /** 写入 dsh 配置失败(消息只含路径/条目名,不含 API Key 等 secret)。 */
26
+ export class DshConfigError extends Error {
27
+ constructor(message: string) {
28
+ super(message);
29
+ this.name = 'DshConfigError';
30
+ }
31
+ }
32
+
33
+ type DshConfigEnv = Pick<
34
+ HarnessEnv,
35
+ 'modelBaseUrl' | 'modelApiKey' | 'modelIds'
36
+ > &
37
+ Partial<Pick<HarnessEnv, 'modelContextLengths'>>;
38
+
39
+ export interface WriteDshConfigOptions {
40
+ env: DshConfigEnv;
41
+ /** 覆盖 dsh home(缺省 `$DSH_HOME` 或 `~/.dsh`)。 */
42
+ dshHome?: string;
43
+ }
44
+
45
+ export interface WriteDshConfigResult {
46
+ /** `cordis.patch.yml` 实际路径。 */
47
+ patchPath: string;
48
+ /** `.credentials.yaml` 实际路径。 */
49
+ credentialsPath: string;
50
+ /** patch 是否新建。 */
51
+ patchCreated: boolean;
52
+ /** credentials 是否新建。 */
53
+ credentialsCreated: boolean;
54
+ /** 写入的模型数量。 */
55
+ modelCount: number;
56
+ /** patch 中我方维护的条目数(固定 4)。 */
57
+ entryCount: number;
58
+ }
59
+
60
+ /** 默认 dsh home:`$DSH_HOME` 优先,否则 `~/.dsh`。 */
61
+ export function defaultDshHome(env: NodeJS.ProcessEnv = process.env): string {
62
+ const configured = typeof env.DSH_HOME === 'string' ? env.DSH_HOME.trim() : '';
63
+ return configured || join(homedir(), '.dsh');
64
+ }
65
+
66
+ async function exists(path: string): Promise<boolean> {
67
+ try {
68
+ await stat(path);
69
+ return true;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ /** `llm-pi-ai.providers.zag`:模型清单整体替换,`contextWindow` 仅在正整数时写入。 */
76
+ function buildZagProvider(env: DshConfigEnv): Record<string, unknown> {
77
+ const models = env.modelIds.map((id) => {
78
+ const context = env.modelContextLengths?.[id];
79
+ return typeof context === 'number' && Number.isInteger(context) && context > 0
80
+ ? { id, name: id, contextWindow: context }
81
+ : { id, name: id };
82
+ });
83
+ return {
84
+ displayName: 'ZAG',
85
+ apiKeyEnv: ZAG_API_KEY_ENV,
86
+ api: 'openai-completions',
87
+ baseURL: env.modelBaseUrl,
88
+ models,
89
+ };
90
+ }
91
+
92
+ /** 我方 patch 条目(按 id;默认模型取 `modelIds[0]`,空清单不写 `model`)。 */
93
+ function buildEntry(id: (typeof DSH_PATCH_ENTRY_IDS)[number], env: DshConfigEnv): Record<string, unknown> {
94
+ const defaultModel = env.modelIds[0];
95
+ switch (id) {
96
+ case 'llm-deepseek':
97
+ return { id, disabled: true };
98
+ case 'llm-pi-ai':
99
+ return { id, config: { providers: { zag: buildZagProvider(env) } } };
100
+ case 'agent-default-model':
101
+ return {
102
+ id,
103
+ config: defaultModel ? { provider: 'zag', model: defaultModel } : { provider: 'zag' },
104
+ };
105
+ case 'acp':
106
+ return {
107
+ id,
108
+ name: DSH_ACP_APP_NAME,
109
+ config: defaultModel ? { provider: 'zag', model: defaultModel } : { provider: 'zag' },
110
+ };
111
+ default:
112
+ throw new DshConfigError(`unsupported dsh patch entry: ${String(id)}`);
113
+ }
114
+ }
115
+
116
+ function parsePatchDocument(text: string, path: string): Document {
117
+ if (text.trim().length === 0) return new Document([]);
118
+ const doc = parseDocument(text);
119
+ if (doc.errors.length > 0) {
120
+ const code = (doc.errors[0] as { code?: string }).code ?? 'PARSE_ERROR';
121
+ throw new DshConfigError(`cannot parse dsh patch at ${path}: ${code}`);
122
+ }
123
+ if (doc.contents === null) return new Document([]);
124
+ if (!isSeq(doc.contents)) {
125
+ throw new DshConfigError(`invalid dsh patch at ${path}: expected a top-level array`);
126
+ }
127
+ return doc;
128
+ }
129
+
130
+ /**
131
+ * 合并 `cordis.patch.yml`:
132
+ *
133
+ * - 顶层条目数组,按 `id` 定位我方 4 个条目并**整体替换其 config**;
134
+ * - 其余条目与注释逐字保留(新条目追加在末尾);
135
+ * - 解析失败抛错、不写文件(不静默丢数据)。
136
+ */
137
+ function mergePatchDocument(doc: Document, env: DshConfigEnv): { content: string; entryCount: number } {
138
+ const seq = doc.contents as YAMLSeq;
139
+ const findIndex = (id: string): number =>
140
+ seq.items.findIndex((item) => isMap(item) && item.get('id') === id);
141
+
142
+ for (const id of DSH_PATCH_ENTRY_IDS) {
143
+ const entry = buildEntry(id, env);
144
+ const index = findIndex(id);
145
+ if (index === -1) {
146
+ seq.add(doc.createNode(entry));
147
+ continue;
148
+ }
149
+ if (id === 'llm-deepseek') {
150
+ doc.setIn([index, 'disabled'], true);
151
+ continue;
152
+ }
153
+ const config = entry.config as Record<string, unknown>;
154
+ doc.setIn([index, 'config'], doc.createNode(config));
155
+ if (id === 'acp') doc.setIn([index, 'name'], DSH_ACP_APP_NAME);
156
+ }
157
+
158
+ let content = doc.toString();
159
+ if (!content.endsWith('\n')) content += '\n';
160
+ return { content, entryCount: DSH_PATCH_ENTRY_IDS.length };
161
+ }
162
+
163
+ /**
164
+ * 合并 `.credentials.yaml`:
165
+ *
166
+ * - 已有文件只替换 `refs.ZAG_MODEL_API_KEY`,保留其他 `refs`/`records` 与注释;
167
+ * - 新建写 `{ version: 1, refs: { ZAG_MODEL_API_KEY } }`;
168
+ * - 永远写 `version: 1`(旧扁平格式由 dsh 迁移,我方不写);
169
+ * - 非法 YAML / 非 mapping 抛错不覆盖。
170
+ */
171
+ function mergeCredentialsDocument(
172
+ text: string,
173
+ path: string,
174
+ env: DshConfigEnv,
175
+ ): string {
176
+ let doc: Document;
177
+ if (text.trim().length === 0) {
178
+ doc = new Document({ version: 1, refs: {} });
179
+ } else {
180
+ doc = parseDocument(text);
181
+ if (doc.errors.length > 0) {
182
+ const code = (doc.errors[0] as { code?: string }).code ?? 'PARSE_ERROR';
183
+ throw new DshConfigError(`cannot parse dsh credentials at ${path}: ${code}`);
184
+ }
185
+ if (doc.contents === null) {
186
+ doc = new Document({ version: 1, refs: {} });
187
+ } else if (!isMap(doc.contents)) {
188
+ throw new DshConfigError(`invalid dsh credentials at ${path}: expected a mapping`);
189
+ }
190
+ }
191
+
192
+ const root = doc.contents as YAMLMap;
193
+ root.set('version', 1);
194
+ const refs = root.get('refs');
195
+ if (refs === undefined || refs === null) {
196
+ root.set('refs', doc.createNode({}));
197
+ } else if (!isMap(refs)) {
198
+ throw new DshConfigError(`invalid dsh credentials at ${path}: refs must be a mapping`);
199
+ }
200
+ const refsMap = root.get('refs') as YAMLMap;
201
+ refsMap.set(ZAG_API_KEY_ENV, env.modelApiKey);
202
+
203
+ let content = doc.toString();
204
+ if (!content.endsWith('\n')) content += '\n';
205
+ return content;
206
+ }
207
+
208
+ /** 同目录临时文件 + rename 原子替换;失败时清理临时文件、原文件保持完整。 */
209
+ async function atomicWrite(path: string, dir: string, content: string, label: string): Promise<void> {
210
+ const tempPath = join(dir, `.${label}.${process.pid}.${randomUUID()}.tmp`);
211
+ try {
212
+ await writeFile(tempPath, content, { encoding: 'utf-8', mode: 0o600 });
213
+ await chmod(tempPath, 0o600);
214
+ await rename(tempPath, path);
215
+ } catch (error) {
216
+ await rm(tempPath, { force: true }).catch(() => {});
217
+ throw new DshConfigError(`cannot write ${label} at ${path}: ${(error as Error).message}`);
218
+ }
219
+ }
220
+
221
+ async function readText(path: string, label: string): Promise<{ text: string; created: boolean }> {
222
+ if (!(await exists(path))) return { text: '', created: true };
223
+ try {
224
+ return { text: await readFile(path, 'utf-8'), created: false };
225
+ } catch (error) {
226
+ throw new DshConfigError(`cannot read ${label} at ${path}: ${(error as Error).message}`);
227
+ }
228
+ }
229
+
230
+ /**
231
+ * 写入/合并 dsh 平台渠道模型注入(计划 §3.2.1 / §3.2.2):
232
+ *
233
+ * 1. `~/.dsh/profiles/acp/cordis.patch.yml`(目录 0700、文件 0600);
234
+ * 2. `~/.dsh/.credentials.yaml`(0600);
235
+ * 3. 两文件均走临时文件 + `rename` 原子替换,失败不破坏既有文件;
236
+ * 4. secret 只落凭据文件,不进入返回值/错误信息。
237
+ */
238
+ export async function writeDshConfig(
239
+ options: WriteDshConfigOptions,
240
+ ): Promise<WriteDshConfigResult> {
241
+ const envSource = options.env as DshConfigEnv & { DSH_HOME?: string };
242
+ const dshHome =
243
+ options.dshHome ?? defaultDshHome(envSource as unknown as NodeJS.ProcessEnv);
244
+ const profilesDir = join(dshHome, 'profiles', DSH_ACP_PROFILE);
245
+ const patchPath = join(profilesDir, 'cordis.patch.yml');
246
+ const credentialsPath = join(dshHome, '.credentials.yaml');
247
+
248
+ try {
249
+ await mkdir(profilesDir, { recursive: true, mode: 0o700 });
250
+ // `mkdir` 的 mode 只对新建目录生效:已存在目录显式收紧到 0700。
251
+ await chmod(profilesDir, 0o700);
252
+ } catch (error) {
253
+ throw new DshConfigError(
254
+ `cannot set permissions on dsh profile directory ${profilesDir}: ${(error as Error).message}`,
255
+ );
256
+ }
257
+
258
+ const patchFile = await readText(patchPath, 'dsh patch');
259
+ const patchDoc = parsePatchDocument(patchFile.text, patchPath);
260
+ const mergedPatch = mergePatchDocument(patchDoc, options.env);
261
+
262
+ const credentialsFile = await readText(credentialsPath, 'dsh credentials');
263
+ const credentialsContent = mergeCredentialsDocument(
264
+ credentialsFile.text,
265
+ credentialsPath,
266
+ options.env,
267
+ );
268
+
269
+ await atomicWrite(patchPath, profilesDir, mergedPatch.content, 'cordis.patch');
270
+ await atomicWrite(credentialsPath, dshHome, credentialsContent, 'dsh-credentials');
271
+
272
+ return {
273
+ patchPath,
274
+ credentialsPath,
275
+ patchCreated: patchFile.created,
276
+ credentialsCreated: credentialsFile.created,
277
+ modelCount: options.env.modelIds.length,
278
+ entryCount: mergedPatch.entryCount,
279
+ };
280
+ }
@@ -1,5 +1,11 @@
1
1
  import { describe, it, expect } from 'vitest';
2
- import { HarnessEnvError, parseModelContextLengths, parseModelIds, readHarnessEnv } from './env.js';
2
+ import {
3
+ HarnessEnvError,
4
+ parseModelContextLengths,
5
+ parseModelIds,
6
+ readHarnessEnv,
7
+ resolvePrepareTypes,
8
+ } from './env.js';
3
9
 
4
10
  const VALID_ENV: NodeJS.ProcessEnv = {
5
11
  ZAG_MODEL_BASE_URL: 'http://admin-api:8002/v1',
@@ -120,3 +126,28 @@ describe('parseModelContextLengths', () => {
120
126
  expect(() => parseModelContextLengths('{"a":1.5}')).toThrowError(/invalid value/);
121
127
  });
122
128
  });
129
+
130
+ describe('resolvePrepareTypes (T-PREP2)', () => {
131
+ it('未设置/空串 → 回退 opencode', () => {
132
+ expect(resolvePrepareTypes({})).toEqual(['opencode']);
133
+ expect(resolvePrepareTypes({ ZAG_HARNESS_TYPES: ' ' })).toEqual(['opencode']);
134
+ });
135
+
136
+ it('解析逗号分隔、去空去重并保持顺序', () => {
137
+ expect(resolvePrepareTypes({ ZAG_HARNESS_TYPES: 'opencode, deepseek_harness ,opencode' })).toEqual([
138
+ 'opencode',
139
+ 'deepseek_harness',
140
+ ]);
141
+ expect(resolvePrepareTypes({ ZAG_HARNESS_TYPES: 'deepseek_harness,opencode' })).toEqual([
142
+ 'deepseek_harness',
143
+ 'opencode',
144
+ ]);
145
+ });
146
+
147
+ it('白名单过滤 kimi_code / 未知类型;过滤后为空回退 opencode', () => {
148
+ expect(resolvePrepareTypes({ ZAG_HARNESS_TYPES: 'kimi_code,deepseek_harness' })).toEqual([
149
+ 'deepseek_harness',
150
+ ]);
151
+ expect(resolvePrepareTypes({ ZAG_HARNESS_TYPES: 'kimi_code,bogus' })).toEqual(['opencode']);
152
+ });
153
+ });
@@ -27,6 +27,32 @@ export class HarnessEnvError extends Error {
27
27
  }
28
28
  }
29
29
 
30
+ /** `harness prepare` 可处理的 harness 类型(与 `ZAG_HARNESS_TYPES` 的 harness slug 对齐)。 */
31
+ export const PREPARE_HARNESS_TYPES = ['opencode', 'deepseek_harness'] as const;
32
+
33
+ export type PrepareHarnessType = (typeof PREPARE_HARNESS_TYPES)[number];
34
+
35
+ /**
36
+ * 解析 `ZAG_HARNESS_TYPES`(计划 §3 B5):
37
+ *
38
+ * - 逗号分隔、trim、去重,保持输入顺序;
39
+ * - 白名单过滤(`kimi_code` 等无 prepare 步骤的类型忽略);
40
+ * - 未设置/空串/过滤后为空 → `['opencode']`(旧 worker 手工执行零退化)。
41
+ */
42
+ export function resolvePrepareTypes(env: NodeJS.ProcessEnv = process.env): PrepareHarnessType[] {
43
+ const raw = typeof env.ZAG_HARNESS_TYPES === 'string' ? env.ZAG_HARNESS_TYPES : '';
44
+ const allowed = new Set<string>(PREPARE_HARNESS_TYPES);
45
+ const types: PrepareHarnessType[] = [];
46
+ const seen = new Set<string>();
47
+ for (const item of raw.split(',')) {
48
+ const value = item.trim();
49
+ if (!value || seen.has(value) || !allowed.has(value)) continue;
50
+ seen.add(value);
51
+ types.push(value as PrepareHarnessType);
52
+ }
53
+ return types.length > 0 ? types : ['opencode'];
54
+ }
55
+
30
56
  function nonEmpty(value: string | undefined): string {
31
57
  return typeof value === 'string' ? value.trim() : '';
32
58
  }
@@ -45,6 +45,14 @@ export function extractVersion(stdout: string, stderr = ''): string | undefined
45
45
  return line.replace(/^v/i, '');
46
46
  }
47
47
 
48
+ /**
49
+ * 版本串归一化:取最后一个空白分隔段(容忍 `dsh 0.1.2` / `v0.1.2` 等输出前缀),
50
+ * 去掉 `v` 前缀。预发布段(如 `0.1.2-alpha.2`)原样保留。
51
+ */
52
+ export function normalizeCliVersion(version: string): string {
53
+ return (version.trim().split(/\s+/).pop() ?? '').replace(/^v/i, '');
54
+ }
55
+
48
56
  /**
49
57
  * `opencode --version` 硬校验(`opencode -v` 仅作旧版 CLI 的兼容探测)。
50
58
  *
@@ -60,8 +68,7 @@ export async function verifyOpencodeCli(
60
68
  ): Promise<string> {
61
69
  const failures: string[] = [];
62
70
 
63
- const normalizeVersion = (version: string): string =>
64
- (version.trim().split(/\s+/).pop() ?? '').replace(/^v/i, '');
71
+ const normalizeVersion = normalizeCliVersion;
65
72
 
66
73
  const ensureExpected = (version: string): string => {
67
74
  if (expectedVersion && normalizeVersion(version) !== normalizeVersion(expectedVersion)) {
@@ -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
 
@@ -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
138
  expect(summary).toContain('workspace=/root/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
  });