agent-gear 2.16.0 → 2.17.1

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 (47) hide show
  1. package/AGENTS.md +21 -4
  2. package/dist/acp/bridge.d.ts +8 -0
  3. package/dist/acp/bridge.d.ts.map +1 -1
  4. package/dist/acp/bridge.js +16 -3
  5. package/dist/acp/bridge.js.map +1 -1
  6. package/dist/acp/bridge.test.js +74 -0
  7. package/dist/acp/bridge.test.js.map +1 -1
  8. package/dist/fs-handler.d.ts +14 -0
  9. package/dist/fs-handler.d.ts.map +1 -1
  10. package/dist/fs-handler.js +89 -1
  11. package/dist/fs-handler.js.map +1 -1
  12. package/dist/fs-handler.read.test.d.ts +2 -0
  13. package/dist/fs-handler.read.test.d.ts.map +1 -0
  14. package/dist/fs-handler.read.test.js +107 -0
  15. package/dist/fs-handler.read.test.js.map +1 -0
  16. package/dist/mcp/relay.d.ts +1 -0
  17. package/dist/mcp/relay.d.ts.map +1 -1
  18. package/dist/mcp/relay.js +19 -2
  19. package/dist/mcp/relay.js.map +1 -1
  20. package/dist/mcp/relay.test.js +38 -0
  21. package/dist/mcp/relay.test.js.map +1 -1
  22. package/dist/observability/logger.d.ts.map +1 -1
  23. package/dist/observability/logger.js +2 -0
  24. package/dist/observability/logger.js.map +1 -1
  25. package/dist/socketio-client.d.ts.map +1 -1
  26. package/dist/socketio-client.js +10 -0
  27. package/dist/socketio-client.js.map +1 -1
  28. package/dist/socketio-client.test.js +38 -0
  29. package/dist/socketio-client.test.js.map +1 -1
  30. package/dist/worktree-handler.d.ts +23 -0
  31. package/dist/worktree-handler.d.ts.map +1 -1
  32. package/dist/worktree-handler.js +75 -6
  33. package/dist/worktree-handler.js.map +1 -1
  34. package/dist/worktree-handler.test.js +91 -0
  35. package/dist/worktree-handler.test.js.map +1 -1
  36. package/package.json +1 -1
  37. package/src/acp/bridge.test.ts +94 -0
  38. package/src/acp/bridge.ts +27 -5
  39. package/src/fs-handler.read.test.ts +128 -0
  40. package/src/fs-handler.ts +93 -1
  41. package/src/mcp/relay.test.ts +46 -1
  42. package/src/mcp/relay.ts +24 -2
  43. package/src/observability/logger.ts +2 -0
  44. package/src/socketio-client.test.ts +42 -0
  45. package/src/socketio-client.ts +22 -0
  46. package/src/worktree-handler.test.ts +95 -0
  47. package/src/worktree-handler.ts +88 -7
