agent-gear 2.24.0 → 2.26.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.
- package/AGENTS.md +43 -11
- package/dist/acp/auth-gate.d.ts +35 -19
- package/dist/acp/auth-gate.d.ts.map +1 -1
- package/dist/acp/auth-gate.js +59 -41
- package/dist/acp/auth-gate.js.map +1 -1
- package/dist/acp/auth-gate.test.js +53 -56
- package/dist/acp/auth-gate.test.js.map +1 -1
- package/dist/acp/bridge.d.ts +12 -2
- package/dist/acp/bridge.d.ts.map +1 -1
- package/dist/acp/bridge.js +50 -10
- package/dist/acp/bridge.js.map +1 -1
- package/dist/acp/bridge.test.js +114 -0
- package/dist/acp/bridge.test.js.map +1 -1
- package/dist/acp/capabilities.d.ts.map +1 -1
- package/dist/acp/capabilities.js +2 -4
- package/dist/acp/capabilities.js.map +1 -1
- package/dist/acp/capabilities.test.js +2 -2
- package/dist/acp/capabilities.test.js.map +1 -1
- package/dist/acp/sync-bridge.d.ts.map +1 -1
- package/dist/acp/sync-bridge.js +2 -1
- package/dist/acp/sync-bridge.js.map +1 -1
- package/dist/harness/kimi-login.d.ts +44 -3
- package/dist/harness/kimi-login.d.ts.map +1 -1
- package/dist/harness/kimi-login.js +133 -4
- package/dist/harness/kimi-login.js.map +1 -1
- package/dist/harness/kimi-login.test.js +54 -1
- package/dist/harness/kimi-login.test.js.map +1 -1
- package/dist/socketio-client.auth-gate.test.js +48 -60
- package/dist/socketio-client.auth-gate.test.js.map +1 -1
- package/dist/socketio-client.d.ts.map +1 -1
- package/dist/socketio-client.js +79 -10
- package/dist/socketio-client.js.map +1 -1
- package/dist/version.d.ts +9 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +10 -0
- package/dist/version.js.map +1 -0
- package/dist/version.test.d.ts +2 -0
- package/dist/version.test.d.ts.map +1 -0
- package/dist/version.test.js +27 -0
- package/dist/version.test.js.map +1 -0
- package/dist/worktree-handler.test.js +26 -0
- package/dist/worktree-handler.test.js.map +1 -1
- package/package.json +1 -1
- package/src/acp/auth-gate.test.ts +55 -58
- package/src/acp/auth-gate.ts +73 -43
- package/src/acp/bridge.test.ts +138 -0
- package/src/acp/bridge.ts +57 -10
- package/src/acp/capabilities.test.ts +2 -2
- package/src/acp/capabilities.ts +2 -4
- package/src/acp/sync-bridge.ts +2 -1
- package/src/harness/kimi-login.test.ts +60 -0
- package/src/harness/kimi-login.ts +149 -4
- package/src/socketio-client.auth-gate.test.ts +49 -60
- package/src/socketio-client.ts +97 -12
- package/src/version.test.ts +36 -0
- package/src/version.ts +13 -0
- package/src/worktree-handler.test.ts +31 -0
- package/tests/acp-bridge.test.ts +32 -1
- package/tests/acp-sync-bridge.test.ts +17 -1
- package/tests/socketio-client.test.ts +138 -0
package/src/acp/bridge.ts
CHANGED
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
} from './capabilities.js';
|
|
10
10
|
import { logger as rootLogger, type ObservationLogger } from '../observability/logger.js';
|
|
11
11
|
import { withSpan } from '../observability/trace.js';
|
|
12
|
+
import { CONTROLLER_VERSION } from '../version.js';
|
|
12
13
|
|
|
13
14
|
const ACP_PROTOCOL_VERSION = 1;
|
|
14
15
|
|
|
@@ -49,10 +50,15 @@ interface QueuedInput {
|
|
|
49
50
|
|
|
50
51
|
/** acp:message parts 元素(契约 agent-session-websocket.md §2.6 AcpPromptPart) */
|
|
51
52
|
export interface AcpPromptPart {
|
|
52
|
-
type: 'text' | 'image';
|
|
53
|
+
type: 'text' | 'image' | 'audio' | 'resource' | 'resource_link';
|
|
53
54
|
text?: string;
|
|
54
55
|
data?: string;
|
|
55
56
|
mimeType?: string;
|
|
57
|
+
uri?: string;
|
|
58
|
+
name?: string;
|
|
59
|
+
title?: string;
|
|
60
|
+
description?: string;
|
|
61
|
+
size?: number;
|
|
56
62
|
}
|
|
57
63
|
|
|
58
64
|
export interface SessionConfigOptionData {
|
|
@@ -178,6 +184,38 @@ export function extractConfigOptions(
|
|
|
178
184
|
});
|
|
179
185
|
}
|
|
180
186
|
|
|
187
|
+
/**
|
|
188
|
+
* 把 AcpPromptPart 映射为 ACP ContentBlock(契约 §2.6)。
|
|
189
|
+
* 非文本类型与 text/image 同口径保序;未知类型降级为文本块(防御旧上游)。
|
|
190
|
+
*/
|
|
191
|
+
export function mapPromptPart(part: AcpPromptPart): acp.ContentBlock {
|
|
192
|
+
switch (part.type) {
|
|
193
|
+
case 'image':
|
|
194
|
+
return { type: 'image', data: part.data ?? '', mimeType: part.mimeType ?? 'image/png' };
|
|
195
|
+
case 'audio':
|
|
196
|
+
return { type: 'audio', data: part.data ?? '', mimeType: part.mimeType ?? 'audio/mpeg' };
|
|
197
|
+
case 'resource_link':
|
|
198
|
+
return {
|
|
199
|
+
type: 'resource_link',
|
|
200
|
+
uri: part.uri ?? '',
|
|
201
|
+
name: part.name ?? part.title ?? part.uri ?? '',
|
|
202
|
+
...(part.title ? { title: part.title } : {}),
|
|
203
|
+
...(part.description ? { description: part.description } : {}),
|
|
204
|
+
...(part.mimeType ? { mimeType: part.mimeType } : {}),
|
|
205
|
+
...(typeof part.size === 'number' ? { size: part.size } : {}),
|
|
206
|
+
};
|
|
207
|
+
case 'resource': {
|
|
208
|
+
const resource = typeof part.text === 'string'
|
|
209
|
+
? { uri: part.uri ?? '', text: part.text, ...(part.mimeType ? { mimeType: part.mimeType } : {}) }
|
|
210
|
+
: { uri: part.uri ?? '', blob: part.data ?? '', ...(part.mimeType ? { mimeType: part.mimeType } : {}) };
|
|
211
|
+
return { type: 'resource', resource };
|
|
212
|
+
}
|
|
213
|
+
case 'text':
|
|
214
|
+
default:
|
|
215
|
+
return { type: 'text', text: part.text ?? '' };
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
181
219
|
function findConfigByCategory(
|
|
182
220
|
configOptions: SessionConfigOptionData[],
|
|
183
221
|
category: string,
|
|
@@ -681,10 +719,20 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
|
|
|
681
719
|
if (!this.connection || !this.acpSessionId) {
|
|
682
720
|
throw new Error('ACP bridge is not initialized');
|
|
683
721
|
}
|
|
722
|
+
// 布尔配置项按本地快照二次归一:兼容旧上游(agent-api 未转换时)传 'true'/'false' 字符串;
|
|
723
|
+
// 无定义信息时维持字符串原样(零回归)。
|
|
724
|
+
const definition = this.configOptions.find((opt) => opt.id === configId);
|
|
725
|
+
let wireValue: string | boolean = value;
|
|
726
|
+
if (typeof value === 'string' && definition?.type === 'boolean') {
|
|
727
|
+
const normalized = value.trim().toLowerCase();
|
|
728
|
+
if (normalized === 'true' || normalized === 'false') {
|
|
729
|
+
wireValue = normalized === 'true';
|
|
730
|
+
}
|
|
731
|
+
}
|
|
684
732
|
const response = await this.connection.setSessionConfigOption({
|
|
685
733
|
sessionId: this.acpSessionId,
|
|
686
734
|
configId,
|
|
687
|
-
...(typeof
|
|
735
|
+
...(typeof wireValue === 'boolean' ? { value: wireValue, type: 'boolean' as const } : { value: wireValue }),
|
|
688
736
|
});
|
|
689
737
|
if (response.configOptions) {
|
|
690
738
|
// SDK 1.3.0:set_config_option 响应携带全量快照,与 config_option_update 通知同源
|
|
@@ -697,11 +745,14 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
|
|
|
697
745
|
return response;
|
|
698
746
|
}
|
|
699
747
|
|
|
700
|
-
async authenticate(methodId: string): Promise<void> {
|
|
748
|
+
async authenticate(methodId: string, input?: Record<string, unknown>): Promise<void> {
|
|
701
749
|
if (!this.connection) {
|
|
702
750
|
throw new Error('ACP bridge is not initialized');
|
|
703
751
|
}
|
|
704
|
-
|
|
752
|
+
// 契约 §2.26:`input` 承载认证所需用户输入(如环境变量值),凭据仅内存透传,
|
|
753
|
+
// 不落库、不进日志。SDK 1.9.0 的 AuthenticateRequest 类型尚未声明 `input`,
|
|
754
|
+
// 按原始 wire 透传(Agent 侧按 schema 自行消费,未知字段忽略)。
|
|
755
|
+
await this.connection.authenticate({ methodId, input } as unknown as acp.AuthenticateRequest);
|
|
705
756
|
}
|
|
706
757
|
|
|
707
758
|
async logout(): Promise<void> {
|
|
@@ -741,11 +792,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
|
|
|
741
792
|
if (message.parts && message.parts.length > 0) {
|
|
742
793
|
// parts 非空:按序映射(保序),不追加 content 文本块(content 仅为合并文本兼容字段)
|
|
743
794
|
for (const part of message.parts) {
|
|
744
|
-
|
|
745
|
-
prompt.push({ type: 'text' as const, text: part.text ?? '' });
|
|
746
|
-
} else {
|
|
747
|
-
prompt.push({ type: 'image' as const, data: part.data ?? '', mimeType: part.mimeType ?? 'image/png' });
|
|
748
|
-
}
|
|
795
|
+
prompt.push(mapPromptPart(part));
|
|
749
796
|
}
|
|
750
797
|
} else {
|
|
751
798
|
for (const attachment of message.attachments ?? []) {
|
|
@@ -795,7 +842,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
|
|
|
795
842
|
clientCapabilities: CLIENT_CAPABILITIES,
|
|
796
843
|
clientInfo: {
|
|
797
844
|
name: 'agent-gear',
|
|
798
|
-
version:
|
|
845
|
+
version: CONTROLLER_VERSION,
|
|
799
846
|
},
|
|
800
847
|
});
|
|
801
848
|
|
|
@@ -63,11 +63,11 @@ describe('normalizeCapabilities', () => {
|
|
|
63
63
|
for (const id of ['session.load', 'session.resume', 'session.close', 'session.list', 'session.delete']) {
|
|
64
64
|
expect(statusOf(snapshot, id)?.status).toBe('supported');
|
|
65
65
|
}
|
|
66
|
-
expect(statusOf(snapshot, 'prompt.image')?.status).toBe('
|
|
66
|
+
expect(statusOf(snapshot, 'prompt.image')?.status).toBe('supported');
|
|
67
67
|
expect(statusOf(snapshot, 'prompt.embeddedContext')?.status).toBe('partial');
|
|
68
68
|
expect(statusOf(snapshot, 'prompt.audio')?.status).toBe('unsupported');
|
|
69
69
|
expect(statusOf(snapshot, 'session.fork')?.status).toBe('partial');
|
|
70
|
-
expect(statusOf(snapshot, 'session.additionalDirectories')?.status).toBe('
|
|
70
|
+
expect(statusOf(snapshot, 'session.additionalDirectories')?.status).toBe('supported');
|
|
71
71
|
expect(statusOf(snapshot, 'config.model')?.status).toBe('supported');
|
|
72
72
|
expect(statusOf(snapshot, 'config.mode')?.status).toBe('supported');
|
|
73
73
|
expect(statusOf(snapshot, 'mcp.http')?.status).toBe('supported');
|
package/src/acp/capabilities.ts
CHANGED
|
@@ -46,8 +46,8 @@ const PLATFORM_SUPPORT: Record<string, PlatformSupport> = {
|
|
|
46
46
|
'session.list': 'full',
|
|
47
47
|
'session.delete': 'full',
|
|
48
48
|
'session.fork': 'none',
|
|
49
|
-
'session.additionalDirectories': '
|
|
50
|
-
'prompt.image': '
|
|
49
|
+
'session.additionalDirectories': 'full',
|
|
50
|
+
'prompt.image': 'full',
|
|
51
51
|
'prompt.audio': 'none',
|
|
52
52
|
'prompt.embeddedContext': 'none',
|
|
53
53
|
'auth.login': 'none',
|
|
@@ -112,8 +112,6 @@ const SOURCE_FIELD: Record<string, string> = {
|
|
|
112
112
|
|
|
113
113
|
const PLATFORM_LIMITATION: Partial<Record<string, string>> = {
|
|
114
114
|
'session.fork': '平台暂未提供入口',
|
|
115
|
-
'session.additionalDirectories': '平台暂未提供入口',
|
|
116
|
-
'prompt.image': '平台暂未提供附件入口',
|
|
117
115
|
'prompt.audio': '平台暂未提供附件入口',
|
|
118
116
|
'prompt.embeddedContext': '平台暂未提供附件入口',
|
|
119
117
|
'auth.login': '平台暂未提供认证入口',
|
package/src/acp/sync-bridge.ts
CHANGED
|
@@ -2,6 +2,7 @@ import * as acp from '@agentclientprotocol/sdk';
|
|
|
2
2
|
import { AcpSpawner } from './spawner.js';
|
|
3
3
|
import { CLIENT_CAPABILITIES } from './capabilities.js';
|
|
4
4
|
import { logger } from '../observability/logger.js';
|
|
5
|
+
import { CONTROLLER_VERSION } from '../version.js';
|
|
5
6
|
|
|
6
7
|
const log = logger.child({ component: 'acp-sync-bridge' });
|
|
7
8
|
|
|
@@ -55,7 +56,7 @@ export class AcpSyncBridge implements acp.Client {
|
|
|
55
56
|
const initPromise = this.connection.initialize({
|
|
56
57
|
protocolVersion: ACP_PROTOCOL_VERSION,
|
|
57
58
|
clientCapabilities: CLIENT_CAPABILITIES,
|
|
58
|
-
clientInfo: { name: 'agent-gear', version:
|
|
59
|
+
clientInfo: { name: 'agent-gear', version: CONTROLLER_VERSION },
|
|
59
60
|
});
|
|
60
61
|
|
|
61
62
|
const result = await withTimeout(
|
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { describe, it, expect, vi } from 'vitest';
|
|
2
2
|
import { EventEmitter } from 'node:events';
|
|
3
|
+
import { existsSync, mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
3
6
|
import {
|
|
4
7
|
KimiLoginFlow,
|
|
8
|
+
KimiLogoutFlow,
|
|
5
9
|
classifyExit,
|
|
10
|
+
detectKimiLoggedIn,
|
|
6
11
|
parseKimiLoginLine,
|
|
7
12
|
resolveKimiLoginWaitMs,
|
|
8
13
|
sanitizeErrorSummary,
|
|
@@ -220,3 +225,58 @@ describe('KimiLoginFlow', () => {
|
|
|
220
225
|
await expect(pending).resolves.toMatchObject({ state: 'failed', reason: 'error' });
|
|
221
226
|
});
|
|
222
227
|
});
|
|
228
|
+
|
|
229
|
+
describe('KimiLogoutFlow(2.26.0 主动登出)', () => {
|
|
230
|
+
function logoutSetup(exitCode: number | null = 0) {
|
|
231
|
+
const child = createFakeChild();
|
|
232
|
+
const spawnFn = vi.fn(() => child);
|
|
233
|
+
const credentialsDir = mkdtempSync(join(tmpdir(), "kimi-logout-"));
|
|
234
|
+
const flow = new KimiLogoutFlow({ spawnFn: spawnFn as never, credentialsDir });
|
|
235
|
+
return { child, spawnFn, flow, credentialsDir };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
it('T-HLO1: kimi logout 退出码 0 → 成功且清理凭据目录', async () => {
|
|
239
|
+
const { child, spawnFn, flow, credentialsDir } = logoutSetup(0);
|
|
240
|
+
writeFileSync(join(credentialsDir, 'kimi.json'), '{}');
|
|
241
|
+
const pending = flow.run();
|
|
242
|
+
await tick();
|
|
243
|
+
child.emit('exit', 0, null);
|
|
244
|
+
await expect(pending).resolves.toEqual({ success: true, usedFallback: false });
|
|
245
|
+
expect(spawnFn).toHaveBeenCalledWith('kimi', ['logout'], expect.anything());
|
|
246
|
+
expect(existsSync(credentialsDir)).toBe(false);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
it('T-HLO2: 非零退出 → 回退删除凭据目录且判成功', async () => {
|
|
250
|
+
const { child, flow, credentialsDir } = logoutSetup(1);
|
|
251
|
+
writeFileSync(join(credentialsDir, 'kimi.json'), '{}');
|
|
252
|
+
const pending = flow.run();
|
|
253
|
+
await tick();
|
|
254
|
+
child.emit('exit', 1, null);
|
|
255
|
+
await expect(pending).resolves.toEqual({ success: true, usedFallback: true });
|
|
256
|
+
expect(existsSync(credentialsDir)).toBe(false);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it('T-HLO3: spawn 不可用(ENOENT)→ 回退删除凭据目录', async () => {
|
|
260
|
+
const credentialsDir = mkdtempSync(join(tmpdir(), "kimi-logout-"));
|
|
261
|
+
writeFileSync(join(credentialsDir, 'kimi.json'), '{}');
|
|
262
|
+
const flow = new KimiLogoutFlow({
|
|
263
|
+
spawnFn: (() => {
|
|
264
|
+
throw Object.assign(new Error('spawn kimi ENOENT'), { code: 'ENOENT' });
|
|
265
|
+
}) as never,
|
|
266
|
+
credentialsDir,
|
|
267
|
+
});
|
|
268
|
+
await expect(flow.run()).resolves.toEqual({ success: true, usedFallback: true });
|
|
269
|
+
expect(existsSync(credentialsDir)).toBe(false);
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
it('T-HLO4: 登录态探测只 stat 凭据目录(存在/不存在/异常)', async () => {
|
|
273
|
+
const credentialsDir = join(mkdtempSync(join(tmpdir(), 'kimi-detect-')), 'credentials');
|
|
274
|
+
await expect(detectKimiLoggedIn(credentialsDir)).resolves.toBe(false);
|
|
275
|
+
mkdirSync(credentialsDir, { recursive: true });
|
|
276
|
+
writeFileSync(join(credentialsDir, 'other.txt'), 'x');
|
|
277
|
+
await expect(detectKimiLoggedIn(credentialsDir)).resolves.toBe(false);
|
|
278
|
+
writeFileSync(join(credentialsDir, 'creds.json'), '{}');
|
|
279
|
+
await expect(detectKimiLoggedIn(credentialsDir)).resolves.toBe(true);
|
|
280
|
+
await expect(detectKimiLoggedIn(join(credentialsDir, 'missing'))).resolves.toBe(false);
|
|
281
|
+
});
|
|
282
|
+
});
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
+
import { rm, readdir, stat } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
2
5
|
|
|
3
6
|
/** 设备码有效期缺省值(实机 `Code expires in 1800s.`)。 */
|
|
4
7
|
export const DEFAULT_KIMI_EXPIRES_IN_SECONDS = 1800;
|
|
5
8
|
/** 登录等待上限:默认 30 分钟(与设备码一致),可 env 覆盖。 */
|
|
6
9
|
export const DEFAULT_KIMI_LOGIN_WAIT_MS = 1_800_000;
|
|
7
|
-
/**
|
|
8
|
-
export const
|
|
10
|
+
/** 登出子命令等待上限(登出为秒级操作)。 */
|
|
11
|
+
export const DEFAULT_KIMI_LOGOUT_WAIT_MS = 30_000;
|
|
12
|
+
/** `kimi login` 凭据目录(相对容器主目录)。 */
|
|
13
|
+
export const KIMI_CREDENTIALS_DIR = '.kimi-code/credentials';
|
|
9
14
|
const MAX_URL_LENGTH = 2048;
|
|
10
15
|
const MAX_USER_CODE_LENGTH = 64;
|
|
11
16
|
const MAX_LINE_BYTES = 8 * 1024;
|
|
@@ -81,8 +86,33 @@ export function resolveKimiLoginWaitMs(env: NodeJS.ProcessEnv = process.env): nu
|
|
|
81
86
|
return positiveIntFromEnv(env.KIMI_LOGIN_WAIT_MS, DEFAULT_KIMI_LOGIN_WAIT_MS);
|
|
82
87
|
}
|
|
83
88
|
|
|
84
|
-
|
|
85
|
-
|
|
89
|
+
/** 登录态:凭据目录(`~/.kimi-code/credentials`,可用 env 覆盖,测试注入)。 */
|
|
90
|
+
export function resolveKimiCredentialsDir(env: NodeJS.ProcessEnv = process.env): string {
|
|
91
|
+
const override = env.KIMI_CREDENTIALS_DIR;
|
|
92
|
+
if (override && override.trim().length > 0) return override;
|
|
93
|
+
return join(homedir(), KIMI_CREDENTIALS_DIR);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 登录态探测(D6):仅判断凭据目录内是否存在 `*.json` 普通文件——**不读取、不解析**。
|
|
98
|
+
* 目录不存在/无权限/异常统一视为未登录;不抛错。
|
|
99
|
+
*/
|
|
100
|
+
export async function detectKimiLoggedIn(credentialsDir: string): Promise<boolean> {
|
|
101
|
+
try {
|
|
102
|
+
const entries = await readdir(credentialsDir);
|
|
103
|
+
for (const name of entries) {
|
|
104
|
+
if (!name.toLowerCase().endsWith('.json')) continue;
|
|
105
|
+
try {
|
|
106
|
+
const info = await stat(join(credentialsDir, name));
|
|
107
|
+
if (info.isFile()) return true;
|
|
108
|
+
} catch {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return false;
|
|
113
|
+
} catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
86
116
|
}
|
|
87
117
|
|
|
88
118
|
export interface KimiExitClassification {
|
|
@@ -326,3 +356,118 @@ export class KimiLoginFlow {
|
|
|
326
356
|
});
|
|
327
357
|
}
|
|
328
358
|
}
|
|
359
|
+
|
|
360
|
+
export interface KimiLogoutOptions {
|
|
361
|
+
command?: string;
|
|
362
|
+
args?: string[];
|
|
363
|
+
waitMs?: number;
|
|
364
|
+
env?: NodeJS.ProcessEnv;
|
|
365
|
+
spawnFn?: KimiSpawnFn;
|
|
366
|
+
/** 凭据目录(缺省 `~/.kimi-code/credentials`,可注 test 目录)。 */
|
|
367
|
+
credentialsDir?: string;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export interface KimiLogoutResult {
|
|
371
|
+
success: boolean;
|
|
372
|
+
error?: string;
|
|
373
|
+
/** 是否走了「删除凭据目录」回退(`kimi logout` 不可用/失败)。 */
|
|
374
|
+
usedFallback: boolean;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** 删除凭据目录(只删不读);目录不存在视为成功。 */
|
|
378
|
+
export async function removeKimiCredentials(credentialsDir: string): Promise<boolean> {
|
|
379
|
+
try {
|
|
380
|
+
await rm(credentialsDir, { recursive: true, force: true });
|
|
381
|
+
return true;
|
|
382
|
+
} catch (error) {
|
|
383
|
+
return (error as NodeJS.ErrnoException)?.code === 'ENOENT';
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* 主动登出(D5):优先 `kimi logout` 子命令,退出码 0 判成功;
|
|
389
|
+
* 子命令不可用(ENOENT)/失败时回退删除凭据目录——「删除或失效」双路径。
|
|
390
|
+
*/
|
|
391
|
+
export class KimiLogoutFlow {
|
|
392
|
+
private readonly command: string;
|
|
393
|
+
private readonly args: string[];
|
|
394
|
+
private readonly waitMs: number;
|
|
395
|
+
private readonly env: NodeJS.ProcessEnv;
|
|
396
|
+
private readonly spawnFn: KimiSpawnFn;
|
|
397
|
+
private readonly credentialsDir: string;
|
|
398
|
+
|
|
399
|
+
constructor(options: KimiLogoutOptions = {}) {
|
|
400
|
+
this.command = options.command ?? 'kimi';
|
|
401
|
+
this.args = options.args ?? ['logout'];
|
|
402
|
+
this.waitMs = options.waitMs ?? DEFAULT_KIMI_LOGOUT_WAIT_MS;
|
|
403
|
+
this.env = options.env ?? process.env;
|
|
404
|
+
this.spawnFn = options.spawnFn ?? (spawn as unknown as KimiSpawnFn);
|
|
405
|
+
this.credentialsDir = options.credentialsDir ?? resolveKimiCredentialsDir(this.env);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
async run(): Promise<KimiLogoutResult> {
|
|
409
|
+
const exit = await this.runCommand();
|
|
410
|
+
if (exit.success) {
|
|
411
|
+
// 子命令成功:尽力清理本地凭据,失败不影响结果(CLI 已登出)。
|
|
412
|
+
await removeKimiCredentials(this.credentialsDir);
|
|
413
|
+
return { success: true, usedFallback: false };
|
|
414
|
+
}
|
|
415
|
+
const removed = await removeKimiCredentials(this.credentialsDir);
|
|
416
|
+
if (removed) {
|
|
417
|
+
return { success: true, usedFallback: true };
|
|
418
|
+
}
|
|
419
|
+
return { success: false, error: exit.error, usedFallback: true };
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** 执行 `kimi logout`;spawn 失败/超时/非零退出统一按失败返回(含脱敏摘要)。 */
|
|
423
|
+
private runCommand(): Promise<{ success: boolean; error?: string }> {
|
|
424
|
+
return new Promise((resolve) => {
|
|
425
|
+
let settled = false;
|
|
426
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
427
|
+
const finish = (result: { success: boolean; error?: string }): void => {
|
|
428
|
+
if (settled) return;
|
|
429
|
+
settled = true;
|
|
430
|
+
if (timer) {
|
|
431
|
+
clearTimeout(timer);
|
|
432
|
+
timer = null;
|
|
433
|
+
}
|
|
434
|
+
resolve(result);
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
let child: ChildLike;
|
|
438
|
+
try {
|
|
439
|
+
child = this.spawnFn(this.command, this.args, { stdio: ['ignore', 'pipe', 'pipe'], env: this.env });
|
|
440
|
+
} catch (error) {
|
|
441
|
+
finish({ success: false, error: sanitizeErrorSummary((error as Error).message) });
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
let stderr = '';
|
|
446
|
+
child.stderr?.on('data', (chunk: Buffer | string) => {
|
|
447
|
+
if (stderr.length < 4096) stderr += chunk.toString();
|
|
448
|
+
});
|
|
449
|
+
child.on('error', (error: Error) => {
|
|
450
|
+
finish({ success: false, error: sanitizeErrorSummary(error?.message ?? String(error)) });
|
|
451
|
+
});
|
|
452
|
+
child.on('exit', (code: number | null, signal?: NodeJS.Signals | null) => {
|
|
453
|
+
if (code === 0) {
|
|
454
|
+
finish({ success: true });
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
const summary = stderr.trim().length > 0
|
|
458
|
+
? stderr
|
|
459
|
+
: `kimi logout exited with ${code === null ? signal ?? 'unknown signal' : `code ${code}`}`;
|
|
460
|
+
finish({ success: false, error: sanitizeErrorSummary(summary) });
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
timer = setTimeout(() => {
|
|
464
|
+
try {
|
|
465
|
+
child.kill('SIGTERM');
|
|
466
|
+
} catch {
|
|
467
|
+
/* 进程可能已退出 */
|
|
468
|
+
}
|
|
469
|
+
finish({ success: false, error: 'kimi logout timed out' });
|
|
470
|
+
}, this.waitMs);
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
}
|
|
@@ -25,6 +25,8 @@ const login = vi.hoisted(() => ({
|
|
|
25
25
|
cancel: ReturnType<typeof vi.fn>;
|
|
26
26
|
finish: (outcome: unknown) => void;
|
|
27
27
|
}>,
|
|
28
|
+
logout: vi.fn(async () => ({ success: true, usedFallback: false })),
|
|
29
|
+
loggedIn: vi.fn(async () => false),
|
|
28
30
|
}));
|
|
29
31
|
|
|
30
32
|
vi.mock('./harness/kimi-login.js', async (importOriginal) => {
|
|
@@ -41,7 +43,15 @@ vi.mock('./harness/kimi-login.js', async (importOriginal) => {
|
|
|
41
43
|
login.instances.push(this as never);
|
|
42
44
|
}
|
|
43
45
|
}
|
|
44
|
-
|
|
46
|
+
class FakeKimiLogoutFlow {
|
|
47
|
+
run = vi.fn(() => login.logout());
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
...actual,
|
|
51
|
+
KimiLoginFlow: FakeKimiLoginFlow,
|
|
52
|
+
KimiLogoutFlow: FakeKimiLogoutFlow,
|
|
53
|
+
detectKimiLoggedIn: vi.fn(() => login.loggedIn()),
|
|
54
|
+
};
|
|
45
55
|
});
|
|
46
56
|
|
|
47
57
|
import { connectToServer } from './socketio-client.js';
|
|
@@ -51,6 +61,8 @@ function setup() {
|
|
|
51
61
|
fake.handlers.clear();
|
|
52
62
|
fake.socket.emit.mockClear();
|
|
53
63
|
login.instances.length = 0;
|
|
64
|
+
login.logout.mockClear();
|
|
65
|
+
login.loggedIn.mockReset().mockResolvedValue(false);
|
|
54
66
|
probe.probeAcpServerOptions.mockReset().mockResolvedValue({
|
|
55
67
|
modes: [],
|
|
56
68
|
availableModels: [],
|
|
@@ -80,7 +92,7 @@ describe('CONTROLLER_VERSION', () => {
|
|
|
80
92
|
});
|
|
81
93
|
});
|
|
82
94
|
|
|
83
|
-
describe('harness
|
|
95
|
+
describe('harness 登录闸门接线(2.26.0 设置项主动发起)', () => {
|
|
84
96
|
it('非 kimi_code: 零登录流程零事件,探测直接执行', async () => {
|
|
85
97
|
setup();
|
|
86
98
|
await fake.handlers.get('acp:probe-options')?.({
|
|
@@ -92,106 +104,83 @@ describe('harness 登录闸门接线', () => {
|
|
|
92
104
|
expect(emitted('harness:login:required')).toHaveLength(0);
|
|
93
105
|
});
|
|
94
106
|
|
|
95
|
-
it('kimi_code
|
|
107
|
+
it('kimi_code 未登录:只探测提示,不发起登录且不阻断动作', async () => {
|
|
96
108
|
setup();
|
|
97
|
-
|
|
109
|
+
await fake.handlers.get('acp:start')?.({
|
|
98
110
|
requestId: 'r2',
|
|
111
|
+
sessionId: 's2',
|
|
99
112
|
serverType: 'kimi_code',
|
|
113
|
+
cwd: '/tmp',
|
|
100
114
|
});
|
|
115
|
+
expect(login.instances).toHaveLength(0);
|
|
116
|
+
expect(emitted('harness:login:required')).toHaveLength(0);
|
|
117
|
+
// 未登录不产生 reason:auth(动作未被拦截),失败原因是真实启动错误
|
|
118
|
+
expect(emitted('acp:start:result')[0]).not.toMatchObject({ reason: 'auth' });
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('harness:login:start 下行 → 设备码 required/succeeded 上行(requestId 回带、trigger=settings)', async () => {
|
|
122
|
+
setup();
|
|
123
|
+
fake.handlers.get('harness:login:start')?.({ requestId: 'req-1', serverType: 'kimi_code' });
|
|
101
124
|
await tick();
|
|
102
125
|
expect(login.instances).toHaveLength(1);
|
|
103
|
-
expect(emitted('harness:login:required')).toHaveLength(0);
|
|
104
126
|
|
|
105
127
|
(login.instances[0] as any).handlersRef.onDeviceFlow({
|
|
106
128
|
url: 'https://www.kimi.com/code/authorize_device?user_code=4CQ4-0XIG',
|
|
107
129
|
userCode: '4CQ4-0XIG',
|
|
108
130
|
expiresInSeconds: 1800,
|
|
109
131
|
});
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
requestId: expect.any(String),
|
|
132
|
+
expect(emitted('harness:login:required')[0]).toEqual({
|
|
133
|
+
requestId: 'req-1',
|
|
113
134
|
serverType: 'kimi_code',
|
|
114
|
-
trigger: '
|
|
135
|
+
trigger: 'settings',
|
|
115
136
|
url: 'https://www.kimi.com/code/authorize_device?user_code=4CQ4-0XIG',
|
|
116
137
|
userCode: '4CQ4-0XIG',
|
|
117
138
|
expiresInSeconds: 1800,
|
|
118
139
|
});
|
|
119
140
|
|
|
120
141
|
(login.instances[0] as any).resolveRef({ state: 'logged-in', account: 'managed:kimi-code' });
|
|
121
|
-
await
|
|
142
|
+
await tick();
|
|
122
143
|
expect(emitted('harness:login:succeeded')[0]).toEqual({
|
|
123
|
-
requestId:
|
|
144
|
+
requestId: 'req-1',
|
|
124
145
|
account: 'managed:kimi-code',
|
|
125
146
|
});
|
|
126
|
-
expect(emitted('acp:probe-options:result')[0]).toMatchObject({ requestId: 'r2', success: true });
|
|
127
147
|
});
|
|
128
148
|
|
|
129
|
-
it('
|
|
149
|
+
it('harness:logout 下行 → logout:result 回执', async () => {
|
|
130
150
|
setup();
|
|
131
|
-
|
|
132
|
-
requestId: 'r3',
|
|
133
|
-
sessionId: 's3',
|
|
134
|
-
serverType: 'kimi_code',
|
|
135
|
-
cwd: '/tmp',
|
|
136
|
-
});
|
|
151
|
+
fake.handlers.get('harness:logout')?.({ requestId: 'req-out', serverType: 'kimi_code' });
|
|
137
152
|
await tick();
|
|
138
|
-
(login.
|
|
139
|
-
|
|
140
|
-
expect(emitted('harness:login:failed')[0]).toEqual({
|
|
141
|
-
requestId: expect.any(String),
|
|
142
|
-
reason: 'timeout',
|
|
143
|
-
// error 缺省不输出该键
|
|
144
|
-
});
|
|
145
|
-
expect(emitted('acp:start:result')[0]).toEqual({
|
|
146
|
-
requestId: 'r3',
|
|
147
|
-
sessionId: 's3',
|
|
148
|
-
success: false,
|
|
149
|
-
error: 'Kimi Code 未登录',
|
|
150
|
-
reason: 'auth',
|
|
151
|
-
});
|
|
153
|
+
expect(login.logout).toHaveBeenCalledTimes(1);
|
|
154
|
+
expect(emitted('harness:logout:result')[0]).toEqual({ requestId: 'req-out', success: true });
|
|
152
155
|
});
|
|
153
156
|
|
|
154
|
-
it('
|
|
157
|
+
it('harness:login:status 下行 → status:result 回执', async () => {
|
|
155
158
|
setup();
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
sessionId: 's4',
|
|
159
|
-
serverType: 'kimi_code',
|
|
160
|
-
cwd: '/tmp',
|
|
161
|
-
externalSessionId: 'ext-4',
|
|
162
|
-
});
|
|
159
|
+
login.loggedIn.mockResolvedValueOnce(true);
|
|
160
|
+
fake.handlers.get('harness:login:status')?.({ requestId: 'req-status', serverType: 'kimi_code' });
|
|
163
161
|
await tick();
|
|
164
|
-
(login
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
success: false,
|
|
168
|
-
error: 'Kimi Code 未登录',
|
|
169
|
-
reason: 'auth',
|
|
162
|
+
expect(emitted('harness:login:status:result')[0]).toEqual({
|
|
163
|
+
requestId: 'req-status',
|
|
164
|
+
status: 'logged_in',
|
|
170
165
|
});
|
|
171
166
|
});
|
|
172
167
|
|
|
173
168
|
it('harness:login:cancel 下行:requestId 匹配才 cancel', async () => {
|
|
174
169
|
setup();
|
|
175
|
-
|
|
176
|
-
requestId: 'r5',
|
|
177
|
-
serverType: 'kimi_code',
|
|
178
|
-
});
|
|
170
|
+
fake.handlers.get('harness:login:start')?.({ requestId: 'req-cancel', serverType: 'kimi_code' });
|
|
179
171
|
await tick();
|
|
180
172
|
const flow = login.instances[0];
|
|
181
|
-
(flow as any).handlersRef.onDeviceFlow({
|
|
182
|
-
url: 'https://kimi.test/login',
|
|
183
|
-
userCode: 'CODE-1',
|
|
184
|
-
expiresInSeconds: 1800,
|
|
185
|
-
});
|
|
186
|
-
const requestId = (emitted('harness:login:required')[0] as any).requestId;
|
|
187
173
|
|
|
188
174
|
fake.handlers.get('harness:login:cancel')?.({ requestId: 'req-other' });
|
|
189
175
|
expect(flow.cancel).not.toHaveBeenCalled();
|
|
190
|
-
fake.handlers.get('harness:login:cancel')?.({ requestId });
|
|
176
|
+
fake.handlers.get('harness:login:cancel')?.({ requestId: 'req-cancel' });
|
|
191
177
|
expect(flow.cancel).toHaveBeenCalledTimes(1);
|
|
192
178
|
|
|
193
179
|
(flow as any).resolveRef({ state: 'failed', reason: 'cancelled' });
|
|
194
|
-
await
|
|
195
|
-
expect(emitted('
|
|
180
|
+
await tick();
|
|
181
|
+
expect(emitted('harness:login:failed')[0]).toMatchObject({
|
|
182
|
+
requestId: 'req-cancel',
|
|
183
|
+
reason: 'cancelled',
|
|
184
|
+
});
|
|
196
185
|
});
|
|
197
186
|
});
|