agent-gear 2.11.0 → 2.12.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 (44) hide show
  1. package/AGENTS.md +30 -2
  2. package/dist/acp/bridge.d.ts +2 -0
  3. package/dist/acp/bridge.d.ts.map +1 -1
  4. package/dist/acp/bridge.js +13 -1
  5. package/dist/acp/bridge.js.map +1 -1
  6. package/dist/acp/sync-bridge.d.ts +2 -0
  7. package/dist/acp/sync-bridge.d.ts.map +1 -1
  8. package/dist/acp/sync-bridge.js +7 -0
  9. package/dist/acp/sync-bridge.js.map +1 -1
  10. package/dist/github/credential-manager.d.ts +15 -3
  11. package/dist/github/credential-manager.d.ts.map +1 -1
  12. package/dist/github/credential-manager.js +34 -6
  13. package/dist/github/credential-manager.js.map +1 -1
  14. package/dist/github/credential-manager.test.js +107 -1
  15. package/dist/github/credential-manager.test.js.map +1 -1
  16. package/dist/harness/dsh-config.atomic-failure.test.js +12 -0
  17. package/dist/harness/dsh-config.atomic-failure.test.js.map +1 -1
  18. package/dist/harness/dsh-config.d.ts +9 -2
  19. package/dist/harness/dsh-config.d.ts.map +1 -1
  20. package/dist/harness/dsh-config.js +56 -3
  21. package/dist/harness/dsh-config.js.map +1 -1
  22. package/dist/harness/dsh-config.test.js +138 -3
  23. package/dist/harness/dsh-config.test.js.map +1 -1
  24. package/dist/socketio-client.d.ts.map +1 -1
  25. package/dist/socketio-client.js +1 -1
  26. package/dist/socketio-client.js.map +1 -1
  27. package/dist/worktree-handler.d.ts +15 -1
  28. package/dist/worktree-handler.d.ts.map +1 -1
  29. package/dist/worktree-handler.js +53 -1
  30. package/dist/worktree-handler.js.map +1 -1
  31. package/dist/worktree-handler.test.js +95 -0
  32. package/dist/worktree-handler.test.js.map +1 -1
  33. package/package.json +2 -2
  34. package/src/acp/bridge.ts +15 -1
  35. package/src/acp/sync-bridge.ts +9 -0
  36. package/src/github/credential-manager.test.ts +134 -0
  37. package/src/github/credential-manager.ts +35 -5
  38. package/src/harness/dsh-config.atomic-failure.test.ts +17 -0
  39. package/src/harness/dsh-config.test.ts +174 -3
  40. package/src/harness/dsh-config.ts +62 -4
  41. package/src/socketio-client.ts +3 -1
  42. package/src/worktree-handler.test.ts +122 -0
  43. package/src/worktree-handler.ts +63 -1
  44. package/tests/manual/repro-question-tool.ts +118 -0
@@ -38,6 +38,23 @@ function mockExecError(errorMsg: string) {
38
38
  });
39
39
  }
40
40
 
41
+ /**
42
+ * 记录所有 `exec` 命令串(按调用顺序),可选按命令内容制造失败。
43
+ * committer 测试断言的是「命令序列 + 转义结果」,必须能看到每条命令原文。
44
+ */
45
+ function mockExecRecorder(commands: string[], shouldFail?: (command: string) => boolean) {
46
+ (exec as unknown as ReturnType<typeof vi.fn>).mockImplementation((...args: unknown[]) => {
47
+ const command = args[0] as string;
48
+ commands.push(command);
49
+ const cb = getCallback(args);
50
+ if (cb) {
51
+ if (shouldFail?.(command)) cb(new Error(`failed: ${command}`), '', '');
52
+ else cb(null, '', '');
53
+ }
54
+ return { on: vi.fn() };
55
+ });
56
+ }
57
+
41
58
  describe('WorktreeHandler', () => {
42
59
  let handler: WorktreeHandler;
43
60
 
@@ -68,6 +85,111 @@ describe('WorktreeHandler', () => {
68
85
  });
69
86
  });