package/src/mcp/relay.ts CHANGED
@@ -27,6 +27,27 @@ interface PendingRequest {
27
27
 
28
28
  const REQUEST_TIMEOUT_MS = 60_000;
29
29
 
30
+ /** Review 等长等待 MCP 服务超时默认值(30min,契约 §2.12.1;env MCP_REVIEW_TIMEOUT_MS 可调) */
31
+ const MCP_REVIEW_TIMEOUT_DEFAULT_MS = 1_800_000;
32
+
33
+ /** 平台内建长时工具服务:会话 Review(agent-api agent-session-preview-tools) */
34
+ const PREVIEW_TOOLS_SERVER_NAME = 'agent-session-preview-tools';
35
+
36
+ function getMcpReviewTimeoutMs(): number {
37
+ const raw = process.env.MCP_REVIEW_TIMEOUT_MS;
38
+ const parsed = raw ? Number(raw) : NaN;
39
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : MCP_REVIEW_TIMEOUT_DEFAULT_MS;
40
+ }
41
+
42
+ /** 按 serverName 取超时的常量表(裁决 9):仅 preview-tools 放宽,其余 server 保持 60s */
43
+ const SERVER_TIMEOUT_OVERRIDES: Record<string, () => number> = {
44
+ [PREVIEW_TOOLS_SERVER_NAME]: getMcpReviewTimeoutMs,
45
+ };
46
+
47
+ export function resolveServerTimeoutMs(serverName: string): number {
48
+ return SERVER_TIMEOUT_OVERRIDES[serverName]?.() ?? REQUEST_TIMEOUT_MS;
49
+ }
50
+
30
51
  export class McpRelay {
31
52
  private pendingRequests = new Map<string, PendingRequest>();
32
53
  private sessionEndpoints = new Map<string, SessionEndpoint>();
@@ -73,14 +94,15 @@ export class McpRelay {
73
94
  () => {
74
95
  this.log.debug({ event: 'mcp_forward', requestId, sessionId, serverName, method }, 'mcp forward');
75
96
  return new Promise<McpRelayResult>((resolve) => {
97
+ const timeoutMs = resolveServerTimeoutMs(serverName);
76
98
  const timer = setTimeout(() => {
77
99
  this.pendingRequests.delete(requestId);
78
100
  this.log.info(
79
- { event: 'mcp_forward_timeout', requestId, timeoutMs: REQUEST_TIMEOUT_MS },
101
+ { event: 'mcp_forward_timeout', requestId, timeoutMs },
80
102
  'mcp request timed out',
81
103
  );
82
104
  resolve({ status: 504, body: { error: 'TIMEOUT', message: 'MCP request timed out' } });
83
- }, REQUEST_TIMEOUT_MS);
105
+ }, timeoutMs);
84
106
  this.pendingRequests.set(requestId, { sessionId, resolve, timer });
85
107
  this.emitMcpRequest({ requestId, sessionId, serverName, token: endpoint.token, body });
86
108
  });
@@ -35,6 +35,8 @@ export const REDACT_PATHS: string[] = [
35
35
  'password', 'passwordHash', 'secret', 'clientSecret', 'privateKey',
36
36
  'apiKey', 'modelApiKey',
37
37
  '*.token', '*.password', '*.secret', '*.apiKey', '*.authorization',
38
+ // D4(MCP+Valut):契约入参嵌套形态精确路径;禁止裸 `*.value`(误伤计费/计量日志)
39
+ '*.newToken', '*.input.value', '*.input.newToken',
38
40
  'secrets', 'secrets.*',
39
41
  'err.config.headers.authorization',
40
42
  ];
@@ -555,3 +555,45 @@ describe('ACP bridge lifecycle wiring (reconcile / disconnect)', () => {
555
555
  expect(bridge.settlePendingOnDisconnect).toHaveBeenCalledTimes(1);
556
556
  });
557
557
  });
558
+
559
+ describe('fs:read-file 事件(T-RF8)', () => {
560
+ beforeEach(() => {
561
+ fake.handlers.clear();
562
+ fake.socket.emit.mockClear();
563
+ setup();
564
+ });
565
+
566
+ it('fs:read-file → fs:read-file:result 回包 requestId 与结果透传', async () => {
567
+ const { mkdtempSync, writeFileSync, rmSync } = await import('fs');
568
+ const { join } = await import('path');
569
+ const { tmpdir } = await import('os');
570
+ const { fsHandler } = await import('./fs-handler.js');
571
+
572
+ const dir = mkdtempSync(join(tmpdir(), 'sio-read-'));
573
+ writeFileSync(join(dir, 'a.txt'), 'content');
574
+ fsHandler.registerAllowedPath(dir);
575
+ try {
576
+ const handler = fake.handlers.get('fs:read-file') as (payload: unknown) => Promise<void>;
577
+ expect(handler).toBeDefined();
578
+
579
+ await handler({ requestId: 'r1', path: join(dir, 'a.txt') });
580
+ expect(fake.socket.emit).toHaveBeenCalledWith('fs:read-file:result', {
581
+ requestId: 'r1',
582
+ success: true,
583
+ content: 'content',
584
+ truncated: false,
585
+ sizeBytes: 7,
586
+ });
587
+
588
+ await handler({ requestId: 'r2', path: '/etc/passwd' });
589
+ expect(fake.socket.emit).toHaveBeenCalledWith('fs:read-file:result', {
590
+ requestId: 'r2',
591
+ success: false,
592
+ error: 'not found',
593
+ });
594
+ } finally {
595
+ fsHandler.unregisterAllowedPath(dir);
596
+ rmSync(dir, { recursive: true, force: true });
597
+ }
598
+ });
599
+ });
@@ -313,6 +313,16 @@ interface GitWorktreeAddPayload {
313
313
  };
314
314
  }
315
315
 
316
+ interface GitWorktreeCoAuthorPayload {
317
+ requestId: string;
318
+ worktreePath: string;
319
+ /** 缺省 = 关闭共同作者(仅清理本平台写入的受管配置)。 */
320
+ coAuthor?: {
321
+ name: string;
322
+ email: string;
323
+ };
324
+ }
325
+
316
326
  interface GitWorktreeRemovePayload {
317
327
  requestId: string;
318
328
  repoPath: string;
@@ -1501,6 +1511,11 @@ export function connectToServer(
1501
1511
  socket.emit('git:worktree:add:result', { requestId: data.requestId, ...result });
1502
1512
  });
