agent-gear 2.7.1 → 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 (96) hide show
  1. package/AGENTS.md +22 -1
  2. package/dist/acp/auth-gate.d.ts +62 -0
  3. package/dist/acp/auth-gate.d.ts.map +1 -0
  4. package/dist/acp/auth-gate.js +110 -0
  5. package/dist/acp/auth-gate.js.map +1 -0
  6. package/dist/acp/auth-gate.test.d.ts +2 -0
  7. package/dist/acp/auth-gate.test.d.ts.map +1 -0
  8. package/dist/acp/auth-gate.test.js +126 -0
  9. package/dist/acp/auth-gate.test.js.map +1 -0
  10. package/dist/acp/detector.d.ts +2 -0
  11. package/dist/acp/detector.d.ts.map +1 -1
  12. package/dist/acp/detector.js +18 -3
  13. package/dist/acp/detector.js.map +1 -1
  14. package/dist/acp/detector.test.d.ts +2 -0
  15. package/dist/acp/detector.test.d.ts.map +1 -0
  16. package/dist/acp/detector.test.js +50 -0
  17. package/dist/acp/detector.test.js.map +1 -0
  18. package/dist/commands/harness.d.ts +5 -1
  19. package/dist/commands/harness.d.ts.map +1 -1
  20. package/dist/commands/harness.js +7 -3
  21. package/dist/commands/harness.js.map +1 -1
  22. package/dist/harness/dsh-cli.d.ts +17 -0
  23. package/dist/harness/dsh-cli.d.ts.map +1 -0
  24. package/dist/harness/dsh-cli.js +51 -0
  25. package/dist/harness/dsh-cli.js.map +1 -0
  26. package/dist/harness/dsh-cli.test.d.ts +2 -0
  27. package/dist/harness/dsh-cli.test.d.ts.map +1 -0
  28. package/dist/harness/dsh-cli.test.js +51 -0
  29. package/dist/harness/dsh-cli.test.js.map +1 -0
  30. package/dist/harness/dsh-config.atomic-failure.test.d.ts +2 -0
  31. package/dist/harness/dsh-config.atomic-failure.test.d.ts.map +1 -0
  32. package/dist/harness/dsh-config.atomic-failure.test.js +35 -0
  33. package/dist/harness/dsh-config.atomic-failure.test.js.map +1 -0
  34. package/dist/harness/dsh-config.d.ts +46 -0
  35. package/dist/harness/dsh-config.d.ts.map +1 -0
  36. package/dist/harness/dsh-config.js +228 -0
  37. package/dist/harness/dsh-config.js.map +1 -0
  38. package/dist/harness/dsh-config.test.d.ts +2 -0
  39. package/dist/harness/dsh-config.test.d.ts.map +1 -0
  40. package/dist/harness/dsh-config.test.js +229 -0
  41. package/dist/harness/dsh-config.test.js.map +1 -0
  42. package/dist/harness/env.d.ts +11 -0
  43. package/dist/harness/env.d.ts.map +1 -1
  44. package/dist/harness/env.js +23 -0
  45. package/dist/harness/env.js.map +1 -1
  46. package/dist/harness/env.test.js +23 -1
  47. package/dist/harness/env.test.js.map +1 -1
  48. package/dist/harness/kimi-login.d.ts +124 -0
  49. package/dist/harness/kimi-login.d.ts.map +1 -0
  50. package/dist/harness/kimi-login.js +263 -0
  51. package/dist/harness/kimi-login.js.map +1 -0
  52. package/dist/harness/kimi-login.test.d.ts +2 -0
  53. package/dist/harness/kimi-login.test.d.ts.map +1 -0
  54. package/dist/harness/kimi-login.test.js +193 -0
  55. package/dist/harness/kimi-login.test.js.map +1 -0
  56. package/dist/harness/opencode-cli.d.ts +5 -0
  57. package/dist/harness/opencode-cli.d.ts.map +1 -1
  58. package/dist/harness/opencode-cli.js +8 -1
  59. package/dist/harness/opencode-cli.js.map +1 -1
  60. package/dist/harness/prepare.d.ts +27 -9
  61. package/dist/harness/prepare.d.ts.map +1 -1
  62. package/dist/harness/prepare.js +67 -23
  63. package/dist/harness/prepare.js.map +1 -1
  64. package/dist/harness/prepare.test.js +110 -3
  65. package/dist/harness/prepare.test.js.map +1 -1
  66. package/dist/socketio-client.auth-gate.test.d.ts +2 -0
  67. package/dist/socketio-client.auth-gate.test.d.ts.map +1 -0
  68. package/dist/socketio-client.auth-gate.test.js +179 -0
  69. package/dist/socketio-client.auth-gate.test.js.map +1 -0
  70. package/dist/socketio-client.d.ts +7 -0
  71. package/dist/socketio-client.d.ts.map +1 -1
  72. package/dist/socketio-client.js +32 -2
  73. package/dist/socketio-client.js.map +1 -1
  74. package/package.json +3 -2
  75. package/src/acp/auth-gate.test.ts +145 -0
  76. package/src/acp/auth-gate.ts +144 -0
  77. package/src/acp/detector.test.ts +64 -0
  78. package/src/acp/detector.ts +18 -3
  79. package/src/commands/harness.ts +9 -3
  80. package/src/harness/dsh-cli.test.ts +58 -0
  81. package/src/harness/dsh-cli.ts +67 -0
  82. package/src/harness/dsh-config.atomic-failure.test.ts +51 -0
  83. package/src/harness/dsh-config.test.ts +275 -0
  84. package/src/harness/dsh-config.ts +280 -0
  85. package/src/harness/env.test.ts +32 -1
  86. package/src/harness/env.ts +26 -0
  87. package/src/harness/kimi-login.test.ts +222 -0
  88. package/src/harness/kimi-login.ts +328 -0
  89. package/src/harness/opencode-cli.ts +9 -2
  90. package/src/harness/prepare.test.ts +129 -3
  91. package/src/harness/prepare.ts +103 -27
  92. package/src/socketio-client.auth-gate.test.ts +200 -0
  93. package/src/socketio-client.ts +36 -2
  94. package/tests/acp-detector.test.ts +28 -8
  95. package/tests/commands/harness.test.ts +17 -7
  96. 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
  }
