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.
@@ -0,0 +1,145 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { AcpAuthGate, AuthRequiredError } from './auth-gate.js';
3
+ import type { KimiLoginHandlers, KimiLoginTerminal } from '../harness/kimi-login.js';
4
+ import type { KimiLoginFlowLike } from './auth-gate.js';
5
+
6
+ interface FakeFlow {
7
+ run: ReturnType<typeof vi.fn>;
8
+ cancel: ReturnType<typeof vi.fn>;
9
+ finish: (outcome: KimiLoginTerminal) => void;
10
+ handlers: () => KimiLoginHandlers;
11
+ }
12
+
13
+ function createFakeFlow(): FakeFlow {
14
+ let resolve!: (outcome: KimiLoginTerminal) => void;
15
+ let handlers: KimiLoginHandlers = {};
16
+ const run = vi.fn((value: KimiLoginHandlers = {}) => {
17
+ handlers = value;
18
+ return new Promise<KimiLoginTerminal>((done) => {
19
+ resolve = done;
20
+ });
21
+ });
22
+ return {
23
+ run,
24
+ cancel: vi.fn(),
25
+ finish: (outcome) => resolve(outcome),
26
+ handlers: () => handlers,
27
+ };
28
+ }
29
+
30
+ function setup(options: { cacheTtlMs?: number; now?: () => number } = {}) {
31
+ const flows: FakeFlow[] = [];
32
+ const emitted: Array<{ event: string; payload: Record<string, unknown> }> = [];
33
+ let seq = 0;
34
+ const gate = new AcpAuthGate({
35
+ emit: (event, payload) => emitted.push({ event, payload }),
36
+ createFlow: () => {
37
+ const flow = createFakeFlow();
38
+ flows.push(flow);
39
+ return flow as unknown as KimiLoginFlowLike;
40
+ },
41
+ createRequestId: () => `req-${++seq}`,
42
+ ...(options.cacheTtlMs != null ? { cacheTtlMs: options.cacheTtlMs } : {}),
43
+ ...(options.now ? { now: options.now } : {}),
44
+ });
45
+ return { gate, flows, emitted };
46
+ }
47
+
48
+ const DEVICE_FLOW = { url: 'https://kimi.test/login', userCode: 'CODE-1', expiresInSeconds: 1800 };
49
+
50
+ describe('AcpAuthGate', () => {
51
+ it('T-AG1: 非 kimi_code 立即 resolve,不创建流程、不发事件', async () => {
52
+ const { gate, flows, emitted } = setup();
53
+ await expect(gate.ensure('opencode', 'acp:start')).resolves.toBeUndefined();
54
+ expect(flows).toHaveLength(0);
55
+ expect(emitted).toHaveLength(0);
56
+ });
57
+
58
+ it('T-AG2/AG3: 缓存命中不重复登录,TTL 过期后重新登录', async () => {
59
+ let now = 1_000;
60
+ const { gate, flows } = setup({ cacheTtlMs: 100, now: () => now });
61
+ const first = gate.ensure('kimi_code', 'probe-options');
62
+ await Promise.resolve();
63
+ flows[0].handlers().onDeviceFlow?.(DEVICE_FLOW);
64
+ flows[0].finish({ state: 'logged-in', account: 'managed:kimi-code' });
65
+ await first;
66
+
67
+ await expect(gate.ensure('kimi_code', 'acp:start')).resolves.toBeUndefined();
68
+ expect(flows).toHaveLength(1);
69
+
70
+ now += 101;
71
+ const second = gate.ensure('kimi_code', 'acp:start');
72
+ await Promise.resolve();
73
+ expect(flows).toHaveLength(2);
74
+ flows[1].finish({ state: 'logged-in' });
75
+ await second;
76
+ });
77
+
78
+ it('T-AG4: 并发 3 次 ensure → 只 1 次 spawn、1 次 required、3 个 resolve', async () => {
79
+ const { gate, flows, emitted } = setup();
80
+ const all = [
81
+ gate.ensure('kimi_code', 'probe-options'),
82
+ gate.ensure('kimi_code', 'acp:start'),
83
+ gate.ensure('kimi_code', 'acp:resume'),
84
+ ];
85
+ await Promise.resolve();
86
+ expect(flows).toHaveLength(1);
87
+ flows[0].handlers().onDeviceFlow?.(DEVICE_FLOW);
88
+ flows[0].finish({ state: 'logged-in' });
89
+ await expect(Promise.all(all)).resolves.toEqual([undefined, undefined, undefined]);
90
+ expect(emitted.filter((item) => item.event === 'harness:login:required')).toHaveLength(1);
91
+ expect(emitted.map((item) => item.event)).toEqual([
92
+ 'harness:login:required',
93
+ 'harness:login:succeeded',
94
+ ]);
95
+ expect(emitted[0].payload).toEqual({
96
+ requestId: 'req-1',
97
+ serverType: 'kimi_code',
98
+ trigger: 'probe-options',
99
+ ...DEVICE_FLOW,
100
+ });
101
+ });
102
+
103
+ it('T-AG5: 失败 → 三次均 reject AuthRequiredError 并上行 failed', async () => {
104
+ const { gate, flows, emitted } = setup();
105
+ const all = [
106
+ gate.ensure('kimi_code', 'probe-options'),
107
+ gate.ensure('kimi_code', 'acp:start'),
108
+ gate.ensure('kimi_code', 'acp:resume'),
109
+ ];
110
+ await Promise.resolve();
111
+ flows[0].finish({ state: 'failed', reason: 'cancelled' });
112
+ for (const promise of all) {
113
+ await expect(promise).rejects.toBeInstanceOf(AuthRequiredError);
114
+ await expect(promise).rejects.toThrow('Kimi Code 未登录');
115
+ }
116
+ expect(emitted.at(-1)).toEqual({
117
+ event: 'harness:login:failed',
118
+ payload: { requestId: 'req-1', reason: 'cancelled' },
119
+ });
120
+ });
121
+
122
+ it('T-AG6: cancel 定向(其他 requestId 无效,当前生效)', async () => {
123
+ const { gate, flows } = setup();
124
+ const pending = gate.ensure('kimi_code', 'acp:start');
125
+ await Promise.resolve();
126
+ gate.cancel('req-other');
127
+ expect(flows[0].cancel).not.toHaveBeenCalled();
128
+ gate.cancel('req-1');
129
+ expect(flows[0].cancel).toHaveBeenCalledTimes(1);
130
+ flows[0].finish({ state: 'failed', reason: 'cancelled' });
131
+ await expect(pending).rejects.toBeInstanceOf(AuthRequiredError);
132
+ expect(gate.pendingRequestId).toBeNull();
133
+ });
134
+
135
+ it('T-AG7: 无 device-flow 且成功 → 仍写缓存(不误判)', async () => {
136
+ const { gate, flows, emitted } = setup();
137
+ const pending = gate.ensure('kimi_code', 'probe-options');
138
+ await Promise.resolve();
139
+ flows[0].finish({ state: 'logged-in' });
140
+ await expect(pending).resolves.toBeUndefined();
141
+ expect(emitted.map((item) => item.event)).toEqual(['harness:login:succeeded']);
142
+ await expect(gate.ensure('kimi_code', 'acp:start')).resolves.toBeUndefined();
143
+ expect(flows).toHaveLength(1);
144
+ });
145
+ });
@@ -0,0 +1,144 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { KimiLoginFlow, resolveKimiAuthCacheTtlMs, type KimiLoginHandlers, type KimiLoginTerminal } from '../harness/kimi-login.js';
3
+
4
+ /** 本期唯一需要登录闸门的 harness 类型。 */
5
+ export const KIMI_SERVER_TYPE = 'kimi_code';
6
+ /** 统一失败文案(前端原样展示,不新增错误码)。 */
7
+ export const AUTH_REQUIRED_MESSAGE = 'Kimi Code 未登录';
8
+
9
+ export type AuthTrigger = 'probe-options' | 'acp:start' | 'acp:resume';
10
+
11
+ /** 使用动作因未登录失败(handler 据此在 result 上带 `reason:'auth'`)。 */
12
+ export class AuthRequiredError extends Error {
13
+ readonly reason = 'auth' as const;
14
+ constructor(message: string = AUTH_REQUIRED_MESSAGE) {
15
+ super(message);
16
+ this.name = 'AuthRequiredError';
17
+ }
18
+ }
19
+
20
+ /** 出站 `harness:login:*` 事件(形状以契约 §2.35–2.37 为准)。 */
21
+ export interface HarnessLoginRequiredPayload {
22
+ requestId: string;
23
+ serverType: typeof KIMI_SERVER_TYPE;
24
+ trigger: AuthTrigger;
25
+ url: string;
26
+ userCode: string;
27
+ expiresInSeconds?: number;
28
+ }
29
+
30
+ export type HarnessLoginEmitter = (event: string, payload: Record<string, unknown>) => void;
31
+
32
+ /** 可注入的登录流程(生产为 KimiLoginFlow,测试用 fake)。 */
33
+ export interface KimiLoginFlowLike {
34
+ run(handlers?: KimiLoginHandlers): Promise<KimiLoginTerminal>;
35
+ cancel(): void;
36
+ }
37
+
38
+ export interface AcpAuthGateOptions {
39
+ emit?: HarnessLoginEmitter;
40
+ /** 登录缓存 TTL(默认 KIMI_AUTH_CACHE_TTL_MS / 300000)。 */
41
+ cacheTtlMs?: number;
42
+ now?: () => number;
43
+ createFlow?: () => KimiLoginFlowLike;
44
+ createRequestId?: () => string;
45
+ }
46
+
47
+ /**
48
+ * harness 使用前登录闸门(仅 `kimi_code`,其余 serverType 立即 resolve 零开销)。
49
+ *
50
+ * 单进程 single-flight:同一时刻只有一个 `kimi login` 与一条 `required`;
51
+ * 并发使用动作共享同一 Promise,登录成功后写入进程内 TTL 缓存(无 Redis 依赖)。
52
+ */
53
+ export class AcpAuthGate {
54
+ private readonly emit: HarnessLoginEmitter;
55
+ private readonly cacheTtlMs: number;
56
+ private readonly now: () => number;
57
+ private readonly createFlow: () => KimiLoginFlowLike;
58
+ private readonly createRequestId: () => string;
59
+
60
+ /** serverType → 缓存到期时间戳。 */
61
+ private readonly cache = new Map<string, number>();
62
+ private readonly inflight = new Map<string, Promise<void>>();
63
+ private current: { requestId: string; flow: KimiLoginFlowLike } | null = null;
64
+
65
+ constructor(options: AcpAuthGateOptions = {}) {
66
+ this.emit = options.emit ?? (() => {});
67
+ this.cacheTtlMs = options.cacheTtlMs ?? resolveKimiAuthCacheTtlMs();
68
+ this.now = options.now ?? Date.now;
69
+ this.createRequestId = options.createRequestId ?? randomUUID;
70
+ this.createFlow = options.createFlow ?? (() => new KimiLoginFlow());
71
+ }
72
+
73
+ /** 当前进行中的登录 requestId(无登录流程时为 null;供日志/测试)。 */
74
+ get pendingRequestId(): string | null {
75
+ return this.current?.requestId ?? null;
76
+ }
77
+
78
+ /** 缓存命中/非 kimi_code 立即 resolve;否则走(或复用)登录流程。 */
79
+ async ensure(serverType: string, trigger: AuthTrigger): Promise<void> {
80
+ if (serverType !== KIMI_SERVER_TYPE) return;
81
+ const expiresAt = this.cache.get(serverType);
82
+ if (expiresAt !== undefined && this.now() < expiresAt) return;
83
+ const existing = this.inflight.get(serverType);
84
+ if (existing) return existing;
85
+
86
+ const promise = this.runLogin(serverType, trigger).finally(() => {
87
+ if (this.inflight.get(serverType) === promise) this.inflight.delete(serverType);
88
+ });
89
+ this.inflight.set(serverType, promise);
90
+ return promise;
91
+ }
92
+
93
+ private async runLogin(serverType: string, trigger: AuthTrigger): Promise<void> {
94
+ const requestId = this.createRequestId();
95
+ const flow = this.createFlow();
96
+ this.current = { requestId, flow };
97
+
98
+ let outcome: KimiLoginTerminal;
99
+ try {
100
+ outcome = await flow.run({
101
+ onDeviceFlow: ({ url, userCode, expiresInSeconds }) => {
102
+ this.emit('harness:login:required', {
103
+ requestId,
104
+ serverType: KIMI_SERVER_TYPE,
105
+ trigger,
106
+ url,
107
+ userCode,
108
+ expiresInSeconds,
109
+ });
110
+ },
111
+ });
112
+ } finally {
113
+ if (this.current?.requestId === requestId) this.current = null;
114
+ }
115
+
116
+ if (outcome.state === 'logged-in') {
117
+ this.cache.set(serverType, this.now() + this.cacheTtlMs);
118
+ this.emit('harness:login:succeeded', {
119
+ requestId,
120
+ ...(outcome.account ? { account: outcome.account } : {}),
121
+ });
122
+ return;
123
+ }
124
+ this.emit('harness:login:failed', {
125
+ requestId,
126
+ reason: outcome.reason,
127
+ ...(outcome.error ? { error: outcome.error } : {}),
128
+ });
129
+ throw new AuthRequiredError();
130
+ }
131
+
132
+ /** 服务端 `harness:login:cancel` 下行:requestId 不匹配时忽略。 */
133
+ cancel(requestId: string): void {
134
+ if (!requestId || this.current?.requestId !== requestId) return;
135
+ this.current.flow.cancel();
136
+ }
137
+
138
+ /** 清空进程内登录状态(测试/调试用;不影响已登录凭证)。 */
139
+ reset(): void {
140
+ this.cache.clear();
141
+ this.inflight.clear();
142
+ this.current = null;
143
+ }
144
+ }
@@ -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
+ });