agent-gear 2.19.0 → 2.21.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 (77) hide show
  1. package/AGENTS.md +50 -10
  2. package/dist/cloud-host/supervisor.js +1 -1
  3. package/dist/cloud-host/supervisor.js.map +1 -1
  4. package/dist/cloud-host/supervisor.test.js +24 -0
  5. package/dist/cloud-host/supervisor.test.js.map +1 -1
  6. package/dist/harness/dsh-config.d.ts +11 -1
  7. package/dist/harness/dsh-config.d.ts.map +1 -1
  8. package/dist/harness/dsh-config.js +44 -18
  9. package/dist/harness/dsh-config.js.map +1 -1
  10. package/dist/harness/dsh-config.test.js +150 -1
  11. package/dist/harness/dsh-config.test.js.map +1 -1
  12. package/dist/harness/env.d.ts +10 -2
  13. package/dist/harness/env.d.ts.map +1 -1
  14. package/dist/harness/env.js +30 -5
  15. package/dist/harness/env.js.map +1 -1
  16. package/dist/harness/env.test.js +64 -0
  17. package/dist/harness/env.test.js.map +1 -1
  18. package/dist/harness/model-credentials.d.ts +26 -0
  19. package/dist/harness/model-credentials.d.ts.map +1 -0
  20. package/dist/harness/model-credentials.js +108 -0
  21. package/dist/harness/model-credentials.js.map +1 -0
  22. package/dist/harness/model-credentials.test.d.ts +2 -0
  23. package/dist/harness/model-credentials.test.d.ts.map +1 -0
  24. package/dist/harness/model-credentials.test.js +80 -0
  25. package/dist/harness/model-credentials.test.js.map +1 -0
  26. package/dist/harness/model-providers.d.ts +107 -0
  27. package/dist/harness/model-providers.d.ts.map +1 -0
  28. package/dist/harness/model-providers.js +197 -0
  29. package/dist/harness/model-providers.js.map +1 -0
  30. package/dist/harness/model-providers.test.d.ts +2 -0
  31. package/dist/harness/model-providers.test.d.ts.map +1 -0
  32. package/dist/harness/model-providers.test.js +216 -0
  33. package/dist/harness/model-providers.test.js.map +1 -0
  34. package/dist/harness/opencode-config.d.ts +41 -8
  35. package/dist/harness/opencode-config.d.ts.map +1 -1
  36. package/dist/harness/opencode-config.js +133 -12
  37. package/dist/harness/opencode-config.js.map +1 -1
  38. package/dist/harness/opencode-config.test.js +227 -50
  39. package/dist/harness/opencode-config.test.js.map +1 -1
  40. package/dist/harness/prepare.d.ts +2 -0
  41. package/dist/harness/prepare.d.ts.map +1 -1
  42. package/dist/harness/prepare.js +17 -2
  43. package/dist/harness/prepare.js.map +1 -1
  44. package/dist/harness/prepare.test.js +33 -0
  45. package/dist/harness/prepare.test.js.map +1 -1
  46. package/dist/knowledge-bases.d.ts +7 -15
  47. package/dist/knowledge-bases.d.ts.map +1 -1
  48. package/dist/knowledge-bases.js +40 -70
  49. package/dist/knowledge-bases.js.map +1 -1
  50. package/dist/knowledge-bases.test.js +79 -60
  51. package/dist/knowledge-bases.test.js.map +1 -1
  52. package/dist/socketio-client.d.ts +11 -0
  53. package/dist/socketio-client.d.ts.map +1 -1
  54. package/dist/socketio-client.js +94 -0
  55. package/dist/socketio-client.js.map +1 -1
  56. package/dist/socketio-client.test.js +128 -0
  57. package/dist/socketio-client.test.js.map +1 -1
  58. package/package.json +1 -1
  59. package/src/cloud-host/supervisor.test.ts +32 -0
  60. package/src/cloud-host/supervisor.ts +1 -1
  61. package/src/harness/dsh-config.test.ts +175 -1
  62. package/src/harness/dsh-config.ts +77 -23
  63. package/src/harness/env.test.ts +74 -0
  64. package/src/harness/env.ts +41 -5
  65. package/src/harness/model-credentials.test.ts +133 -0
  66. package/src/harness/model-credentials.ts +119 -0
  67. package/src/harness/model-providers.test.ts +277 -0
  68. package/src/harness/model-providers.ts +289 -0
  69. package/src/harness/opencode-config.test.ts +278 -57
  70. package/src/harness/opencode-config.ts +180 -20
  71. package/src/harness/prepare.test.ts +36 -0
  72. package/src/harness/prepare.ts +20 -2
  73. package/src/knowledge-bases.test.ts +93 -65
  74. package/src/knowledge-bases.ts +43 -78
  75. package/src/socketio-client.test.ts +153 -0
  76. package/src/socketio-client.ts +122 -0
  77. package/tests/agent-gear-upgrade.test.ts +285 -0