1503
1513
 
1514
+ socket.on('git:worktree:coauthor', async (data: GitWorktreeCoAuthorPayload) => {
1515
+ const result = await worktreeHandler.configureCoAuthor(data.worktreePath, data.coAuthor);
1516
+ socket.emit('git:worktree:coauthor:result', { requestId: data.requestId, ...result });
1517
+ });
1518
+
1504
1519
  socket.on('git:worktree:remove', async (data: GitWorktreeRemovePayload & { force?: boolean }) => {
1505
1520
  const result = await worktreeHandler.remove(data.repoPath, data.worktreePath, data.force);
1506
1521
  socket.emit('git:worktree:remove:result', { requestId: data.requestId, ...result });
@@ -1536,6 +1551,13 @@ export function connectToServer(
1536
1551
  socket.emit('fs:remove-dir:result', { requestId: data.requestId, ...result });
1537
1552
  });
1538
1553
 
1554
+ // FS read-file event(契约 §3.25/§3.26:白名单限量文本读取)
1555
+ socket.on('fs:read-file', async (data: { requestId: string; path: string; maxBytes?: number }) => {
1556
+ log.info({ event: 'fs_read_file', requestId: data.requestId, path: data.path }, 'fs:read-file received');
1557
+ const result = await fsHandler.readFile(data.path, data.maxBytes);
1558
+ socket.emit('fs:read-file:result', { requestId: data.requestId, ...result });
1559
+ });
1560
+
1539
1561
  // Reconnection reconciliation
1540
1562
  socket.on('acp:reconcile', async (data: { activeSessionIds: string[]; pendingKillSessionIds: string[] }) => {
1541
1563
  if (!data || !isStringArray(data.activeSessionIds) || !isStringArray(data.pendingKillSessionIds)) {
@@ -291,6 +291,101 @@ describe('WorktreeHandler', () => {
291
291
  });
292
292
  });
293
293
 
294
+ describe('configureCoAuthor', () => {
295
+ it('T-WTC9: 已有 Worktree 启用共同作者时写 hook、worktree hooksPath 与 bot 身份', async () => {
296
+ const commands: string[] = [];
297
+ (exec as unknown as ReturnType<typeof vi.fn>).mockImplementation((...args: unknown[]) => {
298
+ const command = args[0] as string;
299
+ commands.push(command);
300
+ const cb = getCallback(args);
301
+ if (cb) {
302
+ if (command.includes('rev-parse')) cb(null, '/repo/.git\n', '');
303
+ else cb(null, '', '');
304
+ }
305
+ return { on: vi.fn() };
306
+ });
307
+
308
+ const result = await handler.configureCoAuthor('/wt', {
309
+ name: 'zag-bot[bot]',
310
+ email: '123456+zag-bot[bot]@users.noreply.github.com',
311
+ });
312
+
313
+ expect(result.success).toBe(true);
314
+ expect(commands).toContain("git -C '/wt' rev-parse --path-format=absolute --git-common-dir");
315
+ expect(commands).toContain("git -C '/wt' config extensions.worktreeConfig true");
316
+ expect(commands).toContain("git -C '/wt' config --worktree core.hooksPath '/repo/.git/zag-hooks'");
317
+ expect(commands).toContain("git -C '/wt' config --worktree zag.coAuthorName 'zag-bot[bot]'");
318
+ expect(commands).toContain(
319
+ "git -C '/wt' config --worktree zag.coAuthorEmail '123456+zag-bot[bot]@users.noreply.github.com'",
320
+ );
321
+ });
322
+
323
+ it('T-WTC10: 已有 Worktree 关闭共同作者时仅清理受管 hooksPath / zag.*', async () => {
324
+ const commands: string[] = [];
325
+ (exec as unknown as ReturnType<typeof vi.fn>).mockImplementation((...args: unknown[]) => {
326
+ const command = args[0] as string;
327
+ commands.push(command);
328
+ const cb = getCallback(args);
329
+ if (cb) {
330
+ if (command.includes('rev-parse')) cb(null, '/repo/.git\n', '');
331
+ else if (command.includes('--get core.hooksPath')) cb(null, '/repo/.git/zag-hooks\n', '');
332
+ else cb(null, '', '');
333
+ }
334
+ return { on: vi.fn() };
335
+ });
336
+
337
+ const result = await handler.configureCoAuthor('/wt');
338
+
339
+ expect(result.success).toBe(true);
340
+ expect(commands).toContain("git -C '/wt' config --worktree --unset core.hooksPath");
341
+ expect(commands).toContain("git -C '/wt' config --worktree --unset zag.coAuthorName");
342
+ expect(commands).toContain("git -C '/wt' config --worktree --unset zag.coAuthorEmail");
343
+ expect(writeFileSync).not.toHaveBeenCalled();
344
+ });
345
+
346
+ it('T-WTC11: 关闭共同作者不触碰用户自建 hooksPath', async () => {
347
+ const commands: string[] = [];
348
+ (exec as unknown as ReturnType<typeof vi.fn>).mockImplementation((...args: unknown[]) => {
349
+ const command = args[0] as string;
350
+ commands.push(command);
351
+ const cb = getCallback(args);
352
+ if (cb) {
353
+ if (command.includes('rev-parse')) cb(null, '/repo/.git\n', '');
354
+ else if (command.includes('--get core.hooksPath')) cb(null, '/home/worker/.husky\n', '');
355
+ else cb(null, '', '');
356
+ }
357
+ return { on: vi.fn() };
358
+ });
359
+
360
+ await handler.configureCoAuthor('/wt');
361
+
362
+ expect(commands.some((command) => command.includes('--unset core.hooksPath'))).toBe(false);
363
+ expect(commands).toContain("git -C '/wt' config --worktree --unset zag.coAuthorName");
364
+ });
365
+
366
+ it('T-WTC12: 非法共同作者按关闭处理,不写 hook', async () => {
367
+ const commands: string[] = [];
368
+ (exec as unknown as ReturnType<typeof vi.fn>).mockImplementation((...args: unknown[]) => {
369
+ const command = args[0] as string;
370
+ commands.push(command);
371
+ const cb = getCallback(args);
372
+ if (cb) {
373
+ if (command.includes('rev-parse')) cb(null, '/repo/.git\n', '');
374
+ else cb(null, '', '');
375
+ }
376
+ return { on: vi.fn() };
377
+ });
378
+
379
+ await handler.configureCoAuthor('/wt', {
380
+ name: 'bot\ninjected',
381
+ email: 'bot@example.com',
382
+ });
383
+
384
+ expect(writeFileSync).not.toHaveBeenCalled();
385
+ expect(commands.some((command) => command.includes('--worktree zag.coAuthorName'))).toBe(false);
386
+ });
387
+ });
388
+
294
389
  describe('remove', () => {
295
390
  it('should successfully remove a worktree', async () => {
296
391
  mockExecSuccess('');
@@ -100,6 +100,11 @@ function normalizeCommitter(committer?: WorktreeCommitter): WorktreeCommitter |
100
100
  return coAuthor ? { name, email, ...coAuthor } : { name, email };
101
101
  }
102
102
 
103
+ export interface WorktreeCoAuthorResult {
104
+ success: boolean;
105
+ error?: string;
106
+ }
107
+
103
108
  export interface WorktreeRemoveResult {
104
109
  success: boolean;
105
110
  error?: string;
@@ -198,6 +203,52 @@ export class WorktreeHandler {
198
203
  }
199
204
  }
200
205
 
206
+ /**
207
+ * 更新已有 Worktree 的共同作者配置(不改变作者身份)。
208
+ *
209
+ * 设置页勾选/取消只影响「之后创建的 Worktree」时,用户在旧 Worktree 上提交会看不到变化;
210
+ * 本方法在已有 Worktree 上重新同步:`coAuthor` 缺省 = 移除受管 trailer 配置(仅清理本平台写入的值)。
211
+ */
212
+ async configureCoAuthor(
213
+ worktreePath: string,
214
+ coAuthor?: { name: string; email: string },
215
+ ): Promise<WorktreeCoAuthorResult> {
216
+ try {
217
+ const resolvedPath = expandTilde(worktreePath);
218
+ const normalized = coAuthor
219
+ ? normalizeCoAuthor({
220
+ coAuthorName: coAuthor.name,
221
+ coAuthorEmail: coAuthor.email,
222
+ })
223
+ : undefined;
224
+ if (normalized) {
225
+ await this.applyWorktreeCoAuthor(
226
+ resolvedPath,
227
+ normalized.coAuthorName,
228
+ normalized.coAuthorEmail,
229
+ );
230
+ } else {
231
+ await this.clearWorktreeCoAuthor(resolvedPath);
232
+ }
233
+ return { success: true };
234
+ } catch (err) {
235
+ this.log.warn({ err }, '更新 worktree 共同作者配置失败(忽略)');
236
+ return { success: false, error: (err as Error).message };
237
+ }
238
+ }
239
+
240
+ /** Worktree 共享 git 目录下的受管 hook 目录(多 worktree 共用同一份 hook 文件)。 */
241
+ private async resolveHookDir(worktreePath: string): Promise<string> {
242
+ const pathArg = shellQuote(worktreePath);
243
+ const { stdout } = await execAsync(
244
+ `git -C ${pathArg} rev-parse --path-format=absolute --git-common-dir`,
245
+ );
246
+ const commonDir = stdout.trim();
247
+ if (!commonDir) throw new Error('git-common-dir is empty');
248
+ // `--path-format=absolute` 保证绝对路径;兼容旧 git 的相对输出时以 worktree 为基准解析。
249
+ return join(resolve(worktreePath, commonDir), CO_AUTHOR_HOOK_DIR);
250
+ }
251
+
201
252
  /**
202
253
  * 安装 worktree 级共同作者 hook(仅作用于该 worktree)。
203
254
  *
@@ -214,13 +265,7 @@ export class WorktreeHandler {
214
265
  const pathArg = shellQuote(worktreePath);
215
266
  let hookDir: string;
216
267
  try {
217
- const { stdout } = await execAsync(
218
- `git -C ${pathArg} rev-parse --path-format=absolute --git-common-dir`,
219
- );
220
- const commonDir = stdout.trim();
221
- if (!commonDir) throw new Error('git-common-dir is empty');
222
- // `--path-format=absolute` 保证绝对路径;兼容旧 git 的相对输出时以 worktree 为基准解析。
223
- hookDir = join(resolve(worktreePath, commonDir), CO_AUTHOR_HOOK_DIR);
268
+ hookDir = await this.resolveHookDir(worktreePath);
224
269
  mkdirSync(hookDir, { recursive: true });
225
270
  const hookPath = join(hookDir, CO_AUTHOR_HOOK_NAME);
226
271
  writeFileSync(hookPath, renderCoAuthorHook(), { mode: 0o755 });
@@ -232,6 +277,8 @@ export class WorktreeHandler {
232
277
  }
233
278
 
234
279
  const commands = [
280
+ // 已有 Worktree 可能由旧版本/手工创建,补齐 worktree config 开关后 `--worktree` 才生效。
281
+ `git -C ${pathArg} config extensions.worktreeConfig true`,
235
282
  `git -C ${pathArg} config --worktree core.hooksPath ${shellQuote(hookDir)}`,
236
283
  `git -C ${pathArg} config --worktree zag.coAuthorName ${shellQuote(coAuthorName)}`,
237
284
  `git -C ${pathArg} config --worktree zag.coAuthorEmail ${shellQuote(coAuthorEmail)}`,
@@ -246,6 +293,40 @@ export class WorktreeHandler {
246
293
  }
247
294
  }
248
295
 
296
+ /**
297
+ * 移除 worktree 级共同作者配置(幂等)。
298
+ *
299
+ * - 仅当该 worktree 的 `core.hooksPath` 恰为受管目录时才 unset,用户自建 hooks 零触碰;
300
+ * - 共享 hook 文件保留(其他 worktree 可能仍在引用),仅移除本 worktree 的配置。
301
+ */
302
+ private async clearWorktreeCoAuthor(worktreePath: string): Promise<void> {
303
+ const pathArg = shellQuote(worktreePath);
304
+ let hookDir: string;
305
+ try {
306
+ hookDir = await this.resolveHookDir(worktreePath);
307
+ } catch (err) {
308
+ this.log.warn({ err }, '读取 worktree 共同作者配置失败(忽略)');
309
+ return;
310
+ }
311
+
312
+ try {
313
+ const { stdout } = await execAsync(`git -C ${pathArg} config --worktree --get core.hooksPath`);
314
+ if (stdout.trim() === hookDir) {
315
+ await execAsync(`git -C ${pathArg} config --worktree --unset core.hooksPath`);
316
+ }
317
+ } catch {
318
+ // key 不存在(git 退出码 1)或未启用 worktree config:本就没有可清理的受管路径。
319
+ }
320
+
321
+ for (const key of ['zag.coAuthorName', 'zag.coAuthorEmail']) {
322
+ try {
323
+ await execAsync(`git -C ${pathArg} config --worktree --unset ${key}`);
324
+ } catch {
325
+ // key 不存在 = 已清理,无需告警
326
+ }
327
+ }
328
+ }
329
+
249
330
  async list(workspacePath: string): Promise<WorktreeListResult> {
250
331
  try {
251
332
  const resolvedPath = expandTilde(workspacePath);