@@ -0,0 +1,222 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { EventEmitter } from 'node:events';
3
+ import {
4
+ KimiLoginFlow,
5
+ classifyExit,
6
+ parseKimiLoginLine,
7
+ resolveKimiLoginWaitMs,
8
+ sanitizeErrorSummary,
9
+ } from './kimi-login.js';
10
+
11
+ /** 实机核对逐字输出(附录 B5;URL/验证码为示例值)。 */
12
+ const DEVICE_FLOW_LINES = [
13
+ 'Opening browser for Kimi device login: https://www.kimi.com/code/authorize_device?user_code=4CQ4-0XIG',
14
+ 'If the browser did not open, paste the URL above and enter code: 4CQ4-0XIG',
15
+ 'Code expires in 1800s.',
16
+ 'Waiting for authorization to complete…',
17
+ ];
18
+
19
+ interface FakeChild extends EventEmitter {
20
+ stdout: EventEmitter;
21
+ stderr: EventEmitter;
22
+ kill: ReturnType<typeof vi.fn>;
23
+ killed: NodeJS.Signals | null;
24
+ }
25
+
26
+ function createFakeChild(): FakeChild {
27
+ const child = new EventEmitter() as FakeChild;
28
+ child.stdout = new EventEmitter();
29
+ child.stderr = new EventEmitter();
30
+ child.killed = null;
31
+ child.kill = vi.fn((signal: NodeJS.Signals) => {
32
+ child.killed = signal;
33
+ return true;
34
+ });
35
+ return child;
36
+ }
37
+
38
+ function setup(options: { waitMs?: number } = {}) {
39
+ const child = createFakeChild();
40
+ const spawnFn = vi.fn(() => child);
41
+ const flow = new KimiLoginFlow({
42
+ spawnFn: spawnFn as never,
43
+ ...(options.waitMs ? { waitMs: options.waitMs } : {}),
44
+ });
45
+ return { child, spawnFn, flow };
46
+ }
47
+
48
+ /** 等待流式回调跑完(setImmediate 让出微任务队列)。 */
49
+ const tick = () => new Promise((resolve) => setImmediate(resolve));
50
+
51
+ function emitLines(child: FakeChild, lines: string[], stream: 'stdout' | 'stderr' = 'stderr', eol = '\n'): void {
52
+ child[stream].emit('data', Buffer.from(`${lines.join(eol)}${eol}`));
53
+ }
54
+
55
+ describe('parseKimiLoginLine', () => {
56
+ it('T-KL1: 已登录行解析 providerName(仅日志/事件透出,前端不展示)', () => {
57
+ expect(parseKimiLoginLine('Logged in to managed:kimi-code.')).toEqual({
58
+ kind: 'logged-in',
59
+ account: 'managed:kimi-code',
60
+ });
61
+ });
62
+
63
+ it('T-KL2: 设备码行逐字命中 url / 验证码 / 有效期 / 等待', () => {
64
+ expect(parseKimiLoginLine(DEVICE_FLOW_LINES[0])).toEqual({
65
+ kind: 'device-url',
66
+ url: 'https://www.kimi.com/code/authorize_device?user_code=4CQ4-0XIG',
67
+ });
68
+ expect(parseKimiLoginLine(DEVICE_FLOW_LINES[1])).toEqual({ kind: 'user-code', userCode: '4CQ4-0XIG' });
69
+ expect(parseKimiLoginLine('Code expires in 1800s.')).toEqual({
70
+ kind: 'expires-in',
71
+ expiresInSeconds: 1800,
72
+ });
73
+ expect(parseKimiLoginLine('Waiting for authorization to complete…')).toEqual({ kind: 'waiting' });
74
+ expect(parseKimiLoginLine(' ')).toBeNull();
75
+ });
76
+ });
77
+
78
+ describe('classifyExit', () => {
79
+ it('exit 0 → logged-in;cancel 标志优先于 exit 0', () => {
80
+ expect(classifyExit({ code: 0, account: 'managed:kimi-code' })).toEqual({
81
+ state: 'logged-in',
82
+ account: 'managed:kimi-code',
83
+ });
84
+ expect(classifyExit({ code: 0, cancelled: true })).toEqual({ state: 'failed', reason: 'cancelled' });
85
+ });
86
+
87
+ it('Login cancelled 文案 / 过期 / 其它 → cancelled / timeout / error', () => {
88
+ expect(classifyExit({ code: 1, cancelMessage: true })).toEqual({ state: 'failed', reason: 'cancelled' });
89
+ expect(classifyExit({ code: 1, expiresAt: 1000, now: 1000 })).toEqual({
90
+ state: 'failed',
91
+ reason: 'timeout',
92
+ });
93
+ const failed = classifyExit({ code: 1, errorMessage: 'boom' });
94
+ expect(failed).toEqual({ state: 'failed', reason: 'error', error: 'boom' });
95
+ });
96
+
97
+ it('脱敏摘要 ≤200 且去控制字符', () => {
98
+ const long = `\u001b[31m${'x'.repeat(300)}\n`;
99
+ expect(sanitizeErrorSummary(long)).toHaveLength(200);
100
+ expect(classifyExit({ code: null, signal: 'SIGKILL' })).toEqual({
101
+ state: 'failed',
102
+ reason: 'error',
103
+ error: 'kimi login exited with SIGKILL',
104
+ });
105
+ });
106
+
107
+ it('KIMI_LOGIN_WAIT_MS 可 env 覆盖', () => {
108
+ expect(resolveKimiLoginWaitMs({})).toBe(1_800_000);
109
+ expect(resolveKimiLoginWaitMs({ KIMI_LOGIN_WAIT_MS: '60000' })).toBe(60_000);
110
+ expect(resolveKimiLoginWaitMs({ KIMI_LOGIN_WAIT_MS: '-1' })).toBe(1_800_000);
111
+ });
112
+ });
113
+
114
+ describe('KimiLoginFlow', () => {
115
+ it('T-KL1: 已登录快速路径 exit 0 → logged-in 且不触发 onDeviceFlow', async () => {
116
+ const { child, flow, spawnFn } = setup();
117
+ const onDeviceFlow = vi.fn();
118
+ const pending = flow.run({ onDeviceFlow });
119
+ expect(spawnFn).toHaveBeenCalledWith('kimi', ['login'], expect.objectContaining({
120
+ stdio: ['ignore', 'pipe', 'pipe'],
121
+ }));
122
+ emitLines(child, ['Logged in to managed:kimi-code.']);
123
+ child.emit('exit', 0, null);
124
+ await expect(pending).resolves.toEqual({ state: 'logged-in', account: 'managed:kimi-code' });
125
+ expect(onDeviceFlow).not.toHaveBeenCalled();
126
+ });
127
+
128
+ it('T-KL2: 设备码首次命中只上抛一次(重复 waiting 不重复)', async () => {
129
+ const { child, flow } = setup();
130
+ const onDeviceFlow = vi.fn();
131
+ const pending = flow.run({ onDeviceFlow });
132
+ emitLines(child, DEVICE_FLOW_LINES);
133
+ emitLines(child, [DEVICE_FLOW_LINES[3]]);
134
+ expect(onDeviceFlow).toHaveBeenCalledTimes(1);
135
+ expect(onDeviceFlow).toHaveBeenCalledWith({
136
+ url: 'https://www.kimi.com/code/authorize_device?user_code=4CQ4-0XIG',
137
+ userCode: '4CQ4-0XIG',
138
+ expiresInSeconds: 1800,
139
+ });
140
+ child.emit('exit', 0, null);
141
+ await expect(pending).resolves.toEqual({ state: 'logged-in' });
142
+ });
143
+
144
+ it('T-KL3: stdout/stderr 交错 + \\r\\n 仍能解析', async () => {
145
+ const { child, flow } = setup();
146
+ const onDeviceFlow = vi.fn();
147
+ const pending = flow.run({ onDeviceFlow });
148
+ emitLines(child, [DEVICE_FLOW_LINES[0]], 'stdout', '\r\n');
149
+ emitLines(child, [DEVICE_FLOW_LINES[1], DEVICE_FLOW_LINES[2]], 'stderr', '\r\n');
150
+ await tick();
151
+ expect(onDeviceFlow).toHaveBeenCalledWith(expect.objectContaining({ userCode: '4CQ4-0XIG' }));
152
+ emitLines(child, [DEVICE_FLOW_LINES[3]], 'stdout', '\r\n');
153
+ child.emit('exit', 0, null);
154
+ await expect(pending).resolves.toEqual({ state: 'logged-in' });
155
+ });
156
+
157
+ it('T-KL4: 无特征输出 + exit 1 → failed(error),摘要 ≤200 且脱敏', async () => {
158
+ const { child, flow } = setup();
159
+ const pending = flow.run();
160
+ emitLines(child, [`Login failed: ${'bad '.repeat(80)}`]);
161
+ child.emit('exit', 1, null);
162
+ const outcome = await pending;
163
+ expect(outcome.state).toBe('failed');
164
+ if (outcome.state !== 'failed') return;
165
+ expect(outcome.reason).toBe('error');
166
+ expect(outcome.error!.length).toBeLessThanOrEqual(200);
167
+ expect(outcome.error).not.toContain('\n');
168
+ });
169
+
170
+ it('T-KL5: cancel() → SIGTERM + failed(cancelled),不误判 error', async () => {
171
+ const { child, flow } = setup();
172
+ const pending = flow.run();
173
+ emitLines(child, DEVICE_FLOW_LINES.slice(0, 2));
174
+ flow.cancel();
175
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
176
+ child.emit('exit', null, 'SIGTERM');
177
+ await expect(pending).resolves.toEqual({ state: 'failed', reason: 'cancelled' });
178
+ });
179
+
180
+ it('T-KL6: 等待上限到期 → 杀进程 + failed(timeout)', async () => {
181
+ vi.useFakeTimers();
182
+ try {
183
+ const { child, flow } = setup({ waitMs: 1000 });
184
+ const pending = flow.run();
185
+ emitLines(child, DEVICE_FLOW_LINES.slice(0, 2));
186
+ vi.advanceTimersByTime(1000);
187
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
188
+ await expect(pending).resolves.toEqual({ state: 'failed', reason: 'timeout' });
189
+ } finally {
190
+ vi.useRealTimers();
191
+ }
192
+ });
193
+
194
+ it('T-KL7: 非 http(s)/超长 url、超长 code → failed(error),不产生 device-flow', async () => {
195
+ const cases = [
196
+ ['Opening browser for Kimi device login: javascript:alert(1)'],
197
+ [`Opening browser for Kimi device login: https://x.test/${'a'.repeat(2048)}`],
198
+ [DEVICE_FLOW_LINES[0], `enter code: ${'A'.repeat(65)}`],
199
+ ];
200
+ for (const lines of cases) {
201
+ const { child, flow } = setup();
202
+ const onDeviceFlow = vi.fn();
203
+ const pending = flow.run({ onDeviceFlow });
204
+ emitLines(child, lines);
205
+ child.emit('exit', 1, null);
206
+ const outcome = await pending;
207
+ expect(outcome.state).toBe('failed');
208
+ expect(onDeviceFlow).not.toHaveBeenCalled();
209
+ }
210
+ });
211
+
212
+ it('T-KL8: 无换行超长输出不无界增长(8 KiB 截断)', async () => {
213
+ const { child, flow } = setup();
214
+ const onLineMatched = vi.fn();
215
+ const pending = flow.run({ onLineMatched });
216
+ child.stderr.emit('data', Buffer.from('x'.repeat(64 * 1024)));
217
+ child.stderr.emit('data', Buffer.from('\n'));
218
+ expect(onLineMatched).not.toHaveBeenCalled();
219
+ child.emit('exit', 1, null);
220
+ await expect(pending).resolves.toMatchObject({ state: 'failed', reason: 'error' });
221
+ });
222
+ });