@@ -5,6 +5,12 @@
5
5
  * 绝不回显其它 env 的值(尤其 `ZAG_MODEL_API_KEY` 等 secret)。
6
6
  */
7
7
 
8
+ import {
9
+ parseModelProvision,
10
+ projectToLegacy,
11
+ type ModelProvision,
12
+ } from './model-providers.js';
13
+
8
14
  /** harness prepare 需要的环境(已归一)。 */
9
15
  export interface HarnessEnv {
10
16
  /** 模型网关地址(`ZAG_MODEL_BASE_URL`)。 */
@@ -15,6 +21,11 @@ export interface HarnessEnv {
15
21
  modelIds: string[];
16
22
  /** 模型 ID → 最长上下文 token 数(`ZAG_MODEL_CONTEXT_LENGTHS`,可选;缺省 `{}`)。 */
17
23
  modelContextLengths: Record<string, number>;
24
+ /**
25
+ * 运行期模型清单(`ZAG_MODEL_PROVIDERS`,可选):多 vendor 全量替换载荷。
26
+ * 携带时 `modelIds`/`modelContextLengths` 缺省由投影补齐(事件链路与旧服务端双兼容)。
27
+ */
28
+ modelProviders?: ModelProvision;
18
29
  /** 默认工作区(`ZAG_DEFAULT_WORKSPACE`)。 */
19
30
  defaultWorkspace: string;
20
31
  }
@@ -116,9 +127,11 @@ export function parseModelContextLengths(raw: string): Record<string, number> {
116
127
  /**
117
128
  * 读取并校验 harness env。
118
129
  *
119
- * 必需:`ZAG_MODEL_BASE_URL` / `ZAG_MODEL_API_KEY` / `ZAG_MODEL_IDS` / `ZAG_DEFAULT_WORKSPACE`
130
+ * 必需:`ZAG_MODEL_BASE_URL` / `ZAG_MODEL_API_KEY` / `ZAG_DEFAULT_WORKSPACE`,
131
+ * 以及 `ZAG_MODEL_IDS` **或** `ZAG_MODEL_PROVIDERS` 之一
120
132
  * (云电脑 Job env 与 `workload:run.env` 均由 agent-api 注入,缺失说明编排不正确)。
121
- * 可选:`ZAG_MODEL_CONTEXT_LENGTHS`(缺省/空串归一为 `{}`;旧服务端不下发时优雅降级)。
133
+ * 可选:`ZAG_MODEL_CONTEXT_LENGTHS`(缺省/空串归一为 `{}`)、`ZAG_MODEL_PROVIDERS`
134
+ * (多 vendor 清单;`modelIds`/`modelContextLengths` 同时缺省时由投影补齐)。
122
135
  */
123
136
  export function readHarnessEnv(env: NodeJS.ProcessEnv = process.env): HarnessEnv {
124
137
  const missing: string[] = [];
@@ -127,7 +140,8 @@ export function readHarnessEnv(env: NodeJS.ProcessEnv = process.env): HarnessEnv
127
140
  const modelApiKey = nonEmpty(env.ZAG_MODEL_API_KEY);
128
141
  if (!modelApiKey) missing.push('ZAG_MODEL_API_KEY');
129
142
  const rawModelIds = nonEmpty(env.ZAG_MODEL_IDS);
130
- if (!rawModelIds) missing.push('ZAG_MODEL_IDS');
143
+ const rawModelProviders = nonEmpty(env.ZAG_MODEL_PROVIDERS);
144
+ if (!rawModelIds && !rawModelProviders) missing.push('ZAG_MODEL_IDS');
131
145
  const defaultWorkspace = nonEmpty(env.ZAG_DEFAULT_WORKSPACE);
132
146
  if (!defaultWorkspace) missing.push('ZAG_DEFAULT_WORKSPACE');
133
147
 
@@ -137,11 +151,33 @@ export function readHarnessEnv(env: NodeJS.ProcessEnv = process.env): HarnessEnv
137
151
 
138
152
  const rawModelContextLengths = nonEmpty(env.ZAG_MODEL_CONTEXT_LENGTHS);
139
153
 
154
+ let modelProviders: ModelProvision | undefined;
155
+ if (rawModelProviders) {
156
+ try {
157
+ modelProviders = parseModelProvision(rawModelProviders);
158
+ } catch (error) {
159
+ // 只报变量名与字段/索引;不回显原值(可能含模型名)。
160
+ throw new HarnessEnvError(`invalid ZAG_MODEL_PROVIDERS: ${(error as Error).message}`);
161
+ }
162
+ }
163
+
164
+ let modelIds = rawModelIds ? parseModelIds(rawModelIds) : [];
165
+ let modelContextLengths = rawModelContextLengths
166
+ ? parseModelContextLengths(rawModelContextLengths)
167
+ : {};
168
+ // 事件链路/新服务端:只带 modelProviders 时由投影补齐旧字段(与旧产物逐字一致)。
169
+ if (modelProviders && !rawModelIds && !rawModelContextLengths) {
170
+ const legacy = projectToLegacy(modelProviders);
171
+ modelIds = legacy.modelIds;
172
+ modelContextLengths = legacy.modelContextLengths;
173
+ }
174
+
140
175
  return {
141
176
  modelBaseUrl,
142
177
  modelApiKey,
143
- modelIds: parseModelIds(rawModelIds),
144
- modelContextLengths: rawModelContextLengths ? parseModelContextLengths(rawModelContextLengths) : {},
178
+ modelIds,
179
+ modelContextLengths,
180
+ ...(modelProviders ? { modelProviders } : {}),
145
181
  defaultWorkspace,
146
182
  };
147
183
  }
@@ -0,0 +1,133 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
+ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { resolveConfiguredCredentials } from './model-credentials.js';
6
+
7
+ /**
8
+ * 运行期模型下发的凭据兜底读取(计划 Phase 4 / 返工 P2-4):
9
+ * 进程 env 优先;缺失项从已写入的 opencode/dsh 配置逐项回读;
10
+ * 文件缺失/损坏一律收敛为空串,不抛错、不回显原值。
11
+ */
12
+ describe('resolveConfiguredCredentials', () => {
13
+ let root: string;
14
+ let configDir: string;
15
+ let dshHome: string;
16
+
17
+ beforeEach(async () => {
18
+ root = await mkdtemp(join(tmpdir(), 'zag-model-credentials-'));
19
+ configDir = join(root, 'opencode');
20
+ dshHome = join(root, 'dsh');
21
+ await mkdir(configDir, { recursive: true });
22
+ await mkdir(join(dshHome, 'profiles', 'acp'), { recursive: true });
23
+ });
24
+
25
+ afterEach(async () => {
26
+ await rm(root, { recursive: true, force: true });
27
+ });
28
+
29
+ it('env 同时具备时短路,不读取任何文件', async () => {
30
+ const result = await resolveConfiguredCredentials({
31
+ env: { ZAG_MODEL_BASE_URL: 'https://env.example.com/v1', ZAG_MODEL_API_KEY: 'sk-env' },
32
+ configDir,
33
+ dshHome,
34
+ });
35
+ expect(result).toEqual({
36
+ modelBaseUrl: 'https://env.example.com/v1',
37
+ modelApiKey: 'sk-env',
38
+ });
39
+ });
40
+
41
+ it('逐项兜底:env 仅 baseURL,apiKey 从已写入的 opencode 配置回读', async () => {
42
+ await writeFile(
43
+ join(configDir, 'opencode.jsonc'),
44
+ JSON.stringify(
45
+ { providers: { zag: { settings: { baseURL: 'https://file.example.com/v1', apiKey: 'sk-file' } } } },
46
+ null,
47
+ 2,
48
+ ),
49
+ 'utf-8',
50
+ );
51
+
52
+ const result = await resolveConfiguredCredentials({
53
+ env: { ZAG_MODEL_BASE_URL: 'https://env.example.com/v1' },
54
+ configDir,
55
+ dshHome,
56
+ });
57
+ expect(result).toEqual({
58
+ modelBaseUrl: 'https://env.example.com/v1',
59
+ modelApiKey: 'sk-file',
60
+ });
61
+ });
62
+
63
+ it('无 env 时优先 opencode(jsonc 缺失 → 同名 .json)', async () => {
64
+ await writeFile(
65
+ join(configDir, 'opencode.json'),
66
+ JSON.stringify(
67
+ { providers: { zag: { settings: { baseURL: 'https://json.example.com/v1', apiKey: 'sk-json' } } } },
68
+ null,
69
+ 2,
70
+ ),
71
+ 'utf-8',
72
+ );
73
+
74
+ await expect(
75
+ resolveConfiguredCredentials({ env: {}, configDir, dshHome }),
76
+ ).resolves.toEqual({
77
+ modelBaseUrl: 'https://json.example.com/v1',
78
+ modelApiKey: 'sk-json',
79
+ });
80
+ });
81
+
82
+ it('opencode 不可用/损坏时回退 dsh(cordis baseURL + credentials refs),逐项补齐', async () => {
83
+ await writeFile(join(configDir, 'opencode.jsonc'), '{ not valid jsonc', 'utf-8');
84
+ await writeFile(
85
+ join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'),
86
+ ['- id: llm-pi-ai', ' config:', ' providers:', ' zag:', ' baseURL: https://dsh.example.com/v1'].join('\n'),
87
+ 'utf-8',
88
+ );
89
+ await writeFile(
90
+ join(dshHome, '.credentials.yaml'),
91
+ ['version: 1', 'refs:', ' ZAG_MODEL_API_KEY: sk-dsh'].join('\n'),
92
+ 'utf-8',
93
+ );
94
+
95
+ await expect(
96
+ resolveConfiguredCredentials({ env: {}, configDir, dshHome }),
97
+ ).resolves.toEqual({
98
+ modelBaseUrl: 'https://dsh.example.com/v1',
99
+ modelApiKey: 'sk-dsh',
100
+ });
101
+ });
102
+
103
+ it('全部缺失/损坏时收敛为空串(不抛错)', async () => {
104
+ await writeFile(join(dshHome, '.credentials.yaml'), 'refs: [unexpected, list]', 'utf-8');
105
+
106
+ await expect(
107
+ resolveConfiguredCredentials({ env: {}, configDir, dshHome }),
108
+ ).resolves.toEqual({ modelBaseUrl: '', modelApiKey: '' });
109
+ });
110
+
111
+ it('trim 后为空的环境变量视为缺失,回读配置', async () => {
112
+ await writeFile(
113
+ join(configDir, 'opencode.jsonc'),
114
+ JSON.stringify(
115
+ { providers: { zag: { settings: { baseURL: 'https://file.example.com/v1', apiKey: 'sk-file' } } } },
116
+ null,
117
+ 2,
118
+ ),
119
+ 'utf-8',
120
+ );
121
+
122
+ await expect(
123
+ resolveConfiguredCredentials({
124
+ env: { ZAG_MODEL_BASE_URL: ' ', ZAG_MODEL_API_KEY: '' },
125
+ configDir,
126
+ dshHome,
127
+ }),
128
+ ).resolves.toEqual({
129
+ modelBaseUrl: 'https://file.example.com/v1',
130
+ modelApiKey: 'sk-file',
131
+ });
132
+ });
133
+ });
@@ -0,0 +1,119 @@
1
+ /**
2
+ * 运行期模型下发的凭据兜底读取。
3
+ *
4
+ * 云电脑 Job env **不携带**模型 Key/BaseURL(只经 `workload:run.env` 注入脚本进程),
5
+ * 因此 `harness:models` 事件链路优先取进程 env,其次回读**已写入的** harness 配置:
6
+ *
7
+ * - `opencode.jsonc|json` 的 `providers.zag.settings`;
8
+ * - `cordis.patch.yml` 的 `llm-pi-ai.config.providers.zag.baseURL` +
9
+ * `.credentials.yaml` 的 `refs.ZAG_MODEL_API_KEY`。
10
+ *
11
+ * 只读、不写;任何读取失败都收敛为「缺失」,由调用方按变量名报错。
12
+ */
13
+
14
+ import { readFile } from 'node:fs/promises';
15
+ import { homedir } from 'node:os';
16
+ import { join } from 'node:path';
17
+ import { parse as parseJsonc } from 'jsonc-parser';
18
+ import { parse as parseYaml } from 'yaml';
19
+ import { defaultDshHome } from './dsh-config.js';
20
+ import { defaultConfigDir } from './opencode-config.js';
21
+
22
+ /** 运行期重写需要的网关凭据(禁止打印)。 */
23
+ export interface ConfiguredModelCredentials {
24
+ modelBaseUrl: string;
25
+ modelApiKey: string;
26
+ }
27
+
28
+ function isRecord(value: unknown): value is Record<string, unknown> {
29
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
30
+ }
31
+
32
+ function nonEmptyString(value: unknown): string {
33
+ return typeof value === 'string' ? value.trim() : '';
34
+ }
35
+
36
+ function readOpencodeCredentials(configDir: string): Promise<Partial<ConfiguredModelCredentials>> {
37
+ return (async () => {
38
+ for (const fileName of ['opencode.jsonc', 'opencode.json']) {
39
+ try {
40
+ const text = await readFile(join(configDir, fileName), 'utf-8');
41
+ const parsed = parseJsonc(text, [], { allowTrailingComma: true }) as unknown;
42
+ const providers = isRecord(parsed) ? parsed.providers : undefined;
43
+ const zag = isRecord(providers) ? providers.zag : undefined;
44
+ const settings = isRecord(zag) ? zag.settings : undefined;
45
+ if (!isRecord(settings)) return {};
46
+ return {
47
+ modelBaseUrl: nonEmptyString(settings.baseURL),
48
+ modelApiKey: nonEmptyString(settings.apiKey),
49
+ };
50
+ } catch {
51
+ // 文件不存在/不可读:尝试同名 .json
52
+ }
53
+ }
54
+ return {};
55
+ })();
56
+ }
57
+
58
+ function readDshBaseUrl(patchPath: string): Promise<string> {
59
+ return (async () => {
60
+ try {
61
+ const patch = parseYaml(await readFile(patchPath, 'utf-8')) as unknown;
62
+ if (!Array.isArray(patch)) return '';
63
+ for (const entry of patch) {
64
+ if (!isRecord(entry)) continue;
65
+ const config = entry.config;
66
+ const providers = isRecord(config) ? config.providers : undefined;
67
+ const zag = isRecord(providers) ? providers.zag : undefined;
68
+ const baseURL = isRecord(zag) ? nonEmptyString(zag.baseURL) : '';
69
+ if (baseURL) return baseURL;
70
+ }
71
+ } catch {
72
+ // 忽略:调用方按缺失凭据报错
73
+ }
74
+ return '';
75
+ })();
76
+ }
77
+
78
+ function readDshApiKey(credentialsPath: string): Promise<string> {
79
+ return (async () => {
80
+ try {
81
+ const credentials = parseYaml(await readFile(credentialsPath, 'utf-8')) as unknown;
82
+ const refs = isRecord(credentials) ? credentials.refs : undefined;
83
+ return isRecord(refs) ? nonEmptyString(refs.ZAG_MODEL_API_KEY) : '';
84
+ } catch {
85
+ return '';
86
+ }
87
+ })();
88
+ }
89
+
90
+ /**
91
+ * 解析运行期模型凭据:进程 env 优先,缺失项从已写入配置回读(逐项兜底)。
92
+ */
93
+ export async function resolveConfiguredCredentials(
94
+ options: {
95
+ env?: NodeJS.ProcessEnv;
96
+ configDir?: string;
97
+ dshHome?: string;
98
+ } = {},
99
+ ): Promise<ConfiguredModelCredentials> {
100
+ const source = options.env ?? process.env;
101
+ let modelBaseUrl = nonEmptyString(source.ZAG_MODEL_BASE_URL);
102
+ let modelApiKey = nonEmptyString(source.ZAG_MODEL_API_KEY);
103
+ if (modelBaseUrl && modelApiKey) return { modelBaseUrl, modelApiKey };
104
+
105
+ const opencode = await readOpencodeCredentials(options.configDir ?? defaultConfigDir());
106
+ if (!modelBaseUrl) modelBaseUrl = opencode.modelBaseUrl ?? '';
107
+ if (!modelApiKey) modelApiKey = opencode.modelApiKey ?? '';
108
+ if (modelBaseUrl && modelApiKey) return { modelBaseUrl, modelApiKey };
109
+
110
+ const dshHome = options.dshHome ?? defaultDshHome(source);
111
+ if (!modelBaseUrl) {
112
+ modelBaseUrl = await readDshBaseUrl(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'));
113
+ }
114
+ if (!modelApiKey) {
115
+ modelApiKey = await readDshApiKey(join(dshHome, '.credentials.yaml'));
116
+ }
117
+
118
+ return { modelBaseUrl, modelApiKey };
119
+ }
@@ -0,0 +1,277 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { parse as parseJsonc } from 'jsonc-parser';
5
+ import { parse as parseYaml } from 'yaml';
6
+ import {
7
+ applyModelProvision,
8
+ ModelProvisionError,
9
+ normalizeProvision,
10
+ parseModelProvision,
11
+ projectToLegacy,
12
+ resolveProvision,
13
+ ZAG_DISPLAY_NAME,
14
+ ZAG_VENDOR_ID,
15
+ type ModelProvision,
16
+ } from './model-providers.js';
17
+
18
+ const TMP_BASE = '/tmp/opencode';
19
+
20
+ const VALID = {
21
+ providers: [
22
+ {
23
+ vendorId: 'zag',
24
+ displayName: 'Agent Gear',
25
+ models: [{ id: 'kimi-k2', contextLength: 262144 }, { id: 'model-b' }],
26
+ },
27
+ { vendorId: '65f0a1b2c3d4e5f60718293a', displayName: '我的 OpenAI', models: [{ id: 'gpt-5.1' }] },
28
+ ],
29
+ };
30
+
31
+ async function makeDir(): Promise<string> {
32
+ await mkdir(TMP_BASE, { recursive: true });
33
+ return mkdtemp(join(TMP_BASE, 'model-providers-'));
34
+ }
35
+
36
+ function capture(fn: () => unknown): unknown {
37
+ try {
38
+ fn();
39
+ } catch (error) {
40
+ return error;
41
+ }
42
+ throw new Error('expected an error');
43
+ }
44
+
45
+ describe('parseModelProvision (T-AG-MP1)', () => {
46
+ it('accepts a valid payload (object or JSON string)', () => {
47
+ expect(parseModelProvision(VALID)).toEqual(VALID);
48
+ expect(parseModelProvision(JSON.stringify(VALID))).toEqual(VALID);
49
+ });
50
+
51
+ it('drops unknown fields and trims ids/names', () => {
52
+ const parsed = parseModelProvision({
53
+ extra: true,
54
+ providers: [
55
+ {
56
+ vendorId: ' zag ',
57
+ displayName: ' Agent Gear ',
58
+ models: [{ id: ' m1 ', contextLength: 1000, name: 'ignored' }],
59
+ },
60
+ ],
61
+ });
62
+ expect(parsed).toEqual({
63
+ providers: [{ vendorId: 'zag', displayName: 'Agent Gear', models: [{ id: 'm1', contextLength: 1000 }] }],
64
+ });
65
+ });
66
+
67
+ it('accepts an empty providers array (business invariants are the server’s job)', () => {
68
+ expect(parseModelProvision({ providers: [] })).toEqual({ providers: [] });
69
+ });
70
+
71
+ it('rejects invalid JSON / non-object payloads without echoing the raw value', () => {
72
+ const invalidJson = capture(() => parseModelProvision('not-json-secret-value'));
73
+ expect(invalidJson).toBeInstanceOf(ModelProvisionError);
74
+ expect((invalidJson as Error).message).not.toContain('not-json-secret-value');
75
+
76
+ expect(() => parseModelProvision(null)).toThrowError(/expected a JSON object/);
77
+ expect(() => parseModelProvision([])).toThrowError(/expected a JSON object/);
78
+ expect(() => parseModelProvision({ providers: {} })).toThrowError(/providers must be an array/);
79
+ });
80
+
81
+ it('rejects empty vendorId / displayName / models by field + index only', () => {
82
+ const badVendor = capture(() =>
83
+ parseModelProvision({ providers: [{ vendorId: ' ', displayName: 'x', models: [] }] }),
84
+ );
85
+ expect((badVendor as Error).message).toContain('providers[0].vendorId');
86
+ expect((badVendor as Error).message).not.toContain('displayName');
87
+
88
+ expect(() =>
89
+ parseModelProvision({ providers: [{ vendorId: 'p', displayName: '', models: [] }] }),
90
+ ).toThrowError(/providers\[0\]\.displayName/);
91
+
92
+ expect(() =>
93
+ parseModelProvision({ providers: [{ vendorId: 'p', displayName: 'P', models: 'nope' }] }),
94
+ ).toThrowError(/providers\[0\]\.models must be an array/);
95
+
96
+ expect(() =>
97
+ parseModelProvision({ providers: [{ vendorId: 'p', displayName: 'P', models: [{}] }] }),
98
+ ).toThrowError(/providers\[0\]\.models\[0\]\.id/);
99
+ });
100
+
101
+ it('rejects a non-positive-integer contextLength', () => {
102
+ for (const contextLength of [0, -1, 1.5, '128000', Number.NaN]) {
103
+ expect(() =>
104
+ parseModelProvision({
105
+ providers: [{ vendorId: 'p', displayName: 'P', models: [{ id: 'm', contextLength }] }],
106
+ }),
107
+ ).toThrowError(/providers\[0\]\.models\[0\]\.contextLength must be a positive integer/);
108
+ }
109
+ });
110
+
111
+ it('rejects duplicate vendorIds by index only', () => {
112
+ const error = capture(() =>
113
+ parseModelProvision({
114
+ providers: [
115
+ { vendorId: 'p', displayName: 'P', models: [] },
116
+ { vendorId: 'p', displayName: 'P2', models: [] },
117
+ ],
118
+ }),
119
+ );
120
+ expect(error).toBeInstanceOf(ModelProvisionError);
121
+ expect((error as Error).message).toContain('providers[1].vendorId');
122
+ expect((error as Error).message).not.toContain('P2');
123
+ });
124
+ });
125
+
126
+ describe('projectToLegacy (T-AG-MP1)', () => {
127
+ it('flattens ids in group order and keeps only positive context lengths', () => {
128
+ const provision: ModelProvision = {
129
+ providers: [
130
+ {
131
+ vendorId: 'zag',
132
+ displayName: ZAG_DISPLAY_NAME,
133
+ models: [{ id: 'a', contextLength: 1000 }, { id: 'b' }],
134
+ },
135
+ { vendorId: 'p1', displayName: 'P1', models: [{ id: 'c' }, { id: 'a', contextLength: 5 }] },
136
+ ],
137
+ };
138
+ expect(projectToLegacy(provision)).toEqual({
139
+ modelIds: ['a', 'b', 'c'],
140
+ modelContextLengths: { a: 1000 },
141
+ });
142
+ });
143
+ });
144
+
145
+ describe('resolveProvision (T-AG-MP1)', () => {
146
+ it('prefers modelProviders when present', () => {
147
+ const env = { modelIds: ['ignored'], modelProviders: VALID as ModelProvision };
148
+ const provision = resolveProvision(env);
149
+ expect(provision.providers.map((item) => item.vendorId)).toEqual([
150
+ 'zag',
151
+ '65f0a1b2c3d4e5f60718293a',
152
+ ]);
153
+ });
154
+
155
+ it('falls back to a single zag group with contextLength mapping', () => {
156
+ expect(
157
+ resolveProvision({ modelIds: ['a', 'b'], modelContextLengths: { a: 128000, b: 0 } }),
158
+ ).toEqual({
159
+ providers: [
160
+ {
161
+ vendorId: 'zag',
162
+ displayName: 'Agent Gear',
163
+ models: [{ id: 'a', contextLength: 128000 }, { id: 'b' }],
164
+ },
165
+ ],
166
+ });
167
+ });
168
+
169
+ it('synthesizes an empty zag group without modelIds', () => {
170
+ expect(resolveProvision({})).toEqual({
171
+ providers: [{ vendorId: ZAG_VENDOR_ID, displayName: ZAG_DISPLAY_NAME, models: [] }],
172
+ });
173
+ });
174
+
175
+ it('normalizes group order and forces the zag display name', () => {
176
+ const normalized = normalizeProvision({
177
+ providers: [
178
+ { vendorId: 'p1', displayName: 'P1', models: [] },
179
+ { vendorId: 'zag', displayName: 'ZAG', models: [] },
180
+ ],
181
+ });
182
+ expect(normalized.providers.map((item) => item.vendorId)).toEqual(['zag', 'p1']);
183
+ expect(normalized.providers[0].displayName).toBe('Agent Gear');
184
+ });
185
+ });
186
+
187
+ describe('applyModelProvision (T-AG-MP1)', () => {
188
+ const dirs: string[] = [];
189
+
190
+ afterEach(async () => {
191
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
192
+ });
193
+
194
+ const ENV = { modelBaseUrl: 'http://admin-api:8002/v1', modelApiKey: 'zag_sk_super_secret' };
195
+
196
+ it('rewrites opencode and dsh without touching the CLI checks', async () => {
197
+ const dir = await makeDir();
198
+ dirs.push(dir);
199
+ const configDir = join(dir, 'config');
200
+ const dshHome = join(dir, 'dsh');
201
+
202
+ const result = await applyModelProvision({
203
+ provision: VALID as ModelProvision,
204
+ env: ENV,
205
+ types: ['opencode', 'deepseek_harness'],
206
+ configDir,
207
+ dshHome,
208
+ statePath: join(dir, 'state.json'),
209
+ });
210
+
211
+ expect(result).toEqual({ appliedTypes: ['opencode', 'deepseek_harness'], errors: [] });
212
+
213
+ const config = parseJsonc(await readFile(join(configDir, 'opencode.jsonc'), 'utf-8'));
214
+ expect(config.providers.zag.name).toBe('Agent Gear');
215
+ expect(config.providers['65f0a1b2c3d4e5f60718293a'].name).toBe('我的 OpenAI');
216
+
217
+ const patch = parseYaml(
218
+ await readFile(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'), 'utf-8'),
219
+ ) as Array<Record<string, any>>;
220
+ const providers = patch.find((entry) => entry.id === 'llm-pi-ai')!.config.providers;
221
+ expect(Object.keys(providers)).toEqual(['zag', '65f0a1b2c3d4e5f60718293a']);
222
+ });
223
+
224
+ it('returns no applied types when there is no harness type', async () => {
225
+ const dir = await makeDir();
226
+ dirs.push(dir);
227
+
228
+ const result = await applyModelProvision({
229
+ provision: VALID as ModelProvision,
230
+ env: ENV,
231
+ types: [],
232
+ configDir: join(dir, 'config'),
233
+ dshHome: join(dir, 'dsh'),
234
+ });
235
+
236
+ expect(result).toEqual({ appliedTypes: [], errors: [] });
237
+ });
238
+
239
+ it('reports per-type errors but keeps the other types applied', async () => {
240
+ const dir = await makeDir();
241
+ dirs.push(dir);
242
+ const dshHome = join(dir, 'dsh');
243
+ await mkdir(join(dshHome, 'profiles', 'acp'), { recursive: true });
244
+ await writeFile(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'), '- broken: [\n', 'utf-8');
245
+
246
+ const result = await applyModelProvision({
247
+ provision: VALID as ModelProvision,
248
+ env: ENV,
249
+ types: ['opencode', 'deepseek_harness'],
250
+ configDir: join(dir, 'config'),
251
+ dshHome,
252
+ statePath: join(dir, 'state.json'),
253
+ });
254
+
255
+ expect(result.appliedTypes).toEqual(['opencode']);
256
+ expect(result.errors).toHaveLength(1);
257
+ expect(result.errors[0].type).toBe('deepseek_harness');
258
+ expect(result.errors[0].message).not.toContain(ENV.modelApiKey);
259
+ });
260
+
261
+ it('fails every type when the gateway credentials are missing', async () => {
262
+ const dir = await makeDir();
263
+ dirs.push(dir);
264
+
265
+ const result = await applyModelProvision({
266
+ provision: VALID as ModelProvision,
267
+ env: { modelBaseUrl: '', modelApiKey: '' },
268
+ types: ['opencode', 'deepseek_harness'],
269
+ configDir: join(dir, 'config'),
270
+ dshHome: join(dir, 'dsh'),
271
+ });
272
+
273
+ expect(result.appliedTypes).toEqual([]);
274
+ expect(result.errors.map((item) => item.type)).toEqual(['opencode', 'deepseek_harness']);
275
+ expect(result.errors[0].message).toContain('ZAG_MODEL_BASE_URL');
276
+ });
277
+ });