agent-gear 2.7.1 → 2.8.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 +12 -1
- package/dist/acp/auth-gate.d.ts +62 -0
- package/dist/acp/auth-gate.d.ts.map +1 -0
- package/dist/acp/auth-gate.js +110 -0
- package/dist/acp/auth-gate.js.map +1 -0
- package/dist/acp/auth-gate.test.d.ts +2 -0
- package/dist/acp/auth-gate.test.d.ts.map +1 -0
- package/dist/acp/auth-gate.test.js +126 -0
- package/dist/acp/auth-gate.test.js.map +1 -0
- package/dist/harness/kimi-login.d.ts +124 -0
- package/dist/harness/kimi-login.d.ts.map +1 -0
- package/dist/harness/kimi-login.js +263 -0
- package/dist/harness/kimi-login.js.map +1 -0
- package/dist/harness/kimi-login.test.d.ts +2 -0
- package/dist/harness/kimi-login.test.d.ts.map +1 -0
- package/dist/harness/kimi-login.test.js +193 -0
- package/dist/harness/kimi-login.test.js.map +1 -0
- package/dist/socketio-client.auth-gate.test.d.ts +2 -0
- package/dist/socketio-client.auth-gate.test.d.ts.map +1 -0
- package/dist/socketio-client.auth-gate.test.js +179 -0
- package/dist/socketio-client.auth-gate.test.js.map +1 -0
- package/dist/socketio-client.d.ts +7 -0
- package/dist/socketio-client.d.ts.map +1 -1
- package/dist/socketio-client.js +32 -2
- package/dist/socketio-client.js.map +1 -1
- package/package.json +1 -1
- package/src/acp/auth-gate.test.ts +145 -0
- package/src/acp/auth-gate.ts +144 -0
- package/src/harness/kimi-login.test.ts +222 -0
- package/src/harness/kimi-login.ts +328 -0
- package/src/socketio-client.auth-gate.test.ts +200 -0
- package/src/socketio-client.ts +36 -2
- package/tests/socketio-client.test.ts +2 -2
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/** 设备码有效期缺省值(实机 `Code expires in 1800s.`)。 */
|
|
4
|
+
export const DEFAULT_KIMI_EXPIRES_IN_SECONDS = 1800;
|
|
5
|
+
/** 登录等待上限:默认 30 分钟(与设备码一致),可 env 覆盖。 */
|
|
6
|
+
export const DEFAULT_KIMI_LOGIN_WAIT_MS = 1_800_000;
|
|
7
|
+
/** 进程内登录缓存 TTL(5 分钟)。 */
|
|
8
|
+
export const DEFAULT_KIMI_AUTH_CACHE_TTL_MS = 300_000;
|
|
9
|
+
const MAX_URL_LENGTH = 2048;
|
|
10
|
+
const MAX_USER_CODE_LENGTH = 64;
|
|
11
|
+
const MAX_LINE_BYTES = 8 * 1024;
|
|
12
|
+
const MAX_ERROR_SUMMARY = 200;
|
|
13
|
+
|
|
14
|
+
export type KimiLoginOutcome =
|
|
15
|
+
| { state: 'logged-in'; account?: string }
|
|
16
|
+
| { state: 'device-flow'; url: string; userCode: string; expiresInSeconds: number }
|
|
17
|
+
| { state: 'failed'; reason: 'cancelled' | 'timeout' | 'error'; error?: string };
|
|
18
|
+
|
|
19
|
+
/** `run()` 的终态(device-flow 只经 onDeviceFlow 上抛)。 */
|
|
20
|
+
export type KimiLoginTerminal = Exclude<KimiLoginOutcome, { state: 'device-flow' }>;
|
|
21
|
+
|
|
22
|
+
export type KimiLoginLine =
|
|
23
|
+
| { kind: 'logged-in'; account?: string }
|
|
24
|
+
| { kind: 'device-url'; url: string }
|
|
25
|
+
| { kind: 'user-code'; userCode: string }
|
|
26
|
+
| { kind: 'expires-in'; expiresInSeconds: number }
|
|
27
|
+
| { kind: 'waiting' }
|
|
28
|
+
| { kind: 'cancelled' }
|
|
29
|
+
| { kind: 'error'; message: string };
|
|
30
|
+
|
|
31
|
+
/** 是否为可下发给前端的 http(s) 链接(不可信内容不入库)。 */
|
|
32
|
+
export function isSafeLoginUrl(value: string): boolean {
|
|
33
|
+
if (value.length === 0 || value.length > MAX_URL_LENGTH) return false;
|
|
34
|
+
try {
|
|
35
|
+
const url = new URL(value);
|
|
36
|
+
return url.protocol === 'http:' || url.protocol === 'https:';
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function isSafeUserCode(value: string): boolean {
|
|
43
|
+
return /^[A-Za-z0-9-]{1,64}$/.test(value) && value.length <= MAX_USER_CODE_LENGTH;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 脱敏摘要:去控制字符/压缩空白/截断 200(原始输出不进日志与事件)。 */
|
|
47
|
+
export function sanitizeErrorSummary(text: string): string {
|
|
48
|
+
const cleaned = text
|
|
49
|
+
.replace(/\u001b\[[0-9;]*m/g, '')
|
|
50
|
+
.replace(/[\u0000-\u001f\u007f]/g, ' ')
|
|
51
|
+
.replace(/\s+/g, ' ')
|
|
52
|
+
.trim();
|
|
53
|
+
return cleaned.length > MAX_ERROR_SUMMARY ? cleaned.slice(0, MAX_ERROR_SUMMARY) : cleaned;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 逐行解析(stdout+stderr 合并口径;`\r\n` 由调用方归一)。 */
|
|
57
|
+
export function parseKimiLoginLine(rawLine: string): KimiLoginLine | null {
|
|
58
|
+
const line = rawLine.replace(/\r$/, '').trim();
|
|
59
|
+
if (line.length === 0) return null;
|
|
60
|
+
const loggedIn = /^Logged in to (.+?)\.?$/.exec(line);
|
|
61
|
+
if (loggedIn) return { kind: 'logged-in', account: loggedIn[1].trim() };
|
|
62
|
+
const deviceUrl = /^Opening browser for Kimi device login: (\S+)$/.exec(line);
|
|
63
|
+
if (deviceUrl) return { kind: 'device-url', url: deviceUrl[1] };
|
|
64
|
+
const userCode = /enter code:\s*([A-Za-z0-9-]+)/.exec(line);
|
|
65
|
+
if (userCode) return { kind: 'user-code', userCode: userCode[1] };
|
|
66
|
+
const expires = /^Code expires in (\d+)s\.$/.exec(line);
|
|
67
|
+
if (expires) return { kind: 'expires-in', expiresInSeconds: Number(expires[1]) };
|
|
68
|
+
if (/^Waiting for authorization to complete/.test(line)) return { kind: 'waiting' };
|
|
69
|
+
if (/^Login cancelled/.test(line)) return { kind: 'cancelled' };
|
|
70
|
+
const failed = /^Login failed:?\s*(.*)$/.exec(line);
|
|
71
|
+
if (failed) return { kind: 'error', message: sanitizeErrorSummary(failed[1] || line) };
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function positiveIntFromEnv(value: string | undefined, fallback: number): number {
|
|
76
|
+
const parsed = Number(value);
|
|
77
|
+
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : fallback;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function resolveKimiLoginWaitMs(env: NodeJS.ProcessEnv = process.env): number {
|
|
81
|
+
return positiveIntFromEnv(env.KIMI_LOGIN_WAIT_MS, DEFAULT_KIMI_LOGIN_WAIT_MS);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function resolveKimiAuthCacheTtlMs(env: NodeJS.ProcessEnv = process.env): number {
|
|
85
|
+
return positiveIntFromEnv(env.KIMI_AUTH_CACHE_TTL_MS, DEFAULT_KIMI_AUTH_CACHE_TTL_MS);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface KimiExitClassification {
|
|
89
|
+
code: number | null;
|
|
90
|
+
signal?: NodeJS.Signals | null;
|
|
91
|
+
/** 我方 cancel() 设置的标志(不依赖文案)。 */
|
|
92
|
+
cancelled?: boolean;
|
|
93
|
+
/** 解析到 `Login cancelled*` 文案。 */
|
|
94
|
+
cancelMessage?: boolean;
|
|
95
|
+
/** `Login failed: <msg>` 摘要(已脱敏、≤200)。 */
|
|
96
|
+
errorMessage?: string;
|
|
97
|
+
account?: string;
|
|
98
|
+
/** 设备码到期时间戳(毫秒);缺省视为未到期。 */
|
|
99
|
+
expiresAt?: number;
|
|
100
|
+
now?: number;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 判定 `kimi login` 终态(§3 A5):
|
|
105
|
+
* exit 0 → logged-in;cancel 标志/文案 → cancelled;已过 expiresAt → timeout;其余 → error。
|
|
106
|
+
*/
|
|
107
|
+
export function classifyExit(input: KimiExitClassification): KimiLoginTerminal {
|
|
108
|
+
const now = input.now ?? Date.now();
|
|
109
|
+
if (input.cancelled) return { state: 'failed', reason: 'cancelled' };
|
|
110
|
+
if (input.code === 0) {
|
|
111
|
+
return input.account ? { state: 'logged-in', account: input.account } : { state: 'logged-in' };
|
|
112
|
+
}
|
|
113
|
+
if (input.cancelMessage) return { state: 'failed', reason: 'cancelled' };
|
|
114
|
+
if (typeof input.expiresAt === 'number' && now >= input.expiresAt) {
|
|
115
|
+
return { state: 'failed', reason: 'timeout' };
|
|
116
|
+
}
|
|
117
|
+
const summary = input.errorMessage
|
|
118
|
+
? input.errorMessage
|
|
119
|
+
: `kimi login exited with ${input.code === null ? input.signal ?? 'unknown signal' : `code ${input.code}`}`;
|
|
120
|
+
return { state: 'failed', reason: 'error', error: sanitizeErrorSummary(summary) };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface KimiLoginHandlers {
|
|
124
|
+
/** 设备码首次命中时上抛一次(并发使用动作共用一个登录流程)。 */
|
|
125
|
+
onDeviceFlow?: (payload: { url: string; userCode: string; expiresInSeconds: number }) => void;
|
|
126
|
+
/** 可观测:只上报匹配到的行类型,不含原文。 */
|
|
127
|
+
onLineMatched?: (kind: KimiLoginLine['kind']) => void;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
interface ChildLike {
|
|
131
|
+
stdout?: { on: (event: 'data', cb: (chunk: Buffer | string) => void) => unknown } | null;
|
|
132
|
+
stderr?: { on: (event: 'data', cb: (chunk: Buffer | string) => void) => unknown } | null;
|
|
133
|
+
kill: (signal?: NodeJS.Signals) => unknown;
|
|
134
|
+
on: (event: 'exit' | 'close' | 'error', cb: (...args: any[]) => void) => unknown;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export type KimiSpawnFn = (
|
|
138
|
+
command: string,
|
|
139
|
+
args: string[],
|
|
140
|
+
options: { stdio: ['ignore', 'pipe', 'pipe']; env: NodeJS.ProcessEnv },
|
|
141
|
+
) => ChildLike;
|
|
142
|
+
|
|
143
|
+
export interface KimiLoginFlowOptions {
|
|
144
|
+
command?: string;
|
|
145
|
+
args?: string[];
|
|
146
|
+
waitMs?: number;
|
|
147
|
+
env?: NodeJS.ProcessEnv;
|
|
148
|
+
spawnFn?: KimiSpawnFn;
|
|
149
|
+
now?: () => number;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** `kimi login` 单次子进程(stdio 无 TTY、不传 `--region`、输出按行合并解析)。 */
|
|
153
|
+
export class KimiLoginFlow {
|
|
154
|
+
private readonly command: string;
|
|
155
|
+
private readonly args: string[];
|
|
156
|
+
private readonly waitMs: number;
|
|
157
|
+
private readonly env: NodeJS.ProcessEnv;
|
|
158
|
+
private readonly spawnFn: KimiSpawnFn;
|
|
159
|
+
private readonly now: () => number;
|
|
160
|
+
|
|
161
|
+
private child: ChildLike | null = null;
|
|
162
|
+
private settled = false;
|
|
163
|
+
private cancelled = false;
|
|
164
|
+
private killTimer: ReturnType<typeof setTimeout> | null = null;
|
|
165
|
+
|
|
166
|
+
constructor(options: KimiLoginFlowOptions = {}) {
|
|
167
|
+
this.command = options.command ?? 'kimi';
|
|
168
|
+
this.args = options.args ?? ['login'];
|
|
169
|
+
this.waitMs = options.waitMs ?? resolveKimiLoginWaitMs(options.env);
|
|
170
|
+
this.env = options.env ?? process.env;
|
|
171
|
+
this.spawnFn = options.spawnFn ?? (spawn as unknown as KimiSpawnFn);
|
|
172
|
+
this.now = options.now ?? Date.now;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** 终止进行中的 `kimi login`(SIGTERM;reason 由 cancelled 标志定,不依赖文案)。 */
|
|
176
|
+
cancel(): void {
|
|
177
|
+
if (this.settled) return;
|
|
178
|
+
this.cancelled = true;
|
|
179
|
+
this.killChild('SIGTERM');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private killChild(signal: NodeJS.Signals): void {
|
|
183
|
+
try {
|
|
184
|
+
this.child?.kill(signal);
|
|
185
|
+
} catch {
|
|
186
|
+
/* 进程可能已退出 */
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private clearKillTimer(): void {
|
|
191
|
+
if (this.killTimer) {
|
|
192
|
+
clearTimeout(this.killTimer);
|
|
193
|
+
this.killTimer = null;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
run(handlers: KimiLoginHandlers = {}): Promise<KimiLoginTerminal> {
|
|
198
|
+
return new Promise((resolve) => {
|
|
199
|
+
let url: string | undefined;
|
|
200
|
+
let userCode: string | undefined;
|
|
201
|
+
let expiresInSeconds = DEFAULT_KIMI_EXPIRES_IN_SECONDS;
|
|
202
|
+
let account: string | undefined;
|
|
203
|
+
let cancelMessage = false;
|
|
204
|
+
let errorMessage: string | undefined;
|
|
205
|
+
let expiresAt: number | undefined;
|
|
206
|
+
let emitted = false;
|
|
207
|
+
const buffers: Record<'stdout' | 'stderr', string> = { stdout: '', stderr: '' };
|
|
208
|
+
|
|
209
|
+
const finish = (outcome: KimiLoginTerminal): void => {
|
|
210
|
+
if (this.settled) return;
|
|
211
|
+
this.settled = true;
|
|
212
|
+
this.clearKillTimer();
|
|
213
|
+
resolve(outcome);
|
|
214
|
+
};
|
|
215
|
+
const fail = (error: string): void => {
|
|
216
|
+
this.killChild('SIGTERM');
|
|
217
|
+
finish({ state: 'failed', reason: 'error', error: sanitizeErrorSummary(error) });
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const maybeEmitDeviceFlow = (): void => {
|
|
221
|
+
if (emitted || !url || !userCode) return;
|
|
222
|
+
emitted = true;
|
|
223
|
+
expiresAt = this.now() + expiresInSeconds * 1000;
|
|
224
|
+
handlers.onDeviceFlow?.({ url, userCode, expiresInSeconds });
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
const handleLine = (raw: string): void => {
|
|
228
|
+
const parsed = parseKimiLoginLine(raw);
|
|
229
|
+
if (!parsed) return;
|
|
230
|
+
handlers.onLineMatched?.(parsed.kind);
|
|
231
|
+
switch (parsed.kind) {
|
|
232
|
+
case 'logged-in':
|
|
233
|
+
account = parsed.account;
|
|
234
|
+
return;
|
|
235
|
+
case 'device-url':
|
|
236
|
+
if (!isSafeLoginUrl(parsed.url)) {
|
|
237
|
+
fail('kimi login device URL rejected');
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
url = parsed.url;
|
|
241
|
+
break;
|
|
242
|
+
case 'user-code':
|
|
243
|
+
if (!isSafeUserCode(parsed.userCode)) {
|
|
244
|
+
fail('kimi login user code rejected');
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
userCode = parsed.userCode;
|
|
248
|
+
break;
|
|
249
|
+
case 'expires-in':
|
|
250
|
+
expiresInSeconds = Math.min(3600, Math.max(60, parsed.expiresInSeconds));
|
|
251
|
+
break;
|
|
252
|
+
case 'cancelled':
|
|
253
|
+
cancelMessage = true;
|
|
254
|
+
return;
|
|
255
|
+
case 'error':
|
|
256
|
+
errorMessage = parsed.message;
|
|
257
|
+
return;
|
|
258
|
+
default:
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (emitted && url && userCode) {
|
|
262
|
+
expiresAt = this.now() + expiresInSeconds * 1000;
|
|
263
|
+
} else {
|
|
264
|
+
maybeEmitDeviceFlow();
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const pushChunk = (stream: 'stdout' | 'stderr', chunk: Buffer | string): void => {
|
|
269
|
+
let buffer = buffers[stream] + chunk.toString();
|
|
270
|
+
let index = buffer.indexOf('\n');
|
|
271
|
+
while (index >= 0) {
|
|
272
|
+
const line = buffer.slice(0, index);
|
|
273
|
+
buffer = buffer.slice(index + 1);
|
|
274
|
+
handleLine(line);
|
|
275
|
+
if (this.settled) return;
|
|
276
|
+
index = buffer.indexOf('\n');
|
|
277
|
+
}
|
|
278
|
+
// 行缓冲上限 8 KiB:无换行的超长输出直接丢弃,避免无界增长。
|
|
279
|
+
buffers[stream] = buffer.length > MAX_LINE_BYTES ? '' : buffer;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const flushBuffers = (): void => {
|
|
283
|
+
for (const stream of ['stdout', 'stderr'] as const) {
|
|
284
|
+
const leftover = buffers[stream];
|
|
285
|
+
buffers[stream] = '';
|
|
286
|
+
if (leftover.trim().length > 0) handleLine(leftover);
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
let child: ChildLike;
|
|
291
|
+
try {
|
|
292
|
+
child = this.spawnFn(this.command, this.args, {
|
|
293
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
294
|
+
env: this.env,
|
|
295
|
+
});
|
|
296
|
+
} catch (error) {
|
|
297
|
+
fail((error as Error).message);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
this.child = child;
|
|
301
|
+
|
|
302
|
+
child.stdout?.on('data', (chunk) => pushChunk('stdout', chunk));
|
|
303
|
+
child.stderr?.on('data', (chunk) => pushChunk('stderr', chunk));
|
|
304
|
+
child.on('error', (error: Error) => fail(error?.message ?? String(error)));
|
|
305
|
+
child.on('exit', (code: number | null, signal?: NodeJS.Signals | null) => {
|
|
306
|
+
flushBuffers();
|
|
307
|
+
finish(
|
|
308
|
+
classifyExit({
|
|
309
|
+
code,
|
|
310
|
+
signal: signal ?? null,
|
|
311
|
+
cancelled: this.cancelled,
|
|
312
|
+
cancelMessage,
|
|
313
|
+
errorMessage,
|
|
314
|
+
...(account ? { account } : {}),
|
|
315
|
+
...(expiresAt ? { expiresAt } : {}),
|
|
316
|
+
now: this.now(),
|
|
317
|
+
}),
|
|
318
|
+
);
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
this.killTimer = setTimeout(() => {
|
|
322
|
+
this.killTimer = null;
|
|
323
|
+
this.killChild('SIGTERM');
|
|
324
|
+
finish({ state: 'failed', reason: 'timeout' });
|
|
325
|
+
}, this.waitMs);
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
|
|
3
|
+
const fake = vi.hoisted(() => {
|
|
4
|
+
const handlers = new Map<string, (...args: any[]) => void>();
|
|
5
|
+
const socket: Record<string, any> = {};
|
|
6
|
+
socket.on = (event: string, handler: (...args: any[]) => void) => {
|
|
7
|
+
handlers.set(event, handler);
|
|
8
|
+
return socket;
|
|
9
|
+
};
|
|
10
|
+
socket.emit = vi.fn(() => socket);
|
|
11
|
+
socket.disconnect = vi.fn(() => socket);
|
|
12
|
+
socket.connect = vi.fn(() => socket);
|
|
13
|
+
socket.close = vi.fn(() => socket);
|
|
14
|
+
return { handlers, socket };
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
vi.mock('socket.io-client', () => ({ io: () => fake.socket }));
|
|
18
|
+
|
|
19
|
+
const probe = vi.hoisted(() => ({ probeAcpServerOptions: vi.fn() }));
|
|
20
|
+
vi.mock('./acp/prober.js', () => probe);
|
|
21
|
+
|
|
22
|
+
const login = vi.hoisted(() => ({
|
|
23
|
+
instances: [] as Array<{
|
|
24
|
+
run: ReturnType<typeof vi.fn>;
|
|
25
|
+
cancel: ReturnType<typeof vi.fn>;
|
|
26
|
+
finish: (outcome: unknown) => void;
|
|
27
|
+
}>,
|
|
28
|
+
}));
|
|
29
|
+
|
|
30
|
+
vi.mock('./harness/kimi-login.js', async (importOriginal) => {
|
|
31
|
+
const actual = await importOriginal<typeof import('./harness/kimi-login.js')>();
|
|
32
|
+
class FakeKimiLoginFlow {
|
|
33
|
+
run = vi.fn((handlers: any) => {
|
|
34
|
+
(this as any).handlersRef = handlers;
|
|
35
|
+
return new Promise((resolve) => {
|
|
36
|
+
(this as any).resolveRef = resolve;
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
cancel = vi.fn();
|
|
40
|
+
constructor() {
|
|
41
|
+
login.instances.push(this as never);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { ...actual, KimiLoginFlow: FakeKimiLoginFlow };
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
import { connectToServer } from './socketio-client.js';
|
|
48
|
+
import { version as PACKAGE_VERSION } from '../package.json';
|
|
49
|
+
|
|
50
|
+
function setup() {
|
|
51
|
+
fake.handlers.clear();
|
|
52
|
+
fake.socket.emit.mockClear();
|
|
53
|
+
login.instances.length = 0;
|
|
54
|
+
vi.spyOn(console, 'log').mockImplementation(() => {});
|
|
55
|
+
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
56
|
+
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
57
|
+
probe.probeAcpServerOptions.mockReset().mockResolvedValue({
|
|
58
|
+
modes: [],
|
|
59
|
+
availableModels: [],
|
|
60
|
+
currentModeId: null,
|
|
61
|
+
currentModelId: null,
|
|
62
|
+
});
|
|
63
|
+
connectToServer('http://localhost:4001', 'key', {
|
|
64
|
+
handshakeToken: 'key',
|
|
65
|
+
skipLocalMcpStart: true,
|
|
66
|
+
handleWorkload: false,
|
|
67
|
+
persistConfig: false,
|
|
68
|
+
onShutdown: vi.fn(),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const tick = () => new Promise((resolve) => setImmediate(resolve));
|
|
73
|
+
function emitted(event: string) {
|
|
74
|
+
return fake.socket.emit.mock.calls.filter((call: unknown[]) => call[0] === event).map((call: unknown[]) => call[1]);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
describe('CONTROLLER_VERSION', () => {
|
|
78
|
+
it('register 上报版本取自 package.json(2.8.0,无第二处常量)', () => {
|
|
79
|
+
setup();
|
|
80
|
+
fake.handlers.get('connect')?.();
|
|
81
|
+
expect(PACKAGE_VERSION).toBe('2.8.0');
|
|
82
|
+
expect(emitted('register')[0]).toMatchObject({ version: '2.8.0' });
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
describe('harness 登录闸门接线', () => {
|
|
87
|
+
it('非 kimi_code: 零登录流程零事件,探测直接执行', async () => {
|
|
88
|
+
setup();
|
|
89
|
+
await fake.handlers.get('acp:probe-options')?.({
|
|
90
|
+
requestId: 'r1',
|
|
91
|
+
serverType: 'opencode',
|
|
92
|
+
});
|
|
93
|
+
expect(login.instances).toHaveLength(0);
|
|
94
|
+
expect(probe.probeAcpServerOptions).toHaveBeenCalledWith('opencode');
|
|
95
|
+
expect(emitted('harness:login:required')).toHaveLength(0);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('kimi_code: required 上行形状 → 登录成功后自动继续探测', async () => {
|
|
99
|
+
setup();
|
|
100
|
+
const pending = fake.handlers.get('acp:probe-options')?.({
|
|
101
|
+
requestId: 'r2',
|
|
102
|
+
serverType: 'kimi_code',
|
|
103
|
+
});
|
|
104
|
+
await tick();
|
|
105
|
+
expect(login.instances).toHaveLength(1);
|
|
106
|
+
expect(emitted('harness:login:required')).toHaveLength(0);
|
|
107
|
+
|
|
108
|
+
(login.instances[0] as any).handlersRef.onDeviceFlow({
|
|
109
|
+
url: 'https://www.kimi.com/code/authorize_device?user_code=4CQ4-0XIG',
|
|
110
|
+
userCode: '4CQ4-0XIG',
|
|
111
|
+
expiresInSeconds: 1800,
|
|
112
|
+
});
|
|
113
|
+
const required = emitted('harness:login:required')[0];
|
|
114
|
+
expect(required).toEqual({
|
|
115
|
+
requestId: expect.any(String),
|
|
116
|
+
serverType: 'kimi_code',
|
|
117
|
+
trigger: 'probe-options',
|
|
118
|
+
url: 'https://www.kimi.com/code/authorize_device?user_code=4CQ4-0XIG',
|
|
119
|
+
userCode: '4CQ4-0XIG',
|
|
120
|
+
expiresInSeconds: 1800,
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
(login.instances[0] as any).resolveRef({ state: 'logged-in', account: 'managed:kimi-code' });
|
|
124
|
+
await pending;
|
|
125
|
+
expect(emitted('harness:login:succeeded')[0]).toEqual({
|
|
126
|
+
requestId: required.requestId,
|
|
127
|
+
account: 'managed:kimi-code',
|
|
128
|
+
});
|
|
129
|
+
expect(emitted('acp:probe-options:result')[0]).toMatchObject({ requestId: 'r2', success: true });
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it('acp:start 失败:result 带 reason:auth + 文案,并上行 failed', async () => {
|
|
133
|
+
setup();
|
|
134
|
+
const pending = fake.handlers.get('acp:start')?.({
|
|
135
|
+
requestId: 'r3',
|
|
136
|
+
sessionId: 's3',
|
|
137
|
+
serverType: 'kimi_code',
|
|
138
|
+
cwd: '/tmp',
|
|
139
|
+
});
|
|
140
|
+
await tick();
|
|
141
|
+
(login.instances[0] as any).resolveRef({ state: 'failed', reason: 'timeout' });
|
|
142
|
+
await pending;
|
|
143
|
+
expect(emitted('harness:login:failed')[0]).toEqual({
|
|
144
|
+
requestId: expect.any(String),
|
|
145
|
+
reason: 'timeout',
|
|
146
|
+
// error 缺省不输出该键
|
|
147
|
+
});
|
|
148
|
+
expect(emitted('acp:start:result')[0]).toEqual({
|
|
149
|
+
requestId: 'r3',
|
|
150
|
+
sessionId: 's3',
|
|
151
|
+
success: false,
|
|
152
|
+
error: 'Kimi Code 未登录',
|
|
153
|
+
reason: 'auth',
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('acp:resume 失败:result 带 reason:auth', async () => {
|
|
158
|
+
setup();
|
|
159
|
+
const pending = fake.handlers.get('acp:resume')?.({
|
|
160
|
+
requestId: 'r4',
|
|
161
|
+
sessionId: 's4',
|
|
162
|
+
serverType: 'kimi_code',
|
|
163
|
+
cwd: '/tmp',
|
|
164
|
+
externalSessionId: 'ext-4',
|
|
165
|
+
});
|
|
166
|
+
await tick();
|
|
167
|
+
(login.instances[0] as any).resolveRef({ state: 'failed', reason: 'cancelled' });
|
|
168
|
+
await pending;
|
|
169
|
+
expect(emitted('acp:resume:result')[0]).toMatchObject({
|
|
170
|
+
success: false,
|
|
171
|
+
error: 'Kimi Code 未登录',
|
|
172
|
+
reason: 'auth',
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('harness:login:cancel 下行:requestId 匹配才 cancel', async () => {
|
|
177
|
+
setup();
|
|
178
|
+
const pending = fake.handlers.get('acp:probe-options')?.({
|
|
179
|
+
requestId: 'r5',
|
|
180
|
+
serverType: 'kimi_code',
|
|
181
|
+
});
|
|
182
|
+
await tick();
|
|
183
|
+
const flow = login.instances[0];
|
|
184
|
+
(flow as any).handlersRef.onDeviceFlow({
|
|
185
|
+
url: 'https://kimi.test/login',
|
|
186
|
+
userCode: 'CODE-1',
|
|
187
|
+
expiresInSeconds: 1800,
|
|
188
|
+
});
|
|
189
|
+
const requestId = (emitted('harness:login:required')[0] as any).requestId;
|
|
190
|
+
|
|
191
|
+
fake.handlers.get('harness:login:cancel')?.({ requestId: 'req-other' });
|
|
192
|
+
expect(flow.cancel).not.toHaveBeenCalled();
|
|
193
|
+
fake.handlers.get('harness:login:cancel')?.({ requestId });
|
|
194
|
+
expect(flow.cancel).toHaveBeenCalledTimes(1);
|
|
195
|
+
|
|
196
|
+
(flow as any).resolveRef({ state: 'failed', reason: 'cancelled' });
|
|
197
|
+
await pending;
|
|
198
|
+
expect(emitted('acp:probe-options:result')[0]).toMatchObject({ success: false, reason: 'auth' });
|
|
199
|
+
});
|
|
200
|
+
});
|
package/src/socketio-client.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { io as createSocketIOClient, type Socket } from 'socket.io-client';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
2
3
|
import * as acp from '@agentclientprotocol/sdk';
|
|
3
4
|
import { hostname, platform } from 'os';
|
|
4
5
|
import { readdir, access } from 'fs/promises';
|
|
@@ -10,6 +11,7 @@ import { acpDetector } from './acp/detector.js';
|
|
|
10
11
|
import { probeAcpServerOptions } from './acp/prober.js';
|
|
11
12
|
import { AcpSpawner } from './acp/spawner.js';
|
|
12
13
|
import { AcpSessionBridge } from './acp/bridge.js';
|
|
14
|
+
import { AcpAuthGate, AuthRequiredError } from './acp/auth-gate.js';
|
|
13
15
|
import { AcpSyncBridge } from './acp/sync-bridge.js';
|
|
14
16
|
import { gitHandler } from './git-handler.js';
|
|
15
17
|
import { worktreeHandler } from './worktree-handler.js';
|
|
@@ -20,10 +22,13 @@ import { McpRelay } from './mcp/relay.js';
|
|
|
20
22
|
import { LocalMcpServer } from './mcp/local-server.js';
|
|
21
23
|
import { WorkloadExecutor, type WorkloadRunPayload, collectSecretValues, redactSecrets } from './workload-executor.js';
|
|
22
24
|
|
|
23
|
-
//
|
|
25
|
+
// 版本号唯一事实源为 package.json(register 上报的完整版本;服务端按 MIN_WORKER_VERSION=2.2.0 门禁)。
|
|
26
|
+
// 2.8.0 起 `kimi_code` 使用前登录闸门(`kimi login` stdio 判定 + `harness:login:*` 事件族);
|
|
24
27
|
// 2.6.0 起支持 `workload:run.githubAuth` 与云电脑 Github 凭据管理器(MIN_HARNESS_WORKER_VERSION=2.6.0);
|
|
25
28
|
// 2.5.0 起支持云电脑双连接(`/worker` + controller-api)与 `harness prepare`。
|
|
26
|
-
const CONTROLLER_VERSION =
|
|
29
|
+
const { version: CONTROLLER_VERSION } = createRequire(import.meta.url)('../package.json') as {
|
|
30
|
+
version: string;
|
|
31
|
+
};
|
|
27
32
|
// 进程内全局单实例:工作负载批次严格串行(新批次打断旧批次,见 workload-executor)。
|
|
28
33
|
const workloadExecutor = new WorkloadExecutor();
|
|
29
34
|
// shutdown 到达时若仍有 post 批次在跑,最多等待该时长后退出(契约 §2.8)。
|
|
@@ -77,6 +82,14 @@ export function buildAcpInitResult(payload: Record<string, unknown>): Record<str
|
|
|
77
82
|
return result;
|
|
78
83
|
}
|
|
79
84
|
|
|
85
|
+
/**
|
|
86
|
+
* 登录闸门失败时追加 `reason:'auth'`(A11,可选字段,向后兼容);
|
|
87
|
+
* 文案沿用 `AuthRequiredError` 的「Kimi Code 未登录」。
|
|
88
|
+
*/
|
|
89
|
+
export function authFailureFields(error: unknown): { reason?: 'auth' } {
|
|
90
|
+
return error instanceof AuthRequiredError ? { reason: 'auth' } : {};
|
|
91
|
+
}
|
|
92
|
+
|
|
80
93
|
interface RegisteredPayload {
|
|
81
94
|
controllerId: string;
|
|
82
95
|
resumeToken?: string;
|
|
@@ -419,6 +432,12 @@ export function connectToServer(
|
|
|
419
432
|
const controllerName = options?.serverName || hostname();
|
|
420
433
|
const persistConfig = options?.persistConfig !== false;
|
|
421
434
|
const mcpRelay = new McpRelay((payload) => socket.emit('mcp:request', payload));
|
|
435
|
+
// harness 使用前登录闸门:仅 `kimi_code` 生效(探测/拉起/恢复三处前置 ensure)。
|
|
436
|
+
const authGate = new AcpAuthGate({
|
|
437
|
+
emit: (event, payload) => {
|
|
438
|
+
socket.emit(event, payload);
|
|
439
|
+
},
|
|
440
|
+
});
|
|
422
441
|
const handleWorkload = options?.handleWorkload !== false;
|
|
423
442
|
// 双连接(云电脑)只启动一个本地 MCP 回环服务:worker 连接传 skipLocalMcpStart=true,
|
|
424
443
|
// controller-api 标准连接负责启动(ACP 会话的 `mcpEndpoint` 走标准连接)。
|
|
@@ -634,6 +653,7 @@ export function connectToServer(
|
|
|
634
653
|
socket.on('acp:probe-options', async (data: AcpProbeOptionsPayload) => {
|
|
635
654
|
console.log(`[ACP ctrl] acp:probe-options received: requestId=${data.requestId} serverType=${data.serverType}`);
|
|
636
655
|
try {
|
|
656
|
+
await authGate.ensure(data.serverType, 'probe-options');
|
|
637
657
|
const options = await probeAcpServerOptions(data.serverType);
|
|
638
658
|
console.log(`[ACP ctrl] probe-options success: serverType=${data.serverType} modes=${options.modes.length} models=${options.availableModels.length}`);
|
|
639
659
|
socket.emit('acp:probe-options:result', {
|
|
@@ -649,6 +669,7 @@ export function connectToServer(
|
|
|
649
669
|
serverType: data.serverType,
|
|
650
670
|
success: false,
|
|
651
671
|
error: (error as Error).message,
|
|
672
|
+
...authFailureFields(error),
|
|
652
673
|
});
|
|
653
674
|
}
|
|
654
675
|
});
|
|
@@ -657,6 +678,7 @@ export function connectToServer(
|
|
|
657
678
|
console.log(`[ACP ctrl] acp:start received: requestId=${data.requestId} sessionId=${data.sessionId} serverType=${data.serverType} cwd=${data.cwd} ${describeMcpConfig(data)}`);
|
|
658
679
|
|
|
659
680
|
try {
|
|
681
|
+
await authGate.ensure(data.serverType, 'acp:start');
|
|
660
682
|
// 同 sessionId 重复 start(如 start 超时后的兜底 resume/重试与迟到初始化交叠):
|
|
661
683
|
// 先停掉旧 bridge,避免同会话双进程、旧 bridge 泄漏
|
|
662
684
|
const existingBridge = acpBridges.get(data.sessionId);
|
|
@@ -796,6 +818,7 @@ export function connectToServer(
|
|
|
796
818
|
sessionId: data.sessionId,
|
|
797
819
|
success: false,
|
|
798
820
|
error: (error as Error).message,
|
|
821
|
+
...authFailureFields(error),
|
|
799
822
|
});
|
|
800
823
|
}
|
|
801
824
|
});
|
|
@@ -804,6 +827,7 @@ export function connectToServer(
|
|
|
804
827
|
console.log(`[ACP ctrl] acp:resume received: requestId=${data.requestId} sessionId=${data.sessionId} serverType=${data.serverType} externalSessionId=${data.externalSessionId} ${describeMcpConfig(data)}`);
|
|
805
828
|
|
|
806
829
|
try {
|
|
830
|
+
await authGate.ensure(data.serverType, 'acp:resume');
|
|
807
831
|
// 同 sessionId 重复 resume/start:先停掉旧 bridge(同 acp:start 的防双进程处理)
|
|
808
832
|
const existingBridge = acpBridges.get(data.sessionId);
|
|
809
833
|
if (existingBridge) {
|
|
@@ -911,10 +935,20 @@ export function connectToServer(
|
|
|
911
935
|
sessionId: data.sessionId,
|
|
912
936
|
success: false,
|
|
913
937
|
error: (error as Error).message,
|
|
938
|
+
...authFailureFields(error),
|
|
914
939
|
});
|
|
915
940
|
}
|
|
916
941
|
});
|
|
917
942
|
|
|
943
|
+
// harness 登录取消(Server → Controller,契约 §2.38):requestId 不匹配时忽略
|
|
944
|
+
socket.on('harness:login:cancel', (data: { requestId?: string }) => {
|
|
945
|
+
if (!data || typeof data.requestId !== 'string') {
|
|
946
|
+
console.warn('[ACP ctrl] harness:login:cancel ignored: invalid payload');
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
authGate.cancel(data.requestId);
|
|
950
|
+
});
|
|
951
|
+
|
|
918
952
|
socket.on('acp:list-sessions', async (data: AcpListSessionsPayload) => {
|
|
919
953
|
const serverType = data.serverType ?? 'opencode';
|
|
920
954
|
console.log(`[ACP sync] acp:list-sessions received: requestId=${data.requestId} serverType=${serverType} cwd=${data.cwd}`);
|
|
@@ -229,7 +229,7 @@ describe('SocketIO Client', () => {
|
|
|
229
229
|
expect(mockSocket.emit).toHaveBeenCalledWith('register', {
|
|
230
230
|
key: 'zag_k_1_abc123',
|
|
231
231
|
hostname: 'my-machine',
|
|
232
|
-
version: '2.
|
|
232
|
+
version: '2.8.0',
|
|
233
233
|
resumeToken: undefined,
|
|
234
234
|
homeDir: '/home/user',
|
|
235
235
|
platform: 'linux',
|
|
@@ -247,7 +247,7 @@ describe('SocketIO Client', () => {
|
|
|
247
247
|
expect(mockSocket.emit).toHaveBeenCalledWith('register', {
|
|
248
248
|
key: 'zag_k_1_abc123',
|
|
249
249
|
hostname: 'test-machine',
|
|
250
|
-
version: '2.
|
|
250
|
+
version: '2.8.0',
|
|
251
251
|
resumeToken: undefined,
|
|
252
252
|
homeDir: '/home/user',
|
|
253
253
|
platform: 'linux',
|