agent-gear 2.7.1 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +22 -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/acp/detector.d.ts +2 -0
- package/dist/acp/detector.d.ts.map +1 -1
- package/dist/acp/detector.js +18 -3
- package/dist/acp/detector.js.map +1 -1
- package/dist/acp/detector.test.d.ts +2 -0
- package/dist/acp/detector.test.d.ts.map +1 -0
- package/dist/acp/detector.test.js +50 -0
- package/dist/acp/detector.test.js.map +1 -0
- package/dist/commands/harness.d.ts +5 -1
- package/dist/commands/harness.d.ts.map +1 -1
- package/dist/commands/harness.js +7 -3
- package/dist/commands/harness.js.map +1 -1
- package/dist/harness/dsh-cli.d.ts +17 -0
- package/dist/harness/dsh-cli.d.ts.map +1 -0
- package/dist/harness/dsh-cli.js +51 -0
- package/dist/harness/dsh-cli.js.map +1 -0
- package/dist/harness/dsh-cli.test.d.ts +2 -0
- package/dist/harness/dsh-cli.test.d.ts.map +1 -0
- package/dist/harness/dsh-cli.test.js +51 -0
- package/dist/harness/dsh-cli.test.js.map +1 -0
- package/dist/harness/dsh-config.atomic-failure.test.d.ts +2 -0
- package/dist/harness/dsh-config.atomic-failure.test.d.ts.map +1 -0
- package/dist/harness/dsh-config.atomic-failure.test.js +35 -0
- package/dist/harness/dsh-config.atomic-failure.test.js.map +1 -0
- package/dist/harness/dsh-config.d.ts +46 -0
- package/dist/harness/dsh-config.d.ts.map +1 -0
- package/dist/harness/dsh-config.js +228 -0
- package/dist/harness/dsh-config.js.map +1 -0
- package/dist/harness/dsh-config.test.d.ts +2 -0
- package/dist/harness/dsh-config.test.d.ts.map +1 -0
- package/dist/harness/dsh-config.test.js +229 -0
- package/dist/harness/dsh-config.test.js.map +1 -0
- package/dist/harness/env.d.ts +11 -0
- package/dist/harness/env.d.ts.map +1 -1
- package/dist/harness/env.js +23 -0
- package/dist/harness/env.js.map +1 -1
- package/dist/harness/env.test.js +23 -1
- package/dist/harness/env.test.js.map +1 -1
- 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/harness/opencode-cli.d.ts +5 -0
- package/dist/harness/opencode-cli.d.ts.map +1 -1
- package/dist/harness/opencode-cli.js +8 -1
- package/dist/harness/opencode-cli.js.map +1 -1
- package/dist/harness/prepare.d.ts +27 -9
- package/dist/harness/prepare.d.ts.map +1 -1
- package/dist/harness/prepare.js +67 -23
- package/dist/harness/prepare.js.map +1 -1
- package/dist/harness/prepare.test.js +110 -3
- package/dist/harness/prepare.test.js.map +1 -1
- 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 +3 -2
- package/src/acp/auth-gate.test.ts +145 -0
- package/src/acp/auth-gate.ts +144 -0
- package/src/acp/detector.test.ts +64 -0
- package/src/acp/detector.ts +18 -3
- package/src/commands/harness.ts +9 -3
- package/src/harness/dsh-cli.test.ts +58 -0
- package/src/harness/dsh-cli.ts +67 -0
- package/src/harness/dsh-config.atomic-failure.test.ts +51 -0
- package/src/harness/dsh-config.test.ts +275 -0
- package/src/harness/dsh-config.ts +280 -0
- package/src/harness/env.test.ts +32 -1
- package/src/harness/env.ts +26 -0
- package/src/harness/kimi-login.test.ts +222 -0
- package/src/harness/kimi-login.ts +328 -0
- package/src/harness/opencode-cli.ts +9 -2
- package/src/harness/prepare.test.ts +129 -3
- package/src/harness/prepare.ts +103 -27
- package/src/socketio-client.auth-gate.test.ts +200 -0
- package/src/socketio-client.ts +36 -2
- package/tests/acp-detector.test.ts +28 -8
- package/tests/commands/harness.test.ts +17 -7
- 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
|
+
}
|
|
@@ -45,6 +45,14 @@ export function extractVersion(stdout: string, stderr = ''): string | undefined
|
|
|
45
45
|
return line.replace(/^v/i, '');
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/**
|
|
49
|
+
* 版本串归一化:取最后一个空白分隔段(容忍 `dsh 0.1.2` / `v0.1.2` 等输出前缀),
|
|
50
|
+
* 去掉 `v` 前缀。预发布段(如 `0.1.2-alpha.2`)原样保留。
|
|
51
|
+
*/
|
|
52
|
+
export function normalizeCliVersion(version: string): string {
|
|
53
|
+
return (version.trim().split(/\s+/).pop() ?? '').replace(/^v/i, '');
|
|
54
|
+
}
|
|
55
|
+
|
|
48
56
|
/**
|
|
49
57
|
* `opencode --version` 硬校验(`opencode -v` 仅作旧版 CLI 的兼容探测)。
|
|
50
58
|
*
|
|
@@ -60,8 +68,7 @@ export async function verifyOpencodeCli(
|
|
|
60
68
|
): Promise<string> {
|
|
61
69
|
const failures: string[] = [];
|
|
62
70
|
|
|
63
|
-
const normalizeVersion =
|
|
64
|
-
(version.trim().split(/\s+/).pop() ?? '').replace(/^v/i, '');
|
|
71
|
+
const normalizeVersion = normalizeCliVersion;
|
|
65
72
|
|
|
66
73
|
const ensureExpected = (version: string): string => {
|
|
67
74
|
if (expectedVersion && normalizeVersion(version) !== normalizeVersion(expectedVersion)) {
|
|
@@ -4,6 +4,7 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { parse } from 'jsonc-parser';
|
|
5
5
|
import { formatPrepareSummary, prepareHarness } from './prepare.js';
|
|
6
6
|
import { HarnessEnvError } from './env.js';
|
|
7
|
+
import { DshCliError } from './dsh-cli.js';
|
|
7
8
|
import { OpencodeCliError } from './opencode-cli.js';
|
|
8
9
|
import type { CommandRunner } from './opencode-cli.js';
|
|
9
10
|
|
|
@@ -45,11 +46,13 @@ describe('prepareHarness (T-AG7..T-AG12)', () => {
|
|
|
45
46
|
});
|
|
46
47
|
|
|
47
48
|
expect(runner).toHaveBeenCalledWith('opencode', ['--version']);
|
|
48
|
-
expect(result.
|
|
49
|
+
expect(result.items).toHaveLength(1);
|
|
50
|
+
expect(result.items[0]).toMatchObject({ type: 'opencode', version: '1.2.3', modelCount: 2 });
|
|
49
51
|
expect(result.env).toMatchObject({
|
|
50
52
|
modelBaseUrl: 'http://admin-api:8002/v1',
|
|
51
53
|
defaultWorkspace: workspace,
|
|
52
54
|
modelCount: 2,
|
|
55
|
+
types: ['opencode'],
|
|
53
56
|
});
|
|
54
57
|
expect((await stat(workspace)).isDirectory()).toBe(true);
|
|
55
58
|
|
|
@@ -129,11 +132,134 @@ describe('prepareHarness (T-AG7..T-AG12)', () => {
|
|
|
129
132
|
});
|
|
130
133
|
|
|
131
134
|
const summary = formatPrepareSummary(result);
|
|
132
|
-
expect(summary).toContain('
|
|
133
|
-
expect(summary).toContain('version=1.2.3');
|
|
135
|
+
expect(summary).toContain('Harness prepared: types=opencode');
|
|
136
|
+
expect(summary).toContain('- opencode: version=1.2.3');
|
|
134
137
|
expect(summary).toContain('models=2');
|
|
135
138
|
expect(summary).toContain('workspace=/root/workspace');
|
|
136
139
|
expect(summary).not.toContain('zag_sk_super_secret');
|
|
137
140
|
expect(summary).not.toContain('admin-api');
|
|
138
141
|
});
|
|
142
|
+
|
|
143
|
+
it('T-PREP1: ZAG_HARNESS_TYPES=deepseek_harness 只跑 dsh 校验与写入,不触碰 opencode', async () => {
|
|
144
|
+
const dir = await makeDir();
|
|
145
|
+
dirs.push(dir);
|
|
146
|
+
const configDir = join(dir, 'opencode-config');
|
|
147
|
+
const dshHome = join(dir, 'dsh-home');
|
|
148
|
+
const runner = vi.fn<CommandRunner>(async () => ({ stdout: '0.1.2-alpha.2\n', stderr: '' }));
|
|
149
|
+
|
|
150
|
+
const result = await prepareHarness({
|
|
151
|
+
env: {
|
|
152
|
+
...VALID_ENV,
|
|
153
|
+
ZAG_HARNESS_TYPES: 'deepseek_harness',
|
|
154
|
+
ZAG_DEFAULT_WORKSPACE: join(dir, 'workspace'),
|
|
155
|
+
},
|
|
156
|
+
runner,
|
|
157
|
+
configDir,
|
|
158
|
+
dshHome,
|
|
159
|
+
makeDir: async (path: string) => {
|
|
160
|
+
await mkdir(path, { recursive: true });
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
expect(runner).toHaveBeenCalledTimes(1);
|
|
165
|
+
expect(runner).toHaveBeenCalledWith('dsh', ['--version']);
|
|
166
|
+
expect(result.env.types).toEqual(['deepseek_harness']);
|
|
167
|
+
expect(result.items).toHaveLength(1);
|
|
168
|
+
expect(result.items[0]).toMatchObject({
|
|
169
|
+
type: 'deepseek_harness',
|
|
170
|
+
version: '0.1.2-alpha.2',
|
|
171
|
+
modelCount: 2,
|
|
172
|
+
});
|
|
173
|
+
await expect(stat(configDir)).rejects.toThrow();
|
|
174
|
+
expect((await stat(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'))).isFile()).toBe(true);
|
|
175
|
+
expect((await stat(join(dshHome, '.credentials.yaml'))).isFile()).toBe(true);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it('T-PREP2: 未设置/空串/全部非法 → 回退 opencode;kimi_code 被过滤', async () => {
|
|
179
|
+
const dir = await makeDir();
|
|
180
|
+
dirs.push(dir);
|
|
181
|
+
const runner = vi.fn<CommandRunner>(async () => ({ stdout: '1.2.3', stderr: '' }));
|
|
182
|
+
|
|
183
|
+
for (const ZAG_HARNESS_TYPES of [undefined, '', 'kimi_code', 'kimi_code,bogus']) {
|
|
184
|
+
const result = await prepareHarness({
|
|
185
|
+
env: { ...VALID_ENV, ZAG_HARNESS_TYPES } as NodeJS.ProcessEnv,
|
|
186
|
+
runner,
|
|
187
|
+
configDir: join(dir, `config-${String(ZAG_HARNESS_TYPES)}`),
|
|
188
|
+
makeDir: async () => {},
|
|
189
|
+
});
|
|
190
|
+
expect(result.env.types).toEqual(['opencode']);
|
|
191
|
+
}
|
|
192
|
+
expect(runner).toHaveBeenCalledWith('opencode', ['--version']);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('T-PREP3: opencode,deepseek_harness 两类各执行一次,顺序稳定、摘要两行', async () => {
|
|
196
|
+
const dir = await makeDir();
|
|
197
|
+
dirs.push(dir);
|
|
198
|
+
const runner = vi.fn<CommandRunner>(async (command: string) =>
|
|
199
|
+
command === 'dsh'
|
|
200
|
+
? { stdout: '0.1.2-alpha.2\n', stderr: '' }
|
|
201
|
+
: { stdout: '1.2.3\n', stderr: '' },
|
|
202
|
+
);
|
|
203
|
+
|
|
204
|
+
const result = await prepareHarness({
|
|
205
|
+
env: {
|
|
206
|
+
...VALID_ENV,
|
|
207
|
+
ZAG_HARNESS_TYPES: 'opencode, deepseek_harness,kimi_code,opencode',
|
|
208
|
+
},
|
|
209
|
+
runner,
|
|
210
|
+
configDir: join(dir, 'config'),
|
|
211
|
+
dshHome: join(dir, 'dsh-home'),
|
|
212
|
+
makeDir: async () => {},
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
expect(result.env.types).toEqual(['opencode', 'deepseek_harness']);
|
|
216
|
+
expect(result.items.map((item) => item.type)).toEqual(['opencode', 'deepseek_harness']);
|
|
217
|
+
expect(runner).toHaveBeenNthCalledWith(1, 'opencode', ['--version']);
|
|
218
|
+
expect(runner).toHaveBeenNthCalledWith(2, 'dsh', ['--version']);
|
|
219
|
+
|
|
220
|
+
const summary = formatPrepareSummary(result);
|
|
221
|
+
expect(summary.split('\n')).toHaveLength(3);
|
|
222
|
+
expect(summary).toContain('- opencode: version=1.2.3');
|
|
223
|
+
expect(summary).toContain('- deepseek_harness: version=0.1.2-alpha.2');
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
it('T-PREP4: 重复执行 deepseek_harness 幂等(文件内容一致)', async () => {
|
|
227
|
+
const dir = await makeDir();
|
|
228
|
+
dirs.push(dir);
|
|
229
|
+
const dshHome = join(dir, 'dsh-home');
|
|
230
|
+
const options = {
|
|
231
|
+
env: { ...VALID_ENV, ZAG_HARNESS_TYPES: 'deepseek_harness' },
|
|
232
|
+
runner: async () => ({ stdout: '0.1.2-alpha.2\n', stderr: '' }),
|
|
233
|
+
dshHome,
|
|
234
|
+
makeDir: async () => {},
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
await prepareHarness(options);
|
|
238
|
+
const firstPatch = await readFile(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'), 'utf-8');
|
|
239
|
+
await prepareHarness(options);
|
|
240
|
+
const secondPatch = await readFile(join(dshHome, 'profiles', 'acp', 'cordis.patch.yml'), 'utf-8');
|
|
241
|
+
|
|
242
|
+
expect(secondPatch).toBe(firstPatch);
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it('T-PREP5: dsh 校验失败 → 整体抛错且不写配置(opencode 未执行)', async () => {
|
|
246
|
+
const dir = await makeDir();
|
|
247
|
+
dirs.push(dir);
|
|
248
|
+
const dshHome = join(dir, 'dsh-home');
|
|
249
|
+
const runner = vi.fn<CommandRunner>(async () => {
|
|
250
|
+
throw new Error('spawn dsh ENOENT');
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
await expect(
|
|
254
|
+
prepareHarness({
|
|
255
|
+
env: { ...VALID_ENV, ZAG_HARNESS_TYPES: 'deepseek_harness' },
|
|
256
|
+
runner,
|
|
257
|
+
dshHome,
|
|
258
|
+
makeDir: async () => {},
|
|
259
|
+
}),
|
|
260
|
+
).rejects.toBeInstanceOf(DshCliError);
|
|
261
|
+
|
|
262
|
+
expect(runner).toHaveBeenCalledTimes(1);
|
|
263
|
+
await expect(stat(join(dshHome, 'profiles'))).rejects.toThrow();
|
|
264
|
+
});
|
|
139
265
|
});
|
package/src/harness/prepare.ts
CHANGED
|
@@ -1,13 +1,30 @@
|
|
|
1
1
|
import { mkdir } from 'node:fs/promises';
|
|
2
|
-
import { readHarnessEnv, type HarnessEnv } from './env.js';
|
|
2
|
+
import { readHarnessEnv, resolvePrepareTypes, type HarnessEnv, type PrepareHarnessType } from './env.js';
|
|
3
|
+
import { verifyDshCli } from './dsh-cli.js';
|
|
4
|
+
import { writeDshConfig, defaultDshHome, type WriteDshConfigResult } from './dsh-config.js';
|
|
3
5
|
import { verifyOpencodeCli, type CommandRunner } from './opencode-cli.js';
|
|
4
6
|
import { writeOpencodeConfig, type WriteOpencodeConfigResult } from './opencode-config.js';
|
|
5
7
|
|
|
8
|
+
/** 逐类型的 prepare 结果(摘要不含任何 secret)。 */
|
|
9
|
+
export interface HarnessPrepareItemResult {
|
|
10
|
+
type: PrepareHarnessType;
|
|
11
|
+
ok: boolean;
|
|
12
|
+
/** 实际 CLI 版本(opencode / dsh)。 */
|
|
13
|
+
version: string;
|
|
14
|
+
/** 写入的模型数量。 */
|
|
15
|
+
modelCount: number;
|
|
16
|
+
/** 一行摘要(用于 `harness prepare` 输出)。 */
|
|
17
|
+
summary: string;
|
|
18
|
+
config: WriteOpencodeConfigResult | WriteDshConfigResult;
|
|
19
|
+
}
|
|
20
|
+
|
|
6
21
|
/** `harness prepare` 结果摘要(不含任何 secret)。 */
|
|
7
22
|
export interface HarnessPrepareResult {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
23
|
+
env: Pick<HarnessEnv, 'modelBaseUrl' | 'defaultWorkspace'> & {
|
|
24
|
+
modelCount: number;
|
|
25
|
+
types: PrepareHarnessType[];
|
|
26
|
+
};
|
|
27
|
+
items: HarnessPrepareItemResult[];
|
|
11
28
|
}
|
|
12
29
|
|
|
13
30
|
export interface PrepareHarnessOptions {
|
|
@@ -16,54 +33,113 @@ export interface PrepareHarnessOptions {
|
|
|
16
33
|
runner?: CommandRunner;
|
|
17
34
|
/** 覆盖 OpenCode 配置目录(测试/定制场景)。 */
|
|
18
35
|
configDir?: string;
|
|
36
|
+
/** 覆盖 dsh home(测试/定制场景;缺省 `$DSH_HOME` 或 `~/.dsh`)。 */
|
|
37
|
+
dshHome?: string;
|
|
19
38
|
/** 创建工作区的实现(测试注入)。 */
|
|
20
39
|
makeDir?: (path: string) => Promise<void>;
|
|
21
40
|
}
|
|
22
41
|
|
|
42
|
+
function formatOpencodeSummary(
|
|
43
|
+
version: string,
|
|
44
|
+
config: WriteOpencodeConfigResult,
|
|
45
|
+
): string {
|
|
46
|
+
return `opencode: version=${version} models=${config.modelCount} config=${config.path} (${config.created ? 'created' : 'updated'})`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function formatDeepseekSummary(
|
|
50
|
+
version: string,
|
|
51
|
+
config: WriteDshConfigResult,
|
|
52
|
+
): string {
|
|
53
|
+
return [
|
|
54
|
+
`deepseek_harness: version=${version}`,
|
|
55
|
+
`models=${config.modelCount}`,
|
|
56
|
+
`patch=${config.patchPath} (${config.patchCreated ? 'created' : 'updated'})`,
|
|
57
|
+
`credentials=${config.credentialsPath} (${config.credentialsCreated ? 'created' : 'updated'})`,
|
|
58
|
+
].join(' ');
|
|
59
|
+
}
|
|
60
|
+
|
|
23
61
|
/**
|
|
24
|
-
* 准备
|
|
62
|
+
* 准备 harness 环境(契约/计划 Phase 4):
|
|
25
63
|
*
|
|
26
|
-
* 1. 校验 harness env
|
|
27
|
-
* 2. `
|
|
28
|
-
*
|
|
29
|
-
*
|
|
64
|
+
* 1. 校验 harness env(缺失项明确报错,只执行一次);
|
|
65
|
+
* 2. 按 `ZAG_HARNESS_TYPES` 分流(缺省/空/全非法 → `['opencode']`)逐类型 CLI 硬校验
|
|
66
|
+
* (`opencode --version` / `dsh --version`),全部通过前不触碰文件系统;
|
|
67
|
+
* 3. `mkdir -p ZAG_DEFAULT_WORKSPACE`(幂等,只执行一次);
|
|
68
|
+
* 4. 逐类型写入:`opencode` → 合并 `opencode.jsonc`;`deepseek_harness` → 合并
|
|
69
|
+
* `cordis.patch.yml` / `.credentials.yaml`。任一类型失败整体抛错,已成功部分不回滚(幂等重跑)。
|
|
30
70
|
*
|
|
71
|
+
* 只对所选类型做 CLI 校验与写入:`deepseek_harness` 单选时不触碰 opencode(反之亦然)。
|
|
31
72
|
* secret 只写入配置文件,不进入日志/错误/返回值。
|
|
32
73
|
*/
|
|
33
74
|
export async function prepareHarness(
|
|
34
75
|
options: PrepareHarnessOptions = {},
|
|
35
76
|
): Promise<HarnessPrepareResult> {
|
|
36
|
-
const
|
|
37
|
-
|
|
38
|
-
const
|
|
39
|
-
|
|
77
|
+
const sourceEnv = options.env ?? process.env;
|
|
78
|
+
const env = readHarnessEnv(sourceEnv);
|
|
79
|
+
const types = resolvePrepareTypes(sourceEnv);
|
|
80
|
+
|
|
81
|
+
const makeDir =
|
|
82
|
+
options.makeDir ?? ((path: string) => mkdir(path, { recursive: true }).then(() => undefined));
|
|
83
|
+
|
|
84
|
+
const versions = new Map<PrepareHarnessType, string>();
|
|
85
|
+
for (const type of types) {
|
|
86
|
+
// init 脚本 export OPENCODE_CLI_VERSION / DSH_CLI_VERSION:agent-gear 侧做二次硬校验
|
|
87
|
+
//(opencode C-5 缺省不启用;dsh 预发布段精确比较)。
|
|
88
|
+
versions.set(
|
|
89
|
+
type,
|
|
90
|
+
type === 'opencode'
|
|
91
|
+
? await verifyOpencodeCli(options.runner, sourceEnv.OPENCODE_CLI_VERSION)
|
|
92
|
+
: await verifyDshCli(options.runner, sourceEnv.DSH_CLI_VERSION),
|
|
93
|
+
);
|
|
94
|
+
}
|
|
40
95
|
|
|
41
|
-
const makeDir = options.makeDir ?? ((path: string) => mkdir(path, { recursive: true }).then(() => undefined));
|
|
42
96
|
await makeDir(env.defaultWorkspace);
|
|
43
97
|
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
98
|
+
const items: HarnessPrepareItemResult[] = [];
|
|
99
|
+
for (const type of types) {
|
|
100
|
+
const version = versions.get(type)!;
|
|
101
|
+
if (type === 'opencode') {
|
|
102
|
+
const config = await writeOpencodeConfig({ env, configDir: options.configDir });
|
|
103
|
+
items.push({
|
|
104
|
+
type,
|
|
105
|
+
ok: true,
|
|
106
|
+
version,
|
|
107
|
+
modelCount: config.modelCount,
|
|
108
|
+
summary: formatOpencodeSummary(version, config),
|
|
109
|
+
config,
|
|
110
|
+
});
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const config = await writeDshConfig({
|
|
115
|
+
env,
|
|
116
|
+
dshHome: options.dshHome ?? defaultDshHome(sourceEnv),
|
|
117
|
+
});
|
|
118
|
+
items.push({
|
|
119
|
+
type,
|
|
120
|
+
ok: true,
|
|
121
|
+
version,
|
|
122
|
+
modelCount: config.modelCount,
|
|
123
|
+
summary: formatDeepseekSummary(version, config),
|
|
124
|
+
config,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
48
127
|
|
|
49
128
|
return {
|
|
50
|
-
opencodeVersion,
|
|
51
129
|
env: {
|
|
52
130
|
modelBaseUrl: env.modelBaseUrl,
|
|
53
131
|
defaultWorkspace: env.defaultWorkspace,
|
|
54
132
|
modelCount: env.modelIds.length,
|
|
133
|
+
types,
|
|
55
134
|
},
|
|
56
|
-
|
|
135
|
+
items,
|
|
57
136
|
};
|
|
58
137
|
}
|
|
59
138
|
|
|
60
|
-
/**
|
|
139
|
+
/** 输出摘要(首行汇总,随后逐类型一行;不含 `ZAG_MODEL_API_KEY` / provider apiKey)。 */
|
|
61
140
|
export function formatPrepareSummary(result: HarnessPrepareResult): string {
|
|
62
|
-
const created = result.config.created ? 'created' : 'updated';
|
|
63
141
|
return [
|
|
64
|
-
`
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
`config=${result.config.path} (${created})`,
|
|
68
|
-
].join(' ');
|
|
142
|
+
`Harness prepared: types=${result.env.types.join(',')} models=${result.env.modelCount} workspace=${result.env.defaultWorkspace}`,
|
|
143
|
+
...result.items.map((item) => `- ${item.summary}`),
|
|
144
|
+
].join('\n');
|
|
69
145
|
}
|