70
87
 
88
+ describe('add with committer', () => {
89
+ it('T-WTC1: committer 存在时在 worktree add 之后依次写三条 worktree 级身份命令', async () => {
90
+ const commands: string[] = [];
91
+ mockExecRecorder(commands);
92
+
93
+ const result = await handler.add('/repo', '/wt', 'feat/branch', {
94
+ name: 'Deliay',
95
+ email: 'admin@remiliascarlet.com',
96
+ });
97
+
98
+ expect(result.success).toBe(true);
99
+ expect(result.worktreePath).toBe('/wt');
100
+ expect(commands).toEqual([
101
+ 'git -C "/repo" worktree add -b "feat/branch" "/wt"',
102
+ "git -C '/wt' config extensions.worktreeConfig true",
103
+ "git -C '/wt' config --worktree user.name 'Deliay'",
104
+ "git -C '/wt' config --worktree user.email 'admin@remiliascarlet.com'",
105
+ ]);
106
+ });
107
+
108
+ it('T-WTC2: committer 缺省时不写任何身份配置', async () => {
109
+ const commands: string[] = [];
110
+ mockExecRecorder(commands);
111
+
112
+ const result = await handler.add('/repo', '/wt', 'feat/branch');
113
+
114
+ expect(result.success).toBe(true);
115
+ expect(commands).toHaveLength(1);
116
+ expect(commands[0]).toBe('git -C "/repo" worktree add -b "feat/branch" "/wt"');
117
+ expect(commands.join('\n')).not.toContain('user.name');
118
+ expect(commands.join('\n')).not.toContain('worktreeConfig');
119
+ });
120
+
121
+ it('T-WTC2b: worktree add 失败时不尝试写身份', async () => {
122
+ const commands: string[] = [];
123
+ mockExecRecorder(commands, () => true);
124
+
125
+ const result = await handler.add('/repo', '/wt', 'feat/branch', {
126
+ name: 'Deliay',
127
+ email: 'admin@remiliascarlet.com',
128
+ });
129
+
130
+ expect(result.success).toBe(false);
131
+ expect(commands).toHaveLength(1);
132
+ });
133
+
134
+ it('T-WTC2c: committer 形态非法(非字符串/空值)时按缺省处理,不写身份且不影响成功', async () => {
135
+ const commands: string[] = [];
136
+ mockExecRecorder(commands);
137
+
138
+ const result = await handler.add(
139
+ '/repo',
140
+ '/wt',
141
+ 'feat/branch',
142
+ { name: 42, email: '' } as unknown as { name: string; email: string },
143
+ );
144
+
145
+ expect(result.success).toBe(true);
146
+ expect(commands).toHaveLength(1);
147
+ });
148
+
149
+ it('T-WTC3: 含空格/单引号/双引号/$/分号的姓名被 shell 转义且不注入', async () => {
150
+ const commands: string[] = [];
151
+ mockExecRecorder(commands);
152
+
153
+ const name = `Deliay O'Brien "$HOME"; echo pwned`;
154
+ const email = `o'brien@example.com`;
155
+
156
+ const result = await handler.add('/repo', '/wt', 'feat/branch', { name, email });
157
+
158
+ expect(result.success).toBe(true);
159
+ expect(commands).toHaveLength(4);
160
+ expect(commands[2]).toBe(
161
+ `git -C '/wt' config --worktree user.name 'Deliay O'\\''Brien "$HOME"; echo pwned'`,
162
+ );
163
+ expect(commands[3]).toBe(
164
+ `git -C '/wt' config --worktree user.email 'o'\\''brien@example.com'`,
165
+ );
166
+ // 注入防护:值被单引号整体包裹,分号/命令替换处于引号内而非命令分隔位置
167
+ const nameArg = commands[2].slice(commands[2].indexOf(`config --worktree user.name `) + 'config --worktree user.name '.length);
168
+ expect(nameArg.startsWith("'")).toBe(true);
169
+ expect(nameArg.endsWith("'")).toBe(true);
170
+ expect(nameArg).not.toContain('`');
171
+ expect(nameArg).not.toContain('$(');
172
+ });
173
+
174
+ it('T-WTC4: 单条身份命令失败只告警,不阻断 worktree 创建结果', async () => {
175
+ const commands: string[] = [];
176
+ mockExecRecorder(commands, (command) => command.includes('user.name'));
177
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
178
+
179
+ const result = await handler.add('/repo', '/wt', 'feat/branch', {
180
+ name: 'Deliay',
181
+ email: 'admin@remiliascarlet.com',
182
+ });
183
+
184
+ expect(result.success).toBe(true);
185
+ expect(result.worktreePath).toBe('/wt');
186
+ expect(commands).toHaveLength(4);
187
+ expect(commands[3]).toContain('user.email');
188
+ expect(warnSpy).toHaveBeenCalled();
189
+ warnSpy.mockRestore();
190
+ });
191
+ });
192
+
71
193
  describe('remove', () => {
72
194
  it('should successfully remove a worktree', async () => {
73
195
  mockExecSuccess('');
@@ -19,6 +19,14 @@ function execAsync(command: string): Promise<{ stdout: string; stderr: string }>
19
19
  });
20
20
  }
21
21
 
22
+ /**
23
+ * shell 单引号转义:值整体被单引号包裹,内嵌 `'` 转义为 `'\''`。
24
+ * name/email 来自用户设置(经 agent-api 透传),拼接进 `execAsync` 前必须转义。
25
+ */
26
+ function shellQuote(value: string): string {
27
+ return `'${value.replace(/'/g, `'\\''`)}'`;
28
+ }
29
+
22
30
  export interface WorktreeAddResult {
23
31
  success: boolean;
24
32
  worktreePath?: string;
@@ -26,6 +34,24 @@ export interface WorktreeAddResult {
26
34
  error?: string;
27
35
  }
28
36
 
37
+ /** Worktree 级提交人(`git:worktree:add` 可选载荷,缺省 = 不写身份)。 */
38
+ export interface WorktreeCommitter {
39
+ name: string;
40
+ email: string;
41
+ }
42
+
43
+ /**
44
+ * 载荷净化:仅接受 name/email 均为非空字符串的对象(载荷来自服务端 JSON,运行时不可信)。
45
+ * 非法形态一律视为「未提供 committer」→ 不写身份、沿用容器级 bot,而不是让 worktree 创建失败。
46
+ */
47
+ function normalizeCommitter(committer?: WorktreeCommitter): WorktreeCommitter | undefined {
48
+ if (!committer || typeof committer !== 'object') return undefined;
49
+ const { name, email } = committer as Partial<WorktreeCommitter>;
50
+ if (typeof name !== 'string' || name.trim().length === 0) return undefined;
51
+ if (typeof email !== 'string' || email.trim().length === 0) return undefined;
52
+ return { name, email };
53
+ }
54
+
29
55
  export interface WorktreeRemoveResult {
30
56
  success: boolean;
31
57
  error?: string;
@@ -55,7 +81,12 @@ export interface GitCommitResult {
55
81
  }
56
82
 
57
83
  export class WorktreeHandler {
58
- async add(repoPath: string, worktreePath: string, branch: string): Promise<WorktreeAddResult> {
84
+ async add(
85
+ repoPath: string,
86
+ worktreePath: string,
87
+ branch: string,
88
+ committer?: WorktreeCommitter,
89
+ ): Promise<WorktreeAddResult> {
59
90
  try {
60
91
  const resolvedPath = expandTilde(worktreePath);
61
92
  const parentDir = dirname(resolvedPath);
@@ -68,12 +99,43 @@ export class WorktreeHandler {
68
99
  if (stderr && !stderr.includes('already exists') && !stderr.includes('done') && !stderr.includes('Preparing')) {
69
100
  return { success: false, error: stderr.trim() };
70
101
  }
102
+ if (committer) {
103
+ const normalized = normalizeCommitter(committer);
104
+ if (normalized) {
105
+ await this.applyWorktreeCommitter(resolvedPath, normalized);
106
+ }
107
+ }
71
108
  return { success: true, worktreePath: resolvedPath, branch };
72
109
  } catch (err) {
73
110
  return { success: false, error: (err as Error).message };
74
111
  }
75
112
  }
76
113
 
114
+ /**
115
+ * 向 worktree 写入 worktree 级 git 身份(仅作用于该 worktree,主仓与兄弟 worktree 不受影响)。
116
+ *
117
+ * - `extensions.worktreeConfig true` 落在共享配置(幂等,重复 set 同值无副作用);
118
+ * - `--worktree user.name/user.email` 落在 `.git/worktrees/<name>/config.worktree`;
119
+ * - name/email 为**用户可控值**,一律经 `shellQuote` 转义后拼接;
120
+ * - 单条失败仅 `console.warn`,不阻断 worktree 创建(身份缺失可接受)。
121
+ */
122
+ private async applyWorktreeCommitter(worktreePath: string, committer: WorktreeCommitter): Promise<void> {
123
+ const pathArg = shellQuote(worktreePath);
124
+ const commands = [
125
+ `git -C ${pathArg} config extensions.worktreeConfig true`,
126
+ `git -C ${pathArg} config --worktree user.name ${shellQuote(committer.name)}`,
127
+ `git -C ${pathArg} config --worktree user.email ${shellQuote(committer.email)}`,
128
+ ];
129
+ for (const command of commands) {
130
+ try {
131
+ await execAsync(command);
132
+ } catch (err) {
133
+ // 不输出 name/email 值(用户数据),仅记录失败步骤与原因
134
+ console.warn(`[WorktreeHandler] 写入 worktree 提交人配置失败(忽略):${(err as Error).message}`);
135
+ }
136
+ }
137
+ }
138
+
77
139
  async list(workspacePath: string): Promise<WorktreeListResult> {
78
140
  try {
79
141
  const resolvedPath = expandTilde(workspacePath);
@@ -0,0 +1,118 @@
1
+ /**
2
+ * 手动复现脚本(不参与 `npm test`,vitest 只收集 *.test.ts / *.spec.ts):
3
+ * 「Agent 调用 question 工具后立即报 The user dismissed this question」。
4
+ *
5
+ * 为什么需要它:question 工具的失败文案由 OpenCode 侧产生,单元测试里的假 Agent
6
+ * 无法复刻「elicitation 被 cancel → form cancel → CancelledError」这条真实映射,
7
+ * 必须用真实 `opencode acp` 进程 + 真实 AcpSessionBridge 观测。
8
+ *
9
+ * 前置条件:
10
+ * - 本机已安装 `opencode`(>= 2.1.x),且 ~/.config/opencode 已配置可用模型;
11
+ * - 已 `npm ci`(需要 @agentclientprotocol/sdk)。
12
+ *
13
+ * 用法(在 packages/agent-controller 目录):
14
+ * npx tsx tests/manual/repro-question-tool.ts <policy> [prompt]
15
+ *
16
+ * policy = none 不响应问询(观测 65s bridge 超时后的工具结果)
17
+ * accept 收到问询立即 accept(对照组:question 工具应 completed)
18
+ * decline 收到问询立即 decline
19
+ * cancel 收到问询立即 cancel(秒级复现 "dismissed")
20
+ *
21
+ * 环境变量:
22
+ * REPRO_MODEL 指定模型(形如 zag/deepseek-v4.1-flash),不设则由 OpenCode 默认模型决定。
23
+ */
24
+ import { mkdtempSync } from 'node:fs';
25
+ import { tmpdir } from 'node:os';
26
+ import { join } from 'node:path';
27
+ import { AcpSessionBridge } from '../../src/acp/bridge.js';
28
+ import { AcpSpawner } from '../../src/acp/spawner.js';
29
+
30
+ type Policy = 'none' | 'accept' | 'decline' | 'cancel';
31
+
32
+ const policy = (process.argv[2] ?? 'none') as Policy;
33
+ const promptText =
34
+ process.argv[3] ?? '请用 question 工具向我提一个单选题(3 个选项),问完就停下等我回答。';
35
+
36
+ if (!['none', 'accept', 'decline', 'cancel'].includes(policy)) {
37
+ console.error(`unknown policy: ${policy}`);
38
+ process.exit(2);
39
+ }
40
+
41
+ const cwd = mkdtempSync(join(tmpdir(), 'repro-question-'));
42
+ const startedAt = Date.now();
43
+ const log = (...args: unknown[]) => console.log(`[${Date.now() - startedAt}ms]`, ...args);
44
+
45
+ let bridge: AcpSessionBridge;
46
+
47
+ const socket = {
48
+ emit(event: string, payload: Record<string, unknown>) {
49
+ log('emit', event, JSON.stringify(payload).slice(0, 1200));
50
+
51
+ if (event === 'acp:elicitation' && policy !== 'none') {
52
+ const requestId = payload.requestId as string;
53
+ setTimeout(() => {
54
+ log('-> respond elicitation', requestId, policy);
55
+ bridge.handleElicitationResponse(
56
+ requestId,
57
+ policy,
58
+ policy === 'accept' ? { q0: 'A' } : undefined,
59
+ );
60
+ }, 50);
61
+ }
62
+
63
+ if (event === 'acp:permission' && policy !== 'none') {
64
+ const requestId = payload.requestId as string;
65
+ const options = payload.options as Array<{ optionId: string; kind?: string }> | undefined;
66
+ const allow = options?.find((o) => o.kind === 'allow_once' || o.kind === 'allow_always') ?? options?.[0];
67
+ setTimeout(() => {
68
+ log('-> respond permission', requestId, allow?.optionId);
69
+ bridge.handlePermissionResponse(
70
+ requestId,
71
+ allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' },
72
+ );
73
+ }, 50);
74
+ }
75
+ return true;
76
+ },
77
+ on() { return socket; },
78
+ off() { return socket; },
79
+ };
80
+
81
+ const spawner = new AcpSpawner({ sessionId: `repro-${Date.now()}`, cwd });
82
+ bridge = new AcpSessionBridge(
83
+ socket as never,
84
+ {
85
+ sessionId: `repro-${Date.now()}`,
86
+ cwd,
87
+ ...(process.env.REPRO_MODEL ? { initialModelId: process.env.REPRO_MODEL } : {}),
88
+ } as never,
89
+ spawner,
90
+ );
91
+
92
+ async function main(): Promise<void> {
93
+ log('bridge.start()', { cwd, policy });
94
+ await bridge.start();
95
+ log('bridge started');
96
+ bridge.sendInput({ type: 'text', content: promptText });
97
+ log('prompt sent');
98
+
99
+ await new Promise<void>((resolve) => {
100
+ // 65s bridge 超时 + 余量
101
+ const timer = setTimeout(() => { log('TIMEOUT 100s'); resolve(); }, 100_000);
102
+ bridge.on('acp:stopped', () => {
103
+ log('bridge stopped');
104
+ clearTimeout(timer);
105
+ resolve();
106
+ });
107
+ });
108
+
109
+ await bridge.stop().catch(() => {});
110
+ spawner.stop();
111
+ setTimeout(() => process.exit(0), 300);
112
+ }
113
+
114
+ main().catch((error) => {
115
+ console.error('repro failed', error);
116
+ spawner.stop();
117
+ process.exit(1);
118
+ });