agent-gear 2.7.0 → 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.
Files changed (50) hide show
  1. package/AGENTS.md +17 -5
  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/commands/harness.js +1 -1
  11. package/dist/commands/harness.js.map +1 -1
  12. package/dist/harness/kimi-login.d.ts +124 -0
  13. package/dist/harness/kimi-login.d.ts.map +1 -0
  14. package/dist/harness/kimi-login.js +263 -0
  15. package/dist/harness/kimi-login.js.map +1 -0
  16. package/dist/harness/kimi-login.test.d.ts +2 -0
  17. package/dist/harness/kimi-login.test.d.ts.map +1 -0
  18. package/dist/harness/kimi-login.test.js +193 -0
  19. package/dist/harness/kimi-login.test.js.map +1 -0
  20. package/dist/harness/opencode-config.d.ts +7 -7
  21. package/dist/harness/opencode-config.d.ts.map +1 -1
  22. package/dist/harness/opencode-config.js +7 -7
  23. package/dist/harness/opencode-config.js.map +1 -1
  24. package/dist/harness/opencode-config.test.js +21 -21
  25. package/dist/harness/opencode-config.test.js.map +1 -1
  26. package/dist/harness/prepare.d.ts +1 -1
  27. package/dist/harness/prepare.js +1 -1
  28. package/dist/harness/prepare.test.js +3 -3
  29. package/dist/harness/prepare.test.js.map +1 -1
  30. package/dist/socketio-client.auth-gate.test.d.ts +2 -0
  31. package/dist/socketio-client.auth-gate.test.d.ts.map +1 -0
  32. package/dist/socketio-client.auth-gate.test.js +179 -0
  33. package/dist/socketio-client.auth-gate.test.js.map +1 -0
  34. package/dist/socketio-client.d.ts +7 -0
  35. package/dist/socketio-client.d.ts.map +1 -1
  36. package/dist/socketio-client.js +32 -2
  37. package/dist/socketio-client.js.map +1 -1
  38. package/package.json +1 -1
  39. package/src/acp/auth-gate.test.ts +145 -0
  40. package/src/acp/auth-gate.ts +144 -0
  41. package/src/commands/harness.ts +1 -1
  42. package/src/harness/kimi-login.test.ts +222 -0
  43. package/src/harness/kimi-login.ts +328 -0
  44. package/src/harness/opencode-config.test.ts +21 -21
  45. package/src/harness/opencode-config.ts +10 -10
  46. package/src/harness/prepare.test.ts +3 -3
  47. package/src/harness/prepare.ts +1 -1
  48. package/src/socketio-client.auth-gate.test.ts +200 -0
  49. package/src/socketio-client.ts +36 -2
  50. package/tests/socketio-client.test.ts +2 -2
@@ -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
+ });
@@ -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
+ }
@@ -4,7 +4,7 @@ import { join } from 'node:path';
4
4
  import { parse } from 'jsonc-parser';
5
5
  import {
6
6
  OpencodeConfigError,
7
- ZAG_PROVIDER_NPM,
7
+ ZAG_PROVIDER_PACKAGE,
8
8
  buildZagProvider,
9
9
  resolveOpencodeConfigPath,
10
10
  writeOpencodeConfig,
@@ -30,9 +30,9 @@ async function fileMode(path: string): Promise<number> {
30
30
  describe('buildZagProvider (T-AG9/T-AG11)', () => {
31
31
  it('builds an OpenAI-compatible provider with baseURL/apiKey/models', () => {
32
32
  expect(buildZagProvider(ENV)).toEqual({
33
- npm: '@ai-sdk/openai-compatible',
33
+ package: '@opencode/ai/providers/openai-compatible',
34
34
  name: 'ZAG',
35
- options: {
35
+ settings: {
36
36
  baseURL: 'http://admin-api:8002/v1',
37
37
  apiKey: 'zag_sk_super_secret',
38
38
  },
@@ -41,7 +41,7 @@ describe('buildZagProvider (T-AG9/T-AG11)', () => {
41
41
  'model-b': { name: 'model-b' },
42
42
  },
43
43
  });
44
- expect(ZAG_PROVIDER_NPM).toBe('@ai-sdk/openai-compatible');
44
+ expect(ZAG_PROVIDER_PACKAGE).toBe('@opencode/ai/providers/openai-compatible');
45
45
  });
46
46
 
47
47
  it('writes models:{} for an empty model list', () => {
@@ -69,7 +69,7 @@ describe('writeOpencodeConfig (T-AG9..T-AG12)', () => {
69
69
  await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
70
70
  });
71
71
 
72
- it('T-AG9: creates opencode.jsonc with provider.zag and 0600 permissions', async () => {
72
+ it('T-AG9: creates opencode.jsonc with providers.zag and 0600 permissions', async () => {
73
73
  const dir = await makeDir();
74
74
  dirs.push(dir);
75
75
 
@@ -81,15 +81,15 @@ describe('writeOpencodeConfig (T-AG9..T-AG12)', () => {
81
81
  expect(await fileMode(result.path)).toBe(0o600);
82
82
 
83
83
  const config = parse(await readFile(result.path, 'utf-8'));
84
- expect(config.provider.zag.options.baseURL).toBe('http://admin-api:8002/v1');
85
- expect(config.provider.zag.options.apiKey).toBe('zag_sk_super_secret');
86
- expect(config.provider.zag.models).toEqual({
84
+ expect(config.providers.zag.settings.baseURL).toBe('http://admin-api:8002/v1');
85
+ expect(config.providers.zag.settings.apiKey).toBe('zag_sk_super_secret');
86
+ expect(config.providers.zag.models).toEqual({
87
87
  'model-a': { name: 'model-a' },
88
88
  'model-b': { name: 'model-b' },
89
89
  });
90
90
  });
91
91
 
92
- it('T-AG10: merges an existing config, preserving comments and other providers and replacing provider.zag', async () => {
92
+ it('T-AG10: merges an existing config, preserving comments and other providers and replacing providers.zag', async () => {
93
93
  const dir = await makeDir();
94
94
  dirs.push(dir);
95
95
  const target = join(dir, 'opencode.jsonc');
@@ -98,18 +98,18 @@ describe('writeOpencodeConfig (T-AG9..T-AG12)', () => {
98
98
  `{
99
99
  // keep this comment
100
100
  "$schema": "https://opencode.ai/config.json",
101
- "provider": {
101
+ "providers": {
102
102
  // existing provider must survive
103
103
  "other": {
104
- "npm": "@example/other",
104
+ "package": "@example/other",
105
105
  "name": "Other",
106
- "options": { "baseURL": "http://other" },
106
+ "settings": { "baseURL": "http://other" },
107
107
  "models": { "x": { "name": "x" } }
108
108
  },
109
109
  "zag": {
110
- "npm": "old-npm",
110
+ "package": "old-package",
111
111
  "name": "Old ZAG",
112
- "options": { "baseURL": "http://old", "apiKey": "old-key" },
112
+ "settings": { "baseURL": "http://old", "apiKey": "old-key" },
113
113
  "models": {}
114
114
  }
115
115
  }
@@ -126,11 +126,11 @@ describe('writeOpencodeConfig (T-AG9..T-AG12)', () => {
126
126
 
127
127
  const config = parse(text);
128
128
  expect(config.$schema).toBe('https://opencode.ai/config.json');
129
- expect(config.provider.other).toMatchObject({ npm: '@example/other', name: 'Other' });
130
- expect(config.provider.zag).toMatchObject({
131
- npm: ZAG_PROVIDER_NPM,
129
+ expect(config.providers.other).toMatchObject({ package: '@example/other', name: 'Other' });
130
+ expect(config.providers.zag).toMatchObject({
131
+ package: ZAG_PROVIDER_PACKAGE,
132
132
  name: 'ZAG',
133
- options: { baseURL: 'http://admin-api:8002/v1', apiKey: 'zag_sk_super_secret' },
133
+ settings: { baseURL: 'http://admin-api:8002/v1', apiKey: 'zag_sk_super_secret' },
134
134
  });
135
135
  // 旧 apiKey/baseURL 已被替换
136
136
  expect(text).not.toContain('old-key');
@@ -144,7 +144,7 @@ describe('writeOpencodeConfig (T-AG9..T-AG12)', () => {
144
144
  await writeOpencodeConfig({ env: { ...ENV, modelIds: [] }, configDir: dir });
145
145
 
146
146
  const config = parse(await readFile(join(dir, 'opencode.jsonc'), 'utf-8'));
147
- expect(config.provider.zag.models).toEqual({});
147
+ expect(config.providers.zag.models).toEqual({});
148
148
  });
149
149
 
150
150
  it('T-AG12: merges an existing opencode.json instead of creating a new .jsonc', async () => {
@@ -161,7 +161,7 @@ describe('writeOpencodeConfig (T-AG9..T-AG12)', () => {
161
161
 
162
162
  const config = parse(await readFile(jsonPath, 'utf-8'));
163
163
  expect(config.theme).toBe('dark');
164
- expect(config.provider.zag.name).toBe('ZAG');
164
+ expect(config.providers.zag.name).toBe('ZAG');
165
165
 
166
166
  // 不创建并存的 .jsonc
167
167
  await expect(stat(join(dir, 'opencode.jsonc'))).rejects.toThrow();
@@ -202,7 +202,7 @@ describe('writeOpencodeConfig (T-AG9..T-AG12)', () => {
202
202
  expect(await fileMode(target)).toBe(0o600);
203
203
  const config = parse(await readFile(target, 'utf-8'));
204
204
  expect(config.theme).toBe('dark');
205
- expect(config.provider.zag.name).toBe('ZAG');
205
+ expect(config.providers.zag.name).toBe('ZAG');
206
206
  });
207
207
 
208
208
  it('C-7: keeps the original file intact when the write path fails', async () => {